Debian Codegraph @

git/GitConsole.cpp

raw
1 //////////////////////////////////////////////////////////////////////////////
2 //////////////////////////////////////////////////////////////////////////////
3 //
4 // copyright : (C) 2014 Eran Ifrah
5 // file name : GitConsole.cpp
6 //
7 // -------------------------------------------------------------------------
8 // A
9 // _____ _ _ _ _
10 // / __ \ | | | | (_) |
11 // | / \/ ___ __| | ___| | _| |_ ___
12 // | | / _ \ / _ |/ _ \ | | | __/ _ )
13 // | \__/\ (_) | (_| | __/ |___| | || __/
14 // \____/\___/ \__,_|\___\_____/_|\__\___|
15 //
16 // F i l e
17 //
18 // This program is free software; you can redistribute it and/or modify
19 // it under the terms of the GNU General Public License as published by
20 // the Free Software Foundation; either version 2 of the License, or
21 // (at your option) any later version.
22 //
23 //////////////////////////////////////////////////////////////////////////////
24 //////////////////////////////////////////////////////////////////////////////
25
26 #include "GitConsole.h"
27
28 #include "ColoursAndFontsManager.h"
29 #include "GitResetDlg.h"
30 #include "bitmap_loader.h"
31 #include "clAnsiEscapeCodeColourBuilder.hpp"
32 #include "clBitmap.h"
33 #include "clCommandProcessor.h"
34 #include "clToolBar.h"
35 #include "cl_aui_tool_stickness.h"
36 #include "cl_config.h"
37 #include "drawingutils.h"
38 #include "editor_config.h"
39 #include "event_notifier.h"
40 #include "fileextmanager.h"
41 #include "git.h"
42 #include "gitentry.h"
43 #include "globals.h"
44 #include "lexer_configuration.h"
45 #include "macros.h"
46
47 #include <algorithm>
48 #include <wx/datetime.h>
49 #include <wx/icon.h>
50 #include <wx/tokenzr.h>
51 #include <wx/wupdlock.h>
52
53 #define GIT_MESSAGE(...) AddText(wxString::Format(__VA_ARGS__));
54 #define GIT_MESSAGE1(...)
55
56 #define GIT_ITEM_DATA(viewItem) reinterpret_cast<GitClientData*>(m_dvListCtrl->GetItemData(viewItem))
57
58 namespace
59 {
60 enum class eGitFile {
61 kUnknown = -1,
62 kNewFile,
63 kDeletedFile,
64 kModifiedFile,
65 kUntrackedFile,
66 kRenamedFile,
67 };
68
69 class GitClientData
70 {
71 wxString m_path;
72 eGitFile m_kind;
73
74 public:
75 GitClientData(const wxString& path, eGitFile kind)
76 : m_path(path)
77 , m_kind(kind)
78 {
79 }
80 virtual ~GitClientData() {}
81
82 void SetPath(const wxString& path) { this->m_path = path; }
83 const wxString& GetPath() const { return m_path; }
84 eGitFile GetKind() const { return m_kind; }
85 };
86
87 wxVariant MakeFileBitmapLabel(const wxString& filename)
88 {
89 BitmapLoader* bitmaps = clGetManager()->GetStdIcons();
90 clDataViewTextBitmap tb(filename,
91 bitmaps->GetMimeImageId(FileExtManager::GetType(filename, FileExtManager::TypeText)));
92 wxVariant v;
93 v << tb;
94 return v;
95 }
96
97 struct ToolBarItem {
98 wxString label;
99 int id;
100 wxString bmp;
101 };
102 // ---------------------------------------------------------------------
103 void PopulateToolbarOverflow(clToolBar* toolbar)
104 {
105 std::vector<ToolBarItem> items = { { wxTRANSLATE("Create local branch"), XRCID("git_create_branch"), "file_new" },
106 { wxTRANSLATE("Switch to local branch"), XRCID("git_switch_branch"), "split" },
107 { wxTRANSLATE("Switch to remote branch"), XRCID("git_switch_to_remote_branch"),
108 "remote-folder" },
109 { wxEmptyString, wxID_SEPARATOR, wxEmptyString },
110 { wxTRANSLATE("Refresh"), XRCID("git_refresh"), "file_reload" },
111 { wxTRANSLATE("Apply Patch"), XRCID("git_apply_patch"), "patch" },
112 { wxEmptyString, wxID_SEPARATOR, wxEmptyString },
113 { wxTRANSLATE("Start gitk"), XRCID("git_start_gitk"), "debugger_start" },
114 { wxTRANSLATE("Garbage collect"), XRCID("git_garbage_collection"), "clean" },
115 { wxEmptyString, wxID_SEPARATOR, wxEmptyString },
116 { wxTRANSLATE("Plugin settings"), XRCID("git_settings"), "cog" },
117 { wxTRANSLATE("Clone a git repository"), XRCID("git_clone"), "copy" } };
118
119 auto images = toolbar->GetBitmapsCreateIfNeeded();
120 for(auto item : items) {
121 if(item.id == wxID_SEPARATOR) {
122 toolbar->AddSeparator();
123 } else {
124 toolbar->AddTool(item.id, wxGetTranslation(item.label), images->Add(item.bmp));
125 }
126 }
127 }
128
129 struct GitFileEntry {
130 wxString path;
131 wxString fullname;
132 wxString prefix; // entry type (modified, new, etc)
133
134 GitFileEntry(const wxString& rawpath, const wxString& prefix, const wxString& repopath)
135 : path(rawpath)
136 , prefix(prefix)
137 {
138 fullname = rawpath.AfterLast('/');
139 }
140 };
141 } // namespace
142
143 // ---------------------------------------------------------------------
144
145 GitConsole::GitConsole(wxWindow* parent, GitPlugin* git)
146 : GitConsoleBase(parent)
147 , m_git(git)
148 {
149 // set the font to fit the C++ lexer default font
150 m_bitmapLoader = clGetManager()->GetStdIcons();
151 m_dvListCtrl->SetSortedColumn(1);
152 m_dvListCtrl->SetRendererType(eRendererType::RENDERER_DIRECT2D);
153 m_dvListCtrlUnversioned->SetSortedColumn(1);
154 m_dvListCtrlUnversioned->SetRendererType(eRendererType::RENDERER_DIRECT2D);
155
156 // Error messages will be coloured with red
157 m_errorPatterns = { { "fatal:" },
158 { "error:" },
159 { "tell me who you are" },
160 { "hook failure" },
161 { "not a git repository" },
162 { "No commit message given, aborting" } };
163
164 m_successPatterns =
165 // Informative messages, will be coloured with green
166 { { "up to date" }, { "up-to-date" } };
167
168 // yellow
169 m_warningPatterns = { { "the authenticity of host" }, { "can't be established" }, { "key fingerprint" } };
170
171 m_modifiedBmp = m_bitmapLoader->LoadBitmap("modified");
172 m_untrackedBmp = m_bitmapLoader->LoadBitmap("info");
173 m_folderBmp = m_bitmapLoader->LoadBitmap("folder-yellow");
174 m_newBmp = m_bitmapLoader->LoadBitmap("plus");
175 m_deleteBmp = m_bitmapLoader->LoadBitmap("minus");
176
177 EventNotifier::Get()->Connect(wxEVT_GIT_CONFIG_CHANGED, wxCommandEventHandler(GitConsole::OnConfigurationChanged),
178 NULL, this);
179 EventNotifier::Get()->Bind(wxEVT_WORKSPACE_CLOSED, &GitConsole::OnWorkspaceClosed, this);
180 clConfig conf("git.conf");
181 GitEntry data;
182 conf.ReadItem(&data);
183 m_isVerbose = (data.GetFlags() & GitEntry::Git_Verbose_Log);
184
185 // Toolbar
186 auto images = m_toolbar->GetBitmapsCreateIfNeeded();
187 m_toolbar->AddTool(XRCID("git_clear_log"), _("Clear Git Log"), images->Add("clear"), _("Clear Git Log"));
188 m_toolbar->AddTool(XRCID("git_stop_process"), _("Terminate Git Process"), images->Add("execute_stop"),
189 _("Terminate Git Process"));
190 m_toolbar->AddSeparator();
191 m_toolbar->AddTool(XRCID("git_console_add_file"), _("Add File"), images->Add("plus"), _("Add File"));
192 m_toolbar->AddTool(XRCID("git_console_reset_file"), _("Reset File"), images->Add("undo"), _("Reset File"));
193
194 m_toolbar->AddTool(XRCID("git_reset_repository"), _("Reset"), images->Add("clean"), _("Reset repository"));
195 m_toolbar->AddSeparator();
196
197 m_toolbar->AddTool(XRCID("git_pull"), _("Pull"), images->Add("pull"), _("Pull remote changes"), wxITEM_DROPDOWN);
198
199 m_toolbar->AddTool(XRCID("git_commit"), _("Commit"), images->Add("git-commit"), _("Commit local changes"));
200 m_toolbar->AddTool(XRCID("git_push"), _("Push"), images->Add("up"), _("Push local changes"));
201 m_toolbar->AddTool(XRCID("git_rebase"), _("Rebase"), images->Add("merge"), _("Rebase"), wxITEM_DROPDOWN);
202 m_toolbar->AddSeparator();
203 m_toolbar->AddTool(XRCID("git_commit_diff"), _("Diffs"), images->Add("diff"), _("Show current diffs"));
204 m_toolbar->AddTool(XRCID("git_browse_commit_list"), _("Log"), images->Add("tasks"), _("Browse commit history"));
205 m_toolbar->AddTool(XRCID("git_blame"), _("Blame"), images->Add("finger"), _("Git blame"));
206
207 #ifdef __WXMSW__
208 m_toolbar->AddSeparator();
209 m_toolbar->AddTool(XRCID("git_msysgit"), _("Open MSYS Git"), images->Add("console"),
210 _("Open MSYS Git at the current file location"));
211 #endif
212
213 // Bind the events
214 m_toolbar->Bind(wxEVT_MENU, &GitConsole::OnClearGitLog, this, XRCID("git_clear_log"));
215 m_toolbar->Bind(wxEVT_UPDATE_UI, &GitConsole::OnClearGitLogUI, this, XRCID("git_clear_log"));
216 m_toolbar->Bind(wxEVT_MENU, &GitConsole::OnResetFile, this, XRCID("git_console_reset_file"));
217 m_toolbar->Bind(wxEVT_MENU, &GitConsole::OnStopGitProcess, this, XRCID("git_stop_process"));
218 m_toolbar->Bind(wxEVT_UPDATE_UI, &GitConsole::OnStopGitProcessUI, this, XRCID("git_stop_process"));
219
220 PopulateToolbarOverflow(m_toolbar);
221 m_toolbar->Realize();
222 m_toolbar->Bind(wxEVT_TOOL_DROPDOWN, &GitConsole::OnGitPullDropdown, this, XRCID("git_pull"));
223 m_toolbar->Bind(wxEVT_TOOL_DROPDOWN, &GitConsole::OnGitRebaseDropdown, this, XRCID("git_rebase"));
224 m_gauge->Hide();
225 GetSizer()->Fit(this);
226
227 m_dvListCtrl->SetBitmaps(clGetManager()->GetStdIcons()->GetStandardMimeBitmapListPtr());
228 m_dvListCtrlUnversioned->SetBitmaps(clGetManager()->GetStdIcons()->GetStandardMimeBitmapListPtr());
229 EventNotifier::Get()->Bind(wxEVT_BITMAPS_UPDATED, [this](clCommandEvent& event) {
230 event.Skip();
231 m_dvListCtrl->SetBitmaps(clGetManager()->GetStdIcons()->GetStandardMimeBitmapListPtr());
232 m_dvListCtrlUnversioned->SetBitmaps(clGetManager()->GetStdIcons()->GetStandardMimeBitmapListPtr());
233 m_dvListCtrl->Refresh();
234 m_dvListCtrlUnversioned->Refresh();
235 });
236
237 EventNotifier::Get()->Bind(wxEVT_SYS_COLOURS_CHANGED, &GitConsole::OnSysColoursChanged, this);
238
239 // force font/colours udpate
240 clCommandEvent dummy;
241 OnSysColoursChanged(dummy);
242 }
243
244 GitConsole::~GitConsole()
245 {
246 EventNotifier::Get()->Disconnect(wxEVT_GIT_CONFIG_CHANGED,
247 wxCommandEventHandler(GitConsole::OnConfigurationChanged), NULL, this);
248 EventNotifier::Get()->Unbind(wxEVT_WORKSPACE_CLOSED, &GitConsole::OnWorkspaceClosed, this);
249 m_toolbar->Unbind(wxEVT_TOOL_DROPDOWN, &GitConsole::OnGitPullDropdown, this, XRCID("git_pull"));
250 m_toolbar->Unbind(wxEVT_TOOL_DROPDOWN, &GitConsole::OnGitRebaseDropdown, this, XRCID("git_rebase"));
251 EventNotifier::Get()->Unbind(wxEVT_SYS_COLOURS_CHANGED, &GitConsole::OnSysColoursChanged, this);
252 }
253
254 void GitConsole::OnClearGitLog(wxCommandEvent& event)
255 {
256 wxUnusedVar(event);
257 m_dvListCtrlLog->DeleteAllItems();
258 }
259
260 void GitConsole::OnStopGitProcess(wxCommandEvent& event)
261 {
262 if(m_git->GetProcess()) {
263 m_git->GetProcess()->Terminate();
264 }
265
266 if(m_git->GetFolderProcess()) {
267 m_git->GetFolderProcess()->Terminate();
268 }
269 }
270
271 void GitConsole::OnStopGitProcessUI(wxUpdateUIEvent& event)
272 {
273 event.Enable(m_git->GetProcess() || m_git->GetFolderProcess());
274 }
275
276 void GitConsole::OnClearGitLogUI(wxUpdateUIEvent& event) { event.Enable(!m_dvListCtrlLog->IsEmpty()); }
277
278 bool GitConsole::IsPatternFound(const wxString& buffer, const std::unordered_set<wxString>& m) const
279 {
280 wxString lc = buffer.Lower();
281 for(const auto& s : m) {
282 if(lc.Contains(s)) {
283 return true;
284 }
285 }
286 return false;
287 }
288
289 bool GitConsole::HasAnsiEscapeSequences(const wxString& buffer) const
290 {
291 wxChar ch = 0x1B;
292 return buffer.find(ch) != wxString::npos;
293 }
294
295 void GitConsole::AddText(const wxString& text)
296 {
297 auto lines = ::wxStringTokenize(text, "\n", wxTOKEN_STRTOK);
298 for(const auto& line : lines) {
299 AddLine(line);
300 }
301 }
302
303 bool GitConsole::IsVerbose() const { return m_isVerbose; }
304
305 void GitConsole::OnConfigurationChanged(wxCommandEvent& e)
306 {
307 e.Skip();
308 clConfig conf("git.conf");
309 GitEntry data;
310 conf.ReadItem(&data);
311 m_isVerbose = (data.GetFlags() & GitEntry::Git_Verbose_Log);
312 }
313
314 void GitConsole::UpdateTreeView(const wxString& output)
315 {
316 Clear();
317 wxVector<wxVariant> cols;
318 wxArrayString files = ::wxStringTokenize(output, "\n\r", wxTOKEN_STRTOK);
319
320 // parse the output
321 std::vector<GitFileEntry> lines;
322 lines.reserve(files.size());
323
324 for(wxString& filename : files) {
325
326 filename.Trim().Trim(false);
327 filename.Replace("\t", " ");
328 filename.Replace("\\", "/");
329
330 wxString prefix = filename.BeforeFirst(' ');
331 filename = filename.AfterFirst(' ');
332
333 filename.Trim().Trim(false);
334 if(filename.EndsWith("/"))
335 // a directory
336 continue;
337
338 GitFileEntry entry(filename, prefix, m_git->GetRepositoryPath());
339 lines.push_back(entry);
340 }
341
342 auto sort_cb = [](const GitFileEntry& a, const GitFileEntry& b) {
343 const wxString& fpa = a.path;
344 const wxString& fpb = b.path;
345 return fpa.CmpNoCase(fpb) < 0;
346 };
347 std::sort(lines.begin(), lines.end(), std::move(sort_cb));
348
349 for(const auto& d : lines) {
350 wxString filename = d.fullname;
351 wxChar chX = d.prefix[0];
352
353 wxBitmap statusBmp;
354 eGitFile kind = eGitFile::kUntrackedFile;
355 switch(chX) {
356 case 'M':
357 statusBmp = m_modifiedBmp;
358 kind = eGitFile::kModifiedFile;
359 break;
360 case 'A':
361 statusBmp = m_newBmp;
362 kind = eGitFile::kNewFile;
363 break;
364 case 'D':
365 statusBmp = m_deleteBmp;
366 kind = eGitFile::kDeletedFile;
367 break;
368 case 'R':
369 statusBmp = m_modifiedBmp;
370 kind = eGitFile::kRenamedFile;
371 break;
372 default:
373 statusBmp = m_untrackedBmp;
374 kind = eGitFile::kUntrackedFile;
375 break;
376 }
377
378 if(kind == eGitFile::kUntrackedFile) {
379 // untracked
380 cols.clear();
381 cols.push_back(MakeFileBitmapLabel(d.path));
382 m_dvListCtrlUnversioned->AppendItem(cols, (wxUIntPtr) new GitClientData(d.path, kind));
383 } else {
384 // modified
385 cols.clear();
386 cols.push_back(wxString() << chX);
387 cols.push_back(MakeFileBitmapLabel(d.path));
388 m_dvListCtrl->AppendItem(cols, (wxUIntPtr) new GitClientData(d.path, kind));
389 }
390 }
391 }
392
393 void GitConsole::OnContextMenu(wxDataViewEvent& event)
394 {
395 bool hasSelection = (m_dvListCtrl->GetSelectedItemsCount() > 0);
396 if(!hasSelection) {
397 return;
398 }
399
400 wxMenu menu;
401 menu.Append(XRCID("git_console_open_file"), _("Open File"));
402 menu.AppendSeparator();
403 menu.Append(XRCID("git_console_reset_file"), _("Reset file"));
404
405 menu.Bind(wxEVT_MENU, &GitConsole::OnOpenFile, this, XRCID("git_console_open_file"));
406 menu.Bind(wxEVT_MENU, &GitConsole::OnResetFile, this, XRCID("git_console_reset_file"));
407 m_dvListCtrl->PopupMenu(&menu);
408 }
409
410 void GitConsole::OnResetFile(wxCommandEvent& event)
411 {
412 wxDataViewItemArray items;
413 m_dvListCtrl->GetSelections(items);
414 wxArrayString filesToRevert, filesToRemove;
415
416 for(size_t i = 0; i < items.GetCount(); ++i) {
417 GitClientData* gcd = GIT_ITEM_DATA(items.Item(i));
418 if(gcd) {
419 if(gcd->GetKind() == eGitFile::kNewFile) {
420 filesToRemove.push_back(gcd->GetPath());
421
422 } else if((gcd->GetKind() == eGitFile::kModifiedFile) || (gcd->GetKind() == eGitFile::kRenamedFile)) {
423 filesToRevert.push_back(gcd->GetPath());
424 }
425 }
426 }
427 if(filesToRevert.IsEmpty() && filesToRemove.IsEmpty()) {
428 return;
429 }
430
431 GitResetDlg dlg(EventNotifier::Get()->TopFrame(), filesToRevert, filesToRemove);
432 if(dlg.ShowModal() != wxID_OK) {
433 return;
434 }
435
436 filesToRevert = dlg.GetItemsToRevert();
437 filesToRemove = dlg.GetItemsToRemove();
438
439 if(!filesToRevert.IsEmpty()) {
440 m_git->ResetFiles(filesToRevert);
441 }
442
443 if(!filesToRemove.IsEmpty()) {
444 m_git->UndoAddFiles(filesToRemove);
445 }
446 }
447
448 void GitConsole::OnWorkspaceClosed(clWorkspaceEvent& e)
449 {
450 e.Skip();
451 Clear();
452
453 wxCommandEvent dummy;
454 OnClearGitLog(dummy);
455 }
456
457 void GitConsole::OnItemSelectedUI(wxUpdateUIEvent& event) { event.Enable(m_dvListCtrl->GetSelectedItemsCount()); }
458
459 void GitConsole::OnFileActivated(wxDataViewEvent& event)
460 {
461 CHECK_ITEM_RET(event.GetItem());
462
463 wxArrayString files;
464 GitClientData* gcd = GIT_ITEM_DATA(event.GetItem());
465 if(gcd) {
466 GIT_MESSAGE("Showing diff for: %s", gcd->GetPath().c_str());
467 files.push_back(gcd->GetPath());
468 m_git->ShowDiff(files);
469 }
470 }
471
472 void GitConsole::OnOpenFile(wxCommandEvent& e)
473 {
474 wxDataViewItemArray items;
475 m_dvListCtrl->GetSelections(items);
476 wxArrayString files;
477 for(size_t i = 0; i < items.GetCount(); ++i) {
478 GitClientData* gcd = GIT_ITEM_DATA(items.Item(i));
479 if(gcd) {
480 files.push_back(gcd->GetPath());
481 }
482 }
483
484 if(files.IsEmpty()) {
485 e.Skip();
486 return;
487 }
488
489 // open the files
490 for(size_t i = 0; i < files.GetCount(); ++i) {
491 GIT_MESSAGE("Opening file: %s", files.Item(i).c_str());
492 m_git->OpenFile(files.Item(i));
493 }
494 }
495
496 void GitConsole::OnApplyPatch(wxCommandEvent& event) { wxPostEvent(m_git, event); }
497
498 struct GitCommandData : public wxObject {
499 GitCommandData(const wxArrayString a, const wxString n, int i)
500 : arr(a)
501 , name(n)
502 , id(i)
503 {
504 }
505 wxArrayString arr; // Holds the possible command-strings
506 wxString name; // Holds the name of the command e.g. "git_pull"
507 int id; // Holds the id of the command e.g. XRCID("git_pull")
508 };
509
510 void GitConsole::DoOnDropdown(const wxString& commandName, int id)
511 {
512 GitEntry data;
513 {
514 clConfig conf("git.conf");
515 conf.ReadItem(&data);
516 } // Force conf out of scope, else its dtor clobbers the GitConsole::OnDropDownMenuEvent Save()
517 GitCommandsEntries& ce = data.GetGitCommandsEntries(commandName);
518 vGitLabelCommands_t entries = ce.GetCommands();
519 int lastUsed = ce.GetLastUsedCommandIndex();
520
521 wxArrayString arr;
522 wxMenu menu;
523 for(size_t n = 0; n < entries.size(); ++n) {
524 wxMenuItem* item = menu.AppendRadioItem(n, entries.at(n).label);
525 item->Check(n == (size_t)lastUsed);
526 arr.Add(entries.at(n).command);
527 }
528 menu.Bind(wxEVT_MENU, wxCommandEventHandler(GitConsole::OnDropDownMenuEvent), this, 0, arr.GetCount(),
529 new GitCommandData(arr, commandName, id));
530
531 m_toolbar->ShowMenuForButton(id, &menu);
532 menu.Unbind(wxEVT_MENU, wxCommandEventHandler(GitConsole::OnDropDownMenuEvent), this, 0, arr.GetCount(),
533 new GitCommandData(arr, commandName, id));
534 }
535
536 void GitConsole::OnDropDownMenuEvent(wxCommandEvent& event)
537 {
538 int id = event.GetId();
539 GitCommandData* userdata = static_cast<GitCommandData*>(event.GetEventUserData());
540 wxCHECK_RET((int)userdata->arr.GetCount() > event.GetId(), "Out-of-range ID");
541 event.SetString(userdata->arr.Item(id));
542 event.SetId(userdata->id);
543
544 wxPostEvent(m_git, event); // We've now populated the event object with useful data, so get GitPlugin to process it
545
546 clConfig conf("git.conf");
547 GitEntry data;
548 conf.ReadItem(&data);
549 GitCommandsEntries& ce = data.GetGitCommandsEntries(userdata->name);
550 ce.SetLastUsedCommandIndex(id);
551 conf.WriteItem(&data);
552 conf.Save();
553 }
554
555 void GitConsole::HideProgress()
556 {
557 if(m_gauge->IsShown()) {
558 m_gauge->SetValue(0);
559 m_gauge->Hide();
560 GetSizer()->Layout();
561 }
562 }
563
564 void GitConsole::ShowProgress(const wxString& message, bool pulse)
565 {
566 if(!m_gauge->IsShown()) {
567 m_gauge->Show();
568 GetSizer()->Layout();
569 }
570
571 if(pulse) {
572 m_gauge->Pulse();
573 m_gauge->Update();
574
575 } else {
576 m_gauge->SetValue(0);
577 m_gauge->Update();
578 }
579 }
580
581 void GitConsole::UpdateProgress(unsigned long current, const wxString& message)
582 {
583 wxString trimmedMessage = message;
584 m_gauge->SetValue(wxMin(current, m_gauge->GetRange()));
585 // m_staticTextGauge->SetLabel(trimmedMessage.Trim().Trim(false));
586 }
587
588 bool GitConsole::IsProgressShown() const { return m_gauge->IsShown(); }
589
590 void GitConsole::PulseProgress() { m_gauge->Pulse(); }
591
592 bool GitConsole::IsDirty() const { return (m_dvListCtrl->GetItemCount() > 0); }
593
594 void GitConsole::OnStclogStcChange(wxStyledTextEvent& event) { event.Skip(); }
595
596 void GitConsole::Clear()
597 {
598 m_dvListCtrl->DeleteAllItems([](wxUIntPtr d) {
599 GitClientData* cd = reinterpret_cast<GitClientData*>(d);
600 if(cd) {
601 wxDELETE(cd);
602 }
603 });
604
605 m_dvListCtrlUnversioned->DeleteAllItems([](wxUIntPtr d) {
606 GitClientData* cd = reinterpret_cast<GitClientData*>(d);
607 if(cd) {
608 wxDELETE(cd);
609 }
610 });
611 }
612
613 void GitConsole::OnUpdateUI(wxUpdateUIEvent& event) { event.Enable(!m_git->GetRepositoryPath().IsEmpty()); }
614
615 void GitConsole::OnUnversionedFileActivated(wxDataViewEvent& event)
616 {
617 CHECK_ITEM_RET(event.GetItem());
618 GitClientData* cd = reinterpret_cast<GitClientData*>(m_dvListCtrlUnversioned->GetItemData(event.GetItem()));
619 CHECK_PTR_RET(cd);
620 clGetManager()->OpenFile(cd->GetPath());
621 }
622
623 void GitConsole::OnUnversionedFileContextMenu(wxDataViewEvent& event)
624 {
625 wxMenu menu;
626 menu.Append(wxID_OPEN);
627 menu.Append(wxID_ADD);
628 menu.Bind(wxEVT_MENU, &GitConsole::OnOpenUnversionedFiles, this, wxID_OPEN);
629 menu.Bind(wxEVT_MENU, &GitConsole::OnAddUnversionedFiles, this, wxID_ADD);
630 m_dvListCtrlUnversioned->PopupMenu(&menu);
631 }
632
633 wxArrayString GitConsole::GetSelectedUnversionedFiles() const
634 {
635 if(m_dvListCtrlUnversioned->GetSelectedItemsCount() == 0) {
636 return wxArrayString();
637 }
638 wxArrayString paths;
639 wxDataViewItemArray items;
640 int count = m_dvListCtrlUnversioned->GetSelections(items);
641 for(int i = 0; i < count; i++) {
642 wxDataViewItem item = items.Item(i);
643 if(item.IsOk() == false) {
644 continue;
645 }
646
647 GitClientData* cd = reinterpret_cast<GitClientData*>(m_dvListCtrlUnversioned->GetItemData(item));
648 if(cd && cd->GetKind() == eGitFile::kUntrackedFile) {
649 paths.Add(cd->GetPath());
650 }
651 }
652 return paths;
653 }
654
655 void GitConsole::OnOpenUnversionedFiles(wxCommandEvent& event)
656 {
657 wxUnusedVar(event);
658 wxArrayString paths = GetSelectedUnversionedFiles();
659 if(paths.IsEmpty()) {
660 return;
661 }
662
663 for(const wxString& filepath : paths) {
664 if(!filepath.EndsWith("/")) {
665 m_git->OpenFile(filepath);
666 }
667 }
668 }
669
670 void GitConsole::OnAddUnversionedFiles(wxCommandEvent& event)
671 {
672 wxUnusedVar(event);
673 m_git->AddFiles(GetSelectedUnversionedFiles());
674 }
675
676 void GitConsole::ShowLog()
677 {
678 // Change the selection to the "Log" view
679 // m_notebookLog->SetSelection(m_notebookLog->GetPageIndex(_("Log")));
680 }
681
682 wxString GitConsole::GetPrompt() const
683 {
684 wxString prompt_str = m_git->GetRepositoryPath();
685 #ifndef __WXMSW__
686 wxString home_dir = ::wxGetHomeDir();
687 if(prompt_str.StartsWith(home_dir)) {
688 prompt_str.Replace(home_dir, "~", false);
689 }
690 #endif
691 return prompt_str;
692 }
693
694 void GitConsole::AddLine(const wxString& line)
695 {
696 wxString tmp = line;
697 bool text_ends_with_cr = line.EndsWith("\r");
698 tmp.Replace("\r", wxEmptyString);
699 tmp.Trim();
700
701 auto& builder = m_dvListCtrlLog->GetBuilder();
702 builder.Clear();
703
704 if(HasAnsiEscapeSequences(tmp)) {
705 builder.Add(tmp, eAsciiColours::NORMAL_TEXT);
706 } else {
707 if(IsPatternFound(tmp, m_errorPatterns)) {
708 builder.Add(tmp, eAsciiColours::RED);
709 } else if(IsPatternFound(tmp, m_warningPatterns)) {
710 builder.Add(tmp, eAsciiColours::YELLOW);
711 } else if(IsPatternFound(tmp, m_successPatterns)) {
712 builder.Add(tmp, eAsciiColours::GREEN);
713 } else {
714 builder.Add(tmp, eAsciiColours::NORMAL_TEXT);
715 }
716 }
717 m_dvListCtrlLog->AddLine(builder.GetString(), text_ends_with_cr);
718 }
719
720 void GitConsole::PrintPrompt()
721 {
722 auto& builder = m_dvListCtrlLog->GetBuilder();
723 builder.Clear();
724 builder.Add(GetPrompt(), eAsciiColours::GREEN, true);
725 m_dvListCtrlLog->AddLine(builder.GetString(), false);
726 builder.Clear();
727 }
728
729 void GitConsole::OnSysColoursChanged(clCommandEvent& event)
730 {
731 event.Skip();
732 auto font = ColoursAndFontsManager::Get().GetFixedFont();
733 m_dvListCtrl->SetDefaultFont(font);
734 m_dvListCtrlLog->SetDefaultFont(font);
735 m_dvListCtrlUnversioned->SetDefaultFont(font);
736 }