Debian Codegraph @

git/gitBlameDlg.cpp

raw
1 #include "ColoursAndFontsManager.h"
2 #include "GitDiffOutputParser.h"
3 #include "asyncprocess.h"
4 #include "editor_config.h"
5 #include "file_logger.h"
6 #include "git.h"
7 #include "gitBlameDlg.h"
8 #include "globals.h"
9 #include "lexer_configuration.h"
10 #include "processreaderthread.h"
11 #include "windowattrmanager.h"
12 #include <wx/bitmap.h>
13 #include <wx/dcmemory.h>
14 #include <wx/tokenzr.h>
15
16 #define TEXT_MARGIN_ID 0
17 #define LINENUMBER_MARGIN_ID 1
18 #define DATE_WIDTH 11 // 2000-00-00
19 #define AUTHOR_WIDTH 15
20 #define HASH_WIDTH 8
21
22 size_t FindAuthorLine(wxArrayString& blameArr, size_t n, wxString* author) // Helper function
23 {
24 for(; n < blameArr.GetCount(); ++n) {
25 if(blameArr.Item(n).StartsWith("author ", author)) {
26 break;
27 }
28 }
29 return n; // which will now index either the next 'author ' field, or the end of the array
30 }
31
32 // The text margin needs to be 24 chars wide for the date & hash, the max author-width, plus 2 spaces between
33 static size_t marginwidth = DATE_WIDTH + AUTHOR_WIDTH + HASH_WIDTH + 2;
34
35 // Helper function. 'n' indexes any previous 'author ' field + 1
36 wxArrayString ParseBlame(wxStyledTextCtrl* stc, wxArrayString& blameArr, size_t& n)
37 {
38 // For a format supposedly designed for easy parsing, porcelain is decidedly unhelpful
39 // Each line's entry usually has 13 fields but may have 12 (or less?)
40 // Most fields start with a descriptive string e.g. 'author', 'filename', but the hash and the code-line don't.
41 // 'author ' should normally be present, so search for that and then guess
42 wxArrayString arr;
43 wxString hash, author, dtstring, date;
44 n = FindAuthorLine(blameArr, n, &author);
45 if(n == blameArr.GetCount()) {
46 return arr; // Either something went wrong or we've reached the end
47 }
48
49 // OK, we've found the author field. The hash should be the previous field
50 hash = blameArr.Item(n - 1);
51 wxCHECK_MSG(hash.Len() > 39, arr,
52 "What should have been the 'commit-hash' field is too short"); // Something went seriously wrong, or the
53 // output is very strange. Skip.
54 hash = ' ' + hash.Left(8);
55
56 for(size_t c = n + 1; c < blameArr.GetCount(); ++c) {
57 if(blameArr.Item(c).StartsWith("author-time ", &dtstring)) {
58 break;
59 }
60 if(blameArr.Item(c).StartsWith("author ")) {
61 break; // Abort as we've overrun into the next blame line!
62 }
63 }
64 if(!dtstring.empty()) { // Don't abort the whole item just because there's no date
65 long datetime;
66 if(dtstring.ToLong(&datetime)) {
67 wxDateTime dt((time_t)datetime);
68 if(dt.IsValid()) {
69 date = dt.Format("%d-%m-%Y ");
70 }
71 }
72 }
73
74 // To find the code-line, the safest way is to find the _next_ 'author ' and work backwards
75 size_t cl = FindAuthorLine(blameArr, n + 1, NULL);
76 if(cl == blameArr.GetCount()) {
77 --cl; // This must be the last item, so the code-line should be at the end
78 } else {
79 cl -= 2; // -1 for the next item's author field, -1 for its hash,
80 }
81
82 // Now create the margin line, carefully: the central 'author' field is truncated/padded to fill the available space
83 // All this would be much easier if scintilla allowed writing text to 3 'text' margins, but afaict it doesn't
84 author.Truncate(AUTHOR_WIDTH);
85 author.Pad(AUTHOR_WIDTH - author.Len(), ' ');
86
87 wxString margin;
88 margin << date << author << hash;
89
90 wxASSERT(margin.Len() <= marginwidth);
91 arr.Add(margin);
92 arr.Add(blameArr.Item(cl)); // code-line
93
94 return arr;
95 }
96
97 void StoreExtraArgs(wxComboBox* m_comboExtraArgs, const wxString extraArgs) // Helper function
98 {
99 if(m_comboExtraArgs && !extraArgs.empty()) {
100 int pos = m_comboExtraArgs->FindString(extraArgs);
101 if(pos == 0) {
102 return; // It's already the first item in the list
103 }
104 if(pos != wxNOT_FOUND) {
105 m_comboExtraArgs->Delete(pos);
106 }
107 m_comboExtraArgs->Insert(extraArgs, 0);
108 }
109 }
110
111 GitBlameDlg::GitBlameDlg(wxWindow* parent, GitPlugin* plugin)
112 : GitBlameDlgBase(parent)
113 , m_plugin(plugin)
114 , m_sashPositionMain(0)
115 , m_sashPositionV(0)
116 , m_sashPositionH(0)
117 {
118 m_editEventsHandler.Reset(new clEditEventsHandler(m_stcBlame));
119
120 clConfig conf("git.conf");
121 GitEntry data;
122 conf.ReadItem(&data);
123
124 m_showParentCommit = data.GetGitBlameShowParentCommit();
125 m_showLogControls = data.GetGitBlameShowLogControls();
126
127 m_sashPositionMain = data.GetGitBlameDlgMainSashPos();
128 m_sashPositionV = data.GetGitBlameDlgVSashPos();
129 m_sashPositionH = data.GetGitBlameDlgHSashPos();
130
131 if(m_splitterMain->IsSplit()) {
132 m_splitterMain->SetSashPosition(m_sashPositionMain);
133 m_splitterH->SetSashPosition(m_sashPositionH);
134 m_splitterV->SetSashPosition(m_sashPositionV);
135 if(!m_showLogControls) {
136 m_splitterMain->Unsplit();
137 }
138 } else if(m_showLogControls && !m_splitterMain->IsSplit()) {
139 m_splitterMain->SplitHorizontally(m_splitterPageBottom, m_splitterPageBottom, m_sashPositionMain);
140 m_splitterH->SetSashPosition(m_sashPositionH);
141 m_splitterV->SetSashPosition(m_sashPositionV);
142 }
143 m_comboExtraArgs->Clear(); // Remove the placeholder string (there to make the control wider)
144
145 Bind(wxEVT_ASYNC_PROCESS_OUTPUT, &GitBlameDlg::OnProcessOutput, this);
146 Bind(wxEVT_ASYNC_PROCESS_TERMINATED, &GitBlameDlg::OnProcessTerminated, this);
147 Bind(wxEVT_CHAR_HOOK, &GitBlameDlg::OnCharHook, this);
148 ::clSetDialogBestSizeAndPosition(this);
149 }
150
151 GitBlameDlg::~GitBlameDlg()
152 {
153 m_editEventsHandler.Reset(NULL);
154
155 clConfig conf("git.conf");
156 GitEntry data;
157 conf.ReadItem(&data);
158
159 if(m_showLogControls && m_splitterMain->IsSplit()) {
160 data.SetGitBlameDlgMainSashPos(m_splitterMain->GetSashPosition());
161 data.SetGitBlameDlgHSashPos(m_splitterH->GetSashPosition());
162 data.SetGitBlameDlgVSashPos(m_splitterV->GetSashPosition());
163 } else {
164 data.SetGitBlameDlgMainSashPos(m_sashPositionMain);
165 data.SetGitBlameDlgHSashPos(m_sashPositionH);
166 data.SetGitBlameDlgVSashPos(m_sashPositionV);
167 }
168
169 data.SetGitBlameShowParentCommit(m_showParentCommit);
170 data.SetGitBlameShowLogControls(m_showLogControls);
171
172 conf.WriteItem(&data);
173 }
174
175 void GitBlameDlg::OnCloseDialog(wxCommandEvent& event) { DoCloseDialog(); }
176
177 void GitBlameDlg::DoCloseDialog()
178 {
179 m_stcBlame->ClearAll();
180 m_choiceHistory->Clear();
181 m_comboExtraArgs->Clear();
182 m_commitStore.Clear();
183
184 ClearLogControls();
185
186 Hide();
187 }
188
189 void GitBlameDlg::SetBlame(const wxString& blame, const wxString& args)
190 {
191 wxString filename = args;
192 size_t where = args.Find(" -- ");
193 if(where != wxString::npos) {
194 filename = args.Mid(where + 4);
195 }
196 filename.Trim().Trim(false);
197
198 clDEBUG() << "GitBlame is called for file:" << filename << clEndl;
199 LOG_IF_TRACE { clDEBUG1() << "GitBlame 'blame':\n" << blame << clEndl; }
200
201 // Set blame editor style and fonts
202 LexerConf::Ptr_t lexer = ColoursAndFontsManager::Get().GetLexerForFile(wxFileName(filename).GetFullName());
203 if(!lexer) {
204 lexer = ColoursAndFontsManager::Get().GetLexer("default");
205 }
206 lexer->Apply(m_stcBlame, true);
207
208 LexerConf::Ptr_t lex = EditorConfigST::Get()->GetLexer("diff");
209 if(lex) {
210 lex->Apply(m_stcDiff, true);
211 }
212
213 LexerConf::Ptr_t textLex = EditorConfigST::Get()->GetLexer("text");
214 textLex->Apply(m_stcCommitMessage, true);
215
216 m_stcBlame->SetMarginType(TEXT_MARGIN_ID, wxSTC_MARGIN_RTEXT);
217 // The text margin needs to be 24 chars wide for the date & hash, the max author-width, plus 2 spaces between
218 wxBitmap bmp(1, 1);
219 wxMemoryDC memDC(bmp);
220 memDC.SetFont(m_stcBlame->StyleGetFont(0));
221 int charWidth = memDC.GetTextExtent("W").x;
222
223 m_stcBlame->SetMarginWidth(TEXT_MARGIN_ID, marginwidth * charWidth);
224 m_stcBlame->SetMarginSensitive(TEXT_MARGIN_ID, true);
225
226 wxArrayString lines = wxStringTokenize(blame, "\n");
227 const size_t count = lines.GetCount();
228 wxString blameCommit;
229 if(args.Contains(" -- ")) {
230 // This must be a subsequent SetBlame call after a dclick. We can get the commit from args
231 blameCommit = args.Left(8);
232 }
233
234 size_t numlen =
235 wxString::Format("%i", (int)count).length(); // How many digits must we allow room for in the number margin?
236 int m_stcBlame_PixelWidth = 4 + numlen * m_stcBlame->TextWidth(wxSTC_STYLE_LINENUMBER, "9");
237 m_stcBlame->SetMarginType(LINENUMBER_MARGIN_ID, wxSTC_MARGIN_NUMBER);
238 m_stcBlame->SetMarginWidth(LINENUMBER_MARGIN_ID, m_stcBlame_PixelWidth);
239
240 // In case we're re-entering, ensure we're r/w. For a wxSTC 'readonly' also means can't append text programatically
241 m_stcBlame->SetReadOnly(false);
242 m_stcBlame->ClearAll();
243
244 for(size_t n = 0, line = 0; n < count; ++n) {
245 wxArrayString item = ParseBlame(m_stcBlame, lines, n);
246 if(!item.GetCount()) {
247 continue; // The entry must be corrupt, or we overran
248 }
249
250 // We must append each code-line before doing MarginSetText(), which seems to fail if the line doesn't yet exist
251 m_stcBlame->AppendText(item.Item(1) + '\n');
252 m_stcBlame->MarginSetText(line++, item.Item(0));
253 }
254
255 m_stcBlame->SetReadOnly(true); // Now we can safely set it to r/o
256
257 m_commitStore.LoadChoice(m_choiceHistory);
258 if(!blameCommit.empty()) {
259 for(size_t n = 0; n < m_choiceHistory->GetCount(); ++n) {
260 if(m_choiceHistory->GetString(n).Left(8) == blameCommit.Left(8)) {
261 m_choiceHistory->SetSelection(n);
262 }
263 }
264 }
265
266 if(!m_commitStore.GetRevlistOutput().GetCount()) {
267 wxString filepath = m_plugin->GetEditorRelativeFilepath();
268 if(!filepath.empty()) {
269 m_plugin->OnGitBlameRevList("--parents ", filepath); // Find each commit's parent(s)
270 }
271 }
272
273 if(!blameCommit.Left(8).empty()) {
274 UpdateLogControls(blameCommit.Left(8));
275 }
276 }
277
278 void GitBlameDlg::OnRevListOutput(const wxString& output, const wxString& Arguments)
279 {
280 wxCHECK_RET(!output.empty(), "git rev-list returned no output");
281
282 wxArrayString revlistOutput = wxStringTokenize(output, "\n");
283 wxCHECK_RET(revlistOutput.GetCount(), "git rev-list gave no valid output");
284 m_commitStore.SetRevlistOutput(revlistOutput);
285
286 if(m_commitStore.GetCurrentlyDisplayedCommit().empty()) {
287 wxString head = revlistOutput.Item(0).BeforeFirst(' '); // Add HEAD
288 m_commitStore.AddCommit(head.Left(8) + " (HEAD)");
289 m_commitStore.LoadChoice(m_choiceHistory);
290
291 if(m_stcCommitMessage->IsEmpty()) {
292 UpdateLogControls(head.Left(8));
293 }
294 }
295 }
296
297 void GitBlameDlg::OnStcblameLeftDclick(wxMouseEvent& event)
298 {
299 int position = m_stcBlame->PositionFromPoint(wxPoint(event.GetX(), event.GetY()));
300 int line = m_stcBlame->LineFromPosition(position);
301 wxString commit = m_stcBlame->MarginGetText(line).Right(8), newBlame;
302 wxString filepath(m_plugin->GetEditorRelativeFilepath());
303 if(!commit.empty() && commit != "00000000" /*Not yet committed*/ && !filepath.empty()) {
304 if(m_showParentCommit) {
305 newBlame = m_commitStore.GetCommitParent(commit);
306 } else {
307 newBlame = commit;
308 }
309 if(newBlame.empty()) {
310 return; // This commit is parentless (it's probably the initial commit) so trying to access commit^ will
311 // fail
312 }
313
314 wxString args(newBlame);
315
316 wxString extraArgs = m_comboExtraArgs->GetValue();
317 if(!extraArgs.empty()) {
318 StoreExtraArgs(m_comboExtraArgs, extraArgs);
319 args << ' ' << extraArgs << ' ';
320 }
321 args << " -- " << filepath;
322
323 m_plugin->DoGitBlame(args);
324
325 m_commitStore.AddCommit(newBlame);
326 }
327 }
328
329 void GitBlameDlg::OnExtraArgsTextEnter(wxCommandEvent& event)
330 {
331 GetNewCommitBlame(m_commitStore.GetCurrentlyDisplayedCommit());
332 }
333
334 void GitBlameDlg::OnRefreshBlame(wxCommandEvent& event)
335 {
336 GetNewCommitBlame(m_commitStore.GetCurrentlyDisplayedCommit());
337 }
338
339 void GitBlameDlg::OnPreviousBlame(wxCommandEvent& event)
340 {
341 wxCHECK_RET(m_commitStore.CanGoBack(), "Trying to get a non-existent commit's blame");
342 GetNewCommitBlame(m_commitStore.GetPreviousCommit());
343 }
344
345 void GitBlameDlg::OnBackUpdateUI(wxUpdateUIEvent& event) { event.Enable(m_commitStore.CanGoBack()); }
346
347 void GitBlameDlg::OnNextBlame(wxCommandEvent& event)
348 {
349 wxCHECK_RET(m_commitStore.CanGoForward(), "Trying to get a non-existent commit's blame");
350 GetNewCommitBlame(m_commitStore.GetNextCommit());
351 }
352 void GitBlameDlg::OnForwardUpdateUI(wxUpdateUIEvent& event) { event.Enable(m_commitStore.CanGoForward()); }
353
354 void GitBlameDlg::OnHistoryItemSelected(wxCommandEvent& event)
355 {
356 wxBusyCursor bc;
357 int sel = event.GetSelection();
358 wxString str = event.GetString();
359 wxString commit = m_commitStore.GetCommit(sel);
360 wxASSERT(commit.Left(8) == str.Left(8));
361
362 m_commitStore.SetCurrentlyDisplayedCommit(commit);
363 GetNewCommitBlame(commit);
364 }
365
366 void GitBlameDlg::GetNewCommitBlame(const wxString& commit)
367 {
368 wxString filepath(m_plugin->GetEditorRelativeFilepath());
369 if(!commit.empty() && !filepath.empty()) {
370 wxString args(commit.Left(8)); // Just the first 8 because of "abcd1234 (HEAD)"
371
372 wxString extraArgs = m_comboExtraArgs->GetValue();
373 if(!extraArgs.empty()) {
374 StoreExtraArgs(m_comboExtraArgs, extraArgs);
375 args << ' ' << extraArgs << ' ';
376 }
377
378 args << " -- " << filepath;
379 m_plugin->DoGitBlame(args);
380
381 ClearLogControls();
382 }
383 }
384
385 void GitBlameDlg::ClearLogControls()
386 {
387 m_stcCommitMessage->SetEditable(true);
388 m_stcDiff->SetEditable(true);
389
390 m_stcCommitMessage->ClearAll();
391 m_fileListBox->Clear();
392 m_diffMap.clear();
393 m_stcDiff->ClearAll();
394
395 m_stcCommitMessage->SetEditable(false);
396 m_stcDiff->SetEditable(false);
397 }
398 void GitBlameDlg::OnSettings(wxCommandEvent& event)
399 {
400 GitBlameSettingsDlg dlg(this, m_showParentCommit, m_showLogControls);
401 if(dlg.ShowModal() == wxID_OK) {
402 m_showParentCommit = dlg.GetCheckParentCommit()->IsChecked();
403 m_showLogControls = dlg.GetCheckShowLogControls()->IsChecked();
404
405 clConfig conf("git.conf");
406 GitEntry data;
407 conf.ReadItem(&data);
408
409 data.SetGitBlameShowParentCommit(m_showParentCommit);
410 data.SetGitBlameShowLogControls(m_showLogControls);
411 conf.WriteItem(&data);
412
413 if(m_splitterMain->IsSplit() && !m_showLogControls) {
414 m_sashPositionMain = m_splitterMain->GetSashPosition();
415 m_sashPositionH = m_splitterH->GetSashPosition();
416 m_sashPositionV = m_splitterV->GetSashPosition();
417 m_splitterMain->Unsplit();
418 } else if(m_showLogControls && !m_splitterMain->IsSplit()) {
419 m_splitterMain->SplitHorizontally(m_splitterPageTop, m_splitterPageBottom, m_sashPositionMain);
420 m_splitterH->SetSashPosition(m_sashPositionH);
421 m_splitterV->SetSashPosition(m_sashPositionV);
422 }
423 }
424 }
425
426 GitBlameSettingsDlg::GitBlameSettingsDlg(wxWindow* parent, bool showParentCommit, bool showLogControls)
427 : GitBlameSettingsDlgBase(parent)
428 {
429 m_checkParentCommit->SetValue(showParentCommit);
430 m_checkShowLogControls->SetValue(showLogControls);
431 }
432
433 void GitBlameDlg::OnChangeFile(wxCommandEvent& event)
434 {
435 int sel = m_fileListBox->GetSelection();
436 wxString file = m_fileListBox->GetString(sel);
437 m_stcDiff->SetReadOnly(false);
438 m_stcDiff->SetText(m_diffMap[file]);
439 m_stcDiff->SetReadOnly(true);
440 }
441
442 void GitBlameDlg::OnProcessTerminated(clProcessEvent& event)
443 {
444 wxUnusedVar(event);
445 wxDELETE(m_process);
446
447 m_stcCommitMessage->SetEditable(true);
448 m_stcDiff->SetEditable(true);
449 m_stcCommitMessage->ClearAll();
450 m_fileListBox->Clear();
451 m_diffMap.clear();
452 m_stcDiff->ClearAll();
453 m_commandOutput.Replace(wxT("\r"), wxT(""));
454
455 wxArrayString commitMessage;
456 GitDiffOutputParser diff_parser;
457 diff_parser.GetDiffMap(m_commandOutput, m_diffMap, &commitMessage);
458
459 for(wxStringMap_t::iterator it = m_diffMap.begin(); it != m_diffMap.end(); ++it) {
460 m_fileListBox->Append((*it).first);
461 }
462
463 if(m_diffMap.size() != 0) {
464 wxString file = m_plugin->GetEditorRelativeFilepath();
465 m_stcDiff->SetText(m_diffMap[file]);
466 m_fileListBox->SetStringSelection(file);
467 }
468
469 for(size_t i = 0; i < commitMessage.GetCount(); ++i) {
470 m_stcCommitMessage->AppendText(commitMessage.Item(i));
471 }
472
473 m_stcDiff->SetEditable(false);
474 m_commandOutput.Clear();
475 m_stcCommitMessage->SetEditable(false);
476 }
477
478 void GitBlameDlg::OnProcessOutput(clProcessEvent& event) { m_commandOutput.Append(event.GetOutput()); }
479
480 void GitBlameDlg::UpdateLogControls(const wxString& commit)
481 {
482 if(!commit.empty()) {
483 wxString command_args;
484 command_args << "--no-pager show " << commit;
485 m_process = m_plugin->AsyncRunGit(this, command_args, IProcessCreateDefault | IProcessWrapInShell,
486 m_plugin->GetRepositoryPath());
487 }
488 }
489
490 void GitBlameDlg::Show()
491 {
492 ::clSetDialogBestSizeAndPosition(this);
493 wxDialog::Show();
494 }
495
496 void GitBlameDlg::OnCharHook(wxKeyEvent& event)
497 {
498 event.Skip();
499 if(event.GetKeyCode() == WXK_ESCAPE) {
500 DoCloseDialog();
501 }
502 }