Switch to a ini/git config style version check file
[TortoiseGit.git] / src / TortoiseProc / CommitDlg.cpp
blobd37b374ae68f3e558d7b19b1c80611ca00fa697c
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2003-2013 - TortoiseSVN
4 // Copyright (C) 2008-2014 - 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 "DirFileEnum.h"
24 #include "MessageBox.h"
25 #include "AppUtils.h"
26 #include "PathUtils.h"
27 #include "Git.h"
28 #include "registry.h"
29 #include "GitStatus.h"
30 #include "HistoryDlg.h"
31 #include "Hooks.h"
32 #include "UnicodeUtils.h"
33 #include "../TGitCache/CacheInterface.h"
34 #include "ProgressDlg.h"
35 #include "ShellUpdater.h"
36 #include "Commands/PushCommand.h"
37 #include "COMError.h"
38 #include "Globals.h"
39 #include "SysProgressDlg.h"
40 #include "MassiveGitTask.h"
41 #include "LogDlg.h"
42 #include "BstrSafeVector.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)
86 this->m_bCommitAmend=FALSE;
89 CCommitDlg::~CCommitDlg()
91 if(m_pThread != NULL)
93 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);
121 BEGIN_MESSAGE_MAP(CCommitDlg, CResizableStandAloneDialog)
122 ON_BN_CLICKED(IDC_SHOWUNVERSIONED, OnBnClickedShowunversioned)
123 ON_NOTIFY(SCN_UPDATEUI, IDC_LOGMESSAGE, OnScnUpdateUI)
124 // ON_BN_CLICKED(IDC_HISTORY, OnBnClickedHistory)
125 ON_BN_CLICKED(IDC_BUGTRAQBUTTON, OnBnClickedBugtraqbutton)
126 ON_EN_CHANGE(IDC_LOGMESSAGE, OnEnChangeLogmessage)
127 ON_REGISTERED_MESSAGE(CGitStatusListCtrl::GITSLNM_ITEMCOUNTCHANGED, OnGitStatusListCtrlItemCountChanged)
128 ON_REGISTERED_MESSAGE(CGitStatusListCtrl::GITSLNM_NEEDSREFRESH, OnGitStatusListCtrlNeedsRefresh)
129 ON_REGISTERED_MESSAGE(CGitStatusListCtrl::GITSLNM_ADDFILE, OnFileDropped)
130 ON_REGISTERED_MESSAGE(CGitStatusListCtrl::GITSLNM_CHECKCHANGED, &CCommitDlg::OnGitStatusListCtrlCheckChanged)
131 ON_REGISTERED_MESSAGE(CGitStatusListCtrl::GITSLNM_ITEMCHANGED, &CCommitDlg::OnGitStatusListCtrlItemChanged)
133 ON_REGISTERED_MESSAGE(CLinkControl::LK_LINKITEMCLICKED, &CCommitDlg::OnCheck)
134 ON_REGISTERED_MESSAGE(WM_AUTOLISTREADY, OnAutoListReady)
135 ON_REGISTERED_MESSAGE(WM_UPDATEOKBUTTON, OnUpdateOKButton)
136 ON_REGISTERED_MESSAGE(WM_UPDATEDATAFALSE, OnUpdateDataFalse)
137 ON_WM_TIMER()
138 ON_WM_SIZE()
139 ON_STN_CLICKED(IDC_EXTERNALWARNING, &CCommitDlg::OnStnClickedExternalwarning)
140 ON_BN_CLICKED(IDC_SIGNOFF, &CCommitDlg::OnBnClickedSignOff)
141 ON_BN_CLICKED(IDC_COMMIT_AMEND, &CCommitDlg::OnBnClickedCommitAmend)
142 ON_BN_CLICKED(IDC_COMMIT_MESSAGEONLY, &CCommitDlg::OnBnClickedCommitMessageOnly)
143 ON_BN_CLICKED(IDC_WHOLE_PROJECT, &CCommitDlg::OnBnClickedWholeProject)
144 ON_COMMAND(ID_FOCUS_MESSAGE,&CCommitDlg::OnFocusMessage)
145 ON_COMMAND(ID_FOCUS_FILELIST, OnFocusFileList)
146 ON_STN_CLICKED(IDC_VIEW_PATCH, &CCommitDlg::OnStnClickedViewPatch)
147 ON_WM_MOVE()
148 ON_WM_MOVING()
149 ON_WM_SIZING()
150 ON_NOTIFY(HDN_ITEMCHANGED, 0, &CCommitDlg::OnHdnItemchangedFilelist)
151 ON_BN_CLICKED(IDC_COMMIT_AMENDDIFF, &CCommitDlg::OnBnClickedCommitAmenddiff)
152 ON_BN_CLICKED(IDC_NOAUTOSELECTSUBMODULES, &CCommitDlg::OnBnClickedNoautoselectsubmodules)
153 ON_BN_CLICKED(IDC_COMMIT_SETDATETIME, &CCommitDlg::OnBnClickedCommitSetDateTime)
154 ON_BN_CLICKED(IDC_CHECK_NEWBRANCH, &CCommitDlg::OnBnClickedCheckNewBranch)
155 ON_BN_CLICKED(IDC_COMMIT_SETAUTHOR, &CCommitDlg::OnBnClickedCommitSetauthor)
156 END_MESSAGE_MAP()
158 int GetCommitTemplate(CString &msg)
160 CString tplFilename = g_Git.GetConfigValue(_T("commit.template"));
161 if (tplFilename.IsEmpty())
162 return -1;
164 if (tplFilename[0] == _T('/'))
166 if (tplFilename.GetLength() >= 3)
168 // handle "/d/TortoiseGit/tpl.txt" -> "d:/TortoiseGit/tpl.txt"
169 if (tplFilename[2] == _T('/'))
171 tplFilename.GetBuffer()[0] = tplFilename[1];
172 tplFilename.GetBuffer()[1] = _T(':');
177 tplFilename.Replace(_T('/'), _T('\\'));
179 if (!CGit::LoadTextFile(tplFilename, msg))
180 return -1;
181 return 0;
184 BOOL CCommitDlg::OnInitDialog()
186 CResizableStandAloneDialog::OnInitDialog();
187 CAppUtils::MarkWindowAsUnpinnable(m_hWnd);
189 if (m_sLogMessage.IsEmpty())
191 if (!m_bForceCommitAmend)
192 GetCommitTemplate(m_sLogMessage);
194 CString dotGitPath;
195 g_GitAdminDir.GetAdminDirPath(g_Git.m_CurrentDir, dotGitPath);
196 bool loadedMsg = !CGit::LoadTextFile(dotGitPath + _T("MERGE_MSG"), m_sLogMessage);
197 loadedMsg = loadedMsg && !CGit::LoadTextFile(dotGitPath + _T("SQUASH_MSG"), m_sLogMessage);
199 RunStartCommitHook();
201 if (CTGitPath(g_Git.m_CurrentDir).IsMergeActive())
203 DialogEnableWindow(IDC_CHECK_NEWBRANCH, FALSE);
204 m_bCreateNewBranch = FALSE;
205 GetDlgItem(IDC_MERGEACTIVE)->ShowWindow(SW_SHOW);
208 m_regAddBeforeCommit = CRegDWORD(_T("Software\\TortoiseGit\\AddBeforeCommit"), TRUE);
209 m_bShowUnversioned = m_regAddBeforeCommit;
211 CString regPath(g_Git.m_CurrentDir);
212 regPath.Replace(_T(":"), _T("_"));
213 m_regShowWholeProject = CRegDWORD(_T("Software\\TortoiseGit\\TortoiseProc\\ShowWholeProject\\") + regPath, FALSE);
214 m_bWholeProject = m_regShowWholeProject;
216 m_History.SetMaxHistoryItems((LONG)CRegDWORD(_T("Software\\TortoiseGit\\MaxHistoryItems"), 25));
218 m_regKeepChangelists = CRegDWORD(_T("Software\\TortoiseGit\\KeepChangeLists"), FALSE);
219 m_bKeepChangeList = m_regKeepChangelists;
221 m_regDoNotAutoselectSubmodules = CRegDWORD(_T("Software\\TortoiseGit\\DoNotAutoselectSubmodules"), FALSE);
222 m_bDoNotAutoselectSubmodules = m_regDoNotAutoselectSubmodules;
224 m_hAccel = LoadAccelerators(AfxGetResourceHandle(),MAKEINTRESOURCE(IDR_ACC_COMMITDLG));
226 if (m_pathList.IsEmpty())
227 m_bWholeProject2 = true;
229 if(this->m_pathList.GetCount() == 1 && m_pathList[0].IsEmpty())
230 m_bWholeProject2 = true;
232 SetDlgTitle();
234 UpdateData(FALSE);
236 m_ListCtrl.Init(GITSLC_COLEXT | GITSLC_COLSTATUS | GITSLC_COLADD | GITSLC_COLDEL, _T("CommitDlg"),(GITSLC_POPALL ^ (GITSLC_POPCOMMIT | GITSLC_POPSAVEAS)), true, true);
237 m_ListCtrl.SetStatLabel(GetDlgItem(IDC_STATISTICS));
238 m_ListCtrl.SetCancelBool(&m_bCancelled);
239 m_ListCtrl.SetEmptyString(IDS_COMMITDLG_NOTHINGTOCOMMIT);
240 m_ListCtrl.EnableFileDrop();
241 m_ListCtrl.SetBackgroundImage(IDI_COMMIT_BKG);
243 //this->DialogEnableWindow(IDC_COMMIT_AMEND,FALSE);
244 m_ProjectProperties.ReadProps();
246 m_cLogMessage.Init(m_ProjectProperties);
247 m_cLogMessage.SetFont((CString)CRegString(_T("Software\\TortoiseGit\\LogFontName"), _T("Courier New")), (DWORD)CRegDWORD(_T("Software\\TortoiseGit\\LogFontSize"), 8));
248 m_cLogMessage.RegisterContextMenuHandler(this);
249 std::map<int, UINT> icons;
250 icons[AUTOCOMPLETE_SPELLING] = IDI_SPELL;
251 icons[AUTOCOMPLETE_FILENAME] = IDI_FILE;
252 icons[AUTOCOMPLETE_PROGRAMCODE] = IDI_CODE;
253 icons[AUTOCOMPLETE_SNIPPET] = IDI_SNIPPET;
254 m_cLogMessage.SetIcon(icons);
256 OnEnChangeLogmessage();
258 m_tooltips.Create(this);
259 m_tooltips.AddTool(IDC_EXTERNALWARNING, IDS_COMMITDLG_EXTERNALS);
260 m_tooltips.AddTool(IDC_COMMIT_AMEND,IDS_COMMIT_AMEND_TT);
261 m_tooltips.AddTool(IDC_MERGEACTIVE, IDC_MERGEACTIVE_TT);
262 // m_tooltips.AddTool(IDC_HISTORY, IDS_COMMITDLG_HISTORY_TT);
264 CBugTraqAssociations bugtraq_associations;
265 bugtraq_associations.Load(m_ProjectProperties.GetProviderUUID(), m_ProjectProperties.sProviderParams);
267 if (bugtraq_associations.FindProvider(g_Git.m_CurrentDir, &m_bugtraq_association))
269 GetDlgItem(IDC_BUGID)->ShowWindow(SW_HIDE);
270 GetDlgItem(IDC_BUGIDLABEL)->ShowWindow(SW_HIDE);
272 CComPtr<IBugTraqProvider> pProvider;
273 HRESULT hr = pProvider.CoCreateInstance(m_bugtraq_association.GetProviderClass());
274 if (SUCCEEDED(hr))
276 m_BugTraqProvider = pProvider;
277 ATL::CComBSTR temp;
278 ATL::CComBSTR parameters(m_bugtraq_association.GetParameters());
279 if (SUCCEEDED(hr = pProvider->GetLinkText(GetSafeHwnd(), parameters, &temp)))
281 SetDlgItemText(IDC_BUGTRAQBUTTON, temp);
282 GetDlgItem(IDC_BUGTRAQBUTTON)->EnableWindow(TRUE);
283 GetDlgItem(IDC_BUGTRAQBUTTON)->ShowWindow(SW_SHOW);
287 GetDlgItem(IDC_LOGMESSAGE)->SetFocus();
289 else if (!m_ProjectProperties.sMessage.IsEmpty())
291 GetDlgItem(IDC_BUGID)->ShowWindow(SW_SHOW);
292 GetDlgItem(IDC_BUGIDLABEL)->ShowWindow(SW_SHOW);
293 if (!m_ProjectProperties.sLabel.IsEmpty())
294 SetDlgItemText(IDC_BUGIDLABEL, m_ProjectProperties.sLabel);
295 GetDlgItem(IDC_BUGTRAQBUTTON)->ShowWindow(SW_HIDE);
296 GetDlgItem(IDC_BUGTRAQBUTTON)->EnableWindow(FALSE);
297 GetDlgItem(IDC_BUGID)->SetFocus();
298 CString sBugID = m_ProjectProperties.GetBugIDFromLog(m_sLogMessage);
299 if (!sBugID.IsEmpty())
301 SetDlgItemText(IDC_BUGID, sBugID);
304 else
306 GetDlgItem(IDC_BUGID)->ShowWindow(SW_HIDE);
307 GetDlgItem(IDC_BUGIDLABEL)->ShowWindow(SW_HIDE);
308 GetDlgItem(IDC_BUGTRAQBUTTON)->ShowWindow(SW_HIDE);
309 GetDlgItem(IDC_BUGTRAQBUTTON)->EnableWindow(FALSE);
310 GetDlgItem(IDC_LOGMESSAGE)->SetFocus();
313 if (!m_sLogMessage.IsEmpty())
315 m_cLogMessage.SetText(m_sLogMessage);
316 m_cLogMessage.Call(SCI_SETCURRENTPOS, 0);
317 m_cLogMessage.Call(SCI_SETSEL, 0, 0);
320 GetWindowText(m_sWindowTitle);
322 AdjustControlSize(IDC_SHOWUNVERSIONED);
323 AdjustControlSize(IDC_WHOLE_PROJECT);
324 AdjustControlSize(IDC_CHECK_NEWBRANCH);
325 AdjustControlSize(IDC_COMMIT_AMEND);
326 AdjustControlSize(IDC_COMMIT_MESSAGEONLY);
327 AdjustControlSize(IDC_COMMIT_AMENDDIFF);
328 AdjustControlSize(IDC_COMMIT_SETDATETIME);
329 AdjustControlSize(IDC_COMMIT_SETAUTHOR);
330 AdjustControlSize(IDC_NOAUTOSELECTSUBMODULES);
331 AdjustControlSize(IDC_KEEPLISTS);
333 m_linkControl.ConvertStaticToLink(m_hWnd, IDC_CHECKALL);
334 m_linkControl.ConvertStaticToLink(m_hWnd, IDC_CHECKNONE);
335 m_linkControl.ConvertStaticToLink(m_hWnd, IDC_CHECKUNVERSIONED);
336 m_linkControl.ConvertStaticToLink(m_hWnd, IDC_CHECKVERSIONED);
337 m_linkControl.ConvertStaticToLink(m_hWnd, IDC_CHECKADDED);
338 m_linkControl.ConvertStaticToLink(m_hWnd, IDC_CHECKDELETED);
339 m_linkControl.ConvertStaticToLink(m_hWnd, IDC_CHECKMODIFIED);
340 m_linkControl.ConvertStaticToLink(m_hWnd, IDC_CHECKFILES);
341 m_linkControl.ConvertStaticToLink(m_hWnd, IDC_CHECKSUBMODULES);
343 // line up all controls and adjust their sizes.
344 #define LINKSPACING 9
345 RECT rc = AdjustControlSize(IDC_SELECTLABEL);
346 rc.right -= 15; // AdjustControlSize() adds 20 pixels for the checkbox/radio button bitmap, but this is a label...
347 rc = AdjustStaticSize(IDC_CHECKALL, rc, LINKSPACING);
348 rc = AdjustStaticSize(IDC_CHECKNONE, rc, LINKSPACING);
349 rc = AdjustStaticSize(IDC_CHECKUNVERSIONED, rc, LINKSPACING);
350 rc = AdjustStaticSize(IDC_CHECKVERSIONED, rc, LINKSPACING);
351 rc = AdjustStaticSize(IDC_CHECKADDED, rc, LINKSPACING);
352 rc = AdjustStaticSize(IDC_CHECKDELETED, rc, LINKSPACING);
353 rc = AdjustStaticSize(IDC_CHECKMODIFIED, rc, LINKSPACING);
354 rc = AdjustStaticSize(IDC_CHECKFILES, rc, LINKSPACING);
355 rc = AdjustStaticSize(IDC_CHECKSUBMODULES, rc, LINKSPACING);
357 GetClientRect(m_DlgOrigRect);
358 m_cLogMessage.GetClientRect(m_LogMsgOrigRect);
360 AddAnchor(IDC_COMMITLABEL, TOP_LEFT, TOP_RIGHT);
361 AddAnchor(IDC_BUGIDLABEL, TOP_RIGHT);
362 AddAnchor(IDC_BUGID, TOP_RIGHT);
363 AddAnchor(IDC_BUGTRAQBUTTON, TOP_RIGHT);
364 AddAnchor(IDC_COMMIT_TO, TOP_LEFT, TOP_RIGHT);
365 AddAnchor(IDC_CHECK_NEWBRANCH, TOP_RIGHT);
366 AddAnchor(IDC_NEWBRANCH, TOP_LEFT, TOP_RIGHT);
367 AddAnchor(IDC_MESSAGEGROUP, TOP_LEFT, TOP_RIGHT);
368 // AddAnchor(IDC_HISTORY, TOP_LEFT);
369 AddAnchor(IDC_LOGMESSAGE, TOP_LEFT, TOP_RIGHT);
370 AddAnchor(IDC_SIGNOFF, TOP_RIGHT);
371 AddAnchor(IDC_VIEW_PATCH, BOTTOM_RIGHT);
372 AddAnchor(IDC_LISTGROUP, TOP_LEFT, BOTTOM_RIGHT);
373 AddAnchor(IDC_SPLITTER, TOP_LEFT, TOP_RIGHT);
374 AddAnchor(IDC_FILELIST, TOP_LEFT, BOTTOM_RIGHT);
375 AddAnchor(IDC_SHOWUNVERSIONED, BOTTOM_LEFT);
376 AddAnchor(IDC_EXTERNALWARNING, BOTTOM_RIGHT);
377 AddAnchor(IDC_STATISTICS, BOTTOM_LEFT, BOTTOM_RIGHT);
378 AddAnchor(IDC_TEXT_INFO, TOP_RIGHT);
379 AddAnchor(IDC_WHOLE_PROJECT, BOTTOM_LEFT);
380 AddAnchor(IDC_KEEPLISTS, BOTTOM_LEFT);
381 AddAnchor(IDC_NOAUTOSELECTSUBMODULES, BOTTOM_LEFT);
382 AddAnchor(IDOK, BOTTOM_RIGHT);
383 AddAnchor(IDCANCEL, BOTTOM_RIGHT);
384 AddAnchor(IDHELP, BOTTOM_RIGHT);
385 AddAnchor(IDC_MERGEACTIVE, BOTTOM_RIGHT);
386 AddAnchor(IDC_COMMIT_AMEND,TOP_LEFT);
387 AddAnchor(IDC_COMMIT_MESSAGEONLY, BOTTOM_LEFT);
388 AddAnchor(IDC_COMMIT_AMENDDIFF,TOP_LEFT);
389 AddAnchor(IDC_COMMIT_SETDATETIME,TOP_LEFT);
390 AddAnchor(IDC_COMMIT_DATEPICKER,TOP_LEFT);
391 AddAnchor(IDC_COMMIT_TIMEPICKER,TOP_LEFT);
392 AddAnchor(IDC_COMMIT_SETAUTHOR, TOP_LEFT);
393 AddAnchor(IDC_COMMIT_AUTHORDATA, TOP_LEFT, TOP_RIGHT);
395 AddAnchor(IDC_SELECTLABEL, TOP_LEFT);
396 AddAnchor(IDC_CHECKALL, TOP_LEFT);
397 AddAnchor(IDC_CHECKNONE, TOP_LEFT);
398 AddAnchor(IDC_CHECKUNVERSIONED, TOP_LEFT);
399 AddAnchor(IDC_CHECKVERSIONED, TOP_LEFT);
400 AddAnchor(IDC_CHECKADDED, TOP_LEFT);
401 AddAnchor(IDC_CHECKDELETED, TOP_LEFT);
402 AddAnchor(IDC_CHECKMODIFIED, TOP_LEFT);
403 AddAnchor(IDC_CHECKFILES, TOP_LEFT);
404 AddAnchor(IDC_CHECKSUBMODULES, TOP_LEFT);
406 if (hWndExplorer)
407 CenterWindow(CWnd::FromHandle(hWndExplorer));
408 EnableSaveRestore(_T("CommitDlg"));
409 DWORD yPos = CRegDWORD(_T("Software\\TortoiseGit\\TortoiseProc\\ResizableState\\CommitDlgSizer"));
410 RECT rcDlg, rcLogMsg, rcFileList;
411 GetClientRect(&rcDlg);
412 m_cLogMessage.GetWindowRect(&rcLogMsg);
413 ScreenToClient(&rcLogMsg);
414 m_ListCtrl.GetWindowRect(&rcFileList);
415 ScreenToClient(&rcFileList);
416 if (yPos)
418 RECT rectSplitter;
419 m_wndSplitter.GetWindowRect(&rectSplitter);
420 ScreenToClient(&rectSplitter);
421 int delta = yPos - rectSplitter.top;
422 if ((rcLogMsg.bottom + delta > rcLogMsg.top)&&(rcLogMsg.bottom + delta < rcFileList.bottom - 30))
424 m_wndSplitter.SetWindowPos(NULL, rectSplitter.left, yPos, 0, 0, SWP_NOSIZE);
425 DoSize(delta);
429 SetSplitterRange();
431 if (m_bForceCommitAmend || m_bCommitAmend)
432 GetDlgItem(IDC_COMMIT_AMENDDIFF)->ShowWindow(SW_SHOW);
434 // add all directories to the watcher
436 for (int i=0; i<m_pathList.GetCount(); ++i)
438 if (m_pathList[i].IsDirectory())
439 m_pathwatcher.AddPath(m_pathList[i]);
442 m_updatedPathList = m_pathList;
444 //first start a thread to obtain the file list with the status without
445 //blocking the dialog
446 InterlockedExchange(&m_bBlock, TRUE);
447 m_pThread = AfxBeginThread(StatusThreadEntry, this, THREAD_PRIORITY_NORMAL,0,CREATE_SUSPENDED);
448 if (m_pThread==NULL)
450 CMessageBox::Show(this->m_hWnd, IDS_ERR_THREADSTARTFAILED, IDS_APPNAME, MB_OK | MB_ICONERROR);
451 InterlockedExchange(&m_bBlock, FALSE);
453 else
455 m_pThread->m_bAutoDelete = FALSE;
456 m_pThread->ResumeThread();
458 CRegDWORD err = CRegDWORD(_T("Software\\TortoiseGit\\ErrorOccurred"), FALSE);
459 CRegDWORD historyhint = CRegDWORD(_T("Software\\TortoiseGit\\HistoryHintShown"), FALSE);
460 if ((((DWORD)err)!=FALSE)&&((((DWORD)historyhint)==FALSE)))
462 historyhint = TRUE;
463 // ShowBalloon(IDC_HISTORY, IDS_COMMITDLG_HISTORYHINT_TT, IDI_INFORMATION);
465 err = FALSE;
467 this->m_ctrlShowPatch.SetURL(CString());
469 if (g_Git.GetConfigValueBool(_T("tgit.commitshowpatch")))
470 OnStnClickedViewPatch();
472 return FALSE; // return TRUE unless you set the focus to a control
473 // EXCEPTION: OCX Property Pages should return FALSE
476 static bool UpdateIndex(CMassiveGitTask &mgt, CSysProgressDlg &sysProgressDlg, int progress, int maxProgress)
478 if (sysProgressDlg.HasUserCancelled())
479 return false;
481 if (sysProgressDlg.IsVisible())
483 sysProgressDlg.SetTitle(IDS_APPNAME);
484 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_COMMIT_PREPARECOMMIT)));
485 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROC_COMMIT_UPDATEINDEX)));
486 sysProgressDlg.SetProgress(progress, maxProgress);
487 AfxGetThread()->PumpMessage(); // process messages, in order to avoid freezing
490 BOOL cancel = FALSE;
491 return mgt.Execute(cancel);
494 void CCommitDlg::OnOK()
496 if (m_bBlock)
497 return;
498 if (m_bThreadRunning)
500 m_bCancelled = true;
501 InterlockedExchange(&m_bRunThread, FALSE);
502 WaitForSingleObject(m_pThread->m_hThread, 1000);
503 if (m_bThreadRunning)
505 // we gave the thread a chance to quit. Since the thread didn't
506 // listen to us we have to kill it.
507 TerminateThread(m_pThread->m_hThread, (DWORD)-1);
508 InterlockedExchange(&m_bThreadRunning, FALSE);
511 this->UpdateData();
513 if (m_bCreateNewBranch)
515 if (!g_Git.IsBranchNameValid(m_sCreateNewBranch))
517 ShowEditBalloon(IDC_NEWBRANCH, IDS_B_T_NOTEMPTY, IDS_ERR_ERROR, TTI_ERROR);
518 return;
520 if (g_Git.BranchTagExists(m_sCreateNewBranch))
522 // branch already exists
523 CString msg;
524 msg.LoadString(IDS_B_EXISTS);
525 msg += _T(" ") + CString(MAKEINTRESOURCE(IDS_B_DELETEORDIFFERENTNAME));
526 ShowEditBalloon(IDC_NEWBRANCH, msg, CString(MAKEINTRESOURCE(IDS_WARN_WARNING)));
527 return;
529 if (g_Git.BranchTagExists(m_sCreateNewBranch, false))
531 // tag with the same name exists -> shortref is ambiguous
532 if (CMessageBox::Show(m_hWnd, IDS_B_SAMETAGNAMEEXISTS, IDS_APPNAME, 2, IDI_EXCLAMATION, IDS_CONTINUEBUTTON, IDS_ABORTBUTTON) == 2)
533 return;
537 CString id;
538 GetDlgItemText(IDC_BUGID, id);
539 if (!m_ProjectProperties.CheckBugID(id))
541 ShowEditBalloon(IDC_BUGID, IDS_COMMITDLG_ONLYNUMBERS, IDS_ERR_ERROR, TTI_ERROR);
542 return;
544 m_sLogMessage = m_cLogMessage.GetText();
545 if ( m_sLogMessage.IsEmpty() )
547 // no message entered, go round again
548 CMessageBox::Show(this->m_hWnd, IDS_COMMITDLG_NOMESSAGE, IDS_APPNAME, MB_OK | MB_ICONERROR);
549 return;
551 if ((m_ProjectProperties.bWarnIfNoIssue) && (id.IsEmpty() && !m_ProjectProperties.HasBugID(m_sLogMessage)))
553 if (CMessageBox::Show(this->m_hWnd, IDS_COMMITDLG_NOISSUEWARNING, IDS_APPNAME, MB_YESNO | MB_ICONWARNING)!=IDYES)
554 return;
557 if (m_ProjectProperties.bWarnNoSignedOffBy == TRUE && m_cLogMessage.GetText().Find(GetSignedOffByLine()) == -1)
559 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);
560 if (retval == 1)
562 OnBnClickedSignOff();
563 m_sLogMessage = m_cLogMessage.GetText();
565 else if (retval == 3)
566 return;
569 if (CHooks::Instance().IsHookPresent(pre_commit_hook, g_Git.m_CurrentDir)) {
570 DWORD exitcode = 0xFFFFFFFF;
571 CString error;
572 CTGitPathList list;
573 m_ListCtrl.WriteCheckedNamesToPathList(list);
574 if (CHooks::Instance().PreCommit(g_Git.m_CurrentDir, list, m_sLogMessage, exitcode, error))
576 if (exitcode)
578 CString temp;
579 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
580 MessageBox(temp, _T("TortoiseGit"), MB_ICONERROR);
581 return;
586 int nListItems = m_ListCtrl.GetItemCount();
587 bool needResetIndex = false;
588 for (int i = 0; i < nListItems && !m_bCommitMessageOnly; ++i)
590 CTGitPath *entry = (CTGitPath *)m_ListCtrl.GetItemData(i);
591 if (!entry->m_Checked && !(entry->m_Action & CTGitPath::LOGACTIONS_UNVER))
592 needResetIndex = true;
593 if (!entry->m_Checked || !entry->IsDirectory())
594 continue;
596 bool dirty = false;
597 if (entry->m_Action & CTGitPath::LOGACTIONS_UNVER)
599 CGit subgit;
600 subgit.m_CurrentDir = g_Git.CombinePath(entry);
601 CString subcmdout;
602 subgit.Run(_T("git.exe status --porcelain"), &subcmdout, CP_UTF8);
603 dirty = !subcmdout.IsEmpty();
605 else
607 CString cmd, cmdout;
608 cmd.Format(_T("git.exe diff -- \"%s\""), entry->GetWinPathString());
609 g_Git.Run(cmd, &cmdout, CP_UTF8);
610 dirty = cmdout.Right(7) == _T("-dirty\n");
613 if (dirty)
615 CString message;
616 message.Format(CString(MAKEINTRESOURCE(IDS_COMMITDLG_SUBMODULEDIRTY)), entry->GetGitPathString());
617 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)));
618 if (result == 1)
620 CString cmdCommit;
621 cmdCommit.Format(_T("/command:commit /path:\"%s\\%s\""), g_Git.m_CurrentDir, entry->GetWinPathString());
622 CAppUtils::RunTortoiseGitProc(cmdCommit);
623 return;
625 else if (result == 2)
626 continue;
627 else
628 return;
632 if (!m_bCommitMessageOnly)
633 m_ListCtrl.WriteCheckedNamesToPathList(m_selectedPathList);
634 m_pathwatcher.Stop();
635 InterlockedExchange(&m_bBlock, TRUE);
636 //first add all the unversioned files the user selected
637 //and check if all versioned files are selected
638 int nchecked = 0;
640 CMassiveGitTask mgtReAddAfterCommit(_T("add --ignore-errors -f"));
642 CString cmd;
643 CString out;
645 bool bAddSuccess=true;
646 bool bCloseCommitDlg=false;
648 CSysProgressDlg sysProgressDlg;
649 if (nListItems >= 25)
651 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_PROC_COMMIT_PREPARECOMMIT)));
652 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_COMMIT_UPDATEINDEX)));
653 sysProgressDlg.SetTime(true);
654 sysProgressDlg.SetShowProgressBar(true);
655 sysProgressDlg.ShowModal(this, true);
658 CBlockCacheForPath cacheBlock(g_Git.m_CurrentDir);
659 DWORD currentTicks = GetTickCount();
661 if (g_Git.UsingLibGit2(CGit::GIT_CMD_COMMIT_UPDATE_INDEX))
664 Do not use the libgit2 implementation right now, since it has several flaws:
665 * https://code.google.com/p/tortoisegit/issues/detail?id=1690: possible access denied problem
666 * https://code.google.com/p/tortoisegit/issues/detail?id=2224: filters not correctly applied
667 * changes to x-bit are not correctly committed, since we reset the index
669 bAddSuccess = false;
672 CAutoRepository repository(g_Git.GetGitRepository());
673 if (!repository)
675 CMessageBox::Show(m_hWnd, CGit::GetLibGit2LastErr(_T("Could not open repository.")), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
676 break;
679 CGitHash revHash;
680 CString revRef = _T("HEAD");
681 if (m_bCommitAmend && !m_bAmendDiffToLastCommit)
682 revRef = _T("HEAD~1");
683 if (CGit::GetHash(repository, revHash, revRef))
685 MessageBox(g_Git.GetLibGit2LastErr(_T("Could not get HEAD hash after committing.")), _T("TortoiseGit"), MB_ICONERROR);
686 break;
689 CAutoCommit commit;
690 if (!revHash.IsEmpty() && needResetIndex && git_commit_lookup(commit.GetPointer(), repository, (const git_oid*)revHash.m_hash))
692 CMessageBox::Show(m_hWnd, CGit::GetLibGit2LastErr(_T("Could not get last commit.")), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
693 break;
696 CAutoTree tree;
697 if (!revHash.IsEmpty() && needResetIndex && git_commit_tree(tree.GetPointer(), commit))
699 CMessageBox::Show(m_hWnd, CGit::GetLibGit2LastErr(_T("Could not read tree of commit.")), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
700 break;
703 CAutoIndex index;
704 if (git_repository_index(index.GetPointer(), repository))
706 CMessageBox::Show(m_hWnd, CGit::GetLibGit2LastErr(_T("Could not get the repository index.")), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
707 break;
710 // reset index to the one of the reference commit (HEAD or HEAD~1)
711 if (!revHash.IsEmpty() && needResetIndex && git_index_read_tree(index, tree))
713 CMessageBox::Show(m_hWnd, CGit::GetLibGit2LastErr(_T("Could not read the tree into the index.")), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
714 break;
716 else if (!revHash.IsEmpty() && !needResetIndex)
718 git_index_read(index, true);
721 bAddSuccess = true;
723 for (int j = 0; j < nListItems; ++j)
725 CTGitPath *entry = (CTGitPath*)m_ListCtrl.GetItemData(j);
727 if (sysProgressDlg.IsVisible())
729 if (GetTickCount() - currentTicks > 1000 || j == nListItems - 1 || j == 0)
731 sysProgressDlg.SetLine(2, entry->GetGitPathString(), true);
732 sysProgressDlg.SetProgress(j, nListItems);
733 AfxGetThread()->PumpMessage(); // process messages, in order to avoid freezing; do not call this too often: this takes time!
734 currentTicks = GetTickCount();
738 CStringA filePathA = CUnicodeUtils::GetMulti(entry->GetGitPathString(), CP_UTF8);
740 if (entry->m_Checked && !m_bCommitMessageOnly)
742 if (entry->IsDirectory())
744 git_submodule *submodule = nullptr;
745 if (git_submodule_lookup(&submodule, repository, filePathA))
747 bAddSuccess = false;
748 CMessageBox::Show(m_hWnd, CGit::GetLibGit2LastErr(_T("Could not open submodule \"") + entry->GetGitPathString() + _T("\".")), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
749 break;
751 if (git_submodule_add_to_index(submodule, FALSE))
753 bAddSuccess = false;
754 CMessageBox::Show(m_hWnd, CGit::GetLibGit2LastErr(_T("Could not add submodule \"") + entry->GetGitPathString() + _T("\" to index.")), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
755 break;
758 else if (entry->m_Action & CTGitPath::LOGACTIONS_DELETED)
760 git_index_remove_bypath(index, filePathA); // ignore error
762 else
764 if (git_index_add_bypath(index, filePathA))
766 bAddSuccess = false;
767 CMessageBox::Show(m_hWnd, CGit::GetLibGit2LastErr(_T("Could not add \"") + entry->GetGitPathString() + _T("\" to index.")), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
768 break;
772 if (entry->m_Action & CTGitPath::LOGACTIONS_REPLACED)
774 git_index_remove_bypath(index, filePathA); // ignore error
777 ++nchecked;
779 else if (entry->m_Action & CTGitPath::LOGACTIONS_ADDED || entry->m_Action & CTGitPath::LOGACTIONS_REPLACED)
780 mgtReAddAfterCommit.AddFile(*entry);
782 if (sysProgressDlg.HasUserCancelled())
784 bAddSuccess = false;
785 break;
788 CShellUpdater::Instance().AddPathForUpdate(*entry);
790 if (bAddSuccess && git_index_write(index))
791 bAddSuccess = false;
792 } while (0);
794 else
796 // ***************************************************
797 // ATTENTION: Similar code in RebaseDlg.cpp!!!
798 // ***************************************************
799 CMassiveGitTask mgtAdd(_T("add -f"));
800 CMassiveGitTask mgtUpdateIndexForceRemove(_T("update-index --force-remove"));
801 CMassiveGitTask mgtUpdateIndex(_T("update-index"));
802 CMassiveGitTask mgtRm(_T("rm --ignore-unmatch"));
803 CMassiveGitTask mgtRmFCache(_T("rm -f --cache"));
804 CString resetCmd = _T("reset");
805 if (m_bCommitAmend && !m_bAmendDiffToLastCommit)
806 resetCmd += _T(" HEAD~1");;
807 CMassiveGitTask mgtReset(resetCmd, TRUE, true);
808 for (int j = 0; j < nListItems; ++j)
810 CTGitPath *entry = (CTGitPath*)m_ListCtrl.GetItemData(j);
812 if (entry->m_Checked && !m_bCommitMessageOnly)
814 if (entry->m_Action & CTGitPath::LOGACTIONS_UNVER)
815 mgtAdd.AddFile(entry->GetGitPathString());
816 else if (entry->m_Action & CTGitPath::LOGACTIONS_DELETED)
817 mgtUpdateIndexForceRemove.AddFile(entry->GetGitPathString());
818 else
819 mgtUpdateIndex.AddFile(entry->GetGitPathString());
821 if ((entry->m_Action & CTGitPath::LOGACTIONS_REPLACED) && !entry->GetGitOldPathString().IsEmpty())
822 mgtRm.AddFile(entry->GetGitOldPathString());
824 ++nchecked;
826 else
828 if (entry->m_Action & CTGitPath::LOGACTIONS_ADDED || entry->m_Action & CTGitPath::LOGACTIONS_REPLACED)
829 { //To init git repository, there are not HEAD, so we can use git reset command
830 mgtRmFCache.AddFile(entry->GetGitPathString());
831 mgtReAddAfterCommit.AddFile(*entry);
833 if (entry->m_Action & CTGitPath::LOGACTIONS_REPLACED && !entry->GetGitOldPathString().IsEmpty())
834 mgtReset.AddFile(entry->GetGitOldPathString());
836 else if (!(entry->m_Action & CTGitPath::LOGACTIONS_UNVER))
837 mgtReset.AddFile(entry->GetGitPathString());
840 if (sysProgressDlg.HasUserCancelled())
842 bAddSuccess = false;
843 break;
847 CMassiveGitTask tasks[] = { mgtAdd, mgtUpdateIndexForceRemove, mgtUpdateIndex, mgtRm, mgtRmFCache, mgtReset };
848 int progress = 0, maxProgress = 0;
849 for (int j = 0; j < _countof(tasks); ++j)
850 maxProgress += tasks[j].GetListCount();
851 for (int j = 0; j < _countof(tasks); ++j)
852 bAddSuccess = bAddSuccess && UpdateIndex(tasks[j], sysProgressDlg, progress += tasks[j].GetListCount(), maxProgress);
854 if (sysProgressDlg.HasUserCancelled())
855 bAddSuccess = false;
857 for (int j = 0; bAddSuccess && j < nListItems; ++j)
858 CShellUpdater::Instance().AddPathForUpdate(*(CTGitPath*)m_ListCtrl.GetItemData(j));
861 if (sysProgressDlg.HasUserCancelled())
862 bAddSuccess = false;
864 //sysProgressDlg.Stop();
866 if (bAddSuccess && m_bCreateNewBranch)
868 if (g_Git.Run(_T("git.exe branch ") + m_sCreateNewBranch, &out, CP_UTF8))
870 MessageBox(_T("Creating new branch failed:\n") + out, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
871 bAddSuccess = false;
873 if (g_Git.Run(_T("git.exe checkout ") + m_sCreateNewBranch + _T(" --"), &out, CP_UTF8))
875 MessageBox(_T("Switching to new branch failed:\n") + out, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
876 bAddSuccess = false;
880 if (bAddSuccess && m_bWarnDetachedHead && CheckHeadDetach())
881 bAddSuccess = false;
883 m_sBugID.Trim();
884 CString sExistingBugID = m_ProjectProperties.FindBugID(m_sLogMessage);
885 sExistingBugID.Trim();
886 if (!m_sBugID.IsEmpty() && m_sBugID.Compare(sExistingBugID))
888 m_sBugID.Replace(_T(", "), _T(","));
889 m_sBugID.Replace(_T(" ,"), _T(","));
890 CString sBugID = m_ProjectProperties.sMessage;
891 sBugID.Replace(_T("%BUGID%"), m_sBugID);
892 if (m_ProjectProperties.bAppend)
893 m_sLogMessage += _T("\n") + sBugID + _T("\n");
894 else
895 m_sLogMessage = sBugID + _T("\n") + m_sLogMessage;
898 // now let the bugtraq plugin check the commit message
899 CComPtr<IBugTraqProvider2> pProvider2 = NULL;
900 if (m_BugTraqProvider)
902 HRESULT hr = m_BugTraqProvider.QueryInterface(&pProvider2);
903 if (SUCCEEDED(hr))
905 ATL::CComBSTR temp;
906 ATL::CComBSTR repositoryRoot(g_Git.m_CurrentDir);
907 ATL::CComBSTR parameters(m_bugtraq_association.GetParameters());
908 ATL::CComBSTR commonRoot(m_pathList.GetCommonRoot().GetDirectory().GetWinPath());
909 ATL::CComBSTR commitMessage(m_sLogMessage);
910 CBstrSafeVector pathList(m_selectedPathList.GetCount());
912 for (LONG index = 0; index < m_selectedPathList.GetCount(); ++index)
913 pathList.PutElement(index, m_selectedPathList[index].GetGitPathString());
915 if (FAILED(hr = pProvider2->CheckCommit(GetSafeHwnd(), parameters, repositoryRoot, commonRoot, pathList, commitMessage, &temp)))
917 COMError ce(hr);
918 CString sErr;
919 sErr.Format(IDS_ERR_FAILEDISSUETRACKERCOM, m_bugtraq_association.GetProviderName(), ce.GetMessageAndDescription().c_str());
920 CMessageBox::Show(m_hWnd, sErr, _T("TortoiseGit"), MB_ICONERROR);
922 else
924 CString sError = temp;
925 if (!sError.IsEmpty())
927 CMessageBox::Show(m_hWnd, sError, _T("TortoiseGit"), MB_ICONERROR);
928 return;
934 if (m_bCommitMessageOnly || bAddSuccess && (nchecked || m_bCommitAmend || CTGitPath(g_Git.m_CurrentDir).IsMergeActive()))
936 bCloseCommitDlg = true;
938 CString tempfile=::GetTempFile();
940 if (CAppUtils::SaveCommitUnicodeFile(tempfile, m_sLogMessage))
942 CMessageBox::Show(nullptr, _T("Could not save commit message"), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
943 return;
946 CTGitPath path=g_Git.m_CurrentDir;
948 BOOL IsGitSVN = path.GetAdminDirMask() & ITEMIS_GITSVN;
950 out =_T("");
951 CString amend;
952 if(this->m_bCommitAmend)
954 amend=_T("--amend");
956 CString dateTime;
957 if (m_bSetCommitDateTime)
959 CTime date, time;
960 m_CommitDate.GetTime(date);
961 m_CommitTime.GetTime(time);
962 dateTime.Format(_T("--date=%sT%s"), date.Format(_T("%Y-%m-%d")), time.Format(_T("%H:%M:%S")));
964 CString author;
965 if (m_bSetAuthor)
966 author.Format(_T("--author=\"%s\""), m_sAuthor);
967 CString allowEmpty = m_bCommitMessageOnly ? _T("--allow-empty") : _T("");
968 cmd.Format(_T("git.exe commit %s %s %s %s -F \"%s\""), author, dateTime, amend, allowEmpty, tempfile);
970 CCommitProgressDlg progress;
971 progress.m_bBufferAll=true; // improve show speed when there are many file added.
972 progress.m_GitCmd=cmd;
973 progress.m_bShowCommand = FALSE; // don't show the commit command
974 progress.m_PreText = out; // show any output already generated in log window
976 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
978 if (status || m_bNoPostActions || m_bAutoClose)
979 return;
981 if (IsGitSVN)
982 postCmdList.push_back(PostCmd(IDI_COMMIT, IDS_MENUSVNDCOMMIT, [&]{ m_PostCmd = GIT_POSTCOMMIT_CMD_DCOMMIT; }));
984 postCmdList.push_back(PostCmd(IDI_PUSH, IDS_MENUPUSH, [&]{ m_PostCmd = GIT_POSTCOMMIT_CMD_PUSH; }));
985 postCmdList.push_back(PostCmd(IDI_PULL, IDS_MENUPULL, [&]{ m_PostCmd = GIT_POSTCOMMIT_CMD_PULL; }));
986 postCmdList.push_back(PostCmd(IDI_COMMIT, IDS_PROC_COMMIT_RECOMMIT, [&]{ m_PostCmd = GIT_POSTCOMMIT_CMD_RECOMMIT; }));
987 postCmdList.push_back(PostCmd(IDI_TAG, IDS_MENUTAG, [&]{ m_PostCmd = GIT_POSTCOMMIT_CMD_CREATETAG; }));
990 m_PostCmd = GIT_POSTCOMMIT_CMD_NOTHING;
991 progress.DoModal();
993 if (progress.m_GitStatus || m_PostCmd == GIT_POSTCOMMIT_CMD_RECOMMIT)
995 bCloseCommitDlg = false;
996 if (m_PostCmd == GIT_POSTCOMMIT_CMD_RECOMMIT)
998 if (!m_sLogMessage.IsEmpty())
1000 m_History.AddEntry(m_sLogMessage);
1001 m_History.Save();
1004 this->m_sLogMessage.Empty();
1005 GetCommitTemplate(m_sLogMessage);
1006 RunStartCommitHook();
1007 m_cLogMessage.SetText(m_sLogMessage);
1008 if (m_bCreateNewBranch)
1010 GetDlgItem(IDC_COMMIT_TO)->ShowWindow(SW_SHOW);
1011 GetDlgItem(IDC_NEWBRANCH)->ShowWindow(SW_HIDE);
1013 m_bCreateNewBranch = FALSE;
1016 if (!progress.m_GitStatus)
1018 m_AmendStr.Empty();
1019 m_bCommitAmend = FALSE;
1022 UpdateData(FALSE);
1023 this->Refresh();
1024 this->BringWindowToTop();
1027 ::DeleteFile(tempfile);
1029 if (m_BugTraqProvider && progress.m_GitStatus == 0)
1031 CComPtr<IBugTraqProvider2> pProvider = NULL;
1032 HRESULT hr = m_BugTraqProvider.QueryInterface(&pProvider);
1033 if (SUCCEEDED(hr))
1035 ATL::CComBSTR commonRoot(g_Git.m_CurrentDir);
1036 CBstrSafeVector pathList(m_selectedPathList.GetCount());
1038 for (LONG index = 0; index < m_selectedPathList.GetCount(); ++index)
1039 pathList.PutElement(index, m_selectedPathList[index].GetGitPathString());
1041 ATL::CComBSTR logMessage(m_sLogMessage);
1043 CGitHash hash;
1044 if (g_Git.GetHash(hash, _T("HEAD")))
1045 MessageBox(g_Git.GetGitLastErr(_T("Could not get HEAD hash after committing.")), _T("TortoiseGit"), MB_ICONERROR);
1046 LONG version = g_Git.Hash2int(hash);
1048 ATL::CComBSTR temp;
1049 if (FAILED(hr = pProvider->OnCommitFinished(GetSafeHwnd(),
1050 commonRoot,
1051 pathList,
1052 logMessage,
1053 (LONG)version,
1054 &temp)))
1056 CString sErr = temp;
1057 if (!sErr.IsEmpty())
1058 CMessageBox::Show(NULL,(sErr),_T("TortoiseGit"),MB_OK|MB_ICONERROR);
1059 else
1061 COMError ce(hr);
1062 sErr.Format(IDS_ERR_FAILEDISSUETRACKERCOM, ce.GetSource().c_str(), ce.GetMessageAndDescription().c_str());
1063 CMessageBox::Show(NULL,(sErr),_T("TortoiseGit"),MB_OK|MB_ICONERROR);
1068 RestoreFiles(progress.m_GitStatus == 0);
1069 if (((DWORD)CRegStdDWORD(_T("Software\\TortoiseGit\\ReaddUnselectedAddedFilesAfterCommit"), TRUE)) == TRUE)
1071 BOOL cancel = FALSE;
1072 mgtReAddAfterCommit.Execute(cancel);
1075 else if(bAddSuccess)
1077 CMessageBox::Show(this->m_hWnd, IDS_ERROR_NOTHING_COMMIT, IDS_COMMIT_FINISH, MB_OK | MB_ICONINFORMATION);
1078 bCloseCommitDlg=false;
1081 UpdateData();
1082 m_regAddBeforeCommit = m_bShowUnversioned;
1083 m_regKeepChangelists = m_bKeepChangeList;
1084 m_regDoNotAutoselectSubmodules = m_bDoNotAutoselectSubmodules;
1085 if (!GetDlgItem(IDC_KEEPLISTS)->IsWindowEnabled())
1086 m_bKeepChangeList = FALSE;
1087 InterlockedExchange(&m_bBlock, FALSE);
1089 if (!m_sLogMessage.IsEmpty())
1091 m_History.AddEntry(m_sLogMessage);
1092 m_History.Save();
1095 SaveSplitterPos();
1097 if( bCloseCommitDlg )
1098 CResizableStandAloneDialog::OnOK();
1100 CShellUpdater::Instance().Flush();
1103 void CCommitDlg::SaveSplitterPos()
1105 if (!IsIconic())
1107 CRegDWORD regPos(_T("Software\\TortoiseGit\\TortoiseProc\\ResizableState\\CommitDlgSizer"));
1108 RECT rectSplitter;
1109 m_wndSplitter.GetWindowRect(&rectSplitter);
1110 ScreenToClient(&rectSplitter);
1111 regPos = rectSplitter.top;
1115 UINT CCommitDlg::StatusThreadEntry(LPVOID pVoid)
1117 return ((CCommitDlg*)pVoid)->StatusThread();
1120 UINT CCommitDlg::StatusThread()
1122 //get the status of all selected file/folders recursively
1123 //and show the ones which have to be committed to the user
1124 //in a list control.
1125 InterlockedExchange(&m_bBlock, TRUE);
1126 InterlockedExchange(&m_bThreadRunning, TRUE);// so the main thread knows that this thread is still running
1127 InterlockedExchange(&m_bRunThread, TRUE); // if this is set to FALSE, the thread should stop
1129 m_pathwatcher.Stop();
1131 m_ListCtrl.SetBusy(true);
1132 g_Git.RefreshGitIndex();
1134 m_bCancelled = false;
1136 DialogEnableWindow(IDOK, false);
1137 DialogEnableWindow(IDC_SHOWUNVERSIONED, false);
1138 DialogEnableWindow(IDC_WHOLE_PROJECT, false);
1139 DialogEnableWindow(IDC_NOAUTOSELECTSUBMODULES, false);
1140 GetDlgItem(IDC_EXTERNALWARNING)->ShowWindow(SW_HIDE);
1141 DialogEnableWindow(IDC_EXTERNALWARNING, false);
1142 DialogEnableWindow(IDC_COMMIT_AMEND, FALSE);
1143 DialogEnableWindow(IDC_COMMIT_AMENDDIFF, FALSE);
1144 // read the list of recent log entries before querying the WC for status
1145 // -> the user may select one and modify / update it while we are crawling the WC
1147 DialogEnableWindow(IDC_CHECKALL, false);
1148 DialogEnableWindow(IDC_CHECKNONE, false);
1149 DialogEnableWindow(IDC_CHECKUNVERSIONED, false);
1150 DialogEnableWindow(IDC_CHECKVERSIONED, false);
1151 DialogEnableWindow(IDC_CHECKADDED, false);
1152 DialogEnableWindow(IDC_CHECKDELETED, false);
1153 DialogEnableWindow(IDC_CHECKMODIFIED, false);
1154 DialogEnableWindow(IDC_CHECKFILES, false);
1155 DialogEnableWindow(IDC_CHECKSUBMODULES, false);
1157 if (m_History.IsEmpty())
1159 CString reg;
1160 reg.Format(_T("Software\\TortoiseGit\\History\\commit%s"), (LPCTSTR)m_ListCtrl.m_sUUID);
1161 reg.Replace(_T(':'),_T('_'));
1162 m_History.Load(reg, _T("logmsgs"));
1165 CString dotGitPath;
1166 g_GitAdminDir.GetAdminDirPath(g_Git.m_CurrentDir, dotGitPath);
1167 if (PathFileExists(dotGitPath + _T("CHERRY_PICK_HEAD")))
1169 GetDlgItem(IDC_COMMIT_AMENDDIFF)->ShowWindow(SW_HIDE);
1170 m_bCommitAmend = FALSE;
1171 SendMessage(WM_UPDATEDATAFALSE);
1174 // Initialise the list control with the status of the files/folders below us
1175 m_ListCtrl.Clear();
1176 BOOL success;
1177 CTGitPathList *pList;
1178 m_ListCtrl.m_amend = (m_bCommitAmend==TRUE || m_bForceCommitAmend) && (m_bAmendDiffToLastCommit==FALSE);
1179 m_ListCtrl.m_bDoNotAutoselectSubmodules = (m_bDoNotAutoselectSubmodules == TRUE);
1181 if(m_bWholeProject || m_bWholeProject2)
1182 pList=NULL;
1183 else
1184 pList = &m_pathList;
1186 success=m_ListCtrl.GetStatus(pList);
1188 //m_ListCtrl.UpdateFileList(git_revnum_t(GIT_REV_ZERO));
1189 if(this->m_bShowUnversioned)
1190 m_ListCtrl.UpdateFileList(CGitStatusListCtrl::FILELIST_UNVER,true,pList);
1192 m_ListCtrl.CheckIfChangelistsArePresent(false);
1194 DWORD dwShow = GITSLC_SHOWVERSIONEDBUTNORMALANDEXTERNALSFROMDIFFERENTREPOS | GITSLC_SHOWLOCKS | GITSLC_SHOWINCHANGELIST | GITSLC_SHOWDIRECTFILES;
1195 dwShow |= DWORD(m_regAddBeforeCommit) ? GITSLC_SHOWUNVERSIONED : 0;
1196 if (success)
1198 if (!m_checkedPathList.IsEmpty())
1199 m_ListCtrl.Show(dwShow, m_checkedPathList);
1200 else
1202 DWORD dwCheck = m_bSelectFilesForCommit ? dwShow : 0;
1203 dwCheck &=~(CTGitPath::LOGACTIONS_UNVER); //don't check unversion file default.
1204 m_ListCtrl.Show(dwShow, dwCheck);
1205 m_bSelectFilesForCommit = true;
1208 if (m_ListCtrl.HasExternalsFromDifferentRepos())
1210 GetDlgItem(IDC_EXTERNALWARNING)->ShowWindow(SW_SHOW);
1211 DialogEnableWindow(IDC_EXTERNALWARNING, TRUE);
1214 SetDlgItemText(IDC_COMMIT_TO, g_Git.GetCurrentBranch());
1215 m_tooltips.AddTool(GetDlgItem(IDC_STATISTICS), m_ListCtrl.GetStatisticsString());
1217 if (!success)
1219 if (!m_ListCtrl.GetLastErrorMessage().IsEmpty())
1220 m_ListCtrl.SetEmptyString(m_ListCtrl.GetLastErrorMessage());
1221 m_ListCtrl.Show(dwShow);
1224 if ((m_ListCtrl.GetItemCount()==0)&&(m_ListCtrl.HasUnversionedItems())
1225 && !PathFileExists(dotGitPath + _T("MERGE_HEAD")))
1227 CString temp;
1228 temp.LoadString(IDS_COMMITDLG_NOTHINGTOCOMMITUNVERSIONED);
1229 if (CMessageBox::ShowCheck(m_hWnd, temp, _T("TortoiseGit"), MB_ICONINFORMATION | MB_YESNO, _T("NothingToCommitShowUnversioned"), NULL)==IDYES)
1231 m_bShowUnversioned = TRUE;
1232 GetDlgItem(IDC_SHOWUNVERSIONED)->SendMessage(BM_SETCHECK, BST_CHECKED);
1233 DWORD dwShow = (DWORD)(GITSLC_SHOWVERSIONEDBUTNORMALANDEXTERNALSFROMDIFFERENTREPOS | GITSLC_SHOWUNVERSIONED | GITSLC_SHOWLOCKS);
1234 m_ListCtrl.UpdateFileList(CGitStatusListCtrl::FILELIST_UNVER);
1235 m_ListCtrl.Show(dwShow,dwShow&(~CTGitPath::LOGACTIONS_UNVER));
1239 SetDlgTitle();
1241 m_autolist.clear();
1242 // we don't have to block the commit dialog while we fetch the
1243 // auto completion list.
1244 m_pathwatcher.ClearChangedPaths();
1245 InterlockedExchange(&m_bBlock, FALSE);
1246 if ((DWORD)CRegDWORD(_T("Software\\TortoiseGit\\Autocompletion"), TRUE)==TRUE)
1248 m_ListCtrl.Block(TRUE, TRUE);
1249 GetAutocompletionList();
1250 m_ListCtrl.Block(FALSE, FALSE);
1252 SendMessage(WM_UPDATEOKBUTTON);
1253 if (m_bRunThread)
1255 DialogEnableWindow(IDC_SHOWUNVERSIONED, true);
1256 DialogEnableWindow(IDC_WHOLE_PROJECT, !m_bWholeProject2);
1257 DialogEnableWindow(IDC_NOAUTOSELECTSUBMODULES, true);
1258 if (m_ListCtrl.HasChangeLists())
1259 DialogEnableWindow(IDC_KEEPLISTS, true);
1261 // activate amend checkbox (if necessary)
1262 if (g_Git.IsInitRepos())
1264 m_bCommitAmend = FALSE;
1265 SendMessage(WM_UPDATEDATAFALSE);
1267 else
1269 if (m_bForceCommitAmend)
1271 m_bCommitAmend = TRUE;
1272 SendMessage(WM_UPDATEDATAFALSE);
1274 else
1275 GetDlgItem(IDC_COMMIT_AMEND)->EnableWindow(!PathFileExists(dotGitPath + _T("CHERRY_PICK_HEAD")));
1277 CGitHash hash;
1278 if (g_Git.GetHash(hash, _T("HEAD")))
1280 MessageBox(g_Git.GetGitLastErr(_T("Could not get HEAD hash.")), _T("TortoiseGit"), MB_ICONERROR);
1282 if (!hash.IsEmpty())
1284 GitRev headRevision;
1287 headRevision.GetParentFromHash(hash);
1289 catch (char* msg)
1291 CString err(msg);
1292 MessageBox(_T("Could not get parent from HEAD.\nlibgit reports:\n") + err, _T("TortoiseGit"), MB_ICONERROR);
1294 // do not allow to show diff to "last" revision if it has more that one parent
1295 if (headRevision.ParentsCount() != 1)
1297 m_bAmendDiffToLastCommit = TRUE;
1298 SendMessage(WM_UPDATEDATAFALSE);
1300 else
1301 GetDlgItem(IDC_COMMIT_AMENDDIFF)->EnableWindow(TRUE);
1305 UpdateCheckLinks();
1307 // we have the list, now signal the main thread about it
1308 SendMessage(WM_AUTOLISTREADY); // only send the message if the thread wasn't told to quit!
1311 InterlockedExchange(&m_bRunThread, FALSE);
1312 InterlockedExchange(&m_bThreadRunning, FALSE);
1313 // force the cursor to normal
1314 RefreshCursor();
1316 return 0;
1319 void CCommitDlg::SetDlgTitle()
1321 if (m_sTitle.IsEmpty())
1322 GetWindowText(m_sTitle);
1324 if (m_bWholeProject || m_bWholeProject2)
1325 CAppUtils::SetWindowTitle(m_hWnd, g_Git.m_CurrentDir, m_sTitle);
1326 else
1328 if (m_pathList.GetCount() == 1)
1329 CAppUtils::SetWindowTitle(m_hWnd, g_Git.CombinePath(m_pathList[0].GetUIPathString()), m_sTitle);
1330 else
1331 CAppUtils::SetWindowTitle(m_hWnd, g_Git.CombinePath(m_ListCtrl.GetCommonDirectory(false)), m_sTitle);
1335 void CCommitDlg::OnCancel()
1337 m_bCancelled = true;
1338 m_pathwatcher.Stop();
1340 if (m_bThreadRunning)
1342 InterlockedExchange(&m_bRunThread, FALSE);
1343 WaitForSingleObject(m_pThread->m_hThread, 1000);
1344 if (m_bThreadRunning)
1346 // we gave the thread a chance to quit. Since the thread didn't
1347 // listen to us we have to kill it.
1348 TerminateThread(m_pThread->m_hThread, (DWORD)-1);
1349 InterlockedExchange(&m_bThreadRunning, FALSE);
1352 UpdateData();
1353 m_sBugID.Trim();
1354 m_sLogMessage = m_cLogMessage.GetText();
1355 if (!m_sBugID.IsEmpty())
1357 m_sBugID.Replace(_T(", "), _T(","));
1358 m_sBugID.Replace(_T(" ,"), _T(","));
1359 CString sBugID = m_ProjectProperties.sMessage;
1360 sBugID.Replace(_T("%BUGID%"), m_sBugID);
1361 if (m_ProjectProperties.bAppend)
1362 m_sLogMessage += _T("\n") + sBugID + _T("\n");
1363 else
1364 m_sLogMessage = sBugID + _T("\n") + m_sLogMessage;
1366 if ((m_sLogTemplate.Compare(m_sLogMessage) != 0) && !m_sLogMessage.IsEmpty())
1368 m_History.AddEntry(m_sLogMessage);
1369 m_History.Save();
1371 RestoreFiles();
1372 SaveSplitterPos();
1373 CResizableStandAloneDialog::OnCancel();
1376 BOOL CCommitDlg::PreTranslateMessage(MSG* pMsg)
1378 if (!m_bBlock)
1379 m_tooltips.RelayEvent(pMsg);
1381 if (m_hAccel)
1383 int ret = TranslateAccelerator(m_hWnd, m_hAccel, pMsg);
1384 if (ret)
1385 return TRUE;
1388 if (pMsg->message == WM_KEYDOWN)
1390 switch (pMsg->wParam)
1392 case VK_F5:
1394 if (m_bBlock)
1395 return CResizableStandAloneDialog::PreTranslateMessage(pMsg);
1396 Refresh();
1398 break;
1399 case VK_RETURN:
1401 if (GetAsyncKeyState(VK_CONTROL)&0x8000)
1403 if ( GetDlgItem(IDOK)->IsWindowEnabled() )
1405 PostMessage(WM_COMMAND, IDOK);
1407 return TRUE;
1409 if ( GetFocus()==GetDlgItem(IDC_BUGID) )
1411 // Pressing RETURN in the bug id control
1412 // moves the focus to the message
1413 GetDlgItem(IDC_LOGMESSAGE)->SetFocus();
1414 return TRUE;
1417 break;
1421 return CResizableStandAloneDialog::PreTranslateMessage(pMsg);
1424 void CCommitDlg::Refresh()
1426 if (m_bThreadRunning)
1427 return;
1429 InterlockedExchange(&m_bBlock, TRUE);
1430 m_pThread = AfxBeginThread(StatusThreadEntry, this, THREAD_PRIORITY_NORMAL,0,CREATE_SUSPENDED);
1431 if (m_pThread==NULL)
1433 CMessageBox::Show(this->m_hWnd, IDS_ERR_THREADSTARTFAILED, IDS_APPNAME, MB_OK | MB_ICONERROR);
1434 InterlockedExchange(&m_bBlock, FALSE);
1436 else
1438 m_pThread->m_bAutoDelete = FALSE;
1439 m_pThread->ResumeThread();
1443 void CCommitDlg::OnBnClickedShowunversioned()
1445 m_tooltips.Pop(); // hide the tooltips
1446 UpdateData();
1447 m_regAddBeforeCommit = m_bShowUnversioned;
1448 if (!m_bBlock)
1450 DWORD dwShow = m_ListCtrl.GetShowFlags();
1451 if (DWORD(m_regAddBeforeCommit))
1452 dwShow |= GITSLC_SHOWUNVERSIONED;
1453 else
1454 dwShow &= ~GITSLC_SHOWUNVERSIONED;
1455 if(dwShow & GITSLC_SHOWUNVERSIONED)
1457 if (m_bWholeProject || m_bWholeProject2)
1458 m_ListCtrl.GetStatus(NULL,false,false,true);
1459 else
1460 m_ListCtrl.GetStatus(&this->m_pathList,false,false,true);
1462 m_ListCtrl.Show(dwShow, 0, true, dwShow & ~(CTGitPath::LOGACTIONS_UNVER), true);
1463 UpdateCheckLinks();
1467 void CCommitDlg::OnStnClickedExternalwarning()
1469 m_tooltips.Popup();
1472 void CCommitDlg::OnEnChangeLogmessage()
1474 SendMessage(WM_UPDATEOKBUTTON);
1477 LRESULT CCommitDlg::OnGitStatusListCtrlItemCountChanged(WPARAM, LPARAM)
1479 #if 0
1480 if ((m_ListCtrl.GetItemCount() == 0)&&(m_ListCtrl.HasUnversionedItems())&&(!m_bShowUnversioned))
1482 if (CMessageBox::Show(*this, IDS_COMMITDLG_NOTHINGTOCOMMITUNVERSIONED, IDS_APPNAME, MB_ICONINFORMATION | MB_YESNO)==IDYES)
1484 m_bShowUnversioned = TRUE;
1485 DWORD dwShow = GitSLC_SHOWVERSIONEDBUTNORMALANDEXTERNALSFROMDIFFERENTREPOS | GitSLC_SHOWUNVERSIONED | GitSLC_SHOWLOCKS;
1486 m_ListCtrl.Show(dwShow);
1487 UpdateData(FALSE);
1490 #endif
1491 return 0;
1494 LRESULT CCommitDlg::OnGitStatusListCtrlNeedsRefresh(WPARAM, LPARAM)
1496 Refresh();
1497 return 0;
1500 LRESULT CCommitDlg::OnFileDropped(WPARAM, LPARAM /*lParam*/)
1502 #if 0
1503 BringWindowToTop();
1504 SetForegroundWindow();
1505 SetActiveWindow();
1506 // if multiple files/folders are dropped
1507 // this handler is called for every single item
1508 // separately.
1509 // To avoid creating multiple refresh threads and
1510 // causing crashes, we only add the items to the
1511 // list control and start a timer.
1512 // When the timer expires, we start the refresh thread,
1513 // but only if it isn't already running - otherwise we
1514 // restart the timer.
1515 CTGitPath path;
1516 path.SetFromWin((LPCTSTR)lParam);
1518 // just add all the items we get here.
1519 // if the item is versioned, the add will fail but nothing
1520 // more will happen.
1521 Git Git;
1522 Git.Add(CTGitPathList(path), &m_ProjectProperties, Git_depth_empty, false, true, true);
1524 if (!m_ListCtrl.HasPath(path))
1526 if (m_pathList.AreAllPathsFiles())
1528 m_pathList.AddPath(path);
1529 m_pathList.RemoveDuplicates();
1530 m_updatedPathList.AddPath(path);
1531 m_updatedPathList.RemoveDuplicates();
1533 else
1535 // if the path list contains folders, we have to check whether
1536 // our just (maybe) added path is a child of one of those. If it is
1537 // a child of a folder already in the list, we must not add it. Otherwise
1538 // that path could show up twice in the list.
1539 bool bHasParentInList = false;
1540 for (int i=0; i<m_pathList.GetCount(); ++i)
1542 if (m_pathList[i].IsAncestorOf(path))
1544 bHasParentInList = true;
1545 break;
1548 if (!bHasParentInList)
1550 m_pathList.AddPath(path);
1551 m_pathList.RemoveDuplicates();
1552 m_updatedPathList.AddPath(path);
1553 m_updatedPathList.RemoveDuplicates();
1558 // Always start the timer, since the status of an existing item might have changed
1559 SetTimer(REFRESHTIMER, 200, NULL);
1560 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": Item %s dropped, timer started\n"), path.GetWinPath());
1561 #endif
1562 return 0;
1565 LRESULT CCommitDlg::OnAutoListReady(WPARAM, LPARAM)
1567 m_cLogMessage.SetAutoCompletionList(m_autolist, '*');
1568 return 0;
1571 //////////////////////////////////////////////////////////////////////////
1572 // functions which run in the status thread
1573 //////////////////////////////////////////////////////////////////////////
1575 void CCommitDlg::ParseRegexFile(const CString& sFile, std::map<CString, CString>& mapRegex)
1577 CString strLine;
1580 CStdioFile file(sFile, CFile::typeText | CFile::modeRead | CFile::shareDenyWrite);
1581 while (m_bRunThread && file.ReadString(strLine))
1583 int eqpos = strLine.Find('=');
1584 CString rgx;
1585 rgx = strLine.Mid(eqpos+1).Trim();
1587 int pos = -1;
1588 while (((pos = strLine.Find(','))>=0)&&(pos < eqpos))
1590 mapRegex[strLine.Left(pos)] = rgx;
1591 strLine = strLine.Mid(pos+1).Trim();
1593 mapRegex[strLine.Left(strLine.Find('=')).Trim()] = rgx;
1595 file.Close();
1597 catch (CFileException* pE)
1599 CTraceToOutputDebugString::Instance()(__FUNCTION__ ": CFileException loading auto list regex file\n");
1600 pE->Delete();
1604 void CCommitDlg::ParseSnippetFile(const CString& sFile, std::map<CString, CString>& mapSnippet)
1606 CString strLine;
1609 CStdioFile file(sFile, CFile::typeText | CFile::modeRead | CFile::shareDenyWrite);
1610 while (m_bRunThread && file.ReadString(strLine))
1612 if (strLine.IsEmpty())
1613 continue;
1614 if (strLine.Left(1) == _T('#')) // comment char
1615 continue;
1616 int eqpos = strLine.Find('=');
1617 CString key = strLine.Left(eqpos);
1618 CString value = strLine.Mid(eqpos + 1);
1619 value.Replace(_T("\\\t"), _T("\t"));
1620 value.Replace(_T("\\\r"), _T("\r"));
1621 value.Replace(_T("\\\n"), _T("\n"));
1622 value.Replace(_T("\\\\"), _T("\\"));
1623 mapSnippet[key] = value;
1625 file.Close();
1627 catch (CFileException* pE)
1629 CTraceToOutputDebugString::Instance()(__FUNCTION__ ": CFileException loading auto list regex file\n");
1630 pE->Delete();
1634 void CCommitDlg::GetAutocompletionList()
1636 // the auto completion list is made of strings from each selected files.
1637 // the strings used are extracted from the files with regexes found
1638 // in the file "autolist.txt".
1639 // the format of that file is:
1640 // file extensions separated with commas '=' regular expression to use
1641 // example:
1642 // .h, .hpp = (?<=class[\s])\b\w+\b|(\b\w+(?=[\s ]?\(\);))
1643 // .cpp = (?<=[^\s]::)\b\w+\b
1645 std::map<CString, CString> mapRegex;
1646 CString sRegexFile = CPathUtils::GetAppDirectory();
1647 CRegDWORD regtimeout = CRegDWORD(_T("Software\\TortoiseGit\\AutocompleteParseTimeout"), 5);
1648 DWORD timeoutvalue = regtimeout*1000;
1649 sRegexFile += _T("autolist.txt");
1650 if (!m_bRunThread)
1651 return;
1652 ParseRegexFile(sRegexFile, mapRegex);
1653 sRegexFile = CPathUtils::GetAppDataDirectory();
1654 sRegexFile += _T("autolist.txt");
1655 if (PathFileExists(sRegexFile))
1656 ParseRegexFile(sRegexFile, mapRegex);
1658 m_snippet.clear();
1659 CString sSnippetFile = CPathUtils::GetAppDirectory();
1660 sSnippetFile += _T("snippet.txt");
1661 ParseSnippetFile(sSnippetFile, m_snippet);
1662 sSnippetFile = CPathUtils::GetAppDataDirectory();
1663 sSnippetFile += _T("snippet.txt");
1664 if (PathFileExists(sSnippetFile))
1665 ParseSnippetFile(sSnippetFile, m_snippet);
1666 for (auto snip : m_snippet)
1667 m_autolist.insert(std::make_pair(snip.first, AUTOCOMPLETE_SNIPPET));
1669 DWORD starttime = GetTickCount();
1671 // now we have two arrays of strings, where the first array contains all
1672 // file extensions we can use and the second the corresponding regex strings
1673 // to apply to those files.
1675 // the next step is to go over all files shown in the commit dialog
1676 // and scan them for strings we can use
1677 int nListItems = m_ListCtrl.GetItemCount();
1679 for (int i=0; i<nListItems && m_bRunThread; ++i)
1681 // stop parsing after timeout
1682 if ((!m_bRunThread) || (GetTickCount() - starttime > timeoutvalue))
1683 return;
1685 CTGitPath *path = (CTGitPath*)m_ListCtrl.GetItemData(i);
1687 if(path == NULL)
1688 continue;
1690 CString sPartPath =path->GetGitPathString();
1691 m_autolist.insert(std::make_pair(sPartPath, AUTOCOMPLETE_FILENAME));
1693 int pos = 0;
1694 int lastPos = 0;
1695 while ((pos = sPartPath.Find('/', pos)) >= 0)
1697 ++pos;
1698 lastPos = pos;
1699 m_autolist.insert(std::make_pair(sPartPath.Mid(pos), AUTOCOMPLETE_FILENAME));
1702 // Last inserted entry is a file name.
1703 // Some users prefer to also list file name without extension.
1704 if (CRegDWORD(_T("Software\\TortoiseGit\\AutocompleteRemovesExtensions"), FALSE))
1706 int dotPos = sPartPath.ReverseFind('.');
1707 if ((dotPos >= 0) && (dotPos > lastPos))
1708 m_autolist.insert(std::make_pair(sPartPath.Mid(lastPos, dotPos - lastPos), AUTOCOMPLETE_FILENAME));
1711 if (path->m_Action == CTGitPath::LOGACTIONS_UNVER && !CRegDWORD(_T("Software\\TortoiseGit\\AutocompleteParseUnversioned"), FALSE))
1712 continue;
1713 if (path->m_Action == CTGitPath::LOGACTIONS_IGNORE || path->m_Action == CTGitPath::LOGACTIONS_DELETED)
1714 continue;
1716 CString sExt = path->GetFileExtension();
1717 sExt.MakeLower();
1718 // find the regex string which corresponds to the file extension
1719 CString rdata = mapRegex[sExt];
1720 if (rdata.IsEmpty())
1721 continue;
1723 ScanFile(path->GetWinPathString(), rdata, sExt);
1725 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": Auto completion list loaded in %d msec\n"), GetTickCount() - starttime);
1728 void CCommitDlg::ScanFile(const CString& sFilePath, const CString& sRegex, const CString& sExt)
1730 static std::map<CString, std::tr1::wregex> regexmap;
1732 std::wstring sFileContent;
1733 CAutoFile hFile = CreateFile(sFilePath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL);
1734 if (hFile)
1736 DWORD size = GetFileSize(hFile, NULL);
1737 if (size > CRegDWORD(_T("Software\\TortoiseGit\\AutocompleteParseMaxSize"), 300000L))
1739 // no files bigger than 300k
1740 return;
1742 // allocate memory to hold file contents
1743 std::unique_ptr<char[]> buffer(new char[size]);
1744 DWORD readbytes;
1745 if (!ReadFile(hFile, buffer.get(), size, &readbytes, NULL))
1746 return;
1747 int opts = 0;
1748 IsTextUnicode(buffer.get(), readbytes, &opts);
1749 if (opts & IS_TEXT_UNICODE_NULL_BYTES)
1751 return;
1753 if (opts & IS_TEXT_UNICODE_UNICODE_MASK)
1755 sFileContent = std::wstring((wchar_t*)buffer.get(), readbytes / sizeof(WCHAR));
1757 if ((opts & IS_TEXT_UNICODE_NOT_UNICODE_MASK) || (opts == 0))
1759 const int ret = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, (LPCSTR)buffer.get(), readbytes, NULL, 0);
1760 std::unique_ptr<wchar_t[]> pWideBuf(new wchar_t[ret]);
1761 const int ret2 = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, (LPCSTR)buffer.get(), readbytes, pWideBuf.get(), ret);
1762 if (ret2 == ret)
1763 sFileContent = std::wstring(pWideBuf.get(), ret);
1766 if (sFileContent.empty() || !m_bRunThread)
1768 return;
1774 std::tr1::wregex regCheck;
1775 std::map<CString, std::tr1::wregex>::const_iterator regIt;
1776 if ((regIt = regexmap.find(sExt)) != regexmap.end())
1777 regCheck = regIt->second;
1778 else
1780 regCheck = std::tr1::wregex(sRegex, std::tr1::regex_constants::icase | std::tr1::regex_constants::ECMAScript);
1781 regexmap[sExt] = regCheck;
1783 const std::tr1::wsregex_iterator end;
1784 for (std::tr1::wsregex_iterator it(sFileContent.begin(), sFileContent.end(), regCheck); it != end; ++it)
1786 const std::tr1::wsmatch match = *it;
1787 for (size_t i = 1; i < match.size(); ++i)
1789 if (match[i].second-match[i].first)
1791 m_autolist.insert(std::make_pair(std::wstring(match[i]).c_str(), AUTOCOMPLETE_PROGRAMCODE));
1796 catch (std::exception) {}
1799 // CSciEditContextMenuInterface
1800 void CCommitDlg::InsertMenuItems(CMenu& mPopup, int& nCmd)
1802 CString sMenuItemText;
1803 sMenuItemText.LoadString(IDS_COMMITDLG_POPUP_PICKCOMMITHASH);
1804 m_nPopupPickCommitHash = nCmd++;
1805 mPopup.AppendMenu(MF_STRING | MF_ENABLED, m_nPopupPickCommitHash, sMenuItemText);
1807 sMenuItemText.LoadString(IDS_COMMITDLG_POPUP_PICKCOMMITMESSAGE);
1808 m_nPopupPickCommitMessage = nCmd++;
1809 mPopup.AppendMenu(MF_STRING | MF_ENABLED, m_nPopupPickCommitMessage, sMenuItemText);
1811 sMenuItemText.LoadString(IDS_COMMITDLG_POPUP_PASTEFILELIST);
1812 m_nPopupPasteListCmd = nCmd++;
1813 mPopup.AppendMenu(MF_STRING | MF_ENABLED, m_nPopupPasteListCmd, sMenuItemText);
1815 if (!m_History.IsEmpty())
1817 sMenuItemText.LoadString(IDS_COMMITDLG_POPUP_PASTELASTMESSAGE);
1818 m_nPopupPasteLastMessage = nCmd++;
1819 mPopup.AppendMenu(MF_STRING | MF_ENABLED, m_nPopupPasteLastMessage, sMenuItemText);
1821 sMenuItemText.LoadString(IDS_COMMITDLG_POPUP_LOGHISTORY);
1822 m_nPopupRecentMessage = nCmd++;
1823 mPopup.AppendMenu(MF_STRING | MF_ENABLED, m_nPopupRecentMessage, sMenuItemText);
1827 bool CCommitDlg::HandleMenuItemClick(int cmd, CSciEdit * pSciEdit)
1829 if (cmd == m_nPopupPickCommitHash)
1831 // use the git log to allow selection of a version
1832 CLogDlg dlg;
1833 // tell the dialog to use mode for selecting revisions
1834 dlg.SetSelect(true);
1835 // only one revision must be selected however
1836 dlg.SingleSelection(true);
1837 if (dlg.DoModal() == IDOK)
1839 // get selected hash if any
1840 CString selectedHash = dlg.GetSelectedHash();
1841 pSciEdit->InsertText(selectedHash);
1843 return true;
1846 if (cmd == m_nPopupPickCommitMessage)
1848 // use the git log to allow selection of a version
1849 CLogDlg dlg;
1850 // tell the dialog to use mode for selecting revisions
1851 dlg.SetSelect(true);
1852 // only one revision must be selected however
1853 dlg.SingleSelection(true);
1854 if (dlg.DoModal() == IDOK)
1856 // get selected hash if any
1857 CString selectedHash = dlg.GetSelectedHash();
1858 GitRev rev;
1859 rev.GetCommit(selectedHash);
1860 CString message = rev.GetSubject() + _T("\r\n") + rev.GetBody();
1861 pSciEdit->InsertText(message);
1863 return true;
1866 if (cmd == m_nPopupPasteListCmd)
1868 CString logmsg;
1869 int nListItems = m_ListCtrl.GetItemCount();
1870 for (int i=0; i<nListItems; ++i)
1872 CTGitPath * entry = (CTGitPath*)m_ListCtrl.GetItemData(i);
1873 if (entry&&entry->m_Checked)
1875 CString line;
1876 CString status = entry->GetActionName();
1877 if(entry->m_Action & CTGitPath::LOGACTIONS_UNVER)
1878 status = _T("Add"); // I18N TODO
1880 //git_wc_status_kind status = entry->status;
1881 WORD langID = (WORD)CRegStdDWORD(_T("Software\\TortoiseGit\\LanguageID"), GetUserDefaultLangID());
1882 if (m_ProjectProperties.bFileListInEnglish)
1883 langID = 1033;
1885 line.Format(_T("%-10s %s\r\n"),status , (LPCTSTR)m_ListCtrl.GetItemText(i,0));
1886 logmsg += line;
1889 pSciEdit->InsertText(logmsg);
1890 return true;
1893 if(cmd == m_nPopupPasteLastMessage)
1895 if (m_History.IsEmpty())
1896 return false;
1898 CString logmsg;
1899 logmsg +=m_History.GetEntry(0);
1900 pSciEdit->InsertText(logmsg);
1901 return true;
1904 if(cmd == m_nPopupRecentMessage )
1906 OnBnClickedHistory();
1907 return true;
1909 return false;
1912 void CCommitDlg::HandleSnippet(int type, const CString &text, CSciEdit *pSciEdit)
1914 if (type == AUTOCOMPLETE_SNIPPET)
1916 CString target = m_snippet[text];
1917 pSciEdit->GetWordUnderCursor(true);
1918 pSciEdit->InsertText(target, false);
1922 void CCommitDlg::OnTimer(UINT_PTR nIDEvent)
1924 switch (nIDEvent)
1926 case ENDDIALOGTIMER:
1927 KillTimer(ENDDIALOGTIMER);
1928 EndDialog(0);
1929 break;
1930 case REFRESHTIMER:
1931 if (m_bThreadRunning)
1933 SetTimer(REFRESHTIMER, 200, NULL);
1934 CTraceToOutputDebugString::Instance()(__FUNCTION__ ": Wait some more before refreshing\n");
1936 else
1938 KillTimer(REFRESHTIMER);
1939 CTraceToOutputDebugString::Instance()(__FUNCTION__ ": Refreshing after items dropped\n");
1940 Refresh();
1942 break;
1943 case FILLPATCHVTIMER:
1944 FillPatchView();
1945 break;
1947 __super::OnTimer(nIDEvent);
1950 void CCommitDlg::OnBnClickedHistory()
1952 m_tooltips.Pop(); // hide the tooltips
1953 if (m_pathList.IsEmpty())
1954 return;
1956 CHistoryDlg historyDlg;
1957 historyDlg.SetHistory(m_History);
1958 if (historyDlg.DoModal() != IDOK)
1959 return;
1961 CString sMsg = historyDlg.GetSelectedText();
1962 if (sMsg != m_cLogMessage.GetText().Left(sMsg.GetLength()))
1964 CString sBugID = m_ProjectProperties.FindBugID(sMsg);
1965 if ((!sBugID.IsEmpty()) && ((GetDlgItem(IDC_BUGID)->IsWindowVisible())))
1967 SetDlgItemText(IDC_BUGID, sBugID);
1969 if (m_sLogTemplate.Compare(m_cLogMessage.GetText()) != 0)
1970 m_cLogMessage.InsertText(sMsg, !m_cLogMessage.GetText().IsEmpty());
1971 else
1972 m_cLogMessage.SetText(sMsg);
1975 SendMessage(WM_UPDATEOKBUTTON);
1976 GetDlgItem(IDC_LOGMESSAGE)->SetFocus();
1980 void CCommitDlg::OnBnClickedBugtraqbutton()
1982 m_tooltips.Pop(); // hide the tooltips
1983 CString sMsg = m_cLogMessage.GetText();
1985 if (m_BugTraqProvider == NULL)
1986 return;
1988 ATL::CComBSTR parameters(m_bugtraq_association.GetParameters());
1989 ATL::CComBSTR commonRoot(m_pathList.GetCommonRoot().GetDirectory().GetWinPath());
1990 CBstrSafeVector pathList(m_pathList.GetCount());
1992 for (LONG index = 0; index < m_pathList.GetCount(); ++index)
1993 pathList.PutElement(index, m_pathList[index].GetGitPathString());
1995 ATL::CComBSTR originalMessage(sMsg);
1996 ATL::CComBSTR temp;
1998 // first try the IBugTraqProvider2 interface
1999 CComPtr<IBugTraqProvider2> pProvider2 = NULL;
2000 HRESULT hr = m_BugTraqProvider.QueryInterface(&pProvider2);
2001 bool bugIdOutSet = false;
2002 if (SUCCEEDED(hr))
2004 ATL::CComBSTR repositoryRoot(g_Git.m_CurrentDir);
2005 ATL::CComBSTR bugIDOut;
2006 GetDlgItemText(IDC_BUGID, m_sBugID);
2007 ATL::CComBSTR bugID(m_sBugID);
2008 CBstrSafeVector revPropNames;
2009 CBstrSafeVector revPropValues;
2010 if (FAILED(hr = pProvider2->GetCommitMessage2(GetSafeHwnd(), parameters, repositoryRoot, commonRoot, pathList, originalMessage, bugID, &bugIDOut, &revPropNames, &revPropValues, &temp)))
2012 CString sErr;
2013 sErr.Format(IDS_ERR_FAILEDISSUETRACKERCOM, m_bugtraq_association.GetProviderName(), _com_error(hr).ErrorMessage());
2014 CMessageBox::Show(m_hWnd, sErr, _T("TortoiseGit"), MB_ICONERROR);
2016 else
2018 if (bugIDOut)
2020 bugIdOutSet = true;
2021 m_sBugID = bugIDOut;
2022 SetDlgItemText(IDC_BUGID, m_sBugID);
2024 m_cLogMessage.SetText((LPCTSTR)temp);
2025 BSTR HUGEP *pbRevNames;
2026 BSTR HUGEP *pbRevValues;
2028 HRESULT hr1 = SafeArrayAccessData(revPropNames, (void HUGEP**)&pbRevNames);
2029 if (SUCCEEDED(hr1))
2031 HRESULT hr2 = SafeArrayAccessData(revPropValues, (void HUGEP**)&pbRevValues);
2032 if (SUCCEEDED(hr2))
2034 if (revPropNames->rgsabound->cElements == revPropValues->rgsabound->cElements)
2036 for (ULONG i = 0; i < revPropNames->rgsabound->cElements; ++i)
2038 // m_revProps[pbRevNames[i]] = pbRevValues[i];
2041 SafeArrayUnaccessData(revPropValues);
2043 SafeArrayUnaccessData(revPropNames);
2047 else
2049 // if IBugTraqProvider2 failed, try IBugTraqProvider
2050 CComPtr<IBugTraqProvider> pProvider = NULL;
2051 hr = m_BugTraqProvider.QueryInterface(&pProvider);
2052 if (FAILED(hr))
2054 CString sErr;
2055 sErr.Format(IDS_ERR_FAILEDISSUETRACKERCOM, (LPCTSTR)m_bugtraq_association.GetProviderName(), _com_error(hr).ErrorMessage());
2056 CMessageBox::Show(m_hWnd, sErr, _T("TortoiseGit"), MB_ICONERROR);
2057 return;
2060 if (FAILED(hr = pProvider->GetCommitMessage(GetSafeHwnd(), parameters, commonRoot, pathList, originalMessage, &temp)))
2062 CString sErr;
2063 sErr.Format(IDS_ERR_FAILEDISSUETRACKERCOM, m_bugtraq_association.GetProviderName(), _com_error(hr).ErrorMessage());
2064 CMessageBox::Show(m_hWnd, sErr, _T("TortoiseGit"), MB_ICONERROR);
2066 else
2067 m_cLogMessage.SetText((LPCTSTR)temp);
2069 m_sLogMessage = m_cLogMessage.GetText();
2070 if (!m_ProjectProperties.sMessage.IsEmpty())
2072 CString sBugID = m_ProjectProperties.FindBugID(m_sLogMessage);
2073 if (!sBugID.IsEmpty() && !bugIdOutSet)
2075 SetDlgItemText(IDC_BUGID, sBugID);
2079 m_cLogMessage.SetFocus();
2082 void CCommitDlg::FillPatchView(bool onlySetTimer)
2084 if(::IsWindow(this->m_patchViewdlg.m_hWnd))
2086 KillTimer(FILLPATCHVTIMER);
2087 if (onlySetTimer)
2089 SetTimer(FILLPATCHVTIMER, 100, NULL);
2090 return;
2093 POSITION pos=m_ListCtrl.GetFirstSelectedItemPosition();
2094 CString cmd,out;
2096 while(pos)
2098 int nSelect = m_ListCtrl.GetNextSelectedItem(pos);
2099 CTGitPath * p=(CTGitPath*)m_ListCtrl.GetItemData(nSelect);
2100 if(p && !(p->m_Action&CTGitPath::LOGACTIONS_UNVER) )
2102 CString head = _T("HEAD");
2103 if(m_bCommitAmend==TRUE && m_bAmendDiffToLastCommit==FALSE)
2104 head = _T("HEAD~1");
2105 cmd.Format(_T("git.exe diff %s -- \"%s\""), head, p->GetGitPathString());
2106 g_Git.Run(cmd, &out, CP_UTF8);
2110 m_patchViewdlg.SetText(out);
2113 LRESULT CCommitDlg::OnGitStatusListCtrlItemChanged(WPARAM /*wparam*/, LPARAM /*lparam*/)
2115 this->FillPatchView(true);
2116 return 0;
2120 LRESULT CCommitDlg::OnGitStatusListCtrlCheckChanged(WPARAM, LPARAM)
2122 SendMessage(WM_UPDATEOKBUTTON);
2123 return 0;
2126 LRESULT CCommitDlg::OnCheck(WPARAM wnd, LPARAM)
2128 HWND hwnd = (HWND)wnd;
2129 bool check = !(GetAsyncKeyState(VK_SHIFT) & 0x8000);
2130 if (hwnd == GetDlgItem(IDC_CHECKALL)->GetSafeHwnd())
2131 m_ListCtrl.Check(GITSLC_SHOWEVERYTHING, check);
2132 else if (hwnd == GetDlgItem(IDC_CHECKNONE)->GetSafeHwnd())
2133 m_ListCtrl.Check(GITSLC_SHOWEVERYTHING, !check);
2134 else if (hwnd == GetDlgItem(IDC_CHECKUNVERSIONED)->GetSafeHwnd())
2135 m_ListCtrl.Check(GITSLC_SHOWUNVERSIONED, check);
2136 else if (hwnd == GetDlgItem(IDC_CHECKVERSIONED)->GetSafeHwnd())
2137 m_ListCtrl.Check(GITSLC_SHOWVERSIONED, check);
2138 else if (hwnd == GetDlgItem(IDC_CHECKADDED)->GetSafeHwnd())
2139 m_ListCtrl.Check(GITSLC_SHOWADDED, check);
2140 else if (hwnd == GetDlgItem(IDC_CHECKDELETED)->GetSafeHwnd())
2141 m_ListCtrl.Check(GITSLC_SHOWREMOVED, check);
2142 else if (hwnd == GetDlgItem(IDC_CHECKMODIFIED)->GetSafeHwnd())
2143 m_ListCtrl.Check(GITSLC_SHOWMODIFIED, check);
2144 else if (hwnd == GetDlgItem(IDC_CHECKFILES)->GetSafeHwnd())
2145 m_ListCtrl.Check(GITSLC_SHOWFILES, check);
2146 else if (hwnd == GetDlgItem(IDC_CHECKSUBMODULES)->GetSafeHwnd())
2147 m_ListCtrl.Check(GITSLC_SHOWSUBMODULES, check);
2149 return 0;
2152 LRESULT CCommitDlg::OnUpdateOKButton(WPARAM, LPARAM)
2154 if (m_bBlock)
2155 return 0;
2157 bool bValidLogSize = m_cLogMessage.GetText().GetLength() >= m_ProjectProperties.nMinLogSize && m_cLogMessage.GetText().GetLength() > 0;
2158 bool bAmendOrSelectFilesOrMerge = m_ListCtrl.GetSelected() > 0 || (m_bCommitAmend && m_bAmendDiffToLastCommit) || CTGitPath(g_Git.m_CurrentDir).IsMergeActive();
2160 DialogEnableWindow(IDOK, bValidLogSize && (m_bCommitMessageOnly || bAmendOrSelectFilesOrMerge));
2162 return 0;
2165 LRESULT CCommitDlg::OnUpdateDataFalse(WPARAM, LPARAM)
2167 UpdateData(FALSE);
2168 return 0;
2171 LRESULT CCommitDlg::DefWindowProc(UINT message, WPARAM wParam, LPARAM lParam)
2173 switch (message) {
2174 case WM_NOTIFY:
2175 if (wParam == IDC_SPLITTER)
2177 SPC_NMHDR* pHdr = (SPC_NMHDR*) lParam;
2178 DoSize(pHdr->delta);
2180 break;
2183 return __super::DefWindowProc(message, wParam, lParam);
2186 void CCommitDlg::SetSplitterRange()
2188 if ((m_ListCtrl)&&(m_cLogMessage))
2190 CRect rcTop;
2191 m_cLogMessage.GetWindowRect(rcTop);
2192 ScreenToClient(rcTop);
2193 CRect rcMiddle;
2194 m_ListCtrl.GetWindowRect(rcMiddle);
2195 ScreenToClient(rcMiddle);
2196 if (rcMiddle.Height() && rcMiddle.Width())
2197 m_wndSplitter.SetRange(rcTop.top + 100, rcMiddle.bottom - 80);
2201 void CCommitDlg::DoSize(int delta)
2203 RemoveAnchor(IDC_MESSAGEGROUP);
2204 RemoveAnchor(IDC_LOGMESSAGE);
2205 RemoveAnchor(IDC_SPLITTER);
2206 RemoveAnchor(IDC_SIGNOFF);
2207 RemoveAnchor(IDC_COMMIT_AMEND);
2208 RemoveAnchor(IDC_COMMIT_AMENDDIFF);
2209 RemoveAnchor(IDC_COMMIT_SETDATETIME);
2210 RemoveAnchor(IDC_COMMIT_DATEPICKER);
2211 RemoveAnchor(IDC_COMMIT_TIMEPICKER);
2212 RemoveAnchor(IDC_COMMIT_SETAUTHOR);
2213 RemoveAnchor(IDC_COMMIT_AUTHORDATA);
2214 RemoveAnchor(IDC_LISTGROUP);
2215 RemoveAnchor(IDC_FILELIST);
2216 RemoveAnchor(IDC_TEXT_INFO);
2217 RemoveAnchor(IDC_SELECTLABEL);
2218 RemoveAnchor(IDC_CHECKALL);
2219 RemoveAnchor(IDC_CHECKNONE);
2220 RemoveAnchor(IDC_CHECKUNVERSIONED);
2221 RemoveAnchor(IDC_CHECKVERSIONED);
2222 RemoveAnchor(IDC_CHECKADDED);
2223 RemoveAnchor(IDC_CHECKDELETED);
2224 RemoveAnchor(IDC_CHECKMODIFIED);
2225 RemoveAnchor(IDC_CHECKFILES);
2226 RemoveAnchor(IDC_CHECKSUBMODULES);
2228 CSplitterControl::ChangeHeight(&m_cLogMessage, delta, CW_TOPALIGN);
2229 CSplitterControl::ChangeHeight(GetDlgItem(IDC_MESSAGEGROUP), delta, CW_TOPALIGN);
2230 CSplitterControl::ChangeHeight(&m_ListCtrl, -delta, CW_BOTTOMALIGN);
2231 CSplitterControl::ChangeHeight(GetDlgItem(IDC_LISTGROUP), -delta, CW_BOTTOMALIGN);
2232 CSplitterControl::ChangePos(GetDlgItem(IDC_SIGNOFF),0,delta);
2233 CSplitterControl::ChangePos(GetDlgItem(IDC_COMMIT_AMEND),0,delta);
2234 CSplitterControl::ChangePos(GetDlgItem(IDC_COMMIT_AMENDDIFF),0,delta);
2235 CSplitterControl::ChangePos(GetDlgItem(IDC_COMMIT_SETDATETIME),0,delta);
2236 CSplitterControl::ChangePos(GetDlgItem(IDC_COMMIT_DATEPICKER),0,delta);
2237 CSplitterControl::ChangePos(GetDlgItem(IDC_COMMIT_TIMEPICKER),0,delta);
2238 CSplitterControl::ChangePos(GetDlgItem(IDC_COMMIT_SETAUTHOR), 0, delta);
2239 CSplitterControl::ChangePos(GetDlgItem(IDC_COMMIT_AUTHORDATA), 0, delta);
2240 CSplitterControl::ChangePos(GetDlgItem(IDC_TEXT_INFO),0,delta);
2241 CSplitterControl::ChangePos(GetDlgItem(IDC_SELECTLABEL), 0, delta);
2242 CSplitterControl::ChangePos(GetDlgItem(IDC_CHECKALL), 0, delta);
2243 CSplitterControl::ChangePos(GetDlgItem(IDC_CHECKNONE), 0, delta);
2244 CSplitterControl::ChangePos(GetDlgItem(IDC_CHECKUNVERSIONED), 0, delta);
2245 CSplitterControl::ChangePos(GetDlgItem(IDC_CHECKVERSIONED), 0, delta);
2246 CSplitterControl::ChangePos(GetDlgItem(IDC_CHECKADDED), 0, delta);
2247 CSplitterControl::ChangePos(GetDlgItem(IDC_CHECKDELETED), 0, delta);
2248 CSplitterControl::ChangePos(GetDlgItem(IDC_CHECKMODIFIED), 0, delta);
2249 CSplitterControl::ChangePos(GetDlgItem(IDC_CHECKFILES), 0, delta);
2250 CSplitterControl::ChangePos(GetDlgItem(IDC_CHECKSUBMODULES), 0, delta);
2252 AddAnchor(IDC_MESSAGEGROUP, TOP_LEFT, TOP_RIGHT);
2253 AddAnchor(IDC_LOGMESSAGE, TOP_LEFT, TOP_RIGHT);
2254 AddAnchor(IDC_SPLITTER, TOP_LEFT, TOP_RIGHT);
2255 AddAnchor(IDC_LISTGROUP, TOP_LEFT, BOTTOM_RIGHT);
2256 AddAnchor(IDC_FILELIST, TOP_LEFT, BOTTOM_RIGHT);
2257 AddAnchor(IDC_SIGNOFF,TOP_RIGHT);
2258 AddAnchor(IDC_COMMIT_AMEND,TOP_LEFT);
2259 AddAnchor(IDC_COMMIT_AMENDDIFF,TOP_LEFT);
2260 AddAnchor(IDC_COMMIT_SETDATETIME,TOP_LEFT);
2261 AddAnchor(IDC_COMMIT_DATEPICKER,TOP_LEFT);
2262 AddAnchor(IDC_COMMIT_TIMEPICKER,TOP_LEFT);
2263 AddAnchor(IDC_COMMIT_SETAUTHOR, TOP_LEFT);
2264 AddAnchor(IDC_COMMIT_AUTHORDATA, TOP_LEFT, TOP_RIGHT);
2265 AddAnchor(IDC_TEXT_INFO,TOP_RIGHT);
2266 AddAnchor(IDC_SELECTLABEL, TOP_LEFT);
2267 AddAnchor(IDC_CHECKALL, TOP_LEFT);
2268 AddAnchor(IDC_CHECKNONE, TOP_LEFT);
2269 AddAnchor(IDC_CHECKUNVERSIONED, TOP_LEFT);
2270 AddAnchor(IDC_CHECKVERSIONED, TOP_LEFT);
2271 AddAnchor(IDC_CHECKADDED, TOP_LEFT);
2272 AddAnchor(IDC_CHECKDELETED, TOP_LEFT);
2273 AddAnchor(IDC_CHECKMODIFIED, TOP_LEFT);
2274 AddAnchor(IDC_CHECKFILES, TOP_LEFT);
2275 AddAnchor(IDC_CHECKSUBMODULES, TOP_LEFT);
2276 ArrangeLayout();
2277 // adjust the minimum size of the dialog to prevent the resizing from
2278 // moving the list control too far down.
2279 CRect rcLogMsg;
2280 m_cLogMessage.GetClientRect(rcLogMsg);
2281 SetMinTrackSize(CSize(m_DlgOrigRect.Width(), m_DlgOrigRect.Height()-m_LogMsgOrigRect.Height()+rcLogMsg.Height()));
2283 SetSplitterRange();
2284 m_cLogMessage.Invalidate();
2285 GetDlgItem(IDC_LOGMESSAGE)->Invalidate();
2288 void CCommitDlg::OnSize(UINT nType, int cx, int cy)
2290 // first, let the resizing take place
2291 __super::OnSize(nType, cx, cy);
2293 //set range
2294 SetSplitterRange();
2297 CString CCommitDlg::GetSignedOffByLine()
2299 CString str;
2301 CString username = g_Git.GetUserName();
2302 CString email = g_Git.GetUserEmail();
2303 username.Remove(_T('\n'));
2304 email.Remove(_T('\n'));
2306 str.Format(_T("Signed-off-by: %s <%s>"), username, email);
2308 return str;
2311 void CCommitDlg::OnBnClickedSignOff()
2313 CString str = GetSignedOffByLine();
2315 if (m_cLogMessage.GetText().Find(str) == -1) {
2316 m_cLogMessage.SetText(m_cLogMessage.GetText().TrimRight());
2317 int lastNewline = m_cLogMessage.GetText().ReverseFind(_T('\n'));
2318 int foundByLine = -1;
2319 if (lastNewline > 0)
2320 foundByLine = m_cLogMessage.GetText().Find(_T("-by: "), lastNewline);
2322 if (foundByLine == -1 || foundByLine < lastNewline)
2323 str = _T("\r\n") + str;
2325 m_cLogMessage.SetText(m_cLogMessage.GetText()+_T("\r\n")+str+_T("\r\n"));
2329 void CCommitDlg::OnBnClickedCommitAmend()
2331 this->UpdateData();
2332 if(this->m_bCommitAmend && this->m_AmendStr.IsEmpty())
2334 GitRev rev;
2337 rev.GetCommit(CString(_T("HEAD")));
2339 catch (const char *msg)
2341 CMessageBox::Show(m_hWnd, _T("Could not get HEAD commit.\nlibgit reports:\n") + CString(msg), _T("TortoiseGit"), MB_ICONERROR);
2343 m_AmendStr=rev.GetSubject()+_T("\n")+rev.GetBody();
2346 if(this->m_bCommitAmend)
2348 this->m_NoAmendStr=this->m_cLogMessage.GetText();
2349 m_cLogMessage.SetText(m_AmendStr);
2350 GetDlgItem(IDC_COMMIT_AMENDDIFF)->ShowWindow(SW_SHOW);
2352 else
2354 this->m_AmendStr=this->m_cLogMessage.GetText();
2355 m_cLogMessage.SetText(m_NoAmendStr);
2356 GetDlgItem(IDC_COMMIT_AMENDDIFF)->ShowWindow(SW_HIDE);
2359 OnBnClickedCommitSetDateTime(); // to update the commit date and time
2360 OnBnClickedCommitSetauthor(); // to update the commit author
2362 GetDlgItem(IDC_LOGMESSAGE)->SetFocus();
2363 Refresh();
2366 void CCommitDlg::OnBnClickedCommitMessageOnly()
2368 this->UpdateData();
2369 this->m_ListCtrl.EnableWindow(m_bCommitMessageOnly ? FALSE : TRUE);
2370 SendMessage(WM_UPDATEOKBUTTON);
2373 void CCommitDlg::OnBnClickedWholeProject()
2375 m_tooltips.Pop(); // hide the tooltips
2376 UpdateData();
2377 m_ListCtrl.Clear();
2378 if (!m_bBlock)
2380 if (m_bWholeProject || m_bWholeProject2)
2381 m_ListCtrl.GetStatus(NULL,true,false,true);
2382 else
2383 m_ListCtrl.GetStatus(&this->m_pathList,true,false,true);
2385 m_regShowWholeProject = m_bWholeProject;
2387 DWORD dwShow = m_ListCtrl.GetShowFlags();
2388 if (DWORD(m_regAddBeforeCommit))
2389 dwShow |= GITSLC_SHOWUNVERSIONED;
2390 else
2391 dwShow &= ~GITSLC_SHOWUNVERSIONED;
2393 m_ListCtrl.Show(dwShow, dwShow & ~(CTGitPath::LOGACTIONS_UNVER), true);
2394 UpdateCheckLinks();
2397 SetDlgTitle();
2400 void CCommitDlg::OnFocusMessage()
2402 m_cLogMessage.SetFocus();
2405 void CCommitDlg::OnFocusFileList()
2407 m_ListCtrl.SetFocus();
2410 void CCommitDlg::OnScnUpdateUI(NMHDR * /*pNMHDR*/, LRESULT *pResult)
2412 int pos = (int)this->m_cLogMessage.Call(SCI_GETCURRENTPOS);
2413 int line = (int)this->m_cLogMessage.Call(SCI_LINEFROMPOSITION,pos);
2414 int column = (int)this->m_cLogMessage.Call(SCI_GETCOLUMN,pos);
2416 CString str;
2417 str.Format(_T("%d/%d"),line+1,column+1);
2418 this->GetDlgItem(IDC_TEXT_INFO)->SetWindowText(str);
2420 if(*pResult)
2421 *pResult=0;
2424 void CCommitDlg::TogglePatchView()
2426 OnStnClickedViewPatch();
2429 void CCommitDlg::OnStnClickedViewPatch()
2431 m_patchViewdlg.m_pProjectProperties = &this->m_ProjectProperties;
2432 m_patchViewdlg.m_ParentDlg = this;
2433 if(!IsWindow(this->m_patchViewdlg.m_hWnd))
2435 BOOL viewPatchEnabled = FALSE;
2436 viewPatchEnabled = g_Git.GetConfigValueBool(_T("tgit.commitshowpatch"));
2437 if (viewPatchEnabled == FALSE)
2438 g_Git.SetConfigValue(_T("tgit.commitshowpatch"), _T("true"));
2439 m_patchViewdlg.Create(IDD_PATCH_VIEW,this);
2440 m_patchViewdlg.m_ctrlPatchView.Call(SCI_SETSCROLLWIDTHTRACKING, TRUE);
2441 CRect rect;
2442 this->GetWindowRect(&rect);
2444 m_patchViewdlg.ShowWindow(SW_SHOW);
2446 m_patchViewdlg.SetWindowPos(NULL,rect.right,rect.top,rect.Width(),rect.Height(),
2447 SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
2449 ShowViewPatchText(false);
2450 FillPatchView();
2452 else
2454 g_Git.SetConfigValue(_T("tgit.commitshowpatch"), _T("false"));
2455 m_patchViewdlg.ShowWindow(SW_HIDE);
2456 m_patchViewdlg.DestroyWindow();
2457 ShowViewPatchText(true);
2459 this->m_ctrlShowPatch.Invalidate();
2462 void CCommitDlg::OnMoving(UINT fwSide, LPRECT pRect)
2464 __super::OnMoving(fwSide, pRect);
2466 if (::IsWindow(m_patchViewdlg.m_hWnd))
2468 RECT patchrect;
2469 m_patchViewdlg.GetWindowRect(&patchrect);
2470 if (::IsWindow(m_hWnd))
2472 RECT thisrect;
2473 GetWindowRect(&thisrect);
2474 if (patchrect.left == thisrect.right)
2476 m_patchViewdlg.SetWindowPos(NULL, patchrect.left - (thisrect.left - pRect->left), patchrect.top - (thisrect.top - pRect->top),
2477 0, 0, SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOSIZE | SWP_NOZORDER);
2484 void CCommitDlg::OnSizing(UINT fwSide, LPRECT pRect)
2486 __super::OnSizing(fwSide, pRect);
2488 if(::IsWindow(this->m_patchViewdlg.m_hWnd))
2490 CRect thisrect, patchrect;
2491 this->GetWindowRect(thisrect);
2492 this->m_patchViewdlg.GetWindowRect(patchrect);
2493 if(thisrect.right==patchrect.left)
2495 patchrect.left -= (thisrect.right - pRect->right);
2496 patchrect.right-= (thisrect.right - pRect->right);
2498 if( patchrect.bottom == thisrect.bottom)
2500 patchrect.bottom -= (thisrect.bottom - pRect->bottom);
2502 if( patchrect.top == thisrect.top)
2504 patchrect.top -= thisrect.top-pRect->top;
2506 m_patchViewdlg.MoveWindow(patchrect);
2511 void CCommitDlg::OnHdnItemchangedFilelist(NMHDR * /*pNMHDR*/, LRESULT *pResult)
2513 *pResult = 0;
2514 TRACE("Item Changed\r\n");
2517 int CCommitDlg::CheckHeadDetach()
2519 CString output;
2520 if (CGit::GetCurrentBranchFromFile(g_Git.m_CurrentDir, output))
2522 int retval = CMessageBox::Show(NULL, IDS_PROC_COMMIT_DETACHEDWARNING, IDS_APPNAME, MB_YESNOCANCEL | MB_ICONWARNING);
2523 if(retval == IDYES)
2525 if (CAppUtils::CreateBranchTag(FALSE, NULL, true) == FALSE)
2526 return 1;
2528 else if (retval == IDCANCEL)
2529 return 1;
2531 return 0;
2534 void CCommitDlg::OnBnClickedCommitAmenddiff()
2536 UpdateData();
2537 Refresh();
2540 void CCommitDlg::OnBnClickedNoautoselectsubmodules()
2542 UpdateData();
2543 Refresh();
2546 void CCommitDlg::OnBnClickedCommitSetDateTime()
2548 UpdateData();
2550 if (m_bSetCommitDateTime)
2552 CTime authordate = CTime::GetCurrentTime();
2553 if (m_bCommitAmend)
2555 GitRev headRevision;
2558 headRevision.GetCommit(_T("HEAD"));
2560 catch (const char *msg)
2562 CMessageBox::Show(m_hWnd, _T("Could not get HEAD commit.\nlibgit reports:\n") + CString(msg), _T("TortoiseGit"), MB_ICONERROR);
2564 authordate = headRevision.GetAuthorDate();
2567 m_CommitDate.SetTime(&authordate);
2568 m_CommitTime.SetTime(&authordate);
2570 GetDlgItem(IDC_COMMIT_DATEPICKER)->ShowWindow(SW_SHOW);
2571 GetDlgItem(IDC_COMMIT_TIMEPICKER)->ShowWindow(SW_SHOW);
2573 else
2575 GetDlgItem(IDC_COMMIT_DATEPICKER)->ShowWindow(SW_HIDE);
2576 GetDlgItem(IDC_COMMIT_TIMEPICKER)->ShowWindow(SW_HIDE);
2580 void CCommitDlg::OnBnClickedCheckNewBranch()
2582 UpdateData();
2583 if (m_bCreateNewBranch)
2585 GetDlgItem(IDC_COMMIT_TO)->ShowWindow(SW_HIDE);
2586 GetDlgItem(IDC_NEWBRANCH)->ShowWindow(SW_SHOW);
2588 else
2590 GetDlgItem(IDC_NEWBRANCH)->ShowWindow(SW_HIDE);
2591 GetDlgItem(IDC_COMMIT_TO)->ShowWindow(SW_SHOW);
2595 void CCommitDlg::RestoreFiles(bool doNotAsk)
2597 if (!m_ListCtrl.m_restorepaths.empty() && (doNotAsk || CMessageBox::Show(m_hWnd, IDS_PROC_COMMIT_RESTOREFILES, IDS_APPNAME, 2, IDI_QUESTION, IDS_PROC_COMMIT_RESTOREFILES_RESTORE, IDS_PROC_COMMIT_RESTOREFILES_KEEP) == 1))
2599 for (std::map<CString, CString>::iterator it = m_ListCtrl.m_restorepaths.begin(); it != m_ListCtrl.m_restorepaths.end(); ++it)
2600 CopyFile(it->second, g_Git.CombinePath(it->first), FALSE);
2601 m_ListCtrl.m_restorepaths.clear();
2605 void CCommitDlg::UpdateCheckLinks()
2607 DialogEnableWindow(IDC_CHECKALL, true);
2608 DialogEnableWindow(IDC_CHECKNONE, true);
2609 DialogEnableWindow(IDC_CHECKUNVERSIONED, m_ListCtrl.GetUnversionedCount() > 0);
2610 DialogEnableWindow(IDC_CHECKVERSIONED, m_ListCtrl.GetItemCount() > m_ListCtrl.GetUnversionedCount());
2611 DialogEnableWindow(IDC_CHECKADDED, m_ListCtrl.GetAddedCount() > 0);
2612 DialogEnableWindow(IDC_CHECKDELETED, m_ListCtrl.GetDeletedCount() > 0);
2613 DialogEnableWindow(IDC_CHECKMODIFIED, m_ListCtrl.GetModifiedCount() > 0);
2614 DialogEnableWindow(IDC_CHECKFILES, m_ListCtrl.GetFileCount() > 0);
2615 DialogEnableWindow(IDC_CHECKSUBMODULES, m_ListCtrl.GetSubmoduleCount() > 0);
2618 void CCommitDlg::OnBnClickedCommitSetauthor()
2620 UpdateData();
2622 if (m_bSetAuthor)
2624 m_sAuthor.Format(_T("%s <%s>"), g_Git.GetUserName(), g_Git.GetUserEmail());
2625 if (m_bCommitAmend)
2627 GitRev headRevision;
2630 headRevision.GetCommit(_T("HEAD"));
2632 catch (const char *msg)
2634 CMessageBox::Show(m_hWnd, _T("Could not get HEAD commit.\nlibgit reports:\n") + CString(msg), _T("TortoiseGit"), MB_ICONERROR);
2636 m_sAuthor.Format(_T("%s <%s>"), headRevision.GetAuthorName(), headRevision.GetAuthorEmail());
2639 UpdateData(FALSE);
2641 GetDlgItem(IDC_COMMIT_AUTHORDATA)->ShowWindow(SW_SHOW);
2643 else
2644 GetDlgItem(IDC_COMMIT_AUTHORDATA)->ShowWindow(SW_HIDE);
2647 void CCommitDlg::RunStartCommitHook()
2649 DWORD exitcode = 0xFFFFFFFF;
2650 CString error;
2651 if (CHooks::Instance().StartCommit(g_Git.m_CurrentDir, m_pathList, m_sLogMessage, exitcode, error))
2653 if (exitcode)
2655 CString temp;
2656 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2657 MessageBox(temp, _T("TortoiseGit"), MB_ICONERROR);
2658 return;