Use correct length for buffer
[TortoiseGit.git] / src / TortoiseProc / StatGraphDlg.cpp
blobb4ff21bfdce8537a6d0174947f7ab23842da0281
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2016 - TortoiseGit
4 // Copyright (C) 2003-2011,2014-2015 - TortoiseSVN
6 // This program is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU General Public License
8 // as published by the Free Software Foundation; either version 2
9 // of the License, or (at your option) any later version.
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // You should have received a copy of the GNU General Public License
17 // along with this program; if not, write to the Free Software Foundation,
18 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 #include "stdafx.h"
21 #include "TortoiseProc.h"
22 #include "StatGraphDlg.h"
23 #include <GdiPlus.h>
24 #include "AppUtils.h"
25 #include "PathUtils.h"
26 #include "MessageBox.h"
27 #include "registry.h"
28 #include "FormatMessageWrapper.h"
29 #include "SysProgressDlg.h"
31 #include <iterator>
32 #include <cmath>
33 #include <locale>
34 #include <list>
35 #include <utility>
36 #include <strsafe.h>
38 using namespace Gdiplus;
40 // BinaryPredicate for comparing authors based on their commit count
41 template<class DataType>
42 class MoreCommitsThan : public std::binary_function<tstring, tstring, bool> {
43 public:
44 typedef std::map<tstring, DataType> MapType;
45 MoreCommitsThan(MapType &author_commits) : m_authorCommits(author_commits) {}
47 bool operator()(const tstring& lhs, const tstring& rhs) {
48 return (m_authorCommits)[lhs] > (m_authorCommits)[rhs];
51 private:
52 MapType &m_authorCommits;
56 IMPLEMENT_DYNAMIC(CStatGraphDlg, CResizableStandAloneDialog)
57 CStatGraphDlg::CStatGraphDlg(CWnd* pParent /*=nullptr*/)
58 : CResizableStandAloneDialog(CStatGraphDlg::IDD, pParent)
59 , m_bStacked(FALSE)
60 , m_GraphType(MyGraph::Bar)
61 , m_bAuthorsCaseSensitive(TRUE)
62 , m_bSortByCommitCount(TRUE)
63 , m_nWeeks(-1)
64 , m_nDays(-1)
65 , m_langOrder(0)
66 , m_firstInterval(0)
67 , m_lastInterval(0)
68 , m_nTotalCommits(0)
69 , m_nTotalLinesInc(0)
70 , m_nTotalLinesDec(0)
71 , m_nTotalLinesNew(0)
72 , m_nTotalLinesDel(0)
73 , m_bDiffFetched(FALSE)
74 , m_ShowList(nullptr)
75 , m_minDate(0)
76 , m_maxDate(0)
77 , m_nTotalFileChanges(0)
81 CStatGraphDlg::~CStatGraphDlg()
83 ClearGraph();
86 void CStatGraphDlg::OnOK() {
87 StoreCurrentGraphType();
88 __super::OnOK();
91 void CStatGraphDlg::OnCancel() {
92 StoreCurrentGraphType();
93 __super::OnCancel();
96 void CStatGraphDlg::DoDataExchange(CDataExchange* pDX)
98 CResizableStandAloneDialog::DoDataExchange(pDX);
99 DDX_Control(pDX, IDC_GRAPH, m_graph);
100 DDX_Control(pDX, IDC_GRAPHCOMBO, m_cGraphType);
101 DDX_Control(pDX, IDC_SKIPPER, m_Skipper);
102 DDX_Check(pDX, IDC_AUTHORSCASESENSITIVE, m_bAuthorsCaseSensitive);
103 DDX_Check(pDX, IDC_SORTBYCOMMITCOUNT, m_bSortByCommitCount);
104 DDX_Control(pDX, IDC_GRAPHBARBUTTON, m_btnGraphBar);
105 DDX_Control(pDX, IDC_GRAPHBARSTACKEDBUTTON, m_btnGraphBarStacked);
106 DDX_Control(pDX, IDC_GRAPHLINEBUTTON, m_btnGraphLine);
107 DDX_Control(pDX, IDC_GRAPHLINESTACKEDBUTTON, m_btnGraphLineStacked);
108 DDX_Control(pDX, IDC_GRAPHPIEBUTTON, m_btnGraphPie);
112 BEGIN_MESSAGE_MAP(CStatGraphDlg, CResizableStandAloneDialog)
113 ON_CBN_SELCHANGE(IDC_GRAPHCOMBO, OnCbnSelchangeGraphcombo)
114 ON_WM_HSCROLL()
115 ON_NOTIFY(TTN_NEEDTEXT, nullptr, OnNeedText)
116 ON_BN_CLICKED(IDC_AUTHORSCASESENSITIVE, &CStatGraphDlg::AuthorsCaseSensitiveChanged)
117 ON_BN_CLICKED(IDC_SORTBYCOMMITCOUNT, &CStatGraphDlg::SortModeChanged)
118 ON_BN_CLICKED(IDC_GRAPHBARBUTTON, &CStatGraphDlg::OnBnClickedGraphbarbutton)
119 ON_BN_CLICKED(IDC_GRAPHBARSTACKEDBUTTON, &CStatGraphDlg::OnBnClickedGraphbarstackedbutton)
120 ON_BN_CLICKED(IDC_GRAPHLINEBUTTON, &CStatGraphDlg::OnBnClickedGraphlinebutton)
121 ON_BN_CLICKED(IDC_GRAPHLINESTACKEDBUTTON, &CStatGraphDlg::OnBnClickedGraphlinestackedbutton)
122 ON_BN_CLICKED(IDC_GRAPHPIEBUTTON, &CStatGraphDlg::OnBnClickedGraphpiebutton)
123 ON_COMMAND(ID_FILE_SAVESTATGRAPHAS, &CStatGraphDlg::OnFileSavestatgraphas)
124 ON_BN_CLICKED(IDC_CALC_DIFF, &CStatGraphDlg::OnBnClickedFetchDiff)
125 END_MESSAGE_MAP()
127 void CStatGraphDlg::LoadStatQueries (__in UINT curStr, Metrics loadMetric, bool setDef /* = false */)
129 CString temp;
130 temp.LoadString(curStr);
131 int sel = m_cGraphType.AddString(temp);
132 m_cGraphType.SetItemData(sel, loadMetric);
134 if (setDef) m_cGraphType.SetCurSel(sel);
137 void CStatGraphDlg::SetSkipper (bool reloadSkiper)
139 // We need to limit the number of authors due to GUI resource limitation.
140 // However, since author #251 will properly have < 1000th of the commits,
141 // the resolution limit of the screen will already not allow for displaying
142 // it in a reasonable way
144 int max_authors_count = max(1, (int)min(m_authorNames.size(), 250) );
145 m_Skipper.SetRange (1, max_authors_count);
146 m_Skipper.SetPageSize(5);
148 if (reloadSkiper)
149 m_Skipper.SetPos (max_authors_count);
152 BOOL CStatGraphDlg::OnInitDialog()
154 CResizableStandAloneDialog::OnInitDialog();
156 // gather statistics data, only needs to be updated when the checkbox with
157 // the case sensitivity of author names is changed
158 GatherData();
160 m_tooltips.AddTool(&m_btnGraphPie, IDS_STATGRAPH_PIEBUTTON_TT);
161 m_tooltips.AddTool(&m_btnGraphLineStacked, IDS_STATGRAPH_LINESTACKEDBUTTON_TT);
162 m_tooltips.AddTool(&m_btnGraphLine, IDS_STATGRAPH_LINEBUTTON_TT);
163 m_tooltips.AddTool(&m_btnGraphBarStacked, IDS_STATGRAPH_BARSTACKEDBUTTON_TT);
164 m_tooltips.AddTool(&m_btnGraphBar, IDS_STATGRAPH_BARBUTTON_TT);
165 m_tooltips.Activate(TRUE);
167 m_bAuthorsCaseSensitive = DWORD(CRegDWORD(_T("Software\\TortoiseGit\\StatAuthorsCaseSensitive")));
168 m_bSortByCommitCount = DWORD(CRegDWORD(_T("Software\\TortoiseGit\\StatSortByCommitCount")));
169 UpdateData(FALSE);
171 //Load statistical queries
172 LoadStatQueries(IDS_STATGRAPH_STATS, AllStat, true);
173 LoadStatQueries(IDS_STATGRAPH_COMMITSBYDATE, CommitsByDate);
174 LoadStatQueries(IDS_STATGRAPH_COMMITSBYAUTHOR, CommitsByAuthor);
175 LoadStatQueries(IDS_STATGRAPH_PERCENTAGE_OF_AUTHORSHIP, PercentageOfAuthorship);
176 LoadStatQueries(IDS_STATGRAPH_LINES_BYDATE_W, LinesWByDate);
177 LoadStatQueries(IDS_STATGRAPH_LINES_BYDATE_WO, LinesWOByDate);
179 // set the dialog title to "Statistics - path/to/whatever/we/show/the/statistics/for"
180 CString sTitle;
181 GetWindowText(sTitle);
182 if (m_path.IsEmpty())
183 CAppUtils::SetWindowTitle(m_hWnd, g_Git.m_CurrentDir, sTitle);
184 else
185 CAppUtils::SetWindowTitle(m_hWnd, m_path.GetUIPathString(), sTitle);
187 m_btnGraphBar.SetImage((HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDI_GRAPHBAR), IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR));
188 m_btnGraphBar.SizeToContent();
189 m_btnGraphBar.Invalidate();
190 m_btnGraphBarStacked.SetImage((HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDI_GRAPHBARSTACKED), IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR));
191 m_btnGraphBarStacked.SizeToContent();
192 m_btnGraphBarStacked.Invalidate();
193 m_btnGraphLine.SetImage((HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDI_GRAPHLINE), IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR));
194 m_btnGraphLine.SizeToContent();
195 m_btnGraphLine.Invalidate();
196 m_btnGraphLineStacked.SetImage((HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDI_GRAPHLINESTACKED), IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR));
197 m_btnGraphLineStacked.SizeToContent();
198 m_btnGraphLineStacked.Invalidate();
199 m_btnGraphPie.SetImage((HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDI_GRAPHPIE), IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR));
200 m_btnGraphPie.SizeToContent();
201 m_btnGraphPie.Invalidate();
203 AddAnchor(IDC_GRAPHTYPELABEL, TOP_LEFT);
204 AddAnchor(IDC_GRAPH, TOP_LEFT, BOTTOM_RIGHT);
205 AddAnchor(IDC_GRAPHCOMBO, TOP_LEFT, TOP_RIGHT);
207 AddAnchor(IDC_NUMWEEK, TOP_LEFT);
208 AddAnchor(IDC_NUMWEEKVALUE, TOP_RIGHT);
209 AddAnchor(IDC_NUMAUTHOR, TOP_LEFT);
210 AddAnchor(IDC_NUMAUTHORVALUE, TOP_RIGHT);
211 AddAnchor(IDC_NUMCOMMITS, TOP_LEFT);
212 AddAnchor(IDC_NUMCOMMITSVALUE, TOP_RIGHT);
213 AddAnchor(IDC_NUMFILECHANGES, TOP_LEFT);
214 AddAnchor(IDC_NUMFILECHANGESVALUE, TOP_RIGHT);
216 AddAnchor(IDC_TOTAL_LINE_WITHOUT_NEW_DEL, TOP_LEFT);
217 AddAnchor(IDC_TOTAL_LINE_WITHOUT_NEW_DEL_VALUE, TOP_RIGHT);
218 AddAnchor(IDC_TOTAL_LINE_WITH_NEW_DEL, TOP_LEFT);
219 AddAnchor(IDC_TOTAL_LINE_WITH_NEW_DEL_VALUE, TOP_RIGHT);
221 AddAnchor(IDC_CALC_DIFF, TOP_RIGHT);
223 AddAnchor(IDC_AVG, TOP_RIGHT);
224 AddAnchor(IDC_MIN, TOP_RIGHT);
225 AddAnchor(IDC_MAX, TOP_RIGHT);
226 AddAnchor(IDC_COMMITSEACHWEEK, TOP_LEFT);
227 AddAnchor(IDC_MOSTACTIVEAUTHOR, TOP_LEFT);
228 AddAnchor(IDC_LEASTACTIVEAUTHOR, TOP_LEFT);
229 AddAnchor(IDC_MOSTACTIVEAUTHORNAME, TOP_LEFT, TOP_RIGHT);
230 AddAnchor(IDC_LEASTACTIVEAUTHORNAME, TOP_LEFT, TOP_RIGHT);
231 AddAnchor(IDC_FILECHANGESEACHWEEK, TOP_LEFT);
232 AddAnchor(IDC_COMMITSEACHWEEKAVG, TOP_RIGHT);
233 AddAnchor(IDC_COMMITSEACHWEEKMIN, TOP_RIGHT);
234 AddAnchor(IDC_COMMITSEACHWEEKMAX, TOP_RIGHT);
235 AddAnchor(IDC_MOSTACTIVEAUTHORAVG, TOP_RIGHT);
236 AddAnchor(IDC_MOSTACTIVEAUTHORMIN, TOP_RIGHT);
237 AddAnchor(IDC_MOSTACTIVEAUTHORMAX, TOP_RIGHT);
238 AddAnchor(IDC_LEASTACTIVEAUTHORAVG, TOP_RIGHT);
239 AddAnchor(IDC_LEASTACTIVEAUTHORMIN, TOP_RIGHT);
240 AddAnchor(IDC_LEASTACTIVEAUTHORMAX, TOP_RIGHT);
241 AddAnchor(IDC_FILECHANGESEACHWEEKAVG, TOP_RIGHT);
242 AddAnchor(IDC_FILECHANGESEACHWEEKMIN, TOP_RIGHT);
243 AddAnchor(IDC_FILECHANGESEACHWEEKMAX, TOP_RIGHT);
245 AddAnchor(IDC_GRAPHBARBUTTON, BOTTOM_RIGHT);
246 AddAnchor(IDC_GRAPHBARSTACKEDBUTTON, BOTTOM_RIGHT);
247 AddAnchor(IDC_GRAPHLINEBUTTON, BOTTOM_RIGHT);
248 AddAnchor(IDC_GRAPHLINESTACKEDBUTTON, BOTTOM_RIGHT);
249 AddAnchor(IDC_GRAPHPIEBUTTON, BOTTOM_RIGHT);
251 AddAnchor(IDC_AUTHORSCASESENSITIVE, BOTTOM_LEFT);
252 AddAnchor(IDC_SORTBYCOMMITCOUNT, BOTTOM_LEFT);
253 AddAnchor(IDC_SKIPPER, BOTTOM_LEFT, BOTTOM_RIGHT);
254 AddAnchor(IDC_SKIPPERLABEL, BOTTOM_LEFT);
255 AddAnchor(IDOK, BOTTOM_RIGHT);
256 EnableSaveRestore(_T("StatGraphDlg"));
258 // set the min/max values on the skipper
259 SetSkipper (true);
261 // we use a stats page encoding here, 0 stands for the statistics dialog
262 CRegDWORD lastStatsPage(_T("Software\\TortoiseGit\\LastViewedStatsPage"), 0);
264 // open last viewed statistics page as first page
265 int graphtype = lastStatsPage / 10;
266 for (int i = 0; i < m_cGraphType.GetCount(); i++)
268 if ((int)m_cGraphType.GetItemData(i) == graphtype)
270 m_cGraphType.SetCurSel(i);
271 break;
275 OnCbnSelchangeGraphcombo();
277 int statspage = lastStatsPage % 10;
278 switch (statspage) {
279 case 1 :
280 m_GraphType = MyGraph::Bar;
281 m_bStacked = true;
282 break;
283 case 2 :
284 m_GraphType = MyGraph::Bar;
285 m_bStacked = false;
286 break;
287 case 3 :
288 m_GraphType = MyGraph::Line;
289 m_bStacked = true;
290 break;
291 case 4 :
292 m_GraphType = MyGraph::Line;
293 m_bStacked = false;
294 break;
295 case 5 :
296 m_GraphType = MyGraph::PieChart;
297 break;
299 default : return TRUE;
302 LCID m_locale = MAKELCID((DWORD)CRegStdDWORD(_T("Software\\TortoiseGit\\LanguageID"), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT)), SORT_DEFAULT);
304 bool bUseSystemLocale = !!(DWORD)CRegStdDWORD(_T("Software\\TortoiseGit\\UseSystemLocaleForDates"), TRUE);
305 LCID locale = bUseSystemLocale ? MAKELCID(MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), SORT_DEFAULT) : m_locale;
307 TCHAR langBuf[11] = { 0 };
308 GetLocaleInfo(locale, LOCALE_IDATE, langBuf, _countof(langBuf));
310 m_langOrder = _ttoi(langBuf);
312 return TRUE;
315 void CStatGraphDlg::ShowLabels(BOOL bShow)
317 if (m_parAuthors.IsEmpty() || m_parDates.IsEmpty() || m_parFileChanges.IsEmpty())
318 return;
320 int nCmdShow = bShow ? SW_SHOW : SW_HIDE;
322 GetDlgItem(IDC_GRAPH)->ShowWindow(bShow ? SW_HIDE : SW_SHOW);
323 GetDlgItem(IDC_NUMWEEK)->ShowWindow(nCmdShow);
324 GetDlgItem(IDC_NUMWEEKVALUE)->ShowWindow(nCmdShow);
325 GetDlgItem(IDC_NUMAUTHOR)->ShowWindow(nCmdShow);
326 GetDlgItem(IDC_NUMAUTHORVALUE)->ShowWindow(nCmdShow);
327 GetDlgItem(IDC_NUMCOMMITS)->ShowWindow(nCmdShow);
328 GetDlgItem(IDC_NUMCOMMITSVALUE)->ShowWindow(nCmdShow);
329 GetDlgItem(IDC_NUMFILECHANGES)->ShowWindow(nCmdShow);
330 GetDlgItem(IDC_NUMFILECHANGESVALUE)->ShowWindow(nCmdShow);
331 GetDlgItem(IDC_TOTAL_LINE_WITHOUT_NEW_DEL)->ShowWindow(nCmdShow);
332 GetDlgItem(IDC_TOTAL_LINE_WITHOUT_NEW_DEL_VALUE)->ShowWindow(nCmdShow);
333 GetDlgItem(IDC_TOTAL_LINE_WITH_NEW_DEL)->ShowWindow(nCmdShow);
334 GetDlgItem(IDC_TOTAL_LINE_WITH_NEW_DEL_VALUE)->ShowWindow(nCmdShow);
335 GetDlgItem(IDC_CALC_DIFF)->ShowWindow(nCmdShow && !m_bDiffFetched);
337 GetDlgItem(IDC_AVG)->ShowWindow(nCmdShow);
338 GetDlgItem(IDC_MIN)->ShowWindow(nCmdShow);
339 GetDlgItem(IDC_MAX)->ShowWindow(nCmdShow);
340 GetDlgItem(IDC_COMMITSEACHWEEK)->ShowWindow(nCmdShow);
341 GetDlgItem(IDC_MOSTACTIVEAUTHOR)->ShowWindow(nCmdShow);
342 GetDlgItem(IDC_LEASTACTIVEAUTHOR)->ShowWindow(nCmdShow);
343 GetDlgItem(IDC_MOSTACTIVEAUTHORNAME)->ShowWindow(nCmdShow);
344 GetDlgItem(IDC_LEASTACTIVEAUTHORNAME)->ShowWindow(nCmdShow);
345 //GetDlgItem(IDC_FILECHANGESEACHWEEK)->ShowWindow(nCmdShow);
346 GetDlgItem(IDC_COMMITSEACHWEEKAVG)->ShowWindow(nCmdShow);
347 GetDlgItem(IDC_COMMITSEACHWEEKMIN)->ShowWindow(nCmdShow);
348 GetDlgItem(IDC_COMMITSEACHWEEKMAX)->ShowWindow(nCmdShow);
349 GetDlgItem(IDC_MOSTACTIVEAUTHORAVG)->ShowWindow(nCmdShow);
350 GetDlgItem(IDC_MOSTACTIVEAUTHORMIN)->ShowWindow(nCmdShow);
351 GetDlgItem(IDC_MOSTACTIVEAUTHORMAX)->ShowWindow(nCmdShow);
352 GetDlgItem(IDC_LEASTACTIVEAUTHORAVG)->ShowWindow(nCmdShow);
353 GetDlgItem(IDC_LEASTACTIVEAUTHORMIN)->ShowWindow(nCmdShow);
354 GetDlgItem(IDC_LEASTACTIVEAUTHORMAX)->ShowWindow(nCmdShow);
355 GetDlgItem(IDC_FILECHANGESEACHWEEKAVG)->ShowWindow(nCmdShow);
356 GetDlgItem(IDC_FILECHANGESEACHWEEKMIN)->ShowWindow(nCmdShow);
357 GetDlgItem(IDC_FILECHANGESEACHWEEKMAX)->ShowWindow(nCmdShow);
359 GetDlgItem(IDC_SORTBYCOMMITCOUNT)->ShowWindow(bShow ? SW_HIDE : SW_SHOW);
360 GetDlgItem(IDC_SKIPPER)->ShowWindow(bShow ? SW_HIDE : SW_SHOW);
361 GetDlgItem(IDC_SKIPPERLABEL)->ShowWindow(bShow ? SW_HIDE : SW_SHOW);
362 m_btnGraphBar.ShowWindow(bShow ? SW_HIDE : SW_SHOW);
363 m_btnGraphBarStacked.ShowWindow(bShow ? SW_HIDE : SW_SHOW);
364 m_btnGraphLine.ShowWindow(bShow ? SW_HIDE : SW_SHOW);
365 m_btnGraphLineStacked.ShowWindow(bShow ? SW_HIDE : SW_SHOW);
366 m_btnGraphPie.ShowWindow(bShow ? SW_HIDE : SW_SHOW);
369 void CStatGraphDlg::UpdateWeekCount()
371 // Sanity check
372 if (m_parDates.IsEmpty())
373 return;
375 // Already updated? No need to do it again.
376 if (m_nWeeks >= 0)
377 return;
379 // Determine first and last date in dates array
380 __time64_t min_date = (__time64_t)m_parDates.GetAt(0);
381 __time64_t max_date = min_date;
382 INT_PTR count = m_parDates.GetCount();
383 for (INT_PTR i=0; i<count; ++i)
385 __time64_t d = (__time64_t)m_parDates.GetAt(i);
386 if (d < min_date) min_date = d;
387 else if (d > max_date) max_date = d;
390 // Store start date of the interval in the member variable m_minDate
391 m_minDate = min_date;
392 m_maxDate = max_date;
394 // How many weeks does the time period cover?
396 // Get time difference between start and end date
397 double secs = _difftime64(max_date, m_minDate);
399 m_nWeeks = (int)ceil(secs / (double) m_SecondsInWeek);
400 m_nDays = (int)ceil(secs / (double) m_SecondsInDay);
403 int CStatGraphDlg::GetCalendarWeek(const CTime& time)
405 // Note:
406 // the calculation of the calendar week is wrong if DST is in effect
407 // and the date to calculate the week for is in DST and within the range
408 // of the DST offset (e.g. one hour).
409 // For example, if DST starts on Sunday march 30 and the date to get the week for
410 // is Monday, march 31, 0:30:00, then the returned week is one week less than
411 // the real week.
412 // TODO: ?
413 // write a function
414 // getDSTOffset(const CTime& time)
415 // which returns the DST offset for a given time/date. Then we can use this offset
416 // to correct our GetDays() calculation to get the correct week again
417 // This of course won't work for 'history' dates, because Windows doesn't have
418 // that information (only Vista has such a function: GetTimeZoneInformationForYear() )
419 int iWeekOfYear = 0;
421 int iYear = time.GetYear();
422 int iFirstDayOfWeek = 0;
423 int iFirstWeekOfYear = 0;
424 TCHAR loc[2] = { 0 };
425 GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_IFIRSTDAYOFWEEK, loc, _countof(loc));
426 iFirstDayOfWeek = int(loc[0]-'0');
427 GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_IFIRSTWEEKOFYEAR, loc, _countof(loc));
428 iFirstWeekOfYear = int(loc[0]-'0');
429 CTime dDateFirstJanuary(iYear,1,1,0,0,0);
430 int iDayOfWeek = (dDateFirstJanuary.GetDayOfWeek()+5+iFirstDayOfWeek)%7;
432 // Select mode
433 // 0 Week containing 1/1 is the first week of that year.
434 // 1 First full week following 1/1 is the first week of that year.
435 // 2 First week containing at least four days is the first week of that year.
436 switch (iFirstWeekOfYear)
438 case 0:
440 // Week containing 1/1 is the first week of that year.
442 // check if this week reaches into the next year
443 dDateFirstJanuary = CTime(iYear+1,1,1,0,0,0);
445 // Get start of week
448 iDayOfWeek = (time.GetDayOfWeek()+5+iFirstDayOfWeek)%7;
450 catch (CException* e)
452 e->Delete();
454 CTime dStartOfWeek = time-CTimeSpan(iDayOfWeek,0,0,0);
456 // If this week spans over to 1/1 this is week 1
457 if (dStartOfWeek + CTimeSpan(6,0,0,0) >= dDateFirstJanuary)
459 // we are in the last week of the year that spans over 1/1
460 iWeekOfYear = 1;
462 else
464 // Get week day of 1/1
465 dDateFirstJanuary = CTime(iYear,1,1,0,0,0);
466 iDayOfWeek = (dDateFirstJanuary.GetDayOfWeek() +5 + iFirstDayOfWeek) % 7;
467 // Just count from 1/1
468 iWeekOfYear = (int)(((time-dDateFirstJanuary).GetDays() + iDayOfWeek) / 7) + 1;
471 break;
472 case 1:
474 // First full week following 1/1 is the first week of that year.
476 // If the 1.1 is the start of the week everything is ok
477 // else we need the next week is the correct result
478 iWeekOfYear =
479 (int)(((time-dDateFirstJanuary).GetDays() + iDayOfWeek) / 7) +
480 (iDayOfWeek==0 ? 1:0);
482 // If we are in week 0 we are in the first not full week
483 // calculate from the last year
484 if (iWeekOfYear==0)
486 // Special case: we are in the week of 1.1 but 1.1. is not on the
487 // start of week. Calculate based on the last year
488 dDateFirstJanuary = CTime(iYear-1,1,1,0,0,0);
489 iDayOfWeek =
490 (dDateFirstJanuary.GetDayOfWeek()+5+iFirstDayOfWeek)%7;
491 // and we correct this in the same we we done this before but
492 // the result is now 52 or 53 and not 0
493 iWeekOfYear =
494 (int)(((time-dDateFirstJanuary).GetDays()+iDayOfWeek) / 7) +
495 (iDayOfWeek<=3 ? 1:0);
498 break;
499 case 2:
501 // First week containing at least four days is the first week of that year.
503 // Each year can start with any day of the week. But our
504 // weeks always start with Monday. So we add the day of week
505 // before calculation of the final week of year.
506 // Rule: is the 1.1 a Mo,Tu,We,Th than the week starts on the 1.1 with
507 // week==1, else a week later, so we add one for all those days if
508 // day is less <=3 Mo,Tu,We,Th. Otherwise 1.1 is in the last week of the
509 // previous year
510 iWeekOfYear =
511 (int)(((time-dDateFirstJanuary).GetDays()+iDayOfWeek) / 7) +
512 (iDayOfWeek<=3 ? 1:0);
514 // special cases
515 if (iWeekOfYear==0)
517 // special case week 0. We got a day before the 1.1, 2.1 or 3.1, were the
518 // 1.1. is not a Mo, Tu, We, Th. So the week 1 does not start with the 1.1.
519 // So we calculate the week according to the 1.1 of the year before
521 dDateFirstJanuary = CTime(iYear-1,1,1,0,0,0);
522 iDayOfWeek =
523 (dDateFirstJanuary.GetDayOfWeek()+5+iFirstDayOfWeek)%7;
524 // and we correct this in the same we we done this before but the result
525 // is now 52 or 53 and not 0
526 iWeekOfYear =
527 (int)(((time-dDateFirstJanuary).GetDays()+iDayOfWeek) / 7) +
528 (iDayOfWeek<=3 ? 1:0);
530 else if (iWeekOfYear==53)
532 // special case week 53. Either we got the correct week 53 or we just got the
533 // week 1 of the next year. So is the 1.1.(year+1) also a Mo, Tu, We, Th than
534 // we already have the week 1, otherwise week 53 is correct
536 dDateFirstJanuary = CTime(iYear+1,1,1,0,0,0);
537 iDayOfWeek =
538 (dDateFirstJanuary.GetDayOfWeek()+5+iFirstDayOfWeek)%7;
539 // 1.1. in week 1 or week 53?
540 iWeekOfYear = iDayOfWeek<=3 ? 1:53;
543 break;
544 default:
545 ASSERT(FALSE);
546 break;
548 // return result
549 return iWeekOfYear;
552 class CDateSorter
554 public:
555 class CCommitPointer
557 public:
558 CCommitPointer()
559 : m_cont(nullptr)
560 , m_place(0)
561 , m_Date(0)
562 , m_Changes(0)
563 , m_lineInc(0)
564 , m_lineDec(0)
565 , m_lineNew(0)
566 , m_lineDel(0)
568 CCommitPointer(const CCommitPointer& P_Right)
569 : m_cont(nullptr)
570 , m_place(0)
571 , m_Date(0)
572 , m_Changes(0)
573 , m_lineInc(0)
574 , m_lineDec(0)
575 , m_lineNew(0)
576 , m_lineDel(0)
578 *this = P_Right;
581 CCommitPointer& operator = (const CCommitPointer& P_Right)
583 if(IsPointer())
585 (*m_cont->m_parDates)[m_place] = P_Right.GetDate();
586 (*m_cont->m_parFileChanges)[m_place] = P_Right.GetChanges();
587 (*m_cont->m_parAuthors)[m_place] = P_Right.GetAuthor();
588 (*m_cont->m_lineInc)[m_place] = P_Right.GetLineInc();
589 (*m_cont->m_lineDec)[m_place] = P_Right.GetLineDec();
590 (*m_cont->m_lineNew)[m_place] = P_Right.GetLineNew();
591 (*m_cont->m_lineDel)[m_place] = P_Right.GetLineDel();
593 else
595 m_Date = P_Right.GetDate();
596 m_Changes = P_Right.GetChanges();
597 m_csAuthor = P_Right.GetAuthor();
598 m_lineInc = P_Right.GetLineInc();
599 m_lineDec = P_Right.GetLineDec();
600 m_lineNew = P_Right.GetLineNew();
601 m_lineDel = P_Right.GetLineDel();
603 return *this;
606 void Clone(const CCommitPointer& P_Right)
608 m_cont = P_Right.m_cont;
609 m_place = P_Right.m_place;
610 m_Date = P_Right.m_Date;
611 m_Changes = P_Right.m_Changes;
612 m_csAuthor = P_Right.m_csAuthor;
615 DWORD GetDate() const {return IsPointer() ? (*m_cont->m_parDates)[m_place] : m_Date;}
616 DWORD GetChanges() const {return IsPointer() ? (*m_cont->m_parFileChanges)[m_place] : m_Changes;}
617 DWORD GetLineInc() const {return IsPointer() ? (*m_cont->m_lineInc)[m_place] : m_lineInc;}
618 DWORD GetLineDec() const {return IsPointer() ? (*m_cont->m_lineDec)[m_place] : m_lineDec;}
619 DWORD GetLineNew() const {return IsPointer() ? (*m_cont->m_lineNew)[m_place] : m_lineNew;}
620 DWORD GetLineDel() const {return IsPointer() ? (*m_cont->m_lineDel)[m_place] : m_lineDel;}
621 CString GetAuthor() const {return IsPointer() ? (*m_cont->m_parAuthors)[m_place] : m_csAuthor;}
623 bool IsPointer() const { return m_cont != nullptr; }
624 //When pointer
625 CDateSorter* m_cont;
626 int m_place;
628 //When element
629 DWORD m_Date;
630 DWORD m_Changes;
631 DWORD m_lineInc;
632 DWORD m_lineDec;
633 DWORD m_lineNew;
634 DWORD m_lineDel;
635 CString m_csAuthor;
638 class iterator : public std::iterator<std::random_access_iterator_tag, CCommitPointer>
640 public:
641 CCommitPointer m_ptr;
643 iterator(){}
644 iterator(const iterator& P_Right){*this = P_Right;}
645 iterator& operator=(const iterator& P_Right)
647 m_ptr.Clone(P_Right.m_ptr);
648 return *this;
651 CCommitPointer& operator*(){return m_ptr;}
652 CCommitPointer* operator->(){return &m_ptr;}
653 const CCommitPointer& operator*()const{return m_ptr;}
654 const CCommitPointer* operator->()const{return &m_ptr;}
656 iterator& operator+=(size_t P_iOffset){m_ptr.m_place += (int)P_iOffset;return *this;}
657 iterator& operator-=(size_t P_iOffset){m_ptr.m_place -= (int)P_iOffset;return *this;}
658 iterator operator+(size_t P_iOffset)const{iterator it(*this); it += P_iOffset;return it;}
659 iterator operator-(size_t P_iOffset)const{iterator it(*this); it -= P_iOffset;return it;}
661 iterator& operator++(){++m_ptr.m_place;return *this;}
662 iterator& operator--(){--m_ptr.m_place;return *this;}
663 iterator operator++(int){iterator it(*this);++*this;return it;}
664 iterator operator--(int){iterator it(*this);--*this;return it;}
666 size_t operator-(const iterator& P_itRight)const{return m_ptr.m_place - P_itRight->m_place;}
668 bool operator<(const iterator& P_itRight)const{return m_ptr.m_place < P_itRight->m_place;}
669 bool operator!=(const iterator& P_itRight)const{return m_ptr.m_place != P_itRight->m_place;}
670 bool operator==(const iterator& P_itRight)const{return m_ptr.m_place == P_itRight->m_place;}
671 bool operator>(const iterator& P_itRight)const{return m_ptr.m_place > P_itRight->m_place;}
673 iterator begin()
675 iterator it;
676 it->m_place = 0;
677 it->m_cont = this;
678 return it;
680 iterator end()
682 iterator it;
683 it->m_place = (int)m_parDates->GetCount();
684 it->m_cont = this;
685 return it;
688 CDWordArray * m_parDates;
689 CDWordArray * m_parFileChanges;
690 CDWordArray * m_lineInc;
691 CDWordArray * m_lineDec;
692 CDWordArray * m_lineNew;
693 CDWordArray * m_lineDel;
694 CStringArray * m_parAuthors;
697 class CDateSorterLess
699 public:
700 bool operator () (const CDateSorter::CCommitPointer& P_Left, const CDateSorter::CCommitPointer& P_Right) const
702 return P_Left.GetDate() > P_Right.GetDate(); //Last date first
706 int CStatGraphDlg::GatherData(BOOL fetchdiff, BOOL keepFetchedData)
708 m_parAuthors.RemoveAll();
709 m_parDates.RemoveAll();
710 if (m_parFileChanges2.IsEmpty()) // Fixes issue #1948
711 keepFetchedData = FALSE;
712 if (!keepFetchedData)
714 m_parFileChanges.RemoveAll();
715 m_lineInc.RemoveAll();
716 m_lineDec.RemoveAll();
717 m_lineDel.RemoveAll();
718 m_lineNew.RemoveAll();
720 else
722 m_parFileChanges.Copy(m_parFileChanges2);
723 m_lineNew.Copy(m_lineNew2);
724 m_lineDel.Copy(m_lineDel2);
725 m_lineInc.Copy(m_lineInc2);
726 m_lineDec.Copy(m_lineDec2);
729 CSysProgressDlg progress;
730 if (fetchdiff)
732 progress.SetTitle(CString(MAKEINTRESOURCE(IDS_PROGS_TITLE_GATHERSTATISTICS)));
733 progress.FormatNonPathLine(1, IDS_PROC_STATISTICS_DIFF);
734 progress.SetAnimation(IDR_MOVEANI);
735 progress.SetTime(true);
736 progress.ShowModeless(this);
739 // create arrays which are aware of the current filter
740 ULONGLONG starttime = GetTickCount64();
742 GIT_MAILMAP mailmap = nullptr;
743 git_read_mailmap(&mailmap);
744 for (size_t i = 0; i < m_ShowList.size(); ++i)
746 GitRevLoglist* pLogEntry = m_ShowList.SafeGetAt(i);
747 int inc, dec, incnewfile, decdeletedfile, files;
748 inc = dec = incnewfile = decdeletedfile = files= 0;
750 // do not take working dir changes into statistics
751 if (pLogEntry->m_CommitHash.IsEmpty()) {
752 continue;
755 CString strAuthor = pLogEntry->GetAuthorName();
756 if (strAuthor.IsEmpty())
757 strAuthor.LoadString(IDS_STATGRAPH_EMPTYAUTHOR);
758 if (mailmap)
760 CStringA email2A = CUnicodeUtils::GetUTF8(pLogEntry->GetAuthorEmail());
761 struct payload_struct { GitRev* rev; const char *authorName; };
762 payload_struct payload = { pLogEntry, nullptr };
763 const char *author1 = git_get_mailmap_author(mailmap, email2A, &payload,
764 [] (void *payload) -> const char * { return ((payload_struct *)payload)->authorName = _strdup(CUnicodeUtils::GetUTF8(((payload_struct *)payload)->rev->GetAuthorName())); });
765 free((void *)payload.authorName);
766 if (author1)
767 strAuthor = CUnicodeUtils::GetUnicode(author1);
769 m_parAuthors.Add(strAuthor);
770 m_parDates.Add((DWORD)pLogEntry->GetCommitterDate().GetTime());
772 if (fetchdiff && (pLogEntry->m_ParentHash.size() <= 1))
774 CTGitPathList& list = pLogEntry->GetFiles(nullptr);
775 files = list.GetCount();
777 for (int j = 0; j < files; j++)
779 if (list[j].m_Action & CTGitPath::LOGACTIONS_DELETED)
780 decdeletedfile += _tstol(list[j].m_StatDel);
781 else if(list[j].m_Action & CTGitPath::LOGACTIONS_ADDED)
782 incnewfile += _tstol(list[j].m_StatAdd);
783 else
785 inc += _tstol(list[j].m_StatAdd);
786 dec += _tstol(list[j].m_StatDel);
789 if (progress.HasUserCancelled())
791 git_free_mailmap(mailmap);
792 return -1;
796 if (!keepFetchedData)
798 m_parFileChanges.Add(files);
799 m_lineInc.Add(inc);
800 m_lineDec.Add(dec);
801 m_lineDel.Add(decdeletedfile);
802 m_lineNew.Add(incnewfile);
805 if (progress.IsVisible() && (GetTickCount64() - starttime > 100UL))
807 progress.FormatNonPathLine(2, _T("%s: %s"), (LPCTSTR)pLogEntry->m_CommitHash.ToString().Left(g_Git.GetShortHASHLength()), (LPCTSTR)pLogEntry->GetSubject());
808 progress.SetProgress64(i, m_ShowList.size());
809 starttime = GetTickCount64();
813 git_free_mailmap(mailmap);
815 if (fetchdiff)
817 m_parFileChanges2.Copy(m_parFileChanges);
818 m_lineNew2.Copy(m_lineNew);
819 m_lineDel2.Copy(m_lineDel);
820 m_lineInc2.Copy(m_lineInc);
821 m_lineDec2.Copy(m_lineDec);
824 CDateSorter W_Sorter;
825 W_Sorter.m_parAuthors = &m_parAuthors;
826 W_Sorter.m_parDates = &m_parDates;
827 W_Sorter.m_parFileChanges = &m_parFileChanges;
828 W_Sorter.m_lineNew = &m_lineNew;
829 W_Sorter.m_lineDel = &m_lineDel;
830 W_Sorter.m_lineInc = &m_lineInc;
831 W_Sorter.m_lineDec = &m_lineDec;
833 std::sort(W_Sorter.begin(), W_Sorter.end(), CDateSorterLess());
835 m_nTotalCommits = m_parAuthors.GetCount();
836 m_nTotalFileChanges = 0;
838 // Update m_nWeeks and m_minDate
839 UpdateWeekCount();
841 // Now create a mapping that holds the information per week.
842 m_commitsPerUnitAndAuthor.clear();
843 m_filechangesPerUnitAndAuthor.clear();
844 m_commitsPerAuthor.clear();
845 m_PercentageOfAuthorship.clear();
846 m_LinesWPerUnitAndAuthor.clear();
847 m_LinesWOPerUnitAndAuthor.clear();
849 int interval = 0;
850 __time64_t d = (__time64_t)m_parDates.GetAt(0);
851 int nLastUnit = GetUnit(d);
852 double AllContributionAuthor = 0;
854 m_nTotalLinesInc = m_nTotalLinesDec = m_nTotalLinesNew = m_nTotalLinesDel =0;
856 // Now loop over all weeks and gather the info
857 for (LONG i=0; i<m_nTotalCommits; ++i)
859 // Find the interval number
860 __time64_t commitDate = (__time64_t)m_parDates.GetAt(i);
861 int u = GetUnit(commitDate);
862 if (nLastUnit != u)
863 interval++;
864 nLastUnit = u;
865 // Find the authors name
866 CString sAuth = m_parAuthors.GetAt(i);
867 if (!m_bAuthorsCaseSensitive)
868 sAuth = sAuth.MakeLower();
869 tstring author = tstring(sAuth);
870 // Increase total commit count for this author
871 m_commitsPerAuthor[author]++;
872 // Increase the commit count for this author in this week
873 m_commitsPerUnitAndAuthor[interval][author]++;
875 m_LinesWPerUnitAndAuthor[interval][author] += m_lineInc.GetAt(i) + m_lineDec.GetAt(i) + m_lineNew.GetAt(i) + + m_lineDel.GetAt(i);
876 m_LinesWOPerUnitAndAuthor[interval][author] += m_lineInc.GetAt(i) + m_lineDec.GetAt(i);
878 CTime t = m_parDates.GetAt(i);
879 m_unitNames[interval] = GetUnitLabel(nLastUnit, t);
880 // Increase the file change count for this author in this week
881 int fileChanges = m_parFileChanges.GetAt(i);
882 m_filechangesPerUnitAndAuthor[interval][author] += fileChanges;
883 m_nTotalFileChanges += fileChanges;
885 //calculate Contribution Author
886 double contributionAuthor = CoeffContribution((int)m_nTotalCommits - i -1) * (fileChanges ? fileChanges : 1);
887 AllContributionAuthor += contributionAuthor;
888 m_PercentageOfAuthorship[author] += contributionAuthor;
890 m_nTotalLinesInc += m_lineInc.GetAt(i);
891 m_nTotalLinesDec += m_lineDec.GetAt(i);
892 m_nTotalLinesNew += m_lineNew.GetAt(i);
893 m_nTotalLinesDel += m_lineDel.GetAt(i);
896 // Find first and last interval number.
897 if (!m_commitsPerUnitAndAuthor.empty())
899 IntervalDataMap::iterator interval_it = m_commitsPerUnitAndAuthor.begin();
900 m_firstInterval = interval_it->first;
901 interval_it = m_commitsPerUnitAndAuthor.end();
902 --interval_it;
903 m_lastInterval = interval_it->first;
904 // Sanity check - if m_lastInterval is too large it could freeze TSVN and take up all memory!!!
905 assert(m_lastInterval >= 0 && m_lastInterval < 10000);
907 else
909 m_firstInterval = 0;
910 m_lastInterval = -1;
913 // Get a list of authors names
914 LoadListOfAuthors(m_commitsPerAuthor);
916 // Calculate percent of Contribution Authors
917 for (std::list<tstring>::iterator it = m_authorNames.begin(); it != m_authorNames.end(); ++it)
919 m_PercentageOfAuthorship[*it] = (m_PercentageOfAuthorship[*it] *100)/ AllContributionAuthor;
922 // All done, now the statistics pages can retrieve the data and
923 // extract the information to be shown.
925 return 0;
928 void CStatGraphDlg::FilterSkippedAuthors(std::list<tstring>& included_authors,
929 std::list<tstring>& skipped_authors)
931 included_authors.clear();
932 skipped_authors.clear();
934 unsigned int included_authors_count = m_Skipper.GetPos();
935 // if we only leave out one author, still include him with his name
936 if (included_authors_count + 1 == m_authorNames.size())
937 ++included_authors_count;
939 // add the included authors first
940 std::list<tstring>::iterator author_it = m_authorNames.begin();
941 while (included_authors_count > 0 && author_it != m_authorNames.end())
943 // Add him/her to the included list
944 included_authors.push_back(*author_it);
945 ++author_it;
946 --included_authors_count;
949 // If we haven't reached the end yet, copy all remaining authors into the
950 // skipped author list.
951 std::copy(author_it, m_authorNames.end(), std::back_inserter(skipped_authors) );
953 // Sort authors alphabetically if user wants that.
954 if (!m_bSortByCommitCount)
955 included_authors.sort();
958 bool CStatGraphDlg::PreViewStat(bool fShowLabels)
960 if (m_parAuthors.IsEmpty() || m_parDates.IsEmpty() || m_parFileChanges.IsEmpty())
961 return false;
962 ShowLabels(fShowLabels);
964 //If view graphic
965 if (!fShowLabels) ClearGraph();
967 // This function relies on a previous call of GatherData().
968 // This can be detected by checking the week count.
969 // If the week count is equal to -1, it hasn't been called before.
970 if (m_nWeeks == -1)
971 GatherData(FALSE, TRUE);
972 // If week count is still -1, something bad has happened, probably invalid data!
973 if (m_nWeeks == -1)
974 return false;
976 return true;
979 MyGraphSeries *CStatGraphDlg::PreViewGraph(__in UINT GraphTitle, __in UINT YAxisLabel, __in UINT XAxisLabel /*= nullptr*/)
981 if(!PreViewStat(false))
982 return nullptr;
984 // We need at least one author
985 if (m_authorNames.empty())
986 return nullptr;
988 // Add a single series to the chart
989 MyGraphSeries * graphData = new MyGraphSeries();
990 m_graph.AddSeries(*graphData);
991 m_graphDataArray.Add(graphData);
993 // Set up the graph.
994 CString temp;
995 UpdateData();
996 m_graph.SetGraphType(m_GraphType, m_bStacked);
997 temp.LoadString(YAxisLabel);
998 m_graph.SetYAxisLabel(temp);
999 temp.LoadString(XAxisLabel);
1000 m_graph.SetXAxisLabel(temp);
1001 temp.LoadString(GraphTitle);
1002 m_graph.SetGraphTitle(temp);
1004 return graphData;
1007 void CStatGraphDlg::ShowPercentageOfAuthorship()
1009 // Set up the graph.
1010 MyGraphSeries * graphData = PreViewGraph(IDS_STATGRAPH_PERCENTAGE_OF_AUTHORSHIP,
1011 IDS_STATGRAPH_PERCENTAGE_OF_AUTHORSHIPY,
1012 IDS_STATGRAPH_COMMITSBYAUTHORMOREX);
1013 if (!graphData) return;
1015 // Find out which authors are to be shown and which are to be skipped.
1016 std::list<tstring> authors;
1017 std::list<tstring> others;
1020 FilterSkippedAuthors(authors, others);
1022 // Loop over all authors in the authors list and
1023 // add them to the graph.
1025 if (!authors.empty())
1027 for (std::list<tstring>::iterator it = authors.begin(); it != authors.end(); ++it)
1029 int group = m_graph.AppendGroup(it->c_str());
1030 graphData->SetData(group, RollPercentageOfAuthorship(m_PercentageOfAuthorship[*it]));
1034 // If we have other authors, count them and their commits.
1035 if (!others.empty())
1036 DrawOthers(others, graphData, m_PercentageOfAuthorship);
1038 // Paint the graph now that we're through.
1039 m_graph.Invalidate();
1042 void CStatGraphDlg::ShowCommitsByAuthor()
1044 // Set up the graph.
1045 MyGraphSeries * graphData = PreViewGraph(IDS_STATGRAPH_COMMITSBYAUTHOR,
1046 IDS_STATGRAPH_COMMITSBYAUTHORY,
1047 IDS_STATGRAPH_COMMITSBYAUTHORX);
1048 if (!graphData) return;
1050 // Find out which authors are to be shown and which are to be skipped.
1051 std::list<tstring> authors;
1052 std::list<tstring> others;
1053 FilterSkippedAuthors(authors, others);
1055 // Loop over all authors in the authors list and
1056 // add them to the graph.
1058 if (!authors.empty())
1060 for (std::list<tstring>::iterator it = authors.begin(); it != authors.end(); ++it)
1062 int group = m_graph.AppendGroup(it->c_str());
1063 graphData->SetData(group, m_commitsPerAuthor[*it]);
1067 // If we have other authors, count them and their commits.
1068 if (!others.empty())
1069 DrawOthers(others, graphData, m_commitsPerAuthor);
1071 // Paint the graph now that we're through.
1072 m_graph.Invalidate();
1075 void CStatGraphDlg::ShowByDate(int stringx, int title, IntervalDataMap &data)
1077 if(!PreViewStat(false)) return;
1079 // We need at least one author
1080 if (m_authorNames.empty()) return;
1082 // Set up the graph.
1083 CString temp;
1084 UpdateData();
1085 m_graph.SetGraphType(m_GraphType, m_bStacked);
1086 temp.LoadString(stringx);
1087 m_graph.SetYAxisLabel(temp);
1088 temp.LoadString(title);
1089 m_graph.SetGraphTitle(temp);
1091 m_graph.SetXAxisLabel(GetUnitString());
1093 // Find out which authors are to be shown and which are to be skipped.
1094 std::list<tstring> authors;
1095 std::list<tstring> others;
1096 FilterSkippedAuthors(authors, others);
1098 // Add a graph series for each author.
1099 AuthorDataMap authorGraphMap;
1100 for (std::list<tstring>::iterator it = authors.begin(); it != authors.end(); ++it)
1101 authorGraphMap[*it] = m_graph.AppendGroup(it->c_str());
1102 // If we have skipped authors, add a graph series for all those.
1103 CString sOthers(MAKEINTRESOURCE(IDS_STATGRAPH_OTHERGROUP));
1104 tstring othersName;
1105 if (!others.empty())
1107 sOthers.AppendFormat(L" (%Iu)", others.size());
1108 othersName = (LPCWSTR)sOthers;
1109 authorGraphMap[othersName] = m_graph.AppendGroup(sOthers);
1112 // Mapping to collect commit counts in each interval
1113 AuthorDataMap commitCount;
1115 // Loop over all intervals/weeks and collect filtered data.
1116 // Sum up data in each interval until the time unit changes.
1117 for (int i=m_lastInterval; i>=m_firstInterval; --i)
1119 // Collect data for authors listed by name.
1120 if (!authors.empty())
1122 for (std::list<tstring>::iterator it = authors.begin(); it != authors.end(); ++it)
1124 // Do we have some data for the current author in the current interval?
1125 AuthorDataMap::const_iterator data_it = data[i].find(*it);
1126 if (data_it == data[i].end())
1127 continue;
1128 commitCount[*it] += data_it->second;
1131 // Collect data for all skipped authors.
1132 if (!others.empty())
1134 for (std::list<tstring>::iterator it = others.begin(); it != others.end(); ++it)
1136 // Do we have some data for the author in the current interval?
1137 AuthorDataMap::const_iterator data_it = data[i].find(*it);
1138 if (data_it == data[i].end())
1139 continue;
1140 commitCount[othersName] += data_it->second;
1144 // Create a new data series for this unit/interval.
1145 MyGraphSeries * graphData = new MyGraphSeries();
1146 // Loop over all created graphs and set the corresponding data.
1147 if (!authorGraphMap.empty())
1149 for (AuthorDataMap::const_iterator it = authorGraphMap.begin(); it != authorGraphMap.end(); ++it)
1151 graphData->SetData(it->second, commitCount[it->first]);
1154 graphData->SetLabel(m_unitNames[i].c_str());
1155 m_graph.AddSeries(*graphData);
1156 m_graphDataArray.Add(graphData);
1158 // Reset commit count mapping.
1159 commitCount.clear();
1162 // Paint the graph now that we're through.
1163 m_graph.Invalidate();
1166 void CStatGraphDlg::ShowStats()
1168 if(!PreViewStat(true)) return;
1170 // Now we can use the gathered data to update the stats dialog.
1171 size_t nAuthors = m_authorNames.size();
1173 // Find most and least active author names.
1174 tstring mostActiveAuthor;
1175 tstring leastActiveAuthor;
1176 if (nAuthors > 0)
1178 mostActiveAuthor = m_authorNames.front();
1179 leastActiveAuthor = m_authorNames.back();
1182 // Obtain the statistics for the table.
1183 long nCommitsMin = -1;
1184 long nCommitsMax = -1;
1185 long nFileChangesMin = -1;
1186 long nFileChangesMax = -1;
1188 long nMostActiveMaxCommits = -1;
1189 long nMostActiveMinCommits = -1;
1190 long nLeastActiveMaxCommits = -1;
1191 long nLeastActiveMinCommits = -1;
1193 // Loop over all intervals and find min and max values for commit count and file changes.
1194 // Also store the stats for the most and least active authors.
1195 for (int i=m_firstInterval; i<=m_lastInterval; ++i)
1197 // Loop over all commits in this interval and count the number of commits by all authors.
1198 int commitCount = 0;
1199 AuthorDataMap::iterator commit_endit = m_commitsPerUnitAndAuthor[i].end();
1200 for (AuthorDataMap::iterator commit_it = m_commitsPerUnitAndAuthor[i].begin();
1201 commit_it != commit_endit; ++commit_it)
1203 commitCount += commit_it->second;
1205 if (nCommitsMin == -1 || commitCount < nCommitsMin)
1206 nCommitsMin = commitCount;
1207 if (nCommitsMax == -1 || commitCount > nCommitsMax)
1208 nCommitsMax = commitCount;
1210 // Loop over all commits in this interval and count the number of file changes by all authors.
1211 int fileChangeCount = 0;
1212 AuthorDataMap::iterator filechange_endit = m_filechangesPerUnitAndAuthor[i].end();
1213 for (AuthorDataMap::iterator filechange_it = m_filechangesPerUnitAndAuthor[i].begin();
1214 filechange_it != filechange_endit; ++filechange_it)
1216 fileChangeCount += filechange_it->second;
1218 if (nFileChangesMin == -1 || fileChangeCount < nFileChangesMin)
1219 nFileChangesMin = fileChangeCount;
1220 if (nFileChangesMax == -1 || fileChangeCount > nFileChangesMax)
1221 nFileChangesMax = fileChangeCount;
1223 // also get min/max data for most and least active authors
1224 if (nAuthors > 0)
1226 // check if author is present in this interval
1227 AuthorDataMap::iterator author_it = m_commitsPerUnitAndAuthor[i].find(mostActiveAuthor);
1228 long authorCommits;
1229 if (author_it == m_commitsPerUnitAndAuthor[i].end())
1230 authorCommits = 0;
1231 else
1232 authorCommits = author_it->second;
1233 if (nMostActiveMaxCommits == -1 || authorCommits > nMostActiveMaxCommits)
1234 nMostActiveMaxCommits = authorCommits;
1235 if (nMostActiveMinCommits == -1 || authorCommits < nMostActiveMinCommits)
1236 nMostActiveMinCommits = authorCommits;
1238 author_it = m_commitsPerUnitAndAuthor[i].find(leastActiveAuthor);
1239 if (author_it == m_commitsPerUnitAndAuthor[i].end())
1240 authorCommits = 0;
1241 else
1242 authorCommits = author_it->second;
1243 if (nLeastActiveMaxCommits == -1 || authorCommits > nLeastActiveMaxCommits)
1244 nLeastActiveMaxCommits = authorCommits;
1245 if (nLeastActiveMinCommits == -1 || authorCommits < nLeastActiveMinCommits)
1246 nLeastActiveMinCommits = authorCommits;
1249 if (nMostActiveMaxCommits == -1) nMostActiveMaxCommits = 0;
1250 if (nMostActiveMinCommits == -1) nMostActiveMinCommits = 0;
1251 if (nLeastActiveMaxCommits == -1) nLeastActiveMaxCommits = 0;
1252 if (nLeastActiveMinCommits == -1) nLeastActiveMinCommits = 0;
1254 int nWeeks = m_lastInterval-m_firstInterval;
1255 if (nWeeks == 0)
1256 nWeeks = 1;
1257 // Adjust the labels with the unit type (week, month, ...)
1258 CString labelText;
1259 labelText.Format(IDS_STATGRAPH_NUMBEROFUNIT, (LPCTSTR)GetUnitString());
1260 SetDlgItemText(IDC_NUMWEEK, labelText);
1261 labelText.Format(IDS_STATGRAPH_COMMITSBYUNIT, (LPCTSTR)GetUnitString());
1262 SetDlgItemText(IDC_COMMITSEACHWEEK, labelText);
1263 labelText.Format(IDS_STATGRAPH_FILECHANGESBYUNIT, (LPCTSTR)GetUnitString());
1264 SetDlgItemText(IDC_FILECHANGESEACHWEEK, (LPCTSTR)labelText);
1265 // We have now all data we want and we can fill in the labels...
1266 CString number;
1267 number.Format(_T("%d"), nWeeks);
1268 SetDlgItemText(IDC_NUMWEEKVALUE, number);
1269 number.Format(_T("%Iu"), nAuthors);
1270 SetDlgItemText(IDC_NUMAUTHORVALUE, number);
1271 number.Format(_T("%Id"), m_nTotalCommits);
1272 SetDlgItemText(IDC_NUMCOMMITSVALUE, number);
1273 number.Format(_T("%ld"), m_nTotalFileChanges);
1274 if (m_bDiffFetched)
1275 SetDlgItemText(IDC_NUMFILECHANGESVALUE, number);
1277 number.Format(_T("%Id"), m_parAuthors.GetCount() / nWeeks);
1278 SetDlgItemText(IDC_COMMITSEACHWEEKAVG, number);
1279 number.Format(_T("%ld"), nCommitsMax);
1280 SetDlgItemText(IDC_COMMITSEACHWEEKMAX, number);
1281 number.Format(_T("%ld"), nCommitsMin);
1282 SetDlgItemText(IDC_COMMITSEACHWEEKMIN, number);
1284 number.Format(_T("%ld"), m_nTotalFileChanges / nWeeks);
1285 //SetDlgItemText(IDC_FILECHANGESEACHWEEKAVG, number);
1286 number.Format(_T("%ld"), nFileChangesMax);
1287 //SetDlgItemText(IDC_FILECHANGESEACHWEEKMAX, number);
1288 number.Format(_T("%ld"), nFileChangesMin);
1289 //SetDlgItemText(IDC_FILECHANGESEACHWEEKMIN, number);
1291 number.Format(_T("%ld (%ld (+) %ld (-))"), m_nTotalLinesInc + m_nTotalLinesDec, m_nTotalLinesInc, m_nTotalLinesDec);
1292 if (m_bDiffFetched)
1293 SetDlgItemText(IDC_TOTAL_LINE_WITHOUT_NEW_DEL_VALUE, number);
1294 number.Format(_T("%ld (%ld (+) %ld (-))"), m_nTotalLinesInc + m_nTotalLinesDec + m_nTotalLinesNew + m_nTotalLinesDel,
1295 m_nTotalLinesInc + m_nTotalLinesNew, m_nTotalLinesDec + m_nTotalLinesDel);
1296 if (m_bDiffFetched)
1297 SetDlgItemText(IDC_TOTAL_LINE_WITH_NEW_DEL_VALUE, number);
1299 if (nAuthors == 0)
1301 SetDlgItemText(IDC_MOSTACTIVEAUTHORNAME, _T(""));
1302 SetDlgItemText(IDC_MOSTACTIVEAUTHORAVG, _T("0"));
1303 SetDlgItemText(IDC_MOSTACTIVEAUTHORMAX, _T("0"));
1304 SetDlgItemText(IDC_MOSTACTIVEAUTHORMIN, _T("0"));
1305 SetDlgItemText(IDC_LEASTACTIVEAUTHORNAME, _T(""));
1306 SetDlgItemText(IDC_LEASTACTIVEAUTHORAVG, _T("0"));
1307 SetDlgItemText(IDC_LEASTACTIVEAUTHORMAX, _T("0"));
1308 SetDlgItemText(IDC_LEASTACTIVEAUTHORMIN, _T("0"));
1310 else
1312 SetDlgItemText(IDC_MOSTACTIVEAUTHORNAME, mostActiveAuthor.c_str());
1313 number.Format(_T("%ld"), m_commitsPerAuthor[mostActiveAuthor] / nWeeks);
1314 SetDlgItemText(IDC_MOSTACTIVEAUTHORAVG, number);
1315 number.Format(_T("%ld"), nMostActiveMaxCommits);
1316 SetDlgItemText(IDC_MOSTACTIVEAUTHORMAX, number);
1317 number.Format(_T("%ld"), nMostActiveMinCommits);
1318 SetDlgItemText(IDC_MOSTACTIVEAUTHORMIN, number);
1320 SetDlgItemText(IDC_LEASTACTIVEAUTHORNAME, leastActiveAuthor.c_str());
1321 number.Format(_T("%ld"), m_commitsPerAuthor[leastActiveAuthor] / nWeeks);
1322 SetDlgItemText(IDC_LEASTACTIVEAUTHORAVG, number);
1323 number.Format(_T("%ld"), nLeastActiveMaxCommits);
1324 SetDlgItemText(IDC_LEASTACTIVEAUTHORMAX, number);
1325 number.Format(_T("%ld"), nLeastActiveMinCommits);
1326 SetDlgItemText(IDC_LEASTACTIVEAUTHORMIN, number);
1330 int CStatGraphDlg::RollPercentageOfAuthorship(double it)
1331 { return (int)it + (it - (int)it >= 0.5);}
1333 void CStatGraphDlg::OnCbnSelchangeGraphcombo()
1335 UpdateData();
1337 Metrics useMetric = (Metrics) m_cGraphType.GetItemData(m_cGraphType.GetCurSel());
1338 switch (useMetric )
1340 case AllStat:
1341 case CommitsByDate:
1342 // by date
1343 m_btnGraphLine.EnableWindow(TRUE);
1344 m_btnGraphLineStacked.EnableWindow(TRUE);
1345 m_btnGraphPie.EnableWindow(TRUE);
1346 m_GraphType = MyGraph::Line;
1347 m_bStacked = false;
1348 break;
1349 case PercentageOfAuthorship:
1350 case CommitsByAuthor:
1351 // by author
1352 m_btnGraphLine.EnableWindow(FALSE);
1353 m_btnGraphLineStacked.EnableWindow(FALSE);
1354 m_btnGraphPie.EnableWindow(TRUE);
1355 m_GraphType = MyGraph::Bar;
1356 m_bStacked = false;
1357 break;
1359 RedrawGraph();
1363 int CStatGraphDlg::GetUnitCount()
1365 if (m_nDays < 8)
1366 return m_nDays;
1367 if (m_nWeeks < 15)
1368 return m_nWeeks;
1369 if (m_nWeeks < 80)
1370 return (m_nWeeks/4)+1;
1371 if (m_nWeeks < 320)
1372 return (m_nWeeks/13)+1; // quarters
1373 return (m_nWeeks/52)+1;
1376 int CStatGraphDlg::GetUnit(const CTime& time)
1378 if (m_nDays < 8)
1379 return time.GetMonth()*100 + time.GetDay(); // month*100+day as the unit
1380 if (m_nWeeks < 15)
1381 return GetCalendarWeek(time);
1382 if (m_nWeeks < 80)
1383 return time.GetMonth();
1384 if (m_nWeeks < 320)
1385 return ((time.GetMonth()-1)/3)+1; // quarters
1386 return time.GetYear();
1389 CStatGraphDlg::UnitType CStatGraphDlg::GetUnitType()
1391 if (m_nDays < 8)
1392 return Days;
1393 if (m_nWeeks < 15)
1394 return Weeks;
1395 if (m_nWeeks < 80)
1396 return Months;
1397 if (m_nWeeks < 320)
1398 return Quarters;
1399 return Years;
1402 CString CStatGraphDlg::GetUnitString()
1404 if (m_nDays < 8)
1405 return CString(MAKEINTRESOURCE(IDS_STATGRAPH_COMMITSBYDATEXDAY));
1406 if (m_nWeeks < 15)
1407 return CString(MAKEINTRESOURCE(IDS_STATGRAPH_COMMITSBYDATEXWEEK));
1408 if (m_nWeeks < 80)
1409 return CString(MAKEINTRESOURCE(IDS_STATGRAPH_COMMITSBYDATEXMONTH));
1410 if (m_nWeeks < 320)
1411 return CString(MAKEINTRESOURCE(IDS_STATGRAPH_COMMITSBYDATEXQUARTER));
1412 return CString(MAKEINTRESOURCE(IDS_STATGRAPH_COMMITSBYDATEXYEAR));
1415 CString CStatGraphDlg::GetUnitLabel(int unit, CTime &lasttime)
1417 CString temp;
1418 switch (GetUnitType())
1420 case Days:
1422 // month*100+day as the unit
1423 int day = unit % 100;
1424 int month = unit / 100;
1425 switch (m_langOrder)
1427 case 0: // month day year
1428 temp.Format(_T("%d/%d/%.2d"), month, day, lasttime.GetYear()%100);
1429 break;
1430 case 1: // day month year
1431 default:
1432 temp.Format(_T("%d/%d/%.2d"), day, month, lasttime.GetYear()%100);
1433 break;
1434 case 2: // year month day
1435 temp.Format(_T("%.2d/%d/%d"), lasttime.GetYear()%100, month, day);
1436 break;
1439 break;
1440 case Weeks:
1442 int year = lasttime.GetYear();
1443 if ((unit == 1)&&(lasttime.GetMonth() == 12))
1444 year += 1;
1446 switch (m_langOrder)
1448 case 0: // month day year
1449 case 1: // day month year
1450 default:
1451 temp.Format(_T("%d/%.2d"), unit, year%100);
1452 break;
1453 case 2: // year month day
1454 temp.Format(_T("%.2d/%d"), year%100, unit);
1455 break;
1458 break;
1459 case Months:
1460 switch (m_langOrder)
1462 case 0: // month day year
1463 case 1: // day month year
1464 default:
1465 temp.Format(_T("%d/%.2d"), unit, lasttime.GetYear()%100);
1466 break;
1467 case 2: // year month day
1468 temp.Format(_T("%.2d/%d"), lasttime.GetYear()%100, unit);
1469 break;
1471 break;
1472 case Quarters:
1473 switch (m_langOrder)
1475 case 0: // month day year
1476 case 1: // day month year
1477 default:
1478 temp.Format(_T("%d/%.2d"), unit, lasttime.GetYear()%100);
1479 break;
1480 case 2: // year month day
1481 temp.Format(_T("%.2d/%d"), lasttime.GetYear()%100, unit);
1482 break;
1484 break;
1485 case Years:
1486 temp.Format(_T("%d"), unit);
1487 break;
1489 return temp;
1492 void CStatGraphDlg::OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar)
1494 if (nSBCode == TB_THUMBTRACK)
1495 return CDialog::OnHScroll(nSBCode, nPos, pScrollBar);
1497 ShowSelectStat((Metrics) m_cGraphType.GetItemData(m_cGraphType.GetCurSel()));
1498 CDialog::OnHScroll(nSBCode, nPos, pScrollBar);
1501 void CStatGraphDlg::OnNeedText(NMHDR *pnmh, LRESULT * /*pResult*/)
1503 TOOLTIPTEXT* pttt = (TOOLTIPTEXT*) pnmh;
1504 if (pttt->hdr.idFrom == (UINT_PTR) m_Skipper.GetSafeHwnd())
1506 size_t included_authors_count = m_Skipper.GetPos();
1507 // if we only leave out one author, still include him with his name
1508 if (included_authors_count + 1 == m_authorNames.size())
1509 ++included_authors_count;
1511 // find the minimum number of commits that the shown authors have
1512 int min_commits = 0;
1513 included_authors_count = min(included_authors_count, m_authorNames.size());
1514 std::list<tstring>::iterator author_it = m_authorNames.begin();
1515 advance(author_it, included_authors_count);
1516 if (author_it != m_authorNames.begin())
1517 min_commits = m_commitsPerAuthor[ *(--author_it) ];
1519 CString string;
1520 int percentage = int(min_commits*100.0/(m_nTotalCommits ? m_nTotalCommits : 1));
1521 string.Format(IDS_STATGRAPH_AUTHORSLIDER_TT, m_Skipper.GetPos(), min_commits, percentage);
1522 StringCchCopy(pttt->szText, _countof(pttt->szText), (LPCTSTR) string);
1526 void CStatGraphDlg::AuthorsCaseSensitiveChanged()
1528 UpdateData(); // update checkbox state
1529 GatherData(FALSE, TRUE); // first regenerate the statistics data
1530 RedrawGraph(); // then update the current statistics page
1533 void CStatGraphDlg::SortModeChanged()
1535 UpdateData(); // update checkbox state
1536 RedrawGraph(); // then update the current statistics page
1539 void CStatGraphDlg::ClearGraph()
1541 m_graph.Clear();
1542 for (int j=0; j<m_graphDataArray.GetCount(); ++j)
1543 delete ((MyGraphSeries *)m_graphDataArray.GetAt(j));
1544 m_graphDataArray.RemoveAll();
1547 void CStatGraphDlg::RedrawGraph()
1549 EnableDisableMenu();
1550 m_btnGraphBar.SetState(BST_UNCHECKED);
1551 m_btnGraphBarStacked.SetState(BST_UNCHECKED);
1552 m_btnGraphLine.SetState(BST_UNCHECKED);
1553 m_btnGraphLineStacked.SetState(BST_UNCHECKED);
1554 m_btnGraphPie.SetState(BST_UNCHECKED);
1556 if ((m_GraphType == MyGraph::Bar)&&(m_bStacked))
1558 m_btnGraphBarStacked.SetState(BST_CHECKED);
1560 if ((m_GraphType == MyGraph::Bar)&&(!m_bStacked))
1562 m_btnGraphBar.SetState(BST_CHECKED);
1564 if ((m_GraphType == MyGraph::Line)&&(m_bStacked))
1566 m_btnGraphLineStacked.SetState(BST_CHECKED);
1568 if ((m_GraphType == MyGraph::Line)&&(!m_bStacked))
1570 m_btnGraphLine.SetState(BST_CHECKED);
1572 if (m_GraphType == MyGraph::PieChart)
1574 m_btnGraphPie.SetState(BST_CHECKED);
1577 UpdateData();
1578 ShowSelectStat((Metrics) m_cGraphType.GetItemData(m_cGraphType.GetCurSel()), true);
1580 void CStatGraphDlg::OnBnClickedGraphbarbutton()
1582 m_GraphType = MyGraph::Bar;
1583 m_bStacked = false;
1584 RedrawGraph();
1587 void CStatGraphDlg::OnBnClickedGraphbarstackedbutton()
1589 m_GraphType = MyGraph::Bar;
1590 m_bStacked = true;
1591 RedrawGraph();
1594 void CStatGraphDlg::OnBnClickedGraphlinebutton()
1596 m_GraphType = MyGraph::Line;
1597 m_bStacked = false;
1598 RedrawGraph();
1601 void CStatGraphDlg::OnBnClickedGraphlinestackedbutton()
1603 m_GraphType = MyGraph::Line;
1604 m_bStacked = true;
1605 RedrawGraph();
1608 void CStatGraphDlg::OnBnClickedGraphpiebutton()
1610 m_GraphType = MyGraph::PieChart;
1611 m_bStacked = false;
1612 RedrawGraph();
1615 void CStatGraphDlg::EnableDisableMenu()
1617 UINT nEnable = MF_BYCOMMAND;
1619 Metrics SelectMetric = (Metrics) m_cGraphType.GetItemData(m_cGraphType.GetCurSel());
1621 nEnable |= (SelectMetric > TextStatStart && SelectMetric < TextStatEnd)
1622 ? (MF_DISABLED | MF_GRAYED) : MF_ENABLED;
1624 GetMenu()->EnableMenuItem(ID_FILE_SAVESTATGRAPHAS, nEnable);
1627 void CStatGraphDlg::OnFileSavestatgraphas()
1629 CString tempfile;
1630 int filterindex = 0;
1631 if (CAppUtils::FileOpenSave(tempfile, &filterindex, IDS_REVGRAPH_SAVEPIC, IDS_STATPICFILEFILTER, false, m_hWnd))
1633 // if the user doesn't specify a file extension, default to
1634 // wmf and add that extension to the filename. But only if the
1635 // user chose the 'pictures' filter. The filename isn't changed
1636 // if the 'All files' filter was chosen.
1637 CString extension;
1638 int dotPos = tempfile.ReverseFind('.');
1639 int slashPos = tempfile.ReverseFind('\\');
1640 if (dotPos > slashPos)
1641 extension = tempfile.Mid(dotPos);
1642 if ((filterindex == 1)&&(extension.IsEmpty()))
1644 extension = _T(".wmf");
1645 tempfile += extension;
1647 SaveGraph(tempfile);
1651 void CStatGraphDlg::SaveGraph(CString sFilename)
1653 CString extension = CPathUtils::GetFileExtFromPath(sFilename);
1654 if (extension.CompareNoCase(_T(".wmf"))==0)
1656 // save the graph as an enhanced meta file
1657 CMyMetaFileDC wmfDC;
1658 wmfDC.CreateEnhanced(nullptr, sFilename, nullptr, _T("TortoiseGit\0Statistics\0\0"));
1659 wmfDC.SetAttribDC(GetDC()->GetSafeHdc());
1660 RedrawGraph();
1661 m_graph.DrawGraph(wmfDC);
1662 HENHMETAFILE hemf = wmfDC.CloseEnhanced();
1663 DeleteEnhMetaFile(hemf);
1665 else
1667 // save the graph as a pixel picture instead of a vector picture
1668 // create dc to paint on
1671 CWindowDC ddc(this);
1672 CDC dc;
1673 if (!dc.CreateCompatibleDC(&ddc))
1675 ShowErrorMessage();
1676 return;
1678 CRect rect;
1679 GetDlgItem(IDC_GRAPH)->GetClientRect(&rect);
1680 HBITMAP hbm = ::CreateCompatibleBitmap(ddc.m_hDC, rect.Width(), rect.Height());
1681 if (hbm==0)
1683 ShowErrorMessage();
1684 return;
1686 HBITMAP oldbm = (HBITMAP)dc.SelectObject(hbm);
1687 // paint the whole graph
1688 RedrawGraph();
1689 m_graph.DrawGraph(dc);
1690 // now use GDI+ to save the picture
1691 CLSID encoderClsid;
1692 GdiplusStartupInput gdiplusStartupInput;
1693 ULONG_PTR gdiplusToken;
1694 CString sErrormessage;
1695 if (GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, nullptr) == Ok)
1698 Bitmap bitmap(hbm, nullptr);
1699 if (bitmap.GetLastStatus()==Ok)
1701 // Get the CLSID of the encoder.
1702 int ret = 0;
1703 if (CPathUtils::GetFileExtFromPath(sFilename).CompareNoCase(_T(".png"))==0)
1704 ret = GetEncoderClsid(L"image/png", &encoderClsid);
1705 else if (CPathUtils::GetFileExtFromPath(sFilename).CompareNoCase(_T(".jpg"))==0)
1706 ret = GetEncoderClsid(L"image/jpeg", &encoderClsid);
1707 else if (CPathUtils::GetFileExtFromPath(sFilename).CompareNoCase(_T(".jpeg"))==0)
1708 ret = GetEncoderClsid(L"image/jpeg", &encoderClsid);
1709 else if (CPathUtils::GetFileExtFromPath(sFilename).CompareNoCase(_T(".bmp"))==0)
1710 ret = GetEncoderClsid(L"image/bmp", &encoderClsid);
1711 else if (CPathUtils::GetFileExtFromPath(sFilename).CompareNoCase(_T(".gif"))==0)
1712 ret = GetEncoderClsid(L"image/gif", &encoderClsid);
1713 else
1715 sFilename += _T(".jpg");
1716 ret = GetEncoderClsid(L"image/jpeg", &encoderClsid);
1718 if (ret >= 0)
1720 CStringW tfile = CStringW(sFilename);
1721 bitmap.Save(tfile, &encoderClsid, nullptr);
1723 else
1724 sErrormessage.Format(IDS_REVGRAPH_ERR_NOENCODER, (LPCTSTR)CPathUtils::GetFileExtFromPath(sFilename));
1726 else
1727 sErrormessage.LoadString(IDS_REVGRAPH_ERR_NOBITMAP);
1729 GdiplusShutdown(gdiplusToken);
1731 else
1732 sErrormessage.LoadString(IDS_REVGRAPH_ERR_GDIINIT);
1733 dc.SelectObject(oldbm);
1734 dc.DeleteDC();
1735 if (!sErrormessage.IsEmpty())
1736 ::MessageBox(m_hWnd, sErrormessage, _T("TortoiseGit"), MB_ICONERROR);
1738 catch (CException * pE)
1740 TCHAR szErrorMsg[2048] = { 0 };
1741 pE->GetErrorMessage(szErrorMsg, 2048);
1742 pE->Delete();
1743 ::MessageBox(m_hWnd, szErrorMsg, _T("TortoiseGit"), MB_ICONERROR);
1748 int CStatGraphDlg::GetEncoderClsid(const WCHAR* format, CLSID* pClsid)
1750 UINT num = 0; // number of image encoders
1751 UINT size = 0; // size of the image encoder array in bytes
1753 if (GetImageEncodersSize(&num, &size)!=Ok)
1754 return -1;
1755 if (size == 0)
1756 return -1; // Failure
1758 auto pMem = std::make_unique<BYTE[]>(size);
1759 auto pImageCodecInfo = (ImageCodecInfo*)(pMem.get());
1760 if (!pImageCodecInfo)
1761 return -1; // Failure
1763 if (GetImageEncoders(num, size, pImageCodecInfo)==Ok)
1765 for (UINT j = 0; j < num; ++j)
1767 if (wcscmp(pImageCodecInfo[j].MimeType, format) == 0)
1769 *pClsid = pImageCodecInfo[j].Clsid;
1770 return j; // Success
1774 return -1; // Failure
1777 void CStatGraphDlg::StoreCurrentGraphType()
1779 UpdateData();
1780 DWORD graphtype = static_cast<DWORD>(m_cGraphType.GetItemData(m_cGraphType.GetCurSel()));
1781 // encode the current chart type
1782 DWORD statspage = graphtype*10;
1783 if ((m_GraphType == MyGraph::Bar)&&(m_bStacked))
1784 statspage += 1;
1785 if ((m_GraphType == MyGraph::Bar)&&(!m_bStacked))
1786 statspage += 2;
1787 if ((m_GraphType == MyGraph::Line)&&(m_bStacked))
1788 statspage += 3;
1789 if ((m_GraphType == MyGraph::Line)&&(!m_bStacked))
1790 statspage += 4;
1791 if (m_GraphType == MyGraph::PieChart)
1792 statspage += 5;
1794 // store current chart type in registry
1795 CRegDWORD lastStatsPage(_T("Software\\TortoiseGit\\LastViewedStatsPage"), 0);
1796 lastStatsPage = statspage;
1798 CRegDWORD regAuthors(_T("Software\\TortoiseGit\\StatAuthorsCaseSensitive"));
1799 regAuthors = m_bAuthorsCaseSensitive;
1801 CRegDWORD regSort(_T("Software\\TortoiseGit\\StatSortByCommitCount"));
1802 regSort = m_bSortByCommitCount;
1805 void CStatGraphDlg::ShowErrorMessage()
1807 CFormatMessageWrapper errorDetails;
1808 if (errorDetails)
1809 MessageBox( errorDetails, _T("Error"), MB_OK | MB_ICONINFORMATION );
1812 void CStatGraphDlg::ShowSelectStat(Metrics SelectedMetric, bool reloadSkiper /* = false */)
1814 switch (SelectedMetric)
1816 case AllStat:
1817 LoadListOfAuthors(m_commitsPerAuthor, reloadSkiper);
1818 ShowStats();
1819 break;
1820 case CommitsByDate:
1821 LoadListOfAuthors(m_commitsPerAuthor, reloadSkiper);
1822 ShowByDate(IDS_STATGRAPH_COMMITSBYDATEY, IDS_STATGRAPH_COMMITSBYDATE, m_commitsPerUnitAndAuthor);
1823 break;
1824 case LinesWByDate:
1825 OnBnClickedFetchDiff();
1826 LoadListOfAuthors(m_commitsPerAuthor, reloadSkiper);
1827 ShowByDate(IDS_STATGRAPH_LINES_BYDATE_W_Y, IDS_STATGRAPH_LINES_BYDATE_W, m_LinesWPerUnitAndAuthor);
1828 break;
1829 case LinesWOByDate:
1830 OnBnClickedFetchDiff();
1831 LoadListOfAuthors(m_commitsPerAuthor, reloadSkiper);
1832 ShowByDate(IDS_STATGRAPH_LINES_BYDATE_WO_Y, IDS_STATGRAPH_LINES_BYDATE_WO, m_LinesWOPerUnitAndAuthor);
1833 break;
1834 case CommitsByAuthor:
1835 LoadListOfAuthors(m_commitsPerAuthor, reloadSkiper);
1836 ShowCommitsByAuthor();
1837 break;
1838 case PercentageOfAuthorship:
1839 OnBnClickedFetchDiff();
1840 LoadListOfAuthors(m_PercentageOfAuthorship, reloadSkiper, true);
1841 ShowPercentageOfAuthorship();
1842 break;
1843 default:
1844 ShowErrorMessage();
1848 double CStatGraphDlg::CoeffContribution(int distFromEnd) { return distFromEnd ? 1.0 / m_CoeffAuthorShip * distFromEnd : 1;}
1851 template <class MAP>
1852 void CStatGraphDlg::DrawOthers(const std::list<tstring> &others, MyGraphSeries *graphData, MAP &map)
1854 int nCommits = 0;
1855 for (std::list<tstring>::const_iterator it = others.begin(); it != others.end(); ++it)
1856 nCommits += RollPercentageOfAuthorship(map[*it]);
1858 CString sOthers(MAKEINTRESOURCE(IDS_STATGRAPH_OTHERGROUP));
1859 sOthers.AppendFormat(L" (%Iu)", others.size());
1860 int group = m_graph.AppendGroup(sOthers);
1861 graphData->SetData(group, (int)nCommits);
1865 template <class MAP>
1866 void CStatGraphDlg::LoadListOfAuthors (MAP &map, bool reloadSkiper/*= false*/, bool compare /*= false*/)
1868 m_authorNames.clear();
1869 if (!map.empty())
1871 for (MAP::const_iterator it = map.begin(); it != map.end(); ++it)
1873 if ((compare && RollPercentageOfAuthorship(map[it->first]) != 0) || !compare)
1874 m_authorNames.push_back(it->first);
1878 // Sort the list of authors based on commit count
1879 m_authorNames.sort(MoreCommitsThan<MAP::mapped_type>(map));
1881 // Set Skipper
1882 SetSkipper(reloadSkiper);
1886 void CStatGraphDlg::OnBnClickedFetchDiff()
1888 if (m_bDiffFetched)
1889 return;
1890 if (GatherData(TRUE))
1891 return;
1892 this->m_bDiffFetched = TRUE;
1893 GetDlgItem(IDC_CALC_DIFF)->ShowWindow(!m_bDiffFetched);
1895 ShowStats();