Debian Codegraph @

plugins/vcs/ui/VcsStatus.cpp

raw
1 #include "VcsStatus.h"
2
3 #include "i18n.h"
4 #include "imap.h"
5 #include "ui/iuserinterface.h"
6 #include "ui/imainframe.h"
7 #include "imapformat.h"
8
9 #include <wx/sizer.h>
10 #include <wx/bmpbuttn.h>
11 #include <sigc++/functors/mem_fun.h>
12
13 #include "registry/registry.h"
14 #include "os/file.h"
15 #include "os/path.h"
16 #include "os/fs.h"
17 #include "string/convert.h"
18 #include "gamelib.h"
19 #include "wxutil/menu/CommandMenuItem.h"
20 #include "wxutil/menu/IconTextMenuItem.h"
21 #include "wxutil/dialog/MessageBox.h"
22 #include "util/ScopedBoolLock.h"
23 #include "CommitDialog.h"
24 #include "../GitModule.h"
25 #include "../Diff.h"
26 #include "../GitException.h"
27 #include "../Algorithm.h"
28
29 namespace vcs
30 {
31
32 namespace ui
33 {
34
35 VcsStatus::VcsStatus(wxWindow* parent) :
36 _panel(loadNamedPanel(parent, "VcsStatusBar")),
37 _fetchTimer(this),
38 _statusTimer(this),
39 _taskInProgress(false),
40 _popupMenu(new wxutil::PopupMenu)
41 {
42 _mapStatus = findNamedObject<wxStaticText>(_panel, "MapStatusLabel");
43 _remoteStatus = findNamedObject<wxStaticText>(_panel, "RemoteStatusLabel");
44
45 _panel->SetMinSize(wxSize(300, -1));
46
47 auto* vcsMenu = findNamedObject<wxBitmapButton>(_panel, "VcsMenuButton");
48 vcsMenu->Hide();
49 vcsMenu->Bind(wxEVT_BUTTON, [this] (wxCommandEvent& ev)
50 {
51 _popupMenu->show(wxDynamicCast(ev.GetEventObject(), wxWindow));
52 });
53
54 Bind(wxEVT_TIMER, &VcsStatus::onIntervalReached, this);
55 _panel->Bind(wxEVT_IDLE, &VcsStatus::onIdle, this);
56
57 GlobalRegistry().signalForKey(RKEY_AUTO_FETCH_ENABLED).connect(
58 sigc::mem_fun(this, &VcsStatus::restartFetchTimer)
59 );
60 GlobalRegistry().signalForKey(RKEY_AUTO_FETCH_INTERVAL).connect(
61 sigc::mem_fun(this, &VcsStatus::restartFetchTimer)
62 );
63
64 GlobalMapModule().signal_modifiedChanged().connect(
65 sigc::mem_fun(this, &VcsStatus::updateMapFileStatus)
66 );
67
68 GlobalMapModule().signal_mapEvent().connect(
69 sigc::mem_fun(this, &VcsStatus::onMapEvent)
70 );
71
72 createPopupMenu();
73
74 _statusTimer.Start(5000);
75 }
76
77 VcsStatus::~VcsStatus()
78 {
79 _fetchTimer.Stop();
80 _statusTimer.Stop();
81
82 if (_repositoryTask.valid())
83 {
84 _repositoryTask.get(); // Wait for the thread to complete
85 }
86
87 if (_mapFileTask.valid())
88 {
89 _mapFileTask.get(); // Wait for the thread to complete
90 }
91
92 _panel->Destroy();
93 }
94
95 wxWindow* VcsStatus::getWidget()
96 {
97 return _panel;
98 }
99
100 void VcsStatus::createPopupMenu()
101 {
102 _popupMenu->addItem(std::make_shared<wxutil::MenuItem>(
103 new wxMenuItem(nullptr, wxID_ANY, _("Commit"), ""),
104 [this]() { performCommit(); },
105 [this]() { return canCommit(); }
106
107 ));
108 _popupMenu->addItem(std::make_shared<wxutil::CommandMenuItem>(
109 new wxMenuItem(nullptr, wxID_ANY, _("Check for Server Changes"), ""),
110 "GitFetch",
111 [this]() { return !_taskInProgress; }
112 ));
113
114 _popupMenu->addItem(std::make_shared<wxutil::MenuItem>(
115 new wxMenuItem(nullptr, wxID_ANY, _("Sync/Integrate Server Changes"), ""),
116 [this]() { performSync(_repository); },
117 [this]() { return canSync(); }
118 ));
119 }
120
121 void VcsStatus::setRepository(const std::shared_ptr<git::Repository>& repository)
122 {
123 _repository = repository;
124
125 findNamedObject<wxBitmapButton>(_panel, "VcsMenuButton")->Show(_repository != nullptr);
126
127 if (!_repository)
128 {
129 _remoteStatus->SetLabel(_("Not under version control"));
130 _fetchTimer.Stop();
131 return;
132 }
133
134 _remoteStatus->SetLabel(_repository->getCurrentBranchName());
135 restartFetchTimer();
136
137 // Run a fetch update right after connecting to the repo, if auto-fetch is enabled
138 if (registry::getValue<bool>(RKEY_AUTO_FETCH_ENABLED))
139 {
140 startFetchTask();
141 }
142 }
143
144 void VcsStatus::restartFetchTimer()
145 {
146 _fetchTimer.Stop();
147
148 if (registry::getValue<bool>(RKEY_AUTO_FETCH_ENABLED))
149 {
150 int interval = static_cast<int>(registry::getValue<float>(RKEY_AUTO_FETCH_INTERVAL) * 60 * 1000);
151
152 if (interval > 0)
153 {
154 _fetchTimer.Start(interval);
155 }
156 }
157 }
158
159 void VcsStatus::onMapEvent(IMap::MapEvent ev)
160 {
161 if (ev == IMap::MapSaved || ev == IMap::MapLoaded)
162 {
163 updateMapFileStatus();
164
165 if (_repository)
166 {
167 analyseRemoteStatus(_repository);
168 }
169 }
170
171 // Only when saving: check whether a merge is to be completed
172 if (ev == IMap::MapSaved && _repository && _repository->mergeIsInProgress())
173 {
174 auto mapPath = _repository->getRepositoryRelativePath(GlobalMapModule().getMapName());
175 auto index = _repository->getIndex();
176
177 // Remove the conflict state of the map file after save
178 resolveMapFileConflictUsingOurs(_repository);
179
180 if (wxutil::Messagebox::Show(_("Complete Merge Operation?"),
181 _("Map has been saved. Do you want to complete the ongoing merge operation using this state?"),
182 ::ui::IDialog::MessageType::MESSAGE_ASK) == ::ui::IDialog::RESULT_YES)
183 {
184 try
185 {
186 tryToFinishMerge(_repository);
187 }
188 catch (git::GitException& ex)
189 {
190 wxutil::Messagebox::ShowError(ex.what());
191 }
192
193 analyseRemoteStatus(_repository);
194 return;
195 }
196 }
197
198 if (ev == IMap::MapMergeOperationAborted && _repository && _repository->mergeIsInProgress())
199 {
200 // Ask the user whether to cancel the git merge status
201 if (wxutil::Messagebox::Show(_("Cancel Merge Operation?"),
202 _("You've aborted the map merge. Do you want to abort the ongoing git merge operation too?\n"
203 "This will perform a hard reset in the repository to the state it had before the merge was started.\n\n"
204 "Important: All uncommitted changes in the working tree will be lost!"),
205 ::ui::IDialog::MessageType::MESSAGE_ASK) == ::ui::IDialog::RESULT_YES)
206 {
207 try
208 {
209 _repository->abortMerge();
210 }
211 catch (git::GitException& ex)
212 {
213 wxutil::Messagebox::ShowError(ex.what());
214 }
215
216 analyseRemoteStatus(_repository);
217 }
218 }
219 else if (ev == IMap::MapMergeOperationFinished && _repository && _repository->mergeIsInProgress())
220 {
221 wxutil::Messagebox::Show(_("Save the File to complete the Merge"),
222 _("Now that the map is merged, please save the file\nsuch that the git operation can be completed."),
223 ::ui::IDialog::MessageType::MESSAGE_CONFIRM);
224
225 // Now wait for the merge to complete (MapSaved event)
226 }
227 }
228
229 void VcsStatus::startFetchTask()
230 {
231 {
232 std::lock_guard<std::mutex> guard(_taskLock);
233
234 if (_taskInProgress || !_repository) return;
235
236 if (!GlobalMainFrame().isActiveApp())
237 {
238 rMessage() << "Skipping fetch this round, since the app is not active." << std::endl;
239 return;
240 }
241
242 _taskInProgress = true;
243 }
244
245 auto repository = _repository->clone();
246 _repositoryTask = std::async(std::launch::async, std::bind(&VcsStatus::performFetch, this, repository));
247 }
248
249 void VcsStatus::onIntervalReached(wxTimerEvent& ev)
250 {
251 if (ev.GetTimer().GetId() == _fetchTimer.GetId())
252 {
253 startFetchTask();
254 }
255 else if (ev.GetTimer().GetId() == _statusTimer.GetId())
256 {
257 updateMapFileStatus();
258 }
259 }
260
261 void VcsStatus::updateMapFileStatus()
262 {
263 if (GlobalMapModule().isUnnamed())
264 {
265 setMapFileStatus(_("Map not saved yet"));
266 return;
267 }
268
269 if (GlobalMapModule().getActiveMergeOperation())
270 {
271 setMapFileStatus(_("Merging"));
272 return;
273 }
274
275 if (GlobalMapModule().isModified())
276 {
277 _mapStatus->SetLabel(_("Map is modified"));
278 return;
279 }
280
281 if (_repository)
282 {
283 auto repository = _repository->clone();
284 _mapFileTask = std::async(std::launch::async, std::bind(&VcsStatus::performMapFileStatusCheck, this, repository));
285 }
286 else
287 {
288 _mapStatus->SetLabel(_("Map is saved"));
289 }
290 }
291
292 void VcsStatus::onIdle(wxIdleEvent& ev)
293 {
294 ev.Skip();
295 }
296
297 void VcsStatus::performFetch(std::shared_ptr<git::Repository> repository)
298 {
299 auto head = repository->getHead();
300
301 if (!head)
302 {
303 _taskInProgress = false;
304 return;
305 }
306
307 try
308 {
309 repository->getUpstreamRemoteName(*head);
310 }
311 catch (const git::GitException&)
312 {
313 setRemoteStatus(git::RemoteStatus{ 0, 0, _("Not connected") });
314 _taskInProgress = false;
315 return;
316 }
317
318 try
319 {
320 setRemoteStatus(git::RemoteStatus{ 0, 0, _("Fetching...") });
321
322 repository->fetchFromTrackedRemote();
323 }
324 catch (const git::GitException& ex)
325 {
326 setRemoteStatus(git::RemoteStatus{ 0, 0, ex.what() });
327 }
328
329 analyseRemoteStatus(repository);
330
331 _taskInProgress = false;
332 }
333
334 void VcsStatus::analyseRemoteStatus(std::shared_ptr<git::Repository> repository)
335 {
336 try
337 {
338 setRemoteStatus(git::analyseRemoteStatus(repository));
339 }
340 catch (git::GitException& ex)
341 {
342 setRemoteStatus(git::RemoteStatus{ 0, 0, ex.what() });
343 }
344 }
345
346 void VcsStatus::performSync(std::shared_ptr<git::Repository> repository)
347 {
348 try
349 {
350 syncWithRemote(repository);
351 setRemoteStatus(git::analyseRemoteStatus(repository));
352 }
353 catch (git::GitException& ex)
354 {
355 setRemoteStatus(git::RemoteStatus{ 0, 0, ex.what() });
356 wxutil::Messagebox::ShowError(ex.what());
357 }
358 }
359
360 bool VcsStatus::canSync()
361 {
362 return !_taskInProgress && _repository && !_repository->mergeIsInProgress();
363 }
364
365 bool VcsStatus::canCommit()
366 {
367 return !_taskInProgress && _repository && !_repository->mergeIsInProgress();
368 }
369
370 void VcsStatus::performCommit()
371 {
372 if (!_repository) return;
373
374 {
375 std::lock_guard<std::mutex> guard(_taskLock);
376
377 if (_taskInProgress)
378 {
379 wxutil::Messagebox::Show(_("Another Task in progress"),
380 _("Cannot commit when another task is in progress"),
381 ::ui::IDialog::MessageType::MESSAGE_CONFIRM);
382 return;
383 }
384
385 _taskInProgress = true;
386 }
387
388 try
389 {
390 git::CommitMetadata metadata;
391
392 metadata.name = _repository->getConfigValue("user.name");
393 metadata.email = _repository->getConfigValue("user.email");
394
395 metadata = CommitDialog::RunDialog(metadata);
396
397 if (metadata.isValid())
398 {
399 _repository->createCommit(metadata);
400 }
401
402 analyseRemoteStatus(_repository);
403 }
404 catch (const git::GitException& ex)
405 {
406 wxutil::Messagebox::ShowError(ex.what());
407 }
408
409 {
410 std::lock_guard<std::mutex> guard(_taskLock);
411 _taskInProgress = false;
412 }
413 }
414
415 void VcsStatus::setMapFileStatus(const std::string& status)
416 {
417 GlobalUserInterface().dispatch([this, status]() { _mapStatus->SetLabel(status); });
418 }
419
420 void VcsStatus::setRemoteStatus(const git::RemoteStatus& status)
421 {
422 GlobalUserInterface().dispatch([this, status]()
423 {
424 findNamedObject<wxWindow>(_panel, "OutgoingCommitsIcon")->Show(status.localAheadCount > 0);
425 findNamedObject<wxWindow>(_panel, "IncomingCommitsIcon")->Show(status.remoteAheadCount > 0);
426
427 auto* outgoingLabel = findNamedObject<wxStaticText>(_panel, "NumOutgoingCommits");
428 outgoingLabel->Show(status.localAheadCount > 0);
429 outgoingLabel->SetLabel(string::to_string(status.localAheadCount));
430
431 auto* incomingLabel = findNamedObject<wxStaticText>(_panel, "NumIncomingCommits");
432 incomingLabel->Show(status.remoteAheadCount > 0);
433 incomingLabel->SetLabel(string::to_string(status.remoteAheadCount));
434
435 _remoteStatus->SetLabel(status.label);
436 });
437 }
438
439 void VcsStatus::performMapFileStatusCheck(std::shared_ptr<git::Repository> repository)
440 {
441 try
442 {
443 auto relativePath = repository->getRepositoryRelativePath(GlobalMapModule().getMapName());
444
445 if (relativePath.empty())
446 {
447 setMapFileStatus(_("Map not in VCS"));
448 return;
449 }
450
451 if (repository->fileHasUncommittedChanges(relativePath))
452 {
453 setMapFileStatus(_("Map saved, pending commit"));
454 }
455 else if (repository->fileIsIndexed(relativePath))
456 {
457 setMapFileStatus(_("Map committed"));
458 }
459 else
460 {
461 setMapFileStatus(_("Map saved"));
462 }
463 }
464 catch (const git::GitException& ex)
465 {
466 setMapFileStatus(std::string("ERROR: ") + ex.what());
467 }
468 }
469
470 }
471
472 }