updated copyright year of files we changed since 2012-01-01
[TortoiseGit.git] / src / TortoiseProc / StatGraphDlg.cpp
blobeb78467c726719452f1781675a87e98e4b0cedac
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2012 - TortoiseGit
4 // Copyright (C) 2003-2011 - 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 "StringUtils.h"
26 #include "PathUtils.h"
27 #include "MessageBox.h"
28 #include "Registry.h"
29 #include "FormatMessageWrapper.h"
31 #include <cmath>
32 #include <locale>
33 #include <list>
34 #include <utility>
36 using namespace Gdiplus;
38 // BinaryPredicate for comparing authors based on their commit count
39 template<class DataType>
40 class MoreCommitsThan : public std::binary_function<tstring, tstring, bool> {
41 public:
42 typedef std::map<tstring, DataType> MapType;
43 MoreCommitsThan(MapType &author_commits) : m_authorCommits(author_commits) {}
45 bool operator()(const tstring& lhs, const tstring& rhs) {
46 return (m_authorCommits)[lhs] > (m_authorCommits)[rhs];
49 private:
50 MapType &m_authorCommits;
54 IMPLEMENT_DYNAMIC(CStatGraphDlg, CResizableStandAloneDialog)
55 CStatGraphDlg::CStatGraphDlg(CWnd* pParent /*=NULL*/)
56 : CResizableStandAloneDialog(CStatGraphDlg::IDD, pParent)
57 , m_bStacked(FALSE)
58 , m_GraphType(MyGraph::Bar)
59 , m_bAuthorsCaseSensitive(TRUE)
60 , m_bSortByCommitCount(TRUE)
61 , m_nWeeks(-1)
62 , m_nDays(-1)
63 , m_langOrder(0)
64 , m_firstInterval(0)
65 , m_lastInterval(0)
67 m_parDates = NULL;
68 m_parFileChanges = NULL;
69 m_parAuthors = NULL;
70 m_pToolTip = NULL;
73 CStatGraphDlg::~CStatGraphDlg()
75 ClearGraph();
76 delete m_pToolTip;
79 void CStatGraphDlg::OnOK() {
80 StoreCurrentGraphType();
81 __super::OnOK();
84 void CStatGraphDlg::OnCancel() {
85 StoreCurrentGraphType();
86 __super::OnCancel();
89 void CStatGraphDlg::DoDataExchange(CDataExchange* pDX)
91 CResizableStandAloneDialog::DoDataExchange(pDX);
92 DDX_Control(pDX, IDC_GRAPH, m_graph);
93 DDX_Control(pDX, IDC_GRAPHCOMBO, m_cGraphType);
94 DDX_Control(pDX, IDC_SKIPPER, m_Skipper);
95 DDX_Check(pDX, IDC_AUTHORSCASESENSITIVE, m_bAuthorsCaseSensitive);
96 DDX_Check(pDX, IDC_SORTBYCOMMITCOUNT, m_bSortByCommitCount);
97 DDX_Control(pDX, IDC_GRAPHBARBUTTON, m_btnGraphBar);
98 DDX_Control(pDX, IDC_GRAPHBARSTACKEDBUTTON, m_btnGraphBarStacked);
99 DDX_Control(pDX, IDC_GRAPHLINEBUTTON, m_btnGraphLine);
100 DDX_Control(pDX, IDC_GRAPHLINESTACKEDBUTTON, m_btnGraphLineStacked);
101 DDX_Control(pDX, IDC_GRAPHPIEBUTTON, m_btnGraphPie);
105 BEGIN_MESSAGE_MAP(CStatGraphDlg, CResizableStandAloneDialog)
106 ON_CBN_SELCHANGE(IDC_GRAPHCOMBO, OnCbnSelchangeGraphcombo)
107 ON_WM_HSCROLL()
108 ON_NOTIFY(TTN_NEEDTEXT, NULL, OnNeedText)
109 ON_BN_CLICKED(IDC_AUTHORSCASESENSITIVE, &CStatGraphDlg::AuthorsCaseSensitiveChanged)
110 ON_BN_CLICKED(IDC_SORTBYCOMMITCOUNT, &CStatGraphDlg::SortModeChanged)
111 ON_BN_CLICKED(IDC_GRAPHBARBUTTON, &CStatGraphDlg::OnBnClickedGraphbarbutton)
112 ON_BN_CLICKED(IDC_GRAPHBARSTACKEDBUTTON, &CStatGraphDlg::OnBnClickedGraphbarstackedbutton)
113 ON_BN_CLICKED(IDC_GRAPHLINEBUTTON, &CStatGraphDlg::OnBnClickedGraphlinebutton)
114 ON_BN_CLICKED(IDC_GRAPHLINESTACKEDBUTTON, &CStatGraphDlg::OnBnClickedGraphlinestackedbutton)
115 ON_BN_CLICKED(IDC_GRAPHPIEBUTTON, &CStatGraphDlg::OnBnClickedGraphpiebutton)
116 ON_COMMAND(ID_FILE_SAVESTATGRAPHAS, &CStatGraphDlg::OnFileSavestatgraphas)
117 END_MESSAGE_MAP()
119 void CStatGraphDlg::LoadStatQueries (__in UINT curStr, Metrics loadMetric, bool setDef /* = false */)
121 CString temp;
122 temp.LoadString(curStr);
123 int sel = m_cGraphType.AddString(temp);
124 m_cGraphType.SetItemData(sel, loadMetric);
126 if (setDef) m_cGraphType.SetCurSel(sel);
129 void CStatGraphDlg::SetSkipper (bool reloadSkiper)
131 // We need to limit the number of authors due to GUI resource limitation.
132 // However, since author #251 will properly have < 1000th of the commits,
133 // the resolution limit of the screen will already not allow for displaying
134 // it in a reasonable way
136 int max_authors_count = max(1, (int)min(m_authorNames.size(), 250) );
137 m_Skipper.SetRange (1, max_authors_count);
138 m_Skipper.SetPageSize(5);
140 if (reloadSkiper)
141 m_Skipper.SetPos (max_authors_count);
144 BOOL CStatGraphDlg::OnInitDialog()
146 CResizableStandAloneDialog::OnInitDialog();
148 m_pToolTip = new CToolTipCtrl;
149 if (m_pToolTip->Create(this))
151 m_pToolTip->AddTool(&m_btnGraphPie, IDS_STATGRAPH_PIEBUTTON_TT);
152 m_pToolTip->AddTool(&m_btnGraphLineStacked, IDS_STATGRAPH_LINESTACKEDBUTTON_TT);
153 m_pToolTip->AddTool(&m_btnGraphLine, IDS_STATGRAPH_LINEBUTTON_TT);
154 m_pToolTip->AddTool(&m_btnGraphBarStacked, IDS_STATGRAPH_BARSTACKEDBUTTON_TT);
155 m_pToolTip->AddTool(&m_btnGraphBar, IDS_STATGRAPH_BARBUTTON_TT);
157 m_pToolTip->Activate(TRUE);
160 m_bAuthorsCaseSensitive = DWORD(CRegDWORD(_T("Software\\TortoiseGit\\StatAuthorsCaseSensitive")));
161 m_bSortByCommitCount = DWORD(CRegDWORD(_T("Software\\TortoiseGit\\StatSortByCommitCount")));
162 UpdateData(FALSE);
164 //Load statistical queries
165 LoadStatQueries(IDS_STATGRAPH_STATS, AllStat, true);
166 LoadStatQueries(IDS_STATGRAPH_COMMITSBYDATE, CommitsByDate);
167 LoadStatQueries(IDS_STATGRAPH_COMMITSBYAUTHOR, CommitsByAuthor);
168 LoadStatQueries(IDS_STATGRAPH_PERCENTAGE_OF_AUTHORSHIP, PercentageOfAuthorship);
170 // set the dialog title to "Statistics - path/to/whatever/we/show/the/statistics/for"
171 CString sTitle;
172 GetWindowText(sTitle);
173 CAppUtils::SetWindowTitle(m_hWnd, m_path.GetUIPathString(), sTitle);
175 m_btnGraphBar.SetImage((HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDI_GRAPHBAR), IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR));
176 m_btnGraphBar.SizeToContent();
177 m_btnGraphBar.Invalidate();
178 m_btnGraphBarStacked.SetImage((HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDI_GRAPHBARSTACKED), IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR));
179 m_btnGraphBarStacked.SizeToContent();
180 m_btnGraphBarStacked.Invalidate();
181 m_btnGraphLine.SetImage((HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDI_GRAPHLINE), IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR));
182 m_btnGraphLine.SizeToContent();
183 m_btnGraphLine.Invalidate();
184 m_btnGraphLineStacked.SetImage((HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDI_GRAPHLINESTACKED), IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR));
185 m_btnGraphLineStacked.SizeToContent();
186 m_btnGraphLineStacked.Invalidate();
187 m_btnGraphPie.SetImage((HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDI_GRAPHPIE), IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR));
188 m_btnGraphPie.SizeToContent();
189 m_btnGraphPie.Invalidate();
191 AddAnchor(IDC_GRAPHTYPELABEL, TOP_LEFT);
192 AddAnchor(IDC_GRAPH, TOP_LEFT, BOTTOM_RIGHT);
193 AddAnchor(IDC_GRAPHCOMBO, TOP_LEFT, TOP_RIGHT);
195 AddAnchor(IDC_NUMWEEK, TOP_LEFT);
196 AddAnchor(IDC_NUMWEEKVALUE, TOP_RIGHT);
197 AddAnchor(IDC_NUMAUTHOR, TOP_LEFT);
198 AddAnchor(IDC_NUMAUTHORVALUE, TOP_RIGHT);
199 AddAnchor(IDC_NUMCOMMITS, TOP_LEFT);
200 AddAnchor(IDC_NUMCOMMITSVALUE, TOP_RIGHT);
201 AddAnchor(IDC_NUMFILECHANGES, TOP_LEFT);
202 AddAnchor(IDC_NUMFILECHANGESVALUE, TOP_RIGHT);
204 AddAnchor(IDC_AVG, TOP_RIGHT);
205 AddAnchor(IDC_MIN, TOP_RIGHT);
206 AddAnchor(IDC_MAX, TOP_RIGHT);
207 AddAnchor(IDC_COMMITSEACHWEEK, TOP_LEFT);
208 AddAnchor(IDC_MOSTACTIVEAUTHOR, TOP_LEFT);
209 AddAnchor(IDC_LEASTACTIVEAUTHOR, TOP_LEFT);
210 AddAnchor(IDC_MOSTACTIVEAUTHORNAME, TOP_LEFT, TOP_RIGHT);
211 AddAnchor(IDC_LEASTACTIVEAUTHORNAME, TOP_LEFT, TOP_RIGHT);
212 AddAnchor(IDC_FILECHANGESEACHWEEK, TOP_LEFT);
213 AddAnchor(IDC_COMMITSEACHWEEKAVG, TOP_RIGHT);
214 AddAnchor(IDC_COMMITSEACHWEEKMIN, TOP_RIGHT);
215 AddAnchor(IDC_COMMITSEACHWEEKMAX, TOP_RIGHT);
216 AddAnchor(IDC_MOSTACTIVEAUTHORAVG, TOP_RIGHT);
217 AddAnchor(IDC_MOSTACTIVEAUTHORMIN, TOP_RIGHT);
218 AddAnchor(IDC_MOSTACTIVEAUTHORMAX, TOP_RIGHT);
219 AddAnchor(IDC_LEASTACTIVEAUTHORAVG, TOP_RIGHT);
220 AddAnchor(IDC_LEASTACTIVEAUTHORMIN, TOP_RIGHT);
221 AddAnchor(IDC_LEASTACTIVEAUTHORMAX, TOP_RIGHT);
222 AddAnchor(IDC_FILECHANGESEACHWEEKAVG, TOP_RIGHT);
223 AddAnchor(IDC_FILECHANGESEACHWEEKMIN, TOP_RIGHT);
224 AddAnchor(IDC_FILECHANGESEACHWEEKMAX, TOP_RIGHT);
226 AddAnchor(IDC_GRAPHBARBUTTON, BOTTOM_RIGHT);
227 AddAnchor(IDC_GRAPHBARSTACKEDBUTTON, BOTTOM_RIGHT);
228 AddAnchor(IDC_GRAPHLINEBUTTON, BOTTOM_RIGHT);
229 AddAnchor(IDC_GRAPHLINESTACKEDBUTTON, BOTTOM_RIGHT);
230 AddAnchor(IDC_GRAPHPIEBUTTON, BOTTOM_RIGHT);
232 AddAnchor(IDC_AUTHORSCASESENSITIVE, BOTTOM_LEFT);
233 AddAnchor(IDC_SORTBYCOMMITCOUNT, BOTTOM_LEFT);
234 AddAnchor(IDC_SKIPPER, BOTTOM_LEFT, BOTTOM_RIGHT);
235 AddAnchor(IDC_SKIPPERLABEL, BOTTOM_LEFT);
236 AddAnchor(IDOK, BOTTOM_RIGHT);
237 EnableSaveRestore(_T("StatGraphDlg"));
239 // gather statistics data, only needs to be updated when the checkbox with
240 // the case sensitivity of author names is changed
241 GatherData();
243 // set the min/max values on the skipper
244 SetSkipper (true);
246 // we use a stats page encoding here, 0 stands for the statistics dialog
247 CRegDWORD lastStatsPage = CRegDWORD(_T("Software\\TortoiseGit\\LastViewedStatsPage"), 0);
249 // open last viewed statistics page as first page
250 int graphtype = lastStatsPage / 10;
251 for (int i = 0; i < m_cGraphType.GetCount(); i++)
253 if (m_cGraphType.GetItemData(i) == graphtype)
255 m_cGraphType.SetCurSel(i);
256 break;
260 OnCbnSelchangeGraphcombo();
262 int statspage = lastStatsPage % 10;
263 switch (statspage) {
264 case 1 :
265 m_GraphType = MyGraph::Bar;
266 m_bStacked = true;
267 break;
268 case 2 :
269 m_GraphType = MyGraph::Bar;
270 m_bStacked = false;
271 break;
272 case 3 :
273 m_GraphType = MyGraph::Line;
274 m_bStacked = true;
275 break;
276 case 4 :
277 m_GraphType = MyGraph::Line;
278 m_bStacked = false;
279 break;
280 case 5 :
281 m_GraphType = MyGraph::PieChart;
282 break;
284 default : return TRUE;
287 LCID m_locale = MAKELCID((DWORD)CRegStdDWORD(_T("Software\\TortoiseGit\\LanguageID"), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT)), SORT_DEFAULT);
289 bool bUseSystemLocale = !!(DWORD)CRegStdDWORD(_T("Software\\TortoiseGit\\UseSystemLocaleForDates"), TRUE);
290 LCID locale = bUseSystemLocale ? MAKELCID(MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), SORT_DEFAULT) : m_locale;
292 TCHAR l = 0;
293 GetLocaleInfo(locale, LOCALE_IDATE, &l, sizeof(TCHAR));
295 m_langOrder = (l > 0) ? l - '0' : -1;
297 RedrawGraph();
299 return TRUE;
302 void CStatGraphDlg::ShowLabels(BOOL bShow)
304 if ((m_parAuthors==NULL)||(m_parDates==NULL)||(m_parFileChanges==NULL))
305 return;
307 int nCmdShow = bShow ? SW_SHOW : SW_HIDE;
309 GetDlgItem(IDC_GRAPH)->ShowWindow(bShow ? SW_HIDE : SW_SHOW);
310 GetDlgItem(IDC_NUMWEEK)->ShowWindow(nCmdShow);
311 GetDlgItem(IDC_NUMWEEKVALUE)->ShowWindow(nCmdShow);
312 GetDlgItem(IDC_NUMAUTHOR)->ShowWindow(nCmdShow);
313 GetDlgItem(IDC_NUMAUTHORVALUE)->ShowWindow(nCmdShow);
314 GetDlgItem(IDC_NUMCOMMITS)->ShowWindow(nCmdShow);
315 GetDlgItem(IDC_NUMCOMMITSVALUE)->ShowWindow(nCmdShow);
316 //GetDlgItem(IDC_NUMFILECHANGES)->ShowWindow(nCmdShow);
317 GetDlgItem(IDC_NUMFILECHANGESVALUE)->ShowWindow(nCmdShow);
319 GetDlgItem(IDC_AVG)->ShowWindow(nCmdShow);
320 GetDlgItem(IDC_MIN)->ShowWindow(nCmdShow);
321 GetDlgItem(IDC_MAX)->ShowWindow(nCmdShow);
322 GetDlgItem(IDC_COMMITSEACHWEEK)->ShowWindow(nCmdShow);
323 GetDlgItem(IDC_MOSTACTIVEAUTHOR)->ShowWindow(nCmdShow);
324 GetDlgItem(IDC_LEASTACTIVEAUTHOR)->ShowWindow(nCmdShow);
325 GetDlgItem(IDC_MOSTACTIVEAUTHORNAME)->ShowWindow(nCmdShow);
326 GetDlgItem(IDC_LEASTACTIVEAUTHORNAME)->ShowWindow(nCmdShow);
327 //GetDlgItem(IDC_FILECHANGESEACHWEEK)->ShowWindow(nCmdShow);
328 GetDlgItem(IDC_COMMITSEACHWEEKAVG)->ShowWindow(nCmdShow);
329 GetDlgItem(IDC_COMMITSEACHWEEKMIN)->ShowWindow(nCmdShow);
330 GetDlgItem(IDC_COMMITSEACHWEEKMAX)->ShowWindow(nCmdShow);
331 GetDlgItem(IDC_MOSTACTIVEAUTHORAVG)->ShowWindow(nCmdShow);
332 GetDlgItem(IDC_MOSTACTIVEAUTHORMIN)->ShowWindow(nCmdShow);
333 GetDlgItem(IDC_MOSTACTIVEAUTHORMAX)->ShowWindow(nCmdShow);
334 GetDlgItem(IDC_LEASTACTIVEAUTHORAVG)->ShowWindow(nCmdShow);
335 GetDlgItem(IDC_LEASTACTIVEAUTHORMIN)->ShowWindow(nCmdShow);
336 GetDlgItem(IDC_LEASTACTIVEAUTHORMAX)->ShowWindow(nCmdShow);
337 GetDlgItem(IDC_FILECHANGESEACHWEEKAVG)->ShowWindow(nCmdShow);
338 GetDlgItem(IDC_FILECHANGESEACHWEEKMIN)->ShowWindow(nCmdShow);
339 GetDlgItem(IDC_FILECHANGESEACHWEEKMAX)->ShowWindow(nCmdShow);
341 GetDlgItem(IDC_SORTBYCOMMITCOUNT)->ShowWindow(bShow ? SW_HIDE : SW_SHOW);
342 GetDlgItem(IDC_SKIPPER)->ShowWindow(bShow ? SW_HIDE : SW_SHOW);
343 GetDlgItem(IDC_SKIPPERLABEL)->ShowWindow(bShow ? SW_HIDE : SW_SHOW);
344 m_btnGraphBar.ShowWindow(bShow ? SW_HIDE : SW_SHOW);
345 m_btnGraphBarStacked.ShowWindow(bShow ? SW_HIDE : SW_SHOW);
346 m_btnGraphLine.ShowWindow(bShow ? SW_HIDE : SW_SHOW);
347 m_btnGraphLineStacked.ShowWindow(bShow ? SW_HIDE : SW_SHOW);
348 m_btnGraphPie.ShowWindow(bShow ? SW_HIDE : SW_SHOW);
351 void CStatGraphDlg::UpdateWeekCount()
353 // Sanity check
354 if ((!m_parDates)||(m_parDates->GetCount()==0))
355 return;
357 // Already updated? No need to do it again.
358 if (m_nWeeks >= 0)
359 return;
361 // Determine first and last date in dates array
362 __time64_t min_date = (__time64_t)m_parDates->GetAt(0);
363 __time64_t max_date = min_date;
364 INT_PTR count = m_parDates->GetCount();
365 for (INT_PTR i=0; i<count; ++i)
367 __time64_t d = (__time64_t)m_parDates->GetAt(i);
368 if (d < min_date) min_date = d;
369 else if (d > max_date) max_date = d;
372 // Store start date of the interval in the member variable m_minDate
373 m_minDate = min_date;
374 m_maxDate = max_date;
376 // How many weeks does the time period cover?
378 // Get time difference between start and end date
379 double secs = _difftime64(max_date, m_minDate);
381 m_nWeeks = (int)ceil(secs / (double) m_SecondsInWeek);
382 m_nDays = (int)ceil(secs / (double) m_SecondsInDay);
385 int CStatGraphDlg::GetCalendarWeek(const CTime& time)
387 // Note:
388 // the calculation of the calendar week is wrong if DST is in effect
389 // and the date to calculate the week for is in DST and within the range
390 // of the DST offset (e.g. one hour).
391 // For example, if DST starts on Sunday march 30 and the date to get the week for
392 // is Monday, march 31, 0:30:00, then the returned week is one week less than
393 // the real week.
394 // TODO: ?
395 // write a function
396 // getDSTOffset(const CTime& time)
397 // which returns the DST offset for a given time/date. Then we can use this offset
398 // to correct our GetDays() calculation to get the correct week again
399 // This of course won't work for 'history' dates, because Windows doesn't have
400 // that information (only Vista has such a function: GetTimeZoneInformationForYear() )
401 int iWeekOfYear = 0;
403 int iYear = time.GetYear();
404 int iFirstDayOfWeek = 0;
405 int iFirstWeekOfYear = 0;
406 TCHAR loc[2];
407 GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_IFIRSTDAYOFWEEK, loc, _countof(loc));
408 iFirstDayOfWeek = int(loc[0]-'0');
409 GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_IFIRSTWEEKOFYEAR, loc, _countof(loc));
410 iFirstWeekOfYear = int(loc[0]-'0');
411 CTime dDateFirstJanuary(iYear,1,1,0,0,0);
412 int iDayOfWeek = (dDateFirstJanuary.GetDayOfWeek()+5+iFirstDayOfWeek)%7;
414 // Select mode
415 // 0 Week containing 1/1 is the first week of that year.
416 // 1 First full week following 1/1 is the first week of that year.
417 // 2 First week containing at least four days is the first week of that year.
418 switch (iFirstWeekOfYear)
420 case 0:
422 // Week containing 1/1 is the first week of that year.
424 // check if this week reaches into the next year
425 dDateFirstJanuary = CTime(iYear+1,1,1,0,0,0);
427 // Get start of week
430 iDayOfWeek = (time.GetDayOfWeek()+5+iFirstDayOfWeek)%7;
432 catch (CException* e)
434 e->Delete();
436 CTime dStartOfWeek = time-CTimeSpan(iDayOfWeek,0,0,0);
438 // If this week spans over to 1/1 this is week 1
439 if (dStartOfWeek + CTimeSpan(6,0,0,0) >= dDateFirstJanuary)
441 // we are in the last week of the year that spans over 1/1
442 iWeekOfYear = 1;
444 else
446 // Get week day of 1/1
447 dDateFirstJanuary = CTime(iYear,1,1,0,0,0);
448 iDayOfWeek = (dDateFirstJanuary.GetDayOfWeek() +5 + iFirstDayOfWeek) % 7;
449 // Just count from 1/1
450 iWeekOfYear = (int)(((time-dDateFirstJanuary).GetDays() + iDayOfWeek) / 7) + 1;
453 break;
454 case 1:
456 // First full week following 1/1 is the first week of that year.
458 // If the 1.1 is the start of the week everything is ok
459 // else we need the next week is the correct result
460 iWeekOfYear =
461 (int)(((time-dDateFirstJanuary).GetDays() + iDayOfWeek) / 7) +
462 (iDayOfWeek==0 ? 1:0);
464 // If we are in week 0 we are in the first not full week
465 // calculate from the last year
466 if (iWeekOfYear==0)
468 // Special case: we are in the week of 1.1 but 1.1. is not on the
469 // start of week. Calculate based on the last year
470 dDateFirstJanuary = CTime(iYear-1,1,1,0,0,0);
471 iDayOfWeek =
472 (dDateFirstJanuary.GetDayOfWeek()+5+iFirstDayOfWeek)%7;
473 // and we correct this in the same we we done this before but
474 // the result is now 52 or 53 and not 0
475 iWeekOfYear =
476 (int)(((time-dDateFirstJanuary).GetDays()+iDayOfWeek) / 7) +
477 (iDayOfWeek<=3 ? 1:0);
480 break;
481 case 2:
483 // First week containing at least four days is the first week of that year.
485 // Each year can start with any day of the week. But our
486 // weeks always start with Monday. So we add the day of week
487 // before calculation of the final week of year.
488 // Rule: is the 1.1 a Mo,Tu,We,Th than the week starts on the 1.1 with
489 // week==1, else a week later, so we add one for all those days if
490 // day is less <=3 Mo,Tu,We,Th. Otherwise 1.1 is in the last week of the
491 // previous year
492 iWeekOfYear =
493 (int)(((time-dDateFirstJanuary).GetDays()+iDayOfWeek) / 7) +
494 (iDayOfWeek<=3 ? 1:0);
496 // special cases
497 if (iWeekOfYear==0)
499 // special case week 0. We got a day before the 1.1, 2.1 or 3.1, were the
500 // 1.1. is not a Mo, Tu, We, Th. So the week 1 does not start with the 1.1.
501 // So we calculate the week according to the 1.1 of the year before
503 dDateFirstJanuary = CTime(iYear-1,1,1,0,0,0);
504 iDayOfWeek =
505 (dDateFirstJanuary.GetDayOfWeek()+5+iFirstDayOfWeek)%7;
506 // and we correct this in the same we we done this before but the result
507 // is now 52 or 53 and not 0
508 iWeekOfYear =
509 (int)(((time-dDateFirstJanuary).GetDays()+iDayOfWeek) / 7) +
510 (iDayOfWeek<=3 ? 1:0);
512 else if (iWeekOfYear==53)
514 // special case week 53. Either we got the correct week 53 or we just got the
515 // week 1 of the next year. So is the 1.1.(year+1) also a Mo, Tu, We, Th than
516 // we already have the week 1, otherwise week 53 is correct
518 dDateFirstJanuary = CTime(iYear+1,1,1,0,0,0);
519 iDayOfWeek =
520 (dDateFirstJanuary.GetDayOfWeek()+5+iFirstDayOfWeek)%7;
521 // 1.1. in week 1 or week 53?
522 iWeekOfYear = iDayOfWeek<=3 ? 1:53;
525 break;
526 default:
527 ASSERT(FALSE);
528 break;
530 // return result
531 return iWeekOfYear;
534 void CStatGraphDlg::GatherData()
536 // Sanity check
537 if ((m_parAuthors==NULL)||(m_parDates==NULL)||(m_parFileChanges==NULL))
538 return;
539 m_nTotalCommits = m_parAuthors->GetCount();
540 m_nTotalFileChanges = 0;
542 // Update m_nWeeks and m_minDate
543 UpdateWeekCount();
545 // Now create a mapping that holds the information per week.
546 m_commitsPerUnitAndAuthor.clear();
547 m_filechangesPerUnitAndAuthor.clear();
548 m_commitsPerAuthor.clear();
549 m_PercentageOfAuthorship.clear();
551 int interval = 0;
552 __time64_t d = (__time64_t)m_parDates->GetAt(0);
553 int nLastUnit = GetUnit(d);
554 double AllContributionAuthor = 0;
556 // Now loop over all weeks and gather the info
557 for (LONG i=0; i<m_nTotalCommits; ++i)
559 // Find the interval number
560 __time64_t commitDate = (__time64_t)m_parDates->GetAt(i);
561 int u = GetUnit(commitDate);
562 if (nLastUnit != u)
563 interval++;
564 nLastUnit = u;
565 // Find the authors name
566 CString sAuth = m_parAuthors->GetAt(i);
567 if (!m_bAuthorsCaseSensitive)
568 sAuth = sAuth.MakeLower();
569 tstring author = tstring(sAuth);
570 // Increase total commit count for this author
571 m_commitsPerAuthor[author]++;
572 // Increase the commit count for this author in this week
573 m_commitsPerUnitAndAuthor[interval][author]++;
574 CTime t = m_parDates->GetAt(i);
575 m_unitNames[interval] = GetUnitLabel(nLastUnit, t);
576 // Increase the file change count for this author in this week
577 int fileChanges = m_parFileChanges->GetAt(i);
578 m_filechangesPerUnitAndAuthor[interval][author] += fileChanges;
579 m_nTotalFileChanges += fileChanges;
581 //calculate Contribution Author
582 double contributionAuthor = CoeffContribution((int)m_nTotalCommits - i -1) * fileChanges;
583 AllContributionAuthor += contributionAuthor;
584 m_PercentageOfAuthorship[author] += contributionAuthor;
587 // Find first and last interval number.
588 if (!m_commitsPerUnitAndAuthor.empty())
590 IntervalDataMap::iterator interval_it = m_commitsPerUnitAndAuthor.begin();
591 m_firstInterval = interval_it->first;
592 interval_it = m_commitsPerUnitAndAuthor.end();
593 --interval_it;
594 m_lastInterval = interval_it->first;
595 // Sanity check - if m_lastInterval is too large it could freeze TSVN and take up all memory!!!
596 assert(m_lastInterval >= 0 && m_lastInterval < 10000);
598 else
600 m_firstInterval = 0;
601 m_lastInterval = -1;
604 // Get a list of authors names
605 LoadListOfAuthors(m_commitsPerAuthor);
607 // Calculate percent of Contribution Authors
608 for (std::list<tstring>::iterator it = m_authorNames.begin(); it != m_authorNames.end(); ++it)
610 m_PercentageOfAuthorship[*it] = (m_PercentageOfAuthorship[*it] *100)/ AllContributionAuthor;
613 // All done, now the statistics pages can retrieve the data and
614 // extract the information to be shown.
618 void CStatGraphDlg::FilterSkippedAuthors(std::list<tstring>& included_authors,
619 std::list<tstring>& skipped_authors)
621 included_authors.clear();
622 skipped_authors.clear();
624 unsigned int included_authors_count = m_Skipper.GetPos();
625 // if we only leave out one author, still include him with his name
626 if (included_authors_count + 1 == m_authorNames.size())
627 ++included_authors_count;
629 // add the included authors first
630 std::list<tstring>::iterator author_it = m_authorNames.begin();
631 while (included_authors_count > 0 && author_it != m_authorNames.end())
633 // Add him/her to the included list
634 included_authors.push_back(*author_it);
635 ++author_it;
636 --included_authors_count;
639 // If we haven't reached the end yet, copy all remaining authors into the
640 // skipped author list.
641 std::copy(author_it, m_authorNames.end(), std::back_inserter(skipped_authors) );
643 // Sort authors alphabetically if user wants that.
644 if (!m_bSortByCommitCount)
645 included_authors.sort();
648 bool CStatGraphDlg::PreViewStat(bool fShowLabels)
650 if ((m_parAuthors==NULL)||(m_parDates==NULL)||(m_parFileChanges==NULL))
651 return false;
652 ShowLabels(fShowLabels);
654 //If view graphic
655 if (!fShowLabels) ClearGraph();
657 // This function relies on a previous call of GatherData().
658 // This can be detected by checking the week count.
659 // If the week count is equal to -1, it hasn't been called before.
660 if (m_nWeeks == -1)
661 GatherData();
662 // If week count is still -1, something bad has happened, probably invalid data!
663 if (m_nWeeks == -1)
664 return false;
666 return true;
669 MyGraphSeries *CStatGraphDlg::PreViewGraph(__in UINT GraphTitle, __in UINT YAxisLabel, __in UINT XAxisLabel /*= NULL*/)
671 if(!PreViewStat(false))
672 return NULL;
674 // We need at least one author
675 if (m_authorNames.empty())
676 return NULL;
678 // Add a single series to the chart
679 MyGraphSeries * graphData = new MyGraphSeries();
680 m_graph.AddSeries(*graphData);
681 m_graphDataArray.Add(graphData);
683 // Set up the graph.
684 CString temp;
685 UpdateData();
686 m_graph.SetGraphType(m_GraphType, m_bStacked);
687 temp.LoadString(YAxisLabel);
688 m_graph.SetYAxisLabel(temp);
689 temp.LoadString(XAxisLabel);
690 m_graph.SetXAxisLabel(temp);
691 temp.LoadString(GraphTitle);
692 m_graph.SetGraphTitle(temp);
694 return graphData;
697 void CStatGraphDlg::ShowPercentageOfAuthorship()
699 // Set up the graph.
700 MyGraphSeries * graphData = PreViewGraph(IDS_STATGRAPH_PERCENTAGE_OF_AUTHORSHIP,
701 IDS_STATGRAPH_PERCENTAGE_OF_AUTHORSHIPY,
702 IDS_STATGRAPH_COMMITSBYAUTHORX);
703 if(graphData == NULL) return;
705 // Find out which authors are to be shown and which are to be skipped.
706 std::list<tstring> authors;
707 std::list<tstring> others;
710 FilterSkippedAuthors(authors, others);
712 // Loop over all authors in the authors list and
713 // add them to the graph.
715 if (authors.size())
717 for (std::list<tstring>::iterator it = authors.begin(); it != authors.end(); ++it)
719 int group = m_graph.AppendGroup(it->c_str());
720 graphData->SetData(group, RollPercentageOfAuthorship(m_PercentageOfAuthorship[*it]));
724 // If we have other authors, count them and their commits.
725 if (others.size() != 0)
726 DrawOthers(others, graphData, m_PercentageOfAuthorship);
728 // Paint the graph now that we're through.
729 m_graph.Invalidate();
732 void CStatGraphDlg::ShowCommitsByAuthor()
734 // Set up the graph.
735 MyGraphSeries * graphData = PreViewGraph(IDS_STATGRAPH_COMMITSBYAUTHOR,
736 IDS_STATGRAPH_COMMITSBYAUTHORY,
737 IDS_STATGRAPH_COMMITSBYAUTHORX);
738 if(graphData == NULL) return;
740 // Find out which authors are to be shown and which are to be skipped.
741 std::list<tstring> authors;
742 std::list<tstring> others;
743 FilterSkippedAuthors(authors, others);
745 // Loop over all authors in the authors list and
746 // add them to the graph.
748 if (authors.size())
750 for (std::list<tstring>::iterator it = authors.begin(); it != authors.end(); ++it)
752 int group = m_graph.AppendGroup(it->c_str());
753 graphData->SetData(group, m_commitsPerAuthor[*it]);
757 // If we have other authors, count them and their commits.
758 if (others.size() != 0)
759 DrawOthers(others, graphData, m_commitsPerAuthor);
761 // Paint the graph now that we're through.
762 m_graph.Invalidate();
765 void CStatGraphDlg::ShowCommitsByDate()
767 if(!PreViewStat(false)) return;
769 // We need at least one author
770 if (m_authorNames.empty()) return;
772 // Set up the graph.
773 CString temp;
774 UpdateData();
775 m_graph.SetGraphType(m_GraphType, m_bStacked);
776 temp.LoadString(IDS_STATGRAPH_COMMITSBYDATEY);
777 m_graph.SetYAxisLabel(temp);
778 temp.LoadString(IDS_STATGRAPH_COMMITSBYDATE);
779 m_graph.SetGraphTitle(temp);
781 m_graph.SetXAxisLabel(GetUnitString());
783 // Find out which authors are to be shown and which are to be skipped.
784 std::list<tstring> authors;
785 std::list<tstring> others;
786 FilterSkippedAuthors(authors, others);
788 // Add a graph series for each author.
789 AuthorDataMap authorGraphMap;
790 for (std::list<tstring>::iterator it = authors.begin(); it != authors.end(); ++it)
791 authorGraphMap[*it] = m_graph.AppendGroup(it->c_str());
792 // If we have skipped authors, add a graph series for all those.
793 CString sOthers(MAKEINTRESOURCE(IDS_STATGRAPH_OTHERGROUP));
794 tstring othersName;
795 if (!others.empty())
797 temp.Format(_T(" (%ld)"), others.size());
798 sOthers += temp;
799 othersName = (LPCWSTR)sOthers;
800 authorGraphMap[othersName] = m_graph.AppendGroup(sOthers);
803 // Mapping to collect commit counts in each interval
804 AuthorDataMap commitCount;
806 // Loop over all intervals/weeks and collect filtered data.
807 // Sum up data in each interval until the time unit changes.
808 for (int i=m_lastInterval; i>=m_firstInterval; --i)
810 // Collect data for authors listed by name.
811 if (authors.size())
813 for (std::list<tstring>::iterator it = authors.begin(); it != authors.end(); ++it)
815 // Do we have some data for the current author in the current interval?
816 AuthorDataMap::const_iterator data_it = m_commitsPerUnitAndAuthor[i].find(*it);
817 if (data_it == m_commitsPerUnitAndAuthor[i].end())
818 continue;
819 commitCount[*it] += data_it->second;
822 // Collect data for all skipped authors.
823 if (others.size())
825 for (std::list<tstring>::iterator it = others.begin(); it != others.end(); ++it)
827 // Do we have some data for the author in the current interval?
828 AuthorDataMap::const_iterator data_it = m_commitsPerUnitAndAuthor[i].find(*it);
829 if (data_it == m_commitsPerUnitAndAuthor[i].end())
830 continue;
831 commitCount[othersName] += data_it->second;
835 // Create a new data series for this unit/interval.
836 MyGraphSeries * graphData = new MyGraphSeries();
837 // Loop over all created graphs and set the corresponding data.
838 if (authorGraphMap.size())
840 for (AuthorDataMap::const_iterator it = authorGraphMap.begin(); it != authorGraphMap.end(); ++it)
842 graphData->SetData(it->second, commitCount[it->first]);
845 graphData->SetLabel(m_unitNames[i].c_str());
846 m_graph.AddSeries(*graphData);
847 m_graphDataArray.Add(graphData);
849 // Reset commit count mapping.
850 commitCount.clear();
853 // Paint the graph now that we're through.
854 m_graph.Invalidate();
857 void CStatGraphDlg::ShowStats()
859 if(!PreViewStat(true)) return;
861 // Now we can use the gathered data to update the stats dialog.
862 size_t nAuthors = m_authorNames.size();
864 // Find most and least active author names.
865 tstring mostActiveAuthor;
866 tstring leastActiveAuthor;
867 if (nAuthors > 0)
869 mostActiveAuthor = m_authorNames.front();
870 leastActiveAuthor = m_authorNames.back();
873 // Obtain the statistics for the table.
874 long nCommitsMin = -1;
875 long nCommitsMax = -1;
876 long nFileChangesMin = -1;
877 long nFileChangesMax = -1;
879 long nMostActiveMaxCommits = -1;
880 long nMostActiveMinCommits = -1;
881 long nLeastActiveMaxCommits = -1;
882 long nLeastActiveMinCommits = -1;
884 // Loop over all intervals and find min and max values for commit count and file changes.
885 // Also store the stats for the most and least active authors.
886 for (int i=m_firstInterval; i<=m_lastInterval; ++i)
888 // Loop over all commits in this interval and count the number of commits by all authors.
889 int commitCount = 0;
890 AuthorDataMap::iterator commit_endit = m_commitsPerUnitAndAuthor[i].end();
891 for (AuthorDataMap::iterator commit_it = m_commitsPerUnitAndAuthor[i].begin();
892 commit_it != commit_endit; ++commit_it)
894 commitCount += commit_it->second;
896 if (nCommitsMin == -1 || commitCount < nCommitsMin)
897 nCommitsMin = commitCount;
898 if (nCommitsMax == -1 || commitCount > nCommitsMax)
899 nCommitsMax = commitCount;
901 // Loop over all commits in this interval and count the number of file changes by all authors.
902 int fileChangeCount = 0;
903 AuthorDataMap::iterator filechange_endit = m_filechangesPerUnitAndAuthor[i].end();
904 for (AuthorDataMap::iterator filechange_it = m_filechangesPerUnitAndAuthor[i].begin();
905 filechange_it != filechange_endit; ++filechange_it)
907 fileChangeCount += filechange_it->second;
909 if (nFileChangesMin == -1 || fileChangeCount < nFileChangesMin)
910 nFileChangesMin = fileChangeCount;
911 if (nFileChangesMax == -1 || fileChangeCount > nFileChangesMax)
912 nFileChangesMax = fileChangeCount;
914 // also get min/max data for most and least active authors
915 if (nAuthors > 0)
917 // check if author is present in this interval
918 AuthorDataMap::iterator author_it = m_commitsPerUnitAndAuthor[i].find(mostActiveAuthor);
919 long authorCommits;
920 if (author_it == m_commitsPerUnitAndAuthor[i].end())
921 authorCommits = 0;
922 else
923 authorCommits = author_it->second;
924 if (nMostActiveMaxCommits == -1 || authorCommits > nMostActiveMaxCommits)
925 nMostActiveMaxCommits = authorCommits;
926 if (nMostActiveMinCommits == -1 || authorCommits < nMostActiveMinCommits)
927 nMostActiveMinCommits = authorCommits;
929 author_it = m_commitsPerUnitAndAuthor[i].find(leastActiveAuthor);
930 if (author_it == m_commitsPerUnitAndAuthor[i].end())
931 authorCommits = 0;
932 else
933 authorCommits = author_it->second;
934 if (nLeastActiveMaxCommits == -1 || authorCommits > nLeastActiveMaxCommits)
935 nLeastActiveMaxCommits = authorCommits;
936 if (nLeastActiveMinCommits == -1 || authorCommits < nLeastActiveMinCommits)
937 nLeastActiveMinCommits = authorCommits;
940 if (nMostActiveMaxCommits == -1) nMostActiveMaxCommits = 0;
941 if (nMostActiveMinCommits == -1) nMostActiveMinCommits = 0;
942 if (nLeastActiveMaxCommits == -1) nLeastActiveMaxCommits = 0;
943 if (nLeastActiveMinCommits == -1) nLeastActiveMinCommits = 0;
945 int nWeeks = m_lastInterval-m_firstInterval;
946 if (nWeeks == 0)
947 nWeeks = 1;
948 // Adjust the labels with the unit type (week, month, ...)
949 CString labelText;
950 labelText.Format(IDS_STATGRAPH_NUMBEROFUNIT, GetUnitString());
951 SetDlgItemText(IDC_NUMWEEK, labelText);
952 labelText.Format(IDS_STATGRAPH_COMMITSBYUNIT, GetUnitString());
953 SetDlgItemText(IDC_COMMITSEACHWEEK, labelText);
954 labelText.Format(IDS_STATGRAPH_FILECHANGESBYUNIT, GetUnitString());
955 SetDlgItemText(IDC_FILECHANGESEACHWEEK, labelText);
956 // We have now all data we want and we can fill in the labels...
957 CString number;
958 number.Format(_T("%ld"), nWeeks);
959 SetDlgItemText(IDC_NUMWEEKVALUE, number);
960 number.Format(_T("%ld"), nAuthors);
961 SetDlgItemText(IDC_NUMAUTHORVALUE, number);
962 number.Format(_T("%ld"), m_nTotalCommits);
963 SetDlgItemText(IDC_NUMCOMMITSVALUE, number);
964 number.Format(_T("%ld"), m_nTotalFileChanges);
965 //SetDlgItemText(IDC_NUMFILECHANGESVALUE, number);
967 number.Format(_T("%ld"), m_parAuthors->GetCount() / nWeeks);
968 SetDlgItemText(IDC_COMMITSEACHWEEKAVG, number);
969 number.Format(_T("%ld"), nCommitsMax);
970 SetDlgItemText(IDC_COMMITSEACHWEEKMAX, number);
971 number.Format(_T("%ld"), nCommitsMin);
972 SetDlgItemText(IDC_COMMITSEACHWEEKMIN, number);
974 number.Format(_T("%ld"), m_nTotalFileChanges / nWeeks);
975 //SetDlgItemText(IDC_FILECHANGESEACHWEEKAVG, number);
976 number.Format(_T("%ld"), nFileChangesMax);
977 //SetDlgItemText(IDC_FILECHANGESEACHWEEKMAX, number);
978 number.Format(_T("%ld"), nFileChangesMin);
979 //SetDlgItemText(IDC_FILECHANGESEACHWEEKMIN, number);
981 if (nAuthors == 0)
983 SetDlgItemText(IDC_MOSTACTIVEAUTHORNAME, _T(""));
984 SetDlgItemText(IDC_MOSTACTIVEAUTHORAVG, _T("0"));
985 SetDlgItemText(IDC_MOSTACTIVEAUTHORMAX, _T("0"));
986 SetDlgItemText(IDC_MOSTACTIVEAUTHORMIN, _T("0"));
987 SetDlgItemText(IDC_LEASTACTIVEAUTHORNAME, _T(""));
988 SetDlgItemText(IDC_LEASTACTIVEAUTHORAVG, _T("0"));
989 SetDlgItemText(IDC_LEASTACTIVEAUTHORMAX, _T("0"));
990 SetDlgItemText(IDC_LEASTACTIVEAUTHORMIN, _T("0"));
992 else
994 SetDlgItemText(IDC_MOSTACTIVEAUTHORNAME, mostActiveAuthor.c_str());
995 number.Format(_T("%ld"), m_commitsPerAuthor[mostActiveAuthor] / nWeeks);
996 SetDlgItemText(IDC_MOSTACTIVEAUTHORAVG, number);
997 number.Format(_T("%ld"), nMostActiveMaxCommits);
998 SetDlgItemText(IDC_MOSTACTIVEAUTHORMAX, number);
999 number.Format(_T("%ld"), nMostActiveMinCommits);
1000 SetDlgItemText(IDC_MOSTACTIVEAUTHORMIN, number);
1002 SetDlgItemText(IDC_LEASTACTIVEAUTHORNAME, leastActiveAuthor.c_str());
1003 number.Format(_T("%ld"), m_commitsPerAuthor[leastActiveAuthor] / nWeeks);
1004 SetDlgItemText(IDC_LEASTACTIVEAUTHORAVG, number);
1005 number.Format(_T("%ld"), nLeastActiveMaxCommits);
1006 SetDlgItemText(IDC_LEASTACTIVEAUTHORMAX, number);
1007 number.Format(_T("%ld"), nLeastActiveMinCommits);
1008 SetDlgItemText(IDC_LEASTACTIVEAUTHORMIN, number);
1012 int CStatGraphDlg::RollPercentageOfAuthorship(double it)
1013 { return (int)it + (it - (int)it >= 0.5);}
1015 void CStatGraphDlg::OnCbnSelchangeGraphcombo()
1017 UpdateData();
1019 Metrics useMetric = (Metrics) m_cGraphType.GetItemData(m_cGraphType.GetCurSel());
1020 switch (useMetric )
1022 case AllStat:
1023 case CommitsByDate:
1024 // by date
1025 m_btnGraphLine.EnableWindow(TRUE);
1026 m_btnGraphLineStacked.EnableWindow(TRUE);
1027 m_btnGraphPie.EnableWindow(TRUE);
1028 m_GraphType = MyGraph::Line;
1029 m_bStacked = false;
1030 break;
1031 case PercentageOfAuthorship:
1032 case CommitsByAuthor:
1033 // by author
1034 m_btnGraphLine.EnableWindow(FALSE);
1035 m_btnGraphLineStacked.EnableWindow(FALSE);
1036 m_btnGraphPie.EnableWindow(TRUE);
1037 m_GraphType = MyGraph::Bar;
1038 m_bStacked = false;
1039 break;
1041 RedrawGraph();
1045 int CStatGraphDlg::GetUnitCount()
1047 if (m_nDays < 8)
1048 return m_nDays;
1049 if (m_nWeeks < 15)
1050 return m_nWeeks;
1051 if (m_nWeeks < 80)
1052 return (m_nWeeks/4)+1;
1053 if (m_nWeeks < 320)
1054 return (m_nWeeks/13)+1; // quarters
1055 return (m_nWeeks/52)+1;
1058 int CStatGraphDlg::GetUnit(const CTime& time)
1060 if (m_nDays < 8)
1061 return time.GetMonth()*100 + time.GetDay(); // month*100+day as the unit
1062 if (m_nWeeks < 15)
1063 return GetCalendarWeek(time);
1064 if (m_nWeeks < 80)
1065 return time.GetMonth();
1066 if (m_nWeeks < 320)
1067 return ((time.GetMonth()-1)/3)+1; // quarters
1068 return time.GetYear();
1071 CStatGraphDlg::UnitType CStatGraphDlg::GetUnitType()
1073 if (m_nDays < 8)
1074 return Days;
1075 if (m_nWeeks < 15)
1076 return Weeks;
1077 if (m_nWeeks < 80)
1078 return Months;
1079 if (m_nWeeks < 320)
1080 return Quarters;
1081 return Years;
1084 CString CStatGraphDlg::GetUnitString()
1086 if (m_nDays < 8)
1087 return CString(MAKEINTRESOURCE(IDS_STATGRAPH_COMMITSBYDATEXDAY));
1088 if (m_nWeeks < 15)
1089 return CString(MAKEINTRESOURCE(IDS_STATGRAPH_COMMITSBYDATEXWEEK));
1090 if (m_nWeeks < 80)
1091 return CString(MAKEINTRESOURCE(IDS_STATGRAPH_COMMITSBYDATEXMONTH));
1092 if (m_nWeeks < 320)
1093 return CString(MAKEINTRESOURCE(IDS_STATGRAPH_COMMITSBYDATEXQUARTER));
1094 return CString(MAKEINTRESOURCE(IDS_STATGRAPH_COMMITSBYDATEXYEAR));
1097 CString CStatGraphDlg::GetUnitLabel(int unit, CTime &lasttime)
1099 CString temp;
1100 switch (GetUnitType())
1102 case Days:
1104 // month*100+day as the unit
1105 int day = unit % 100;
1106 int month = unit / 100;
1107 switch (m_langOrder)
1109 case 0: // month day year
1110 temp.Format(_T("%d/%d/%.2d"), month, day, lasttime.GetYear()%100);
1111 break;
1112 case 1: // day month year
1113 default:
1114 temp.Format(_T("%d/%d/%.2d"), day, month, lasttime.GetYear()%100);
1115 break;
1116 case 2: // year month day
1117 temp.Format(_T("%.2d/%d/%d"), lasttime.GetYear()%100, month, day);
1118 break;
1121 break;
1122 case Weeks:
1124 int year = lasttime.GetYear();
1125 if ((unit == 1)&&(lasttime.GetMonth() == 12))
1126 year += 1;
1128 switch (m_langOrder)
1130 case 0: // month day year
1131 case 1: // day month year
1132 default:
1133 temp.Format(_T("%d/%.2d"), unit, year%100);
1134 break;
1135 case 2: // year month day
1136 temp.Format(_T("%.2d/%d"), year%100, unit);
1137 break;
1140 break;
1141 case Months:
1142 switch (m_langOrder)
1144 case 0: // month day year
1145 case 1: // day month year
1146 default:
1147 temp.Format(_T("%d/%.2d"), unit, lasttime.GetYear()%100);
1148 break;
1149 case 2: // year month day
1150 temp.Format(_T("%.2d/%d"), lasttime.GetYear()%100, unit);
1151 break;
1153 break;
1154 case Quarters:
1155 switch (m_langOrder)
1157 case 0: // month day year
1158 case 1: // day month year
1159 default:
1160 temp.Format(_T("%d/%.2d"), unit, lasttime.GetYear()%100);
1161 break;
1162 case 2: // year month day
1163 temp.Format(_T("%.2d/%d"), lasttime.GetYear()%100, unit);
1164 break;
1166 break;
1167 case Years:
1168 temp.Format(_T("%d"), unit);
1169 break;
1171 return temp;
1174 void CStatGraphDlg::OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar)
1176 if (nSBCode == TB_THUMBTRACK)
1177 return CDialog::OnHScroll(nSBCode, nPos, pScrollBar);
1179 ShowSelectStat((Metrics) m_cGraphType.GetItemData(m_cGraphType.GetCurSel()));
1180 CDialog::OnHScroll(nSBCode, nPos, pScrollBar);
1183 void CStatGraphDlg::OnNeedText(NMHDR *pnmh, LRESULT * /*pResult*/)
1185 TOOLTIPTEXT* pttt = (TOOLTIPTEXT*) pnmh;
1186 if (pttt->hdr.idFrom == (UINT_PTR) m_Skipper.GetSafeHwnd())
1188 size_t included_authors_count = m_Skipper.GetPos();
1189 // if we only leave out one author, still include him with his name
1190 if (included_authors_count + 1 == m_authorNames.size())
1191 ++included_authors_count;
1193 // find the minimum number of commits that the shown authors have
1194 int min_commits = 0;
1195 included_authors_count = min(included_authors_count, m_authorNames.size());
1196 std::list<tstring>::iterator author_it = m_authorNames.begin();
1197 advance(author_it, included_authors_count);
1198 if (author_it != m_authorNames.begin())
1199 min_commits = m_commitsPerAuthor[ *(--author_it) ];
1201 CString string;
1202 int percentage = int(min_commits*100.0/(m_nTotalCommits ? m_nTotalCommits : 1));
1203 string.Format(IDS_STATGRAPH_AUTHORSLIDER_TT, m_Skipper.GetPos(), min_commits, percentage);
1204 ::lstrcpy(pttt->szText, (LPCTSTR) string);
1208 void CStatGraphDlg::AuthorsCaseSensitiveChanged()
1210 UpdateData(); // update checkbox state
1211 GatherData(); // first regenerate the statistics data
1212 RedrawGraph(); // then update the current statistics page
1215 void CStatGraphDlg::SortModeChanged()
1217 UpdateData(); // update checkbox state
1218 RedrawGraph(); // then update the current statistics page
1221 void CStatGraphDlg::ClearGraph()
1223 m_graph.Clear();
1224 for (int j=0; j<m_graphDataArray.GetCount(); ++j)
1225 delete ((MyGraphSeries *)m_graphDataArray.GetAt(j));
1226 m_graphDataArray.RemoveAll();
1229 void CStatGraphDlg::RedrawGraph()
1231 EnableDisableMenu();
1232 m_btnGraphBar.SetState(BST_UNCHECKED);
1233 m_btnGraphBarStacked.SetState(BST_UNCHECKED);
1234 m_btnGraphLine.SetState(BST_UNCHECKED);
1235 m_btnGraphLineStacked.SetState(BST_UNCHECKED);
1236 m_btnGraphPie.SetState(BST_UNCHECKED);
1238 if ((m_GraphType == MyGraph::Bar)&&(m_bStacked))
1240 m_btnGraphBarStacked.SetState(BST_CHECKED);
1242 if ((m_GraphType == MyGraph::Bar)&&(!m_bStacked))
1244 m_btnGraphBar.SetState(BST_CHECKED);
1246 if ((m_GraphType == MyGraph::Line)&&(m_bStacked))
1248 m_btnGraphLineStacked.SetState(BST_CHECKED);
1250 if ((m_GraphType == MyGraph::Line)&&(!m_bStacked))
1252 m_btnGraphLine.SetState(BST_CHECKED);
1254 if (m_GraphType == MyGraph::PieChart)
1256 m_btnGraphPie.SetState(BST_CHECKED);
1259 UpdateData();
1260 ShowSelectStat((Metrics) m_cGraphType.GetItemData(m_cGraphType.GetCurSel()), true);
1262 void CStatGraphDlg::OnBnClickedGraphbarbutton()
1264 m_GraphType = MyGraph::Bar;
1265 m_bStacked = false;
1266 RedrawGraph();
1269 void CStatGraphDlg::OnBnClickedGraphbarstackedbutton()
1271 m_GraphType = MyGraph::Bar;
1272 m_bStacked = true;
1273 RedrawGraph();
1276 void CStatGraphDlg::OnBnClickedGraphlinebutton()
1278 m_GraphType = MyGraph::Line;
1279 m_bStacked = false;
1280 RedrawGraph();
1283 void CStatGraphDlg::OnBnClickedGraphlinestackedbutton()
1285 m_GraphType = MyGraph::Line;
1286 m_bStacked = true;
1287 RedrawGraph();
1290 void CStatGraphDlg::OnBnClickedGraphpiebutton()
1292 m_GraphType = MyGraph::PieChart;
1293 m_bStacked = false;
1294 RedrawGraph();
1297 BOOL CStatGraphDlg::PreTranslateMessage(MSG* pMsg)
1299 if (NULL != m_pToolTip)
1300 m_pToolTip->RelayEvent(pMsg);
1302 return CStandAloneDialogTmpl<CResizableDialog>::PreTranslateMessage(pMsg);
1305 void CStatGraphDlg::EnableDisableMenu()
1307 UINT nEnable = MF_BYCOMMAND;
1309 Metrics SelectMetric = (Metrics) m_cGraphType.GetItemData(m_cGraphType.GetCurSel());
1311 nEnable |= (SelectMetric > TextStatStart && SelectMetric < TextStatEnd)
1312 ? (MF_DISABLED | MF_GRAYED) : MF_ENABLED;
1314 GetMenu()->EnableMenuItem(ID_FILE_SAVESTATGRAPHAS, nEnable);
1317 void CStatGraphDlg::OnFileSavestatgraphas()
1319 CString tempfile;
1320 int filterindex = 0;
1321 if (CAppUtils::FileOpenSave(tempfile, &filterindex, IDS_REVGRAPH_SAVEPIC, IDS_PICTUREFILEFILTER, false, m_hWnd))
1323 // if the user doesn't specify a file extension, default to
1324 // wmf and add that extension to the filename. But only if the
1325 // user chose the 'pictures' filter. The filename isn't changed
1326 // if the 'All files' filter was chosen.
1327 CString extension;
1328 int dotPos = tempfile.ReverseFind('.');
1329 int slashPos = tempfile.ReverseFind('\\');
1330 if (dotPos > slashPos)
1331 extension = tempfile.Mid(dotPos);
1332 if ((filterindex == 1)&&(extension.IsEmpty()))
1334 extension = _T(".wmf");
1335 tempfile += extension;
1337 SaveGraph(tempfile);
1341 void CStatGraphDlg::SaveGraph(CString sFilename)
1343 CString extension = CPathUtils::GetFileExtFromPath(sFilename);
1344 if (extension.CompareNoCase(_T(".wmf"))==0)
1346 // save the graph as an enhanced meta file
1347 CMyMetaFileDC wmfDC;
1348 wmfDC.CreateEnhanced(NULL, sFilename, NULL, _T("TortoiseGit\0Statistics\0\0"));
1349 wmfDC.SetAttribDC(GetDC()->GetSafeHdc());
1350 RedrawGraph();
1351 m_graph.DrawGraph(wmfDC);
1352 HENHMETAFILE hemf = wmfDC.CloseEnhanced();
1353 DeleteEnhMetaFile(hemf);
1355 else
1357 // save the graph as a pixel picture instead of a vector picture
1358 // create dc to paint on
1361 CWindowDC ddc(this);
1362 CDC dc;
1363 if (!dc.CreateCompatibleDC(&ddc))
1365 ShowErrorMessage();
1366 return;
1368 CRect rect;
1369 GetDlgItem(IDC_GRAPH)->GetClientRect(&rect);
1370 HBITMAP hbm = ::CreateCompatibleBitmap(ddc.m_hDC, rect.Width(), rect.Height());
1371 if (hbm==0)
1373 ShowErrorMessage();
1374 return;
1376 HBITMAP oldbm = (HBITMAP)dc.SelectObject(hbm);
1377 // paint the whole graph
1378 RedrawGraph();
1379 m_graph.DrawGraph(dc);
1380 // now use GDI+ to save the picture
1381 CLSID encoderClsid;
1382 GdiplusStartupInput gdiplusStartupInput;
1383 ULONG_PTR gdiplusToken;
1384 CString sErrormessage;
1385 if (GdiplusStartup( &gdiplusToken, &gdiplusStartupInput, NULL )==Ok)
1388 Bitmap bitmap(hbm, NULL);
1389 if (bitmap.GetLastStatus()==Ok)
1391 // Get the CLSID of the encoder.
1392 int ret = 0;
1393 if (CPathUtils::GetFileExtFromPath(sFilename).CompareNoCase(_T(".png"))==0)
1394 ret = GetEncoderClsid(L"image/png", &encoderClsid);
1395 else if (CPathUtils::GetFileExtFromPath(sFilename).CompareNoCase(_T(".jpg"))==0)
1396 ret = GetEncoderClsid(L"image/jpeg", &encoderClsid);
1397 else if (CPathUtils::GetFileExtFromPath(sFilename).CompareNoCase(_T(".jpeg"))==0)
1398 ret = GetEncoderClsid(L"image/jpeg", &encoderClsid);
1399 else if (CPathUtils::GetFileExtFromPath(sFilename).CompareNoCase(_T(".bmp"))==0)
1400 ret = GetEncoderClsid(L"image/bmp", &encoderClsid);
1401 else if (CPathUtils::GetFileExtFromPath(sFilename).CompareNoCase(_T(".gif"))==0)
1402 ret = GetEncoderClsid(L"image/gif", &encoderClsid);
1403 else
1405 sFilename += _T(".jpg");
1406 ret = GetEncoderClsid(L"image/jpeg", &encoderClsid);
1408 if (ret >= 0)
1410 CStringW tfile = CStringW(sFilename);
1411 bitmap.Save(tfile, &encoderClsid, NULL);
1413 else
1415 sErrormessage.Format(IDS_REVGRAPH_ERR_NOENCODER, CPathUtils::GetFileExtFromPath(sFilename));
1418 else
1420 sErrormessage.LoadString(IDS_REVGRAPH_ERR_NOBITMAP);
1423 GdiplusShutdown(gdiplusToken);
1425 else
1427 sErrormessage.LoadString(IDS_REVGRAPH_ERR_GDIINIT);
1429 dc.SelectObject(oldbm);
1430 dc.DeleteDC();
1431 if (!sErrormessage.IsEmpty())
1433 ::MessageBox(m_hWnd, sErrormessage, _T("TortoiseGit"), MB_ICONERROR);
1436 catch (CException * pE)
1438 TCHAR szErrorMsg[2048];
1439 pE->GetErrorMessage(szErrorMsg, 2048);
1440 pE->Delete();
1441 ::MessageBox(m_hWnd, szErrorMsg, _T("TortoiseGit"), MB_ICONERROR);
1446 int CStatGraphDlg::GetEncoderClsid(const WCHAR* format, CLSID* pClsid)
1448 UINT num = 0; // number of image encoders
1449 UINT size = 0; // size of the image encoder array in bytes
1451 ImageCodecInfo* pImageCodecInfo = NULL;
1453 if (GetImageEncodersSize(&num, &size)!=Ok)
1454 return -1;
1455 if (size == 0)
1456 return -1; // Failure
1458 pImageCodecInfo = (ImageCodecInfo*)(malloc(size));
1459 if (pImageCodecInfo == NULL)
1460 return -1; // Failure
1462 if (GetImageEncoders(num, size, pImageCodecInfo)==Ok)
1464 for (UINT j = 0; j < num; ++j)
1466 if (wcscmp(pImageCodecInfo[j].MimeType, format) == 0)
1468 *pClsid = pImageCodecInfo[j].Clsid;
1469 free(pImageCodecInfo);
1470 return j; // Success
1474 free (pImageCodecInfo);
1475 return -1; // Failure
1478 void CStatGraphDlg::StoreCurrentGraphType()
1480 UpdateData();
1481 DWORD graphtype = static_cast<DWORD>(m_cGraphType.GetItemData(m_cGraphType.GetCurSel()));
1482 // encode the current chart type
1483 DWORD statspage = graphtype*10;
1484 if ((m_GraphType == MyGraph::Bar)&&(m_bStacked))
1486 statspage += 1;
1488 if ((m_GraphType == MyGraph::Bar)&&(!m_bStacked))
1490 statspage += 2;
1492 if ((m_GraphType == MyGraph::Line)&&(m_bStacked))
1494 statspage += 3;
1496 if ((m_GraphType == MyGraph::Line)&&(!m_bStacked))
1498 statspage += 4;
1500 if (m_GraphType == MyGraph::PieChart)
1502 statspage += 5;
1505 // store current chart type in registry
1506 CRegDWORD lastStatsPage = CRegDWORD(_T("Software\\TortoiseGit\\LastViewedStatsPage"), 0);
1507 lastStatsPage = statspage;
1509 CRegDWORD regAuthors = CRegDWORD(_T("Software\\TortoiseGit\\StatAuthorsCaseSensitive"));
1510 regAuthors = m_bAuthorsCaseSensitive;
1512 CRegDWORD regSort = CRegDWORD(_T("Software\\TortoiseGit\\StatSortByCommitCount"));
1513 regSort = m_bSortByCommitCount;
1516 void CStatGraphDlg::ShowErrorMessage()
1518 CFormatMessageWrapper errorDetails;
1519 if (errorDetails)
1520 MessageBox( errorDetails, _T("Error"), MB_OK | MB_ICONINFORMATION );
1523 void CStatGraphDlg::ShowSelectStat(Metrics SelectedMetric, bool reloadSkiper /* = false */)
1525 switch (SelectedMetric)
1527 case AllStat:
1528 LoadListOfAuthors(m_commitsPerAuthor, reloadSkiper);
1529 ShowStats();
1530 break;
1531 case CommitsByDate:
1532 LoadListOfAuthors(m_commitsPerAuthor, reloadSkiper);
1533 ShowCommitsByDate();
1534 break;
1535 case CommitsByAuthor:
1536 LoadListOfAuthors(m_commitsPerAuthor, reloadSkiper);
1537 ShowCommitsByAuthor();
1538 break;
1539 case PercentageOfAuthorship:
1540 LoadListOfAuthors(m_PercentageOfAuthorship, reloadSkiper, true);
1541 ShowPercentageOfAuthorship();
1542 break;
1543 default:
1544 ShowErrorMessage();
1548 double CStatGraphDlg::CoeffContribution(int distFromEnd) { return distFromEnd ? 1.0 / m_CoeffAuthorShip * distFromEnd : 1;}
1551 template <class MAP>
1552 void CStatGraphDlg::DrawOthers(const std::list<tstring> &others, MyGraphSeries *graphData, MAP &map)
1554 int nCommits = 0;
1555 for (std::list<tstring>::const_iterator it = others.begin(); it != others.end(); ++it)
1557 nCommits += RollPercentageOfAuthorship(map[*it]);
1560 CString temp;
1561 temp.Format(_T(" (%ld)"), others.size());
1563 CString sOthers(MAKEINTRESOURCE(IDS_STATGRAPH_OTHERGROUP));
1564 sOthers += temp;
1565 int group = m_graph.AppendGroup(sOthers);
1566 graphData->SetData(group, (int)nCommits);
1570 template <class MAP>
1571 void CStatGraphDlg::LoadListOfAuthors (MAP &map, bool reloadSkiper/*= false*/, bool compare /*= false*/)
1573 m_authorNames.clear();
1574 if (map.size())
1576 for (MAP::const_iterator it = map.begin(); it != map.end(); ++it)
1578 if ((compare && RollPercentageOfAuthorship(map[it->first]) != 0) || !compare)
1579 m_authorNames.push_back(it->first);
1583 // Sort the list of authors based on commit count
1584 m_authorNames.sort(MoreCommitsThan< MAP::referent_type>(map));
1586 // Set Skipper
1587 SetSkipper(reloadSkiper);