CommitDlg: Disable amend buttons while refreshing
[TortoiseGit.git] / src / TortoiseProc / CommitDlg.cpp
blobde708bd4012550ee0abfd6ac7f96863b65f18198
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2003-2008 - TortoiseSVN
4 // Copyright (C) 2008-2012 - 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 "GitConfig.h"
25 #include "ProjectProperties.h"
26 #include "MessageBox.h"
27 #include "AppUtils.h"
28 #include "PathUtils.h"
29 #include "Git.h"
30 #include "Registry.h"
31 #include "GitStatus.h"
32 #include "HistoryDlg.h"
33 #include "Hooks.h"
34 #include "UnicodeUtils.h"
35 #include "../TGitCache/CacheInterface.h"
36 #include "ProgressDlg.h"
37 #include "ShellUpdater.h"
38 #include "Commands/PushCommand.h"
39 #include "PatchViewDlg.h"
40 #include "COMError.h"
41 #include "Globals.h"
42 #include "SysProgressDlg.h"
43 #include "MassiveGitTask.h"
45 #ifdef _DEBUG
46 #define new DEBUG_NEW
47 #undef THIS_FILE
48 static char THIS_FILE[] = __FILE__;
49 #endif
51 UINT CCommitDlg::WM_AUTOLISTREADY = RegisterWindowMessage(_T("TORTOISEGIT_AUTOLISTREADY_MSG"));
53 IMPLEMENT_DYNAMIC(CCommitDlg, CResizableStandAloneDialog)
54 CCommitDlg::CCommitDlg(CWnd* pParent /*=NULL*/)
55 : CResizableStandAloneDialog(CCommitDlg::IDD, pParent)
56 , m_bRecursive(FALSE)
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_bKeepChangeList(TRUE)
64 , m_bDoNotAutoselectSubmodules(FALSE)
65 , m_itemsCount(0)
66 , m_bSelectFilesForCommit(TRUE)
67 , m_bNoPostActions(FALSE)
68 , m_bAutoClose(false)
69 , m_bSetCommitDateTime(FALSE)
70 , m_bCreateNewBranch(FALSE)
71 , m_bCreateTagAfterCommit(FALSE)
72 , m_bForceCommitAmend(false)
74 this->m_bCommitAmend=FALSE;
75 m_bPushAfterCommit = FALSE;
78 CCommitDlg::~CCommitDlg()
80 if(m_pThread != NULL)
82 delete m_pThread;
86 void CCommitDlg::DoDataExchange(CDataExchange* pDX)
88 CResizableStandAloneDialog::DoDataExchange(pDX);
89 DDX_Control(pDX, IDC_FILELIST, m_ListCtrl);
90 DDX_Control(pDX, IDC_LOGMESSAGE, m_cLogMessage);
91 DDX_Check(pDX, IDC_SHOWUNVERSIONED, m_bShowUnversioned);
92 DDX_Check(pDX, IDC_COMMIT_SETDATETIME, m_bSetCommitDateTime);
93 DDX_Check(pDX, IDC_CHECK_NEWBRANCH, m_bCreateNewBranch);
94 DDX_Text(pDX, IDC_NEWBRANCH, m_sCreateNewBranch);
95 DDX_Control(pDX, IDC_SELECTALL, m_SelectAll);
96 DDX_Text(pDX, IDC_BUGID, m_sBugID);
97 DDX_Check(pDX, IDC_WHOLE_PROJECT, m_bWholeProject);
98 DDX_Control(pDX, IDC_SPLITTER, m_wndSplitter);
99 DDX_Check(pDX, IDC_KEEPLISTS, m_bKeepChangeList);
100 DDX_Check(pDX, IDC_NOAUTOSELECTSUBMODULES, m_bDoNotAutoselectSubmodules);
101 DDX_Check(pDX,IDC_COMMIT_AMEND,m_bCommitAmend);
102 DDX_Check(pDX,IDC_COMMIT_AMENDDIFF,m_bAmendDiffToLastCommit);
103 DDX_Control(pDX,IDC_VIEW_PATCH,m_ctrlShowPatch);
104 DDX_Control(pDX, IDC_COMMIT_DATEPICKER, m_CommitDate);
105 DDX_Control(pDX, IDC_COMMIT_TIMEPICKER, m_CommitTime);
108 BEGIN_MESSAGE_MAP(CCommitDlg, CResizableStandAloneDialog)
109 ON_BN_CLICKED(IDC_SELECTALL, OnBnClickedSelectall)
110 ON_BN_CLICKED(IDHELP, OnBnClickedHelp)
111 ON_BN_CLICKED(IDC_SHOWUNVERSIONED, OnBnClickedShowunversioned)
112 ON_NOTIFY(SCN_UPDATEUI, IDC_LOGMESSAGE, OnScnUpdateUI)
113 // ON_BN_CLICKED(IDC_HISTORY, OnBnClickedHistory)
114 ON_BN_CLICKED(IDC_BUGTRAQBUTTON, OnBnClickedBugtraqbutton)
115 ON_EN_CHANGE(IDC_LOGMESSAGE, OnEnChangeLogmessage)
116 ON_REGISTERED_MESSAGE(CGitStatusListCtrl::GITSLNM_ITEMCOUNTCHANGED, OnGitStatusListCtrlItemCountChanged)
117 ON_REGISTERED_MESSAGE(CGitStatusListCtrl::GITSLNM_NEEDSREFRESH, OnGitStatusListCtrlNeedsRefresh)
118 ON_REGISTERED_MESSAGE(CGitStatusListCtrl::GITSLNM_ADDFILE, OnFileDropped)
119 ON_REGISTERED_MESSAGE(CGitStatusListCtrl::GITSLNM_CHECKCHANGED, &CCommitDlg::OnGitStatusListCtrlCheckChanged)
120 ON_REGISTERED_MESSAGE(CGitStatusListCtrl::GITSLNM_ITEMCHANGED, &CCommitDlg::OnGitStatusListCtrlItemChanged)
122 ON_REGISTERED_MESSAGE(WM_AUTOLISTREADY, OnAutoListReady)
123 ON_WM_TIMER()
124 ON_WM_SIZE()
125 ON_STN_CLICKED(IDC_EXTERNALWARNING, &CCommitDlg::OnStnClickedExternalwarning)
126 ON_BN_CLICKED(IDC_SIGNOFF, &CCommitDlg::OnBnClickedSignOff)
127 ON_BN_CLICKED(IDC_COMMIT_AMEND, &CCommitDlg::OnBnClickedCommitAmend)
128 ON_BN_CLICKED(IDC_WHOLE_PROJECT, &CCommitDlg::OnBnClickedWholeProject)
129 ON_COMMAND(ID_FOCUS_MESSAGE,&CCommitDlg::OnFocusMessage)
130 ON_STN_CLICKED(IDC_VIEW_PATCH, &CCommitDlg::OnStnClickedViewPatch)
131 ON_WM_MOVE()
132 ON_WM_MOVING()
133 ON_WM_SIZING()
134 ON_NOTIFY(HDN_ITEMCHANGED, 0, &CCommitDlg::OnHdnItemchangedFilelist)
135 ON_BN_CLICKED(IDC_COMMIT_AMENDDIFF, &CCommitDlg::OnBnClickedCommitAmenddiff)
136 ON_BN_CLICKED(IDC_NOAUTOSELECTSUBMODULES, &CCommitDlg::OnBnClickedNoautoselectsubmodules)
137 ON_BN_CLICKED(IDC_COMMIT_SETDATETIME, &CCommitDlg::OnBnClickedCommitSetDateTime)
138 ON_BN_CLICKED(IDC_CHECK_NEWBRANCH, &CCommitDlg::OnBnClickedCheckNewBranch)
139 END_MESSAGE_MAP()
141 BOOL CCommitDlg::OnInitDialog()
143 CResizableStandAloneDialog::OnInitDialog();
144 CAppUtils::MarkWindowAsUnpinnable(m_hWnd);
146 CAppUtils::GetCommitTemplate(this->m_sLogMessage);
148 CString dotGitPath;
149 g_GitAdminDir.GetAdminDirPath(g_Git.m_CurrentDir, dotGitPath);
150 if(PathFileExists(dotGitPath + _T("MERGE_MSG")))
152 CStdioFile file;
153 if(file.Open(dotGitPath + _T("MERGE_MSG"), CFile::modeRead))
155 CString str;
156 while(file.ReadString(str))
158 m_sLogMessage += str;
159 str.Empty();
160 m_sLogMessage += _T("\n");
165 if (CTGitPath(g_Git.m_CurrentDir).IsMergeActive())
166 DialogEnableWindow(IDC_CHECK_NEWBRANCH, FALSE);
168 m_regAddBeforeCommit = CRegDWORD(_T("Software\\TortoiseGit\\AddBeforeCommit"), TRUE);
169 m_bShowUnversioned = m_regAddBeforeCommit;
171 m_History.SetMaxHistoryItems((LONG)CRegDWORD(_T("Software\\TortoiseGit\\MaxHistoryItems"), 25));
173 m_regKeepChangelists = CRegDWORD(_T("Software\\TortoiseGit\\KeepChangeLists"), FALSE);
174 m_bKeepChangeList = m_regKeepChangelists;
176 m_regDoNotAutoselectSubmodules = CRegDWORD(_T("Software\\TortoiseGit\\DoNotAutoselectSubmodules"), FALSE);
177 m_bDoNotAutoselectSubmodules = m_regDoNotAutoselectSubmodules;
179 m_hAccel = LoadAccelerators(AfxGetResourceHandle(),MAKEINTRESOURCE(IDR_ACC_COMMITDLG));
181 // GitConfig config;
182 // m_bWholeProject = config.KeepLocks();
184 if(this->m_pathList.GetCount() == 0)
185 m_bWholeProject =true;
187 if(this->m_pathList.GetCount() == 1 && m_pathList[0].IsEmpty())
188 m_bWholeProject =true;
190 SetDlgTitle();
192 UpdateData(FALSE);
194 m_ListCtrl.Init(GITSLC_COLEXT | GITSLC_COLSTATUS | GITSLC_COLADD |GITSLC_COLDEL, _T("CommitDlg"),(GITSLC_POPALL ^ (GITSLC_POPCOMMIT | GITSLC_POPSAVEAS)));
195 m_ListCtrl.SetSelectButton(&m_SelectAll);
196 m_ListCtrl.SetStatLabel(GetDlgItem(IDC_STATISTICS));
197 m_ListCtrl.SetCancelBool(&m_bCancelled);
198 m_ListCtrl.SetEmptyString(IDS_COMMITDLG_NOTHINGTOCOMMIT);
199 m_ListCtrl.EnableFileDrop();
200 m_ListCtrl.SetBackgroundImage(IDI_COMMIT_BKG);
202 //this->DialogEnableWindow(IDC_COMMIT_AMEND,FALSE);
203 m_ProjectProperties.ReadPropsPathList(m_pathList);
205 m_cLogMessage.Init(m_ProjectProperties);
206 m_cLogMessage.SetFont((CString)CRegString(_T("Software\\TortoiseGit\\LogFontName"), _T("Courier New")), (DWORD)CRegDWORD(_T("Software\\TortoiseGit\\LogFontSize"), 8));
207 m_cLogMessage.RegisterContextMenuHandler(this);
209 OnEnChangeLogmessage();
211 m_tooltips.Create(this);
212 m_tooltips.AddTool(IDC_EXTERNALWARNING, IDS_COMMITDLG_EXTERNALS);
213 m_tooltips.AddTool(IDC_COMMIT_AMEND,IDS_COMMIT_AMEND_TT);
214 // m_tooltips.AddTool(IDC_HISTORY, IDS_COMMITDLG_HISTORY_TT);
216 m_SelectAll.SetCheck(BST_INDETERMINATE);
218 CBugTraqAssociations bugtraq_associations;
219 bugtraq_associations.Load();
221 if (bugtraq_associations.FindProvider(g_Git.m_CurrentDir, &m_bugtraq_association))
223 GetDlgItem(IDC_BUGID)->ShowWindow(SW_HIDE);
224 GetDlgItem(IDC_BUGIDLABEL)->ShowWindow(SW_HIDE);
226 CComPtr<IBugTraqProvider> pProvider;
227 HRESULT hr = pProvider.CoCreateInstance(m_bugtraq_association.GetProviderClass());
228 if (SUCCEEDED(hr))
230 m_BugTraqProvider = pProvider;
231 BSTR temp = NULL;
232 if (SUCCEEDED(hr = pProvider->GetLinkText(GetSafeHwnd(), m_bugtraq_association.GetParameters().AllocSysString(), &temp)))
234 SetDlgItemText(IDC_BUGTRAQBUTTON, temp);
235 GetDlgItem(IDC_BUGTRAQBUTTON)->EnableWindow(TRUE);
236 GetDlgItem(IDC_BUGTRAQBUTTON)->ShowWindow(SW_SHOW);
239 SysFreeString(temp);
242 GetDlgItem(IDC_LOGMESSAGE)->SetFocus();
244 else if (!m_ProjectProperties.sMessage.IsEmpty())
246 GetDlgItem(IDC_BUGID)->ShowWindow(SW_SHOW);
247 GetDlgItem(IDC_BUGIDLABEL)->ShowWindow(SW_SHOW);
248 if (!m_ProjectProperties.sLabel.IsEmpty())
249 SetDlgItemText(IDC_BUGIDLABEL, m_ProjectProperties.sLabel);
250 GetDlgItem(IDC_BUGTRAQBUTTON)->ShowWindow(SW_HIDE);
251 GetDlgItem(IDC_BUGTRAQBUTTON)->EnableWindow(FALSE);
252 GetDlgItem(IDC_BUGID)->SetFocus();
253 CString sBugID = m_ProjectProperties.GetBugIDFromLog(m_sLogMessage);
254 if (!sBugID.IsEmpty())
256 SetDlgItemText(IDC_BUGID, sBugID);
259 else
261 GetDlgItem(IDC_BUGID)->ShowWindow(SW_HIDE);
262 GetDlgItem(IDC_BUGIDLABEL)->ShowWindow(SW_HIDE);
263 GetDlgItem(IDC_BUGTRAQBUTTON)->ShowWindow(SW_HIDE);
264 GetDlgItem(IDC_BUGTRAQBUTTON)->EnableWindow(FALSE);
265 GetDlgItem(IDC_LOGMESSAGE)->SetFocus();
268 if (!m_sLogMessage.IsEmpty())
269 m_cLogMessage.SetText(m_sLogMessage);
271 GetWindowText(m_sWindowTitle);
273 AdjustControlSize(IDC_SHOWUNVERSIONED);
274 AdjustControlSize(IDC_SELECTALL);
275 AdjustControlSize(IDC_WHOLE_PROJECT);
276 AdjustControlSize(IDC_CHECK_NEWBRANCH);
277 AdjustControlSize(IDC_COMMIT_AMEND);
278 AdjustControlSize(IDC_COMMIT_AMENDDIFF);
279 AdjustControlSize(IDC_COMMIT_SETDATETIME);
280 AdjustControlSize(IDC_NOAUTOSELECTSUBMODULES);
281 AdjustControlSize(IDC_KEEPLISTS);
283 GetClientRect(m_DlgOrigRect);
284 m_cLogMessage.GetClientRect(m_LogMsgOrigRect);
286 AddAnchor(IDC_COMMITLABEL, TOP_LEFT, TOP_RIGHT);
287 AddAnchor(IDC_BUGIDLABEL, TOP_RIGHT);
288 AddAnchor(IDC_BUGID, TOP_RIGHT);
289 AddAnchor(IDC_BUGTRAQBUTTON, TOP_RIGHT);
290 AddAnchor(IDC_COMMIT_TO, TOP_LEFT, TOP_RIGHT);
291 AddAnchor(IDC_CHECK_NEWBRANCH, TOP_RIGHT);
292 AddAnchor(IDC_NEWBRANCH, TOP_LEFT, TOP_RIGHT);
293 AddAnchor(IDC_MESSAGEGROUP, TOP_LEFT, TOP_RIGHT);
294 // AddAnchor(IDC_HISTORY, TOP_LEFT);
295 AddAnchor(IDC_LOGMESSAGE, TOP_LEFT, TOP_RIGHT);
296 AddAnchor(IDC_SIGNOFF, TOP_RIGHT);
297 AddAnchor(IDC_VIEW_PATCH, BOTTOM_RIGHT);
298 AddAnchor(IDC_LISTGROUP, TOP_LEFT, BOTTOM_RIGHT);
299 AddAnchor(IDC_SPLITTER, TOP_LEFT, TOP_RIGHT);
300 AddAnchor(IDC_FILELIST, TOP_LEFT, BOTTOM_RIGHT);
301 AddAnchor(IDC_SHOWUNVERSIONED, BOTTOM_LEFT);
302 AddAnchor(IDC_SELECTALL, BOTTOM_LEFT);
303 AddAnchor(IDC_EXTERNALWARNING, BOTTOM_RIGHT);
304 AddAnchor(IDC_STATISTICS, BOTTOM_LEFT, BOTTOM_RIGHT);
305 AddAnchor(IDC_TEXT_INFO, TOP_RIGHT);
306 AddAnchor(IDC_WHOLE_PROJECT, BOTTOM_LEFT);
307 AddAnchor(IDC_KEEPLISTS, BOTTOM_LEFT);
308 AddAnchor(IDC_NOAUTOSELECTSUBMODULES, BOTTOM_LEFT);
309 AddAnchor(IDOK, BOTTOM_RIGHT);
310 AddAnchor(IDCANCEL, BOTTOM_RIGHT);
311 AddAnchor(IDHELP, BOTTOM_RIGHT);
312 AddAnchor(IDC_COMMIT_AMEND,TOP_LEFT);
313 AddAnchor(IDC_COMMIT_AMENDDIFF,TOP_LEFT);
314 AddAnchor(IDC_COMMIT_SETDATETIME,TOP_LEFT);
315 AddAnchor(IDC_COMMIT_DATEPICKER,TOP_LEFT);
316 AddAnchor(IDC_COMMIT_TIMEPICKER,TOP_LEFT);
318 if (hWndExplorer)
319 CenterWindow(CWnd::FromHandle(hWndExplorer));
320 EnableSaveRestore(_T("CommitDlg"));
321 DWORD yPos = CRegDWORD(_T("Software\\TortoiseGit\\TortoiseProc\\ResizableState\\CommitDlgSizer"));
322 RECT rcDlg, rcLogMsg, rcFileList;
323 GetClientRect(&rcDlg);
324 m_cLogMessage.GetWindowRect(&rcLogMsg);
325 ScreenToClient(&rcLogMsg);
326 m_ListCtrl.GetWindowRect(&rcFileList);
327 ScreenToClient(&rcFileList);
328 if (yPos)
330 RECT rectSplitter;
331 m_wndSplitter.GetWindowRect(&rectSplitter);
332 ScreenToClient(&rectSplitter);
333 int delta = yPos - rectSplitter.top;
334 if ((rcLogMsg.bottom + delta > rcLogMsg.top)&&(rcLogMsg.bottom + delta < rcFileList.bottom - 30))
336 m_wndSplitter.SetWindowPos(NULL, 0, yPos, 0, 0, SWP_NOSIZE);
337 DoSize(delta);
341 // add all directories to the watcher
343 for (int i=0; i<m_pathList.GetCount(); ++i)
345 if (m_pathList[i].IsDirectory())
346 m_pathwatcher.AddPath(m_pathList[i]);
349 m_updatedPathList = m_pathList;
351 //first start a thread to obtain the file list with the status without
352 //blocking the dialog
353 InterlockedExchange(&m_bBlock, TRUE);
354 m_pThread = AfxBeginThread(StatusThreadEntry, this, THREAD_PRIORITY_NORMAL,0,CREATE_SUSPENDED);
355 if (m_pThread==NULL)
357 CMessageBox::Show(this->m_hWnd, IDS_ERR_THREADSTARTFAILED, IDS_APPNAME, MB_OK | MB_ICONERROR);
358 InterlockedExchange(&m_bBlock, FALSE);
360 else
362 m_pThread->m_bAutoDelete = FALSE;
363 m_pThread->ResumeThread();
365 CRegDWORD err = CRegDWORD(_T("Software\\TortoiseGit\\ErrorOccurred"), FALSE);
366 CRegDWORD historyhint = CRegDWORD(_T("Software\\TortoiseGit\\HistoryHintShown"), FALSE);
367 if ((((DWORD)err)!=FALSE)&&((((DWORD)historyhint)==FALSE)))
369 historyhint = TRUE;
370 // ShowBalloon(IDC_HISTORY, IDS_COMMITDLG_HISTORYHINT_TT, IDI_INFORMATION);
372 err = FALSE;
374 this->m_ctrlShowPatch.SetURL(CString());
376 BOOL viewPatchEnabled = FALSE;
377 m_ProjectProperties.GetBOOLProps(viewPatchEnabled, _T("tgit.commitshowpatch"));
378 if (viewPatchEnabled)
379 OnStnClickedViewPatch();
381 return FALSE; // return TRUE unless you set the focus to a control
382 // EXCEPTION: OCX Property Pages should return FALSE
385 void CCommitDlg::OnOK()
387 if (m_bBlock)
388 return;
389 if (m_bThreadRunning)
391 m_bCancelled = true;
392 InterlockedExchange(&m_bRunThread, FALSE);
393 WaitForSingleObject(m_pThread->m_hThread, 1000);
394 if (m_bThreadRunning)
396 // we gave the thread a chance to quit. Since the thread didn't
397 // listen to us we have to kill it.
398 TerminateThread(m_pThread->m_hThread, (DWORD)-1);
399 InterlockedExchange(&m_bThreadRunning, FALSE);
402 this->UpdateData();
404 if (m_bCreateNewBranch && !g_Git.IsBranchNameValid(m_sCreateNewBranch))
406 ShowEditBalloon(IDC_NEWBRANCH, IDS_B_T_NOTEMPTY, TTI_ERROR);
407 return;
410 CString id;
411 GetDlgItemText(IDC_BUGID, id);
412 if (!m_ProjectProperties.CheckBugID(id))
414 ShowEditBalloon(IDC_BUGID, IDS_COMMITDLG_ONLYNUMBERS, TTI_ERROR);
415 return;
417 m_sLogMessage = m_cLogMessage.GetText();
418 if ( m_sLogMessage.IsEmpty() )
420 // no message entered, go round again
421 CMessageBox::Show(this->m_hWnd, IDS_COMMITDLG_NOMESSAGE, IDS_APPNAME, MB_OK | MB_ICONERROR);
422 return;
424 if ((m_ProjectProperties.bWarnIfNoIssue) && (id.IsEmpty() && !m_ProjectProperties.HasBugID(m_sLogMessage)))
426 if (CMessageBox::Show(this->m_hWnd, IDS_COMMITDLG_NOISSUEWARNING, IDS_APPNAME, MB_YESNO | MB_ICONWARNING)!=IDYES)
427 return;
430 BOOL bWarnNoSignedOffBy = FALSE;
431 ProjectProperties::GetBOOLProps(bWarnNoSignedOffBy, _T("tgit.warnnosignedoffby"));
432 if (bWarnNoSignedOffBy == TRUE && m_cLogMessage.GetText().Find(GetSignedOffByLine()) == -1)
434 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);
435 if (retval == 1)
437 OnBnClickedSignOff();
438 m_sLogMessage = m_cLogMessage.GetText();
440 else if (retval == 3)
441 return;
444 m_ListCtrl.WriteCheckedNamesToPathList(m_selectedPathList);
445 m_pathwatcher.Stop();
446 InterlockedExchange(&m_bBlock, TRUE);
447 CDWordArray arDeleted;
448 //first add all the unversioned files the user selected
449 //and check if all versioned files are selected
450 int nchecked = 0;
451 m_bRecursive = true;
452 int nListItems = m_ListCtrl.GetItemCount();
454 CTGitPathList itemsToAdd;
455 CTGitPathList itemsToRemove;
456 CMassiveGitTask mgtReAddAfterCommit(_T("add --ignore-errors -f"));
457 //std::set<CString> checkedLists;
458 //std::set<CString> uncheckedLists;
460 // now let the bugtraq plugin check the commit message
461 CComPtr<IBugTraqProvider2> pProvider2 = NULL;
462 if (m_BugTraqProvider)
464 HRESULT hr = m_BugTraqProvider.QueryInterface(&pProvider2);
465 if (SUCCEEDED(hr))
467 BSTR temp = NULL;
468 CString common = g_Git.m_CurrentDir;
469 BSTR repositoryRoot = common.AllocSysString();
470 BSTR parameters = m_bugtraq_association.GetParameters().AllocSysString();
471 BSTR commonRoot = SysAllocString(m_pathList.GetCommonRoot().GetDirectory().GetWinPath());
472 BSTR commitMessage = m_sLogMessage.AllocSysString();
473 SAFEARRAY *pathList = SafeArrayCreateVector(VT_BSTR, 0, m_selectedPathList.GetCount());
475 for (LONG index = 0; index < m_selectedPathList.GetCount(); ++index)
476 SafeArrayPutElement(pathList, &index, m_selectedPathList[index].GetGitPathString().AllocSysString());
478 if (FAILED(hr = pProvider2->CheckCommit(GetSafeHwnd(), parameters, repositoryRoot, commonRoot, pathList, commitMessage, &temp)))
480 COMError ce(hr);
481 CString sErr;
482 sErr.Format(IDS_ERR_FAILEDISSUETRACKERCOM, m_bugtraq_association.GetProviderName(), ce.GetMessageAndDescription().c_str());
483 CMessageBox::Show(m_hWnd, sErr, _T("TortoiseGit"), MB_ICONERROR);
485 else
487 CString sError = temp;
488 if (!sError.IsEmpty())
490 CMessageBox::Show(m_hWnd, sError, _T("TortoiseGit"), MB_ICONERROR);
491 return;
493 SysFreeString(temp);
498 //CString checkedfiles;
499 //CString uncheckedfiles;
501 CString cmd;
502 CString out;
504 bool bAddSuccess=true;
505 bool bCloseCommitDlg=false;
507 CSysProgressDlg sysProgressDlg;
508 if (nListItems >= 25 && sysProgressDlg.IsValid())
510 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_PROC_COMMIT_PREPARECOMMIT)));
511 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_COMMIT_UPDATEINDEX)));
512 sysProgressDlg.SetTime(true);
513 sysProgressDlg.SetShowProgressBar(true);
514 sysProgressDlg.ShowModal(this, true);
517 CBlockCacheForPath cacheBlock(g_Git.m_CurrentDir);
518 DWORD currentTicks = GetTickCount();
520 for (int j=0; j<nListItems; j++)
522 CTGitPath *entry = (CTGitPath*)m_ListCtrl.GetItemData(j);
523 if (sysProgressDlg.IsValid())
525 if (GetTickCount() - currentTicks > 1000 || j == nListItems - 1 || j == 0)
527 sysProgressDlg.SetLine(2, entry->GetGitPathString(), true);
528 sysProgressDlg.SetProgress(j, nListItems);
529 AfxGetThread()->PumpMessage(); // process messages, in order to avoid freezing; do not call this too: this takes time!
530 currentTicks = GetTickCount();
533 //const CGitStatusListCtrl::FileEntry * entry = m_ListCtrl.GetListEntry(j);
534 if (entry->m_Checked)
536 #if 0
537 if (entry->status == Git_wc_status_unversioned)
539 itemsToAdd.AddPath(entry->GetPath());
541 if (entry->status == Git_wc_status_conflicted)
543 bHasConflicted = true;
545 if (entry->status == Git_wc_status_missing)
547 itemsToRemove.AddPath(entry->GetPath());
549 if (entry->status == Git_wc_status_deleted)
551 arDeleted.Add(j);
553 if (entry->IsInExternal())
555 bCheckedInExternal = true;
557 #endif
558 if( entry->m_Action & CTGitPath::LOGACTIONS_UNVER)
559 cmd.Format(_T("git.exe add -f -- \"%s\""),entry->GetGitPathString());
560 else if ( entry->m_Action & CTGitPath::LOGACTIONS_DELETED)
561 cmd.Format(_T("git.exe update-index --force-remove -- \"%s\""),entry->GetGitPathString());
562 else
563 cmd.Format(_T("git.exe update-index -- \"%s\""),entry->GetGitPathString());
565 if (g_Git.Run(cmd, &out, CP_UTF8))
567 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
568 bAddSuccess = false ;
569 break;
572 if( entry->m_Action & CTGitPath::LOGACTIONS_REPLACED)
573 cmd.Format(_T("git.exe rm -- \"%s\""), entry->GetGitOldPathString());
575 g_Git.Run(cmd, &out, CP_UTF8);
577 nchecked++;
579 //checkedLists.insert(entry->GetGitPathString());
580 // checkedfiles += _T("\"")+entry->GetGitPathString()+_T("\" ");
582 else
584 //uncheckedLists.insert(entry->GetGitPathString());
585 if(entry->m_Action & CTGitPath::LOGACTIONS_ADDED)
586 { //To init git repository, there are not HEAD, so we can use git reset command
587 cmd.Format(_T("git.exe rm -f --cache -- \"%s\""),entry->GetGitPathString());
588 if (g_Git.Run(cmd, &out, CP_UTF8))
590 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
591 bAddSuccess = false ;
592 bCloseCommitDlg=false;
593 break;
595 mgtReAddAfterCommit.AddFile(*entry);
597 else if(!( entry->m_Action & CTGitPath::LOGACTIONS_UNVER ) )
599 if (m_bCommitAmend && !m_bAmendDiffToLastCommit)
601 cmd.Format(_T("git.exe reset HEAD~2 -- \"%s\""), entry->GetGitPathString());
603 else
605 cmd.Format(_T("git.exe reset -- \"%s\""), entry->GetGitPathString());
607 if (g_Git.Run(cmd, &out, CP_UTF8))
609 /* when reset a unstage file will report error.
610 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
611 bAddSuccess = false ;
612 bCloseCommitDlg=false;
613 break;
616 // && !entry->IsDirectory()
617 if (m_bCommitAmend && !m_bAmendDiffToLastCommit)
618 continue;
621 // uncheckedfiles += _T("\"")+entry->GetGitPathString()+_T("\" ");
622 #if 0
623 if ((entry->status != Git_wc_status_unversioned) &&
624 (entry->status != Git_wc_status_ignored))
626 nUnchecked++;
627 uncheckedLists.insert(entry->GetChangeList());
628 if (m_bRecursive)
630 // This algorithm is for the sake of simplicity of the complexity O(N?
631 for (int k=0; k<nListItems; k++)
633 const CGitStatusListCtrl::FileEntry * entryK = m_ListCtrl.GetListEntry(k);
634 if (entryK->IsChecked() && entryK->GetPath().IsAncestorOf(entry->GetPath()) )
636 // Fall back to a non-recursive commit to prevent items being
637 // committed which aren't checked although its parent is checked
638 // (property change, directory deletion, ... )
639 m_bRecursive = false;
640 break;
645 #endif
648 if (sysProgressDlg.IsValid() && sysProgressDlg.HasUserCancelled())
650 bAddSuccess = false;
651 break;
654 CShellUpdater::Instance().AddPathForUpdate(*entry);
657 if (sysProgressDlg.IsValid())
658 sysProgressDlg.Stop();
660 if (bAddSuccess && m_bCreateNewBranch)
662 if (g_Git.Run(_T("git branch ") + m_sCreateNewBranch, &out, CP_UTF8))
664 MessageBox(_T("Creating new branch failed:\n") + out, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
665 bAddSuccess = false;
667 if (g_Git.Run(_T("git checkout ") + m_sCreateNewBranch, &out, CP_UTF8))
669 MessageBox(_T("Switching to new branch failed:\n") + out, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
670 bAddSuccess = false;
674 if (bAddSuccess && CheckHeadDetach())
675 bAddSuccess = false;
677 //if(uncheckedfiles.GetLength()>0)
679 // cmd.Format(_T("git.exe reset -- %s"),uncheckedfiles);
680 // g_Git.Run(cmd,&out);
683 m_sBugID.Trim();
684 if (!m_sBugID.IsEmpty())
686 m_sBugID.Replace(_T(", "), _T(","));
687 m_sBugID.Replace(_T(" ,"), _T(","));
688 CString sBugID = m_ProjectProperties.sMessage;
689 sBugID.Replace(_T("%BUGID%"), m_sBugID);
690 if (m_ProjectProperties.bAppend)
691 m_sLogMessage += _T("\n") + sBugID + _T("\n");
692 else
693 m_sLogMessage = sBugID + _T("\n") + m_sLogMessage;
696 //if(checkedfiles.GetLength()>0)
697 if (bAddSuccess && (nchecked || m_bCommitAmend || CTGitPath(g_Git.m_CurrentDir).IsMergeActive()))
699 // cmd.Format(_T("git.exe update-index -- %s"),checkedfiles);
700 // g_Git.Run(cmd,&out);
702 bCloseCommitDlg = true;
704 CString tempfile=::GetTempFile();
706 CAppUtils::SaveCommitUnicodeFile(tempfile,m_sLogMessage);
707 //file.WriteString(m_sLogMessage);
709 CTGitPath path=g_Git.m_CurrentDir;
711 BOOL IsGitSVN = path.GetAdminDirMask() & ITEMIS_GITSVN;
713 out =_T("");
714 CString amend;
715 if(this->m_bCommitAmend)
717 amend=_T("--amend");
719 CString dateTime;
720 if (m_bSetCommitDateTime)
722 CTime date, time;
723 m_CommitDate.GetTime(date);
724 m_CommitTime.GetTime(time);
725 dateTime.Format(_T("--date=%sT%s"), date.Format(_T("%Y-%m-%d")), time.Format(_T("%H:%M:%S")));
727 cmd.Format(_T("git.exe commit %s %s -F \"%s\""), dateTime, amend, tempfile);
729 CCommitProgressDlg progress;
730 progress.m_bBufferAll=true; // improve show speed when there are many file added.
731 progress.m_GitCmd=cmd;
732 progress.m_bShowCommand = FALSE; // don't show the commit command
733 progress.m_PreText = out; // show any output already generated in log window
734 progress.m_bAutoCloseOnSuccess = m_bAutoClose;
736 if (!m_bNoPostActions && !m_bAutoClose)
738 progress.m_PostCmdList.Add( IsGitSVN? CString(MAKEINTRESOURCE(IDS_MENUSVNDCOMMIT)): CString(MAKEINTRESOURCE(IDS_MENUPUSH)));
739 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_PROC_COMMIT_RECOMMIT)));
740 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_MENUTAG)));
743 m_PostCmd = IsGitSVN? GIT_POST_CMD_DCOMMIT:GIT_POST_CMD_PUSH;
745 DWORD userResponse = progress.DoModal();
747 if(progress.m_GitStatus || userResponse == (IDC_PROGRESS_BUTTON1+1))
749 bCloseCommitDlg = false;
750 if( userResponse == (IDC_PROGRESS_BUTTON1+1 ))
752 this->m_sLogMessage.Empty();
753 m_cLogMessage.SetText(m_sLogMessage);
756 this->Refresh();
758 else if(userResponse == IDC_PROGRESS_BUTTON1 + 2)
760 m_bCreateTagAfterCommit=true;
762 else if(userResponse == IDC_PROGRESS_BUTTON1)
764 //User pressed 'Push' button after successful commit.
765 m_bPushAfterCommit=true;
768 CFile::Remove(tempfile);
770 if (m_BugTraqProvider && progress.m_GitStatus == 0)
772 CComPtr<IBugTraqProvider2> pProvider = NULL;
773 HRESULT hr = m_BugTraqProvider.QueryInterface(&pProvider);
774 if (SUCCEEDED(hr))
776 BSTR commonRoot = SysAllocString(g_Git.m_CurrentDir);
777 SAFEARRAY *pathList = SafeArrayCreateVector(VT_BSTR, 0,this->m_selectedPathList.GetCount());
779 for (LONG index = 0; index < m_selectedPathList.GetCount(); ++index)
780 SafeArrayPutElement(pathList, &index, m_selectedPathList[index].GetGitPathString().AllocSysString());
782 BSTR logMessage = m_sLogMessage.AllocSysString();
784 CGitHash hash=g_Git.GetHash(_T("HEAD"));
785 LONG version = g_Git.Hash2int(hash);
787 BSTR temp = NULL;
788 if (FAILED(hr = pProvider->OnCommitFinished(GetSafeHwnd(),
789 commonRoot,
790 pathList,
791 logMessage,
792 (LONG)version,
793 &temp)))
795 CString sErr = temp;
796 if (!sErr.IsEmpty())
797 CMessageBox::Show(NULL,(sErr),_T("TortoiseGit"),MB_OK|MB_ICONERROR);
798 else
800 COMError ce(hr);
801 sErr.Format(IDS_ERR_FAILEDISSUETRACKERCOM, ce.GetSource().c_str(), ce.GetMessageAndDescription().c_str());
802 CMessageBox::Show(NULL,(sErr),_T("TortoiseGit"),MB_OK|MB_ICONERROR);
806 SysFreeString(temp);
809 RestoreFiles(progress.m_GitStatus == 0);
810 if (((DWORD)CRegStdDWORD(_T("Software\\TortoiseGit\\ReaddUnselectedAddedFilesAfterCommit"), TRUE)) == TRUE)
812 BOOL cancel;
813 mgtReAddAfterCommit.Execute(cancel);
816 else if(bAddSuccess)
818 CMessageBox::Show(this->m_hWnd, IDS_ERROR_NOTHING_COMMIT, IDS_COMMIT_FINISH, MB_OK | MB_ICONINFORMATION);
819 bCloseCommitDlg=false;
821 #if 0
822 if (m_pathwatcher.GetNumberOfChangedPaths() && m_bRecursive)
824 // There are paths which got changed (touched at least).
825 // We have to find out if this affects the selection in the commit dialog
826 // If it could affect the selection, revert back to a non-recursive commit
827 CTGitPathList changedList = m_pathwatcher.GetChangedPaths();
828 changedList.RemoveDuplicates();
829 for (int i=0; i<changedList.GetCount(); ++i)
831 if (changedList[i].IsAdminDir())
833 // something inside an admin dir was changed.
834 // if it's the entries file, then we have to fully refresh because
835 // files may have been added/removed from version control
836 if ((changedList[i].GetWinPathString().Right(7).CompareNoCase(_T("entries")) == 0) &&
837 (changedList[i].GetWinPathString().Find(_T("\\tmp\\"))<0))
839 m_bRecursive = false;
840 break;
843 else if (!m_ListCtrl.IsPathShown(changedList[i]))
845 // a path which is not shown in the list has changed
846 CGitStatusListCtrl::FileEntry * entry = m_ListCtrl.GetListEntry(changedList[i]);
847 if (entry)
849 // check if the changed path would get committed by a recursive commit
850 if ((!entry->IsFromDifferentRepository()) &&
851 (!entry->IsInExternal()) &&
852 (!entry->IsNested()) &&
853 (!entry->IsChecked()))
855 m_bRecursive = false;
856 break;
864 // Now, do all the adds - make sure that the list is sorted so that parents
865 // are added before their children
866 itemsToAdd.SortByPathname();
867 Git Git;
868 if (!Git.Add(itemsToAdd, &m_ProjectProperties, Git_depth_empty, FALSE, FALSE, TRUE))
870 CMessageBox::Show(m_hWnd, Git.GetLastErrorMessage(), _T("TortoiseGit"), MB_ICONERROR);
871 InterlockedExchange(&m_bBlock, FALSE);
872 Refresh();
873 return;
876 // Remove any missing items
877 // Not sure that this sort is really necessary - indeed, it might be better to do a reverse sort at this point
878 itemsToRemove.SortByPathname();
879 Git.Remove(itemsToRemove, TRUE);
881 //the next step: find all deleted files and check if they're
882 //inside a deleted folder. If that's the case, then remove those
883 //files from the list since they'll get deleted by the parent
884 //folder automatically.
885 m_ListCtrl.Block(TRUE, FALSE);
886 INT_PTR nDeleted = arDeleted.GetCount();
887 for (INT_PTR i=0; i<arDeleted.GetCount(); i++)
889 if (m_ListCtrl.GetCheck(arDeleted.GetAt(i)))
891 const CTGitPath& path = m_ListCtrl.GetListEntry(arDeleted.GetAt(i))->GetPath();
892 if (path.IsDirectory())
894 //now find all children of this directory
895 for (int j=0; j<arDeleted.GetCount(); j++)
897 if (i!=j)
899 CGitStatusListCtrl::FileEntry* childEntry = m_ListCtrl.GetListEntry(arDeleted.GetAt(j));
900 if (childEntry->IsChecked())
902 if (path.IsAncestorOf(childEntry->GetPath()))
904 m_ListCtrl.SetEntryCheck(childEntry, arDeleted.GetAt(j), false);
905 nDeleted--;
913 m_ListCtrl.Block(FALSE, FALSE);
915 if ((nUnchecked != 0)||(bCheckedInExternal)||(bHasConflicted)||(!m_bRecursive))
917 //save only the files the user has checked into the temporary file
918 m_ListCtrl.WriteCheckedNamesToPathList(m_pathList);
921 // the item count is used in the progress dialog to show the overall commit
922 // progress.
923 // deleted items only send one notification event, all others send two
924 m_itemsCount = ((m_selectedPathList.GetCount() - nDeleted - itemsToRemove.GetCount()) * 2) + nDeleted + itemsToRemove.GetCount();
926 if ((m_bRecursive)&&(checkedLists.size() == 1))
928 // all checked items belong to the same changelist
929 // find out if there are any unchecked items which belong to that changelist
930 if (uncheckedLists.find(*checkedLists.begin()) == uncheckedLists.end())
931 m_sChangeList = *checkedLists.begin();
933 #endif
934 UpdateData();
935 m_regAddBeforeCommit = m_bShowUnversioned;
936 if (!GetDlgItem(IDC_WHOLE_PROJECT)->IsWindowEnabled())
937 m_bWholeProject = FALSE;
938 m_regKeepChangelists = m_bKeepChangeList;
939 m_regDoNotAutoselectSubmodules = m_bDoNotAutoselectSubmodules;
940 if (!GetDlgItem(IDC_KEEPLISTS)->IsWindowEnabled())
941 m_bKeepChangeList = FALSE;
942 InterlockedExchange(&m_bBlock, FALSE);
944 m_History.AddEntry(m_sLogMessage);
945 m_History.Save();
947 SaveSplitterPos();
949 if( bCloseCommitDlg )
950 CResizableStandAloneDialog::OnOK();
952 CShellUpdater::Instance().Flush();
955 void CCommitDlg::SaveSplitterPos()
957 if (!IsIconic())
959 CRegDWORD regPos = CRegDWORD(_T("Software\\TortoiseGit\\TortoiseProc\\ResizableState\\CommitDlgSizer"));
960 RECT rectSplitter;
961 m_wndSplitter.GetWindowRect(&rectSplitter);
962 ScreenToClient(&rectSplitter);
963 regPos = rectSplitter.top;
967 UINT CCommitDlg::StatusThreadEntry(LPVOID pVoid)
969 return ((CCommitDlg*)pVoid)->StatusThread();
972 UINT CCommitDlg::StatusThread()
974 //get the status of all selected file/folders recursively
975 //and show the ones which have to be committed to the user
976 //in a list control.
977 InterlockedExchange(&m_bBlock, TRUE);
978 InterlockedExchange(&m_bThreadRunning, TRUE);// so the main thread knows that this thread is still running
979 InterlockedExchange(&m_bRunThread, TRUE); // if this is set to FALSE, the thread should stop
981 m_pathwatcher.Stop();
983 g_Git.RefreshGitIndex();
985 m_bCancelled = false;
987 DialogEnableWindow(IDOK, false);
988 DialogEnableWindow(IDC_SHOWUNVERSIONED, false);
989 DialogEnableWindow(IDC_WHOLE_PROJECT, false);
990 DialogEnableWindow(IDC_SELECTALL, false);
991 DialogEnableWindow(IDC_NOAUTOSELECTSUBMODULES, false);
992 GetDlgItem(IDC_EXTERNALWARNING)->ShowWindow(SW_HIDE);
993 DialogEnableWindow(IDC_EXTERNALWARNING, false);
994 DialogEnableWindow(IDC_COMMIT_AMEND, FALSE);
995 DialogEnableWindow(IDC_COMMIT_AMENDDIFF, FALSE);
996 // read the list of recent log entries before querying the WC for status
997 // -> the user may select one and modify / update it while we are crawling the WC
999 if (m_History.GetCount()==0)
1001 CString reg;
1002 reg.Format(_T("Software\\TortoiseGit\\History\\commit%s"), (LPCTSTR)m_ListCtrl.m_sUUID);
1003 reg.Replace(_T(':'),_T('_'));
1004 m_History.Load(reg, _T("logmsgs"));
1007 // Initialise the list control with the status of the files/folders below us
1008 m_ListCtrl.Clear();
1009 BOOL success;
1010 CTGitPathList *pList;
1011 m_ListCtrl.m_amend = (m_bCommitAmend==TRUE) && (m_bAmendDiffToLastCommit==FALSE);
1012 m_ListCtrl.m_bDoNotAutoselectSubmodules = (m_bDoNotAutoselectSubmodules == TRUE);
1014 if(m_bWholeProject)
1015 pList=NULL;
1016 else
1017 pList = &m_pathList;
1019 success=m_ListCtrl.GetStatus(pList);
1021 //m_ListCtrl.UpdateFileList(git_revnum_t(GIT_REV_ZERO));
1022 if(this->m_bShowUnversioned)
1023 m_ListCtrl.UpdateFileList(CGitStatusListCtrl::FILELIST_UNVER,true,pList);
1025 m_ListCtrl.CheckIfChangelistsArePresent(false);
1027 DWORD dwShow = GITSLC_SHOWVERSIONEDBUTNORMALANDEXTERNALSFROMDIFFERENTREPOS | GITSLC_SHOWLOCKS | GITSLC_SHOWINCHANGELIST;
1028 dwShow |= DWORD(m_regAddBeforeCommit) ? GITSLC_SHOWUNVERSIONED : 0;
1029 if (success)
1031 if (m_checkedPathList.GetCount())
1032 m_ListCtrl.Show(dwShow, m_checkedPathList);
1033 else
1035 DWORD dwCheck = m_bSelectFilesForCommit ? dwShow : 0;
1036 dwCheck &=~(CTGitPath::LOGACTIONS_UNVER); //don't check unversion file default.
1037 m_ListCtrl.Show(dwShow, dwCheck);
1038 m_bSelectFilesForCommit = true;
1041 if (m_ListCtrl.HasExternalsFromDifferentRepos())
1043 GetDlgItem(IDC_EXTERNALWARNING)->ShowWindow(SW_SHOW);
1044 DialogEnableWindow(IDC_EXTERNALWARNING, TRUE);
1047 SetDlgItemText(IDC_COMMIT_TO, g_Git.GetCurrentBranch());
1048 m_tooltips.AddTool(GetDlgItem(IDC_STATISTICS), m_ListCtrl.GetStatisticsString());
1050 if (!success)
1052 if (!m_ListCtrl.GetLastErrorMessage().IsEmpty())
1053 m_ListCtrl.SetEmptyString(m_ListCtrl.GetLastErrorMessage());
1054 m_ListCtrl.Show(dwShow);
1057 if ((m_ListCtrl.GetItemCount()==0)&&(m_ListCtrl.HasUnversionedItems())
1058 && !PathFileExists(g_Git.m_CurrentDir+_T("\\.git\\MERGE_HEAD")))
1060 CString temp;
1061 temp.LoadString(IDS_COMMITDLG_NOTHINGTOCOMMITUNVERSIONED);
1062 if (CMessageBox::ShowCheck(m_hWnd, temp, _T("TortoiseGit"), MB_ICONINFORMATION | MB_YESNO, _T("NothingToCommitShowUnversioned"), NULL)==IDYES)
1064 m_bShowUnversioned = TRUE;
1065 GetDlgItem(IDC_SHOWUNVERSIONED)->SendMessage(BM_SETCHECK, BST_CHECKED);
1066 DWORD dwShow = (DWORD)(GITSLC_SHOWVERSIONEDBUTNORMALANDEXTERNALSFROMDIFFERENTREPOS | GITSLC_SHOWUNVERSIONED | GITSLC_SHOWLOCKS);
1067 m_ListCtrl.UpdateFileList(CGitStatusListCtrl::FILELIST_UNVER);
1068 m_ListCtrl.Show(dwShow,dwShow&(~CTGitPath::LOGACTIONS_UNVER));
1072 SetDlgTitle();
1074 m_autolist.clear();
1075 // we don't have to block the commit dialog while we fetch the
1076 // auto completion list.
1077 m_pathwatcher.ClearChangedPaths();
1078 InterlockedExchange(&m_bBlock, FALSE);
1079 if ((DWORD)CRegDWORD(_T("Software\\TortoiseGit\\Autocompletion"), TRUE)==TRUE)
1081 m_ListCtrl.Block(TRUE, TRUE);
1082 GetAutocompletionList();
1083 m_ListCtrl.Block(FALSE, FALSE);
1085 UpdateOKButton();
1086 if (m_bRunThread)
1088 DialogEnableWindow(IDC_SHOWUNVERSIONED, true);
1089 DialogEnableWindow(IDC_WHOLE_PROJECT, true);
1090 DialogEnableWindow(IDC_SELECTALL, true);
1091 DialogEnableWindow(IDC_NOAUTOSELECTSUBMODULES, true);
1092 if (m_ListCtrl.HasChangeLists())
1093 DialogEnableWindow(IDC_KEEPLISTS, true);
1094 if (m_ListCtrl.HasLocks())
1095 DialogEnableWindow(IDC_WHOLE_PROJECT, true);
1097 // activate amend checkbox (if necessary)
1098 if (g_Git.IsInitRepos())
1100 m_bCommitAmend = FALSE;
1101 UpdateData(FALSE);
1103 else
1105 if (m_bForceCommitAmend)
1107 GetDlgItem(IDC_COMMIT_AMENDDIFF)->ShowWindow(SW_SHOW);
1108 m_bCommitAmend = TRUE;
1109 UpdateData(FALSE);
1111 else
1112 GetDlgItem(IDC_COMMIT_AMEND)->EnableWindow(TRUE);
1114 CGitHash hash = g_Git.GetHash(_T("HEAD"));
1115 GitRev headRevision;
1116 headRevision.GetParentFromHash(hash);
1117 // do not allow to show diff to "last" revision if it has more that one parent
1118 if (headRevision.ParentsCount() != 1)
1120 m_bAmendDiffToLastCommit = true;
1121 UpdateData(FALSE);
1123 else
1124 GetDlgItem(IDC_COMMIT_AMENDDIFF)->EnableWindow(TRUE);
1127 // we have the list, now signal the main thread about it
1128 SendMessage(WM_AUTOLISTREADY); // only send the message if the thread wasn't told to quit!
1131 InterlockedExchange(&m_bRunThread, FALSE);
1132 InterlockedExchange(&m_bThreadRunning, FALSE);
1133 // force the cursor to normal
1134 RefreshCursor();
1136 return 0;
1139 void CCommitDlg::SetDlgTitle()
1141 if (m_sTitle.IsEmpty())
1142 GetWindowText(m_sTitle);
1144 if (m_bWholeProject)
1145 CAppUtils::SetWindowTitle(m_hWnd, g_Git.m_CurrentDir, m_sTitle);
1146 else
1148 if (m_pathList.GetCount() == 1)
1149 CAppUtils::SetWindowTitle(m_hWnd, (g_Git.m_CurrentDir + _T("\\") + m_pathList[0].GetUIPathString()).TrimRight('\\'), m_sTitle);
1150 else
1151 CAppUtils::SetWindowTitle(m_hWnd, g_Git.m_CurrentDir + _T("\\") + m_ListCtrl.GetCommonDirectory(false), m_sTitle);
1155 void CCommitDlg::OnCancel()
1157 m_bCancelled = true;
1158 m_pathwatcher.Stop();
1160 if (m_bThreadRunning)
1162 InterlockedExchange(&m_bRunThread, FALSE);
1163 WaitForSingleObject(m_pThread->m_hThread, 1000);
1164 if (m_bThreadRunning)
1166 // we gave the thread a chance to quit. Since the thread didn't
1167 // listen to us we have to kill it.
1168 TerminateThread(m_pThread->m_hThread, (DWORD)-1);
1169 InterlockedExchange(&m_bThreadRunning, FALSE);
1172 UpdateData();
1173 m_sBugID.Trim();
1174 m_sLogMessage = m_cLogMessage.GetText();
1175 if (!m_sBugID.IsEmpty())
1177 m_sBugID.Replace(_T(", "), _T(","));
1178 m_sBugID.Replace(_T(" ,"), _T(","));
1179 CString sBugID = m_ProjectProperties.sMessage;
1180 sBugID.Replace(_T("%BUGID%"), m_sBugID);
1181 if (m_ProjectProperties.bAppend)
1182 m_sLogMessage += _T("\n") + sBugID + _T("\n");
1183 else
1184 m_sLogMessage = sBugID + _T("\n") + m_sLogMessage;
1186 if (m_ProjectProperties.sLogTemplate.Compare(m_sLogMessage) != 0)
1187 m_History.AddEntry(m_sLogMessage);
1188 m_History.Save();
1189 RestoreFiles();
1190 SaveSplitterPos();
1191 CResizableStandAloneDialog::OnCancel();
1194 void CCommitDlg::OnBnClickedSelectall()
1196 m_tooltips.Pop(); // hide the tooltips
1197 UINT state = (m_SelectAll.GetState() & 0x0003);
1198 if (state == BST_INDETERMINATE)
1200 // It is not at all useful to manually place the checkbox into the indeterminate state...
1201 // We will force this on to the unchecked state
1202 state = BST_UNCHECKED;
1203 m_SelectAll.SetCheck(state);
1205 m_ListCtrl.SelectAll(state == BST_CHECKED);
1208 BOOL CCommitDlg::PreTranslateMessage(MSG* pMsg)
1210 if (!m_bBlock)
1211 m_tooltips.RelayEvent(pMsg);
1213 if (m_hAccel)
1215 int ret = TranslateAccelerator(m_hWnd, m_hAccel, pMsg);
1216 if (ret)
1217 return TRUE;
1220 if (pMsg->message == WM_KEYDOWN)
1222 switch (pMsg->wParam)
1224 case VK_F5:
1226 if (m_bBlock)
1227 return CResizableStandAloneDialog::PreTranslateMessage(pMsg);
1228 Refresh();
1230 break;
1231 case VK_RETURN:
1233 if (GetAsyncKeyState(VK_CONTROL)&0x8000)
1235 if ( GetDlgItem(IDOK)->IsWindowEnabled() )
1237 PostMessage(WM_COMMAND, IDOK);
1239 return TRUE;
1241 if ( GetFocus()==GetDlgItem(IDC_BUGID) )
1243 // Pressing RETURN in the bug id control
1244 // moves the focus to the message
1245 GetDlgItem(IDC_LOGMESSAGE)->SetFocus();
1246 return TRUE;
1249 break;
1253 return CResizableStandAloneDialog::PreTranslateMessage(pMsg);
1256 void CCommitDlg::Refresh()
1258 if (m_bThreadRunning)
1259 return;
1261 InterlockedExchange(&m_bBlock, TRUE);
1262 m_pThread = AfxBeginThread(StatusThreadEntry, this, THREAD_PRIORITY_NORMAL,0,CREATE_SUSPENDED);
1263 if (m_pThread==NULL)
1265 CMessageBox::Show(this->m_hWnd, IDS_ERR_THREADSTARTFAILED, IDS_APPNAME, MB_OK | MB_ICONERROR);
1266 InterlockedExchange(&m_bBlock, FALSE);
1268 else
1270 m_pThread->m_bAutoDelete = FALSE;
1271 m_pThread->ResumeThread();
1275 void CCommitDlg::OnBnClickedHelp()
1277 OnHelp();
1280 void CCommitDlg::OnBnClickedShowunversioned()
1282 m_tooltips.Pop(); // hide the tooltips
1283 UpdateData();
1284 m_regAddBeforeCommit = m_bShowUnversioned;
1285 if (!m_bBlock)
1287 DWORD dwShow = m_ListCtrl.GetShowFlags();
1288 if (DWORD(m_regAddBeforeCommit))
1289 dwShow |= GITSLC_SHOWUNVERSIONED;
1290 else
1291 dwShow &= ~GITSLC_SHOWUNVERSIONED;
1292 if(dwShow & GITSLC_SHOWUNVERSIONED)
1294 if(m_bWholeProject)
1295 m_ListCtrl.GetStatus(NULL,false,false,true);
1296 else
1297 m_ListCtrl.GetStatus(&this->m_pathList,false,false,true);
1299 m_ListCtrl.Show(dwShow, 0, true, dwShow & ~(CTGitPath::LOGACTIONS_UNVER), true);
1303 void CCommitDlg::OnStnClickedExternalwarning()
1305 m_tooltips.Popup();
1308 void CCommitDlg::OnEnChangeLogmessage()
1310 UpdateOKButton();
1313 LRESULT CCommitDlg::OnGitStatusListCtrlItemCountChanged(WPARAM, LPARAM)
1315 #if 0
1316 if ((m_ListCtrl.GetItemCount() == 0)&&(m_ListCtrl.HasUnversionedItems())&&(!m_bShowUnversioned))
1318 if (CMessageBox::Show(*this, IDS_COMMITDLG_NOTHINGTOCOMMITUNVERSIONED, IDS_APPNAME, MB_ICONINFORMATION | MB_YESNO)==IDYES)
1320 m_bShowUnversioned = TRUE;
1321 DWORD dwShow = GitSLC_SHOWVERSIONEDBUTNORMALANDEXTERNALSFROMDIFFERENTREPOS | GitSLC_SHOWUNVERSIONED | GitSLC_SHOWLOCKS;
1322 m_ListCtrl.Show(dwShow);
1323 UpdateData(FALSE);
1326 #endif
1327 return 0;
1330 LRESULT CCommitDlg::OnGitStatusListCtrlNeedsRefresh(WPARAM, LPARAM)
1332 Refresh();
1333 return 0;
1336 LRESULT CCommitDlg::OnFileDropped(WPARAM, LPARAM /*lParam*/)
1338 #if 0
1339 BringWindowToTop();
1340 SetForegroundWindow();
1341 SetActiveWindow();
1342 // if multiple files/folders are dropped
1343 // this handler is called for every single item
1344 // separately.
1345 // To avoid creating multiple refresh threads and
1346 // causing crashes, we only add the items to the
1347 // list control and start a timer.
1348 // When the timer expires, we start the refresh thread,
1349 // but only if it isn't already running - otherwise we
1350 // restart the timer.
1351 CTGitPath path;
1352 path.SetFromWin((LPCTSTR)lParam);
1354 // just add all the items we get here.
1355 // if the item is versioned, the add will fail but nothing
1356 // more will happen.
1357 Git Git;
1358 Git.Add(CTGitPathList(path), &m_ProjectProperties, Git_depth_empty, false, true, true);
1360 if (!m_ListCtrl.HasPath(path))
1362 if (m_pathList.AreAllPathsFiles())
1364 m_pathList.AddPath(path);
1365 m_pathList.RemoveDuplicates();
1366 m_updatedPathList.AddPath(path);
1367 m_updatedPathList.RemoveDuplicates();
1369 else
1371 // if the path list contains folders, we have to check whether
1372 // our just (maybe) added path is a child of one of those. If it is
1373 // a child of a folder already in the list, we must not add it. Otherwise
1374 // that path could show up twice in the list.
1375 bool bHasParentInList = false;
1376 for (int i=0; i<m_pathList.GetCount(); ++i)
1378 if (m_pathList[i].IsAncestorOf(path))
1380 bHasParentInList = true;
1381 break;
1384 if (!bHasParentInList)
1386 m_pathList.AddPath(path);
1387 m_pathList.RemoveDuplicates();
1388 m_updatedPathList.AddPath(path);
1389 m_updatedPathList.RemoveDuplicates();
1394 // Always start the timer, since the status of an existing item might have changed
1395 SetTimer(REFRESHTIMER, 200, NULL);
1396 ATLTRACE(_T("Item %s dropped, timer started\n"), path.GetWinPath());
1397 #endif
1398 return 0;
1401 LRESULT CCommitDlg::OnAutoListReady(WPARAM, LPARAM)
1403 m_cLogMessage.SetAutoCompletionList(m_autolist, '*');
1404 return 0;
1407 //////////////////////////////////////////////////////////////////////////
1408 // functions which run in the status thread
1409 //////////////////////////////////////////////////////////////////////////
1411 void CCommitDlg::ParseRegexFile(const CString& sFile, std::map<CString, CString>& mapRegex)
1413 CString strLine;
1416 CStdioFile file(sFile, CFile::typeText | CFile::modeRead | CFile::shareDenyWrite);
1417 while (m_bRunThread && file.ReadString(strLine))
1419 int eqpos = strLine.Find('=');
1420 CString rgx;
1421 rgx = strLine.Mid(eqpos+1).Trim();
1423 int pos = -1;
1424 while (((pos = strLine.Find(','))>=0)&&(pos < eqpos))
1426 mapRegex[strLine.Left(pos)] = rgx;
1427 strLine = strLine.Mid(pos+1).Trim();
1429 mapRegex[strLine.Left(strLine.Find('=')).Trim()] = rgx;
1431 file.Close();
1433 catch (CFileException* pE)
1435 TRACE("CFileException loading auto list regex file\n");
1436 pE->Delete();
1437 return;
1440 void CCommitDlg::GetAutocompletionList()
1442 // the auto completion list is made of strings from each selected files.
1443 // the strings used are extracted from the files with regexes found
1444 // in the file "autolist.txt".
1445 // the format of that file is:
1446 // file extensions separated with commas '=' regular expression to use
1447 // example:
1448 // .h, .hpp = (?<=class[\s])\b\w+\b|(\b\w+(?=[\s ]?\(\);))
1449 // .cpp = (?<=[^\s]::)\b\w+\b
1451 std::map<CString, CString> mapRegex;
1452 CString sRegexFile = CPathUtils::GetAppDirectory();
1453 CRegDWORD regtimeout = CRegDWORD(_T("Software\\TortoiseGit\\AutocompleteParseTimeout"), 5);
1454 DWORD timeoutvalue = regtimeout*1000;
1455 sRegexFile += _T("autolist.txt");
1456 if (!m_bRunThread)
1457 return;
1458 ParseRegexFile(sRegexFile, mapRegex);
1459 SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, SHGFP_TYPE_CURRENT, sRegexFile.GetBuffer(MAX_PATH+1));
1460 sRegexFile.ReleaseBuffer();
1461 sRegexFile += _T("\\TortoiseGit\\autolist.txt");
1462 if (PathFileExists(sRegexFile))
1464 ParseRegexFile(sRegexFile, mapRegex);
1466 DWORD starttime = GetTickCount();
1468 // now we have two arrays of strings, where the first array contains all
1469 // file extensions we can use and the second the corresponding regex strings
1470 // to apply to those files.
1472 // the next step is to go over all files shown in the commit dialog
1473 // and scan them for strings we can use
1474 int nListItems = m_ListCtrl.GetItemCount();
1476 for (int i=0; i<nListItems && m_bRunThread; ++i)
1478 // stop parsing after timeout
1479 if ((!m_bRunThread) || (GetTickCount() - starttime > timeoutvalue))
1480 return;
1482 CTGitPath *path = (CTGitPath*)m_ListCtrl.GetItemData(i);
1484 if(path == NULL)
1485 continue;
1487 CString sPartPath =path->GetGitPathString();
1488 m_autolist.insert(sPartPath);
1490 // const CGitStatusListCtrl::FileEntry * entry = m_ListCtrl.GetListEntry(i);
1491 // if (!entry)
1492 // continue;
1494 // add the path parts to the auto completion list too
1495 // CString sPartPath = entry->GetRelativeGitPath();
1496 // m_autolist.insert(sPartPath);
1499 int pos = 0;
1500 int lastPos = 0;
1501 while ((pos = sPartPath.Find('/', pos)) >= 0)
1503 pos++;
1504 lastPos = pos;
1505 m_autolist.insert(sPartPath.Mid(pos));
1508 // Last inserted entry is a file name.
1509 // Some users prefer to also list file name without extension.
1510 if (CRegDWORD(_T("Software\\TortoiseGit\\AutocompleteRemovesExtensions"), FALSE))
1512 int dotPos = sPartPath.ReverseFind('.');
1513 if ((dotPos >= 0) && (dotPos > lastPos))
1514 m_autolist.insert(sPartPath.Mid(lastPos, dotPos - lastPos));
1516 #if 0
1517 if ((entry->status <= Git_wc_status_normal)||(entry->status == Git_wc_status_ignored))
1518 continue;
1520 CString sExt = entry->GetPath().GetFileExtension();
1521 sExt.MakeLower();
1522 // find the regex string which corresponds to the file extension
1523 CString rdata = mapRegex[sExt];
1524 if (rdata.IsEmpty())
1525 continue;
1527 ScanFile(entry->GetPath().GetWinPathString(), rdata);
1528 if ((entry->textstatus != Git_wc_status_unversioned) &&
1529 (entry->textstatus != Git_wc_status_none) &&
1530 (entry->textstatus != Git_wc_status_ignored) &&
1531 (entry->textstatus != Git_wc_status_added) &&
1532 (entry->textstatus != Git_wc_status_normal))
1534 CTGitPath basePath = Git::GetPristinePath(entry->GetPath());
1535 if (!basePath.IsEmpty())
1536 ScanFile(basePath.GetWinPathString(), rdata);
1538 #endif
1540 ATLTRACE(_T("Auto completion list loaded in %d msec\n"), GetTickCount() - starttime);
1543 void CCommitDlg::ScanFile(const CString& sFilePath, const CString& sRegex)
1545 wstring sFileContent;
1546 HANDLE hFile = CreateFile(sFilePath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL);
1547 if (hFile != INVALID_HANDLE_VALUE)
1549 DWORD size = GetFileSize(hFile, NULL);
1550 if (size > 1000000L)
1552 // no files bigger than 1 Meg
1553 CloseHandle(hFile);
1554 return;
1556 // allocate memory to hold file contents
1557 char * buffer = new char[size];
1558 DWORD readbytes;
1559 ReadFile(hFile, buffer, size, &readbytes, NULL);
1560 CloseHandle(hFile);
1561 int opts = 0;
1562 IsTextUnicode(buffer, readbytes, &opts);
1563 if (opts & IS_TEXT_UNICODE_NULL_BYTES)
1565 delete [] buffer;
1566 return;
1568 if (opts & IS_TEXT_UNICODE_UNICODE_MASK)
1570 sFileContent = wstring((wchar_t*)buffer, readbytes/sizeof(WCHAR));
1572 if ((opts & IS_TEXT_UNICODE_NOT_UNICODE_MASK)||(opts == 0))
1574 int ret = MultiByteToWideChar(CP_UTF8, MB_PRECOMPOSED, (LPCSTR)buffer, readbytes, NULL, 0);
1575 wchar_t * pWideBuf = new wchar_t[ret];
1576 int ret2 = MultiByteToWideChar(CP_UTF8, MB_PRECOMPOSED, (LPCSTR)buffer, readbytes, pWideBuf, ret);
1577 if (ret2 == ret)
1578 sFileContent = wstring(pWideBuf, ret);
1579 delete [] pWideBuf;
1581 delete [] buffer;
1583 if (sFileContent.empty()|| !m_bRunThread)
1585 return;
1590 const tr1::wregex regCheck(sRegex, tr1::regex_constants::icase | tr1::regex_constants::ECMAScript);
1591 const tr1::wsregex_iterator end;
1592 wstring s = sFileContent;
1593 for (tr1::wsregex_iterator it(s.begin(), s.end(), regCheck); it != end; ++it)
1595 const tr1::wsmatch match = *it;
1596 for (size_t i=1; i<match.size(); ++i)
1598 if (match[i].second-match[i].first)
1600 ATLTRACE(_T("matched keyword : %s\n"), wstring(match[i]).c_str());
1601 m_autolist.insert(wstring(match[i]).c_str());
1606 catch (exception) {}
1609 // CSciEditContextMenuInterface
1610 void CCommitDlg::InsertMenuItems(CMenu& mPopup, int& nCmd)
1612 CString sMenuItemText(MAKEINTRESOURCE(IDS_COMMITDLG_POPUP_PASTEFILELIST));
1613 m_nPopupPasteListCmd = nCmd++;
1614 mPopup.AppendMenu(MF_STRING | MF_ENABLED, m_nPopupPasteListCmd, sMenuItemText);
1616 //CString sMenuItemText(MAKEINTRESOURCE(IDS_COMMITDLG_POPUP_PASTEFILELIST));
1617 if(m_History.GetCount() > 0)
1619 sMenuItemText.LoadString(IDS_COMMITDLG_POPUP_PASTELASTMESSAGE);
1620 m_nPopupPasteLastMessage = nCmd++;
1621 mPopup.AppendMenu(MF_STRING | MF_ENABLED, m_nPopupPasteLastMessage, sMenuItemText);
1623 sMenuItemText.LoadString(IDS_COMMITDLG_POPUP_LOGHISTORY);
1624 m_nPopupRecentMessage = nCmd++;
1625 mPopup.AppendMenu(MF_STRING | MF_ENABLED, m_nPopupRecentMessage, sMenuItemText);
1631 bool CCommitDlg::HandleMenuItemClick(int cmd, CSciEdit * pSciEdit)
1634 if (m_bBlock)
1635 return false;
1636 if (cmd == m_nPopupPasteListCmd)
1638 CString logmsg;
1639 int nListItems = m_ListCtrl.GetItemCount();
1640 for (int i=0; i<nListItems; ++i)
1642 CTGitPath * entry = (CTGitPath*)m_ListCtrl.GetItemData(i);
1643 if (entry&&entry->m_Checked)
1645 CString line;
1646 CString status = entry->GetActionName();
1647 if(entry->m_Action & CTGitPath::LOGACTIONS_UNVER)
1648 status = _T("Add"); // I18N TODO
1650 //git_wc_status_kind status = entry->status;
1651 WORD langID = (WORD)CRegStdDWORD(_T("Software\\TortoiseGit\\LanguageID"), GetUserDefaultLangID());
1652 if (m_ProjectProperties.bFileListInEnglish)
1653 langID = 1033;
1655 line.Format(_T("%-10s %s\r\n"),status , (LPCTSTR)m_ListCtrl.GetItemText(i,0));
1656 logmsg += line;
1659 pSciEdit->InsertText(logmsg);
1660 return true;
1663 if(cmd == m_nPopupPasteLastMessage)
1665 if(m_History.GetCount() ==0 )
1666 return false;
1668 CString logmsg;
1669 logmsg +=m_History.GetEntry(0);
1670 pSciEdit->InsertText(logmsg);
1671 return true;
1674 if(cmd == m_nPopupRecentMessage )
1676 OnBnClickedHistory();
1677 return true;
1679 return false;
1682 void CCommitDlg::OnTimer(UINT_PTR nIDEvent)
1684 switch (nIDEvent)
1686 case ENDDIALOGTIMER:
1687 KillTimer(ENDDIALOGTIMER);
1688 EndDialog(0);
1689 break;
1690 case REFRESHTIMER:
1691 if (m_bThreadRunning)
1693 SetTimer(REFRESHTIMER, 200, NULL);
1694 ATLTRACE("Wait some more before refreshing\n");
1696 else
1698 KillTimer(REFRESHTIMER);
1699 ATLTRACE("Refreshing after items dropped\n");
1700 Refresh();
1702 break;
1704 __super::OnTimer(nIDEvent);
1707 void CCommitDlg::OnBnClickedHistory()
1709 m_tooltips.Pop(); // hide the tooltips
1710 if (m_pathList.GetCount() == 0)
1711 return;
1713 CHistoryDlg historyDlg;
1714 historyDlg.SetHistory(m_History);
1715 if (historyDlg.DoModal() != IDOK)
1716 return;
1718 CString sMsg = historyDlg.GetSelectedText();
1719 if (sMsg != m_cLogMessage.GetText().Left(sMsg.GetLength()))
1721 CString sBugID = m_ProjectProperties.GetBugIDFromLog(sMsg);
1722 if (!sBugID.IsEmpty())
1724 SetDlgItemText(IDC_BUGID, sBugID);
1726 if (m_ProjectProperties.sLogTemplate.Compare(m_cLogMessage.GetText())!=0)
1727 m_cLogMessage.InsertText(sMsg, !m_cLogMessage.GetText().IsEmpty());
1728 else
1729 m_cLogMessage.SetText(sMsg);
1732 UpdateOKButton();
1733 GetDlgItem(IDC_LOGMESSAGE)->SetFocus();
1737 void CCommitDlg::OnBnClickedBugtraqbutton()
1739 m_tooltips.Pop(); // hide the tooltips
1740 CString sMsg = m_cLogMessage.GetText();
1742 if (m_BugTraqProvider == NULL)
1743 return;
1745 BSTR parameters = m_bugtraq_association.GetParameters().AllocSysString();
1746 BSTR commonRoot = SysAllocString(g_Git.m_CurrentDir);
1747 SAFEARRAY *pathList = SafeArrayCreateVector(VT_BSTR, 0, m_pathList.GetCount());
1749 for (LONG index = 0; index < m_pathList.GetCount(); ++index)
1750 SafeArrayPutElement(pathList, &index, m_pathList[index].GetGitPathString().AllocSysString());
1752 BSTR originalMessage = sMsg.AllocSysString();
1753 BSTR temp = NULL;
1754 // m_revProps.clear();
1756 // first try the IBugTraqProvider2 interface
1757 CComPtr<IBugTraqProvider2> pProvider2 = NULL;
1758 HRESULT hr = m_BugTraqProvider.QueryInterface(&pProvider2);
1759 if (SUCCEEDED(hr))
1761 //CString common = m_ListCtrl.GetCommonURL(false).GetGitPathString();
1762 BSTR repositoryRoot = g_Git.m_CurrentDir.AllocSysString();
1763 BSTR bugIDOut = NULL;
1764 GetDlgItemText(IDC_BUGID, m_sBugID);
1765 BSTR bugID = m_sBugID.AllocSysString();
1766 SAFEARRAY * revPropNames = NULL;
1767 SAFEARRAY * revPropValues = NULL;
1768 if (FAILED(hr = pProvider2->GetCommitMessage2(GetSafeHwnd(), parameters, repositoryRoot, commonRoot, pathList, originalMessage, bugID, &bugIDOut, &revPropNames, &revPropValues, &temp)))
1770 CString sErr;
1771 sErr.Format(IDS_ERR_FAILEDISSUETRACKERCOM, m_bugtraq_association.GetProviderName(), _com_error(hr).ErrorMessage());
1772 CMessageBox::Show(m_hWnd, sErr, _T("TortoiseGit"), MB_ICONERROR);
1774 else
1776 if (bugIDOut)
1778 m_sBugID = bugIDOut;
1779 SysFreeString(bugIDOut);
1780 SetDlgItemText(IDC_BUGID, m_sBugID);
1782 SysFreeString(bugID);
1783 SysFreeString(repositoryRoot);
1784 m_cLogMessage.SetText(temp);
1785 BSTR HUGEP *pbRevNames;
1786 BSTR HUGEP *pbRevValues;
1788 HRESULT hr1 = SafeArrayAccessData(revPropNames, (void HUGEP**)&pbRevNames);
1789 if (SUCCEEDED(hr1))
1791 HRESULT hr2 = SafeArrayAccessData(revPropValues, (void HUGEP**)&pbRevValues);
1792 if (SUCCEEDED(hr2))
1794 if (revPropNames->rgsabound->cElements == revPropValues->rgsabound->cElements)
1796 for (ULONG i = 0; i < revPropNames->rgsabound->cElements; i++)
1798 // m_revProps[pbRevNames[i]] = pbRevValues[i];
1801 SafeArrayUnaccessData(revPropValues);
1803 SafeArrayUnaccessData(revPropNames);
1805 if (revPropNames)
1806 SafeArrayDestroy(revPropNames);
1807 if (revPropValues)
1808 SafeArrayDestroy(revPropValues);
1811 else
1813 // if IBugTraqProvider2 failed, try IBugTraqProvider
1814 CComPtr<IBugTraqProvider> pProvider = NULL;
1815 hr = m_BugTraqProvider.QueryInterface(&pProvider);
1816 if (FAILED(hr))
1818 CString sErr;
1819 sErr.Format(IDS_ERR_FAILEDISSUETRACKERCOM, (LPCTSTR)m_bugtraq_association.GetProviderName(), _com_error(hr).ErrorMessage());
1820 CMessageBox::Show(m_hWnd, sErr, _T("TortoiseGit"), MB_ICONERROR);
1821 return;
1824 if (FAILED(hr = pProvider->GetCommitMessage(GetSafeHwnd(), parameters, commonRoot, pathList, originalMessage, &temp)))
1826 CString sErr;
1827 sErr.Format(IDS_ERR_FAILEDISSUETRACKERCOM, m_bugtraq_association.GetProviderName(), _com_error(hr).ErrorMessage());
1828 CMessageBox::Show(m_hWnd, sErr, _T("TortoiseGit"), MB_ICONERROR);
1830 else
1831 m_cLogMessage.SetText(temp);
1833 m_sLogMessage = m_cLogMessage.GetText();
1834 if (!m_ProjectProperties.sMessage.IsEmpty())
1836 CString sBugID = m_ProjectProperties.FindBugID(m_sLogMessage);
1837 if (!sBugID.IsEmpty())
1839 SetDlgItemText(IDC_BUGID, sBugID);
1843 m_cLogMessage.SetFocus();
1845 SysFreeString(parameters);
1846 SysFreeString(commonRoot);
1847 SafeArrayDestroy(pathList);
1848 SysFreeString(originalMessage);
1849 SysFreeString(temp);
1853 void CCommitDlg::FillPatchView()
1855 if(::IsWindow(this->m_patchViewdlg.m_hWnd))
1857 m_patchViewdlg.m_ctrlPatchView.SetText(CString());
1859 POSITION pos=m_ListCtrl.GetFirstSelectedItemPosition();
1860 m_patchViewdlg.m_ctrlPatchView.Call(SCI_SETREADONLY, FALSE);
1861 CString cmd,out;
1863 while(pos)
1865 int nSelect = m_ListCtrl.GetNextSelectedItem(pos);
1866 CTGitPath * p=(CTGitPath*)m_ListCtrl.GetItemData(nSelect);
1867 if(p && !(p->m_Action&CTGitPath::LOGACTIONS_UNVER) )
1869 CString head = _T("HEAD");
1870 if(m_bCommitAmend==TRUE && m_bAmendDiffToLastCommit==FALSE)
1871 head = _T("HEAD~1");
1872 cmd.Format(_T("git.exe diff %s -- \"%s\""), head, p->GetGitPathString());
1873 g_Git.Run(cmd, &out, CP_UTF8);
1877 m_patchViewdlg.m_ctrlPatchView.SetText(out);
1878 m_patchViewdlg.m_ctrlPatchView.Call(SCI_SETREADONLY, TRUE);
1879 m_patchViewdlg.m_ctrlPatchView.Call(SCI_GOTOPOS, 0);
1880 CRect rect;
1881 m_patchViewdlg.m_ctrlPatchView.GetClientRect(rect);
1882 m_patchViewdlg.m_ctrlPatchView.Call(SCI_SETSCROLLWIDTH, rect.Width() - 4);
1885 LRESULT CCommitDlg::OnGitStatusListCtrlItemChanged(WPARAM /*wparam*/, LPARAM /*lparam*/)
1887 this->FillPatchView();
1888 return 0;
1892 LRESULT CCommitDlg::OnGitStatusListCtrlCheckChanged(WPARAM, LPARAM)
1894 UpdateOKButton();
1895 return 0;
1898 void CCommitDlg::UpdateOKButton()
1900 if (m_bBlock)
1901 return;
1903 bool bValidLogSize = m_cLogMessage.GetText().GetLength() >= m_ProjectProperties.nMinLogSize && m_cLogMessage.GetText().GetLength() > 0;
1904 bool bAmendOrSelectFilesOrMerge = m_ListCtrl.GetSelected() > 0 || (m_bCommitAmend && m_bAmendDiffToLastCommit) || CTGitPath(g_Git.m_CurrentDir).IsMergeActive();
1906 DialogEnableWindow(IDOK, bValidLogSize && bAmendOrSelectFilesOrMerge);
1909 LRESULT CCommitDlg::DefWindowProc(UINT message, WPARAM wParam, LPARAM lParam)
1911 switch (message) {
1912 case WM_NOTIFY:
1913 if (wParam == IDC_SPLITTER)
1915 SPC_NMHDR* pHdr = (SPC_NMHDR*) lParam;
1916 DoSize(pHdr->delta);
1918 break;
1921 return __super::DefWindowProc(message, wParam, lParam);
1924 void CCommitDlg::SetSplitterRange()
1926 if ((m_ListCtrl)&&(m_cLogMessage))
1928 CRect rcTop;
1929 m_cLogMessage.GetWindowRect(rcTop);
1930 ScreenToClient(rcTop);
1931 CRect rcMiddle;
1932 m_ListCtrl.GetWindowRect(rcMiddle);
1933 ScreenToClient(rcMiddle);
1934 if (rcMiddle.Height() && rcMiddle.Width())
1935 m_wndSplitter.SetRange(rcTop.top+60, rcMiddle.bottom-80);
1939 void CCommitDlg::DoSize(int delta)
1941 RemoveAnchor(IDC_MESSAGEGROUP);
1942 RemoveAnchor(IDC_LOGMESSAGE);
1943 RemoveAnchor(IDC_SPLITTER);
1944 RemoveAnchor(IDC_SIGNOFF);
1945 RemoveAnchor(IDC_COMMIT_AMEND);
1946 RemoveAnchor(IDC_COMMIT_AMENDDIFF);
1947 RemoveAnchor(IDC_COMMIT_SETDATETIME);
1948 RemoveAnchor(IDC_COMMIT_DATEPICKER);
1949 RemoveAnchor(IDC_COMMIT_TIMEPICKER);
1950 RemoveAnchor(IDC_LISTGROUP);
1951 RemoveAnchor(IDC_FILELIST);
1952 RemoveAnchor(IDC_TEXT_INFO);
1954 CSplitterControl::ChangeHeight(&m_cLogMessage, delta, CW_TOPALIGN);
1955 CSplitterControl::ChangeHeight(GetDlgItem(IDC_MESSAGEGROUP), delta, CW_TOPALIGN);
1956 CSplitterControl::ChangeHeight(&m_ListCtrl, -delta, CW_BOTTOMALIGN);
1957 CSplitterControl::ChangeHeight(GetDlgItem(IDC_LISTGROUP), -delta, CW_BOTTOMALIGN);
1958 CSplitterControl::ChangePos(GetDlgItem(IDC_SIGNOFF),0,delta);
1959 CSplitterControl::ChangePos(GetDlgItem(IDC_COMMIT_AMEND),0,delta);
1960 CSplitterControl::ChangePos(GetDlgItem(IDC_COMMIT_AMENDDIFF),0,delta);
1961 CSplitterControl::ChangePos(GetDlgItem(IDC_COMMIT_SETDATETIME),0,delta);
1962 CSplitterControl::ChangePos(GetDlgItem(IDC_COMMIT_DATEPICKER),0,delta);
1963 CSplitterControl::ChangePos(GetDlgItem(IDC_COMMIT_TIMEPICKER),0,delta);
1964 CSplitterControl::ChangePos(GetDlgItem(IDC_TEXT_INFO),0,delta);
1966 AddAnchor(IDC_MESSAGEGROUP, TOP_LEFT, TOP_RIGHT);
1967 AddAnchor(IDC_LOGMESSAGE, TOP_LEFT, TOP_RIGHT);
1968 AddAnchor(IDC_SPLITTER, TOP_LEFT, TOP_RIGHT);
1969 AddAnchor(IDC_LISTGROUP, TOP_LEFT, BOTTOM_RIGHT);
1970 AddAnchor(IDC_FILELIST, TOP_LEFT, BOTTOM_RIGHT);
1971 AddAnchor(IDC_SIGNOFF,TOP_RIGHT);
1972 AddAnchor(IDC_COMMIT_AMEND,TOP_LEFT);
1973 AddAnchor(IDC_COMMIT_AMENDDIFF,TOP_LEFT);
1974 AddAnchor(IDC_COMMIT_SETDATETIME,TOP_LEFT);
1975 AddAnchor(IDC_COMMIT_DATEPICKER,TOP_LEFT);
1976 AddAnchor(IDC_COMMIT_TIMEPICKER,TOP_LEFT);
1977 AddAnchor(IDC_TEXT_INFO,TOP_RIGHT);
1978 ArrangeLayout();
1979 // adjust the minimum size of the dialog to prevent the resizing from
1980 // moving the list control too far down.
1981 CRect rcLogMsg;
1982 m_cLogMessage.GetClientRect(rcLogMsg);
1983 SetMinTrackSize(CSize(m_DlgOrigRect.Width(), m_DlgOrigRect.Height()-m_LogMsgOrigRect.Height()+rcLogMsg.Height()));
1985 SetSplitterRange();
1986 m_cLogMessage.Invalidate();
1987 GetDlgItem(IDC_LOGMESSAGE)->Invalidate();
1990 void CCommitDlg::OnSize(UINT nType, int cx, int cy)
1992 // first, let the resizing take place
1993 __super::OnSize(nType, cx, cy);
1995 //set range
1996 SetSplitterRange();
1999 CString CCommitDlg::GetSignedOffByLine()
2001 CString str;
2003 CString username = g_Git.GetUserName();
2004 CString email = g_Git.GetUserEmail();
2005 username.Remove(_T('\n'));
2006 email.Remove(_T('\n'));
2008 str.Format(_T("Signed-off-by: %s <%s>"), username, email);
2010 return str;
2013 void CCommitDlg::OnBnClickedSignOff()
2015 CString str = GetSignedOffByLine();
2017 if (m_cLogMessage.GetText().Find(str) == -1) {
2018 m_cLogMessage.SetText(m_cLogMessage.GetText().TrimRight());
2019 int lastNewline = m_cLogMessage.GetText().ReverseFind(_T('\n'));
2020 int foundByLine = -1;
2021 if (lastNewline > 0)
2022 foundByLine = m_cLogMessage.GetText().Find(_T("-by: "), lastNewline);
2024 if (foundByLine == -1 || foundByLine < lastNewline)
2025 str = _T("\r\n") + str;
2027 m_cLogMessage.SetText(m_cLogMessage.GetText()+_T("\r\n")+str+_T("\r\n"));
2031 void CCommitDlg::OnBnClickedCommitAmend()
2033 this->UpdateData();
2034 if(this->m_bCommitAmend && this->m_AmendStr.IsEmpty())
2036 GitRev rev;
2037 rev.GetCommit(CString(_T("HEAD")));
2038 m_AmendStr=rev.GetSubject()+_T("\n")+rev.GetBody();
2041 if(this->m_bCommitAmend)
2043 this->m_NoAmendStr=this->m_cLogMessage.GetText();
2044 m_cLogMessage.SetText(m_AmendStr);
2045 GetDlgItem(IDC_COMMIT_AMENDDIFF)->ShowWindow(SW_SHOW);
2047 else
2049 this->m_AmendStr=this->m_cLogMessage.GetText();
2050 m_cLogMessage.SetText(m_NoAmendStr);
2051 GetDlgItem(IDC_COMMIT_AMENDDIFF)->ShowWindow(SW_HIDE);
2054 OnBnClickedCommitSetDateTime(); // to update the commit date and time
2056 Refresh();
2059 void CCommitDlg::OnBnClickedWholeProject()
2061 m_tooltips.Pop(); // hide the tooltips
2062 UpdateData();
2063 m_ListCtrl.Clear();
2064 if (!m_bBlock)
2066 if(m_bWholeProject)
2067 m_ListCtrl.GetStatus(NULL,true,false,true);
2068 else
2069 m_ListCtrl.GetStatus(&this->m_pathList,true,false,true);
2071 DWORD dwShow = m_ListCtrl.GetShowFlags();
2072 if (DWORD(m_regAddBeforeCommit))
2073 dwShow |= GITSLC_SHOWUNVERSIONED;
2074 else
2075 dwShow &= ~GITSLC_SHOWUNVERSIONED;
2077 m_ListCtrl.Show(dwShow, dwShow & ~(CTGitPath::LOGACTIONS_UNVER), true);
2080 SetDlgTitle();
2083 void CCommitDlg::OnFocusMessage()
2085 m_cLogMessage.SetFocus();
2088 void CCommitDlg::OnScnUpdateUI(NMHDR *pNMHDR, LRESULT *pResult)
2090 UNREFERENCED_PARAMETER(pNMHDR);
2091 int pos=this->m_cLogMessage.Call(SCI_GETCURRENTPOS);
2092 int line=this->m_cLogMessage.Call(SCI_LINEFROMPOSITION,pos);
2093 int column=this->m_cLogMessage.Call(SCI_GETCOLUMN,pos);
2095 CString str;
2096 str.Format(_T("%d/%d"),line+1,column+1);
2097 this->GetDlgItem(IDC_TEXT_INFO)->SetWindowText(str);
2099 if(*pResult)
2100 *pResult=0;
2102 void CCommitDlg::OnStnClickedViewPatch()
2104 m_patchViewdlg.m_pProjectProperties = &this->m_ProjectProperties;
2105 m_patchViewdlg.m_ParentCommitDlg = this;
2106 if(!IsWindow(this->m_patchViewdlg.m_hWnd))
2108 BOOL viewPatchEnabled = FALSE;
2109 m_ProjectProperties.GetBOOLProps(viewPatchEnabled, _T("tgit.commitshowpatch"));
2110 if (viewPatchEnabled == FALSE)
2111 g_Git.SetConfigValue(_T("tgit.commitshowpatch"), _T("true"));
2112 m_patchViewdlg.Create(IDD_PATCH_VIEW,this);
2113 m_patchViewdlg.m_ctrlPatchView.Call(SCI_SETSCROLLWIDTHTRACKING, TRUE);
2114 CRect rect;
2115 this->GetWindowRect(&rect);
2117 m_patchViewdlg.ShowWindow(SW_SHOW);
2119 m_patchViewdlg.SetWindowPos(NULL,rect.right,rect.top,rect.Width(),rect.Height(),
2120 SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
2122 ShowViewPatchText(false);
2123 FillPatchView();
2125 else
2127 g_Git.SetConfigValue(_T("tgit.commitshowpatch"), _T("false"));
2128 m_patchViewdlg.ShowWindow(SW_HIDE);
2129 m_patchViewdlg.DestroyWindow();
2130 ShowViewPatchText(true);
2132 this->m_ctrlShowPatch.Invalidate();
2135 void CCommitDlg::OnMoving(UINT fwSide, LPRECT pRect)
2137 __super::OnMoving(fwSide, pRect);
2139 if (::IsWindow(m_patchViewdlg.m_hWnd))
2141 RECT patchrect;
2142 m_patchViewdlg.GetWindowRect(&patchrect);
2143 if (::IsWindow(m_hWnd))
2145 RECT thisrect;
2146 GetWindowRect(&thisrect);
2147 if (patchrect.left == thisrect.right)
2149 m_patchViewdlg.SetWindowPos(NULL, patchrect.left - (thisrect.left - pRect->left), patchrect.top - (thisrect.top - pRect->top),
2150 0, 0, SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOSIZE | SWP_NOZORDER);
2157 void CCommitDlg::OnSizing(UINT fwSide, LPRECT pRect)
2159 __super::OnSizing(fwSide, pRect);
2161 if(::IsWindow(this->m_patchViewdlg.m_hWnd))
2163 CRect thisrect, patchrect;
2164 this->GetWindowRect(thisrect);
2165 this->m_patchViewdlg.GetWindowRect(patchrect);
2166 if(thisrect.right==patchrect.left)
2168 patchrect.left -= (thisrect.right - pRect->right);
2169 patchrect.right-= (thisrect.right - pRect->right);
2171 if( patchrect.bottom == thisrect.bottom)
2173 patchrect.bottom -= (thisrect.bottom - pRect->bottom);
2175 if( patchrect.top == thisrect.top)
2177 patchrect.top -= thisrect.top-pRect->top;
2179 m_patchViewdlg.MoveWindow(patchrect);
2184 void CCommitDlg::OnHdnItemchangedFilelist(NMHDR *pNMHDR, LRESULT *pResult)
2186 UNREFERENCED_PARAMETER(pNMHDR);
2187 *pResult = 0;
2188 TRACE("Item Changed\r\n");
2191 int CCommitDlg::CheckHeadDetach()
2193 CString output;
2194 if(g_Git.GetCurrentBranchFromFile(g_Git.m_CurrentDir,output))
2196 int retval = CMessageBox::Show(NULL, IDS_PROC_COMMIT_DETACHEDWARNING, IDS_APPNAME, MB_YESNOCANCEL | MB_ICONWARNING);
2197 if(retval == IDYES)
2199 if (CAppUtils::CreateBranchTag(FALSE, NULL, true) == FALSE)
2200 return 1;
2202 else if (retval == IDCANCEL)
2203 return 1;
2205 return 0;
2208 void CCommitDlg::OnBnClickedCommitAmenddiff()
2210 UpdateData();
2211 Refresh();
2214 void CCommitDlg::OnBnClickedNoautoselectsubmodules()
2216 UpdateData();
2217 Refresh();
2220 void CCommitDlg::OnBnClickedCommitSetDateTime()
2222 UpdateData();
2224 if (m_bSetCommitDateTime)
2226 CTime authordate = CTime::GetCurrentTime();
2227 if (m_bCommitAmend)
2229 GitRev headRevision;
2230 headRevision.GetCommit(_T("HEAD"));
2231 authordate = headRevision.GetAuthorDate();
2234 m_CommitDate.SetTime(&authordate);
2235 m_CommitTime.SetTime(&authordate);
2237 GetDlgItem(IDC_COMMIT_DATEPICKER)->ShowWindow(SW_SHOW);
2238 GetDlgItem(IDC_COMMIT_TIMEPICKER)->ShowWindow(SW_SHOW);
2240 else
2242 GetDlgItem(IDC_COMMIT_DATEPICKER)->ShowWindow(SW_HIDE);
2243 GetDlgItem(IDC_COMMIT_TIMEPICKER)->ShowWindow(SW_HIDE);
2247 void CCommitDlg::OnBnClickedCheckNewBranch()
2249 UpdateData();
2250 if (m_bCreateNewBranch)
2252 GetDlgItem(IDC_COMMIT_TO)->ShowWindow(SW_HIDE);
2253 GetDlgItem(IDC_NEWBRANCH)->ShowWindow(SW_SHOW);
2255 else
2257 GetDlgItem(IDC_NEWBRANCH)->ShowWindow(SW_HIDE);
2258 GetDlgItem(IDC_COMMIT_TO)->ShowWindow(SW_SHOW);
2262 void CCommitDlg::RestoreFiles(bool doNotAsk)
2264 if (m_ListCtrl.m_restorepaths.size() && (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))
2266 for (std::map<CString, CString>::iterator it = m_ListCtrl.m_restorepaths.begin(); it != m_ListCtrl.m_restorepaths.end(); ++it)
2267 CopyFile(it->second, g_Git.m_CurrentDir + _T("\\") + it->first, FALSE);
2268 m_ListCtrl.m_restorepaths.clear();