CommitDlg: Update index using libgit2 incrementally
[TortoiseGit.git] / src / TortoiseUDiff / MainWindow.cpp
blob3473e85d26dddd4615dc4a50df6bc99f6e40999e
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2012-2014 - TortoiseGit
4 // Copyright (C) 2003-2014 - TortoiseSVN
6 // This program is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU General Public License
8 // as published by the Free Software Foundation; either version 2
9 // of the License, or (at your option) any later version.
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // You should have received a copy of the GNU General Public License
17 // along with this program; if not, write to the Free Software Foundation,
18 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 #include "stdafx.h"
21 #include "TortoiseUDiff.h"
22 #include "MainWindow.h"
23 #include "UnicodeUtils.h"
24 #include "StringUtils.h"
25 #include "TaskbarUUID.h"
26 #include "CreateProcessHelper.h"
27 #include "SysInfo.h"
28 #include "UDiffColors.h"
29 #include "registry.h"
31 const UINT TaskBarButtonCreated = RegisterWindowMessage(L"TaskbarButtonCreated");
33 CMainWindow::CMainWindow(HINSTANCE hInst, const WNDCLASSEX* wcx /* = NULL*/)
34 : CWindow(hInst, wcx)
35 , m_bShowFindBar(false)
36 , m_directFunction(0)
37 , m_directPointer(0)
38 , m_hWndEdit(NULL)
39 , m_bMatchCase(false)
41 SetWindowTitle(_T("TortoiseGitUDiff"));
44 CMainWindow::~CMainWindow(void)
48 bool CMainWindow::RegisterAndCreateWindow()
50 WNDCLASSEX wcx;
52 // Fill in the window class structure with default parameters
53 wcx.cbSize = sizeof(WNDCLASSEX);
54 wcx.style = CS_HREDRAW | CS_VREDRAW;
55 wcx.lpfnWndProc = CWindow::stWinMsgHandler;
56 wcx.cbClsExtra = 0;
57 wcx.cbWndExtra = 0;
58 wcx.hInstance = hResource;
59 wcx.hCursor = NULL;
60 ResString clsname(hResource, IDS_APP_TITLE);
61 wcx.lpszClassName = clsname;
62 wcx.hIcon = LoadIcon(hResource, MAKEINTRESOURCE(IDI_TORTOISEUDIFF));
63 wcx.hbrBackground = (HBRUSH)(COLOR_3DFACE+1);
64 wcx.lpszMenuName = MAKEINTRESOURCE(IDC_TORTOISEUDIFF);
65 wcx.hIconSm = LoadIcon(wcx.hInstance, MAKEINTRESOURCE(IDI_TORTOISEUDIFF));
66 if (RegisterWindow(&wcx))
68 if (Create(WS_CAPTION | WS_MAXIMIZEBOX | WS_MINIMIZEBOX | WS_SIZEBOX | WS_SYSMENU | WS_CLIPCHILDREN, NULL))
70 m_FindBar.SetParent(*this);
71 m_FindBar.Create(::hResource, IDD_FINDBAR, *this);
72 UpdateWindow(*this);
73 return true;
76 return false;
79 LRESULT CALLBACK CMainWindow::WinMsgHandler(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
81 if (uMsg == TaskBarButtonCreated)
83 SetUUIDOverlayIcon(hwnd);
85 switch (uMsg)
87 case WM_CREATE:
89 m_hwnd = hwnd;
90 Initialize();
92 break;
93 case WM_COMMAND:
95 return DoCommand(LOWORD(wParam));
97 break;
98 case WM_MOUSEWHEEL:
100 if (GET_KEYSTATE_WPARAM(wParam) == MK_SHIFT)
102 // scroll sideways
103 SendEditor(SCI_LINESCROLL, -GET_WHEEL_DELTA_WPARAM(wParam)/40, 0);
105 else
106 return DefWindowProc(hwnd, uMsg, wParam, lParam);
108 break;
109 case WM_SIZE:
111 RECT rect;
112 GetClientRect(*this, &rect);
113 if (m_bShowFindBar)
115 ::SetWindowPos(m_hWndEdit, HWND_TOP,
116 rect.left, rect.top,
117 rect.right-rect.left, rect.bottom-rect.top-30,
118 SWP_SHOWWINDOW);
119 ::SetWindowPos(m_FindBar, HWND_TOP,
120 rect.left, rect.bottom-30,
121 rect.right-rect.left, 30,
122 SWP_SHOWWINDOW);
124 else
126 ::SetWindowPos(m_hWndEdit, HWND_TOP,
127 rect.left, rect.top,
128 rect.right-rect.left, rect.bottom-rect.top,
129 SWP_SHOWWINDOW);
130 ::ShowWindow(m_FindBar, SW_HIDE);
133 break;
134 case WM_GETMINMAXINFO:
136 MINMAXINFO * mmi = (MINMAXINFO*)lParam;
137 mmi->ptMinTrackSize.x = 100;
138 mmi->ptMinTrackSize.y = 100;
139 return 0;
141 break;
142 case WM_DESTROY:
143 PostQuitMessage(0);
144 break;
145 case WM_CLOSE:
146 ::DestroyWindow(m_hwnd);
147 break;
148 case WM_SETFOCUS:
149 SetFocus(m_hWndEdit);
150 break;
151 case COMMITMONITOR_FINDMSGNEXT:
153 SendEditor(SCI_CHARRIGHT);
154 SendEditor(SCI_SEARCHANCHOR);
155 m_bMatchCase = !!wParam;
156 m_findtext = (LPCTSTR)lParam;
157 SendEditor(SCI_SEARCHNEXT, m_bMatchCase ? SCFIND_MATCHCASE : 0, (LPARAM)CUnicodeUtils::StdGetUTF8(m_findtext).c_str());
158 SendEditor(SCI_SCROLLCARET);
160 break;
161 case COMMITMONITOR_FINDMSGPREV:
163 SendEditor(SCI_SEARCHANCHOR);
164 m_bMatchCase = !!wParam;
165 m_findtext = (LPCTSTR)lParam;
166 SendEditor(SCI_SEARCHPREV, m_bMatchCase ? SCFIND_MATCHCASE : 0, (LPARAM)CUnicodeUtils::StdGetUTF8(m_findtext).c_str());
167 SendEditor(SCI_SCROLLCARET);
169 break;
170 case COMMITMONITOR_FINDEXIT:
172 RECT rect;
173 GetClientRect(*this, &rect);
174 m_bShowFindBar = false;
175 ::ShowWindow(m_FindBar, SW_HIDE);
176 ::SetWindowPos(m_hWndEdit, HWND_TOP,
177 rect.left, rect.top,
178 rect.right-rect.left, rect.bottom-rect.top,
179 SWP_SHOWWINDOW);
181 break;
182 case COMMITMONITOR_FINDRESET:
183 SendEditor(SCI_SETSELECTIONSTART, 0);
184 SendEditor(SCI_SETSELECTIONEND, 0);
185 SendEditor(SCI_SEARCHANCHOR);
186 break;
187 default:
188 return DefWindowProc(hwnd, uMsg, wParam, lParam);
191 return 0;
194 LRESULT CMainWindow::DoCommand(int id)
196 switch (id)
198 case ID_FILE_OPEN:
199 loadOrSaveFile(true);
200 break;
201 case ID_FILE_SAVEAS:
202 loadOrSaveFile(false);
203 break;
204 case ID_FILE_SAVE:
205 loadOrSaveFile(false, m_filename);
206 break;
207 case ID_FILE_EXIT:
208 ::PostQuitMessage(0);
209 return 0;
210 case IDM_SHOWFINDBAR:
212 m_bShowFindBar = true;
213 ::ShowWindow(m_FindBar, SW_SHOW);
214 RECT rect;
215 GetClientRect(*this, &rect);
216 ::SetWindowPos(m_hWndEdit, HWND_TOP,
217 rect.left, rect.top,
218 rect.right-rect.left, rect.bottom-rect.top-30,
219 SWP_SHOWWINDOW);
220 ::SetWindowPos(m_FindBar, HWND_TOP,
221 rect.left, rect.bottom-30,
222 rect.right-rect.left, 30,
223 SWP_SHOWWINDOW);
224 ::SetFocus(m_FindBar);
225 SendEditor(SCI_SETSELECTIONSTART, 0);
226 SendEditor(SCI_SETSELECTIONEND, 0);
227 SendEditor(SCI_SEARCHANCHOR);
229 break;
230 case IDM_FINDNEXT:
231 SendEditor(SCI_SEARCHANCHOR);
232 SendEditor(SCI_SEARCHNEXT, m_bMatchCase ? SCFIND_MATCHCASE : 0, (LPARAM)CUnicodeUtils::StdGetUTF8(m_findtext).c_str());
233 SendEditor(SCI_SCROLLCARET);
234 break;
235 case IDM_FINDPREV:
236 SendEditor(SCI_SEARCHANCHOR);
237 SendEditor(SCI_SEARCHPREV, m_bMatchCase ? SCFIND_MATCHCASE : 0, (LPARAM)CUnicodeUtils::StdGetUTF8(m_findtext).c_str());
238 SendEditor(SCI_SCROLLCARET);
239 break;
240 case IDM_FINDEXIT:
241 if (IsWindowVisible(m_FindBar))
243 RECT rect;
244 GetClientRect(*this, &rect);
245 m_bShowFindBar = false;
246 ::ShowWindow(m_FindBar, SW_HIDE);
247 ::SetWindowPos(m_hWndEdit, HWND_TOP,
248 rect.left, rect.top,
249 rect.right-rect.left, rect.bottom-rect.top,
250 SWP_SHOWWINDOW);
252 else
253 PostQuitMessage(0);
254 break;
255 case ID_FILE_SETTINGS:
257 tstring gitCmd = _T(" /command:settings /page:udiff");
258 RunCommand(gitCmd);
260 break;
261 case ID_FILE_APPLYPATCH:
263 std::wstring command = L" /diff:\"";
264 command += m_filename;
265 command += L"\"";
266 std::wstring tortoiseMergePath = GetAppDirectory() + _T("TortoiseGitMerge.exe");
267 CCreateProcessHelper::CreateProcessDetached(tortoiseMergePath.c_str(), const_cast<TCHAR*>(command.c_str()));
269 break;
270 case ID_FILE_PAGESETUP:
272 TCHAR localeInfo[3] = { 0 };
273 GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_IMEASURE, localeInfo, 3);
274 // Metric system. '1' is US System
275 int defaultMargin = localeInfo[0] == '0' ? 2540 : 1000;
277 PAGESETUPDLG pdlg = {0};
278 pdlg.lStructSize = sizeof(PAGESETUPDLG);
279 pdlg.hwndOwner = *this;
280 pdlg.hInstance = NULL;
281 pdlg.Flags = PSD_DEFAULTMINMARGINS|PSD_MARGINS|PSD_DISABLEPAPER|PSD_DISABLEORIENTATION;
282 if (localeInfo[0] == '0')
283 pdlg.Flags |= PSD_INHUNDREDTHSOFMILLIMETERS;
285 CRegStdDWORD m_regMargLeft = CRegStdDWORD(L"Software\\TortoiseGit\\UDiffpagesetupmarginleft", defaultMargin);
286 CRegStdDWORD m_regMargTop = CRegStdDWORD(L"Software\\TortoiseGit\\UDiffpagesetupmargintop", defaultMargin);
287 CRegStdDWORD m_regMargRight = CRegStdDWORD(L"Software\\TortoiseGit\\UDiffpagesetupmarginright", defaultMargin);
288 CRegStdDWORD m_regMargBottom = CRegStdDWORD(L"Software\\TortoiseGit\\UDiffpagesetupmarginbottom", defaultMargin);
290 pdlg.rtMargin.left = (long)(DWORD)m_regMargLeft;
291 pdlg.rtMargin.top = (long)(DWORD)m_regMargTop;
292 pdlg.rtMargin.right = (long)(DWORD)m_regMargRight;
293 pdlg.rtMargin.bottom = (long)(DWORD)m_regMargBottom;
295 if (!PageSetupDlg(&pdlg))
296 return false;
298 m_regMargLeft = pdlg.rtMargin.left;
299 m_regMargTop = pdlg.rtMargin.top;
300 m_regMargRight = pdlg.rtMargin.right;
301 m_regMargBottom = pdlg.rtMargin.bottom;
303 break;
304 case ID_FILE_PRINT:
306 PRINTDLGEX pdlg = {0};
307 pdlg.lStructSize = sizeof(PRINTDLGEX);
308 pdlg.hwndOwner = *this;
309 pdlg.hInstance = NULL;
310 pdlg.Flags = PD_USEDEVMODECOPIESANDCOLLATE | PD_ALLPAGES | PD_RETURNDC | PD_NOCURRENTPAGE | PD_NOPAGENUMS;
311 pdlg.nMinPage = 1;
312 pdlg.nMaxPage = 0xffffU; // We do not know how many pages in the document
313 pdlg.nCopies = 1;
314 pdlg.hDC = 0;
315 pdlg.nStartPage = START_PAGE_GENERAL;
317 // See if a range has been selected
318 size_t startPos = SendEditor(SCI_GETSELECTIONSTART);
319 size_t endPos = SendEditor(SCI_GETSELECTIONEND);
321 if (startPos == endPos)
322 pdlg.Flags |= PD_NOSELECTION;
323 else
324 pdlg.Flags |= PD_SELECTION;
326 HRESULT hResult = PrintDlgEx(&pdlg);
327 if ((hResult != S_OK) || (pdlg.dwResultAction != PD_RESULT_PRINT))
328 return 0;
330 // reset all indicators
331 size_t endpos = SendEditor(SCI_GETLENGTH);
332 for (int i = INDIC_CONTAINER; i <= INDIC_MAX; ++i)
334 SendEditor(SCI_SETINDICATORCURRENT, i);
335 SendEditor(SCI_INDICATORCLEARRANGE, 0, endpos);
337 // store and reset UI settings
338 int viewws = (int)SendEditor(SCI_GETVIEWWS);
339 SendEditor(SCI_SETVIEWWS, 0);
340 int edgemode = (int)SendEditor(SCI_GETEDGEMODE);
341 SendEditor(SCI_SETEDGEMODE, EDGE_NONE);
342 SendEditor(SCI_SETWRAPVISUALFLAGS, SC_WRAPVISUALFLAG_END);
344 HDC hdc = pdlg.hDC;
346 RECT rectMargins, rectPhysMargins;
347 POINT ptPage;
348 POINT ptDpi;
350 // Get printer resolution
351 ptDpi.x = GetDeviceCaps(hdc, LOGPIXELSX); // dpi in X direction
352 ptDpi.y = GetDeviceCaps(hdc, LOGPIXELSY); // dpi in Y direction
354 // Start by getting the physical page size (in device units).
355 ptPage.x = GetDeviceCaps(hdc, PHYSICALWIDTH); // device units
356 ptPage.y = GetDeviceCaps(hdc, PHYSICALHEIGHT); // device units
358 // Get the dimensions of the unprintable
359 // part of the page (in device units).
360 rectPhysMargins.left = GetDeviceCaps(hdc, PHYSICALOFFSETX);
361 rectPhysMargins.top = GetDeviceCaps(hdc, PHYSICALOFFSETY);
363 // To get the right and lower unprintable area,
364 // we take the entire width and height of the paper and
365 // subtract everything else.
366 rectPhysMargins.right = ptPage.x // total paper width
367 - GetDeviceCaps(hdc, HORZRES) // printable width
368 - rectPhysMargins.left; // left unprintable margin
370 rectPhysMargins.bottom = ptPage.y // total paper height
371 - GetDeviceCaps(hdc, VERTRES) // printable height
372 - rectPhysMargins.top; // right unprintable margin
374 TCHAR localeInfo[3] = { 0 };
375 GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_IMEASURE, localeInfo, 3);
376 // Metric system. '1' is US System
377 int defaultMargin = localeInfo[0] == '0' ? 2540 : 1000;
378 RECT pagesetupMargin;
379 CRegStdDWORD m_regMargLeft = CRegStdDWORD(L"Software\\TortoiseGit\\UDiffpagesetupmarginleft", defaultMargin);
380 CRegStdDWORD m_regMargTop = CRegStdDWORD(L"Software\\TortoiseGit\\UDiffpagesetupmargintop", defaultMargin);
381 CRegStdDWORD m_regMargRight = CRegStdDWORD(L"Software\\TortoiseGit\\UDiffpagesetupmarginright", defaultMargin);
382 CRegStdDWORD m_regMargBottom = CRegStdDWORD(L"Software\\TortoiseGit\\UDiffpagesetupmarginbottom", defaultMargin);
384 pagesetupMargin.left = (long)(DWORD)m_regMargLeft;
385 pagesetupMargin.top = (long)(DWORD)m_regMargTop;
386 pagesetupMargin.right = (long)(DWORD)m_regMargRight;
387 pagesetupMargin.bottom = (long)(DWORD)m_regMargBottom;
389 if (pagesetupMargin.left != 0 || pagesetupMargin.right != 0 ||
390 pagesetupMargin.top != 0 || pagesetupMargin.bottom != 0)
392 RECT rectSetup;
394 // Convert the hundredths of millimeters (HiMetric) or
395 // thousandths of inches (HiEnglish) margin values
396 // from the Page Setup dialog to device units.
397 // (There are 2540 hundredths of a mm in an inch.)
398 if (localeInfo[0] == '0')
400 // Metric system. '1' is US System
401 rectSetup.left = MulDiv (pagesetupMargin.left, ptDpi.x, 2540);
402 rectSetup.top = MulDiv (pagesetupMargin.top, ptDpi.y, 2540);
403 rectSetup.right = MulDiv(pagesetupMargin.right, ptDpi.x, 2540);
404 rectSetup.bottom = MulDiv(pagesetupMargin.bottom, ptDpi.y, 2540);
406 else
408 rectSetup.left = MulDiv(pagesetupMargin.left, ptDpi.x, 1000);
409 rectSetup.top = MulDiv(pagesetupMargin.top, ptDpi.y, 1000);
410 rectSetup.right = MulDiv(pagesetupMargin.right, ptDpi.x, 1000);
411 rectSetup.bottom = MulDiv(pagesetupMargin.bottom, ptDpi.y, 1000);
414 // Don't reduce margins below the minimum printable area
415 rectMargins.left = max(rectPhysMargins.left, rectSetup.left);
416 rectMargins.top = max(rectPhysMargins.top, rectSetup.top);
417 rectMargins.right = max(rectPhysMargins.right, rectSetup.right);
418 rectMargins.bottom = max(rectPhysMargins.bottom, rectSetup.bottom);
420 else
422 rectMargins.left = rectPhysMargins.left;
423 rectMargins.top = rectPhysMargins.top;
424 rectMargins.right = rectPhysMargins.right;
425 rectMargins.bottom = rectPhysMargins.bottom;
428 // rectMargins now contains the values used to shrink the printable
429 // area of the page.
431 // Convert device coordinates into logical coordinates
432 DPtoLP(hdc, (LPPOINT) &rectMargins, 2);
433 DPtoLP(hdc, (LPPOINT)&rectPhysMargins, 2);
435 // Convert page size to logical units and we're done!
436 DPtoLP(hdc, (LPPOINT) &ptPage, 1);
439 DOCINFO di = {sizeof(DOCINFO), 0, 0, 0, 0};
440 di.lpszDocName = m_filename.c_str();
441 di.lpszOutput = 0;
442 di.lpszDatatype = 0;
443 di.fwType = 0;
444 if (::StartDoc(hdc, &di) < 0)
446 ::DeleteDC(hdc);
447 return 0;
450 size_t lengthDoc = SendEditor(SCI_GETLENGTH);
451 size_t lengthDocMax = lengthDoc;
452 size_t lengthPrinted = 0;
454 // Requested to print selection
455 if (pdlg.Flags & PD_SELECTION)
457 if (startPos > endPos)
459 lengthPrinted = endPos;
460 lengthDoc = startPos;
462 else
464 lengthPrinted = startPos;
465 lengthDoc = endPos;
468 if (lengthDoc > lengthDocMax)
469 lengthDoc = lengthDocMax;
472 // We must subtract the physical margins from the printable area
473 Sci_RangeToFormat frPrint;
474 frPrint.hdc = hdc;
475 frPrint.hdcTarget = hdc;
476 frPrint.rc.left = rectMargins.left - rectPhysMargins.left;
477 frPrint.rc.top = rectMargins.top - rectPhysMargins.top;
478 frPrint.rc.right = ptPage.x - rectMargins.right - rectPhysMargins.left;
479 frPrint.rc.bottom = ptPage.y - rectMargins.bottom - rectPhysMargins.top;
480 frPrint.rcPage.left = 0;
481 frPrint.rcPage.top = 0;
482 frPrint.rcPage.right = ptPage.x - rectPhysMargins.left - rectPhysMargins.right - 1;
483 frPrint.rcPage.bottom = ptPage.y - rectPhysMargins.top - rectPhysMargins.bottom - 1;
485 // Print each page
486 while (lengthPrinted < lengthDoc)
488 ::StartPage(hdc);
490 frPrint.chrg.cpMin = (long)lengthPrinted;
491 frPrint.chrg.cpMax = (long)lengthDoc;
493 lengthPrinted = SendEditor(SCI_FORMATRANGE, true, reinterpret_cast<LPARAM>(&frPrint));
495 ::EndPage(hdc);
498 SendEditor(SCI_FORMATRANGE, FALSE, 0);
500 ::EndDoc(hdc);
501 ::DeleteDC(hdc);
503 if (pdlg.hDevMode != NULL)
504 GlobalFree(pdlg.hDevMode);
505 if (pdlg.hDevNames != NULL)
506 GlobalFree(pdlg.hDevNames);
507 if (pdlg.lpPageRanges != NULL)
508 GlobalFree(pdlg.lpPageRanges);
510 // reset the UI
511 SendEditor(SCI_SETVIEWWS, viewws);
512 SendEditor(SCI_SETEDGEMODE, edgemode);
513 SendEditor(SCI_SETWRAPVISUALFLAGS, SC_WRAPVISUALFLAG_NONE);
515 break;
516 default:
517 break;
519 return 1;
522 std::wstring CMainWindow::GetAppDirectory()
524 std::wstring path;
525 DWORD len = 0;
526 DWORD bufferlen = MAX_PATH; // MAX_PATH is not the limit here!
529 bufferlen += MAX_PATH; // MAX_PATH is not the limit here!
530 std::unique_ptr<TCHAR[]> pBuf(new TCHAR[bufferlen]);
531 len = GetModuleFileName(NULL, pBuf.get(), bufferlen);
532 path = std::wstring(pBuf.get(), len);
533 } while(len == bufferlen);
534 path = path.substr(0, path.rfind('\\') + 1);
536 return path;
539 void CMainWindow::RunCommand(const std::wstring& command)
541 tstring tortoiseProcPath = GetAppDirectory() + _T("TortoiseGitProc.exe");
542 CCreateProcessHelper::CreateProcessDetached(tortoiseProcPath.c_str(), const_cast<TCHAR*>(command.c_str()));
545 LRESULT CMainWindow::SendEditor(UINT Msg, WPARAM wParam, LPARAM lParam)
547 if (m_directFunction)
549 return ((SciFnDirect) m_directFunction)(m_directPointer, Msg, wParam, lParam);
551 return ::SendMessage(m_hWndEdit, Msg, wParam, lParam);
554 bool CMainWindow::Initialize()
556 m_hWndEdit = ::CreateWindow(
557 _T("Scintilla"),
558 _T("Source"),
559 WS_CHILD | WS_VSCROLL | WS_HSCROLL | WS_CLIPCHILDREN,
560 CW_USEDEFAULT, CW_USEDEFAULT,
561 CW_USEDEFAULT, CW_USEDEFAULT,
562 *this,
564 hResource,
566 if (m_hWndEdit == NULL)
567 return false;
569 RECT rect;
570 GetClientRect(*this, &rect);
571 ::SetWindowPos(m_hWndEdit, HWND_TOP,
572 rect.left, rect.top,
573 rect.right-rect.left, rect.bottom-rect.top,
574 SWP_SHOWWINDOW);
576 m_directFunction = SendMessage(m_hWndEdit, SCI_GETDIRECTFUNCTION, 0, 0);
577 m_directPointer = SendMessage(m_hWndEdit, SCI_GETDIRECTPOINTER, 0, 0);
579 // Set up the global default style. These attributes are used wherever no explicit choices are made.
580 SetAStyle(STYLE_DEFAULT, ::GetSysColor(COLOR_WINDOWTEXT), ::GetSysColor(COLOR_WINDOW),
581 CRegStdDWORD(L"Software\\TortoiseGit\\UDiffFontSize", 10),
582 CUnicodeUtils::StdGetUTF8(CRegStdString(L"Software\\TortoiseGit\\UDiffFontName", L"Courier New")).c_str());
583 SendEditor(SCI_SETTABWIDTH, CRegStdDWORD(L"Software\\TortoiseGit\\UDiffTabSize", 4));
584 SendEditor(SCI_SETREADONLY, TRUE);
585 LRESULT pix = SendEditor(SCI_TEXTWIDTH, STYLE_LINENUMBER, (LPARAM)"_99999");
586 SendEditor(SCI_SETMARGINWIDTHN, 0, pix);
587 SendEditor(SCI_SETMARGINWIDTHN, 1);
588 SendEditor(SCI_SETMARGINWIDTHN, 2);
589 //Set the default windows colors for edit controls
590 SendEditor(SCI_STYLESETFORE, STYLE_DEFAULT, ::GetSysColor(COLOR_WINDOWTEXT));
591 SendEditor(SCI_STYLESETBACK, STYLE_DEFAULT, ::GetSysColor(COLOR_WINDOW));
592 SendEditor(SCI_SETSELFORE, TRUE, ::GetSysColor(COLOR_HIGHLIGHTTEXT));
593 SendEditor(SCI_SETSELBACK, TRUE, ::GetSysColor(COLOR_HIGHLIGHT));
594 SendEditor(SCI_SETCARETFORE, ::GetSysColor(COLOR_WINDOWTEXT));
595 CRegStdDWORD used2d(L"Software\\TortoiseGit\\ScintillaDirect2D", FALSE);
596 if (SysInfo::Instance().IsWin7OrLater() && DWORD(used2d))
598 SendEditor(SCI_SETTECHNOLOGY, SC_TECHNOLOGY_DIRECTWRITERETAIN);
599 SendEditor(SCI_SETBUFFEREDDRAW, 0);
601 SendEditor(SCI_SETVIEWWS, 1);
602 SendEditor(SCI_SETWHITESPACESIZE, 2);
603 SendEditor(SCI_SETWHITESPACEFORE, true, ::GetSysColor(COLOR_3DSHADOW));
604 SendEditor(SCI_STYLESETVISIBLE, STYLE_CONTROLCHAR, TRUE);
606 return true;
609 bool CMainWindow::LoadFile(HANDLE hFile)
611 InitEditor();
612 char data[4096] = { 0 };
613 DWORD dwRead = 0;
615 BOOL bRet = ReadFile(hFile, data, sizeof(data), &dwRead, NULL);
616 bool bUTF8 = IsUTF8(data, dwRead);
617 while ((dwRead > 0) && (bRet))
619 SendEditor(SCI_ADDTEXT, dwRead,
620 reinterpret_cast<LPARAM>(static_cast<char *>(data)));
621 bRet = ReadFile(hFile, data, sizeof(data), &dwRead, NULL);
623 SetupWindow(bUTF8);
624 return true;
627 bool CMainWindow::LoadFile(LPCTSTR filename)
629 InitEditor();
630 FILE *fp = NULL;
631 _tfopen_s(&fp, filename, _T("rb"));
632 if (!fp)
633 return false;
635 //SetTitle();
636 char data[4096] = { 0 };
637 size_t lenFile = fread(data, 1, sizeof(data), fp);
638 bool bUTF8 = IsUTF8(data, lenFile);
639 while (lenFile > 0)
641 SendEditor(SCI_ADDTEXT, lenFile,
642 reinterpret_cast<LPARAM>(static_cast<char *>(data)));
643 lenFile = fread(data, 1, sizeof(data), fp);
645 fclose(fp);
646 SetupWindow(bUTF8);
647 m_filename = filename;
648 return true;
651 void CMainWindow::InitEditor()
653 SendEditor(SCI_SETREADONLY, FALSE);
654 SendEditor(SCI_CLEARALL);
655 SendEditor(EM_EMPTYUNDOBUFFER);
656 SendEditor(SCI_SETSAVEPOINT);
657 SendEditor(SCI_CANCEL);
658 SendEditor(SCI_SETUNDOCOLLECTION, 0);
661 void CMainWindow::SetupWindow(bool bUTF8)
663 SendEditor(SCI_SETCODEPAGE, bUTF8 ? SC_CP_UTF8 : GetACP());
665 SendEditor(SCI_SETUNDOCOLLECTION, 1);
666 ::SetFocus(m_hWndEdit);
667 SendEditor(EM_EMPTYUNDOBUFFER);
668 SendEditor(SCI_SETSAVEPOINT);
669 SendEditor(SCI_GOTOPOS, 0);
671 SendEditor(SCI_CLEARDOCUMENTSTYLE, 0, 0);
672 SendEditor(SCI_SETSTYLEBITS, 5, 0);
674 HIGHCONTRAST highContrast = { 0 };
675 highContrast.cbSize = sizeof(HIGHCONTRAST);
676 if (SystemParametersInfo(SPI_GETHIGHCONTRAST, 0, &highContrast, 0) == TRUE && (highContrast.dwFlags & HCF_HIGHCONTRASTON))
677 return;
679 //SetAStyle(SCE_DIFF_DEFAULT, RGB(0, 0, 0));
680 SetAStyle(SCE_DIFF_COMMAND,
681 CRegStdDWORD(L"Software\\TortoiseGit\\UDiffForeCommandColor", UDIFF_COLORFORECOMMAND),
682 CRegStdDWORD(L"Software\\TortoiseGit\\UDiffBackCommandColor", UDIFF_COLORBACKCOMMAND));
683 SetAStyle(SCE_DIFF_POSITION,
684 CRegStdDWORD(L"Software\\TortoiseGit\\UDiffForePositionColor", UDIFF_COLORFOREPOSITION),
685 CRegStdDWORD(L"Software\\TortoiseGit\\UDiffBackPositionColor", UDIFF_COLORBACKPOSITION));
686 SetAStyle(SCE_DIFF_HEADER,
687 CRegStdDWORD(L"Software\\TortoiseGit\\UDiffForeHeaderColor", UDIFF_COLORFOREHEADER),
688 CRegStdDWORD(L"Software\\TortoiseGit\\UDiffBackHeaderColor", UDIFF_COLORBACKHEADER));
689 SetAStyle(SCE_DIFF_COMMENT,
690 CRegStdDWORD(L"Software\\TortoiseGit\\UDiffForeCommentColor", UDIFF_COLORFORECOMMENT),
691 CRegStdDWORD(L"Software\\TortoiseGit\\UDiffBackCommentColor", UDIFF_COLORBACKCOMMENT));
692 SendEditor(SCI_STYLESETBOLD, SCE_DIFF_COMMENT, TRUE);
694 SetAStyle(SCE_DIFF_ADDED,
695 CRegStdDWORD(L"Software\\TortoiseGit\\UDiffForeAddedColor", UDIFF_COLORFOREADDED),
696 CRegStdDWORD(L"Software\\TortoiseGit\\UDiffBackAddedColor", UDIFF_COLORBACKADDED));
697 SetAStyle(SCE_DIFF_DELETED,
698 CRegStdDWORD(L"Software\\TortoiseGit\\UDiffForeRemovedColor", UDIFF_COLORFOREREMOVED),
699 CRegStdDWORD(L"Software\\TortoiseGit\\UDiffBackRemovedColor", UDIFF_COLORBACKREMOVED));
701 SendEditor(SCI_SETLEXER, SCLEX_DIFF);
702 SendEditor(SCI_SETKEYWORDS, 0, (LPARAM)"revision");
703 SendEditor(SCI_COLOURISE, 0, -1);
704 ::ShowWindow(m_hWndEdit, SW_SHOW);
707 bool CMainWindow::SaveFile(LPCTSTR filename)
709 FILE *fp = NULL;
710 _tfopen_s(&fp, filename, _T("w+b"));
711 if (!fp)
712 return false;
714 LRESULT len = SendEditor(SCI_GETTEXT, 0, 0);
715 std::unique_ptr<char[]> data (new char[len+1]);
716 SendEditor(SCI_GETTEXT, len, reinterpret_cast<LPARAM>(static_cast<char *>(data.get())));
717 fwrite(data.get(), sizeof(char), len-1, fp);
718 fclose(fp);
720 SendEditor(SCI_SETSAVEPOINT);
721 ::ShowWindow(m_hWndEdit, SW_SHOW);
722 return true;
725 void CMainWindow::SetTitle(LPCTSTR title)
727 size_t len = _tcslen(title);
728 std::unique_ptr<TCHAR[]> pBuf(new TCHAR[len + 40]);
729 _stprintf_s(pBuf.get(), len + 40, _T("%s - TortoiseGitUDiff"), title);
730 SetWindowTitle(std::wstring(pBuf.get()));
733 void CMainWindow::SetAStyle(int style, COLORREF fore, COLORREF back, int size, const char *face)
735 SendEditor(SCI_STYLESETFORE, style, fore);
736 SendEditor(SCI_STYLESETBACK, style, back);
737 if (size >= 1)
738 SendEditor(SCI_STYLESETSIZE, style, size);
739 if (face)
740 SendEditor(SCI_STYLESETFONT, style, reinterpret_cast<LPARAM>(face));
743 bool CMainWindow::IsUTF8(LPVOID pBuffer, size_t cb)
745 if (cb < 2)
746 return true;
747 UINT16 * pVal16 = (UINT16 *)pBuffer;
748 UINT8 * pVal8 = (UINT8 *)(pVal16+1);
749 // scan the whole buffer for a 0x0000 sequence
750 // if found, we assume a binary file
751 for (size_t i=0; i<(cb-2); i=i+2)
753 if (0x0000 == *pVal16++)
754 return false;
756 pVal16 = (UINT16 *)pBuffer;
757 if (*pVal16 == 0xFEFF)
758 return false;
759 if (cb < 3)
760 return false;
761 if (*pVal16 == 0xBBEF)
763 if (*pVal8 == 0xBF)
764 return true;
766 // check for illegal UTF8 chars
767 pVal8 = (UINT8 *)pBuffer;
768 for (size_t i=0; i<cb; ++i)
770 if ((*pVal8 == 0xC0)||(*pVal8 == 0xC1)||(*pVal8 >= 0xF5))
771 return false;
772 pVal8++;
774 pVal8 = (UINT8 *)pBuffer;
775 bool bUTF8 = false;
776 for (size_t i=0; i<(cb-3); ++i)
778 if ((*pVal8 & 0xE0)==0xC0)
780 pVal8++;i++;
781 if ((*pVal8 & 0xC0)!=0x80)
782 return false;
783 bUTF8 = true;
785 else if ((*pVal8 & 0xF0)==0xE0)
787 pVal8++;i++;
788 if ((*pVal8 & 0xC0)!=0x80)
789 return false;
790 pVal8++;i++;
791 if ((*pVal8 & 0xC0)!=0x80)
792 return false;
793 bUTF8 = true;
795 else if ((*pVal8 & 0xF8)==0xF0)
797 pVal8++;i++;
798 if ((*pVal8 & 0xC0)!=0x80)
799 return false;
800 pVal8++;i++;
801 if ((*pVal8 & 0xC0)!=0x80)
802 return false;
803 pVal8++;i++;
804 if ((*pVal8 & 0xC0)!=0x80)
805 return false;
806 bUTF8 = true;
808 else if (*pVal8 >= 0x80)
809 return false;
811 pVal8++;
813 if (bUTF8)
814 return true;
815 return false;
818 void CMainWindow::loadOrSaveFile(bool doLoad, const std::wstring& filename /* = L"" */)
820 OPENFILENAME ofn = {0}; // common dialog box structure
821 TCHAR szFile[MAX_PATH] = {0}; // buffer for file name
822 // Initialize OPENFILENAME
823 ofn.lStructSize = sizeof(OPENFILENAME);
824 ofn.hwndOwner = *this;
825 ofn.lpstrFile = szFile;
826 ofn.nMaxFile = sizeof(szFile)/sizeof(TCHAR);
827 TCHAR filter[1024] = { 0 };
828 LoadString(::hResource, IDS_PATCHFILEFILTER, filter, sizeof(filter)/sizeof(TCHAR));
829 CStringUtils::PipesToNulls(filter);
830 ofn.lpstrFilter = filter;
831 ofn.nFilterIndex = 1;
832 ofn.lpstrFileTitle = NULL;
833 ofn.nMaxFileTitle = 0;
834 ofn.lpstrInitialDir = NULL;
835 TCHAR fileTitle[1024] = { 0 };
836 LoadString(::hResource, doLoad ? IDS_OPENPATCH : IDS_SAVEPATCH, fileTitle, sizeof(fileTitle)/sizeof(TCHAR));
837 ofn.lpstrTitle = fileTitle;
838 ofn.Flags = OFN_ENABLESIZING | OFN_EXPLORER;
839 if(doLoad)
840 ofn.Flags |= OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
841 else
842 ofn.Flags |= OFN_OVERWRITEPROMPT;
843 // Display the Open dialog box.
844 if( doLoad )
846 if (GetOpenFileName(&ofn)==TRUE)
848 LoadFile(ofn.lpstrFile);
851 else
853 if (filename.empty())
855 if (GetSaveFileName(&ofn)==TRUE)
857 SaveFile(ofn.lpstrFile);
860 else
861 SaveFile(filename.c_str());