OSDN Git Service

Fix osdn.net ticket #47553: Allow text to wrap in the Table Compare Window and unwrap...
[winmerge-jp/winmerge-jp.git] / Src / MergeEditView.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 //    WinMerge:  an interactive diff/merge utility
3 //    Copyright (C) 1997-2000  Thingamahoochie Software
4 //    Author: Dean Grimm
5 //    SPDX-License-Identifier: GPL-2.0-or-later
6 /////////////////////////////////////////////////////////////////////////////
7 /**
8  * @file  MergeEditView.cpp
9  *
10  * @brief Implementation of the CMergeEditView class
11  */
12
13 #include "StdAfx.h"
14 #include "MergeEditView.h"
15 #include <vector>
16 #include "BCMenu.h"
17 #include "Merge.h"
18 #include "LocationView.h"
19 #include "MergeDoc.h"
20 #include "MainFrm.h"
21 #include "OptionsMgr.h"
22 #include "OptionsDiffColors.h"
23 #include "WMGotoDlg.h"
24 #include "OptionsDef.h"
25 #include "SyntaxColors.h"
26 #include "MergeEditFrm.h"
27 #include "MergeLineFlags.h"
28 #include "paths.h"
29 #include "DropHandler.h"
30 #include "DirDoc.h"
31 #include "ShellContextMenu.h"
32 #include "editcmd.h"
33 #include "Shell.h"
34 #include "SelectPluginDlg.h"
35 #include "Constants.h"
36
37 #ifdef _DEBUG
38 #define new DEBUG_NEW
39 #endif
40
41 #ifndef WM_MOUSEHWHEEL
42 #  define WM_MOUSEHWHEEL 0x20e
43 #endif
44
45 using std::vector;
46 using CrystalLineParser::TEXTBLOCK;
47
48 /** @brief Timer ID for delayed rescan. */
49 const UINT IDT_RESCAN = 2;
50 /** @brief Timer timeout for delayed rescan. */
51 const UINT RESCAN_TIMEOUT = 1000;
52
53 /////////////////////////////////////////////////////////////////////////////
54 // CMergeEditView
55
56 IMPLEMENT_DYNCREATE(CMergeEditView, CCrystalEditViewEx)
57
58 CMergeEditView::CMergeEditView()
59 : m_bCurrentLineIsDiff(false)
60 , m_nThisPane(0)
61 , m_nThisGroup(0)
62 , m_bDetailView(false)
63 , m_piMergeEditStatus(nullptr)
64 , fTimerWaitingForIdle(0)
65 , m_lineBegin(0)
66 , m_lineEnd(-1)
67 {
68         SetParser(&m_xParser);
69         
70         Options::DiffColors::Load(GetOptionsMgr(), m_cachedColors);
71 }
72
73 CMergeEditView::~CMergeEditView()
74 {
75 }
76
77
78 BEGIN_MESSAGE_MAP(CMergeEditView, CCrystalEditViewEx)
79         //{{AFX_MSG_MAP(CMergeEditView)
80         ON_WM_CONTEXTMENU()
81         ON_WM_TIMER()
82         ON_WM_LBUTTONDBLCLK()
83         ON_WM_LBUTTONUP()
84         ON_WM_RBUTTONDOWN()
85         ON_WM_VSCROLL ()
86         ON_WM_HSCROLL ()
87         ON_WM_SIZE()
88         ON_WM_MOVE()
89         ON_WM_MOUSEWHEEL()
90         ON_WM_MOUSEHWHEEL()
91         // [File] menu
92         ON_COMMAND_RANGE(ID_EOL_TO_DOS, ID_EOL_TO_MAC, OnConvertEolTo)
93         ON_UPDATE_COMMAND_UI_RANGE(ID_EOL_TO_DOS, ID_EOL_TO_MAC, OnUpdateConvertEolTo)
94         // [Edit] menu
95         ON_COMMAND(ID_EDIT_COPY, OnEditCopy)
96         ON_UPDATE_COMMAND_UI(ID_EDIT_COPY, OnUpdateEditCopy)
97         ON_COMMAND(ID_EDIT_CUT, OnEditCut)
98         ON_UPDATE_COMMAND_UI(ID_EDIT_CUT, OnUpdateEditCut)
99         ON_COMMAND(ID_EDIT_PASTE, OnEditPaste)
100         ON_UPDATE_COMMAND_UI(ID_EDIT_PASTE, OnUpdateEditPaste)
101         ON_COMMAND(ID_EDIT_UNDO, OnEditUndo)
102         ON_UPDATE_COMMAND_UI(ID_EDIT_UNDO, OnUpdateEditUndo)
103         ON_COMMAND(ID_EDIT_REDO, OnEditRedo)
104         ON_UPDATE_COMMAND_UI(ID_EDIT_REDO, OnUpdateEditRedo)
105         ON_UPDATE_COMMAND_UI(ID_EDIT_REPLACE, OnUpdateEditReplace)
106         ON_COMMAND(ID_EDIT_WMGOTO, OnWMGoto)
107         ON_COMMAND(ID_EDIT_COPY_LINENUMBERS, OnEditCopyLineNumbers)
108         ON_UPDATE_COMMAND_UI(ID_EDIT_COPY_LINENUMBERS, OnUpdateEditCopyLinenumbers)
109         // [View] menu
110         ON_COMMAND(ID_SELECTLINEDIFF, OnSelectLineDiff<false>)
111         ON_UPDATE_COMMAND_UI(ID_SELECTLINEDIFF, OnUpdateSelectLineDiff)
112         ON_COMMAND(ID_SELECTPREVLINEDIFF, OnSelectLineDiff<true>)
113         ON_UPDATE_COMMAND_UI(ID_SELECTPREVLINEDIFF, OnUpdateSelectLineDiff)
114         ON_COMMAND(ID_VIEW_LINEDIFFS, OnViewLineDiffs)
115         ON_UPDATE_COMMAND_UI(ID_VIEW_LINEDIFFS, OnUpdateViewLineDiffs)
116         ON_COMMAND(ID_VIEW_WORDWRAP, OnViewWordWrap)
117         ON_UPDATE_COMMAND_UI(ID_VIEW_WORDWRAP, OnUpdateViewWordWrap)
118         ON_COMMAND(ID_VIEW_LINENUMBERS, OnViewLineNumbers)
119         ON_UPDATE_COMMAND_UI(ID_VIEW_LINENUMBERS, OnUpdateViewLineNumbers)
120         ON_COMMAND(ID_VIEW_WHITESPACE, OnViewWhitespace)
121         ON_UPDATE_COMMAND_UI(ID_VIEW_WHITESPACE, OnUpdateViewWhitespace)
122         ON_COMMAND(ID_VIEW_EOL, OnViewEOL)
123         ON_UPDATE_COMMAND_UI(ID_VIEW_EOL, OnUpdateViewEOL)
124         ON_COMMAND(ID_VIEW_SELMARGIN, OnViewMargin)
125         ON_UPDATE_COMMAND_UI(ID_VIEW_SELMARGIN, OnUpdateViewMargin)
126         ON_COMMAND(ID_VIEW_TOPMARGIN, OnViewTopMargin)
127         ON_UPDATE_COMMAND_UI(ID_VIEW_TOPMARGIN, OnUpdateViewTopMargin)
128         ON_UPDATE_COMMAND_UI(ID_VIEW_CHANGESCHEME, OnUpdateViewChangeScheme)
129         ON_COMMAND_RANGE(ID_COLORSCHEME_FIRST, ID_COLORSCHEME_LAST, OnChangeScheme)
130         ON_UPDATE_COMMAND_UI_RANGE(ID_COLORSCHEME_FIRST, ID_COLORSCHEME_LAST, OnUpdateChangeScheme)
131         ON_COMMAND(ID_VIEW_ZOOMIN, OnViewZoomIn)
132         ON_COMMAND(ID_VIEW_ZOOMOUT, OnViewZoomOut)
133         ON_COMMAND(ID_VIEW_ZOOMNORMAL, OnViewZoomNormal)
134         // [Merge] menu
135         ON_COMMAND(ID_CURDIFF, OnCurdiff)
136         ON_UPDATE_COMMAND_UI(ID_CURDIFF, OnUpdateCurdiff)
137         ON_COMMAND(ID_FIRSTDIFF, OnFirstdiff)
138         ON_UPDATE_COMMAND_UI(ID_FIRSTDIFF, OnUpdateFirstdiff)
139         ON_COMMAND(ID_LASTDIFF, OnLastdiff)
140         ON_UPDATE_COMMAND_UI(ID_LASTDIFF, OnUpdateLastdiff)
141         ON_COMMAND(ID_NEXTDIFF, OnNextdiff)
142         ON_UPDATE_COMMAND_UI(ID_NEXTDIFF, OnUpdateNextdiff)
143         ON_COMMAND(ID_PREVDIFF, OnPrevdiff)
144         ON_UPDATE_COMMAND_UI(ID_PREVDIFF, OnUpdatePrevdiff)
145         ON_COMMAND(ID_NEXTCONFLICT, OnNextConflict)
146         ON_UPDATE_COMMAND_UI(ID_NEXTCONFLICT, OnUpdateNextConflict)
147         ON_COMMAND(ID_PREVCONFLICT, OnPrevConflict)
148         ON_UPDATE_COMMAND_UI(ID_PREVCONFLICT, OnUpdatePrevConflict)
149         ON_COMMAND(ID_NEXTDIFFLM, OnNextdiffLM)
150         ON_UPDATE_COMMAND_UI(ID_NEXTDIFFLM, OnUpdateNextdiffLM)
151         ON_COMMAND(ID_PREVDIFFLM, OnPrevdiffLM)
152         ON_UPDATE_COMMAND_UI(ID_PREVDIFFLM, OnUpdatePrevdiffLM)
153         ON_COMMAND(ID_NEXTDIFFLR, OnNextdiffLR)
154         ON_UPDATE_COMMAND_UI(ID_NEXTDIFFLR, OnUpdateNextdiffLR)
155         ON_COMMAND(ID_PREVDIFFLR, OnPrevdiffLR)
156         ON_UPDATE_COMMAND_UI(ID_PREVDIFFLR, OnUpdatePrevdiffLR)
157         ON_COMMAND(ID_NEXTDIFFMR, OnNextdiffMR)
158         ON_UPDATE_COMMAND_UI(ID_NEXTDIFFMR, OnUpdateNextdiffMR)
159         ON_COMMAND(ID_PREVDIFFMR, OnPrevdiffMR)
160         ON_UPDATE_COMMAND_UI(ID_PREVDIFFMR, OnUpdatePrevdiffMR)
161         ON_COMMAND(ID_NEXTDIFFLO, OnNextdiffLO)
162         ON_UPDATE_COMMAND_UI(ID_NEXTDIFFLO, OnUpdateNextdiffLO)
163         ON_COMMAND(ID_PREVDIFFLO, OnPrevdiffLO)
164         ON_UPDATE_COMMAND_UI(ID_PREVDIFFLO, OnUpdatePrevdiffLO)
165         ON_COMMAND(ID_NEXTDIFFMO, OnNextdiffMO)
166         ON_UPDATE_COMMAND_UI(ID_NEXTDIFFMO, OnUpdateNextdiffMO)
167         ON_COMMAND(ID_PREVDIFFMO, OnPrevdiffMO)
168         ON_UPDATE_COMMAND_UI(ID_PREVDIFFMO, OnUpdatePrevdiffMO)
169         ON_COMMAND(ID_NEXTDIFFRO, OnNextdiffRO)
170         ON_UPDATE_COMMAND_UI(ID_NEXTDIFFRO, OnUpdateNextdiffRO)
171         ON_COMMAND(ID_PREVDIFFRO, OnPrevdiffRO)
172         ON_UPDATE_COMMAND_UI(ID_PREVDIFFRO, OnUpdatePrevdiffRO)
173         ON_COMMAND(ID_ALL_LEFT, OnAllLeft)
174         ON_UPDATE_COMMAND_UI(ID_ALL_LEFT, OnUpdateAllLeft)
175         ON_COMMAND(ID_ALL_RIGHT, OnAllRight)
176         ON_UPDATE_COMMAND_UI(ID_ALL_RIGHT, OnUpdateAllRight)
177         ON_COMMAND(ID_AUTO_MERGE, OnAutoMerge)
178         ON_UPDATE_COMMAND_UI(ID_AUTO_MERGE, OnUpdateAutoMerge)
179         ON_COMMAND(ID_L2R, OnL2r)
180         ON_UPDATE_COMMAND_UI(ID_L2R, OnUpdateL2r)
181         ON_COMMAND(ID_LINES_L2R, OnLinesL2r)
182         ON_UPDATE_COMMAND_UI(ID_LINES_L2R, OnUpdateLinesL2r)
183         ON_COMMAND(ID_R2L, OnR2l)
184         ON_UPDATE_COMMAND_UI(ID_R2L, OnUpdateR2l)
185         ON_COMMAND(ID_LINES_R2L, OnLinesR2l)
186         ON_UPDATE_COMMAND_UI(ID_LINES_R2L, OnUpdateLinesR2l)
187         ON_COMMAND(ID_COPY_FROM_LEFT, OnCopyFromLeft)
188         ON_UPDATE_COMMAND_UI(ID_COPY_FROM_LEFT, OnUpdateCopyFromLeft)
189         ON_COMMAND(ID_COPY_LINES_FROM_LEFT, OnCopyLinesFromLeft)
190         ON_UPDATE_COMMAND_UI(ID_COPY_LINES_FROM_LEFT, OnUpdateCopyLinesFromLeft)
191         ON_COMMAND(ID_COPY_FROM_RIGHT, OnCopyFromRight)
192         ON_UPDATE_COMMAND_UI(ID_COPY_FROM_RIGHT, OnUpdateCopyFromRight)
193         ON_COMMAND(ID_COPY_LINES_FROM_RIGHT, OnCopyLinesFromRight)
194         ON_UPDATE_COMMAND_UI(ID_COPY_LINES_FROM_RIGHT, OnUpdateCopyLinesFromRight)
195         ON_COMMAND(ID_L2RNEXT, OnL2RNext)
196         ON_UPDATE_COMMAND_UI(ID_L2RNEXT, OnUpdateL2RNext)
197         ON_COMMAND(ID_R2LNEXT, OnR2LNext)
198         ON_UPDATE_COMMAND_UI(ID_R2LNEXT, OnUpdateR2LNext)
199         ON_COMMAND(ID_ADD_SYNCPOINT, OnAddSyncPoint)
200         ON_COMMAND(ID_CLEAR_SYNCPOINTS, OnClearSyncPoints)
201         ON_UPDATE_COMMAND_UI(ID_CLEAR_SYNCPOINTS, OnUpdateClearSyncPoints)
202         ON_COMMAND_RANGE(ID_COPY_TO_MIDDLE_L, ID_COPY_FROM_LEFT_R, OnCopyX2Y)
203         ON_UPDATE_COMMAND_UI_RANGE(ID_COPY_TO_MIDDLE_L, ID_COPY_FROM_LEFT_R, OnUpdateX2Y)
204         ON_COMMAND_RANGE(ID_COPY_LINES_TO_MIDDLE_L, ID_COPY_LINES_FROM_LEFT_R, OnCopyLinesX2Y)
205         ON_UPDATE_COMMAND_UI_RANGE(ID_COPY_LINES_TO_MIDDLE_L, ID_COPY_LINES_FROM_LEFT_R, OnUpdateX2Y)
206         // [Plugins] menu
207         ON_COMMAND_RANGE(ID_SCRIPT_FIRST, ID_SCRIPT_LAST, OnScripts)
208         ON_COMMAND(ID_TRANSFORM_WITH_SCRIPT, OnTransformWithScript)
209         // [Window] menu
210         ON_COMMAND_RANGE(ID_NEXT_PANE, ID_PREV_PANE, OnChangePane)
211         ON_COMMAND(ID_WINDOW_SPLIT, OnWindowSplit)
212         ON_UPDATE_COMMAND_UI(ID_WINDOW_SPLIT, OnUpdateWindowSplit)
213         // [Help] menu
214         ON_COMMAND(ID_HELP, OnHelp)
215         // Context menu
216         ON_COMMAND(ID_ADD_TO_IGNORED_SUBSTITUTIONS, OnAddToSubstitutionFilters)
217         ON_UPDATE_COMMAND_UI(ID_ADD_TO_IGNORED_SUBSTITUTIONS, OnUpdateAddToSubstitutionFilters)
218         ON_COMMAND(ID_ADD_TO_LINE_FILTERS, OnAddToLineFilters)
219         ON_UPDATE_COMMAND_UI(ID_ADD_TO_LINE_FILTERS, OnUpdateAddToLineFilters)
220         ON_COMMAND(ID_GOTO_MOVED_LINE_LM, OnGotoMovedLineLM)
221         ON_UPDATE_COMMAND_UI(ID_GOTO_MOVED_LINE_LM, OnUpdateGotoMovedLineLM)
222         ON_COMMAND(ID_GOTO_MOVED_LINE_MR, OnGotoMovedLineMR)
223         ON_UPDATE_COMMAND_UI(ID_GOTO_MOVED_LINE_MR, OnUpdateGotoMovedLineMR)
224         ON_COMMAND(ID_FILE_SHELLMENU, OnShellMenu)
225         ON_UPDATE_COMMAND_UI(ID_FILE_SHELLMENU, OnUpdateShellMenu)
226         ON_COMMAND(ID_FILE_OPEN_REGISTERED, OnOpenFile)
227         ON_COMMAND(ID_FILE_OPEN_WITHEDITOR, OnOpenFileWithEditor)
228         ON_COMMAND(ID_FILE_OPEN_WITH, OnOpenFileWith)
229         ON_COMMAND(ID_FILE_OPEN_PARENT_FOLDER, OnOpenParentFolder)
230         // Context menu (Header)
231         ON_COMMAND(ID_USE_FIRST_LINE_AS_HEADERS, OnUseFirstLineAsHeaders)
232         ON_UPDATE_COMMAND_UI(ID_USE_FIRST_LINE_AS_HEADERS, OnUpdateUseFirstLineAsHeaders)
233         ON_COMMAND(ID_AUTO_FIT_ALL_COLUMNS, OnAutoFitAllColumns)
234         // Status bar
235         ON_NOTIFY(NM_CLICK, AFX_IDW_STATUS_BAR, OnStatusBarClick)
236         ON_UPDATE_COMMAND_UI(ID_STATUS_PANE0FILE_EOL, OnUpdateStatusEOL)
237         ON_UPDATE_COMMAND_UI(ID_STATUS_PANE1FILE_EOL, OnUpdateStatusEOL)
238         ON_UPDATE_COMMAND_UI(ID_STATUS_PANE2FILE_EOL, OnUpdateStatusEOL)
239         //}}AFX_MSG_MAP
240 END_MESSAGE_MAP()
241
242
243 /////////////////////////////////////////////////////////////////////////////
244 // CMergeEditView diagnostics
245
246 #ifdef _DEBUG
247 CMergeDoc* CMergeEditView::GetDocument() // non-debug version is inline
248 {
249         ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CMergeDoc)));
250         return (CMergeDoc*)m_pDocument;
251 }
252
253 #endif //_DEBUG
254
255 /////////////////////////////////////////////////////////////////////////////
256 // CMergeEditView message handlers
257
258 /**
259  * @brief Return text buffer for file in view
260  */
261 CCrystalTextBuffer *CMergeEditView::LocateTextBuffer()
262 {
263         return GetDocument()->m_ptBuf[m_nThisPane].get();
264 }
265
266 /**
267  * @brief Update any resources necessary after a GUI language change
268  */
269 void CMergeEditView::UpdateResources()
270 {
271 }
272
273 CMergeEditView *CMergeEditView::GetGroupView(int nBuffer) const
274 {
275         return GetDocument()->GetView(m_nThisGroup, nBuffer);
276 }
277
278 void CMergeEditView::PrimeListWithFile()
279 {
280         // Set the tab size now, just in case the options change...
281         // We don't update it at the end of OnOptions,
282         // we can update it safely now
283         SetTabSize(GetOptionsMgr()->GetInt(OPT_TAB_SIZE));
284 }
285 /**
286  * @brief Return text from line given
287  */
288 CString CMergeEditView::GetLineText(int idx)
289 {
290         return GetLineChars(idx);
291 }
292
293 /**
294  * @brief Return text from selection
295  */
296 CString CMergeEditView::GetSelectedText()
297 {
298         CString strText;
299         auto [ptStart, ptEnd] = GetSelection();
300         if (ptStart != ptEnd)
301                 GetTextWithoutEmptys(ptStart.y, ptStart.x, ptEnd.y, ptEnd.x, strText);
302         return strText;
303 }
304
305 /**
306  * @brief Return number of selected characters
307  */
308 std::pair<int, int> CMergeEditView::GetSelectedLineAndCharacterCount()
309 {
310         auto [ptStart, ptEnd] = GetSelection();
311         int nCharsOrColumns =0;
312         int nSelectedLines = 0;
313         for (int nLine = ptStart.y; nLine <= ptEnd.y; ++nLine)
314         {
315                 if ((GetLineFlags(nLine) & (LF_GHOST | LF_INVISIBLE)) == 0)
316                 {
317                         int nLineLength = GetLineLength(nLine) + (m_pTextBuffer->GetLineEol(nLine)[0] ? 1 : 0);
318                         nCharsOrColumns += (nLine == ptEnd.y) ? ptEnd.x : nLineLength;
319                         if (nLine == ptStart.y)
320                                 nCharsOrColumns -= ptStart.x;
321                         if (nLine < ptEnd.y || (ptStart != ptEnd && ptEnd.x > 0))
322                                 ++nSelectedLines;
323                 }
324         }
325         if (m_bRectangularSelection)
326         {
327                 int nStartLeft, nStartRight, nEndLeft, nEndRight;
328                 GetColumnSelection(ptStart.y, nStartLeft, nStartRight);
329                 GetColumnSelection(ptEnd.y, nEndLeft, nEndRight);
330                 nCharsOrColumns = (std::max)(nStartRight, nEndRight) - (std::min)(nStartLeft, nEndLeft);
331         }
332         return { nSelectedLines, nCharsOrColumns };
333 }
334
335 /**
336  * @brief Get diffs inside selection.
337  * @param [out] firstDiff First diff inside selection
338  * @param [out] lastDiff Last diff inside selection
339  * @note -1 is returned in parameters if diffs cannot be determined
340  * @todo This shouldn't be called when there is no diffs, so replace
341  * first 'if' with ASSERT()?
342  */
343 void CMergeEditView::GetFullySelectedDiffs(int & firstDiff, int & lastDiff)
344 {
345         firstDiff = -1;
346         lastDiff = -1;
347
348         CMergeDoc *pd = GetDocument();
349         const int nDiffs = pd->m_diffList.GetSignificantDiffs();
350         if (nDiffs == 0)
351                 return;
352
353         int firstLine, lastLine;
354         GetFullySelectedLines(firstLine, lastLine);
355         if (lastLine < firstLine)
356                 return;
357
358         firstDiff = pd->m_diffList.NextSignificantDiffFromLine(firstLine);
359         lastDiff = pd->m_diffList.PrevSignificantDiffFromLine(lastLine);
360         if (firstDiff != -1 && lastDiff != -1)
361         {
362                 DIFFRANGE di;
363
364                 // Check that first selected line is first diff's first line or above it
365                 VERIFY(pd->m_diffList.GetDiff(firstDiff, di));
366                 if ((int)di.dbegin < firstLine)
367                 {
368                         if (firstDiff < lastDiff)
369                                 ++firstDiff;
370                 }
371
372                 // Check that last selected line is last diff's last line or below it
373                 VERIFY(pd->m_diffList.GetDiff(lastDiff, di));
374                 if ((int)di.dend > lastLine)
375                 {
376                         if (firstDiff < lastDiff)
377                                 --lastDiff;
378                 }
379
380                 // Special case: one-line diff is not selected if cursor is in it
381                 if (firstLine == lastLine)
382                 {
383                         firstDiff = -1;
384                         lastDiff = -1;
385                 }
386         }
387 }
388
389 /**
390  * @brief Get diffs inside selection.
391  * @param [out] firstDiff First diff inside selection
392  * @param [out] lastDiff Last diff inside selection
393  * @param [out] firstWordDiff First word level diff inside selection
394  * @param [out] lastWordDiff Last word level diff inside selection
395  * @note -1 is returned in parameters if diffs cannot be determined
396  * @todo This shouldn't be called when there is no diffs, so replace
397  * first 'if' with ASSERT()?
398  */
399 void CMergeEditView::GetFullySelectedDiffs(int & firstDiff, int & lastDiff, int & firstWordDiff, int & lastWordDiff, const CEPoint *pptStart, const CEPoint *pptEnd)
400 {
401         firstDiff = -1;
402         lastDiff = -1;
403         firstWordDiff = -1;
404         lastWordDiff = -1;
405
406         CMergeDoc *pd = GetDocument();
407         const int nDiffs = pd->m_diffList.GetSignificantDiffs();
408         if (nDiffs == 0)
409                 return;
410
411         int firstLine, lastLine;
412         auto [ptStart, ptEnd] = GetSelection();
413         if (pptStart != nullptr)
414                 ptStart = *pptStart;
415         if (pptEnd != nullptr)
416                 ptEnd = *pptEnd;
417         firstLine = ptStart.y;
418         lastLine = ptEnd.y;
419
420         firstDiff = pd->m_diffList.LineToDiff(firstLine);
421         bool firstLineIsNotInDiff = firstDiff == -1;
422         if (firstDiff == -1)
423         {
424                 firstDiff = pd->m_diffList.NextSignificantDiffFromLine(firstLine);
425                 if (firstDiff == -1)
426                         return;
427                 firstWordDiff = 0;
428         }
429         lastDiff = pd->m_diffList.LineToDiff(lastLine);
430         bool lastLineIsNotInDiff = lastDiff == -1;      
431         if (lastDiff == -1)
432                 lastDiff = pd->m_diffList.PrevSignificantDiffFromLine(lastLine);
433         if (lastDiff < firstDiff)
434         {
435                 firstDiff = -1;
436                 firstWordDiff = -1;
437                 return;
438         }
439
440         if (firstDiff != -1 && lastDiff != -1)
441         {
442                 DIFFRANGE di;
443                 
444                 if (pd->EqualCurrentWordDiff(m_nThisPane, ptStart, ptEnd))
445                 {
446                         firstWordDiff = lastWordDiff = static_cast<int>(pd->GetCurrentWordDiff().nWordDiff);
447                 }
448                 else if (ptStart != ptEnd)
449                 {
450                         VERIFY(pd->m_diffList.GetDiff(firstDiff, di));
451                         constexpr int LineLimit = 256;
452                         if ((lastLineIsNotInDiff && (firstLineIsNotInDiff || (di.dbegin == firstLine && ptStart.x == 0))) ||
453                             (di.dend - di.dbegin > LineLimit))
454                         {
455                                 firstWordDiff = -1;
456                                 return;
457                         }
458
459                         if (firstWordDiff == -1)
460                         {
461                                 vector<WordDiff> worddiffs = pd->GetWordDiffArrayInDiffBlock(firstDiff);
462                                 for (size_t i = 0; i < worddiffs.size(); ++i)
463                                 {
464                                         int worddiffLen = worddiffs[i].end[m_nThisPane] - worddiffs[i].begin[m_nThisPane];
465                                         if (worddiffs[i].endline[m_nThisPane] > firstLine ||
466                                                 (firstLine == worddiffs[i].endline[m_nThisPane] && 
467                                                  worddiffs[i].end[m_nThisPane] - (worddiffLen == 0 ? 0 : 1) > ptStart.x))
468                                         {
469                                                 firstWordDiff = static_cast<int>(i);
470                                                 break;
471                                         }
472                                 }
473
474                                 if (firstLine >= di.dbegin && firstWordDiff == -1)
475                                 {
476                                         ++firstDiff;
477                                         firstWordDiff = 0;
478                                 }
479                         }
480
481                         VERIFY(pd->m_diffList.GetDiff(lastDiff, di));
482                         vector<WordDiff> worddiffs = pd->GetWordDiffArrayInDiffBlock(lastDiff);
483                         for (size_t i = worddiffs.size() - 1; i != (size_t)-1; --i)
484                         {
485                                 if (worddiffs[i].beginline[m_nThisPane] < lastLine ||
486                                     (lastLine == worddiffs[i].beginline[m_nThisPane] && worddiffs[i].begin[m_nThisPane] + 1 <= ptEnd.x))
487                                 {
488                                         lastWordDiff = static_cast<int>(i);
489                                         break;
490                                 }
491                         }
492
493                         if (lastLine <= di.dend && lastWordDiff == -1)
494                                 --lastDiff;
495
496                         if (firstDiff == lastDiff && (lastWordDiff != -1 && lastWordDiff < firstWordDiff))
497                         {
498                                 firstDiff = -1;
499                                 lastDiff = -1;
500                                 firstWordDiff = -1;
501                                 lastWordDiff = -1;
502                         }
503                         else if (lastDiff < firstDiff || (firstDiff == lastDiff && firstWordDiff == -1 && lastWordDiff == -1))
504                         {
505                                 firstDiff = -1;
506                                 lastDiff = -1;
507                                 firstWordDiff = -1;
508                                 lastWordDiff = -1;
509                         }
510                 }
511                 else
512                 {
513                         firstDiff = -1;
514                         lastDiff = -1;
515                         firstWordDiff = -1;
516                         lastWordDiff = -1;
517                 }
518         }
519
520         ASSERT(firstDiff == -1 ? (lastDiff  == -1 && firstWordDiff == -1 && lastWordDiff == -1) : true);
521         ASSERT(lastDiff  == -1 ? (firstDiff == -1 && firstWordDiff == -1 && lastWordDiff == -1) : true);
522         ASSERT(firstDiff != -1 ? firstWordDiff != -1 : true);
523 }
524
525 void CMergeEditView::GetSelectedDiffs(int & firstDiff, int & lastDiff)
526 {
527         firstDiff = -1;
528         lastDiff = -1;
529
530         CMergeDoc *pd = GetDocument();
531         const int nDiffs = pd->m_diffList.GetSignificantDiffs();
532         if (nDiffs == 0)
533                 return;
534
535         int firstLine, lastLine;
536         auto [ptStart, ptEnd] = GetSelection();
537         firstLine = ptStart.y;
538         lastLine = ptEnd.y;
539
540         firstDiff = pd->m_diffList.LineToDiff(firstLine);
541         if (firstDiff == -1)
542         {
543                 firstDiff = pd->m_diffList.NextSignificantDiffFromLine(firstLine);
544                 if (firstDiff == -1)
545                         return;
546         }
547         lastDiff = pd->m_diffList.LineToDiff(lastLine);
548         if (lastDiff == -1)
549                 lastDiff = pd->m_diffList.PrevSignificantDiffFromLine(lastLine);
550         if (lastDiff < firstDiff)
551         {
552                 firstDiff = -1;
553                 return;
554         }
555
556         ASSERT(firstDiff == -1 ? (lastDiff  == -1) : true);
557         ASSERT(lastDiff  == -1 ? (firstDiff == -1) : true);
558 }
559
560 std::map<int, std::vector<int>> CMergeEditView::GetColumnSelectedWordDiffIndice()
561 {
562         CMergeDoc *pDoc = GetDocument();
563         std::map<int, std::vector<int>> ret;
564         std::map<int, std::vector<int> *> list;
565         auto [ptStart, ptEnd] = GetSelection();
566         for (int nLine = ptStart.y; nLine <= ptEnd.y; ++nLine)
567         {
568                 if (pDoc->m_diffList.LineToDiff(nLine) != -1)
569                 {
570                         int firstDiff, lastDiff, firstWordDiff, lastWordDiff;
571                         int nLeft, nRight;
572                         GetColumnSelection(nLine, nLeft, nRight);
573                         CEPoint ptStart2, ptEnd2;
574                         ptStart2.x = nLeft;
575                         ptEnd2.x = nRight;
576                         ptStart2.y = ptEnd2.y = nLine;
577                         GetFullySelectedDiffs(firstDiff, lastDiff, firstWordDiff, lastWordDiff, &ptStart2, &ptEnd2);
578                         if (firstDiff != -1 && lastDiff != -1)
579                         {
580                                 std::vector<int> *pWordDiffs;
581                                 if (list.find(firstDiff) == list.end())
582                                         list.emplace(firstDiff, new std::vector<int>());
583                                 pWordDiffs = list[firstDiff];
584                                 for (int i = firstWordDiff; i <= lastWordDiff; ++i)
585                                 {
586                                         if (pWordDiffs->empty() || i != (*pWordDiffs)[pWordDiffs->size() - 1])
587                                                 pWordDiffs->push_back(i);
588                                 }
589                         }
590                 }
591         }
592         for (auto& it : list)
593                 ret.emplace(it.first, *it.second);
594         return ret;
595 }
596
597 void CMergeEditView::OnInitialUpdate()
598 {
599         PushCursors();
600         CCrystalEditViewEx::OnInitialUpdate();
601         PopCursors();
602         LOGFONT lf = dynamic_cast<CMainFrame*>(AfxGetMainWnd())->m_lfDiff;
603         lf.lfHeight = static_cast<LONG>(lf.lfHeight * GetOptionsMgr()->GetInt(OPT_VIEW_ZOOM) / 1000.0);
604         SetFont(lf);
605         SetAlternateDropTarget(new DropHandler(std::bind(&CMergeEditView::OnDropFiles, this, std::placeholders::_1)));
606
607         m_lineBegin = 0;
608         m_lineEnd = -1;
609 }
610
611 void CMergeEditView::OnActivateView(BOOL bActivate, CView* pActivateView, CView* pDeactiveView)
612 {
613         CCrystalEditViewEx::OnActivateView(bActivate, pActivateView, pDeactiveView);
614
615         CMergeDoc* pDoc = GetDocument();
616         pDoc->UpdateHeaderActivity(m_nThisPane, !!bActivate);
617 }
618
619 std::vector<CrystalLineParser::TEXTBLOCK> CMergeEditView::GetMarkerTextBlocks(int nLineIndex) const
620 {
621         if (m_bDetailView)
622         {
623                 if (nLineIndex < m_lineBegin || nLineIndex > m_lineEnd)
624                         return std::vector<CrystalLineParser::TEXTBLOCK>();
625         }
626         return CCrystalTextView::GetMarkerTextBlocks(nLineIndex);
627 }
628
629 std::vector<TEXTBLOCK> CMergeEditView::GetAdditionalTextBlocks (int nLineIndex)
630 {
631         static const std::vector<TEXTBLOCK> emptyBlocks;
632         if (m_bDetailView)
633         {
634                 if (nLineIndex < m_lineBegin || nLineIndex > m_lineEnd)
635                         return emptyBlocks;
636         }
637
638         DWORD dwLineFlags = GetLineFlags(nLineIndex);
639         if ((dwLineFlags & LF_SNP) == LF_SNP || (dwLineFlags & LF_DIFF) != LF_DIFF || (dwLineFlags & LF_MOVED) == LF_MOVED)
640                 return emptyBlocks;
641
642         if (!GetOptionsMgr()->GetBool(OPT_WORDDIFF_HIGHLIGHT))
643                 return emptyBlocks;
644
645         CMergeDoc *pDoc = GetDocument();
646         if (pDoc->IsEditedAfterRescan(m_nThisPane))
647                 return emptyBlocks;
648         
649         int nDiff = pDoc->m_diffList.LineToDiff(nLineIndex);
650         if (nDiff == -1)
651                 return emptyBlocks;
652
653         DIFFRANGE cd;
654         pDoc->m_diffList.GetDiff(nDiff, cd);
655         int unemptyLineCount = 0;
656         for (int nPane = 0; nPane < pDoc->m_nBuffers; nPane++)
657         {
658                 if (cd.begin[nPane] != cd.end[nPane] + 1)
659                         unemptyLineCount++;
660         }
661         if (unemptyLineCount < 2)
662                 return emptyBlocks;
663
664         vector<WordDiff> worddiffs = pDoc->GetWordDiffArray(nLineIndex);
665         size_t nWordDiffs = worddiffs.size();
666
667         bool lineInCurrentDiff = IsLineInCurrentDiff(nLineIndex);
668
669         std::vector<TEXTBLOCK> blocks(nWordDiffs * 2 + 1);
670         blocks[0].m_nCharPos = 0;
671         blocks[0].m_nColorIndex = COLORINDEX_NONE;
672         blocks[0].m_nBgColorIndex = COLORINDEX_NONE;
673         size_t i, j;
674         for (i = 0, j = 1; i < nWordDiffs; i++)
675         {
676                 if (worddiffs[i].beginline[m_nThisPane] > nLineIndex || worddiffs[i].endline[m_nThisPane] < nLineIndex )
677                         continue;
678                 if (pDoc->m_nBuffers > 2)
679                 {
680                         if (m_nThisPane == 0 && worddiffs[i].op == OP_3RDONLY)
681                                 continue;
682                         else if (m_nThisPane == 2 && worddiffs[i].op == OP_1STONLY)
683                                 continue;
684                 }
685                 int begin[3]{}, end[3]{};
686                 bool deleted = false;
687                 for (int pane = 0; pane < pDoc->m_nBuffers; pane++)
688                 {
689                         begin[pane] = (worddiffs[i].beginline[pane] < nLineIndex) ? 0 : worddiffs[i].begin[pane];
690                         end[pane]   = (worddiffs[i].endline[pane]   > nLineIndex) ? GetGroupView(pane)->GetLineLength(nLineIndex) : worddiffs[i].end[pane];
691                         if (worddiffs[i].beginline[pane] == worddiffs[i].endline[pane] &&
692                                 worddiffs[i].begin[pane] == worddiffs[i].end[pane])
693                                 deleted = true;
694                 }
695                 blocks[j].m_nCharPos = begin[m_nThisPane];
696                 if (lineInCurrentDiff)
697                 {
698                         blocks[j].m_nColorIndex = COLORINDEX_APPLYFORCE |
699                                 ((m_cachedColors.clrSelWordDiffText != CLR_NONE) ? COLORINDEX_HIGHLIGHTTEXT1 : COLORINDEX_NONE);
700                         blocks[j].m_nBgColorIndex = COLORINDEX_APPLYFORCE | 
701                                 (deleted ? COLORINDEX_HIGHLIGHTBKGND4 : COLORINDEX_HIGHLIGHTBKGND1);
702                 }
703                 else
704                 {
705                         blocks[j].m_nColorIndex = COLORINDEX_APPLYFORCE |
706                                 ((m_cachedColors.clrWordDiffText != CLR_NONE) ? COLORINDEX_HIGHLIGHTTEXT2 : COLORINDEX_NONE);
707                         blocks[j].m_nBgColorIndex = COLORINDEX_APPLYFORCE |
708                                 (deleted ? COLORINDEX_HIGHLIGHTBKGND3 : COLORINDEX_HIGHLIGHTBKGND2);
709                 }
710                 j++;
711                 blocks[j].m_nCharPos = end[m_nThisPane];
712                 blocks[j].m_nColorIndex = COLORINDEX_NONE;
713                 blocks[j].m_nBgColorIndex = COLORINDEX_NONE;
714                 j++;
715         }
716
717         blocks.resize(j);
718
719         return blocks;
720 }
721
722 CEColor CMergeEditView::GetColor(int nColorIndex) const
723 {
724         switch (nColorIndex & ~COLORINDEX_MASK)
725         {
726         case COLORINDEX_HIGHLIGHTBKGND1:
727                 return m_cachedColors.clrSelWordDiff;
728         case COLORINDEX_HIGHLIGHTTEXT1:
729                 return m_cachedColors.clrSelWordDiffText;
730         case COLORINDEX_HIGHLIGHTBKGND2:
731                 return m_cachedColors.clrWordDiff;
732         case COLORINDEX_HIGHLIGHTTEXT2:
733                 return m_cachedColors.clrWordDiffText;
734         case COLORINDEX_HIGHLIGHTBKGND3:
735                 return m_cachedColors.clrWordDiffDeleted;
736         case COLORINDEX_HIGHLIGHTBKGND4:
737                 return m_cachedColors.clrSelWordDiffDeleted;
738
739         default:
740                 return CCrystalTextView::GetColor(nColorIndex);
741         }
742 }
743
744 /**
745  * @brief Determine text and background color for line
746  * @param [in] nLineIndex Index of line in view (NOT line in file)
747  * @param [out] crBkgnd Backround color for line
748  * @param [out] crText Text color for line
749  */
750 void CMergeEditView::GetLineColors(int nLineIndex, CEColor & crBkgnd,
751                                 CEColor & crText, bool & bDrawWhitespace)
752 {
753         DWORD ignoreFlags = 0;
754         GetLineColors2(nLineIndex, ignoreFlags, crBkgnd, crText, bDrawWhitespace);
755 }
756
757 /**
758  * @brief Determine text and background color for line
759  * @param [in] nLineIndex Index of line in view (NOT line in file)
760  * @param [in] ignoreFlags Flags that caller wishes ignored
761  * @param [out] crBkgnd Backround color for line
762  * @param [out] crText Text color for line
763  *
764  * This version allows caller to suppress particular flags
765  */
766 void CMergeEditView::GetLineColors2(int nLineIndex, DWORD ignoreFlags, CEColor & crBkgnd,
767                                 CEColor & crText, bool & bDrawWhitespace)
768 {
769         if (GetLineCount() <= nLineIndex)
770                 return;
771
772         DWORD dwLineFlags = GetLineFlags(nLineIndex);
773
774         if (dwLineFlags & ignoreFlags)
775                 dwLineFlags &= (~ignoreFlags);
776
777         if (m_bDetailView)
778         {
779                 // Line with WinMerge flag, 
780                 // Lines with only the LF_DIFF/LF_TRIVIAL flags are not colored with Winmerge colors
781                 if (dwLineFlags & (LF_WINMERGE_FLAGS & ~LF_DIFF & ~LF_TRIVIAL & ~LF_MOVED & ~LF_SNP))
782                 {
783                         crText = m_cachedColors.clrDiffText;
784                         bDrawWhitespace = true;
785
786                         if (dwLineFlags & LF_GHOST)
787                         {
788                                 crBkgnd = m_cachedColors.clrDiffDeleted;
789                         }
790                 }
791                 else
792                 {
793                         // If no syntax hilighting
794                         if (!GetOptionsMgr()->GetBool(OPT_SYNTAX_HIGHLIGHT))
795                         {
796                                 crBkgnd = GetColor (COLORINDEX_BKGND);
797                                 crText = GetColor (COLORINDEX_NORMALTEXT);
798                                 bDrawWhitespace = false;
799                         }
800                         else
801                                 // Line not inside diff, get colors from CrystalEditor
802                                 CCrystalEditViewEx::GetLineColors(nLineIndex, crBkgnd,
803                                         crText, bDrawWhitespace);
804                 }
805                 if (nLineIndex < m_lineBegin || nLineIndex > m_lineEnd)
806                 {
807                         crBkgnd = GetColor (COLORINDEX_WHITESPACE);
808                         crText = GetColor (COLORINDEX_WHITESPACE);
809                         bDrawWhitespace = false;
810                 }
811                 return;
812         }
813
814         // Line inside diff
815         if (dwLineFlags & LF_WINMERGE_FLAGS)
816         {
817                 crText = m_cachedColors.clrDiffText;
818                 bDrawWhitespace = true;
819                 bool lineInCurrentDiff = IsLineInCurrentDiff(nLineIndex);
820
821                 if (dwLineFlags & LF_SNP)
822                 {
823                         if (lineInCurrentDiff)
824                         {
825                                 if (dwLineFlags & LF_GHOST)
826                                         crBkgnd = m_cachedColors.clrSelSNPDeleted;
827                                 else
828                                         crBkgnd = m_cachedColors.clrSelSNP;
829                                 crText = m_cachedColors.clrSelSNPText;
830                         }
831                         else
832                         {
833                                 if (dwLineFlags & LF_GHOST)
834                                         crBkgnd = m_cachedColors.clrSNPDeleted;
835                                 else
836                                         crBkgnd = m_cachedColors.clrSNP;
837                                 crText = m_cachedColors.clrSNPText;
838                         }
839                         return;
840                 }
841                 else if (dwLineFlags & LF_DIFF)
842                 {
843                         if (lineInCurrentDiff)
844                         {
845                                 if (dwLineFlags & LF_MOVED)
846                                 {
847                                         crBkgnd = m_cachedColors.clrSelMoved;
848                                         crText = m_cachedColors.clrSelMovedText;
849                                 }
850                                 else
851                                 {
852                                         crBkgnd = m_cachedColors.clrSelDiff;
853                                         crText = m_cachedColors.clrSelDiffText;
854                                 }
855                         
856                         }
857                         else
858                         {
859                                 if (dwLineFlags & LF_MOVED)
860                                 {
861                                         crBkgnd = m_cachedColors.clrMoved;
862                                         crText = m_cachedColors.clrMovedText;
863                                 }
864                                 else
865                                 {
866                                         crBkgnd = m_cachedColors.clrDiff;
867                                         crText = m_cachedColors.clrDiffText;
868                                 }
869                         }
870                         return;
871                 }
872                 else if (dwLineFlags & LF_TRIVIAL)
873                 {
874                         // trivial diff can not be selected
875                         if (dwLineFlags & LF_GHOST)
876                                 // ghost lines in trivial diff has their own color
877                                 crBkgnd = m_cachedColors.clrTrivialDeleted;
878                         else
879                                 crBkgnd = m_cachedColors.clrTrivial;
880                         crText = m_cachedColors.clrTrivialText;
881                         return;
882                 }
883                 else if (dwLineFlags & LF_GHOST)
884                 {
885                         if (lineInCurrentDiff)
886                         {
887                                 if (dwLineFlags & LF_MOVED)
888                                         crBkgnd = m_cachedColors.clrSelMovedDeleted;
889                                 else
890                                         crBkgnd = m_cachedColors.clrSelDiffDeleted;
891                         }
892                         else
893                         {
894                                 if (dwLineFlags & LF_MOVED)
895                                         crBkgnd = m_cachedColors.clrMovedDeleted;
896                                 else
897                                         crBkgnd = m_cachedColors.clrDiffDeleted;
898                         }
899                         return;
900                 }
901         }
902         else
903         {
904                 // Line not inside diff,
905                 if (!GetOptionsMgr()->GetBool(OPT_SYNTAX_HIGHLIGHT))
906                 {
907                         // If no syntax hilighting, get windows default colors
908                         crBkgnd = GetColor (COLORINDEX_BKGND);
909                         crText = GetColor (COLORINDEX_NORMALTEXT);
910                         bDrawWhitespace = false;
911                 }
912                 else
913                         // Syntax highlighting, get colors from CrystalEditor
914                         CCrystalEditViewEx::GetLineColors(nLineIndex, crBkgnd,
915                                 crText, bDrawWhitespace);
916         }
917 }
918
919 /**
920  * @brief Sync other pane position
921  */
922 void CMergeEditView::UpdateSiblingScrollPos (bool bHorz)
923 {
924         CSplitterWnd *pSplitterWnd = GetParentSplitter (this, false);
925         if (pSplitterWnd != nullptr)
926         {
927                 //  See CSplitterWnd::IdFromRowCol() implementation for details
928                 int nCurrentRow = (GetDlgCtrlID () - AFX_IDW_PANE_FIRST) / 16;
929                 int nCurrentCol = (GetDlgCtrlID () - AFX_IDW_PANE_FIRST) % 16;
930                 ASSERT (nCurrentRow >= 0 && nCurrentRow < pSplitterWnd->GetRowCount ());
931                 ASSERT (nCurrentCol >= 0 && nCurrentCol < pSplitterWnd->GetColumnCount ());
932
933                 // limit the TopLine : must be smaller than GetLineCount for all the panels
934                 int newTopSubLine = m_nTopSubLine;
935                 int nRows = pSplitterWnd->GetRowCount ();
936                 int nCols = pSplitterWnd->GetColumnCount ();
937                 int nRow=0;
938 //              for (nRow = 0; nRow < nRows; nRow++)
939 //              {
940 //                      for (int nCol = 0; nCol < nCols; nCol++)
941 //                      {
942 //                              CMergeEditView *pSiblingView = static_cast<CMergeEditView*>(GetSiblingView (nRow, nCol));
943 //                              if (pSiblingView != nullptr)
944 //                                      if (pSiblingView->GetSubLineCount() <= newTopSubLine)
945 //                                              newTopSubLine = pSiblingView->GetSubLineCount()-1;
946 //                      }
947 //              }
948                 if (m_nTopSubLine != newTopSubLine)
949                         ScrollToSubLine(newTopSubLine);
950
951                 for (nRow = 0; nRow < nRows; nRow++)
952                 {
953                         for (int nCol = 0; nCol < nCols; nCol++)
954                         {
955                                 if (!(nRow == nCurrentRow && nCol == nCurrentCol))  //  We don't need to update ourselves
956                                 {
957                                         CMergeEditView *pSiblingView = static_cast<CMergeEditView*>(GetSiblingView (nRow, nCol));
958                                         if (pSiblingView != nullptr && pSiblingView->m_nThisGroup == m_nThisGroup)
959                                                 pSiblingView->OnUpdateSibling (this, bHorz);
960                                 }
961                         }
962                 }
963         }
964 }
965
966 /**
967  * @brief Update other panes
968  */
969 void CMergeEditView::OnUpdateSibling (CCrystalTextView * pUpdateSource, bool bHorz)
970 {
971         if (pUpdateSource != this)
972         {
973                 ASSERT (pUpdateSource != nullptr);
974                 ASSERT_KINDOF (CCrystalTextView, pUpdateSource);
975                 CMergeEditView *pSrcView = static_cast<CMergeEditView*>(pUpdateSource);
976                 if (!bHorz)  // changed this so bHorz works right
977                 {
978                         ASSERT (pSrcView->m_nTopSubLine >= 0);
979
980                         // This ASSERT is wrong: panes have different files and
981                         // different linecounts
982                         // ASSERT (pSrcView->m_nTopLine < GetLineCount ());
983                         if (pSrcView->m_nTopSubLine != m_nTopSubLine)
984                         {
985                                 ScrollToSubLine (pSrcView->m_nTopSubLine, true, false);
986                                 UpdateCaret ();
987                                 RecalcVertScrollBar(true);
988                                 InvalidateHorzScrollBar();
989                         }
990                 }
991                 else
992                 {
993                         ASSERT (pSrcView->m_nOffsetChar >= 0);
994
995                         // This ASSERT is wrong: panes have different files and
996                         // different linelengths
997                         // ASSERT (pSrcView->m_nOffsetChar < GetMaxLineLength ());
998                         if (pSrcView->m_nOffsetChar != m_nOffsetChar)
999                         {
1000                                 ScrollToChar (pSrcView->m_nOffsetChar, true, false);
1001                                 UpdateCaret ();
1002                                 RecalcHorzScrollBar(true);
1003                                 InvalidateHorzScrollBar();
1004                         }
1005                 }
1006         }
1007 }
1008
1009 void CMergeEditView::OnDisplayDiff(int nDiff /*=0*/)
1010 {
1011         int newlineBegin, newlineEnd;
1012         CMergeDoc *pd = GetDocument();
1013         if (nDiff < 0 || nDiff >= pd->m_diffList.GetSize())
1014         {
1015                 newlineBegin = 0;
1016                 newlineEnd = -1;
1017         }
1018         else
1019         {
1020                 DIFFRANGE curDiff;
1021                 VERIFY(pd->m_diffList.GetDiff(nDiff, curDiff));
1022
1023                 newlineBegin = curDiff.dbegin;
1024                 ASSERT (newlineBegin >= 0);
1025                 newlineEnd = curDiff.dend;
1026         }
1027
1028         m_lineBegin = newlineBegin;
1029         m_lineEnd = newlineEnd;
1030
1031         int nLineCount = GetLineCount();
1032         if (m_lineBegin > nLineCount)
1033                 m_lineBegin = nLineCount - 1;
1034         if (m_lineEnd > nLineCount)
1035                 m_lineEnd = nLineCount - 1;
1036
1037         if (m_nTopLine == newlineBegin)
1038                 return;
1039
1040         // scroll to the first line of the diff
1041         vector<WordDiff> worddiffs;
1042         if (GetOptionsMgr()->GetBool(OPT_SCROLL_TO_FIRST_INLINE_DIFF))
1043                 worddiffs = pd->GetWordDiffArrayInDiffBlock(nDiff);
1044         CEPoint pt = worddiffs.size() > 0 ?
1045                 CEPoint{ worddiffs[0].begin[m_nThisPane], worddiffs[0].beginline[m_nThisPane] } : 
1046                 CEPoint{ 0, m_lineBegin };
1047         ScrollToLine(m_lineBegin);
1048         if (pt.x > 0)
1049                 EnsureVisible(pt);
1050
1051         // update the width of the horizontal scrollbar
1052         InvalidateHorzScrollBar();
1053 }
1054
1055 /**
1056  * @brief Selects diff by number and syncs other file
1057  * @param [in] nDiff Diff to select, must be >= 0
1058  * @param [in] bScroll Scroll diff to view
1059  * @param [in] bSelectText Select diff text
1060  * @sa CMergeEditView::ShowDiff()
1061  * @sa CMergeDoc::SetCurrentDiff()
1062  * @todo Parameter bSelectText is never used?
1063  */
1064 void CMergeEditView::SelectDiff(int nDiff, bool bScroll /*= true*/, bool bSelectText /*= true*/)
1065 {
1066         CMergeDoc *pd = GetDocument();
1067
1068         // Check that nDiff is valid
1069         if (nDiff < 0)
1070                 _RPTF1(_CRT_ERROR, "Diffnumber negative (%d)", nDiff);
1071         if (nDiff >= pd->m_diffList.GetSize())
1072                 _RPTF2(_CRT_ERROR, "Selected diff > diffcount (%d >= %d)",
1073                         nDiff, pd->m_diffList.GetSize());
1074
1075         SelectNone();
1076         pd->SetCurrentDiff(nDiff);
1077         ShowDiff(bScroll, bSelectText);
1078         pd->UpdateAllViews(this);
1079         UpdateSiblingScrollPos(false);
1080
1081         // notify either side, as it will notify the other one
1082         pd->ForEachView ([&](auto& pView) { if (pView->m_bDetailView) pView->OnDisplayDiff(nDiff); });
1083 }
1084
1085 void CMergeEditView::DeselectDiffIfCursorNotInCurrentDiff()
1086 {
1087         CMergeDoc *pd = GetDocument();
1088         // If we have a selected diff, deselect it
1089         int nCurrentDiff = pd->GetCurrentDiff();
1090         if (nCurrentDiff != -1)
1091         {
1092                 CEPoint pos = GetCursorPos();
1093                 if (!IsLineInCurrentDiff(pos.y))
1094                 {
1095                         pd->SetCurrentDiff(-1);
1096                         Invalidate();
1097                         pd->UpdateAllViews(this);
1098                 }
1099         }
1100 }
1101
1102 /**
1103  * @brief Called when user selects "Current Difference".
1104  * Goes to active diff. If no active diff, selects diff under cursor
1105  * @sa CMergeEditView::SelectDiff()
1106  * @sa CMergeDoc::GetCurrentDiff()
1107  * @sa CMergeDoc::LineToDiff()
1108  */
1109 void CMergeEditView::OnCurdiff()
1110 {
1111         CMergeDoc *pd = GetDocument();
1112
1113         // If no diffs, nothing to select
1114         if (!pd->m_diffList.HasSignificantDiffs())
1115                 return;
1116
1117         // GetCurrentDiff() returns -1 if no diff selected
1118         int nDiff = pd->GetCurrentDiff();
1119         if (nDiff != -1)
1120         {
1121                 // Scroll to the first line of the currently selected diff
1122                 SelectDiff(nDiff, true, false);
1123         }
1124         else
1125         {
1126                 // If cursor is inside diff, select that diff
1127                 CEPoint pos = GetCursorPos();
1128                 nDiff = pd->m_diffList.LineToDiff(pos.y);
1129                 if (nDiff != -1 && pd->m_diffList.IsDiffSignificant(nDiff))
1130                         SelectDiff(nDiff, true, false);
1131         }
1132 }
1133
1134 /**
1135  * @brief Called when "Current diff" item is updated
1136  */
1137 void CMergeEditView::OnUpdateCurdiff(CCmdUI* pCmdUI)
1138 {
1139         CMergeDoc *pd = GetDocument();
1140         int nCurrentDiff = pd->GetCurrentDiff();
1141         if (nCurrentDiff == -1)
1142         {
1143                 CEPoint pos = GetCursorPos();
1144                 int nNewDiff = pd->m_diffList.LineToDiff(pos.y);
1145                 pCmdUI->Enable(nNewDiff != -1 && pd->m_diffList.IsDiffSignificant(nNewDiff));
1146         }
1147         else
1148                 pCmdUI->Enable(true);
1149 }
1150
1151 /**
1152  * @brief Copy selected text to clipboard
1153  */
1154 void CMergeEditView::OnEditCopy()
1155 {
1156         CMergeDoc * pDoc = GetDocument();
1157         auto [ptSelStart, ptSelEnd] = GetSelection();
1158
1159         // Nothing selected
1160         if (ptSelStart == ptSelEnd)
1161                 return;
1162
1163         CString text;
1164
1165         if (!m_bRectangularSelection)
1166         {
1167                 CDiffTextBuffer * buffer = pDoc->m_ptBuf[m_nThisPane].get();
1168
1169                 buffer->GetTextWithoutEmptys(ptSelStart.y, ptSelStart.x,
1170                         ptSelEnd.y, ptSelEnd.x, text);
1171         }
1172         else
1173                 GetTextWithoutEmptysInColumnSelection(text);
1174
1175         PutToClipboard(text, text.GetLength(), m_bRectangularSelection);
1176 }
1177
1178 /**
1179  * @brief Called when "Copy" item is updated
1180  */
1181 void CMergeEditView::OnUpdateEditCopy(CCmdUI* pCmdUI)
1182 {
1183         CCrystalEditViewEx::OnUpdateEditCopy(pCmdUI);
1184 }
1185
1186 /**
1187  * @brief Cut current selection to clipboard
1188  */
1189 void CMergeEditView::OnEditCut()
1190 {
1191         if (!QueryEditable())
1192                 return;
1193
1194         CMergeDoc * pDoc = GetDocument();
1195         auto [ptSelStart, ptSelEnd] = GetSelection();
1196
1197         // Nothing selected
1198         if (ptSelStart == ptSelEnd)
1199                 return;
1200
1201         CString text;
1202         if (!m_bRectangularSelection)
1203                 pDoc->m_ptBuf[m_nThisPane]->GetTextWithoutEmptys(ptSelStart.y, ptSelStart.x,
1204                         ptSelEnd.y, ptSelEnd.x, text);
1205         else
1206                 GetTextWithoutEmptysInColumnSelection(text);
1207
1208         PutToClipboard(text, text.GetLength(), m_bRectangularSelection);
1209
1210         if (!m_bRectangularSelection)
1211         {
1212                 CEPoint ptCursorPos = ptSelStart;
1213                 ASSERT_VALIDTEXTPOS(ptCursorPos);
1214                 SetAnchor(ptCursorPos);
1215                 SetSelection(ptCursorPos, ptCursorPos);
1216                 SetCursorPos(ptCursorPos);
1217                 EnsureVisible(ptCursorPos);
1218
1219                 pDoc->m_ptBuf[m_nThisPane]->DeleteText(this, ptSelStart.y, ptSelStart.x, ptSelEnd.y,
1220                         ptSelEnd.x, CE_ACTION_CUT);
1221         }
1222         else
1223                 DeleteCurrentColumnSelection (CE_ACTION_CUT);
1224
1225         m_pTextBuffer->SetModified(true);
1226 }
1227
1228 /**
1229  * @brief Called when "Cut" item is updated
1230  */
1231 void CMergeEditView::OnUpdateEditCut(CCmdUI* pCmdUI)
1232 {
1233         if (QueryEditable())
1234                 CCrystalEditViewEx::OnUpdateEditCut(pCmdUI);
1235         else
1236                 pCmdUI->Enable(false);
1237 }
1238
1239 /**
1240  * @brief Paste text from clipboard
1241  */
1242 void CMergeEditView::OnEditPaste()
1243 {
1244         if (!QueryEditable())
1245                 return;
1246
1247         CCrystalEditViewEx::Paste();
1248         m_pTextBuffer->SetModified(true);
1249 }
1250
1251 /**
1252  * @brief Called when "Paste" item is updated
1253  */
1254 void CMergeEditView::OnUpdateEditPaste(CCmdUI* pCmdUI)
1255 {
1256         if (QueryEditable())
1257                 CCrystalEditViewEx::OnUpdateEditPaste(pCmdUI);
1258         else
1259                 pCmdUI->Enable(false);
1260 }
1261
1262 /**
1263  * @brief Undo last action
1264  */
1265 void CMergeEditView::OnEditUndo()
1266 {
1267         CWaitCursor waitstatus;
1268         CMergeDoc* pDoc = GetDocument();
1269         CMergeEditView *tgt = pDoc->GetView(m_nThisGroup, *(pDoc->curUndo-1));
1270         if(tgt==this)
1271         {
1272                 if (!QueryEditable())
1273                         return;
1274
1275                 GetParentFrame()->SetActiveView(this, true);
1276                 if(CCrystalEditViewEx::DoEditUndo())
1277                 {
1278                         --pDoc->curUndo;
1279                         pDoc->UpdateHeaderPath(m_nThisPane);
1280                         pDoc->FlushAndRescan();
1281
1282                         int nAction;
1283                         m_pTextBuffer->GetRedoActionCode(nAction);
1284                         if (nAction == CE_ACTION_MERGE)
1285                                 // select the diff so we may just merge it again
1286                                 OnCurdiff();
1287                 }
1288         }
1289         else
1290         {
1291                 tgt->SendMessage(WM_COMMAND, ID_EDIT_UNDO);
1292         }
1293         if (!pDoc->CanUndo())
1294                 pDoc->SetAutoMerged(false);
1295 }
1296
1297 /**
1298  * @brief Called when "Undo" item is updated
1299  */
1300 void CMergeEditView::OnUpdateEditUndo(CCmdUI* pCmdUI)
1301 {
1302         CMergeDoc* pDoc = GetDocument();
1303         if (pDoc->curUndo!=pDoc->undoTgt.begin())
1304         {
1305                 CMergeEditView *tgt = pDoc->GetView(m_nThisGroup, *(pDoc->curUndo-1));
1306                 pCmdUI->Enable( !IsReadOnly(tgt->m_nThisPane));
1307         }
1308         else
1309                 pCmdUI->Enable(false);
1310 }
1311
1312 /**
1313  * @brief Go to first diff
1314  *
1315  * Called when user selects "First Difference"
1316  * @sa CMergeEditView::SelectDiff()
1317  */
1318 void CMergeEditView::OnFirstdiff()
1319 {
1320         CMergeDoc *pd = GetDocument();
1321         if (pd->m_diffList.HasSignificantDiffs())
1322         {
1323                 int nDiff = pd->m_diffList.FirstSignificantDiff();
1324                 SelectDiff(nDiff, true, false);
1325         }
1326 }
1327
1328 /**
1329  * @brief Update "First diff" UI items
1330  */
1331 void CMergeEditView::OnUpdateFirstdiff(CCmdUI* pCmdUI)
1332 {
1333         OnUpdatePrevdiff(pCmdUI);
1334 }
1335
1336 /**
1337  * @brief Go to last diff
1338  */
1339 void CMergeEditView::OnLastdiff()
1340 {
1341         CMergeDoc *pd = GetDocument();
1342         if (pd->m_diffList.HasSignificantDiffs())
1343         {
1344                 int nDiff = pd->m_diffList.LastSignificantDiff();
1345                 SelectDiff(nDiff, true, false);
1346         }
1347 }
1348
1349 /**
1350  * @brief Update "Last diff" UI items
1351  */
1352 void CMergeEditView::OnUpdateLastdiff(CCmdUI* pCmdUI)
1353 {
1354         OnUpdateNextdiff(pCmdUI);
1355 }
1356
1357 /**
1358  * @brief Go to next diff and select it.
1359  *
1360  * Finds and selects next difference. There are several cases:
1361  * - if there is selected difference, and that difference is visible
1362  * on screen, next found difference is selected.
1363  * - if there is selected difference but it is not visible, next
1364  * difference from cursor position is selected. This is what user
1365  * expects to happen and is natural thing to do. Also reduces
1366  * needless scrolling.
1367  * - if there is no selected difference, next difference from cursor
1368  * position is selected.
1369  */
1370 void CMergeEditView::OnNextdiff()
1371 {
1372         CMergeDoc *pd = GetDocument();
1373         int cnt = pd->m_ptBuf[0]->GetLineCount();
1374         if (cnt <= 0)
1375                 return;
1376
1377         // Returns -1 if no diff selected
1378         int nextDiff = -1;
1379         int curDiff = pd->GetCurrentDiff();
1380         if (curDiff != -1)
1381         {
1382                 // We're on a diff
1383                 if (!IsDiffVisible(curDiff))
1384                 {
1385                         // Selected difference not visible, select next from cursor
1386                         int line = GetCursorPos().y;
1387                         // Make sure we aren't in the first line of the diff
1388                         ++line;
1389                         if (!IsValidTextPosY(CEPoint(0, line)))
1390                                 line = m_nTopLine;
1391                         nextDiff = pd->m_diffList.NextSignificantDiffFromLine(line);
1392                 }
1393                 else
1394                 {
1395                         // Find out if there is a following significant diff
1396                         if (curDiff < pd->m_diffList.GetSize() - 1)
1397                         {
1398                                 nextDiff = pd->m_diffList.NextSignificantDiff(curDiff);
1399                         }
1400                 }
1401         }
1402         else
1403         {
1404                 // We don't have a selected difference,
1405                 // but cursor can be inside inactive diff
1406                 int line = GetCursorPos().y;
1407                 if (!IsValidTextPosY(CEPoint(0, line)))
1408                         line = m_nTopLine;
1409                 nextDiff = pd->m_diffList.NextSignificantDiffFromLine(line);
1410         }
1411
1412         int lastDiff = pd->m_diffList.LastSignificantDiff();
1413         if (nextDiff >= 0 && nextDiff <= lastDiff)
1414                 SelectDiff(nextDiff, true, false);
1415         else if (CDirDoc *pDirDoc = pd->GetDirDoc())
1416         {
1417                 if (pDirDoc->MoveableToNextDiff())
1418                         pDirDoc->MoveToNextDiff(pd);
1419         }
1420 }
1421
1422 /**
1423  * @brief Update "Next diff" UI items
1424  */
1425 void CMergeEditView::OnUpdateNextdiff(CCmdUI* pCmdUI)
1426 {
1427         CMergeDoc *pd = GetDocument();
1428         const DIFFRANGE * dfi = pd->m_diffList.LastSignificantDiffRange();
1429         bool enabled;
1430
1431         if (dfi == nullptr)
1432         {
1433                 // There aren't any significant differences
1434                 enabled = false;
1435         }
1436         else
1437         {
1438                 // Enable if the beginning of the last significant difference is after caret
1439                 enabled = (GetCursorPos().y < (long)dfi->dbegin);
1440         }
1441
1442         if (!enabled && pd->GetDirDoc())
1443                 enabled = pd->GetDirDoc()->MoveableToNextDiff();
1444
1445         pCmdUI->Enable(enabled);
1446 }
1447
1448 /**
1449  * @brief Go to previous diff and select it.
1450  *
1451  * Finds and selects previous difference. There are several cases:
1452  * - if there is selected difference, and that difference is visible
1453  * on screen, previous found difference is selected.
1454  * - if there is selected difference but it is not visible, previous
1455  * difference from cursor position is selected. This is what user
1456  * expects to happen and is natural thing to do. Also reduces
1457  * needless scrolling.
1458  * - if there is no selected difference, previous difference from cursor
1459  * position is selected.
1460  */
1461 void CMergeEditView::OnPrevdiff()
1462 {
1463         CMergeDoc *pd = GetDocument();
1464         int cnt = pd->m_ptBuf[0]->GetLineCount();
1465         if (cnt <= 0)
1466                 return;
1467
1468         // GetCurrentDiff() returns -1 if no diff selected
1469         int prevDiff = -1;
1470         int curDiff = pd->GetCurrentDiff();
1471         if (curDiff != -1)
1472         {
1473                 // We're on a diff
1474                 if (!IsDiffVisible(curDiff))
1475                 {
1476                         // Selected difference not visible, select previous from cursor
1477                         int line = GetCursorPos().y;
1478                         // Make sure we aren't in the last line of the diff
1479                         --line;
1480                         if (!IsValidTextPosY(CEPoint(0, line)))
1481                                 line = m_nTopLine;
1482                         prevDiff = pd->m_diffList.PrevSignificantDiffFromLine(line);
1483                 }
1484                 else
1485                 {
1486                         // Find out if there is a preceding significant diff
1487                         if (curDiff > 0)
1488                         {
1489                                 prevDiff = pd->m_diffList.PrevSignificantDiff(curDiff);
1490                         }
1491                 }
1492         }
1493         else
1494         {
1495                 // We don't have a selected difference,
1496                 // but cursor can be inside inactive diff
1497                 int line = GetCursorPos().y;
1498                 if (!IsValidTextPosY(CEPoint(0, line)))
1499                         line = m_nTopLine;
1500                 prevDiff = pd->m_diffList.PrevSignificantDiffFromLine(line);
1501         }
1502
1503         int firstDiff = pd->m_diffList.FirstSignificantDiff();
1504         if (prevDiff >= 0 && prevDiff >= firstDiff)
1505                 SelectDiff(prevDiff, true, false);
1506         else if (CDirDoc *pDirDoc = pd->GetDirDoc())
1507         {
1508                 if (pDirDoc->MoveableToPrevDiff())
1509                         pDirDoc->MoveToPrevDiff(pd);
1510         }
1511 }
1512
1513 /**
1514  * @brief Update "Previous diff" UI items
1515  */
1516 void CMergeEditView::OnUpdatePrevdiff(CCmdUI* pCmdUI)
1517 {
1518         CMergeDoc *pd = GetDocument();
1519         const DIFFRANGE * dfi = pd->m_diffList.FirstSignificantDiffRange();
1520         bool enabled;
1521
1522         if (dfi == nullptr)
1523         {
1524                 // There aren't any significant differences
1525                 enabled = false;
1526         }
1527         else
1528         {
1529                 // Enable if the end of the first significant difference is before caret
1530                 enabled = (GetCursorPos().y > (long)dfi->dend);
1531         }
1532
1533         if (!enabled && pd->GetDirDoc())
1534                 enabled = pd->GetDirDoc()->MoveableToPrevDiff();
1535
1536         pCmdUI->Enable(enabled);
1537 }
1538
1539 void CMergeEditView::OnNextConflict()
1540 {
1541         OnNext3wayDiff(THREEWAYDIFFTYPE_CONFLICT);
1542 }
1543
1544 /**
1545  * @brief Update "Next Conflict" UI items
1546  */
1547 void CMergeEditView::OnUpdateNextConflict(CCmdUI* pCmdUI)
1548 {
1549         OnUpdateNext3wayDiff(pCmdUI, THREEWAYDIFFTYPE_CONFLICT);
1550 }
1551
1552 void CMergeEditView::OnPrevConflict()
1553 {
1554         OnPrev3wayDiff(THREEWAYDIFFTYPE_CONFLICT);
1555 }
1556
1557 /**
1558  * @brief Update "Prev Conflict" UI items
1559  */
1560 void CMergeEditView::OnUpdatePrevConflict(CCmdUI* pCmdUI)
1561 {
1562         OnUpdatePrev3wayDiff(pCmdUI, THREEWAYDIFFTYPE_CONFLICT);
1563 }
1564
1565 /**
1566  * @brief Go to next 3-way diff and select it.
1567  */
1568 void CMergeEditView::OnNext3wayDiff(int nDiffType)
1569 {
1570         CMergeDoc *pd = GetDocument();
1571         int cnt = pd->m_ptBuf[0]->GetLineCount();
1572         if (cnt <= 0)
1573                 return;
1574
1575         // Returns -1 if no diff selected
1576         int curDiff = pd->GetCurrentDiff();
1577         if (curDiff != -1)
1578         {
1579                 // We're on a diff
1580                 int nextDiff = curDiff;
1581                 if (!IsDiffVisible(curDiff))
1582                 {
1583                         // Selected difference not visible, select next from cursor
1584                         int line = GetCursorPos().y;
1585                         // Make sure we aren't in the first line of the diff
1586                         ++line;
1587                         if (!IsValidTextPosY(CEPoint(0, line)))
1588                                 line = m_nTopLine;
1589                         nextDiff = pd->m_diffList.NextSignificant3wayDiffFromLine(line, nDiffType);
1590                 }
1591                 else
1592                 {
1593                         // Find out if there is a following significant diff
1594                         if (curDiff < pd->m_diffList.GetSize() - 1)
1595                         {
1596                                 nextDiff = pd->m_diffList.NextSignificant3wayDiff(curDiff, nDiffType);
1597                         }
1598                 }
1599                 if (nextDiff == -1)
1600                         nextDiff = curDiff;
1601
1602                 // nextDiff is the next one if there is one, else it is the one we're on
1603                 SelectDiff(nextDiff, true, false);
1604         }
1605         else
1606         {
1607                 // We don't have a selected difference,
1608                 // but cursor can be inside inactive diff
1609                 int line = GetCursorPos().y;
1610                 if (!IsValidTextPosY(CEPoint(0, line)))
1611                         line = m_nTopLine;
1612                 curDiff = pd->m_diffList.NextSignificant3wayDiffFromLine(line, nDiffType);
1613                 if (curDiff >= 0)
1614                         SelectDiff(curDiff, true, false);
1615         }
1616 }
1617
1618 /**
1619  * @brief Update "Next 3-way diff" UI items
1620  */
1621 void CMergeEditView::OnUpdateNext3wayDiff(CCmdUI* pCmdUI, int nDiffType)
1622 {
1623         CMergeDoc *pd = GetDocument();
1624
1625         if (pd->m_nBuffers < 3)
1626         {
1627                 pCmdUI->Enable(false);
1628                 return;
1629         }
1630
1631         const DIFFRANGE * dfi = pd->m_diffList.LastSignificant3wayDiffRange(nDiffType);
1632
1633         if (dfi == nullptr)
1634         {
1635                 // There aren't any significant differences
1636                 pCmdUI->Enable(false);
1637         }
1638         else
1639         {
1640                 // Enable if the beginning of the last significant difference is after caret
1641                 CEPoint pos = GetCursorPos();
1642                 pCmdUI->Enable(pos.y < (long)dfi->dbegin);
1643         }
1644 }
1645
1646 /**
1647  * @brief Go to previous 3-way diff and select it.
1648  */
1649 void CMergeEditView::OnPrev3wayDiff(int nDiffType)
1650 {
1651         CMergeDoc *pd = GetDocument();
1652
1653         int cnt = pd->m_ptBuf[0]->GetLineCount();
1654         if (cnt <= 0)
1655                 return;
1656
1657         // GetCurrentDiff() returns -1 if no diff selected
1658         int curDiff = pd->GetCurrentDiff();
1659         if (curDiff != -1)
1660         {
1661                 // We're on a diff
1662                 int prevDiff = curDiff;
1663                 if (!IsDiffVisible(curDiff))
1664                 {
1665                         // Selected difference not visible, select previous from cursor
1666                         int line = GetCursorPos().y;
1667                         // Make sure we aren't in the last line of the diff
1668                         --line;
1669                         if (!IsValidTextPosY(CEPoint(0, line)))
1670                                 line = m_nTopLine;
1671                         prevDiff = pd->m_diffList.PrevSignificant3wayDiffFromLine(line, nDiffType);
1672                 }
1673                 else
1674                 {
1675                         // Find out if there is a preceding significant diff
1676                         if (curDiff > 0)
1677                         {
1678                                 prevDiff = pd->m_diffList.PrevSignificant3wayDiff(curDiff, nDiffType);
1679                         }
1680                 }
1681                 if (prevDiff == -1)
1682                         prevDiff = curDiff;
1683
1684                 // prevDiff is the preceding one if there is one, else it is the one we're on
1685                 SelectDiff(prevDiff, true, false);
1686         }
1687         else
1688         {
1689                 // We don't have a selected difference,
1690                 // but cursor can be inside inactive diff
1691                 int line = GetCursorPos().y;
1692                 if (!IsValidTextPosY(CEPoint(0, line)))
1693                         line = m_nTopLine;
1694                 curDiff = pd->m_diffList.PrevSignificant3wayDiffFromLine(line, nDiffType);
1695                 if (curDiff >= 0)
1696                         SelectDiff(curDiff, true, false);
1697         }
1698 }
1699
1700 /**
1701  * @brief Update "Previous diff X and Y" UI items
1702  */
1703 void CMergeEditView::OnUpdatePrev3wayDiff(CCmdUI* pCmdUI, int nDiffType)
1704 {
1705         CMergeDoc *pd = GetDocument();
1706
1707         if (pd->m_nBuffers < 3)
1708         {
1709                 pCmdUI->Enable(false);
1710                 return;
1711         }
1712
1713         const DIFFRANGE * dfi = pd->m_diffList.FirstSignificant3wayDiffRange(nDiffType);
1714
1715         if (dfi == nullptr)
1716         {
1717                 // There aren't any significant differences
1718                 pCmdUI->Enable(false);
1719         }
1720         else
1721         {
1722                 // Enable if the end of the first significant difference is before caret
1723                 CEPoint pos = GetCursorPos();
1724                 pCmdUI->Enable(pos.y > (long)dfi->dend);
1725         }
1726 }
1727
1728 void CMergeEditView::OnNextdiffLM()
1729 {
1730         OnNext3wayDiff(THREEWAYDIFFTYPE_LEFTMIDDLE);
1731 }
1732
1733 void CMergeEditView::OnUpdateNextdiffLM(CCmdUI* pCmdUI)
1734 {
1735         OnUpdateNext3wayDiff(pCmdUI, THREEWAYDIFFTYPE_LEFTMIDDLE);
1736 }
1737
1738 void CMergeEditView::OnNextdiffLR()
1739 {
1740         OnNext3wayDiff(THREEWAYDIFFTYPE_LEFTRIGHT);
1741 }
1742
1743 void CMergeEditView::OnUpdateNextdiffLR(CCmdUI* pCmdUI)
1744 {
1745         OnUpdateNext3wayDiff(pCmdUI, THREEWAYDIFFTYPE_LEFTRIGHT);
1746 }
1747
1748 void CMergeEditView::OnNextdiffMR()
1749 {
1750         OnNext3wayDiff(THREEWAYDIFFTYPE_MIDDLERIGHT);
1751 }
1752
1753 void CMergeEditView::OnUpdateNextdiffMR(CCmdUI* pCmdUI)
1754 {
1755         OnUpdateNext3wayDiff(pCmdUI, THREEWAYDIFFTYPE_MIDDLERIGHT);
1756 }
1757
1758 void CMergeEditView::OnNextdiffLO()
1759 {
1760         OnNext3wayDiff(THREEWAYDIFFTYPE_LEFTONLY);
1761 }
1762
1763 void CMergeEditView::OnUpdateNextdiffLO(CCmdUI* pCmdUI)
1764 {
1765         OnUpdateNext3wayDiff(pCmdUI, THREEWAYDIFFTYPE_LEFTONLY);
1766 }
1767
1768 void CMergeEditView::OnNextdiffMO()
1769 {
1770         OnNext3wayDiff(THREEWAYDIFFTYPE_MIDDLEONLY);
1771 }
1772
1773 void CMergeEditView::OnUpdateNextdiffMO(CCmdUI* pCmdUI)
1774 {
1775         OnUpdateNext3wayDiff(pCmdUI, THREEWAYDIFFTYPE_MIDDLEONLY);
1776 }
1777
1778 void CMergeEditView::OnNextdiffRO()
1779 {
1780         OnNext3wayDiff(THREEWAYDIFFTYPE_RIGHTONLY);
1781 }
1782
1783 void CMergeEditView::OnUpdateNextdiffRO(CCmdUI* pCmdUI)
1784 {
1785         OnUpdateNext3wayDiff(pCmdUI, THREEWAYDIFFTYPE_RIGHTONLY);
1786 }
1787
1788 void CMergeEditView::OnPrevdiffLM()
1789 {
1790         OnPrev3wayDiff(THREEWAYDIFFTYPE_LEFTMIDDLE);
1791 }
1792
1793 void CMergeEditView::OnUpdatePrevdiffLM(CCmdUI* pCmdUI)
1794 {
1795         OnUpdatePrev3wayDiff(pCmdUI, THREEWAYDIFFTYPE_LEFTMIDDLE);
1796 }
1797
1798 void CMergeEditView::OnPrevdiffLR()
1799 {
1800         OnPrev3wayDiff(THREEWAYDIFFTYPE_LEFTRIGHT);
1801 }
1802
1803 void CMergeEditView::OnUpdatePrevdiffLR(CCmdUI* pCmdUI)
1804 {
1805         OnUpdatePrev3wayDiff(pCmdUI, THREEWAYDIFFTYPE_LEFTRIGHT);
1806 }
1807
1808 void CMergeEditView::OnPrevdiffMR()
1809 {
1810         OnPrev3wayDiff(THREEWAYDIFFTYPE_MIDDLERIGHT);
1811 }
1812
1813 void CMergeEditView::OnUpdatePrevdiffMR(CCmdUI* pCmdUI)
1814 {
1815         OnUpdatePrev3wayDiff(pCmdUI, THREEWAYDIFFTYPE_MIDDLERIGHT);
1816 }
1817
1818 void CMergeEditView::OnPrevdiffLO()
1819 {
1820         OnPrev3wayDiff(THREEWAYDIFFTYPE_LEFTONLY);
1821 }
1822
1823 void CMergeEditView::OnUpdatePrevdiffLO(CCmdUI* pCmdUI)
1824 {
1825         OnUpdatePrev3wayDiff(pCmdUI, THREEWAYDIFFTYPE_LEFTONLY);
1826 }
1827
1828 void CMergeEditView::OnPrevdiffMO()
1829 {
1830         OnPrev3wayDiff(THREEWAYDIFFTYPE_MIDDLEONLY);
1831 }
1832
1833 void CMergeEditView::OnUpdatePrevdiffMO(CCmdUI* pCmdUI)
1834 {
1835         OnUpdatePrev3wayDiff(pCmdUI, THREEWAYDIFFTYPE_MIDDLEONLY);
1836 }
1837
1838 void CMergeEditView::OnPrevdiffRO()
1839 {
1840         OnPrev3wayDiff(THREEWAYDIFFTYPE_RIGHTONLY);
1841 }
1842
1843 void CMergeEditView::OnUpdatePrevdiffRO(CCmdUI* pCmdUI)
1844 {
1845         OnUpdatePrev3wayDiff(pCmdUI, THREEWAYDIFFTYPE_RIGHTONLY);
1846 }
1847
1848 /**
1849  * @brief Clear selection
1850  */
1851 void CMergeEditView::SelectNone()
1852 {
1853         SetSelection (GetCursorPos(), GetCursorPos());
1854         UpdateCaret();
1855 }
1856
1857 /**
1858  * @brief Check if line is inside currently selected diff
1859  * @param [in] nLine 0-based linenumber in view
1860  * @sa CMergeDoc::GetCurrentDiff()
1861  * @sa CMergeDoc::LineInDiff()
1862  */
1863 bool CMergeEditView::IsLineInCurrentDiff(int nLine) const
1864 {
1865         // Check validity of nLine
1866 #ifdef _DEBUG
1867         if (nLine < 0)
1868                 _RPTF1(_CRT_ERROR, "Linenumber is negative (%d)!", nLine);
1869         int nLineCount = LocateTextBuffer()->GetLineCount();
1870         if (nLine >= nLineCount)
1871                 _RPTF2(_CRT_ERROR, "Linenumber > linecount (%d>%d)!", nLine, nLineCount);
1872 #endif
1873
1874         const CMergeDoc *pd = GetDocument();
1875         int curDiff = pd->GetCurrentDiff();
1876         if (curDiff == -1)
1877                 return false;
1878         return pd->m_diffList.LineInDiff(nLine, curDiff);
1879 }
1880
1881 /**
1882  * @brief Called when mouse left-button double-clicked
1883  *
1884  * Double-clicking mouse inside diff selects that diff
1885  */
1886 void CMergeEditView::OnLButtonDblClk(UINT nFlags, CPoint point)
1887 {
1888         CMergeDoc *pd = GetDocument();
1889         CEPoint pos = GetCursorPos();
1890
1891         int diff = pd->m_diffList.LineToDiff(pos.y);
1892         if (diff != -1 && pd->m_diffList.IsDiffSignificant(diff))
1893                 SelectDiff(diff, false, false);
1894
1895         CCrystalEditViewEx::OnLButtonDblClk(nFlags, point);
1896 }
1897
1898 /**
1899  * @brief Called when mouse left button is released.
1900  *
1901  * If button is released outside diffs, current diff
1902  * is deselected.
1903  */
1904 void CMergeEditView::OnLButtonUp(UINT nFlags, CPoint point)
1905 {
1906         CCrystalEditViewEx::OnLButtonUp(nFlags, point);
1907         DeselectDiffIfCursorNotInCurrentDiff();
1908 }
1909
1910 /**
1911  * @brief Called when mouse right button is pressed.
1912  *
1913  * If right button is pressed outside diffs, current diff
1914  * is deselected.
1915  */
1916 void CMergeEditView::OnRButtonDown(UINT nFlags, CPoint point)
1917 {
1918         CCrystalEditViewEx::OnRButtonDown(nFlags, point);
1919         DeselectDiffIfCursorNotInCurrentDiff();
1920 }
1921
1922 void CMergeEditView::OnX2Y(int srcPane, int dstPane, bool selectedLineOnly)
1923 {
1924         // Check that right side is not readonly
1925         if (IsReadOnly(dstPane))
1926                 return;
1927
1928         CMergeDoc *pDoc = GetDocument();
1929         int currentDiff = pDoc->GetCurrentDiff();
1930
1931         if (currentDiff == -1)
1932         {
1933                 // No selected diff
1934                 // If cursor is inside diff get number of that diff
1935                 if (m_bCurrentLineIsDiff)
1936                 {
1937                         CEPoint pt = GetCursorPos();
1938                         currentDiff = pDoc->m_diffList.LineToDiff(pt.y);
1939                 }
1940         }
1941
1942         auto [ptStart, ptEnd] = GetSelection();
1943         if (IsSelection() || pDoc->EqualCurrentWordDiff(srcPane, ptStart, ptEnd))
1944         {
1945                 if (!m_bRectangularSelection)
1946                 {
1947                         if (selectedLineOnly)
1948                         {
1949                                 int firstDiff, lastDiff;
1950                                 GetSelectedDiffs(firstDiff, lastDiff);
1951                                 if (firstDiff != -1 && lastDiff != -1)
1952                                 {
1953                                         CWaitCursor waitstatus;
1954                                         pDoc->CopyMultiplePartialList(srcPane, dstPane, firstDiff, lastDiff, ptStart.y, ptEnd.y);
1955                                 }
1956                         }
1957                         else
1958                         {
1959                                 int firstDiff, lastDiff, firstWordDiff, lastWordDiff;
1960                                 GetFullySelectedDiffs(firstDiff, lastDiff, firstWordDiff, lastWordDiff);
1961                                 if (firstDiff != -1 && lastDiff != -1)
1962                                 {
1963                                         CWaitCursor waitstatus;
1964                                         
1965                                         // Setting CopyFullLine (OPT_COPY_FULL_LINE)
1966                                         // restore old copy behaviour (always copy "full line" instead of "selected text only"), with a hidden option
1967                                         if (GetOptionsMgr()->GetBool(OPT_COPY_FULL_LINE))
1968                                         {
1969                                                 // old behaviour: copy full line
1970                                                 pDoc->CopyMultipleList(srcPane, dstPane, firstDiff, lastDiff);
1971                                         }
1972                                         else
1973                                         {
1974                                                 // new behaviour: copy selected text only
1975                                                 pDoc->CopyMultipleList(srcPane, dstPane, firstDiff, lastDiff, firstWordDiff, lastWordDiff);
1976                                         }
1977                                 }
1978                         }
1979                 }
1980                 else
1981                 {
1982                         CWaitCursor waitstatus;
1983                         auto wordDiffs = GetColumnSelectedWordDiffIndice();
1984                         int i = 0;
1985                         std::for_each(wordDiffs.rbegin(), wordDiffs.rend(), [&](auto& it) {
1986                                 pDoc->WordListCopy(srcPane, dstPane, it.first, it.second[0], it.second[it.second.size() - 1], &it.second, i != 0, i == 0);
1987                                 ++i;
1988                         });
1989                 }
1990         }
1991         else if (currentDiff != -1 && pDoc->m_diffList.IsDiffSignificant(currentDiff))
1992         {
1993                 if (selectedLineOnly)
1994                 {
1995                         CWaitCursor waitstatus;
1996                         pDoc->PartialListCopy(srcPane, dstPane, currentDiff, ptStart.y, ptEnd.y);
1997                 }
1998                 else
1999                 {
2000                         CWaitCursor waitstatus;
2001                         pDoc->ListCopy(srcPane, dstPane, currentDiff);
2002                 }
2003         }
2004 }
2005
2006 void CMergeEditView::OnUpdateX2Y(CCmdUI* pCmdUI)
2007 {
2008         auto [srcPane, dstPane] = CMergeFrameCommon::MenuIDtoXY(pCmdUI->m_nID, m_nThisPane, GetDocument()->m_nBuffers);
2009         if (GetDocument()->m_nBuffers > 2)
2010                 CMergeFrameCommon::ChangeMergeMenuText(srcPane, dstPane, pCmdUI);
2011         if (srcPane < 0 || dstPane < 0)
2012         {
2013                 pCmdUI->Enable(false);
2014                 return;
2015         }
2016         // Check that right side is not readonly
2017         if (!IsReadOnly(dstPane))
2018         {
2019                 // If one or more diffs inside selection OR
2020                 // there is an active diff OR
2021                 // cursor is inside diff
2022                 auto [ptStart, ptEnd] = GetSelection();
2023                 if (IsSelection() || GetDocument()->EqualCurrentWordDiff(m_nThisPane, ptStart, ptEnd))
2024                 {
2025                         int firstDiff, lastDiff, firstWordDiff, lastWordDiff;
2026                         GetFullySelectedDiffs(firstDiff, lastDiff, firstWordDiff, lastWordDiff);
2027
2028                         pCmdUI->Enable((firstDiff != -1 && lastDiff != -1) || (firstWordDiff != -1 && lastWordDiff != -1));
2029                 }
2030                 else
2031                 {
2032                         const int currDiff = GetDocument()->GetCurrentDiff();
2033                         pCmdUI->Enable(m_bCurrentLineIsDiff || (currDiff != -1 && GetDocument()->m_diffList.IsDiffSignificant(currDiff)));
2034                 }
2035         }
2036         else
2037                 pCmdUI->Enable(false);
2038 }
2039
2040 void CMergeEditView::OnCopyX2Y(UINT nID)
2041 {
2042         auto [srcPane, dstPane] = CMergeFrameCommon::MenuIDtoXY(nID, m_nThisPane, GetDocument()->m_nBuffers);
2043         if (srcPane >= 0 && dstPane >= 0)
2044                 OnX2Y(srcPane, dstPane);
2045 }
2046
2047 void CMergeEditView::OnCopyLinesX2Y(UINT nID)
2048 {
2049         auto [srcPane, dstPane] = CMergeFrameCommon::MenuIDtoXY(nID, m_nThisPane, GetDocument()->m_nBuffers);
2050         if (srcPane >= 0 && dstPane >= 0)
2051                 OnX2Y(srcPane, dstPane, true);
2052 }
2053
2054 /**
2055  * @brief Copy diff from left pane to right pane
2056  *
2057  * Difference is copied from left to right when
2058  * - difference is selected
2059  * - difference is inside selection (allows merging multiple differences).
2060  * - cursor is inside diff
2061  *
2062  * If there is selected diff outside selection, we copy selected
2063  * difference only.
2064  */
2065 void CMergeEditView::OnL2r()
2066 {
2067         OnCopyX2Y(ID_L2R);
2068 }
2069
2070 /**
2071  * @brief Called when "Copy to Right" item is updated
2072  */
2073 void CMergeEditView::OnUpdateL2r(CCmdUI* pCmdUI)
2074 {
2075         OnUpdateX2Y(pCmdUI);
2076 }
2077
2078 void CMergeEditView::OnLinesL2r()
2079 {
2080         OnCopyLinesX2Y(ID_LINES_L2R);
2081 }
2082
2083 void CMergeEditView::OnUpdateLinesL2r(CCmdUI* pCmdUI)
2084 {
2085         OnUpdateX2Y(pCmdUI);
2086 }
2087
2088 /**
2089  * @brief Copy diff from right pane to left pane
2090  *
2091  * Difference is copied from left to right when
2092  * - difference is selected
2093  * - difference is inside selection (allows merging multiple differences).
2094  * - cursor is inside diff
2095  *
2096  * If there is selected diff outside selection, we copy selected
2097  * difference only.
2098  */
2099 void CMergeEditView::OnR2l()
2100 {
2101         OnCopyX2Y(ID_R2L);
2102 }
2103
2104 /**
2105  * @brief Called when "Copy to Left" item is updated
2106  */
2107 void CMergeEditView::OnUpdateR2l(CCmdUI* pCmdUI)
2108 {
2109         OnUpdateX2Y(pCmdUI);
2110 }
2111
2112 void CMergeEditView::OnLinesR2l()
2113 {
2114         OnCopyLinesX2Y(ID_LINES_R2L);
2115 }
2116
2117 void CMergeEditView::OnUpdateLinesR2l(CCmdUI* pCmdUI)
2118 {
2119         OnUpdateX2Y(pCmdUI);
2120 }
2121
2122 void CMergeEditView::OnCopyFromLeft()
2123 {
2124         OnCopyX2Y(ID_COPY_FROM_LEFT);
2125 }
2126
2127 void CMergeEditView::OnUpdateCopyFromLeft(CCmdUI* pCmdUI)
2128 {
2129         OnUpdateX2Y(pCmdUI);
2130 }
2131
2132 void CMergeEditView::OnCopyLinesFromLeft()
2133 {
2134         OnCopyLinesX2Y(ID_COPY_LINES_FROM_LEFT);
2135 }
2136
2137 void CMergeEditView::OnUpdateCopyLinesFromLeft(CCmdUI* pCmdUI)
2138 {
2139         OnUpdateX2Y(pCmdUI);
2140 }
2141
2142 void CMergeEditView::OnCopyFromRight()
2143 {
2144         OnCopyX2Y(ID_COPY_FROM_RIGHT);
2145 }
2146
2147 void CMergeEditView::OnUpdateCopyFromRight(CCmdUI* pCmdUI)
2148 {
2149         OnUpdateX2Y(pCmdUI);
2150 }
2151
2152 void CMergeEditView::OnCopyLinesFromRight()
2153 {
2154         OnCopyLinesX2Y(ID_COPY_LINES_FROM_RIGHT);
2155 }
2156
2157 void CMergeEditView::OnUpdateCopyLinesFromRight(CCmdUI* pCmdUI)
2158 {
2159         OnUpdateX2Y(pCmdUI);
2160 }
2161
2162 /**
2163  * @brief Copy all diffs from right pane to left pane
2164  */
2165 void CMergeEditView::OnAllLeft()
2166 {
2167         // Check that left side is not readonly
2168         auto [srcPane, dstPane] = CMergeFrameCommon::MenuIDtoXY(ID_ALL_LEFT, m_nThisPane, GetDocument()->m_nBuffers);
2169         if (IsReadOnly(dstPane))
2170                 return;
2171         CWaitCursor waitstatus;
2172
2173         GetDocument()->CopyAllList(srcPane, dstPane);
2174 }
2175
2176 /**
2177  * @brief Called when "Copy all to left" item is updated
2178  */
2179 void CMergeEditView::OnUpdateAllLeft(CCmdUI* pCmdUI)
2180 {
2181         // Check that left side is not readonly
2182         [[maybe_unused]] auto [srcPane, dstPane] = CMergeFrameCommon::MenuIDtoXY(pCmdUI->m_nID, m_nThisPane, GetDocument()->m_nBuffers);
2183         if (!IsReadOnly(dstPane))
2184                 pCmdUI->Enable(GetDocument()->m_diffList.HasSignificantDiffs());
2185         else
2186                 pCmdUI->Enable(false);
2187         if (GetDocument()->m_nBuffers > 2)
2188                 CMergeFrameCommon::ChangeMergeMenuText(m_nThisPane, dstPane, pCmdUI);
2189 }
2190
2191 /**
2192  * @brief Copy all diffs from left pane to right pane
2193  */
2194 void CMergeEditView::OnAllRight()
2195 {
2196         // Check that right side is not readonly
2197         auto [srcPane, dstPane] = CMergeFrameCommon::MenuIDtoXY(ID_ALL_RIGHT, m_nThisPane, GetDocument()->m_nBuffers);
2198         if (IsReadOnly(dstPane))
2199                 return;
2200
2201         CWaitCursor waitstatus;
2202
2203         GetDocument()->CopyAllList(srcPane, dstPane);
2204 }
2205
2206 /**
2207  * @brief Called when "Copy all to right" item is updated
2208  */
2209 void CMergeEditView::OnUpdateAllRight(CCmdUI* pCmdUI)
2210 {
2211         // Check that right side is not readonly
2212         [[maybe_unused]] auto [srcPane, dstPane] = CMergeFrameCommon::MenuIDtoXY(pCmdUI->m_nID, m_nThisPane, GetDocument()->m_nBuffers);
2213         if (!IsReadOnly(dstPane))
2214                 pCmdUI->Enable(GetDocument()->m_diffList.HasSignificantDiffs());
2215         else
2216                 pCmdUI->Enable(false);
2217         if (GetDocument()->m_nBuffers > 2)
2218                 CMergeFrameCommon::ChangeMergeMenuText(m_nThisPane, dstPane, pCmdUI);
2219 }
2220
2221 /**
2222  * @brief Do Auto merge
2223  */
2224 void CMergeEditView::OnAutoMerge()
2225 {
2226         // Check current pane is not readonly
2227         if (GetDocument()->IsModified() || GetDocument()->GetAutoMerged() || !QueryEditable())
2228                 return;
2229
2230         CWaitCursor waitstatus;
2231
2232         GetDocument()->DoAutoMerge(m_nThisPane);
2233 }
2234
2235 /**
2236  * @brief Called when "Auto Merge" item is updated
2237  */
2238 void CMergeEditView::OnUpdateAutoMerge(CCmdUI* pCmdUI)
2239 {
2240         pCmdUI->Enable(GetDocument()->m_nBuffers == 3 && 
2241                 !GetDocument()->IsModified() && 
2242                 !GetDocument()->GetAutoMerged() && 
2243                 QueryEditable());
2244 }
2245
2246 /**
2247  * @brief Add synchronization point
2248  */
2249 void CMergeEditView::OnAddSyncPoint()
2250 {
2251         GetDocument()->AddSyncPoint();
2252 }
2253
2254 /**
2255  * @brief Clear synchronization points
2256  */
2257 void CMergeEditView::OnClearSyncPoints()
2258 {
2259         GetDocument()->ClearSyncPoints();
2260 }
2261
2262 /**
2263  * @brief Called when "Clear Synchronization Points" item is updated
2264  */
2265 void CMergeEditView::OnUpdateClearSyncPoints(CCmdUI* pCmdUI)
2266 {
2267         pCmdUI->Enable(GetDocument()->HasSyncPoints());
2268 }
2269
2270 /**
2271  * @brief This function is called before other edit events.
2272  * @param [in] nAction Edit operation to do
2273  * @param [in] pszText Text to insert, delete etc
2274  * @sa CCrystalEditView::OnEditOperation()
2275  * @todo More edit-events for rescan delaying?
2276  */
2277 void CMergeEditView::OnEditOperation(int nAction, const tchar_t* pszText, size_t cchText)
2278 {
2279         if (!QueryEditable())
2280         {
2281                 // We must not arrive here, and assert helps detect troubles
2282                 ASSERT(false);
2283                 return;
2284         }
2285
2286         CMergeDoc* pDoc = GetDocument();
2287         pDoc->SetEditedAfterRescan(m_nThisPane);
2288
2289         // simple hook for multiplex undo operations
2290         // deleted by jtuc 2003-06-28
2291         // now AddUndoRecords does it (so we don't create entry for OnEditOperation with no Undo data in m_pTextBuffer)
2292         /*if(dynamic_cast<CMergeDoc::CDiffTextBuffer*>(m_pTextBuffer)->curUndoGroup())
2293         {
2294                 pDoc->undoTgt.erase(pDoc->curUndo, pDoc->undoTgt.end());
2295                 pDoc->undoTgt.push_back(this);
2296                 pDoc->curUndo = pDoc->undoTgt.end();
2297         }*/
2298
2299         // perform original function
2300         CCrystalEditViewEx::OnEditOperation(nAction, pszText, cchText);
2301
2302         // augment with additional operations
2303
2304         // Change header to inform about changed doc
2305         pDoc->UpdateHeaderPath(m_nThisPane);
2306
2307         // If automatic rescan enabled, rescan after edit events
2308         if (pDoc->GetAutomaticRescan())
2309         {
2310                 // keep document up to date     
2311                 // (Re)start timer to rescan only when user edits text
2312                 // If timer starting fails, rescan immediately
2313                 if (nAction == CE_ACTION_TYPING ||
2314                         nAction == CE_ACTION_REPLACE ||
2315                         nAction == CE_ACTION_BACKSPACE ||
2316                         nAction == CE_ACTION_INDENT ||
2317                         nAction == CE_ACTION_PASTE ||
2318                         nAction == CE_ACTION_DELSEL ||
2319                         nAction == CE_ACTION_DELETE ||
2320                         nAction == CE_ACTION_CUT)
2321                 {
2322                         if (!SetTimer(IDT_RESCAN, RESCAN_TIMEOUT, nullptr))
2323                                 pDoc->FlushAndRescan();
2324                 }
2325                 else
2326                         pDoc->FlushAndRescan();
2327         }
2328         else
2329         {
2330                 if (m_bWordWrap)
2331                 {
2332                         // Update other pane for sync line.
2333                         for (int nPane = 0; nPane < pDoc->m_nBuffers; nPane++)
2334                         {
2335                                 if (nPane == m_nThisPane)
2336                                         continue;
2337                                 CCrystalEditView *pView = GetGroupView(nPane);
2338                                 if (pView != nullptr)
2339                                         pView->Invalidate();
2340                         }
2341                 }
2342         }
2343 }
2344
2345 /**
2346  * @brief Redo last action
2347  */
2348 void CMergeEditView::OnEditRedo()
2349 {
2350         CWaitCursor waitstatus;
2351         CMergeDoc* pDoc = GetDocument();
2352         CMergeEditView *tgt = pDoc->GetView(m_nThisGroup, *(pDoc->curUndo));
2353         if(tgt==this)
2354         {
2355                 if (!QueryEditable())
2356                         return;
2357
2358                 GetParentFrame()->SetActiveView(this, true);
2359                 if(CCrystalEditViewEx::DoEditRedo())
2360                 {
2361                         ++pDoc->curUndo;
2362                         pDoc->UpdateHeaderPath(m_nThisPane);
2363                         pDoc->FlushAndRescan();
2364                 }
2365         }
2366         else
2367         {
2368                 tgt->SendMessage(WM_COMMAND, ID_EDIT_REDO);
2369         }
2370 }
2371
2372 /**
2373  * @brief Called when "Redo" item is updated
2374  */
2375 void CMergeEditView::OnUpdateEditRedo(CCmdUI* pCmdUI)
2376 {
2377         CMergeDoc* pDoc = GetDocument();
2378         if (pDoc->curUndo!=pDoc->undoTgt.end())
2379         {
2380                 CMergeEditView *tgt = pDoc->GetView(m_nThisGroup, *(pDoc->curUndo));
2381                 pCmdUI->Enable( !IsReadOnly(tgt->m_nThisPane));
2382         }
2383         else
2384                 pCmdUI->Enable(false);
2385 }
2386
2387 void CMergeEditView::OnUpdate(CView* pSender, LPARAM lHint, CObject* pHint)
2388 {
2389         CCrystalEditViewEx::OnUpdate(pSender, lHint, pHint);
2390 }
2391
2392 /**
2393  * @brief Scrolls to current diff and/or selects diff text
2394  * @param [in] bScroll If true scroll diff to view
2395  * @param [in] bSelectText If true select diff text
2396  * @note If bScroll and bSelectText are false, this does nothing!
2397  * @todo This shouldn't be called when no diff is selected, so
2398  * somebody could try to ASSERT(nDiff > -1)...
2399  */
2400 void CMergeEditView::ShowDiff(bool bScroll, bool bSelectText)
2401 {
2402         CMergeDoc *pd = GetDocument();
2403         const int nDiff = pd->GetCurrentDiff();
2404
2405         // Try to trap some errors
2406         if (nDiff >= pd->m_diffList.GetSize())
2407                 _RPTF2(_CRT_ERROR, "Selected diff > diffcount (%d > %d)!",
2408                         nDiff, pd->m_diffList.GetSize());
2409
2410         if (nDiff >= 0 && nDiff < pd->m_diffList.GetSize())
2411         {
2412                 CEPoint ptStart, ptEnd;
2413                 DIFFRANGE curDiff;
2414                 pd->m_diffList.GetDiff(nDiff, curDiff);
2415
2416                 ptStart.x = 0;
2417                 ptStart.y = curDiff.dbegin;
2418                 ptEnd.x = 0;
2419                 ptEnd.y = curDiff.dend;
2420
2421                 if (bScroll && !m_bDetailView)
2422                 {
2423                         if (!IsDiffVisible(curDiff, CONTEXT_LINES_BELOW))
2424                         {
2425                                 // Difference is not visible, scroll it so that max amount of
2426                                 // scrolling is done while keeping the diff in screen. So if
2427                                 // scrolling is downwards, scroll the diff to as up in screen
2428                                 // as possible. This usually brings next diff to the screen
2429                                 // and we don't need to scroll into it.
2430                                 int nLine = GetSubLineIndex(ptStart.y);
2431                                 if (nLine > CONTEXT_LINES_ABOVE)
2432                                 {
2433                                         nLine -= CONTEXT_LINES_ABOVE;
2434                                 }
2435                                 GetGroupView(m_nThisPane)->ScrollToSubLine(nLine);
2436                                 for (int nPane = 0; nPane < pd->m_nBuffers; nPane++)
2437                                 {
2438                                         if (nPane != m_nThisPane)
2439                                                 GetGroupView(nPane)->ScrollToSubLine(nLine);
2440                                 }
2441                         }
2442
2443                         vector<WordDiff> worddiffs;
2444                         if (GetOptionsMgr()->GetBool(OPT_SCROLL_TO_FIRST_INLINE_DIFF))
2445                                 worddiffs = pd->GetWordDiffArrayInDiffBlock(nDiff);
2446                         CEPoint pt = worddiffs.size() > 0 ?
2447                                 CEPoint{ worddiffs[0].begin[m_nThisPane], worddiffs[0].beginline[m_nThisPane] } :
2448                                 ptStart;
2449                         GetGroupView(m_nThisPane)->SetCursorPos(pt);
2450                         GetGroupView(m_nThisPane)->SetAnchor(pt);
2451                         GetGroupView(m_nThisPane)->SetSelection(pt, pt);
2452                         GetGroupView(m_nThisPane)->EnsureVisible(pt);
2453                         for (int nPane = 0; nPane < pd->m_nBuffers; nPane++)
2454                         {
2455                                 if (nPane != m_nThisPane)
2456                                 {
2457                                         if (worddiffs.size() > 0)
2458                                         {
2459                                                 pt.x = worddiffs[0].begin[nPane];
2460                                                 pt.y = worddiffs[0].beginline[nPane];
2461                                         }
2462                                         GetGroupView(nPane)->SetCursorPos(pt);
2463                                         GetGroupView(nPane)->SetAnchor(pt);
2464                                         GetGroupView(nPane)->SetSelection(pt, pt);
2465                                 }
2466                         }
2467                 }
2468
2469                 if (bSelectText)
2470                 {
2471                         ptEnd.x = GetLineLength(ptEnd.y);
2472                         SetSelection(ptStart, ptEnd);
2473                         UpdateCaret();
2474                 }
2475                 else
2476                         Invalidate();
2477         }
2478 }
2479
2480
2481 void CMergeEditView::OnTimer(UINT_PTR nIDEvent)
2482 {
2483         // Maybe we want theApp::OnIdle to proceed before processing a timer message
2484         // ...but for this the queue must be empty
2485         // The timer message is a low priority message but the queue is maybe not yet empty
2486         // So we set a flag, wait for OnIdle to proceed, then come back here...
2487         // We come back here with a IDLE_TIMER OnTimer message (send with SendMessage
2488         // not with SetTimer so there is no delay)
2489
2490         // IDT_RESCAN was posted because the app wanted to do a flushAndRescan with some delay
2491
2492         // IDLE_TIMER is the false timer used to come back here after OnIdle
2493         // fTimerWaitingForIdle is a bool to store the commands waiting for idle
2494         // (one normal timer = one flag = one command)
2495
2496         if (nIDEvent == IDT_RESCAN)
2497         {
2498                 KillTimer(IDT_RESCAN);
2499                 fTimerWaitingForIdle |= FLAG_RESCAN_WAITS_FOR_IDLE;
2500                 // notify the app to come back after OnIdle
2501                 theApp.SetNeedIdleTimer();
2502         }
2503
2504         if (nIDEvent == IDLE_TIMER)
2505         {
2506                 // not a real timer, just come back after OnIdle
2507                 // look to flags to know what to do
2508                 if (fTimerWaitingForIdle & FLAG_RESCAN_WAITS_FOR_IDLE)
2509                         GetDocument()->RescanIfNeeded(RESCAN_TIMEOUT/1000);
2510                 fTimerWaitingForIdle = 0;
2511         }
2512
2513         CCrystalEditViewEx::OnTimer(nIDEvent);
2514 }
2515
2516 /**
2517  * @brief Returns if buffer is read-only
2518  * @note This has no any relation to file being read-only!
2519  */
2520 bool CMergeEditView::IsReadOnly(int pane) const
2521 {
2522         return m_bDetailView ? true : (GetDocument()->m_ptBuf[pane]->GetReadOnly() != false);
2523 }
2524
2525 /**
2526  * @brief Handle some keys when in merging mode
2527  */
2528 bool CMergeEditView::MergeModeKeyDown(MSG* pMsg)
2529 {
2530         bool bHandled = false;
2531
2532         // Allow default text selection when SHIFT pressed
2533         if (::GetAsyncKeyState(VK_SHIFT))
2534                 return false;
2535
2536         // Allow default editor functions when CTRL pressed
2537         if (::GetAsyncKeyState(VK_CONTROL))
2538                 return false;
2539
2540         // If we are in merging mode (merge with cursor keys)
2541         // handle some keys here
2542         switch (pMsg->wParam)
2543         {
2544         case VK_LEFT:
2545                 OnR2l();
2546                 bHandled = true;
2547                 break;
2548
2549         case VK_RIGHT:
2550                 OnL2r();
2551                 bHandled = true;
2552                 break;
2553
2554         case VK_UP:
2555                 PostMessage(WM_COMMAND, ID_PREVDIFF);
2556                 bHandled = true;
2557                 break;
2558
2559         case VK_DOWN:
2560                 PostMessage(WM_COMMAND, ID_NEXTDIFF);
2561                 bHandled = true;
2562                 break;
2563         }
2564
2565         return bHandled;
2566 }
2567
2568 /**
2569  * @brief Called before messages are translated.
2570  *
2571  * Checks if ESC key was pressed, saves and closes doc.
2572  * Also if in merge mode traps cursor keys.
2573  */
2574 BOOL CMergeEditView::PreTranslateMessage(MSG* pMsg)
2575 {
2576         if (pMsg->message == WM_KEYDOWN)
2577         {
2578                 // If we are in merging mode (merge with cursor keys)
2579                 // handle some keys here
2580                 if (theApp.GetMergingMode())
2581                 {
2582                         bool bHandled = MergeModeKeyDown(pMsg);
2583                         if (bHandled)
2584                                 return false;
2585                 }
2586
2587                 // Close window if user has allowed it from options
2588                 if (pMsg->wParam == VK_ESCAPE)
2589                 {
2590                         int nCloseWithEsc = GetOptionsMgr()->GetInt(OPT_CLOSE_WITH_ESC);
2591                         if (nCloseWithEsc != 0)
2592                                 GetParentFrame()->PostMessage(WM_CLOSE, 0, 0);
2593                         return false;
2594                 }
2595         }
2596
2597         return CCrystalEditViewEx::PreTranslateMessage(pMsg);
2598 }
2599
2600 /// Store interface we use to display status line info
2601 void CMergeEditView::SetStatusInterface(IMergeEditStatus * piMergeEditStatus)
2602 {
2603         ASSERT(m_piMergeEditStatus == nullptr);
2604         m_piMergeEditStatus = piMergeEditStatus;
2605 }
2606
2607 /**
2608  * @brief Update status bar contents.
2609  */
2610 void CMergeEditView::UpdateStatusbar()
2611 {
2612         OnUpdateCaret();
2613 }
2614
2615 /**
2616  * @brief Update statusbar info, Override from CCrystalTextView
2617  * @note we tab-expand column, but we don't tab-expand char count,
2618  * since we want to show how many chars there are and tab is just one
2619  * character although it expands to several spaces.
2620  */
2621 void CMergeEditView::OnUpdateCaret()
2622 {
2623         if (m_bCursorHidden || m_piMergeEditStatus == nullptr || !IsTextBufferInitialized())
2624                 return;
2625
2626         CEPoint cursorPos = GetCursorPos();
2627         int nScreenLine = cursorPos.y;
2628         const int nRealLine = ComputeRealLine(nScreenLine);
2629         CString sLine;
2630         int chars = -1;
2631         CString sEol;
2632         int column = -1;
2633         int columns = -1;
2634         int curChar = -1;
2635         auto [selectedLines, selectedChars] = GetSelectedLineAndCharacterCount();
2636         DWORD dwLineFlags = 0;
2637
2638         dwLineFlags = m_pTextBuffer->GetLineFlags(nScreenLine);
2639         // Is this a ghost line ?
2640         if (dwLineFlags & LF_GHOST)
2641         {
2642                 // Ghost lines display eg "Line 12-13"
2643                 sLine.Format(_T("%d-%d"), nRealLine, nRealLine+1);
2644                 sEol = _T("hidden");
2645         }
2646         else
2647         {
2648                 // Regular lines display eg "Line 13 Characters: 25 EOL: CRLF"
2649                 sLine.Format(_T("%d"), nRealLine+1);
2650                 curChar = cursorPos.x + 1;
2651                 chars = GetLineLength(nScreenLine);
2652                 column = CalculateActualOffset(nScreenLine, cursorPos.x, true) + 1;
2653                 columns = CalculateActualOffset(nScreenLine, chars, true) + 1;
2654                 chars++;
2655                 if (GetOptionsMgr()->GetBool(OPT_ALLOW_MIXED_EOL) ||
2656                                 GetDocument()->IsMixedEOL(m_nThisPane))
2657                 {
2658                         sEol = GetTextBufferEol(nScreenLine);
2659                 }
2660                 else
2661                         sEol = _T("hidden");
2662         }
2663         m_piMergeEditStatus->SetLineInfo(sLine, column, columns,
2664                 curChar, chars, selectedLines, selectedChars,
2665                 sEol, GetDocument()->m_ptBuf[m_nThisPane]->getCodepage(), GetDocument()->m_ptBuf[m_nThisPane]->getHasBom());
2666
2667         // Is cursor inside difference?
2668         if (dwLineFlags & LF_NONTRIVIAL_DIFF)
2669                 m_bCurrentLineIsDiff = true;
2670         else
2671                 m_bCurrentLineIsDiff = false;
2672
2673         CWnd* pWnd = GetFocus();
2674         if (!m_bDetailView || (pWnd && pWnd->m_hWnd == this->m_hWnd))
2675                 UpdateLocationViewPosition(m_nTopSubLine, m_nTopSubLine + GetScreenLines());
2676 }
2677 /**
2678  * @brief Select linedifference in the current line.
2679  *
2680  * Select line difference in current line. Selection type
2681  * is choosed by highlight type.
2682  */
2683 template<bool reversed>
2684 void CMergeEditView::OnSelectLineDiff()
2685 {
2686         // Pass this to the document, to compare this file to other
2687         GetDocument()->Showlinediff(this, reversed);
2688 }
2689
2690 /// Enable select difference menuitem if current line is inside difference.
2691 void CMergeEditView::OnUpdateSelectLineDiff(CCmdUI* pCmdUI)
2692 {
2693         pCmdUI->Enable(!GetDocument()->IsEditedAfterRescan());
2694 }
2695
2696 void CMergeEditView::OnAddToSubstitutionFilters()
2697 {
2698         // Pass this to the document, to compare this file to other
2699         GetDocument()->AddToSubstitutionFilters(this, false);
2700 }
2701
2702 void CMergeEditView::OnUpdateAddToSubstitutionFilters(CCmdUI* pCmdUI)
2703 {
2704         pCmdUI->Enable(GetDocument()->m_nBuffers == 2 && !GetDocument()->IsEditedAfterRescan());
2705 }
2706
2707 void CMergeEditView::OnAddToLineFilters()
2708 {
2709         // Pass this to the document, to compare this file to other
2710         CMergeDoc* pDoc = GetDocument();
2711         auto [ptSelStart, ptSelEnd] = GetSelection();
2712
2713         // Nothing selected
2714         if (ptSelStart == ptSelEnd)
2715                 return;
2716
2717         CString text;
2718
2719         if (!m_bRectangularSelection)
2720         {
2721                 CDiffTextBuffer* buffer = pDoc->m_ptBuf[m_nThisPane].get();
2722
2723                 buffer->GetTextWithoutEmptys(ptSelStart.y, ptSelStart.x,
2724                         ptSelEnd.y, ptSelEnd.x, text);
2725         }
2726         else
2727                 GetTextWithoutEmptysInColumnSelection(text);
2728
2729         CMergeDoc* pd = GetDocument();
2730         pd->AddToLineFilters(text.GetString());
2731         pd->FlushAndRescan(true);
2732 }
2733
2734 void CMergeEditView::OnUpdateAddToLineFilters(CCmdUI* pCmdUI)
2735 {
2736         pCmdUI->Enable(IsSelection() && GetDocument()->m_nBuffers == 2 && !GetDocument()->IsEditedAfterRescan());
2737 }
2738
2739 /**
2740  * @brief Enable/disable Replace-menuitem
2741  */
2742 void CMergeEditView::OnUpdateEditReplace(CCmdUI* pCmdUI)
2743 {
2744         CMergeDoc *pd = GetDocument();
2745         bool bReadOnly = pd->m_ptBuf[m_nThisPane]->GetReadOnly();
2746
2747         pCmdUI->Enable(!bReadOnly);
2748 }
2749
2750 /**
2751  * @brief Offer a context menu built with scriptlet/ActiveX functions
2752  */
2753 void CMergeEditView::OnContextMenu(CWnd* pWnd, CPoint point)
2754 {
2755         CRect rect;
2756         GetClientRect(rect);
2757         ClientToScreen(rect);
2758
2759         if (GetDocument()->m_ptBuf[m_nThisPane]->GetTableEditing())
2760         {
2761                 if (rect.top <= point.y && point.y < rect.top + GetTopMarginHeight())
2762                 {
2763                         BCMenu menu;
2764                         VERIFY(menu.LoadMenu(IDR_POPUP_MERGEVIEWHEADER));
2765                         theApp.TranslateMenu(menu.m_hMenu);
2766                         BCMenu* pSub = static_cast<BCMenu*>(menu.GetSubMenu(0));
2767                         pSub->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON,
2768                                 point.x, point.y, AfxGetMainWnd());
2769                         return;
2770                 }
2771         }
2772
2773         // Create the menu and populate it with the available functions
2774         BCMenu menu;
2775         VERIFY(menu.LoadMenu(IDR_POPUP_MERGEVIEW));
2776
2777         // Remove copying item copying from active side
2778         if (m_nThisPane == 0) // left?
2779         {
2780                 if (GetDocument()->m_nBuffers < 3)
2781                 {
2782                         menu.RemoveMenu(ID_COPY_TO_MIDDLE_L, MF_BYCOMMAND);
2783                         menu.RemoveMenu(ID_COPY_FROM_MIDDLE_L, MF_BYCOMMAND);
2784                         menu.RemoveMenu(ID_COPY_LINES_TO_MIDDLE_L, MF_BYCOMMAND);
2785                         menu.RemoveMenu(ID_COPY_LINES_FROM_MIDDLE_L, MF_BYCOMMAND);
2786                 }
2787                 for (UINT id = ID_COPY_TO_LEFT_M; id <= ID_COPY_FROM_LEFT_R; ++id)
2788                         menu.RemoveMenu(id, MF_BYCOMMAND);
2789                 for (UINT id = ID_COPY_LINES_TO_LEFT_M; id <= ID_COPY_LINES_FROM_LEFT_R; ++id)
2790                         menu.RemoveMenu(id, MF_BYCOMMAND);
2791         }
2792         if (m_nThisPane == 1 && GetDocument()->m_nBuffers == 3)
2793         {
2794                 for (UINT id = ID_COPY_TO_MIDDLE_L; id <= ID_COPY_FROM_RIGHT_L; ++id)
2795                         menu.RemoveMenu(id, MF_BYCOMMAND);
2796                 for (UINT id = ID_COPY_TO_MIDDLE_R; id <= ID_COPY_FROM_LEFT_R; ++id)
2797                         menu.RemoveMenu(id, MF_BYCOMMAND);
2798                 for (UINT id = ID_COPY_LINES_TO_MIDDLE_L; id <= ID_COPY_LINES_FROM_RIGHT_L; ++id)
2799                         menu.RemoveMenu(id, MF_BYCOMMAND);
2800                 for (UINT id = ID_COPY_LINES_TO_MIDDLE_R; id <= ID_COPY_LINES_FROM_LEFT_R; ++id)
2801                         menu.RemoveMenu(id, MF_BYCOMMAND);
2802         }
2803         if (m_nThisPane == GetDocument()->m_nBuffers - 1)
2804         {
2805                 if (GetDocument()->m_nBuffers < 3)
2806                 {
2807                         menu.RemoveMenu(ID_COPY_TO_MIDDLE_R, MF_BYCOMMAND);
2808                         menu.RemoveMenu(ID_COPY_FROM_MIDDLE_R, MF_BYCOMMAND);
2809                         menu.RemoveMenu(ID_COPY_LINES_TO_MIDDLE_R, MF_BYCOMMAND);
2810                         menu.RemoveMenu(ID_COPY_LINES_FROM_MIDDLE_R, MF_BYCOMMAND);
2811                 }
2812                 for (UINT id = ID_COPY_TO_MIDDLE_L; id <= ID_COPY_FROM_RIGHT_M; ++id)
2813                         menu.RemoveMenu(id, MF_BYCOMMAND);
2814                 for (UINT id = ID_COPY_LINES_TO_MIDDLE_L; id <= ID_COPY_LINES_FROM_RIGHT_M; ++id)
2815                         menu.RemoveMenu(id, MF_BYCOMMAND);
2816         }
2817
2818         // Remove "Go to Moved Line Between Middle and Right" if in 2-way file comparison.
2819         // Remove "Go to Moved Line Between Middle and Right" if the right pane is active in 3-way file comparison.
2820         // Remove "Go to Moved Line Between Left and Middle" if the right pane is active in 3-way file comparison.
2821         int nBuffers = GetDocument()->m_nBuffers;
2822         if (nBuffers == 2 || (nBuffers == 3 && m_nThisPane == 0))
2823                 menu.RemoveMenu(ID_GOTO_MOVED_LINE_MR, MF_BYCOMMAND);
2824         else if (nBuffers == 3 && m_nThisPane == 2)
2825                 menu.RemoveMenu(ID_GOTO_MOVED_LINE_LM, MF_BYCOMMAND);
2826
2827         VERIFY(menu.LoadToolbar(IDR_MAINFRAME, GetMainFrame()->GetToolbar()));
2828         theApp.TranslateMenu(menu.m_hMenu);
2829
2830         BCMenu *pSub = static_cast<BCMenu *>(menu.GetSubMenu(0));
2831         ASSERT(pSub != nullptr);
2832
2833         // Context menu opened using keyboard has no coordinates
2834         if (point.x == -1 && point.y == -1)
2835         {
2836                 point = rect.TopLeft();
2837                 point.Offset(5, 5);
2838         }
2839
2840         pSub->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON,
2841                 point.x, point.y, AfxGetMainWnd());
2842
2843 }
2844
2845 /**
2846  * @brief Update EOL mode in status bar
2847  */
2848 void CMergeEditView::OnUpdateStatusEOL(CCmdUI* pCmdUI)
2849 {
2850         GetGroupView(pCmdUI->m_nID - ID_STATUS_PANE0FILE_EOL)->OnUpdateIndicatorCRLF(pCmdUI);
2851 }
2852
2853 /**
2854  * @brief Change EOL mode and unify all the lines EOL to this new mode
2855  */
2856 void CMergeEditView::OnConvertEolTo(UINT nID )
2857 {
2858         CRLFSTYLE nStyle = CRLFSTYLE::AUTOMATIC;;
2859         switch (nID)
2860         {
2861                 case ID_EOL_TO_DOS:
2862                         nStyle = CRLFSTYLE::DOS;
2863                         break;
2864                 case ID_EOL_TO_UNIX:
2865                         nStyle = CRLFSTYLE::UNIX;
2866                         break;
2867                 case ID_EOL_TO_MAC:
2868                         nStyle = CRLFSTYLE::MAC;
2869                         break;
2870                 default:
2871                         // Catch errors
2872                         _RPTF0(_CRT_ERROR, "Unhandled EOL type conversion!");
2873                         break;
2874         }
2875         m_pTextBuffer->SetCRLFMode(nStyle);
2876
2877         // we don't need a derived applyEOLMode for ghost lines as they have no EOL char
2878         if (m_pTextBuffer->applyEOLMode())
2879         {
2880                 CMergeDoc *pd = GetDocument();
2881                 ASSERT(pd != nullptr);
2882                 pd->UpdateHeaderPath(m_nThisPane);
2883                 pd->FlushAndRescan(true);
2884         }
2885 }
2886
2887 /**
2888  * @brief allow convert to entries in file submenu
2889  */
2890 void CMergeEditView::OnUpdateConvertEolTo(CCmdUI* pCmdUI)
2891 {
2892         CRLFSTYLE nStyle = CRLFSTYLE::AUTOMATIC;
2893         switch (pCmdUI->m_nID)
2894         {
2895                 case ID_EOL_TO_DOS:
2896                         nStyle = CRLFSTYLE::DOS;
2897                         break;
2898                 case ID_EOL_TO_UNIX:
2899                         nStyle = CRLFSTYLE::UNIX;
2900                         break;
2901                 case ID_EOL_TO_MAC:
2902                         nStyle = CRLFSTYLE::MAC;
2903                         break;
2904                 default:
2905                         // Catch errors
2906                         _RPTF0(_CRT_ERROR, "Missing menuitem handler for EOL convert menu!");
2907                         break;
2908         }
2909
2910         if (GetOptionsMgr()->GetBool(OPT_ALLOW_MIXED_EOL) ||
2911                 GetDocument()->IsMixedEOL(m_nThisPane) ||
2912                 nStyle != m_pTextBuffer->GetCRLFMode())
2913         {
2914                 pCmdUI->SetRadio(false);
2915
2916                 // Don't allow selecting other EOL style for protected pane
2917                 if (!QueryEditable())
2918                         pCmdUI->Enable(false);
2919         }
2920         else
2921                 pCmdUI->SetRadio(true);
2922 }
2923
2924 /**
2925  * @brief Copy diff from left to right and advance to next diff
2926  */
2927 void CMergeEditView::OnL2RNext()
2928 {
2929         OnL2r();
2930         if (GetDocument()->m_nBuffers > 2 && IsCursorInDiff()) // for 3-way file compare
2931                 OnNextdiff();
2932         OnNextdiff();
2933 }
2934
2935 /**
2936  * @brief Update "Copy right and advance" UI item
2937  */
2938 void CMergeEditView::OnUpdateL2RNext(CCmdUI* pCmdUI)
2939 {
2940         OnUpdateL2r(pCmdUI);
2941 }
2942
2943 /**
2944  * @brief Copy diff from right to left and advance to next diff
2945  */
2946 void CMergeEditView::OnR2LNext()
2947 {
2948         OnR2l();
2949         if (GetDocument()->m_nBuffers > 2 && IsCursorInDiff()) // for 3-way file compare
2950                 OnNextdiff();
2951         OnNextdiff();
2952 }
2953
2954 /**
2955  * @brief Update "Copy left and advance" UI item
2956  */
2957 void CMergeEditView::OnUpdateR2LNext(CCmdUI* pCmdUI)
2958 {
2959         OnUpdateR2l(pCmdUI);
2960 }
2961
2962 /**
2963  * @brief Change active pane in MergeView.
2964  * Changes active pane and makes sure cursor position is kept in
2965  * screen. Currently we put cursor in same line than in original
2966  * active pane but we could be smarter too? Maybe update cursor
2967  * only when it is not visible in new pane?
2968  */
2969 void CMergeEditView::OnChangePane(UINT nID)
2970 {
2971         CSplitterWnd *pSplitterWnd = GetParentSplitter(this, false);
2972         CMergeEditView *pWnd = static_cast<CMergeEditView*>(pSplitterWnd->GetActivePane());
2973         CMergeDoc *pDoc = GetDocument();
2974         bool bFound = false;
2975         CMergeEditView *pNextActiveView = nullptr;
2976         std::vector<CMergeEditView *> list = pDoc->GetViewList();
2977         list.insert(list.end(), list.begin(), list.end());
2978         if (nID == ID_PREV_PANE)
2979                 std::reverse(list.begin(), list.end());
2980
2981         for (auto& pView : list)
2982         {
2983                 if (bFound && pView->m_bDetailView == pWnd->m_bDetailView)
2984                 {
2985                         pNextActiveView = pView;
2986                         break;
2987                 }
2988                 if (pWnd == pView)
2989                         bFound = true;
2990         }
2991         GetParentFrame()->SetActiveView(pNextActiveView);
2992         CEPoint ptCursor = pWnd->GetCursorPos();
2993         ptCursor.x = 0;
2994         if (ptCursor.y >= pNextActiveView->GetLineCount())
2995                 ptCursor.y = pNextActiveView->GetLineCount() - 1;
2996         pNextActiveView->SetCursorPos(ptCursor);
2997         pNextActiveView->SetAnchor(ptCursor);
2998         pNextActiveView->SetSelection(ptCursor, ptCursor);
2999 }
3000
3001 /**
3002  * @brief Show "Go To" dialog and scroll views to line or diff.
3003  *
3004  * Before dialog is opened, current line and file is determined
3005  * and selected.
3006  * @note Conversions needed between apparent and real lines
3007  */
3008 void CMergeEditView::OnWMGoto()
3009 {
3010         WMGotoDlg dlg;
3011         CMergeDoc *pDoc = GetDocument();
3012         CEPoint pos = GetCursorPos();
3013         int nRealLine = 0;
3014         int nLastLine = 0;
3015
3016         nRealLine = pDoc->m_ptBuf[m_nThisPane]->ComputeRealLine(pos.y);
3017         int nLineCount = pDoc->m_ptBuf[m_nThisPane]->GetLineCount();
3018         nLastLine = pDoc->m_ptBuf[m_nThisPane]->ComputeRealLine(nLineCount - 1);
3019
3020         // Set active file and current line selected in dialog
3021         dlg.m_strParam = strutils::to_str(nRealLine + 1);
3022         dlg.m_nFile = (pDoc->m_nBuffers < 3) ? (m_nThisPane == 1 ? 2 : 0) : m_nThisPane;
3023         dlg.m_nGotoWhat = 0;
3024
3025         if (dlg.DoModal() == IDOK)
3026         {
3027                 CMergeDoc * pDoc1 = GetDocument();
3028
3029                 // Get views
3030                 CMergeEditView * pCurrentView = GetGroupView(m_nThisPane);
3031
3032                 int num = 0;
3033                 try { num = std::stoi(dlg.m_strParam) - 1; } catch(...) {}
3034
3035                 if (dlg.m_nGotoWhat == 0)
3036                 {
3037                         int nRealLine1 = num;
3038                         if (nRealLine1 < 0)
3039                                 nRealLine1 = 0;
3040                         if (nRealLine1 > nLastLine)
3041                                 nRealLine1 = nLastLine;
3042
3043                         bool bShift = (GetKeyState(VK_SHIFT) & 0x8000) != 0;
3044                         GotoLine(nRealLine1, true, (pDoc1->m_nBuffers < 3) ? (dlg.m_nFile == 2 ? 1 : 0) : dlg.m_nFile, !bShift);
3045                 }
3046                 else
3047                 {
3048                         int diff = num;
3049                         if (diff < 0)
3050                                 diff = 0;
3051                         if (diff >= pDoc1->m_diffList.GetSize())
3052                                 diff = pDoc1->m_diffList.GetSize();
3053
3054                         if (pCurrentView)
3055                                 pCurrentView->SelectDiff(diff, true, false);
3056                 }
3057         }
3058 }
3059
3060 /**
3061 * @brief Called when "Go to Moved Line Between Left and Middle" item is selected.
3062 * Go to moved line between the left and right panes when in 2-way file comparison.
3063 * Go to moved line between the left and middle panes when in 3-way file comparison.
3064 */
3065 void CMergeEditView::OnGotoMovedLineLM()
3066 {
3067         if (!GetOptionsMgr()->GetBool(OPT_CMP_MOVED_BLOCKS))
3068                 return;
3069
3070         CMergeDoc* pDoc = GetDocument();
3071         CEPoint pos = GetCursorPos();
3072
3073         ASSERT(m_nThisPane >= 0 && m_nThisPane < 3);
3074         ASSERT(pDoc != nullptr);
3075         ASSERT(pDoc->m_nBuffers == 2 || pDoc->m_nBuffers == 3);
3076         ASSERT(pos.y >= 0);
3077
3078         if (m_nThisPane == 0)
3079         {
3080                 int line = pDoc->RightLineInMovedBlock(m_nThisPane, pos.y);
3081                 if (line >= 0)
3082                         GotoLine(line, false, 1);
3083         }
3084         else if (m_nThisPane == 1)
3085         {
3086                 int line = pDoc->LeftLineInMovedBlock(m_nThisPane, pos.y);
3087                 if (line >= 0)
3088                         GotoLine(line, false, 0);
3089         }
3090 }
3091
3092 /**
3093  * @brief Called when "Go to Moved Line Between Left and Middle" item is updated.
3094  * @param [in] pCmdUI UI component to update.
3095  * @note The item label is changed to "Go to Moved Line" when 2-way file comparison.
3096  */
3097 void CMergeEditView::OnUpdateGotoMovedLineLM(CCmdUI* pCmdUI)
3098 {
3099         CMergeDoc* pDoc = GetDocument();
3100         CEPoint pos = GetCursorPos();
3101
3102         ASSERT(m_nThisPane >= 0 && m_nThisPane < 3);
3103         ASSERT(pCmdUI != nullptr);
3104         ASSERT(pDoc != nullptr);
3105         ASSERT(pDoc->m_nBuffers == 2 || pDoc->m_nBuffers == 3);
3106         ASSERT(pos.y >= 0);
3107
3108         if (pDoc->m_nBuffers == 2)
3109                 pCmdUI->SetText(_("Go to Moved Line\tCtrl+Shift+G").c_str());
3110
3111         if (!GetOptionsMgr()->GetBool(OPT_CMP_MOVED_BLOCKS) || m_nThisPane == 2)
3112         {
3113                 pCmdUI->Enable(false);
3114                 return;
3115         }
3116
3117         if (m_nThisPane == 0)
3118         {
3119                 bool bOn = (pDoc->RightLineInMovedBlock(m_nThisPane, pos.y) >= 0);
3120                 pCmdUI->Enable(bOn);
3121         }
3122         else if (m_nThisPane == 1)
3123         {
3124                 bool bOn = (pDoc->LeftLineInMovedBlock(m_nThisPane, pos.y) >= 0);
3125                 pCmdUI->Enable(bOn);
3126         }
3127 }
3128
3129 /**
3130 * @brief Called when "Go to Moved Line Between Middle and Right" item is selected.
3131 * Go to moved line between the middle and right panes when in 3-way file comparison.
3132 */
3133 void CMergeEditView::OnGotoMovedLineMR()
3134 {
3135         if (!GetOptionsMgr()->GetBool(OPT_CMP_MOVED_BLOCKS))
3136                 return;
3137
3138         CMergeDoc* pDoc = GetDocument();
3139         CEPoint pos = GetCursorPos();
3140
3141         ASSERT(m_nThisPane >= 0 && m_nThisPane < 3);
3142         ASSERT(pDoc != nullptr);
3143         ASSERT(pDoc->m_nBuffers == 2 || pDoc->m_nBuffers == 3);
3144         ASSERT(pos.y >= 0);
3145
3146         if (m_nThisPane == 1)
3147         {
3148                 int line = pDoc->RightLineInMovedBlock(m_nThisPane, pos.y);
3149                 if (line >= 0)
3150                         GotoLine(line, false, 2);
3151         }
3152         else if (m_nThisPane == 2)
3153         {
3154                 int line = pDoc->LeftLineInMovedBlock(m_nThisPane, pos.y);
3155                 if (line >= 0)
3156                         GotoLine(line, false, 1);
3157         }
3158 }
3159
3160 /**
3161  * @brief Called when "Go to Moved Line Between Middle and Right" item is updated.
3162  * @param [in] pCmdUI UI component to update.
3163  */
3164 void CMergeEditView::OnUpdateGotoMovedLineMR(CCmdUI* pCmdUI)
3165 {
3166         CMergeDoc* pDoc = GetDocument();
3167         CEPoint pos = GetCursorPos();
3168
3169         ASSERT(m_nThisPane >= 0 && m_nThisPane < 3);
3170         ASSERT(pCmdUI != nullptr);
3171         ASSERT(pDoc != nullptr);
3172         ASSERT(pDoc->m_nBuffers == 2 || pDoc->m_nBuffers == 3);
3173         ASSERT(pos.y >= 0);
3174
3175         if (!GetOptionsMgr()->GetBool(OPT_CMP_MOVED_BLOCKS) || pDoc->m_nBuffers == 2 || m_nThisPane == 0)
3176         {
3177                 pCmdUI->Enable(false);
3178                 return;
3179         }
3180
3181         if (m_nThisPane == 1)
3182         {
3183                 bool bOn = (pDoc->RightLineInMovedBlock(m_nThisPane, pos.y) >= 0);
3184                 pCmdUI->Enable(bOn);
3185         }
3186         else if (m_nThisPane == 2)
3187         {
3188                 bool bOn = (pDoc->LeftLineInMovedBlock(m_nThisPane, pos.y) >= 0);
3189                 pCmdUI->Enable(bOn);
3190         }
3191 }
3192
3193 void CMergeEditView::OnShellMenu()
3194 {
3195         CFrameWnd *pFrame = GetTopLevelFrame();
3196         ASSERT(pFrame != nullptr);
3197         BOOL bAutoMenuEnableOld = pFrame->m_bAutoMenuEnable;
3198         pFrame->m_bAutoMenuEnable = FALSE;
3199
3200         String path = GetDocument()->m_filePaths[m_nThisPane];
3201         auto pContextMenu = std::make_unique<CShellContextMenu>(CShellContextMenu(0x9000, 0x9FFF));
3202         pContextMenu->Initialize();
3203         pContextMenu->AddItem(paths::GetParentPath(path), paths::FindFileName(path));
3204         pContextMenu->RequeryShellContextMenu();
3205         CPoint point;
3206         ::GetCursorPos(&point);
3207         HWND hWnd = GetSafeHwnd();
3208         BOOL nCmd = TrackPopupMenu(pContextMenu->GetHMENU(), TPM_LEFTALIGN | TPM_RIGHTBUTTON | TPM_RETURNCMD, point.x, point.y, 0, hWnd, nullptr);
3209         if (nCmd)
3210                 pContextMenu->InvokeCommand(nCmd, hWnd);
3211         pContextMenu->ReleaseShellContextMenu();
3212
3213         pFrame->m_bAutoMenuEnable = bAutoMenuEnableOld;
3214 }
3215
3216 void CMergeEditView::OnUpdateShellMenu(CCmdUI* pCmdUI)
3217 {
3218         pCmdUI->Enable(!GetDocument()->m_filePaths[m_nThisPane].empty());
3219 }
3220
3221 /**
3222  * @brief Reload options.
3223  */
3224 void CMergeEditView::RefreshOptions()
3225
3226         RENDERING_MODE nRenderingMode = static_cast<RENDERING_MODE>(GetOptionsMgr()->GetInt(OPT_RENDERING_MODE));
3227         SetRenderingMode(nRenderingMode);
3228
3229         if (GetOptionsMgr()->GetInt(OPT_TAB_TYPE) == 0)
3230                 SetInsertTabs(true);
3231         else
3232                 SetInsertTabs(false);
3233
3234         SetSelectionMargin(GetOptionsMgr()->GetBool(OPT_VIEW_FILEMARGIN));
3235         SetTopMargin(GetOptionsMgr()->GetBool(
3236                 GetDocument()->m_ptBuf[m_nThisPane]->GetTableEditing() ? OPT_VIEW_TOPMARGIN_TABLE : OPT_VIEW_TOPMARGIN));
3237         SetLineUsedAsHeaders(GetOptionsMgr()->GetInt(OPT_LINE_NUMBER_USED_AS_HEADERS));
3238
3239         if (!GetOptionsMgr()->GetBool(OPT_SYNTAX_HIGHLIGHT))
3240                 SetTextType(CrystalLineParser::SRC_PLAIN);
3241         else if (!GetDocument()->GetChangedSchemeManually())
3242         {
3243                 // The syntax highlighting scheme should only be applied if it has not been manually changed.
3244                 String fileName = GetDocument()->m_ptBuf[m_nThisPane]->GetTempFileName();
3245                 String sExt;
3246                 paths::SplitFilename(fileName, nullptr, nullptr, &sExt);
3247                 CrystalLineParser::TextDefinition* def = CrystalLineParser::GetTextType(sExt.c_str());
3248                 if (def != nullptr)
3249                         SetTextType(def->type);
3250                 else
3251                         SetTextType(CrystalLineParser::SRC_PLAIN);
3252                 SetDisableBSAtSOL(false);
3253         }
3254
3255         SetWordWrapping(GetOptionsMgr()->GetBool(OPT_WORDWRAP));
3256         SetViewLineNumbers(GetOptionsMgr()->GetBool(OPT_VIEW_LINENUMBERS));
3257
3258         SetViewTabs(GetOptionsMgr()->GetBool(OPT_VIEW_WHITESPACE));
3259         SetViewEols(GetOptionsMgr()->GetBool(OPT_VIEW_EOL),
3260                 GetOptionsMgr()->GetBool(OPT_ALLOW_MIXED_EOL) ||
3261                 GetDocument()->IsMixedEOL(m_nThisPane));
3262
3263         Options::DiffColors::Load(GetOptionsMgr(), m_cachedColors);
3264 }
3265
3266 void CMergeEditView::OnScripts(UINT nID)
3267 {
3268         // text is CHAR if compiled without UNICODE, WCHAR with UNICODE
3269         CString ctext = GetSelectedText();
3270         String text{ ctext, static_cast<unsigned>(ctext.GetLength()) };
3271
3272         EditorScriptInfo scriptInfo(
3273                 CMainFrame::GetPluginPipelineByMenuId(nID, FileTransform::EditorScriptEventNames, ID_SCRIPT_FIRST));
3274         // transform the text with a script/ActiveX function, event=EDITOR_SCRIPT
3275         bool bChanged = false;
3276         scriptInfo.TransformText(text, { GetDocument()->m_filePaths[m_nThisPane] }, bChanged);
3277         if (bChanged)
3278                 // now replace the text
3279                 ReplaceSelection(text.c_str(), text.length(), 0);
3280 }
3281
3282 void CMergeEditView::OnTransformWithScript() 
3283 {
3284         // let the user choose a handler
3285         CSelectPluginDlg dlg(_T(""),
3286                 strutils::join(GetDocument()->m_filePaths.begin(), GetDocument()->m_filePaths.end(), _T("|")),
3287                 CSelectPluginDlg::PluginType::EditorScript, false);
3288         if (dlg.DoModal() != IDOK)
3289                 return;
3290         EditorScriptInfo scriptInfo(dlg.GetPluginPipeline());
3291         CString ctext = GetSelectedText();
3292         String text{ ctext, static_cast<unsigned>(ctext.GetLength()) };
3293         bool bChanged = false;
3294         scriptInfo.TransformText(text, { GetDocument()->m_filePaths[m_nThisPane] }, bChanged);
3295         if (bChanged)
3296                 // now replace the text
3297                 ReplaceSelection(text.c_str(), text.length(), 0);
3298 }
3299
3300 /** 
3301  * @brief Goto given line.
3302  * @param [in] nLine Destination linenumber
3303  * @param [in] bRealLine if true linenumber is real line, otherwise
3304  * it is apparent line (including deleted lines)
3305  * @param [in] pane Pane index of goto target pane (0 = left, 1 = right).
3306  * @param [in] bMoveAnchor if true the anchor is moved to nLine
3307  * @param [in] nChar Destination character position
3308  */
3309 void CMergeEditView::GotoLine(UINT nLine, bool bRealLine, int pane, bool bMoveAnchor, int nChar)
3310 {
3311         CMergeDoc *pDoc = GetDocument();
3312         CSplitterWnd *pSplitterWnd = GetParentSplitter(this, false);
3313         CMergeEditView *pCurrentView = nullptr;
3314         if (pSplitterWnd != nullptr)
3315                 pCurrentView = static_cast<CMergeEditView*>
3316                         (pSplitterWnd->GetActivePane());
3317
3318         int nRealLine = nLine;
3319         int nApparentLine = nLine;
3320
3321         // Compute apparent (shown linenumber) line
3322         if (bRealLine)
3323         {
3324                 if (nRealLine > pDoc->m_ptBuf[pane]->GetLineCount() - 1)
3325                         nRealLine = pDoc->m_ptBuf[pane]->GetLineCount() - 1;
3326
3327                 nApparentLine = pDoc->m_ptBuf[pane]->ComputeApparentLine(nRealLine);
3328         }
3329         CEPoint ptPos;
3330         ptPos.x = nChar == -1 ? 0 : nChar;
3331         ptPos.y = nApparentLine;
3332
3333         // Scroll line to center of view
3334         int nScrollLine = GetSubLineIndex(nApparentLine);
3335         nScrollLine -= GetScreenLines() / 2;
3336         if (nScrollLine < 0)
3337                 nScrollLine = 0;
3338
3339         for (int nPane = 0; nPane < pDoc->m_nBuffers; nPane++)
3340         {
3341                 int nGroup = m_bDetailView ? 0 : m_nThisGroup;
3342                 CMergeEditView* pView = GetDocument()->GetView(nGroup, nPane);
3343                 pView->ScrollToSubLine(nScrollLine);
3344                 CEPoint pt = (ptPos.y < pView->GetLineCount()) ? ptPos : CEPoint(ptPos.x, pView->GetLineCount() - 1);
3345                 pt.x = std::clamp(static_cast<int>(pt.x), 0, pView->GetLineLength(pt.y));
3346                 pView->SetCursorPos(pt);
3347                 if (bMoveAnchor || nPane != pane)
3348                         pView->SetAnchor(pt);
3349                 pView->SetSelection(pView->GetAnchor(), pt);
3350                 pView->EnsureVisible(pt);
3351         }
3352
3353         // If goto target is another view - activate another view.
3354         // This is done for user convenience as user probably wants to
3355         // work with goto target file.
3356         if (m_bDetailView)
3357                 GetDocument()->GetView(0, pane)->SetActivePane();
3358         else if (GetGroupView(pane) != pCurrentView)
3359                 GetGroupView(pane)->SetActivePane();
3360 }
3361
3362 /**
3363  * @brief Check for horizontal scroll. Re-route to CSplitterEx if not from
3364  * a scroll bar.
3365  */
3366 void CMergeEditView::OnHScroll(UINT nSBCode, UINT nPos, CScrollBar *pScrollBar)
3367 {
3368         if (pScrollBar == nullptr)
3369         {
3370                 // Scroll did not come frome a scroll bar
3371                 // Find the appropriate scroll bar
3372                 // and send the message to the splitter window instead
3373                 // The event should eventually come back here but with a valid scrollbar
3374                 // Along the way it will be propagated to other windows that need it
3375                 CSplitterWnd *pSplitterWnd = GetParentSplitter(this, false);
3376                 CScrollBar* curBar = this->GetScrollBarCtrl(SB_HORZ);
3377                 pSplitterWnd->SendMessage(WM_HSCROLL,
3378                         MAKELONG(nSBCode, nPos), (LPARAM)curBar->m_hWnd);
3379                 return;
3380         }
3381         CCrystalTextView::OnHScroll (nSBCode, nPos, pScrollBar);
3382 }
3383
3384 /**
3385  * @brief When view is scrolled using scrollbars update location pane.
3386  */
3387 void CMergeEditView::OnVScroll(UINT nSBCode, UINT nPos, CScrollBar *pScrollBar)
3388 {
3389         if (pScrollBar == nullptr)
3390         {
3391                 // Scroll did not come frome a scroll bar
3392                 // Find the appropriate scroll bar
3393                 // and send the message to the splitter window instead
3394                 // The event should eventually come back here but with a valid scrollbar
3395                 // Along the way it will be propagated to other windows that need it
3396                 CSplitterWnd *pSplitterWnd = GetParentSplitter(this, false);
3397                 CScrollBar* curBar = this->GetScrollBarCtrl(SB_VERT);
3398                 pSplitterWnd->SendMessage(WM_VSCROLL,
3399                         MAKELONG(nSBCode, nPos), (LPARAM)curBar->m_hWnd);
3400                 return;
3401         }
3402         CCrystalTextView::OnVScroll (nSBCode, nPos, pScrollBar);
3403
3404         if (nSBCode == SB_ENDSCROLL)
3405                 return;
3406
3407         // Note we cannot use nPos because of its 16-bit nature
3408         SCROLLINFO si{ sizeof(si) };
3409         si.fMask = SIF_PAGE | SIF_POS | SIF_RANGE | SIF_TRACKPOS;
3410         VERIFY (GetScrollInfo (SB_VERT, &si));
3411
3412         // Get the current position of scroll   box.
3413         int nCurPos =   si.nPos;
3414         
3415         UpdateLocationViewPosition(nCurPos, nCurPos + GetScreenLines());
3416 }
3417
3418 /**
3419  * @brief Copy selected lines adding linenumbers.
3420  */
3421 void CMergeEditView::OnEditCopyLineNumbers()
3422 {
3423         CString strText;
3424         CString strLine;
3425         CString strNumLine;
3426
3427         CMergeDoc *pDoc = GetDocument();
3428         auto [ptStart, ptEnd] = GetSelection();
3429
3430         // Get last selected line (having widest linenumber)
3431         int line = pDoc->m_ptBuf[m_nThisPane]->ComputeRealLine(ptEnd.y);
3432         size_t nNumWidth = strutils::to_str(line + 1).length();
3433         
3434         for (int i = ptStart.y; i <= ptEnd.y; i++)
3435         {
3436                 if (GetLineFlags(i) & LF_GHOST || (GetEnableHideLines() && (GetLineFlags(i) & LF_INVISIBLE)))
3437                         continue;
3438
3439                 // We need to convert to real linenumbers
3440                 line = pDoc->m_ptBuf[m_nThisPane]->ComputeRealLine(i);
3441
3442                 // Insert spaces to align different width linenumbers (99, 100)
3443                 strLine = GetLineText(i);
3444                 CString sSpaces(' ', static_cast<int>(nNumWidth - strutils::to_str(line + 1).length()));
3445                 
3446                 strText += sSpaces;
3447                 strNumLine.Format(_T("%d: %s"), line + 1, (const tchar_t*)strLine);
3448                 strText += strNumLine;
3449         }
3450         PutToClipboard(strText, strText.GetLength(), m_bRectangularSelection);
3451 }
3452
3453 void CMergeEditView::OnUpdateEditCopyLinenumbers(CCmdUI* pCmdUI)
3454 {
3455         CCrystalEditViewEx::OnUpdateEditCopy(pCmdUI);
3456 }
3457
3458 /**
3459  * @brief Open active file with associated application.
3460  *
3461  * First tries to open file using shell 'Edit' action, since that
3462  * action open scripts etc. to editor instead of running them. If
3463  * edit-action is not registered, 'Open' action is used.
3464  */
3465 void CMergeEditView::OnOpenFile()
3466 {
3467         CMergeDoc * pDoc = GetDocument();
3468         ASSERT(pDoc != nullptr);
3469
3470         String sFileName = pDoc->m_filePaths[m_nThisPane];
3471         if (sFileName.empty())
3472                 return;
3473         shell::Edit(sFileName.c_str());
3474 }
3475
3476 /**
3477  * @brief Open active file with app selection dialog
3478  */
3479 void CMergeEditView::OnOpenFileWith()
3480 {
3481         CMergeDoc * pDoc = GetDocument();
3482         ASSERT(pDoc != nullptr);
3483
3484         String sFileName = pDoc->m_filePaths[m_nThisPane];
3485         if (sFileName.empty())
3486                 return;
3487         shell::OpenWith(sFileName.c_str());
3488 }
3489
3490 /**
3491  * @brief Open active file with external editor
3492  */
3493 void CMergeEditView::OnOpenFileWithEditor()
3494 {
3495         CMergeDoc * pDoc = GetDocument();
3496         ASSERT(pDoc != nullptr);
3497
3498         String sFileName = pDoc->m_filePaths[m_nThisPane];
3499         if (sFileName.empty())
3500                 return;
3501
3502         int nRealLine = ComputeRealLine(GetCursorPos().y) + 1;
3503         CMergeApp::OpenFileToExternalEditor(sFileName, nRealLine);
3504 }
3505
3506 /**
3507  * @brief Open parent folder of active file
3508  */
3509 void CMergeEditView::OnOpenParentFolder()
3510 {
3511         CMergeDoc * pDoc = GetDocument();
3512         ASSERT(pDoc != nullptr);
3513
3514         String sFileName = pDoc->m_filePaths[m_nThisPane];
3515         if (sFileName.empty())
3516                 return;
3517
3518         shell::OpenParentFolder(sFileName.c_str());
3519 }
3520
3521 /**
3522  * @brief Force repaint of the location pane.
3523  */
3524 void CMergeEditView::RepaintLocationPane()
3525 {
3526         // Must force recalculation due to caching of data in location pane.
3527         CLocationView *pLocationView = GetDocument()->GetLocationView();
3528         if (pLocationView != nullptr)
3529                 pLocationView->ForceRecalculate();
3530 }
3531
3532 /**
3533  * @brief Enables/disables linediff (different color for diffs)
3534  */
3535 void CMergeEditView::OnViewLineDiffs()
3536 {
3537         bool bWordDiffHighlight = GetOptionsMgr()->GetBool(OPT_WORDDIFF_HIGHLIGHT);
3538         GetOptionsMgr()->SaveOption(OPT_WORDDIFF_HIGHLIGHT, !bWordDiffHighlight);
3539
3540         // Call CMergeDoc RefreshOptions() to refresh *both* views
3541         CMergeDoc *pDoc = GetDocument();
3542         pDoc->RefreshOptions();
3543         pDoc->FlushAndRescan(true);
3544 }
3545
3546 void CMergeEditView::OnUpdateViewLineDiffs(CCmdUI* pCmdUI)
3547 {
3548         pCmdUI->Enable(true);
3549         pCmdUI->SetCheck(GetOptionsMgr()->GetBool(OPT_WORDDIFF_HIGHLIGHT));
3550 }
3551
3552 /**
3553  * @brief Enables/disables line number
3554  */
3555 void CMergeEditView::OnViewLineNumbers()
3556 {
3557         GetOptionsMgr()->SaveOption(OPT_VIEW_LINENUMBERS, !GetViewLineNumbers());
3558
3559         // Call CMergeDoc RefreshOptions() to refresh *both* views
3560         CMergeDoc *pDoc = GetDocument();
3561         pDoc->RefreshOptions();
3562 }
3563
3564 void CMergeEditView::OnUpdateViewLineNumbers(CCmdUI* pCmdUI)
3565 {
3566         pCmdUI->Enable(true);
3567         pCmdUI->SetCheck(GetViewLineNumbers());
3568 }
3569
3570 /**
3571  * @brief Enables/disables word wrap
3572  */
3573 void CMergeEditView::OnViewWordWrap()
3574 {
3575         GetOptionsMgr()->SaveOption(
3576                 GetDocument()->m_ptBuf[0]->GetTableEditing() ?  OPT_WORDWRAP_TABLE : OPT_WORDWRAP,
3577                 !m_bWordWrap);
3578
3579         // Call CMergeDoc RefreshOptions() to refresh *both* views
3580         CMergeDoc *pDoc = GetDocument();
3581         pDoc->RefreshOptions();
3582         pDoc->UpdateAllViews(this);
3583
3584         UpdateCaret();
3585 }
3586
3587 void CMergeEditView::OnUpdateViewWordWrap(CCmdUI* pCmdUI)
3588 {
3589         pCmdUI->Enable(true);
3590         pCmdUI->SetCheck(m_bWordWrap);
3591         pCmdUI->SetText((GetDocument()->m_ptBuf[0]->GetTableEditing() ?
3592                 _("W&rap Text") : _("W&rap Lines")).c_str());
3593 }
3594
3595 void CMergeEditView::OnViewWhitespace() 
3596 {
3597         GetOptionsMgr()->SaveOption(OPT_VIEW_WHITESPACE, !GetViewTabs());
3598
3599         // Call CMergeDoc RefreshOptions() to refresh *both* views
3600         CMergeDoc *pDoc = GetDocument();
3601         pDoc->RefreshOptions();
3602 }
3603
3604 void CMergeEditView::OnUpdateViewWhitespace(CCmdUI* pCmdUI) 
3605 {
3606         pCmdUI->SetCheck(GetViewTabs());
3607 }
3608
3609 void CMergeEditView::OnViewEOL() 
3610 {
3611         GetOptionsMgr()->SaveOption(OPT_VIEW_EOL, !GetViewEols());
3612         GetDocument()->RefreshOptions();
3613 }
3614
3615 void CMergeEditView::OnUpdateViewEOL(CCmdUI* pCmdUI) 
3616 {
3617         pCmdUI->SetCheck(GetViewEols());
3618 }
3619
3620 void CMergeEditView::OnSize(UINT nType, int cx, int cy) 
3621 {
3622         if (!IsInitialized())
3623                 return;
3624
3625         CMergeDoc * pDoc = GetDocument();
3626         if (m_nThisPane < pDoc->m_nBuffers - 1)
3627         {
3628                 // To calculate subline index correctly
3629                 // we have to invalidate line cache in all pane before calling the function related the subline.
3630                 for (int nPane = 0; nPane < pDoc->m_nBuffers; nPane++) 
3631                 {
3632                         CMergeEditView *pView = GetGroupView(nPane);
3633                         if (pView != nullptr)
3634                                 pView->InvalidateScreenRect(false);
3635                 }
3636         }
3637         else
3638         {
3639                 for (int nPane = 0; nPane < pDoc->m_nBuffers; nPane++) 
3640                 {
3641                         CMergeEditView *pView = GetGroupView(nPane);
3642                         if (pView != nullptr)
3643                                 pView->Invalidate();
3644                 }
3645         }
3646         // recalculate m_nTopSubLine
3647         m_nTopSubLine = GetSubLineIndex(m_nTopLine);
3648
3649         UpdateCaret();
3650         
3651         RecalcVertScrollBar (false, false);
3652         RecalcHorzScrollBar (false, false);
3653 }
3654
3655 /**
3656 * @brief allocates GDI resources for printing
3657 * @param pDC [in] points to the printer device context
3658 * @param pInfo [in] points to a CPrintInfo structure that describes the current print job
3659 */
3660 void CMergeEditView::OnBeginPrinting(CDC * pDC, CPrintInfo * pInfo)
3661 {
3662         GetParentFrame()->PostMessage(WM_TIMER);
3663
3664         for (int pane = 0; pane < GetDocument()->m_nBuffers; pane++)
3665         {
3666                 CMergeEditView *pView = GetDocument()->GetView(m_nThisGroup, pane);
3667                 pView->m_bPrintHeader = true;
3668                 pView->m_bPrintFooter = true;
3669                 pView->CGhostTextView::OnBeginPrinting(pDC, pInfo);
3670         }
3671 }
3672
3673 /**
3674 * @brief frees GDI resources for printing
3675 * @param pDC [in] points to the printer device context
3676 * @param pInfo [in] points to a CPrintInfo structure that describes the current print job
3677 */
3678 void CMergeEditView::OnEndPrinting(CDC * pDC, CPrintInfo * pInfo)
3679 {
3680         for (int pane = 0; pane < GetDocument()->m_nBuffers; pane++)
3681                 GetDocument()->GetView(m_nThisGroup, pane)->CGhostTextView::OnEndPrinting(pDC, pInfo);
3682
3683         GetParentFrame()->PostMessage(WM_TIMER);
3684 }
3685
3686 /**
3687 * @brief Gets header text to print
3688 * @param [in]  nPageNum the page number to print
3689 * @param [out] header text to print
3690 */
3691 void CMergeEditView::GetPrintHeaderText(int nPageNum, CString & text)
3692 {
3693         text = GetDocument()->GetTitle();
3694 }
3695
3696 /**
3697 * @brief Prints header
3698 * @param [in] nPageNum the page number to print
3699 */
3700 void CMergeEditView::PrintHeader(CDC * pdc, int nPageNum)
3701 {
3702         if (m_nThisPane > 0)
3703                 return;
3704         int oldRight = m_rcPrintArea.right;
3705         m_rcPrintArea.right += m_rcPrintArea.Width() * (GetDocument()->m_nBuffers - 1);
3706         CGhostTextView::PrintHeader(pdc, nPageNum);
3707         m_rcPrintArea.right = oldRight;
3708 }
3709
3710 /**
3711 * @brief Prints footer
3712 * @param [in] nPageNum the page number to print
3713 */
3714 void CMergeEditView::PrintFooter(CDC * pdc, int nPageNum)
3715 {
3716         if (m_nThisPane > 0)
3717                 return;
3718         int oldRight = m_rcPrintArea.right;
3719         m_rcPrintArea.right += m_rcPrintArea.Width() * (GetDocument()->m_nBuffers - 1);
3720         CGhostTextView::PrintFooter(pdc, nPageNum);
3721         m_rcPrintArea.right = oldRight;
3722 }
3723
3724 void CMergeEditView::RecalcPageLayouts (CDC * pDC, CPrintInfo * pInfo)
3725 {
3726         for (int pane = 0; pane < GetDocument()->m_nBuffers; pane++)
3727                 GetDocument()->GetView(m_nThisGroup, pane)->CGhostTextView::RecalcPageLayouts(pDC, pInfo);
3728 }
3729
3730 /**
3731 * @brief Prints or previews both panes.
3732 * @param pDC [in] points to the printer device context
3733 * @param pInfo [in] points to a CPrintInfo structure that describes the current print job
3734 */
3735 void CMergeEditView::OnPrint(CDC* pDC, CPrintInfo* pInfo) 
3736 {
3737         CRect rDraw = pInfo->m_rectDraw;
3738         CSize sz = rDraw.Size();
3739         CMergeDoc *pDoc = GetDocument();
3740
3741         SIZE szLeftTop{}, szRightBottom{};
3742         GetPrintMargins(szLeftTop.cx, szLeftTop.cy, szRightBottom.cx, szRightBottom.cy);
3743         pDC->HIMETRICtoLP(&szLeftTop);
3744         pDC->HIMETRICtoLP(&szRightBottom);
3745         
3746         int midX = (sz.cx - szLeftTop.cx - szRightBottom.cx) / pDoc->m_nBuffers;
3747
3748         // print pane
3749         for (int pane = 0; pane < pDoc->m_nBuffers; pane++)
3750         {
3751                 pInfo->m_rectDraw.left = rDraw.left + midX * pane;
3752                 pInfo->m_rectDraw.right = pInfo->m_rectDraw.left + midX + szLeftTop.cx + szRightBottom.cx;
3753                 CMergeEditView* pPane = pDoc->GetView(m_nThisGroup, pane);
3754                 pPane->CGhostTextView::OnPrint(pDC, pInfo);
3755         }
3756 }
3757
3758 bool CMergeEditView::IsInitialized() const
3759 {
3760         CMergeEditView * pThis = const_cast<CMergeEditView *>(this);
3761         CDiffTextBuffer * pBuffer = dynamic_cast<CDiffTextBuffer *>(pThis->LocateTextBuffer());
3762         return pBuffer->IsInitialized();
3763 }
3764
3765 /**
3766  * @brief returns the number of empty lines which are added for synchronizing the line in two/three panes.
3767  */
3768 int CMergeEditView::GetEmptySubLines( int nLineIndex )
3769 {
3770         int     nBreaks[3] = {0};
3771         int nMaxBreaks = -1;
3772         CMergeDoc * pDoc = GetDocument();
3773         for (int nPane = 0; nPane < pDoc->m_nBuffers; nPane++) 
3774         {
3775                 CMergeEditView *pView = GetGroupView(nPane);
3776                 if (pView != nullptr)
3777                 {
3778                         if (nLineIndex >= pView->GetLineCount())
3779                                 return 0;
3780                         pView->WrapLineCached( nLineIndex, pView->GetScreenChars(), nullptr, nBreaks[nPane] );
3781                 }
3782                 nMaxBreaks = (std::max)(nMaxBreaks, nBreaks[nPane]);
3783         }
3784
3785         if (nBreaks[m_nThisPane] < nMaxBreaks)
3786                 return nMaxBreaks - nBreaks[m_nThisPane];
3787         else
3788                 return 0;
3789 }
3790
3791 /**
3792  * @brief Invalidate sub line index cache from the specified index to the end of file.
3793  * @param [in] nLineIndex Index of the first line to invalidate 
3794  */
3795 void CMergeEditView::InvalidateSubLineIndexCache( int nLineIndex )
3796 {
3797         CMergeDoc * pDoc = GetDocument();
3798         ASSERT(pDoc != nullptr);
3799
3800     // We have to invalidate sub line index cache on both panes.
3801         for (int nPane = 0; nPane < pDoc->m_nBuffers; nPane++) 
3802         {
3803                 CMergeEditView *pView = GetGroupView(nPane);
3804                 if (pView != nullptr)
3805                         pView->CCrystalTextView::InvalidateSubLineIndexCache( nLineIndex );
3806         }
3807 }
3808
3809 void CMergeEditView::SetWordWrapping( bool bWordWrap )
3810 {
3811         for (int pane = 0; pane < GetDocument()->m_nBuffers; pane++)
3812                 GetGroupView(pane)->m_bWordWrap = bWordWrap;
3813         CCrystalTextView::SetWordWrapping(bWordWrap);
3814 }
3815
3816 /**
3817 * @brief Determine if difference is visible on screen.
3818 * @param [in] nDiff Number of diff to check.
3819 * @return true if difference is visible.
3820 */
3821 bool CMergeEditView::IsDiffVisible(int nDiff)
3822 {
3823         const CMergeDoc *pd = GetDocument();
3824
3825         DIFFRANGE diff;
3826         pd->m_diffList.GetDiff(nDiff, diff);
3827
3828         return IsDiffVisible(diff);
3829 }
3830
3831 /**
3832  * @brief Determine if difference is visible on screen.
3833  * @param [in] diff diff to check.
3834  * @param [in] nLinesBelow Allow "minimizing" the number of visible lines.
3835  * @return true if difference is visible, false otherwise.
3836  */
3837 bool CMergeEditView::IsDiffVisible(const DIFFRANGE& diff, int nLinesBelow /*=0*/)
3838 {
3839         const int nDiffStart = GetSubLineIndex(diff.dbegin);
3840         const int nDiffEnd = GetSubLineIndex(diff.dend);
3841         // Diff's height is last line - first line + last line's line count
3842         const int nDiffHeight = nDiffEnd - nDiffStart + GetSubLines(diff.dend) + 1;
3843
3844         // If diff first line outside current view - context OR
3845         // if diff last line outside current view - context OR
3846         // if diff is bigger than screen
3847         if ((nDiffStart < m_nTopSubLine) ||
3848                 (nDiffEnd >= m_nTopSubLine + GetScreenLines() - nLinesBelow) ||
3849                 (nDiffHeight >= GetScreenLines()))
3850         {
3851                 return false;
3852         }
3853         else
3854         {
3855                 return true;
3856         }
3857 }
3858
3859 /** @brief Open help from mainframe when user presses F1*/
3860 void CMergeEditView::OnHelp()
3861 {
3862         theApp.ShowHelp(MergeViewHelpLocation);
3863 }
3864
3865 /**
3866  * @brief Called after document is loaded.
3867  * This function is called from CMergeDoc::OpenDocs() after documents are
3868  * loaded. So this is good place to set View's options etc.
3869  */
3870 void CMergeEditView::DocumentsLoaded()
3871 {
3872         if (GetDocument()->m_ptBuf[m_nThisPane]->GetTableEditing())
3873         {
3874                 SetTopMargin(GetOptionsMgr()->GetBool(OPT_VIEW_TOPMARGIN_TABLE));
3875                 SetLineUsedAsHeaders(GetOptionsMgr()->GetInt(OPT_LINE_NUMBER_USED_AS_HEADERS));
3876                 if (m_nThisPane == GetDocument()->m_nBuffers - 1 && !m_bDetailView)
3877                         AutoFitColumn();
3878         }
3879         else
3880         {
3881                 SetTopMargin(GetOptionsMgr()->GetBool(OPT_VIEW_TOPMARGIN));
3882         }
3883
3884         // SetTextType will revert to language dependent defaults for tab
3885         SetTabSize(GetOptionsMgr()->GetInt(OPT_TAB_SIZE));
3886         SetViewTabs(GetOptionsMgr()->GetBool(OPT_VIEW_WHITESPACE));
3887         const bool mixedEOLs = GetOptionsMgr()->GetBool(OPT_ALLOW_MIXED_EOL) ||
3888                 GetDocument()->IsMixedEOL(m_nThisPane);
3889         SetViewEols(GetOptionsMgr()->GetBool(OPT_VIEW_EOL), mixedEOLs);
3890         SetWordWrapping(GetOptionsMgr()->GetBool(GetDocument()->m_ptBuf[m_nThisPane]->GetTableEditing() ?
3891                 OPT_WORDWRAP_TABLE : OPT_WORDWRAP));
3892         SetViewLineNumbers(GetOptionsMgr()->GetBool(OPT_VIEW_LINENUMBERS));
3893         SetSelectionMargin(GetOptionsMgr()->GetBool(OPT_VIEW_FILEMARGIN));
3894
3895         // Enable Backspace at beginning of line
3896         SetDisableBSAtSOL(false);
3897
3898         // Set tab type (tabs/spaces)
3899         bool bInsertTabs = (GetOptionsMgr()->GetInt(OPT_TAB_TYPE) == 0);
3900         SetInsertTabs(bInsertTabs);
3901
3902         // Sometimes WinMerge doesn't update scrollbars correctly (they remain
3903         // disabled) after docs are open in screen. So lets make sure they are
3904         // really updated, even though this is unnecessary in most cases.
3905         InvalidateHorzScrollBar();
3906         InvalidateVertScrollBar();
3907 }
3908
3909 /**
3910  * @brief Update LocationView position.
3911  * This function updates LocationView position to given lines.
3912  * Usually we want to lines in file compare view and area in
3913  * LocationView to match. Be extra carefull to not call non-existing
3914  * LocationView.
3915  * @param [in] nTopLine Top line of current view.
3916  * @param [in] nBottomLine Bottom line of current view.
3917  */
3918 void CMergeEditView::UpdateLocationViewPosition(int nTopLine /*=-1*/,
3919                 int nBottomLine /*= -1*/)
3920 {
3921         CMergeDoc *pDoc = GetDocument();
3922         if (pDoc == nullptr)
3923                 return;
3924
3925         CLocationView *pLocationView = pDoc->GetLocationView();
3926
3927         if (pLocationView != nullptr && IsWindow(pLocationView->GetSafeHwnd()))
3928         {
3929                 pLocationView->UpdateVisiblePos(nTopLine, nBottomLine);
3930         }
3931 }
3932
3933 /**
3934  * @brief Enable/Disable view's selection margins.
3935  * Selection margins show bookmarks and word-wrap symbols, so they are pretty
3936  * useful. But it appears many users don't use/need those features and for them
3937  * selection margins are just wasted screen estate.
3938  */
3939 void CMergeEditView::OnViewMargin()
3940 {
3941         bool bViewMargin = GetOptionsMgr()->GetBool(OPT_VIEW_FILEMARGIN);
3942         GetOptionsMgr()->SaveOption(OPT_VIEW_FILEMARGIN, !bViewMargin);
3943
3944         SetSelectionMargin(!bViewMargin);
3945         CMergeDoc *pDoc = GetDocument();
3946         pDoc->RefreshOptions();
3947         pDoc->UpdateAllViews(this);
3948 }
3949
3950 /**
3951  * @brief Update GUI for Enable/Disable view's selection margin.
3952  * @param [in] pCmdUI Pointer to UI item to update.
3953  */
3954 void CMergeEditView::OnUpdateViewMargin(CCmdUI* pCmdUI)
3955 {
3956         pCmdUI->Enable(true);
3957         pCmdUI->SetCheck(GetOptionsMgr()->GetBool(OPT_VIEW_FILEMARGIN));
3958 }
3959
3960 /**
3961  * @brief Enable/Disable view's top margins.
3962  */
3963 void CMergeEditView::OnViewTopMargin()
3964 {
3965         bool bTableEditing = GetDocument()->m_ptBuf[m_nThisPane]->GetTableEditing();
3966         bool bViewMargin = GetOptionsMgr()->GetBool(bTableEditing ? OPT_VIEW_TOPMARGIN_TABLE : OPT_VIEW_TOPMARGIN);
3967         GetOptionsMgr()->SaveOption(bTableEditing ? OPT_VIEW_TOPMARGIN_TABLE : OPT_VIEW_TOPMARGIN, !bViewMargin);
3968
3969         SetTopMargin(!bViewMargin);
3970         CMergeDoc *pDoc = GetDocument();
3971         pDoc->RefreshOptions();
3972         pDoc->UpdateAllViews(this);
3973 }
3974
3975 /**
3976  * @brief Update GUI for Enable/Disable view's top margin.
3977  * @param [in] pCmdUI Pointer to UI item to update.
3978  */
3979 void CMergeEditView::OnUpdateViewTopMargin(CCmdUI* pCmdUI)
3980 {
3981         pCmdUI->Enable(true);
3982         pCmdUI->SetCheck(GetOptionsMgr()->GetBool(
3983                 GetDocument()->m_ptBuf[m_nThisPane]->GetTableEditing() ? OPT_VIEW_TOPMARGIN_TABLE : OPT_VIEW_TOPMARGIN));
3984 }
3985
3986 void CMergeEditView::OnUseFirstLineAsHeaders()
3987 {
3988         bool bUseFirstLineAsHeaders = GetOptionsMgr()->GetInt(OPT_LINE_NUMBER_USED_AS_HEADERS) != -1;
3989         GetOptionsMgr()->SaveOption(OPT_LINE_NUMBER_USED_AS_HEADERS, !bUseFirstLineAsHeaders ? 0 : -1);
3990
3991         SetLineUsedAsHeaders(!bUseFirstLineAsHeaders ? 0 : -1);
3992         CMergeDoc *pDoc = GetDocument();
3993         pDoc->RefreshOptions();
3994         pDoc->UpdateAllViews(this);
3995 }
3996
3997 void CMergeEditView::OnUpdateUseFirstLineAsHeaders(CCmdUI* pCmdUI)
3998 {
3999         pCmdUI->Enable(true);
4000         pCmdUI->SetCheck(GetOptionsMgr()->GetInt(OPT_LINE_NUMBER_USED_AS_HEADERS) != -1);
4001 }
4002
4003 void CMergeEditView::OnAutoFitAllColumns()
4004 {
4005         AutoFitColumn();
4006 }
4007
4008 /**
4009 * @brief Create the "Change Scheme" sub menu.
4010 * @param [in] pCmdUI Pointer to UI item to update.
4011 */
4012 void CMergeEditView::OnUpdateViewChangeScheme(CCmdUI *pCmdUI)
4013 {
4014         // Delete the place holder menu.
4015         pCmdUI->m_pSubMenu->DeleteMenu(0, MF_BYPOSITION);
4016
4017         const HMENU hSubMenu = pCmdUI->m_pSubMenu->m_hMenu;
4018
4019         String name = theApp.LoadString(ID_COLORSCHEME_FIRST);
4020         AppendMenu(hSubMenu, MF_STRING, ID_COLORSCHEME_FIRST, name.c_str());
4021
4022         for (int i = ID_COLORSCHEME_FIRST + 1, j = 0; i <= ID_COLORSCHEME_LAST; ++i, ++j)
4023         {
4024                 name = theApp.LoadString(i);
4025                 AppendMenu(hSubMenu, MF_STRING | (((j % 22) == 21) ? MF_MENUBREAK : 0), i, name.c_str());
4026         }
4027
4028         pCmdUI->Enable(true);
4029 }
4030
4031 /**
4032 * @brief Change the editor's syntax highlighting scheme.
4033 * @param [in] nID Selected color scheme sub menu id.
4034 */
4035 void CMergeEditView::OnChangeScheme(UINT nID)
4036 {
4037         CMergeDoc *pDoc = GetDocument();
4038         ASSERT(pDoc != nullptr);
4039         pDoc->SetTextType(nID - ID_COLORSCHEME_FIRST);
4040         pDoc->FlushAndRescan(true);
4041 }
4042
4043 /**
4044 * @brief Enable all color schemes sub menu items.
4045 * @param [in] pCmdUI Pointer to UI item to update.
4046 */
4047 void CMergeEditView::OnUpdateChangeScheme(CCmdUI* pCmdUI)
4048 {
4049         const bool bIsCurrentScheme = (static_cast<UINT>(m_CurSourceDef->type) == (pCmdUI->m_nID - ID_COLORSCHEME_FIRST));
4050         pCmdUI->SetRadio(bIsCurrentScheme);
4051         pCmdUI->Enable(GetOptionsMgr()->GetBool(OPT_SYNTAX_HIGHLIGHT));
4052 }
4053
4054 /**
4055  * @brief Called when mouse's wheel is scrolled.
4056  */
4057 BOOL CMergeEditView::OnMouseWheel(UINT nFlags, short zDelta, CPoint pt)
4058 {
4059         if ( nFlags == MK_CONTROL )
4060         {
4061                 short amount = zDelta < 0 ? -1: 1;
4062                 ZoomText(amount);
4063
4064                 // no default CCrystalTextView
4065                 return CView::OnMouseWheel(nFlags, zDelta, pt);
4066         }
4067
4068         if (nFlags == MK_SHIFT)
4069         {
4070                 SCROLLINFO si = { sizeof SCROLLINFO };
4071                 si.fMask = SIF_PAGE | SIF_POS | SIF_RANGE;
4072
4073                 VERIFY(GetScrollInfo(SB_HORZ, &si));
4074
4075                 // new horz pos
4076                 si.nPos -= zDelta / 40;
4077                 if (si.nPos > si.nMax) si.nPos = si.nMax;
4078                 if (si.nPos < si.nMin) si.nPos = si.nMin;
4079
4080                 SetScrollInfo(SB_HORZ, &si);
4081
4082                 // for update
4083                 SendMessage(WM_HSCROLL, MAKEWPARAM(SB_THUMBPOSITION, si.nPos) , NULL );
4084
4085                 // no default CCrystalTextView
4086                 return CView::OnMouseWheel(nFlags, zDelta, pt);
4087         }
4088
4089         return CGhostTextView::OnMouseWheel(nFlags, zDelta, pt);
4090 }
4091
4092 /**
4093  * @brief Called when mouse's horizontal wheel is scrolled.
4094  */
4095 void CMergeEditView::OnMouseHWheel(UINT nFlags, short zDelta, CPoint pt)
4096 {
4097         SCROLLINFO si = { sizeof SCROLLINFO };
4098         si.fMask = SIF_PAGE | SIF_POS | SIF_RANGE;
4099
4100         VERIFY(GetScrollInfo(SB_HORZ, &si));
4101
4102         // new horz pos
4103         si.nPos += zDelta / 40;
4104         if (si.nPos > si.nMax) si.nPos = si.nMax;
4105         if (si.nPos < si.nMin) si.nPos = si.nMin;
4106
4107         SetScrollInfo(SB_HORZ, &si);
4108
4109         // for update
4110         SendMessage(WM_HSCROLL, MAKEWPARAM(SB_THUMBPOSITION, si.nPos) , NULL );
4111
4112         // no default CCrystalTextView
4113         CView::OnMouseHWheel(nFlags, zDelta, pt);
4114 }
4115
4116 /**
4117  * @brief Change font size (zoom) in views.
4118  * @param [in] amount Amount of change/zoom, negative number makes
4119  *  font smaller, positive number bigger and 0 reset the font size.
4120  */
4121 void CMergeEditView::ZoomText(short amount)
4122 {
4123         LOGFONT lf = { 0 };
4124         GetFont(lf);
4125
4126         const int nLogPixelsY = CClientDC(this).GetDeviceCaps(LOGPIXELSY);
4127         int nPointSize = -MulDiv(lf.lfHeight, 72, nLogPixelsY);
4128
4129         int nOrgPointSize = GetOptionsMgr()->GetInt(OPT_FONT_FILECMP + OPT_FONT_POINTSIZE);
4130         if (nOrgPointSize ==  0)
4131                 nOrgPointSize = -MulDiv(GetOptionsMgr()->GetInt(OPT_FONT_FILECMP + OPT_FONT_HEIGHT), 72, nLogPixelsY);
4132
4133         if ( amount == 0)
4134                 nPointSize = nOrgPointSize;
4135
4136         nPointSize += amount;
4137         if (nPointSize < 2)
4138                 nPointSize = 2;
4139
4140         lf.lfHeight = -MulDiv(nPointSize, nLogPixelsY, 72);
4141
4142         CMergeDoc *pDoc = GetDocument();
4143         ASSERT(pDoc != nullptr);
4144
4145         if (pDoc != nullptr)
4146         {
4147                 for (int nPane = 0; nPane < pDoc->m_nBuffers; nPane++) 
4148                 {
4149                         CMergeEditView *pView = GetGroupView(nPane);
4150                         ASSERT(pView != nullptr);
4151                         
4152                         if (pView != nullptr)
4153                         {
4154                                 pView->SetFont(lf);
4155                         }
4156                 }
4157         }
4158
4159         GetOptionsMgr()->SaveOption(OPT_VIEW_ZOOM, nPointSize * 1000 / nOrgPointSize);
4160 }
4161
4162 bool CMergeEditView::QueryEditable()
4163 {
4164         return m_bDetailView ? false : !GetDocument()->m_ptBuf[m_nThisPane]->GetReadOnly();
4165 }
4166
4167 /**
4168  * @brief Adjust the point to remain in the displayed diff
4169  *
4170  * @return Tells if the point has been changed
4171  */
4172 bool CMergeEditView::EnsureInDiff(CEPoint& pt)
4173 {
4174         int nLineCount = GetLineCount();
4175         if (m_lineBegin >= nLineCount)
4176                 m_lineBegin = nLineCount - 1;
4177         if (m_lineEnd >= nLineCount)
4178                 m_lineEnd = nLineCount - 1;
4179
4180         int diffLength = m_lineEnd - m_lineBegin + 1;
4181         // first get the degenerate case out of the way
4182         // no diff ?
4183         if (diffLength == 0)
4184         {
4185                 if (pt.y == m_lineBegin && pt.x == 0)
4186                         return false;
4187                 pt.y = m_lineBegin;
4188                 pt.x = 0;
4189                 return true;
4190         }
4191
4192         // not above diff
4193         if (pt.y < m_lineBegin)
4194         {
4195                 pt.y = m_lineBegin;
4196                 pt.x = 0;
4197                 return true;
4198         }
4199         // diff is defined and not below diff
4200         if (m_lineEnd > -1 && pt.y > m_lineEnd)
4201         {
4202                 pt.y = m_lineEnd;
4203                 pt.x = GetLineLength(pt.y);
4204                 return true;
4205         }
4206         return false;
4207 }
4208
4209 void CMergeEditView::EnsureVisible(CEPoint pt)
4210 {
4211         CEPoint ptNew = pt;
4212         if (m_bDetailView)
4213         {
4214                 // ensure we remain in diff
4215                 if (EnsureInDiff(ptNew))
4216                         SetCursorPos(ptNew);
4217         }
4218         CCrystalTextView::EnsureVisible(ptNew);
4219 }
4220
4221 void CMergeEditView::EnsureVisible(CEPoint ptStart, CEPoint ptEnd)
4222 {
4223         CCrystalTextView::EnsureVisible(ptStart, ptEnd);
4224 }
4225
4226 void CMergeEditView::SetSelection(const CEPoint& ptStart, const CEPoint& ptEnd, bool bUpdateView)
4227 {
4228         CEPoint ptStartNew = ptStart;
4229         CEPoint ptEndNew = ptEnd;
4230         if (m_bDetailView)
4231         {
4232                 // ensure we remain in diff
4233                 EnsureInDiff(ptStartNew);
4234                 EnsureInDiff(ptEndNew);
4235         }
4236         CCrystalTextView::SetSelection(ptStartNew, ptEndNew, bUpdateView);
4237 }
4238
4239 void CMergeEditView::ScrollToSubLine(int nNewTopLine, bool bNoSmoothScroll /*= FALSE*/, bool bTrackScrollBar /*= TRUE*/)
4240 {
4241         if (m_bDetailView)
4242         {
4243                 int nLineCount = GetLineCount();
4244                 if (m_lineBegin >= nLineCount)
4245                         m_lineBegin = nLineCount - 1;
4246                 if (m_lineEnd >= nLineCount)
4247                         m_lineEnd = nLineCount - 1;
4248
4249                 // ensure we remain in diff
4250                 int sublineBegin = GetSubLineIndex(m_lineBegin);
4251                 int sublineEnd = m_lineEnd < 0 ? -1 : GetSubLineIndex(m_lineEnd) + GetSubLines(m_lineEnd) - 1;
4252                 int diffLength = sublineEnd - sublineBegin + 1;
4253                 int displayLength = GetScreenLines();
4254                 if (diffLength <= displayLength)
4255                         nNewTopLine = sublineBegin;
4256                 else
4257                 {
4258                         if (nNewTopLine < sublineBegin)
4259                                 nNewTopLine = sublineBegin;
4260                         if (nNewTopLine + displayLength - 1 > sublineEnd)
4261                                 nNewTopLine = GetSubLineIndex(sublineEnd - displayLength + 1);
4262                 }
4263
4264                 CEPoint pt = GetCursorPos();
4265                 if (EnsureInDiff(pt))
4266                         SetCursorPos(pt);
4267
4268                 auto [ptSelStart, ptSelEnd] = GetSelection();
4269                 if (EnsureInDiff(ptSelStart) || EnsureInDiff(ptSelEnd))
4270                         SetSelection(ptSelStart, ptSelEnd);
4271         }
4272         CCrystalTextView::ScrollToSubLine(nNewTopLine, bNoSmoothScroll, bTrackScrollBar);
4273 }
4274
4275 void CMergeEditView::SetActivePane()
4276 {
4277         auto* pwndSplitterChild = GetParentSplitter(this, false);
4278         if (!pwndSplitterChild)
4279                 return;
4280         if (pwndSplitterChild->GetColumnCount() > 1)
4281                 pwndSplitterChild->SetActivePane(0, m_nThisPane);
4282         else
4283                 pwndSplitterChild->SetActivePane(m_nThisPane, 0);
4284 }
4285
4286 /**
4287  * @brief Called when user selects View/Zoom In from menu.
4288  */
4289 void CMergeEditView::OnViewZoomIn()
4290 {
4291         ZoomText(1);
4292 }
4293
4294 /**
4295  * @brief Called when user selects View/Zoom Out from menu.
4296  */
4297 void CMergeEditView::OnViewZoomOut()
4298 {
4299         ZoomText(-1);
4300 }
4301
4302 /**
4303  * @brief Called when user selects View/Zoom Normal from menu.
4304  */
4305 void CMergeEditView::OnViewZoomNormal()
4306 {
4307         ZoomText(0);
4308 }
4309
4310 void CMergeEditView::OnDropFiles(const std::vector<String>& tFiles)
4311 {
4312         if (tFiles.size() > 1 || paths::IsDirectory(tFiles[0]))
4313         {
4314                 GetMainFrame()->GetDropHandler()->GetCallback()(tFiles);
4315                 return;
4316         }
4317
4318         GetDocument()->ChangeFile(m_nThisPane, tFiles[0]);
4319 }
4320
4321 void CMergeEditView::OnWindowSplit()
4322 {
4323
4324         auto& wndSplitter = dynamic_cast<CMergeEditFrame *>(GetParentFrame())->GetSplitter();
4325         CMergeDoc *pDoc = GetDocument();
4326         int nBuffer = m_nThisPane;
4327         if (pDoc->m_nGroups <= 2)
4328         {
4329                 wndSplitter.SplitRow(1);
4330                 wndSplitter.EqualizeRows();
4331         }
4332         else
4333         {
4334                 wndSplitter.SetActivePane(0, 0);
4335                 wndSplitter.DeleteRow(1);
4336                 pDoc->GetView(0, nBuffer)->SetActivePane();
4337         }
4338 }
4339
4340 void CMergeEditView::OnUpdateWindowSplit(CCmdUI* pCmdUI)
4341 {
4342         pCmdUI->Enable(!m_bDetailView);
4343         pCmdUI->SetCheck(GetDocument()->m_nGroups > 2);
4344 }
4345
4346 void CMergeEditView::OnStatusBarClick(NMHDR* pNMHDR, LRESULT* pResult)
4347 {
4348         *pResult = 0;
4349         LPNMITEMACTIVATE pNMItemActivate = reinterpret_cast<LPNMITEMACTIVATE>(pNMHDR);
4350         const int pane = pNMItemActivate->iItem / 4;
4351         CMergeDoc* pDoc = GetDocument();
4352         if (pane >= pDoc->m_nBuffers || !GetParentFrame()->IsChild(CWnd::FromHandle(pNMItemActivate->hdr.hwndFrom)))
4353                 return;
4354
4355         switch (pNMItemActivate->iItem % 4)
4356         {
4357         case 0:
4358                 pDoc->GetView(0, pane)->PostMessage(WM_COMMAND, ID_EDIT_WMGOTO);
4359                 break;
4360         case 1:
4361                 pDoc->DoFileEncodingDialog(pane);
4362                 break;
4363         case 2:
4364         {
4365                 CPoint point;
4366                 ::GetCursorPos(&point);
4367
4368                 BCMenu menu;
4369                 VERIFY(menu.LoadMenu(IDR_POPUP_MERGEEDITFRAME_STATUSBAR_EOL));
4370                 theApp.TranslateMenu(menu.m_hMenu);
4371                 menu.GetSubMenu(0)->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y, GetDocument()->GetView(0, pane));
4372                 break;
4373         }
4374         case 3:
4375                 pDoc->m_ptBuf[pane]->SetReadOnly(!GetDocument()->m_ptBuf[pane]->GetReadOnly());
4376                 break;
4377         default:
4378                 break;
4379         }
4380 }