Fixed issue #1610: Average values on statistics dialog graph
[TortoiseGit.git] / src / Utils / MiscUI / MyGraph.cpp
blob4b5d28659257c800dea7c4a6d332e35eede5999c
1 // MyGraph.cpp
3 #include "stdafx.h"
4 #include "MyGraph.h"
5 #include "BufferDC.h"
7 #include <cmath>
8 #include <memory>
9 using namespace std;
11 #ifdef _DEBUG
12 #define new DEBUG_NEW
13 #undef THIS_FILE
14 static char THIS_FILE[] = __FILE__;
15 #endif
18 /////////////////////////////////////////////////////////////////////////////
19 // This macro can be called at the beginning and ending of every
20 // method. It is identical to saying "ASSERT_VALID(); ASSERT_KINDOF();"
21 // but is written like this so that VALIDATE can be a macro. It is useful
22 // as an "early warning" that something has gone wrong with "this" object.
23 #ifndef VALIDATE
24 #ifdef _DEBUG
25 #define VALIDATE ::AfxAssertValidObject(this, __FILE__ , __LINE__ ); \
26 _ASSERTE(IsKindOf(GetRuntimeClass()));
27 #else
28 #define VALIDATE
29 #endif
30 #endif
33 /////////////////////////////////////////////////////////////////////////////
34 // Constants.
36 #define TICK_PIXELS 4 // Size of tick marks.
37 #define GAP_PIXELS 6 // Better if an even value.
38 #define LEGEND_COLOR_BAR_WIDTH_PIXELS 50 // Width of color bar.
39 #define LEGEND_COLOR_BAR_GAP_PIXELS 1 // Space between color bars.
40 #define Y_AXIS_TICK_COUNT_TARGET 5 // How many ticks should be there on the y axis.
41 #define MIN_FONT_SIZE 70 // The minimum font-size in pt*10.
42 #define LEGEND_VISIBILITY_THRESHOLD 300 // The width of the graph in pixels when the legend gets hidden.
44 #define INTERSERIES_PERCENT_USED 0.85 // How much of the graph is
45 // used for bars/pies (the
46 // rest is for inter-series
47 // spacing).
49 #define TITLE_DIVISOR 5 // Scale font to graph width.
50 #define LEGEND_DIVISOR 8 // Scale font to graph height.
51 #define Y_AXIS_LABEL_DIVISOR 6 // Scale font to graph height.
53 const double PI = 3.1415926535897932384626433832795;
55 /////////////////////////////////////////////////////////////////////////////
56 // MyGraphSeries
58 // Constructor.
59 MyGraphSeries::MyGraphSeries(const CString& sLabel /* = "" */ )
60 : m_sLabel(sLabel)
64 // Destructor.
65 /* virtual */ MyGraphSeries::~MyGraphSeries()
67 for (int nGroup = 0; nGroup < m_oaRegions.GetSize(); ++nGroup) {
68 delete m_oaRegions.GetAt(nGroup);
73 void MyGraphSeries::SetLabel(const CString& sLabel)
75 VALIDATE;
77 m_sLabel = sLabel;
81 void MyGraphSeries::SetData(int nGroup, int nValue)
83 VALIDATE;
84 _ASSERTE(0 <= nGroup);
86 m_dwaValues.SetAtGrow(nGroup, nValue);
90 void MyGraphSeries::SetTipRegion(int nGroup, const CRect& rc)
92 VALIDATE;
94 CRgn* prgnNew = new CRgn;
95 ASSERT_VALID(prgnNew);
97 VERIFY(prgnNew->CreateRectRgnIndirect(rc));
98 SetTipRegion(nGroup, prgnNew);
102 void MyGraphSeries::SetTipRegion(int nGroup, CRgn* prgn)
104 VALIDATE;
105 _ASSERTE(0 <= nGroup);
106 ASSERT_VALID(prgn);
108 // If there is an existing region, delete it.
109 CRgn* prgnOld = NULL;
111 if (nGroup < m_oaRegions.GetSize())
113 prgnOld = m_oaRegions.GetAt(nGroup);
114 ASSERT_NULL_OR_POINTER(prgnOld, CRgn);
117 if (prgnOld) {
118 delete prgnOld;
119 prgnOld = NULL;
122 // Add the new region.
123 m_oaRegions.SetAtGrow(nGroup, prgn);
125 _ASSERTE(m_oaRegions.GetSize() <= m_dwaValues.GetSize());
129 CString MyGraphSeries::GetLabel() const
131 VALIDATE;
133 return m_sLabel;
137 int MyGraphSeries::GetData(int nGroup) const
139 VALIDATE;
140 _ASSERTE(0 <= nGroup);
141 _ASSERTE(m_dwaValues.GetSize() > nGroup);
143 return m_dwaValues[nGroup];
146 // Returns the largest data value in this series.
147 int MyGraphSeries::GetMaxDataValue(bool bStackedGraph) const
149 VALIDATE;
151 int nMax(0);
153 for (int nGroup = 0; nGroup < m_dwaValues.GetSize(); ++nGroup) {
154 if(!bStackedGraph){
155 nMax = max(nMax, static_cast<int> (m_dwaValues.GetAt(nGroup)));
157 else{
158 nMax += static_cast<int> (m_dwaValues.GetAt(nGroup));
162 return nMax;
165 // Returns the average data value in this series.
166 int MyGraphSeries::GetAverageDataValue() const
168 VALIDATE;
170 int nTotal = 0;
172 for (int nGroup = 0; nGroup < m_dwaValues.GetSize(); ++nGroup) {
173 nTotal += static_cast<int> (m_dwaValues.GetAt(nGroup));
176 return nTotal / m_dwaValues.GetSize();
179 // Returns the number of data points that are not zero.
180 int MyGraphSeries::GetNonZeroElementCount() const
182 VALIDATE;
184 int nCount(0);
186 for (int nGroup = 0; nGroup < m_dwaValues.GetSize(); ++nGroup) {
188 if (m_dwaValues.GetAt(nGroup)) {
189 ++nCount;
193 return nCount;
196 // Returns the sum of the data points for this series.
197 int MyGraphSeries::GetDataTotal() const
199 VALIDATE;
201 int nTotal(0);
203 for (int nGroup = 0; nGroup < m_dwaValues.GetSize(); ++nGroup) {
204 nTotal += m_dwaValues.GetAt(nGroup);
207 return nTotal;
210 // Returns which group (if any) the sent point lies within in this series.
211 int MyGraphSeries::HitTest(const CPoint& pt, int searchStart = 0) const
213 VALIDATE;
215 for (int nGroup = searchStart; nGroup < m_oaRegions.GetSize(); ++nGroup) {
216 CRgn* prgnData = m_oaRegions.GetAt(nGroup);
217 ASSERT_NULL_OR_POINTER(prgnData, CRgn);
219 if (prgnData && prgnData->PtInRegion(pt)) {
220 return nGroup;
224 return -1;
227 // Get the series portion of the tip for this group in this series.
228 CString MyGraphSeries::GetTipText(int nGroup, const CString &unitString) const
230 VALIDATE;
231 _ASSERTE(0 <= nGroup);
232 _ASSERTE(m_oaRegions.GetSize() <= m_dwaValues.GetSize());
234 CString sTip;
236 sTip.Format(_T("%d %s (%d%%)"), m_dwaValues.GetAt(nGroup),
237 unitString,
238 GetDataTotal() ? (int) (100.0 * (double) m_dwaValues.GetAt(nGroup) /
239 (double) GetDataTotal()) : 0);
241 return sTip;
245 /////////////////////////////////////////////////////////////////////////////
246 // MyGraph
248 // Constructor.
249 MyGraph::MyGraph(GraphType eGraphType /* = MyGraph::Pie */ , bool bStackedGraph /* = false */)
250 : m_nXAxisWidth(0)
251 , m_nYAxisHeight(0)
252 , m_nAxisLabelHeight(0)
253 , m_nAxisTickLabelHeight(0)
254 , m_eGraphType(eGraphType)
255 , m_bStackedGraph(bStackedGraph)
257 m_ptOrigin.x = m_ptOrigin.y = 0;
258 m_rcGraph.SetRectEmpty();
259 m_rcLegend.SetRectEmpty();
260 m_rcTitle.SetRectEmpty();
263 // Destructor.
264 /* virtual */ MyGraph::~MyGraph()
268 BEGIN_MESSAGE_MAP(MyGraph, CStatic)
269 //{{AFX_MSG_MAP(MyGraph)
270 ON_WM_PAINT()
271 ON_WM_SIZE()
272 //}}AFX_MSG_MAP
273 ON_NOTIFY_EX_RANGE(TTN_NEEDTEXTW, 0, 0xFFFF, OnNeedText)
274 ON_NOTIFY_EX_RANGE(TTN_NEEDTEXTA, 0, 0xFFFF, OnNeedText)
275 END_MESSAGE_MAP()
277 // Called by the framework to allow other necessary sub classing to occur
278 // before the window is sub classed.
279 void MyGraph::PreSubclassWindow()
281 VALIDATE;
283 CStatic::PreSubclassWindow();
285 VERIFY(EnableToolTips(true));
289 /////////////////////////////////////////////////////////////////////////////
290 // MyGraph message handlers
292 // Handle the tooltip messages. Returns true to mean message was handled.
293 BOOL MyGraph::OnNeedText(UINT /*uiId*/, NMHDR* pNMHDR, LRESULT* pResult)
295 _ASSERTE(pNMHDR && "Bad parameter passed");
296 _ASSERTE(pResult && "Bad parameter passed");
298 bool bReturn(false);
299 UINT_PTR uiID(pNMHDR->idFrom);
301 // Notification in NT from automatically created tooltip.
302 if (0U != uiID) {
303 bReturn = true;
305 // Need to handle both ANSI and UNICODE versions of the message.
306 TOOLTIPTEXTA* pTTTA = reinterpret_cast<TOOLTIPTEXTA*> (pNMHDR);
307 ASSERT_POINTER(pTTTA, TOOLTIPTEXTA);
309 TOOLTIPTEXTW* pTTTW = reinterpret_cast<TOOLTIPTEXTW*> (pNMHDR);
310 ASSERT_POINTER(pTTTW, TOOLTIPTEXTW);
312 CString sTipText(GetTipText());
314 #ifndef _UNICODE
315 if (TTN_NEEDTEXTA == pNMHDR->code) {
316 lstrcpyn(pTTTA->szText, sTipText, _countof(pTTTA->szText));
318 else {
319 _mbstowcsz(pTTTW->szText, sTipText, _countof(pTTTA->szText));
321 #else
322 if (pNMHDR->code == TTN_NEEDTEXTA) {
323 _wcstombsz(pTTTA->szText, sTipText, _countof(pTTTA->szText));
325 else {
326 lstrcpyn(pTTTW->szText, sTipText, _countof(pTTTA->szText));
328 #endif
330 *pResult = 0;
333 return bReturn;
336 // The framework calls this member function to determine whether a point is in
337 // the bounding rectangle of the specified tool.
338 INT_PTR MyGraph::OnToolHitTest(CPoint point, TOOLINFO* pTI) const
340 _ASSERTE(pTI && "Bad parameter passed");
342 // This works around the problem of the tip remaining visible when you move
343 // the mouse to various positions over this control.
344 INT_PTR nReturn(0);
345 static bool bTipPopped(false);
346 static CPoint ptPrev(-1,-1);
348 if (point != ptPrev) {
349 ptPrev = point;
351 if (bTipPopped) {
352 bTipPopped = false;
353 nReturn = -1;
355 else {
356 ::Sleep(50);
357 bTipPopped = true;
359 pTI->hwnd = m_hWnd;
360 pTI->uId = (UINT_PTR) m_hWnd;
361 pTI->lpszText = LPSTR_TEXTCALLBACK;
363 CRect rcWnd;
364 GetClientRect(&rcWnd);
365 pTI->rect = rcWnd;
366 nReturn = 1;
369 else {
370 nReturn = 1;
373 MyGraph::SpinTheMessageLoop();
375 return nReturn;
378 // Build the tip text for the part of the graph that the mouse is currently
379 // over.
380 CString MyGraph::GetTipText() const
382 VALIDATE;
384 CString sTip("");
386 // Get the position of the mouse.
387 CPoint pt;
388 VERIFY(::GetCursorPos(&pt));
389 ScreenToClient(&pt);
391 // Ask each part of the graph to check and see if the mouse is over it.
392 if (m_rcLegend.PtInRect(pt)) {
393 sTip = "Legend";
395 else if (m_rcTitle.PtInRect(pt)) {
396 sTip = "Title";
398 else {
399 int maxXAxis = m_ptOrigin.x + (m_nXAxisWidth - m_rcLegend.Width() - (GAP_PIXELS * 2));
400 if (pt.x >= m_ptOrigin.x && pt.x <= maxXAxis) {
401 int average = GetAverageDataValue();
402 int nMaxDataValue = max(GetMaxDataValue(), 1);
403 double barTop = m_ptOrigin.y - (double)m_nYAxisHeight *
404 (average / (double)nMaxDataValue);
405 if (pt.y >= barTop - 2 && pt.y <= barTop + 2) {
406 sTip.Format(_T("Average: %d %s (%d%%)"), average, m_sYAxisLabel, nMaxDataValue ? (100 * average / nMaxDataValue) : 0);
407 return sTip;
411 POSITION pos(m_olMyGraphSeries.GetHeadPosition());
413 while (pos && sTip=="") {
414 MyGraphSeries* pSeries = m_olMyGraphSeries.GetNext(pos);
415 ASSERT_VALID(pSeries);
417 int nGroup(0);
419 nGroup = pSeries->HitTest(pt,nGroup);
421 if (-1 != nGroup) {
422 if("" != sTip){
423 sTip += _T(", ");
425 sTip += m_saLegendLabels.GetAt(nGroup) + _T(": ");
426 sTip += pSeries->GetTipText(nGroup, m_sYAxisLabel);
427 nGroup++;
429 }while(-1 != nGroup);
433 return sTip;
436 // Handle WM_PAINT.
437 void MyGraph::OnPaint()
439 VALIDATE;
441 CBufferDC dc(this);
442 DrawGraph(dc);
445 // Handle WM_SIZE.
446 void MyGraph::OnSize(UINT nType, int cx, int cy)
448 VALIDATE;
450 CStatic::OnSize(nType, cx, cy);
452 Invalidate();
455 // Change the type of the graph; the caller should call Invalidate() on this
456 // window to make the effect of this change visible.
457 void MyGraph::SetGraphType(GraphType e, bool bStackedGraph)
459 VALIDATE;
461 m_eGraphType = e;
462 m_bStackedGraph = bStackedGraph;
465 // Calculate the current max legend label length in pixels.
466 int MyGraph::GetMaxLegendLabelLength(CDC& dc) const
468 VALIDATE;
469 ASSERT_VALID(&dc);
471 CString sMax;
472 int nMaxChars(-1);
473 CSize siz(-1,-1);
475 // First get max number of characters.
476 for (int nGroup = 0; nGroup < m_saLegendLabels.GetSize(); ++nGroup) {
477 int nLabelLength(m_saLegendLabels.GetAt(nGroup).GetLength());
479 if (nMaxChars < nLabelLength) {
480 nMaxChars = nLabelLength;
481 sMax = m_saLegendLabels.GetAt(nGroup);
485 // Now calculate the pixels.
486 siz = dc.GetTextExtent(sMax);
488 _ASSERTE(-1 < siz.cx);
490 return siz.cx;
493 // Returns the largest number of data points in any series.
494 int MyGraph::GetMaxSeriesSize() const
496 VALIDATE;
498 int nMax(0);
499 POSITION pos(m_olMyGraphSeries.GetHeadPosition());
501 while (pos) {
502 MyGraphSeries* pSeries = m_olMyGraphSeries.GetNext(pos);
503 ASSERT_VALID(pSeries);
505 nMax = max(nMax, (int)pSeries->m_dwaValues.GetSize());
508 return nMax;
511 // Returns the largest number of non-zero data points in any series.
512 int MyGraph::GetMaxNonZeroSeriesSize() const
514 VALIDATE;
516 int nMax(0);
517 POSITION pos(m_olMyGraphSeries.GetHeadPosition());
519 while (pos) {
520 MyGraphSeries* pSeries = m_olMyGraphSeries.GetNext(pos);
521 ASSERT_VALID(pSeries);
523 nMax = max(nMax, pSeries->GetNonZeroElementCount());
526 return nMax;
529 // Get the largest data value in all series.
530 int MyGraph::GetMaxDataValue() const
532 VALIDATE;
534 int nMax(0);
535 POSITION pos(m_olMyGraphSeries.GetHeadPosition());
537 while (pos) {
538 MyGraphSeries* pSeries = m_olMyGraphSeries.GetNext(pos);
539 ASSERT_VALID(pSeries);
541 nMax = max(nMax, pSeries->GetMaxDataValue(m_bStackedGraph));
544 return nMax;
547 // Get the average data value in all series.
548 int MyGraph::GetAverageDataValue() const
550 VALIDATE;
552 int nTotal = 0, nCount = 0;
553 POSITION pos(m_olMyGraphSeries.GetHeadPosition());
555 while (pos) {
556 MyGraphSeries* pSeries = m_olMyGraphSeries.GetNext(pos);
557 ASSERT_VALID(pSeries);
559 nTotal += pSeries->GetAverageDataValue();
560 ++nCount;
563 return nTotal / nCount;
566 // How many series are populated?
567 int MyGraph::GetNonZeroSeriesCount() const
569 VALIDATE;
571 int nCount(0);
572 POSITION pos(m_olMyGraphSeries.GetHeadPosition());
574 while (pos) {
575 MyGraphSeries* pSeries = m_olMyGraphSeries.GetNext(pos);
576 ASSERT_VALID(pSeries);
578 if (0 < pSeries->GetNonZeroElementCount()) {
579 ++nCount;
583 return nCount ? nCount : 1;
586 // Returns the group number for the sent label; -1 if not found.
587 int MyGraph::LookupLabel(const CString& sLabel) const
589 VALIDATE;
590 _ASSERTE(! sLabel.IsEmpty());
592 for (int nGroup = 0; nGroup < m_saLegendLabels.GetSize(); ++nGroup) {
594 if (0 == sLabel.CompareNoCase(m_saLegendLabels.GetAt(nGroup))) {
595 return nGroup;
599 return -1;
602 void MyGraph::Clear()
604 m_dwaColors.RemoveAll();
605 m_saLegendLabels.RemoveAll();
606 m_olMyGraphSeries.RemoveAll();
610 void MyGraph::AddSeries(MyGraphSeries& rMyGraphSeries)
612 VALIDATE;
613 ASSERT_VALID(&rMyGraphSeries);
614 _ASSERTE(m_saLegendLabels.GetSize() == rMyGraphSeries.m_dwaValues.GetSize());
616 m_olMyGraphSeries.AddTail(&rMyGraphSeries);
620 void MyGraph::SetXAxisLabel(const CString& sLabel)
622 VALIDATE;
623 _ASSERTE(! sLabel.IsEmpty());
625 m_sXAxisLabel = sLabel;
629 void MyGraph::SetYAxisLabel(const CString& sLabel)
631 VALIDATE;
632 _ASSERTE(! sLabel.IsEmpty());
634 m_sYAxisLabel = sLabel;
637 // Returns the group number added. Also, makes sure that all the series have
638 // this many elements.
639 int MyGraph::AppendGroup(const CString& sLabel)
641 VALIDATE;
643 // Add the group.
644 int nGroup((int)m_saLegendLabels.GetSize());
645 SetLegend(nGroup, sLabel);
647 // Make sure that all series have this element.
648 POSITION pos(m_olMyGraphSeries.GetHeadPosition());
650 while (pos) {
652 MyGraphSeries* pSeries = m_olMyGraphSeries.GetNext(pos);
653 ASSERT_VALID(pSeries);
655 if (nGroup >= pSeries->m_dwaValues.GetSize()) {
656 pSeries->m_dwaValues.SetAtGrow(nGroup, 0);
660 return nGroup;
663 // Set this value to the legend.
664 void MyGraph::SetLegend(int nGroup, const CString& sLabel)
666 VALIDATE;
667 _ASSERTE(0 <= nGroup);
669 m_saLegendLabels.SetAtGrow(nGroup, sLabel);
673 void MyGraph::SetGraphTitle(const CString& sTitle)
675 VALIDATE;
676 _ASSERTE(! sTitle.IsEmpty());
678 m_sTitle = sTitle;
682 void MyGraph::DrawGraph(CDC& dc)
684 VALIDATE;
685 ASSERT_VALID(&dc);
687 if (GetMaxSeriesSize()) {
688 dc.SetBkMode(TRANSPARENT);
690 // Populate the colors as a group of evenly spaced colors of maximum
691 // saturation.
692 int nColorsDelta(240 / GetMaxSeriesSize());
694 int baseColorL = 120;
695 int diffColorL = 60;
696 DWORD backgroundColor = ::GetSysColor(COLOR_WINDOW);
697 // If graph is a non-stacked line graph, use darker colors if system window color is light.
698 #if 0
699 if (m_eGraphType == MyGraph::Line && !m_bStackedGraph) {
700 int backgroundLuma = (GetRValue(backgroundColor) + GetGValue(backgroundColor) + GetBValue(backgroundColor)) / 3;
701 if (backgroundLuma > 128) {
702 baseColorL = 70;
703 diffColorL = 50;
706 #endif
707 for (WORD nGroup = 0; nGroup < GetMaxSeriesSize(); ++nGroup) {
708 WORD colorH = (WORD)(nColorsDelta * nGroup);
709 WORD colorL = (WORD)(baseColorL+(diffColorL*(nGroup%2)));
710 WORD colorS = (WORD)(180)+(30*((1-nGroup%2)*(nGroup%3)));
711 COLORREF cr(MyGraph::HLStoRGB(colorH, colorL, colorS)); // Populate colors cleverly
712 m_dwaColors.SetAtGrow(nGroup, cr);
715 // Reduce the graphable area by the frame window and status bar. We will
716 // leave GAP_PIXELS pixels blank on all sides of the graph. So top-left
717 // side of graph is at GAP_PIXELS,GAP_PIXELS and the bottom-right side
718 // of graph is at (m_rcGraph.Height() - GAP_PIXELS), (m_rcGraph.Width() -
719 // GAP_PIXELS). These settings are altered by axis labels and legends.
720 CRect rcWnd;
721 GetClientRect(&rcWnd);
722 m_rcGraph.left = GAP_PIXELS;
723 m_rcGraph.top = GAP_PIXELS;
724 m_rcGraph.right = rcWnd.Width() - GAP_PIXELS;
725 m_rcGraph.bottom = rcWnd.Height() - GAP_PIXELS;
727 CBrush br;
728 VERIFY(br.CreateSolidBrush(backgroundColor));
729 dc.FillRect(rcWnd, &br);
730 br.DeleteObject();
732 // Draw graph title.
733 DrawTitle(dc);
735 // Set the axes and origin values.
736 SetupAxes(dc);
738 // Draw legend if there is one and there's enough space.
739 if (m_saLegendLabels.GetSize() && m_rcGraph.right-m_rcGraph.left > LEGEND_VISIBILITY_THRESHOLD) {
740 DrawLegend(dc);
742 else{
743 m_rcLegend.SetRectEmpty();
746 // Draw axes unless it's a pie.
747 if (m_eGraphType != MyGraph::PieChart) {
748 DrawAxes(dc);
751 // Draw series data and labels.
752 switch (m_eGraphType) {
753 case MyGraph::Bar: DrawSeriesBar(dc); break;
754 case MyGraph::Line: if (m_bStackedGraph) DrawSeriesLineStacked(dc); else DrawSeriesLine(dc); break;
755 case MyGraph::PieChart: DrawSeriesPie(dc); break;
756 default: _ASSERTE(! "Bad default case"); break;
761 // Draw graph title; size is proportionate to width.
762 void MyGraph::DrawTitle(CDC& dc)
764 VALIDATE;
765 ASSERT_VALID(&dc);
767 // Create the title font.
768 CFont fontTitle;
769 VERIFY(fontTitle.CreatePointFont(max(m_rcGraph.Width() / TITLE_DIVISOR, MIN_FONT_SIZE),
770 _T("Arial"), &dc));
771 CFont* pFontOld = dc.SelectObject(&fontTitle);
772 ASSERT_VALID(pFontOld);
774 // Draw the title.
775 m_rcTitle.SetRect(GAP_PIXELS, GAP_PIXELS, m_rcGraph.Width() + GAP_PIXELS,
776 m_rcGraph.Height() + GAP_PIXELS);
778 dc.DrawText(m_sTitle, m_rcTitle, DT_CENTER | DT_NOPREFIX | DT_SINGLELINE |
779 DT_TOP | DT_CALCRECT);
781 m_rcTitle.right = m_rcGraph.Width() + GAP_PIXELS;
783 dc.DrawText(m_sTitle, m_rcTitle, DT_CENTER | DT_NOPREFIX | DT_SINGLELINE |
784 DT_TOP);
786 VERIFY(dc.SelectObject(pFontOld));
787 fontTitle.DeleteObject();
790 // Set the axes and origin values.
791 void MyGraph::SetupAxes(CDC& dc)
793 VALIDATE;
794 ASSERT_VALID(&dc);
796 // Since pie has no axis lines, set to full size minus GAP_PIXELS on each
797 // side. These are needed for legend to plot itself.
798 if (MyGraph::PieChart == m_eGraphType) {
799 m_nXAxisWidth = m_rcGraph.Width() - (GAP_PIXELS * 2);
800 m_nYAxisHeight = m_rcGraph.Height() - m_rcTitle.bottom;
801 m_ptOrigin.x = GAP_PIXELS;
802 m_ptOrigin.y = m_rcGraph.Height() - GAP_PIXELS;
804 else {
805 // Bar and Line graphs.
807 // Need to find out how wide the biggest Y-axis tick label is
809 // Get and store height of axis label font.
810 m_nAxisLabelHeight = max(m_rcGraph.Height() / Y_AXIS_LABEL_DIVISOR, MIN_FONT_SIZE);
811 // Get and store height of tick label font.
812 m_nAxisTickLabelHeight = max(int(m_nAxisLabelHeight*0.8), MIN_FONT_SIZE);
814 CFont fontTickLabels;
815 VERIFY(fontTickLabels.CreatePointFont(m_nAxisTickLabelHeight, _T("Arial"), &dc));
816 // Select font and store the old.
817 CFont* pFontOld = dc.SelectObject(&fontTickLabels);
818 ASSERT_VALID(pFontOld);
820 // Obtain tick label dimensions.
821 CString sTickLabel;
822 sTickLabel.Format(_T("%d"), GetMaxDataValue());
823 CSize sizTickLabel(dc.GetTextExtent(sTickLabel));
825 // Set old font object again and delete temporary font object.
826 VERIFY(dc.SelectObject(pFontOld));
827 fontTickLabels.DeleteObject();
829 // Determine axis specifications.
830 m_ptOrigin.x = m_rcGraph.left + m_nAxisLabelHeight/10 + 2*GAP_PIXELS
831 + sizTickLabel.cx + GAP_PIXELS + TICK_PIXELS;
832 m_ptOrigin.y = m_rcGraph.bottom - m_nAxisLabelHeight/10 - 2*GAP_PIXELS -
833 sizTickLabel.cy - GAP_PIXELS - TICK_PIXELS;
834 m_nYAxisHeight = m_ptOrigin.y - m_rcTitle.bottom - (2 * GAP_PIXELS);
835 m_nXAxisWidth = (m_rcGraph.Width() - GAP_PIXELS) - m_ptOrigin.x;
840 void MyGraph::DrawLegend(CDC& dc)
842 VALIDATE;
843 ASSERT_VALID(&dc);
845 // Create the legend font.
846 CFont fontLegend;
847 int pointFontHeight = max(m_rcGraph.Height() / LEGEND_DIVISOR, MIN_FONT_SIZE);
848 VERIFY(fontLegend.CreatePointFont(pointFontHeight, _T("Arial"), &dc));
850 // Get the height of each label.
851 LOGFONT lf;
852 ::SecureZeroMemory(&lf, sizeof(lf));
853 VERIFY(fontLegend.GetLogFont(&lf));
854 int nLabelHeight(abs(lf.lfHeight));
856 // Get number of legend entries
857 int nLegendEntries = max(1, GetMaxSeriesSize());
859 // Calculate optimal label height = AvailableLegendHeight/AllAuthors
860 // Use a buffer of (GAP_PIXELS / 2) on each side inside the legend, and in addition the same
861 // gab above and below the legend frame, so in total 2*GAP_PIXELS
862 double optimalLabelHeight = double(m_rcGraph.Height() - 2*GAP_PIXELS)/nLegendEntries;
864 // Now relate the LabelHeight to the PointFontHeight
865 int optimalPointFontHeight = int(pointFontHeight*optimalLabelHeight/nLabelHeight);
867 // Limit the optimal PointFontHeight to the available range
868 optimalPointFontHeight = min( max(optimalPointFontHeight, MIN_FONT_SIZE), pointFontHeight);
870 // If the optimalPointFontHeight is different from the initial one, create a new legend font
871 if (optimalPointFontHeight != pointFontHeight) {
872 fontLegend.DeleteObject();
873 VERIFY(fontLegend.CreatePointFont(optimalPointFontHeight, _T("Arial"), &dc));
874 VERIFY(fontLegend.GetLogFont(&lf));
875 nLabelHeight = abs(lf.lfHeight);
878 // Calculate maximum number of authors that can be shown with the current label height
879 int nShownAuthors = (m_rcGraph.Height() - 2*GAP_PIXELS)/nLabelHeight - 1;
880 // Fix rounding errors.
881 if (nShownAuthors+1 == GetMaxSeriesSize())
882 ++nShownAuthors;
884 // Get number of authors to be shown.
885 nShownAuthors = min(nShownAuthors, GetMaxSeriesSize());
886 // nShownAuthors contains now the number of authors
888 CFont* pFontOld = dc.SelectObject(&fontLegend);
889 ASSERT_VALID(pFontOld);
891 // Determine actual size of legend. A buffer of (GAP_PIXELS / 2) on each side,
892 // plus the height of each label based on the pint size of the font.
893 int nLegendHeight = (GAP_PIXELS / 2) + (nShownAuthors * nLabelHeight) + (GAP_PIXELS / 2);
894 // Draw the legend border. Allow LEGEND_COLOR_BAR_PIXELS pixels for
895 // display of label bars.
896 m_rcLegend.top = (m_rcGraph.Height() - nLegendHeight) / 2;
897 m_rcLegend.bottom = m_rcLegend.top + nLegendHeight;
898 m_rcLegend.right = m_rcGraph.Width() - GAP_PIXELS;
899 m_rcLegend.left = m_rcLegend.right - GetMaxLegendLabelLength(dc) -
900 LEGEND_COLOR_BAR_WIDTH_PIXELS;
901 VERIFY(dc.Rectangle(m_rcLegend));
903 int skipped_row = -1; // if != -1, this is the row that we show the ... in
904 if (nShownAuthors < GetMaxSeriesSize())
905 skipped_row = nShownAuthors-2;
906 // Draw each group's label and bar.
907 for (int nGroup = 0; nGroup < nShownAuthors; ++nGroup) {
909 int nLabelTop(m_rcLegend.top + (nGroup * nLabelHeight) +
910 (GAP_PIXELS / 2));
912 int nShownGroup = nGroup; // introduce helper variable to avoid code duplication
914 // Do we have a skipped row?
915 if (skipped_row != -1)
917 if (nGroup == skipped_row) {
918 // draw the dots
919 VERIFY(dc.TextOut(m_rcLegend.left + GAP_PIXELS, nLabelTop, _T("...") ));
920 continue;
922 if (nGroup == nShownAuthors-1) {
923 // we show the last group instead of the scheduled group
924 nShownGroup = GetMaxSeriesSize()-1;
927 // Draw the label.
928 VERIFY(dc.TextOut(m_rcLegend.left + GAP_PIXELS, nLabelTop,
929 m_saLegendLabels.GetAt(nShownGroup)));
931 // Determine the bar.
932 CRect rcBar;
933 rcBar.left = m_rcLegend.left + GAP_PIXELS + GetMaxLegendLabelLength(dc) + GAP_PIXELS;
934 rcBar.top = nLabelTop + LEGEND_COLOR_BAR_GAP_PIXELS;
935 rcBar.right = m_rcLegend.right - GAP_PIXELS;
936 rcBar.bottom = rcBar.top + nLabelHeight - LEGEND_COLOR_BAR_GAP_PIXELS;
937 VERIFY(dc.Rectangle(rcBar));
939 // Draw bar for group.
940 COLORREF crBar(m_dwaColors.GetAt(nShownGroup));
941 CBrush br(crBar);
943 CBrush* pBrushOld = dc.SelectObject(&br);
944 ASSERT_VALID(pBrushOld);
946 rcBar.DeflateRect(LEGEND_COLOR_BAR_GAP_PIXELS, LEGEND_COLOR_BAR_GAP_PIXELS);
947 dc.FillRect(rcBar, &br);
949 dc.SelectObject(pBrushOld);
950 br.DeleteObject();
953 VERIFY(dc.SelectObject(pFontOld));
954 fontLegend.DeleteObject();
958 void MyGraph::DrawAxes(CDC& dc) const
960 VALIDATE;
961 ASSERT_VALID(&dc);
962 _ASSERTE(MyGraph::PieChart != m_eGraphType);
964 dc.SetTextColor(::GetSysColor(COLOR_WINDOWTEXT));
966 // Draw y axis.
967 dc.MoveTo(m_ptOrigin);
968 VERIFY(dc.LineTo(m_ptOrigin.x, m_ptOrigin.y - m_nYAxisHeight));
970 // Draw x axis.
971 dc.MoveTo(m_ptOrigin);
973 if (m_saLegendLabels.GetSize()) {
975 VERIFY(dc.LineTo(m_ptOrigin.x +
976 (m_nXAxisWidth - m_rcLegend.Width() - (GAP_PIXELS * 2)),
977 m_ptOrigin.y));
979 else {
980 VERIFY(dc.LineTo(m_ptOrigin.x + m_nXAxisWidth, m_ptOrigin.y));
983 // Note: m_nAxisLabelHeight and m_nAxisTickLabelHeight have been calculated in SetupAxis()
985 // Create the x-axis label font.
986 CFont fontXAxis;
987 VERIFY(fontXAxis.CreatePointFont(m_nAxisLabelHeight, _T("Arial"), &dc));
989 // Obtain the height of the font in device coordinates.
990 LOGFONT pLF;
991 VERIFY(fontXAxis.GetLogFont(&pLF));
992 int fontHeightDC = pLF.lfHeight;
994 // Create the y-axis label font.
995 CFont fontYAxis;
996 VERIFY(fontYAxis.CreateFont(
997 /* nHeight */ fontHeightDC,
998 /* nWidth */ 0,
999 /* nEscapement */ 90 * 10,
1000 /* nOrientation */ 0,
1001 /* nWeight */ FW_DONTCARE,
1002 /* bItalic */ false,
1003 /* bUnderline */ false,
1004 /* cStrikeOut */ 0,
1005 ANSI_CHARSET,
1006 OUT_DEFAULT_PRECIS,
1007 CLIP_DEFAULT_PRECIS,
1008 PROOF_QUALITY,
1009 VARIABLE_PITCH | FF_DONTCARE,
1010 _T("Arial"))
1013 // Set the y-axis label font and draw the label.
1014 CFont* pFontOld = dc.SelectObject(&fontYAxis);
1015 ASSERT_VALID(pFontOld);
1016 CSize sizYLabel(dc.GetTextExtent(m_sYAxisLabel));
1017 VERIFY(dc.TextOut(GAP_PIXELS, (m_rcGraph.Height() + sizYLabel.cx) / 2,
1018 m_sYAxisLabel));
1020 // Set the x-axis label font and draw the label.
1021 VERIFY(dc.SelectObject(&fontXAxis));
1022 CSize sizXLabel(dc.GetTextExtent(m_sXAxisLabel));
1023 VERIFY(dc.TextOut(m_ptOrigin.x + (m_nXAxisWidth - sizXLabel.cx) / 2,
1024 m_rcGraph.bottom - GAP_PIXELS - sizXLabel.cy, m_sXAxisLabel));
1026 // chose suitable tick step (1, 2, 5, 10, 20, 50, etc.)
1027 int nMaxDataValue(GetMaxDataValue());
1028 nMaxDataValue = max(nMaxDataValue, 1);
1029 int nTickStep = 1;
1030 while (10 * nTickStep * Y_AXIS_TICK_COUNT_TARGET <= nMaxDataValue)
1031 nTickStep *= 10;
1033 if (5 * nTickStep * Y_AXIS_TICK_COUNT_TARGET <= nMaxDataValue)
1034 nTickStep *= 5;
1035 if (2 * nTickStep * Y_AXIS_TICK_COUNT_TARGET <= nMaxDataValue)
1036 nTickStep *= 2;
1038 // We hardwire TITLE_DIVISOR y-axis ticks here for simplicity.
1039 int nTickCount(nMaxDataValue / nTickStep);
1040 double tickSpace = (double)m_nYAxisHeight * nTickStep / (double)nMaxDataValue;
1042 // create tick label font and set it in the device context
1043 CFont fontTickLabels;
1044 VERIFY(fontTickLabels.CreatePointFont(m_nAxisTickLabelHeight, _T("Arial"), &dc));
1045 VERIFY(dc.SelectObject(&fontTickLabels));
1047 for (int nTick = 0; nTick < nTickCount; ++nTick)
1049 int nTickYLocation = static_cast<int>(m_ptOrigin.y - tickSpace * (nTick + 1) + 0.5);
1050 dc.MoveTo(m_ptOrigin.x - TICK_PIXELS, nTickYLocation);
1051 VERIFY(dc.LineTo(m_ptOrigin.x + TICK_PIXELS, nTickYLocation));
1053 // Draw tick label.
1054 CString sTickLabel;
1055 sTickLabel.Format(_T("%d"), nTickStep * (nTick+1));
1056 CSize sizTickLabel(dc.GetTextExtent(sTickLabel));
1058 VERIFY(dc.TextOut(m_ptOrigin.x - GAP_PIXELS - sizTickLabel.cx - TICK_PIXELS,
1059 nTickYLocation - sizTickLabel.cy/2, sTickLabel));
1062 // Draw X axis tick marks.
1063 POSITION pos(m_olMyGraphSeries.GetHeadPosition());
1064 int nSeries(0);
1066 while (pos) {
1068 MyGraphSeries* pSeries = m_olMyGraphSeries.GetNext(pos);
1069 ASSERT_VALID(pSeries);
1071 // Ignore unpopulated series if bar chart.
1072 if (m_eGraphType != MyGraph::Bar ||
1073 0 < pSeries->GetNonZeroElementCount()) {
1075 // Get the spacing of the series.
1076 int nSeriesSpace(0);
1078 if (m_saLegendLabels.GetSize()) {
1080 nSeriesSpace =
1081 (m_nXAxisWidth - m_rcLegend.Width() - (GAP_PIXELS * 2)) /
1082 (m_eGraphType == MyGraph::Bar ?
1083 GetNonZeroSeriesCount() : (int)m_olMyGraphSeries.GetCount());
1085 else {
1086 nSeriesSpace = m_nXAxisWidth / (m_eGraphType == MyGraph::Bar ?
1087 GetNonZeroSeriesCount() : (int)m_olMyGraphSeries.GetCount());
1090 int nTickXLocation(m_ptOrigin.x + ((nSeries + 1) * nSeriesSpace) -
1091 (nSeriesSpace / 2));
1093 dc.MoveTo(nTickXLocation, m_ptOrigin.y - TICK_PIXELS);
1094 VERIFY(dc.LineTo(nTickXLocation, m_ptOrigin.y + TICK_PIXELS));
1096 // Draw x-axis tick label.
1097 CString sTickLabel(pSeries->GetLabel());
1098 CSize sizTickLabel(dc.GetTextExtent(sTickLabel));
1100 VERIFY(dc.TextOut(nTickXLocation - (sizTickLabel.cx / 2),
1101 m_ptOrigin.y + TICK_PIXELS + GAP_PIXELS, sTickLabel));
1103 ++nSeries;
1107 VERIFY(dc.SelectObject(pFontOld));
1108 fontXAxis.DeleteObject();
1109 fontYAxis.DeleteObject();
1110 fontTickLabels.DeleteObject();
1114 void MyGraph::DrawSeriesBar(CDC& dc) const
1116 VALIDATE;
1117 ASSERT_VALID(&dc);
1119 // How much space does each series get (includes inter series space)?
1120 // We ignore series whose members are all zero.
1121 double availableSpace = m_saLegendLabels.GetSize()
1122 ? m_nXAxisWidth - m_rcLegend.Width() - (GAP_PIXELS * 2)
1123 : m_nXAxisWidth;
1125 double seriesSpace = availableSpace / (double)GetNonZeroSeriesCount();
1127 // Determine width of bars. Data points with a value of zero are assumed
1128 // to be empty. This is a bad assumption.
1129 double barWidth(0.0);
1131 // This is the width of the largest series (no inter series space).
1132 double maxSeriesPlotSize(0.0);
1134 if(!m_bStackedGraph){
1135 barWidth = seriesSpace / GetMaxNonZeroSeriesSize();
1136 if (1 < GetNonZeroSeriesCount()) {
1137 barWidth *= INTERSERIES_PERCENT_USED;
1139 maxSeriesPlotSize = GetMaxNonZeroSeriesSize() * barWidth;
1141 else{
1142 barWidth = seriesSpace * INTERSERIES_PERCENT_USED;
1143 maxSeriesPlotSize = barWidth;
1146 // Iterate the series.
1147 POSITION pos(m_olMyGraphSeries.GetHeadPosition());
1148 int nSeries(0);
1150 while (pos) {
1152 MyGraphSeries* pSeries = m_olMyGraphSeries.GetNext(pos);
1153 ASSERT_VALID(pSeries);
1155 // Ignore unpopulated series.
1156 if (0 < pSeries->GetNonZeroElementCount()) {
1158 // Draw each bar; empty bars are not drawn.
1159 double runningLeft(m_ptOrigin.x + (nSeries + 1) * seriesSpace -
1160 maxSeriesPlotSize);
1162 double stackAccumulator(0.0);
1164 for (int nGroup = 0; nGroup < GetMaxSeriesSize(); ++nGroup) {
1166 if (pSeries->GetData(nGroup)) {
1168 int nMaxDataValue(GetMaxDataValue());
1169 nMaxDataValue = max(nMaxDataValue, 1);
1170 double barTop = m_ptOrigin.y - (double)m_nYAxisHeight *
1171 pSeries->GetData(nGroup) / (double)nMaxDataValue - stackAccumulator;
1173 CRect rcBar;
1174 rcBar.left = (int)runningLeft;
1175 rcBar.top = (int)barTop;
1176 // Make adjacent bar borders overlap, so there's only one pixel border line between them.
1177 rcBar.right = (int)(runningLeft + barWidth) + 1;
1178 rcBar.bottom = (int)((double)m_ptOrigin.y - stackAccumulator) + 1;
1180 if(m_bStackedGraph){
1181 stackAccumulator = (double)m_ptOrigin.y - barTop;
1184 pSeries->SetTipRegion(nGroup, rcBar);
1186 COLORREF crBar(m_dwaColors.GetAt(nGroup));
1187 CBrush br(crBar);
1188 CBrush* pBrushOld = dc.SelectObject(&br);
1189 ASSERT_VALID(pBrushOld);
1191 VERIFY(dc.Rectangle(rcBar));
1192 dc.SelectObject(pBrushOld);
1193 br.DeleteObject();
1195 if(!m_bStackedGraph){
1196 runningLeft += barWidth;
1201 ++nSeries;
1205 if (!m_bStackedGraph) {
1206 int nMaxDataValue = max(GetMaxDataValue(), 1);
1207 double barTop = m_ptOrigin.y - (double)m_nYAxisHeight *
1208 (GetAverageDataValue() / (double)nMaxDataValue);
1209 dc.MoveTo(m_ptOrigin.x, barTop);
1210 VERIFY(dc.LineTo(m_ptOrigin.x + (m_nXAxisWidth - m_rcLegend.Width() - (GAP_PIXELS * 2)), barTop));
1215 void MyGraph::DrawSeriesLine(CDC& dc) const
1217 VALIDATE;
1218 ASSERT_VALID(&dc);
1219 _ASSERTE(!m_bStackedGraph);
1221 // Iterate the groups.
1222 CPoint ptLastLoc(0,0);
1223 int dataLastLoc(0);
1225 for (int nGroup = 0; nGroup < GetMaxSeriesSize(); nGroup++) {
1227 // How much space does each series get (includes inter series space)?
1228 int nSeriesSpace(0);
1230 if (m_saLegendLabels.GetSize()) {
1232 nSeriesSpace = (m_nXAxisWidth - m_rcLegend.Width() - (GAP_PIXELS * 2)) /
1233 (int)m_olMyGraphSeries.GetCount();
1235 else {
1236 nSeriesSpace = m_nXAxisWidth / (int)m_olMyGraphSeries.GetCount();
1239 // Determine width of bars.
1240 int nMaxSeriesSize(GetMaxSeriesSize());
1241 nMaxSeriesSize = max(nMaxSeriesSize, 1);
1242 int nBarWidth(nSeriesSpace / nMaxSeriesSize);
1244 if (1 < m_olMyGraphSeries.GetCount()) {
1245 nBarWidth = (int) ((double) nBarWidth * INTERSERIES_PERCENT_USED);
1248 // This is the width of the largest series (no inter series space).
1249 //int nMaxSeriesPlotSize(GetMaxSeriesSize() * nBarWidth);
1251 // Iterate the series.
1252 POSITION pos(m_olMyGraphSeries.GetHeadPosition());
1254 // Build objects.
1255 COLORREF crLine(m_dwaColors.GetAt(nGroup));
1256 CBrush br(crLine);
1257 CBrush* pBrushOld = dc.SelectObject(&br);
1258 ASSERT_VALID(pBrushOld);
1259 CPen penLine(PS_SOLID, 1, crLine);
1260 CPen* pPenOld = dc.SelectObject(&penLine);
1261 ASSERT_VALID(pPenOld);
1263 for (int nSeries = 0; nSeries < m_olMyGraphSeries.GetCount(); ++nSeries) {
1265 MyGraphSeries* pSeries = m_olMyGraphSeries.GetNext(pos);
1266 ASSERT_VALID(pSeries);
1268 // Get x and y location of center of ellipse.
1269 CPoint ptLoc(0,0);
1271 ptLoc.x = m_ptOrigin.x + (((nSeries + 1) * nSeriesSpace) -
1272 (nSeriesSpace / 2));
1274 int nMaxDataValue(GetMaxDataValue());
1275 nMaxDataValue = max(nMaxDataValue, 1);
1276 double dLineHeight(pSeries->GetData(nGroup) * m_nYAxisHeight /
1277 nMaxDataValue);
1279 ptLoc.y = (int) ((double) m_ptOrigin.y - dLineHeight);
1282 // Draw line back to last data member.
1283 if (nSeries > 0 && (pSeries->GetData(nGroup)!=0 || dataLastLoc != 0)) {
1285 dc.MoveTo(ptLastLoc.x, ptLastLoc.y - 1);
1286 VERIFY(dc.LineTo(ptLoc.x - 1, ptLoc.y - 1));
1289 // Now draw ellipse.
1290 CRect rcEllipse(ptLoc.x - 3, ptLoc.y - 3, ptLoc.x + 3, ptLoc.y + 3);
1291 if(pSeries->GetData(nGroup)!=0){
1292 VERIFY(dc.Ellipse(rcEllipse));
1294 if (m_olMyGraphSeries.GetCount() < 40)
1296 pSeries->SetTipRegion(nGroup, rcEllipse);
1299 // Save last pt and data
1300 ptLastLoc = ptLoc;
1301 dataLastLoc = pSeries->GetData(nGroup);
1303 VERIFY(dc.SelectObject(pPenOld));
1304 penLine.DeleteObject();
1305 VERIFY(dc.SelectObject(pBrushOld));
1306 br.DeleteObject();
1309 int nMaxDataValue = max(GetMaxDataValue(), 1);
1310 double barTop = m_ptOrigin.y - (double)m_nYAxisHeight *
1311 (GetAverageDataValue() / (double)nMaxDataValue);
1312 dc.MoveTo(m_ptOrigin.x, barTop);
1313 VERIFY(dc.LineTo(m_ptOrigin.x + (m_nXAxisWidth - m_rcLegend.Width() - (GAP_PIXELS * 2)), barTop));
1317 void MyGraph::DrawSeriesLineStacked(CDC& dc) const
1319 VALIDATE;
1320 ASSERT_VALID(&dc);
1321 _ASSERTE(m_bStackedGraph);
1323 int nSeriesCount = (int)m_olMyGraphSeries.GetCount();
1325 CArray<int> stackAccumulator;
1326 stackAccumulator.SetSize(nSeriesCount);
1328 CArray<CPoint> polygon;
1329 // Special case: if we only have single series, make polygon
1330 // a bar instead of one pixel line.
1331 polygon.SetSize(nSeriesCount==1 ? 4 : nSeriesCount * 2);
1333 // How much space does each series get?
1334 int nSeriesSpace(0);
1335 if (m_saLegendLabels.GetSize()) {
1336 nSeriesSpace = (m_nXAxisWidth - m_rcLegend.Width() - (GAP_PIXELS * 2)) /
1337 nSeriesCount;
1339 else {
1340 nSeriesSpace = m_nXAxisWidth / nSeriesCount;
1343 int nMaxDataValue(GetMaxDataValue());
1344 nMaxDataValue = max(nMaxDataValue, 1);
1345 double dYScaling = double(m_nYAxisHeight) / nMaxDataValue;
1347 // Iterate the groups.
1348 for (int nGroup = 0; nGroup < GetMaxSeriesSize(); nGroup++) {
1350 // Build objects.
1351 COLORREF crGroup(m_dwaColors.GetAt(nGroup));
1352 CBrush br(crGroup);
1353 CBrush* pBrushOld = dc.SelectObject(&br);
1354 ASSERT_VALID(pBrushOld);
1355 // For polygon outline, use average of this and previous color, and darken it.
1356 COLORREF crPrevGroup(nGroup > 0 ? m_dwaColors.GetAt(nGroup-1) : crGroup);
1357 COLORREF crOutline = RGB(
1358 (GetRValue(crGroup)+GetRValue(crPrevGroup))/3,
1359 (GetGValue(crGroup)+GetGValue(crPrevGroup))/3,
1360 (GetBValue(crGroup)+GetBValue(crPrevGroup))/3);
1361 CPen penLine(PS_SOLID, 1, crOutline);
1362 CPen* pPenOld = dc.SelectObject(&penLine);
1363 ASSERT_VALID(pPenOld);
1365 // Construct bottom part of polygon from current stack accumulator
1366 for (int nPolyBottom = 0; nPolyBottom < nSeriesCount; ++nPolyBottom) {
1367 CPoint ptLoc;
1368 ptLoc.x = m_ptOrigin.x + (((nPolyBottom + 1) * nSeriesSpace) - (nSeriesSpace / 2));
1369 double dLineHeight((stackAccumulator[nPolyBottom]) * dYScaling);
1370 ptLoc.y = (int) ((double) m_ptOrigin.y - dLineHeight);
1372 if (nSeriesCount > 1) {
1373 polygon[nSeriesCount-nPolyBottom-1] = ptLoc;
1374 } else {
1375 // special case: when there's one series, make polygon a bar
1376 polygon[0] = CPoint(ptLoc.x-GAP_PIXELS/2, ptLoc.y);
1377 polygon[1] = CPoint(ptLoc.x+GAP_PIXELS/2, ptLoc.y);
1381 // Iterate the series, construct upper part of polygon and upadte stack accumulator
1382 POSITION pos(m_olMyGraphSeries.GetHeadPosition());
1383 for (int nSeries = 0; nSeries < nSeriesCount; ++nSeries) {
1385 MyGraphSeries* pSeries = m_olMyGraphSeries.GetNext(pos);
1386 ASSERT_VALID(pSeries);
1388 CPoint ptLoc;
1389 ptLoc.x = m_ptOrigin.x + (((nSeries + 1) * nSeriesSpace) -
1390 (nSeriesSpace / 2));
1391 double dLineHeight((pSeries->GetData(nGroup) + stackAccumulator[nSeries]) * dYScaling);
1392 ptLoc.y = (int) ((double) m_ptOrigin.y - dLineHeight);
1393 if (nSeriesCount > 1) {
1394 polygon[nSeriesCount+nSeries] = ptLoc;
1395 } else {
1396 // special case: when there's one series, make polygon a bar
1397 polygon[2] = CPoint(ptLoc.x+GAP_PIXELS/2, ptLoc.y);
1398 polygon[3] = CPoint(ptLoc.x-GAP_PIXELS/2, ptLoc.y);
1401 stackAccumulator[nSeries] += pSeries->GetData(nGroup);
1404 // Draw polygon
1405 VERIFY(dc.Polygon(polygon.GetData(), (int)polygon.GetSize()));
1407 VERIFY(dc.SelectObject(pPenOld));
1408 penLine.DeleteObject();
1409 VERIFY(dc.SelectObject(pBrushOld));
1410 br.DeleteObject();
1415 void MyGraph::DrawSeriesPie(CDC& dc) const
1417 VALIDATE;
1418 ASSERT_VALID(&dc);
1420 // Determine width of pie display area (pie and space).
1421 int nSeriesSpace(0);
1423 int seriesCount = GetNonZeroSeriesCount();
1424 int horizontalSpace(0);
1426 if (m_saLegendLabels.GetSize()) {
1427 // With legend box.
1429 horizontalSpace = m_nXAxisWidth - m_rcLegend.Width() - (GAP_PIXELS * 2);
1430 int nPieAndSpaceWidth(horizontalSpace / (seriesCount ? seriesCount : 1));
1432 // Height is limiting factor.
1433 if (nPieAndSpaceWidth > m_nYAxisHeight - (GAP_PIXELS * 2)) {
1434 nSeriesSpace = (m_nYAxisHeight - (GAP_PIXELS * 2));
1436 else {
1437 // Width is limiting factor.
1438 nSeriesSpace = nPieAndSpaceWidth;
1441 else {
1442 // No legend box.
1444 horizontalSpace = m_nXAxisWidth;
1446 // Height is limiting factor.
1447 if (m_nXAxisWidth > m_nYAxisHeight * (seriesCount ? seriesCount : 1)) {
1448 nSeriesSpace = m_nYAxisHeight;
1450 else {
1451 // Width is limiting factor.
1452 nSeriesSpace = m_nXAxisWidth / (seriesCount ? seriesCount : 1);
1456 // Make pies be centered horizontally
1457 int xOrigin = m_ptOrigin.x + GAP_PIXELS + (horizontalSpace - nSeriesSpace * seriesCount) / 2;
1459 // Create font for labels.
1460 CFont fontLabels;
1461 int pointFontHeight = max(m_rcGraph.Height() / Y_AXIS_LABEL_DIVISOR, MIN_FONT_SIZE);
1462 VERIFY(fontLabels.CreatePointFont(pointFontHeight, _T("Arial"), &dc));
1463 CFont* pFontOld = dc.SelectObject(&fontLabels);
1464 ASSERT_VALID(pFontOld);
1466 // Draw each pie.
1467 int nPie(0);
1468 int nRadius((int) (nSeriesSpace * INTERSERIES_PERCENT_USED / 2.0));
1469 POSITION pos(m_olMyGraphSeries.GetHeadPosition());
1471 while (pos) {
1473 MyGraphSeries* pSeries = m_olMyGraphSeries.GetNext(pos);
1474 ASSERT_VALID(pSeries);
1476 // Don't leave a space for empty pies.
1477 if (0 < pSeries->GetNonZeroElementCount()) {
1479 // Locate this pie.
1480 CPoint ptCenter;
1481 ptCenter.x = xOrigin + (nSeriesSpace * nPie) + nSeriesSpace / 2;
1482 ptCenter.y = m_ptOrigin.y - m_nYAxisHeight / 2;
1484 CRect rcPie;
1485 rcPie.left = ptCenter.x - nRadius;
1486 rcPie.right = ptCenter.x + nRadius;
1487 rcPie.top = ptCenter.y - nRadius;
1488 rcPie.bottom = ptCenter.y + nRadius;
1490 // Draw series label.
1491 CSize sizPieLabel(dc.GetTextExtent(pSeries->GetLabel()));
1493 VERIFY(dc.TextOut(ptCenter.x - (sizPieLabel.cx / 2),
1494 ptCenter.y + nRadius + GAP_PIXELS, pSeries->GetLabel()));
1496 // How much do the wedges total to?
1497 double dPieTotal(pSeries->GetDataTotal());
1499 // Draw each wedge in this pie.
1500 CPoint ptStart(rcPie.left, ptCenter.y);
1501 double dRunningWedgeTotal(0.0);
1503 for (int nGroup = 0; nGroup < m_saLegendLabels.GetSize(); ++nGroup) {
1505 // Ignore empty wedges.
1506 if (0 < pSeries->GetData(nGroup)) {
1508 // Get the degrees of this wedge.
1509 dRunningWedgeTotal += pSeries->GetData(nGroup);
1510 double dPercent(dRunningWedgeTotal * 100.0 / dPieTotal);
1511 double degrees(360.0 * dPercent / 100.0);
1513 // Find the location of the wedge's endpoint.
1514 CPoint ptEnd(WedgeEndFromDegrees(degrees, ptCenter, nRadius));
1516 // Special case: a wedge that takes up the whole pie would
1517 // otherwise be confused with an empty wedge.
1518 bool drawEmptyWedges = false;
1519 if (1 == pSeries->GetNonZeroElementCount()) {
1520 _ASSERTE(360 == (int)degrees && ptStart == ptEnd && "This is the problem we're correcting");
1521 --ptEnd.y;
1522 drawEmptyWedges = true;
1525 // If the wedge is zero size or very narrow, don't paint it.
1526 // If pie is small, and wedge data is small, we might get a wedges
1527 // where center and both endpoints lie on the same coordinate,
1528 // and endpoints differ only in one pixel. GDI draws such pie as whole pie,
1529 // so we just skip them instead.
1530 int distance = abs(ptStart.x-ptEnd.x) + abs(ptStart.y-ptEnd.y);
1531 if (drawEmptyWedges || distance > 1) {
1533 // Draw wedge.
1534 COLORREF crWedge(m_dwaColors.GetAt(nGroup));
1535 CBrush br(crWedge);
1536 CBrush* pBrushOld = dc.SelectObject(&br);
1537 ASSERT_VALID(pBrushOld);
1538 VERIFY(dc.Pie(rcPie, ptStart, ptEnd));
1540 // Create a region from the path we create.
1541 VERIFY(dc.BeginPath());
1542 VERIFY(dc.Pie(rcPie, ptStart, ptEnd));
1543 VERIFY(dc.EndPath());
1544 CRgn * prgnWedge = new CRgn;
1545 VERIFY(prgnWedge->CreateFromPath(&dc));
1546 pSeries->SetTipRegion(nGroup, prgnWedge);
1548 // Cleanup.
1549 dc.SelectObject(pBrushOld);
1550 br.DeleteObject();
1551 ptStart = ptEnd;
1556 ++nPie;
1560 // Draw X axis title
1561 CSize sizXLabel(dc.GetTextExtent(m_sXAxisLabel));
1562 VERIFY(dc.TextOut(xOrigin + (nSeriesSpace * nPie - sizXLabel.cx)/2,
1563 m_ptOrigin.y - m_nYAxisHeight/2 + nRadius + GAP_PIXELS*2 + sizXLabel.cy, m_sXAxisLabel));
1565 VERIFY(dc.SelectObject(pFontOld));
1566 fontLabels.DeleteObject();
1569 // Convert degrees to x and y coords.
1570 CPoint MyGraph::WedgeEndFromDegrees(double degrees, const CPoint& ptCenter,
1571 double radius) const
1573 VALIDATE;
1575 CPoint pt;
1577 double radians = degrees / 360.0 * PI * 2.0;
1579 pt.x = (int) (radius * cos(radians));
1580 pt.x = ptCenter.x - pt.x;
1582 pt.y = (int) (radius * sin(radians));
1583 pt.y = ptCenter.y + pt.y;
1585 return pt;
1588 // Spin The Message Loop: C++ version. See "Advanced Windows Programming",
1589 // M. Heller, p. 153, and the MS TechNet CD, PSS ID Number: Q99999.
1590 /* static */ UINT MyGraph::SpinTheMessageLoop(bool bNoDrawing /* = false */ ,
1591 bool bOnlyDrawing /* = false */ ,
1592 UINT uiMsgAllowed /* = WM_NULL */ )
1594 MSG msg;
1595 ::SecureZeroMemory(&msg, sizeof(msg));
1597 while (::PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
1599 // Do painting only.
1600 if (bOnlyDrawing && WM_PAINT == msg.message) {
1601 ::TranslateMessage(&msg);
1602 ::DispatchMessage(&msg);
1604 // Update user interface.
1605 AfxGetApp()->OnIdle(0);
1607 // Do everything *but* painting.
1608 else if (bNoDrawing && WM_PAINT == msg.message) {
1609 break;
1611 // Special handling for this message.
1612 else if (WM_QUIT == msg.message) {
1613 ::PostQuitMessage(static_cast<int>(msg.wParam));
1614 break;
1616 // Allow one message (like WM_LBUTTONDOWN).
1617 else if (uiMsgAllowed == msg.message
1618 && ! AfxGetApp()->PreTranslateMessage(&msg)) {
1619 ::TranslateMessage(&msg);
1620 ::DispatchMessage(&msg);
1621 break;
1623 // This is the general case.
1624 else if (! bOnlyDrawing && ! AfxGetApp()->PreTranslateMessage(&msg)) {
1625 ::TranslateMessage(&msg);
1626 ::DispatchMessage(&msg);
1628 // Update user interface, then free temporary objects.
1629 AfxGetApp()->OnIdle(0);
1630 AfxGetApp()->OnIdle(1);
1634 return msg.message;
1638 /////////////////////////////////////////////////////////////////////////////
1639 // Conversion routines: RGB to HLS (Red-Green-Blue to Hue-Luminosity-Saturation).
1640 // See Microsoft KnowledgeBase article Q29240.
1642 #define HLSMAX 240 // H,L, and S vary over 0-HLSMAX
1643 #define RGBMAX 255 // R,G, and B vary over 0-RGBMAX
1644 // HLSMAX BEST IF DIVISIBLE BY 6
1645 // RGBMAX, HLSMAX must each fit in a byte (255).
1647 #define UNDEFINED (HLSMAX * 2 / 3) // Hue is undefined if Saturation is 0
1648 // (grey-scale). This value determines
1649 // where the Hue scrollbar is initially
1650 // set for achromatic colors.
1653 // Convert HLS to RGB.
1654 /* static */ COLORREF MyGraph::HLStoRGB(WORD wH, WORD wL, WORD wS)
1656 _ASSERTE(0 <= wH && 240 >= wH && "Illegal hue value");
1657 _ASSERTE(0 <= wL && 240 >= wL && "Illegal lum value");
1658 _ASSERTE(0 <= wS && 240 >= wS && "Illegal sat value");
1660 WORD wR(0);
1661 WORD wG(0);
1662 WORD wB(0);
1664 // Achromatic case.
1665 if (0 == wS) {
1666 wR = wG = wB = (wL * RGBMAX) / HLSMAX;
1668 if (UNDEFINED != wH) {
1669 _ASSERTE(! "ERROR");
1672 else {
1673 // Chromatic case.
1674 WORD Magic1(0);
1675 WORD Magic2(0);
1677 // Set up magic numbers.
1678 if (wL <= HLSMAX / 2) {
1679 Magic2 = (wL * (HLSMAX + wS) + (HLSMAX / 2)) / HLSMAX;
1681 else {
1682 Magic2 = wL + wS - ((wL * wS) + (HLSMAX / 2)) / HLSMAX;
1685 Magic1 = 2 * wL - Magic2;
1687 // Get RGB, change units from HLSMAX to RGBMAX.
1688 wR = (HueToRGB(Magic1, Magic2, wH + (HLSMAX / 3)) * RGBMAX + (HLSMAX / 2)) / HLSMAX;
1689 wG = (HueToRGB(Magic1, Magic2, wH) * RGBMAX + (HLSMAX / 2)) / HLSMAX;
1690 wB = (HueToRGB(Magic1, Magic2, wH - (HLSMAX / 3)) * RGBMAX + (HLSMAX / 2)) / HLSMAX;
1693 return RGB(wR,wG,wB);
1696 // Utility routine for HLStoRGB.
1697 /* static */ WORD MyGraph::HueToRGB(WORD w1, WORD w2, WORD wH)
1699 // Range check: note values passed add/subtract thirds of range.
1700 if (wH < 0) {
1701 wH += HLSMAX;
1704 if (wH > HLSMAX) {
1705 wH -= HLSMAX;
1708 // Return r, g, or b value from this tridrant.
1709 if (wH < HLSMAX / 6) {
1710 return w1 + (((w2 - w1) * wH + (HLSMAX / 12)) / (HLSMAX / 6));
1713 if (wH < HLSMAX / 2) {
1714 return w2;
1717 if (wH < (HLSMAX * 2) / 3) {
1718 return w1 + (((w2 - w1) * (((HLSMAX * 2) / 3) - wH) + (HLSMAX / 12)) / (HLSMAX / 6));
1720 else {
1721 return w1;