deduplicate code
[TortoiseGit.git] / src / TortoiseProc / CommitDlg.cpp
blob8f36cd196296dd6fbebdd5fc979467e5d5ec6952
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 "CommonResource.h"
35 #include "UnicodeUtils.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"
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"));
52 IMPLEMENT_DYNAMIC(CCommitDlg, CResizableStandAloneDialog)
53 CCommitDlg::CCommitDlg(CWnd* pParent /*=NULL*/)
54 : CResizableStandAloneDialog(CCommitDlg::IDD, pParent)
55 , m_bRecursive(FALSE)
56 , m_bShowUnversioned(FALSE)
57 , m_bBlock(FALSE)
58 , m_bThreadRunning(FALSE)
59 , m_bRunThread(FALSE)
60 , m_pThread(NULL)
61 , m_bWholeProject(FALSE)
62 , m_bKeepChangeList(TRUE)
63 , m_bDoNotAutoselectSubmodules(FALSE)
64 , m_itemsCount(0)
65 , m_bSelectFilesForCommit(TRUE)
66 , m_bNoPostActions(FALSE)
67 , m_bAutoClose(false)
68 , m_bSetCommitDateTime(FALSE)
70 this->m_bCommitAmend=FALSE;
71 m_bPushAfterCommit = FALSE;
74 CCommitDlg::~CCommitDlg()
76 if(m_pThread != NULL)
78 delete m_pThread;
82 void CCommitDlg::DoDataExchange(CDataExchange* pDX)
84 CResizableStandAloneDialog::DoDataExchange(pDX);
85 DDX_Control(pDX, IDC_FILELIST, m_ListCtrl);
86 DDX_Control(pDX, IDC_LOGMESSAGE, m_cLogMessage);
87 DDX_Check(pDX, IDC_SHOWUNVERSIONED, m_bShowUnversioned);
88 DDX_Check(pDX, IDC_COMMIT_SETDATETIME, m_bSetCommitDateTime);
89 DDX_Control(pDX, IDC_SELECTALL, m_SelectAll);
90 DDX_Text(pDX, IDC_BUGID, m_sBugID);
91 DDX_Check(pDX, IDC_WHOLE_PROJECT, m_bWholeProject);
92 DDX_Control(pDX, IDC_SPLITTER, m_wndSplitter);
93 DDX_Check(pDX, IDC_KEEPLISTS, m_bKeepChangeList);
94 DDX_Check(pDX, IDC_NOAUTOSELECTSUBMODULES, m_bDoNotAutoselectSubmodules);
95 DDX_Check(pDX,IDC_COMMIT_AMEND,m_bCommitAmend);
96 DDX_Check(pDX,IDC_COMMIT_AMENDDIFF,m_bAmendDiffToLastCommit);
97 DDX_Control(pDX,IDC_VIEW_PATCH,m_ctrlShowPatch);
98 DDX_Control(pDX, IDC_COMMIT_DATEPICKER, m_CommitDate);
99 DDX_Control(pDX, IDC_COMMIT_TIMEPICKER, m_CommitTime);
102 BEGIN_MESSAGE_MAP(CCommitDlg, CResizableStandAloneDialog)
103 ON_BN_CLICKED(IDC_SELECTALL, OnBnClickedSelectall)
104 ON_BN_CLICKED(IDHELP, OnBnClickedHelp)
105 ON_BN_CLICKED(IDC_SHOWUNVERSIONED, OnBnClickedShowunversioned)
106 ON_NOTIFY(SCN_UPDATEUI, IDC_LOGMESSAGE, OnScnUpdateUI)
107 // ON_BN_CLICKED(IDC_HISTORY, OnBnClickedHistory)
108 ON_BN_CLICKED(IDC_BUGTRAQBUTTON, OnBnClickedBugtraqbutton)
109 ON_EN_CHANGE(IDC_LOGMESSAGE, OnEnChangeLogmessage)
110 ON_REGISTERED_MESSAGE(CGitStatusListCtrl::GITSLNM_ITEMCOUNTCHANGED, OnGitStatusListCtrlItemCountChanged)
111 ON_REGISTERED_MESSAGE(CGitStatusListCtrl::GITSLNM_NEEDSREFRESH, OnGitStatusListCtrlNeedsRefresh)
112 ON_REGISTERED_MESSAGE(CGitStatusListCtrl::GITSLNM_ADDFILE, OnFileDropped)
113 ON_REGISTERED_MESSAGE(CGitStatusListCtrl::GITSLNM_CHECKCHANGED, &CCommitDlg::OnGitStatusListCtrlCheckChanged)
114 ON_REGISTERED_MESSAGE(CGitStatusListCtrl::GITSLNM_ITEMCHANGED, &CCommitDlg::OnGitStatusListCtrlItemChanged)
116 ON_REGISTERED_MESSAGE(WM_AUTOLISTREADY, OnAutoListReady)
117 ON_WM_TIMER()
118 ON_WM_SIZE()
119 ON_STN_CLICKED(IDC_EXTERNALWARNING, &CCommitDlg::OnStnClickedExternalwarning)
120 ON_BN_CLICKED(IDC_SIGNOFF, &CCommitDlg::OnBnClickedSignOff)
121 ON_BN_CLICKED(IDC_COMMIT_AMEND, &CCommitDlg::OnBnClickedCommitAmend)
122 ON_BN_CLICKED(IDC_WHOLE_PROJECT, &CCommitDlg::OnBnClickedWholeProject)
123 ON_COMMAND(ID_FOCUS_MESSAGE,&CCommitDlg::OnFocusMessage)
124 ON_STN_CLICKED(IDC_VIEW_PATCH, &CCommitDlg::OnStnClickedViewPatch)
125 ON_WM_MOVE()
126 ON_WM_MOVING()
127 ON_WM_SIZING()
128 ON_NOTIFY(HDN_ITEMCHANGED, 0, &CCommitDlg::OnHdnItemchangedFilelist)
129 ON_BN_CLICKED(IDC_COMMIT_AMENDDIFF, &CCommitDlg::OnBnClickedCommitAmenddiff)
130 ON_BN_CLICKED(IDC_NOAUTOSELECTSUBMODULES, &CCommitDlg::OnBnClickedNoautoselectsubmodules)
131 ON_BN_CLICKED(IDC_COMMIT_SETDATETIME, &CCommitDlg::OnBnClickedCommitSetDateTime)
132 END_MESSAGE_MAP()
134 BOOL CCommitDlg::OnInitDialog()
136 CResizableStandAloneDialog::OnInitDialog();
137 CAppUtils::MarkWindowAsUnpinnable(m_hWnd);
139 CAppUtils::GetCommitTemplate(this->m_sLogMessage);
141 CString dotGitPath;
142 g_GitAdminDir.GetAdminDirPath(g_Git.m_CurrentDir, dotGitPath);
143 if(PathFileExists(dotGitPath + _T("MERGE_MSG")))
145 CStdioFile file;
146 if(file.Open(dotGitPath + _T("MERGE_MSG"), CFile::modeRead))
148 CString str;
149 while(file.ReadString(str))
151 m_sLogMessage += str;
152 str.Empty();
153 m_sLogMessage += _T("\n");
157 m_regAddBeforeCommit = CRegDWORD(_T("Software\\TortoiseGit\\AddBeforeCommit"), TRUE);
158 m_bShowUnversioned = m_regAddBeforeCommit;
160 m_History.SetMaxHistoryItems((LONG)CRegDWORD(_T("Software\\TortoiseGit\\MaxHistoryItems"), 25));
162 m_regKeepChangelists = CRegDWORD(_T("Software\\TortoiseGit\\KeepChangeLists"), FALSE);
163 m_bKeepChangeList = m_regKeepChangelists;
165 m_regDoNotAutoselectSubmodules = CRegDWORD(_T("Software\\TortoiseGit\\DoNotAutoselectSubmodules"), FALSE);
166 m_bDoNotAutoselectSubmodules = m_regDoNotAutoselectSubmodules;
168 m_hAccel = LoadAccelerators(AfxGetResourceHandle(),MAKEINTRESOURCE(IDR_ACC_COMMITDLG));
170 // GitConfig config;
171 // m_bWholeProject = config.KeepLocks();
173 if(this->m_pathList.GetCount() == 0)
174 m_bWholeProject =true;
176 if(this->m_pathList.GetCount() == 1 && m_pathList[0].IsEmpty())
177 m_bWholeProject =true;
179 SetDlgTitle();
181 UpdateData(FALSE);
183 m_ListCtrl.Init(GITSLC_COLEXT | GITSLC_COLSTATUS | GITSLC_COLADD |GITSLC_COLDEL, _T("CommitDlg"),(GITSLC_POPALL ^ (GITSLC_POPCOMMIT | GITSLC_POPSAVEAS)));
184 m_ListCtrl.SetSelectButton(&m_SelectAll);
185 m_ListCtrl.SetStatLabel(GetDlgItem(IDC_STATISTICS));
186 m_ListCtrl.SetCancelBool(&m_bCancelled);
187 m_ListCtrl.SetEmptyString(IDS_COMMITDLG_NOTHINGTOCOMMIT);
188 m_ListCtrl.EnableFileDrop();
189 m_ListCtrl.SetBackgroundImage(IDI_COMMIT_BKG);
191 //this->DialogEnableWindow(IDC_COMMIT_AMEND,FALSE);
192 m_ProjectProperties.ReadPropsPathList(m_pathList);
194 m_cLogMessage.Init(m_ProjectProperties);
195 m_cLogMessage.SetFont((CString)CRegString(_T("Software\\TortoiseGit\\LogFontName"), _T("Courier New")), (DWORD)CRegDWORD(_T("Software\\TortoiseGit\\LogFontSize"), 8));
196 m_cLogMessage.RegisterContextMenuHandler(this);
198 OnEnChangeLogmessage();
200 m_tooltips.Create(this);
201 m_tooltips.AddTool(IDC_EXTERNALWARNING, IDS_COMMITDLG_EXTERNALS);
202 m_tooltips.AddTool(IDC_COMMIT_AMEND,IDS_COMMIT_AMEND_TT);
203 // m_tooltips.AddTool(IDC_HISTORY, IDS_COMMITDLG_HISTORY_TT);
205 m_SelectAll.SetCheck(BST_INDETERMINATE);
207 CBugTraqAssociations bugtraq_associations;
208 bugtraq_associations.Load();
210 if (bugtraq_associations.FindProvider(g_Git.m_CurrentDir, &m_bugtraq_association))
212 GetDlgItem(IDC_BUGID)->ShowWindow(SW_HIDE);
213 GetDlgItem(IDC_BUGIDLABEL)->ShowWindow(SW_HIDE);
215 CComPtr<IBugTraqProvider> pProvider;
216 HRESULT hr = pProvider.CoCreateInstance(m_bugtraq_association.GetProviderClass());
217 if (SUCCEEDED(hr))
219 m_BugTraqProvider = pProvider;
220 BSTR temp = NULL;
221 if (SUCCEEDED(hr = pProvider->GetLinkText(GetSafeHwnd(), m_bugtraq_association.GetParameters().AllocSysString(), &temp)))
223 SetDlgItemText(IDC_BUGTRAQBUTTON, temp);
224 GetDlgItem(IDC_BUGTRAQBUTTON)->EnableWindow(TRUE);
225 GetDlgItem(IDC_BUGTRAQBUTTON)->ShowWindow(SW_SHOW);
228 SysFreeString(temp);
231 GetDlgItem(IDC_LOGMESSAGE)->SetFocus();
233 else if (!m_ProjectProperties.sMessage.IsEmpty())
235 GetDlgItem(IDC_BUGID)->ShowWindow(SW_SHOW);
236 GetDlgItem(IDC_BUGIDLABEL)->ShowWindow(SW_SHOW);
237 if (!m_ProjectProperties.sLabel.IsEmpty())
238 SetDlgItemText(IDC_BUGIDLABEL, m_ProjectProperties.sLabel);
239 GetDlgItem(IDC_BUGTRAQBUTTON)->ShowWindow(SW_HIDE);
240 GetDlgItem(IDC_BUGTRAQBUTTON)->EnableWindow(FALSE);
241 GetDlgItem(IDC_BUGID)->SetFocus();
242 CString sBugID = m_ProjectProperties.GetBugIDFromLog(m_sLogMessage);
243 if (!sBugID.IsEmpty())
245 SetDlgItemText(IDC_BUGID, sBugID);
248 else
250 GetDlgItem(IDC_BUGID)->ShowWindow(SW_HIDE);
251 GetDlgItem(IDC_BUGIDLABEL)->ShowWindow(SW_HIDE);
252 GetDlgItem(IDC_BUGTRAQBUTTON)->ShowWindow(SW_HIDE);
253 GetDlgItem(IDC_BUGTRAQBUTTON)->EnableWindow(FALSE);
254 GetDlgItem(IDC_LOGMESSAGE)->SetFocus();
257 if (!m_sLogMessage.IsEmpty())
258 m_cLogMessage.SetText(m_sLogMessage);
260 GetWindowText(m_sWindowTitle);
262 AdjustControlSize(IDC_SHOWUNVERSIONED);
263 AdjustControlSize(IDC_SELECTALL);
264 AdjustControlSize(IDC_WHOLE_PROJECT);
266 GetClientRect(m_DlgOrigRect);
267 m_cLogMessage.GetClientRect(m_LogMsgOrigRect);
269 AddAnchor(IDC_COMMITLABEL, TOP_LEFT, TOP_RIGHT);
270 AddAnchor(IDC_BUGIDLABEL, TOP_RIGHT);
271 AddAnchor(IDC_BUGID, TOP_RIGHT);
272 AddAnchor(IDC_BUGTRAQBUTTON, TOP_RIGHT);
273 AddAnchor(IDC_COMMIT_TO, TOP_LEFT, TOP_RIGHT);
274 AddAnchor(IDC_MESSAGEGROUP, TOP_LEFT, TOP_RIGHT);
275 // AddAnchor(IDC_HISTORY, TOP_LEFT);
276 AddAnchor(IDC_LOGMESSAGE, TOP_LEFT, TOP_RIGHT);
277 AddAnchor(IDC_SIGNOFF, TOP_RIGHT);
278 AddAnchor(IDC_VIEW_PATCH, BOTTOM_RIGHT);
279 AddAnchor(IDC_LISTGROUP, TOP_LEFT, BOTTOM_RIGHT);
280 AddAnchor(IDC_SPLITTER, TOP_LEFT, TOP_RIGHT);
281 AddAnchor(IDC_FILELIST, TOP_LEFT, BOTTOM_RIGHT);
282 AddAnchor(IDC_SHOWUNVERSIONED, BOTTOM_LEFT);
283 AddAnchor(IDC_SELECTALL, BOTTOM_LEFT);
284 AddAnchor(IDC_EXTERNALWARNING, BOTTOM_RIGHT);
285 AddAnchor(IDC_STATISTICS, BOTTOM_LEFT, BOTTOM_RIGHT);
286 AddAnchor(IDC_TEXT_INFO, TOP_RIGHT);
287 AddAnchor(IDC_WHOLE_PROJECT, BOTTOM_LEFT);
288 AddAnchor(IDC_KEEPLISTS, BOTTOM_LEFT);
289 AddAnchor(IDC_NOAUTOSELECTSUBMODULES, BOTTOM_LEFT);
290 AddAnchor(IDOK, BOTTOM_RIGHT);
291 AddAnchor(IDCANCEL, BOTTOM_RIGHT);
292 AddAnchor(IDHELP, BOTTOM_RIGHT);
293 AddAnchor(IDC_COMMIT_AMEND,TOP_LEFT);
294 AddAnchor(IDC_COMMIT_AMENDDIFF,TOP_LEFT);
295 AddAnchor(IDC_COMMIT_SETDATETIME,TOP_LEFT);
296 AddAnchor(IDC_COMMIT_DATEPICKER,TOP_LEFT);
297 AddAnchor(IDC_COMMIT_TIMEPICKER,TOP_LEFT);
299 if (hWndExplorer)
300 CenterWindow(CWnd::FromHandle(hWndExplorer));
301 EnableSaveRestore(_T("CommitDlg"));
302 DWORD yPos = CRegDWORD(_T("Software\\TortoiseGit\\TortoiseProc\\ResizableState\\CommitDlgSizer"));
303 RECT rcDlg, rcLogMsg, rcFileList;
304 GetClientRect(&rcDlg);
305 m_cLogMessage.GetWindowRect(&rcLogMsg);
306 ScreenToClient(&rcLogMsg);
307 m_ListCtrl.GetWindowRect(&rcFileList);
308 ScreenToClient(&rcFileList);
309 if (yPos)
311 RECT rectSplitter;
312 m_wndSplitter.GetWindowRect(&rectSplitter);
313 ScreenToClient(&rectSplitter);
314 int delta = yPos - rectSplitter.top;
315 if ((rcLogMsg.bottom + delta > rcLogMsg.top)&&(rcLogMsg.bottom + delta < rcFileList.bottom - 30))
317 m_wndSplitter.SetWindowPos(NULL, 0, yPos, 0, 0, SWP_NOSIZE);
318 DoSize(delta);
322 // add all directories to the watcher
324 for (int i=0; i<m_pathList.GetCount(); ++i)
326 if (m_pathList[i].IsDirectory())
327 m_pathwatcher.AddPath(m_pathList[i]);
330 m_updatedPathList = m_pathList;
332 //first start a thread to obtain the file list with the status without
333 //blocking the dialog
334 InterlockedExchange(&m_bBlock, TRUE);
335 m_pThread = AfxBeginThread(StatusThreadEntry, this, THREAD_PRIORITY_NORMAL,0,CREATE_SUSPENDED);
336 if (m_pThread==NULL)
338 CMessageBox::Show(this->m_hWnd, IDS_ERR_THREADSTARTFAILED, IDS_APPNAME, MB_OK | MB_ICONERROR);
339 InterlockedExchange(&m_bBlock, FALSE);
341 else
343 m_pThread->m_bAutoDelete = FALSE;
344 m_pThread->ResumeThread();
346 CRegDWORD err = CRegDWORD(_T("Software\\TortoiseGit\\ErrorOccurred"), FALSE);
347 CRegDWORD historyhint = CRegDWORD(_T("Software\\TortoiseGit\\HistoryHintShown"), FALSE);
348 if ((((DWORD)err)!=FALSE)&&((((DWORD)historyhint)==FALSE)))
350 historyhint = TRUE;
351 // ShowBalloon(IDC_HISTORY, IDS_COMMITDLG_HISTORYHINT_TT, IDI_INFORMATION);
353 err = FALSE;
355 if (g_Git.IsInitRepos())
357 m_bCommitAmend = FALSE;
358 GetDlgItem(IDC_COMMIT_AMEND)->EnableWindow(FALSE);
359 UpdateData(FALSE);
361 else
363 if(m_bCommitAmend)
365 GetDlgItem(IDC_COMMIT_AMEND)->EnableWindow(FALSE);
366 GetDlgItem(IDC_COMMIT_AMENDDIFF)->ShowWindow(SW_SHOW);
369 CGitHash hash = g_Git.GetHash(_T("HEAD"));
370 GitRev headRevision;
371 headRevision.GetParentFromHash(hash);
372 // do not allow to show diff to "last" revision if it has more that one parent
373 if (headRevision.ParentsCount() != 1)
375 m_bAmendDiffToLastCommit = true;
376 UpdateData(FALSE);
377 GetDlgItem(IDC_COMMIT_AMENDDIFF)->EnableWindow(FALSE);
381 this->m_ctrlShowPatch.SetURL(CString());
383 BOOL viewPatchEnabled = FALSE;
384 m_ProjectProperties.GetBOOLProps(viewPatchEnabled, _T("tgit.commitshowpatch"));
385 if (viewPatchEnabled)
386 OnStnClickedViewPatch();
388 return FALSE; // return TRUE unless you set the focus to a control
389 // EXCEPTION: OCX Property Pages should return FALSE
392 void CCommitDlg::OnOK()
394 if (m_bBlock)
395 return;
396 if (m_bThreadRunning)
398 m_bCancelled = true;
399 InterlockedExchange(&m_bRunThread, FALSE);
400 WaitForSingleObject(m_pThread->m_hThread, 1000);
401 if (m_bThreadRunning)
403 // we gave the thread a chance to quit. Since the thread didn't
404 // listen to us we have to kill it.
405 TerminateThread(m_pThread->m_hThread, (DWORD)-1);
406 InterlockedExchange(&m_bThreadRunning, FALSE);
409 this->UpdateData();
411 CString id;
412 GetDlgItemText(IDC_BUGID, id);
413 if (!m_ProjectProperties.CheckBugID(id))
415 ShowEditBalloon(IDC_BUGID, IDS_COMMITDLG_ONLYNUMBERS, TTI_ERROR);
416 return;
418 m_sLogMessage = m_cLogMessage.GetText();
419 if ( m_sLogMessage.IsEmpty() )
421 // no message entered, go round again
422 CMessageBox::Show(this->m_hWnd, IDS_COMMITDLG_NOMESSAGE, IDS_APPNAME, MB_OK | MB_ICONERROR);
423 return;
425 if ((m_ProjectProperties.bWarnIfNoIssue) && (id.IsEmpty() && !m_ProjectProperties.HasBugID(m_sLogMessage)))
427 if (CMessageBox::Show(this->m_hWnd, IDS_COMMITDLG_NOISSUEWARNING, IDS_APPNAME, MB_YESNO | MB_ICONWARNING)!=IDYES)
428 return;
431 BOOL bWarnNoSignedOffBy = FALSE;
432 ProjectProperties::GetBOOLProps(bWarnNoSignedOffBy, _T("tgit.warnnosignedoffby"));
433 if (bWarnNoSignedOffBy == TRUE && m_cLogMessage.GetText().Find(GetSignedOffByLine()) == -1)
435 UINT retval = CMessageBox::Show(this->m_hWnd, _T("You haven't entered your Signed-Off-By line!"), _T("TortoiseGit"), 1, IDI_WARNING, _T("&Add it"), _T("&Commit w/o"), _T("A&bort"));
436 if (retval == 1)
438 OnBnClickedSignOff();
439 m_sLogMessage = m_cLogMessage.GetText();
441 else if (retval == 3)
442 return;
445 m_ListCtrl.WriteCheckedNamesToPathList(m_selectedPathList);
446 m_pathwatcher.Stop();
447 InterlockedExchange(&m_bBlock, TRUE);
448 CDWordArray arDeleted;
449 //first add all the unversioned files the user selected
450 //and check if all versioned files are selected
451 int nchecked = 0;
452 m_bRecursive = true;
453 int nListItems = m_ListCtrl.GetItemCount();
455 CTGitPathList itemsToAdd;
456 CTGitPathList itemsToRemove;
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 >= 10 && sysProgressDlg.IsValid())
510 sysProgressDlg.SetTitle(_T("Preparing commit..."));
511 sysProgressDlg.SetLine(1, _T("Updating index"));
512 sysProgressDlg.SetTime(true);
513 sysProgressDlg.SetShowProgressBar(true);
514 sysProgressDlg.ShowModal(this, true);
517 for (int j=0; j<nListItems; j++)
519 CTGitPath *entry = (CTGitPath*)m_ListCtrl.GetItemData(j);
520 if (sysProgressDlg.IsValid())
522 sysProgressDlg.SetLine(2, entry->GetGitPathString(), true);
523 sysProgressDlg.SetProgress(j, nListItems);
524 AfxGetThread()->PumpMessage(); // process messages, in order to avoid freezing
526 //const CGitStatusListCtrl::FileEntry * entry = m_ListCtrl.GetListEntry(j);
527 if (entry->m_Checked)
529 #if 0
530 if (entry->status == Git_wc_status_unversioned)
532 itemsToAdd.AddPath(entry->GetPath());
534 if (entry->status == Git_wc_status_conflicted)
536 bHasConflicted = true;
538 if (entry->status == Git_wc_status_missing)
540 itemsToRemove.AddPath(entry->GetPath());
542 if (entry->status == Git_wc_status_deleted)
544 arDeleted.Add(j);
546 if (entry->IsInExternal())
548 bCheckedInExternal = true;
550 #endif
551 if( entry->m_Action & CTGitPath::LOGACTIONS_UNVER)
552 cmd.Format(_T("git.exe add -f -- \"%s\""),entry->GetGitPathString());
553 else if ( entry->m_Action & CTGitPath::LOGACTIONS_DELETED)
554 cmd.Format(_T("git.exe update-index --force-remove -- \"%s\""),entry->GetGitPathString());
555 else
556 cmd.Format(_T("git.exe update-index -- \"%s\""),entry->GetGitPathString());
558 if(g_Git.Run(cmd,&out,CP_ACP))
560 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
561 bAddSuccess = false ;
562 break;
565 if( entry->m_Action & CTGitPath::LOGACTIONS_REPLACED)
566 cmd.Format(_T("git.exe rm -- \"%s\""), entry->GetGitOldPathString());
568 g_Git.Run(cmd,&out,CP_ACP);
570 nchecked++;
572 //checkedLists.insert(entry->GetGitPathString());
573 // checkedfiles += _T("\"")+entry->GetGitPathString()+_T("\" ");
575 else
577 //uncheckedLists.insert(entry->GetGitPathString());
578 if(entry->m_Action & CTGitPath::LOGACTIONS_ADDED)
579 { //To init git repository, there are not HEAD, so we can use git reset command
580 cmd.Format(_T("git.exe rm -f --cache -- \"%s\""),entry->GetGitPathString());
581 if(g_Git.Run(cmd,&out,CP_ACP))
583 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
584 bAddSuccess = false ;
585 bCloseCommitDlg=false;
586 break;
590 else if(!( entry->m_Action & CTGitPath::LOGACTIONS_UNVER ) )
592 if (m_bCommitAmend && !m_bAmendDiffToLastCommit)
594 cmd.Format(_T("git.exe reset HEAD~2 -- \"%s\""), entry->GetGitPathString());
596 else
598 cmd.Format(_T("git.exe reset -- \"%s\""), entry->GetGitPathString());
600 if(g_Git.Run(cmd,&out,CP_ACP))
602 /* when reset a unstage file will report error.
603 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
604 bAddSuccess = false ;
605 bCloseCommitDlg=false;
606 break;
609 // && !entry->IsDirectory()
610 if (m_bCommitAmend && !m_bAmendDiffToLastCommit)
611 continue;
614 // uncheckedfiles += _T("\"")+entry->GetGitPathString()+_T("\" ");
615 #if 0
616 if ((entry->status != Git_wc_status_unversioned) &&
617 (entry->status != Git_wc_status_ignored))
619 nUnchecked++;
620 uncheckedLists.insert(entry->GetChangeList());
621 if (m_bRecursive)
623 // This algorithm is for the sake of simplicity of the complexity O(N?
624 for (int k=0; k<nListItems; k++)
626 const CGitStatusListCtrl::FileEntry * entryK = m_ListCtrl.GetListEntry(k);
627 if (entryK->IsChecked() && entryK->GetPath().IsAncestorOf(entry->GetPath()) )
629 // Fall back to a non-recursive commit to prevent items being
630 // committed which aren't checked although its parent is checked
631 // (property change, directory deletion, ... )
632 m_bRecursive = false;
633 break;
638 #endif
641 if (sysProgressDlg.IsValid() && sysProgressDlg.HasUserCancelled())
643 bAddSuccess = false;
644 break;
647 CShellUpdater::Instance().AddPathForUpdate(*entry);
650 if (sysProgressDlg.IsValid())
651 sysProgressDlg.Stop();
653 //if(uncheckedfiles.GetLength()>0)
655 // cmd.Format(_T("git.exe reset -- %s"),uncheckedfiles);
656 // g_Git.Run(cmd,&out);
659 m_sBugID.Trim();
660 if (!m_sBugID.IsEmpty())
662 m_sBugID.Replace(_T(", "), _T(","));
663 m_sBugID.Replace(_T(" ,"), _T(","));
664 CString sBugID = m_ProjectProperties.sMessage;
665 sBugID.Replace(_T("%BUGID%"), m_sBugID);
666 if (m_ProjectProperties.bAppend)
667 m_sLogMessage += _T("\n") + sBugID + _T("\n");
668 else
669 m_sLogMessage = sBugID + _T("\n") + m_sLogMessage;
672 //if(checkedfiles.GetLength()>0)
673 if (bAddSuccess && (nchecked || m_bCommitAmend || CTGitPath(g_Git.m_CurrentDir).IsMergeActive()))
675 // cmd.Format(_T("git.exe update-index -- %s"),checkedfiles);
676 // g_Git.Run(cmd,&out);
678 bCloseCommitDlg = true;
680 CString tempfile=::GetTempFile();
682 CAppUtils::SaveCommitUnicodeFile(tempfile,m_sLogMessage);
683 //file.WriteString(m_sLogMessage);
685 CTGitPath path=g_Git.m_CurrentDir;
687 BOOL IsGitSVN = path.GetAdminDirMask() & ITEMIS_GITSVN;
689 out =_T("");
690 CString amend;
691 if(this->m_bCommitAmend)
693 amend=_T("--amend");
695 CString dateTime;
696 if (m_bSetCommitDateTime)
698 CTime date, time;
699 m_CommitDate.GetTime(date);
700 m_CommitTime.GetTime(time);
701 dateTime.Format(_T("--date=%sT%s"), date.Format(_T("%Y-%m-%d")), time.Format(_T("%H:%M:%S")));
703 cmd.Format(_T("git.exe commit %s %s -F \"%s\""), dateTime, amend, tempfile);
705 CheckHeadDetach();
707 CCommitProgressDlg progress;
708 progress.m_bBufferAll=true; // improve show speed when there are many file added.
709 progress.m_GitCmd=cmd;
710 progress.m_bShowCommand = FALSE; // don't show the commit command
711 progress.m_PreText = out; // show any output already generated in log window
712 progress.m_bAutoCloseOnSuccess = m_bAutoClose;
714 if (!m_bNoPostActions && !m_bAutoClose)
716 progress.m_PostCmdList.Add( IsGitSVN? _T("&DCommit"): _T("&Push"));
717 progress.m_PostCmdList.Add(_T("&ReCommit"));
720 m_PostCmd = IsGitSVN? GIT_POST_CMD_DCOMMIT:GIT_POST_CMD_PUSH;
722 DWORD userResponse = progress.DoModal();
724 if(progress.m_GitStatus || userResponse == (IDC_PROGRESS_BUTTON1+1))
726 bCloseCommitDlg = false;
727 if( userResponse == (IDC_PROGRESS_BUTTON1+1 ))
729 this->m_sLogMessage.Empty();
730 m_cLogMessage.SetText(m_sLogMessage);
733 this->Refresh();
735 else if(userResponse == IDC_PROGRESS_BUTTON1)
737 //User pressed 'Push' button after successful commit.
738 m_bPushAfterCommit=true;
741 CFile::Remove(tempfile);
743 if (m_BugTraqProvider && progress.m_GitStatus == 0)
745 CComPtr<IBugTraqProvider2> pProvider = NULL;
746 HRESULT hr = m_BugTraqProvider.QueryInterface(&pProvider);
747 if (SUCCEEDED(hr))
749 BSTR commonRoot = SysAllocString(g_Git.m_CurrentDir);
750 SAFEARRAY *pathList = SafeArrayCreateVector(VT_BSTR, 0,this->m_selectedPathList.GetCount());
752 for (LONG index = 0; index < m_selectedPathList.GetCount(); ++index)
753 SafeArrayPutElement(pathList, &index, m_selectedPathList[index].GetGitPathString().AllocSysString());
755 BSTR logMessage = m_sLogMessage.AllocSysString();
757 CGitHash hash=g_Git.GetHash(_T("HEAD"));
758 LONG version = g_Git.Hash2int(hash);
760 BSTR temp = NULL;
761 if (FAILED(hr = pProvider->OnCommitFinished(GetSafeHwnd(),
762 commonRoot,
763 pathList,
764 logMessage,
765 (LONG)version,
766 &temp)))
768 CString sErr = temp;
769 if (!sErr.IsEmpty())
770 CMessageBox::Show(NULL,(sErr),_T("TortoiseGit"),MB_OK|MB_ICONERROR);
771 else
773 COMError ce(hr);
774 sErr.Format(IDS_ERR_FAILEDISSUETRACKERCOM, ce.GetSource().c_str(), ce.GetMessageAndDescription().c_str());
775 CMessageBox::Show(NULL,(sErr),_T("TortoiseGit"),MB_OK|MB_ICONERROR);
779 SysFreeString(temp);
784 else if(bAddSuccess)
786 CMessageBox::Show(this->m_hWnd, IDS_ERROR_NOTHING_COMMIT, IDS_COMMIT_FINISH, MB_OK | MB_ICONINFORMATION);
787 bCloseCommitDlg=false;
789 #if 0
790 if (m_pathwatcher.GetNumberOfChangedPaths() && m_bRecursive)
792 // There are paths which got changed (touched at least).
793 // We have to find out if this affects the selection in the commit dialog
794 // If it could affect the selection, revert back to a non-recursive commit
795 CTGitPathList changedList = m_pathwatcher.GetChangedPaths();
796 changedList.RemoveDuplicates();
797 for (int i=0; i<changedList.GetCount(); ++i)
799 if (changedList[i].IsAdminDir())
801 // something inside an admin dir was changed.
802 // if it's the entries file, then we have to fully refresh because
803 // files may have been added/removed from version control
804 if ((changedList[i].GetWinPathString().Right(7).CompareNoCase(_T("entries")) == 0) &&
805 (changedList[i].GetWinPathString().Find(_T("\\tmp\\"))<0))
807 m_bRecursive = false;
808 break;
811 else if (!m_ListCtrl.IsPathShown(changedList[i]))
813 // a path which is not shown in the list has changed
814 CGitStatusListCtrl::FileEntry * entry = m_ListCtrl.GetListEntry(changedList[i]);
815 if (entry)
817 // check if the changed path would get committed by a recursive commit
818 if ((!entry->IsFromDifferentRepository()) &&
819 (!entry->IsInExternal()) &&
820 (!entry->IsNested()) &&
821 (!entry->IsChecked()))
823 m_bRecursive = false;
824 break;
832 // Now, do all the adds - make sure that the list is sorted so that parents
833 // are added before their children
834 itemsToAdd.SortByPathname();
835 Git Git;
836 if (!Git.Add(itemsToAdd, &m_ProjectProperties, Git_depth_empty, FALSE, FALSE, TRUE))
838 CMessageBox::Show(m_hWnd, Git.GetLastErrorMessage(), _T("TortoiseGit"), MB_ICONERROR);
839 InterlockedExchange(&m_bBlock, FALSE);
840 Refresh();
841 return;
844 // Remove any missing items
845 // Not sure that this sort is really necessary - indeed, it might be better to do a reverse sort at this point
846 itemsToRemove.SortByPathname();
847 Git.Remove(itemsToRemove, TRUE);
849 //the next step: find all deleted files and check if they're
850 //inside a deleted folder. If that's the case, then remove those
851 //files from the list since they'll get deleted by the parent
852 //folder automatically.
853 m_ListCtrl.Block(TRUE, FALSE);
854 INT_PTR nDeleted = arDeleted.GetCount();
855 for (INT_PTR i=0; i<arDeleted.GetCount(); i++)
857 if (m_ListCtrl.GetCheck(arDeleted.GetAt(i)))
859 const CTGitPath& path = m_ListCtrl.GetListEntry(arDeleted.GetAt(i))->GetPath();
860 if (path.IsDirectory())
862 //now find all children of this directory
863 for (int j=0; j<arDeleted.GetCount(); j++)
865 if (i!=j)
867 CGitStatusListCtrl::FileEntry* childEntry = m_ListCtrl.GetListEntry(arDeleted.GetAt(j));
868 if (childEntry->IsChecked())
870 if (path.IsAncestorOf(childEntry->GetPath()))
872 m_ListCtrl.SetEntryCheck(childEntry, arDeleted.GetAt(j), false);
873 nDeleted--;
881 m_ListCtrl.Block(FALSE, FALSE);
883 if ((nUnchecked != 0)||(bCheckedInExternal)||(bHasConflicted)||(!m_bRecursive))
885 //save only the files the user has checked into the temporary file
886 m_ListCtrl.WriteCheckedNamesToPathList(m_pathList);
889 // the item count is used in the progress dialog to show the overall commit
890 // progress.
891 // deleted items only send one notification event, all others send two
892 m_itemsCount = ((m_selectedPathList.GetCount() - nDeleted - itemsToRemove.GetCount()) * 2) + nDeleted + itemsToRemove.GetCount();
894 if ((m_bRecursive)&&(checkedLists.size() == 1))
896 // all checked items belong to the same changelist
897 // find out if there are any unchecked items which belong to that changelist
898 if (uncheckedLists.find(*checkedLists.begin()) == uncheckedLists.end())
899 m_sChangeList = *checkedLists.begin();
901 #endif
902 UpdateData();
903 m_regAddBeforeCommit = m_bShowUnversioned;
904 if (!GetDlgItem(IDC_WHOLE_PROJECT)->IsWindowEnabled())
905 m_bWholeProject = FALSE;
906 m_regKeepChangelists = m_bKeepChangeList;
907 m_regDoNotAutoselectSubmodules = m_bDoNotAutoselectSubmodules;
908 if (!GetDlgItem(IDC_KEEPLISTS)->IsWindowEnabled())
909 m_bKeepChangeList = FALSE;
910 InterlockedExchange(&m_bBlock, FALSE);
912 m_History.AddEntry(m_sLogMessage);
913 m_History.Save();
915 SaveSplitterPos();
917 if( bCloseCommitDlg )
918 CResizableStandAloneDialog::OnOK();
920 CShellUpdater::Instance().Flush();
923 void CCommitDlg::SaveSplitterPos()
925 if (!IsIconic())
927 CRegDWORD regPos = CRegDWORD(_T("Software\\TortoiseGit\\TortoiseProc\\ResizableState\\CommitDlgSizer"));
928 RECT rectSplitter;
929 m_wndSplitter.GetWindowRect(&rectSplitter);
930 ScreenToClient(&rectSplitter);
931 regPos = rectSplitter.top;
935 UINT CCommitDlg::StatusThreadEntry(LPVOID pVoid)
937 return ((CCommitDlg*)pVoid)->StatusThread();
940 UINT CCommitDlg::StatusThread()
942 //get the status of all selected file/folders recursively
943 //and show the ones which have to be committed to the user
944 //in a list control.
945 InterlockedExchange(&m_bBlock, TRUE);
946 InterlockedExchange(&m_bThreadRunning, TRUE);// so the main thread knows that this thread is still running
947 InterlockedExchange(&m_bRunThread, TRUE); // if this is set to FALSE, the thread should stop
949 m_pathwatcher.Stop();
951 g_Git.RefreshGitIndex();
953 m_bCancelled = false;
955 DialogEnableWindow(IDOK, false);
956 DialogEnableWindow(IDC_SHOWUNVERSIONED, false);
957 DialogEnableWindow(IDC_WHOLE_PROJECT, false);
958 DialogEnableWindow(IDC_SELECTALL, false);
959 DialogEnableWindow(IDC_NOAUTOSELECTSUBMODULES, false);
960 GetDlgItem(IDC_EXTERNALWARNING)->ShowWindow(SW_HIDE);
961 DialogEnableWindow(IDC_EXTERNALWARNING, false);
962 // read the list of recent log entries before querying the WC for status
963 // -> the user may select one and modify / update it while we are crawling the WC
965 if (m_History.GetCount()==0)
967 CString reg;
968 reg.Format(_T("Software\\TortoiseGit\\History\\commit%s"), (LPCTSTR)m_ListCtrl.m_sUUID);
969 reg.Replace(_T(':'),_T('_'));
970 m_History.Load(reg, _T("logmsgs"));
973 // Initialise the list control with the status of the files/folders below us
974 m_ListCtrl.Clear();
975 BOOL success;
976 CTGitPathList *pList;
977 m_ListCtrl.m_amend = (m_bCommitAmend==TRUE) && (m_bAmendDiffToLastCommit==FALSE);
978 m_ListCtrl.m_bDoNotAutoselectSubmodules = (m_bDoNotAutoselectSubmodules == TRUE);
980 if(m_bWholeProject)
981 pList=NULL;
982 else
983 pList = &m_pathList;
985 success=m_ListCtrl.GetStatus(pList);
987 //m_ListCtrl.UpdateFileList(git_revnum_t(GIT_REV_ZERO));
988 if(this->m_bShowUnversioned)
989 m_ListCtrl.UpdateFileList(CGitStatusListCtrl::FILELIST_UNVER,true,pList);
991 m_ListCtrl.CheckIfChangelistsArePresent(false);
993 DWORD dwShow = GITSLC_SHOWVERSIONEDBUTNORMALANDEXTERNALSFROMDIFFERENTREPOS | GITSLC_SHOWLOCKS | GITSLC_SHOWINCHANGELIST;
994 dwShow |= DWORD(m_regAddBeforeCommit) ? GITSLC_SHOWUNVERSIONED : 0;
995 if (success)
997 if (m_checkedPathList.GetCount())
998 m_ListCtrl.Show(dwShow, m_checkedPathList);
999 else
1001 DWORD dwCheck = m_bSelectFilesForCommit ? dwShow : 0;
1002 dwCheck &=~(CTGitPath::LOGACTIONS_UNVER); //don't check unversion file default.
1003 m_ListCtrl.Show(dwShow, dwCheck);
1004 m_bSelectFilesForCommit = true;
1007 if (m_ListCtrl.HasExternalsFromDifferentRepos())
1009 GetDlgItem(IDC_EXTERNALWARNING)->ShowWindow(SW_SHOW);
1010 DialogEnableWindow(IDC_EXTERNALWARNING, TRUE);
1013 SetDlgItemText(IDC_COMMIT_TO, g_Git.GetCurrentBranch());
1014 m_tooltips.AddTool(GetDlgItem(IDC_STATISTICS), m_ListCtrl.GetStatisticsString());
1016 if (!success)
1018 if (!m_ListCtrl.GetLastErrorMessage().IsEmpty())
1019 m_ListCtrl.SetEmptyString(m_ListCtrl.GetLastErrorMessage());
1020 m_ListCtrl.Show(dwShow);
1023 if ((m_ListCtrl.GetItemCount()==0)&&(m_ListCtrl.HasUnversionedItems())
1024 && !PathFileExists(g_Git.m_CurrentDir+_T("\\.git\\MERGE_HEAD")))
1026 if (CMessageBox::Show(m_hWnd, IDS_COMMITDLG_NOTHINGTOCOMMITUNVERSIONED, IDS_APPNAME, MB_ICONINFORMATION | MB_YESNO)==IDYES)
1028 m_bShowUnversioned = TRUE;
1029 GetDlgItem(IDC_SHOWUNVERSIONED)->SendMessage(BM_SETCHECK, BST_CHECKED);
1030 DWORD dwShow = (DWORD)(GITSLC_SHOWVERSIONEDBUTNORMALANDEXTERNALSFROMDIFFERENTREPOS | GITSLC_SHOWUNVERSIONED | GITSLC_SHOWLOCKS);
1031 m_ListCtrl.UpdateFileList(CGitStatusListCtrl::FILELIST_UNVER);
1032 m_ListCtrl.Show(dwShow,dwShow&(~CTGitPath::LOGACTIONS_UNVER));
1036 SetDlgTitle();
1038 m_autolist.clear();
1039 // we don't have to block the commit dialog while we fetch the
1040 // auto completion list.
1041 m_pathwatcher.ClearChangedPaths();
1042 InterlockedExchange(&m_bBlock, FALSE);
1043 if ((DWORD)CRegDWORD(_T("Software\\TortoiseGit\\Autocompletion"), TRUE)==TRUE)
1045 m_ListCtrl.Block(TRUE, TRUE);
1046 GetAutocompletionList();
1047 m_ListCtrl.Block(FALSE, FALSE);
1049 UpdateOKButton();
1050 if (m_bRunThread)
1052 DialogEnableWindow(IDC_SHOWUNVERSIONED, true);
1053 DialogEnableWindow(IDC_WHOLE_PROJECT, true);
1054 DialogEnableWindow(IDC_SELECTALL, true);
1055 DialogEnableWindow(IDC_NOAUTOSELECTSUBMODULES, true);
1056 if (m_ListCtrl.HasChangeLists())
1057 DialogEnableWindow(IDC_KEEPLISTS, true);
1058 if (m_ListCtrl.HasLocks())
1059 DialogEnableWindow(IDC_WHOLE_PROJECT, true);
1060 // we have the list, now signal the main thread about it
1061 SendMessage(WM_AUTOLISTREADY); // only send the message if the thread wasn't told to quit!
1064 InterlockedExchange(&m_bRunThread, FALSE);
1065 InterlockedExchange(&m_bThreadRunning, FALSE);
1066 // force the cursor to normal
1067 RefreshCursor();
1069 return 0;
1072 void CCommitDlg::SetDlgTitle()
1074 if (m_sTitle.IsEmpty())
1075 GetWindowText(m_sTitle);
1077 if (m_bWholeProject)
1078 CAppUtils::SetWindowTitle(m_hWnd, g_Git.m_CurrentDir, m_sTitle);
1079 else
1081 if (m_pathList.GetCount() == 1)
1082 CAppUtils::SetWindowTitle(m_hWnd, (g_Git.m_CurrentDir + _T("\\") + m_pathList[0].GetUIPathString()).TrimRight('\\'), m_sTitle);
1083 else
1084 CAppUtils::SetWindowTitle(m_hWnd, g_Git.m_CurrentDir + _T("\\") + m_ListCtrl.GetCommonDirectory(false), m_sTitle);
1088 void CCommitDlg::OnCancel()
1090 m_bCancelled = true;
1091 m_pathwatcher.Stop();
1093 if (m_bBlock)
1094 return;
1096 if (m_bThreadRunning)
1098 InterlockedExchange(&m_bRunThread, FALSE);
1099 WaitForSingleObject(m_pThread->m_hThread, 1000);
1100 if (m_bThreadRunning)
1102 // we gave the thread a chance to quit. Since the thread didn't
1103 // listen to us we have to kill it.
1104 TerminateThread(m_pThread->m_hThread, (DWORD)-1);
1105 InterlockedExchange(&m_bThreadRunning, FALSE);
1108 UpdateData();
1109 m_sBugID.Trim();
1110 m_sLogMessage = m_cLogMessage.GetText();
1111 if (!m_sBugID.IsEmpty())
1113 m_sBugID.Replace(_T(", "), _T(","));
1114 m_sBugID.Replace(_T(" ,"), _T(","));
1115 CString sBugID = m_ProjectProperties.sMessage;
1116 sBugID.Replace(_T("%BUGID%"), m_sBugID);
1117 if (m_ProjectProperties.bAppend)
1118 m_sLogMessage += _T("\n") + sBugID + _T("\n");
1119 else
1120 m_sLogMessage = sBugID + _T("\n") + m_sLogMessage;
1122 if (m_ProjectProperties.sLogTemplate.Compare(m_sLogMessage) != 0)
1123 m_History.AddEntry(m_sLogMessage);
1124 m_History.Save();
1125 SaveSplitterPos();
1126 CResizableStandAloneDialog::OnCancel();
1129 void CCommitDlg::OnBnClickedSelectall()
1131 m_tooltips.Pop(); // hide the tooltips
1132 UINT state = (m_SelectAll.GetState() & 0x0003);
1133 if (state == BST_INDETERMINATE)
1135 // It is not at all useful to manually place the checkbox into the indeterminate state...
1136 // We will force this on to the unchecked state
1137 state = BST_UNCHECKED;
1138 m_SelectAll.SetCheck(state);
1140 m_ListCtrl.SelectAll(state == BST_CHECKED);
1143 BOOL CCommitDlg::PreTranslateMessage(MSG* pMsg)
1145 if (!m_bBlock)
1146 m_tooltips.RelayEvent(pMsg);
1148 if (m_hAccel)
1150 int ret = TranslateAccelerator(m_hWnd, m_hAccel, pMsg);
1151 if (ret)
1152 return TRUE;
1155 if (pMsg->message == WM_KEYDOWN)
1157 switch (pMsg->wParam)
1159 case VK_F5:
1161 if (m_bBlock)
1162 return CResizableStandAloneDialog::PreTranslateMessage(pMsg);
1163 Refresh();
1165 break;
1166 case VK_RETURN:
1168 if (GetAsyncKeyState(VK_CONTROL)&0x8000)
1170 if ( GetDlgItem(IDOK)->IsWindowEnabled() )
1172 PostMessage(WM_COMMAND, IDOK);
1174 return TRUE;
1176 if ( GetFocus()==GetDlgItem(IDC_BUGID) )
1178 // Pressing RETURN in the bug id control
1179 // moves the focus to the message
1180 GetDlgItem(IDC_LOGMESSAGE)->SetFocus();
1181 return TRUE;
1184 break;
1188 return CResizableStandAloneDialog::PreTranslateMessage(pMsg);
1191 void CCommitDlg::Refresh()
1193 if (m_bThreadRunning)
1194 return;
1196 InterlockedExchange(&m_bBlock, TRUE);
1197 m_pThread = AfxBeginThread(StatusThreadEntry, this, THREAD_PRIORITY_NORMAL,0,CREATE_SUSPENDED);
1198 if (m_pThread==NULL)
1200 CMessageBox::Show(this->m_hWnd, IDS_ERR_THREADSTARTFAILED, IDS_APPNAME, MB_OK | MB_ICONERROR);
1201 InterlockedExchange(&m_bBlock, FALSE);
1203 else
1205 m_pThread->m_bAutoDelete = FALSE;
1206 m_pThread->ResumeThread();
1210 void CCommitDlg::OnBnClickedHelp()
1212 OnHelp();
1215 void CCommitDlg::OnBnClickedShowunversioned()
1217 m_tooltips.Pop(); // hide the tooltips
1218 UpdateData();
1219 m_regAddBeforeCommit = m_bShowUnversioned;
1220 if (!m_bBlock)
1222 DWORD dwShow = m_ListCtrl.GetShowFlags();
1223 if (DWORD(m_regAddBeforeCommit))
1224 dwShow |= GITSLC_SHOWUNVERSIONED;
1225 else
1226 dwShow &= ~GITSLC_SHOWUNVERSIONED;
1227 if(dwShow & GITSLC_SHOWUNVERSIONED)
1229 if(m_bWholeProject)
1230 m_ListCtrl.GetStatus(NULL,false,false,true);
1231 else
1232 m_ListCtrl.GetStatus(&this->m_pathList,false,false,true);
1234 m_ListCtrl.Show(dwShow,0,true,0,true);
1238 void CCommitDlg::OnStnClickedExternalwarning()
1240 m_tooltips.Popup();
1243 void CCommitDlg::OnEnChangeLogmessage()
1245 UpdateOKButton();
1248 LRESULT CCommitDlg::OnGitStatusListCtrlItemCountChanged(WPARAM, LPARAM)
1250 #if 0
1251 if ((m_ListCtrl.GetItemCount() == 0)&&(m_ListCtrl.HasUnversionedItems())&&(!m_bShowUnversioned))
1253 if (CMessageBox::Show(*this, IDS_COMMITDLG_NOTHINGTOCOMMITUNVERSIONED, IDS_APPNAME, MB_ICONINFORMATION | MB_YESNO)==IDYES)
1255 m_bShowUnversioned = TRUE;
1256 DWORD dwShow = GitSLC_SHOWVERSIONEDBUTNORMALANDEXTERNALSFROMDIFFERENTREPOS | GitSLC_SHOWUNVERSIONED | GitSLC_SHOWLOCKS;
1257 m_ListCtrl.Show(dwShow);
1258 UpdateData(FALSE);
1261 #endif
1262 return 0;
1265 LRESULT CCommitDlg::OnGitStatusListCtrlNeedsRefresh(WPARAM, LPARAM)
1267 Refresh();
1268 return 0;
1271 LRESULT CCommitDlg::OnFileDropped(WPARAM, LPARAM /*lParam*/)
1273 #if 0
1274 BringWindowToTop();
1275 SetForegroundWindow();
1276 SetActiveWindow();
1277 // if multiple files/folders are dropped
1278 // this handler is called for every single item
1279 // separately.
1280 // To avoid creating multiple refresh threads and
1281 // causing crashes, we only add the items to the
1282 // list control and start a timer.
1283 // When the timer expires, we start the refresh thread,
1284 // but only if it isn't already running - otherwise we
1285 // restart the timer.
1286 CTGitPath path;
1287 path.SetFromWin((LPCTSTR)lParam);
1289 // just add all the items we get here.
1290 // if the item is versioned, the add will fail but nothing
1291 // more will happen.
1292 Git Git;
1293 Git.Add(CTGitPathList(path), &m_ProjectProperties, Git_depth_empty, false, true, true);
1295 if (!m_ListCtrl.HasPath(path))
1297 if (m_pathList.AreAllPathsFiles())
1299 m_pathList.AddPath(path);
1300 m_pathList.RemoveDuplicates();
1301 m_updatedPathList.AddPath(path);
1302 m_updatedPathList.RemoveDuplicates();
1304 else
1306 // if the path list contains folders, we have to check whether
1307 // our just (maybe) added path is a child of one of those. If it is
1308 // a child of a folder already in the list, we must not add it. Otherwise
1309 // that path could show up twice in the list.
1310 bool bHasParentInList = false;
1311 for (int i=0; i<m_pathList.GetCount(); ++i)
1313 if (m_pathList[i].IsAncestorOf(path))
1315 bHasParentInList = true;
1316 break;
1319 if (!bHasParentInList)
1321 m_pathList.AddPath(path);
1322 m_pathList.RemoveDuplicates();
1323 m_updatedPathList.AddPath(path);
1324 m_updatedPathList.RemoveDuplicates();
1329 // Always start the timer, since the status of an existing item might have changed
1330 SetTimer(REFRESHTIMER, 200, NULL);
1331 ATLTRACE(_T("Item %s dropped, timer started\n"), path.GetWinPath());
1332 #endif
1333 return 0;
1336 LRESULT CCommitDlg::OnAutoListReady(WPARAM, LPARAM)
1338 m_cLogMessage.SetAutoCompletionList(m_autolist, '*');
1339 return 0;
1342 //////////////////////////////////////////////////////////////////////////
1343 // functions which run in the status thread
1344 //////////////////////////////////////////////////////////////////////////
1346 void CCommitDlg::ParseRegexFile(const CString& sFile, std::map<CString, CString>& mapRegex)
1348 CString strLine;
1351 CStdioFile file(sFile, CFile::typeText | CFile::modeRead | CFile::shareDenyWrite);
1352 while (m_bRunThread && file.ReadString(strLine))
1354 int eqpos = strLine.Find('=');
1355 CString rgx;
1356 rgx = strLine.Mid(eqpos+1).Trim();
1358 int pos = -1;
1359 while (((pos = strLine.Find(','))>=0)&&(pos < eqpos))
1361 mapRegex[strLine.Left(pos)] = rgx;
1362 strLine = strLine.Mid(pos+1).Trim();
1364 mapRegex[strLine.Left(strLine.Find('=')).Trim()] = rgx;
1366 file.Close();
1368 catch (CFileException* pE)
1370 TRACE("CFileException loading auto list regex file\n");
1371 pE->Delete();
1372 return;
1375 void CCommitDlg::GetAutocompletionList()
1377 // the auto completion list is made of strings from each selected files.
1378 // the strings used are extracted from the files with regexes found
1379 // in the file "autolist.txt".
1380 // the format of that file is:
1381 // file extensions separated with commas '=' regular expression to use
1382 // example:
1383 // .h, .hpp = (?<=class[\s])\b\w+\b|(\b\w+(?=[\s ]?\(\);))
1384 // .cpp = (?<=[^\s]::)\b\w+\b
1386 std::map<CString, CString> mapRegex;
1387 CString sRegexFile = CPathUtils::GetAppDirectory();
1388 CRegDWORD regtimeout = CRegDWORD(_T("Software\\TortoiseGit\\AutocompleteParseTimeout"), 5);
1389 DWORD timeoutvalue = regtimeout*1000;
1390 sRegexFile += _T("autolist.txt");
1391 if (!m_bRunThread)
1392 return;
1393 ParseRegexFile(sRegexFile, mapRegex);
1394 SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, SHGFP_TYPE_CURRENT, sRegexFile.GetBuffer(MAX_PATH+1));
1395 sRegexFile.ReleaseBuffer();
1396 sRegexFile += _T("\\TortoiseGit\\autolist.txt");
1397 if (PathFileExists(sRegexFile))
1399 ParseRegexFile(sRegexFile, mapRegex);
1401 DWORD starttime = GetTickCount();
1403 // now we have two arrays of strings, where the first array contains all
1404 // file extensions we can use and the second the corresponding regex strings
1405 // to apply to those files.
1407 // the next step is to go over all files shown in the commit dialog
1408 // and scan them for strings we can use
1409 int nListItems = m_ListCtrl.GetItemCount();
1411 for (int i=0; i<nListItems && m_bRunThread; ++i)
1413 // stop parsing after timeout
1414 if ((!m_bRunThread) || (GetTickCount() - starttime > timeoutvalue))
1415 return;
1417 CTGitPath *path = (CTGitPath*)m_ListCtrl.GetItemData(i);
1419 if(path == NULL)
1420 continue;
1422 CString sPartPath =path->GetGitPathString();
1423 m_autolist.insert(sPartPath);
1425 // const CGitStatusListCtrl::FileEntry * entry = m_ListCtrl.GetListEntry(i);
1426 // if (!entry)
1427 // continue;
1429 // add the path parts to the auto completion list too
1430 // CString sPartPath = entry->GetRelativeGitPath();
1431 // m_autolist.insert(sPartPath);
1434 int pos = 0;
1435 int lastPos = 0;
1436 while ((pos = sPartPath.Find('/', pos)) >= 0)
1438 pos++;
1439 lastPos = pos;
1440 m_autolist.insert(sPartPath.Mid(pos));
1443 // Last inserted entry is a file name.
1444 // Some users prefer to also list file name without extension.
1445 if (CRegDWORD(_T("Software\\TortoiseGit\\AutocompleteRemovesExtensions"), FALSE))
1447 int dotPos = sPartPath.ReverseFind('.');
1448 if ((dotPos >= 0) && (dotPos > lastPos))
1449 m_autolist.insert(sPartPath.Mid(lastPos, dotPos - lastPos));
1451 #if 0
1452 if ((entry->status <= Git_wc_status_normal)||(entry->status == Git_wc_status_ignored))
1453 continue;
1455 CString sExt = entry->GetPath().GetFileExtension();
1456 sExt.MakeLower();
1457 // find the regex string which corresponds to the file extension
1458 CString rdata = mapRegex[sExt];
1459 if (rdata.IsEmpty())
1460 continue;
1462 ScanFile(entry->GetPath().GetWinPathString(), rdata);
1463 if ((entry->textstatus != Git_wc_status_unversioned) &&
1464 (entry->textstatus != Git_wc_status_none) &&
1465 (entry->textstatus != Git_wc_status_ignored) &&
1466 (entry->textstatus != Git_wc_status_added) &&
1467 (entry->textstatus != Git_wc_status_normal))
1469 CTGitPath basePath = Git::GetPristinePath(entry->GetPath());
1470 if (!basePath.IsEmpty())
1471 ScanFile(basePath.GetWinPathString(), rdata);
1473 #endif
1475 ATLTRACE(_T("Auto completion list loaded in %d msec\n"), GetTickCount() - starttime);
1478 void CCommitDlg::ScanFile(const CString& sFilePath, const CString& sRegex)
1480 wstring sFileContent;
1481 HANDLE hFile = CreateFile(sFilePath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL);
1482 if (hFile != INVALID_HANDLE_VALUE)
1484 DWORD size = GetFileSize(hFile, NULL);
1485 if (size > 1000000L)
1487 // no files bigger than 1 Meg
1488 CloseHandle(hFile);
1489 return;
1491 // allocate memory to hold file contents
1492 char * buffer = new char[size];
1493 DWORD readbytes;
1494 ReadFile(hFile, buffer, size, &readbytes, NULL);
1495 CloseHandle(hFile);
1496 int opts = 0;
1497 IsTextUnicode(buffer, readbytes, &opts);
1498 if (opts & IS_TEXT_UNICODE_NULL_BYTES)
1500 delete [] buffer;
1501 return;
1503 if (opts & IS_TEXT_UNICODE_UNICODE_MASK)
1505 sFileContent = wstring((wchar_t*)buffer, readbytes/sizeof(WCHAR));
1507 if ((opts & IS_TEXT_UNICODE_NOT_UNICODE_MASK)||(opts == 0))
1509 int ret = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, (LPCSTR)buffer, readbytes, NULL, 0);
1510 wchar_t * pWideBuf = new wchar_t[ret];
1511 int ret2 = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, (LPCSTR)buffer, readbytes, pWideBuf, ret);
1512 if (ret2 == ret)
1513 sFileContent = wstring(pWideBuf, ret);
1514 delete [] pWideBuf;
1516 delete [] buffer;
1518 if (sFileContent.empty()|| !m_bRunThread)
1520 return;
1525 const tr1::wregex regCheck(sRegex, tr1::regex_constants::icase | tr1::regex_constants::ECMAScript);
1526 const tr1::wsregex_iterator end;
1527 wstring s = sFileContent;
1528 for (tr1::wsregex_iterator it(s.begin(), s.end(), regCheck); it != end; ++it)
1530 const tr1::wsmatch match = *it;
1531 for (size_t i=1; i<match.size(); ++i)
1533 if (match[i].second-match[i].first)
1535 ATLTRACE(_T("matched keyword : %s\n"), wstring(match[i]).c_str());
1536 m_autolist.insert(wstring(match[i]).c_str());
1541 catch (exception) {}
1544 // CSciEditContextMenuInterface
1545 void CCommitDlg::InsertMenuItems(CMenu& mPopup, int& nCmd)
1547 CString sMenuItemText(MAKEINTRESOURCE(IDS_COMMITDLG_POPUP_PASTEFILELIST));
1548 m_nPopupPasteListCmd = nCmd++;
1549 mPopup.AppendMenu(MF_STRING | MF_ENABLED, m_nPopupPasteListCmd, sMenuItemText);
1551 //CString sMenuItemText(MAKEINTRESOURCE(IDS_COMMITDLG_POPUP_PASTEFILELIST));
1552 if(m_History.GetCount() > 0)
1554 sMenuItemText.LoadString(IDS_COMMITDLG_POPUP_PASTELASTMESSAGE);
1555 m_nPopupPasteLastMessage = nCmd++;
1556 mPopup.AppendMenu(MF_STRING | MF_ENABLED, m_nPopupPasteLastMessage, sMenuItemText);
1558 sMenuItemText.LoadString(IDS_COMMITDLG_POPUP_LOGHISTORY);
1559 m_nPopupRecentMessage = nCmd++;
1560 mPopup.AppendMenu(MF_STRING | MF_ENABLED, m_nPopupRecentMessage, sMenuItemText);
1566 bool CCommitDlg::HandleMenuItemClick(int cmd, CSciEdit * pSciEdit)
1569 if (m_bBlock)
1570 return false;
1571 if (cmd == m_nPopupPasteListCmd)
1573 CString logmsg;
1574 int nListItems = m_ListCtrl.GetItemCount();
1575 for (int i=0; i<nListItems; ++i)
1577 CTGitPath * entry = (CTGitPath*)m_ListCtrl.GetItemData(i);
1578 if (entry&&entry->m_Checked)
1580 CString line;
1581 CString status = entry->GetActionName();
1582 if(entry->m_Action & CTGitPath::LOGACTIONS_UNVER)
1583 status = _T("Add");
1585 //git_wc_status_kind status = entry->status;
1586 WORD langID = (WORD)CRegStdDWORD(_T("Software\\TortoiseGit\\LanguageID"), GetUserDefaultLangID());
1587 if (m_ProjectProperties.bFileListInEnglish)
1588 langID = 1033;
1590 line.Format(_T("%-10s %s\r\n"),status , (LPCTSTR)m_ListCtrl.GetItemText(i,0));
1591 logmsg += line;
1594 pSciEdit->InsertText(logmsg);
1595 return true;
1598 if(cmd == m_nPopupPasteLastMessage)
1600 if(m_History.GetCount() ==0 )
1601 return false;
1603 CString logmsg;
1604 logmsg +=m_History.GetEntry(0);
1605 pSciEdit->InsertText(logmsg);
1606 return true;
1609 if(cmd == m_nPopupRecentMessage )
1611 OnBnClickedHistory();
1612 return true;
1614 return false;
1617 void CCommitDlg::OnTimer(UINT_PTR nIDEvent)
1619 switch (nIDEvent)
1621 case ENDDIALOGTIMER:
1622 KillTimer(ENDDIALOGTIMER);
1623 EndDialog(0);
1624 break;
1625 case REFRESHTIMER:
1626 if (m_bThreadRunning)
1628 SetTimer(REFRESHTIMER, 200, NULL);
1629 ATLTRACE("Wait some more before refreshing\n");
1631 else
1633 KillTimer(REFRESHTIMER);
1634 ATLTRACE("Refreshing after items dropped\n");
1635 Refresh();
1637 break;
1639 __super::OnTimer(nIDEvent);
1642 void CCommitDlg::OnBnClickedHistory()
1644 m_tooltips.Pop(); // hide the tooltips
1645 if (m_pathList.GetCount() == 0)
1646 return;
1648 CHistoryDlg historyDlg;
1649 historyDlg.SetHistory(m_History);
1650 if (historyDlg.DoModal() != IDOK)
1651 return;
1653 CString sMsg = historyDlg.GetSelectedText();
1654 if (sMsg != m_cLogMessage.GetText().Left(sMsg.GetLength()))
1656 CString sBugID = m_ProjectProperties.GetBugIDFromLog(sMsg);
1657 if (!sBugID.IsEmpty())
1659 SetDlgItemText(IDC_BUGID, sBugID);
1661 if (m_ProjectProperties.sLogTemplate.Compare(m_cLogMessage.GetText())!=0)
1662 m_cLogMessage.InsertText(sMsg, !m_cLogMessage.GetText().IsEmpty());
1663 else
1664 m_cLogMessage.SetText(sMsg);
1667 UpdateOKButton();
1668 GetDlgItem(IDC_LOGMESSAGE)->SetFocus();
1672 void CCommitDlg::OnBnClickedBugtraqbutton()
1674 m_tooltips.Pop(); // hide the tooltips
1675 CString sMsg = m_cLogMessage.GetText();
1677 if (m_BugTraqProvider == NULL)
1678 return;
1680 BSTR parameters = m_bugtraq_association.GetParameters().AllocSysString();
1681 BSTR commonRoot = SysAllocString(g_Git.m_CurrentDir);
1682 SAFEARRAY *pathList = SafeArrayCreateVector(VT_BSTR, 0, m_pathList.GetCount());
1684 for (LONG index = 0; index < m_pathList.GetCount(); ++index)
1685 SafeArrayPutElement(pathList, &index, m_pathList[index].GetGitPathString().AllocSysString());
1687 BSTR originalMessage = sMsg.AllocSysString();
1688 BSTR temp = NULL;
1689 // m_revProps.clear();
1691 // first try the IBugTraqProvider2 interface
1692 CComPtr<IBugTraqProvider2> pProvider2 = NULL;
1693 HRESULT hr = m_BugTraqProvider.QueryInterface(&pProvider2);
1694 if (SUCCEEDED(hr))
1696 //CString common = m_ListCtrl.GetCommonURL(false).GetGitPathString();
1697 BSTR repositoryRoot = g_Git.m_CurrentDir.AllocSysString();
1698 BSTR bugIDOut = NULL;
1699 GetDlgItemText(IDC_BUGID, m_sBugID);
1700 BSTR bugID = m_sBugID.AllocSysString();
1701 SAFEARRAY * revPropNames = NULL;
1702 SAFEARRAY * revPropValues = NULL;
1703 if (FAILED(hr = pProvider2->GetCommitMessage2(GetSafeHwnd(), parameters, repositoryRoot, commonRoot, pathList, originalMessage, bugID, &bugIDOut, &revPropNames, &revPropValues, &temp)))
1705 CString sErr;
1706 sErr.Format(IDS_ERR_FAILEDISSUETRACKERCOM, m_bugtraq_association.GetProviderName(), _com_error(hr).ErrorMessage());
1707 CMessageBox::Show(m_hWnd, sErr, _T("TortoiseGit"), MB_ICONERROR);
1709 else
1711 if (bugIDOut)
1713 m_sBugID = bugIDOut;
1714 SysFreeString(bugIDOut);
1715 SetDlgItemText(IDC_BUGID, m_sBugID);
1717 SysFreeString(bugID);
1718 SysFreeString(repositoryRoot);
1719 m_cLogMessage.SetText(temp);
1720 BSTR HUGEP *pbRevNames;
1721 BSTR HUGEP *pbRevValues;
1723 HRESULT hr1 = SafeArrayAccessData(revPropNames, (void HUGEP**)&pbRevNames);
1724 if (SUCCEEDED(hr1))
1726 HRESULT hr2 = SafeArrayAccessData(revPropValues, (void HUGEP**)&pbRevValues);
1727 if (SUCCEEDED(hr2))
1729 if (revPropNames->rgsabound->cElements == revPropValues->rgsabound->cElements)
1731 for (ULONG i = 0; i < revPropNames->rgsabound->cElements; i++)
1733 // m_revProps[pbRevNames[i]] = pbRevValues[i];
1736 SafeArrayUnaccessData(revPropValues);
1738 SafeArrayUnaccessData(revPropNames);
1740 if (revPropNames)
1741 SafeArrayDestroy(revPropNames);
1742 if (revPropValues)
1743 SafeArrayDestroy(revPropValues);
1746 else
1748 // if IBugTraqProvider2 failed, try IBugTraqProvider
1749 CComPtr<IBugTraqProvider> pProvider = NULL;
1750 hr = m_BugTraqProvider.QueryInterface(&pProvider);
1751 if (FAILED(hr))
1753 CString sErr;
1754 sErr.Format(IDS_ERR_FAILEDISSUETRACKERCOM, (LPCTSTR)m_bugtraq_association.GetProviderName(), _com_error(hr).ErrorMessage());
1755 CMessageBox::Show(m_hWnd, sErr, _T("TortoiseGit"), MB_ICONERROR);
1756 return;
1759 if (FAILED(hr = pProvider->GetCommitMessage(GetSafeHwnd(), parameters, commonRoot, pathList, originalMessage, &temp)))
1761 CString sErr;
1762 sErr.Format(IDS_ERR_FAILEDISSUETRACKERCOM, m_bugtraq_association.GetProviderName(), _com_error(hr).ErrorMessage());
1763 CMessageBox::Show(m_hWnd, sErr, _T("TortoiseGit"), MB_ICONERROR);
1765 else
1766 m_cLogMessage.SetText(temp);
1768 m_sLogMessage = m_cLogMessage.GetText();
1769 if (!m_ProjectProperties.sMessage.IsEmpty())
1771 CString sBugID = m_ProjectProperties.FindBugID(m_sLogMessage);
1772 if (!sBugID.IsEmpty())
1774 SetDlgItemText(IDC_BUGID, sBugID);
1778 m_cLogMessage.SetFocus();
1780 SysFreeString(parameters);
1781 SysFreeString(commonRoot);
1782 SafeArrayDestroy(pathList);
1783 SysFreeString(originalMessage);
1784 SysFreeString(temp);
1788 void CCommitDlg::FillPatchView()
1790 if(::IsWindow(this->m_patchViewdlg.m_hWnd))
1792 m_patchViewdlg.m_ctrlPatchView.SetText(CString());
1794 POSITION pos=m_ListCtrl.GetFirstSelectedItemPosition();
1795 m_patchViewdlg.m_ctrlPatchView.Call(SCI_SETREADONLY, FALSE);
1796 CString cmd,out;
1798 while(pos)
1800 int nSelect = m_ListCtrl.GetNextSelectedItem(pos);
1801 CTGitPath * p=(CTGitPath*)m_ListCtrl.GetItemData(nSelect);
1802 if(p && !(p->m_Action&CTGitPath::LOGACTIONS_UNVER) )
1804 CString head = _T("HEAD");
1805 if(m_bCommitAmend==TRUE && m_bAmendDiffToLastCommit==FALSE)
1806 head = _T("HEAD~1");
1807 cmd.Format(_T("git.exe diff %s -- \"%s\""), head, p->GetGitPathString());
1808 g_Git.Run(cmd,&out,CP_ACP);
1812 m_patchViewdlg.m_ctrlPatchView.SetText(out);
1813 m_patchViewdlg.m_ctrlPatchView.Call(SCI_SETREADONLY, TRUE);
1814 m_patchViewdlg.m_ctrlPatchView.Call(SCI_GOTOPOS, 0);
1817 LRESULT CCommitDlg::OnGitStatusListCtrlItemChanged(WPARAM /*wparam*/, LPARAM /*lparam*/)
1819 this->FillPatchView();
1820 return 0;
1824 LRESULT CCommitDlg::OnGitStatusListCtrlCheckChanged(WPARAM, LPARAM)
1826 UpdateOKButton();
1827 return 0;
1830 void CCommitDlg::UpdateOKButton()
1832 if (m_bBlock)
1833 return;
1835 bool bValidLogSize = m_cLogMessage.GetText().GetLength() >= m_ProjectProperties.nMinLogSize && m_cLogMessage.GetText().GetLength() > 0;
1836 bool bAmendOrSelectFilesOrMerge = m_ListCtrl.GetSelected() > 0 || (m_bCommitAmend && m_bAmendDiffToLastCommit) || CTGitPath(g_Git.m_CurrentDir).IsMergeActive();
1838 DialogEnableWindow(IDOK, bValidLogSize && bAmendOrSelectFilesOrMerge);
1841 LRESULT CCommitDlg::DefWindowProc(UINT message, WPARAM wParam, LPARAM lParam)
1843 switch (message) {
1844 case WM_NOTIFY:
1845 if (wParam == IDC_SPLITTER)
1847 SPC_NMHDR* pHdr = (SPC_NMHDR*) lParam;
1848 DoSize(pHdr->delta);
1850 break;
1853 return __super::DefWindowProc(message, wParam, lParam);
1856 void CCommitDlg::SetSplitterRange()
1858 if ((m_ListCtrl)&&(m_cLogMessage))
1860 CRect rcTop;
1861 m_cLogMessage.GetWindowRect(rcTop);
1862 ScreenToClient(rcTop);
1863 CRect rcMiddle;
1864 m_ListCtrl.GetWindowRect(rcMiddle);
1865 ScreenToClient(rcMiddle);
1866 if (rcMiddle.Height() && rcMiddle.Width())
1867 m_wndSplitter.SetRange(rcTop.top+60, rcMiddle.bottom-80);
1871 void CCommitDlg::DoSize(int delta)
1873 RemoveAnchor(IDC_MESSAGEGROUP);
1874 RemoveAnchor(IDC_LOGMESSAGE);
1875 RemoveAnchor(IDC_SPLITTER);
1876 RemoveAnchor(IDC_SIGNOFF);
1877 RemoveAnchor(IDC_COMMIT_AMEND);
1878 RemoveAnchor(IDC_COMMIT_AMENDDIFF);
1879 RemoveAnchor(IDC_COMMIT_SETDATETIME);
1880 RemoveAnchor(IDC_COMMIT_DATEPICKER);
1881 RemoveAnchor(IDC_COMMIT_TIMEPICKER);
1882 RemoveAnchor(IDC_LISTGROUP);
1883 RemoveAnchor(IDC_FILELIST);
1884 RemoveAnchor(IDC_TEXT_INFO);
1886 CSplitterControl::ChangeHeight(&m_cLogMessage, delta, CW_TOPALIGN);
1887 CSplitterControl::ChangeHeight(GetDlgItem(IDC_MESSAGEGROUP), delta, CW_TOPALIGN);
1888 CSplitterControl::ChangeHeight(&m_ListCtrl, -delta, CW_BOTTOMALIGN);
1889 CSplitterControl::ChangeHeight(GetDlgItem(IDC_LISTGROUP), -delta, CW_BOTTOMALIGN);
1890 CSplitterControl::ChangePos(GetDlgItem(IDC_SIGNOFF),0,delta);
1891 CSplitterControl::ChangePos(GetDlgItem(IDC_COMMIT_AMEND),0,delta);
1892 CSplitterControl::ChangePos(GetDlgItem(IDC_COMMIT_AMENDDIFF),0,delta);
1893 CSplitterControl::ChangePos(GetDlgItem(IDC_COMMIT_SETDATETIME),0,delta);
1894 CSplitterControl::ChangePos(GetDlgItem(IDC_COMMIT_DATEPICKER),0,delta);
1895 CSplitterControl::ChangePos(GetDlgItem(IDC_COMMIT_TIMEPICKER),0,delta);
1896 CSplitterControl::ChangePos(GetDlgItem(IDC_TEXT_INFO),0,delta);
1898 AddAnchor(IDC_MESSAGEGROUP, TOP_LEFT, TOP_RIGHT);
1899 AddAnchor(IDC_LOGMESSAGE, TOP_LEFT, TOP_RIGHT);
1900 AddAnchor(IDC_SPLITTER, TOP_LEFT, TOP_RIGHT);
1901 AddAnchor(IDC_LISTGROUP, TOP_LEFT, BOTTOM_RIGHT);
1902 AddAnchor(IDC_FILELIST, TOP_LEFT, BOTTOM_RIGHT);
1903 AddAnchor(IDC_SIGNOFF,TOP_RIGHT);
1904 AddAnchor(IDC_COMMIT_AMEND,TOP_LEFT);
1905 AddAnchor(IDC_COMMIT_AMENDDIFF,TOP_LEFT);
1906 AddAnchor(IDC_COMMIT_SETDATETIME,TOP_LEFT);
1907 AddAnchor(IDC_COMMIT_DATEPICKER,TOP_LEFT);
1908 AddAnchor(IDC_COMMIT_TIMEPICKER,TOP_LEFT);
1909 AddAnchor(IDC_TEXT_INFO,TOP_RIGHT);
1910 ArrangeLayout();
1911 // adjust the minimum size of the dialog to prevent the resizing from
1912 // moving the list control too far down.
1913 CRect rcLogMsg;
1914 m_cLogMessage.GetClientRect(rcLogMsg);
1915 SetMinTrackSize(CSize(m_DlgOrigRect.Width(), m_DlgOrigRect.Height()-m_LogMsgOrigRect.Height()+rcLogMsg.Height()));
1917 SetSplitterRange();
1918 m_cLogMessage.Invalidate();
1919 GetDlgItem(IDC_LOGMESSAGE)->Invalidate();
1922 void CCommitDlg::OnSize(UINT nType, int cx, int cy)
1924 // first, let the resizing take place
1925 __super::OnSize(nType, cx, cy);
1927 //set range
1928 SetSplitterRange();
1931 CString CCommitDlg::GetSignedOffByLine()
1933 CString str;
1935 CString username = g_Git.GetUserName();
1936 CString email = g_Git.GetUserEmail();
1937 username.Remove(_T('\n'));
1938 email.Remove(_T('\n'));
1940 str.Format(_T("Signed-off-by: %s <%s>"), username, email);
1942 return str;
1945 void CCommitDlg::OnBnClickedSignOff()
1947 CString str = GetSignedOffByLine();
1949 if (m_cLogMessage.GetText().Find(str) == -1) {
1950 m_cLogMessage.SetText(m_cLogMessage.GetText().TrimRight());
1951 int lastNewline = m_cLogMessage.GetText().ReverseFind(_T('\n'));
1952 int foundByLine = -1;
1953 if (lastNewline > 0)
1954 foundByLine = m_cLogMessage.GetText().Find(_T("-by: "), lastNewline);
1956 if (foundByLine == -1 || foundByLine < lastNewline)
1957 str = _T("\r\n") + str;
1959 m_cLogMessage.SetText(m_cLogMessage.GetText()+_T("\r\n")+str+_T("\r\n"));
1963 void CCommitDlg::OnBnClickedCommitAmend()
1965 this->UpdateData();
1966 if(this->m_bCommitAmend && this->m_AmendStr.IsEmpty())
1968 GitRev rev;
1969 rev.GetCommit(CString(_T("HEAD")));
1970 m_AmendStr=rev.GetSubject()+_T("\n")+rev.GetBody();
1973 if(this->m_bCommitAmend)
1975 this->m_NoAmendStr=this->m_cLogMessage.GetText();
1976 m_cLogMessage.SetText(m_AmendStr);
1977 GetDlgItem(IDC_COMMIT_AMENDDIFF)->ShowWindow(SW_SHOW);
1979 else
1981 this->m_AmendStr=this->m_cLogMessage.GetText();
1982 m_cLogMessage.SetText(m_NoAmendStr);
1983 GetDlgItem(IDC_COMMIT_AMENDDIFF)->ShowWindow(SW_HIDE);
1986 OnBnClickedCommitSetDateTime(); // to update the commit date and time
1988 Refresh();
1991 void CCommitDlg::OnBnClickedWholeProject()
1993 m_tooltips.Pop(); // hide the tooltips
1994 UpdateData();
1995 m_ListCtrl.Clear();
1996 if (!m_bBlock)
1998 if(m_bWholeProject)
1999 m_ListCtrl.GetStatus(NULL,true,false,true);
2000 else
2001 m_ListCtrl.GetStatus(&this->m_pathList,true,false,true);
2003 DWORD dwShow = (DWORD)(GITSLC_SHOWVERSIONEDBUTNORMALANDEXTERNALSFROMDIFFERENTREPOS | GITSLC_SHOWUNVERSIONED | GITSLC_SHOWLOCKS);
2004 m_ListCtrl.Show(m_ListCtrl.GetShowFlags(), dwShow & (~CTGitPath::LOGACTIONS_UNVER|~CTGitPath::LOGACTIONS_IGNORE));
2007 SetDlgTitle();
2010 void CCommitDlg::OnFocusMessage()
2012 m_cLogMessage.SetFocus();
2015 void CCommitDlg::OnScnUpdateUI(NMHDR *pNMHDR, LRESULT *pResult)
2017 UNREFERENCED_PARAMETER(pNMHDR);
2018 int pos=this->m_cLogMessage.Call(SCI_GETCURRENTPOS);
2019 int line=this->m_cLogMessage.Call(SCI_LINEFROMPOSITION,pos);
2020 int column=this->m_cLogMessage.Call(SCI_GETCOLUMN,pos);
2022 CString str;
2023 str.Format(_T("%d/%d"),line+1,column+1);
2024 this->GetDlgItem(IDC_TEXT_INFO)->SetWindowText(str);
2026 if(*pResult)
2027 *pResult=0;
2029 void CCommitDlg::OnStnClickedViewPatch()
2031 m_patchViewdlg.m_pProjectProperties = &this->m_ProjectProperties;
2032 m_patchViewdlg.m_ParentCommitDlg = this;
2033 if(!IsWindow(this->m_patchViewdlg.m_hWnd))
2035 BOOL viewPatchEnabled = FALSE;
2036 m_ProjectProperties.GetBOOLProps(viewPatchEnabled, _T("tgit.commitshowpatch"));
2037 if (viewPatchEnabled == FALSE)
2038 g_Git.SetConfigValue(_T("tgit.showpatch"), _T("true"));
2039 m_patchViewdlg.Create(IDD_PATCH_VIEW,this);
2040 CRect rect;
2041 this->GetWindowRect(&rect);
2043 m_patchViewdlg.ShowWindow(SW_SHOW);
2045 m_patchViewdlg.SetWindowPos(NULL,rect.right,rect.top,rect.Width(),rect.Height(),
2046 SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
2048 ShowViewPatchText(false);
2049 FillPatchView();
2051 else
2053 g_Git.SetConfigValue(_T("tgit.commitshowpatch"), _T("false"));
2054 m_patchViewdlg.ShowWindow(SW_HIDE);
2055 m_patchViewdlg.DestroyWindow();
2056 ShowViewPatchText(true);
2058 this->m_ctrlShowPatch.Invalidate();
2061 void CCommitDlg::OnMoving(UINT fwSide, LPRECT pRect)
2063 __super::OnMoving(fwSide, pRect);
2065 if (::IsWindow(m_patchViewdlg.m_hWnd))
2067 RECT patchrect;
2068 m_patchViewdlg.GetWindowRect(&patchrect);
2069 if (::IsWindow(m_hWnd))
2071 RECT thisrect;
2072 GetWindowRect(&thisrect);
2073 if (patchrect.left == thisrect.right)
2075 m_patchViewdlg.SetWindowPos(NULL, patchrect.left - (thisrect.left - pRect->left), patchrect.top - (thisrect.top - pRect->top),
2076 0, 0, SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOSIZE | SWP_NOZORDER);
2083 void CCommitDlg::OnSizing(UINT fwSide, LPRECT pRect)
2085 __super::OnSizing(fwSide, pRect);
2087 if(::IsWindow(this->m_patchViewdlg.m_hWnd))
2089 CRect thisrect, patchrect;
2090 this->GetWindowRect(thisrect);
2091 this->m_patchViewdlg.GetWindowRect(patchrect);
2092 if(thisrect.right==patchrect.left)
2094 patchrect.left -= (thisrect.right - pRect->right);
2095 patchrect.right-= (thisrect.right - pRect->right);
2097 if( patchrect.bottom == thisrect.bottom)
2099 patchrect.bottom -= (thisrect.bottom - pRect->bottom);
2101 if( patchrect.top == thisrect.top)
2103 patchrect.top -= thisrect.top-pRect->top;
2105 m_patchViewdlg.MoveWindow(patchrect);
2110 void CCommitDlg::OnHdnItemchangedFilelist(NMHDR *pNMHDR, LRESULT *pResult)
2112 UNREFERENCED_PARAMETER(pNMHDR);
2113 *pResult = 0;
2114 TRACE("Item Changed\r\n");
2117 int CCommitDlg::CheckHeadDetach()
2119 CString output;
2120 if(g_Git.GetCurrentBranchFromFile(g_Git.m_CurrentDir,output))
2122 if(CMessageBox::Show(NULL,_T("<ct=0x0000FF>Current HEAD Detached</ct>, you are working on (no branch)\nDo you want create branch now?"),
2123 _T("TortoiseGit"),MB_YESNO|MB_ICONWARNING) == IDYES)
2125 CAppUtils::CreateBranchTag(FALSE,NULL,true);
2128 return 0;
2131 void CCommitDlg::OnBnClickedCommitAmenddiff()
2133 UpdateData();
2134 Refresh();
2137 void CCommitDlg::OnBnClickedNoautoselectsubmodules()
2139 UpdateData();
2140 Refresh();
2143 void CCommitDlg::OnBnClickedCommitSetDateTime()
2145 UpdateData();
2147 if (m_bSetCommitDateTime)
2149 CTime authordate = CTime::GetCurrentTime();
2150 if (m_bCommitAmend)
2152 GitRev headRevision;
2153 headRevision.GetCommit(_T("HEAD"));
2154 authordate = headRevision.GetAuthorDate();
2157 m_CommitDate.SetTime(&authordate);
2158 m_CommitTime.SetTime(&authordate);
2160 GetDlgItem(IDC_COMMIT_DATEPICKER)->ShowWindow(SW_SHOW);
2161 GetDlgItem(IDC_COMMIT_TIMEPICKER)->ShowWindow(SW_SHOW);
2163 else
2165 GetDlgItem(IDC_COMMIT_DATEPICKER)->ShowWindow(SW_HIDE);
2166 GetDlgItem(IDC_COMMIT_TIMEPICKER)->ShowWindow(SW_HIDE);