Avoid a possible division-by-zero, and cast to a double to avoid premature precision...
[TortoiseGit.git] / src / Utils / MiscUI / MyGraph.cpp
blob7a577220defc0a4f3292679d05afae851a45ad57
1 // MyGraph.cpp
3 #include "stdafx.h"
4 #include "MyGraph.h"
5 #include "BufferDC.h"
7 #include <cmath>
8 #include <memory>
10 #ifdef _DEBUG
11 #define new DEBUG_NEW
12 #undef THIS_FILE
13 static char THIS_FILE[] = __FILE__;
14 #endif
17 /////////////////////////////////////////////////////////////////////////////
18 // This macro can be called at the beginning and ending of every
19 // method. It is identical to saying "ASSERT_VALID(); ASSERT_KINDOF();"
20 // but is written like this so that VALIDATE can be a macro. It is useful
21 // as an "early warning" that something has gone wrong with "this" object.
22 #ifndef VALIDATE
23 #ifdef _DEBUG
24 #define VALIDATE ::AfxAssertValidObject(this, __FILE__ , __LINE__ ); \
25 _ASSERTE(IsKindOf(GetRuntimeClass()));
26 #else
27 #define VALIDATE
28 #endif
29 #endif
32 /////////////////////////////////////////////////////////////////////////////
33 // Constants.
35 #define TICK_PIXELS 4 // Size of tick marks.
36 #define GAP_PIXELS 6 // Better if an even value.
37 #define LEGEND_COLOR_BAR_WIDTH_PIXELS 50 // Width of color bar.
38 #define LEGEND_COLOR_BAR_GAP_PIXELS 1 // Space between color bars.
39 #define Y_AXIS_TICK_COUNT_TARGET 5 // How many ticks should be there on the y axis.
40 #define MIN_FONT_SIZE 70 // The minimum font-size in pt*10.
41 #define LEGEND_VISIBILITY_THRESHOLD 300 // The width of the graph in pixels when the legend gets hidden.
43 #define INTERSERIES_PERCENT_USED 0.85 // How much of the graph is
44 // used for bars/pies (the
45 // rest is for inter-series
46 // spacing).
48 #define TITLE_DIVISOR 5 // Scale font to graph width.
49 #define LEGEND_DIVISOR 8 // Scale font to graph height.
50 #define Y_AXIS_LABEL_DIVISOR 6 // Scale font to graph height.
52 const double PI = 3.1415926535897932384626433832795;
54 /////////////////////////////////////////////////////////////////////////////
55 // MyGraphSeries
57 // Constructor.
58 MyGraphSeries::MyGraphSeries(const CString& sLabel /* = "" */ )
59 : m_sLabel(sLabel)
63 // Destructor.
64 /* virtual */ MyGraphSeries::~MyGraphSeries()
66 for (int nGroup = 0; nGroup < m_oaRegions.GetSize(); ++nGroup) {
67 delete m_oaRegions.GetAt(nGroup);
72 void MyGraphSeries::SetLabel(const CString& sLabel)
74 VALIDATE;
76 m_sLabel = sLabel;
80 void MyGraphSeries::SetData(int nGroup, int nValue)
82 VALIDATE;
83 _ASSERTE(0 <= nGroup);
85 m_dwaValues.SetAtGrow(nGroup, nValue);
89 void MyGraphSeries::SetTipRegion(int nGroup, const CRect& rc)
91 VALIDATE;
93 CRgn* prgnNew = new CRgn;
94 ASSERT_VALID(prgnNew);
96 VERIFY(prgnNew->CreateRectRgnIndirect(rc));
97 SetTipRegion(nGroup, prgnNew);
101 void MyGraphSeries::SetTipRegion(int nGroup, CRgn* prgn)
103 VALIDATE;
104 _ASSERTE(0 <= nGroup);
105 ASSERT_VALID(prgn);
107 // If there is an existing region, delete it.
108 CRgn* prgnOld = NULL;
110 if (nGroup < m_oaRegions.GetSize())
112 prgnOld = m_oaRegions.GetAt(nGroup);
113 ASSERT_NULL_OR_POINTER(prgnOld, CRgn);
116 if (prgnOld) {
117 delete prgnOld;
118 prgnOld = NULL;
121 // Add the new region.
122 m_oaRegions.SetAtGrow(nGroup, prgn);
124 _ASSERTE(m_oaRegions.GetSize() <= m_dwaValues.GetSize());
128 CString MyGraphSeries::GetLabel() const
130 VALIDATE;
132 return m_sLabel;
136 int MyGraphSeries::GetData(int nGroup) const
138 VALIDATE;
139 _ASSERTE(0 <= nGroup);
140 _ASSERTE(m_dwaValues.GetSize() > nGroup);
142 return m_dwaValues[nGroup];
145 // Returns the largest data value in this series.
146 int MyGraphSeries::GetMaxDataValue(bool bStackedGraph) const
148 VALIDATE;
150 int nMax(0);
152 for (int nGroup = 0; nGroup < m_dwaValues.GetSize(); ++nGroup) {
153 if(!bStackedGraph){
154 nMax = max(nMax, static_cast<int> (m_dwaValues.GetAt(nGroup)));
156 else{
157 nMax += static_cast<int> (m_dwaValues.GetAt(nGroup));
161 return nMax;
164 // Returns the average data value in this series.
165 int MyGraphSeries::GetAverageDataValue() const
167 VALIDATE;
169 int nTotal = 0;
171 for (int nGroup = 0; nGroup < m_dwaValues.GetSize(); ++nGroup) {
172 nTotal += static_cast<int> (m_dwaValues.GetAt(nGroup));
175 return nTotal / m_dwaValues.GetSize();
178 // Returns the number of data points that are not zero.
179 int MyGraphSeries::GetNonZeroElementCount() const
181 VALIDATE;
183 int nCount(0);
185 for (int nGroup = 0; nGroup < m_dwaValues.GetSize(); ++nGroup) {
187 if (m_dwaValues.GetAt(nGroup)) {
188 ++nCount;
192 return nCount;
195 // Returns the sum of the data points for this series.
196 int MyGraphSeries::GetDataTotal() const
198 VALIDATE;
200 int nTotal(0);
202 for (int nGroup = 0; nGroup < m_dwaValues.GetSize(); ++nGroup) {
203 nTotal += m_dwaValues.GetAt(nGroup);
206 return nTotal;
209 // Returns which group (if any) the sent point lies within in this series.
210 int MyGraphSeries::HitTest(const CPoint& pt, int searchStart = 0) const
212 VALIDATE;
214 for (int nGroup = searchStart; nGroup < m_oaRegions.GetSize(); ++nGroup) {
215 CRgn* prgnData = m_oaRegions.GetAt(nGroup);
216 ASSERT_NULL_OR_POINTER(prgnData, CRgn);
218 if (prgnData && prgnData->PtInRegion(pt)) {
219 return nGroup;
223 return -1;
226 // Get the series portion of the tip for this group in this series.
227 CString MyGraphSeries::GetTipText(int nGroup, const CString &unitString) const
229 VALIDATE;
230 _ASSERTE(0 <= nGroup);
231 _ASSERTE(m_oaRegions.GetSize() <= m_dwaValues.GetSize());
233 CString sTip;
235 sTip.Format(_T("%d %s (%d%%)"), m_dwaValues.GetAt(nGroup),
236 (LPCTSTR)unitString,
237 GetDataTotal() ? (int) (100.0 * (double) m_dwaValues.GetAt(nGroup) /
238 (double) GetDataTotal()) : 0);
240 return sTip;
244 /////////////////////////////////////////////////////////////////////////////
245 // MyGraph
247 // Constructor.
248 MyGraph::MyGraph(GraphType eGraphType /* = MyGraph::Pie */ , bool bStackedGraph /* = false */)
249 : m_nXAxisWidth(0)
250 , m_nYAxisHeight(0)
251 , m_nAxisLabelHeight(0)
252 , m_nAxisTickLabelHeight(0)
253 , m_eGraphType(eGraphType)
254 , m_bStackedGraph(bStackedGraph)
256 m_ptOrigin.x = m_ptOrigin.y = 0;
257 m_rcGraph.SetRectEmpty();
258 m_rcLegend.SetRectEmpty();
259 m_rcTitle.SetRectEmpty();
262 // Destructor.
263 /* virtual */ MyGraph::~MyGraph()
267 BEGIN_MESSAGE_MAP(MyGraph, CStatic)
268 //{{AFX_MSG_MAP(MyGraph)
269 ON_WM_PAINT()
270 ON_WM_SIZE()
271 //}}AFX_MSG_MAP
272 ON_NOTIFY_EX_RANGE(TTN_NEEDTEXTW, 0, 0xFFFF, OnNeedText)
273 ON_NOTIFY_EX_RANGE(TTN_NEEDTEXTA, 0, 0xFFFF, OnNeedText)
274 END_MESSAGE_MAP()
276 // Called by the framework to allow other necessary sub classing to occur
277 // before the window is sub classed.
278 void MyGraph::PreSubclassWindow()
280 VALIDATE;
282 CStatic::PreSubclassWindow();
284 VERIFY(EnableToolTips(true));
288 /////////////////////////////////////////////////////////////////////////////
289 // MyGraph message handlers
291 // Handle the tooltip messages. Returns true to mean message was handled.
292 BOOL MyGraph::OnNeedText(UINT /*uiId*/, NMHDR* pNMHDR, LRESULT* pResult)
294 _ASSERTE(pNMHDR && "Bad parameter passed");
295 _ASSERTE(pResult && "Bad parameter passed");
297 bool bReturn(false);
298 UINT_PTR uiID(pNMHDR->idFrom);
300 // Notification in NT from automatically created tooltip.
301 if (0U != uiID) {
302 bReturn = true;
304 // Need to handle both ANSI and UNICODE versions of the message.
305 TOOLTIPTEXTA* pTTTA = reinterpret_cast<TOOLTIPTEXTA*> (pNMHDR);
306 ASSERT_POINTER(pTTTA, TOOLTIPTEXTA);
308 TOOLTIPTEXTW* pTTTW = reinterpret_cast<TOOLTIPTEXTW*> (pNMHDR);
309 ASSERT_POINTER(pTTTW, TOOLTIPTEXTW);
311 CString sTipText(GetTipText());
313 #ifndef _UNICODE
314 if (TTN_NEEDTEXTA == pNMHDR->code) {
315 lstrcpyn(pTTTA->szText, sTipText, _countof(pTTTA->szText));
317 else {
318 _mbstowcsz(pTTTW->szText, sTipText, _countof(pTTTA->szText));
320 #else
321 if (pNMHDR->code == TTN_NEEDTEXTA) {
322 _wcstombsz(pTTTA->szText, sTipText, _countof(pTTTA->szText));
324 else {
325 lstrcpyn(pTTTW->szText, sTipText, _countof(pTTTA->szText));
327 #endif
329 *pResult = 0;
332 return bReturn;
335 // The framework calls this member function to determine whether a point is in
336 // the bounding rectangle of the specified tool.
337 INT_PTR MyGraph::OnToolHitTest(CPoint point, TOOLINFO* pTI) const
339 _ASSERTE(pTI && "Bad parameter passed");
341 // This works around the problem of the tip remaining visible when you move
342 // the mouse to various positions over this control.
343 INT_PTR nReturn(0);
344 static bool bTipPopped(false);
345 static CPoint ptPrev(-1,-1);
347 if (point != ptPrev) {
348 ptPrev = point;
350 if (bTipPopped) {
351 bTipPopped = false;
352 nReturn = -1;
354 else {
355 ::Sleep(50);
356 bTipPopped = true;
358 pTI->hwnd = m_hWnd;
359 pTI->uId = (UINT_PTR) m_hWnd;
360 pTI->lpszText = LPSTR_TEXTCALLBACK;
362 CRect rcWnd;
363 GetClientRect(&rcWnd);
364 pTI->rect = rcWnd;
365 nReturn = 1;
368 else {
369 nReturn = 1;
372 MyGraph::SpinTheMessageLoop();
374 return nReturn;
377 // Build the tip text for the part of the graph that the mouse is currently
378 // over.
379 CString MyGraph::GetTipText() const
381 VALIDATE;
383 CString sTip("");
385 // Get the position of the mouse.
386 CPoint pt;
387 VERIFY(::GetCursorPos(&pt));
388 ScreenToClient(&pt);
390 // Ask each part of the graph to check and see if the mouse is over it.
391 if (m_rcLegend.PtInRect(pt)) {
392 sTip = "Legend";
394 else if (m_rcTitle.PtInRect(pt)) {
395 sTip = "Title";
397 else {
398 int maxXAxis = m_ptOrigin.x + (m_nXAxisWidth - m_rcLegend.Width() - (GAP_PIXELS * 2));
399 if (pt.x >= m_ptOrigin.x && pt.x <= maxXAxis) {
400 int average = GetAverageDataValue();
401 int nMaxDataValue = max(GetMaxDataValue(), 1);
402 double barTop = m_ptOrigin.y - (double)m_nYAxisHeight *
403 (average / (double)nMaxDataValue);
404 if (pt.y >= barTop - 2 && pt.y <= barTop + 2) {
405 sTip.Format(_T("Average: %d %s (%d%%)"), average, m_sYAxisLabel, nMaxDataValue ? (100 * average / nMaxDataValue) : 0);
406 return sTip;
410 POSITION pos(m_olMyGraphSeries.GetHeadPosition());
412 while (pos && sTip.IsEmpty()) {
413 MyGraphSeries* pSeries = m_olMyGraphSeries.GetNext(pos);
414 ASSERT_VALID(pSeries);
416 int nGroup(0);
418 nGroup = pSeries->HitTest(pt,nGroup);
420 if (-1 != nGroup) {
421 if("" != sTip){
422 sTip += _T(", ");
424 sTip += m_saLegendLabels.GetAt(nGroup) + _T(": ");
425 sTip += pSeries->GetTipText(nGroup, m_sYAxisLabel);
426 nGroup++;
428 }while(-1 != nGroup);
432 return sTip;
435 // Handle WM_PAINT.
436 void MyGraph::OnPaint()
438 VALIDATE;
440 CBufferDC dc(this);
441 DrawGraph(dc);
444 // Handle WM_SIZE.
445 void MyGraph::OnSize(UINT nType, int cx, int cy)
447 VALIDATE;
449 CStatic::OnSize(nType, cx, cy);
451 Invalidate();
454 // Change the type of the graph; the caller should call Invalidate() on this
455 // window to make the effect of this change visible.
456 void MyGraph::SetGraphType(GraphType e, bool bStackedGraph)
458 VALIDATE;
460 m_eGraphType = e;
461 m_bStackedGraph = bStackedGraph;
464 // Calculate the current max legend label length in pixels.
465 int MyGraph::GetMaxLegendLabelLength(CDC& dc) const
467 VALIDATE;
468 ASSERT_VALID(&dc);
470 CString sMax;
471 int nMaxChars(-1);
472 CSize siz(-1,-1);
474 // First get max number of characters.
475 for (int nGroup = 0; nGroup < m_saLegendLabels.GetSize(); ++nGroup) {
476 int nLabelLength(m_saLegendLabels.GetAt(nGroup).GetLength());
478 if (nMaxChars < nLabelLength) {
479 nMaxChars = nLabelLength;
480 sMax = m_saLegendLabels.GetAt(nGroup);
484 // Now calculate the pixels.
485 siz = dc.GetTextExtent(sMax);
487 _ASSERTE(-1 < siz.cx);
489 return siz.cx;
492 // Returns the largest number of data points in any series.
493 int MyGraph::GetMaxSeriesSize() const
495 VALIDATE;
497 int nMax(0);
498 POSITION pos(m_olMyGraphSeries.GetHeadPosition());
500 while (pos) {
501 MyGraphSeries* pSeries = m_olMyGraphSeries.GetNext(pos);
502 ASSERT_VALID(pSeries);
504 nMax = max(nMax, (int)pSeries->m_dwaValues.GetSize());
507 return nMax;
510 // Returns the largest number of non-zero data points in any series.
511 int MyGraph::GetMaxNonZeroSeriesSize() const
513 VALIDATE;
515 int nMax(0);
516 POSITION pos(m_olMyGraphSeries.GetHeadPosition());
518 while (pos) {
519 MyGraphSeries* pSeries = m_olMyGraphSeries.GetNext(pos);
520 ASSERT_VALID(pSeries);
522 nMax = max(nMax, pSeries->GetNonZeroElementCount());
525 return nMax;
528 // Get the largest data value in all series.
529 int MyGraph::GetMaxDataValue() const
531 VALIDATE;
533 int nMax(0);
534 POSITION pos(m_olMyGraphSeries.GetHeadPosition());
536 while (pos) {
537 MyGraphSeries* pSeries = m_olMyGraphSeries.GetNext(pos);
538 ASSERT_VALID(pSeries);
540 nMax = max(nMax, pSeries->GetMaxDataValue(m_bStackedGraph));
543 return nMax;
546 // Get the average data value in all series.
547 int MyGraph::GetAverageDataValue() const
549 VALIDATE;
551 int nTotal = 0, nCount = 0;
552 POSITION pos(m_olMyGraphSeries.GetHeadPosition());
554 while (pos) {
555 MyGraphSeries* pSeries = m_olMyGraphSeries.GetNext(pos);
556 ASSERT_VALID(pSeries);
558 nTotal += pSeries->GetAverageDataValue();
559 ++nCount;
562 return nTotal / nCount;
565 // How many series are populated?
566 int MyGraph::GetNonZeroSeriesCount() const
568 VALIDATE;
570 int nCount(0);
571 POSITION pos(m_olMyGraphSeries.GetHeadPosition());
573 while (pos) {
574 MyGraphSeries* pSeries = m_olMyGraphSeries.GetNext(pos);
575 ASSERT_VALID(pSeries);
577 if (0 < pSeries->GetNonZeroElementCount()) {
578 ++nCount;
582 return nCount ? nCount : 1;
585 // Returns the group number for the sent label; -1 if not found.
586 int MyGraph::LookupLabel(const CString& sLabel) const
588 VALIDATE;
589 _ASSERTE(! sLabel.IsEmpty());
591 for (int nGroup = 0; nGroup < m_saLegendLabels.GetSize(); ++nGroup) {
593 if (0 == sLabel.CompareNoCase(m_saLegendLabels.GetAt(nGroup))) {
594 return nGroup;
598 return -1;
601 void MyGraph::Clear()
603 m_dwaColors.RemoveAll();
604 m_saLegendLabels.RemoveAll();
605 m_olMyGraphSeries.RemoveAll();
609 void MyGraph::AddSeries(MyGraphSeries& rMyGraphSeries)
611 VALIDATE;
612 ASSERT_VALID(&rMyGraphSeries);
613 _ASSERTE(m_saLegendLabels.GetSize() == rMyGraphSeries.m_dwaValues.GetSize());
615 m_olMyGraphSeries.AddTail(&rMyGraphSeries);
619 void MyGraph::SetXAxisLabel(const CString& sLabel)
621 VALIDATE;
622 _ASSERTE(! sLabel.IsEmpty());
624 m_sXAxisLabel = sLabel;
628 void MyGraph::SetYAxisLabel(const CString& sLabel)
630 VALIDATE;
631 _ASSERTE(! sLabel.IsEmpty());
633 m_sYAxisLabel = sLabel;
636 // Returns the group number added. Also, makes sure that all the series have
637 // this many elements.
638 int MyGraph::AppendGroup(const CString& sLabel)
640 VALIDATE;
642 // Add the group.
643 int nGroup((int)m_saLegendLabels.GetSize());
644 SetLegend(nGroup, sLabel);
646 // Make sure that all series have this element.
647 POSITION pos(m_olMyGraphSeries.GetHeadPosition());
649 while (pos) {
651 MyGraphSeries* pSeries = m_olMyGraphSeries.GetNext(pos);
652 ASSERT_VALID(pSeries);
654 if (nGroup >= pSeries->m_dwaValues.GetSize()) {
655 pSeries->m_dwaValues.SetAtGrow(nGroup, 0);
659 return nGroup;
662 // Set this value to the legend.
663 void MyGraph::SetLegend(int nGroup, const CString& sLabel)
665 VALIDATE;
666 _ASSERTE(0 <= nGroup);
668 m_saLegendLabels.SetAtGrow(nGroup, sLabel);
672 void MyGraph::SetGraphTitle(const CString& sTitle)
674 VALIDATE;
675 _ASSERTE(! sTitle.IsEmpty());
677 m_sTitle = sTitle;
681 void MyGraph::DrawGraph(CDC& dc)
683 VALIDATE;
684 ASSERT_VALID(&dc);
686 if (GetMaxSeriesSize()) {
687 dc.SetBkMode(TRANSPARENT);
689 // Populate the colors as a group of evenly spaced colors of maximum
690 // saturation.
691 int nColorsDelta(240 / GetMaxSeriesSize());
693 int baseColorL = 120;
694 int diffColorL = 60;
695 DWORD backgroundColor = ::GetSysColor(COLOR_WINDOW);
696 // If graph is a non-stacked line graph, use darker colors if system window color is light.
697 #if 0
698 if (m_eGraphType == MyGraph::Line && !m_bStackedGraph) {
699 int backgroundLuma = (GetRValue(backgroundColor) + GetGValue(backgroundColor) + GetBValue(backgroundColor)) / 3;
700 if (backgroundLuma > 128) {
701 baseColorL = 70;
702 diffColorL = 50;
705 #endif
706 for (WORD nGroup = 0; nGroup < GetMaxSeriesSize(); ++nGroup) {
707 WORD colorH = (WORD)(nColorsDelta * nGroup);
708 WORD colorL = (WORD)(baseColorL+(diffColorL*(nGroup%2)));
709 WORD colorS = (WORD)(180)+(30*((1-nGroup%2)*(nGroup%3)));
710 COLORREF cr(MyGraph::HLStoRGB(colorH, colorL, colorS)); // Populate colors cleverly
711 m_dwaColors.SetAtGrow(nGroup, cr);
714 // Reduce the graphable area by the frame window and status bar. We will
715 // leave GAP_PIXELS pixels blank on all sides of the graph. So top-left
716 // side of graph is at GAP_PIXELS,GAP_PIXELS and the bottom-right side
717 // of graph is at (m_rcGraph.Height() - GAP_PIXELS), (m_rcGraph.Width() -
718 // GAP_PIXELS). These settings are altered by axis labels and legends.
719 CRect rcWnd;
720 GetClientRect(&rcWnd);
721 m_rcGraph.left = GAP_PIXELS;
722 m_rcGraph.top = GAP_PIXELS;
723 m_rcGraph.right = rcWnd.Width() - GAP_PIXELS;
724 m_rcGraph.bottom = rcWnd.Height() - GAP_PIXELS;
726 CBrush br;
727 VERIFY(br.CreateSolidBrush(backgroundColor));
728 dc.FillRect(rcWnd, &br);
729 br.DeleteObject();
731 // Draw graph title.
732 DrawTitle(dc);
734 // Set the axes and origin values.
735 SetupAxes(dc);
737 // Draw legend if there is one and there's enough space.
738 if (m_saLegendLabels.GetSize() && m_rcGraph.right-m_rcGraph.left > LEGEND_VISIBILITY_THRESHOLD) {
739 DrawLegend(dc);
741 else{
742 m_rcLegend.SetRectEmpty();
745 // Draw axes unless it's a pie.
746 if (m_eGraphType != MyGraph::PieChart) {
747 DrawAxes(dc);
750 // Draw series data and labels.
751 switch (m_eGraphType) {
752 case MyGraph::Bar: DrawSeriesBar(dc); break;
753 case MyGraph::Line: if (m_bStackedGraph) DrawSeriesLineStacked(dc); else DrawSeriesLine(dc); break;
754 case MyGraph::PieChart: DrawSeriesPie(dc); break;
755 default: _ASSERTE(! "Bad default case"); break;
760 // Draw graph title; size is proportionate to width.
761 void MyGraph::DrawTitle(CDC& dc)
763 VALIDATE;
764 ASSERT_VALID(&dc);
766 // Create the title font.
767 CFont fontTitle;
768 VERIFY(fontTitle.CreatePointFont(max(m_rcGraph.Width() / TITLE_DIVISOR, MIN_FONT_SIZE),
769 _T("Arial"), &dc));
770 CFont* pFontOld = dc.SelectObject(&fontTitle);
771 ASSERT_VALID(pFontOld);
773 // Draw the title.
774 m_rcTitle.SetRect(GAP_PIXELS, GAP_PIXELS, m_rcGraph.Width() + GAP_PIXELS,
775 m_rcGraph.Height() + GAP_PIXELS);
777 dc.DrawText(m_sTitle, m_rcTitle, DT_CENTER | DT_NOPREFIX | DT_SINGLELINE |
778 DT_TOP | DT_CALCRECT);
780 m_rcTitle.right = m_rcGraph.Width() + GAP_PIXELS;
782 dc.DrawText(m_sTitle, m_rcTitle, DT_CENTER | DT_NOPREFIX | DT_SINGLELINE |
783 DT_TOP);
785 VERIFY(dc.SelectObject(pFontOld));
786 fontTitle.DeleteObject();
789 // Set the axes and origin values.
790 void MyGraph::SetupAxes(CDC& dc)
792 VALIDATE;
793 ASSERT_VALID(&dc);
795 // Since pie has no axis lines, set to full size minus GAP_PIXELS on each
796 // side. These are needed for legend to plot itself.
797 if (MyGraph::PieChart == m_eGraphType) {
798 m_nXAxisWidth = m_rcGraph.Width() - (GAP_PIXELS * 2);
799 m_nYAxisHeight = m_rcGraph.Height() - m_rcTitle.bottom;
800 m_ptOrigin.x = GAP_PIXELS;
801 m_ptOrigin.y = m_rcGraph.Height() - GAP_PIXELS;
803 else {
804 // Bar and Line graphs.
806 // Need to find out how wide the biggest Y-axis tick label is
808 // Get and store height of axis label font.
809 m_nAxisLabelHeight = max(m_rcGraph.Height() / Y_AXIS_LABEL_DIVISOR, MIN_FONT_SIZE);
810 // Get and store height of tick label font.
811 m_nAxisTickLabelHeight = max(int(m_nAxisLabelHeight*0.8), MIN_FONT_SIZE);
813 CFont fontTickLabels;
814 VERIFY(fontTickLabels.CreatePointFont(m_nAxisTickLabelHeight, _T("Arial"), &dc));
815 // Select font and store the old.
816 CFont* pFontOld = dc.SelectObject(&fontTickLabels);
817 ASSERT_VALID(pFontOld);
819 // Obtain tick label dimensions.
820 CString sTickLabel;
821 sTickLabel.Format(_T("%d"), GetMaxDataValue());
822 CSize sizTickLabel(dc.GetTextExtent(sTickLabel));
824 // Set old font object again and delete temporary font object.
825 VERIFY(dc.SelectObject(pFontOld));
826 fontTickLabels.DeleteObject();
828 // Determine axis specifications.
829 m_ptOrigin.x = m_rcGraph.left + m_nAxisLabelHeight/10 + 2*GAP_PIXELS
830 + sizTickLabel.cx + GAP_PIXELS + TICK_PIXELS;
831 m_ptOrigin.y = m_rcGraph.bottom - m_nAxisLabelHeight/10 - 2*GAP_PIXELS -
832 sizTickLabel.cy - GAP_PIXELS - TICK_PIXELS;
833 m_nYAxisHeight = m_ptOrigin.y - m_rcTitle.bottom - (2 * GAP_PIXELS);
834 m_nXAxisWidth = (m_rcGraph.Width() - GAP_PIXELS) - m_ptOrigin.x;
839 void MyGraph::DrawLegend(CDC& dc)
841 VALIDATE;
842 ASSERT_VALID(&dc);
844 // Create the legend font.
845 CFont fontLegend;
846 int pointFontHeight = max(m_rcGraph.Height() / LEGEND_DIVISOR, MIN_FONT_SIZE);
847 VERIFY(fontLegend.CreatePointFont(pointFontHeight, _T("Arial"), &dc));
849 // Get the height of each label.
850 LOGFONT lf;
851 ::SecureZeroMemory(&lf, sizeof(lf));
852 VERIFY(fontLegend.GetLogFont(&lf));
853 int nLabelHeight(abs(lf.lfHeight));
855 // Get number of legend entries
856 int nLegendEntries = max(1, GetMaxSeriesSize());
858 // Calculate optimal label height = AvailableLegendHeight/AllAuthors
859 // Use a buffer of (GAP_PIXELS / 2) on each side inside the legend, and in addition the same
860 // gab above and below the legend frame, so in total 2*GAP_PIXELS
861 double optimalLabelHeight = double(m_rcGraph.Height() - 2*GAP_PIXELS)/nLegendEntries;
863 // Now relate the LabelHeight to the PointFontHeight
864 int optimalPointFontHeight = int(pointFontHeight*optimalLabelHeight/nLabelHeight);
866 // Limit the optimal PointFontHeight to the available range
867 optimalPointFontHeight = min( max(optimalPointFontHeight, MIN_FONT_SIZE), pointFontHeight);
869 // If the optimalPointFontHeight is different from the initial one, create a new legend font
870 if (optimalPointFontHeight != pointFontHeight) {
871 fontLegend.DeleteObject();
872 VERIFY(fontLegend.CreatePointFont(optimalPointFontHeight, _T("Arial"), &dc));
873 VERIFY(fontLegend.GetLogFont(&lf));
874 nLabelHeight = abs(lf.lfHeight);
877 // Calculate maximum number of authors that can be shown with the current label height
878 int nShownAuthors = (m_rcGraph.Height() - 2*GAP_PIXELS)/nLabelHeight - 1;
879 // Fix rounding errors.
880 if (nShownAuthors+1 == GetMaxSeriesSize())
881 ++nShownAuthors;
883 // Get number of authors to be shown.
884 nShownAuthors = min(nShownAuthors, GetMaxSeriesSize());
885 // nShownAuthors contains now the number of authors
887 CFont* pFontOld = dc.SelectObject(&fontLegend);
888 ASSERT_VALID(pFontOld);
890 // Determine actual size of legend. A buffer of (GAP_PIXELS / 2) on each side,
891 // plus the height of each label based on the pint size of the font.
892 int nLegendHeight = (GAP_PIXELS / 2) + (nShownAuthors * nLabelHeight) + (GAP_PIXELS / 2);
893 // Draw the legend border. Allow LEGEND_COLOR_BAR_PIXELS pixels for
894 // display of label bars.
895 m_rcLegend.top = (m_rcGraph.Height() - nLegendHeight) / 2;
896 m_rcLegend.bottom = m_rcLegend.top + nLegendHeight;
897 m_rcLegend.right = m_rcGraph.Width() - GAP_PIXELS;
898 m_rcLegend.left = m_rcLegend.right - GetMaxLegendLabelLength(dc) -
899 LEGEND_COLOR_BAR_WIDTH_PIXELS;
900 VERIFY(dc.Rectangle(m_rcLegend));
902 int skipped_row = -1; // if != -1, this is the row that we show the ... in
903 if (nShownAuthors < GetMaxSeriesSize())
904 skipped_row = nShownAuthors-2;
905 // Draw each group's label and bar.
906 for (int nGroup = 0; nGroup < nShownAuthors; ++nGroup) {
908 int nLabelTop(m_rcLegend.top + (nGroup * nLabelHeight) +
909 (GAP_PIXELS / 2));
911 int nShownGroup = nGroup; // introduce helper variable to avoid code duplication
913 // Do we have a skipped row?
914 if (skipped_row != -1)
916 if (nGroup == skipped_row) {
917 // draw the dots
918 VERIFY(dc.TextOut(m_rcLegend.left + GAP_PIXELS, nLabelTop, _T("...") ));
919 continue;
921 if (nGroup == nShownAuthors-1) {
922 // we show the last group instead of the scheduled group
923 nShownGroup = GetMaxSeriesSize()-1;
926 // Draw the label.
927 VERIFY(dc.TextOut(m_rcLegend.left + GAP_PIXELS, nLabelTop,
928 m_saLegendLabels.GetAt(nShownGroup)));
930 // Determine the bar.
931 CRect rcBar;
932 rcBar.left = m_rcLegend.left + GAP_PIXELS + GetMaxLegendLabelLength(dc) + GAP_PIXELS;
933 rcBar.top = nLabelTop + LEGEND_COLOR_BAR_GAP_PIXELS;
934 rcBar.right = m_rcLegend.right - GAP_PIXELS;
935 rcBar.bottom = rcBar.top + nLabelHeight - LEGEND_COLOR_BAR_GAP_PIXELS;
936 VERIFY(dc.Rectangle(rcBar));
938 // Draw bar for group.
939 COLORREF crBar(m_dwaColors.GetAt(nShownGroup));
940 CBrush br(crBar);
942 CBrush* pBrushOld = dc.SelectObject(&br);
943 ASSERT_VALID(pBrushOld);
945 rcBar.DeflateRect(LEGEND_COLOR_BAR_GAP_PIXELS, LEGEND_COLOR_BAR_GAP_PIXELS);
946 dc.FillRect(rcBar, &br);
948 dc.SelectObject(pBrushOld);
949 br.DeleteObject();
952 VERIFY(dc.SelectObject(pFontOld));
953 fontLegend.DeleteObject();
957 void MyGraph::DrawAxes(CDC& dc) const
959 VALIDATE;
960 ASSERT_VALID(&dc);
961 _ASSERTE(MyGraph::PieChart != m_eGraphType);
963 dc.SetTextColor(::GetSysColor(COLOR_WINDOWTEXT));
965 // Draw y axis.
966 dc.MoveTo(m_ptOrigin);
967 VERIFY(dc.LineTo(m_ptOrigin.x, m_ptOrigin.y - m_nYAxisHeight));
969 // Draw x axis.
970 dc.MoveTo(m_ptOrigin);
972 if (m_saLegendLabels.GetSize()) {
974 VERIFY(dc.LineTo(m_ptOrigin.x +
975 (m_nXAxisWidth - m_rcLegend.Width() - (GAP_PIXELS * 2)),
976 m_ptOrigin.y));
978 else {
979 VERIFY(dc.LineTo(m_ptOrigin.x + m_nXAxisWidth, m_ptOrigin.y));
982 // Note: m_nAxisLabelHeight and m_nAxisTickLabelHeight have been calculated in SetupAxis()
984 // Create the x-axis label font.
985 CFont fontXAxis;
986 VERIFY(fontXAxis.CreatePointFont(m_nAxisLabelHeight, _T("Arial"), &dc));
988 // Obtain the height of the font in device coordinates.
989 LOGFONT pLF;
990 VERIFY(fontXAxis.GetLogFont(&pLF));
991 int fontHeightDC = pLF.lfHeight;
993 // Create the y-axis label font.
994 CFont fontYAxis;
995 VERIFY(fontYAxis.CreateFont(
996 /* nHeight */ fontHeightDC,
997 /* nWidth */ 0,
998 /* nEscapement */ 90 * 10,
999 /* nOrientation */ 0,
1000 /* nWeight */ FW_DONTCARE,
1001 /* bItalic */ false,
1002 /* bUnderline */ false,
1003 /* cStrikeOut */ 0,
1004 ANSI_CHARSET,
1005 OUT_DEFAULT_PRECIS,
1006 CLIP_DEFAULT_PRECIS,
1007 PROOF_QUALITY,
1008 VARIABLE_PITCH | FF_DONTCARE,
1009 _T("Arial"))
1012 // Set the y-axis label font and draw the label.
1013 CFont* pFontOld = dc.SelectObject(&fontYAxis);
1014 ASSERT_VALID(pFontOld);
1015 CSize sizYLabel(dc.GetTextExtent(m_sYAxisLabel));
1016 VERIFY(dc.TextOut(GAP_PIXELS, (m_rcGraph.Height() + sizYLabel.cx) / 2,
1017 m_sYAxisLabel));
1019 // Set the x-axis label font and draw the label.
1020 VERIFY(dc.SelectObject(&fontXAxis));
1021 CSize sizXLabel(dc.GetTextExtent(m_sXAxisLabel));
1022 VERIFY(dc.TextOut(m_ptOrigin.x + (m_nXAxisWidth - sizXLabel.cx) / 2,
1023 m_rcGraph.bottom - GAP_PIXELS - sizXLabel.cy, m_sXAxisLabel));
1025 // chose suitable tick step (1, 2, 5, 10, 20, 50, etc.)
1026 int nMaxDataValue(GetMaxDataValue());
1027 nMaxDataValue = max(nMaxDataValue, 1);
1028 int nTickStep = 1;
1029 while (10 * nTickStep * Y_AXIS_TICK_COUNT_TARGET <= nMaxDataValue)
1030 nTickStep *= 10;
1032 if (5 * nTickStep * Y_AXIS_TICK_COUNT_TARGET <= nMaxDataValue)
1033 nTickStep *= 5;
1034 if (2 * nTickStep * Y_AXIS_TICK_COUNT_TARGET <= nMaxDataValue)
1035 nTickStep *= 2;
1037 // We hardwire TITLE_DIVISOR y-axis ticks here for simplicity.
1038 int nTickCount(nMaxDataValue / nTickStep);
1039 double tickSpace = (double)m_nYAxisHeight * nTickStep / (double)nMaxDataValue;
1041 // create tick label font and set it in the device context
1042 CFont fontTickLabels;
1043 VERIFY(fontTickLabels.CreatePointFont(m_nAxisTickLabelHeight, _T("Arial"), &dc));
1044 VERIFY(dc.SelectObject(&fontTickLabels));
1046 for (int nTick = 0; nTick < nTickCount; ++nTick)
1048 int nTickYLocation = static_cast<int>(m_ptOrigin.y - tickSpace * (nTick + 1) + 0.5);
1049 dc.MoveTo(m_ptOrigin.x - TICK_PIXELS, nTickYLocation);
1050 VERIFY(dc.LineTo(m_ptOrigin.x + TICK_PIXELS, nTickYLocation));
1052 // Draw tick label.
1053 CString sTickLabel;
1054 sTickLabel.Format(_T("%d"), nTickStep * (nTick+1));
1055 CSize sizTickLabel(dc.GetTextExtent(sTickLabel));
1057 VERIFY(dc.TextOut(m_ptOrigin.x - GAP_PIXELS - sizTickLabel.cx - TICK_PIXELS,
1058 nTickYLocation - sizTickLabel.cy/2, sTickLabel));
1061 // Draw X axis tick marks.
1062 POSITION pos(m_olMyGraphSeries.GetHeadPosition());
1063 int nSeries(0);
1065 while (pos) {
1067 MyGraphSeries* pSeries = m_olMyGraphSeries.GetNext(pos);
1068 ASSERT_VALID(pSeries);
1070 // Ignore unpopulated series if bar chart.
1071 if (m_eGraphType != MyGraph::Bar ||
1072 0 < pSeries->GetNonZeroElementCount()) {
1074 // Get the spacing of the series.
1075 int nSeriesSpace(0);
1077 if (m_saLegendLabels.GetSize()) {
1079 nSeriesSpace =
1080 (m_nXAxisWidth - m_rcLegend.Width() - (GAP_PIXELS * 2)) /
1081 (m_eGraphType == MyGraph::Bar ?
1082 GetNonZeroSeriesCount() : (int)m_olMyGraphSeries.GetCount());
1084 else {
1085 nSeriesSpace = m_nXAxisWidth / (m_eGraphType == MyGraph::Bar ?
1086 GetNonZeroSeriesCount() : (int)m_olMyGraphSeries.GetCount());
1089 int nTickXLocation(m_ptOrigin.x + ((nSeries + 1) * nSeriesSpace) -
1090 (nSeriesSpace / 2));
1092 dc.MoveTo(nTickXLocation, m_ptOrigin.y - TICK_PIXELS);
1093 VERIFY(dc.LineTo(nTickXLocation, m_ptOrigin.y + TICK_PIXELS));
1095 // Draw x-axis tick label.
1096 CString sTickLabel(pSeries->GetLabel());
1097 CSize sizTickLabel(dc.GetTextExtent(sTickLabel));
1099 VERIFY(dc.TextOut(nTickXLocation - (sizTickLabel.cx / 2),
1100 m_ptOrigin.y + TICK_PIXELS + GAP_PIXELS, sTickLabel));
1102 ++nSeries;
1106 VERIFY(dc.SelectObject(pFontOld));
1107 fontXAxis.DeleteObject();
1108 fontYAxis.DeleteObject();
1109 fontTickLabels.DeleteObject();
1113 void MyGraph::DrawSeriesBar(CDC& dc) const
1115 VALIDATE;
1116 ASSERT_VALID(&dc);
1118 // How much space does each series get (includes inter series space)?
1119 // We ignore series whose members are all zero.
1120 double availableSpace = m_saLegendLabels.GetSize()
1121 ? m_nXAxisWidth - m_rcLegend.Width() - (GAP_PIXELS * 2)
1122 : m_nXAxisWidth;
1124 double seriesSpace = availableSpace / (double)GetNonZeroSeriesCount();
1126 // Determine width of bars. Data points with a value of zero are assumed
1127 // to be empty. This is a bad assumption.
1128 double barWidth(0.0);
1130 // This is the width of the largest series (no inter series space).
1131 double maxSeriesPlotSize(0.0);
1133 if(!m_bStackedGraph){
1134 int seriessize = GetMaxNonZeroSeriesSize();
1135 barWidth = seriessize ? seriesSpace / seriessize : 0;
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 double(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;