OSDN Git Service

Update CWindowsManagerDialog - check some pointers for null and made … (#824) (2)
[winmerge-jp/winmerge-jp.git] / Src / MergeDoc.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  MergeDoc.cpp
9  *
10  * @brief Implementation file for CMergeDoc
11  *
12  */
13
14 #include "StdAfx.h"
15 #include "MergeDoc.h"
16 #include <io.h>
17 #include <Poco/Timestamp.h>
18 #include "UnicodeString.h"
19 #include "Merge.h"
20 #include "MainFrm.h"
21 #include "DiffTextBuffer.h"
22 #include "Environment.h"
23 #include "MovedLines.h"
24 #include "MergeEditView.h"
25 #include "MergeEditFrm.h"
26 #include "DirDoc.h"
27 #include "files.h"
28 #include "FileTransform.h"
29 #include "unicoder.h"
30 #include "UniFile.h"
31 #include "OptionsDef.h"
32 #include "DiffFileInfo.h"
33 #include "SaveClosingDlg.h"
34 #include "OpenTableDlg.h"
35 #include "DiffList.h"
36 #include "paths.h"
37 #include "OptionsMgr.h"
38 #include "OptionsDiffOptions.h"
39 #include "MergeLineFlags.h"
40 #include "FileOrFolderSelect.h"
41 #include "LineFiltersList.h"
42 #include "SubstitutionFiltersList.h"
43 #include "TempFile.h"
44 #include "codepage_detect.h"
45 #include "SelectUnpackerDlg.h"
46 #include "EncodingErrorBar.h"
47 #include "MergeCmdLineInfo.h"
48 #include "TFile.h"
49 #include "Constants.h"
50 #include "Merge7zFormatMergePluginImpl.h"
51 #include "7zCommon.h"
52 #include "PatchTool.h"
53 #include "charsets.h"
54 #include "markdown.h"
55 #include "stringdiffs.h"
56
57 #ifdef _DEBUG
58 #define new DEBUG_NEW
59 #endif
60
61 using std::swap;
62
63 int CMergeDoc::m_nBuffersTemp = 2;
64
65 static void SaveBuffForDiff(CDiffTextBuffer & buf, const String& filepath, int nStartLine = 0, int nLines = -1);
66
67 /////////////////////////////////////////////////////////////////////////////
68 // CMergeDoc
69
70 IMPLEMENT_DYNCREATE(CMergeDoc, CDocument)
71
72 BEGIN_MESSAGE_MAP(CMergeDoc, CDocument)
73         //{{AFX_MSG_MAP(CMergeDoc)
74         ON_COMMAND(ID_FILE_SAVE, OnFileSave)
75         ON_COMMAND(ID_FILE_SAVE_LEFT, OnFileSaveLeft)
76         ON_COMMAND(ID_FILE_SAVE_MIDDLE, OnFileSaveMiddle)
77         ON_COMMAND(ID_FILE_SAVE_RIGHT, OnFileSaveRight)
78         ON_COMMAND(ID_FILE_SAVEAS_LEFT, OnFileSaveAsLeft)
79         ON_UPDATE_COMMAND_UI(ID_FILE_SAVEAS_MIDDLE, OnUpdateFileSaveAsMiddle)
80         ON_COMMAND(ID_FILE_SAVEAS_MIDDLE, OnFileSaveAsMiddle)
81         ON_COMMAND(ID_FILE_SAVEAS_RIGHT, OnFileSaveAsRight)
82         ON_UPDATE_COMMAND_UI(ID_STATUS_DIFFNUM, OnUpdateStatusNum)
83         ON_UPDATE_COMMAND_UI(ID_STATUS_PLUGIN, OnUpdatePluginName)
84         ON_COMMAND(ID_TOOLS_GENERATEREPORT, OnToolsGenerateReport)
85         ON_COMMAND(ID_TOOLS_GENERATEPATCH, OnToolsGeneratePatch)
86         ON_COMMAND(ID_RESCAN, OnFileReload)
87         ON_COMMAND(ID_FILE_ENCODING, OnFileEncoding)
88         ON_COMMAND_RANGE(ID_VIEW_DIFFCONTEXT_ALL, ID_VIEW_DIFFCONTEXT_INVERT, OnDiffContext)
89         ON_UPDATE_COMMAND_UI_RANGE(ID_VIEW_DIFFCONTEXT_ALL, ID_VIEW_DIFFCONTEXT_INVERT, OnUpdateDiffContext)
90         ON_COMMAND(ID_POPUP_OPEN_WITH_UNPACKER, OnCtxtOpenWithUnpacker)
91         ON_BN_CLICKED(IDC_FILEENCODING, OnBnClickedFileEncoding)
92         ON_BN_CLICKED(IDC_PLUGIN, OnBnClickedPlugin)
93         ON_BN_CLICKED(IDC_HEXVIEW, OnBnClickedHexView)
94         ON_COMMAND(IDOK, OnOK)
95         ON_COMMAND(ID_MERGE_COMPARE_TEXT, OnFileRecompareAsText)
96         ON_UPDATE_COMMAND_UI(ID_MERGE_COMPARE_TEXT, OnUpdateFileRecompareAsText)
97         ON_COMMAND(ID_MERGE_COMPARE_TABLE, OnFileRecompareAsTable)
98         ON_UPDATE_COMMAND_UI(ID_MERGE_COMPARE_TABLE, OnUpdateFileRecompareAsTable)
99         ON_COMMAND(ID_MERGE_COMPARE_XML, OnFileRecompareAsXML)
100         ON_UPDATE_COMMAND_UI(ID_MERGE_COMPARE_XML, OnUpdateFileRecompareAsXML)
101         ON_COMMAND_RANGE(ID_MERGE_COMPARE_HEX, ID_MERGE_COMPARE_IMAGE, OnFileRecompareAs)
102         ON_UPDATE_COMMAND_UI_RANGE(ID_SWAPPANES_SWAP23, ID_SWAPPANES_SWAP13, OnUpdateSwapContext)
103         //}}AFX_MSG_MAP
104 END_MESSAGE_MAP()
105
106 /////////////////////////////////////////////////////////////////////////////
107 // CMergeDoc construction/destruction
108
109 /**
110  * @brief Constructor.
111  */
112 CMergeDoc::CMergeDoc()
113 : m_bEnableRescan(true)
114 , m_nCurDiff(-1)
115 , m_CurWordDiff{ -1, static_cast<size_t>(-1), -1 }
116 , m_pDirDoc(nullptr)
117 , m_bMixedEol(false)
118 , m_pInfoUnpacker(new PackingInfo)
119 , m_pEncodingErrorBar(nullptr)
120 , m_bHasSyncPoints(false)
121 , m_bAutoMerged(false)
122 , m_nGroups(0)
123 , m_pView{nullptr}
124 , m_bAutomaticRescan(false)
125 {
126         DIFFOPTIONS options = {0};
127
128         m_nBuffers = m_nBuffersTemp;
129         m_filePaths.SetSize(m_nBuffers);
130
131         for (int nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
132         {
133                 m_ptBuf[nBuffer].reset(new CDiffTextBuffer(this, nBuffer));
134                 m_pSaveFileInfo[nBuffer].reset(new DiffFileInfo());
135                 m_pRescanFileInfo[nBuffer].reset(new DiffFileInfo());
136                 m_nBufferType[nBuffer] = BUFFERTYPE::NORMAL;
137                 m_bEditAfterRescan[nBuffer] = false;
138         }
139
140         m_bEnableRescan = true;
141         m_bAutomaticRescan = GetOptionsMgr()->GetBool(OPT_AUTOMATIC_RESCAN);
142
143         // COleDateTime m_LastRescan
144         curUndo = undoTgt.begin();
145         m_nDiffContext = GetOptionsMgr()->GetInt(OPT_DIFF_CONTEXT);
146         m_bInvertDiffContext = GetOptionsMgr()->GetBool(OPT_INVERT_DIFF_CONTEXT);
147
148         m_diffWrapper.SetDetectMovedBlocks(GetOptionsMgr()->GetBool(OPT_CMP_MOVED_BLOCKS));
149         Options::DiffOptions::Load(GetOptionsMgr(), options);
150
151         m_diffWrapper.SetOptions(&options);
152         m_diffWrapper.SetPrediffer(nullptr);
153 }
154
155 /**
156  * @brief Destructor.
157  *
158  * Informs associated dirdoc that mergedoc is closing.
159  */
160 CMergeDoc::~CMergeDoc()
161 {       
162         if (m_pDirDoc != nullptr)
163         {
164                 m_pDirDoc->MergeDocClosing(this);
165                 m_pDirDoc = nullptr;
166         }
167 }
168
169 /**
170  * @brief Deleted data associated with doc before closing.
171  */
172 void CMergeDoc::DeleteContents ()
173 {
174         CDocument::DeleteContents ();
175         for (int nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
176         {
177                 m_ptBuf[nBuffer]->FreeAll ();
178                 m_tempFiles[nBuffer].Delete();
179         }
180 }
181
182 /**
183  * @brief Called when new document is created.
184  *
185  * Initialises buffers.
186  */
187 BOOL CMergeDoc::OnNewDocument()
188 {
189         if (!CDocument::OnNewDocument())
190                 return false;
191
192         SetTitle(_("File Comparison").c_str());
193         
194         for (int nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
195                 m_ptBuf[nBuffer]->InitNew ();
196         return true;
197 }
198
199 /**
200  * @brief Return active merge edit view (or left one if neither active)
201  */
202 CMergeEditView * CMergeDoc::GetActiveMergeView()
203 {
204         CView * pActiveView = GetParentFrame()->GetActiveView();
205         CMergeEditView * pMergeEditView = dynamic_cast<CMergeEditView *>(pActiveView);
206         if (pMergeEditView == nullptr)
207                 pMergeEditView = GetView(0, 0); // default to left view (in case some location or detail view active)
208         return pMergeEditView;
209 }
210
211 CMergeEditView * CMergeDoc::GetActiveMergeGroupView(int nBuffer)
212 {
213         return m_pView[GetActiveMergeView()->m_nThisGroup][nBuffer];
214 }
215
216 void CMergeDoc::SetUnpacker(const PackingInfo * infoNewHandler)
217 {
218         if (infoNewHandler != nullptr)
219         {
220                 *m_pInfoUnpacker = *infoNewHandler;
221         }
222 }
223
224 void CMergeDoc::SetPrediffer(const PrediffingInfo * infoPrediffer)
225 {
226         m_diffWrapper.SetPrediffer(infoPrediffer);
227 }
228 void CMergeDoc::GetPrediffer(PrediffingInfo * infoPrediffer)
229 {
230         m_diffWrapper.GetPrediffer(infoPrediffer);
231 }
232
233 /////////////////////////////////////////////////////////////////////////////
234 // CMergeDoc serialization
235
236 void CMergeDoc::Serialize(CArchive& ar)
237 {
238         ASSERT(false); // we do not use CDocument serialization
239 }
240
241 /////////////////////////////////////////////////////////////////////////////
242 // CMergeDoc commands
243
244 /**
245  * @brief Save an editor text buffer to a file for prediffing (make UCS-2LE if appropriate)
246  *
247  * @note 
248  * original file is Ansi : 
249  *   buffer  -> save as Ansi -> Ansi plugins -> diffutils
250  * original file is Unicode (UCS2-LE, UCS2-BE, UTF-8) :
251  *   buffer  -> save as UTF-8 -> Unicode plugins -> convert to UTF-8 -> diffutils
252  * (the plugins are optional, not the conversion)
253  * @todo Show SaveToFile() errors?
254  */
255 static void SaveBuffForDiff(CDiffTextBuffer & buf, const String& filepath, int nStartLine, int nLines)
256 {
257         // and we don't repack the file
258         PackingInfo * tempPacker = nullptr;
259
260         // write buffer out to temporary file
261         String sError;
262         int retVal = buf.SaveToFile(filepath, true, sError, tempPacker,
263                 CRLFSTYLE::AUTOMATIC, false, nStartLine, nLines);
264 }
265
266 /**
267  * @brief Save files to temp files & compare again.
268  *
269  * @param bBinary [in,out] [in] If true, compare two binary files
270  * [out] If true binary file was detected.
271  * @param bIdentical [out] If true files were identical
272  * @param bForced [in] If true, suppressing is ignored and rescan
273  * is done always
274  * @return Tells if rescan was successfully, was suppressed, or
275  * error happened
276  * If this code is OK, Rescan has detached the views temporarily
277  * (positions of cursors have been lost)
278  * @note Rescan() ALWAYS compares temp files. Actual user files are not
279  * touched by Rescan().
280  * @sa CDiffWrapper::RunFileDiff()
281  */
282 int CMergeDoc::Rescan(bool &bBinary, IDENTLEVEL &identical,
283                 bool bForced /* =false */)
284 {
285         DIFFOPTIONS diffOptions = {0};
286         DiffFileInfo fileInfo;
287         bool diffSuccess = false;
288         int nResult = RESCAN_OK;
289         FileChange Changed[3] = {FileChange::NoChange, FileChange::NoChange, FileChange::NoChange};
290         int nBuffer;
291
292         if (!bForced)
293         {
294                 if (!m_bEnableRescan)
295                         return RESCAN_SUPPRESSED;
296         }
297
298         ClearWordDiffCache();
299
300         if (GetOptionsMgr()->GetBool(OPT_LINEFILTER_ENABLED))
301         {
302                 m_diffWrapper.SetFilterList(theApp.m_pLineFilters->GetAsString());
303         }
304         else
305         {
306                 m_diffWrapper.SetFilterList(_T(""));
307         }
308
309         if (theApp.m_pSubstitutionFiltersList && theApp.m_pSubstitutionFiltersList->GetEnabled())
310         {
311                 m_diffWrapper.SetSubstitutionList(theApp.m_pSubstitutionFiltersList->MakeSubstitutionList());
312         }
313         else
314         {
315                 m_diffWrapper.SetSubstitutionList(nullptr);
316         }
317
318         if (GetView(0, 0)->m_CurSourceDef->type != 0)
319                 m_diffWrapper.SetFilterCommentsSourceDef(GetView(0, 0)->m_CurSourceDef);
320         else
321                 m_diffWrapper.SetFilterCommentsSourceDef(GetFileExt(m_filePaths[0].c_str(), m_strDesc[0].c_str()));
322
323         for (nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
324         {
325                 // Check if files have been modified since last rescan
326                 // Ignore checking in case of scratchpads (empty filenames)
327                 if (!m_filePaths[nBuffer].empty())
328                 {
329                         Changed[nBuffer] = IsFileChangedOnDisk(m_filePaths[nBuffer].c_str(),
330                                         fileInfo, false, nBuffer);
331                 }
332         }
333         m_LastRescan = COleDateTime::GetCurrentTime();
334
335         LPCTSTR tnames[] = {_T("t0_wmdoc"), _T("t1_wmdoc"), _T("t2_wmdoc")};
336         for (nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
337         {
338                 if (Changed[nBuffer] == FileChange::Removed)
339                 {
340                         String msg = strutils::format_string1(_("The file\n%1\nhas disappeared. Please save a copy of the file to continue."), m_filePaths[nBuffer]);
341                         ShowMessageBox(msg, MB_ICONWARNING);
342                         bool bSaveResult = false;
343                         bool ok = DoSaveAs(m_filePaths[nBuffer].c_str(), bSaveResult, nBuffer);
344                         if (!ok || !bSaveResult)
345                         {
346                                 return RESCAN_FILE_ERR;
347                         }
348                 }
349
350                 String temp = m_tempFiles[nBuffer].GetPath();
351                 if (temp.empty())
352                         temp = m_tempFiles[nBuffer].Create(tnames[nBuffer]);
353                 if (temp.empty())
354                         return RESCAN_TEMP_ERR;
355         }
356
357         CheckFileChanged();
358
359         String tempPath = env::GetTemporaryPath();
360
361         // Set up DiffWrapper
362         m_diffWrapper.GetOptions(&diffOptions);
363
364         // Clear diff list
365         m_diffList.Clear();
366         m_nCurDiff = -1;
367         m_CurWordDiff = { -1, static_cast<size_t>(-1), -1 };
368         // Clear moved lines lists
369         if (m_diffWrapper.GetDetectMovedBlocks())
370         {
371                 for (nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
372                         m_diffWrapper.GetMovedLines(nBuffer)->Clear();
373         }
374
375         // Set paths for diffing and run diff
376         m_diffWrapper.EnablePlugins(GetOptionsMgr()->GetBool(OPT_PLUGINS_ENABLED));
377         if (m_nBuffers < 3)
378                 m_diffWrapper.SetPaths(PathContext(m_tempFiles[0].GetPath(), m_tempFiles[1].GetPath()), true);
379         else
380                 m_diffWrapper.SetPaths(PathContext(m_tempFiles[0].GetPath(), m_tempFiles[1].GetPath(), m_tempFiles[2].GetPath()), true);
381         m_diffWrapper.SetCompareFiles(m_filePaths);
382
383         DIFFSTATUS status;
384
385         if (!HasSyncPoints())
386         {
387                 // Save text buffer to file
388                 for (nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
389                 {
390                         m_ptBuf[nBuffer]->SetTempPath(tempPath);
391                         SaveBuffForDiff(*m_ptBuf[nBuffer], m_tempFiles[nBuffer].GetPath());
392                 }
393
394                 m_diffWrapper.SetCreateDiffList(&m_diffList);
395                 diffSuccess = m_diffWrapper.RunFileDiff();
396
397                 // Read diff-status
398                 m_diffWrapper.GetDiffStatus(&status);
399                 if (bBinary) // believe caller if we were told these are binaries
400                         status.bBinaries = true;
401         }
402         else
403         {
404                 const std::vector<std::vector<int> > syncpoints = GetSyncPointList();   
405                 int nStartLine[3] = {0};
406                 int nLines[3], nRealLine[3];
407                 for (size_t i = 0; i <= syncpoints.size(); ++i)
408                 {
409                         // Save text buffer to file
410                         for (nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
411                         {
412                                 nLines[nBuffer] = (i >= syncpoints.size()) ? -1 : syncpoints[i][nBuffer] - nStartLine[nBuffer];
413                                 m_ptBuf[nBuffer]->SetTempPath(tempPath);
414                                 SaveBuffForDiff(*m_ptBuf[nBuffer], m_tempFiles[nBuffer].GetPath(), 
415                                         nStartLine[nBuffer], nLines[nBuffer]);
416                         }
417                         DiffList templist;
418                         templist.Clear();
419                         m_diffWrapper.SetCreateDiffList(&templist);
420                         diffSuccess = m_diffWrapper.RunFileDiff();
421                         for (nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
422                                 nRealLine[nBuffer] = m_ptBuf[nBuffer]->ComputeRealLine(nStartLine[nBuffer]);
423
424                         // Correct the comparison results made by diffutils if the first file separated by the sync point is an empty file.
425                         if (i == 0 && templist.GetSize() > 0)
426                                 for (nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
427                                         if (nStartLine[nBuffer] == 0)
428                                         {
429                                                 bool isEmptyFile = true;
430                                                 for (int j = 0; j < nLines[nBuffer]; j++)
431                                                 {
432                                                         if (!(m_ptBuf[nBuffer]->GetLineFlags(nStartLine[nBuffer] + j) & LF_GHOST))
433                                                         {
434                                                                 isEmptyFile = false;
435                                                                 break;
436                                                         }
437                                                 }
438                                                 if (isEmptyFile)
439                                                 {
440                                                         DIFFRANGE di;
441                                                         templist.GetDiff(0, di);
442                                                         if (di.begin[nBuffer] == 0 && di.end[nBuffer] == 0)
443                                                         {
444                                                                 di.end[nBuffer] = -1;
445                                                                 templist.SetDiff(0, di);
446                                                         }
447                                                 }
448                                         }
449
450                         m_diffList.AppendDiffList(templist, nRealLine);
451                         for (nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
452                                 nStartLine[nBuffer] += nLines[nBuffer];
453
454                         // Read diff-status
455                         DIFFSTATUS status_part;
456                         m_diffWrapper.GetDiffStatus(&status_part);
457                         if (bBinary) // believe caller if we were told these are binaries
458                                 status.bBinaries = true;
459                         status.MergeStatus(status_part);
460                 }
461                 m_diffWrapper.SetCreateDiffList(&m_diffList);
462         }
463
464         // If one file has EOL before EOF and other not...
465         if (std::count(status.bMissingNL, status.bMissingNL + m_nBuffers, status.bMissingNL[0]) < m_nBuffers)
466         {
467                 // ..last DIFFRANGE of file which has EOL must be
468                 // fixed to contain last line too
469                 int lineCount[3] = { 0,0,0 };
470                 for (nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
471                         lineCount[nBuffer] = m_ptBuf[nBuffer]->GetLineCount();
472                 m_diffWrapper.FixLastDiffRange(m_nBuffers, lineCount, status.bMissingNL, diffOptions.bIgnoreBlankLines);
473         }
474
475         // set identical/diff result as recorded by diffutils
476         identical = status.Identical;
477
478         // Determine errors and binary file compares
479         if (!diffSuccess)
480                 nResult = RESCAN_FILE_ERR;
481         else if (status.bBinaries)
482         {
483                 bBinary = true;
484         }
485         else
486         {
487                 // Now update views and buffers for ghost lines
488
489                 // Prevent displaying views during this update 
490                 // BTW, this solves the problem of double asserts
491                 // (during the display of an assert message box, a second assert in one of the 
492                 //  display functions happens, and hides the first assert)
493                 ForEachView([](auto& pView) { pView->DetachFromBuffer(); });
494
495                 // Remove blank lines and clear winmerge flags
496                 // this operation does not change the modified flag
497                 for (nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
498                         m_ptBuf[nBuffer]->prepareForRescan();
499
500                 // Divide diff blocks to match lines.
501                 if (GetOptionsMgr()->GetBool(OPT_CMP_MATCH_SIMILAR_LINES) && m_nBuffers < 3)
502                         AdjustDiffBlocks();
503
504                 // Analyse diff-list (updating real line-numbers)
505                 // this operation does not change the modified flag
506                 PrimeTextBuffers();
507
508                 // Hide identical lines if diff-context is not 'All'
509                 HideLines();
510
511                 // Apply flags to lines that are trivial
512                 PrediffingInfo infoPrediffer;
513                 GetPrediffer(&infoPrediffer);
514                 if (!infoPrediffer.m_PluginName.empty())
515                         FlagTrivialLines();
516                 
517                 // Apply flags to lines that moved, to differentiate from appeared/disappeared lines
518                 if (m_diffWrapper.GetDetectMovedBlocks())
519                         FlagMovedLines();
520                 
521                 // After PrimeTextBuffers() we know amount of real diffs
522                 // (m_nDiffs) and trivial diffs (m_nTrivialDiffs)
523
524                 // Identical files are also updated
525                 if (!m_diffList.HasSignificantDiffs())
526                         identical = IDENTLEVEL::ALL;
527
528                 ForEachView([](auto& pView) {
529                         // just apply some options to the views
530                         pView->PrimeListWithFile();
531                         // Now buffers data are valid
532                         pView->ReAttachToBuffer();
533                 });
534                 for (nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
535                 {
536                         m_bEditAfterRescan[nBuffer] = false;
537                 }
538         }
539
540         if (!GetOptionsMgr()->GetBool(OPT_CMP_IGNORE_CODEPAGE) &&
541                 identical == IDENTLEVEL::ALL &&
542                 std::any_of(m_ptBuf, m_ptBuf + m_nBuffers,
543                         [&](std::unique_ptr<CDiffTextBuffer>& buf) { return buf->getEncoding() != m_ptBuf[0]->getEncoding(); }))
544                 identical = IDENTLEVEL::NONE;
545
546         GetParentFrame()->SetLastCompareResult(identical != IDENTLEVEL::ALL ? 1 : 0);
547
548         return nResult;
549 }
550
551 void CMergeDoc::CheckFileChanged(void)
552 {
553         int nBuffer;
554         DiffFileInfo fileInfo;
555         FileChange FileChange[3];
556
557         for (nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
558         {
559                 FileChange[nBuffer] = IsFileChangedOnDisk(m_filePaths[nBuffer].c_str(), fileInfo,
560                         false, nBuffer);
561
562                 m_pRescanFileInfo[nBuffer]->Update((LPCTSTR)m_filePaths[nBuffer].c_str());
563         }
564
565         bool bDoReload = false;
566         for (nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
567         {
568                 if (FileChange[nBuffer] == FileChange::Changed)
569                 {
570                         String msg = strutils::format_string1(_("Another application has updated file\n%1\nsince WinMerge scanned it last time.\n\nDo you want to reload the file?"), m_filePaths[nBuffer]);
571                         if (ShowMessageBox(msg, MB_YESNO | MB_ICONWARNING | MB_DONT_ASK_AGAIN, IDS_FILECHANGED_RESCAN) == IDYES)
572                                 bDoReload = true;
573                         break;
574                 }
575         }
576         if (bDoReload)
577         {
578                 for (nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
579                 {
580                         if (FileChange[nBuffer] == FileChange::Changed)
581                         {
582                                 CPoint pt = GetView(0, nBuffer)->GetCursorPos();
583                                 ChangeFile(nBuffer, m_filePaths[nBuffer], pt.y);
584                         }
585                 }
586         }
587 }
588
589 /** @brief Apply flags to lines that are trivial */
590 void CMergeDoc::FlagTrivialLines(void)
591 {
592         for (int i = 0; i < m_ptBuf[0]->GetLineCount(); ++i)
593         {
594                 if ((m_ptBuf[0]->GetLineFlags(i) & LF_NONTRIVIAL_DIFF) == 0)
595                 {
596                         String str[3];
597                         for (int file = 0; file < m_nBuffers; ++file)
598                         {
599                                 const TCHAR *p = m_ptBuf[file]->GetLineChars(i);
600                                 str[file] = p ? p : _T("");
601                         }
602
603                         if (std::count(str + 1, str + m_nBuffers, str[0]) != m_nBuffers - 1)
604                         {
605                                 DIFFOPTIONS diffOptions = {0};
606                                 m_diffWrapper.GetOptions(&diffOptions);
607
608                                 // Make the call to stringdiffs, which does all the hard & tedious computations
609                                 std::vector<strdiff::wdiff> worddiffs = strdiff::ComputeWordDiffs(m_nBuffers, str,
610                                         !diffOptions.bIgnoreCase,
611                                         !diffOptions.bIgnoreEol,
612                                         diffOptions.nIgnoreWhitespace,
613                                         GetBreakType(), // whitespace only or include punctuation
614                                         GetByteColoringOption());
615                                 if (!worddiffs.empty())
616                                 {
617                                         for (int file = 0; file < m_nBuffers; ++file)
618                                                 m_ptBuf[file]->SetLineFlag(i, LF_TRIVIAL, true, false, false);
619                                 }
620                         }
621                 }
622         }
623 }
624
625 /** @brief Adjust all different lines that were detected as actually matching moved lines */
626 void CMergeDoc::FlagMovedLines(void)
627 {
628         int i;
629         MovedLines *pMovedLines;
630
631         pMovedLines = m_diffWrapper.GetMovedLines(0);
632         for (i = 0; i < m_ptBuf[0]->GetLineCount(); ++i)
633         {
634                 int j = pMovedLines->LineInBlock(i, MovedLines::SIDE::RIGHT);
635                 if (j != -1)
636                 {
637                         TRACE(_T("%d->%d\n"), i, j);
638                         ASSERT(j>=0);
639                         // We only flag lines that are already marked as being different
640                         int apparent = m_ptBuf[0]->ComputeApparentLine(i);
641                         if (m_ptBuf[0]->FlagIsSet(apparent, LF_DIFF))
642                         {
643                                 m_ptBuf[0]->SetLineFlag(apparent, LF_MOVED, true, false, false);
644                                 if (m_ptBuf[1]->FlagIsSet(apparent, LF_GHOST))
645                                 {
646                                         int apparentJ = m_ptBuf[1]->ComputeApparentLine(j);
647                                         if (m_ptBuf[0]->FlagIsSet(apparentJ, LF_GHOST))
648                                                 m_ptBuf[1]->SetLineFlag(apparent, LF_MOVED, true, false, false);
649                                 }
650                         }
651                 }
652         }
653
654         pMovedLines = m_diffWrapper.GetMovedLines(1);
655         for (i=0; i<m_ptBuf[1]->GetLineCount(); ++i)
656         {
657                 int j = pMovedLines->LineInBlock(i, MovedLines::SIDE::LEFT);
658                 if (j != -1)
659                 {
660                         TRACE(_T("%d->%d\n"), i, j);
661                         ASSERT(j>=0);
662                         // We only flag lines that are already marked as being different
663                         int apparent = m_ptBuf[1]->ComputeApparentLine(i);
664                         if (m_ptBuf[1]->FlagIsSet(apparent, LF_DIFF))
665                         {
666                                 m_ptBuf[1]->SetLineFlag(apparent, LF_MOVED, true, false, false);
667                                 if (m_ptBuf[0]->FlagIsSet(apparent, LF_GHOST))
668                                 {
669                                         int apparentJ = m_ptBuf[0]->ComputeApparentLine(j);
670                                         if (m_ptBuf[1]->FlagIsSet(apparentJ, LF_GHOST))
671                                                 m_ptBuf[0]->SetLineFlag(apparent, LF_MOVED, true, false, false);
672                                 }
673                         }
674                 }
675         }
676
677         if (m_nBuffers < 3)
678                 return;
679
680         pMovedLines = m_diffWrapper.GetMovedLines(1);
681         for (i=0; i<m_ptBuf[1]->GetLineCount(); ++i)
682         {
683                 int j = pMovedLines->LineInBlock(i, MovedLines::SIDE::RIGHT);
684                 if (j != -1)
685                 {
686                         TRACE(_T("%d->%d\n"), i, j);
687                         ASSERT(j>=0);
688                         // We only flag lines that are already marked as being different
689                         int apparent = m_ptBuf[1]->ComputeApparentLine(i);
690                         if (m_ptBuf[1]->FlagIsSet(apparent, LF_DIFF))
691                         {
692                                 m_ptBuf[1]->SetLineFlag(apparent, LF_MOVED, true, false, false);
693                                 if (m_ptBuf[2]->FlagIsSet(apparent, LF_GHOST))
694                                 {
695                                         int apparentJ = m_ptBuf[2]->ComputeApparentLine(j);
696                                         if (m_ptBuf[1]->FlagIsSet(apparentJ, LF_GHOST))
697                                                 m_ptBuf[2]->SetLineFlag(apparent, LF_MOVED, true, false, false);
698                                 }
699                         }
700                 }
701         }
702
703         pMovedLines = m_diffWrapper.GetMovedLines(2);
704         for (i=0; i<m_ptBuf[2]->GetLineCount(); ++i)
705         {
706                 int j = pMovedLines->LineInBlock(i, MovedLines::SIDE::LEFT);
707                 if (j != -1)
708                 {
709                         TRACE(_T("%d->%d\n"), i, j);
710                         ASSERT(j>=0);
711                         // We only flag lines that are already marked as being different
712                         int apparent = m_ptBuf[2]->ComputeApparentLine(i);
713                         if (m_ptBuf[2]->FlagIsSet(apparent, LF_DIFF))
714                         {
715                                 m_ptBuf[2]->SetLineFlag(apparent, LF_MOVED, true, false, false);
716                                 if (m_ptBuf[1]->FlagIsSet(apparent, LF_GHOST))
717                                 {
718                                         int apparentJ = m_ptBuf[1]->ComputeApparentLine(j);
719                                         if (m_ptBuf[2]->FlagIsSet(apparentJ, LF_GHOST))
720                                                 m_ptBuf[1]->SetLineFlag(apparent, LF_MOVED, true, false, false);
721                                 }
722                         }
723                 }
724         }
725
726         // todo: Need to record actual moved information
727 }
728
729 int CMergeDoc::ShowMessageBox(const String& sText, unsigned nType, unsigned nIDHelp)
730 {
731         if (m_pView[0][0] && m_pView[0][0]->IsTextBufferInitialized() && !GetParentFrame()->IsActivated())
732         {
733                 GetParentFrame()->InitialUpdateFrame(this, true);
734                 GetParentFrame()->SendMessageToDescendants(WM_IDLEUPDATECMDUI, static_cast<WPARAM>(true), 0, true, true);
735         }
736         return AfxMessageBox(sText.c_str(), nType, nIDHelp);
737 }
738
739 /**
740  * @brief Prints (error) message by rescan status.
741  *
742  * @param nRescanResult [in] Resultcocode from rescan().
743  * @param bIdentical [in] Were files identical?.
744  * @sa CMergeDoc::Rescan()
745  */
746 void CMergeDoc::ShowRescanError(int nRescanResult, IDENTLEVEL identical)
747 {
748         // Rescan was suppressed, there is no sensible status
749         if (nRescanResult == RESCAN_SUPPRESSED)
750                 return;
751
752         String s;
753
754         if (nRescanResult == RESCAN_FILE_ERR)
755         {
756                 s = _("An error occurred while comparing the files.");
757                 LogErrorString(s);
758                 ShowMessageBox(s, MB_ICONSTOP);
759                 return;
760         }
761
762         if (nRescanResult == RESCAN_TEMP_ERR)
763         {
764                 s = _("Temporary files could not be created. Check your temporary path settings.");
765                 LogErrorString(s);
766                 ShowMessageBox(s, MB_ICONSTOP);
767                 return;
768         }
769
770         // Files are not binaries, but they are identical
771         if (identical != IDENTLEVEL::NONE)
772         {
773                 CMergeFrameCommon::ShowIdenticalMessage(m_filePaths, identical == IDENTLEVEL::ALL,
774                         [this](LPCTSTR msg, UINT flags, UINT id) -> int { return ShowMessageBox(msg, flags, id); });
775         }
776 }
777
778 bool CMergeDoc::Undo()
779 {
780         return false;
781 }
782
783 /**
784  * @brief An instance of RescanSuppress prevents rescan during its lifetime
785  * (or until its Clear method is called, which ends its effect).
786  */
787 class RescanSuppress
788 {
789 public:
790         explicit RescanSuppress(CMergeDoc & doc) : m_doc(doc)
791         {
792                 m_bSuppress = true;
793                 m_bPrev = doc.m_bEnableRescan;
794                 m_doc.m_bEnableRescan = false;
795         }
796         void Clear() 
797         {
798                 if (m_bSuppress)
799                 {
800                         m_bSuppress = false;
801                         m_doc.m_bEnableRescan = m_bPrev;
802                 }
803         }
804         ~RescanSuppress()
805         {
806                 Clear();
807         }
808 private:
809         CMergeDoc & m_doc;
810         bool m_bPrev;
811         bool m_bSuppress;
812 };
813
814 /**
815  * @brief Copy all diffs from one side to side.
816  * @param [in] srcPane Source side from which diff is copied
817  * @param [in] dstPane Destination side
818  */
819 void CMergeDoc::CopyAllList(int srcPane, int dstPane)
820 {
821         CopyMultipleList(srcPane, dstPane, 0, m_diffList.GetSize() - 1);
822 }
823
824 /**
825  * @brief Copy range of diffs from one side to side.
826  * This function copies given range of differences from side to another.
827  * Ignored differences are skipped, and not copied.
828  * @param [in] srcPane Source side from which diff is copied
829  * @param [in] dstPane Destination side
830  * @param [in] firstDiff First diff copied (0-based index)
831  * @param [in] lastDiff Last diff copied (0-based index)
832  */
833 void CMergeDoc::CopyMultipleList(int srcPane, int dstPane, int firstDiff, int lastDiff, int firstWordDiff, int lastWordDiff)
834 {
835 #ifdef _DEBUG
836         if (firstDiff > lastDiff)
837                 _RPTF0(_CRT_ERROR, "Invalid diff range (firstDiff > lastDiff)!");
838         if (firstDiff < 0)
839                 _RPTF0(_CRT_ERROR, "Invalid diff range (firstDiff < 0)!");
840         if (lastDiff > m_diffList.GetSize() - 1)
841                 _RPTF0(_CRT_ERROR, "Invalid diff range (lastDiff < diffcount)!");
842 #endif
843
844         lastDiff = min(m_diffList.GetSize() - 1, lastDiff);
845         firstDiff = max(0, firstDiff);
846         if (firstDiff > lastDiff)
847                 return;
848         
849         RescanSuppress suppressRescan(*this);
850
851         // Note we don't care about m_nDiffs count to become zero,
852         // because we don't rescan() so it does not change
853
854         SetCurrentDiff(lastDiff);
855
856         bool bGroupWithPrevious = false;
857         if (firstWordDiff <= 0 && lastWordDiff == -1)
858         {
859                 if (!ListCopy(srcPane, dstPane, -1, bGroupWithPrevious, true))
860                         return; // sync failure
861         }
862         else
863         {
864                 if (!WordListCopy(srcPane, dstPane, lastDiff, 
865                         (firstDiff == lastDiff) ? firstWordDiff : 0, lastWordDiff, nullptr, bGroupWithPrevious, true))
866                         return; // sync failure
867         }
868
869         SetEditedAfterRescan(dstPane);
870
871         int nGroup = GetActiveMergeView()->m_nThisGroup;
872         CMergeEditView *pViewSrc = m_pView[nGroup][srcPane];
873         CMergeEditView *pViewDst = m_pView[nGroup][dstPane];
874         CPoint currentPosSrc = pViewSrc->GetCursorPos();
875         currentPosSrc.x = 0;
876         CPoint currentPosDst = pViewDst->GetCursorPos();
877         currentPosDst.x = 0;
878
879         CPoint pt(0, 0);
880         pViewDst->SetCursorPos(pt);
881         pViewDst->SetNewSelection(pt, pt, false);
882         pViewDst->SetNewAnchor(pt);
883
884         // copy from bottom up is more efficient
885         for (int i = lastDiff - 1; i >= firstDiff; --i)
886         {
887                 if (m_diffList.IsDiffSignificant(i))
888                 {
889                         SetCurrentDiff(i);
890                         const DIFFRANGE *pdi = m_diffList.DiffRangeAt(i);
891                         if (currentPosDst.y > pdi->dend)
892                         {
893                                 if (pdi->blank[dstPane] >= 0)
894                                         currentPosDst.y -= pdi->dend - pdi->blank[dstPane] + 1;
895                                 else if (pdi->blank[srcPane] >= 0)
896                                         currentPosDst.y -= pdi->dend - pdi->blank[srcPane] + 1;
897                         }                       
898                         // Group merge with previous (merge undo data to one action)
899                         bGroupWithPrevious = true;
900                         if (i > firstDiff || firstWordDiff <= 0)
901                         {
902                                 if (!ListCopy(srcPane, dstPane, -1, bGroupWithPrevious, false))
903                                         break; // sync failure
904                         }
905                         else
906                         {
907                                 if (!WordListCopy(srcPane, dstPane, firstDiff, firstWordDiff, -1, nullptr, bGroupWithPrevious, false))
908                                         break; // sync failure
909                         }
910                 }
911         }
912
913         ForEachView(dstPane, [currentPosDst](auto& pView) {
914                 pView->SetCursorPos(currentPosDst);
915                 pView->SetNewSelection(currentPosDst, currentPosDst, false);
916                 pView->SetNewAnchor(currentPosDst);
917         });
918
919         suppressRescan.Clear(); // done suppress Rescan
920         FlushAndRescan();
921 }
922
923 void CMergeDoc::CopyMultiplePartialList(int srcPane, int dstPane, int firstDiff, int lastDiff,
924         int firstLineDiff, int lastLineDiff)
925 {
926         lastDiff = min(m_diffList.GetSize() - 1, lastDiff);
927         firstDiff = max(0, firstDiff);
928         if (firstDiff > lastDiff)
929                 return;
930         
931         RescanSuppress suppressRescan(*this);
932
933         bool bGroupWithPrevious = false;
934         if (firstLineDiff <= 0 && lastLineDiff == -1)
935         {
936                 if (!ListCopy(srcPane, dstPane, -1, bGroupWithPrevious, true))
937                         return; // sync failure
938         }
939         else
940         {
941                 if (!PartialListCopy(srcPane, dstPane, lastDiff, 
942                         (firstDiff == lastDiff) ? firstLineDiff : 0, lastLineDiff, bGroupWithPrevious, true))
943                         return; // sync failure
944         }
945
946
947         SetEditedAfterRescan(dstPane);
948
949         int nGroup = GetActiveMergeView()->m_nThisGroup;
950         CMergeEditView *pViewSrc = m_pView[nGroup][srcPane];
951         CMergeEditView *pViewDst = m_pView[nGroup][dstPane];
952         CPoint currentPosSrc = pViewSrc->GetCursorPos();
953         currentPosSrc.x = 0;
954         CPoint currentPosDst = pViewDst->GetCursorPos();
955         currentPosDst.x = 0;
956
957         CPoint pt(0, 0);
958         pViewDst->SetCursorPos(pt);
959         pViewDst->SetNewSelection(pt, pt, false);
960         pViewDst->SetNewAnchor(pt);
961
962         // copy from bottom up is more efficient
963         for (int i = lastDiff - 1; i >= firstDiff; --i)
964         {
965                 if (m_diffList.IsDiffSignificant(i))
966                 {
967                         SetCurrentDiff(i);
968                         const DIFFRANGE *pdi = m_diffList.DiffRangeAt(i);
969                         if (currentPosDst.y > pdi->dend)
970                         {
971                                 if (pdi->blank[dstPane] >= 0)
972                                         currentPosDst.y -= pdi->dend - pdi->blank[dstPane] + 1;
973                                 else if (pdi->blank[srcPane] >= 0)
974                                         currentPosDst.y -= pdi->dend - pdi->blank[srcPane] + 1;
975                         }                       
976                         // Group merge with previous (merge undo data to one action)
977                         bGroupWithPrevious = true;
978                         if (i > firstDiff || firstLineDiff <= 0)
979                         {
980                                 if (!ListCopy(srcPane, dstPane, -1, bGroupWithPrevious, false))
981                                         break; // sync failure
982                         }
983                         else
984                         {
985                                 if (!PartialListCopy(srcPane, dstPane, firstDiff, firstLineDiff, -1, bGroupWithPrevious, false))
986                                         break; // sync failure
987                         }
988                 }
989         }
990
991         ForEachView(dstPane, [currentPosDst](auto& pView) {
992                 pView->SetCursorPos(currentPosDst);
993                 pView->SetNewSelection(currentPosDst, currentPosDst, false);
994                 pView->SetNewAnchor(currentPosDst);
995         });
996
997         suppressRescan.Clear(); // done suppress Rescan
998         FlushAndRescan();
999 }
1000
1001 enum MergeResult { NoMergeNeeded, Merged, Conflict };
1002
1003 template<class Type>
1004 static std::pair<MergeResult, Type> DoMergeValue(Type left, Type middle, Type right, int dstPane)
1005 {
1006         bool equal_all = middle == left && middle == right && left == right;
1007         if (equal_all)
1008                 return std::pair<MergeResult, Type>(NoMergeNeeded, left);
1009         bool conflict = middle != left && middle != right && left != right;
1010         if (conflict)
1011                 return std::pair<MergeResult, Type>(Conflict, left);
1012         switch (dstPane)
1013         {
1014         case 0:
1015                 if (left == right)
1016                         return std::pair<MergeResult, Type>(Merged, middle);
1017                 break;
1018         case 1:
1019                 if (left == middle)
1020                         return std::pair<MergeResult, Type>(Merged, right);
1021                 else
1022                         return std::pair<MergeResult, Type>(Merged, left);
1023                 break;
1024         case 2:
1025                 if (left == right)
1026                         return std::pair<MergeResult, Type>(Merged, middle);
1027                 break;
1028         }
1029         return std::pair<MergeResult, Type>(NoMergeNeeded, left);
1030 }
1031
1032 /**
1033  * @brief Do auto-merge.
1034  * @param [in] dstPane Destination side
1035  */
1036 void CMergeDoc::DoAutoMerge(int dstPane)
1037 {
1038         const int lastDiff = m_diffList.GetSize() - 1;
1039         const int firstDiff = 0;
1040         bool bGroupWithPrevious = false;
1041         int autoMergedCount = 0;
1042         int unresolvedConflictCount = 0;
1043
1044         std::pair<MergeResult, FileTextEncoding> mergedEncoding = 
1045                 DoMergeValue(m_ptBuf[0]->getEncoding(), m_ptBuf[1]->getEncoding(), m_ptBuf[2]->getEncoding(), dstPane);
1046         if (mergedEncoding.first == Merged)
1047         {
1048                 ShowMessageBox(_("The change of codepage has been merged."), MB_ICONINFORMATION);
1049                 m_ptBuf[dstPane]->setEncoding(mergedEncoding.second);
1050         }
1051         else if (mergedEncoding.first == Conflict)
1052                 ShowMessageBox(_("The changes of codepage are conflicting."), MB_ICONINFORMATION);
1053
1054         std::pair<MergeResult, CRLFSTYLE> mergedEOLStyle = 
1055                 DoMergeValue(m_ptBuf[0]->GetCRLFMode(), m_ptBuf[1]->GetCRLFMode(), m_ptBuf[2]->GetCRLFMode(), dstPane);
1056         if (mergedEOLStyle.first == Merged)
1057         {
1058                 ShowMessageBox(_("The change of EOL has been merged."), MB_ICONINFORMATION);
1059                 m_ptBuf[dstPane]->SetCRLFMode(mergedEOLStyle.second);
1060         }
1061         else if (mergedEOLStyle.first == Conflict)
1062                 ShowMessageBox(_("The changes of EOL are conflicting."), MB_ICONINFORMATION);
1063
1064         RescanSuppress suppressRescan(*this);
1065
1066         // Note we don't care about m_nDiffs count to become zero,
1067         // because we don't rescan() so it does not change
1068
1069         SetCurrentDiff(lastDiff);
1070
1071         SetEditedAfterRescan(dstPane);
1072
1073         int nGroup = GetActiveMergeView()->m_nThisGroup;
1074         CMergeEditView *pViewDst = m_pView[nGroup][dstPane];
1075         CPoint currentPosDst = pViewDst->GetCursorPos();
1076         currentPosDst.x = 0;
1077
1078         CPoint pt(0, 0);
1079         pViewDst->SetCursorPos(pt);
1080         pViewDst->SetNewSelection(pt, pt, false);
1081         pViewDst->SetNewAnchor(pt);
1082
1083         // copy from bottom up is more efficient
1084         for (int i = lastDiff; i >= firstDiff; --i)
1085         {
1086                 const DIFFRANGE *pdi = m_diffList.DiffRangeAt(i);
1087                 const int srcPane = m_diffList.GetMergeableSrcIndex(i, dstPane);
1088                 if (srcPane != -1)
1089                 {
1090                         SetCurrentDiff(i);
1091                         if (currentPosDst.y > pdi->dend)
1092                         {
1093                                 if (pdi->blank[dstPane] >= 0)
1094                                         currentPosDst.y -= pdi->dend - pdi->blank[dstPane] + 1;
1095                                 else if (pdi->blank[srcPane] >= 0)
1096                                         currentPosDst.y -= pdi->dend - pdi->blank[srcPane] + 1;
1097                         }                       
1098                         // Group merge with previous (merge undo data to one action)
1099                         if (!ListCopy(srcPane, dstPane, -1, bGroupWithPrevious, false))
1100                                 break; // sync failure
1101                         if (!bGroupWithPrevious)
1102                                 bGroupWithPrevious = true;
1103                         ++autoMergedCount;
1104                 }
1105                 if (pdi->op == OP_DIFF)
1106                         ++unresolvedConflictCount;
1107         }
1108
1109         ForEachView(dstPane, [currentPosDst](auto& pView) {
1110                 pView->SetCursorPos(currentPosDst);
1111                 pView->SetNewSelection(currentPosDst, currentPosDst, false);
1112                 pView->SetNewAnchor(currentPosDst);
1113         });
1114
1115         suppressRescan.Clear(); // done suppress Rescan
1116         FlushAndRescan();
1117         UpdateHeaderPath(dstPane);
1118
1119         if (autoMergedCount > 0)
1120                 m_bAutoMerged = true;
1121
1122         // move to first conflict 
1123         const int nDiff = m_diffList.FirstSignificant3wayDiff(THREEWAYDIFFTYPE_CONFLICT);
1124         if (nDiff != -1)
1125                 pViewDst->SelectDiff(nDiff, true, false);
1126
1127         ShowMessageBox(
1128                 strutils::format_string2(
1129                         _("The number of automatically merged changes: %1\nThe number of unresolved conflicts: %2"), 
1130                         strutils::format(_T("%d"), autoMergedCount),
1131                         strutils::format(_T("%d"), unresolvedConflictCount)),
1132                 MB_ICONINFORMATION);
1133 }
1134
1135 /**
1136  * @brief Sanity check difference.
1137  *
1138  * Checks that lines in difference are inside difference in both files.
1139  * If file is edited, lines added or removed diff lines get out of sync and
1140  * merging fails miserably.
1141  *
1142  * @param [in] dr Difference to check.
1143  * @return true if difference lines match, false otherwise.
1144  */
1145 bool CMergeDoc::SanityCheckDiff(DIFFRANGE dr) const
1146 {
1147         const int cd_dbegin = dr.dbegin;
1148         const int cd_dend = dr.dend;
1149
1150         for (int nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
1151         {
1152                 // Must ensure line number is in range before getting line flags
1153                 if (cd_dend >= m_ptBuf[nBuffer]->GetLineCount())
1154                         return false;
1155
1156                 // Optimization - check last line first so we don't need to
1157                 // check whole diff for obvious cases
1158                 DWORD dwFlags = m_ptBuf[nBuffer]->GetLineFlags(cd_dend);
1159                 if (!(dwFlags & LF_WINMERGE_FLAGS))
1160                         return false;
1161         }
1162
1163         for (int line = cd_dbegin; line < cd_dend; line++)
1164         {
1165                 for (int nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
1166                 {
1167                         DWORD dwFlags = m_ptBuf[nBuffer]->GetLineFlags(cd_dend);
1168                         if (!(dwFlags & LF_WINMERGE_FLAGS))
1169                                 return false;
1170                 }
1171         }
1172         return true;
1173 }
1174
1175 /**
1176  * @brief Copy selected (=current) difference from from side to side.
1177  * @param [in] srcPane Source side from which diff is copied
1178  * @param [in] dstPane Destination side
1179  * @param [in] nDiff Diff to copy, if -1 function determines it.
1180  * @param [in] bGroupWithPrevious Adds diff to same undo group with
1181  * @return true if ok, false if sync failure & need to abort copy
1182  * previous action (allows one undo for copy all)
1183  */
1184 bool CMergeDoc::ListCopy(int srcPane, int dstPane, int nDiff /* = -1*/,
1185                 bool bGroupWithPrevious /*= false*/, bool bUpdateView /*= true*/)
1186 {
1187         int nGroup = GetActiveMergeView()->m_nThisGroup;
1188         CMergeEditView *pViewSrc = m_pView[nGroup][srcPane];
1189         CMergeEditView *pViewDst = m_pView[nGroup][dstPane];
1190         CCrystalTextView *pSource = bUpdateView ? pViewDst : nullptr;
1191
1192         // suppress Rescan during this method
1193         // (Not only do we not want to rescan a lot of times, but
1194         // it will wreck the line status array to rescan as we merge)
1195         RescanSuppress suppressRescan(*this);
1196
1197         // If diff-number not given, determine it from active view
1198         if (nDiff == -1)
1199         {
1200                 nDiff = GetCurrentDiff();
1201
1202                 // No current diff, but maybe cursor is in diff?
1203                 if (nDiff == -1 && (pViewSrc->IsCursorInDiff() ||
1204                         pViewDst->IsCursorInDiff()))
1205                 {
1206                         // Find out diff under cursor
1207                         CPoint ptCursor = GetActiveMergeView()->GetCursorPos();
1208                         nDiff = m_diffList.LineToDiff(ptCursor.y);
1209                 }
1210         }
1211
1212         if (nDiff != -1)
1213         {
1214                 DIFFRANGE cd;
1215                 VERIFY(m_diffList.GetDiff(nDiff, cd));
1216                 CDiffTextBuffer& sbuf = *m_ptBuf[srcPane];
1217                 CDiffTextBuffer& dbuf = *m_ptBuf[dstPane];
1218                 bool bSrcWasMod = sbuf.IsModified();
1219                 const int cd_dbegin = cd.dbegin;
1220                 const int cd_dend = cd.dend;
1221                 const int cd_blank = cd.blank[srcPane];
1222                 bool bInSync = SanityCheckDiff(cd);
1223
1224                 if (!bInSync)
1225                 {
1226                         LangMessageBox(IDS_VIEWS_OUTOFSYNC, MB_ICONSTOP);
1227                         return false; // abort copying
1228                 }
1229
1230                 // If we remove whole diff from current view, we must fix cursor
1231                 // position first. Normally we would move to end of previous line,
1232                 // but we want to move to begin of that line for usability.
1233                 if (bUpdateView)
1234                 {
1235                         CPoint currentPos = pViewDst->GetCursorPos();
1236                         currentPos.x = 0;
1237                         if (currentPos.y > cd_dend)
1238                         {
1239                                 if (cd.blank[dstPane] >= 0)
1240                                         currentPos.y -= cd_dend - cd.blank[dstPane] + 1;
1241                                 else if (cd.blank[srcPane] >= 0)
1242                                         currentPos.y -= cd_dend - cd.blank[srcPane] + 1;
1243                         }
1244                         ForEachView(dstPane, [currentPos](auto& pView) { pView->SetCursorPos(currentPos); });
1245                 }
1246
1247                 // if the current diff contains missing lines, remove them from both sides
1248                 int limit = cd_dend;
1249
1250                 // curView is the view which is changed, so the opposite of the source view
1251                 dbuf.BeginUndoGroup(bGroupWithPrevious);
1252                 if (cd_blank>=0)
1253                 {
1254                         // text was missing, so delete rest of lines on both sides
1255                         // delete only on destination side since rescan will clear the other side
1256                         if (cd_dend + 1 < dbuf.GetLineCount())
1257                         {
1258                                 dbuf.DeleteText(pSource, cd_blank, 0, cd_dend+1, 0, CE_ACTION_MERGE);
1259                         }
1260                         else
1261                         {
1262                                 // To removing EOL chars of last line, deletes from the end of the line (cd_blank - 1).
1263                                 ASSERT(cd_blank > 0);
1264                                 dbuf.DeleteText(pSource, cd_blank-1, dbuf.GetLineLength(cd_blank-1), cd_dend, dbuf.GetLineLength(cd_dend), CE_ACTION_MERGE);
1265                         }
1266
1267                         limit=cd_blank-1;
1268                         dbuf.FlushUndoGroup(pSource);
1269                         dbuf.BeginUndoGroup(true);
1270                 }
1271
1272
1273                 // copy the selected text over
1274                 if (cd_dbegin <= limit)
1275                 {
1276                         // text exists on left side, so just replace
1277                         dbuf.ReplaceFullLines(dbuf, sbuf, pSource, cd_dbegin, limit, CE_ACTION_MERGE);
1278                         dbuf.FlushUndoGroup(pSource);
1279                         dbuf.BeginUndoGroup(true);
1280                 }
1281                 dbuf.FlushUndoGroup(pSource);
1282
1283                 // remove the diff
1284                 SetCurrentDiff(-1);
1285
1286                 // reset the mod status of the source view because we do make some
1287                 // changes, but none that concern the source text
1288                 sbuf.SetModified(bSrcWasMod);
1289         }
1290
1291         suppressRescan.Clear(); // done suppress Rescan
1292         FlushAndRescan();
1293         return true;
1294 }
1295
1296 bool CMergeDoc::PartialListCopy(int srcPane, int dstPane, int nDiff, int firstLine, int lastLine /*= -1*/,
1297         bool bGroupWithPrevious /*= false*/, bool bUpdateView /*= true*/)
1298 {
1299         int nGroup = GetActiveMergeView()->m_nThisGroup;
1300         CMergeEditView *pViewSrc = m_pView[nGroup][srcPane];
1301         CMergeEditView *pViewDst = m_pView[nGroup][dstPane];
1302         CCrystalTextView *pSource = bUpdateView ? pViewDst : nullptr;
1303
1304         // suppress Rescan during this method
1305         // (Not only do we not want to rescan a lot of times, but
1306         // it will wreck the line status array to rescan as we merge)
1307         RescanSuppress suppressRescan(*this);
1308
1309         DIFFRANGE cd;
1310         VERIFY(m_diffList.GetDiff(nDiff, cd));
1311         CDiffTextBuffer& sbuf = *m_ptBuf[srcPane];
1312         CDiffTextBuffer& dbuf = *m_ptBuf[dstPane];
1313         bool bSrcWasMod = sbuf.IsModified();
1314         const int cd_dbegin = (firstLine > cd.dbegin) ? firstLine : cd.dbegin;
1315         const int cd_dend = cd.dend;
1316         const int cd_blank = cd.blank[srcPane];
1317         bool bInSync = SanityCheckDiff(cd);
1318
1319         if (!bInSync)
1320         {
1321                 LangMessageBox(IDS_VIEWS_OUTOFSYNC, MB_ICONSTOP);
1322                 return false; // abort copying
1323         }
1324
1325         // If we remove whole diff from current view, we must fix cursor
1326         // position first. Normally we would move to end of previous line,
1327         // but we want to move to begin of that line for usability.
1328         if (bUpdateView)
1329         {
1330                 CPoint currentPos = pViewDst->GetCursorPos();
1331                 currentPos.x = 0;
1332                 if (currentPos.y > cd_dend)
1333                 {
1334                         if (cd.blank[dstPane] >= 0)
1335                                 currentPos.y -= cd_dend - cd.blank[dstPane] + 1;
1336                         else if (cd.blank[srcPane] >= 0)
1337                                 currentPos.y -= cd_dend - cd.blank[srcPane] + 1;
1338                 }
1339                 ForEachView(dstPane, [currentPos](auto& pView) { pView->SetCursorPos(currentPos); });
1340         }
1341
1342         // if the current diff contains missing lines, remove them from both sides
1343         int limit = ((lastLine < 0) || (lastLine > cd_dend)) ? cd_dend : lastLine;
1344
1345         // curView is the view which is changed, so the opposite of the source view
1346         dbuf.BeginUndoGroup(bGroupWithPrevious);
1347         if ((cd_blank >= 0) && (cd_dbegin >= cd_blank))
1348         {
1349                 // text was missing, so delete rest of lines on both sides
1350                 // delete only on destination side since rescan will clear the other side
1351                 if (limit+1 < dbuf.GetLineCount())
1352                 {
1353                         dbuf.DeleteText(pSource, cd_dbegin, 0, limit+1, 0, CE_ACTION_MERGE);
1354                 }
1355                 else
1356                 {
1357                         // To removing EOL chars of last line, deletes from the end of the line (cd_blank - 1).
1358                         ASSERT(cd_dbegin > 0);
1359                         dbuf.DeleteText(pSource, cd_dbegin-1, dbuf.GetLineLength(cd_dbegin-1), limit, dbuf.GetLineLength(limit), CE_ACTION_MERGE);
1360                 }
1361
1362                 limit = cd_dbegin-1;
1363                 dbuf.FlushUndoGroup(pSource);
1364                 dbuf.BeginUndoGroup(true);
1365         }
1366
1367         // copy the selected text over
1368         if (cd_dbegin <= limit)
1369         {
1370                 // text exists on left side, so just replace
1371                 dbuf.ReplaceFullLines(dbuf, sbuf, pSource, cd_dbegin, limit, CE_ACTION_MERGE);
1372                 dbuf.FlushUndoGroup(pSource);
1373                 dbuf.BeginUndoGroup(true);
1374         }
1375         dbuf.FlushUndoGroup(pSource);
1376
1377         // remove the diff
1378         SetCurrentDiff(-1);
1379
1380         // reset the mod status of the source view because we do make some
1381         // changes, but none that concern the source text
1382         sbuf.SetModified(bSrcWasMod);
1383
1384         suppressRescan.Clear(); // done suppress Rescan
1385         FlushAndRescan();
1386         return true;
1387 }
1388
1389 bool CMergeDoc::WordListCopy(int srcPane, int dstPane, int nDiff, int firstWordDiff, int lastWordDiff,
1390                 const std::vector<int> *pWordDiffIndice, bool bGroupWithPrevious /*= false*/, bool bUpdateView /*= true*/)
1391 {
1392         int nGroup = GetActiveMergeView()->m_nThisGroup;
1393         CMergeEditView *pViewSrc = m_pView[nGroup][srcPane];
1394         CMergeEditView *pViewDst = m_pView[nGroup][dstPane];
1395         CCrystalTextView *pSource = bUpdateView ? pViewDst : nullptr;
1396
1397         // suppress Rescan during this method
1398         // (Not only do we not want to rescan a lot of times, but
1399         // it will wreck the line status array to rescan as we merge)
1400         RescanSuppress suppressRescan(*this);
1401
1402         DIFFRANGE cd;
1403         VERIFY(m_diffList.GetDiff(nDiff, cd));
1404         CDiffTextBuffer& sbuf = *m_ptBuf[srcPane];
1405         CDiffTextBuffer& dbuf = *m_ptBuf[dstPane];
1406         bool bSrcWasMod = sbuf.IsModified();
1407         const int cd_dbegin = cd.dbegin;
1408         const int cd_dend = cd.dend;
1409         const int cd_blank = cd.blank[srcPane];
1410         bool bInSync = SanityCheckDiff(cd);
1411
1412         if (!bInSync)
1413         {
1414                 LangMessageBox(IDS_VIEWS_OUTOFSYNC, MB_ICONSTOP);
1415                 return false; // abort copying
1416         }
1417
1418         std::vector<WordDiff> worddiffs = GetWordDiffArrayInDiffBlock(nDiff);
1419
1420         if (worddiffs.empty())
1421                 return false;
1422
1423         if (cd.end[srcPane] < cd.begin[srcPane])
1424                 return ListCopy(srcPane, dstPane, nDiff, bGroupWithPrevious, bUpdateView);
1425
1426         if (firstWordDiff == -1)
1427                 firstWordDiff = 0;
1428         if (lastWordDiff == -1)
1429                 lastWordDiff = static_cast<int>(worddiffs.size() - 1);
1430
1431         // If we remove whole diff from current view, we must fix cursor
1432         // position first. Normally we would move to end of previous line,
1433         // but we want to move to begin of that line for usability.
1434         if (bUpdateView)
1435         {
1436                 CPoint currentPos = pViewDst->GetCursorPos();
1437                 currentPos.x = 0;
1438                 if (currentPos.y > cd_dend)
1439                 {
1440                         if (cd.blank[dstPane] >= 0)
1441                                 currentPos.y -= cd_dend - cd.blank[dstPane] + 1;
1442                         else if (cd.blank[srcPane] >= 0)
1443                                 currentPos.y -= cd_dend - cd.blank[srcPane] + 1;
1444                 }
1445                 ForEachView(dstPane, [currentPos](auto& pView) { pView->SetCursorPos(currentPos); });
1446         }
1447
1448         // if the current diff contains missing lines, remove them from both sides
1449         int limit = cd_dend;
1450
1451         // curView is the view which is changed, so the opposite of the source view
1452         dbuf.BeginUndoGroup(bGroupWithPrevious);
1453
1454         CString srcText, dstText;
1455         CPoint ptDstStart, ptDstEnd;
1456         CPoint ptSrcStart, ptSrcEnd;
1457
1458         ptDstStart.x = worddiffs[firstWordDiff].begin[dstPane];
1459         ptDstStart.y = worddiffs[firstWordDiff].beginline[dstPane];
1460         ptDstEnd.x = worddiffs[lastWordDiff].end[dstPane];
1461         ptDstEnd.y = worddiffs[lastWordDiff].endline[dstPane];
1462         ptSrcStart.x = worddiffs[firstWordDiff].begin[srcPane];
1463         ptSrcStart.y = worddiffs[firstWordDiff].beginline[srcPane];
1464         ptSrcEnd.x = worddiffs[lastWordDiff].end[srcPane];
1465         ptSrcEnd.y = worddiffs[lastWordDiff].endline[srcPane];
1466
1467         std::vector<int> nDstOffsets(ptDstEnd.y - ptDstStart.y + 2);
1468         std::vector<int> nSrcOffsets(ptSrcEnd.y - ptSrcStart.y + 2);
1469
1470         dbuf.GetTextWithoutEmptys(ptDstStart.y, ptDstStart.x, ptDstEnd.y, ptDstEnd.x, dstText);
1471         sbuf.GetTextWithoutEmptys(ptSrcStart.y, ptSrcStart.x, ptSrcEnd.y, ptSrcEnd.x, srcText);
1472
1473         nDstOffsets[0] = 0;
1474         for (int nLine = ptDstStart.y; nLine <= ptDstEnd.y; nLine++)
1475                 nDstOffsets[nLine-ptDstStart.y+1] = nDstOffsets[nLine-ptDstStart.y] + dbuf.GetFullLineLength(nLine);
1476         nSrcOffsets[0] = 0;
1477         for (int nLine = ptSrcStart.y; nLine <= ptSrcEnd.y; nLine++)
1478                 nSrcOffsets[nLine-ptSrcStart.y+1] = nSrcOffsets[nLine-ptSrcStart.y] + sbuf.GetFullLineLength(nLine);
1479
1480         for (int i = lastWordDiff; i != firstWordDiff-1; --i)
1481         {
1482                 if (pWordDiffIndice && std::find(pWordDiffIndice->begin(), pWordDiffIndice->end(), i) == pWordDiffIndice->end())
1483                         continue;
1484                 int srcBegin = nSrcOffsets[worddiffs[i].beginline[srcPane] - ptSrcStart.y] + worddiffs[i].begin[srcPane];
1485                 int srcEnd   = nSrcOffsets[worddiffs[i].endline[srcPane] - ptSrcStart.y] + worddiffs[i].end[srcPane];
1486                 int dstBegin = nDstOffsets[worddiffs[i].beginline[dstPane] - ptDstStart.y] + worddiffs[i].begin[dstPane];
1487                 int dstEnd   = nDstOffsets[worddiffs[i].endline[dstPane] - ptDstStart.y] + worddiffs[i].end[dstPane];
1488                 dstText = dstText.Mid(0, dstBegin - ptDstStart.x)
1489                         + srcText.Mid(srcBegin - ptSrcStart.x, srcEnd - srcBegin)
1490                         + dstText.Mid(dstEnd - ptDstStart.x);
1491         }
1492
1493         dbuf.DeleteText(pSource, ptDstStart.y, ptDstStart.x, ptDstEnd.y, ptDstEnd.x, CE_ACTION_MERGE);
1494
1495         int endl,endc;
1496         dbuf.InsertText(pSource, ptDstStart.y, ptDstStart.x, dstText, dstText.GetLength(), endl, endc, CE_ACTION_MERGE);
1497
1498         dbuf.FlushUndoGroup(pSource);
1499
1500         // reset the mod status of the source view because we do make some
1501         // changes, but none that concern the source text
1502         sbuf.SetModified(bSrcWasMod);
1503
1504         suppressRescan.Clear(); // done suppress Rescan
1505         FlushAndRescan();
1506
1507         return true;
1508 }
1509
1510 /**
1511  * @brief Save file with new filename.
1512  *
1513  * This function is called by CMergeDoc::DoSave() or CMergeDoc::DoSAveAs()
1514  * to save file with new filename. CMergeDoc::DoSave() calls if saving with
1515  * normal filename fails, to let user choose another filename/location.
1516  * Also, if file is unnamed file (e.g. scratchpad) then it must be saved
1517  * using this function.
1518  * @param [in, out] strPath 
1519  * - [in] : Initial path shown to user
1520  * - [out] : Path to new filename if saving succeeds
1521  * @param [in, out] nSaveResult 
1522  * - [in] : Statuscode telling why we ended up here. Maybe the result of
1523  * previous save.
1524  * - [out] : Statuscode of this saving try
1525  * @param [in, out] sError Error string from lower level saving code
1526  * @param [in] nBuffer Buffer we are saving
1527  * @return false as long as the user is not satisfied. Calling function
1528  * should not continue until true is returned.
1529  * @sa CMergeDoc::DoSave()
1530  * @sa CMergeDoc::DoSaveAs()
1531  * @sa CMergeDoc::CDiffTextBuffer::SaveToFile()
1532  */
1533 bool CMergeDoc::TrySaveAs(String &strPath, int &nSaveResult, String & sError,
1534         int nBuffer, PackingInfo * pInfoTempUnpacker)
1535 {
1536         String s;
1537         String str;
1538         String strSavePath; // New path for next saving try
1539         String title;
1540         bool result = true;
1541         int answer = IDOK; // Set default we use for scratchpads
1542
1543         // We shouldn't get here if saving is succeed before
1544         ASSERT(nSaveResult != SAVE_DONE);
1545
1546         // Select message based on reason function called
1547         if (nSaveResult == SAVE_PACK_FAILED)
1548         {
1549                 str = CMergeApp::GetPackingErrorMessage(nBuffer, m_nBuffers, strPath, pInfoTempUnpacker->m_PluginName);
1550                 // replace the unpacker with a "do nothing" unpacker
1551                 pInfoTempUnpacker->Initialize(PLUGIN_MODE::PLUGIN_MANUAL);
1552         }
1553         else
1554         {
1555                 str = strutils::format_string2(_("Saving file failed.\n%1\n%2\nDo you want to:\n\t- use a different filename (Press OK)\n\t- abort the current operation (Press Cancel)?"), strPath, sError);
1556         }
1557
1558         // SAVE_NO_FILENAME is temporarily used for scratchpad.
1559         // So don't ask about saving in that case.
1560         if (nSaveResult != SAVE_NO_FILENAME)
1561                 answer = ShowMessageBox(str, MB_OKCANCEL | MB_ICONWARNING);
1562
1563         switch (answer)
1564         {
1565         case IDOK:
1566                 if (nBuffer == 0)
1567                         title = _("Save Left File As");
1568                 else if (nBuffer == m_nBuffers - 1)
1569                         title = _("Save Right File As");
1570                 else
1571                         title = _("Save Middle File As");
1572
1573                 if (SelectFile(GetActiveMergeView()->GetSafeHwnd(), s, false, strPath.c_str(), title))
1574                 {
1575                         CDiffTextBuffer *pBuffer = m_ptBuf[nBuffer].get();
1576                         strSavePath = s;
1577                         nSaveResult = pBuffer->SaveToFile(strSavePath, false, sError,
1578                                 pInfoTempUnpacker);
1579
1580                         if (nSaveResult == SAVE_DONE)
1581                         {
1582                                 // We are saving scratchpad (unnamed file)
1583                                 if (strPath.empty())
1584                                 {
1585                                         m_nBufferType[nBuffer] = BUFFERTYPE::UNNAMED_SAVED;
1586                                         m_strDesc[nBuffer].erase();
1587                                 }
1588                                         
1589                                 strPath = strSavePath;
1590                                 UpdateHeaderPath(nBuffer);
1591                         }
1592                         else
1593                                 result = false;
1594                 }
1595                 else
1596                         nSaveResult = SAVE_CANCELLED;
1597                 break;
1598
1599         case IDCANCEL:
1600                 nSaveResult = SAVE_CANCELLED;
1601                 break;
1602         }
1603         return result;
1604 }
1605
1606 /**
1607  * @brief Save file creating backups etc.
1608  *
1609  * Safe top-level file saving function. Checks validity of given path.
1610  * Creates backup file if wanted to. And if saving to given path fails,
1611  * allows user to select new location/name for file.
1612  * @param [in] szPath Path where to save including filename. Can be
1613  * empty/`nullptr` if new file is created (scratchpad) without filename.
1614  * @param [out] bSaveSuccess Will contain information about save success with
1615  * the original name (to determine if file statuses should be changed)
1616  * @param [in] nBuffer Index (0-based) of buffer to save
1617  * @return Tells if caller can continue (no errors happened)
1618  * @note Return value does not tell if SAVING succeeded. Caller must
1619  * Check value of bSaveSuccess parameter after calling this function!
1620  * @note If CMainFrame::m_strSaveAsPath is non-empty, file is saved
1621  * to directory it points to. If m_strSaveAsPath contains filename,
1622  * that filename is used.
1623  * @sa CMergeDoc::TrySaveAs()
1624  * @sa CMainFrame::CheckSavePath()
1625  * @sa CMergeDoc::CDiffTextBuffer::SaveToFile()
1626  */
1627 bool CMergeDoc::DoSave(LPCTSTR szPath, bool &bSaveSuccess, int nBuffer)
1628 {
1629         DiffFileInfo fileInfo;
1630         String strSavePath(szPath);
1631         FileChange fileChanged;
1632         bool bApplyToAll = false;       
1633         int nRetVal = -1;
1634
1635         fileChanged = IsFileChangedOnDisk(szPath, fileInfo, true, nBuffer);
1636         if (fileChanged == FileChange::Changed)
1637         {
1638                 String msg = strutils::format_string1(_("Another application has updated file\n%1\nsince WinMerge loaded it.\n\nOverwrite changed file?"), szPath);
1639                 if (ShowMessageBox(msg, MB_ICONWARNING | MB_YESNO) == IDNO)
1640                 {
1641                         bSaveSuccess = true;
1642                         return true;
1643                 }               
1644         }
1645
1646         // use a temp packer
1647         // first copy the m_pInfoUnpacker
1648         // if an error arises during packing, change and take a "do nothing" packer
1649         PackingInfo infoTempUnpacker = *m_pInfoUnpacker;
1650
1651         bSaveSuccess = false;
1652         
1653         // Check third arg possibly given from command-line
1654         if (!theApp.m_strSaveAsPath.empty())
1655         {
1656                 if (paths::DoesPathExist(theApp.m_strSaveAsPath) == paths::IS_EXISTING_DIR)
1657                 {
1658                         // third arg was a directory, so get append the filename
1659                         String sname;
1660                         paths::SplitFilename(szPath, 0, &sname, 0);
1661                         strSavePath = theApp.m_strSaveAsPath;
1662                         strSavePath = paths::ConcatPath(strSavePath, sname);
1663                 }
1664                 else
1665                         strSavePath = theApp.m_strSaveAsPath;   
1666         }
1667
1668         nRetVal = CMergeApp::HandleReadonlySave(strSavePath, false, bApplyToAll);
1669         if (nRetVal == IDCANCEL)
1670                 return false;
1671
1672         if (!CMergeApp::CreateBackup(false, strSavePath))
1673                 return false;
1674
1675         // false as long as the user is not satisfied
1676         // true if saving succeeds, even with another filename, or if the user cancels
1677         bool result = false;
1678         // the error code from the latest save operation, 
1679         // or SAVE_DONE when the save succeeds
1680         // TODO: Shall we return this code in addition to bSaveSuccess ?
1681         int nSaveErrorCode = SAVE_DONE;
1682         CDiffTextBuffer *pBuffer = m_ptBuf[nBuffer].get();
1683
1684         // Assume empty filename means Scratchpad (unnamed file)
1685         // Todo: This is not needed? - buffer type check should be enough
1686         if (strSavePath.empty())
1687                 nSaveErrorCode = SAVE_NO_FILENAME;
1688
1689         // Handle unnamed buffers
1690         if (m_nBufferType[nBuffer] == BUFFERTYPE::UNNAMED)
1691                 nSaveErrorCode = SAVE_NO_FILENAME;
1692
1693         String sError;
1694         if (nSaveErrorCode == SAVE_DONE)
1695                 // We have a filename, just try to save
1696                 nSaveErrorCode = pBuffer->SaveToFile(strSavePath, false, sError, &infoTempUnpacker);
1697
1698         if (nSaveErrorCode != SAVE_DONE)
1699         {
1700                 // Saving failed, user may save to another location if wants to
1701                 do
1702                         result = TrySaveAs(strSavePath, nSaveErrorCode, sError, nBuffer, &infoTempUnpacker);
1703                 while (!result);
1704         }
1705
1706         // Saving succeeded with given/selected filename
1707         if (nSaveErrorCode == SAVE_DONE)
1708         {
1709                 // Preserve file times if user wants to
1710                 if (GetOptionsMgr()->GetBool(OPT_PRESERVE_FILETIMES))
1711                 {
1712                         fileInfo.SetFile(strSavePath);
1713                         try
1714                         {
1715                                 TFile file(strSavePath);
1716                                 file.setLastModified(fileInfo.mtime);
1717                         }
1718                         catch (...)
1719                         {
1720                         }
1721                 }
1722
1723                 m_ptBuf[nBuffer]->SetModified(false);
1724                 m_pSaveFileInfo[nBuffer]->Update(strSavePath.c_str());
1725                 m_filePaths[nBuffer] = strSavePath;
1726                 m_pRescanFileInfo[nBuffer]->Update(m_filePaths[nBuffer].c_str());
1727                 UpdateHeaderPath(nBuffer);
1728                 bSaveSuccess = true;
1729                 result = true;
1730         }
1731         else if (nSaveErrorCode == SAVE_CANCELLED)
1732         {
1733                 // User cancelled current operation, lets do what user wanted to do
1734                 result = false;
1735         }
1736         return result;
1737 }
1738
1739 /**
1740  * @brief Save file with different filename.
1741  *
1742  * Safe top-level file saving function. Asks user to select filename
1743  * and path. Does not create backups.
1744  * @param [in] szPath Path where to save including filename. Can be
1745  * empty/`nullptr` if new file is created (scratchpad) without filename.
1746  * @param [out] bSaveSuccess Will contain information about save success with
1747  * the original name (to determine if file statuses should be changed)
1748  * @param [in] nBuffer Index (0-based) of buffer to save
1749  * @return Tells if caller can continue (no errors happened)
1750  * @note Return value does not tell if SAVING succeeded. Caller must
1751  * Check value of bSaveSuccess parameter after calling this function!
1752  * @sa CMergeDoc::TrySaveAs()
1753  * @sa CMainFrame::CheckSavePath()
1754  * @sa CMergeDoc::CDiffTextBuffer::SaveToFile()
1755  */
1756 bool CMergeDoc::DoSaveAs(LPCTSTR szPath, bool &bSaveSuccess, int nBuffer)
1757 {
1758         String strSavePath(szPath);
1759
1760         // use a temp packer
1761         // first copy the m_pInfoUnpacker
1762         // if an error arises during packing, change and take a "do nothing" packer
1763         PackingInfo infoTempUnpacker = *m_pInfoUnpacker;
1764
1765         bSaveSuccess = false;
1766         // false as long as the user is not satisfied
1767         // true if saving succeeds, even with another filename, or if the user cancels
1768         bool result = false;
1769         // the error code from the latest save operation, 
1770         // or SAVE_DONE when the save succeeds
1771         // TODO: Shall we return this code in addition to bSaveSuccess ?
1772         int nSaveErrorCode = SAVE_DONE;
1773
1774         // Use SAVE_NO_FILENAME to prevent asking about error
1775         nSaveErrorCode = SAVE_NO_FILENAME;
1776
1777         // Loop until user succeeds saving or cancels
1778         String sError;
1779         do
1780                 result = TrySaveAs(strSavePath, nSaveErrorCode, sError, nBuffer, &infoTempUnpacker);
1781         while (!result);
1782
1783         // Saving succeeded with given/selected filename
1784         if (nSaveErrorCode == SAVE_DONE)
1785         {
1786                 m_pSaveFileInfo[nBuffer]->Update(strSavePath);
1787                 m_filePaths[nBuffer] = strSavePath;
1788                 m_pRescanFileInfo[nBuffer]->Update(m_filePaths[nBuffer]);
1789                 UpdateHeaderPath(nBuffer);
1790                 bSaveSuccess = true;
1791                 result = true;
1792         }
1793         return result;
1794 }
1795
1796 /**
1797  * @brief Get left->right info for a moved line (apparent line number)
1798  */
1799 int CMergeDoc::RightLineInMovedBlock(int nBuffer, int apparentLeftLine)
1800 {
1801         if (!(m_ptBuf[nBuffer]->GetLineFlags(apparentLeftLine) & LF_MOVED))
1802                 return -1;
1803
1804         int realLeftLine = m_ptBuf[nBuffer]->ComputeRealLine(apparentLeftLine);
1805         int realRightLine = -1;
1806         if (m_diffWrapper.GetDetectMovedBlocks())
1807         {
1808                 realRightLine = m_diffWrapper.GetMovedLines(nBuffer)->LineInBlock(realLeftLine,
1809                                 MovedLines::SIDE::RIGHT);
1810         }
1811         if (realRightLine != -1)
1812                 return m_ptBuf[nBuffer + 1]->ComputeApparentLine(realRightLine);
1813         else
1814                 return -1;
1815 }
1816
1817 /**
1818  * @brief Get right->left info for a moved line (apparent line number)
1819  */
1820 int CMergeDoc::LeftLineInMovedBlock(int nBuffer, int apparentRightLine)
1821 {
1822         if (!(m_ptBuf[nBuffer]->GetLineFlags(apparentRightLine) & LF_MOVED))
1823                 return -1;
1824
1825         int realRightLine = m_ptBuf[nBuffer]->ComputeRealLine(apparentRightLine);
1826         int realLeftLine = -1;
1827         if (m_diffWrapper.GetDetectMovedBlocks())
1828         {
1829                 realLeftLine = m_diffWrapper.GetMovedLines(nBuffer)->LineInBlock(realRightLine,
1830                                 MovedLines::SIDE::LEFT);
1831         }
1832         if (realLeftLine != -1)
1833                 return m_ptBuf[nBuffer - 1]->ComputeApparentLine(realLeftLine);
1834         else
1835                 return -1;
1836 }
1837
1838 /**
1839  * @brief Save modified documents.
1840  * This function asks if user wants to save modified documents. We also
1841  * allow user to cancel the closing.
1842  *
1843  * There is a special trick avoiding showing two save-dialogs, as MFC framework
1844  * sometimes calls this function twice. We use static counter for these calls
1845  * and if we already have saving in progress (counter == 1) we skip the new
1846  * saving dialog.
1847  *
1848  * @return true if docs are closed, false if closing is cancelled.
1849  */
1850 BOOL CMergeDoc::SaveModified()
1851 {
1852         static int counter;
1853         ++counter;
1854         if (counter > 1)
1855                 return false;
1856
1857         if (PromptAndSaveIfNeeded(true))
1858         {
1859                 counter = 0;
1860                 return true;
1861         }
1862         else
1863         {
1864                 counter = 0;
1865                 return false;
1866         }
1867 }
1868
1869 /**
1870  * @brief Sets the current difference.
1871  * @param [in] nDiff Difference to set as current difference.
1872  */
1873 void CMergeDoc::SetCurrentDiff(int nDiff)
1874 {
1875         if (nDiff >= 0 && nDiff <= m_diffList.LastSignificantDiff())
1876                 m_nCurDiff = nDiff;
1877         else
1878                 m_nCurDiff = -1;
1879 }
1880
1881 /**
1882  * @brief Take care of rescanning document.
1883  * 
1884  * Update view and restore cursor and scroll position after
1885  * rescanning document.
1886  * @param [in] bForced If true rescan cannot be suppressed
1887  */
1888 void CMergeDoc::FlushAndRescan(bool bForced /* =false */)
1889 {
1890         // Ignore suppressing when forced rescan
1891         if (!bForced)
1892                 if (!m_bEnableRescan) return;
1893
1894         CWaitCursor waitstatus;
1895
1896         CMergeEditView *pActiveView = GetActiveMergeView();
1897
1898         // store cursors and hide caret
1899         ForEachView([](auto& pView) { pView->PushCursors(); });
1900         pActiveView->HideCursor();
1901
1902         bool bBinary = false;
1903         IDENTLEVEL identical = IDENTLEVEL::NONE;
1904         int nRescanResult = Rescan(bBinary, identical, bForced);
1905
1906         // restore cursors and caret
1907         ForEachView([](auto& pView) { pView->PopCursors(); });
1908         pActiveView->ShowCursor();
1909
1910         ForEachView(pActiveView->m_nThisPane, [](auto& pView) {
1911                 // because of ghostlines, m_nTopLine may differ just after Rescan
1912                 // scroll both views to the same top line
1913                 pView->UpdateSiblingScrollPos(false);
1914         });
1915         // make sure we see the cursor from the curent view
1916         pActiveView->EnsureVisible(pActiveView->GetCursorPos());
1917
1918         // Refresh display
1919         UpdateAllViews(nullptr);
1920
1921         // Show possible error after updating screen
1922         if (nRescanResult != RESCAN_SUPPRESSED)
1923                 ShowRescanError(nRescanResult, identical);
1924         m_LastRescan = COleDateTime::GetCurrentTime();
1925 }
1926
1927 /**
1928  * @brief Saves both files
1929  */
1930 void CMergeDoc::OnFileSave() 
1931 {
1932         // We will need to know if either of the originals actually changed
1933         // so we know whether to update the diff status
1934         bool bChangedOriginal = false;
1935
1936         for (int nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
1937         {
1938                 if (m_ptBuf[nBuffer]->IsModified() && !m_ptBuf[nBuffer]->GetReadOnly())
1939                 {
1940                         // (why we don't use return value of DoSave)
1941                         // DoSave will return true if it wrote to something successfully
1942                         // but we have to know if it overwrote the original file
1943                         bool bSaveOriginal = false;
1944                         DoSave(m_filePaths[nBuffer].c_str(), bSaveOriginal, nBuffer );
1945                         if (bSaveOriginal)
1946                                 bChangedOriginal = true;
1947                 }
1948         }
1949
1950         // If either of the actual source files being compared was changed
1951         // we need to update status in the dir view
1952         if (bChangedOriginal)
1953         {
1954                 // If DirDoc contains diffs
1955                 if (m_pDirDoc != nullptr && m_pDirDoc->HasDiffs())
1956                 {
1957                         for (int nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
1958                         {
1959                                 if (m_bEditAfterRescan[nBuffer])
1960                                 {
1961                                         FlushAndRescan(false);
1962                                         break;
1963                                 }
1964                         }
1965
1966                         bool bIdentical = !m_diffList.HasSignificantDiffs(); // True if status should be set to identical
1967                         m_pDirDoc->UpdateChangedItem(m_filePaths, m_diffList.GetSignificantDiffs(),
1968                                         m_nTrivialDiffs, bIdentical);
1969                 }
1970         }
1971 }
1972
1973 void CMergeDoc::DoFileSave(int nBuffer)
1974 {
1975         bool bSaveSuccess = false;
1976         bool bModified = false;
1977
1978         if (m_ptBuf[nBuffer]->IsModified() && !m_ptBuf[nBuffer]->GetReadOnly())
1979         {
1980                 bModified = true;
1981                 DoSave(m_filePaths[nBuffer].c_str(), bSaveSuccess, nBuffer );
1982         }
1983
1984         // If file were modified and saving succeeded,
1985         // update status on dir view
1986         if (bModified && bSaveSuccess)
1987         {
1988                 // If DirDoc contains compare results
1989                 if (m_pDirDoc != nullptr && m_pDirDoc->HasDiffs())
1990                 {
1991                         for (int nBuffer1 = 0; nBuffer1 < m_nBuffers; nBuffer1++)
1992                         {
1993                                 if (m_bEditAfterRescan[nBuffer1])
1994                                 {
1995                                         FlushAndRescan(false);
1996                                         break;
1997                                 }
1998                         }
1999
2000                         bool bIdentical = !m_diffList.HasSignificantDiffs(); // True if status should be set to identical
2001                         m_pDirDoc->UpdateChangedItem(m_filePaths, m_diffList.GetSignificantDiffs(),
2002                                         m_nTrivialDiffs, bIdentical);
2003                 }
2004         }
2005 }
2006
2007 /**
2008  * @brief Saves left-side file
2009  */
2010 void CMergeDoc::OnFileSaveLeft()
2011 {
2012         DoFileSave(0);
2013 }
2014
2015 /**
2016  * @brief Saves middle-side file
2017  */
2018 void CMergeDoc::OnFileSaveMiddle()
2019 {
2020         DoFileSave(1);
2021 }
2022
2023 /**
2024  * @brief Saves right-side file
2025  */
2026 void CMergeDoc::OnFileSaveRight()
2027 {
2028         DoFileSave(m_nBuffers - 1);
2029 }
2030
2031 /**
2032  * @brief Saves left-side file with name asked
2033  */
2034 void CMergeDoc::OnFileSaveAsLeft()
2035 {
2036         bool bSaveResult = false;
2037         DoSaveAs(m_filePaths.GetLeft().c_str(), bSaveResult, 0);
2038 }
2039
2040 /**
2041  * @brief Called when "Save middle (as...)" item is updated
2042  */
2043 void CMergeDoc::OnUpdateFileSaveAsMiddle(CCmdUI* pCmdUI)
2044 {
2045         pCmdUI->Enable(m_nBuffers == 3);
2046 }
2047
2048 /**
2049  * @brief Saves right-side file with name asked
2050  */
2051 void CMergeDoc::OnFileSaveAsMiddle()
2052 {
2053         bool bSaveResult = false;
2054         DoSaveAs(m_filePaths.GetMiddle().c_str(), bSaveResult, 1);
2055 }
2056
2057 /**
2058  * @brief Saves right-side file with name asked
2059  */
2060 void CMergeDoc::OnFileSaveAsRight()
2061 {
2062         bool bSaveResult = false;
2063         DoSaveAs(m_filePaths.GetRight().c_str(), bSaveResult, m_nBuffers - 1);
2064 }
2065
2066 /**
2067  * @brief Update diff-number pane text in file compare.
2068  * The diff number pane shows selected difference/amount of differences when
2069  * there is difference selected. If there is no difference selected, then
2070  * the panel shows amount of differences. If there are ignored differences,
2071  * those are not count into numbers.
2072  * @param [in] pCmdUI UI component to update.
2073  */
2074 void CMergeDoc::OnUpdateStatusNum(CCmdUI* pCmdUI) 
2075 {
2076         TCHAR sIdx[32] = { 0 };
2077         TCHAR sCnt[32] = { 0 };
2078         String s;
2079         const int nDiffs = m_diffList.GetSignificantDiffs();
2080         
2081         // Files are identical - show text "Identical"
2082         if (nDiffs <= 0)
2083                 s = _("Identical");
2084         
2085         // There are differences, but no selected diff
2086         // - show amount of diffs
2087         else if (GetCurrentDiff() < 0)
2088         {
2089                 s = nDiffs == 1 ? _("1 Difference Found") : _("%1 Differences Found");
2090                 _itot_s(nDiffs, sCnt, 10);
2091                 strutils::replace(s, _T("%1"), sCnt);
2092         }
2093         
2094         // There are differences and diff selected
2095         // - show diff number and amount of diffs
2096         else
2097         {
2098                 s = _("Difference %1 of %2");
2099                 const int signInd = m_diffList.GetSignificantIndex(GetCurrentDiff());
2100                 _itot_s(signInd + 1, sIdx, 10);
2101                 strutils::replace(s, _T("%1"), sIdx);
2102                 _itot_s(nDiffs, sCnt, 10);
2103                 strutils::replace(s, _T("%2"), sCnt);
2104         }
2105         pCmdUI->SetText(s.c_str());
2106 }
2107
2108 /**
2109  * @brief Update plugin name
2110  * @param [in] pCmdUI UI component to update.
2111  */
2112 void CMergeDoc::OnUpdatePluginName(CCmdUI* pCmdUI)
2113 {
2114         String pluginNames;
2115         if (m_pInfoUnpacker && !m_pInfoUnpacker->m_PluginName.empty())
2116                 pluginNames += m_pInfoUnpacker->m_PluginName + _T("&");
2117         PrediffingInfo prediffer;
2118         GetPrediffer(&prediffer);
2119         if (!prediffer.m_PluginName.empty())
2120                 pluginNames += prediffer.m_PluginName + _T("&");
2121         pCmdUI->SetText(pluginNames.substr(0, pluginNames.length() - 1).c_str());
2122 }
2123
2124 /**
2125  * @brief Change number of diff context lines
2126  */
2127 void CMergeDoc::OnDiffContext(UINT nID)
2128 {
2129         switch (nID)
2130         {
2131         case ID_VIEW_DIFFCONTEXT_0:
2132                 m_nDiffContext = 0; break;
2133         case ID_VIEW_DIFFCONTEXT_1:
2134                 m_nDiffContext = 1; break;
2135         case ID_VIEW_DIFFCONTEXT_3:
2136                 m_nDiffContext = 3; break;
2137         case ID_VIEW_DIFFCONTEXT_5:
2138                 m_nDiffContext = 5; break;
2139         case ID_VIEW_DIFFCONTEXT_7:
2140                 m_nDiffContext = 7; break;
2141         case ID_VIEW_DIFFCONTEXT_9:
2142                 m_nDiffContext = 9; break;
2143         case ID_VIEW_DIFFCONTEXT_TOGGLE:
2144                 m_nDiffContext = -m_nDiffContext - 1; break;
2145         case ID_VIEW_DIFFCONTEXT_ALL:
2146                 if (m_nDiffContext >= 0)
2147                         m_nDiffContext = -m_nDiffContext - 1;
2148                 break;
2149         case ID_VIEW_DIFFCONTEXT_INVERT:
2150                 m_bInvertDiffContext = !m_bInvertDiffContext;
2151                 break;
2152         }
2153         GetOptionsMgr()->SaveOption(OPT_DIFF_CONTEXT, m_nDiffContext);
2154         GetOptionsMgr()->SaveOption(OPT_INVERT_DIFF_CONTEXT, m_bInvertDiffContext);
2155         FlushAndRescan(true);
2156 }
2157
2158 /**
2159  * @brief Swap context enable for 3 file compares 
2160  */
2161 void CMergeDoc::OnUpdateSwapContext(CCmdUI* pCmdUI)
2162 {
2163         if (m_nBuffers > 2)
2164         {
2165                 pCmdUI->Enable(true);
2166         }
2167         else
2168         {
2169                 pCmdUI->Enable(false);
2170         }
2171 }
2172
2173 /**
2174  * @brief Update number of diff context lines
2175  */
2176 void CMergeDoc::OnUpdateDiffContext(CCmdUI* pCmdUI)
2177 {
2178         bool bCheck;
2179         switch (pCmdUI->m_nID)
2180         {
2181         case ID_VIEW_DIFFCONTEXT_0:
2182                 bCheck = (m_nDiffContext == 0); break;
2183         case ID_VIEW_DIFFCONTEXT_1:
2184                 bCheck = (m_nDiffContext == 1); break;
2185         case ID_VIEW_DIFFCONTEXT_3:
2186                 bCheck = (m_nDiffContext == 3); break;
2187         case ID_VIEW_DIFFCONTEXT_5:
2188                 bCheck = (m_nDiffContext == 5); break;
2189         case ID_VIEW_DIFFCONTEXT_7:
2190                 bCheck = (m_nDiffContext == 7); break;
2191         case ID_VIEW_DIFFCONTEXT_9:
2192                 bCheck = (m_nDiffContext == 9); break;
2193         case ID_VIEW_DIFFCONTEXT_TOGGLE:
2194                 bCheck = false; break;
2195         case ID_VIEW_DIFFCONTEXT_INVERT:
2196                 bCheck = m_bInvertDiffContext; break;
2197         default:
2198                 bCheck = (m_nDiffContext < 0); break;
2199         }
2200         pCmdUI->SetCheck(bCheck);
2201         pCmdUI->Enable(!(pCmdUI->m_nID == ID_VIEW_DIFFCONTEXT_INVERT && (m_nDiffContext < 0)));
2202 }
2203
2204 /**
2205  * @brief Build the diff array and prepare buffers accordingly (insert ghost lines, set WinMerge flags)
2206  *
2207  * @note After PrimeTextBuffers(), all buffers should have the same length.
2208  */
2209 void CMergeDoc::PrimeTextBuffers()
2210 {
2211         SetCurrentDiff(-1);
2212         m_nTrivialDiffs = 0;
2213         int nDiff;
2214         int nDiffCount = m_diffList.GetSize();
2215         int file;
2216
2217         // walk the diff list and calculate numbers of extra lines to add
2218         int extras[3] = {0, 0, 0};   // extra lines added to each view
2219         m_diffList.GetExtraLinesCounts(m_nBuffers, extras);
2220
2221         // resize m_aLines once for each view
2222         UINT lcount[3] = {0, 0, 0};
2223         UINT lcountnew[3] = {0, 0, 0};
2224         UINT lcountmax = 0;
2225         
2226         for (file = 0; file < m_nBuffers; file++)
2227         {
2228                 lcount[file] = m_ptBuf[file]->GetLineCount();
2229                 lcountnew[file] = lcount[file] + extras[file];
2230                 lcountmax = max(lcountmax, lcountnew[file]);
2231         }
2232         for (file = 0; file < m_nBuffers; file++)
2233         {
2234                 m_ptBuf[file]->m_aLines.resize(lcountmax);
2235         }
2236
2237         // walk the diff list backward, move existing lines to proper place,
2238         // add ghost lines, and set flags
2239         for (nDiff = nDiffCount - 1; nDiff >= 0; nDiff --)
2240         {
2241                 DIFFRANGE curDiff;
2242                 VERIFY(m_diffList.GetDiff(nDiff, curDiff));
2243
2244                 // move matched lines after curDiff
2245                 int nline[3] = { 0, 0, 0 };
2246                 for (file = 0; file < m_nBuffers; file++)
2247                         nline[file] = lcount[file] - curDiff.end[file] - 1; // #lines on left/middle/right after current diff
2248                 // Matched lines should really match...
2249                 // But matched lines after last diff may differ because of empty last line (see function's note)
2250                 if (nDiff < nDiffCount - 1)
2251                         ASSERT(nline[0] == nline[1]);
2252
2253                 int nmaxline = 0;
2254                 for (file = 0; file < m_nBuffers; file++)
2255                 {
2256                         // Move all lines after current diff down as far as needed
2257                         // for any ghost lines we're about to insert
2258                         m_ptBuf[file]->MoveLine(curDiff.end[file]+1, lcount[file]-1, lcountnew[file]-nline[file]);
2259                         lcountnew[file] -= nline[file];
2260                         lcount[file] -= nline[file];
2261                         // move unmatched lines and add ghost lines
2262                         nline[file] = curDiff.end[file] - curDiff.begin[file] + 1; // #lines in diff on left/middle/right
2263                         nmaxline = max(nmaxline, nline[file]);
2264                 }
2265
2266                 for (file = 0; file < m_nBuffers; file++)
2267                 {
2268                         DWORD dflag = LF_GHOST;
2269                         if ((file == 0 && curDiff.op == OP_3RDONLY) || (file == 2 && curDiff.op == OP_1STONLY))
2270                                 dflag |= LF_SNP;
2271                         m_ptBuf[file]->MoveLine(curDiff.begin[file], curDiff.end[file], lcountnew[file]-nmaxline);
2272                         int nextra = nmaxline - nline[file];
2273                         if (nextra > 0)
2274                         {
2275                                 m_ptBuf[file]->SetEmptyLine(lcountnew[file] - nextra, nextra);
2276                                 for (int i = 1; i <= nextra; i++)
2277                                         m_ptBuf[file]->SetLineFlag(lcountnew[file]-i, dflag, true, false, false);
2278                         }
2279                         lcountnew[file] -= nmaxline;
2280
2281                         lcount[file] -= nline[file];
2282
2283                 }
2284                 // set dbegin, dend, blank, and line flags
2285                 curDiff.dbegin = lcountnew[0];
2286
2287                 switch (curDiff.op)
2288                 {
2289                 case OP_TRIVIAL:
2290                         ++m_nTrivialDiffs;
2291                         [[fallthrough]];
2292                 case OP_DIFF:
2293                 case OP_1STONLY:
2294                 case OP_2NDONLY:
2295                 case OP_3RDONLY:
2296                         // set curdiff
2297                         {
2298                                 curDiff.dend = lcountnew[0]+nmaxline-1;
2299                                 for (file = 0; file < m_nBuffers; file++)
2300                                 {
2301                                         curDiff.blank[file] = -1;
2302                                         int nextra = nmaxline - nline[file];
2303                                         if (nmaxline > nline[file])
2304                                         {
2305                                                 // more lines on left, ghost lines on right side
2306                                                 curDiff.blank[file] = curDiff.dend + 1 - nextra;
2307                                         }
2308                                 }
2309                         }
2310                         // flag lines
2311                         {
2312                                 for (file = 0; file < m_nBuffers; file++)
2313                                 {
2314                                         // left side
2315                                         int i;
2316                                         for (i = curDiff.dbegin; i <= curDiff.dend; i++)
2317                                         {
2318                                                 if (curDiff.blank[file] == -1 || (int)i < curDiff.blank[file])
2319                                                 {
2320                                                         // set diff or trivial flag
2321                                                         DWORD dflag = (curDiff.op == OP_TRIVIAL) ? LF_TRIVIAL : LF_DIFF;
2322                                                         if ((file == 0 && curDiff.op == OP_3RDONLY) || (file == 2 && curDiff.op == OP_1STONLY))
2323                                                                 dflag |= LF_SNP;
2324                                                         m_ptBuf[file]->SetLineFlag(i, dflag, true, false, false);
2325                                                         m_ptBuf[file]->SetLineFlag(i, LF_INVISIBLE, false, false, false);
2326                                                 }
2327                                                 else
2328                                                 {
2329                                                         // ghost lines are already inserted (and flagged)
2330                                                         // ghost lines opposite to trivial lines are ghost and trivial
2331                                                         if (curDiff.op == OP_TRIVIAL)
2332                                                                 m_ptBuf[file]->SetLineFlag(i, LF_TRIVIAL, true, false, false);
2333                                                 }
2334                                         }
2335                                 }
2336                         }
2337                         break;
2338                 }           // switch (curDiff.op)
2339                 VERIFY(m_diffList.SetDiff(nDiff, curDiff));
2340         }             // for (nDiff = nDiffCount; nDiff-- > 0; )
2341
2342         m_diffList.ConstructSignificantChain();
2343
2344 #ifdef _DEBUG
2345         // Note: By this point all `m_ptBuf[]` buffers must have the same  
2346         //              number of line entries; eventual buffer processing typically
2347         //              uses the line count from `m_ptBuf[0]` for all buffer processing.
2348
2349         for (file = 0; file < m_nBuffers; file++)
2350         {
2351                 ASSERT(m_ptBuf[0]->GetLineCount() == m_ptBuf[file]->GetLineCount());
2352         }
2353 #endif
2354
2355         for (file = 0; file < m_nBuffers; file++)
2356                 m_ptBuf[file]->FinishLoading();
2357 }
2358
2359 /**
2360  * @brief Checks if file has changed since last update (save or rescan).
2361  * @param [in] szPath File to check
2362  * @param [in] dfi Previous fileinfo of file
2363  * @param [in] bSave If true Compare to last save-info, else to rescan-info
2364  * @param [in] nBuffer Index (0-based) of buffer
2365  * @return true if file is changed.
2366  */
2367 CMergeDoc::FileChange CMergeDoc::IsFileChangedOnDisk(LPCTSTR szPath, DiffFileInfo &dfi,
2368         bool bSave, int nBuffer)
2369 {
2370         DiffFileInfo *fileInfo = nullptr;
2371         bool bFileChanged = false;
2372         bool bIgnoreSmallDiff = GetOptionsMgr()->GetBool(OPT_IGNORE_SMALL_FILETIME);
2373         int tolerance = 0;
2374         if (bIgnoreSmallDiff)
2375                 tolerance = SmallTimeDiff; // From MainFrm.h
2376
2377         if (bSave)
2378                 fileInfo = m_pSaveFileInfo[nBuffer].get();
2379         else
2380                 fileInfo = m_pRescanFileInfo[nBuffer].get();
2381
2382         // We assume file existed, so disappearing means removal
2383         if (!dfi.Update(szPath))
2384                 return FileChange::Removed;
2385
2386         int64_t timeDiff = dfi.mtime - fileInfo->mtime;
2387         if (timeDiff < 0) timeDiff = -timeDiff;
2388         if ((timeDiff > tolerance * Poco::Timestamp::resolution()) || (dfi.size != fileInfo->size))
2389         {
2390                 bFileChanged = true;
2391         }
2392
2393         if (bFileChanged)
2394                 return FileChange::Changed;
2395         else
2396                 return FileChange::NoChange;
2397 }
2398
2399 void CMergeDoc::HideLines()
2400 {
2401         int nLine;
2402         int file;
2403
2404         if (m_nDiffContext < 0)
2405         {
2406                 ForEachView([](auto& pView) { pView->SetEnableHideLines(false); });
2407                 return;
2408         }
2409
2410         int nLineCount = 0x7fffffff;
2411         for (file = 0; file < m_nBuffers; file++)
2412         {
2413                 if (nLineCount > m_ptBuf[file]->GetLineCount())
2414                         nLineCount = m_ptBuf[file]->GetLineCount();
2415         }
2416
2417         for (nLine =  0; nLine < nLineCount;)
2418         {
2419                 bool diff = !!(m_ptBuf[0]->GetLineFlags(nLine) & (LF_DIFF | LF_GHOST));
2420                 if ((!m_bInvertDiffContext && !diff) || (m_bInvertDiffContext && diff))
2421                 {
2422                         for (file = 0; file < m_nBuffers; file++)
2423                                 m_ptBuf[file]->SetLineFlag(nLine, LF_INVISIBLE, true, false, false);
2424                         nLine++;
2425                 }
2426                 else
2427                 {
2428                         int nLine2 = (nLine - m_nDiffContext < 0) ? 0 : (nLine - m_nDiffContext);
2429                         for (; nLine2 < nLine; nLine2++)
2430                         {
2431                                 for (file = 0; file < m_nBuffers; file++)
2432                                         m_ptBuf[file]->SetLineFlag(nLine2, LF_INVISIBLE, false, false, false);
2433                         }
2434                 
2435                         for (; nLine < nLineCount; nLine++)
2436                         {
2437                                 diff = !!(m_ptBuf[0]->GetLineFlags(nLine) & (LF_DIFF | LF_GHOST));
2438                                 if ((!m_bInvertDiffContext && !diff) || (m_bInvertDiffContext && diff))
2439                                         break;
2440                                 for (file = 0; file < m_nBuffers; file++)
2441                                         m_ptBuf[file]->SetLineFlag(nLine, LF_INVISIBLE, false, false, false);
2442                         }
2443
2444                         int nLineEnd2 = (nLine + m_nDiffContext >= nLineCount) ? nLineCount-1 : (nLine + m_nDiffContext);
2445                         for (; nLine < nLineEnd2; nLine++)
2446                         {
2447                                 for (file = 0; file < m_nBuffers; file++)
2448                                         m_ptBuf[file]->SetLineFlag(nLine, LF_INVISIBLE, false, false, false);
2449                                 diff = !!(m_ptBuf[0]->GetLineFlags(nLine) & (LF_DIFF | LF_GHOST));
2450                                 if ((!m_bInvertDiffContext && diff) || (m_bInvertDiffContext && !diff))
2451                                         nLineEnd2 = (nLine + 1 + m_nDiffContext >= nLineCount) ? nLineCount-1 : (nLine + 1 + m_nDiffContext);
2452                         }
2453                 }
2454         }
2455
2456         ForEachView([](auto& pView) { pView->SetEnableHideLines(true); });
2457 }
2458
2459 /**
2460  * @brief Asks and then saves modified files.
2461  *
2462  * This function saves modified files. Dialog is shown for user to select
2463  * modified file(s) one wants to save or discard changed. Cancelling of
2464  * save operation is allowed unless denied by parameter. After successfully
2465  * save operation file statuses are updated to directory compare.
2466  * @param [in] bAllowCancel If false "Cancel" button is disabled.
2467  * @return true if user selected "OK" so next operation can be
2468  * executed. If false user choosed "Cancel".
2469  * @note If filename is empty, we assume scratchpads are saved,
2470  * so instead of filename, description is shown.
2471  * @todo If we have filename and description for file, what should
2472  * we do after saving to different filename? Empty description?
2473  * @todo Parameter @p bAllowCancel is always true in callers - can be removed.
2474  */
2475 bool CMergeDoc::PromptAndSaveIfNeeded(bool bAllowCancel)
2476 {
2477         bool bLModified = false, bMModified = false, bRModified = false;
2478         bool result = true;
2479         bool bLSaveSuccess = false, bMSaveSuccess = false, bRSaveSuccess = false;
2480
2481         if (m_nBuffers == 3)
2482         {
2483                 bLModified = m_ptBuf[0]->IsModified();
2484                 bMModified = m_ptBuf[1]->IsModified();
2485                 bRModified = m_ptBuf[2]->IsModified();
2486         }
2487         else
2488         {
2489                 bLModified = m_ptBuf[0]->IsModified();
2490                 bRModified = m_ptBuf[1]->IsModified();
2491         }
2492         if (!bLModified && !bMModified && !bRModified)
2493                  return true;
2494
2495         SaveClosingDlg dlg;
2496         dlg.DoAskFor(bLModified, bMModified, bRModified);
2497         if (!bAllowCancel)
2498                 dlg.m_bDisableCancel = true;
2499         if (!m_filePaths.GetLeft().empty())
2500         {
2501                 if (theApp.m_strSaveAsPath.empty())
2502                         dlg.m_sLeftFile = m_filePaths.GetLeft();
2503                 else
2504                         dlg.m_sLeftFile = theApp.m_strSaveAsPath;
2505         }
2506         else
2507                 dlg.m_sLeftFile = m_strDesc[0];
2508         if (m_nBuffers == 3)
2509         {
2510                 if (!m_filePaths.GetMiddle().empty())
2511                 {
2512                         if (theApp.m_strSaveAsPath.empty())
2513                                 dlg.m_sMiddleFile = m_filePaths.GetMiddle();
2514                         else
2515                                 dlg.m_sMiddleFile = theApp.m_strSaveAsPath;
2516                 }
2517                 else
2518                         dlg.m_sMiddleFile = m_strDesc[1];
2519         }
2520         if (!m_filePaths.GetRight().empty())
2521         {
2522                 if (theApp.m_strSaveAsPath.empty())
2523                         dlg.m_sRightFile = m_filePaths.GetRight();
2524                 else
2525                         dlg.m_sRightFile = theApp.m_strSaveAsPath;
2526         }
2527         else
2528                 dlg.m_sRightFile = m_strDesc[m_nBuffers - 1];
2529
2530         if (dlg.DoModal() == IDOK)
2531         {
2532                 if (bLModified && dlg.m_leftSave == SaveClosingDlg::SAVECLOSING_SAVE)
2533                 {
2534                         if (!DoSave(m_filePaths.GetLeft().c_str(), bLSaveSuccess, 0))
2535                                 result = false;
2536                 }
2537
2538                 if (bMModified && dlg.m_middleSave == SaveClosingDlg::SAVECLOSING_SAVE)
2539                 {
2540                         if (!DoSave(m_filePaths.GetMiddle().c_str(), bMSaveSuccess, 1))
2541                                 result = false;
2542                 }
2543
2544                 if (bRModified && dlg.m_rightSave == SaveClosingDlg::SAVECLOSING_SAVE)
2545                 {
2546                         if (!DoSave(m_filePaths.GetRight().c_str(), bRSaveSuccess, m_nBuffers - 1))
2547                                 result = false;
2548                 }
2549         }
2550         else
2551         {       
2552                 result = false;
2553         }
2554
2555         // If file were modified and saving was successfull,
2556         // update status on dir view
2557         if ((bLModified && bLSaveSuccess) || 
2558              (bMModified && bMSaveSuccess) ||
2559                  (bRModified && bRSaveSuccess))
2560         {
2561                 // If directory compare has results
2562                 if (m_pDirDoc != nullptr && m_pDirDoc->HasDiffs())
2563                 {
2564                         if (m_bEditAfterRescan[0] || m_bEditAfterRescan[1] || (m_nBuffers == 3 && m_bEditAfterRescan[2]))
2565                                 FlushAndRescan(false);
2566
2567                         bool bIdentical = !m_diffList.HasSignificantDiffs(); // True if status should be set to identical
2568                         m_pDirDoc->UpdateChangedItem(m_filePaths, m_diffList.GetSignificantDiffs(),
2569                                         m_nTrivialDiffs, bIdentical);
2570                 }
2571         }
2572
2573         return result;
2574 }
2575
2576 /** Rescan only if we did not Rescan during the last timeOutInSecond seconds*/
2577 void CMergeDoc::RescanIfNeeded(float timeOutInSecond)
2578 {
2579         // if we did not rescan during the request timeOut, Rescan
2580         // else we did Rescan after the request, so do nothing
2581         COleDateTimeSpan elapsed = COleDateTime::GetCurrentTime() - m_LastRescan;
2582         if (elapsed.GetTotalSeconds() >= timeOutInSecond)
2583                 // (laoran 08-01-2003) maybe should be FlushAndRescan(true) ??
2584                 FlushAndRescan();
2585 }
2586
2587 /**
2588  * @brief We have two child views (left & right), so we keep pointers directly
2589  * at them (the MFC view list doesn't have them both)
2590  */
2591 void CMergeDoc::AddMergeViews(CMergeEditView *pView[3])
2592 {
2593
2594         for (int nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
2595                 m_pView[m_nGroups][nBuffer] = pView[nBuffer];
2596         ++m_nGroups;
2597 }
2598
2599 void CMergeDoc::RemoveMergeViews(int nGroup)
2600 {
2601
2602         for (; nGroup < m_nGroups - 1; nGroup++)
2603         {
2604                 for (int nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
2605                 {
2606                         m_pView[nGroup][nBuffer] = m_pView[nGroup + 1][nBuffer];
2607                         m_pView[nGroup][nBuffer]->m_nThisGroup = nGroup;
2608                 }
2609         }
2610         --m_nGroups;
2611 }
2612
2613 /**
2614  * @brief DirDoc gives us its identity just after it creates us
2615  */
2616 void CMergeDoc::SetDirDoc(CDirDoc * pDirDoc)
2617 {
2618         ASSERT(pDirDoc != nullptr && m_pDirDoc == nullptr);
2619         m_pDirDoc = pDirDoc;
2620 }
2621
2622 /**
2623  * @brief Return pointer to parent frame
2624  */
2625 CMergeEditFrame * CMergeDoc::GetParentFrame() 
2626 {
2627         return dynamic_cast<CMergeEditFrame *>(m_pView[0][0]->GetParentFrame()); 
2628 }
2629
2630 /**
2631  * @brief DirDoc is closing
2632  */
2633 void CMergeDoc::DirDocClosing(CDirDoc * pDirDoc)
2634 {
2635         ASSERT(m_pDirDoc == pDirDoc);
2636         m_pDirDoc = nullptr;
2637         // TODO (Perry 2003-03-30): perhaps merge doc should close now ?
2638 }
2639
2640 /**
2641  * @brief DirDoc commanding us to close
2642  */
2643 bool CMergeDoc::CloseNow()
2644 {
2645         // Allow user to cancel closing
2646         if (!PromptAndSaveIfNeeded(true))
2647                 return false;
2648
2649         GetParentFrame()->CloseNow();
2650         return true;
2651 }
2652
2653 /**
2654  * @brief Loads file to buffer and shows load-errors
2655  * @param [in] sFileName File to open
2656  * @param [in] nBuffer Index (0-based) of buffer to load
2657  * @param [out] readOnly whether file is read-only
2658  * @param [in] encoding encoding used
2659  * @return Tells if files were loaded successfully
2660  * @sa CMergeDoc::OpenDocs()
2661  **/
2662 int CMergeDoc::LoadFile(CString sFileName, int nBuffer, bool & readOnly, const FileTextEncoding & encoding)
2663 {
2664         String sError;
2665         DWORD retVal = FileLoadResult::FRESULT_ERROR;
2666
2667         CDiffTextBuffer *pBuf = m_ptBuf[nBuffer].get();
2668         m_filePaths[nBuffer] = sFileName;
2669
2670         CRLFSTYLE nCrlfStyle = CRLFSTYLE::AUTOMATIC;
2671         CString sOpenError;
2672         retVal = pBuf->LoadFromFile(sFileName, m_pInfoUnpacker.get(),
2673                 m_strBothFilenames.c_str(), readOnly, nCrlfStyle, encoding, sOpenError);
2674
2675         // if CMergeDoc::CDiffTextBuffer::LoadFromFile failed,
2676         // it left the pBuf in a valid (but empty) state via a call to InitNew
2677
2678         if (FileLoadResult::IsOkImpure(retVal))
2679         {
2680                 // File loaded, and multiple EOL types in this file
2681                 FileLoadResult::SetMainOk(retVal);
2682
2683                 // If mixed EOLs are not enabled, enable them for this doc.
2684                 if (!GetOptionsMgr()->GetBool(OPT_ALLOW_MIXED_EOL))
2685                 {
2686                         pBuf->SetMixedEOL(true);
2687                 }
2688         }
2689
2690         if (FileLoadResult::IsError(retVal))
2691         {
2692                 // Error from Unifile/system
2693                 if (!sOpenError.IsEmpty())
2694                         sError = strutils::format_string2(_("Cannot open file\n%1\n\n%2"), (LPCTSTR)sFileName, (LPCTSTR)sOpenError);
2695                 else
2696                         sError = strutils::format_string1(_("File not found: %1"), (LPCTSTR)sFileName);
2697                 ShowMessageBox(sError, MB_OK | MB_ICONSTOP | MB_MODELESS);
2698         }
2699         else if (FileLoadResult::IsErrorUnpack(retVal))
2700         {
2701                 sError = strutils::format_string1(_("File not unpacked: %1"), (LPCTSTR)sFileName);
2702                 ShowMessageBox(sError, MB_OK | MB_ICONSTOP | MB_MODELESS);
2703         }
2704         return retVal;
2705 }
2706
2707 /**
2708  * @brief Check if specified codepage number is valid for WinMerge Editor.
2709  * @param [in] cp Codepage number to check.
2710  * @return true if codepage is valid, false otherwise.
2711  */
2712 bool CMergeDoc::IsValidCodepageForMergeEditor(unsigned cp) const
2713 {
2714         if (cp == 0) // 0 is our signal value for invalid
2715                 return false;
2716         return GetEncodingNameFromCodePage(cp) != nullptr;
2717 }
2718
2719 /**
2720  * @brief Sanity check file's specified codepage.
2721  * This function checks if file's specified codepage is valid for WinMerge
2722  * editor and if not resets the codepage to default.
2723  * @param [in,out] fileinfo Class containing file's codepage.
2724  */
2725 void CMergeDoc::SanityCheckCodepage(FileLocation & fileinfo)
2726 {
2727         if (fileinfo.encoding.m_unicoding == ucr::NONE
2728                 && !IsValidCodepageForMergeEditor(fileinfo.encoding.m_codepage))
2729         {
2730                 int cp = ucr::getDefaultCodepage();
2731                 if (!IsValidCodepageForMergeEditor(cp))
2732                         cp = CP_ACP;
2733                 fileinfo.encoding.SetCodepage(cp);
2734         }
2735 }
2736
2737 /**
2738  * @brief Loads one file from disk and updates file infos.
2739  * @param [in] index Index of file in internal buffers.
2740  * @param [in] filename File's name.
2741  * @param [in] readOnly Is file read-only?
2742  * @param [in] encoding File's encoding.
2743  * @return One of FileLoadResult values.
2744  */
2745 DWORD CMergeDoc::LoadOneFile(int index, String filename, bool readOnly, const String& strDesc, 
2746                 const FileTextEncoding & encoding)
2747 {
2748         DWORD loadSuccess = FileLoadResult::FRESULT_ERROR;;
2749         
2750         m_strDesc[index] = strDesc;
2751         if (!filename.empty())
2752         {
2753                 if (strDesc.empty())
2754                         m_nBufferType[index] = BUFFERTYPE::NORMAL;
2755                 else
2756                         m_nBufferType[index] = BUFFERTYPE::NORMAL_NAMED;
2757                 m_pSaveFileInfo[index]->Update(filename);
2758                 m_pRescanFileInfo[index]->Update(filename);
2759
2760                 loadSuccess = LoadFile(filename.c_str(), index, readOnly, encoding);
2761                 if (FileLoadResult::IsLossy(loadSuccess))
2762                 {
2763                         // Determine the file encoding by looking at all the contents of the file, not just part of it
2764                         FileTextEncoding encodingNew = codepage_detect::Guess(filename, GetOptionsMgr()->GetInt(OPT_CP_DETECT), -1);
2765                         if (encoding != encodingNew)
2766                         {
2767                                 m_ptBuf[index]->FreeAll();
2768                                 loadSuccess = LoadFile(filename.c_str(), index, readOnly, encodingNew);
2769                         }
2770                 }
2771         }
2772         else
2773         {
2774                 m_nBufferType[index] = BUFFERTYPE::UNNAMED;
2775                 m_ptBuf[index]->InitNew();
2776                 m_ptBuf[index]->m_encoding = encoding;
2777                 m_ptBuf[index]->FinishLoading(); // should clear GGhostTextBuffer::m_RealityBlock when reloading unnamed buffer 
2778                 loadSuccess = FileLoadResult::FRESULT_OK;
2779         }
2780         return loadSuccess;
2781 }
2782
2783 void CMergeDoc::SetTableProperties()
2784 {
2785         struct TableProps { bool istable; TCHAR delimiter; TCHAR quote; bool allowNewlinesInQuotes; };
2786         auto getTablePropsByFileName = [](const String& path, const std::optional<bool>& enableTableEditing)-> TableProps
2787         {
2788                 const TCHAR quote = GetOptionsMgr()->GetString(OPT_CMP_TBL_QUOTE_CHAR).c_str()[0];
2789                 FileFilterHelper filterCSV, filterTSV, filterDSV;
2790                 bool allowNewlineIQuotes = GetOptionsMgr()->GetBool(OPT_CMP_TBL_ALLOW_NEWLINES_IN_QUOTES);
2791                 const String csvFilePattern = GetOptionsMgr()->GetString(OPT_CMP_CSV_FILEPATTERNS);
2792                 if (!csvFilePattern.empty())
2793                 {
2794                         filterCSV.UseMask(true);
2795                         filterCSV.SetMask(csvFilePattern);
2796                         if (filterCSV.includeFile(path))
2797                                 return { true, ',', quote, allowNewlineIQuotes };
2798                 }
2799                 const String tsvFilePattern = GetOptionsMgr()->GetString(OPT_CMP_TSV_FILEPATTERNS);
2800                 if (!tsvFilePattern.empty())
2801                 {
2802                         filterTSV.UseMask(true);
2803                         filterTSV.SetMask(tsvFilePattern);
2804                         if (filterTSV.includeFile(path))
2805                                 return { true, '\t', quote, allowNewlineIQuotes };
2806                 }
2807                 const String dsvFilePattern = GetOptionsMgr()->GetString(OPT_CMP_DSV_FILEPATTERNS);
2808                 if (!dsvFilePattern.empty())
2809                 {
2810                         filterDSV.UseMask(true);
2811                         filterDSV.SetMask(dsvFilePattern);
2812                         if (filterDSV.includeFile(path))
2813                                 return { true, GetOptionsMgr()->GetString(OPT_CMP_DSV_DELIM_CHAR).c_str()[0], quote };
2814                 }
2815                 if (enableTableEditing.value_or(false))
2816                 {
2817                         COpenTableDlg dlg;
2818                         if (dlg.DoModal() == IDOK)
2819                                 return { true, dlg.m_sDelimiterChar.c_str()[0], dlg.m_sQuoteChar.c_str()[0], dlg.m_bAllowNewlinesInQuotes };
2820                 }
2821                 return { false, 0, 0, false };
2822         };
2823
2824         TableProps tableProps[3] = {};
2825         int nTableFileIndex = -1;
2826         for (int nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
2827         {
2828                 if (nBuffer == 0 ||
2829                         paths::FindExtension(m_ptBuf[nBuffer - 1]->GetTempFileName()) != paths::FindExtension(m_ptBuf[nBuffer]->GetTempFileName()))
2830                         tableProps[nBuffer] = getTablePropsByFileName(m_ptBuf[nBuffer]->GetTempFileName(), m_bEnableTableEditing);
2831                 else
2832                         tableProps[nBuffer] = tableProps[nBuffer - 1];
2833                 if (tableProps[nBuffer].istable)
2834                         nTableFileIndex = nBuffer;
2835         }
2836         for (int nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
2837         {
2838                 if (m_bEnableTableEditing.value_or(true) && nTableFileIndex >= 0)
2839                 {
2840                         int i = tableProps[nBuffer].istable ? nBuffer : nTableFileIndex;
2841                         m_ptBuf[nBuffer]->SetTableEditing(true);
2842                         m_ptBuf[nBuffer]->ShareColumnWidths(*m_ptBuf[0]);
2843                         m_ptBuf[nBuffer]->SetAllowNewlinesInQuotes(tableProps[i].allowNewlinesInQuotes);
2844                         m_ptBuf[nBuffer]->SetFieldDelimiter(tableProps[i].delimiter);
2845                         m_ptBuf[nBuffer]->SetFieldEnclosure(tableProps[i].quote);
2846                         m_ptBuf[nBuffer]->JoinLinesForTableEditingMode();
2847                 }
2848                 else
2849                 {
2850                         m_ptBuf[nBuffer]->SetTableEditing(false);
2851                 }
2852         }
2853 }
2854
2855 /**
2856  * @brief Loads files and does initial rescan.
2857  * @param fileloc [in] File to open to left/middle/right side (path & encoding info)
2858  * @param bRO [in] Is left/middle/right file read-only
2859  * @return Success/Failure/Binary (failure) per typedef enum OpenDocsResult_TYPE
2860  * @todo Options are still read from CMainFrame, this will change
2861  * @sa CMainFrame::ShowTextMergeDoc()
2862  */
2863 bool CMergeDoc::OpenDocs(int nFiles, const FileLocation ifileloc[],
2864                 const bool bRO[], const String strDesc[])
2865 {
2866         IDENTLEVEL identical = IDENTLEVEL::NONE;
2867         int nRescanResult = RESCAN_OK;
2868         int nBuffer;
2869         FileLocation fileloc[3];
2870
2871         std::copy_n(ifileloc, 3, fileloc);
2872
2873         // Filter out invalid codepages, or editor will display all blank
2874         for (nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
2875                 SanityCheckCodepage(fileloc[nBuffer]);
2876
2877         // clear undo stack
2878         undoTgt.clear();
2879         curUndo = undoTgt.begin();
2880
2881         // Prevent displaying views during LoadFile
2882         // Note : attach buffer again only if both loads succeed
2883         m_strBothFilenames.erase();
2884
2885         ForEachView([](auto& pView) { pView->DetachFromBuffer(); });
2886
2887         for (nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
2888         {
2889                 // clear undo buffers
2890                 m_ptBuf[nBuffer]->m_aUndoBuf.clear();
2891
2892                 // free the buffers
2893                 m_ptBuf[nBuffer]->FreeAll ();
2894
2895                 // build the text being filtered, "|" separates files as it is forbidden in filenames
2896                 m_strBothFilenames += fileloc[nBuffer].filepath + _T("|");
2897         }
2898         m_strBothFilenames.erase(m_strBothFilenames.length() - 1);
2899
2900         // Load files
2901         DWORD nSuccess[3] = { FileLoadResult::FRESULT_ERROR,  FileLoadResult::FRESULT_ERROR,  FileLoadResult::FRESULT_ERROR };
2902         for (nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
2903         {
2904                 nSuccess[nBuffer] = LoadOneFile(nBuffer, fileloc[nBuffer].filepath, bRO[nBuffer], strDesc ? strDesc[nBuffer] : _T(""),
2905                         fileloc[nBuffer].encoding);
2906                 if (!FileLoadResult::IsOk(nSuccess[nBuffer]))
2907                 {
2908                         CMergeEditFrame* pFrame = GetParentFrame();
2909                         if (pFrame != nullptr)
2910                         {
2911                                 // Use verify macro to trap possible error in debug.
2912                                 VERIFY(pFrame->DestroyWindow());
2913                         }
2914                         return false;
2915                 }
2916         }
2917
2918         SetTableProperties();
2919
2920         const bool bFiltersEnabled = GetOptionsMgr()->GetBool(OPT_PLUGINS_ENABLED);
2921
2922         // scratchpad : we don't call LoadFile, so
2923         // we need to initialize the unpacker as a "do nothing" one
2924         if (bFiltersEnabled)
2925         { 
2926                 if (std::count(m_nBufferType, m_nBufferType + m_nBuffers, BUFFERTYPE::UNNAMED) == m_nBuffers)
2927                 {
2928                         m_pInfoUnpacker->Initialize(PLUGIN_MODE::PLUGIN_MANUAL);
2929                 }
2930         }
2931
2932         // Warn user if file load was lossy (bad encoding)
2933         int idres=0;
2934         int nLossyBuffers = 0;
2935         for (nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
2936         {
2937                 if (FileLoadResult::IsLossy(nSuccess[nBuffer]))
2938                 {
2939                         // TODO: It would be nice to report how many lines were lossy
2940                         // we did calculate those numbers when we loaded the files, in the text stats
2941         
2942                         idres = IDS_LOSSY_TRANSCODING_FIRST + nBuffer;
2943                         nLossyBuffers++;
2944                 }
2945         }
2946         if (nLossyBuffers > 1)
2947                 idres = IDS_LOSSY_TRANSCODING_BOTH; /* FIXEME */
2948         
2949         if (nLossyBuffers > 0)
2950         {
2951                 if (m_pEncodingErrorBar == nullptr)
2952                 {
2953                         m_pEncodingErrorBar.reset(new CEncodingErrorBar());
2954                         m_pEncodingErrorBar->Create(this->m_pView[0][0]->GetParentFrame());
2955                 }
2956                 m_pEncodingErrorBar->SetText(LoadResString(idres));
2957                 m_pView[0][0]->GetParentFrame()->ShowControlBar(m_pEncodingErrorBar.get(), TRUE, FALSE);
2958         }
2959
2960         ForEachView([](auto& pView) {
2961                 // Now buffers data are valid
2962                 pView->AttachToBuffer();
2963                 // Currently there is only one set of syntax colors, which all documents & views share
2964                 pView->SetColorContext(theApp.GetMainSyntaxColors());
2965                 // Currently there is only one set of markers, which all documents & views share
2966                 pView->SetMarkersContext(theApp.GetMainMarkers());
2967         });
2968         for (nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
2969         {
2970                 // Set read-only statuses
2971                 m_ptBuf[nBuffer]->SetReadOnly(bRO[nBuffer]);
2972         }
2973
2974         // Check the EOL sensitivity option (do it before Rescan)
2975         DIFFOPTIONS diffOptions = {0};
2976         m_diffWrapper.GetOptions(&diffOptions);
2977         if (!GetOptionsMgr()->GetBool(OPT_ALLOW_MIXED_EOL) && !diffOptions.bIgnoreEol)
2978         {
2979                 for (nBuffer = 1; nBuffer < m_nBuffers; nBuffer++)
2980                         if (m_ptBuf[0]->GetCRLFMode() != m_ptBuf[nBuffer]->GetCRLFMode())
2981                                 break;
2982
2983                 if (nBuffer < m_nBuffers)
2984                 {
2985                         // Options and files not are not compatible :
2986                         // Sensitive to EOL on, allow mixing EOL off, and files have a different EOL style.
2987                         // All lines will differ, that is not very interesting and probably not wanted.
2988                         // Propose to turn off the option 'sensitive to EOL'
2989                         String s = theApp.LoadString(IDS_SUGGEST_IGNOREEOL);
2990                         if (ShowMessageBox(s, MB_YESNO | MB_ICONWARNING | MB_DONT_ASK_AGAIN, IDS_SUGGEST_IGNOREEOL) == IDYES)
2991                         {
2992                                 diffOptions.bIgnoreEol = true;
2993                                 m_diffWrapper.SetOptions(&diffOptions);
2994
2995                                 CMessageBoxDialog dlg(nullptr, s.c_str(), _T(""), 0, IDS_SUGGEST_IGNOREEOL);
2996                                 const int nFormerResult = dlg.GetFormerResult();
2997                                 if (nFormerResult != -1)
2998                                 {
2999                                         // "Don't ask this question again" checkbox is checked
3000                                         GetOptionsMgr()->SaveOption(OPT_CMP_IGNORE_EOL, true);
3001                                 }
3002                         }
3003                 }
3004         }
3005
3006         // Define the prediffer
3007         PackingInfo * infoUnpacker = nullptr;
3008         PrediffingInfo * infoPrediffer = nullptr;
3009         if (bFiltersEnabled && m_pDirDoc != nullptr)
3010         {
3011                 m_pDirDoc->GetPluginManager().FetchPluginInfos(m_strBothFilenames, &infoUnpacker, &infoPrediffer);
3012                 m_diffWrapper.SetPrediffer(infoPrediffer);
3013                 m_diffWrapper.SetTextForAutomaticPrediff(m_strBothFilenames);
3014         }
3015
3016         bool bBinary = false;
3017         nRescanResult = Rescan(bBinary, identical);
3018
3019         // Open filed if rescan succeed and files are not binaries
3020         if (nRescanResult == RESCAN_OK)
3021         {
3022                 // set the document types
3023                 // Warning : it is the first thing to do (must be done before UpdateView,
3024                 // or any function that calls UpdateView, like SelectDiff)
3025                 // Note: If option enabled, and another side type is not recognized,
3026                 // we use recognized type for unrecognized side too.
3027                 String sext[3];
3028                 bool bTyped[3];
3029                 int paneTyped = 0;
3030
3031                 for (nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
3032                 {
3033                         if (bFiltersEnabled && m_pInfoUnpacker->m_textType.length())
3034                                 sext[nBuffer] = m_pInfoUnpacker->m_textType;
3035                         else
3036                                 sext[nBuffer] = GetFileExt(fileloc[nBuffer].filepath.c_str(), m_strDesc[nBuffer].c_str());
3037                         ForEachView(nBuffer, [&](auto& pView) {
3038                                 bTyped[nBuffer] = pView->SetTextType(sext[nBuffer].c_str());
3039                                 if (bTyped[nBuffer])
3040                                         paneTyped = nBuffer;
3041                         });
3042                 }
3043
3044                 for (nBuffer = 1; nBuffer < m_nBuffers; nBuffer++)
3045                 {
3046                         if (bTyped[0] != bTyped[nBuffer])
3047                                 break;
3048                 }
3049
3050                 bool syntaxHLEnabled = GetOptionsMgr()->GetBool(OPT_SYNTAX_HIGHLIGHT);
3051                 if (syntaxHLEnabled && nBuffer < m_nBuffers)
3052                 {
3053                         if (std::count(bTyped, bTyped + m_nBuffers, false) == m_nBuffers)
3054                         {
3055                                 CString sFirstLine;
3056                                 m_ptBuf[0]->GetLine(0, sFirstLine);
3057                                 for (nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
3058                                 {
3059                                         bTyped[nBuffer] = GetView(0, nBuffer)->SetTextTypeByContent(sFirstLine);
3060                                 }
3061                         }
3062                 }
3063
3064                 if (syntaxHLEnabled)
3065                 {
3066                         CrystalLineParser::TextDefinition *enuType = CrystalLineParser::GetTextType(sext[paneTyped].c_str());
3067                         ForEachView([&bTyped, enuType](auto& pView) {
3068                                 if (!bTyped[pView->m_nThisPane])
3069                                         pView->SetTextType(enuType);
3070                         });
3071                 }
3072
3073                 int nNormalBuffer = 0;
3074                 for (nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
3075                 {
3076                         // set the frame window header
3077                         UpdateHeaderPath(nBuffer);
3078
3079                         ForEachView(nBuffer, [](auto& pView) { pView->DocumentsLoaded(); });
3080                         
3081                         if ((m_nBufferType[nBuffer] == BUFFERTYPE::NORMAL) ||
3082                             (m_nBufferType[nBuffer] == BUFFERTYPE::NORMAL_NAMED))
3083                         {
3084                                 nNormalBuffer++;
3085                         }
3086                         
3087                 }
3088
3089                 // Inform user that files are identical
3090                 // Don't show message if new buffers created
3091                 if (identical == IDENTLEVEL::ALL && nNormalBuffer > 0)
3092                 {
3093                         ShowRescanError(nRescanResult, identical);
3094                 }
3095
3096                 // Exit if files are identical should only work for the first
3097                 // comparison and must be disabled afterward.
3098                 theApp.m_bExitIfNoDiff = MergeCmdLineInfo::Disabled;
3099         }
3100         else
3101         {
3102                 // CMergeDoc::Rescan fails if files do not exist on both sides 
3103                 // or the really arcane case that the temp files couldn't be created, 
3104                 // which is too obscure to bother reporting if you can't write to 
3105                 // your temp directory, doing nothing is graceful enough for that).
3106                 ShowRescanError(nRescanResult, identical);
3107                 GetParentFrame()->DestroyWindow();
3108                 return false;
3109         }
3110
3111         // Force repaint of location pane to update it in case we had some warning
3112         // dialog visible and it got painted before files were loaded
3113         if (m_pView[0][0] != nullptr)
3114                 m_pView[0][0]->RepaintLocationPane();
3115
3116         return true;
3117 }
3118
3119 void CMergeDoc::MoveOnLoad(int nPane, int nLineIndex)
3120 {
3121         if (nPane < 0)
3122         {
3123                 nPane = GetOptionsMgr()->GetInt(OPT_ACTIVE_PANE);
3124                 if (nPane < 0 || nPane >= m_nBuffers)
3125                         nPane = 0;
3126         }
3127         if (nLineIndex == -1)
3128         {
3129                 // scroll to first diff
3130                 if (GetOptionsMgr()->GetBool(OPT_SCROLL_TO_FIRST) &&
3131                         m_diffList.HasSignificantDiffs())
3132                 {
3133                         int nDiff = m_diffList.FirstSignificantDiff();
3134                         if (nDiff != -1)
3135                                 m_pView[0][nPane]->SelectDiff(nDiff, true, false);
3136                         m_pView[0][nPane]->SetActivePane();
3137                         return;
3138                 }
3139         }
3140         m_pView[0][nPane]->GotoLine(nLineIndex < 0 ? 0 : nLineIndex, false, nPane);
3141 }
3142
3143 void CMergeDoc::ChangeFile(int nBuffer, const String& path, int nLineIndex)
3144 {
3145         if (!PromptAndSaveIfNeeded(true))
3146                 return;
3147
3148         FileLocation fileloc[3];
3149         String strDesc[3];
3150         bool bRO[3];
3151         for (int pane = 0; pane < m_nBuffers; pane++)
3152         {
3153                 bRO[pane] = m_ptBuf[pane]->GetReadOnly();
3154                 fileloc[pane].encoding.m_unicoding = m_ptBuf[pane]->getUnicoding();
3155                 fileloc[pane].encoding.m_codepage = m_ptBuf[pane]->getCodepage();
3156                 fileloc[pane].setPath(m_filePaths[pane]);
3157         }
3158         std::copy_n(m_strDesc, m_nBuffers, strDesc);
3159
3160         strDesc[nBuffer] = _T("");
3161         fileloc[nBuffer].setPath(path);
3162         fileloc[nBuffer].encoding = codepage_detect::Guess(path, GetOptionsMgr()->GetInt(OPT_CP_DETECT));
3163         
3164         if (OpenDocs(m_nBuffers, fileloc, bRO, strDesc))
3165                 MoveOnLoad(nBuffer, nLineIndex);
3166 }
3167
3168 /**
3169  * @brief Re-load a document.
3170  * This methods re-loads the file compare document. The re-loaded document is
3171  * one side of the file compare.
3172  * @param [in] index The document to re-load.
3173  * @return Open result code.
3174  */
3175 void CMergeDoc::RefreshOptions()
3176 {
3177         DIFFOPTIONS options = {0};
3178         
3179         m_bAutomaticRescan = GetOptionsMgr()->GetBool(OPT_AUTOMATIC_RESCAN);
3180
3181         m_diffWrapper.SetDetectMovedBlocks(GetOptionsMgr()->GetBool(OPT_CMP_MOVED_BLOCKS));
3182         Options::DiffOptions::Load(GetOptionsMgr(), options);
3183
3184         m_diffWrapper.SetOptions(&options);
3185
3186         // Refresh view options
3187         ForEachView([](auto& pView) { pView->RefreshOptions(); });
3188 }
3189
3190 /**
3191  * @brief Write path and filename to headerbar
3192  * @note SetText() does not repaint unchanged text
3193  */
3194 void CMergeDoc::UpdateHeaderPath(int pane)
3195 {
3196         CMergeEditFrame *pf = GetParentFrame();
3197         ASSERT(pf != nullptr);
3198         String sText;
3199         bool bChanges = false;
3200
3201         if (m_nBufferType[pane] == BUFFERTYPE::UNNAMED ||
3202                 m_nBufferType[pane] == BUFFERTYPE::NORMAL_NAMED)
3203         {
3204                 sText = m_strDesc[pane];
3205         }
3206         else
3207         {
3208                 sText = m_filePaths[pane];
3209                 if (m_pDirDoc != nullptr)
3210                 {
3211                         m_pDirDoc->ApplyDisplayRoot(pane, sText);
3212                 }
3213         }
3214         bChanges = m_ptBuf[pane]->IsModified();
3215
3216         if (bChanges)
3217                 sText.insert(0, _T("* "));
3218
3219         pf->GetHeaderInterface()->SetText(pane, sText);
3220
3221         SetTitle(nullptr);
3222 }
3223
3224 /**
3225  * @brief Paint differently the headerbar of the active view
3226  */
3227 void CMergeDoc::UpdateHeaderActivity(int pane, bool bActivate)
3228 {
3229         CMergeEditFrame *pf = GetParentFrame();
3230         ASSERT(pf != nullptr);
3231         pf->GetHeaderInterface()->SetActive(pane, bActivate);
3232 }
3233
3234 /**
3235  * @brief Set detect/not detect Moved Blocks
3236  */
3237 void CMergeDoc::SetDetectMovedBlocks(bool bDetectMovedBlocks)
3238 {
3239         if (bDetectMovedBlocks == m_diffWrapper.GetDetectMovedBlocks())
3240                 return;
3241
3242         GetOptionsMgr()->SaveOption(OPT_CMP_MOVED_BLOCKS, bDetectMovedBlocks);
3243         m_diffWrapper.SetDetectMovedBlocks(bDetectMovedBlocks);
3244         FlushAndRescan();
3245 }
3246
3247 /**
3248  * @brief Check if given buffer has mixed EOL style.
3249  * @param [in] nBuffer Buffer to check.
3250  * @return true if buffer's EOL style is mixed, false otherwise.
3251  */
3252 bool CMergeDoc::IsMixedEOL(int nBuffer) const
3253 {
3254         CDiffTextBuffer *pBuf = m_ptBuf[nBuffer].get();
3255         return pBuf->IsMixedEOL();
3256 }
3257
3258 void CMergeDoc::SetEditedAfterRescan(int nBuffer)
3259 {
3260         m_bEditAfterRescan[nBuffer] = true;
3261 }
3262
3263 bool CMergeDoc::IsEditedAfterRescan(int nBuffer) const
3264 {
3265         if (nBuffer >= 0 && nBuffer < m_nBuffers)
3266                 return m_bEditAfterRescan[nBuffer];
3267
3268         for (nBuffer = 0; nBuffer < m_nBuffers; ++nBuffer)
3269         {
3270                 if (m_bEditAfterRescan[nBuffer])
3271                         return true;
3272         }
3273
3274         return false;
3275 }
3276
3277 /**
3278  * @brief Update document filenames to title
3279  */
3280 void CMergeDoc::SetTitle(LPCTSTR lpszTitle)
3281 {
3282         String sTitle = (lpszTitle != nullptr) ? lpszTitle : CMergeFrameCommon::GetTitleString(m_filePaths, m_strDesc);
3283         CDocument::SetTitle(sTitle.c_str());
3284 }
3285
3286 /**
3287  * @brief Update any resources necessary after a GUI language change
3288  */
3289 void CMergeDoc::UpdateResources()
3290 {
3291         if (m_nBufferType[0] == BUFFERTYPE::UNNAMED)
3292                 m_strDesc[0] = _("Untitled left");
3293         if (m_nBufferType[m_nBuffers - 1] == BUFFERTYPE::UNNAMED)
3294                 m_strDesc[m_nBuffers - 1] = _("Untitled right");
3295         if (m_nBuffers == 3 && m_nBufferType[1] == BUFFERTYPE::UNNAMED)
3296                 m_strDesc[1] = _("Untitled middle");
3297         for (int nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
3298                 UpdateHeaderPath(nBuffer);
3299
3300         GetParentFrame()->UpdateResources();
3301         ForEachView([](auto& pView) { pView->UpdateResources(); });
3302 }
3303
3304 // Return current word breaking break type setting (whitespace only or include punctuation)
3305 bool CMergeDoc::GetBreakType() const
3306 {
3307         bool breakType = !!GetOptionsMgr()->GetInt(OPT_BREAK_TYPE);
3308         return breakType;
3309 }
3310
3311 // Return true to do line diff colors at the byte level (false to do them at word level)
3312 bool CMergeDoc::GetByteColoringOption() const
3313 {
3314         // color at byte level if 'break_on_words' option not set
3315         bool breakWords = GetOptionsMgr()->GetBool(OPT_BREAK_ON_WORDS);
3316         return !breakWords;
3317 }
3318
3319 /// Swap files and update views
3320 void CMergeDoc::SwapFiles(int nFromIndex, int nToIndex)
3321 {
3322         if ((nFromIndex >= 0 && nFromIndex < m_nBuffers) && (nToIndex >= 0 && nToIndex < m_nBuffers))
3323         {
3324                 // Swap views
3325                 for (int nGroup = 0; nGroup < m_nGroups; ++nGroup)
3326                 {
3327                         int nLeftViewId = m_pView[nGroup][nFromIndex]->GetDlgCtrlID();
3328                         int nRightViewId = m_pView[nGroup][nToIndex]->GetDlgCtrlID();
3329                         m_pView[nGroup][nFromIndex]->SetDlgCtrlID(nRightViewId);
3330                         m_pView[nGroup][nToIndex]->SetDlgCtrlID(nLeftViewId);
3331                 }
3332
3333
3334                 // Swap buffers and so on
3335                 std::swap(m_ptBuf[nFromIndex], m_ptBuf[nToIndex]);
3336                 for (int nGroup = 0; nGroup < m_nGroups; ++nGroup)
3337                         std::swap(m_pView[nGroup][nFromIndex], m_pView[nGroup][nToIndex]);
3338                 std::swap(m_pSaveFileInfo[nFromIndex], m_pSaveFileInfo[nToIndex]);
3339                 std::swap(m_pRescanFileInfo[nFromIndex], m_pRescanFileInfo[nToIndex]);
3340                 std::swap(m_nBufferType[nFromIndex], m_nBufferType[nToIndex]);
3341                 std::swap(m_bEditAfterRescan[nFromIndex], m_bEditAfterRescan[nToIndex]);
3342                 std::swap(m_strDesc[nFromIndex], m_strDesc[nToIndex]);
3343
3344                 m_filePaths.Swap(nFromIndex, nToIndex);
3345                 m_diffList.Swap(nFromIndex, nToIndex);
3346                 for (int nGroup = 0; nGroup < m_nGroups; nGroup++)
3347                         swap(m_pView[nGroup][nFromIndex]->m_piMergeEditStatus, m_pView[nGroup][nToIndex]->m_piMergeEditStatus);
3348
3349                 ClearWordDiffCache();
3350
3351                 for (int nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
3352                 {
3353                         m_ptBuf[nBuffer]->m_nThisPane = nBuffer;
3354                         for (int nGroup = 0; nGroup < m_nGroups; nGroup++)
3355                                 m_pView[nGroup][nBuffer]->m_nThisPane = nBuffer;
3356
3357                         // Update views
3358                         UpdateHeaderPath(nBuffer);
3359                 }
3360                 GetParentFrame()->UpdateSplitter();
3361                 ForEachView([](auto& pView) { pView->UpdateStatusbar(); });
3362
3363                 UpdateAllViews(nullptr);
3364         }
3365 }
3366
3367 /**
3368  * @brief Display unpacker dialog to user & handle user's choices
3369  */
3370 bool CMergeDoc::OpenWithUnpackerDialog()
3371 {
3372         // let the user choose a handler
3373         CSelectUnpackerDlg dlg(m_filePaths[0], nullptr);
3374         // create now a new infoUnpacker to initialize the manual/automatic flag
3375         PackingInfo infoUnpacker(PLUGIN_MODE::PLUGIN_AUTO);
3376         dlg.SetInitialInfoHandler(&infoUnpacker);
3377
3378         if (dlg.DoModal() == IDOK)
3379         {
3380                 infoUnpacker = dlg.GetInfoHandler();
3381                 Merge7zFormatMergePluginScope scope(&infoUnpacker);
3382                 if (HasZipSupport() && std::count_if(m_filePaths.begin(), m_filePaths.end(), ArchiveGuessFormat) == m_nBuffers)
3383                 {
3384                         DWORD dwFlags[3] = {FFILEOPEN_NOMRU, FFILEOPEN_NOMRU, FFILEOPEN_NOMRU};
3385                         GetMainFrame()->DoFileOpen(&m_filePaths, dwFlags, m_strDesc, _T(""), 
3386                                 GetOptionsMgr()->GetBool(OPT_CMP_INCLUDE_SUBDIRS), nullptr, _T(""), &infoUnpacker);
3387                         CloseNow();
3388                 }
3389                 else
3390                 {
3391                         SetUnpacker(&infoUnpacker);
3392                         OnFileReload();
3393                 }
3394                 return true;
3395         }
3396         else
3397         {
3398                 return false;
3399         }
3400 }
3401
3402 /**
3403  * @brief Reloads the opened files
3404  */
3405 void CMergeDoc::OnFileReload()
3406 {
3407         if (!PromptAndSaveIfNeeded(true))
3408                 return;
3409         
3410         FileLocation fileloc[3];
3411         bool bRO[3];
3412         for (int pane = 0; pane < m_nBuffers; pane++)
3413         {
3414                 bRO[pane] = m_ptBuf[pane]->GetReadOnly();
3415                 fileloc[pane].encoding.m_unicoding = m_ptBuf[pane]->getUnicoding();
3416                 fileloc[pane].encoding.m_codepage = m_ptBuf[pane]->getCodepage();
3417                 fileloc[pane].setPath(m_filePaths[pane]);
3418         }
3419         CPoint pt = GetActiveMergeView()->GetCursorPos();
3420         if (OpenDocs(m_nBuffers, fileloc, bRO, m_strDesc))
3421                 MoveOnLoad(GetActiveMergeView()->m_nThisPane, pt.y);
3422 }
3423
3424 /**
3425  * @brief Display encodings to user
3426  */
3427 void CMergeDoc::OnFileEncoding()
3428 {
3429         DoFileEncodingDialog();
3430 }
3431
3432 void CMergeDoc::OnCtxtOpenWithUnpacker() 
3433 {
3434         OpenWithUnpackerDialog();
3435 }
3436
3437 void CMergeDoc::OnBnClickedFileEncoding()
3438 {
3439         if (m_pEncodingErrorBar == nullptr || m_pView[0][0] == nullptr)
3440                 return;
3441         m_pView[0][0]->GetParentFrame()->ShowControlBar(m_pEncodingErrorBar.get(), FALSE, FALSE);
3442         DoFileEncodingDialog();
3443 }
3444
3445 void CMergeDoc::OnBnClickedPlugin()
3446 {
3447         if (m_pEncodingErrorBar == nullptr || m_pView[0][0] == nullptr)
3448                 return;
3449         m_pView[0][0]->GetParentFrame()->ShowControlBar(m_pEncodingErrorBar.get(), FALSE, FALSE);
3450         OpenWithUnpackerDialog();
3451 }
3452
3453 void CMergeDoc::OnBnClickedHexView()
3454 {
3455         OnFileRecompareAs(ID_MERGE_COMPARE_HEX);
3456 }
3457
3458 void CMergeDoc::OnOK()
3459 {
3460         if (m_pEncodingErrorBar == nullptr || m_pView[0][0] == nullptr)
3461                 return;
3462         m_pView[0][0]->GetParentFrame()->ShowControlBar(m_pEncodingErrorBar.get(), FALSE, FALSE);
3463 }
3464
3465 void CMergeDoc::OnFileRecompareAsText()
3466 {
3467         m_bEnableTableEditing = false;
3468         PackingInfo infoUnpacker;
3469         SetUnpacker(&infoUnpacker);
3470         OnFileReload();
3471 }
3472
3473 void CMergeDoc::OnUpdateFileRecompareAsText(CCmdUI *pCmdUI)
3474 {
3475         pCmdUI->Enable(m_pInfoUnpacker->m_PluginOrPredifferMode == PLUGIN_MODE::PLUGIN_BUILTIN_XML ||
3476                 m_ptBuf[0]->GetTableEditing());
3477 }
3478
3479 void CMergeDoc::OnFileRecompareAsTable()
3480 {
3481         m_bEnableTableEditing = true;
3482         PackingInfo infoUnpacker;
3483         SetUnpacker(&infoUnpacker);
3484         OnFileReload();
3485 }
3486
3487 void CMergeDoc::OnUpdateFileRecompareAsTable(CCmdUI *pCmdUI)
3488 {
3489         pCmdUI->Enable(!m_ptBuf[0]->GetTableEditing());
3490 }
3491
3492 void CMergeDoc::OnFileRecompareAsXML()
3493 {
3494         m_bEnableTableEditing = false;
3495         PackingInfo infoUnpacker(PLUGIN_MODE::PLUGIN_BUILTIN_XML);
3496         SetUnpacker(&infoUnpacker);
3497         OnFileReload();
3498 }
3499
3500 void CMergeDoc::OnUpdateFileRecompareAsXML(CCmdUI *pCmdUI)
3501 {
3502         pCmdUI->Enable(m_pInfoUnpacker->m_PluginOrPredifferMode != PLUGIN_MODE::PLUGIN_BUILTIN_XML);
3503 }
3504
3505 void CMergeDoc::OnFileRecompareAs(UINT nID)
3506 {
3507         if (!PromptAndSaveIfNeeded(true))
3508                 return;
3509         
3510         DWORD dwFlags[3] = { 0 };
3511         FileLocation fileloc[3];
3512         for (int pane = 0; pane < m_nBuffers; pane++)
3513         {
3514                 fileloc[pane].setPath(m_filePaths[pane]);
3515                 dwFlags[pane] |= FFILEOPEN_NOMRU | (m_ptBuf[pane]->GetReadOnly() ? FFILEOPEN_READONLY : 0);
3516         }
3517         if (m_pEncodingErrorBar!=nullptr && m_pEncodingErrorBar->IsWindowVisible())
3518                 m_pView[0][0]->GetParentFrame()->ShowControlBar(m_pEncodingErrorBar.get(), FALSE, FALSE);
3519         GetMainFrame()->ShowMergeDoc(nID, m_pDirDoc, m_nBuffers, fileloc, dwFlags, m_strDesc);
3520         GetParentFrame()->ShowWindow(SW_RESTORE);
3521         GetParentFrame()->DestroyWindow();
3522 }
3523
3524 // Return file extension either from file name 
3525 String CMergeDoc::GetFileExt(LPCTSTR sFileName, LPCTSTR sDescription) const
3526 {
3527         String sExt;
3528         paths::SplitFilename(sFileName, nullptr, nullptr, &sExt);
3529         return sExt;
3530 }
3531
3532 /**
3533  * @brief Generate report from file compare results.
3534  */
3535 bool CMergeDoc::GenerateReport(const String& sFileName) const
3536 {
3537         // calculate HTML font size
3538         LOGFONT lf;
3539         CDC dc;
3540         dc.CreateDC(_T("DISPLAY"), nullptr, nullptr, nullptr);
3541         m_pView[0][0]->GetFont(lf);
3542         int nFontSize = -MulDiv (lf.lfHeight, 72, dc.GetDeviceCaps (LOGPIXELSY));
3543
3544         // create HTML report
3545         UniStdioFile file;
3546         if (!file.Open(sFileName, _T("wt")))
3547         {
3548                 String errMsg = GetSysError(GetLastError());
3549                 String msg = strutils::format_string1(
3550                         _("Error creating the report:\n%1"), errMsg);
3551                 AfxMessageBox(msg.c_str(), MB_OK | MB_ICONSTOP);
3552                 return false;
3553         }
3554
3555         file.SetCodepage(ucr::CP_UTF_8);
3556
3557         CString headerText =
3558                 _T("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\n")
3559                 _T("\t\"http://www.w3.org/TR/html4/loose.dtd\">\n")
3560                 _T("<html>\n")
3561                 _T("<head>\n")
3562                 _T("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n")
3563                 _T("<title>WinMerge File Compare Report</title>\n")
3564                 _T("<style type=\"text/css\">\n")
3565                 _T("<!--\n")
3566                 _T("table {margin: 0; border: 1px solid #a0a0a0; box-shadow: 1px 1px 2px rgba(0, 0, 0, 0.15);}\n")
3567                 _T("td,th {word-break: break-all; font-size: %dpt;padding: 0 3px;}\n")
3568                 _T("tr { vertical-align: top; }\n")
3569                 _T(".title {color: white; background-color: blue; vertical-align: top; padding: 4px 4px; background: linear-gradient(mediumblue, darkblue);}\n")
3570                 _T("%s")
3571                 _T("-->\n")
3572                 _T("</style>\n")
3573                 _T("</head>\n")
3574                 _T("<body>\n")
3575                 _T("<table cellspacing=\"0\" cellpadding=\"0\" style=\"width:100%%;\">\n")
3576                 _T("<thead>\n")
3577                 _T("<tr>\n");
3578         String header = 
3579                 strutils::format((LPCTSTR)headerText, nFontSize, (LPCTSTR)m_pView[0][0]->GetHTMLStyles());
3580         file.WriteString(header);
3581
3582         // Get paths
3583         // If archive, use archive path + folder + filename inside archive
3584         // If desc text given, use it
3585         PathContext paths = m_filePaths;
3586         if (m_pDirDoc != nullptr && m_pDirDoc->IsArchiveFolders())
3587         {
3588                 for (int i = 0; i < paths.GetSize(); i++)
3589                         m_pDirDoc->ApplyDisplayRoot(i, paths[i]);
3590         }
3591         else
3592         {
3593                 for (int i = 0; i < paths.GetSize(); i++)
3594                 {
3595                         if (!m_strDesc[i].empty())
3596                                 paths[i] = m_strDesc[i];
3597                 }
3598         }
3599
3600         // titles
3601         int nBuffer;
3602         for (nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
3603         {
3604                 String data = strutils::format(_T("<th colspan=\"2\" class=\"title\" style=\"width:%f%%\">"),
3605                         (double)100 / m_nBuffers);
3606                 file.WriteString(data);
3607                 file.WriteString(ucr::toTString(CMarkdown::Entities(ucr::toUTF8(paths[nBuffer]))));
3608                 file.WriteString(_T("</th>\n"));
3609         }
3610         file.WriteString(
3611                 _T("</tr>\n")
3612                 _T("</thead>\n")
3613                 _T("<tbody>\n"));
3614
3615         // write the body of the report
3616         int idx[3] = {0};
3617         int nLineCount[3] = {0};
3618         int nDiff = 0;
3619         for (nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
3620                 nLineCount[nBuffer] = m_ptBuf[nBuffer]->GetLineCount();
3621
3622         for (;;)
3623         {
3624                 file.WriteString(_T("<tr>\n"));
3625                 for (nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
3626                 {
3627                         for (; idx[nBuffer] < nLineCount[nBuffer]; idx[nBuffer]++)
3628                         {
3629                                 if (m_pView[0][nBuffer]->GetLineVisible(idx[nBuffer]))
3630                                         break;
3631                         }
3632                                 
3633                         if (idx[nBuffer] < nLineCount[nBuffer])
3634                         {
3635                                 // line number
3636                                 int iVisibleLineNumber = 0;
3637                                 String tdtag = _T("<td class=\"ln\">");
3638                                 DWORD dwFlags = m_ptBuf[nBuffer]->GetLineFlags(idx[nBuffer]);
3639                                 if ((dwFlags & LF_GHOST) == 0 && m_pView[0][nBuffer]->GetViewLineNumbers())
3640                                 {
3641                                         iVisibleLineNumber = m_ptBuf[nBuffer]->ComputeRealLine(idx[nBuffer]) + 1;
3642                                 }
3643                                 if (nBuffer == 0 &&
3644                                         (dwFlags & (LF_DIFF | LF_GHOST)) != 0 && (idx[nBuffer] == 0 ||
3645                                         (m_ptBuf[nBuffer]->GetLineFlags(idx[nBuffer] - 1) & (LF_DIFF | LF_GHOST)) == 0))
3646                                 {
3647                                         ++nDiff;
3648                                         if (iVisibleLineNumber > 0)
3649                                         {
3650                                                 tdtag += strutils::format(_T("<a name=\"d%d\" href=\"#d%d\">%d</a>"), nDiff, nDiff, iVisibleLineNumber);
3651                                                 iVisibleLineNumber = 0;
3652                                         }
3653                                         else
3654                                                 tdtag += strutils::format(_T("<a name=\"d%d\" href=\"#d%d\">.</a>"), nDiff, nDiff);
3655                                 }
3656                                 if (iVisibleLineNumber > 0)
3657                                         tdtag += strutils::format(_T("%d</td>"), iVisibleLineNumber);
3658                                 else
3659                                         tdtag += _T("</td>");
3660                                 file.WriteString(tdtag);
3661                                 // line content
3662                                 file.WriteString((LPCTSTR)m_pView[0][nBuffer]->GetHTMLLine(idx[nBuffer], _T("td")));
3663                                 idx[nBuffer]++;
3664                         }
3665                         else
3666                                 file.WriteString(_T("<td class=\"ln\"></td><td></td>"));
3667                         file.WriteString(_T("\n"));
3668                 }
3669                 file.WriteString(_T("</tr>\n"));
3670
3671                 bool bBorderLine = false;
3672                 for (nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
3673                 {
3674                         if (idx[nBuffer] < nLineCount[nBuffer] && !m_pView[0][nBuffer]->GetLineVisible(idx[nBuffer]))
3675                                 bBorderLine = true;
3676                 }
3677
3678                 if (bBorderLine)
3679                 {
3680                         file.WriteString(_T("<tr height=1>"));
3681                         for (nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
3682                         {
3683                                 if (idx[nBuffer] < nLineCount[nBuffer] && !m_pView[0][nBuffer]->GetLineVisible(idx[nBuffer]))
3684                                         file.WriteString(_T("<td style=\"background-color: black\"></td><td style=\"background-color: black\"></td>"));
3685                                 else
3686                                         file.WriteString(_T("<td></td><td></td>"));
3687                         }
3688                         file.WriteString(_T("</tr>\n"));
3689                 }
3690
3691                 if (idx[0] >= nLineCount[0] && idx[1] >= nLineCount[1] && (m_nBuffers < 3 || idx[2] >= nLineCount[2]))
3692                         break;
3693         }
3694         file.WriteString(
3695                 _T("</tbody>\n")
3696                 _T("</table>\n")
3697                 _T("</body>\n")
3698                 _T("</html>\n"));
3699
3700         file.Close();
3701
3702         return true;
3703 }
3704
3705 /**
3706  * @brief Generate report from file compare results.
3707  */
3708 void CMergeDoc::OnToolsGenerateReport()
3709 {
3710         String s;
3711         CString folder;
3712
3713         if (!SelectFile(AfxGetMainWnd()->GetSafeHwnd(), s, false, folder, _T(""), _("HTML Files (*.htm,*.html)|*.htm;*.html|All Files (*.*)|*.*||"), _T("htm")))
3714                 return;
3715
3716         if (GenerateReport(s.c_str()))
3717                 LangMessageBox(IDS_REPORT_SUCCESS, MB_OK | MB_ICONINFORMATION);
3718 }
3719
3720 /**
3721  * @brief Generate patch from files selected.
3722  *
3723  * Creates a patch from selected files in active directory compare, or
3724  * active file compare. Files in file compare must be saved before
3725  * creating a patch.
3726  */
3727 void CMergeDoc::OnToolsGeneratePatch()
3728 {
3729         // If there are changes in files, tell user to save them first
3730         if (IsModified())
3731         {
3732                 LangMessageBox(IDS_SAVEFILES_FORPATCH, MB_ICONSTOP);
3733                 return;
3734         }
3735
3736         CPatchTool patcher;
3737         patcher.AddFiles(m_filePaths.GetLeft(),
3738                         m_filePaths.GetRight());
3739         patcher.CreatePatch();
3740 }
3741
3742 /**
3743  * @brief Add synchronization point
3744  */
3745 void CMergeDoc::AddSyncPoint()
3746 {
3747         int nLine[3];
3748         for (int nBuffer = 0; nBuffer < m_nBuffers; ++nBuffer)
3749         {
3750                 int tmp = m_pView[0][nBuffer]->GetCursorPos().y;
3751                 nLine[nBuffer] = m_ptBuf[nBuffer]->ComputeApparentLine(m_ptBuf[nBuffer]->ComputeRealLine(tmp));
3752         }
3753
3754         // If adding a sync point by selecting a ghost line that is after the last block, Cancel the process adding a sync point.
3755         for (int nBuffer = 0; nBuffer < m_nBuffers; ++nBuffer)
3756                 if (nLine[nBuffer] >= m_ptBuf[nBuffer]->GetLineCount())
3757                 {
3758                         LangMessageBox(IDS_SYNCPOINT_LASTBLOCK, MB_ICONSTOP);
3759                         return;
3760                 }
3761
3762         for (int nBuffer = 0; nBuffer < m_nBuffers; ++nBuffer)
3763                 if (m_ptBuf[nBuffer]->GetLineFlags(nLine[nBuffer]) & LF_INVALID_BREAKPOINT)
3764                         DeleteSyncPoint(nBuffer, nLine[nBuffer], false);
3765
3766         for (int nBuffer = 0; nBuffer < m_nBuffers; ++nBuffer)
3767                 m_ptBuf[nBuffer]->SetLineFlag(nLine[nBuffer], LF_INVALID_BREAKPOINT, true, false);
3768
3769         m_bHasSyncPoints = true;
3770
3771         ForEachView([](auto& pView) { pView->SetSelectionMargin(true); });
3772
3773         FlushAndRescan(true);
3774 }
3775
3776 /**
3777  * @brief Delete a synchronization point
3778  */
3779 bool CMergeDoc::DeleteSyncPoint(int pane, int nLine, bool bRescan)
3780 {
3781         const auto syncpoints = GetSyncPointList();     
3782         for (auto syncpnt : syncpoints)
3783         {
3784                 if (syncpnt[pane] == nLine)
3785                 {
3786                         for (int nBuffer = 0; nBuffer < m_nBuffers; ++nBuffer)
3787                                 m_ptBuf[nBuffer]->SetLineFlag(syncpnt[nBuffer], LF_INVALID_BREAKPOINT, false, false);
3788                 }
3789         }
3790
3791         if (syncpoints.size() == 1)
3792                 m_bHasSyncPoints = false;
3793
3794         if (bRescan)
3795                 FlushAndRescan(true);
3796         return true;
3797 }
3798
3799 /**
3800  * @brief Clear Synchronization points
3801  */
3802 void CMergeDoc::ClearSyncPoints()
3803 {
3804         if (!m_bHasSyncPoints)
3805                 return;
3806
3807         for (int nBuffer = 0; nBuffer < m_nBuffers; ++nBuffer)
3808         {
3809                 int nLineCount = m_ptBuf[nBuffer]->GetLineCount();
3810                 for (int nLine = 0; nLine < nLineCount; ++nLine)
3811                 {
3812                         if (m_ptBuf[nBuffer]->GetLineFlags(nLine) & LF_INVALID_BREAKPOINT)
3813                                 m_ptBuf[nBuffer]->SetLineFlag(nLine, LF_INVALID_BREAKPOINT, false, false);
3814                 }
3815         }
3816         
3817         m_bHasSyncPoints = false;
3818
3819         FlushAndRescan(true);
3820 }
3821
3822 std::vector<std::vector<int> > CMergeDoc::GetSyncPointList()
3823 {
3824         std::vector<std::vector<int> > list;
3825         if (!m_bHasSyncPoints)
3826                 return list;
3827         int idx[3] = {-1, -1, -1};
3828         std::vector<int> points(m_nBuffers);
3829         for (int nBuffer = 0; nBuffer < m_nBuffers; ++nBuffer)
3830                 points[nBuffer] = m_ptBuf[nBuffer]->GetLineCount() - 1;
3831         for (int nBuffer = 0; nBuffer < m_nBuffers; ++nBuffer)
3832         {
3833                 int nLineCount = m_ptBuf[nBuffer]->GetLineCount();
3834                 for (int nLine = 0; nLine < nLineCount; ++nLine)
3835                 {
3836                         if (m_ptBuf[nBuffer]->GetLineFlags(nLine) & LF_INVALID_BREAKPOINT)
3837                         {
3838                                 idx[nBuffer]++;
3839                                 if (static_cast<int>(list.size()) <= idx[nBuffer])
3840                                         list.push_back(points);
3841                                 list[idx[nBuffer]][nBuffer] = nLine;
3842                         }
3843                 }
3844         }
3845         return list;
3846 }
3847