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 /////////////////////////////////////////////////////////////////////////////
8 * @file HexMergeView.cpp
10 * @brief Implementation file for CHexMergeView
15 #include "HexMergeFrm.h"
18 #include "HexMergeView.h"
19 #include "HexMergeDoc.h"
20 #include "OptionsDef.h"
21 #include "OptionsMgr.h"
22 #include "Environment.h"
28 /** @brief Location for hex compare specific help to open. */
29 static TCHAR HexMergeViewHelpLocation[] = _T("::/htmlhelp/Compare_bin.html");
32 * @brief Turn bool api result into success/error code
34 static HRESULT NTAPI SE(BOOL f)
38 HRESULT hr = (HRESULT)::GetLastError();
45 static UINT64 NTAPI GetLastWriteTime(HANDLE h)
48 return ::GetFileTime(h, 0, 0, reinterpret_cast<FILETIME *>(&ft)) ? ft : 0;
51 static void NTAPI SetLastWriteTime(HANDLE h, UINT64 ft)
53 ::SetFileTime(h, 0, 0, reinterpret_cast<FILETIME *>(&ft));
56 /////////////////////////////////////////////////////////////////////////////
59 IMPLEMENT_DYNCREATE(CHexMergeView, CView)
61 BEGIN_MESSAGE_MAP(CHexMergeView, CView)
62 //{{AFX_MSG_MAP(CHexMergeView)
63 ON_MESSAGE_VOID(WM_PAINT, CWnd::OnPaint)
69 ON_COMMAND(ID_HELP, OnHelp)
70 ON_COMMAND(ID_EDIT_FIND, OnEditFind)
71 ON_COMMAND(ID_EDIT_REPLACE, OnEditReplace)
72 ON_COMMAND(ID_EDIT_REPEAT, OnEditRepeat)
73 ON_UPDATE_COMMAND_UI(ID_EDIT_UNDO, OnUpdateEditUndo)
74 ON_COMMAND(ID_EDIT_UNDO, OnEditUndo)
75 ON_UPDATE_COMMAND_UI(ID_EDIT_REDO, OnUpdateEditRedo)
76 ON_COMMAND(ID_EDIT_REDO, OnEditRedo)
77 ON_COMMAND(ID_EDIT_CUT, OnEditCut)
78 ON_COMMAND(ID_EDIT_COPY, OnEditCopy)
79 ON_COMMAND(ID_EDIT_PASTE, OnEditPaste)
80 ON_COMMAND(ID_EDIT_CLEAR, OnEditClear)
81 ON_COMMAND(ID_EDIT_SELECT_ALL, OnEditSelectAll)
82 ON_COMMAND(ID_FIRSTDIFF, OnFirstdiff)
83 ON_COMMAND(ID_LASTDIFF, OnLastdiff)
84 ON_COMMAND(ID_NEXTDIFF, OnNextdiff)
85 ON_COMMAND(ID_PREVDIFF, OnPrevdiff)
87 // Test case to verify WM_COMMAND won't accidentally go through Default()
88 //ON_COMMAND(ID_APP_ABOUT, Default)
91 /////////////////////////////////////////////////////////////////////////////
92 // CHexMergeView construction/destruction
97 CHexMergeView::CHexMergeView()
100 , m_unpackerSubcode(0)
105 * @brief Drawing is not supported
107 void CHexMergeView::OnDraw(CDC *)
113 * @brief returns true if heksedit.dll is loadable
115 bool CHexMergeView::IsLoadable()
117 static void *pv = nullptr;
120 pv = LoadLibrary(_T("Frhed\\hekseditU.dll"));
122 return pv != nullptr;
126 * @brief Load heksedit.dll and setup window class name
128 BOOL CHexMergeView::PreCreateWindow(CREATESTRUCT& cs)
131 LangMessageBox(IDS_FRHED_NOTINSTALLED, MB_OK);
132 cs.lpszClass = _T("heksedit");
133 cs.style |= WS_HSCROLL | WS_VSCROLL;
138 * @brief Grab the control's IHexEditorWindow interface pointer upon window creation
140 int CHexMergeView::OnCreate(LPCREATESTRUCT lpCreateStruct)
142 if (CView::OnCreate(lpCreateStruct) == -1)
144 m_pif = reinterpret_cast<IHexEditorWindow *>(::GetWindowLongPtr(m_hWnd, GWLP_USERDATA));
145 if (m_pif == nullptr || m_pif->get_interface_version() < HEKSEDIT_INTERFACE_VERSION)
151 * @brief Skip default WM_NCCALCSIZE processing so as to prevent scrollbars from showing up
153 void CHexMergeView::OnNcCalcSize(BOOL, NCCALCSIZE_PARAMS *)
158 * @brief Synchronize all involved scrollbars
160 void CHexMergeView::OnHScroll(UINT nSBCode, UINT nPos, CScrollBar * pScrollBar)
163 if (pScrollBar && nSBCode == SB_THUMBTRACK)
165 pScrollBar->GetScrollInfo(&si, SIF_ALL | SIF_DISABLENOSCROLL);
166 si.nPos = si.nTrackPos;
167 SetScrollInfo(SB_HORZ, &si);
169 CView::OnHScroll(nSBCode, nPos, pScrollBar);
170 if (pScrollBar != nullptr)
172 GetScrollInfo(SB_HORZ, &si, SIF_ALL | SIF_DISABLENOSCROLL);
173 if (nSBCode != SB_THUMBTRACK)
175 pScrollBar->SetScrollInfo(&si);
178 CSplitterWndEx *pSplitter = static_cast<CSplitterWndEx *>(GetParentSplitter(this, TRUE));
179 for (int pane = 0; pane < pSplitter->GetColumnCount(); ++pane)
181 if (pane != m_nThisPane)
183 CWnd *pWnd = pSplitter->GetDlgItem(pSplitter->IdFromRowCol(0, pane));
184 pWnd->SetScrollInfo(SB_HORZ, &si);
185 pWnd->SendMessage(WM_HSCROLL, MAKEWPARAM(nSBCode, nPos));
192 * @brief Synchronize all involved scrollbars
194 void CHexMergeView::OnVScroll(UINT nSBCode, UINT nPos, CScrollBar * pScrollBar)
197 if (pScrollBar && nSBCode == SB_THUMBTRACK)
199 pScrollBar->GetScrollInfo(&si);
200 si.nPos = si.nTrackPos;
201 SetScrollInfo(SB_VERT, &si, SIF_ALL | SIF_DISABLENOSCROLL);
203 CView::OnVScroll(nSBCode, nPos, pScrollBar);
204 if (pScrollBar && nSBCode != SB_THUMBTRACK)
206 GetScrollInfo(SB_VERT, &si);
207 pScrollBar->SetScrollInfo(&si, SIF_ALL | SIF_DISABLENOSCROLL);
211 BOOL CHexMergeView::OnMouseWheel(UINT nFlags, short zDelta, CPoint pt)
213 if ((GetAsyncKeyState(VK_CONTROL) &0x8000) != 0) // if (nFlags & MK_CONTROL)
215 PostMessage(WM_COMMAND, zDelta < 0 ? ID_VIEW_ZOOMOUT : ID_VIEW_ZOOMIN);
222 * @brief Synchronize file path bar activation states
224 void CHexMergeView::OnActivateView(BOOL bActivate, CView* pActivateView, CView* pDeactiveView)
226 CView::OnActivateView(bActivate, pActivateView, pDeactiveView);
227 CHexMergeFrame *pFrameWnd = static_cast<CHexMergeFrame *>(GetParentFrame());
228 pFrameWnd->GetHeaderInterface()->SetActive(m_nThisPane, !!bActivate);
232 * @brief Get pointer to control's content buffer
234 BYTE *CHexMergeView::GetBuffer(int length)
236 return m_pif->get_buffer(length);
240 * @brief Get length of control's content buffer
242 int CHexMergeView::GetLength()
244 return m_pif->get_length();
248 * @brief Checks if file has changed since last update
249 * @param [in] path File to check
250 * @return `true` if file is changed.
252 IMergeDoc::FileChange CHexMergeView::IsFileChangedOnDisk(LPCTSTR path)
255 if (!dfi.Update(path))
256 return IMergeDoc::FileChange::Removed;
258 if (GetOptionsMgr()->GetBool(OPT_IGNORE_SMALL_FILETIME))
259 tolerance = SmallTimeDiff; // From MainFrm.h
260 int64_t timeDiff = dfi.mtime - m_fileInfo.mtime;
261 if (timeDiff < 0) timeDiff = -timeDiff;
262 if ((timeDiff > tolerance * Poco::Timestamp::resolution()) || (dfi.size != m_fileInfo.size))
263 return IMergeDoc::FileChange::Changed;
264 return IMergeDoc::FileChange::NoChange;
270 HRESULT CHexMergeView::LoadFile(LPCTSTR path)
272 CHexMergeDoc *pDoc = static_cast<CHexMergeDoc *>(GetDocument());
273 String strTempFileName = path;
274 if (!FileTransform::Unpacking(pDoc->GetUnpacker(), &m_unpackerSubcode, strTempFileName, path))
276 HANDLE h = CreateFile(strTempFileName.c_str(), GENERIC_READ,
277 FILE_SHARE_READ | FILE_SHARE_WRITE,
278 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
279 HRESULT hr = SE(h != INVALID_HANDLE_VALUE);
280 if (h == INVALID_HANDLE_VALUE)
282 DWORD length = GetFileSize(h, 0);
283 hr = SE(length != INVALID_FILE_SIZE);
286 if (void *buffer = GetBuffer(length))
289 hr = SE(ReadFile(h, buffer, length, &cb, 0) && cb == length);
293 else if (length != 0)
299 m_fileInfo.Update(path);
306 HRESULT CHexMergeView::SaveFile(LPCTSTR path, bool packing)
308 // Warn user in case file has been changed by someone else
309 if (IsFileChangedOnDisk(path) == IMergeDoc::FileChange::Changed)
311 String msg = strutils::format_string1(_("Another application has updated file\n%1\nsince WinMerge loaded it.\n\nOverwrite changed file?"), path);
312 if (AfxMessageBox(msg.c_str(), MB_ICONWARNING | MB_YESNO) == IDNO)
315 // Ask user what to do about FILE_ATTRIBUTE_READONLY
316 String strPath = path;
317 bool bApplyToAll = false;
318 if (CMergeApp::HandleReadonlySave(strPath, false, bApplyToAll) == IDCANCEL)
320 path = strPath.c_str();
321 // Take a chance to create a backup
322 if (!CMergeApp::CreateBackup(false, path))
324 // Write data to an intermediate file
325 String tempPath = env::GetTemporaryPath();
326 String sIntermediateFilename = env::GetTemporaryFileName(tempPath, _T("MRG_"), 0);
327 if (sIntermediateFilename.empty())
328 return E_FAIL; //Nothing to do if even tempfile name fails
329 HANDLE h = CreateFile(sIntermediateFilename.c_str(), GENERIC_WRITE, FILE_SHARE_READ,
330 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
331 HRESULT hr = SE(h != INVALID_HANDLE_VALUE);
332 if (h == INVALID_HANDLE_VALUE)
334 DWORD length = GetLength();
335 void *buffer = GetBuffer(length);
342 hr = SE(WriteFile(h, buffer, length, &cb, 0) && cb == length);
349 CHexMergeDoc* pDoc = static_cast<CHexMergeDoc*>(GetDocument());
350 if (!FileTransform::Packing(sIntermediateFilename, path, *pDoc->GetUnpacker(), m_unpackerSubcode))
352 String str = CMergeApp::GetPackingErrorMessage(m_nThisPane, pDoc->m_nBuffers, path, pDoc->GetUnpacker()->m_PluginName);
353 int answer = AfxMessageBox(str.c_str(), MB_OKCANCEL | MB_ICONWARNING);
356 pDoc->SaveAs(m_nThisPane, false);
364 hr = SE(CopyFile(sIntermediateFilename.c_str(), path, FALSE));
369 m_fileInfo.Update(path);
371 hr = SE(DeleteFile(sIntermediateFilename.c_str()));
374 LogErrorString(strutils::format(_T("DeleteFile(%s) failed: %s"),
375 sIntermediateFilename, GetSysError(hr)));
381 * @brief Get modified flag
383 bool CHexMergeView::GetModified()
385 return m_pif->get_status()->iFileChanged != 0;
389 * @brief Set modified flag
391 void CHexMergeView::SetSavePoint()
393 m_pif->set_savepoint();
397 * @brief Clear undo records
399 void CHexMergeView::ClearUndoRecords()
401 m_pif->clear_undorecords();
405 * @brief Get readonly flag
407 bool CHexMergeView::GetReadOnly()
409 return m_pif->get_settings()->bReadOnly;
413 * @brief Set readonly flag
415 void CHexMergeView::SetReadOnly(bool bReadOnly)
417 m_pif->get_settings()->bReadOnly = bReadOnly;
421 * @brief Allow the control to update all kinds of things that need to be updated when
422 * the window or content buffer have been resized or certain settings have been changed.
424 void CHexMergeView::ResizeWindow()
426 m_pif->resize_window();
430 * @brief Find a sequence of bytes
432 void CHexMergeView::OnEditFind()
438 * @brief Find & replace a sequence of bytes
440 void CHexMergeView::OnEditReplace()
442 m_pif->CMD_replace();
446 * @brief Repeat last find in one or another direction
448 void CHexMergeView::OnEditRepeat()
450 if (GetKeyState(VK_SHIFT) < 0)
451 m_pif->CMD_findprev();
453 m_pif->CMD_findnext();
457 * @brief Called when "Undo" item is updated
459 void CHexMergeView::OnUpdateEditUndo(CCmdUI* pCmdUI)
461 pCmdUI->Enable(m_pif->can_undo());
465 * @brief Undo last action
467 void CHexMergeView::OnEditUndo()
469 m_pif->CMD_edit_undo();
473 * @brief Called when "Redo" item is updated
475 void CHexMergeView::OnUpdateEditRedo(CCmdUI* pCmdUI)
477 pCmdUI->Enable(m_pif->can_redo());
481 * @brief Redo last action
483 void CHexMergeView::OnEditRedo()
485 m_pif->CMD_edit_redo();
489 * @brief Cut selected content
491 void CHexMergeView::OnEditCut()
493 m_pif->CMD_edit_cut();
497 * @brief Copy selected content
499 void CHexMergeView::OnEditCopy()
501 m_pif->CMD_edit_copy();
505 * @brief Paste clipboard content over selected content
507 void CHexMergeView::OnEditPaste()
509 m_pif->CMD_edit_paste();
513 * @brief Select entire content
515 void CHexMergeView::OnEditSelectAll()
517 m_pif->CMD_select_all();
521 * @brief Clear selected content
523 void CHexMergeView::OnEditClear()
525 m_pif->CMD_edit_clear();
529 * @brief Check for keyboard commands
531 BOOL CHexMergeView::PreTranslateMessage(MSG* pMsg)
533 if (GetTopLevelFrame()->PreTranslateMessage(pMsg))
535 if (pMsg->message == WM_KEYDOWN)
537 // Close window in response to VK_ESCAPE if user has allowed it from options
538 if (pMsg->wParam == VK_ESCAPE && GetOptionsMgr()->GetInt(OPT_CLOSE_WITH_ESC) != 0)
540 GetParentFrame()->PostMessage(WM_CLOSE, 0, 0);
544 return m_pif->translate_accelerator(pMsg);
548 * @brief Go to first diff
550 void CHexMergeView::OnFirstdiff()
552 m_pif->select_next_diff(TRUE);
556 * @brief Go to last diff
558 void CHexMergeView::OnLastdiff()
560 m_pif->select_prev_diff(TRUE);
564 * @brief Go to next diff
566 void CHexMergeView::OnNextdiff()
568 m_pif->select_next_diff(FALSE);
572 * @brief Go to previous diff
574 void CHexMergeView::OnPrevdiff()
576 m_pif->select_prev_diff(FALSE);
579 /** @brief Open help from mainframe when user presses F1*/
580 void CHexMergeView::OnHelp()
582 theApp.ShowHelp(HexMergeViewHelpLocation);
585 void CHexMergeView::ZoomText(int amount)
587 m_pif->CMD_zoom(amount);
591 * @brief Copy selected bytes from source view to destination view
592 * @note Grows destination buffer as appropriate
594 void CHexMergeView::CopySel(const CHexMergeView *src, CHexMergeView *dst)
596 dst->m_pif->copy_sel_from(src->m_pif);
600 * @brief Copy all bytes from source view to destination view
601 * @note Grows destination buffer as appropriate
603 void CHexMergeView::CopyAll(const CHexMergeView *src, CHexMergeView *dst)
605 dst->m_pif->copy_all_from(src->m_pif);