1 /////////////////////////////////////////////////////////////////////////////
2 // WinMerge: an interactive diff/merge utility
3 // Copyright (C) 1997-2000 Thingamahoochie Software
5 // SPDX-License-Identifier: GPL-2.0-or-later
6 /////////////////////////////////////////////////////////////////////////////
10 * @brief Implementation file for CMergeDoc
17 #include <Poco/Timestamp.h>
18 #include "UnicodeString.h"
21 #include "DiffTextBuffer.h"
22 #include "Environment.h"
23 #include "MovedLines.h"
24 #include "MergeEditView.h"
25 #include "MergeEditFrm.h"
28 #include "FileTransform.h"
31 #include "OptionsDef.h"
32 #include "DiffFileInfo.h"
33 #include "SaveClosingDlg.h"
34 #include "OpenTableDlg.h"
37 #include "OptionsMgr.h"
38 #include "OptionsDiffOptions.h"
39 #include "MergeLineFlags.h"
40 #include "FileOrFolderSelect.h"
41 #include "LineFiltersList.h"
43 #include "codepage_detect.h"
44 #include "SelectUnpackerDlg.h"
45 #include "EncodingErrorBar.h"
46 #include "MergeCmdLineInfo.h"
48 #include "Constants.h"
49 #include "Merge7zFormatMergePluginImpl.h"
51 #include "PatchTool.h"
54 #include "stringdiffs.h"
62 /** @brief Max len of path in caption. */
63 static const UINT CAPTION_PATH_MAX = 50;
65 int CMergeDoc::m_nBuffersTemp = 2;
67 /** @brief EOL types */
68 static LPCTSTR crlfs[] =
70 _T ("\x0d\x0a"), // DOS/Windows style
71 _T ("\x0a"), // UNIX style
72 _T ("\x0d") // Macintosh style
75 static void SaveBuffForDiff(CDiffTextBuffer & buf, const String& filepath, int nStartLine = 0, int nLines = -1);
77 /////////////////////////////////////////////////////////////////////////////
80 IMPLEMENT_DYNCREATE(CMergeDoc, CDocument)
82 BEGIN_MESSAGE_MAP(CMergeDoc, CDocument)
83 //{{AFX_MSG_MAP(CMergeDoc)
84 ON_COMMAND(ID_FILE_SAVE, OnFileSave)
85 ON_COMMAND(ID_FILE_SAVE_LEFT, OnFileSaveLeft)
86 ON_COMMAND(ID_FILE_SAVE_MIDDLE, OnFileSaveMiddle)
87 ON_COMMAND(ID_FILE_SAVE_RIGHT, OnFileSaveRight)
88 ON_COMMAND(ID_FILE_SAVEAS_LEFT, OnFileSaveAsLeft)
89 ON_UPDATE_COMMAND_UI(ID_FILE_SAVEAS_MIDDLE, OnUpdateFileSaveAsMiddle)
90 ON_COMMAND(ID_FILE_SAVEAS_MIDDLE, OnFileSaveAsMiddle)
91 ON_COMMAND(ID_FILE_SAVEAS_RIGHT, OnFileSaveAsRight)
92 ON_UPDATE_COMMAND_UI(ID_STATUS_DIFFNUM, OnUpdateStatusNum)
93 ON_UPDATE_COMMAND_UI(ID_STATUS_PLUGIN, OnUpdatePluginName)
94 ON_COMMAND(ID_TOOLS_GENERATEREPORT, OnToolsGenerateReport)
95 ON_COMMAND(ID_TOOLS_GENERATEPATCH, OnToolsGeneratePatch)
96 ON_COMMAND(ID_RESCAN, OnFileReload)
97 ON_COMMAND(ID_FILE_ENCODING, OnFileEncoding)
98 ON_COMMAND_RANGE(ID_VIEW_DIFFCONTEXT_ALL, ID_VIEW_DIFFCONTEXT_TOGGLE, OnDiffContext)
99 ON_UPDATE_COMMAND_UI_RANGE(ID_VIEW_DIFFCONTEXT_ALL, ID_VIEW_DIFFCONTEXT_TOGGLE, OnUpdateDiffContext)
100 ON_COMMAND(ID_POPUP_OPEN_WITH_UNPACKER, OnCtxtOpenWithUnpacker)
101 ON_BN_CLICKED(IDC_FILEENCODING, OnBnClickedFileEncoding)
102 ON_BN_CLICKED(IDC_PLUGIN, OnBnClickedPlugin)
103 ON_BN_CLICKED(IDC_HEXVIEW, OnBnClickedHexView)
104 ON_COMMAND(IDOK, OnOK)
105 ON_COMMAND(ID_MERGE_COMPARE_TEXT, OnFileRecompareAsText)
106 ON_UPDATE_COMMAND_UI(ID_MERGE_COMPARE_TEXT, OnUpdateFileRecompareAsText)
107 ON_COMMAND(ID_MERGE_COMPARE_TABLE, OnFileRecompareAsTable)
108 ON_UPDATE_COMMAND_UI(ID_MERGE_COMPARE_TABLE, OnUpdateFileRecompareAsTable)
109 ON_COMMAND(ID_MERGE_COMPARE_XML, OnFileRecompareAsXML)
110 ON_UPDATE_COMMAND_UI(ID_MERGE_COMPARE_XML, OnUpdateFileRecompareAsXML)
111 ON_COMMAND_RANGE(ID_MERGE_COMPARE_HEX, ID_MERGE_COMPARE_IMAGE, OnFileRecompareAs)
115 /////////////////////////////////////////////////////////////////////////////
116 // CMergeDoc construction/destruction
119 * @brief Constructor.
121 CMergeDoc::CMergeDoc()
122 : m_bEnableRescan(true)
124 , m_CurWordDiff{ -1, static_cast<size_t>(-1), -1 }
127 , m_pInfoUnpacker(new PackingInfo)
128 , m_pEncodingErrorBar(nullptr)
129 , m_bHasSyncPoints(false)
130 , m_bAutoMerged(false)
134 DIFFOPTIONS options = {0};
136 m_nBuffers = m_nBuffersTemp;
137 m_filePaths.SetSize(m_nBuffers);
139 for (int nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
141 m_ptBuf[nBuffer].reset(new CDiffTextBuffer(this, nBuffer));
142 m_pSaveFileInfo[nBuffer].reset(new DiffFileInfo());
143 m_pRescanFileInfo[nBuffer].reset(new DiffFileInfo());
144 m_nBufferType[nBuffer] = BUFFER_NORMAL;
145 m_bEditAfterRescan[nBuffer] = false;
148 m_bEnableRescan = true;
149 // COleDateTime m_LastRescan
150 curUndo = undoTgt.begin();
151 m_nDiffContext = GetOptionsMgr()->GetInt(OPT_DIFF_CONTEXT);
153 m_diffWrapper.SetDetectMovedBlocks(GetOptionsMgr()->GetBool(OPT_CMP_MOVED_BLOCKS));
154 Options::DiffOptions::Load(GetOptionsMgr(), options);
156 m_diffWrapper.SetOptions(&options);
157 m_diffWrapper.SetPrediffer(nullptr);
163 * Informs associated dirdoc that mergedoc is closing.
165 CMergeDoc::~CMergeDoc()
167 if (m_pDirDoc != nullptr)
169 m_pDirDoc->MergeDocClosing(this);
175 * @brief Deleted data associated with doc before closing.
177 void CMergeDoc::DeleteContents ()
179 CDocument::DeleteContents ();
180 for (int nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
182 m_ptBuf[nBuffer]->FreeAll ();
183 m_tempFiles[nBuffer].Delete();
188 * @brief Called when new document is created.
190 * Initialises buffers.
192 BOOL CMergeDoc::OnNewDocument()
194 if (!CDocument::OnNewDocument())
197 SetTitle(_("File Comparison").c_str());
199 for (int nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
200 m_ptBuf[nBuffer]->InitNew ();
205 * @brief Return active merge edit view (or left one if neither active)
207 CMergeEditView * CMergeDoc::GetActiveMergeView()
209 CView * pActiveView = GetParentFrame()->GetActiveView();
210 CMergeEditView * pMergeEditView = dynamic_cast<CMergeEditView *>(pActiveView);
211 if (pMergeEditView == nullptr)
212 pMergeEditView = GetView(0, 0); // default to left view (in case some location or detail view active)
213 return pMergeEditView;
216 CMergeEditView * CMergeDoc::GetActiveMergeGroupView(int nBuffer)
218 return m_pView[GetActiveMergeView()->m_nThisGroup][nBuffer];
221 void CMergeDoc::SetUnpacker(const PackingInfo * infoNewHandler)
223 if (infoNewHandler != nullptr)
225 *m_pInfoUnpacker = *infoNewHandler;
229 void CMergeDoc::SetPrediffer(const PrediffingInfo * infoPrediffer)
231 m_diffWrapper.SetPrediffer(infoPrediffer);
233 void CMergeDoc::GetPrediffer(PrediffingInfo * infoPrediffer)
235 m_diffWrapper.GetPrediffer(infoPrediffer);
238 /////////////////////////////////////////////////////////////////////////////
239 // CMergeDoc serialization
241 void CMergeDoc::Serialize(CArchive& ar)
243 ASSERT(false); // we do not use CDocument serialization
246 /////////////////////////////////////////////////////////////////////////////
247 // CMergeDoc commands
250 * @brief Save an editor text buffer to a file for prediffing (make UCS-2LE if appropriate)
253 * original file is Ansi :
254 * buffer -> save as Ansi -> Ansi plugins -> diffutils
255 * original file is Unicode (UCS2-LE, UCS2-BE, UTF-8) :
256 * buffer -> save as UTF-8 -> Unicode plugins -> convert to UTF-8 -> diffutils
257 * (the plugins are optional, not the conversion)
258 * @todo Show SaveToFile() errors?
260 static void SaveBuffForDiff(CDiffTextBuffer & buf, const String& filepath, int nStartLine, int nLines)
262 // and we don't repack the file
263 PackingInfo * tempPacker = nullptr;
265 // write buffer out to temporary file
267 int retVal = buf.SaveToFile(filepath, true, sError, tempPacker,
268 CRLF_STYLE_AUTOMATIC, false, nStartLine, nLines);
272 * @brief Save files to temp files & compare again.
274 * @param bBinary [in,out] [in] If true, compare two binary files
275 * [out] If true binary file was detected.
276 * @param bIdentical [out] If true files were identical
277 * @param bForced [in] If true, suppressing is ignored and rescan
279 * @return Tells if rescan was successfully, was suppressed, or
281 * If this code is OK, Rescan has detached the views temporarily
282 * (positions of cursors have been lost)
283 * @note Rescan() ALWAYS compares temp files. Actual user files are not
284 * touched by Rescan().
285 * @sa CDiffWrapper::RunFileDiff()
287 int CMergeDoc::Rescan(bool &bBinary, IDENTLEVEL &identical,
288 bool bForced /* =false */)
290 DIFFOPTIONS diffOptions = {0};
291 DiffFileInfo fileInfo;
292 bool diffSuccess = false;
293 int nResult = RESCAN_OK;
294 FileChange FileChanged[3] = {FileNoChange, FileNoChange, FileNoChange};
299 if (!m_bEnableRescan)
300 return RESCAN_SUPPRESSED;
303 ClearWordDiffCache();
305 if (GetOptionsMgr()->GetBool(OPT_LINEFILTER_ENABLED))
307 m_diffWrapper.SetFilterList(theApp.m_pLineFilters->GetAsString());
311 m_diffWrapper.SetFilterList(_T(""));
313 if (GetView(0, 0)->m_CurSourceDef->type != 0)
314 m_diffWrapper.SetFilterCommentsSourceDef(GetView(0, 0)->m_CurSourceDef);
316 m_diffWrapper.SetFilterCommentsSourceDef(GetFileExt(m_filePaths[0].c_str(), m_strDesc[0].c_str()));
318 for (nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
320 // Check if files have been modified since last rescan
321 // Ignore checking in case of scratchpads (empty filenames)
322 if (!m_filePaths[nBuffer].empty())
324 FileChanged[nBuffer] = IsFileChangedOnDisk(m_filePaths[nBuffer].c_str(),
325 fileInfo, false, nBuffer);
328 m_LastRescan = COleDateTime::GetCurrentTime();
330 LPCTSTR tnames[] = {_T("t0_wmdoc"), _T("t1_wmdoc"), _T("t2_wmdoc")};
331 for (nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
333 if (FileChanged[nBuffer] == FileRemoved)
335 String msg = strutils::format_string1(_("The file\n%1\nhas disappeared. Please save a copy of the file to continue."), m_filePaths[nBuffer]);
336 ShowMessageBox(msg, MB_ICONWARNING);
337 bool bSaveResult = false;
338 bool ok = DoSaveAs(m_filePaths[nBuffer].c_str(), bSaveResult, nBuffer);
339 if (!ok || !bSaveResult)
341 return RESCAN_FILE_ERR;
345 String temp = m_tempFiles[nBuffer].GetPath();
347 temp = m_tempFiles[nBuffer].Create(tnames[nBuffer]);
349 return RESCAN_TEMP_ERR;
354 String tempPath = env::GetTemporaryPath();
356 // Set up DiffWrapper
357 m_diffWrapper.GetOptions(&diffOptions);
362 m_CurWordDiff = { -1, static_cast<size_t>(-1), -1 };
363 // Clear moved lines lists
364 if (m_diffWrapper.GetDetectMovedBlocks())
366 for (nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
367 m_diffWrapper.GetMovedLines(nBuffer)->Clear();
370 // Set paths for diffing and run diff
371 m_diffWrapper.EnablePlugins(GetOptionsMgr()->GetBool(OPT_PLUGINS_ENABLED));
373 m_diffWrapper.SetPaths(PathContext(m_tempFiles[0].GetPath(), m_tempFiles[1].GetPath()), true);
375 m_diffWrapper.SetPaths(PathContext(m_tempFiles[0].GetPath(), m_tempFiles[1].GetPath(), m_tempFiles[2].GetPath()), true);
376 m_diffWrapper.SetCompareFiles(m_filePaths);
380 if (!HasSyncPoints())
382 // Save text buffer to file
383 for (nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
385 m_ptBuf[nBuffer]->SetTempPath(tempPath);
386 SaveBuffForDiff(*m_ptBuf[nBuffer], m_tempFiles[nBuffer].GetPath());
389 m_diffWrapper.SetCreateDiffList(&m_diffList);
390 diffSuccess = m_diffWrapper.RunFileDiff();
393 m_diffWrapper.GetDiffStatus(&status);
394 if (bBinary) // believe caller if we were told these are binaries
395 status.bBinaries = true;
399 const std::vector<std::vector<int> > syncpoints = GetSyncPointList();
400 int nStartLine[3] = {0};
401 int nLines[3], nRealLine[3];
402 for (size_t i = 0; i <= syncpoints.size(); ++i)
404 // Save text buffer to file
405 for (nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
407 nLines[nBuffer] = (i >= syncpoints.size()) ? -1 : syncpoints[i][nBuffer] - nStartLine[nBuffer];
408 m_ptBuf[nBuffer]->SetTempPath(tempPath);
409 SaveBuffForDiff(*m_ptBuf[nBuffer], m_tempFiles[nBuffer].GetPath(),
410 nStartLine[nBuffer], nLines[nBuffer]);
414 m_diffWrapper.SetCreateDiffList(&templist);
415 diffSuccess = m_diffWrapper.RunFileDiff();
416 for (nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
417 nRealLine[nBuffer] = m_ptBuf[nBuffer]->ComputeRealLine(nStartLine[nBuffer]);
419 // Correct the comparison results made by diffutils if the first file separated by the sync point is an empty file.
420 if (i == 0 && templist.GetSize() > 0)
421 for (nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
422 if (nStartLine[nBuffer] == 0)
424 bool isEmptyFile = true;
425 for (int j = 0; j < nLines[nBuffer]; j++)
427 if (!(m_ptBuf[nBuffer]->GetLineFlags(nStartLine[nBuffer] + j) & LF_GHOST))
436 templist.GetDiff(0, di);
437 if (di.begin[nBuffer] == 0 && di.end[nBuffer] == 0)
439 di.end[nBuffer] = -1;
440 templist.SetDiff(0, di);
445 m_diffList.AppendDiffList(templist, nRealLine);
446 for (nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
447 nStartLine[nBuffer] += nLines[nBuffer];
450 DIFFSTATUS status_part;
451 m_diffWrapper.GetDiffStatus(&status_part);
452 if (bBinary) // believe caller if we were told these are binaries
453 status.bBinaries = true;
454 status.MergeStatus(status_part);
456 m_diffWrapper.SetCreateDiffList(&m_diffList);
459 // If one file has EOL before EOF and other not...
460 if (std::count(status.bMissingNL, status.bMissingNL + m_nBuffers, status.bMissingNL[0]) < m_nBuffers)
462 // ..last DIFFRANGE of file which has EOL must be
463 // fixed to contain last line too
464 int lineCount[3] = { 0,0,0 };
465 for (nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
466 lineCount[nBuffer] = m_ptBuf[nBuffer]->GetLineCount();
467 m_diffWrapper.FixLastDiffRange(m_nBuffers, lineCount, status.bMissingNL, diffOptions.bIgnoreBlankLines);
470 // set identical/diff result as recorded by diffutils
471 identical = status.Identical;
473 // Determine errors and binary file compares
475 nResult = RESCAN_FILE_ERR;
476 else if (status.bBinaries)
482 // Now update views and buffers for ghost lines
484 // Prevent displaying views during this update
485 // BTW, this solves the problem of double asserts
486 // (during the display of an assert message box, a second assert in one of the
487 // display functions happens, and hides the first assert)
488 ForEachView([](auto& pView) { pView->DetachFromBuffer(); });
490 // Remove blank lines and clear winmerge flags
491 // this operation does not change the modified flag
492 for (nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
493 m_ptBuf[nBuffer]->prepareForRescan();
495 // Divide diff blocks to match lines.
496 if (GetOptionsMgr()->GetBool(OPT_CMP_MATCH_SIMILAR_LINES) && m_nBuffers < 3)
499 // Analyse diff-list (updating real line-numbers)
500 // this operation does not change the modified flag
503 // Hide identical lines if diff-context is not 'All'
506 // Apply flags to lines that are trivial
507 PrediffingInfo infoPrediffer;
508 GetPrediffer(&infoPrediffer);
509 if (!infoPrediffer.m_PluginName.empty())
512 // Apply flags to lines that moved, to differentiate from appeared/disappeared lines
513 if (m_diffWrapper.GetDetectMovedBlocks())
516 // After PrimeTextBuffers() we know amount of real diffs
517 // (m_nDiffs) and trivial diffs (m_nTrivialDiffs)
519 // Identical files are also updated
520 if (!m_diffList.HasSignificantDiffs())
521 identical = IDENTLEVEL_ALL;
523 ForEachView([](auto& pView) {
524 // just apply some options to the views
525 pView->PrimeListWithFile();
526 // Now buffers data are valid
527 pView->ReAttachToBuffer();
529 for (nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
531 m_bEditAfterRescan[nBuffer] = false;
535 if (!GetOptionsMgr()->GetBool(OPT_CMP_IGNORE_CODEPAGE) &&
536 identical == IDENTLEVEL_ALL &&
537 std::any_of(m_ptBuf, m_ptBuf + m_nBuffers,
538 [&](std::unique_ptr<CDiffTextBuffer>& buf) { return buf->getEncoding() != m_ptBuf[0]->getEncoding(); }))
539 identical = IDENTLEVEL_NONE;
541 GetParentFrame()->SetLastCompareResult(identical != IDENTLEVEL_ALL ? 1 : 0);
546 void CMergeDoc::CheckFileChanged(void)
549 DiffFileInfo fileInfo;
550 FileChange FileChange[3];
552 for (nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
554 FileChange[nBuffer] = IsFileChangedOnDisk(m_filePaths[nBuffer].c_str(), fileInfo,
557 m_pRescanFileInfo[nBuffer]->Update((LPCTSTR)m_filePaths[nBuffer].c_str());
560 bool bDoReload = false;
561 for (nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
563 if (FileChange[nBuffer] == FileChanged)
565 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]);
566 if (ShowMessageBox(msg, MB_YESNO | MB_ICONWARNING | MB_DONT_ASK_AGAIN, IDS_FILECHANGED_RESCAN) == IDYES)
573 for (nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
575 if (FileChange[nBuffer] == FileChanged)
577 CPoint pt = GetView(0, nBuffer)->GetCursorPos();
578 ChangeFile(nBuffer, m_filePaths[nBuffer], pt.y);
584 /** @brief Apply flags to lines that are trivial */
585 void CMergeDoc::FlagTrivialLines(void)
587 for (int i = 0; i < m_ptBuf[0]->GetLineCount(); ++i)
589 if ((m_ptBuf[0]->GetLineFlags(i) & LF_NONTRIVIAL_DIFF) == 0)
592 for (int file = 0; file < m_nBuffers; ++file)
594 const TCHAR *p = m_ptBuf[file]->GetLineChars(i);
595 str[file] = p ? p : _T("");
598 if (std::count(str + 1, str + m_nBuffers, str[0]) != m_nBuffers - 1)
600 DIFFOPTIONS diffOptions = {0};
601 m_diffWrapper.GetOptions(&diffOptions);
603 // Make the call to stringdiffs, which does all the hard & tedious computations
604 std::vector<strdiff::wdiff> worddiffs = strdiff::ComputeWordDiffs(m_nBuffers, str,
605 !diffOptions.bIgnoreCase,
606 !diffOptions.bIgnoreEol,
607 diffOptions.nIgnoreWhitespace,
608 GetBreakType(), // whitespace only or include punctuation
609 GetByteColoringOption());
610 if (!worddiffs.empty())
612 for (int file = 0; file < m_nBuffers; ++file)
613 m_ptBuf[file]->SetLineFlag(i, LF_TRIVIAL, true, false, false);
620 /** @brief Adjust all different lines that were detected as actually matching moved lines */
621 void CMergeDoc::FlagMovedLines(void)
624 MovedLines *pMovedLines;
626 pMovedLines = m_diffWrapper.GetMovedLines(0);
627 for (i = 0; i < m_ptBuf[0]->GetLineCount(); ++i)
629 int j = pMovedLines->LineInBlock(i, MovedLines::SIDE_RIGHT);
632 TRACE(_T("%d->%d\n"), i, j);
634 // We only flag lines that are already marked as being different
635 int apparent = m_ptBuf[0]->ComputeApparentLine(i);
636 if (m_ptBuf[0]->FlagIsSet(apparent, LF_DIFF))
638 m_ptBuf[0]->SetLineFlag(apparent, LF_MOVED, true, false, false);
639 if (m_ptBuf[1]->FlagIsSet(apparent, LF_GHOST))
641 int apparentJ = m_ptBuf[1]->ComputeApparentLine(j);
642 if (m_ptBuf[0]->FlagIsSet(apparentJ, LF_GHOST))
643 m_ptBuf[1]->SetLineFlag(apparent, LF_MOVED, true, false, false);
649 pMovedLines = m_diffWrapper.GetMovedLines(1);
650 for (i=0; i<m_ptBuf[1]->GetLineCount(); ++i)
652 int j = pMovedLines->LineInBlock(i, MovedLines::SIDE_LEFT);
655 TRACE(_T("%d->%d\n"), i, j);
657 // We only flag lines that are already marked as being different
658 int apparent = m_ptBuf[1]->ComputeApparentLine(i);
659 if (m_ptBuf[1]->FlagIsSet(apparent, LF_DIFF))
661 m_ptBuf[1]->SetLineFlag(apparent, LF_MOVED, true, false, false);
662 if (m_ptBuf[0]->FlagIsSet(apparent, LF_GHOST))
664 int apparentJ = m_ptBuf[0]->ComputeApparentLine(j);
665 if (m_ptBuf[1]->FlagIsSet(apparentJ, LF_GHOST))
666 m_ptBuf[0]->SetLineFlag(apparent, LF_MOVED, true, false, false);
675 pMovedLines = m_diffWrapper.GetMovedLines(1);
676 for (i=0; i<m_ptBuf[1]->GetLineCount(); ++i)
678 int j = pMovedLines->LineInBlock(i, MovedLines::SIDE_RIGHT);
681 TRACE(_T("%d->%d\n"), i, j);
683 // We only flag lines that are already marked as being different
684 int apparent = m_ptBuf[1]->ComputeApparentLine(i);
685 if (m_ptBuf[1]->FlagIsSet(apparent, LF_DIFF))
687 m_ptBuf[1]->SetLineFlag(apparent, LF_MOVED, true, false, false);
688 if (m_ptBuf[2]->FlagIsSet(apparent, LF_GHOST))
690 int apparentJ = m_ptBuf[2]->ComputeApparentLine(j);
691 if (m_ptBuf[1]->FlagIsSet(apparentJ, LF_GHOST))
692 m_ptBuf[2]->SetLineFlag(apparent, LF_MOVED, true, false, false);
698 pMovedLines = m_diffWrapper.GetMovedLines(2);
699 for (i=0; i<m_ptBuf[2]->GetLineCount(); ++i)
701 int j = pMovedLines->LineInBlock(i, MovedLines::SIDE_LEFT);
704 TRACE(_T("%d->%d\n"), i, j);
706 // We only flag lines that are already marked as being different
707 int apparent = m_ptBuf[2]->ComputeApparentLine(i);
708 if (m_ptBuf[2]->FlagIsSet(apparent, LF_DIFF))
710 m_ptBuf[2]->SetLineFlag(apparent, LF_MOVED, true, false, false);
711 if (m_ptBuf[1]->FlagIsSet(apparent, LF_GHOST))
713 int apparentJ = m_ptBuf[1]->ComputeApparentLine(j);
714 if (m_ptBuf[2]->FlagIsSet(apparentJ, LF_GHOST))
715 m_ptBuf[1]->SetLineFlag(apparent, LF_MOVED, true, false, false);
721 // todo: Need to record actual moved information
724 int CMergeDoc::ShowMessageBox(const String& sText, unsigned nType, unsigned nIDHelp)
726 if (m_pView[0][0] && m_pView[0][0]->IsTextBufferInitialized() && !GetParentFrame()->IsActivated())
728 GetParentFrame()->InitialUpdateFrame(this, true);
729 GetParentFrame()->SendMessageToDescendants(WM_IDLEUPDATECMDUI, static_cast<WPARAM>(true), 0, true, true);
731 return AfxMessageBox(sText.c_str(), nType, nIDHelp);
735 * @brief Prints (error) message by rescan status.
737 * @param nRescanResult [in] Resultcocode from rescan().
738 * @param bIdentical [in] Were files identical?.
739 * @sa CMergeDoc::Rescan()
741 void CMergeDoc::ShowRescanError(int nRescanResult, IDENTLEVEL identical)
743 // Rescan was suppressed, there is no sensible status
744 if (nRescanResult == RESCAN_SUPPRESSED)
749 if (nRescanResult == RESCAN_FILE_ERR)
751 s = _("An error occurred while comparing the files.");
753 ShowMessageBox(s, MB_ICONSTOP);
757 if (nRescanResult == RESCAN_TEMP_ERR)
759 s = _("Temporary files could not be created. Check your temporary path settings.");
761 ShowMessageBox(s, MB_ICONSTOP);
765 // Files are not binaries, but they are identical
766 if (identical != IDENTLEVEL_NONE)
768 if (theApp.m_bExitIfNoDiff != MergeCmdLineInfo::ExitQuiet)
770 UINT nFlags = MB_ICONINFORMATION | MB_DONT_DISPLAY_AGAIN;
772 if (theApp.m_bExitIfNoDiff == MergeCmdLineInfo::Exit)
774 // Show the "files are identical" for basic "exit no diff" flag
775 // If user don't want to see the message one uses the quiet version
776 // of the "exit no diff".
777 nFlags &= ~MB_DONT_DISPLAY_AGAIN;
779 if ((m_nBuffers == 2 && !m_filePaths.GetLeft().empty() && !m_filePaths.GetRight().empty() &&
780 strutils::compare_nocase(m_filePaths.GetLeft(), m_filePaths.GetRight()) == 0) ||
781 (m_nBuffers == 3 && !m_filePaths.GetLeft().empty() && !m_filePaths.GetMiddle().empty() && !m_filePaths.GetRight().empty() &&
782 (strutils::compare_nocase(m_filePaths.GetLeft(), m_filePaths.GetRight()) == 0 ||
783 strutils::compare_nocase(m_filePaths.GetMiddle(), m_filePaths.GetRight()) == 0 ||
784 strutils::compare_nocase(m_filePaths.GetLeft(), m_filePaths.GetMiddle()) == 0)))
786 // compare file to itself, a custom message so user may hide the message in this case only
787 s = _("The same file is opened in both panels.");
788 ShowMessageBox(s, nFlags, IDS_FILE_TO_ITSELF);
790 else if (identical == IDENTLEVEL_ALL)
792 s = _("The selected files are identical.");
793 ShowMessageBox(s, nFlags, IDS_FILESSAME);
797 if (identical == IDENTLEVEL_ALL)
799 // Exit application if files are identical.
800 if (theApp.m_bExitIfNoDiff == MergeCmdLineInfo::Exit ||
801 theApp.m_bExitIfNoDiff == MergeCmdLineInfo::ExitQuiet)
803 AfxGetMainWnd()->PostMessage(WM_COMMAND, ID_APP_EXIT);
809 bool CMergeDoc::Undo()
815 * @brief An instance of RescanSuppress prevents rescan during its lifetime
816 * (or until its Clear method is called, which ends its effect).
821 explicit RescanSuppress(CMergeDoc & doc) : m_doc(doc)
824 m_bPrev = doc.m_bEnableRescan;
825 m_doc.m_bEnableRescan = false;
832 m_doc.m_bEnableRescan = m_bPrev;
846 * @brief Copy all diffs from one side to side.
847 * @param [in] srcPane Source side from which diff is copied
848 * @param [in] dstPane Destination side
850 void CMergeDoc::CopyAllList(int srcPane, int dstPane)
852 CopyMultipleList(srcPane, dstPane, 0, m_diffList.GetSize() - 1);
856 * @brief Copy range of diffs from one side to side.
857 * This function copies given range of differences from side to another.
858 * Ignored differences are skipped, and not copied.
859 * @param [in] srcPane Source side from which diff is copied
860 * @param [in] dstPane Destination side
861 * @param [in] firstDiff First diff copied (0-based index)
862 * @param [in] lastDiff Last diff copied (0-based index)
864 void CMergeDoc::CopyMultipleList(int srcPane, int dstPane, int firstDiff, int lastDiff, int firstWordDiff, int lastWordDiff)
867 if (firstDiff > lastDiff)
868 _RPTF0(_CRT_ERROR, "Invalid diff range (firstDiff > lastDiff)!");
870 _RPTF0(_CRT_ERROR, "Invalid diff range (firstDiff < 0)!");
871 if (lastDiff > m_diffList.GetSize() - 1)
872 _RPTF0(_CRT_ERROR, "Invalid diff range (lastDiff < diffcount)!");
875 lastDiff = min(m_diffList.GetSize() - 1, lastDiff);
876 firstDiff = max(0, firstDiff);
877 if (firstDiff > lastDiff)
880 RescanSuppress suppressRescan(*this);
882 // Note we don't care about m_nDiffs count to become zero,
883 // because we don't rescan() so it does not change
885 SetCurrentDiff(lastDiff);
887 bool bGroupWithPrevious = false;
888 if (firstWordDiff <= 0 && lastWordDiff == -1)
890 if (!ListCopy(srcPane, dstPane, -1, bGroupWithPrevious, true))
891 return; // sync failure
895 if (!WordListCopy(srcPane, dstPane, lastDiff,
896 (firstDiff == lastDiff) ? firstWordDiff : 0, lastWordDiff, nullptr, bGroupWithPrevious, true))
897 return; // sync failure
900 SetEditedAfterRescan(dstPane);
902 int nGroup = GetActiveMergeView()->m_nThisGroup;
903 CMergeEditView *pViewSrc = m_pView[nGroup][srcPane];
904 CMergeEditView *pViewDst = m_pView[nGroup][dstPane];
905 CPoint currentPosSrc = pViewSrc->GetCursorPos();
907 CPoint currentPosDst = pViewDst->GetCursorPos();
911 pViewDst->SetCursorPos(pt);
912 pViewDst->SetNewSelection(pt, pt, false);
913 pViewDst->SetNewAnchor(pt);
915 // copy from bottom up is more efficient
916 for (int i = lastDiff - 1; i >= firstDiff; --i)
918 if (m_diffList.IsDiffSignificant(i))
921 const DIFFRANGE *pdi = m_diffList.DiffRangeAt(i);
922 if (currentPosDst.y > pdi->dend)
924 if (pdi->blank[dstPane] >= 0)
925 currentPosDst.y -= pdi->dend - pdi->blank[dstPane] + 1;
926 else if (pdi->blank[srcPane] >= 0)
927 currentPosDst.y -= pdi->dend - pdi->blank[srcPane] + 1;
929 // Group merge with previous (merge undo data to one action)
930 bGroupWithPrevious = true;
931 if (i > firstDiff || firstWordDiff <= 0)
933 if (!ListCopy(srcPane, dstPane, -1, bGroupWithPrevious, false))
934 break; // sync failure
938 if (!WordListCopy(srcPane, dstPane, firstDiff, firstWordDiff, -1, nullptr, bGroupWithPrevious, false))
939 break; // sync failure
944 ForEachView(dstPane, [currentPosDst](auto& pView) {
945 pView->SetCursorPos(currentPosDst);
946 pView->SetNewSelection(currentPosDst, currentPosDst, false);
947 pView->SetNewAnchor(currentPosDst);
950 suppressRescan.Clear(); // done suppress Rescan
954 enum MergeResult { NoMergeNeeded, Merged, Conflict };
957 static std::pair<MergeResult, Type> DoMergeValue(Type left, Type middle, Type right, int dstPane)
959 bool equal_all = middle == left && middle == right && left == right;
961 return std::pair<MergeResult, Type>(NoMergeNeeded, left);
962 bool conflict = middle != left && middle != right && left != right;
964 return std::pair<MergeResult, Type>(Conflict, left);
969 return std::pair<MergeResult, Type>(Merged, middle);
973 return std::pair<MergeResult, Type>(Merged, right);
975 return std::pair<MergeResult, Type>(Merged, left);
979 return std::pair<MergeResult, Type>(Merged, middle);
982 return std::pair<MergeResult, Type>(NoMergeNeeded, left);
986 * @brief Do auto-merge.
987 * @param [in] dstPane Destination side
989 void CMergeDoc::DoAutoMerge(int dstPane)
991 const int lastDiff = m_diffList.GetSize() - 1;
992 const int firstDiff = 0;
993 bool bGroupWithPrevious = false;
994 int autoMergedCount = 0;
995 int unresolvedConflictCount = 0;
997 std::pair<MergeResult, FileTextEncoding> mergedEncoding =
998 DoMergeValue(m_ptBuf[0]->getEncoding(), m_ptBuf[1]->getEncoding(), m_ptBuf[2]->getEncoding(), dstPane);
999 if (mergedEncoding.first == Merged)
1001 ShowMessageBox(_("The change of codepage has been merged."), MB_ICONINFORMATION);
1002 m_ptBuf[dstPane]->setEncoding(mergedEncoding.second);
1004 else if (mergedEncoding.first == Conflict)
1005 ShowMessageBox(_("The changes of codepage are conflicting."), MB_ICONINFORMATION);
1007 std::pair<MergeResult, CRLFSTYLE> mergedEOLStyle =
1008 DoMergeValue(m_ptBuf[0]->GetCRLFMode(), m_ptBuf[1]->GetCRLFMode(), m_ptBuf[2]->GetCRLFMode(), dstPane);
1009 if (mergedEOLStyle.first == Merged)
1011 ShowMessageBox(_("The change of EOL has been merged."), MB_ICONINFORMATION);
1012 m_ptBuf[dstPane]->SetCRLFMode(mergedEOLStyle.second);
1014 else if (mergedEOLStyle.first == Conflict)
1015 ShowMessageBox(_("The changes of EOL are conflicting."), MB_ICONINFORMATION);
1017 RescanSuppress suppressRescan(*this);
1019 // Note we don't care about m_nDiffs count to become zero,
1020 // because we don't rescan() so it does not change
1022 SetCurrentDiff(lastDiff);
1024 SetEditedAfterRescan(dstPane);
1026 int nGroup = GetActiveMergeView()->m_nThisGroup;
1027 CMergeEditView *pViewDst = m_pView[nGroup][dstPane];
1028 CPoint currentPosDst = pViewDst->GetCursorPos();
1029 currentPosDst.x = 0;
1032 pViewDst->SetCursorPos(pt);
1033 pViewDst->SetNewSelection(pt, pt, false);
1034 pViewDst->SetNewAnchor(pt);
1036 // copy from bottom up is more efficient
1037 for (int i = lastDiff; i >= firstDiff; --i)
1039 const DIFFRANGE *pdi = m_diffList.DiffRangeAt(i);
1040 const int srcPane = m_diffList.GetMergeableSrcIndex(i, dstPane);
1044 if (currentPosDst.y > pdi->dend)
1046 if (pdi->blank[dstPane] >= 0)
1047 currentPosDst.y -= pdi->dend - pdi->blank[dstPane] + 1;
1048 else if (pdi->blank[srcPane] >= 0)
1049 currentPosDst.y -= pdi->dend - pdi->blank[srcPane] + 1;
1051 // Group merge with previous (merge undo data to one action)
1052 if (!ListCopy(srcPane, dstPane, -1, bGroupWithPrevious, false))
1053 break; // sync failure
1054 if (!bGroupWithPrevious)
1055 bGroupWithPrevious = true;
1058 if (pdi->op == OP_DIFF)
1059 ++unresolvedConflictCount;
1062 ForEachView(dstPane, [currentPosDst](auto& pView) {
1063 pView->SetCursorPos(currentPosDst);
1064 pView->SetNewSelection(currentPosDst, currentPosDst, false);
1065 pView->SetNewAnchor(currentPosDst);
1068 suppressRescan.Clear(); // done suppress Rescan
1070 UpdateHeaderPath(dstPane);
1072 if (autoMergedCount > 0)
1073 m_bAutoMerged = true;
1075 // move to first conflict
1076 const int nDiff = m_diffList.FirstSignificant3wayDiff(THREEWAYDIFFTYPE_CONFLICT);
1078 pViewDst->SelectDiff(nDiff, true, false);
1081 strutils::format_string2(
1082 _T("The number of automatically merged changes: %1\nThe number of unresolved conflicts: %2"),
1083 strutils::format(_T("%d"), autoMergedCount),
1084 strutils::format(_T("%d"), unresolvedConflictCount)),
1085 MB_ICONINFORMATION);
1089 * @brief Sanity check difference.
1091 * Checks that lines in difference are inside difference in both files.
1092 * If file is edited, lines added or removed diff lines get out of sync and
1093 * merging fails miserably.
1095 * @param [in] dr Difference to check.
1096 * @return true if difference lines match, false otherwise.
1098 bool CMergeDoc::SanityCheckDiff(DIFFRANGE dr) const
1100 const int cd_dbegin = dr.dbegin;
1101 const int cd_dend = dr.dend;
1103 for (int nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
1105 // Must ensure line number is in range before getting line flags
1106 if (cd_dend >= m_ptBuf[nBuffer]->GetLineCount())
1109 // Optimization - check last line first so we don't need to
1110 // check whole diff for obvious cases
1111 DWORD dwFlags = m_ptBuf[nBuffer]->GetLineFlags(cd_dend);
1112 if (!(dwFlags & LF_WINMERGE_FLAGS))
1116 for (int line = cd_dbegin; line < cd_dend; line++)
1118 for (int nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
1120 DWORD dwFlags = m_ptBuf[nBuffer]->GetLineFlags(cd_dend);
1121 if (!(dwFlags & LF_WINMERGE_FLAGS))
1129 * @brief Copy selected (=current) difference from from side to side.
1130 * @param [in] srcPane Source side from which diff is copied
1131 * @param [in] dstPane Destination side
1132 * @param [in] nDiff Diff to copy, if -1 function determines it.
1133 * @param [in] bGroupWithPrevious Adds diff to same undo group with
1134 * @return true if ok, false if sync failure & need to abort copy
1135 * previous action (allows one undo for copy all)
1137 bool CMergeDoc::ListCopy(int srcPane, int dstPane, int nDiff /* = -1*/,
1138 bool bGroupWithPrevious /*= false*/, bool bUpdateView /*= true*/)
1140 int nGroup = GetActiveMergeView()->m_nThisGroup;
1141 CMergeEditView *pViewSrc = m_pView[nGroup][srcPane];
1142 CMergeEditView *pViewDst = m_pView[nGroup][dstPane];
1143 CCrystalTextView *pSource = bUpdateView ? pViewDst : nullptr;
1145 // suppress Rescan during this method
1146 // (Not only do we not want to rescan a lot of times, but
1147 // it will wreck the line status array to rescan as we merge)
1148 RescanSuppress suppressRescan(*this);
1150 // If diff-number not given, determine it from active view
1153 nDiff = GetCurrentDiff();
1155 // No current diff, but maybe cursor is in diff?
1156 if (nDiff == -1 && (pViewSrc->IsCursorInDiff() ||
1157 pViewDst->IsCursorInDiff()))
1159 // Find out diff under cursor
1160 CPoint ptCursor = GetActiveMergeView()->GetCursorPos();
1161 nDiff = m_diffList.LineToDiff(ptCursor.y);
1168 VERIFY(m_diffList.GetDiff(nDiff, cd));
1169 CDiffTextBuffer& sbuf = *m_ptBuf[srcPane];
1170 CDiffTextBuffer& dbuf = *m_ptBuf[dstPane];
1171 bool bSrcWasMod = sbuf.IsModified();
1172 const int cd_dbegin = cd.dbegin;
1173 const int cd_dend = cd.dend;
1174 const int cd_blank = cd.blank[srcPane];
1175 bool bInSync = SanityCheckDiff(cd);
1179 LangMessageBox(IDS_VIEWS_OUTOFSYNC, MB_ICONSTOP);
1180 return false; // abort copying
1183 // If we remove whole diff from current view, we must fix cursor
1184 // position first. Normally we would move to end of previous line,
1185 // but we want to move to begin of that line for usability.
1188 CPoint currentPos = pViewDst->GetCursorPos();
1190 if (currentPos.y > cd_dend)
1192 if (cd.blank[dstPane] >= 0)
1193 currentPos.y -= cd_dend - cd.blank[dstPane] + 1;
1194 else if (cd.blank[srcPane] >= 0)
1195 currentPos.y -= cd_dend - cd.blank[srcPane] + 1;
1197 ForEachView(dstPane, [currentPos](auto& pView) { pView->SetCursorPos(currentPos); });
1200 // if the current diff contains missing lines, remove them from both sides
1201 int limit = cd_dend;
1203 // curView is the view which is changed, so the opposite of the source view
1204 dbuf.BeginUndoGroup(bGroupWithPrevious);
1207 // text was missing, so delete rest of lines on both sides
1208 // delete only on destination side since rescan will clear the other side
1209 if (cd_dend + 1 < dbuf.GetLineCount())
1211 dbuf.DeleteText(pSource, cd_blank, 0, cd_dend+1, 0, CE_ACTION_MERGE);
1215 // To removing EOL chars of last line, deletes from the end of the line (cd_blank - 1).
1216 ASSERT(cd_blank > 0);
1217 dbuf.DeleteText(pSource, cd_blank-1, dbuf.GetLineLength(cd_blank-1), cd_dend, dbuf.GetLineLength(cd_dend), CE_ACTION_MERGE);
1221 dbuf.FlushUndoGroup(pSource);
1222 dbuf.BeginUndoGroup(true);
1226 // copy the selected text over
1227 if (cd_dbegin <= limit)
1229 // text exists on left side, so just replace
1230 dbuf.ReplaceFullLines(dbuf, sbuf, pSource, cd_dbegin, limit, CE_ACTION_MERGE);
1231 dbuf.FlushUndoGroup(pSource);
1232 dbuf.BeginUndoGroup(true);
1234 dbuf.FlushUndoGroup(pSource);
1239 // reset the mod status of the source view because we do make some
1240 // changes, but none that concern the source text
1241 sbuf.SetModified(bSrcWasMod);
1244 suppressRescan.Clear(); // done suppress Rescan
1249 bool CMergeDoc::WordListCopy(int srcPane, int dstPane, int nDiff, int firstWordDiff, int lastWordDiff,
1250 const std::vector<int> *pWordDiffIndice, bool bGroupWithPrevious /*= false*/, bool bUpdateView /*= true*/)
1252 int nGroup = GetActiveMergeView()->m_nThisGroup;
1253 CMergeEditView *pViewSrc = m_pView[nGroup][srcPane];
1254 CMergeEditView *pViewDst = m_pView[nGroup][dstPane];
1255 CCrystalTextView *pSource = bUpdateView ? pViewDst : nullptr;
1257 // suppress Rescan during this method
1258 // (Not only do we not want to rescan a lot of times, but
1259 // it will wreck the line status array to rescan as we merge)
1260 RescanSuppress suppressRescan(*this);
1263 VERIFY(m_diffList.GetDiff(nDiff, cd));
1264 CDiffTextBuffer& sbuf = *m_ptBuf[srcPane];
1265 CDiffTextBuffer& dbuf = *m_ptBuf[dstPane];
1266 bool bSrcWasMod = sbuf.IsModified();
1267 const int cd_dbegin = cd.dbegin;
1268 const int cd_dend = cd.dend;
1269 const int cd_blank = cd.blank[srcPane];
1270 bool bInSync = SanityCheckDiff(cd);
1274 LangMessageBox(IDS_VIEWS_OUTOFSYNC, MB_ICONSTOP);
1275 return false; // abort copying
1278 std::vector<WordDiff> worddiffs = GetWordDiffArrayInDiffBlock(nDiff);
1280 if (worddiffs.empty())
1283 if (cd.end[srcPane] < cd.begin[srcPane])
1284 return ListCopy(srcPane, dstPane, nDiff, bGroupWithPrevious, bUpdateView);
1286 if (firstWordDiff == -1)
1288 if (lastWordDiff == -1)
1289 lastWordDiff = static_cast<int>(worddiffs.size() - 1);
1291 // If we remove whole diff from current view, we must fix cursor
1292 // position first. Normally we would move to end of previous line,
1293 // but we want to move to begin of that line for usability.
1296 CPoint currentPos = pViewDst->GetCursorPos();
1298 if (currentPos.y > cd_dend)
1300 if (cd.blank[dstPane] >= 0)
1301 currentPos.y -= cd_dend - cd.blank[dstPane] + 1;
1302 else if (cd.blank[srcPane] >= 0)
1303 currentPos.y -= cd_dend - cd.blank[srcPane] + 1;
1305 ForEachView(dstPane, [currentPos](auto& pView) { pView->SetCursorPos(currentPos); });
1308 // if the current diff contains missing lines, remove them from both sides
1309 int limit = cd_dend;
1311 // curView is the view which is changed, so the opposite of the source view
1312 dbuf.BeginUndoGroup(bGroupWithPrevious);
1314 CString srcText, dstText;
1315 CPoint ptDstStart, ptDstEnd;
1316 CPoint ptSrcStart, ptSrcEnd;
1318 ptDstStart.x = worddiffs[firstWordDiff].begin[dstPane];
1319 ptDstStart.y = worddiffs[firstWordDiff].beginline[dstPane];
1320 ptDstEnd.x = worddiffs[lastWordDiff].end[dstPane];
1321 ptDstEnd.y = worddiffs[lastWordDiff].endline[dstPane];
1322 ptSrcStart.x = worddiffs[firstWordDiff].begin[srcPane];
1323 ptSrcStart.y = worddiffs[firstWordDiff].beginline[srcPane];
1324 ptSrcEnd.x = worddiffs[lastWordDiff].end[srcPane];
1325 ptSrcEnd.y = worddiffs[lastWordDiff].endline[srcPane];
1327 std::vector<int> nDstOffsets(ptDstEnd.y - ptDstStart.y + 2);
1328 std::vector<int> nSrcOffsets(ptSrcEnd.y - ptSrcStart.y + 2);
1330 dbuf.GetTextWithoutEmptys(ptDstStart.y, ptDstStart.x, ptDstEnd.y, ptDstEnd.x, dstText);
1331 sbuf.GetTextWithoutEmptys(ptSrcStart.y, ptSrcStart.x, ptSrcEnd.y, ptSrcEnd.x, srcText);
1334 for (int nLine = ptDstStart.y; nLine <= ptDstEnd.y; nLine++)
1335 nDstOffsets[nLine-ptDstStart.y+1] = nDstOffsets[nLine-ptDstStart.y] + dbuf.GetFullLineLength(nLine);
1337 for (int nLine = ptSrcStart.y; nLine <= ptSrcEnd.y; nLine++)
1338 nSrcOffsets[nLine-ptSrcStart.y+1] = nSrcOffsets[nLine-ptSrcStart.y] + sbuf.GetFullLineLength(nLine);
1340 for (int i = lastWordDiff; i != firstWordDiff-1; --i)
1342 if (pWordDiffIndice && std::find(pWordDiffIndice->begin(), pWordDiffIndice->end(), i) == pWordDiffIndice->end())
1344 int srcBegin = nSrcOffsets[worddiffs[i].beginline[srcPane] - ptSrcStart.y] + worddiffs[i].begin[srcPane];
1345 int srcEnd = nSrcOffsets[worddiffs[i].endline[srcPane] - ptSrcStart.y] + worddiffs[i].end[srcPane];
1346 int dstBegin = nDstOffsets[worddiffs[i].beginline[dstPane] - ptDstStart.y] + worddiffs[i].begin[dstPane];
1347 int dstEnd = nDstOffsets[worddiffs[i].endline[dstPane] - ptDstStart.y] + worddiffs[i].end[dstPane];
1348 dstText = dstText.Mid(0, dstBegin - ptDstStart.x)
1349 + srcText.Mid(srcBegin - ptSrcStart.x, srcEnd - srcBegin)
1350 + dstText.Mid(dstEnd - ptDstStart.x);
1353 dbuf.DeleteText(pSource, ptDstStart.y, ptDstStart.x, ptDstEnd.y, ptDstEnd.x, CE_ACTION_MERGE);
1356 dbuf.InsertText(pSource, ptDstStart.y, ptDstStart.x, dstText, dstText.GetLength(), endl, endc, CE_ACTION_MERGE);
1358 dbuf.FlushUndoGroup(pSource);
1360 // reset the mod status of the source view because we do make some
1361 // changes, but none that concern the source text
1362 sbuf.SetModified(bSrcWasMod);
1364 suppressRescan.Clear(); // done suppress Rescan
1371 * @brief Save file with new filename.
1373 * This function is called by CMergeDoc::DoSave() or CMergeDoc::DoSAveAs()
1374 * to save file with new filename. CMergeDoc::DoSave() calls if saving with
1375 * normal filename fails, to let user choose another filename/location.
1376 * Also, if file is unnamed file (e.g. scratchpad) then it must be saved
1377 * using this function.
1378 * @param [in, out] strPath
1379 * - [in] : Initial path shown to user
1380 * - [out] : Path to new filename if saving succeeds
1381 * @param [in, out] nSaveResult
1382 * - [in] : Statuscode telling why we ended up here. Maybe the result of
1384 * - [out] : Statuscode of this saving try
1385 * @param [in, out] sError Error string from lower level saving code
1386 * @param [in] nBuffer Buffer we are saving
1387 * @return false as long as the user is not satisfied. Calling function
1388 * should not continue until true is returned.
1389 * @sa CMergeDoc::DoSave()
1390 * @sa CMergeDoc::DoSaveAs()
1391 * @sa CMergeDoc::CDiffTextBuffer::SaveToFile()
1393 bool CMergeDoc::TrySaveAs(String &strPath, int &nSaveResult, String & sError,
1394 int nBuffer, PackingInfo * pInfoTempUnpacker)
1398 String strSavePath; // New path for next saving try
1401 int answer = IDOK; // Set default we use for scratchpads
1403 // We shouldn't get here if saving is succeed before
1404 ASSERT(nSaveResult != SAVE_DONE);
1406 // Select message based on reason function called
1407 if (nSaveResult == SAVE_PACK_FAILED)
1409 if (m_nBuffers == 3)
1411 str = strutils::format_string2(
1413 _("Plugin '%2' cannot pack your changes to the left file back into '%1'.\n\nThe original file will not be changed.\n\nDo you want to save the unpacked version to another file?")
1415 _("Plugin '%2' cannot pack your changes to the middle file back into '%1'.\n\nThe original file will not be changed.\n\nDo you want to save the unpacked version to another file?"):
1416 _("Plugin '%2' cannot pack your changes to the right file back into '%1'.\n\nThe original file will not be changed.\n\nDo you want to save the unpacked version to another file?")),
1417 strPath, pInfoTempUnpacker->m_PluginName);
1421 str = strutils::format_string2(nBuffer == 0 ? _("Plugin '%2' cannot pack your changes to the left file back into '%1'.\n\nThe original file will not be changed.\n\nDo you want to save the unpacked version to another file?") :
1422 _("Plugin '%2' cannot pack your changes to the right file back into '%1'.\n\nThe original file will not be changed.\n\nDo you want to save the unpacked version to another file?"),
1423 strPath, pInfoTempUnpacker->m_PluginName);
1425 // replace the unpacker with a "do nothing" unpacker
1426 pInfoTempUnpacker->Initialize(PLUGIN_MANUAL);
1430 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);
1433 // SAVE_NO_FILENAME is temporarily used for scratchpad.
1434 // So don't ask about saving in that case.
1435 if (nSaveResult != SAVE_NO_FILENAME)
1436 answer = ShowMessageBox(str, MB_OKCANCEL | MB_ICONWARNING);
1442 title = _("Save Left File As");
1443 else if (nBuffer == m_nBuffers - 1)
1444 title = _("Save Right File As");
1446 title = _("Save Middle File As");
1448 if (SelectFile(GetActiveMergeView()->GetSafeHwnd(), s, false, strPath.c_str(), title))
1450 CDiffTextBuffer *pBuffer = m_ptBuf[nBuffer].get();
1452 nSaveResult = pBuffer->SaveToFile(strSavePath, false, sError,
1455 if (nSaveResult == SAVE_DONE)
1457 // We are saving scratchpad (unnamed file)
1458 if (strPath.empty())
1460 m_nBufferType[nBuffer] = BUFFER_UNNAMED_SAVED;
1461 m_strDesc[nBuffer].erase();
1464 strPath = strSavePath;
1465 UpdateHeaderPath(nBuffer);
1471 nSaveResult = SAVE_CANCELLED;
1475 nSaveResult = SAVE_CANCELLED;
1482 * @brief Save file creating backups etc.
1484 * Safe top-level file saving function. Checks validity of given path.
1485 * Creates backup file if wanted to. And if saving to given path fails,
1486 * allows user to select new location/name for file.
1487 * @param [in] szPath Path where to save including filename. Can be
1488 * empty/`nullptr` if new file is created (scratchpad) without filename.
1489 * @param [out] bSaveSuccess Will contain information about save success with
1490 * the original name (to determine if file statuses should be changed)
1491 * @param [in] nBuffer Index (0-based) of buffer to save
1492 * @return Tells if caller can continue (no errors happened)
1493 * @note Return value does not tell if SAVING succeeded. Caller must
1494 * Check value of bSaveSuccess parameter after calling this function!
1495 * @note If CMainFrame::m_strSaveAsPath is non-empty, file is saved
1496 * to directory it points to. If m_strSaveAsPath contains filename,
1497 * that filename is used.
1498 * @sa CMergeDoc::TrySaveAs()
1499 * @sa CMainFrame::CheckSavePath()
1500 * @sa CMergeDoc::CDiffTextBuffer::SaveToFile()
1502 bool CMergeDoc::DoSave(LPCTSTR szPath, bool &bSaveSuccess, int nBuffer)
1504 DiffFileInfo fileInfo;
1505 String strSavePath(szPath);
1506 FileChange fileChanged;
1507 bool bApplyToAll = false;
1510 fileChanged = IsFileChangedOnDisk(szPath, fileInfo, true, nBuffer);
1511 if (fileChanged == FileChanged)
1513 String msg = strutils::format_string1(_("Another application has updated file\n%1\nsince WinMerge loaded it.\n\nOverwrite changed file?"), szPath);
1514 if (ShowMessageBox(msg, MB_ICONWARNING | MB_YESNO) == IDNO)
1516 bSaveSuccess = true;
1521 // use a temp packer
1522 // first copy the m_pInfoUnpacker
1523 // if an error arises during packing, change and take a "do nothing" packer
1524 PackingInfo infoTempUnpacker = *m_pInfoUnpacker;
1526 bSaveSuccess = false;
1528 // Check third arg possibly given from command-line
1529 if (!theApp.m_strSaveAsPath.empty())
1531 if (paths::DoesPathExist(theApp.m_strSaveAsPath) == paths::IS_EXISTING_DIR)
1533 // third arg was a directory, so get append the filename
1535 paths::SplitFilename(szPath, 0, &sname, 0);
1536 strSavePath = theApp.m_strSaveAsPath;
1537 strSavePath = paths::ConcatPath(strSavePath, sname);
1540 strSavePath = theApp.m_strSaveAsPath;
1543 nRetVal = theApp.HandleReadonlySave(strSavePath, false, bApplyToAll);
1544 if (nRetVal == IDCANCEL)
1547 if (!theApp.CreateBackup(false, strSavePath))
1550 // false as long as the user is not satisfied
1551 // true if saving succeeds, even with another filename, or if the user cancels
1552 bool result = false;
1553 // the error code from the latest save operation,
1554 // or SAVE_DONE when the save succeeds
1555 // TODO: Shall we return this code in addition to bSaveSuccess ?
1556 int nSaveErrorCode = SAVE_DONE;
1557 CDiffTextBuffer *pBuffer = m_ptBuf[nBuffer].get();
1559 // Assume empty filename means Scratchpad (unnamed file)
1560 // Todo: This is not needed? - buffer type check should be enough
1561 if (strSavePath.empty())
1562 nSaveErrorCode = SAVE_NO_FILENAME;
1564 // Handle unnamed buffers
1565 if (m_nBufferType[nBuffer] == BUFFER_UNNAMED)
1566 nSaveErrorCode = SAVE_NO_FILENAME;
1569 if (nSaveErrorCode == SAVE_DONE)
1570 // We have a filename, just try to save
1571 nSaveErrorCode = pBuffer->SaveToFile(strSavePath, false, sError, &infoTempUnpacker);
1573 if (nSaveErrorCode != SAVE_DONE)
1575 // Saving failed, user may save to another location if wants to
1577 result = TrySaveAs(strSavePath, nSaveErrorCode, sError, nBuffer, &infoTempUnpacker);
1581 // Saving succeeded with given/selected filename
1582 if (nSaveErrorCode == SAVE_DONE)
1584 // Preserve file times if user wants to
1585 if (GetOptionsMgr()->GetBool(OPT_PRESERVE_FILETIMES))
1587 fileInfo.SetFile(strSavePath);
1590 TFile file(strSavePath);
1591 file.setLastModified(fileInfo.mtime);
1598 m_ptBuf[nBuffer]->SetModified(false);
1599 m_pSaveFileInfo[nBuffer]->Update(strSavePath.c_str());
1600 m_filePaths[nBuffer] = strSavePath;
1601 m_pRescanFileInfo[nBuffer]->Update(m_filePaths[nBuffer].c_str());
1602 UpdateHeaderPath(nBuffer);
1603 bSaveSuccess = true;
1606 else if (nSaveErrorCode == SAVE_CANCELLED)
1608 // User cancelled current operation, lets do what user wanted to do
1615 * @brief Save file with different filename.
1617 * Safe top-level file saving function. Asks user to select filename
1618 * and path. Does not create backups.
1619 * @param [in] szPath Path where to save including filename. Can be
1620 * empty/`nullptr` if new file is created (scratchpad) without filename.
1621 * @param [out] bSaveSuccess Will contain information about save success with
1622 * the original name (to determine if file statuses should be changed)
1623 * @param [in] nBuffer Index (0-based) of buffer to save
1624 * @return Tells if caller can continue (no errors happened)
1625 * @note Return value does not tell if SAVING succeeded. Caller must
1626 * Check value of bSaveSuccess parameter after calling this function!
1627 * @sa CMergeDoc::TrySaveAs()
1628 * @sa CMainFrame::CheckSavePath()
1629 * @sa CMergeDoc::CDiffTextBuffer::SaveToFile()
1631 bool CMergeDoc::DoSaveAs(LPCTSTR szPath, bool &bSaveSuccess, int nBuffer)
1633 String strSavePath(szPath);
1635 // use a temp packer
1636 // first copy the m_pInfoUnpacker
1637 // if an error arises during packing, change and take a "do nothing" packer
1638 PackingInfo infoTempUnpacker = *m_pInfoUnpacker;
1640 bSaveSuccess = false;
1641 // false as long as the user is not satisfied
1642 // true if saving succeeds, even with another filename, or if the user cancels
1643 bool result = false;
1644 // the error code from the latest save operation,
1645 // or SAVE_DONE when the save succeeds
1646 // TODO: Shall we return this code in addition to bSaveSuccess ?
1647 int nSaveErrorCode = SAVE_DONE;
1649 // Use SAVE_NO_FILENAME to prevent asking about error
1650 nSaveErrorCode = SAVE_NO_FILENAME;
1652 // Loop until user succeeds saving or cancels
1655 result = TrySaveAs(strSavePath, nSaveErrorCode, sError, nBuffer, &infoTempUnpacker);
1658 // Saving succeeded with given/selected filename
1659 if (nSaveErrorCode == SAVE_DONE)
1661 m_pSaveFileInfo[nBuffer]->Update(strSavePath);
1662 m_filePaths[nBuffer] = strSavePath;
1663 m_pRescanFileInfo[nBuffer]->Update(m_filePaths[nBuffer]);
1664 UpdateHeaderPath(nBuffer);
1665 bSaveSuccess = true;
1672 * @brief Get left->right info for a moved line (apparent line number)
1674 int CMergeDoc::RightLineInMovedBlock(int nBuffer, int apparentLeftLine)
1676 if (!(m_ptBuf[nBuffer]->GetLineFlags(apparentLeftLine) & LF_MOVED))
1679 int realLeftLine = m_ptBuf[nBuffer]->ComputeRealLine(apparentLeftLine);
1680 int realRightLine = -1;
1681 if (m_diffWrapper.GetDetectMovedBlocks())
1683 realRightLine = m_diffWrapper.GetMovedLines(nBuffer)->LineInBlock(realLeftLine,
1684 MovedLines::SIDE_RIGHT);
1686 if (realRightLine != -1)
1687 return m_ptBuf[nBuffer + 1]->ComputeApparentLine(realRightLine);
1693 * @brief Get right->left info for a moved line (apparent line number)
1695 int CMergeDoc::LeftLineInMovedBlock(int nBuffer, int apparentRightLine)
1697 if (!(m_ptBuf[nBuffer]->GetLineFlags(apparentRightLine) & LF_MOVED))
1700 int realRightLine = m_ptBuf[nBuffer]->ComputeRealLine(apparentRightLine);
1701 int realLeftLine = -1;
1702 if (m_diffWrapper.GetDetectMovedBlocks())
1704 realLeftLine = m_diffWrapper.GetMovedLines(nBuffer)->LineInBlock(realRightLine,
1705 MovedLines::SIDE_LEFT);
1707 if (realLeftLine != -1)
1708 return m_ptBuf[nBuffer - 1]->ComputeApparentLine(realLeftLine);
1714 * @brief Save modified documents.
1715 * This function asks if user wants to save modified documents. We also
1716 * allow user to cancel the closing.
1718 * There is a special trick avoiding showing two save-dialogs, as MFC framework
1719 * sometimes calls this function twice. We use static counter for these calls
1720 * and if we already have saving in progress (counter == 1) we skip the new
1723 * @return true if docs are closed, false if closing is cancelled.
1725 BOOL CMergeDoc::SaveModified()
1732 if (PromptAndSaveIfNeeded(true))
1745 * @brief Sets the current difference.
1746 * @param [in] nDiff Difference to set as current difference.
1748 void CMergeDoc::SetCurrentDiff(int nDiff)
1750 if (nDiff >= 0 && nDiff <= m_diffList.LastSignificantDiff())
1757 * @brief Take care of rescanning document.
1759 * Update view and restore cursor and scroll position after
1760 * rescanning document.
1761 * @param [in] bForced If true rescan cannot be suppressed
1763 void CMergeDoc::FlushAndRescan(bool bForced /* =false */)
1765 // Ignore suppressing when forced rescan
1767 if (!m_bEnableRescan) return;
1769 CWaitCursor waitstatus;
1771 CMergeEditView *pActiveView = GetActiveMergeView();
1773 // store cursors and hide caret
1774 ForEachView([](auto& pView) { pView->PushCursors(); });
1775 pActiveView->HideCursor();
1777 bool bBinary = false;
1778 IDENTLEVEL identical = IDENTLEVEL_NONE;
1779 int nRescanResult = Rescan(bBinary, identical, bForced);
1781 // restore cursors and caret
1782 ForEachView([](auto& pView) { pView->PopCursors(); });
1783 pActiveView->ShowCursor();
1785 ForEachView(pActiveView->m_nThisPane, [](auto& pView) {
1786 // because of ghostlines, m_nTopLine may differ just after Rescan
1787 // scroll both views to the same top line
1788 pView->UpdateSiblingScrollPos(false);
1790 // make sure we see the cursor from the curent view
1791 pView->EnsureVisible(pView->GetCursorPos());
1795 UpdateAllViews(nullptr);
1797 // Show possible error after updating screen
1798 if (nRescanResult != RESCAN_SUPPRESSED)
1799 ShowRescanError(nRescanResult, identical);
1800 m_LastRescan = COleDateTime::GetCurrentTime();
1804 * @brief Saves both files
1806 void CMergeDoc::OnFileSave()
1808 // We will need to know if either of the originals actually changed
1809 // so we know whether to update the diff status
1810 bool bChangedOriginal = false;
1812 for (int nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
1814 if (m_ptBuf[nBuffer]->IsModified() && !m_ptBuf[nBuffer]->GetReadOnly())
1816 // (why we don't use return value of DoSave)
1817 // DoSave will return true if it wrote to something successfully
1818 // but we have to know if it overwrote the original file
1819 bool bSaveOriginal = false;
1820 DoSave(m_filePaths[nBuffer].c_str(), bSaveOriginal, nBuffer );
1822 bChangedOriginal = true;
1826 // If either of the actual source files being compared was changed
1827 // we need to update status in the dir view
1828 if (bChangedOriginal)
1830 // If DirDoc contains diffs
1831 if (m_pDirDoc != nullptr && m_pDirDoc->HasDiffs())
1833 for (int nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
1835 if (m_bEditAfterRescan[nBuffer])
1837 FlushAndRescan(false);
1842 bool bIdentical = !m_diffList.HasSignificantDiffs(); // True if status should be set to identical
1843 m_pDirDoc->UpdateChangedItem(m_filePaths, m_diffList.GetSignificantDiffs(),
1844 m_nTrivialDiffs, bIdentical);
1849 void CMergeDoc::DoFileSave(int nBuffer)
1851 bool bSaveSuccess = false;
1852 bool bModified = false;
1854 if (m_ptBuf[nBuffer]->IsModified() && !m_ptBuf[nBuffer]->GetReadOnly())
1857 DoSave(m_filePaths[nBuffer].c_str(), bSaveSuccess, nBuffer );
1860 // If file were modified and saving succeeded,
1861 // update status on dir view
1862 if (bModified && bSaveSuccess)
1864 // If DirDoc contains compare results
1865 if (m_pDirDoc != nullptr && m_pDirDoc->HasDiffs())
1867 for (int nBuffer1 = 0; nBuffer1 < m_nBuffers; nBuffer1++)
1869 if (m_bEditAfterRescan[nBuffer1])
1871 FlushAndRescan(false);
1876 bool bIdentical = !m_diffList.HasSignificantDiffs(); // True if status should be set to identical
1877 m_pDirDoc->UpdateChangedItem(m_filePaths, m_diffList.GetSignificantDiffs(),
1878 m_nTrivialDiffs, bIdentical);
1884 * @brief Saves left-side file
1886 void CMergeDoc::OnFileSaveLeft()
1892 * @brief Saves middle-side file
1894 void CMergeDoc::OnFileSaveMiddle()
1900 * @brief Saves right-side file
1902 void CMergeDoc::OnFileSaveRight()
1904 DoFileSave(m_nBuffers - 1);
1908 * @brief Saves left-side file with name asked
1910 void CMergeDoc::OnFileSaveAsLeft()
1912 bool bSaveResult = false;
1913 DoSaveAs(m_filePaths.GetLeft().c_str(), bSaveResult, 0);
1917 * @brief Called when "Save middle (as...)" item is updated
1919 void CMergeDoc::OnUpdateFileSaveAsMiddle(CCmdUI* pCmdUI)
1921 pCmdUI->Enable(m_nBuffers == 3);
1925 * @brief Saves right-side file with name asked
1927 void CMergeDoc::OnFileSaveAsMiddle()
1929 bool bSaveResult = false;
1930 DoSaveAs(m_filePaths.GetMiddle().c_str(), bSaveResult, 1);
1934 * @brief Saves right-side file with name asked
1936 void CMergeDoc::OnFileSaveAsRight()
1938 bool bSaveResult = false;
1939 DoSaveAs(m_filePaths.GetRight().c_str(), bSaveResult, m_nBuffers - 1);
1943 * @brief Update diff-number pane text in file compare.
1944 * The diff number pane shows selected difference/amount of differences when
1945 * there is difference selected. If there is no difference selected, then
1946 * the panel shows amount of differences. If there are ignored differences,
1947 * those are not count into numbers.
1948 * @param [in] pCmdUI UI component to update.
1950 void CMergeDoc::OnUpdateStatusNum(CCmdUI* pCmdUI)
1952 TCHAR sIdx[32] = { 0 };
1953 TCHAR sCnt[32] = { 0 };
1955 const int nDiffs = m_diffList.GetSignificantDiffs();
1957 // Files are identical - show text "Identical"
1961 // There are differences, but no selected diff
1962 // - show amount of diffs
1963 else if (GetCurrentDiff() < 0)
1965 s = nDiffs == 1 ? _("1 Difference Found") : _("%1 Differences Found");
1966 _itot_s(nDiffs, sCnt, 10);
1967 strutils::replace(s, _T("%1"), sCnt);
1970 // There are differences and diff selected
1971 // - show diff number and amount of diffs
1974 s = _("Difference %1 of %2");
1975 const int signInd = m_diffList.GetSignificantIndex(GetCurrentDiff());
1976 _itot_s(signInd + 1, sIdx, 10);
1977 strutils::replace(s, _T("%1"), sIdx);
1978 _itot_s(nDiffs, sCnt, 10);
1979 strutils::replace(s, _T("%2"), sCnt);
1981 pCmdUI->SetText(s.c_str());
1985 * @brief Update plugin name
1986 * @param [in] pCmdUI UI component to update.
1988 void CMergeDoc::OnUpdatePluginName(CCmdUI* pCmdUI)
1991 if (m_pInfoUnpacker && !m_pInfoUnpacker->m_PluginName.empty())
1992 pluginNames += m_pInfoUnpacker->m_PluginName + _T("&");
1993 PrediffingInfo prediffer;
1994 GetPrediffer(&prediffer);
1995 if (!prediffer.m_PluginName.empty())
1996 pluginNames += prediffer.m_PluginName + _T("&");
1997 pCmdUI->SetText(pluginNames.substr(0, pluginNames.length() - 1).c_str());
2001 * @brief Change number of diff context lines
2003 void CMergeDoc::OnDiffContext(UINT nID)
2007 case ID_VIEW_DIFFCONTEXT_0:
2008 m_nDiffContext = 0; break;
2009 case ID_VIEW_DIFFCONTEXT_1:
2010 m_nDiffContext = 1; break;
2011 case ID_VIEW_DIFFCONTEXT_3:
2012 m_nDiffContext = 3; break;
2013 case ID_VIEW_DIFFCONTEXT_5:
2014 m_nDiffContext = 5; break;
2015 case ID_VIEW_DIFFCONTEXT_7:
2016 m_nDiffContext = 7; break;
2017 case ID_VIEW_DIFFCONTEXT_9:
2018 m_nDiffContext = 9; break;
2019 case ID_VIEW_DIFFCONTEXT_TOGGLE:
2020 m_nDiffContext = -m_nDiffContext - 1; break;
2021 case ID_VIEW_DIFFCONTEXT_ALL:
2022 if (m_nDiffContext >= 0)
2023 m_nDiffContext = -m_nDiffContext - 1;
2026 GetOptionsMgr()->SaveOption(OPT_DIFF_CONTEXT, m_nDiffContext);
2027 FlushAndRescan(true);
2031 * @brief Update number of diff context lines
2033 void CMergeDoc::OnUpdateDiffContext(CCmdUI* pCmdUI)
2036 switch (pCmdUI->m_nID)
2038 case ID_VIEW_DIFFCONTEXT_0:
2039 bCheck = (m_nDiffContext == 0); break;
2040 case ID_VIEW_DIFFCONTEXT_1:
2041 bCheck = (m_nDiffContext == 1); break;
2042 case ID_VIEW_DIFFCONTEXT_3:
2043 bCheck = (m_nDiffContext == 3); break;
2044 case ID_VIEW_DIFFCONTEXT_5:
2045 bCheck = (m_nDiffContext == 5); break;
2046 case ID_VIEW_DIFFCONTEXT_7:
2047 bCheck = (m_nDiffContext == 7); break;
2048 case ID_VIEW_DIFFCONTEXT_9:
2049 bCheck = (m_nDiffContext == 9); break;
2050 case ID_VIEW_DIFFCONTEXT_TOGGLE:
2051 bCheck = false; break;
2053 bCheck = (m_nDiffContext < 0); break;
2055 pCmdUI->SetCheck(bCheck);
2056 pCmdUI->Enable(true);
2060 * @brief Build the diff array and prepare buffers accordingly (insert ghost lines, set WinMerge flags)
2062 * @note After PrimeTextBuffers(), all buffers should have the same length.
2064 void CMergeDoc::PrimeTextBuffers()
2067 m_nTrivialDiffs = 0;
2069 int nDiffCount = m_diffList.GetSize();
2072 // walk the diff list and calculate numbers of extra lines to add
2073 int extras[3] = {0, 0, 0}; // extra lines added to each view
2074 m_diffList.GetExtraLinesCounts(m_nBuffers, extras);
2076 // resize m_aLines once for each view
2077 UINT lcount[3] = {0, 0, 0};
2078 UINT lcountnew[3] = {0, 0, 0};
2081 for (file = 0; file < m_nBuffers; file++)
2083 lcount[file] = m_ptBuf[file]->GetLineCount();
2084 lcountnew[file] = lcount[file] + extras[file];
2085 lcountmax = max(lcountmax, lcountnew[file]);
2087 for (file = 0; file < m_nBuffers; file++)
2089 m_ptBuf[file]->m_aLines.resize(lcountmax);
2092 // walk the diff list backward, move existing lines to proper place,
2093 // add ghost lines, and set flags
2094 for (nDiff = nDiffCount - 1; nDiff >= 0; nDiff --)
2097 VERIFY(m_diffList.GetDiff(nDiff, curDiff));
2099 // move matched lines after curDiff
2100 int nline[3] = { 0, 0, 0 };
2101 for (file = 0; file < m_nBuffers; file++)
2102 nline[file] = lcount[file] - curDiff.end[file] - 1; // #lines on left/middle/right after current diff
2103 // Matched lines should really match...
2104 // But matched lines after last diff may differ because of empty last line (see function's note)
2105 if (nDiff < nDiffCount - 1)
2106 ASSERT(nline[0] == nline[1]);
2109 for (file = 0; file < m_nBuffers; file++)
2111 // Move all lines after current diff down as far as needed
2112 // for any ghost lines we're about to insert
2113 m_ptBuf[file]->MoveLine(curDiff.end[file]+1, lcount[file]-1, lcountnew[file]-nline[file]);
2114 lcountnew[file] -= nline[file];
2115 lcount[file] -= nline[file];
2116 // move unmatched lines and add ghost lines
2117 nline[file] = curDiff.end[file] - curDiff.begin[file] + 1; // #lines in diff on left/middle/right
2118 nmaxline = max(nmaxline, nline[file]);
2121 for (file = 0; file < m_nBuffers; file++)
2123 DWORD dflag = LF_GHOST;
2124 if ((file == 0 && curDiff.op == OP_3RDONLY) || (file == 2 && curDiff.op == OP_1STONLY))
2126 m_ptBuf[file]->MoveLine(curDiff.begin[file], curDiff.end[file], lcountnew[file]-nmaxline);
2127 int nextra = nmaxline - nline[file];
2130 m_ptBuf[file]->SetEmptyLine(lcountnew[file] - nextra, nextra);
2131 for (int i = 1; i <= nextra; i++)
2132 m_ptBuf[file]->SetLineFlag(lcountnew[file]-i, dflag, true, false, false);
2134 lcountnew[file] -= nmaxline;
2136 lcount[file] -= nline[file];
2139 // set dbegin, dend, blank, and line flags
2140 curDiff.dbegin = lcountnew[0];
2146 // fall through and handle as diff
2153 curDiff.dend = lcountnew[0]+nmaxline-1;
2154 for (file = 0; file < m_nBuffers; file++)
2156 curDiff.blank[file] = -1;
2157 int nextra = nmaxline - nline[file];
2158 if (nmaxline > nline[file])
2160 // more lines on left, ghost lines on right side
2161 curDiff.blank[file] = curDiff.dend + 1 - nextra;
2167 for (file = 0; file < m_nBuffers; file++)
2171 for (i = curDiff.dbegin; i <= curDiff.dend; i++)
2173 if (curDiff.blank[file] == -1 || (int)i < curDiff.blank[file])
2175 // set diff or trivial flag
2176 DWORD dflag = (curDiff.op == OP_TRIVIAL) ? LF_TRIVIAL : LF_DIFF;
2177 if ((file == 0 && curDiff.op == OP_3RDONLY) || (file == 2 && curDiff.op == OP_1STONLY))
2179 m_ptBuf[file]->SetLineFlag(i, dflag, true, false, false);
2180 m_ptBuf[file]->SetLineFlag(i, LF_INVISIBLE, false, false, false);
2184 // ghost lines are already inserted (and flagged)
2185 // ghost lines opposite to trivial lines are ghost and trivial
2186 if (curDiff.op == OP_TRIVIAL)
2187 m_ptBuf[file]->SetLineFlag(i, LF_TRIVIAL, true, false, false);
2193 } // switch (curDiff.op)
2194 VERIFY(m_diffList.SetDiff(nDiff, curDiff));
2195 } // for (nDiff = nDiffCount; nDiff-- > 0; )
2197 m_diffList.ConstructSignificantChain();
2200 // Note: By this point all `m_ptBuf[]` buffers must have the same
2201 // number of line entries; eventual buffer processing typically
2202 // uses the line count from `m_ptBuf[0]` for all buffer processing.
2204 for (file = 0; file < m_nBuffers; file++)
2206 ASSERT(m_ptBuf[0]->GetLineCount() == m_ptBuf[file]->GetLineCount());
2210 for (file = 0; file < m_nBuffers; file++)
2211 m_ptBuf[file]->FinishLoading();
2215 * @brief Checks if file has changed since last update (save or rescan).
2216 * @param [in] szPath File to check
2217 * @param [in] dfi Previous fileinfo of file
2218 * @param [in] bSave If true Compare to last save-info, else to rescan-info
2219 * @param [in] nBuffer Index (0-based) of buffer
2220 * @return true if file is changed.
2222 CMergeDoc::FileChange CMergeDoc::IsFileChangedOnDisk(LPCTSTR szPath, DiffFileInfo &dfi,
2223 bool bSave, int nBuffer)
2225 DiffFileInfo *fileInfo = nullptr;
2226 bool bFileChanged = false;
2227 bool bIgnoreSmallDiff = GetOptionsMgr()->GetBool(OPT_IGNORE_SMALL_FILETIME);
2229 if (bIgnoreSmallDiff)
2230 tolerance = SmallTimeDiff; // From MainFrm.h
2233 fileInfo = m_pSaveFileInfo[nBuffer].get();
2235 fileInfo = m_pRescanFileInfo[nBuffer].get();
2237 // We assume file existed, so disappearing means removal
2238 if (!dfi.Update(szPath))
2241 int64_t timeDiff = dfi.mtime - fileInfo->mtime;
2242 if (timeDiff < 0) timeDiff = -timeDiff;
2243 if ((timeDiff > tolerance * Poco::Timestamp::resolution()) || (dfi.size != fileInfo->size))
2245 bFileChanged = true;
2251 return FileNoChange;
2254 void CMergeDoc::HideLines()
2259 if (m_nDiffContext < 0)
2261 ForEachView([](auto& pView) { pView->SetEnableHideLines(false); });
2265 int nLineCount = 0x7fffffff;
2266 for (file = 0; file < m_nBuffers; file++)
2268 if (nLineCount > m_ptBuf[file]->GetLineCount())
2269 nLineCount = m_ptBuf[file]->GetLineCount();
2272 for (nLine = 0; nLine < nLineCount;)
2274 if (!(m_ptBuf[0]->GetLineFlags(nLine) & (LF_DIFF | LF_GHOST)))
2276 for (file = 0; file < m_nBuffers; file++)
2277 m_ptBuf[file]->SetLineFlag(nLine, LF_INVISIBLE, true, false, false);
2282 int nLine2 = (nLine - m_nDiffContext < 0) ? 0 : (nLine - m_nDiffContext);
2283 for (; nLine2 < nLine; nLine2++)
2285 for (file = 0; file < m_nBuffers; file++)
2286 m_ptBuf[file]->SetLineFlag(nLine2, LF_INVISIBLE, false, false, false);
2289 for (; nLine < nLineCount; nLine++)
2291 if (!(m_ptBuf[0]->GetLineFlags(nLine) & (LF_DIFF | LF_GHOST)))
2293 for (file = 0; file < m_nBuffers; file++)
2294 m_ptBuf[file]->SetLineFlag(nLine, LF_INVISIBLE, false, false, false);
2297 int nLineEnd2 = (nLine + m_nDiffContext >= nLineCount) ? nLineCount-1 : (nLine + m_nDiffContext);
2298 for (; nLine < nLineEnd2; nLine++)
2300 for (file = 0; file < m_nBuffers; file++)
2301 m_ptBuf[file]->SetLineFlag(nLine, LF_INVISIBLE, false, false, false);
2302 if (m_ptBuf[0]->GetLineFlags(nLine) & (LF_DIFF | LF_GHOST))
2303 nLineEnd2 = (nLine + 1 + m_nDiffContext >= nLineCount) ? nLineCount-1 : (nLine + 1 + m_nDiffContext);
2308 ForEachView([](auto& pView) { pView->SetEnableHideLines(true); });
2312 * @brief Asks and then saves modified files.
2314 * This function saves modified files. Dialog is shown for user to select
2315 * modified file(s) one wants to save or discard changed. Cancelling of
2316 * save operation is allowed unless denied by parameter. After successfully
2317 * save operation file statuses are updated to directory compare.
2318 * @param [in] bAllowCancel If false "Cancel" button is disabled.
2319 * @return true if user selected "OK" so next operation can be
2320 * executed. If false user choosed "Cancel".
2321 * @note If filename is empty, we assume scratchpads are saved,
2322 * so instead of filename, description is shown.
2323 * @todo If we have filename and description for file, what should
2324 * we do after saving to different filename? Empty description?
2325 * @todo Parameter @p bAllowCancel is always true in callers - can be removed.
2327 bool CMergeDoc::PromptAndSaveIfNeeded(bool bAllowCancel)
2329 bool bLModified = false, bMModified = false, bRModified = false;
2331 bool bLSaveSuccess = false, bMSaveSuccess = false, bRSaveSuccess = false;
2333 if (m_nBuffers == 3)
2335 bLModified = m_ptBuf[0]->IsModified();
2336 bMModified = m_ptBuf[1]->IsModified();
2337 bRModified = m_ptBuf[2]->IsModified();
2341 bLModified = m_ptBuf[0]->IsModified();
2342 bRModified = m_ptBuf[1]->IsModified();
2344 if (!bLModified && !bMModified && !bRModified)
2348 dlg.DoAskFor(bLModified, bMModified, bRModified);
2350 dlg.m_bDisableCancel = true;
2351 if (!m_filePaths.GetLeft().empty())
2353 if (theApp.m_strSaveAsPath.empty())
2354 dlg.m_sLeftFile = m_filePaths.GetLeft();
2356 dlg.m_sLeftFile = theApp.m_strSaveAsPath;
2359 dlg.m_sLeftFile = m_strDesc[0];
2360 if (m_nBuffers == 3)
2362 if (!m_filePaths.GetMiddle().empty())
2364 if (theApp.m_strSaveAsPath.empty())
2365 dlg.m_sMiddleFile = m_filePaths.GetMiddle();
2367 dlg.m_sMiddleFile = theApp.m_strSaveAsPath;
2370 dlg.m_sMiddleFile = m_strDesc[1];
2372 if (!m_filePaths.GetRight().empty())
2374 if (theApp.m_strSaveAsPath.empty())
2375 dlg.m_sRightFile = m_filePaths.GetRight();
2377 dlg.m_sRightFile = theApp.m_strSaveAsPath;
2380 dlg.m_sRightFile = m_strDesc[m_nBuffers - 1];
2382 if (dlg.DoModal() == IDOK)
2384 if (bLModified && dlg.m_leftSave == SaveClosingDlg::SAVECLOSING_SAVE)
2386 if (!DoSave(m_filePaths.GetLeft().c_str(), bLSaveSuccess, 0))
2390 if (bMModified && dlg.m_middleSave == SaveClosingDlg::SAVECLOSING_SAVE)
2392 if (!DoSave(m_filePaths.GetMiddle().c_str(), bMSaveSuccess, 1))
2396 if (bRModified && dlg.m_rightSave == SaveClosingDlg::SAVECLOSING_SAVE)
2398 if (!DoSave(m_filePaths.GetRight().c_str(), bRSaveSuccess, m_nBuffers - 1))
2407 // If file were modified and saving was successfull,
2408 // update status on dir view
2409 if ((bLModified && bLSaveSuccess) ||
2410 (bMModified && bMSaveSuccess) ||
2411 (bRModified && bRSaveSuccess))
2413 // If directory compare has results
2414 if (m_pDirDoc != nullptr && m_pDirDoc->HasDiffs())
2416 if (m_bEditAfterRescan[0] || m_bEditAfterRescan[1] || (m_nBuffers == 3 && m_bEditAfterRescan[2]))
2417 FlushAndRescan(false);
2419 bool bIdentical = !m_diffList.HasSignificantDiffs(); // True if status should be set to identical
2420 m_pDirDoc->UpdateChangedItem(m_filePaths, m_diffList.GetSignificantDiffs(),
2421 m_nTrivialDiffs, bIdentical);
2428 /** Rescan only if we did not Rescan during the last timeOutInSecond seconds*/
2429 void CMergeDoc::RescanIfNeeded(float timeOutInSecond)
2431 // if we did not rescan during the request timeOut, Rescan
2432 // else we did Rescan after the request, so do nothing
2433 COleDateTimeSpan elapsed = COleDateTime::GetCurrentTime() - m_LastRescan;
2434 if (elapsed.GetTotalSeconds() >= timeOutInSecond)
2435 // (laoran 08-01-2003) maybe should be FlushAndRescan(true) ??
2440 * @brief We have two child views (left & right), so we keep pointers directly
2441 * at them (the MFC view list doesn't have them both)
2443 void CMergeDoc::AddMergeViews(CMergeEditView *pView[3])
2446 for (int nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
2447 m_pView[m_nGroups][nBuffer] = pView[nBuffer];
2451 void CMergeDoc::RemoveMergeViews(int nGroup)
2454 for (; nGroup < m_nGroups - 1; nGroup++)
2456 for (int nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
2458 m_pView[nGroup][nBuffer] = m_pView[nGroup + 1][nBuffer];
2459 m_pView[nGroup][nBuffer]->m_nThisGroup = nGroup;
2466 * @brief DirDoc gives us its identity just after it creates us
2468 void CMergeDoc::SetDirDoc(CDirDoc * pDirDoc)
2470 ASSERT(pDirDoc != nullptr && m_pDirDoc == nullptr);
2471 m_pDirDoc = pDirDoc;
2475 * @brief Return pointer to parent frame
2477 CMergeEditFrame * CMergeDoc::GetParentFrame()
2479 return dynamic_cast<CMergeEditFrame *>(m_pView[0][0]->GetParentFrame());
2483 * @brief DirDoc is closing
2485 void CMergeDoc::DirDocClosing(CDirDoc * pDirDoc)
2487 ASSERT(m_pDirDoc == pDirDoc);
2488 m_pDirDoc = nullptr;
2489 // TODO (Perry 2003-03-30): perhaps merge doc should close now ?
2493 * @brief DirDoc commanding us to close
2495 bool CMergeDoc::CloseNow()
2497 // Allow user to cancel closing
2498 if (!PromptAndSaveIfNeeded(true))
2501 GetParentFrame()->CloseNow();
2506 * @brief Loads file to buffer and shows load-errors
2507 * @param [in] sFileName File to open
2508 * @param [in] nBuffer Index (0-based) of buffer to load
2509 * @param [out] readOnly whether file is read-only
2510 * @param [in] encoding encoding used
2511 * @return Tells if files were loaded successfully
2512 * @sa CMergeDoc::OpenDocs()
2514 int CMergeDoc::LoadFile(CString sFileName, int nBuffer, bool & readOnly, const FileTextEncoding & encoding)
2517 DWORD retVal = FileLoadResult::FRESULT_ERROR;
2519 CDiffTextBuffer *pBuf = m_ptBuf[nBuffer].get();
2520 m_filePaths[nBuffer] = sFileName;
2522 CRLFSTYLE nCrlfStyle = CRLF_STYLE_AUTOMATIC;
2524 retVal = pBuf->LoadFromFile(sFileName, m_pInfoUnpacker.get(),
2525 m_strBothFilenames.c_str(), readOnly, nCrlfStyle, encoding, sOpenError);
2527 // if CMergeDoc::CDiffTextBuffer::LoadFromFile failed,
2528 // it left the pBuf in a valid (but empty) state via a call to InitNew
2530 if (FileLoadResult::IsOkImpure(retVal))
2532 // File loaded, and multiple EOL types in this file
2533 FileLoadResult::SetMainOk(retVal);
2535 // If mixed EOLs are not enabled, enable them for this doc.
2536 if (!GetOptionsMgr()->GetBool(OPT_ALLOW_MIXED_EOL))
2538 pBuf->SetMixedEOL(true);
2542 if (FileLoadResult::IsError(retVal))
2544 // Error from Unifile/system
2545 if (!sOpenError.IsEmpty())
2546 sError = strutils::format_string2(_("Cannot open file\n%1\n\n%2"), (LPCTSTR)sFileName, (LPCTSTR)sOpenError);
2548 sError = strutils::format_string1(_("File not found: %1"), (LPCTSTR)sFileName);
2549 ShowMessageBox(sError, MB_OK | MB_ICONSTOP | MB_MODELESS);
2551 else if (FileLoadResult::IsErrorUnpack(retVal))
2553 sError = strutils::format_string1(_("File not unpacked: %1"), (LPCTSTR)sFileName);
2554 ShowMessageBox(sError, MB_OK | MB_ICONSTOP | MB_MODELESS);
2560 * @brief Check if specified codepage number is valid for WinMerge Editor.
2561 * @param [in] cp Codepage number to check.
2562 * @return true if codepage is valid, false otherwise.
2564 bool CMergeDoc::IsValidCodepageForMergeEditor(unsigned cp) const
2566 if (cp == 0) // 0 is our signal value for invalid
2568 return GetEncodingNameFromCodePage(cp) != nullptr;
2572 * @brief Sanity check file's specified codepage.
2573 * This function checks if file's specified codepage is valid for WinMerge
2574 * editor and if not resets the codepage to default.
2575 * @param [in,out] fileinfo Class containing file's codepage.
2577 void CMergeDoc::SanityCheckCodepage(FileLocation & fileinfo)
2579 if (fileinfo.encoding.m_unicoding == ucr::NONE
2580 && !IsValidCodepageForMergeEditor(fileinfo.encoding.m_codepage))
2582 int cp = ucr::getDefaultCodepage();
2583 if (!IsValidCodepageForMergeEditor(cp))
2585 fileinfo.encoding.SetCodepage(cp);
2590 * @brief Loads one file from disk and updates file infos.
2591 * @param [in] index Index of file in internal buffers.
2592 * @param [in] filename File's name.
2593 * @param [in] readOnly Is file read-only?
2594 * @param [in] encoding File's encoding.
2595 * @return One of FileLoadResult values.
2597 DWORD CMergeDoc::LoadOneFile(int index, String filename, bool readOnly, const String& strDesc,
2598 const FileTextEncoding & encoding)
2600 DWORD loadSuccess = FileLoadResult::FRESULT_ERROR;;
2602 m_strDesc[index] = strDesc;
2603 if (!filename.empty())
2605 if (strDesc.empty())
2606 m_nBufferType[index] = BUFFER_NORMAL;
2608 m_nBufferType[index] = BUFFER_NORMAL_NAMED;
2609 m_pSaveFileInfo[index]->Update(filename);
2610 m_pRescanFileInfo[index]->Update(filename);
2612 loadSuccess = LoadFile(filename.c_str(), index, readOnly, encoding);
2613 if (FileLoadResult::IsLossy(loadSuccess))
2615 m_ptBuf[index]->FreeAll();
2616 loadSuccess = LoadFile(filename.c_str(), index, readOnly,
2617 GuessCodepageEncoding(filename, GetOptionsMgr()->GetInt(OPT_CP_DETECT), -1));
2622 m_nBufferType[index] = BUFFER_UNNAMED;
2623 m_ptBuf[index]->InitNew();
2624 m_ptBuf[index]->m_encoding = encoding;
2625 m_ptBuf[index]->FinishLoading(); // should clear GGhostTextBuffer::m_RealityBlock when reloading unnamed buffer
2626 loadSuccess = FileLoadResult::FRESULT_OK;
2631 void CMergeDoc::SetTableProperties()
2633 struct TableProps { bool istable; TCHAR delimiter; TCHAR quote; bool allowNewlinesInQuotes; };
2634 auto getTablePropsByFileName = [](const String& path, const std::optional<bool>& enableTableEditing)-> TableProps
2636 const TCHAR quote = GetOptionsMgr()->GetString(OPT_CMP_TBL_QUOTE_CHAR).c_str()[0];
2637 FileFilterHelper filterCSV, filterTSV, filterDSV;
2638 bool allowNewlineIQuotes = GetOptionsMgr()->GetBool(OPT_CMP_TBL_ALLOW_NEWLINES_IN_QUOTES);
2639 const String csvFilePattern = GetOptionsMgr()->GetString(OPT_CMP_CSV_FILEPATTERNS);
2640 if (!csvFilePattern.empty())
2642 filterCSV.UseMask(true);
2643 filterCSV.SetMask(csvFilePattern);
2644 if (filterCSV.includeFile(path))
2645 return { true, ',', quote, allowNewlineIQuotes };
2647 const String tsvFilePattern = GetOptionsMgr()->GetString(OPT_CMP_TSV_FILEPATTERNS);
2648 if (!tsvFilePattern.empty())
2650 filterTSV.UseMask(true);
2651 filterTSV.SetMask(tsvFilePattern);
2652 if (filterTSV.includeFile(path))
2653 return { true, '\t', quote, allowNewlineIQuotes };
2655 const String dsvFilePattern = GetOptionsMgr()->GetString(OPT_CMP_DSV_FILEPATTERNS);
2656 if (!dsvFilePattern.empty())
2658 filterDSV.UseMask(true);
2659 filterDSV.SetMask(dsvFilePattern);
2660 if (filterDSV.includeFile(path))
2661 return { true, GetOptionsMgr()->GetString(OPT_CMP_DSV_DELIM_CHAR).c_str()[0], quote };
2663 if (enableTableEditing.value_or(false))
2666 if (dlg.DoModal() == IDOK)
2667 return { true, dlg.m_sDelimiterChar.c_str()[0], dlg.m_sQuoteChar.c_str()[0], dlg.m_bAllowNewlinesInQuotes };
2669 return { false, 0, 0, false };
2672 TableProps tableProps[3] = {};
2673 int nTableFileIndex = -1;
2674 for (int nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
2677 paths::FindExtension(m_ptBuf[nBuffer - 1]->GetTempFileName()) != paths::FindExtension(m_ptBuf[nBuffer]->GetTempFileName()))
2678 tableProps[nBuffer] = getTablePropsByFileName(m_ptBuf[nBuffer]->GetTempFileName(), m_bEnableTableEditing);
2680 tableProps[nBuffer] = tableProps[nBuffer - 1];
2681 if (tableProps[nBuffer].istable)
2682 nTableFileIndex = nBuffer;
2684 for (int nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
2686 if (m_bEnableTableEditing.value_or(true) && nTableFileIndex >= 0)
2688 int i = tableProps[nBuffer].istable ? nBuffer : nTableFileIndex;
2689 m_ptBuf[nBuffer]->SetTableEditing(true);
2690 m_ptBuf[nBuffer]->ShareColumnWidths(*m_ptBuf[0]);
2691 m_ptBuf[nBuffer]->SetAllowNewlinesInQuotes(tableProps[i].allowNewlinesInQuotes);
2692 m_ptBuf[nBuffer]->SetFieldDelimiter(tableProps[i].delimiter);
2693 m_ptBuf[nBuffer]->SetFieldEnclosure(tableProps[i].quote);
2694 m_ptBuf[nBuffer]->JoinLinesForTableEditingMode();
2698 m_ptBuf[nBuffer]->SetTableEditing(false);
2704 * @brief Loads files and does initial rescan.
2705 * @param fileloc [in] File to open to left/middle/right side (path & encoding info)
2706 * @param bRO [in] Is left/middle/right file read-only
2707 * @return Success/Failure/Binary (failure) per typedef enum OpenDocsResult_TYPE
2708 * @todo Options are still read from CMainFrame, this will change
2709 * @sa CMainFrame::ShowMergeDoc()
2711 bool CMergeDoc::OpenDocs(int nFiles, const FileLocation ifileloc[],
2712 const bool bRO[], const String strDesc[])
2714 IDENTLEVEL identical = IDENTLEVEL_NONE;
2715 int nRescanResult = RESCAN_OK;
2717 FileLocation fileloc[3];
2719 std::copy_n(ifileloc, 3, fileloc);
2721 // Filter out invalid codepages, or editor will display all blank
2722 for (nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
2723 SanityCheckCodepage(fileloc[nBuffer]);
2727 curUndo = undoTgt.begin();
2729 // Prevent displaying views during LoadFile
2730 // Note : attach buffer again only if both loads succeed
2731 m_strBothFilenames.erase();
2733 ForEachView([](auto& pView) { pView->DetachFromBuffer(); });
2735 for (nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
2737 // clear undo buffers
2738 m_ptBuf[nBuffer]->m_aUndoBuf.clear();
2741 m_ptBuf[nBuffer]->FreeAll ();
2743 // build the text being filtered, "|" separates files as it is forbidden in filenames
2744 m_strBothFilenames += fileloc[nBuffer].filepath + _T("|");
2746 m_strBothFilenames.erase(m_strBothFilenames.length() - 1);
2750 for (nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
2752 nSuccess[nBuffer] = LoadOneFile(nBuffer, fileloc[nBuffer].filepath, bRO[nBuffer], strDesc ? strDesc[nBuffer] : _T(""),
2753 fileloc[nBuffer].encoding);
2756 SetTableProperties();
2758 const bool bFiltersEnabled = GetOptionsMgr()->GetBool(OPT_PLUGINS_ENABLED);
2760 // scratchpad : we don't call LoadFile, so
2761 // we need to initialize the unpacker as a "do nothing" one
2762 if (bFiltersEnabled)
2764 if (std::count(m_nBufferType, m_nBufferType + m_nBuffers, BUFFER_UNNAMED) == m_nBuffers)
2766 m_pInfoUnpacker->Initialize(PLUGIN_MANUAL);
2770 // Bail out if either side failed
2771 if (std::find_if(nSuccess, nSuccess + m_nBuffers, [](DWORD d){return !FileLoadResult::IsOk(d);} ) != nSuccess + m_nBuffers)
2773 CMergeEditFrame *pFrame = GetParentFrame();
2774 if (pFrame != nullptr)
2776 // Use verify macro to trap possible error in debug.
2777 VERIFY(pFrame->DestroyWindow());
2782 // Warn user if file load was lossy (bad encoding)
2784 int nLossyBuffers = 0;
2785 for (nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
2787 if (FileLoadResult::IsLossy(nSuccess[nBuffer]))
2789 // TODO: It would be nice to report how many lines were lossy
2790 // we did calculate those numbers when we loaded the files, in the text stats
2792 idres = IDS_LOSSY_TRANSCODING_FIRST + nBuffer;
2796 if (nLossyBuffers > 1)
2797 idres = IDS_LOSSY_TRANSCODING_BOTH; /* FIXEME */
2799 if (nLossyBuffers > 0)
2801 if (m_pEncodingErrorBar == nullptr)
2803 m_pEncodingErrorBar.reset(new CEncodingErrorBar());
2804 m_pEncodingErrorBar->Create(this->m_pView[0][0]->GetParentFrame());
2806 m_pEncodingErrorBar->SetText(LoadResString(idres));
2807 m_pView[0][0]->GetParentFrame()->ShowControlBar(m_pEncodingErrorBar.get(), TRUE, FALSE);
2810 ForEachView([](auto& pView) {
2811 // Now buffers data are valid
2812 pView->AttachToBuffer();
2813 // Currently there is only one set of syntax colors, which all documents & views share
2814 pView->SetColorContext(theApp.GetMainSyntaxColors());
2815 // Currently there is only one set of markers, which all documents & views share
2816 pView->SetMarkersContext(theApp.GetMainMarkers());
2818 for (nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
2820 // Set read-only statuses
2821 m_ptBuf[nBuffer]->SetReadOnly(bRO[nBuffer]);
2824 // Check the EOL sensitivity option (do it before Rescan)
2825 DIFFOPTIONS diffOptions = {0};
2826 m_diffWrapper.GetOptions(&diffOptions);
2827 if (!GetOptionsMgr()->GetBool(OPT_ALLOW_MIXED_EOL) && !diffOptions.bIgnoreEol)
2829 for (nBuffer = 1; nBuffer < m_nBuffers; nBuffer++)
2830 if (m_ptBuf[0]->GetCRLFMode() != m_ptBuf[nBuffer]->GetCRLFMode())
2833 if (nBuffer < m_nBuffers)
2835 // Options and files not are not compatible :
2836 // Sensitive to EOL on, allow mixing EOL off, and files have a different EOL style.
2837 // All lines will differ, that is not very interesting and probably not wanted.
2838 // Propose to turn off the option 'sensitive to EOL'
2839 String s = theApp.LoadString(IDS_SUGGEST_IGNOREEOL);
2840 if (ShowMessageBox(s, MB_YESNO | MB_ICONWARNING | MB_DONT_ASK_AGAIN, IDS_SUGGEST_IGNOREEOL) == IDYES)
2842 diffOptions.bIgnoreEol = true;
2843 m_diffWrapper.SetOptions(&diffOptions);
2845 CMessageBoxDialog dlg(nullptr, s.c_str(), _T(""), 0, IDS_SUGGEST_IGNOREEOL);
2846 const int nFormerResult = dlg.GetFormerResult();
2847 if (nFormerResult != -1)
2849 // "Don't ask this question again" checkbox is checked
2850 GetOptionsMgr()->SaveOption(OPT_CMP_IGNORE_EOL, true);
2856 // Define the prediffer
2857 PackingInfo * infoUnpacker = nullptr;
2858 PrediffingInfo * infoPrediffer = nullptr;
2859 if (bFiltersEnabled && m_pDirDoc != nullptr)
2861 m_pDirDoc->GetPluginManager().FetchPluginInfos(m_strBothFilenames, &infoUnpacker, &infoPrediffer);
2862 m_diffWrapper.SetPrediffer(infoPrediffer);
2863 m_diffWrapper.SetTextForAutomaticPrediff(m_strBothFilenames);
2866 bool bBinary = false;
2867 nRescanResult = Rescan(bBinary, identical);
2869 // Open filed if rescan succeed and files are not binaries
2870 if (nRescanResult == RESCAN_OK)
2872 // set the document types
2873 // Warning : it is the first thing to do (must be done before UpdateView,
2874 // or any function that calls UpdateView, like SelectDiff)
2875 // Note: If option enabled, and another side type is not recognized,
2876 // we use recognized type for unrecognized side too.
2881 for (nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
2883 if (bFiltersEnabled && m_pInfoUnpacker->m_textType.length())
2884 sext[nBuffer] = m_pInfoUnpacker->m_textType;
2886 sext[nBuffer] = GetFileExt(fileloc[nBuffer].filepath.c_str(), m_strDesc[nBuffer].c_str());
2887 ForEachView(nBuffer, [&](auto& pView) {
2888 bTyped[nBuffer] = pView->SetTextType(sext[nBuffer].c_str());
2889 if (bTyped[nBuffer])
2890 paneTyped = nBuffer;
2894 for (nBuffer = 1; nBuffer < m_nBuffers; nBuffer++)
2896 if (bTyped[0] != bTyped[nBuffer])
2900 bool syntaxHLEnabled = GetOptionsMgr()->GetBool(OPT_SYNTAX_HIGHLIGHT);
2901 if (syntaxHLEnabled && nBuffer < m_nBuffers)
2903 if (std::count(bTyped, bTyped + m_nBuffers, false) == m_nBuffers)
2906 m_ptBuf[0]->GetLine(0, sFirstLine);
2907 for (nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
2909 bTyped[nBuffer] = GetView(0, nBuffer)->SetTextTypeByContent(sFirstLine);
2914 if (syntaxHLEnabled)
2916 CrystalLineParser::TextDefinition *enuType = CrystalLineParser::GetTextType(sext[paneTyped].c_str());
2917 ForEachView([&bTyped, enuType](auto& pView) {
2918 if (!bTyped[pView->m_nThisPane])
2919 pView->SetTextType(enuType);
2923 int nNormalBuffer = 0;
2924 for (nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
2926 // set the frame window header
2927 UpdateHeaderPath(nBuffer);
2929 ForEachView(nBuffer, [](auto& pView) { pView->DocumentsLoaded(); });
2931 if ((m_nBufferType[nBuffer] == BUFFER_NORMAL) ||
2932 (m_nBufferType[nBuffer] == BUFFER_NORMAL_NAMED))
2939 // Inform user that files are identical
2940 // Don't show message if new buffers created
2941 if (identical == IDENTLEVEL_ALL && nNormalBuffer > 0)
2943 ShowRescanError(nRescanResult, identical);
2946 // Exit if files are identical should only work for the first
2947 // comparison and must be disabled afterward.
2948 theApp.m_bExitIfNoDiff = MergeCmdLineInfo::Disabled;
2952 // CMergeDoc::Rescan fails if files do not exist on both sides
2953 // or the really arcane case that the temp files couldn't be created,
2954 // which is too obscure to bother reporting if you can't write to
2955 // your temp directory, doing nothing is graceful enough for that).
2956 ShowRescanError(nRescanResult, identical);
2957 GetParentFrame()->DestroyWindow();
2961 // Force repaint of location pane to update it in case we had some warning
2962 // dialog visible and it got painted before files were loaded
2963 if (m_pView[0][0] != nullptr)
2964 m_pView[0][0]->RepaintLocationPane();
2969 void CMergeDoc::MoveOnLoad(int nPane, int nLineIndex)
2973 nPane = GetOptionsMgr()->GetInt(OPT_ACTIVE_PANE);
2974 if (nPane < 0 || nPane >= m_nBuffers)
2977 if (nLineIndex == -1)
2979 // scroll to first diff
2980 if (GetOptionsMgr()->GetBool(OPT_SCROLL_TO_FIRST) &&
2981 m_diffList.HasSignificantDiffs())
2983 int nDiff = m_diffList.FirstSignificantDiff();
2985 m_pView[0][nPane]->SelectDiff(nDiff, true, false);
2986 m_pView[0][nPane]->SetActivePane();
2990 m_pView[0][nPane]->GotoLine(nLineIndex < 0 ? 0 : nLineIndex, false, nPane);
2993 void CMergeDoc::ChangeFile(int nBuffer, const String& path, int nLineIndex)
2995 if (!PromptAndSaveIfNeeded(true))
2998 FileLocation fileloc[3];
3001 for (int pane = 0; pane < m_nBuffers; pane++)
3003 bRO[pane] = m_ptBuf[pane]->GetReadOnly();
3004 fileloc[pane].encoding.m_unicoding = m_ptBuf[pane]->getUnicoding();
3005 fileloc[pane].encoding.m_codepage = m_ptBuf[pane]->getCodepage();
3006 fileloc[pane].setPath(m_filePaths[pane]);
3008 std::copy_n(m_strDesc, m_nBuffers, strDesc);
3010 strDesc[nBuffer] = _T("");
3011 fileloc[nBuffer].setPath(path);
3012 fileloc[nBuffer].encoding = GuessCodepageEncoding(path, GetOptionsMgr()->GetInt(OPT_CP_DETECT));
3014 if (OpenDocs(m_nBuffers, fileloc, bRO, strDesc))
3015 MoveOnLoad(nBuffer, nLineIndex);
3019 * @brief Re-load a document.
3020 * This methods re-loads the file compare document. The re-loaded document is
3021 * one side of the file compare.
3022 * @param [in] index The document to re-load.
3023 * @return Open result code.
3025 void CMergeDoc::RefreshOptions()
3027 DIFFOPTIONS options = {0};
3029 m_diffWrapper.SetDetectMovedBlocks(GetOptionsMgr()->GetBool(OPT_CMP_MOVED_BLOCKS));
3030 Options::DiffOptions::Load(GetOptionsMgr(), options);
3032 m_diffWrapper.SetOptions(&options);
3034 // Refresh view options
3035 ForEachView([](auto& pView) { pView->RefreshOptions(); });
3039 * @brief Write path and filename to headerbar
3040 * @note SetText() does not repaint unchanged text
3042 void CMergeDoc::UpdateHeaderPath(int pane)
3044 CMergeEditFrame *pf = GetParentFrame();
3045 ASSERT(pf != nullptr);
3047 bool bChanges = false;
3049 if (m_nBufferType[pane] == BUFFER_UNNAMED ||
3050 m_nBufferType[pane] == BUFFER_NORMAL_NAMED)
3052 sText = m_strDesc[pane];
3056 sText = m_filePaths[pane];
3057 if (m_pDirDoc != nullptr)
3059 m_pDirDoc->ApplyDisplayRoot(pane, sText);
3062 bChanges = m_ptBuf[pane]->IsModified();
3065 sText.insert(0, _T("* "));
3067 pf->GetHeaderInterface()->SetText(pane, sText);
3073 * @brief Paint differently the headerbar of the active view
3075 void CMergeDoc::UpdateHeaderActivity(int pane, bool bActivate)
3077 CMergeEditFrame *pf = GetParentFrame();
3078 ASSERT(pf != nullptr);
3079 pf->GetHeaderInterface()->SetActive(pane, bActivate);
3083 * @brief Set detect/not detect Moved Blocks
3085 void CMergeDoc::SetDetectMovedBlocks(bool bDetectMovedBlocks)
3087 if (bDetectMovedBlocks == m_diffWrapper.GetDetectMovedBlocks())
3090 GetOptionsMgr()->SaveOption(OPT_CMP_MOVED_BLOCKS, bDetectMovedBlocks);
3091 m_diffWrapper.SetDetectMovedBlocks(bDetectMovedBlocks);
3096 * @brief Check if given buffer has mixed EOL style.
3097 * @param [in] nBuffer Buffer to check.
3098 * @return true if buffer's EOL style is mixed, false otherwise.
3100 bool CMergeDoc::IsMixedEOL(int nBuffer) const
3102 CDiffTextBuffer *pBuf = m_ptBuf[nBuffer].get();
3103 return pBuf->IsMixedEOL();
3106 void CMergeDoc::SetEditedAfterRescan(int nBuffer)
3108 m_bEditAfterRescan[nBuffer] = true;
3111 bool CMergeDoc::IsEditedAfterRescan(int nBuffer) const
3113 if (nBuffer >= 0 && nBuffer < m_nBuffers)
3114 return m_bEditAfterRescan[nBuffer];
3116 for (nBuffer = 0; nBuffer < m_nBuffers; ++nBuffer)
3118 if (m_bEditAfterRescan[nBuffer])
3126 * @brief Update document filenames to title
3128 void CMergeDoc::SetTitle(LPCTSTR lpszTitle)
3131 String sFileName[3];
3133 if (lpszTitle != nullptr)
3137 for (int nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
3138 sFileName[nBuffer] = !m_strDesc[nBuffer].empty() ? m_strDesc[nBuffer] : paths::FindFileName(m_filePaths[nBuffer]);
3139 if (std::count(&sFileName[0], &sFileName[0] + m_nBuffers, sFileName[0]) == m_nBuffers)
3140 sTitle = sFileName[0] + strutils::format(_T(" x %d"), m_nBuffers);
3142 sTitle = strutils::join(&sFileName[0], &sFileName[0] + m_nBuffers, _T(" - "));
3144 CDocument::SetTitle(sTitle.c_str());
3148 * @brief Update any resources necessary after a GUI language change
3150 void CMergeDoc::UpdateResources()
3152 if (m_nBufferType[0] == BUFFER_UNNAMED)
3153 m_strDesc[0] = _("Untitled left");
3154 if (m_nBufferType[m_nBuffers - 1] == BUFFER_UNNAMED)
3155 m_strDesc[m_nBuffers - 1] = _("Untitled right");
3156 if (m_nBuffers == 3 && m_nBufferType[1] == BUFFER_UNNAMED)
3157 m_strDesc[1] = _("Untitled middle");
3158 for (int nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
3159 UpdateHeaderPath(nBuffer);
3161 GetParentFrame()->UpdateResources();
3162 ForEachView([](auto& pView) { pView->UpdateResources(); });
3165 // Return current word breaking break type setting (whitespace only or include punctuation)
3166 bool CMergeDoc::GetBreakType() const
3168 bool breakType = !!GetOptionsMgr()->GetInt(OPT_BREAK_TYPE);
3172 // Return true to do line diff colors at the byte level (false to do them at word level)
3173 bool CMergeDoc::GetByteColoringOption() const
3175 // color at byte level if 'break_on_words' option not set
3176 bool breakWords = GetOptionsMgr()->GetBool(OPT_BREAK_ON_WORDS);
3180 /// Swap files and update views
3181 void CMergeDoc::SwapFiles()
3184 for (int nGroup = 0; nGroup < m_nGroups; ++nGroup)
3186 int nLeftViewId = m_pView[nGroup][0]->GetDlgCtrlID();
3187 int nRightViewId = m_pView[nGroup][m_nBuffers - 1]->GetDlgCtrlID();
3188 m_pView[nGroup][0]->SetDlgCtrlID(nRightViewId);
3189 m_pView[nGroup][m_nBuffers - 1]->SetDlgCtrlID(nLeftViewId);
3193 // Swap buffers and so on
3194 std::swap(m_ptBuf[0], m_ptBuf[m_nBuffers - 1]);
3195 for (int nGroup = 0; nGroup < m_nGroups; ++nGroup)
3196 std::swap(m_pView[nGroup][0], m_pView[nGroup][m_nBuffers - 1]);
3197 std::swap(m_pSaveFileInfo[0], m_pSaveFileInfo[m_nBuffers - 1]);
3198 std::swap(m_pRescanFileInfo[0], m_pRescanFileInfo[m_nBuffers - 1]);
3199 std::swap(m_nBufferType[0], m_nBufferType[m_nBuffers - 1]);
3200 std::swap(m_bEditAfterRescan[0], m_bEditAfterRescan[m_nBuffers - 1]);
3201 std::swap(m_strDesc[0], m_strDesc[m_nBuffers - 1]);
3204 m_diffList.Swap(0, m_nBuffers - 1);
3205 for (int nGroup = 0; nGroup < m_nGroups; nGroup++)
3206 swap(m_pView[nGroup][0]->m_piMergeEditStatus, m_pView[nGroup][m_nBuffers - 1]->m_piMergeEditStatus);
3208 ClearWordDiffCache();
3210 for (int nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
3212 m_ptBuf[nBuffer]->m_nThisPane = nBuffer;
3213 for (int nGroup = 0; nGroup < m_nGroups; nGroup++)
3214 m_pView[nGroup][nBuffer]->m_nThisPane = nBuffer;
3217 UpdateHeaderPath(nBuffer);
3219 GetParentFrame()->UpdateSplitter();
3220 ForEachView([](auto& pView) { pView->UpdateStatusbar(); });
3222 UpdateAllViews(nullptr);
3226 * @brief Display unpacker dialog to user & handle user's choices
3228 bool CMergeDoc::OpenWithUnpackerDialog()
3230 // let the user choose a handler
3231 CSelectUnpackerDlg dlg(m_filePaths[0], nullptr);
3232 // create now a new infoUnpacker to initialize the manual/automatic flag
3233 PackingInfo infoUnpacker(PLUGIN_AUTO);
3234 dlg.SetInitialInfoHandler(&infoUnpacker);
3236 if (dlg.DoModal() == IDOK)
3238 infoUnpacker = dlg.GetInfoHandler();
3239 Merge7zFormatMergePluginScope scope(&infoUnpacker);
3240 if (HasZipSupport() && std::count_if(m_filePaths.begin(), m_filePaths.end(), ArchiveGuessFormat) == m_nBuffers)
3242 DWORD dwFlags[3] = {FFILEOPEN_NOMRU, FFILEOPEN_NOMRU, FFILEOPEN_NOMRU};
3243 GetMainFrame()->DoFileOpen(&m_filePaths, dwFlags, m_strDesc, _T(""),
3244 GetOptionsMgr()->GetBool(OPT_CMP_INCLUDE_SUBDIRS), nullptr, _T(""), &infoUnpacker);
3249 SetUnpacker(&infoUnpacker);
3261 * @brief Reloads the opened files
3263 void CMergeDoc::OnFileReload()
3265 if (!PromptAndSaveIfNeeded(true))
3268 FileLocation fileloc[3];
3270 for (int pane = 0; pane < m_nBuffers; pane++)
3272 bRO[pane] = m_ptBuf[pane]->GetReadOnly();
3273 fileloc[pane].encoding.m_unicoding = m_ptBuf[pane]->getUnicoding();
3274 fileloc[pane].encoding.m_codepage = m_ptBuf[pane]->getCodepage();
3275 fileloc[pane].setPath(m_filePaths[pane]);
3277 CPoint pt = GetActiveMergeView()->GetCursorPos();
3278 if (OpenDocs(m_nBuffers, fileloc, bRO, m_strDesc))
3279 MoveOnLoad(GetActiveMergeView()->m_nThisPane, pt.y);
3283 * @brief Display encodings to user
3285 void CMergeDoc::OnFileEncoding()
3287 DoFileEncodingDialog();
3290 void CMergeDoc::OnCtxtOpenWithUnpacker()
3292 OpenWithUnpackerDialog();
3295 void CMergeDoc::OnBnClickedFileEncoding()
3297 if (m_pEncodingErrorBar == nullptr || m_pView[0][0] == nullptr)
3299 m_pView[0][0]->GetParentFrame()->ShowControlBar(m_pEncodingErrorBar.get(), FALSE, FALSE);
3300 DoFileEncodingDialog();
3303 void CMergeDoc::OnBnClickedPlugin()
3305 if (m_pEncodingErrorBar == nullptr || m_pView[0][0] == nullptr)
3307 m_pView[0][0]->GetParentFrame()->ShowControlBar(m_pEncodingErrorBar.get(), FALSE, FALSE);
3308 OpenWithUnpackerDialog();
3311 void CMergeDoc::OnBnClickedHexView()
3313 OnFileRecompareAs(ID_MERGE_COMPARE_HEX);
3316 void CMergeDoc::OnOK()
3318 if (m_pEncodingErrorBar == nullptr || m_pView[0][0] == nullptr)
3320 m_pView[0][0]->GetParentFrame()->ShowControlBar(m_pEncodingErrorBar.get(), FALSE, FALSE);
3323 void CMergeDoc::OnFileRecompareAsText()
3325 m_bEnableTableEditing = false;
3326 PackingInfo infoUnpacker;
3327 SetUnpacker(&infoUnpacker);
3331 void CMergeDoc::OnUpdateFileRecompareAsText(CCmdUI *pCmdUI)
3333 pCmdUI->Enable(m_pInfoUnpacker->m_PluginOrPredifferMode == PLUGIN_BUILTIN_XML ||
3334 m_ptBuf[0]->GetTableEditing());
3337 void CMergeDoc::OnFileRecompareAsTable()
3339 m_bEnableTableEditing = true;
3340 PackingInfo infoUnpacker;
3341 SetUnpacker(&infoUnpacker);
3345 void CMergeDoc::OnUpdateFileRecompareAsTable(CCmdUI *pCmdUI)
3347 pCmdUI->Enable(!m_ptBuf[0]->GetTableEditing());
3350 void CMergeDoc::OnFileRecompareAsXML()
3352 m_bEnableTableEditing = false;
3353 PackingInfo infoUnpacker(PLUGIN_BUILTIN_XML);
3354 SetUnpacker(&infoUnpacker);
3358 void CMergeDoc::OnUpdateFileRecompareAsXML(CCmdUI *pCmdUI)
3360 pCmdUI->Enable(m_pInfoUnpacker->m_PluginOrPredifferMode != PLUGIN_BUILTIN_XML);
3363 void CMergeDoc::OnFileRecompareAs(UINT nID)
3365 DWORD dwFlags[3] = { 0 };
3366 FileLocation fileloc[3];
3367 for (int pane = 0; pane < m_nBuffers; pane++)
3369 fileloc[pane].setPath(m_filePaths[pane]);
3370 dwFlags[pane] |= FFILEOPEN_NOMRU | (m_ptBuf[pane]->GetReadOnly() ? FFILEOPEN_READONLY : 0);
3372 if (m_pEncodingErrorBar!=nullptr && m_pEncodingErrorBar->IsWindowVisible())
3373 m_pView[0][0]->GetParentFrame()->ShowControlBar(m_pEncodingErrorBar.get(), FALSE, FALSE);
3374 if (nID == ID_MERGE_COMPARE_HEX)
3375 GetMainFrame()->ShowHexMergeDoc(m_pDirDoc, m_nBuffers, fileloc, dwFlags, m_strDesc);
3377 GetMainFrame()->ShowImgMergeDoc(m_pDirDoc, m_nBuffers, fileloc, dwFlags, m_strDesc);
3378 GetParentFrame()->ShowWindow(SW_RESTORE);
3379 GetParentFrame()->DestroyWindow();
3382 // Return file extension either from file name
3383 String CMergeDoc::GetFileExt(LPCTSTR sFileName, LPCTSTR sDescription) const
3386 paths::SplitFilename(sFileName, nullptr, nullptr, &sExt);
3391 * @brief Generate report from file compare results.
3393 bool CMergeDoc::GenerateReport(const String& sFileName) const
3395 // calculate HTML font size
3398 dc.CreateDC(_T("DISPLAY"), nullptr, nullptr, nullptr);
3399 m_pView[0][0]->GetFont(lf);
3400 int nFontSize = -MulDiv (lf.lfHeight, 72, dc.GetDeviceCaps (LOGPIXELSY));
3402 // create HTML report
3404 if (!file.Open(sFileName, _T("wt")))
3406 String errMsg = GetSysError(GetLastError());
3407 String msg = strutils::format_string1(
3408 _("Error creating the report:\n%1"), errMsg);
3409 AfxMessageBox(msg.c_str(), MB_OK | MB_ICONSTOP);
3413 file.SetCodepage(ucr::CP_UTF_8);
3415 CString headerText =
3416 _T("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\n")
3417 _T("\t\"http://www.w3.org/TR/html4/loose.dtd\">\n")
3420 _T("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n")
3421 _T("<title>WinMerge File Compare Report</title>\n")
3422 _T("<style type=\"text/css\">\n")
3424 _T("table {margin: 0; border: 1px solid #a0a0a0; box-shadow: 1px 1px 2px rgba(0, 0, 0, 0.15);}\n")
3425 _T("td,th {word-break: break-all; font-size: %dpt;padding: 0 3px;}\n")
3426 _T("tr { vertical-align: top; }\n")
3427 _T(".title {color: white; background-color: blue; vertical-align: top; padding: 4px 4px; background: linear-gradient(mediumblue, darkblue);}\n")
3433 _T("<table cellspacing=\"0\" cellpadding=\"0\" style=\"width:100%%;\">\n")
3437 strutils::format((LPCTSTR)headerText, nFontSize, (LPCTSTR)m_pView[0][0]->GetHTMLStyles());
3438 file.WriteString(header);
3441 // If archive, use archive path + folder + filename inside archive
3442 // If desc text given, use it
3443 PathContext paths = m_filePaths;
3444 if (m_pDirDoc != nullptr && m_pDirDoc->IsArchiveFolders())
3446 for (int i = 0; i < paths.GetSize(); i++)
3447 m_pDirDoc->ApplyDisplayRoot(i, paths[i]);
3451 for (int i = 0; i < paths.GetSize(); i++)
3453 if (!m_strDesc[i].empty())
3454 paths[i] = m_strDesc[i];
3460 for (nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
3462 String data = strutils::format(_T("<th colspan=\"2\" class=\"title\" style=\"width:%f%%\">"),
3463 (double)100 / m_nBuffers);
3464 file.WriteString(data);
3465 file.WriteString(ucr::toTString(CMarkdown::Entities(ucr::toUTF8(paths[nBuffer]))));
3466 file.WriteString(_T("</th>\n"));
3473 // write the body of the report
3475 int nLineCount[3] = {0};
3477 for (nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
3478 nLineCount[nBuffer] = m_ptBuf[nBuffer]->GetLineCount();
3482 file.WriteString(_T("<tr>\n"));
3483 for (nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
3485 for (; idx[nBuffer] < nLineCount[nBuffer]; idx[nBuffer]++)
3487 if (m_pView[0][nBuffer]->GetLineVisible(idx[nBuffer]))
3491 if (idx[nBuffer] < nLineCount[nBuffer])
3494 int iVisibleLineNumber = 0;
3495 String tdtag = _T("<td class=\"ln\">");
3496 DWORD dwFlags = m_ptBuf[nBuffer]->GetLineFlags(idx[nBuffer]);
3497 if ((dwFlags & LF_GHOST) == 0 && m_pView[0][nBuffer]->GetViewLineNumbers())
3499 iVisibleLineNumber = m_ptBuf[nBuffer]->ComputeRealLine(idx[nBuffer]) + 1;
3502 (dwFlags & (LF_DIFF | LF_GHOST)) != 0 && (idx[nBuffer] == 0 ||
3503 (m_ptBuf[nBuffer]->GetLineFlags(idx[nBuffer] - 1) & (LF_DIFF | LF_GHOST)) == 0))
3506 if (iVisibleLineNumber > 0)
3508 tdtag += strutils::format(_T("<a name=\"d%d\" href=\"#d%d\">%d</a>"), nDiff, nDiff, iVisibleLineNumber);
3509 iVisibleLineNumber = 0;
3512 tdtag += strutils::format(_T("<a name=\"d%d\" href=\"#d%d\">.</a>"), nDiff, nDiff);
3514 if (iVisibleLineNumber > 0)
3515 tdtag += strutils::format(_T("%d</td>"), iVisibleLineNumber);
3517 tdtag += _T("</td>");
3518 file.WriteString(tdtag);
3520 file.WriteString((LPCTSTR)m_pView[0][nBuffer]->GetHTMLLine(idx[nBuffer], _T("td")));
3524 file.WriteString(_T("<td class=\"ln\"></td><td></td>"));
3525 file.WriteString(_T("\n"));
3527 file.WriteString(_T("</tr>\n"));
3529 bool bBorderLine = false;
3530 for (nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
3532 if (idx[nBuffer] < nLineCount[nBuffer] && !m_pView[0][nBuffer]->GetLineVisible(idx[nBuffer]))
3538 file.WriteString(_T("<tr height=1>"));
3539 for (nBuffer = 0; nBuffer < m_nBuffers; nBuffer++)
3541 if (idx[nBuffer] < nLineCount[nBuffer] && !m_pView[0][nBuffer]->GetLineVisible(idx[nBuffer]))
3542 file.WriteString(_T("<td style=\"background-color: black\"></td><td style=\"background-color: black\"></td>"));
3544 file.WriteString(_T("<td></td><td></td>"));
3546 file.WriteString(_T("</tr>\n"));
3549 if (idx[0] >= nLineCount[0] && idx[1] >= nLineCount[1] && (m_nBuffers < 3 || idx[2] >= nLineCount[2]))
3564 * @brief Generate report from file compare results.
3566 void CMergeDoc::OnToolsGenerateReport()
3571 if (!SelectFile(AfxGetMainWnd()->GetSafeHwnd(), s, false, folder, _T(""), _("HTML Files (*.htm,*.html)|*.htm;*.html|All Files (*.*)|*.*||"), _T("htm")))
3574 if (GenerateReport(s.c_str()))
3575 LangMessageBox(IDS_REPORT_SUCCESS, MB_OK | MB_ICONINFORMATION);
3579 * @brief Generate patch from files selected.
3581 * Creates a patch from selected files in active directory compare, or
3582 * active file compare. Files in file compare must be saved before
3585 void CMergeDoc::OnToolsGeneratePatch()
3587 // If there are changes in files, tell user to save them first
3590 LangMessageBox(IDS_SAVEFILES_FORPATCH, MB_ICONSTOP);
3595 patcher.AddFiles(m_filePaths.GetLeft(),
3596 m_filePaths.GetRight());
3597 patcher.CreatePatch();
3601 * @brief Add synchronization point
3603 void CMergeDoc::AddSyncPoint()
3606 for (int nBuffer = 0; nBuffer < m_nBuffers; ++nBuffer)
3608 int tmp = m_pView[0][nBuffer]->GetCursorPos().y;
3609 nLine[nBuffer] = m_ptBuf[nBuffer]->ComputeApparentLine(m_ptBuf[nBuffer]->ComputeRealLine(tmp));
3612 // If adding a sync point by selecting a ghost line that is after the last block, Cancel the process adding a sync point.
3613 for (int nBuffer = 0; nBuffer < m_nBuffers; ++nBuffer)
3614 if (nLine[nBuffer] >= m_ptBuf[nBuffer]->GetLineCount())
3616 LangMessageBox(IDS_SYNCPOINT_LASTBLOCK, MB_ICONSTOP);
3620 for (int nBuffer = 0; nBuffer < m_nBuffers; ++nBuffer)
3621 if (m_ptBuf[nBuffer]->GetLineFlags(nLine[nBuffer]) & LF_INVALID_BREAKPOINT)
3622 DeleteSyncPoint(nBuffer, nLine[nBuffer], false);
3624 for (int nBuffer = 0; nBuffer < m_nBuffers; ++nBuffer)
3625 m_ptBuf[nBuffer]->SetLineFlag(nLine[nBuffer], LF_INVALID_BREAKPOINT, true, false);
3627 m_bHasSyncPoints = true;
3629 ForEachView([](auto& pView) { pView->SetSelectionMargin(true); });
3631 FlushAndRescan(true);
3635 * @brief Delete a synchronization point
3637 bool CMergeDoc::DeleteSyncPoint(int pane, int nLine, bool bRescan)
3639 const auto syncpoints = GetSyncPointList();
3640 for (auto syncpnt : syncpoints)
3642 if (syncpnt[pane] == nLine)
3644 for (int nBuffer = 0; nBuffer < m_nBuffers; ++nBuffer)
3645 m_ptBuf[nBuffer]->SetLineFlag(syncpnt[nBuffer], LF_INVALID_BREAKPOINT, false, false);
3649 if (syncpoints.size() == 1)
3650 m_bHasSyncPoints = false;
3653 FlushAndRescan(true);
3658 * @brief Clear Synchronization points
3660 void CMergeDoc::ClearSyncPoints()
3662 if (!m_bHasSyncPoints)
3665 for (int nBuffer = 0; nBuffer < m_nBuffers; ++nBuffer)
3667 int nLineCount = m_ptBuf[nBuffer]->GetLineCount();
3668 for (int nLine = 0; nLine < nLineCount; ++nLine)
3670 if (m_ptBuf[nBuffer]->GetLineFlags(nLine) & LF_INVALID_BREAKPOINT)
3671 m_ptBuf[nBuffer]->SetLineFlag(nLine, LF_INVALID_BREAKPOINT, false, false);
3675 m_bHasSyncPoints = false;
3677 FlushAndRescan(true);
3680 std::vector<std::vector<int> > CMergeDoc::GetSyncPointList()
3682 std::vector<std::vector<int> > list;
3683 if (!m_bHasSyncPoints)
3685 int idx[3] = {-1, -1, -1};
3686 std::vector<int> points(m_nBuffers);
3687 for (int nBuffer = 0; nBuffer < m_nBuffers; ++nBuffer)
3688 points[nBuffer] = m_ptBuf[nBuffer]->GetLineCount() - 1;
3689 for (int nBuffer = 0; nBuffer < m_nBuffers; ++nBuffer)
3691 int nLineCount = m_ptBuf[nBuffer]->GetLineCount();
3692 for (int nLine = 0; nLine < nLineCount; ++nLine)
3694 if (m_ptBuf[nBuffer]->GetLineFlags(nLine) & LF_INVALID_BREAKPOINT)
3697 if (static_cast<int>(list.size()) <= idx[nBuffer])
3698 list.push_back(points);
3699 list[idx[nBuffer]][nBuffer] = nLine;