Use constants
[TortoiseGit.git] / src / TortoiseUDiff / MainWindow.cpp
blob2122fbf06cee94c41d57d6e537cc63d79c0dc555
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2012-2013 - 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 "MainWindow.h"
22 #include "UnicodeUtils.h"
23 #include "StringUtils.h"
24 #include "TaskbarUUID.h"
25 #include "CreateProcessHelper.h"
26 #include "SysInfo.h"
28 const UINT TaskBarButtonCreated = RegisterWindowMessage(L"TaskbarButtonCreated");
30 CMainWindow::CMainWindow(HINSTANCE hInst, const WNDCLASSEX* wcx /* = NULL*/)
31 : CWindow(hInst, wcx)
32 , m_bShowFindBar(false)
33 , m_directFunction(0)
34 , m_directPointer(0)
35 , m_hWndEdit(NULL)
36 , m_bMatchCase(false)
38 SetWindowTitle(_T("TortoiseGitUDiff"));
41 CMainWindow::~CMainWindow(void)
45 bool CMainWindow::RegisterAndCreateWindow()
47 WNDCLASSEX wcx;
49 // Fill in the window class structure with default parameters
50 wcx.cbSize = sizeof(WNDCLASSEX);
51 wcx.style = CS_HREDRAW | CS_VREDRAW;
52 wcx.lpfnWndProc = CWindow::stWinMsgHandler;
53 wcx.cbClsExtra = 0;
54 wcx.cbWndExtra = 0;
55 wcx.hInstance = hResource;
56 wcx.hCursor = NULL;
57 ResString clsname(hResource, IDS_APP_TITLE);
58 wcx.lpszClassName = clsname;
59 wcx.hIcon = LoadIcon(hResource, MAKEINTRESOURCE(IDI_TORTOISEUDIFF));
60 wcx.hbrBackground = (HBRUSH)(COLOR_3DFACE+1);
61 wcx.lpszMenuName = MAKEINTRESOURCE(IDC_TORTOISEUDIFF);
62 wcx.hIconSm = LoadIcon(wcx.hInstance, MAKEINTRESOURCE(IDI_TORTOISEUDIFF));
63 if (RegisterWindow(&wcx))
65 if (Create(WS_CAPTION | WS_MAXIMIZEBOX | WS_MINIMIZEBOX | WS_SIZEBOX | WS_SYSMENU | WS_CLIPCHILDREN, NULL))
67 m_FindBar.SetParent(*this);
68 m_FindBar.Create(hResource, IDD_FINDBAR, *this);
69 UpdateWindow(*this);
70 return true;
73 return false;
76 LRESULT CALLBACK CMainWindow::WinMsgHandler(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
78 if (uMsg == TaskBarButtonCreated)
80 SetUUIDOverlayIcon(hwnd);
82 switch (uMsg)
84 case WM_CREATE:
86 m_hwnd = hwnd;
87 Initialize();
89 break;
90 case WM_COMMAND:
92 return DoCommand(LOWORD(wParam));
94 break;
95 case WM_MOUSEWHEEL:
97 if (GET_KEYSTATE_WPARAM(wParam) == MK_SHIFT)
99 // scroll sideways
100 SendEditor(SCI_LINESCROLL, -GET_WHEEL_DELTA_WPARAM(wParam)/40, 0);
102 else
103 return DefWindowProc(hwnd, uMsg, wParam, lParam);
105 break;
106 case WM_SIZE:
108 RECT rect;
109 GetClientRect(*this, &rect);
110 if (m_bShowFindBar)
112 ::SetWindowPos(m_hWndEdit, HWND_TOP,
113 rect.left, rect.top,
114 rect.right-rect.left, rect.bottom-rect.top-30,
115 SWP_SHOWWINDOW);
116 ::SetWindowPos(m_FindBar, HWND_TOP,
117 rect.left, rect.bottom-30,
118 rect.right-rect.left, 30,
119 SWP_SHOWWINDOW);
121 else
123 ::SetWindowPos(m_hWndEdit, HWND_TOP,
124 rect.left, rect.top,
125 rect.right-rect.left, rect.bottom-rect.top,
126 SWP_SHOWWINDOW);
127 ::ShowWindow(m_FindBar, SW_HIDE);
130 break;
131 case WM_GETMINMAXINFO:
133 MINMAXINFO * mmi = (MINMAXINFO*)lParam;
134 mmi->ptMinTrackSize.x = 100;
135 mmi->ptMinTrackSize.y = 100;
136 return 0;
138 break;
139 case WM_DESTROY:
140 PostQuitMessage(0);
141 break;
142 case WM_CLOSE:
143 ::DestroyWindow(m_hwnd);
144 break;
145 case WM_SETFOCUS:
146 SetFocus(m_hWndEdit);
147 break;
148 case COMMITMONITOR_FINDMSGNEXT:
150 SendEditor(SCI_CHARRIGHT);
151 SendEditor(SCI_SEARCHANCHOR);
152 m_bMatchCase = !!wParam;
153 m_findtext = (LPCTSTR)lParam;
154 SendEditor(SCI_SEARCHNEXT, m_bMatchCase ? SCFIND_MATCHCASE : 0, (LPARAM)CUnicodeUtils::StdGetUTF8(m_findtext).c_str());
155 SendEditor(SCI_SCROLLCARET);
157 break;
158 case COMMITMONITOR_FINDMSGPREV:
160 SendEditor(SCI_SEARCHANCHOR);
161 m_bMatchCase = !!wParam;
162 m_findtext = (LPCTSTR)lParam;
163 SendEditor(SCI_SEARCHPREV, m_bMatchCase ? SCFIND_MATCHCASE : 0, (LPARAM)CUnicodeUtils::StdGetUTF8(m_findtext).c_str());
164 SendEditor(SCI_SCROLLCARET);
166 break;
167 case COMMITMONITOR_FINDEXIT:
169 RECT rect;
170 GetClientRect(*this, &rect);
171 m_bShowFindBar = false;
172 ::ShowWindow(m_FindBar, SW_HIDE);
173 ::SetWindowPos(m_hWndEdit, HWND_TOP,
174 rect.left, rect.top,
175 rect.right-rect.left, rect.bottom-rect.top,
176 SWP_SHOWWINDOW);
178 break;
179 case COMMITMONITOR_FINDRESET:
180 SendEditor(SCI_SETSELECTIONSTART, 0);
181 SendEditor(SCI_SETSELECTIONEND, 0);
182 SendEditor(SCI_SEARCHANCHOR);
183 break;
184 default:
185 return DefWindowProc(hwnd, uMsg, wParam, lParam);
188 return 0;
191 LRESULT CMainWindow::DoCommand(int id)
193 switch (id)
195 case ID_FILE_OPEN:
196 loadOrSaveFile(true);
197 break;
198 case ID_FILE_SAVEAS:
199 loadOrSaveFile(false);
200 break;
201 case ID_FILE_SAVE:
202 loadOrSaveFile(false, m_filename);
203 break;
204 case ID_FILE_EXIT:
205 ::PostQuitMessage(0);
206 return 0;
207 case IDM_SHOWFINDBAR:
209 m_bShowFindBar = true;
210 ::ShowWindow(m_FindBar, SW_SHOW);
211 RECT rect;
212 GetClientRect(*this, &rect);
213 ::SetWindowPos(m_hWndEdit, HWND_TOP,
214 rect.left, rect.top,
215 rect.right-rect.left, rect.bottom-rect.top-30,
216 SWP_SHOWWINDOW);
217 ::SetWindowPos(m_FindBar, HWND_TOP,
218 rect.left, rect.bottom-30,
219 rect.right-rect.left, 30,
220 SWP_SHOWWINDOW);
221 ::SetFocus(m_FindBar);
222 SendEditor(SCI_SETSELECTIONSTART, 0);
223 SendEditor(SCI_SETSELECTIONEND, 0);
224 SendEditor(SCI_SEARCHANCHOR);
226 break;
227 case IDM_FINDNEXT:
228 SendEditor(SCI_CHARRIGHT);
229 SendEditor(SCI_SEARCHANCHOR);
230 SendEditor(SCI_SEARCHNEXT, m_bMatchCase ? SCFIND_MATCHCASE : 0, (LPARAM)CUnicodeUtils::StdGetUTF8(m_findtext).c_str());
231 SendEditor(SCI_SCROLLCARET);
232 break;
233 case IDM_FINDPREV:
234 SendEditor(SCI_SEARCHANCHOR);
235 SendEditor(SCI_SEARCHPREV, m_bMatchCase ? SCFIND_MATCHCASE : 0, (LPARAM)CUnicodeUtils::StdGetUTF8(m_findtext).c_str());
236 SendEditor(SCI_SCROLLCARET);
237 break;
238 case IDM_FINDEXIT:
239 if (IsWindowVisible(m_FindBar))
241 RECT rect;
242 GetClientRect(*this, &rect);
243 m_bShowFindBar = false;
244 ::ShowWindow(m_FindBar, SW_HIDE);
245 ::SetWindowPos(m_hWndEdit, HWND_TOP,
246 rect.left, rect.top,
247 rect.right-rect.left, rect.bottom-rect.top,
248 SWP_SHOWWINDOW);
250 else
251 PostQuitMessage(0);
252 break;
253 case ID_FILE_SETTINGS:
255 tstring gitCmd = _T(" /command:settings /page:blame");
256 RunCommand(gitCmd);
258 break;
259 case ID_FILE_APPLYPATCH:
261 std::wstring command = L" /diff:\"";
262 command += m_filename;
263 command += L"\"";
264 std::wstring tortoiseMergePath = GetAppDirectory() + _T("TortoiseGitMerge.exe");
265 CCreateProcessHelper::CreateProcessDetached(tortoiseMergePath.c_str(), const_cast<TCHAR*>(command.c_str()));
267 break;
268 case ID_FILE_PAGESETUP:
270 TCHAR localeInfo[3] = { 0 };
271 GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_IMEASURE, localeInfo, 3);
272 // Metric system. '1' is US System
273 int defaultMargin = localeInfo[0] == '0' ? 2540 : 1000;
275 PAGESETUPDLG pdlg = {0};
276 pdlg.lStructSize = sizeof(PAGESETUPDLG);
277 pdlg.hwndOwner = *this;
278 pdlg.hInstance = NULL;
279 pdlg.Flags = PSD_DEFAULTMINMARGINS|PSD_MARGINS|PSD_DISABLEPAPER|PSD_DISABLEORIENTATION;
280 if (localeInfo[0] == '0')
281 pdlg.Flags |= PSD_INHUNDREDTHSOFMILLIMETERS;
283 CRegStdDWORD m_regMargLeft = CRegStdDWORD(L"Software\\TortoiseGit\\UDiffpagesetupmarginleft", defaultMargin);
284 CRegStdDWORD m_regMargTop = CRegStdDWORD(L"Software\\TortoiseGit\\UDiffpagesetupmargintop", defaultMargin);
285 CRegStdDWORD m_regMargRight = CRegStdDWORD(L"Software\\TortoiseGit\\UDiffpagesetupmarginright", defaultMargin);
286 CRegStdDWORD m_regMargBottom = CRegStdDWORD(L"Software\\TortoiseGit\\UDiffpagesetupmarginbottom", defaultMargin);
288 pdlg.rtMargin.left = (long)(DWORD)m_regMargLeft;
289 pdlg.rtMargin.top = (long)(DWORD)m_regMargTop;
290 pdlg.rtMargin.right = (long)(DWORD)m_regMargRight;
291 pdlg.rtMargin.bottom = (long)(DWORD)m_regMargBottom;
293 if (!PageSetupDlg(&pdlg))
294 return false;
296 m_regMargLeft = pdlg.rtMargin.left;
297 m_regMargTop = pdlg.rtMargin.top;
298 m_regMargRight = pdlg.rtMargin.right;
299 m_regMargBottom = pdlg.rtMargin.bottom;
301 break;
302 case ID_FILE_PRINT:
304 PRINTDLGEX pdlg = {0};
305 pdlg.lStructSize = sizeof(PRINTDLGEX);
306 pdlg.hwndOwner = *this;
307 pdlg.hInstance = NULL;
308 pdlg.Flags = PD_USEDEVMODECOPIESANDCOLLATE | PD_ALLPAGES | PD_RETURNDC | PD_NOCURRENTPAGE | PD_NOPAGENUMS;
309 pdlg.nMinPage = 1;
310 pdlg.nMaxPage = 0xffffU; // We do not know how many pages in the document
311 pdlg.nCopies = 1;
312 pdlg.hDC = 0;
313 pdlg.nStartPage = START_PAGE_GENERAL;
315 // See if a range has been selected
316 size_t startPos = SendEditor(SCI_GETSELECTIONSTART);
317 size_t endPos = SendEditor(SCI_GETSELECTIONEND);
319 if (startPos == endPos)
320 pdlg.Flags |= PD_NOSELECTION;
321 else
322 pdlg.Flags |= PD_SELECTION;
324 HRESULT hResult = PrintDlgEx(&pdlg);
325 if ((hResult != S_OK) || (pdlg.dwResultAction != PD_RESULT_PRINT))
326 return 0;
328 // reset all indicators
329 size_t endpos = SendEditor(SCI_GETLENGTH);
330 for (int i = INDIC_CONTAINER; i <= INDIC_MAX; ++i)
332 SendEditor(SCI_SETINDICATORCURRENT, i);
333 SendEditor(SCI_INDICATORCLEARRANGE, 0, endpos);
335 // store and reset UI settings
336 int viewws = (int)SendEditor(SCI_GETVIEWWS);
337 SendEditor(SCI_SETVIEWWS, 0);
338 int edgemode = (int)SendEditor(SCI_GETEDGEMODE);
339 SendEditor(SCI_SETEDGEMODE, EDGE_NONE);
340 SendEditor(SCI_SETWRAPVISUALFLAGS, SC_WRAPVISUALFLAG_END);
342 HDC hdc = pdlg.hDC;
344 RECT rectMargins, rectPhysMargins;
345 POINT ptPage;
346 POINT ptDpi;
348 // Get printer resolution
349 ptDpi.x = GetDeviceCaps(hdc, LOGPIXELSX); // dpi in X direction
350 ptDpi.y = GetDeviceCaps(hdc, LOGPIXELSY); // dpi in Y direction
352 // Start by getting the physical page size (in device units).
353 ptPage.x = GetDeviceCaps(hdc, PHYSICALWIDTH); // device units
354 ptPage.y = GetDeviceCaps(hdc, PHYSICALHEIGHT); // device units
356 // Get the dimensions of the unprintable
357 // part of the page (in device units).
358 rectPhysMargins.left = GetDeviceCaps(hdc, PHYSICALOFFSETX);
359 rectPhysMargins.top = GetDeviceCaps(hdc, PHYSICALOFFSETY);
361 // To get the right and lower unprintable area,
362 // we take the entire width and height of the paper and
363 // subtract everything else.
364 rectPhysMargins.right = ptPage.x // total paper width
365 - GetDeviceCaps(hdc, HORZRES) // printable width
366 - rectPhysMargins.left; // left unprintable margin
368 rectPhysMargins.bottom = ptPage.y // total paper height
369 - GetDeviceCaps(hdc, VERTRES) // printable height
370 - rectPhysMargins.top; // right unprintable margin
372 TCHAR localeInfo[3] = { 0 };
373 GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_IMEASURE, localeInfo, 3);
374 // Metric system. '1' is US System
375 int defaultMargin = localeInfo[0] == '0' ? 2540 : 1000;
376 RECT pagesetupMargin;
377 CRegStdDWORD m_regMargLeft = CRegStdDWORD(L"Software\\TortoiseGit\\UDiffpagesetupmarginleft", defaultMargin);
378 CRegStdDWORD m_regMargTop = CRegStdDWORD(L"Software\\TortoiseGit\\UDiffpagesetupmargintop", defaultMargin);
379 CRegStdDWORD m_regMargRight = CRegStdDWORD(L"Software\\TortoiseGit\\UDiffpagesetupmarginright", defaultMargin);
380 CRegStdDWORD m_regMargBottom = CRegStdDWORD(L"Software\\TortoiseGit\\UDiffpagesetupmarginbottom", defaultMargin);
382 pagesetupMargin.left = (long)(DWORD)m_regMargLeft;
383 pagesetupMargin.top = (long)(DWORD)m_regMargTop;
384 pagesetupMargin.right = (long)(DWORD)m_regMargRight;
385 pagesetupMargin.bottom = (long)(DWORD)m_regMargBottom;
387 if (pagesetupMargin.left != 0 || pagesetupMargin.right != 0 ||
388 pagesetupMargin.top != 0 || pagesetupMargin.bottom != 0)
390 RECT rectSetup;
392 // Convert the hundredths of millimeters (HiMetric) or
393 // thousandths of inches (HiEnglish) margin values
394 // from the Page Setup dialog to device units.
395 // (There are 2540 hundredths of a mm in an inch.)
396 if (localeInfo[0] == '0')
398 // Metric system. '1' is US System
399 rectSetup.left = MulDiv (pagesetupMargin.left, ptDpi.x, 2540);
400 rectSetup.top = MulDiv (pagesetupMargin.top, ptDpi.y, 2540);
401 rectSetup.right = MulDiv(pagesetupMargin.right, ptDpi.x, 2540);
402 rectSetup.bottom = MulDiv(pagesetupMargin.bottom, ptDpi.y, 2540);
404 else
406 rectSetup.left = MulDiv(pagesetupMargin.left, ptDpi.x, 1000);
407 rectSetup.top = MulDiv(pagesetupMargin.top, ptDpi.y, 1000);
408 rectSetup.right = MulDiv(pagesetupMargin.right, ptDpi.x, 1000);
409 rectSetup.bottom = MulDiv(pagesetupMargin.bottom, ptDpi.y, 1000);
412 // Don't reduce margins below the minimum printable area
413 rectMargins.left = max(rectPhysMargins.left, rectSetup.left);
414 rectMargins.top = max(rectPhysMargins.top, rectSetup.top);
415 rectMargins.right = max(rectPhysMargins.right, rectSetup.right);
416 rectMargins.bottom = max(rectPhysMargins.bottom, rectSetup.bottom);
418 else
420 rectMargins.left = rectPhysMargins.left;
421 rectMargins.top = rectPhysMargins.top;
422 rectMargins.right = rectPhysMargins.right;
423 rectMargins.bottom = rectPhysMargins.bottom;
426 // rectMargins now contains the values used to shrink the printable
427 // area of the page.
429 // Convert device coordinates into logical coordinates
430 DPtoLP(hdc, (LPPOINT) &rectMargins, 2);
431 DPtoLP(hdc, (LPPOINT)&rectPhysMargins, 2);
433 // Convert page size to logical units and we're done!
434 DPtoLP(hdc, (LPPOINT) &ptPage, 1);
437 DOCINFO di = {sizeof(DOCINFO), 0, 0, 0, 0};
438 di.lpszDocName = m_filename.c_str();
439 di.lpszOutput = 0;
440 di.lpszDatatype = 0;
441 di.fwType = 0;
442 if (::StartDoc(hdc, &di) < 0)
444 ::DeleteDC(hdc);
445 return 0;
448 size_t lengthDoc = SendEditor(SCI_GETLENGTH);
449 size_t lengthDocMax = lengthDoc;
450 size_t lengthPrinted = 0;
452 // Requested to print selection
453 if (pdlg.Flags & PD_SELECTION)
455 if (startPos > endPos)
457 lengthPrinted = endPos;
458 lengthDoc = startPos;
460 else
462 lengthPrinted = startPos;
463 lengthDoc = endPos;
466 if (lengthDoc > lengthDocMax)
467 lengthDoc = lengthDocMax;
470 // We must subtract the physical margins from the printable area
471 Sci_RangeToFormat frPrint;
472 frPrint.hdc = hdc;
473 frPrint.hdcTarget = hdc;
474 frPrint.rc.left = rectMargins.left - rectPhysMargins.left;
475 frPrint.rc.top = rectMargins.top - rectPhysMargins.top;
476 frPrint.rc.right = ptPage.x - rectMargins.right - rectPhysMargins.left;
477 frPrint.rc.bottom = ptPage.y - rectMargins.bottom - rectPhysMargins.top;
478 frPrint.rcPage.left = 0;
479 frPrint.rcPage.top = 0;
480 frPrint.rcPage.right = ptPage.x - rectPhysMargins.left - rectPhysMargins.right - 1;
481 frPrint.rcPage.bottom = ptPage.y - rectPhysMargins.top - rectPhysMargins.bottom - 1;
483 // Print each page
484 while (lengthPrinted < lengthDoc)
486 ::StartPage(hdc);
488 frPrint.chrg.cpMin = (long)lengthPrinted;
489 frPrint.chrg.cpMax = (long)lengthDoc;
491 lengthPrinted = SendEditor(SCI_FORMATRANGE, true, reinterpret_cast<LPARAM>(&frPrint));
493 ::EndPage(hdc);
496 SendEditor(SCI_FORMATRANGE, FALSE, 0);
498 ::EndDoc(hdc);
499 ::DeleteDC(hdc);
501 if (pdlg.hDevMode != NULL)
502 GlobalFree(pdlg.hDevMode);
503 if (pdlg.hDevNames != NULL)
504 GlobalFree(pdlg.hDevNames);
505 if (pdlg.lpPageRanges != NULL)
506 GlobalFree(pdlg.lpPageRanges);
508 // reset the UI
509 SendEditor(SCI_SETVIEWWS, viewws);
510 SendEditor(SCI_SETEDGEMODE, edgemode);
511 SendEditor(SCI_SETWRAPVISUALFLAGS, SC_WRAPVISUALFLAG_NONE);
513 break;
514 default:
515 break;
517 return 1;
520 std::wstring CMainWindow::GetAppDirectory()
522 std::wstring path;
523 DWORD len = 0;
524 DWORD bufferlen = MAX_PATH; // MAX_PATH is not the limit here!
527 bufferlen += MAX_PATH; // MAX_PATH is not the limit here!
528 std::unique_ptr<TCHAR[]> pBuf(new TCHAR[bufferlen]);
529 len = GetModuleFileName(NULL, pBuf.get(), bufferlen);
530 path = pBuf.get();
531 } while(len == bufferlen);
532 path = path.substr(0, path.rfind('\\') + 1);
534 return path;
537 void CMainWindow::RunCommand(const std::wstring& command)
539 tstring tortoiseProcPath = GetAppDirectory() + _T("TortoiseGitProc.exe");
540 CCreateProcessHelper::CreateProcessDetached(tortoiseProcPath.c_str(), const_cast<TCHAR*>(command.c_str()));
543 LRESULT CMainWindow::SendEditor(UINT Msg, WPARAM wParam, LPARAM lParam)
545 if (m_directFunction)
547 return ((SciFnDirect) m_directFunction)(m_directPointer, Msg, wParam, lParam);
549 return ::SendMessage(m_hWndEdit, Msg, wParam, lParam);
552 bool CMainWindow::Initialize()
554 m_hWndEdit = ::CreateWindow(
555 _T("Scintilla"),
556 _T("Source"),
557 WS_CHILD | WS_VSCROLL | WS_HSCROLL | WS_CLIPCHILDREN,
558 CW_USEDEFAULT, CW_USEDEFAULT,
559 CW_USEDEFAULT, CW_USEDEFAULT,
560 *this,
562 hResource,
564 if (m_hWndEdit == NULL)
565 return false;
567 RECT rect;
568 GetClientRect(*this, &rect);
569 ::SetWindowPos(m_hWndEdit, HWND_TOP,
570 rect.left, rect.top,
571 rect.right-rect.left, rect.bottom-rect.top,
572 SWP_SHOWWINDOW);
574 m_directFunction = SendMessage(m_hWndEdit, SCI_GETDIRECTFUNCTION, 0, 0);
575 m_directPointer = SendMessage(m_hWndEdit, SCI_GETDIRECTPOINTER, 0, 0);
577 // Set up the global default style. These attributes are used wherever no explicit choices are made.
578 SetAStyle(STYLE_DEFAULT, ::GetSysColor(COLOR_WINDOWTEXT), ::GetSysColor(COLOR_WINDOW),
579 // Reusing TortoiseBlame's setting which already have an user friendly
580 // pane in TortoiseSVN's Settings dialog, while there is no such
581 // pane for TortoiseUDiff.
582 CRegStdDWORD(_T("Software\\TortoiseGit\\BlameFontSize"), 10),
583 CUnicodeUtils::StdGetUTF8(CRegStdString(_T("Software\\TortoiseGit\\BlameFontName"), _T("Courier New"))).c_str());
584 SendEditor(SCI_SETTABWIDTH, 4);
585 SendEditor(SCI_SETREADONLY, TRUE);
586 LRESULT pix = SendEditor(SCI_TEXTWIDTH, STYLE_LINENUMBER, (LPARAM)"_99999");
587 SendEditor(SCI_SETMARGINWIDTHN, 0, pix);
588 SendEditor(SCI_SETMARGINWIDTHN, 1);
589 SendEditor(SCI_SETMARGINWIDTHN, 2);
590 //Set the default windows colors for edit controls
591 SendEditor(SCI_STYLESETFORE, STYLE_DEFAULT, ::GetSysColor(COLOR_WINDOWTEXT));
592 SendEditor(SCI_STYLESETBACK, STYLE_DEFAULT, ::GetSysColor(COLOR_WINDOW));
593 SendEditor(SCI_SETSELFORE, TRUE, ::GetSysColor(COLOR_HIGHLIGHTTEXT));
594 SendEditor(SCI_SETSELBACK, TRUE, ::GetSysColor(COLOR_HIGHLIGHT));
595 SendEditor(SCI_SETCARETFORE, ::GetSysColor(COLOR_WINDOWTEXT));
596 CRegStdDWORD used2d(L"Software\\TortoiseGit\\ScintillaDirect2D", FALSE);
597 if (SysInfo::Instance().IsWin7OrLater() && DWORD(used2d))
599 SendEditor(SCI_SETTECHNOLOGY, SC_TECHNOLOGY_DIRECTWRITE);
600 SendEditor(SCI_SETBUFFEREDDRAW, 0);
602 SendEditor(SCI_SETVIEWWS, 1);
603 SendEditor(SCI_SETWHITESPACESIZE, 2);
604 SendEditor(SCI_SETWHITESPACEFORE, true, ::GetSysColor(COLOR_3DSHADOW));
605 SendEditor(SCI_STYLESETVISIBLE, STYLE_CONTROLCHAR, TRUE);
607 return true;
610 bool CMainWindow::LoadFile(HANDLE hFile)
612 InitEditor();
613 char data[4096] = { 0 };
614 DWORD dwRead = 0;
616 BOOL bRet = ReadFile(hFile, data, sizeof(data), &dwRead, NULL);
617 bool bUTF8 = IsUTF8(data, dwRead);
618 while ((dwRead > 0) && (bRet))
620 SendEditor(SCI_ADDTEXT, dwRead,
621 reinterpret_cast<LPARAM>(static_cast<char *>(data)));
622 bRet = ReadFile(hFile, data, sizeof(data), &dwRead, NULL);
624 SetupWindow(bUTF8);
625 return true;
628 bool CMainWindow::LoadFile(LPCTSTR filename)
630 InitEditor();
631 FILE *fp = NULL;
632 _tfopen_s(&fp, filename, _T("rb"));
633 if (!fp)
634 return false;
636 //SetTitle();
637 char data[4096] = { 0 };
638 size_t lenFile = fread(data, 1, sizeof(data), fp);
639 bool bUTF8 = IsUTF8(data, lenFile);
640 while (lenFile > 0)
642 SendEditor(SCI_ADDTEXT, lenFile,
643 reinterpret_cast<LPARAM>(static_cast<char *>(data)));
644 lenFile = fread(data, 1, sizeof(data), fp);
646 fclose(fp);
647 SetupWindow(bUTF8);
648 m_filename = filename;
649 return true;
652 void CMainWindow::InitEditor()
654 SendEditor(SCI_SETREADONLY, FALSE);
655 SendEditor(SCI_CLEARALL);
656 SendEditor(EM_EMPTYUNDOBUFFER);
657 SendEditor(SCI_SETSAVEPOINT);
658 SendEditor(SCI_CANCEL);
659 SendEditor(SCI_SETUNDOCOLLECTION, 0);
662 void CMainWindow::SetupWindow(bool bUTF8)
664 SendEditor(SCI_SETCODEPAGE, bUTF8 ? SC_CP_UTF8 : GetACP());
666 SendEditor(SCI_SETUNDOCOLLECTION, 1);
667 ::SetFocus(m_hWndEdit);
668 SendEditor(EM_EMPTYUNDOBUFFER);
669 SendEditor(SCI_SETSAVEPOINT);
670 SendEditor(SCI_GOTOPOS, 0);
672 SendEditor(SCI_CLEARDOCUMENTSTYLE, 0, 0);
673 SendEditor(SCI_SETSTYLEBITS, 5, 0);
675 //SetAStyle(SCE_DIFF_DEFAULT, RGB(0, 0, 0));
676 SetAStyle(SCE_DIFF_COMMAND, RGB(0x0A, 0x24, 0x36));
677 SetAStyle(SCE_DIFF_POSITION, RGB(0xFF, 0, 0));
678 SetAStyle(SCE_DIFF_HEADER, RGB(0x80, 0, 0), RGB(0xFF, 0xFF, 0x80));
679 SetAStyle(SCE_DIFF_COMMENT, RGB(0, 0x80, 0));
680 SendEditor(SCI_STYLESETBOLD, SCE_DIFF_COMMENT, TRUE);
681 SetAStyle(SCE_DIFF_DELETED, ::GetSysColor(COLOR_WINDOWTEXT), RGB(0xFF, 0x80, 0x80));
682 SetAStyle(SCE_DIFF_ADDED, ::GetSysColor(COLOR_WINDOWTEXT), RGB(0x80, 0xFF, 0x80));
684 SendEditor(SCI_SETLEXER, SCLEX_DIFF);
685 SendEditor(SCI_SETKEYWORDS, 0, (LPARAM)"revision");
686 SendEditor(SCI_COLOURISE, 0, -1);
687 ::ShowWindow(m_hWndEdit, SW_SHOW);
690 bool CMainWindow::SaveFile(LPCTSTR filename)
692 FILE *fp = NULL;
693 _tfopen_s(&fp, filename, _T("w+b"));
694 if (!fp)
695 return false;
697 LRESULT len = SendEditor(SCI_GETTEXT, 0, 0);
698 std::unique_ptr<char[]> data (new char[len+1]);
699 SendEditor(SCI_GETTEXT, len, reinterpret_cast<LPARAM>(static_cast<char *>(data.get())));
700 fwrite(data.get(), sizeof(char), len-1, fp);
701 fclose(fp);
703 SendEditor(SCI_SETSAVEPOINT);
704 ::ShowWindow(m_hWndEdit, SW_SHOW);
705 return true;
708 void CMainWindow::SetTitle(LPCTSTR title)
710 size_t len = _tcslen(title);
711 std::unique_ptr<TCHAR[]> pBuf(new TCHAR[len + 40]);
712 _stprintf_s(pBuf.get(), len + 40, _T("%s - TortoiseGitUDiff"), title);
713 SetWindowTitle(std::wstring(pBuf.get()));
716 void CMainWindow::SetAStyle(int style, COLORREF fore, COLORREF back, int size, const char *face)
718 SendEditor(SCI_STYLESETFORE, style, fore);
719 SendEditor(SCI_STYLESETBACK, style, back);
720 if (size >= 1)
721 SendEditor(SCI_STYLESETSIZE, style, size);
722 if (face)
723 SendEditor(SCI_STYLESETFONT, style, reinterpret_cast<LPARAM>(face));
726 bool CMainWindow::IsUTF8(LPVOID pBuffer, size_t cb)
728 if (cb < 2)
729 return true;
730 UINT16 * pVal16 = (UINT16 *)pBuffer;
731 UINT8 * pVal8 = (UINT8 *)(pVal16+1);
732 // scan the whole buffer for a 0x0000 sequence
733 // if found, we assume a binary file
734 for (size_t i=0; i<(cb-2); i=i+2)
736 if (0x0000 == *pVal16++)
737 return false;
739 pVal16 = (UINT16 *)pBuffer;
740 if (*pVal16 == 0xFEFF)
741 return false;
742 if (cb < 3)
743 return false;
744 if (*pVal16 == 0xBBEF)
746 if (*pVal8 == 0xBF)
747 return true;
749 // check for illegal UTF8 chars
750 pVal8 = (UINT8 *)pBuffer;
751 for (size_t i=0; i<cb; ++i)
753 if ((*pVal8 == 0xC0)||(*pVal8 == 0xC1)||(*pVal8 >= 0xF5))
754 return false;
755 pVal8++;
757 pVal8 = (UINT8 *)pBuffer;
758 bool bUTF8 = false;
759 for (size_t i=0; i<(cb-3); ++i)
761 if ((*pVal8 & 0xE0)==0xC0)
763 pVal8++;i++;
764 if ((*pVal8 & 0xC0)!=0x80)
765 return false;
766 bUTF8 = true;
768 else if ((*pVal8 & 0xF0)==0xE0)
770 pVal8++;i++;
771 if ((*pVal8 & 0xC0)!=0x80)
772 return false;
773 pVal8++;i++;
774 if ((*pVal8 & 0xC0)!=0x80)
775 return false;
776 bUTF8 = true;
778 else if ((*pVal8 & 0xF8)==0xF0)
780 pVal8++;i++;
781 if ((*pVal8 & 0xC0)!=0x80)
782 return false;
783 pVal8++;i++;
784 if ((*pVal8 & 0xC0)!=0x80)
785 return false;
786 pVal8++;i++;
787 if ((*pVal8 & 0xC0)!=0x80)
788 return false;
789 bUTF8 = true;
791 else if (*pVal8 >= 0x80)
792 return false;
794 pVal8++;
796 if (bUTF8)
797 return true;
798 return false;
801 void CMainWindow::loadOrSaveFile(bool doLoad, const std::wstring& filename /* = L"" */)
803 OPENFILENAME ofn = {0}; // common dialog box structure
804 TCHAR szFile[MAX_PATH] = {0}; // buffer for file name
805 // Initialize OPENFILENAME
806 ofn.lStructSize = sizeof(OPENFILENAME);
807 ofn.hwndOwner = *this;
808 ofn.lpstrFile = szFile;
809 ofn.nMaxFile = sizeof(szFile)/sizeof(TCHAR);
810 TCHAR filter[1024] = { 0 };
811 LoadString(hResource, IDS_PATCHFILEFILTER, filter, sizeof(filter)/sizeof(TCHAR));
812 CStringUtils::PipesToNulls(filter);
813 ofn.lpstrFilter = filter;
814 ofn.nFilterIndex = 1;
815 ofn.lpstrFileTitle = NULL;
816 ofn.nMaxFileTitle = 0;
817 ofn.lpstrInitialDir = NULL;
818 TCHAR fileTitle[1024] = { 0 };
819 LoadString(hResource, doLoad ? IDS_OPENPATCH : IDS_SAVEPATCH, fileTitle, sizeof(fileTitle)/sizeof(TCHAR));
820 ofn.lpstrTitle = fileTitle;
821 ofn.Flags = OFN_ENABLESIZING | OFN_EXPLORER;
822 if(doLoad)
823 ofn.Flags |= OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
824 else
825 ofn.Flags |= OFN_OVERWRITEPROMPT;
826 // Display the Open dialog box.
827 if( doLoad )
829 if (GetOpenFileName(&ofn)==TRUE)
831 LoadFile(ofn.lpstrFile);
834 else
836 if (filename.empty())
838 if (GetSaveFileName(&ofn)==TRUE)
840 SaveFile(ofn.lpstrFile);
843 else
844 SaveFile(filename.c_str());