Fix possible crash if git config is broken
[TortoiseGit.git] / src / TortoiseProc / CommitDlg.cpp
blob93d0eb12b755edb27854c1e47fd95ce8fe876159
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2003-2014 - TortoiseSVN
4 // Copyright (C) 2008-2016 - TortoiseGit
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 "TortoiseProc.h"
22 #include "CommitDlg.h"
23 #include "MessageBox.h"
24 #include "AppUtils.h"
25 #include "PathUtils.h"
26 #include "Git.h"
27 #include "registry.h"
28 #include "GitStatus.h"
29 #include "HistoryDlg.h"
30 #include "Hooks.h"
31 #include "UnicodeUtils.h"
32 #include "../TGitCache/CacheInterface.h"
33 #include "ProgressDlg.h"
34 #include "ShellUpdater.h"
35 #include "Commands/PushCommand.h"
36 #include "COMError.h"
37 #include "Globals.h"
38 #include "SysProgressDlg.h"
39 #include "MassiveGitTask.h"
40 #include "LogDlg.h"
41 #include "BstrSafeVector.h"
42 #include "StringUtils.h"
44 #ifdef _DEBUG
45 #define new DEBUG_NEW
46 #undef THIS_FILE
47 static char THIS_FILE[] = __FILE__;
48 #endif
50 UINT CCommitDlg::WM_AUTOLISTREADY = RegisterWindowMessage(_T("TORTOISEGIT_AUTOLISTREADY_MSG"));
51 UINT CCommitDlg::WM_UPDATEOKBUTTON = RegisterWindowMessage(_T("TORTOISEGIT_COMMIT_UPDATEOKBUTTON"));
52 UINT CCommitDlg::WM_UPDATEDATAFALSE = RegisterWindowMessage(_T("TORTOISEGIT_COMMIT_UPDATEDATAFALSE"));
54 IMPLEMENT_DYNAMIC(CCommitDlg, CResizableStandAloneDialog)
55 CCommitDlg::CCommitDlg(CWnd* pParent /*=NULL*/)
56 : CResizableStandAloneDialog(CCommitDlg::IDD, pParent)
57 , m_bShowUnversioned(FALSE)
58 , m_bBlock(FALSE)
59 , m_bThreadRunning(FALSE)
60 , m_bRunThread(FALSE)
61 , m_pThread(NULL)
62 , m_bWholeProject(FALSE)
63 , m_bWholeProject2(FALSE)
64 , m_bKeepChangeList(TRUE)
65 , m_bDoNotAutoselectSubmodules(FALSE)
66 , m_itemsCount(0)
67 , m_bSelectFilesForCommit(TRUE)
68 , m_bNoPostActions(FALSE)
69 , m_bAutoClose(false)
70 , m_bSetCommitDateTime(FALSE)
71 , m_bCreateNewBranch(FALSE)
72 , m_bForceCommitAmend(false)
73 , m_bCommitMessageOnly(FALSE)
74 , m_bSetAuthor(FALSE)
75 , m_bCancelled(false)
76 , m_PostCmd(GIT_POSTCOMMIT_CMD_NOTHING)
77 , m_bAmendDiffToLastCommit(FALSE)
78 , m_nPopupPasteListCmd(0)
79 , m_nPopupPasteLastMessage(0)
80 , m_nPopupRecentMessage(0)
81 , m_nPopupPickCommitHash(0)
82 , m_nPopupPickCommitMessage(0)
83 , m_hAccel(nullptr)
84 , m_bWarnDetachedHead(true)
85 , m_hAccelOkButton(nullptr)
87 this->m_bCommitAmend=FALSE;
90 CCommitDlg::~CCommitDlg()
92 if (m_hAccelOkButton)
93 DestroyAcceleratorTable(m_hAccelOkButton);
94 delete m_pThread;
97 void CCommitDlg::DoDataExchange(CDataExchange* pDX)
99 CResizableStandAloneDialog::DoDataExchange(pDX);
100 DDX_Control(pDX, IDC_FILELIST, m_ListCtrl);
101 DDX_Control(pDX, IDC_LOGMESSAGE, m_cLogMessage);
102 DDX_Check(pDX, IDC_SHOWUNVERSIONED, m_bShowUnversioned);
103 DDX_Check(pDX, IDC_COMMIT_SETDATETIME, m_bSetCommitDateTime);
104 DDX_Check(pDX, IDC_CHECK_NEWBRANCH, m_bCreateNewBranch);
105 DDX_Text(pDX, IDC_NEWBRANCH, m_sCreateNewBranch);
106 DDX_Text(pDX, IDC_BUGID, m_sBugID);
107 DDX_Text(pDX, IDC_COMMIT_AUTHORDATA, m_sAuthor);
108 DDX_Check(pDX, IDC_WHOLE_PROJECT, m_bWholeProject);
109 DDX_Control(pDX, IDC_SPLITTER, m_wndSplitter);
110 DDX_Check(pDX, IDC_KEEPLISTS, m_bKeepChangeList);
111 DDX_Check(pDX, IDC_NOAUTOSELECTSUBMODULES, m_bDoNotAutoselectSubmodules);
112 DDX_Check(pDX,IDC_COMMIT_AMEND,m_bCommitAmend);
113 DDX_Check(pDX, IDC_COMMIT_MESSAGEONLY, m_bCommitMessageOnly);
114 DDX_Check(pDX,IDC_COMMIT_AMENDDIFF,m_bAmendDiffToLastCommit);
115 DDX_Check(pDX, IDC_COMMIT_SETAUTHOR, m_bSetAuthor);
116 DDX_Control(pDX,IDC_VIEW_PATCH,m_ctrlShowPatch);
117 DDX_Control(pDX, IDC_COMMIT_DATEPICKER, m_CommitDate);
118 DDX_Control(pDX, IDC_COMMIT_TIMEPICKER, m_CommitTime);
119 DDX_Control(pDX, IDC_COMMIT_AS_COMMIT_DATE, m_AsCommitDateCtrl);
120 DDX_Control(pDX, IDC_CHECKALL, m_CheckAll);
121 DDX_Control(pDX, IDC_CHECKNONE, m_CheckNone);
122 DDX_Control(pDX, IDC_CHECKUNVERSIONED, m_CheckUnversioned);
123 DDX_Control(pDX, IDC_CHECKVERSIONED, m_CheckVersioned);
124 DDX_Control(pDX, IDC_CHECKADDED, m_CheckAdded);
125 DDX_Control(pDX, IDC_CHECKDELETED, m_CheckDeleted);
126 DDX_Control(pDX, IDC_CHECKMODIFIED, m_CheckModified);
127 DDX_Control(pDX, IDC_CHECKFILES, m_CheckFiles);
128 DDX_Control(pDX, IDC_CHECKSUBMODULES, m_CheckSubmodules);
129 DDX_Control(pDX, IDOK, m_ctrlOkButton);
132 BEGIN_MESSAGE_MAP(CCommitDlg, CResizableStandAloneDialog)
133 ON_BN_CLICKED(IDC_SHOWUNVERSIONED, OnBnClickedShowunversioned)
134 ON_NOTIFY(SCN_UPDATEUI, IDC_LOGMESSAGE, OnScnUpdateUI)
135 // ON_BN_CLICKED(IDC_HISTORY, OnBnClickedHistory)
136 ON_BN_CLICKED(IDC_BUGTRAQBUTTON, OnBnClickedBugtraqbutton)
137 ON_EN_CHANGE(IDC_LOGMESSAGE, OnEnChangeLogmessage)
138 ON_REGISTERED_MESSAGE(CGitStatusListCtrl::GITSLNM_ITEMCOUNTCHANGED, OnGitStatusListCtrlItemCountChanged)
139 ON_REGISTERED_MESSAGE(CGitStatusListCtrl::GITSLNM_NEEDSREFRESH, OnGitStatusListCtrlNeedsRefresh)
140 ON_REGISTERED_MESSAGE(CGitStatusListCtrl::GITSLNM_ADDFILE, OnFileDropped)
141 ON_REGISTERED_MESSAGE(CGitStatusListCtrl::GITSLNM_CHECKCHANGED, &CCommitDlg::OnGitStatusListCtrlCheckChanged)
142 ON_REGISTERED_MESSAGE(CGitStatusListCtrl::GITSLNM_ITEMCHANGED, &CCommitDlg::OnGitStatusListCtrlItemChanged)
144 ON_REGISTERED_MESSAGE(CLinkControl::LK_LINKITEMCLICKED, &CCommitDlg::OnCheck)
145 ON_REGISTERED_MESSAGE(WM_AUTOLISTREADY, OnAutoListReady)
146 ON_REGISTERED_MESSAGE(WM_UPDATEOKBUTTON, OnUpdateOKButton)
147 ON_REGISTERED_MESSAGE(WM_UPDATEDATAFALSE, OnUpdateDataFalse)
148 ON_WM_TIMER()
149 ON_WM_SIZE()
150 ON_STN_CLICKED(IDC_EXTERNALWARNING, &CCommitDlg::OnStnClickedExternalwarning)
151 ON_BN_CLICKED(IDC_SIGNOFF, &CCommitDlg::OnBnClickedSignOff)
152 ON_BN_CLICKED(IDC_COMMIT_AMEND, &CCommitDlg::OnBnClickedCommitAmend)
153 ON_BN_CLICKED(IDC_COMMIT_MESSAGEONLY, &CCommitDlg::OnBnClickedCommitMessageOnly)
154 ON_BN_CLICKED(IDC_WHOLE_PROJECT, &CCommitDlg::OnBnClickedWholeProject)
155 ON_COMMAND(ID_FOCUS_MESSAGE,&CCommitDlg::OnFocusMessage)
156 ON_COMMAND(ID_FOCUS_FILELIST, OnFocusFileList)
157 ON_STN_CLICKED(IDC_VIEW_PATCH, &CCommitDlg::OnStnClickedViewPatch)
158 ON_WM_MOVE()
159 ON_WM_MOVING()
160 ON_WM_SIZING()
161 ON_NOTIFY(HDN_ITEMCHANGED, 0, &CCommitDlg::OnHdnItemchangedFilelist)
162 ON_BN_CLICKED(IDC_COMMIT_AMENDDIFF, &CCommitDlg::OnBnClickedCommitAmenddiff)
163 ON_BN_CLICKED(IDC_NOAUTOSELECTSUBMODULES, &CCommitDlg::OnBnClickedNoautoselectsubmodules)
164 ON_BN_CLICKED(IDC_COMMIT_SETDATETIME, &CCommitDlg::OnBnClickedCommitSetDateTime)
165 ON_BN_CLICKED(IDC_COMMIT_AS_COMMIT_DATE, &CCommitDlg::OnBnClickedCommitAsCommitDate)
166 ON_BN_CLICKED(IDC_CHECK_NEWBRANCH, &CCommitDlg::OnBnClickedCheckNewBranch)
167 ON_BN_CLICKED(IDC_COMMIT_SETAUTHOR, &CCommitDlg::OnBnClickedCommitSetauthor)
168 END_MESSAGE_MAP()
170 int GetCommitTemplate(CString &msg)
172 CString tplFilename = g_Git.GetConfigValue(_T("commit.template"));
173 if (tplFilename.IsEmpty())
174 return -1;
176 if (tplFilename[0] == _T('/'))
178 if (tplFilename.GetLength() >= 3)
180 // handle "/d/TortoiseGit/tpl.txt" -> "d:/TortoiseGit/tpl.txt"
181 if (tplFilename[2] == _T('/'))
183 LPWSTR buf = tplFilename.GetBuffer();
184 buf[0] = buf[1];
185 buf[1] = _T(':');
186 tplFilename.ReleaseBuffer();
191 tplFilename.Replace(_T('/'), _T('\\'));
193 if (!CGit::LoadTextFile(tplFilename, msg))
194 return -1;
195 return 0;
198 BOOL CCommitDlg::OnInitDialog()
200 CResizableStandAloneDialog::OnInitDialog();
201 CAppUtils::MarkWindowAsUnpinnable(m_hWnd);
203 if (m_sLogMessage.IsEmpty())
205 if (!m_bForceCommitAmend)
206 GetCommitTemplate(m_sLogMessage);
208 CString dotGitPath;
209 GitAdminDir::GetAdminDirPath(g_Git.m_CurrentDir, dotGitPath);
210 CGit::LoadTextFile(dotGitPath + _T("SQUASH_MSG"), m_sLogMessage);
211 CGit::LoadTextFile(dotGitPath + _T("MERGE_MSG"), m_sLogMessage);
213 RunStartCommitHook();
215 m_regAddBeforeCommit = CRegDWORD(_T("Software\\TortoiseGit\\AddBeforeCommit"), TRUE);
216 m_bShowUnversioned = m_regAddBeforeCommit;
218 CString regPath(g_Git.m_CurrentDir);
219 regPath.Replace(_T(":"), _T("_"));
220 m_regShowWholeProject = CRegDWORD(_T("Software\\TortoiseGit\\TortoiseProc\\ShowWholeProject\\") + regPath, FALSE);
221 m_bWholeProject = m_regShowWholeProject;
223 m_History.SetMaxHistoryItems((LONG)CRegDWORD(_T("Software\\TortoiseGit\\MaxHistoryItems"), 25));
225 m_regKeepChangelists = CRegDWORD(_T("Software\\TortoiseGit\\KeepChangeLists"), FALSE);
226 m_bKeepChangeList = m_regKeepChangelists;
228 m_regDoNotAutoselectSubmodules = CRegDWORD(_T("Software\\TortoiseGit\\DoNotAutoselectSubmodules"), FALSE);
229 m_bDoNotAutoselectSubmodules = m_regDoNotAutoselectSubmodules;
231 m_hAccel = LoadAccelerators(AfxGetResourceHandle(),MAKEINTRESOURCE(IDR_ACC_COMMITDLG));
233 if (m_pathList.IsEmpty())
234 m_bWholeProject2 = true;
236 if(this->m_pathList.GetCount() == 1 && m_pathList[0].IsEmpty())
237 m_bWholeProject2 = true;
239 SetDlgTitle();
241 if (m_bSetAuthor)
242 GetDlgItem(IDC_COMMIT_AUTHORDATA)->ShowWindow(SW_SHOW);
244 if (m_bSetCommitDateTime)
246 m_CommitDate.SetTime(&m_wantCommitTime);
247 m_CommitTime.SetTime(&m_wantCommitTime);
248 GetDlgItem(IDC_COMMIT_DATEPICKER)->ShowWindow(SW_SHOW);
249 GetDlgItem(IDC_COMMIT_TIMEPICKER)->ShowWindow(SW_SHOW);
252 UpdateData(FALSE);
254 m_ListCtrl.Init(GITSLC_COLEXT | GITSLC_COLSTATUS | GITSLC_COLADD | GITSLC_COLDEL, _T("CommitDlg"), (GITSLC_POPALL ^ (GITSLC_POPCOMMIT | GITSLC_POPSAVEAS | GITSLC_PREPAREDIFF)), true, true);
255 m_ListCtrl.SetStatLabel(GetDlgItem(IDC_STATISTICS));
256 m_ListCtrl.SetCancelBool(&m_bCancelled);
257 m_ListCtrl.SetEmptyString(IDS_COMMITDLG_NOTHINGTOCOMMIT);
258 m_ListCtrl.EnableFileDrop();
259 m_ListCtrl.SetBackgroundImage(IDI_COMMIT_BKG);
261 //this->DialogEnableWindow(IDC_COMMIT_AMEND,FALSE);
262 m_ProjectProperties.ReadProps();
264 m_cLogMessage.Init(m_ProjectProperties);
265 m_cLogMessage.SetFont((CString)CRegString(_T("Software\\TortoiseGit\\LogFontName"), _T("Courier New")), (DWORD)CRegDWORD(_T("Software\\TortoiseGit\\LogFontSize"), 8));
266 m_cLogMessage.RegisterContextMenuHandler(this);
267 std::map<int, UINT> icons;
268 icons[AUTOCOMPLETE_SPELLING] = IDI_SPELL;
269 icons[AUTOCOMPLETE_FILENAME] = IDI_FILE;
270 icons[AUTOCOMPLETE_PROGRAMCODE] = IDI_CODE;
271 icons[AUTOCOMPLETE_SNIPPET] = IDI_SNIPPET;
272 m_cLogMessage.SetIcon(icons);
274 OnEnChangeLogmessage();
276 m_tooltips.AddTool(IDC_EXTERNALWARNING, IDS_COMMITDLG_EXTERNALS);
277 m_tooltips.AddTool(IDC_COMMIT_AMEND,IDS_COMMIT_AMEND_TT);
278 m_tooltips.AddTool(IDC_MERGEACTIVE, IDC_MERGEACTIVE_TT);
279 m_tooltips.AddTool(IDC_COMMIT_MESSAGEONLY, IDS_COMMIT_MESSAGEONLY_TT);
280 m_tooltips.AddTool(IDC_COMMIT_AS_COMMIT_DATE, IDS_COMMIT_AS_COMMIT_DATE_TT);
282 CBugTraqAssociations bugtraq_associations;
283 bugtraq_associations.Load(m_ProjectProperties.GetProviderUUID(), m_ProjectProperties.sProviderParams);
285 if (bugtraq_associations.FindProvider(g_Git.m_CurrentDir, &m_bugtraq_association))
287 GetDlgItem(IDC_BUGID)->ShowWindow(SW_HIDE);
288 GetDlgItem(IDC_BUGIDLABEL)->ShowWindow(SW_HIDE);
290 CComPtr<IBugTraqProvider> pProvider;
291 HRESULT hr = pProvider.CoCreateInstance(m_bugtraq_association.GetProviderClass());
292 if (SUCCEEDED(hr))
294 m_BugTraqProvider = pProvider;
295 ATL::CComBSTR temp;
296 ATL::CComBSTR parameters(m_bugtraq_association.GetParameters());
297 if (SUCCEEDED(hr = pProvider->GetLinkText(GetSafeHwnd(), parameters, &temp)))
299 SetDlgItemText(IDC_BUGTRAQBUTTON, temp);
300 GetDlgItem(IDC_BUGTRAQBUTTON)->EnableWindow(TRUE);
301 GetDlgItem(IDC_BUGTRAQBUTTON)->ShowWindow(SW_SHOW);
305 GetDlgItem(IDC_LOGMESSAGE)->SetFocus();
307 else if (!m_ProjectProperties.sMessage.IsEmpty())
309 GetDlgItem(IDC_BUGID)->ShowWindow(SW_SHOW);
310 GetDlgItem(IDC_BUGIDLABEL)->ShowWindow(SW_SHOW);
311 if (!m_ProjectProperties.sLabel.IsEmpty())
312 SetDlgItemText(IDC_BUGIDLABEL, m_ProjectProperties.sLabel);
313 GetDlgItem(IDC_BUGTRAQBUTTON)->ShowWindow(SW_HIDE);
314 GetDlgItem(IDC_BUGTRAQBUTTON)->EnableWindow(FALSE);
315 GetDlgItem(IDC_BUGID)->SetFocus();
316 CString sBugID = m_ProjectProperties.GetBugIDFromLog(m_sLogMessage);
317 if (!sBugID.IsEmpty())
319 SetDlgItemText(IDC_BUGID, sBugID);
322 else
324 GetDlgItem(IDC_BUGID)->ShowWindow(SW_HIDE);
325 GetDlgItem(IDC_BUGIDLABEL)->ShowWindow(SW_HIDE);
326 GetDlgItem(IDC_BUGTRAQBUTTON)->ShowWindow(SW_HIDE);
327 GetDlgItem(IDC_BUGTRAQBUTTON)->EnableWindow(FALSE);
328 GetDlgItem(IDC_LOGMESSAGE)->SetFocus();
331 if (!m_sLogMessage.IsEmpty())
333 m_cLogMessage.SetText(m_sLogMessage);
334 m_cLogMessage.Call(SCI_SETCURRENTPOS, 0);
335 m_cLogMessage.Call(SCI_SETSEL, 0, 0);
338 GetWindowText(m_sWindowTitle);
340 AdjustControlSize(IDC_SHOWUNVERSIONED);
341 AdjustControlSize(IDC_WHOLE_PROJECT);
342 AdjustControlSize(IDC_CHECK_NEWBRANCH);
343 AdjustControlSize(IDC_COMMIT_AMEND);
344 AdjustControlSize(IDC_COMMIT_MESSAGEONLY);
345 AdjustControlSize(IDC_COMMIT_AMENDDIFF);
346 AdjustControlSize(IDC_COMMIT_SETDATETIME);
347 AdjustControlSize(IDC_COMMIT_SETAUTHOR);
348 AdjustControlSize(IDC_NOAUTOSELECTSUBMODULES);
349 AdjustControlSize(IDC_KEEPLISTS);
350 AdjustControlSize(IDC_COMMIT_AS_COMMIT_DATE);
352 // line up all controls and adjust their sizes.
353 #define LINKSPACING 9
354 RECT rc = AdjustControlSize(IDC_SELECTLABEL);
355 rc.right -= 15; // AdjustControlSize() adds 20 pixels for the checkbox/radio button bitmap, but this is a label...
356 rc = AdjustStaticSize(IDC_CHECKALL, rc, LINKSPACING);
357 rc = AdjustStaticSize(IDC_CHECKNONE, rc, LINKSPACING);
358 rc = AdjustStaticSize(IDC_CHECKUNVERSIONED, rc, LINKSPACING);
359 rc = AdjustStaticSize(IDC_CHECKVERSIONED, rc, LINKSPACING);
360 rc = AdjustStaticSize(IDC_CHECKADDED, rc, LINKSPACING);
361 rc = AdjustStaticSize(IDC_CHECKDELETED, rc, LINKSPACING);
362 rc = AdjustStaticSize(IDC_CHECKMODIFIED, rc, LINKSPACING);
363 rc = AdjustStaticSize(IDC_CHECKFILES, rc, LINKSPACING);
364 rc = AdjustStaticSize(IDC_CHECKSUBMODULES, rc, LINKSPACING);
366 GetClientRect(m_DlgOrigRect);
367 m_cLogMessage.GetClientRect(m_LogMsgOrigRect);
369 AddAnchor(IDC_COMMITLABEL, TOP_LEFT, TOP_RIGHT);
370 AddAnchor(IDC_BUGIDLABEL, TOP_RIGHT);
371 AddAnchor(IDC_BUGID, TOP_RIGHT);
372 AddAnchor(IDC_BUGTRAQBUTTON, TOP_RIGHT);
373 AddAnchor(IDC_COMMIT_TO, TOP_LEFT, TOP_RIGHT);
374 AddAnchor(IDC_CHECK_NEWBRANCH, TOP_RIGHT);
375 AddAnchor(IDC_NEWBRANCH, TOP_LEFT, TOP_RIGHT);
376 AddAnchor(IDC_MESSAGEGROUP, TOP_LEFT, TOP_RIGHT);
377 // AddAnchor(IDC_HISTORY, TOP_LEFT);
378 AddAnchor(IDC_LOGMESSAGE, TOP_LEFT, TOP_RIGHT);
379 AddAnchor(IDC_SIGNOFF, TOP_RIGHT);
380 AddAnchor(IDC_VIEW_PATCH, BOTTOM_RIGHT);
381 AddAnchor(IDC_LISTGROUP, TOP_LEFT, BOTTOM_RIGHT);
382 AddAnchor(IDC_SPLITTER, TOP_LEFT, TOP_RIGHT);
383 AddAnchor(IDC_FILELIST, TOP_LEFT, BOTTOM_RIGHT);
384 AddAnchor(IDC_SHOWUNVERSIONED, BOTTOM_LEFT);
385 AddAnchor(IDC_EXTERNALWARNING, BOTTOM_RIGHT);
386 AddAnchor(IDC_STATISTICS, BOTTOM_LEFT, BOTTOM_RIGHT);
387 AddAnchor(IDC_TEXT_INFO, TOP_RIGHT);
388 AddAnchor(IDC_WHOLE_PROJECT, BOTTOM_LEFT);
389 AddAnchor(IDC_KEEPLISTS, BOTTOM_LEFT);
390 AddAnchor(IDC_NOAUTOSELECTSUBMODULES, BOTTOM_LEFT);
391 AddAnchor(IDOK, BOTTOM_RIGHT);
392 AddAnchor(IDCANCEL, BOTTOM_RIGHT);
393 AddAnchor(IDHELP, BOTTOM_RIGHT);
394 AddAnchor(IDC_MERGEACTIVE, BOTTOM_RIGHT);
395 AddAnchor(IDC_COMMIT_AMEND,TOP_LEFT);
396 AddAnchor(IDC_COMMIT_MESSAGEONLY, BOTTOM_LEFT);
397 AddAnchor(IDC_COMMIT_AMENDDIFF,TOP_LEFT);
398 AddAnchor(IDC_COMMIT_SETDATETIME,TOP_LEFT);
399 AddAnchor(IDC_COMMIT_DATEPICKER,TOP_LEFT);
400 AddAnchor(IDC_COMMIT_TIMEPICKER,TOP_LEFT);
401 AddAnchor(IDC_COMMIT_AS_COMMIT_DATE, TOP_LEFT);
402 AddAnchor(IDC_COMMIT_SETAUTHOR, TOP_LEFT);
403 AddAnchor(IDC_COMMIT_AUTHORDATA, TOP_LEFT, TOP_RIGHT);
405 AddAnchor(IDC_SELECTLABEL, TOP_LEFT);
406 AddAnchor(IDC_CHECKALL, TOP_LEFT);
407 AddAnchor(IDC_CHECKNONE, TOP_LEFT);
408 AddAnchor(IDC_CHECKUNVERSIONED, TOP_LEFT);
409 AddAnchor(IDC_CHECKVERSIONED, TOP_LEFT);
410 AddAnchor(IDC_CHECKADDED, TOP_LEFT);
411 AddAnchor(IDC_CHECKDELETED, TOP_LEFT);
412 AddAnchor(IDC_CHECKMODIFIED, TOP_LEFT);
413 AddAnchor(IDC_CHECKFILES, TOP_LEFT);
414 AddAnchor(IDC_CHECKSUBMODULES, TOP_LEFT);
416 if (hWndExplorer)
417 CenterWindow(CWnd::FromHandle(hWndExplorer));
418 EnableSaveRestore(_T("CommitDlg"));
419 DWORD yPos = CRegDWORD(_T("Software\\TortoiseGit\\TortoiseProc\\ResizableState\\CommitDlgSizer"));
420 RECT rcDlg, rcLogMsg, rcFileList;
421 GetClientRect(&rcDlg);
422 m_cLogMessage.GetWindowRect(&rcLogMsg);
423 ScreenToClient(&rcLogMsg);
424 m_ListCtrl.GetWindowRect(&rcFileList);
425 ScreenToClient(&rcFileList);
426 if (yPos)
428 RECT rectSplitter;
429 m_wndSplitter.GetWindowRect(&rectSplitter);
430 ScreenToClient(&rectSplitter);
431 int delta = yPos - rectSplitter.top;
432 if ((rcLogMsg.bottom + delta > rcLogMsg.top)&&(rcLogMsg.bottom + delta < rcFileList.bottom - 30))
434 m_wndSplitter.SetWindowPos(NULL, rectSplitter.left, yPos, 0, 0, SWP_NOSIZE);
435 DoSize(delta);
439 SetSplitterRange();
441 if (m_bForceCommitAmend || m_bCommitAmend)
442 GetDlgItem(IDC_COMMIT_AMENDDIFF)->ShowWindow(SW_SHOW);
444 // add all directories to the watcher
446 for (int i=0; i<m_pathList.GetCount(); ++i)
448 if (m_pathList[i].IsDirectory())
449 m_pathwatcher.AddPath(m_pathList[i]);
452 m_updatedPathList = m_pathList;
454 StartStatusThread();
455 CRegDWORD err = CRegDWORD(_T("Software\\TortoiseGit\\ErrorOccurred"), FALSE);
456 CRegDWORD historyhint = CRegDWORD(_T("Software\\TortoiseGit\\HistoryHintShown"), FALSE);
457 if ((((DWORD)err)!=FALSE)&&((((DWORD)historyhint)==FALSE)))
459 historyhint = TRUE;
460 // ShowBalloon(IDC_HISTORY, IDS_COMMITDLG_HISTORYHINT_TT, IDI_INFORMATION);
462 err = FALSE;
464 this->m_ctrlShowPatch.SetURL(CString());
466 if (g_Git.GetConfigValueBool(_T("tgit.commitshowpatch")))
467 OnStnClickedViewPatch();
469 if (CTGitPath(g_Git.m_CurrentDir).IsMergeActive())
471 DialogEnableWindow(IDC_CHECK_NEWBRANCH, FALSE);
472 m_bCreateNewBranch = FALSE;
473 GetDlgItem(IDC_MERGEACTIVE)->ShowWindow(SW_SHOW);
474 CMessageBox::ShowCheck(GetSafeHwnd(), IDS_COMMIT_MERGE_HINT, IDS_APPNAME, MB_ICONINFORMATION, L"CommitMergeHint", IDS_MSGBOX_DONOTSHOWAGAIN);
477 PrepareOkButton();
479 return FALSE; // return TRUE unless you set the focus to a control
480 // EXCEPTION: OCX Property Pages should return FALSE
483 void CCommitDlg::PrepareOkButton()
485 if (m_bNoPostActions)
486 return;
487 m_regLastAction = CRegDWORD(L"Software\\TortoiseGit\\CommitLastAction", 0);
488 int i = 0;
489 for (auto labelId : { IDS_COMMIT_COMMIT, IDS_COMMIT_RECOMMIT, IDS_COMMIT_COMMITPUSH })
491 ++i;
492 CString label;
493 label.LoadString(labelId);
494 m_ctrlOkButton.AddEntry(label);
495 TCHAR accellerator = CStringUtils::GetAccellerator(label);
496 if (accellerator == L'\0')
497 continue;
498 ++m_accellerators[accellerator].cnt;
499 if (m_accellerators[accellerator].cnt > 1)
500 m_accellerators[accellerator].id = -1;
501 else
502 m_accellerators[accellerator].id = i - 1;
504 m_ctrlOkButton.SetCurrentEntry(m_regLastAction);
505 if (m_accellerators.size())
507 LPACCEL lpaccelNew = (LPACCEL)LocalAlloc(LPTR, m_accellerators.size() * sizeof(ACCEL));
508 if (!lpaccelNew)
509 return;
510 SCOPE_EXIT{ LocalFree(lpaccelNew); };
511 i = 0;
512 for (auto& entry : m_accellerators)
514 lpaccelNew[i].cmd = (WORD)(WM_USER + 1 + entry.second.id);
515 lpaccelNew[i].fVirt = FVIRTKEY | FALT;
516 lpaccelNew[i].key = entry.first;
517 entry.second.wmid = lpaccelNew[i].cmd;
518 ++i;
520 m_hAccelOkButton = CreateAcceleratorTable(lpaccelNew, (int)m_accellerators.size());
524 static bool UpdateIndex(CMassiveGitTask &mgt, CSysProgressDlg &sysProgressDlg, int progress, int maxProgress)
526 if (!mgt.GetListCount())
527 return true;
529 if (sysProgressDlg.HasUserCancelled())
530 return false;
532 if (sysProgressDlg.IsVisible())
534 sysProgressDlg.SetTitle(IDS_APPNAME);
535 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_COMMIT_PREPARECOMMIT)));
536 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROC_COMMIT_UPDATEINDEX)));
537 sysProgressDlg.SetProgress(progress, maxProgress);
538 AfxGetThread()->PumpMessage(); // process messages, in order to avoid freezing
541 BOOL cancel = FALSE;
542 return mgt.Execute(cancel);
545 static void DoPush()
547 CString head;
548 if (g_Git.GetCurrentBranchFromFile(g_Git.m_CurrentDir, head))
549 return;
550 CString remote, remotebranch;
551 g_Git.GetRemotePushBranch(head, remote, remotebranch);
552 if (remote.IsEmpty() || remotebranch.IsEmpty())
554 CAppUtils::Push();
555 return;
558 CAppUtils::DoPush(CAppUtils::IsSSHPutty(), false, false, false, false, false, false, head, remote, remotebranch, false, 0);
561 void CCommitDlg::OnOK()
563 if (m_bBlock)
564 return;
565 if (m_bThreadRunning)
567 m_bCancelled = true;
568 StopStatusThread();
570 this->UpdateData();
572 if (m_bCreateNewBranch)
574 if (!g_Git.IsBranchNameValid(m_sCreateNewBranch))
576 ShowEditBalloon(IDC_NEWBRANCH, IDS_B_T_NOTEMPTY, IDS_ERR_ERROR, TTI_ERROR);
577 return;
579 if (g_Git.BranchTagExists(m_sCreateNewBranch))
581 // branch already exists
582 CString msg;
583 msg.LoadString(IDS_B_EXISTS);
584 msg += _T(" ") + CString(MAKEINTRESOURCE(IDS_B_DELETEORDIFFERENTNAME));
585 ShowEditBalloon(IDC_NEWBRANCH, msg, CString(MAKEINTRESOURCE(IDS_WARN_WARNING)));
586 return;
588 if (g_Git.BranchTagExists(m_sCreateNewBranch, false))
590 // tag with the same name exists -> shortref is ambiguous
591 if (CMessageBox::Show(m_hWnd, IDS_B_SAMETAGNAMEEXISTS, IDS_APPNAME, 2, IDI_EXCLAMATION, IDS_CONTINUEBUTTON, IDS_ABORTBUTTON) == 2)
592 return;
596 CString id;
597 GetDlgItemText(IDC_BUGID, id);
598 if (!m_ProjectProperties.CheckBugID(id))
600 ShowEditBalloon(IDC_BUGID, IDS_COMMITDLG_ONLYNUMBERS, IDS_ERR_ERROR, TTI_ERROR);
601 return;
603 m_sLogMessage = m_cLogMessage.GetText();
604 if ( m_sLogMessage.IsEmpty() )
606 // no message entered, go round again
607 CMessageBox::Show(this->m_hWnd, IDS_COMMITDLG_NOMESSAGE, IDS_APPNAME, MB_OK | MB_ICONERROR);
608 return;
610 if ((m_ProjectProperties.bWarnIfNoIssue) && (id.IsEmpty() && !m_ProjectProperties.HasBugID(m_sLogMessage)))
612 if (CMessageBox::Show(this->m_hWnd, IDS_COMMITDLG_NOISSUEWARNING, IDS_APPNAME, MB_YESNO | MB_ICONWARNING)!=IDYES)
613 return;
616 if (m_ProjectProperties.bWarnNoSignedOffBy == TRUE && m_cLogMessage.GetText().Find(GetSignedOffByLine()) == -1)
618 UINT retval = CMessageBox::Show(this->m_hWnd, IDS_PROC_COMMIT_NOSIGNOFFLINE, IDS_APPNAME, 1, IDI_WARNING, IDS_PROC_COMMIT_ADDSIGNOFFBUTTON, IDS_PROC_COMMIT_NOADDSIGNOFFBUTTON, IDS_ABORTBUTTON);
619 if (retval == 1)
621 OnBnClickedSignOff();
622 m_sLogMessage = m_cLogMessage.GetText();
624 else if (retval == 3)
625 return;
628 if (CHooks::Instance().IsHookPresent(pre_commit_hook, g_Git.m_CurrentDir)) {
629 DWORD exitcode = 0xFFFFFFFF;
630 CString error;
631 CTGitPathList list;
632 m_ListCtrl.WriteCheckedNamesToPathList(list);
633 if (CHooks::Instance().PreCommit(g_Git.m_CurrentDir, list, m_sLogMessage, exitcode, error))
635 if (exitcode)
637 CString temp;
638 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
639 MessageBox(temp, _T("TortoiseGit"), MB_ICONERROR);
640 return;
645 int nListItems = m_ListCtrl.GetItemCount();
646 for (int i = 0; i < nListItems && !m_bCommitMessageOnly; ++i)
648 CTGitPath *entry = (CTGitPath *)m_ListCtrl.GetItemData(i);
649 if (!entry->m_Checked || !entry->IsDirectory())
650 continue;
652 bool dirty = false;
653 if (entry->m_Action & CTGitPath::LOGACTIONS_UNVER)
655 CGit subgit;
656 subgit.m_CurrentDir = g_Git.CombinePath(entry);
657 CString subcmdout;
658 subgit.Run(_T("git.exe status --porcelain"), &subcmdout, CP_UTF8);
659 dirty = !subcmdout.IsEmpty();
661 else
663 CString cmd, cmdout;
664 cmd.Format(_T("git.exe diff -- \"%s\""), entry->GetWinPath());
665 g_Git.Run(cmd, &cmdout, CP_UTF8);
666 dirty = cmdout.Right(7) == _T("-dirty\n");
669 if (dirty)
671 CString message;
672 message.Format(IDS_COMMITDLG_SUBMODULEDIRTY, (LPCTSTR)entry->GetGitPathString());
673 int result = CMessageBox::Show(m_hWnd, message, _T("TortoiseGit"), 1, IDI_QUESTION, CString(MAKEINTRESOURCE(IDS_PROGRS_CMD_COMMIT)), CString(MAKEINTRESOURCE(IDS_MSGBOX_IGNORE)), CString(MAKEINTRESOURCE(IDS_MSGBOX_CANCEL)));
674 if (result == 1)
676 CString cmdCommit;
677 cmdCommit.Format(_T("/command:commit /path:\"%s\\%s\""), (LPCTSTR)g_Git.m_CurrentDir, entry->GetWinPath());
678 CAppUtils::RunTortoiseGitProc(cmdCommit);
679 return;
681 else if (result == 2)
682 continue;
683 else
684 return;
688 if (!m_bCommitMessageOnly)
689 m_ListCtrl.WriteCheckedNamesToPathList(m_selectedPathList);
690 m_pathwatcher.Stop();
691 InterlockedExchange(&m_bBlock, TRUE);
692 //first add all the unversioned files the user selected
693 //and check if all versioned files are selected
694 int nchecked = 0;
696 CMassiveGitTask mgtReAddAfterCommit(_T("add --ignore-errors -f"));
697 CMassiveGitTask mgtReDelAfterCommit(_T("rm --cached --ignore-unmatch"));
699 CString cmd;
700 CString out;
702 bool bAddSuccess=true;
703 bool bCloseCommitDlg=false;
705 CSysProgressDlg sysProgressDlg;
706 if (nListItems >= 25)
708 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_PROC_COMMIT_PREPARECOMMIT)));
709 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_COMMIT_UPDATEINDEX)));
710 sysProgressDlg.SetTime(true);
711 sysProgressDlg.SetShowProgressBar(true);
712 sysProgressDlg.ShowModal(this, true);
715 CBlockCacheForPath cacheBlock(g_Git.m_CurrentDir);
716 ULONGLONG currentTicks = GetTickCount64();
718 if (g_Git.UsingLibGit2(CGit::GIT_CMD_COMMIT_UPDATE_INDEX))
720 bAddSuccess = false;
723 CAutoRepository repository(g_Git.GetGitRepository());
724 if (!repository)
726 CMessageBox::Show(m_hWnd, CGit::GetLibGit2LastErr(_T("Could not open repository.")), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
727 break;
730 CGitHash revHash;
731 CString revRef = _T("HEAD");
732 if (m_bCommitAmend && !m_bAmendDiffToLastCommit)
733 revRef = _T("HEAD~1");
734 if (CGit::GetHash(repository, revHash, revRef))
736 MessageBox(g_Git.GetLibGit2LastErr(_T("Could not get HEAD hash after committing.")), _T("TortoiseGit"), MB_ICONERROR);
737 break;
740 CAutoCommit commit;
741 if (!revHash.IsEmpty() && git_commit_lookup(commit.GetPointer(), repository, (const git_oid*)revHash.m_hash))
743 CMessageBox::Show(m_hWnd, CGit::GetLibGit2LastErr(_T("Could not get last commit.")), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
744 break;
747 CAutoTree tree;
748 if (!revHash.IsEmpty() && git_commit_tree(tree.GetPointer(), commit))
750 CMessageBox::Show(m_hWnd, CGit::GetLibGit2LastErr(_T("Could not read tree of commit.")), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
751 break;
754 CAutoIndex index;
755 if (git_repository_index(index.GetPointer(), repository))
757 CMessageBox::Show(m_hWnd, CGit::GetLibGit2LastErr(_T("Could not get the repository index.")), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
758 break;
761 CAutoIndex indexOld;
762 if (!revHash.IsEmpty() && (git_index_new(indexOld.GetPointer()) || git_index_read_tree(indexOld, tree)))
764 CMessageBox::Show(m_hWnd, CGit::GetLibGit2LastErr(_T("Could not read the tree into the index.")), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
765 break;
768 bAddSuccess = true;
770 for (int j = 0; j < nListItems; ++j)
772 CTGitPath *entry = (CTGitPath*)m_ListCtrl.GetItemData(j);
774 if (sysProgressDlg.IsVisible())
776 if (GetTickCount64() - currentTicks > 1000UL || j == nListItems - 1 || j == 0)
778 sysProgressDlg.SetLine(2, entry->GetGitPathString(), true);
779 sysProgressDlg.SetProgress(j, nListItems);
780 AfxGetThread()->PumpMessage(); // process messages, in order to avoid freezing; do not call this too often: this takes time!
781 currentTicks = GetTickCount64();
785 CStringA filePathA = CUnicodeUtils::GetMulti(entry->GetGitPathString(), CP_UTF8).TrimRight(_T('/'));
787 if (entry->m_Checked && !m_bCommitMessageOnly)
789 if (entry->m_Action & CTGitPath::LOGACTIONS_DELETED)
790 git_index_remove_bypath(index, filePathA); // ignore error
791 else
793 if (git_index_add_bypath(index, filePathA))
795 bAddSuccess = false;
796 CMessageBox::Show(m_hWnd, CGit::GetLibGit2LastErr(_T("Could not add \"") + entry->GetGitPathString() + _T("\" to index.")), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
797 break;
801 if ((entry->m_Action & CTGitPath::LOGACTIONS_REPLACED) && !entry->GetGitOldPathString().IsEmpty())
802 git_index_remove_bypath(index, CUnicodeUtils::GetUTF8(entry->GetGitOldPathString())); // ignore error
804 ++nchecked;
806 else
808 if (entry->m_Action & CTGitPath::LOGACTIONS_ADDED || entry->m_Action & CTGitPath::LOGACTIONS_REPLACED)
810 git_index_remove_bypath(index, filePathA); // ignore error
811 mgtReAddAfterCommit.AddFile(*entry);
813 if (entry->m_Action & CTGitPath::LOGACTIONS_REPLACED && !entry->GetGitOldPathString().IsEmpty())
815 const git_index_entry* oldIndexEntry = nullptr;
816 if ((oldIndexEntry = git_index_get_bypath(indexOld, CUnicodeUtils::GetUTF8(entry->GetGitOldPathString()), 0)) == nullptr || git_index_add(index, oldIndexEntry))
818 bAddSuccess = false;
819 CMessageBox::Show(m_hWnd, CGit::GetLibGit2LastErr(_T("Could not reset \"") + entry->GetGitOldPathString() + _T("\" to old index entry.")), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
820 break;
822 mgtReDelAfterCommit.AddFile(entry->GetGitOldPathString());
825 else if (!(entry->m_Action & CTGitPath::LOGACTIONS_UNVER))
827 const git_index_entry* oldIndexEntry = nullptr;
828 if ((oldIndexEntry = git_index_get_bypath(indexOld, filePathA, 0)) == nullptr || git_index_add(index, oldIndexEntry))
830 bAddSuccess = false;
831 CMessageBox::Show(m_hWnd, CGit::GetLibGit2LastErr(_T("Could not reset \"") + entry->GetGitPathString() + _T("\" to old index entry.")), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
832 break;
834 if (entry->m_Action & CTGitPath::LOGACTIONS_DELETED && !(entry->m_Action & CTGitPath::LOGACTIONS_MISSING))
835 mgtReDelAfterCommit.AddFile(entry->GetGitPathString());
839 if (sysProgressDlg.HasUserCancelled())
841 bAddSuccess = false;
842 break;
845 if (bAddSuccess && git_index_write(index))
846 bAddSuccess = false;
848 for (int j = 0; bAddSuccess && j < nListItems; ++j)
849 CShellUpdater::Instance().AddPathForUpdate(*(CTGitPath*)m_ListCtrl.GetItemData(j));
850 } while (0);
852 else
854 // ***************************************************
855 // ATTENTION: Similar code in RebaseDlg.cpp!!!
856 // ***************************************************
857 CMassiveGitTask mgtAdd(_T("add -f"));
858 CMassiveGitTask mgtUpdateIndexForceRemove(_T("update-index --force-remove"));
859 CMassiveGitTask mgtUpdateIndex(_T("update-index"));
860 CMassiveGitTask mgtRm(_T("rm --ignore-unmatch"));
861 CMassiveGitTask mgtRmFCache(_T("rm -f --cache"));
862 CString resetCmd = _T("reset");
863 if (m_bCommitAmend && !m_bAmendDiffToLastCommit)
864 resetCmd += _T(" HEAD~1");;
865 CMassiveGitTask mgtReset(resetCmd, TRUE, true);
866 for (int j = 0; j < nListItems; ++j)
868 CTGitPath *entry = (CTGitPath*)m_ListCtrl.GetItemData(j);
870 if (entry->m_Checked && !m_bCommitMessageOnly)
872 if (entry->m_Action & CTGitPath::LOGACTIONS_UNVER)
873 mgtAdd.AddFile(entry->GetGitPathString());
874 else if (entry->m_Action & CTGitPath::LOGACTIONS_DELETED)
875 mgtUpdateIndexForceRemove.AddFile(entry->GetGitPathString());
876 else
877 mgtUpdateIndex.AddFile(entry->GetGitPathString());
879 if ((entry->m_Action & CTGitPath::LOGACTIONS_REPLACED) && !entry->GetGitOldPathString().IsEmpty())
880 mgtRm.AddFile(entry->GetGitOldPathString());
882 ++nchecked;
884 else
886 if (entry->m_Action & CTGitPath::LOGACTIONS_ADDED || entry->m_Action & CTGitPath::LOGACTIONS_REPLACED)
887 { //To init git repository, there are not HEAD, so we can use git reset command
888 mgtRmFCache.AddFile(entry->GetGitPathString());
889 mgtReAddAfterCommit.AddFile(*entry);
891 if (entry->m_Action & CTGitPath::LOGACTIONS_REPLACED && !entry->GetGitOldPathString().IsEmpty())
893 mgtReset.AddFile(entry->GetGitOldPathString());
894 mgtReDelAfterCommit.AddFile(entry->GetGitOldPathString());
897 else if (!(entry->m_Action & CTGitPath::LOGACTIONS_UNVER))
899 mgtReset.AddFile(entry->GetGitPathString());
900 if (entry->m_Action & CTGitPath::LOGACTIONS_DELETED && !(entry->m_Action & CTGitPath::LOGACTIONS_MISSING))
901 mgtReDelAfterCommit.AddFile(entry->GetGitPathString());
905 if (sysProgressDlg.HasUserCancelled())
907 bAddSuccess = false;
908 break;
912 CMassiveGitTask tasks[] = { mgtAdd, mgtUpdateIndexForceRemove, mgtUpdateIndex, mgtRm, mgtRmFCache, mgtReset };
913 int progress = 0, maxProgress = 0;
914 for (int j = 0; j < _countof(tasks); ++j)
915 maxProgress += tasks[j].GetListCount();
916 for (int j = 0; j < _countof(tasks); ++j)
917 bAddSuccess = bAddSuccess && UpdateIndex(tasks[j], sysProgressDlg, progress += tasks[j].GetListCount(), maxProgress);
919 if (sysProgressDlg.HasUserCancelled())
920 bAddSuccess = false;
922 for (int j = 0; bAddSuccess && j < nListItems; ++j)
923 CShellUpdater::Instance().AddPathForUpdate(*(CTGitPath*)m_ListCtrl.GetItemData(j));
926 if (sysProgressDlg.HasUserCancelled())
927 bAddSuccess = false;
929 sysProgressDlg.Stop();
931 if (bAddSuccess && m_bCreateNewBranch)
933 if (g_Git.Run(_T("git.exe branch ") + m_sCreateNewBranch, &out, CP_UTF8))
935 MessageBox(_T("Creating new branch failed:\n") + out, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
936 bAddSuccess = false;
938 if (g_Git.Run(_T("git.exe checkout ") + m_sCreateNewBranch + _T(" --"), &out, CP_UTF8))
940 MessageBox(_T("Switching to new branch failed:\n") + out, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
941 bAddSuccess = false;
945 if (bAddSuccess && m_bWarnDetachedHead && CheckHeadDetach())
946 bAddSuccess = false;
948 m_sBugID.Trim();
949 CString sExistingBugID = m_ProjectProperties.FindBugID(m_sLogMessage);
950 sExistingBugID.Trim();
951 if (!m_sBugID.IsEmpty() && m_sBugID.Compare(sExistingBugID))
953 m_sBugID.Replace(_T(", "), _T(","));
954 m_sBugID.Replace(_T(" ,"), _T(","));
955 CString sBugID = m_ProjectProperties.sMessage;
956 sBugID.Replace(_T("%BUGID%"), m_sBugID);
957 if (m_ProjectProperties.bAppend)
958 m_sLogMessage += _T("\n") + sBugID + _T("\n");
959 else
960 m_sLogMessage = sBugID + _T("\n") + m_sLogMessage;
963 // now let the bugtraq plugin check the commit message
964 CComPtr<IBugTraqProvider2> pProvider2 = NULL;
965 if (m_BugTraqProvider)
967 HRESULT hr = m_BugTraqProvider.QueryInterface(&pProvider2);
968 if (SUCCEEDED(hr))
970 ATL::CComBSTR temp;
971 ATL::CComBSTR repositoryRoot(g_Git.m_CurrentDir);
972 ATL::CComBSTR parameters(m_bugtraq_association.GetParameters());
973 ATL::CComBSTR commonRoot(m_pathList.GetCommonRoot().GetDirectory().GetWinPath());
974 ATL::CComBSTR commitMessage(m_sLogMessage);
975 CBstrSafeVector pathList(m_selectedPathList.GetCount());
977 for (LONG index = 0; index < m_selectedPathList.GetCount(); ++index)
978 pathList.PutElement(index, m_selectedPathList[index].GetGitPathString());
980 if (FAILED(hr = pProvider2->CheckCommit(GetSafeHwnd(), parameters, repositoryRoot, commonRoot, pathList, commitMessage, &temp)))
982 COMError ce(hr);
983 CString sErr;
984 sErr.Format(IDS_ERR_FAILEDISSUETRACKERCOM, (LPCTSTR)m_bugtraq_association.GetProviderName(), ce.GetMessageAndDescription().c_str());
985 CMessageBox::Show(m_hWnd, sErr, _T("TortoiseGit"), MB_ICONERROR);
987 else
989 CString sError = temp;
990 if (!sError.IsEmpty())
992 CMessageBox::Show(m_hWnd, sError, _T("TortoiseGit"), MB_ICONERROR);
993 InterlockedExchange(&m_bBlock, FALSE);
994 return;
1000 if (m_bCommitMessageOnly || bAddSuccess && (nchecked || m_bCommitAmend || CTGitPath(g_Git.m_CurrentDir).IsMergeActive()))
1002 bCloseCommitDlg = true;
1004 CString tempfile=::GetTempFile();
1006 if (CAppUtils::SaveCommitUnicodeFile(tempfile, m_sLogMessage))
1008 CMessageBox::Show(nullptr, _T("Could not save commit message"), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
1009 InterlockedExchange(&m_bBlock, FALSE);
1010 return;
1013 CTGitPath path=g_Git.m_CurrentDir;
1015 BOOL IsGitSVN = path.GetAdminDirMask() & ITEMIS_GITSVN;
1017 out.Empty();
1018 CString amend;
1019 if(this->m_bCommitAmend)
1021 amend=_T("--amend");
1023 CString dateTime;
1024 if (m_bSetCommitDateTime)
1026 CTime date, time;
1027 m_CommitDate.GetTime(date);
1028 m_CommitTime.GetTime(time);
1029 if (m_bCommitAmend && m_AsCommitDateCtrl.GetCheck())
1030 dateTime = CAppUtils::GetMsysgitVersion() > 0x02010000 ? L"--date=\"now\"" : L"--date=\"\"" ;
1031 else
1032 dateTime.Format(_T("--date=%sT%s"), (LPCTSTR)date.Format(_T("%Y-%m-%d")), (LPCTSTR)time.Format(_T("%H:%M:%S")));
1034 CString author;
1035 if (m_bSetAuthor)
1036 author.Format(_T("--author=\"%s\""), (LPCTSTR)m_sAuthor);
1037 CString allowEmpty = m_bCommitMessageOnly ? _T("--allow-empty") : _T("");
1038 // TODO: make sure notes.amend.rewrite does still work when switching to libgit2
1039 cmd.Format(_T("git.exe commit %s %s %s %s -F \"%s\""), (LPCTSTR)author, (LPCTSTR)dateTime, (LPCTSTR)amend, (LPCTSTR)allowEmpty, (LPCTSTR)tempfile);
1041 CCommitProgressDlg progress;
1042 progress.m_bBufferAll=true; // improve show speed when there are many file added.
1043 progress.m_GitCmd=cmd;
1044 progress.m_bShowCommand = FALSE; // don't show the commit command
1045 progress.m_PreText = out; // show any output already generated in log window
1046 if (m_ctrlOkButton.GetCurrentEntry() > 0)
1047 progress.m_AutoClose = GitProgressAutoClose::AUTOCLOSE_IF_NO_ERRORS;
1049 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
1051 if (status || m_bNoPostActions || m_bAutoClose)
1052 return;
1054 if (IsGitSVN)
1055 postCmdList.emplace_back(IDI_COMMIT, IDS_MENUSVNDCOMMIT, [&]{ m_PostCmd = GIT_POSTCOMMIT_CMD_DCOMMIT; });
1057 postCmdList.emplace_back(IDI_PUSH, IDS_MENUPUSH, [&]{ m_PostCmd = GIT_POSTCOMMIT_CMD_PUSH; });
1058 postCmdList.emplace_back(IDI_PULL, IDS_MENUPULL, [&]{ m_PostCmd = GIT_POSTCOMMIT_CMD_PULL; });
1059 postCmdList.emplace_back(IDI_COMMIT, IDS_PROC_COMMIT_RECOMMIT, [&]{ m_PostCmd = GIT_POSTCOMMIT_CMD_RECOMMIT; });
1060 postCmdList.emplace_back(IDI_TAG, IDS_MENUTAG, [&]{ m_PostCmd = GIT_POSTCOMMIT_CMD_CREATETAG; });
1063 m_PostCmd = GIT_POSTCOMMIT_CMD_NOTHING;
1064 progress.DoModal();
1066 if (!m_bNoPostActions)
1067 m_regLastAction = (int)m_ctrlOkButton.GetCurrentEntry();
1068 if (m_ctrlOkButton.GetCurrentEntry() == 1)
1069 m_PostCmd = GIT_POSTCOMMIT_CMD_RECOMMIT;
1071 if (progress.m_GitStatus || m_PostCmd == GIT_POSTCOMMIT_CMD_RECOMMIT)
1073 bCloseCommitDlg = false;
1074 if (m_PostCmd == GIT_POSTCOMMIT_CMD_RECOMMIT)
1076 if (!m_sLogMessage.IsEmpty())
1078 ReloadHistoryEntries();
1079 m_History.AddEntry(m_sLogMessage);
1080 m_History.Save();
1083 this->m_sLogMessage.Empty();
1084 GetCommitTemplate(m_sLogMessage);
1085 RunStartCommitHook();
1086 m_cLogMessage.SetText(m_sLogMessage);
1087 if (m_bCreateNewBranch)
1089 GetDlgItem(IDC_COMMIT_TO)->ShowWindow(SW_SHOW);
1090 GetDlgItem(IDC_NEWBRANCH)->ShowWindow(SW_HIDE);
1092 m_bCreateNewBranch = FALSE;
1095 if (!progress.m_GitStatus)
1097 m_AmendStr.Empty();
1098 m_bCommitAmend = FALSE;
1101 UpdateData(FALSE);
1104 ::DeleteFile(tempfile);
1106 if (m_BugTraqProvider && progress.m_GitStatus == 0)
1108 CComPtr<IBugTraqProvider2> pProvider = NULL;
1109 HRESULT hr = m_BugTraqProvider.QueryInterface(&pProvider);
1110 if (SUCCEEDED(hr))
1112 ATL::CComBSTR commonRoot(g_Git.m_CurrentDir);
1113 CBstrSafeVector pathList(m_selectedPathList.GetCount());
1115 for (LONG index = 0; index < m_selectedPathList.GetCount(); ++index)
1116 pathList.PutElement(index, m_selectedPathList[index].GetGitPathString());
1118 ATL::CComBSTR logMessage(m_sLogMessage);
1120 CGitHash hash;
1121 if (g_Git.GetHash(hash, _T("HEAD")))
1122 MessageBox(g_Git.GetGitLastErr(_T("Could not get HEAD hash after committing.")), _T("TortoiseGit"), MB_ICONERROR);
1123 LONG version = g_Git.Hash2int(hash);
1125 ATL::CComBSTR temp;
1126 if (FAILED(hr = pProvider->OnCommitFinished(GetSafeHwnd(),
1127 commonRoot,
1128 pathList,
1129 logMessage,
1130 (LONG)version,
1131 &temp)))
1133 CString sErr = temp;
1134 if (!sErr.IsEmpty())
1135 CMessageBox::Show(NULL,(sErr),_T("TortoiseGit"),MB_OK|MB_ICONERROR);
1136 else
1138 COMError ce(hr);
1139 sErr.Format(IDS_ERR_FAILEDISSUETRACKERCOM, ce.GetSource().c_str(), ce.GetMessageAndDescription().c_str());
1140 CMessageBox::Show(NULL,(sErr),_T("TortoiseGit"),MB_OK|MB_ICONERROR);
1145 RestoreFiles(progress.m_GitStatus == 0, false);
1146 if (((DWORD)CRegStdDWORD(_T("Software\\TortoiseGit\\ReaddUnselectedAddedFilesAfterCommit"), TRUE)) == TRUE)
1148 BOOL cancel = FALSE;
1149 mgtReAddAfterCommit.Execute(cancel);
1150 mgtReDelAfterCommit.Execute(cancel);
1153 else if(bAddSuccess)
1155 CMessageBox::Show(this->m_hWnd, IDS_ERROR_NOTHING_COMMIT, IDS_COMMIT_FINISH, MB_OK | MB_ICONINFORMATION);
1156 bCloseCommitDlg=false;
1159 UpdateData();
1160 m_regAddBeforeCommit = m_bShowUnversioned;
1161 m_regKeepChangelists = m_bKeepChangeList;
1162 m_regDoNotAutoselectSubmodules = m_bDoNotAutoselectSubmodules;
1163 if (!GetDlgItem(IDC_KEEPLISTS)->IsWindowEnabled())
1164 m_bKeepChangeList = FALSE;
1165 InterlockedExchange(&m_bBlock, FALSE);
1167 if (!m_sLogMessage.IsEmpty())
1169 ReloadHistoryEntries();
1170 m_History.AddEntry(m_sLogMessage);
1171 m_History.Save();
1174 SaveSplitterPos();
1176 if (bCloseCommitDlg)
1178 if (m_ctrlOkButton.GetCurrentEntry() == 2)
1179 DoPush();
1180 CResizableStandAloneDialog::OnOK();
1182 else if (m_PostCmd == GIT_POSTCOMMIT_CMD_RECOMMIT)
1184 this->Refresh();
1185 this->BringWindowToTop();
1188 CShellUpdater::Instance().Flush();
1191 void CCommitDlg::SaveSplitterPos()
1193 if (!IsIconic())
1195 CRegDWORD regPos(_T("Software\\TortoiseGit\\TortoiseProc\\ResizableState\\CommitDlgSizer"));
1196 RECT rectSplitter;
1197 m_wndSplitter.GetWindowRect(&rectSplitter);
1198 ScreenToClient(&rectSplitter);
1199 regPos = rectSplitter.top;
1203 UINT CCommitDlg::StatusThreadEntry(LPVOID pVoid)
1205 return ((CCommitDlg*)pVoid)->StatusThread();
1208 void CCommitDlg::ReloadHistoryEntries()
1210 CString reg;
1211 reg.Format(_T("Software\\TortoiseGit\\History\\commit%s"), (LPCTSTR)m_ListCtrl.m_sUUID);
1212 reg.Replace(_T(':'), _T('_'));
1213 m_History.Load(reg, _T("logmsgs"));
1216 UINT CCommitDlg::StatusThread()
1218 //get the status of all selected file/folders recursively
1219 //and show the ones which have to be committed to the user
1220 //in a list control.
1221 m_pathwatcher.Stop();
1223 m_ListCtrl.SetBusy(true);
1224 g_Git.RefreshGitIndex();
1226 m_bCancelled = false;
1228 DialogEnableWindow(IDOK, false);
1229 DialogEnableWindow(IDC_SHOWUNVERSIONED, false);
1230 DialogEnableWindow(IDC_WHOLE_PROJECT, false);
1231 DialogEnableWindow(IDC_NOAUTOSELECTSUBMODULES, false);
1232 GetDlgItem(IDC_EXTERNALWARNING)->ShowWindow(SW_HIDE);
1233 DialogEnableWindow(IDC_EXTERNALWARNING, false);
1234 DialogEnableWindow(IDC_COMMIT_AMEND, FALSE);
1235 DialogEnableWindow(IDC_COMMIT_AMENDDIFF, FALSE);
1236 // read the list of recent log entries before querying the WC for status
1237 // -> the user may select one and modify / update it while we are crawling the WC
1239 DialogEnableWindow(IDC_CHECKALL, false);
1240 DialogEnableWindow(IDC_CHECKNONE, false);
1241 DialogEnableWindow(IDC_CHECKUNVERSIONED, false);
1242 DialogEnableWindow(IDC_CHECKVERSIONED, false);
1243 DialogEnableWindow(IDC_CHECKADDED, false);
1244 DialogEnableWindow(IDC_CHECKDELETED, false);
1245 DialogEnableWindow(IDC_CHECKMODIFIED, false);
1246 DialogEnableWindow(IDC_CHECKFILES, false);
1247 DialogEnableWindow(IDC_CHECKSUBMODULES, false);
1249 CString dotGitPath;
1250 GitAdminDir::GetAdminDirPath(g_Git.m_CurrentDir, dotGitPath);
1251 if (PathFileExists(dotGitPath + _T("CHERRY_PICK_HEAD")))
1253 GetDlgItem(IDC_COMMIT_AMENDDIFF)->ShowWindow(SW_HIDE);
1254 m_bCommitAmend = FALSE;
1255 SendMessage(WM_UPDATEDATAFALSE);
1258 // Initialise the list control with the status of the files/folders below us
1259 m_ListCtrl.Clear();
1260 BOOL success;
1261 CTGitPathList *pList;
1262 m_ListCtrl.m_amend = (m_bCommitAmend==TRUE || m_bForceCommitAmend) && (m_bAmendDiffToLastCommit==FALSE);
1263 m_ListCtrl.m_bDoNotAutoselectSubmodules = (m_bDoNotAutoselectSubmodules == TRUE);
1265 if(m_bWholeProject || m_bWholeProject2)
1266 pList=NULL;
1267 else
1268 pList = &m_pathList;
1270 success=m_ListCtrl.GetStatus(pList);
1272 //m_ListCtrl.UpdateFileList(git_revnum_t(GIT_REV_ZERO));
1273 if(this->m_bShowUnversioned)
1274 m_ListCtrl.UpdateFileList(CGitStatusListCtrl::FILELIST_UNVER,true,pList);
1276 m_ListCtrl.CheckIfChangelistsArePresent(false);
1278 DWORD dwShow = GITSLC_SHOWVERSIONEDBUTNORMALANDEXTERNALSFROMDIFFERENTREPOS | GITSLC_SHOWLOCKS | GITSLC_SHOWINCHANGELIST | GITSLC_SHOWDIRECTFILES;
1279 dwShow |= DWORD(m_regAddBeforeCommit) ? GITSLC_SHOWUNVERSIONED : 0;
1280 if (success)
1282 if (!m_checkedPathList.IsEmpty())
1283 m_ListCtrl.Show(dwShow, m_checkedPathList);
1284 else
1286 DWORD dwCheck = m_bSelectFilesForCommit ? dwShow : 0;
1287 dwCheck &=~(CTGitPath::LOGACTIONS_UNVER); //don't check unversion file default.
1288 m_ListCtrl.Show(dwShow, dwCheck);
1289 m_bSelectFilesForCommit = true;
1292 if (m_ListCtrl.HasExternalsFromDifferentRepos())
1294 GetDlgItem(IDC_EXTERNALWARNING)->ShowWindow(SW_SHOW);
1295 DialogEnableWindow(IDC_EXTERNALWARNING, TRUE);
1298 SetDlgItemText(IDC_COMMIT_TO, g_Git.GetCurrentBranch());
1299 m_tooltips.AddTool(GetDlgItem(IDC_STATISTICS), m_ListCtrl.GetStatisticsString());
1300 if (m_ListCtrl.GetItemCount() != 0)
1301 m_ListCtrl.SetItemState(0, LVIS_SELECTED, LVIS_SELECTED);
1303 if (!success)
1305 if (!m_ListCtrl.GetLastErrorMessage().IsEmpty())
1306 m_ListCtrl.SetEmptyString(m_ListCtrl.GetLastErrorMessage());
1307 m_ListCtrl.Show(dwShow);
1310 if ((m_ListCtrl.GetItemCount()==0)&&(m_ListCtrl.HasUnversionedItems())
1311 && !PathFileExists(dotGitPath + _T("MERGE_HEAD")))
1313 CString temp;
1314 temp.LoadString(IDS_COMMITDLG_NOTHINGTOCOMMITUNVERSIONED);
1315 if (CMessageBox::ShowCheck(m_hWnd, temp, _T("TortoiseGit"), MB_ICONINFORMATION | MB_YESNO, _T("NothingToCommitShowUnversioned"), NULL)==IDYES)
1317 m_bShowUnversioned = TRUE;
1318 GetDlgItem(IDC_SHOWUNVERSIONED)->SendMessage(BM_SETCHECK, BST_CHECKED);
1319 dwShow = (DWORD)(GITSLC_SHOWVERSIONEDBUTNORMALANDEXTERNALSFROMDIFFERENTREPOS | GITSLC_SHOWUNVERSIONED | GITSLC_SHOWLOCKS);
1320 m_ListCtrl.UpdateFileList(CGitStatusListCtrl::FILELIST_UNVER);
1321 m_ListCtrl.Show(dwShow,dwShow&(~CTGitPath::LOGACTIONS_UNVER));
1325 SetDlgTitle();
1327 m_autolist.clear();
1328 // we don't have to block the commit dialog while we fetch the
1329 // auto completion list.
1330 m_pathwatcher.ClearChangedPaths();
1331 InterlockedExchange(&m_bBlock, FALSE);
1332 if ((DWORD)CRegDWORD(_T("Software\\TortoiseGit\\Autocompletion"), TRUE)==TRUE)
1334 m_ListCtrl.Block(TRUE, TRUE);
1335 GetAutocompletionList();
1336 m_ListCtrl.Block(FALSE, FALSE);
1338 SendMessage(WM_UPDATEOKBUTTON);
1339 if (m_bRunThread)
1341 DialogEnableWindow(IDC_SHOWUNVERSIONED, true);
1342 DialogEnableWindow(IDC_WHOLE_PROJECT, !m_bWholeProject2);
1343 DialogEnableWindow(IDC_NOAUTOSELECTSUBMODULES, true);
1344 if (m_ListCtrl.HasChangeLists())
1345 DialogEnableWindow(IDC_KEEPLISTS, true);
1347 // activate amend checkbox (if necessary)
1348 if (g_Git.IsInitRepos())
1350 m_bCommitAmend = FALSE;
1351 SendMessage(WM_UPDATEDATAFALSE);
1353 else
1355 if (m_bForceCommitAmend)
1357 m_bCommitAmend = TRUE;
1358 SendMessage(WM_UPDATEDATAFALSE);
1360 else
1361 GetDlgItem(IDC_COMMIT_AMEND)->EnableWindow(!PathFileExists(dotGitPath + _T("CHERRY_PICK_HEAD")));
1363 CGitHash hash;
1364 if (g_Git.GetHash(hash, _T("HEAD")))
1366 MessageBox(g_Git.GetGitLastErr(_T("Could not get HEAD hash.")), _T("TortoiseGit"), MB_ICONERROR);
1368 if (!hash.IsEmpty())
1370 GitRev headRevision;
1371 if (headRevision.GetParentFromHash(hash))
1372 MessageBox(headRevision.GetLastErr(), _T("TortoiseGit"), MB_ICONERROR);
1373 // do not allow to show diff to "last" revision if it has more that one parent
1374 if (headRevision.ParentsCount() != 1)
1376 m_bAmendDiffToLastCommit = TRUE;
1377 SendMessage(WM_UPDATEDATAFALSE);
1379 else
1380 GetDlgItem(IDC_COMMIT_AMENDDIFF)->EnableWindow(TRUE);
1384 UpdateCheckLinks();
1386 // we have the list, now signal the main thread about it
1387 SendMessage(WM_AUTOLISTREADY); // only send the message if the thread wasn't told to quit!
1390 InterlockedExchange(&m_bRunThread, FALSE);
1391 InterlockedExchange(&m_bThreadRunning, FALSE);
1392 // force the cursor to normal
1393 RefreshCursor();
1395 return 0;
1398 void CCommitDlg::SetDlgTitle()
1400 if (m_sTitle.IsEmpty())
1401 GetWindowText(m_sTitle);
1403 if (m_bWholeProject || m_bWholeProject2)
1404 CAppUtils::SetWindowTitle(m_hWnd, g_Git.m_CurrentDir, m_sTitle);
1405 else
1407 if (m_pathList.GetCount() == 1)
1408 CAppUtils::SetWindowTitle(m_hWnd, g_Git.CombinePath(m_pathList[0].GetUIPathString()), m_sTitle);
1409 else
1410 CAppUtils::SetWindowTitle(m_hWnd, g_Git.CombinePath(m_ListCtrl.GetCommonDirectory(false)), m_sTitle);
1414 void CCommitDlg::OnCancel()
1416 m_bCancelled = true;
1417 m_pathwatcher.Stop();
1419 if (m_bThreadRunning)
1420 StopStatusThread();
1421 if (!RestoreFiles())
1422 return;
1423 UpdateData();
1424 m_sBugID.Trim();
1425 m_sLogMessage = m_cLogMessage.GetText();
1426 if (!m_sBugID.IsEmpty())
1428 m_sBugID.Replace(_T(", "), _T(","));
1429 m_sBugID.Replace(_T(" ,"), _T(","));
1430 CString sBugID = m_ProjectProperties.sMessage;
1431 sBugID.Replace(_T("%BUGID%"), m_sBugID);
1432 if (m_ProjectProperties.bAppend)
1433 m_sLogMessage += _T("\n") + sBugID + _T("\n");
1434 else
1435 m_sLogMessage = sBugID + _T("\n") + m_sLogMessage;
1437 if ((m_sLogTemplate.Compare(m_sLogMessage) != 0) && !m_sLogMessage.IsEmpty())
1439 ReloadHistoryEntries();
1440 m_History.AddEntry(m_sLogMessage);
1441 m_History.Save();
1443 SaveSplitterPos();
1444 CResizableStandAloneDialog::OnCancel();
1447 BOOL CCommitDlg::PreTranslateMessage(MSG* pMsg)
1449 if (m_hAccel)
1451 int ret = TranslateAccelerator(m_hWnd, m_hAccel, pMsg);
1452 if (ret)
1453 return TRUE;
1455 if (m_hAccelOkButton && GetDlgItem(IDOK)->IsWindowEnabled() && TranslateAccelerator(m_hWnd, m_hAccelOkButton, pMsg))
1456 return TRUE;
1458 if (pMsg->message == WM_KEYDOWN)
1460 switch (pMsg->wParam)
1462 case VK_F5:
1464 if (m_bBlock)
1465 return CResizableStandAloneDialog::PreTranslateMessage(pMsg);
1466 Refresh();
1468 break;
1469 case VK_RETURN:
1471 if (GetAsyncKeyState(VK_CONTROL)&0x8000)
1473 if ( GetDlgItem(IDOK)->IsWindowEnabled() )
1475 PostMessage(WM_COMMAND, IDOK);
1477 return TRUE;
1479 if ( GetFocus()==GetDlgItem(IDC_BUGID) )
1481 // Pressing RETURN in the bug id control
1482 // moves the focus to the message
1483 GetDlgItem(IDC_LOGMESSAGE)->SetFocus();
1484 return TRUE;
1487 break;
1491 return CResizableStandAloneDialog::PreTranslateMessage(pMsg);
1494 void CCommitDlg::Refresh()
1496 if (m_bThreadRunning)
1497 return;
1499 StartStatusThread();
1502 void CCommitDlg::StartStatusThread()
1504 if (InterlockedExchange(&m_bBlock, TRUE) != FALSE)
1505 return;
1507 delete m_pThread;
1508 m_pThread = nullptr;
1510 m_pThread = AfxBeginThread(StatusThreadEntry, this, THREAD_PRIORITY_NORMAL, 0, CREATE_SUSPENDED);
1511 if (!m_pThread)
1513 CMessageBox::Show(GetSafeHwnd(), IDS_ERR_THREADSTARTFAILED, IDS_APPNAME, MB_OK | MB_ICONERROR);
1514 InterlockedExchange(&m_bBlock, FALSE);
1515 return;
1517 InterlockedExchange(&m_bThreadRunning, TRUE);// so the main thread knows that this thread is still running
1518 InterlockedExchange(&m_bRunThread, TRUE); // if this is set to FALSE, the thread should stop
1519 m_pThread->m_bAutoDelete = FALSE;
1520 m_pThread->ResumeThread();
1523 void CCommitDlg::StopStatusThread()
1525 InterlockedExchange(&m_bRunThread, FALSE);
1526 WaitForSingleObject(m_pThread->m_hThread, 1000);
1527 if (!m_bThreadRunning)
1528 return;
1530 // we gave the thread a chance to quit. Since the thread didn't
1531 // listen to us we have to kill it.
1532 TerminateThread(m_pThread->m_hThread, (DWORD)-1);
1533 InterlockedExchange(&m_bThreadRunning, FALSE);
1536 void CCommitDlg::OnBnClickedShowunversioned()
1538 m_tooltips.Pop(); // hide the tooltips
1539 UpdateData();
1540 m_regAddBeforeCommit = m_bShowUnversioned;
1541 if (!m_bBlock)
1543 DWORD dwShow = m_ListCtrl.GetShowFlags();
1544 if (DWORD(m_regAddBeforeCommit))
1545 dwShow |= GITSLC_SHOWUNVERSIONED;
1546 else
1547 dwShow &= ~GITSLC_SHOWUNVERSIONED;
1548 if(dwShow & GITSLC_SHOWUNVERSIONED)
1550 if (m_bWholeProject || m_bWholeProject2)
1551 m_ListCtrl.GetStatus(NULL,false,false,true);
1552 else
1553 m_ListCtrl.GetStatus(&this->m_pathList,false,false,true);
1555 m_ListCtrl.Show(dwShow, 0, true, dwShow & ~(CTGitPath::LOGACTIONS_UNVER), true);
1556 UpdateCheckLinks();
1560 void CCommitDlg::OnStnClickedExternalwarning()
1562 m_tooltips.Popup();
1565 void CCommitDlg::OnEnChangeLogmessage()
1567 SendMessage(WM_UPDATEOKBUTTON);
1570 LRESULT CCommitDlg::OnGitStatusListCtrlItemCountChanged(WPARAM, LPARAM)
1572 #if 0
1573 if ((m_ListCtrl.GetItemCount() == 0)&&(m_ListCtrl.HasUnversionedItems())&&(!m_bShowUnversioned))
1575 if (CMessageBox::Show(*this, IDS_COMMITDLG_NOTHINGTOCOMMITUNVERSIONED, IDS_APPNAME, MB_ICONINFORMATION | MB_YESNO)==IDYES)
1577 m_bShowUnversioned = TRUE;
1578 DWORD dwShow = GitSLC_SHOWVERSIONEDBUTNORMALANDEXTERNALSFROMDIFFERENTREPOS | GitSLC_SHOWUNVERSIONED | GitSLC_SHOWLOCKS;
1579 m_ListCtrl.Show(dwShow);
1580 UpdateData(FALSE);
1583 #endif
1584 return 0;
1587 LRESULT CCommitDlg::OnGitStatusListCtrlNeedsRefresh(WPARAM, LPARAM)
1589 Refresh();
1590 return 0;
1593 LRESULT CCommitDlg::OnFileDropped(WPARAM, LPARAM /*lParam*/)
1595 #if 0
1596 BringWindowToTop();
1597 SetForegroundWindow();
1598 SetActiveWindow();
1599 // if multiple files/folders are dropped
1600 // this handler is called for every single item
1601 // separately.
1602 // To avoid creating multiple refresh threads and
1603 // causing crashes, we only add the items to the
1604 // list control and start a timer.
1605 // When the timer expires, we start the refresh thread,
1606 // but only if it isn't already running - otherwise we
1607 // restart the timer.
1608 CTGitPath path;
1609 path.SetFromWin((LPCTSTR)lParam);
1611 // just add all the items we get here.
1612 // if the item is versioned, the add will fail but nothing
1613 // more will happen.
1614 Git Git;
1615 Git.Add(CTGitPathList(path), &m_ProjectProperties, Git_depth_empty, false, true, true);
1617 if (!m_ListCtrl.HasPath(path))
1619 if (m_pathList.AreAllPathsFiles())
1621 m_pathList.AddPath(path);
1622 m_pathList.RemoveDuplicates();
1623 m_updatedPathList.AddPath(path);
1624 m_updatedPathList.RemoveDuplicates();
1626 else
1628 // if the path list contains folders, we have to check whether
1629 // our just (maybe) added path is a child of one of those. If it is
1630 // a child of a folder already in the list, we must not add it. Otherwise
1631 // that path could show up twice in the list.
1632 bool bHasParentInList = false;
1633 for (int i=0; i<m_pathList.GetCount(); ++i)
1635 if (m_pathList[i].IsAncestorOf(path))
1637 bHasParentInList = true;
1638 break;
1641 if (!bHasParentInList)
1643 m_pathList.AddPath(path);
1644 m_pathList.RemoveDuplicates();
1645 m_updatedPathList.AddPath(path);
1646 m_updatedPathList.RemoveDuplicates();
1651 // Always start the timer, since the status of an existing item might have changed
1652 SetTimer(REFRESHTIMER, 200, NULL);
1653 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": Item %s dropped, timer started\n"), path.GetWinPath());
1654 #endif
1655 return 0;
1658 LRESULT CCommitDlg::OnAutoListReady(WPARAM, LPARAM)
1660 m_cLogMessage.SetAutoCompletionList(m_autolist, '*');
1661 return 0;
1664 //////////////////////////////////////////////////////////////////////////
1665 // functions which run in the status thread
1666 //////////////////////////////////////////////////////////////////////////
1668 void CCommitDlg::ParseRegexFile(const CString& sFile, std::map<CString, CString>& mapRegex)
1670 CString strLine;
1673 CStdioFile file(sFile, CFile::typeText | CFile::modeRead | CFile::shareDenyWrite);
1674 while (m_bRunThread && file.ReadString(strLine))
1676 if (strLine.IsEmpty())
1677 continue;
1678 if (strLine.Left(1) == L'#')
1679 continue;
1680 int eqpos = strLine.Find('=');
1681 CString rgx;
1682 rgx = strLine.Mid(eqpos+1).Trim();
1684 int pos = -1;
1685 while (((pos = strLine.Find(','))>=0)&&(pos < eqpos))
1687 mapRegex[strLine.Left(pos)] = rgx;
1688 strLine = strLine.Mid(pos+1).Trim();
1690 mapRegex[strLine.Left(strLine.Find('=')).Trim()] = rgx;
1692 file.Close();
1694 catch (CFileException* pE)
1696 CTraceToOutputDebugString::Instance()(__FUNCTION__ ": CFileException loading auto list regex file\n");
1697 pE->Delete();
1701 void CCommitDlg::ParseSnippetFile(const CString& sFile, std::map<CString, CString>& mapSnippet)
1703 CString strLine;
1706 CStdioFile file(sFile, CFile::typeText | CFile::modeRead | CFile::shareDenyWrite);
1707 while (m_bRunThread && file.ReadString(strLine))
1709 if (strLine.IsEmpty())
1710 continue;
1711 if (strLine.Left(1) == _T('#')) // comment char
1712 continue;
1713 int eqpos = strLine.Find('=');
1714 CString key = strLine.Left(eqpos);
1715 CString value = strLine.Mid(eqpos + 1);
1716 value.Replace(_T("\\\t"), _T("\t"));
1717 value.Replace(_T("\\\r"), _T("\r"));
1718 value.Replace(_T("\\\n"), _T("\n"));
1719 value.Replace(_T("\\\\"), _T("\\"));
1720 mapSnippet[key] = value;
1722 file.Close();
1724 catch (CFileException* pE)
1726 CTraceToOutputDebugString::Instance()(__FUNCTION__ ": CFileException loading auto list regex file\n");
1727 pE->Delete();
1731 void CCommitDlg::GetAutocompletionList()
1733 // the auto completion list is made of strings from each selected files.
1734 // the strings used are extracted from the files with regexes found
1735 // in the file "autolist.txt".
1736 // the format of that file is:
1737 // file extensions separated with commas '=' regular expression to use
1738 // example:
1739 // .h, .hpp = (?<=class[\s])\b\w+\b|(\b\w+(?=[\s ]?\(\);))
1740 // .cpp = (?<=[^\s]::)\b\w+\b
1742 std::map<CString, CString> mapRegex;
1743 CString sRegexFile = CPathUtils::GetAppDirectory();
1744 CRegDWORD regtimeout = CRegDWORD(_T("Software\\TortoiseGit\\AutocompleteParseTimeout"), 5);
1745 ULONGLONG timeoutvalue = ULONGLONG(DWORD(regtimeout)) * 1000UL;;
1746 sRegexFile += _T("autolist.txt");
1747 if (!m_bRunThread)
1748 return;
1749 ParseRegexFile(sRegexFile, mapRegex);
1750 sRegexFile = CPathUtils::GetAppDataDirectory();
1751 sRegexFile += _T("autolist.txt");
1752 if (PathFileExists(sRegexFile))
1753 ParseRegexFile(sRegexFile, mapRegex);
1755 m_snippet.clear();
1756 CString sSnippetFile = CPathUtils::GetAppDirectory();
1757 sSnippetFile += _T("snippet.txt");
1758 ParseSnippetFile(sSnippetFile, m_snippet);
1759 sSnippetFile = CPathUtils::GetAppDataDirectory();
1760 sSnippetFile += _T("snippet.txt");
1761 if (PathFileExists(sSnippetFile))
1762 ParseSnippetFile(sSnippetFile, m_snippet);
1763 for (const auto& snip : m_snippet)
1764 m_autolist.emplace(snip.first, AUTOCOMPLETE_SNIPPET);
1766 ULONGLONG starttime = GetTickCount64();
1768 // now we have two arrays of strings, where the first array contains all
1769 // file extensions we can use and the second the corresponding regex strings
1770 // to apply to those files.
1772 // the next step is to go over all files shown in the commit dialog
1773 // and scan them for strings we can use
1774 int nListItems = m_ListCtrl.GetItemCount();
1776 for (int i=0; i<nListItems && m_bRunThread; ++i)
1778 // stop parsing after timeout
1779 if ((!m_bRunThread) || (GetTickCount64() - starttime > timeoutvalue))
1780 return;
1782 CTGitPath *path = (CTGitPath*)m_ListCtrl.GetItemData(i);
1784 if(path == NULL)
1785 continue;
1787 CString sPartPath =path->GetGitPathString();
1788 m_autolist.emplace(sPartPath, AUTOCOMPLETE_FILENAME);
1790 int pos = 0;
1791 int lastPos = 0;
1792 while ((pos = sPartPath.Find('/', pos)) >= 0)
1794 ++pos;
1795 lastPos = pos;
1796 m_autolist.emplace(sPartPath.Mid(pos), AUTOCOMPLETE_FILENAME);
1799 // Last inserted entry is a file name.
1800 // Some users prefer to also list file name without extension.
1801 if (CRegDWORD(_T("Software\\TortoiseGit\\AutocompleteRemovesExtensions"), FALSE))
1803 int dotPos = sPartPath.ReverseFind('.');
1804 if ((dotPos >= 0) && (dotPos > lastPos))
1805 m_autolist.emplace(sPartPath.Mid(lastPos, dotPos - lastPos), AUTOCOMPLETE_FILENAME);
1808 if (path->m_Action == CTGitPath::LOGACTIONS_UNVER && !CRegDWORD(_T("Software\\TortoiseGit\\AutocompleteParseUnversioned"), FALSE))
1809 continue;
1810 if (path->m_Action == CTGitPath::LOGACTIONS_IGNORE)
1811 continue;
1813 CString sExt = path->GetFileExtension();
1814 sExt.MakeLower();
1815 // find the regex string which corresponds to the file extension
1816 CString rdata = mapRegex[sExt];
1817 if (rdata.IsEmpty())
1818 continue;
1820 ScanFile(path->GetWinPathString(), rdata, sExt);
1822 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": Auto completion list loaded in %I64u msec\n"), GetTickCount64() - starttime);
1825 void CCommitDlg::ScanFile(const CString& sFilePath, const CString& sRegex, const CString& sExt)
1827 static std::map<CString, std::tr1::wregex> regexmap;
1829 std::wstring sFileContent;
1830 CAutoFile hFile = CreateFile(sFilePath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL);
1831 if (hFile)
1833 DWORD size = GetFileSize(hFile, NULL);
1834 if (size > CRegDWORD(_T("Software\\TortoiseGit\\AutocompleteParseMaxSize"), 300000L))
1836 // no files bigger than 300k
1837 return;
1839 // allocate memory to hold file contents
1840 auto buffer = std::make_unique<char[]>(size);
1841 DWORD readbytes;
1842 if (!ReadFile(hFile, buffer.get(), size, &readbytes, NULL))
1843 return;
1844 int opts = 0;
1845 IsTextUnicode(buffer.get(), readbytes, &opts);
1846 if (opts & IS_TEXT_UNICODE_NULL_BYTES)
1848 return;
1850 if (opts & IS_TEXT_UNICODE_UNICODE_MASK)
1852 sFileContent = std::wstring((wchar_t*)buffer.get(), readbytes / sizeof(WCHAR));
1854 if ((opts & IS_TEXT_UNICODE_NOT_UNICODE_MASK) || (opts == 0))
1856 const int ret = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, (LPCSTR)buffer.get(), readbytes, NULL, 0);
1857 auto pWideBuf = std::make_unique<wchar_t[]>(ret);
1858 const int ret2 = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, (LPCSTR)buffer.get(), readbytes, pWideBuf.get(), ret);
1859 if (ret2 == ret)
1860 sFileContent = std::wstring(pWideBuf.get(), ret);
1863 if (sFileContent.empty() || !m_bRunThread)
1865 return;
1871 std::tr1::wregex regCheck;
1872 std::map<CString, std::tr1::wregex>::const_iterator regIt;
1873 if ((regIt = regexmap.find(sExt)) != regexmap.end())
1874 regCheck = regIt->second;
1875 else
1877 regCheck = std::tr1::wregex(sRegex, std::tr1::regex_constants::icase | std::tr1::regex_constants::ECMAScript);
1878 regexmap[sExt] = regCheck;
1880 const std::tr1::wsregex_iterator end;
1881 for (std::tr1::wsregex_iterator it(sFileContent.cbegin(), sFileContent.cend(), regCheck); it != end; ++it)
1883 const std::tr1::wsmatch match = *it;
1884 for (size_t i = 1; i < match.size(); ++i)
1886 if (match[i].second-match[i].first)
1888 m_autolist.emplace(std::wstring(match[i]).c_str(), AUTOCOMPLETE_PROGRAMCODE);
1893 catch (std::exception) {}
1896 // CSciEditContextMenuInterface
1897 void CCommitDlg::InsertMenuItems(CMenu& mPopup, int& nCmd)
1899 CString sMenuItemText;
1900 sMenuItemText.LoadString(IDS_COMMITDLG_POPUP_PICKCOMMITHASH);
1901 m_nPopupPickCommitHash = nCmd++;
1902 mPopup.AppendMenu(MF_STRING | MF_ENABLED, m_nPopupPickCommitHash, sMenuItemText);
1904 sMenuItemText.LoadString(IDS_COMMITDLG_POPUP_PICKCOMMITMESSAGE);
1905 m_nPopupPickCommitMessage = nCmd++;
1906 mPopup.AppendMenu(MF_STRING | MF_ENABLED, m_nPopupPickCommitMessage, sMenuItemText);
1908 sMenuItemText.LoadString(IDS_COMMITDLG_POPUP_PASTEFILELIST);
1909 m_nPopupPasteListCmd = nCmd++;
1910 mPopup.AppendMenu(MF_STRING | MF_ENABLED, m_nPopupPasteListCmd, sMenuItemText);
1912 ReloadHistoryEntries();
1913 if (!m_History.IsEmpty())
1915 sMenuItemText.LoadString(IDS_COMMITDLG_POPUP_PASTELASTMESSAGE);
1916 m_nPopupPasteLastMessage = nCmd++;
1917 mPopup.AppendMenu(MF_STRING | MF_ENABLED, m_nPopupPasteLastMessage, sMenuItemText);
1919 sMenuItemText.LoadString(IDS_COMMITDLG_POPUP_LOGHISTORY);
1920 m_nPopupRecentMessage = nCmd++;
1921 mPopup.AppendMenu(MF_STRING | MF_ENABLED, m_nPopupRecentMessage, sMenuItemText);
1925 bool CCommitDlg::HandleMenuItemClick(int cmd, CSciEdit * pSciEdit)
1927 if (cmd == m_nPopupPickCommitHash)
1929 // use the git log to allow selection of a version
1930 CLogDlg dlg;
1931 // tell the dialog to use mode for selecting revisions
1932 dlg.SetSelect(true);
1933 // only one revision must be selected however
1934 dlg.SingleSelection(true);
1935 dlg.ShowWorkingTreeChanges(false);
1936 if (dlg.DoModal() == IDOK)
1937 pSciEdit->InsertText(dlg.GetSelectedHash().at(0).ToString());
1938 return true;
1941 if (cmd == m_nPopupPickCommitMessage)
1943 // use the git log to allow selection of a version
1944 CLogDlg dlg;
1945 // tell the dialog to use mode for selecting revisions
1946 dlg.SetSelect(true);
1947 // only one revision must be selected however
1948 dlg.SingleSelection(true);
1949 dlg.ShowWorkingTreeChanges(false);
1950 if (dlg.DoModal() == IDOK)
1952 GitRev rev;
1953 if (rev.GetCommit(dlg.GetSelectedHash().at(0).ToString()))
1955 MessageBox(rev.GetLastErr(), _T("TortoiseGit"), MB_ICONERROR);
1956 return false;
1958 CString message = rev.GetSubject() + _T("\r\n") + rev.GetBody();
1959 pSciEdit->InsertText(message);
1961 return true;
1964 if (cmd == m_nPopupPasteListCmd)
1966 CString logmsg;
1967 int nListItems = m_ListCtrl.GetItemCount();
1968 for (int i=0; i<nListItems; ++i)
1970 CTGitPath * entry = (CTGitPath*)m_ListCtrl.GetItemData(i);
1971 if (entry&&entry->m_Checked)
1973 CString line;
1974 CString status = entry->GetActionName();
1975 if(entry->m_Action & CTGitPath::LOGACTIONS_UNVER)
1976 status = _T("Add"); // I18N TODO
1978 //git_wc_status_kind status = entry->status;
1979 WORD langID = (WORD)CRegStdDWORD(_T("Software\\TortoiseGit\\LanguageID"), GetUserDefaultLangID());
1980 if (m_ProjectProperties.bFileListInEnglish)
1981 langID = 1033;
1983 line.Format(_T("%-10s %s\r\n"),status , (LPCTSTR)m_ListCtrl.GetItemText(i,0));
1984 logmsg += line;
1987 pSciEdit->InsertText(logmsg);
1988 return true;
1991 if(cmd == m_nPopupPasteLastMessage)
1993 if (m_History.IsEmpty())
1994 return false;
1996 CString logmsg;
1997 logmsg +=m_History.GetEntry(0);
1998 pSciEdit->InsertText(logmsg);
1999 return true;
2002 if(cmd == m_nPopupRecentMessage )
2004 OnBnClickedHistory();
2005 return true;
2007 return false;
2010 void CCommitDlg::HandleSnippet(int type, const CString &text, CSciEdit *pSciEdit)
2012 if (type == AUTOCOMPLETE_SNIPPET)
2014 CString target = m_snippet[text];
2015 pSciEdit->GetWordUnderCursor(true);
2016 pSciEdit->InsertText(target, false);
2020 void CCommitDlg::OnTimer(UINT_PTR nIDEvent)
2022 switch (nIDEvent)
2024 case ENDDIALOGTIMER:
2025 KillTimer(ENDDIALOGTIMER);
2026 EndDialog(0);
2027 break;
2028 case REFRESHTIMER:
2029 if (m_bThreadRunning)
2031 SetTimer(REFRESHTIMER, 200, NULL);
2032 CTraceToOutputDebugString::Instance()(__FUNCTION__ ": Wait some more before refreshing\n");
2034 else
2036 KillTimer(REFRESHTIMER);
2037 CTraceToOutputDebugString::Instance()(__FUNCTION__ ": Refreshing after items dropped\n");
2038 Refresh();
2040 break;
2041 case FILLPATCHVTIMER:
2042 FillPatchView();
2043 break;
2045 __super::OnTimer(nIDEvent);
2048 void CCommitDlg::OnBnClickedHistory()
2050 m_tooltips.Pop(); // hide the tooltips
2051 if (m_pathList.IsEmpty())
2052 return;
2054 CHistoryDlg historyDlg;
2055 ReloadHistoryEntries();
2056 historyDlg.SetHistory(m_History);
2057 if (historyDlg.DoModal() != IDOK)
2058 return;
2060 CString sMsg = historyDlg.GetSelectedText();
2061 if (sMsg != m_cLogMessage.GetText().Left(sMsg.GetLength()))
2063 CString sBugID = m_ProjectProperties.FindBugID(sMsg);
2064 if ((!sBugID.IsEmpty()) && ((GetDlgItem(IDC_BUGID)->IsWindowVisible())))
2066 SetDlgItemText(IDC_BUGID, sBugID);
2068 if (m_sLogTemplate.Compare(m_cLogMessage.GetText()) != 0)
2069 m_cLogMessage.InsertText(sMsg, !m_cLogMessage.GetText().IsEmpty());
2070 else
2071 m_cLogMessage.SetText(sMsg);
2074 SendMessage(WM_UPDATEOKBUTTON);
2075 GetDlgItem(IDC_LOGMESSAGE)->SetFocus();
2079 void CCommitDlg::OnBnClickedBugtraqbutton()
2081 m_tooltips.Pop(); // hide the tooltips
2082 CString sMsg = m_cLogMessage.GetText();
2084 if (m_BugTraqProvider == NULL)
2085 return;
2087 ATL::CComBSTR parameters(m_bugtraq_association.GetParameters());
2088 ATL::CComBSTR commonRoot(m_pathList.GetCommonRoot().GetDirectory().GetWinPath());
2089 CBstrSafeVector pathList(m_pathList.GetCount());
2091 for (LONG index = 0; index < m_pathList.GetCount(); ++index)
2092 pathList.PutElement(index, m_pathList[index].GetGitPathString());
2094 ATL::CComBSTR originalMessage(sMsg);
2095 ATL::CComBSTR temp;
2097 // first try the IBugTraqProvider2 interface
2098 CComPtr<IBugTraqProvider2> pProvider2 = NULL;
2099 HRESULT hr = m_BugTraqProvider.QueryInterface(&pProvider2);
2100 bool bugIdOutSet = false;
2101 if (SUCCEEDED(hr))
2103 ATL::CComBSTR repositoryRoot(g_Git.m_CurrentDir);
2104 ATL::CComBSTR bugIDOut;
2105 GetDlgItemText(IDC_BUGID, m_sBugID);
2106 ATL::CComBSTR bugID(m_sBugID);
2107 CBstrSafeVector revPropNames;
2108 CBstrSafeVector revPropValues;
2109 if (FAILED(hr = pProvider2->GetCommitMessage2(GetSafeHwnd(), parameters, repositoryRoot, commonRoot, pathList, originalMessage, bugID, &bugIDOut, &revPropNames, &revPropValues, &temp)))
2111 CString sErr;
2112 sErr.Format(IDS_ERR_FAILEDISSUETRACKERCOM, m_bugtraq_association.GetProviderName(), _com_error(hr).ErrorMessage());
2113 CMessageBox::Show(m_hWnd, sErr, _T("TortoiseGit"), MB_ICONERROR);
2115 else
2117 if (bugIDOut)
2119 bugIdOutSet = true;
2120 m_sBugID = bugIDOut;
2121 SetDlgItemText(IDC_BUGID, m_sBugID);
2123 m_cLogMessage.SetText((LPCTSTR)temp);
2124 BSTR HUGEP *pbRevNames;
2125 BSTR HUGEP *pbRevValues;
2127 HRESULT hr1 = SafeArrayAccessData(revPropNames, (void HUGEP**)&pbRevNames);
2128 if (SUCCEEDED(hr1))
2130 HRESULT hr2 = SafeArrayAccessData(revPropValues, (void HUGEP**)&pbRevValues);
2131 if (SUCCEEDED(hr2))
2133 // if (revPropNames->rgsabound->cElements == revPropValues->rgsabound->cElements)
2134 // {
2135 // for (ULONG i = 0; i < revPropNames->rgsabound->cElements; ++i)
2136 // {
2137 // m_revProps[pbRevNames[i]] = pbRevValues[i];
2138 // }
2139 // }
2140 SafeArrayUnaccessData(revPropValues);
2142 SafeArrayUnaccessData(revPropNames);
2146 else
2148 // if IBugTraqProvider2 failed, try IBugTraqProvider
2149 CComPtr<IBugTraqProvider> pProvider = NULL;
2150 hr = m_BugTraqProvider.QueryInterface(&pProvider);
2151 if (FAILED(hr))
2153 CString sErr;
2154 sErr.Format(IDS_ERR_FAILEDISSUETRACKERCOM, (LPCTSTR)m_bugtraq_association.GetProviderName(), _com_error(hr).ErrorMessage());
2155 CMessageBox::Show(m_hWnd, sErr, _T("TortoiseGit"), MB_ICONERROR);
2156 return;
2159 if (FAILED(hr = pProvider->GetCommitMessage(GetSafeHwnd(), parameters, commonRoot, pathList, originalMessage, &temp)))
2161 CString sErr;
2162 sErr.Format(IDS_ERR_FAILEDISSUETRACKERCOM, m_bugtraq_association.GetProviderName(), _com_error(hr).ErrorMessage());
2163 CMessageBox::Show(m_hWnd, sErr, _T("TortoiseGit"), MB_ICONERROR);
2165 else
2166 m_cLogMessage.SetText((LPCTSTR)temp);
2168 m_sLogMessage = m_cLogMessage.GetText();
2169 if (!m_ProjectProperties.sMessage.IsEmpty())
2171 CString sBugID = m_ProjectProperties.FindBugID(m_sLogMessage);
2172 if (!sBugID.IsEmpty() && !bugIdOutSet)
2174 SetDlgItemText(IDC_BUGID, sBugID);
2178 m_cLogMessage.SetFocus();
2181 void CCommitDlg::FillPatchView(bool onlySetTimer)
2183 if(::IsWindow(this->m_patchViewdlg.m_hWnd))
2185 KillTimer(FILLPATCHVTIMER);
2186 if (onlySetTimer)
2188 SetTimer(FILLPATCHVTIMER, 100, NULL);
2189 return;
2192 POSITION pos=m_ListCtrl.GetFirstSelectedItemPosition();
2193 CString cmd,out;
2195 while(pos)
2197 int nSelect = m_ListCtrl.GetNextSelectedItem(pos);
2198 CTGitPath * p=(CTGitPath*)m_ListCtrl.GetItemData(nSelect);
2199 if(p && !(p->m_Action&CTGitPath::LOGACTIONS_UNVER) )
2201 CString head = _T("HEAD");
2202 if(m_bCommitAmend==TRUE && m_bAmendDiffToLastCommit==FALSE)
2203 head = _T("HEAD~1");
2204 cmd.Format(_T("git.exe diff %s -- \"%s\""), (LPCTSTR)head, (LPCTSTR)p->GetGitPathString());
2205 g_Git.Run(cmd, &out, CP_UTF8);
2209 m_patchViewdlg.SetText(out);
2212 LRESULT CCommitDlg::OnGitStatusListCtrlItemChanged(WPARAM /*wparam*/, LPARAM /*lparam*/)
2214 this->FillPatchView(true);
2215 return 0;
2219 LRESULT CCommitDlg::OnGitStatusListCtrlCheckChanged(WPARAM, LPARAM)
2221 SendMessage(WM_UPDATEOKBUTTON);
2222 return 0;
2225 LRESULT CCommitDlg::OnCheck(WPARAM wnd, LPARAM)
2227 HWND hwnd = (HWND)wnd;
2228 bool check = !(GetAsyncKeyState(VK_SHIFT) & 0x8000);
2229 if (hwnd == GetDlgItem(IDC_CHECKALL)->GetSafeHwnd())
2230 m_ListCtrl.Check(GITSLC_SHOWEVERYTHING, check);
2231 else if (hwnd == GetDlgItem(IDC_CHECKNONE)->GetSafeHwnd())
2232 m_ListCtrl.Check(GITSLC_SHOWEVERYTHING, !check);
2233 else if (hwnd == GetDlgItem(IDC_CHECKUNVERSIONED)->GetSafeHwnd())
2234 m_ListCtrl.Check(GITSLC_SHOWUNVERSIONED, check);
2235 else if (hwnd == GetDlgItem(IDC_CHECKVERSIONED)->GetSafeHwnd())
2236 m_ListCtrl.Check(GITSLC_SHOWVERSIONED, check);
2237 else if (hwnd == GetDlgItem(IDC_CHECKADDED)->GetSafeHwnd())
2238 m_ListCtrl.Check(GITSLC_SHOWADDED, check);
2239 else if (hwnd == GetDlgItem(IDC_CHECKDELETED)->GetSafeHwnd())
2240 m_ListCtrl.Check(GITSLC_SHOWREMOVED, check);
2241 else if (hwnd == GetDlgItem(IDC_CHECKMODIFIED)->GetSafeHwnd())
2242 m_ListCtrl.Check(GITSLC_SHOWMODIFIED, check);
2243 else if (hwnd == GetDlgItem(IDC_CHECKFILES)->GetSafeHwnd())
2244 m_ListCtrl.Check(GITSLC_SHOWFILES, check);
2245 else if (hwnd == GetDlgItem(IDC_CHECKSUBMODULES)->GetSafeHwnd())
2246 m_ListCtrl.Check(GITSLC_SHOWSUBMODULES, check);
2248 return 0;
2251 LRESULT CCommitDlg::OnUpdateOKButton(WPARAM, LPARAM)
2253 if (m_bBlock)
2254 return 0;
2256 CString text = m_cLogMessage.GetText().Trim();
2257 bool bValidLogSize = !text.IsEmpty() && text.GetLength() >= m_ProjectProperties.nMinLogSize;
2258 bool bAmendOrSelectFilesOrMerge = m_ListCtrl.GetSelected() > 0 || (m_bCommitAmend && m_bAmendDiffToLastCommit) || CTGitPath(g_Git.m_CurrentDir).IsMergeActive();
2260 DialogEnableWindow(IDOK, bValidLogSize && (m_bCommitMessageOnly || bAmendOrSelectFilesOrMerge));
2262 return 0;
2265 LRESULT CCommitDlg::OnUpdateDataFalse(WPARAM, LPARAM)
2267 UpdateData(FALSE);
2268 return 0;
2271 LRESULT CCommitDlg::DefWindowProc(UINT message, WPARAM wParam, LPARAM lParam)
2273 switch (message) {
2274 case WM_NOTIFY:
2275 if (wParam == IDC_SPLITTER)
2277 SPC_NMHDR* pHdr = (SPC_NMHDR*) lParam;
2278 DoSize(pHdr->delta);
2280 break;
2281 case WM_COMMAND:
2282 if (m_hAccelOkButton && LOWORD(wParam) >= WM_USER && LOWORD(wParam) <= WM_USER + m_accellerators.size())
2284 for (const auto& entry : m_accellerators)
2286 if (entry.second.wmid != LOWORD(wParam))
2287 continue;
2288 if (entry.second.id == -1)
2289 m_ctrlOkButton.PostMessage(WM_KEYDOWN, VK_F4, NULL);
2290 else
2292 m_ctrlOkButton.SetCurrentEntry(entry.second.id);
2293 OnOK();
2295 return 0;
2298 break;
2301 return __super::DefWindowProc(message, wParam, lParam);
2304 void CCommitDlg::SetSplitterRange()
2306 if ((m_ListCtrl)&&(m_cLogMessage))
2308 CRect rcTop;
2309 m_cLogMessage.GetWindowRect(rcTop);
2310 ScreenToClient(rcTop);
2311 CRect rcMiddle;
2312 m_ListCtrl.GetWindowRect(rcMiddle);
2313 ScreenToClient(rcMiddle);
2314 if (rcMiddle.Height() && rcMiddle.Width())
2315 m_wndSplitter.SetRange(rcTop.top + 100, rcMiddle.bottom - 80);
2319 void CCommitDlg::DoSize(int delta)
2321 RemoveAnchor(IDC_MESSAGEGROUP);
2322 RemoveAnchor(IDC_LOGMESSAGE);
2323 RemoveAnchor(IDC_SPLITTER);
2324 RemoveAnchor(IDC_SIGNOFF);
2325 RemoveAnchor(IDC_COMMIT_AMEND);
2326 RemoveAnchor(IDC_COMMIT_AMENDDIFF);
2327 RemoveAnchor(IDC_COMMIT_SETDATETIME);
2328 RemoveAnchor(IDC_COMMIT_DATEPICKER);
2329 RemoveAnchor(IDC_COMMIT_TIMEPICKER);
2330 RemoveAnchor(IDC_COMMIT_AS_COMMIT_DATE);
2331 RemoveAnchor(IDC_COMMIT_SETAUTHOR);
2332 RemoveAnchor(IDC_COMMIT_AUTHORDATA);
2333 RemoveAnchor(IDC_LISTGROUP);
2334 RemoveAnchor(IDC_FILELIST);
2335 RemoveAnchor(IDC_TEXT_INFO);
2336 RemoveAnchor(IDC_SELECTLABEL);
2337 RemoveAnchor(IDC_CHECKALL);
2338 RemoveAnchor(IDC_CHECKNONE);
2339 RemoveAnchor(IDC_CHECKUNVERSIONED);
2340 RemoveAnchor(IDC_CHECKVERSIONED);
2341 RemoveAnchor(IDC_CHECKADDED);
2342 RemoveAnchor(IDC_CHECKDELETED);
2343 RemoveAnchor(IDC_CHECKMODIFIED);
2344 RemoveAnchor(IDC_CHECKFILES);
2345 RemoveAnchor(IDC_CHECKSUBMODULES);
2347 CSplitterControl::ChangeHeight(&m_cLogMessage, delta, CW_TOPALIGN);
2348 CSplitterControl::ChangeHeight(GetDlgItem(IDC_MESSAGEGROUP), delta, CW_TOPALIGN);
2349 CSplitterControl::ChangeHeight(&m_ListCtrl, -delta, CW_BOTTOMALIGN);
2350 CSplitterControl::ChangeHeight(GetDlgItem(IDC_LISTGROUP), -delta, CW_BOTTOMALIGN);
2351 CSplitterControl::ChangePos(GetDlgItem(IDC_SIGNOFF),0,delta);
2352 CSplitterControl::ChangePos(GetDlgItem(IDC_COMMIT_AMEND),0,delta);
2353 CSplitterControl::ChangePos(GetDlgItem(IDC_COMMIT_AMENDDIFF),0,delta);
2354 CSplitterControl::ChangePos(GetDlgItem(IDC_COMMIT_SETDATETIME),0,delta);
2355 CSplitterControl::ChangePos(GetDlgItem(IDC_COMMIT_DATEPICKER),0,delta);
2356 CSplitterControl::ChangePos(GetDlgItem(IDC_COMMIT_TIMEPICKER),0,delta);
2357 CSplitterControl::ChangePos(GetDlgItem(IDC_COMMIT_AS_COMMIT_DATE), 0, delta);
2358 CSplitterControl::ChangePos(GetDlgItem(IDC_COMMIT_SETAUTHOR), 0, delta);
2359 CSplitterControl::ChangePos(GetDlgItem(IDC_COMMIT_AUTHORDATA), 0, delta);
2360 CSplitterControl::ChangePos(GetDlgItem(IDC_TEXT_INFO),0,delta);
2361 CSplitterControl::ChangePos(GetDlgItem(IDC_SELECTLABEL), 0, delta);
2362 CSplitterControl::ChangePos(GetDlgItem(IDC_CHECKALL), 0, delta);
2363 CSplitterControl::ChangePos(GetDlgItem(IDC_CHECKNONE), 0, delta);
2364 CSplitterControl::ChangePos(GetDlgItem(IDC_CHECKUNVERSIONED), 0, delta);
2365 CSplitterControl::ChangePos(GetDlgItem(IDC_CHECKVERSIONED), 0, delta);
2366 CSplitterControl::ChangePos(GetDlgItem(IDC_CHECKADDED), 0, delta);
2367 CSplitterControl::ChangePos(GetDlgItem(IDC_CHECKDELETED), 0, delta);
2368 CSplitterControl::ChangePos(GetDlgItem(IDC_CHECKMODIFIED), 0, delta);
2369 CSplitterControl::ChangePos(GetDlgItem(IDC_CHECKFILES), 0, delta);
2370 CSplitterControl::ChangePos(GetDlgItem(IDC_CHECKSUBMODULES), 0, delta);
2372 AddAnchor(IDC_MESSAGEGROUP, TOP_LEFT, TOP_RIGHT);
2373 AddAnchor(IDC_LOGMESSAGE, TOP_LEFT, TOP_RIGHT);
2374 AddAnchor(IDC_SPLITTER, TOP_LEFT, TOP_RIGHT);
2375 AddAnchor(IDC_LISTGROUP, TOP_LEFT, BOTTOM_RIGHT);
2376 AddAnchor(IDC_FILELIST, TOP_LEFT, BOTTOM_RIGHT);
2377 AddAnchor(IDC_SIGNOFF,TOP_RIGHT);
2378 AddAnchor(IDC_COMMIT_AMEND,TOP_LEFT);
2379 AddAnchor(IDC_COMMIT_AMENDDIFF,TOP_LEFT);
2380 AddAnchor(IDC_COMMIT_SETDATETIME,TOP_LEFT);
2381 AddAnchor(IDC_COMMIT_DATEPICKER,TOP_LEFT);
2382 AddAnchor(IDC_COMMIT_TIMEPICKER,TOP_LEFT);
2383 AddAnchor(IDC_COMMIT_AS_COMMIT_DATE, TOP_LEFT);
2384 AddAnchor(IDC_COMMIT_SETAUTHOR, TOP_LEFT);
2385 AddAnchor(IDC_COMMIT_AUTHORDATA, TOP_LEFT, TOP_RIGHT);
2386 AddAnchor(IDC_TEXT_INFO,TOP_RIGHT);
2387 AddAnchor(IDC_SELECTLABEL, TOP_LEFT);
2388 AddAnchor(IDC_CHECKALL, TOP_LEFT);
2389 AddAnchor(IDC_CHECKNONE, TOP_LEFT);
2390 AddAnchor(IDC_CHECKUNVERSIONED, TOP_LEFT);
2391 AddAnchor(IDC_CHECKVERSIONED, TOP_LEFT);
2392 AddAnchor(IDC_CHECKADDED, TOP_LEFT);
2393 AddAnchor(IDC_CHECKDELETED, TOP_LEFT);
2394 AddAnchor(IDC_CHECKMODIFIED, TOP_LEFT);
2395 AddAnchor(IDC_CHECKFILES, TOP_LEFT);
2396 AddAnchor(IDC_CHECKSUBMODULES, TOP_LEFT);
2397 ArrangeLayout();
2398 // adjust the minimum size of the dialog to prevent the resizing from
2399 // moving the list control too far down.
2400 CRect rcLogMsg;
2401 m_cLogMessage.GetClientRect(rcLogMsg);
2402 SetMinTrackSize(CSize(m_DlgOrigRect.Width(), m_DlgOrigRect.Height()-m_LogMsgOrigRect.Height()+rcLogMsg.Height()));
2404 SetSplitterRange();
2405 m_cLogMessage.Invalidate();
2406 GetDlgItem(IDC_LOGMESSAGE)->Invalidate();
2409 void CCommitDlg::OnSize(UINT nType, int cx, int cy)
2411 // first, let the resizing take place
2412 __super::OnSize(nType, cx, cy);
2414 //set range
2415 SetSplitterRange();
2418 CString CCommitDlg::GetSignedOffByLine()
2420 CString str;
2422 CString username = g_Git.GetUserName();
2423 CString email = g_Git.GetUserEmail();
2424 username.Remove(_T('\n'));
2425 email.Remove(_T('\n'));
2427 str.Format(_T("Signed-off-by: %s <%s>"), (LPCTSTR)username, (LPCTSTR)email);
2429 return str;
2432 void CCommitDlg::OnBnClickedSignOff()
2434 CString str = GetSignedOffByLine();
2436 if (m_cLogMessage.GetText().Find(str) == -1) {
2437 m_cLogMessage.SetText(m_cLogMessage.GetText().TrimRight());
2438 int lastNewline = m_cLogMessage.GetText().ReverseFind(_T('\n'));
2439 int foundByLine = -1;
2440 if (lastNewline > 0)
2441 foundByLine = m_cLogMessage.GetText().Find(_T("-by: "), lastNewline);
2443 if (foundByLine == -1 || foundByLine < lastNewline)
2444 str = _T("\r\n") + str;
2446 m_cLogMessage.SetText(m_cLogMessage.GetText()+_T("\r\n")+str+_T("\r\n"));
2450 void CCommitDlg::OnBnClickedCommitAmend()
2452 this->UpdateData();
2453 if(this->m_bCommitAmend && this->m_AmendStr.IsEmpty())
2455 GitRev rev;
2456 if (rev.GetCommit(CString(_T("HEAD"))))
2457 MessageBox(rev.GetLastErr(), _T("TortoiseGit"), MB_ICONERROR);
2458 m_AmendStr=rev.GetSubject()+_T("\n")+rev.GetBody();
2461 if(this->m_bCommitAmend)
2463 this->m_NoAmendStr=this->m_cLogMessage.GetText();
2464 m_cLogMessage.SetText(m_AmendStr);
2465 GetDlgItem(IDC_COMMIT_AMENDDIFF)->ShowWindow(SW_SHOW);
2466 if (m_bSetCommitDateTime)
2467 m_AsCommitDateCtrl.ShowWindow(SW_SHOW);
2469 else
2471 this->m_AmendStr=this->m_cLogMessage.GetText();
2472 m_cLogMessage.SetText(m_NoAmendStr);
2473 GetDlgItem(IDC_COMMIT_AMENDDIFF)->ShowWindow(SW_HIDE);
2474 m_AsCommitDateCtrl.ShowWindow(SW_HIDE);
2475 m_AsCommitDateCtrl.SetCheck(FALSE);
2476 OnBnClickedCommitAsCommitDate();
2479 OnBnClickedCommitSetDateTime(); // to update the commit date and time
2480 OnBnClickedCommitSetauthor(); // to update the commit author
2482 GetDlgItem(IDC_LOGMESSAGE)->SetFocus();
2483 Refresh();
2486 void CCommitDlg::OnBnClickedCommitMessageOnly()
2488 this->UpdateData();
2489 this->m_ListCtrl.EnableWindow(m_bCommitMessageOnly ? FALSE : TRUE);
2490 SendMessage(WM_UPDATEOKBUTTON);
2493 void CCommitDlg::OnBnClickedWholeProject()
2495 m_tooltips.Pop(); // hide the tooltips
2496 UpdateData();
2497 m_ListCtrl.Clear();
2498 if (!m_bBlock)
2500 if (m_bWholeProject || m_bWholeProject2)
2501 m_ListCtrl.GetStatus(NULL,true,false,true);
2502 else
2503 m_ListCtrl.GetStatus(&this->m_pathList,true,false,true);
2505 m_regShowWholeProject = m_bWholeProject;
2507 DWORD dwShow = m_ListCtrl.GetShowFlags();
2508 if (DWORD(m_regAddBeforeCommit))
2509 dwShow |= GITSLC_SHOWUNVERSIONED;
2510 else
2511 dwShow &= ~GITSLC_SHOWUNVERSIONED;
2513 m_ListCtrl.Show(dwShow, dwShow & ~(CTGitPath::LOGACTIONS_UNVER), true);
2514 UpdateCheckLinks();
2517 SetDlgTitle();
2520 void CCommitDlg::OnFocusMessage()
2522 m_cLogMessage.SetFocus();
2525 void CCommitDlg::OnFocusFileList()
2527 m_ListCtrl.SetFocus();
2530 void CCommitDlg::OnScnUpdateUI(NMHDR * /*pNMHDR*/, LRESULT *pResult)
2532 int pos = (int)this->m_cLogMessage.Call(SCI_GETCURRENTPOS);
2533 int line = (int)this->m_cLogMessage.Call(SCI_LINEFROMPOSITION,pos);
2534 int column = (int)this->m_cLogMessage.Call(SCI_GETCOLUMN,pos);
2536 CString str;
2537 str.Format(_T("%d/%d"),line+1,column+1);
2538 this->GetDlgItem(IDC_TEXT_INFO)->SetWindowText(str);
2540 if(*pResult)
2541 *pResult=0;
2544 void CCommitDlg::TogglePatchView()
2546 OnStnClickedViewPatch();
2549 void CCommitDlg::OnStnClickedViewPatch()
2551 m_patchViewdlg.m_ParentDlg = this;
2552 if(!IsWindow(this->m_patchViewdlg.m_hWnd))
2554 BOOL viewPatchEnabled = FALSE;
2555 viewPatchEnabled = g_Git.GetConfigValueBool(_T("tgit.commitshowpatch"));
2556 if (viewPatchEnabled == FALSE)
2557 g_Git.SetConfigValue(_T("tgit.commitshowpatch"), _T("true"));
2558 m_patchViewdlg.Create(IDD_PATCH_VIEW,this);
2559 m_patchViewdlg.m_ctrlPatchView.Call(SCI_SETSCROLLWIDTHTRACKING, TRUE);
2560 CRect rect;
2561 this->GetWindowRect(&rect);
2563 m_patchViewdlg.ShowWindow(SW_SHOW);
2565 m_patchViewdlg.SetWindowPos(NULL,rect.right,rect.top,rect.Width(),rect.Height(),
2566 SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
2568 GetDlgItem(IDC_LOGMESSAGE)->SetFocus();
2570 ShowViewPatchText(false);
2571 FillPatchView();
2573 else
2575 g_Git.SetConfigValue(_T("tgit.commitshowpatch"), _T("false"));
2576 m_patchViewdlg.ShowWindow(SW_HIDE);
2577 m_patchViewdlg.DestroyWindow();
2578 ShowViewPatchText(true);
2580 this->m_ctrlShowPatch.Invalidate();
2583 void CCommitDlg::OnMoving(UINT fwSide, LPRECT pRect)
2585 __super::OnMoving(fwSide, pRect);
2587 if (::IsWindow(m_patchViewdlg.m_hWnd))
2589 RECT patchrect;
2590 m_patchViewdlg.GetWindowRect(&patchrect);
2591 if (::IsWindow(m_hWnd))
2593 RECT thisrect;
2594 GetWindowRect(&thisrect);
2595 if (patchrect.left == thisrect.right)
2597 m_patchViewdlg.SetWindowPos(NULL, patchrect.left - (thisrect.left - pRect->left), patchrect.top - (thisrect.top - pRect->top),
2598 0, 0, SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOSIZE | SWP_NOZORDER);
2605 void CCommitDlg::OnSizing(UINT fwSide, LPRECT pRect)
2607 __super::OnSizing(fwSide, pRect);
2609 if(::IsWindow(this->m_patchViewdlg.m_hWnd))
2611 CRect thisrect, patchrect;
2612 this->GetWindowRect(thisrect);
2613 this->m_patchViewdlg.GetWindowRect(patchrect);
2614 if(thisrect.right==patchrect.left)
2616 patchrect.left -= (thisrect.right - pRect->right);
2617 patchrect.right-= (thisrect.right - pRect->right);
2619 if( patchrect.bottom == thisrect.bottom)
2621 patchrect.bottom -= (thisrect.bottom - pRect->bottom);
2623 if( patchrect.top == thisrect.top)
2625 patchrect.top -= thisrect.top-pRect->top;
2627 m_patchViewdlg.MoveWindow(patchrect);
2632 void CCommitDlg::OnHdnItemchangedFilelist(NMHDR * /*pNMHDR*/, LRESULT *pResult)
2634 *pResult = 0;
2635 TRACE("Item Changed\r\n");
2638 int CCommitDlg::CheckHeadDetach()
2640 CString output;
2641 if (CGit::GetCurrentBranchFromFile(g_Git.m_CurrentDir, output))
2643 int retval = CMessageBox::Show(NULL, IDS_PROC_COMMIT_DETACHEDWARNING, IDS_APPNAME, MB_YESNOCANCEL | MB_ICONWARNING);
2644 if(retval == IDYES)
2646 if (CAppUtils::CreateBranchTag(FALSE, NULL, true) == FALSE)
2647 return 1;
2649 else if (retval == IDCANCEL)
2650 return 1;
2652 return 0;
2655 void CCommitDlg::OnBnClickedCommitAmenddiff()
2657 UpdateData();
2658 Refresh();
2661 void CCommitDlg::OnBnClickedNoautoselectsubmodules()
2663 UpdateData();
2664 Refresh();
2667 void CCommitDlg::OnBnClickedCommitSetDateTime()
2669 UpdateData();
2671 if (m_bSetCommitDateTime)
2673 CTime authordate = CTime::GetCurrentTime();
2674 if (m_bCommitAmend)
2676 GitRev headRevision;
2677 if (headRevision.GetCommit(_T("HEAD")))
2678 MessageBox(headRevision.GetLastErr(), _T("TortoiseGit"), MB_ICONERROR);
2679 authordate = headRevision.GetAuthorDate();
2680 m_AsCommitDateCtrl.ShowWindow(SW_SHOW);
2683 m_CommitDate.SetTime(&authordate);
2684 m_CommitTime.SetTime(&authordate);
2686 GetDlgItem(IDC_COMMIT_DATEPICKER)->ShowWindow(SW_SHOW);
2687 GetDlgItem(IDC_COMMIT_TIMEPICKER)->ShowWindow(SW_SHOW);
2689 else
2691 GetDlgItem(IDC_COMMIT_DATEPICKER)->ShowWindow(SW_HIDE);
2692 GetDlgItem(IDC_COMMIT_TIMEPICKER)->ShowWindow(SW_HIDE);
2693 m_AsCommitDateCtrl.ShowWindow(SW_HIDE);
2694 m_AsCommitDateCtrl.SetCheck(FALSE);
2695 OnBnClickedCommitAsCommitDate();
2699 void CCommitDlg::OnBnClickedCommitAsCommitDate()
2701 GetDlgItem(IDC_COMMIT_DATEPICKER)->EnableWindow(!m_AsCommitDateCtrl.GetCheck());
2702 GetDlgItem(IDC_COMMIT_TIMEPICKER)->EnableWindow(!m_AsCommitDateCtrl.GetCheck());
2705 void CCommitDlg::OnBnClickedCheckNewBranch()
2707 UpdateData();
2708 if (m_bCreateNewBranch)
2710 GetDlgItem(IDC_COMMIT_TO)->ShowWindow(SW_HIDE);
2711 GetDlgItem(IDC_NEWBRANCH)->ShowWindow(SW_SHOW);
2713 else
2715 GetDlgItem(IDC_NEWBRANCH)->ShowWindow(SW_HIDE);
2716 GetDlgItem(IDC_COMMIT_TO)->ShowWindow(SW_SHOW);
2720 bool CCommitDlg::RestoreFiles(bool doNotAsk, bool allowCancel)
2722 if (m_ListCtrl.m_restorepaths.empty())
2723 return true;
2725 if (!doNotAsk)
2727 auto ret = CMessageBox::Show(m_hWnd, IDS_PROC_COMMIT_RESTOREFILES, IDS_APPNAME, 2, IDI_QUESTION, IDS_PROC_COMMIT_RESTOREFILES_RESTORE, IDS_PROC_COMMIT_RESTOREFILES_KEEP, allowCancel ? IDS_MSGBOX_CANCEL : 0);
2728 if (ret == 3)
2729 return false;
2730 if (ret == 2)
2731 return true;
2734 for (const auto& item : m_ListCtrl.m_restorepaths)
2735 CopyFile(item.second, g_Git.CombinePath(item.first), FALSE);
2736 m_ListCtrl.m_restorepaths.clear();
2738 return true;
2741 void CCommitDlg::UpdateCheckLinks()
2743 DialogEnableWindow(IDC_CHECKALL, true);
2744 DialogEnableWindow(IDC_CHECKNONE, true);
2745 DialogEnableWindow(IDC_CHECKUNVERSIONED, m_ListCtrl.GetUnversionedCount() > 0);
2746 DialogEnableWindow(IDC_CHECKVERSIONED, m_ListCtrl.GetItemCount() > m_ListCtrl.GetUnversionedCount());
2747 DialogEnableWindow(IDC_CHECKADDED, m_ListCtrl.GetAddedCount() > 0);
2748 DialogEnableWindow(IDC_CHECKDELETED, m_ListCtrl.GetDeletedCount() > 0);
2749 DialogEnableWindow(IDC_CHECKMODIFIED, m_ListCtrl.GetModifiedCount() > 0);
2750 DialogEnableWindow(IDC_CHECKFILES, m_ListCtrl.GetFileCount() > 0);
2751 DialogEnableWindow(IDC_CHECKSUBMODULES, m_ListCtrl.GetSubmoduleCount() > 0);
2754 void CCommitDlg::OnBnClickedCommitSetauthor()
2756 UpdateData();
2758 if (m_bSetAuthor)
2760 m_sAuthor.Format(_T("%s <%s>"), (LPCTSTR)g_Git.GetUserName(), (LPCTSTR)g_Git.GetUserEmail());
2761 if (m_bCommitAmend)
2763 GitRev headRevision;
2764 if (headRevision.GetCommit(_T("HEAD")))
2765 MessageBox(headRevision.GetLastErr(), _T("TortoiseGit"), MB_ICONERROR);
2766 m_sAuthor.Format(_T("%s <%s>"), (LPCTSTR)headRevision.GetAuthorName(), (LPCTSTR)headRevision.GetAuthorEmail());
2769 UpdateData(FALSE);
2771 GetDlgItem(IDC_COMMIT_AUTHORDATA)->ShowWindow(SW_SHOW);
2773 else
2774 GetDlgItem(IDC_COMMIT_AUTHORDATA)->ShowWindow(SW_HIDE);
2777 void CCommitDlg::RunStartCommitHook()
2779 DWORD exitcode = 0xFFFFFFFF;
2780 CString error;
2781 if (CHooks::Instance().StartCommit(g_Git.m_CurrentDir, m_pathList, m_sLogMessage, exitcode, error))
2783 if (exitcode)
2785 CString temp;
2786 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2787 MessageBox(temp, _T("TortoiseGit"), MB_ICONERROR);
2788 return;