OSDN Git Service

Bump revision to 2.16.32+-jp-2
[winmerge-jp/winmerge-jp.git] / Src / LocationView.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 //    WinMerge: An interactive diff/merge utility
3 //    Copyright (C) 1997 Dean P. Grimm
4 //    SPDX-License-Identifier: GPL-2.0-or-later
5 /////////////////////////////////////////////////////////////////////////////
6
7 /** 
8  * @file  LocationView.cpp
9  *
10  * @brief Implementation file for CLocationView
11  *
12  */
13
14
15 #include "StdAfx.h"
16 #include "LocationView.h"
17 #include <vector>
18 #include "Merge.h"
19 #include "OptionsMgr.h"
20 #include "MergeEditView.h"
21 #include "MergeDoc.h"
22 #include "BCMenu.h"
23 #include "OptionsDef.h"
24 #include "Bitmap.h"
25 #include "memdc.h"
26 #include "SyntaxColors.h"
27
28 #ifdef _DEBUG
29 #define new DEBUG_NEW
30 #endif
31
32 using std::vector;
33
34 /** @brief Size of empty frame above and below bars (in pixels). */
35 static const int Y_OFFSET = 5;
36 /** @brief Max pixels in view per line in file. */
37 static const double MAX_LINEPIX = 4.0;
38 /** @brief Top of difference marker, relative to difference start. */
39 static const int DIFFMARKER_TOP = 3;
40 /** @brief Bottom of difference marker, relative to difference start. */
41 static const int DIFFMARKER_BOTTOM = 3;
42 /** @brief Width of difference marker. */
43 static const int DIFFMARKER_WIDTH = 6;
44 /** @brief Minimum height of the visible area indicator */
45 static const int INDICATOR_MIN_HEIGHT = 2;
46
47 /** 
48  * @brief Bars in location pane
49  */
50 enum LOCBAR_TYPE
51 {
52         BAR_NONE = -1,  /**< No bar in given coords */
53         BAR_0,                  /**< first bar in given coords */
54         BAR_1,                  /**< second bar in given coords */
55         BAR_2,                  /**< third side bar in given coords */
56         BAR_YAREA,              /**< Y-Coord in bar area */
57 };
58
59 /////////////////////////////////////////////////////////////////////////////
60 // CLocationView
61
62 IMPLEMENT_DYNCREATE(CLocationView, CView)
63
64
65 CLocationView::CLocationView()
66         : m_visibleTop(-1)
67         , m_visibleBottom(-1)
68 //      MOVEDLINE_LIST m_movedLines; //*< List of moved block connecting lines */
69         , m_hwndFrame(nullptr)
70         , m_pSavedBackgroundBitmap(nullptr)
71         , m_bDrawn(false)
72         , m_bRecalculateBlocks(true) // calculate for the first time
73 {
74         // NB: set m_bIgnoreTrivials to false to see trivial diffs in the LocationView
75         // There is no GUI to do this
76
77         SetConnectMovedBlocks(GetOptionsMgr()->GetBool(OPT_CMP_MOVED_BLOCKS));
78
79         std::fill_n(m_nSubLineCount, std::size(m_nSubLineCount), 0);
80 }
81
82 CLocationView::~CLocationView()
83 {
84 }
85
86 BEGIN_MESSAGE_MAP(CLocationView, CView)
87         //{{AFX_MSG_MAP(CLocationView)
88         ON_WM_LBUTTONDOWN()
89         ON_WM_LBUTTONUP()
90         ON_WM_MOUSEMOVE()
91         ON_WM_MOUSEACTIVATE()
92         ON_WM_MOUSEWHEEL()
93         ON_WM_LBUTTONDBLCLK()
94         ON_WM_CONTEXTMENU()
95         ON_WM_CLOSE()
96         ON_WM_SIZE()
97         ON_WM_VSCROLL()
98         ON_WM_ERASEBKGND()
99         //}}AFX_MSG_MAP
100 END_MESSAGE_MAP()
101
102
103 void CLocationView::SetConnectMovedBlocks(bool displayMovedBlocks) 
104 {
105         if (m_displayMovedBlocks == displayMovedBlocks)
106                 return;
107
108         m_displayMovedBlocks = displayMovedBlocks;
109         if (this->GetSafeHwnd() != nullptr)
110                 if (IsWindowVisible())
111                         Invalidate();
112 }
113
114 /////////////////////////////////////////////////////////////////////////////
115 // CLocationView diagnostics
116 #ifdef _DEBUG
117 CMergeDoc* CLocationView::GetDocument() // non-debug version is inline
118 {
119         ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CMergeDoc)));
120         return (CMergeDoc*)m_pDocument;
121 }
122 #endif //_DEBUG
123
124 /////////////////////////////////////////////////////////////////////////////
125 // CLocationView message handlers
126
127 /**
128  * @brief Force recalculation and update of location pane.
129  * This method forces location pane to first recalculate its data and
130  * then repaint itself. This method bypasses location pane's caching
131  * of the diff data.
132  */
133 void CLocationView::ForceRecalculate()
134 {
135         m_bRecalculateBlocks = true;
136         Invalidate();
137 }
138
139 /** 
140  * @brief Update view.
141  */
142 void CLocationView::OnUpdate( CView* pSender, LPARAM lHint, CObject* pHint )
143 {
144         UNREFERENCED_PARAMETER(pSender);
145         UNREFERENCED_PARAMETER(lHint);
146
147         m_bRecalculateBlocks = true;
148         Invalidate();
149 }
150
151 /** 
152  * @brief Override for CMemDC to work.
153  */
154 BOOL CLocationView::OnEraseBkgnd(CDC* pDC)
155 {
156         return FALSE;
157 }
158
159 static bool IsColorDark(COLORREF clrBackground)
160 {
161         return !(GetRValue(clrBackground) >= 0x80 || GetGValue(clrBackground) >= 0x80 || GetBValue(clrBackground) >= 0x80);
162
163 }
164
165 COLORREF CLocationView::GetBackgroundColor()
166 {
167         COLORREF clrBackground = GetDocument()->GetView(0, 0)->GetColor(COLORINDEX_WHITESPACE);
168         if (!IsColorDark(clrBackground))
169         {
170                 return RGB(
171                         (std::max)(GetRValue(clrBackground) - 24, 0),
172                         (std::max)(GetGValue(clrBackground) - 24, 0),
173                         (std::max)(GetBValue(clrBackground) - 12, 0));
174         }
175         return RGB(
176                 (std::min)(GetRValue(clrBackground) + 20, 255),
177                 (std::min)(GetGValue(clrBackground) + 20, 255),
178                 (std::min)(GetBValue(clrBackground) + 32, 255));
179 }
180
181 /**
182  * @brief Draw custom (non-white) background.
183  * @param [in] pDC Pointer to draw context.
184  */
185 void CLocationView::DrawBackground(CDC* pDC)
186 {
187         // Set brush to desired background color
188         CBrush backBrush(GetBackgroundColor());
189         
190         // Save old brush
191         CBrush* pOldBrush = pDC->SelectObject(&backBrush);
192         
193         CRect rect;
194         pDC->GetClipBox(&rect);     // Erase the area needed
195         
196         pDC->PatBlt(rect.left, rect.top, rect.Width(), rect.Height(), PATCOPY);
197
198         pDC->SelectObject(pOldBrush);
199 }
200
201 /**
202  * @brief Calculate bar coordinates and scaling factors.
203  */
204 void CLocationView::CalculateBars()
205 {
206         CMergeDoc *pDoc = GetDocument();
207         CRect rc;
208         GetClientRect(rc);
209         const int w = rc.Width() / (pDoc->m_nBuffers * 2);
210         const int margin = (rc.Width() - w * pDoc->m_nBuffers) / (pDoc->m_nBuffers + 1);
211         int pane;
212         for (pane = 0; pane < pDoc->m_nBuffers; pane++)
213         {
214                 m_bar[pane].left = pane * (w + margin) + margin;
215                 m_bar[pane].right = m_bar[pane].left + w;
216         }       const double hTotal = rc.Height() - (2 * Y_OFFSET); // Height of draw area
217         int nbLines = 0;
218         pDoc->ForEachActiveGroupView([&](auto& pView) {
219                 nbLines = max(nbLines, pView->GetSubLineCount());
220         });
221
222         m_lineInPix = hTotal / nbLines;
223         m_pixInLines = nbLines / hTotal;
224         if (m_lineInPix > MAX_LINEPIX)
225         {
226                 m_lineInPix = MAX_LINEPIX;
227                 m_pixInLines = 1 / MAX_LINEPIX;
228         }
229
230         for (pane = 0; pane < pDoc->m_nBuffers; pane++)
231         {
232                 m_bar[pane].top = Y_OFFSET - 1;
233                 m_bar[pane].bottom = (LONG)(m_lineInPix * nbLines + Y_OFFSET + 1);
234         }
235 }
236
237 /**
238  * @brief Calculate difference lines and coordinates.
239  * This function calculates begin- and end-lines of differences when word-wrap
240  * is enabled. Otherwise the value from original difflist is used. Line
241  * numbers are also converted to coordinates in the window. All calculated
242  * (and not ignored) differences are added to the new list.
243  */
244 void CLocationView::CalculateBlocks()
245 {
246         // lineposition in pixels.
247         int nBeginY;
248         int nEndY;
249
250         m_diffBlocks.clear();
251
252         CMergeDoc *pDoc = GetDocument();
253         const int nDiffs = pDoc->m_diffList.GetSize();
254         if (nDiffs > 0)
255                 m_diffBlocks.reserve(nDiffs); // Pre-allocate space for the list.
256
257         int nGroup = pDoc->GetActiveMergeView()->m_nThisGroup;
258         int nLineCount = pDoc->GetView(nGroup, 0)->GetLineCount();
259         int nDiff = pDoc->m_diffList.FirstSignificantDiff();
260         while (nDiff != -1)
261         {
262                 DIFFRANGE diff;
263                 VERIFY(pDoc->m_diffList.GetDiff(nDiff, diff));
264
265                 CMergeEditView *pView = pDoc->GetView(nGroup, 0);
266
267                 DiffBlock block;
268                 int i, nBlocks = 0;
269                 int bs[4] = {0};
270                 int minY = INT_MAX, maxY = -1;
271
272                 bs[nBlocks++] = diff.dbegin;
273                 for (i = 0; i < pDoc->m_nBuffers; i++)
274                 {
275                         if (diff.blank[i] >= 0)
276                         {
277                                 if (minY > diff.blank[i])
278                                         minY = diff.blank[i];
279                                 if (maxY < diff.blank[i])
280                                         maxY = diff.blank[i];
281                         }
282                 }
283                 if (minY == maxY)
284                 {
285                         bs[nBlocks++] = minY;
286                 }
287                 else if (maxY != -1)
288                 {
289                         bs[nBlocks++] = minY;
290                         bs[nBlocks++] = maxY;
291                 }
292                 bs[nBlocks] = diff.dend + 1;
293                 if (bs[nBlocks] >= nLineCount)
294                         bs[nBlocks] = nLineCount - 1;
295
296                 for (i = 0; i < nBlocks; i++)
297                 {
298                         CalculateBlocksPixel(
299                                 pView->GetSubLineIndex(bs[i]),
300                                 pView->GetSubLineIndex(bs[i + 1]),
301                                 pView->GetSubLines(bs[i + 1]), nBeginY, nEndY);
302
303                         block.top_line = bs[i];
304                         block.bottom_line = bs[i + 1];
305                         block.top_coord = nBeginY;
306                         block.bottom_coord = nEndY;
307                         block.diff_index = nDiff;
308                         block.op = diff.op;
309                         m_diffBlocks.push_back(block);
310                 }
311
312                 nDiff = pDoc->m_diffList.NextSignificantDiff(nDiff);
313         }
314         m_bRecalculateBlocks = false;
315 }
316
317 /**
318  * @brief Calculate Blocksize to pixel.
319  * @param [in] nBlockStart line where block starts
320  * @param [in] nBlockEnd   line where block ends 
321  * @param [in] nBlockLength length of the block
322  * @param [in,out] nBeginY pixel in y  where block starts
323  * @param [in,out] nEndY   pixel in y  where block ends
324
325  */
326 void CLocationView::CalculateBlocksPixel(int nBlockStart, int nBlockEnd,
327                 int nBlockLength, int &nBeginY, int &nEndY)
328 {
329         // Count how many line does the diff block have.
330         const int nBlockHeight = nBlockEnd - nBlockStart + nBlockLength;
331
332         // Convert diff block size from lines to pixels.
333         nBeginY = (int)(nBlockStart * m_lineInPix + Y_OFFSET);
334         nEndY = (int)((nBlockStart + nBlockHeight) * m_lineInPix + Y_OFFSET);
335 }
336
337 /** 
338  * @brief Draw maps of files.
339  *
340  * Draws maps of differences in files. Difference list is walked and
341  * every difference is drawn with same colors as in editview.
342  * @note We MUST use doubles when calculating coords to avoid rounding
343  * to integers. Rounding causes miscalculation of coords.
344  * @sa CLocationView::DrawRect()
345  */
346 void CLocationView::OnDraw(CDC* pDC)
347 {
348         CMergeDoc *pDoc = GetDocument();
349         int nGroup = pDoc->GetActiveMergeView()->m_nThisGroup;
350         if (pDoc->GetView(nGroup, 0) == nullptr)
351                 return;
352
353         if (!pDoc->GetView(nGroup, 0)->IsInitialized()) return;
354
355         bool bEditedAfterRescan = false;
356         int nPaneNotModified = -1;
357         for (int pane = 0; pane < pDoc->m_nBuffers; pane++)
358         {
359                 if (!pDoc->IsEditedAfterRescan(pane))
360                         nPaneNotModified = pane;
361                 else
362                         bEditedAfterRescan = true;
363         }
364
365         CRect rc;
366         GetClientRect(&rc);
367
368         CMyMemDC dc(pDC, &rc);
369
370         CEColor cr[3] = {CLR_NONE, CLR_NONE, CLR_NONE};
371         CEColor crt = CLR_NONE; // Text color
372         bool bwh = false;
373
374         m_movedLines.RemoveAll();
375
376         CalculateBars();
377         DrawBackground(&dc);
378
379         COLORREF clrFace    = GetBackgroundColor();
380         COLORREF clrShadow  = GetSysColor(COLOR_BTNSHADOW);
381         COLORREF clrShadow2 = CEColor::GetIntermediateColor(clrFace, clrShadow, 0.9f);
382         COLORREF clrShadow3 = CEColor::GetIntermediateColor(clrFace, clrShadow2, 0.5f);
383         COLORREF clrShadow4 = CEColor::GetIntermediateColor(clrFace, clrShadow3, 0.5f);
384         COLORREF clrShadow5 = CEColor::GetIntermediateColor(clrFace, clrShadow4, 0.5f);
385
386         // Draw bar outlines
387         CPen* oldObj = (CPen*)dc.SelectStockObject(NULL_PEN);
388         CBrush brush(pDoc->GetView(nGroup, 0)->GetColor(COLORINDEX_WHITESPACE));
389         CBrush* oldBrush = (CBrush*)dc.SelectObject(&brush);
390         for (int pane = 0; pane < pDoc->m_nBuffers; pane++)
391         {
392                 CBrush *pOldBrush = nullptr;
393                 if (pDoc->IsEditedAfterRescan(pane))
394                         pOldBrush = (CBrush *)dc.SelectStockObject(HOLLOW_BRUSH);
395                 dc.Rectangle(m_bar[pane]);
396                 if (pOldBrush != nullptr)
397                         dc.SelectObject(pOldBrush);
398
399                 CRect rect = m_bar[pane];
400                 rect.InflateRect(1, 1);
401                 dc.Draw3dRect(rect, clrShadow5, clrShadow4);
402                 rect.InflateRect(-1, -1);
403                 dc.Draw3dRect(rect, clrShadow3, clrShadow2);
404         }
405         dc.SelectObject(oldBrush);
406         dc.SelectObject(oldBrush);
407         dc.SelectObject(oldObj);
408
409         // Iterate the differences list and draw differences as colored blocks.
410
411         // Don't recalculate blocks if we earlier determined it is not needed
412         // This may save lots of processing
413         if (m_bRecalculateBlocks)
414                 CalculateBlocks();
415
416         unsigned nPrevEndY = static_cast<unsigned>(-1);
417         const unsigned nCurDiff = pDoc->GetCurrentDiff();
418         DIFFRANGE diCur;
419         if (nCurDiff != -1)
420                 pDoc->m_diffList.GetDiff(nCurDiff, diCur);
421
422         vector<DiffBlock>::const_iterator iter = m_diffBlocks.begin();
423         for (; iter != m_diffBlocks.end(); ++iter)
424         {
425                 if (nPaneNotModified == -1)
426                         continue;
427                 CMergeEditView *pView = pDoc->GetView(nGroup, nPaneNotModified);
428                 const bool bInsideDiff = (nCurDiff == (*iter).diff_index);
429
430                 if ((nPrevEndY != (*iter).bottom_coord) || bInsideDiff)
431                 {
432                         for (int pane = 0; pane < pDoc->m_nBuffers; pane++)
433                         {
434                                 if (pDoc->IsEditedAfterRescan(pane))
435                                         continue;
436                                 // Draw 3way-diff state
437                                 if (pDoc->m_nBuffers == 3 && pane < 2)
438                                 {
439                                         CRect r(m_bar[pane].right - 1, (*iter).top_coord, m_bar[pane + 1].left + 1, (*iter).bottom_coord);
440                                         if ((pane == 0 && (*iter).op == OP_3RDONLY) || (pane == 1 && (*iter).op == OP_1STONLY))
441                                                 DrawRect(&dc, r, RGB(255, 255, 127), false);
442                                         else if ((*iter).op == OP_2NDONLY)
443                                                 DrawRect(&dc, r, RGB(127, 255, 255), false);
444                                         else if ((*iter).op == OP_DIFF)
445                                                 DrawRect(&dc, r, RGB(255, 0, 0), false);
446                                 }
447                                 // Draw block
448                                 pDoc->GetView(0, pane)->GetLineColors2((*iter).top_line, 0, cr[pane], crt, bwh);
449                                 CRect r(m_bar[pane].left, (*iter).top_coord, m_bar[pane].right, (*iter).bottom_coord);
450                                 DrawRect(&dc, r, cr[pane], bInsideDiff);
451                         }
452                 }
453                 nPrevEndY = (*iter).bottom_coord;
454
455                 if (bEditedAfterRescan)
456                         continue;
457
458                 for (int pane = 0; pane < pDoc->m_nBuffers; pane++)
459                 {
460                         if (m_displayMovedBlocks && pane < 2)
461                         {
462                                 int apparent0 = (*iter).top_line;
463                                 int apparent1 = pDoc->RightLineInMovedBlock(pane, apparent0);
464                                 const int nBlockHeight = (*iter).bottom_line - (*iter).top_line + 1;
465                                 if (apparent1 != -1)
466                                 {
467                                         MovedLine line;
468
469                                         line.currentDiff = bInsideDiff || (nCurDiff != -1 && diCur.dbegin <= apparent1 && apparent1 <= diCur.dend);
470
471                                         apparent0 = pView->GetSubLineIndex(apparent0);
472                                         apparent1 = pView->GetSubLineIndex(apparent1);
473
474                                         int leftUpper = (int) (apparent0 * m_lineInPix + Y_OFFSET);
475                                         int leftLower = (int) ((nBlockHeight + apparent0) * m_lineInPix + Y_OFFSET - 1);
476                                         int rightUpper = (int) (apparent1 * m_lineInPix + Y_OFFSET);
477                                         int rightLower = (int) ((nBlockHeight + apparent1) * m_lineInPix + Y_OFFSET - 1);
478                                         line.ptLeftUpper.x = line.ptLeftLower.x = m_bar[pane].right - 1;
479                                         line.ptLeftUpper.y = leftUpper;
480                                         line.ptLeftLower.y = leftLower;
481                                         line.ptRightUpper.x = line.ptRightLower.x = m_bar[pane + 1].left;
482                                         line.ptRightUpper.y = rightUpper;
483                                         line.ptRightLower.y = rightLower;
484                                         line.apparent0 = apparent0;
485                                         line.apparent1 = apparent1;
486                                         line.blockHeight = nBlockHeight;
487                                         if (!m_movedLines.IsEmpty())
488                                         {
489                                                 MovedLine& movedLineTail = m_movedLines.GetTail();
490                                                 if (line.apparent0 - movedLineTail.blockHeight - 1 == movedLineTail.apparent0 &&
491                                                     line.apparent1 - movedLineTail.blockHeight - 1 == movedLineTail.apparent1)
492                                                 {
493                                                         line.ptLeftUpper = movedLineTail.ptLeftUpper;
494                                                         line.ptRightUpper = movedLineTail.ptRightUpper;
495                                                         line.apparent0 = movedLineTail.apparent0;
496                                                         line.apparent1 = movedLineTail.apparent1;
497                                                         line.blockHeight += movedLineTail.blockHeight;
498                                                         m_movedLines.RemoveTail();
499                                                 }
500                                         }
501                                         m_movedLines.AddTail(line);
502                                 }
503                         }
504                 }
505         }
506
507         if (m_displayMovedBlocks)
508                 DrawConnectLines(&dc);
509
510         m_pSavedBackgroundBitmap.reset(CopyRectToBitmap(&dc, rc));
511
512         // Since we have invalidated locationbar there is no previous
513         // arearect to remove
514         m_visibleTop = -1;
515         m_visibleBottom = -1;
516         DrawVisibleAreaRect(&dc);
517
518         m_bDrawn = true;
519 }
520
521 /** 
522  * @brief Draw one block of map.
523  * @param [in] pDC Draw context.
524  * @param [in] r Rectangle to draw.
525  * @param [in] cr Color for rectangle.
526  * @param [in] bSelected Is rectangle for selected difference?
527  */
528 void CLocationView::DrawRect(CDC* pDC, const CRect& r, COLORREF cr, bool bSelected /*= false*/)
529 {
530         // Draw only colored blocks
531         if (cr != CLR_NONE && cr != GetSysColor(COLOR_WINDOW))
532         {
533                 CRect drawRect(r);
534                 drawRect.DeflateRect(1, 0);
535
536                 // With long files and small difference areas rect may become 0-height.
537                 // Make sure all diffs are drawn at least one pixel height.
538                 if (drawRect.Height() < 1)
539                         ++drawRect.bottom;
540                 pDC->FillSolidRect(drawRect, cr);
541                 CRect drawRect2(drawRect.left, drawRect.top, drawRect.right, drawRect.top + 1);
542                 pDC->FillSolidRect(drawRect2, CEColor::GetDarkenColor(cr, 0.96f));
543                 CRect drawRect3(drawRect.left, drawRect.bottom - 1, drawRect.right, drawRect.bottom);
544                 pDC->FillSolidRect(drawRect3, CEColor::GetDarkenColor(cr, 0.91f));
545
546                 if (bSelected)
547                 {
548                         DrawDiffMarker(pDC, r.top);
549                 }
550         }
551 }
552
553 /**
554  * @brief Capture the mouse target.
555  */
556 void CLocationView::OnLButtonDown(UINT nFlags, CPoint point) 
557 {
558         SetCapture();
559
560         bool bShift = (GetKeyState(VK_SHIFT) & 0x8000) != 0;
561         if (!GotoLocation(point, false, !bShift))
562                 CView::OnLButtonDown(nFlags, point);
563 }
564
565 /**
566  * @brief Release the mouse target.
567  */
568 void CLocationView::OnLButtonUp(UINT nFlags, CPoint point) 
569 {
570         ReleaseCapture();
571
572         CView::OnLButtonUp(nFlags, point);
573 }
574
575 /**
576  * @brief Process drag action on a captured mouse.
577  *
578  * Reposition on every dragged movement.
579  * The Screen update stress will be similar to a mouse wheeling.:-)
580  */
581 void CLocationView::OnMouseMove(UINT nFlags, CPoint point) 
582 {
583         if (GetCapture() == this)
584         {
585                 CMergeDoc *pDoc = GetDocument();
586                 int nGroup = pDoc->GetActiveMergeView()->m_nThisGroup;
587
588                 // Don't go above bars.
589                 point.y = max(point.y, Y_OFFSET);
590
591                 // Vertical scroll handlers are range safe, so there is no need to
592                 // make sure value is valid and in range.
593                 int nSubLine = (int) (m_pixInLines * (point.y - Y_OFFSET));
594                 nSubLine -= pDoc->GetView(nGroup, 0)->GetScreenLines() / 2;
595                 if (nSubLine < 0)
596                         nSubLine = 0;
597
598                 // Just a random choose as both view share the same scroll bar.
599                 CWnd *pView = pDoc->GetView(nGroup, 0);
600
601                 SCROLLINFO si = { sizeof SCROLLINFO };
602                 si.fMask = SIF_POS;
603                 si.nPos = nSubLine;
604                 pView->SetScrollInfo(SB_VERT, &si);
605
606                 // The views are child windows of a splitter windows. Splitter window
607                 // doesn't accept scroll bar updates not send from scroll bar control.
608                 // So we need to update both views.
609                 int pane;
610                 int nBuffers = pDoc->m_nBuffers;
611                 for (pane = 0; pane < nBuffers; pane++)
612                         pDoc->GetView(nGroup, pane)->SendMessage(WM_VSCROLL, MAKEWPARAM(SB_THUMBPOSITION, 0), NULL);
613         }
614
615         CView::OnMouseMove(nFlags, point);
616 }
617
618 int  CLocationView::OnMouseActivate(CWnd* pDesktopWnd, UINT nHitTest, UINT message)
619 {
620         return MA_NOACTIVATE;
621 }
622
623 BOOL CLocationView::OnMouseWheel(UINT nFlags, short zDelta, CPoint pt)
624 {
625         CMergeEditView* pView = GetDocument()->GetActiveMergeView();
626         if (pView)
627                 return static_cast<BOOL>(pView->SendMessage(WM_MOUSEWHEEL,
628                         MAKEWPARAM(nFlags, zDelta), MAKELPARAM(pt.x, pt.y)));
629         return CView::OnMouseWheel(nFlags, zDelta, pt);
630 }
631
632 /**
633  * User left double-clicked mouse
634  * @todo We can give alternative action to a double clicking. 
635  */
636 void CLocationView::OnLButtonDblClk(UINT nFlags, CPoint point) 
637 {
638         bool bShift = (GetKeyState(VK_SHIFT) & 0x8000) != 0;
639         if (!GotoLocation(point, false, !bShift))
640                 CView::OnLButtonDblClk(nFlags, point);
641 }
642
643 /**
644  * @brief Scroll both views to point given.
645  *
646  * Scroll views to given line. There is two ways to scroll, based on
647  * view lines (ghost lines counted in) or on real lines (no ghost lines).
648  * In most cases view lines should be used as it avoids real line number
649  * calculation and is able to scroll to all lines - real line numbers
650  * cannot be used to scroll to ghost lines.
651  *
652  * @param [in] point Point to move to
653  * @param [in] bRealLine `true` if we want to scroll using real line num,
654  *                       `false` if view linenumbers are OK.
655  * @param [in] bMoveAnchor if true the anchor is moved to the point
656  * @return `true` if succeeds, `false` if point not inside bars.
657  */
658 bool CLocationView::GotoLocation(const CPoint& point, bool bRealLine /*= true*/, bool bMoveAnchor)
659 {
660         CRect rc;
661         GetClientRect(rc);
662         CMergeDoc* pDoc = GetDocument();
663
664         if (!pDoc->GetActiveMergeView())
665                 return false;
666
667         int line = -1;
668         int bar = IsInsideBar(rc, point);
669         if (bar == BAR_0 || bar == BAR_1 || bar == BAR_2)
670         {
671                 line = GetLineFromYPos(point.y, bar, bRealLine);
672         }
673         else if (bar == BAR_YAREA)
674         {
675                 // Outside bars, use left bar
676                 bar = BAR_0;
677                 line = GetLineFromYPos(point.y, bar, false);
678         }
679         else
680                 return false;
681
682         pDoc->GetActiveMergeGroupView(0)->GotoLine(line, bRealLine, bar, bMoveAnchor);
683         if (bar == BAR_0 || bar == BAR_1 || bar == BAR_2)
684                 pDoc->GetActiveMergeGroupView(bar)->SetFocus();
685
686         return true;
687 }
688
689 /**
690  * @brief Handle scroll events sent directly.
691  *
692  */
693 void CLocationView::OnVScroll(UINT nSBCode, UINT nPos, CScrollBar *pScrollBar)
694 {
695         if (pScrollBar == nullptr)
696         {
697                 // Scroll did not come frome a scroll bar
698                 // Send it to the right view instead
699           CMergeDoc *pDoc = GetDocument();
700                 pDoc->GetActiveMergeGroupView(pDoc->m_nBuffers - 1)->SendMessage(WM_VSCROLL,
701                         MAKELONG(nSBCode, nPos), (LPARAM)NULL);
702                 return;
703         }
704         CView::OnVScroll (nSBCode, nPos, pScrollBar);
705 }
706
707 /**
708  * Show context menu and handle user selection.
709  */
710 void CLocationView::OnContextMenu(CWnd* pWnd, CPoint point) 
711 {
712         if (point.x == -1 && point.y == -1)
713         {
714                 //keystroke invocation
715                 CRect rect;
716                 GetClientRect(rect);
717                 ClientToScreen(rect);
718
719                 point = rect.TopLeft();
720                 point.Offset(5, 5);
721         }
722
723         CRect rc;
724         CPoint pt = point;
725         GetClientRect(rc);
726         ScreenToClient(&pt);
727         BCMenu menu;
728         VERIFY(menu.LoadMenu(IDR_POPUP_LOCATIONBAR));
729         theApp.TranslateMenu(menu.m_hMenu);
730
731         BCMenu* pPopup = static_cast<BCMenu *>(menu.GetSubMenu(0));
732         ASSERT(pPopup != nullptr);
733
734         CCmdUI cmdUI;
735         cmdUI.m_pMenu = pPopup;
736         cmdUI.m_nIndexMax = cmdUI.m_pMenu->GetMenuItemCount();
737         for (cmdUI.m_nIndex = 0 ; cmdUI.m_nIndex < cmdUI.m_nIndexMax ; ++cmdUI.m_nIndex)
738         {
739                 cmdUI.m_nID = cmdUI.m_pMenu->GetMenuItemID(cmdUI.m_nIndex);
740                 switch (cmdUI.m_nID)
741                 {
742                 case ID_DISPLAY_MOVED_NONE:
743                         cmdUI.SetRadio(!m_displayMovedBlocks);
744                         break;
745                 case ID_DISPLAY_MOVED_ALL:
746                         cmdUI.SetRadio(m_displayMovedBlocks);
747                         break;
748                 }
749         }
750
751         String strItem;
752         String strNum;
753         int nLine = -1;
754         int bar = IsInsideBar(rc, pt);
755
756         // If cursor over bar, format string with linenumber, else disable item
757         if (bar != BAR_NONE)
758         {
759                 // If outside bar area use left bar
760                 if (bar == BAR_YAREA)
761                         bar = BAR_0;
762                 nLine = GetLineFromYPos(pt.y, bar);
763                 strNum = strutils::to_str(nLine + 1); // Show linenumber not lineindex
764         }
765         else
766                 pPopup->EnableMenuItem(ID_LOCBAR_GOTODIFF, MF_GRAYED);
767         strItem = strutils::format_string1(_("G&o to Line %1"), strNum);
768         pPopup->SetMenuText(ID_LOCBAR_GOTODIFF, strItem.c_str(), MF_BYCOMMAND);
769
770         // invoke context menu
771         // we don't want to use the main application handlers, so we use flags TPM_NONOTIFY | TPM_RETURNCMD
772         // and handle the command after TrackPopupMenu
773         int command = pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON | TPM_NONOTIFY  | TPM_RETURNCMD, point.x, point.y, AfxGetMainWnd());
774
775         CMergeDoc* pDoc = GetDocument();
776         switch (command)
777         {
778         case ID_LOCBAR_GOTODIFF:
779                 pDoc->GetActiveMergeGroupView(0)->GotoLine(nLine, true, bar);
780                 if (bar == BAR_0 || bar == BAR_1 || bar == BAR_2)
781                         pDoc->GetActiveMergeGroupView(bar)->SetFocus();
782                 break;
783         case ID_EDIT_WMGOTO:
784                 pDoc->GetActiveMergeGroupView(0)->WMGoto();
785                 break;
786         case ID_DISPLAY_MOVED_NONE:
787                 SetConnectMovedBlocks(false);
788                 pDoc->SetDetectMovedBlocks(false);
789                 break;
790         case ID_DISPLAY_MOVED_ALL:
791                 SetConnectMovedBlocks(true);
792                 pDoc->SetDetectMovedBlocks(true);
793                 break;
794         }
795 }
796
797 /** 
798  * @brief Calculates view/real line in file from given YCoord in bar.
799  * @param [in] nYCoord ycoord in pane
800  * @param [in] bar bar/file
801  * @param [in] bRealLine `true` if real line is returned, `false` for view line
802  * @return 0-based index of view/real line in file [0...lines-1]
803  */
804 int CLocationView::GetLineFromYPos(int nYCoord, int bar, bool bRealLine /*= true*/)
805 {
806         CMergeEditView *pView = GetDocument()->GetActiveMergeGroupView(bar);
807
808         int nSubLineIndex = (int) (m_pixInLines * (nYCoord - Y_OFFSET));
809
810         // Keep sub-line index in range.
811         if (nSubLineIndex < 0)
812         {
813                 nSubLineIndex = 0;
814         }
815         else if (nSubLineIndex >= pView->GetSubLineCount())
816         {
817                 nSubLineIndex = pView->GetSubLineCount() - 1;
818         }
819
820         // Find the real (not wrapped) line number from sub-line index.
821         int nLine = 0;
822         int nSubLine = 0;
823         pView->GetLineBySubLine(nSubLineIndex, nLine, nSubLine);
824
825         // Convert line number to line index.
826         if (nLine > 0)
827         {
828                 nLine -= 1;
829         }
830
831         // We've got a view line now
832         if (!bRealLine)
833                 return nLine;
834
835         // Get real line (exclude ghost lines)
836         CMergeDoc* pDoc = GetDocument();
837         const int nRealLine = pDoc->m_ptBuf[bar]->ComputeRealLine(nLine);
838         return nRealLine;
839 }
840
841 /** 
842  * @brief Determines if given coords are inside left/right bar.
843  * @param rc [in] size of locationpane client area
844  * @param pt [in] point we want to check, in client coordinates.
845  * @return LOCBAR_TYPE area where point is.
846  */
847 int CLocationView::IsInsideBar(const CRect& rc, const POINT& pt)
848 {
849         CMergeDoc *pDoc = GetDocument();
850         for (int pane = 0; pane < pDoc->m_nBuffers; pane++)
851         {
852                 if (m_bar[pane].PtInRect(pt))
853                         return BAR_0 + pane;
854         }
855         if (pt.y > m_bar[0].top && pt.y <= m_bar[0].bottom)
856                 return BAR_YAREA;
857         return BAR_NONE;
858 }
859
860 /** 
861  * @brief Draws rect indicating visible area in file views.
862  *
863  * @param [in] nTopLine New topline for indicator
864  * @param [in] nBottomLine New bottomline for indicator
865  * @todo This function dublicates too much DrawRect() code.
866  */
867 void CLocationView::DrawVisibleAreaRect(CDC *pClientDC, int nTopLine, int nBottomLine)
868 {
869         CMergeDoc* pDoc = GetDocument();
870         int nGroup = pDoc->GetActiveMergeView()->m_nThisGroup;
871         
872         if (nTopLine == -1)
873                 nTopLine = pDoc->GetView(nGroup, 0)->GetTopSubLine();
874         
875         if (nBottomLine == -1)
876         {
877                 const int nScreenLines = pDoc->GetView(nGroup, 1)->GetScreenLines();
878                 nBottomLine = nTopLine + nScreenLines;
879         }
880
881         CRect rc;
882         GetClientRect(rc);
883         int nbLines = INT_MAX;
884         pDoc->ForEachActiveGroupView([&](auto& pView) {
885                 nbLines = min(nbLines, pView->GetSubLineCount());
886         });
887
888         int nTopCoord = static_cast<int>(Y_OFFSET +
889                         (static_cast<double>(nTopLine * m_lineInPix)));
890         int nBottomCoord = static_cast<int>(Y_OFFSET +
891                         (static_cast<double>(nBottomLine * m_lineInPix)));
892         
893         double xbarBottom = min(nbLines / m_pixInLines + Y_OFFSET, rc.Height() - Y_OFFSET);
894         int barBottom = (int)xbarBottom;
895         // Make sure bottom coord is in bar range
896         nBottomCoord = min(nBottomCoord, barBottom);
897
898         // Ensure visible area is at least minimum height
899         if (nBottomCoord - nTopCoord < INDICATOR_MIN_HEIGHT)
900         {
901                 // If area is near top of file, add additional area to bottom
902                 // of the bar and vice versa.
903                 if (nTopCoord < Y_OFFSET + 20)
904                         nBottomCoord += INDICATOR_MIN_HEIGHT - (nBottomCoord - nTopCoord);
905                 else
906                 {
907                         // If we have a high number of lines, it may be better
908                         // to keep the topline, otherwise the cursor can 
909                         // jump up and down unexpected
910                         nBottomCoord = nTopCoord + INDICATOR_MIN_HEIGHT;
911                 }
912         }
913
914         // Store current values for later use (to check if area changes)
915         m_visibleTop = nTopCoord;
916         m_visibleBottom = nBottomCoord;
917
918         CRect rcVisibleArea(2, m_visibleTop, rc.right - 2, m_visibleBottom);
919         std::unique_ptr<CBitmap> pBitmap(CopyRectToBitmap(pClientDC, rcVisibleArea));
920         std::unique_ptr<CBitmap> pDarkenedBitmap(GetDarkenedBitmap(pClientDC, pBitmap.get(), IsColorDark(GetBackgroundColor())));
921         DrawBitmap(pClientDC, rcVisibleArea.left, rcVisibleArea.top, pDarkenedBitmap.get());
922 }
923
924 /**
925  * @brief Public function for updating visible area indicator.
926  *
927  * @param [in] nTopLine New topline for indicator
928  * @param [in] nBottomLine New bottomline for indicator
929  */
930 void CLocationView::UpdateVisiblePos(int nTopLine, int nBottomLine)
931 {
932         if (m_bDrawn)
933         {
934                 CMergeDoc *pDoc = GetDocument();
935                 int nGroup = pDoc->GetActiveMergeView()->m_nThisGroup;
936                 int pane = 0;
937                 if (std::all_of(m_nSubLineCount, m_nSubLineCount + pDoc->m_nBuffers,
938                         [&](int nSubLineCount) { return nSubLineCount == pDoc->GetView(nGroup, pane++)->GetSubLineCount(); }))
939                 {
940                         int nTopCoord = static_cast<int>(Y_OFFSET +
941                                         (static_cast<double>(nTopLine * m_lineInPix)));
942                         int nBottomCoord = static_cast<int>(Y_OFFSET +
943                                         (static_cast<double>(nBottomLine * m_lineInPix)));
944                         if (m_visibleTop != nTopCoord || m_visibleBottom != nBottomCoord)
945                         {
946                                 // Visible area was changed
947                                 if (m_pSavedBackgroundBitmap != nullptr)
948                                 {
949                                         CClientDC dc(this);
950                                         CMyMemDC dcMem(&dc);
951                                         // Clear previous visible rect
952                                         DrawBitmap(&dcMem, 0, 0, m_pSavedBackgroundBitmap.get());
953
954                                         DrawVisibleAreaRect(&dcMem, nTopLine, nBottomLine);
955                                 }
956                         }
957                 }
958                 else
959                 {
960                         InvalidateRect(nullptr);
961                         for (pane = 0; pane < pDoc->m_nBuffers; pane++)
962                                 m_nSubLineCount[pane] = pDoc->GetView(nGroup, pane)->GetSubLineCount();
963                 }
964         }
965 }
966
967 /**
968  * @brief Unset pointers to MergeEditView when location pane is closed.
969  */
970 void CLocationView::OnClose()
971 {
972         CView::OnClose();
973 }
974
975 /** 
976  * @brief Draw lines connecting moved blocks.
977  */
978 void CLocationView::DrawConnectLines(CDC *pClientDC)
979 {
980         COLORREF clrMovedBlock = GetOptionsMgr()->GetInt(OPT_CLR_MOVEDBLOCK);
981         COLORREF clrSelectedMovedBlock = GetOptionsMgr()->GetInt(OPT_CLR_SELECTED_MOVEDBLOCK);
982         CBrush brushMovedBlock(clrMovedBlock);
983         CBrush brushSelectedMovedBlock(clrSelectedMovedBlock);
984         CPen penMovedBlock(PS_SOLID, 0, clrMovedBlock);
985         CPen penSelectedMovedBlock(PS_SOLID, 0, clrSelectedMovedBlock);
986
987         POSITION pos = m_movedLines.GetHeadPosition();
988         int oldMode = pClientDC->SetPolyFillMode(ALTERNATE);
989
990         while (pos != nullptr)
991         {
992                 MovedLine line = m_movedLines.GetNext(pos);
993                 CPen *pOldPen = (CPen *)pClientDC->SelectObject(line.currentDiff ? &penSelectedMovedBlock : &penMovedBlock);
994                 if (line.ptLeftLower.y - line.ptLeftUpper.y <= 1)
995                 {
996                         CPoint points[4] = {
997                                 line.ptLeftUpper,
998                                 {(line.ptLeftUpper.x + line.ptRightUpper.x) / 2, line.ptLeftUpper.y},
999                                 {(line.ptLeftUpper.x + line.ptRightUpper.x) / 2, line.ptRightLower.y},
1000                                 line.ptRightUpper };
1001                         pClientDC->PolyBezier(points, 4);
1002                 }
1003                 else
1004                 {
1005                         BYTE types[9] = {
1006                                 PT_MOVETO, PT_BEZIERTO, PT_BEZIERTO, PT_BEZIERTO,
1007                                 PT_LINETO, PT_BEZIERTO, PT_BEZIERTO, PT_BEZIERTO, PT_LINETO };
1008                         CPoint points[9] = {
1009                                 line.ptLeftUpper,
1010                                 {(line.ptLeftUpper.x + line.ptRightUpper.x) / 2, line.ptLeftUpper.y},
1011                                 {(line.ptLeftUpper.x + line.ptRightUpper.x) / 2, line.ptRightUpper.y},
1012                                 line.ptRightUpper,
1013                                 line.ptRightLower,
1014                                 {(line.ptLeftLower.x + line.ptRightLower.x) / 2, line.ptRightLower.y},
1015                                 {(line.ptLeftLower.x + line.ptRightLower.x) / 2, line.ptLeftLower.y},
1016                                 line.ptLeftLower, line.ptLeftUpper };
1017                         pClientDC->BeginPath();
1018                         pClientDC->PolyDraw(points, types, 8);
1019                         pClientDC->EndPath();
1020                         CRgn rgn;
1021                         if (rgn.CreateFromPath(pClientDC))
1022                                 pClientDC->FillRgn(&rgn, line.currentDiff ? &brushSelectedMovedBlock : &brushMovedBlock);
1023                         pClientDC->PolyDraw(points, types, 9);
1024                 }
1025                 pClientDC->SelectObject(pOldPen);
1026         }
1027
1028         pClientDC->SetPolyFillMode(oldMode);
1029 }
1030
1031 /** 
1032  * @brief Request frame window to store sizes.
1033  *
1034  * When locationview size changes we want to save new size
1035  * for new windows. But we must do it through frame window.
1036  * @param [in] nType Type of resizing, SIZE_MAXIMIZED etc.
1037  * @param [in] cx New panel width.
1038  * @param [in] cy New panel height.
1039  */
1040 void CLocationView::OnSize(UINT nType, int cx, int cy) 
1041 {
1042         CView::OnSize(nType, cx, cy);
1043
1044         // Height change needs block recalculation
1045         // TODO: Perhaps this should be determined from need to change bar size?
1046         // And we could change bar sizes more lazily, not from every one pixel change in size?
1047         if (cy != m_currentSize.cy)
1048                 m_bRecalculateBlocks = true;
1049
1050         if (cx != m_currentSize.cx)
1051         {
1052                 if (m_hwndFrame != nullptr)
1053                         ::PostMessage(m_hwndFrame, MSG_STORE_PANESIZES, 0, 0);
1054         }
1055
1056         m_currentSize.cx = cx;
1057         m_currentSize.cy = cy;
1058 }
1059
1060 /** 
1061  * @brief Draw marker for top of currently selected difference.
1062  * This function draws marker for top of currently selected difference.
1063  * This marker makes it a lot easier to see where currently selected
1064  * difference is in location bar. Especially when selected diffence is
1065  * small and it is not easy to find it otherwise.
1066  * @param [in] pDC Pointer to draw context.
1067  * @param [in] yCoord Y-coord of top of difference, -1 if no difference.
1068  */
1069 void CLocationView::DrawDiffMarker(CDC* pDC, int yCoord)
1070 {
1071         int nBuffers = GetDocument()->m_nBuffers;
1072
1073         CPoint points[3];
1074         points[0].x = m_bar[0].left - DIFFMARKER_WIDTH - 1;
1075         points[0].y = yCoord - DIFFMARKER_TOP;
1076         points[1].x = m_bar[0].left - 1;
1077         points[1].y = yCoord;
1078         points[2].x = m_bar[0].left - DIFFMARKER_WIDTH - 1;
1079         points[2].y = yCoord + DIFFMARKER_BOTTOM;
1080
1081         COLORREF clrBlue = GetSysColor(COLOR_ACTIVECAPTION);
1082         CPen penDarkBlue(PS_SOLID, 0, CEColor::GetDarkenColor(clrBlue, 0.9f));
1083         CPen* oldObj = (CPen*)pDC->SelectObject(&penDarkBlue);
1084         CBrush brushBlue(clrBlue);
1085         CBrush* pOldBrush = pDC->SelectObject(&brushBlue);
1086
1087         pDC->SetPolyFillMode(WINDING);
1088         pDC->Polygon(points, 3);
1089
1090         points[0].x = m_bar[nBuffers - 1].right + 1 + DIFFMARKER_WIDTH;
1091         points[1].x = m_bar[nBuffers - 1].right + 1;
1092         points[2].x = m_bar[nBuffers - 1].right + 1 + DIFFMARKER_WIDTH;
1093         pDC->Polygon(points, 3);
1094
1095         pDC->SelectObject(pOldBrush);
1096         pDC->SelectObject(oldObj);
1097 }