-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.cpp
More file actions
538 lines (479 loc) · 18.3 KB
/
main.cpp
File metadata and controls
538 lines (479 loc) · 18.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
/*
* This file is part of Perastage.
* Copyright (C) 2025 Luisma Peramato
*
* Perastage is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Perastage is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Perastage. If not, see <https://www.gnu.org/licenses/>.
*/
#include "app_version.h"
#include "configmanager.h"
#include "logger.h"
#include "mainwindow.h"
#include "projectutils.h"
#include "splashscreen.h"
#include <filesystem>
#include <algorithm>
#include <atomic>
#include <cctype>
#include <cstdlib>
#include <deque>
#include <new>
#include <optional>
#include <string>
#if defined(_MSC_VER) && defined(_DEBUG)
#include <crtdbg.h>
#endif
#include <wx/stackwalk.h>
#include <wx/sysopt.h>
#include <wx/uri.h>
#include <wx/weakref.h>
#include <wx/wx.h>
#include <wx/filename.h>
#include <wx/stdpaths.h>
class MyApp : public wxApp {
public:
virtual bool OnInit() override;
int OnExit() override;
int FilterEvent(wxEvent &event) override;
bool OnExceptionInMainLoop() override;
void OnUnhandledException() override;
#if defined(__WXOSX__)
void MacOpenFiles(const wxArrayString &fileNames) override;
void MacOpenFile(const wxString &fileName) override;
void MacOpenURL(const wxString &url) override;
#else
void MacOpenFiles(const wxArrayString &fileNames);
void MacOpenFile(const wxString &fileName);
void MacOpenURL(const wxString &url);
#endif
private:
void FinalizeStartupOpenResolution(
const wxWeakRef<MainWindow> &mainWindowRef,
const std::optional<std::string> &cliStartupPath,
const std::optional<std::string> &lastPathOpt);
void HandleExternalOpenPath(const std::string &pathUtf8);
void StorePendingStartupExternalOpenPath(const std::string &pathUtf8);
std::optional<std::string> ConsumePendingStartupExternalOpenPath();
std::optional<std::string> ConsumePendingExternalOpenPath();
void QueueProjectLoadedEvent(const wxWeakRef<MainWindow> &mainWindowRef,
bool loaded, bool clearLastProject,
const std::string &path = {});
std::string last_event_summary_;
std::atomic<bool> project_load_event_sent_{false};
std::atomic<bool> startup_resolution_pending_{true};
std::optional<std::string> explicit_startup_open_path_;
std::deque<std::string> pending_external_open_paths_;
};
namespace {
// Converts a file:// URI into a local path while handling encoded characters and localhost-style authorities.
wxString DecodeFileUriToPath(const wxString &fileUri) {
wxURI uri(fileUri);
if (!uri.IsReference() && uri.GetScheme().CmpNoCase("file") == 0 &&
uri.HasPath()) {
wxString path = wxURI::Unescape(uri.GetPath());
#if defined(__WXOSX__)
if (path.StartsWith("//")) {
while (path.StartsWith("//"))
path = path.Mid(1);
path.Prepend("/");
}
#endif
if (!path.empty())
return path;
}
return fileUri;
}
// Converts external open input into a UTF-8 path while avoiding Windows shell-folder normalization stalls.
std::string NormalizeExternalOpenPath(const std::string &rawPathUtf8) {
if (rawPathUtf8.empty())
return {};
wxString wxPath = wxString::FromUTF8(rawPathUtf8);
if (wxPath.StartsWith("file://"))
wxPath = DecodeFileUriToPath(wxPath);
#if defined(__WXMSW__)
wxPath.Replace("/", "\\");
#else
wxFileName fileName(wxPath);
if (fileName.Normalize(wxPATH_NORM_DOTS | wxPATH_NORM_TILDE |
wxPATH_NORM_ABSOLUTE)) {
wxPath = fileName.GetFullPath();
}
#endif
wxCharBuffer utf8 = wxPath.ToUTF8();
const std::string normalizedPath =
utf8 ? std::string(utf8.data()) : rawPathUtf8;
if (normalizedPath != rawPathUtf8) {
Logger::Instance().Log("NormalizeExternalOpenPath normalized '" +
rawPathUtf8 + "' -> '" + normalizedPath + "'");
}
return normalizedPath;
}
// Converts an ASCII string to lowercase.
std::string ToLowerAscii(std::string text) {
std::transform(text.begin(), text.end(), text.begin(), [](unsigned char c) {
return static_cast<char>(std::tolower(c));
});
return text;
}
// Returns the first startup-open candidate from CLI arguments as a normalized absolute UTF-8 path.
std::optional<std::string> GetStartupPathFromArgs(
int argc, wxChar **argv, const std::string &launchWorkingDirectoryUtf8) {
namespace fs = std::filesystem;
const std::string projectExtension = ToLowerAscii(ProjectUtils::PROJECT_EXTENSION);
const fs::path launchWorkingDirectory =
launchWorkingDirectoryUtf8.empty()
? fs::path()
: fs::u8path(launchWorkingDirectoryUtf8);
auto toUtf8 = [](const wxString &text) {
wxCharBuffer utf8 = text.ToUTF8();
if (!utf8)
return text.ToStdString();
return std::string(utf8.data());
};
for (int i = 1; i < argc; ++i) {
wxString argumentText(argv[i]);
if ((argumentText.StartsWith("\"") && argumentText.EndsWith("\"")) ||
(argumentText.StartsWith("'") && argumentText.EndsWith("'"))) {
argumentText = argumentText.Mid(1, argumentText.length() - 2);
}
const std::string rawPath = toUtf8(argumentText);
if (rawPath.empty())
continue;
const std::string normalizedRawPath = NormalizeExternalOpenPath(rawPath);
const fs::path candidate = fs::u8path(normalizedRawPath);
const std::u8string extensionU8 = candidate.extension().u8string();
const std::string extension(extensionU8.begin(), extensionU8.end());
const std::string normalizedExtension = ToLowerAscii(extension);
if (normalizedExtension != projectExtension && normalizedExtension != ".mvr")
continue;
std::error_code ec;
fs::path absolutePath;
if (!candidate.is_absolute() && !launchWorkingDirectory.empty()) {
absolutePath = fs::absolute(launchWorkingDirectory / candidate, ec);
} else {
absolutePath = fs::absolute(candidate, ec);
}
if (ec)
return normalizedRawPath;
const std::u8string absoluteU8 = absolutePath.u8string();
if (absoluteU8.empty())
return normalizedRawPath;
return std::string(absoluteU8.begin(), absoluteU8.end());
}
return std::nullopt;
}
#if defined(_MSC_VER) && defined(_DEBUG)
// Configures optional CRT leak checking for Windows debug builds via an environment toggle.
void ConfigureWindowsDebugHeapLeakCheck() {
int flags = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
const char *requestedLeakCheck = std::getenv("PERASTAGE_CRT_LEAK_CHECK");
const bool enableLeakCheck =
requestedLeakCheck && std::string(requestedLeakCheck) == "1";
if (enableLeakCheck) {
flags |= _CRTDBG_LEAK_CHECK_DF;
} else {
flags &= ~_CRTDBG_LEAK_CHECK_DF;
}
_CrtSetDbgFlag(flags);
}
#endif
} // namespace
wxIMPLEMENT_APP(MyApp);
// Initializes the application, creates the main window, and routes startup open requests.
bool MyApp::OnInit() {
#if defined(_MSC_VER) && defined(_DEBUG)
ConfigureWindowsDebugHeapLeakCheck();
#endif
const wxString launchCwdWx = wxFileName::GetCwd();
const wxCharBuffer launchCwdUtf8Buffer = launchCwdWx.ToUTF8();
const std::string launchWorkingDirectoryUtf8 =
launchCwdUtf8Buffer ? std::string(launchCwdUtf8Buffer.data())
: launchCwdWx.ToStdString();
SetAppName(app::kName);
SetVendorName("Perasoft");
// Ensure a stable working directory when launching from Explorer.
// This avoids issues caused by relative paths during startup/project load.
{
wxFileName exe(wxStandardPaths::Get().GetExecutablePath());
if (exe.IsOk()) {
wxFileName::SetCwd(exe.GetPath());
}
}
// Enable support for common image formats used by the app
wxInitAllImageHandlers();
// Force dark mode when supported by the wxWidgets version in use
#if wxCHECK_VERSION(3, 3, 0)
SetAppearance(wxApp::Appearance::Dark);
#endif
// Enable dark mode for Windows (if supported by wxWidgets)
wxSystemOptions::SetOption("msw.useDarkMode", 1);
SplashScreen::Show();
SplashScreen::SetMessage("Initializing logger...");
// Initialize logging system (overwrites log file each launch)
Logger::Instance();
SplashScreen::SetMessage("Running library bootstrap...");
ProjectUtils::RunStartupLibraryBootstrap();
SplashScreen::SetMessage("Creating main window...");
MainWindow *mainWindow = new MainWindow(app::kName);
mainWindow->Show(true);
// Start maximized so minimize and restore buttons remain available
mainWindow->Maximize(true);
SplashScreen::SetMessage("Loading last project...");
wxWeakRef<MainWindow> mainWindowRef(mainWindow);
auto lastPathOpt = ProjectUtils::LoadLastProjectPath();
std::optional<std::string> cliStartupPath =
GetStartupPathFromArgs(argc, argv, launchWorkingDirectoryUtf8);
Logger::Instance().Log(
"Startup resolution delayed to allow macOS open-file event.");
mainWindow->CallAfter([this, mainWindowRef, cliStartupPath, lastPathOpt]() {
if (!mainWindowRef)
return;
mainWindowRef->CallAfter([this, mainWindowRef, cliStartupPath, lastPathOpt]() {
FinalizeStartupOpenResolution(mainWindowRef, cliStartupPath, lastPathOpt);
});
});
return true;
}
// Finalizes startup path selection after allowing macOS open-file events to arrive.
void MyApp::FinalizeStartupOpenResolution(
const wxWeakRef<MainWindow> &mainWindowRef,
const std::optional<std::string> &cliStartupPath,
const std::optional<std::string> &lastPathOpt) {
if (!mainWindowRef)
return;
if (auto macPath = ConsumePendingStartupExternalOpenPath()) {
Logger::Instance().Log("Startup explicit macOS path selected: " + *macPath);
Logger::Instance().Log("Opening startup path: " + *macPath);
QueueProjectLoadedEvent(mainWindowRef, false, true, *macPath);
startup_resolution_pending_.store(false);
return;
}
if (cliStartupPath.has_value()) {
Logger::Instance().Log("Startup CLI path selected: " + *cliStartupPath);
Logger::Instance().Log("Opening startup path: " + *cliStartupPath);
QueueProjectLoadedEvent(mainWindowRef, false, true, *cliStartupPath);
startup_resolution_pending_.store(false);
return;
}
if (lastPathOpt.has_value()) {
if (explicit_startup_open_path_.has_value()) {
Logger::Instance().Log(
"Skipping last project because explicit startup path exists.");
} else {
Logger::Instance().Log("Startup last project selected: " + *lastPathOpt);
QueueProjectLoadedEvent(mainWindowRef, false, false, *lastPathOpt);
}
startup_resolution_pending_.store(false);
return;
}
Logger::Instance().Log("Startup empty project selected.");
QueueProjectLoadedEvent(mainWindowRef, false, false);
startup_resolution_pending_.store(false);
}
// Routes a single macOS file-open request to the shared external-open handler.
void MyApp::MacOpenFile(const wxString &fileName) {
const wxCharBuffer utf8 = fileName.ToUTF8();
const std::string rawPathUtf8 =
utf8 ? std::string(utf8.data()) : fileName.ToStdString();
Logger::Instance().Log("MacOpenFile received: " + rawPathUtf8);
HandleExternalOpenPath(NormalizeExternalOpenPath(rawPathUtf8));
}
// Routes macOS multi-file open requests to the external open pipeline in order.
void MyApp::MacOpenFiles(const wxArrayString &fileNames) {
Logger::Instance().Log("MacOpenFiles received count: " +
std::to_string(fileNames.GetCount()));
for (const wxString &fileName : fileNames) {
MacOpenFile(fileName);
}
}
// Routes macOS URL open requests (Finder/LaunchServices) to the shared external-open handler.
void MyApp::MacOpenURL(const wxString &url) {
const wxCharBuffer utf8 = url.ToUTF8();
const std::string rawUrlUtf8 =
utf8 ? std::string(utf8.data()) : url.ToStdString();
Logger::Instance().Log("MacOpenURL received: " + rawUrlUtf8);
HandleExternalOpenPath(NormalizeExternalOpenPath(rawUrlUtf8));
}
// Handles external file-open requests by deferring them until startup loading is safe.
void MyApp::HandleExternalOpenPath(const std::string &pathUtf8) {
if (pathUtf8.empty())
return;
Logger::Instance().Log("macOS external open received: " + pathUtf8);
if (startup_resolution_pending_.load()) {
StorePendingStartupExternalOpenPath(pathUtf8);
Logger::Instance().Log("macOS startup explicit path stored: " + pathUtf8);
return;
}
MainWindow *mainWindow = wxDynamicCast(GetTopWindow(), MainWindow);
if (!mainWindow) {
Logger::Instance().Log(
"HandleExternalOpenPath queued: MainWindow is not ready.");
pending_external_open_paths_.push_back(pathUtf8);
return;
}
if (!project_load_event_sent_.load()) {
Logger::Instance().Log("Opening startup path: " + pathUtf8);
QueueProjectLoadedEvent(wxWeakRef<MainWindow>(mainWindow), false, true, pathUtf8);
return;
}
Logger::Instance().Log(
"HandleExternalOpenPath routing through MainWindow deferred-open pipeline.");
mainWindow->CallAfter([mainWindow, pathUtf8]() {
if (!mainWindow->CanProcessExternalOpenPath())
return;
mainWindow->EnqueueExternalOpenPath(pathUtf8);
});
}
// Stores the most recent explicit startup external-open path received during app initialization.
void MyApp::StorePendingStartupExternalOpenPath(const std::string &pathUtf8) {
if (pathUtf8.empty())
return;
explicit_startup_open_path_ = pathUtf8;
}
// Returns and clears the explicit startup external-open path captured during initialization.
std::optional<std::string> MyApp::ConsumePendingStartupExternalOpenPath() {
if (!explicit_startup_open_path_.has_value())
return std::nullopt;
std::optional<std::string> path = explicit_startup_open_path_;
explicit_startup_open_path_.reset();
return path;
}
// Pops and returns the next queued external-open path, if any.
std::optional<std::string> MyApp::ConsumePendingExternalOpenPath() {
if (pending_external_open_paths_.empty())
return std::nullopt;
std::string path = pending_external_open_paths_.front();
pending_external_open_paths_.pop_front();
return path;
}
// Releases application-level resources before process shutdown.
int MyApp::OnExit() {
// Release application-level singletons before CRT leak reporting runs in
// debug builds on Windows.
ConfigManager::Get().Reset();
ConfigManager::Get().ClearHistory();
wxImage::CleanUpHandlers();
return wxApp::OnExit();
}
// Queues a single startup project-loaded event to avoid duplicate startup routing.
void MyApp::QueueProjectLoadedEvent(const wxWeakRef<MainWindow> &mainWindowRef,
bool loaded, bool clearLastProject,
const std::string &path) {
if (!mainWindowRef)
return;
bool expected = false;
if (!project_load_event_sent_.compare_exchange_strong(expected, true))
return;
wxCommandEvent evt(EVT_PROJECT_LOADED);
evt.SetInt(loaded ? 1 : 0);
evt.SetExtraLong(clearLastProject ? 1 : 0);
evt.SetString(wxString::FromUTF8(path));
wxQueueEvent(mainWindowRef.get(), evt.Clone());
}
// Captures the latest event metadata to improve crash diagnostics.
int MyApp::FilterEvent(wxEvent &event) {
const wxClassInfo *eventInfo = event.GetClassInfo();
wxString eventClassName =
eventInfo ? eventInfo->GetClassName() : wxT("UnknownEvent");
wxString objectClassName = wxT("None");
if (event.GetEventObject()) {
const wxClassInfo *objectInfo = event.GetEventObject()->GetClassInfo();
if (objectInfo) {
objectClassName = objectInfo->GetClassName();
} else {
objectClassName = wxT("UnknownObject");
}
}
last_event_summary_ = wxString::Format(
"Last event: class=%s type=%d id=%d object=%s",
eventClassName, static_cast<int>(event.GetEventType()),
event.GetId(), objectClassName)
.ToStdString();
return -1;
}
namespace {
// Logs an exception message and an optional platform stack trace for diagnostics.
void LogExceptionWithStack(const std::exception &ex,
const char *contextMessage) {
Logger::Instance().Log(std::string(contextMessage) + ex.what());
#if defined(__WXMSW__)
class StackWalker : public wxStackWalker {
public:
std::string TakeStackTrace() {
lines_.clear();
Walk();
return lines_;
}
protected:
void OnStackFrame(const wxStackFrame &frame) override {
lines_ += std::string(frame.GetName().ToStdString());
lines_ += " (";
lines_ += std::string(frame.GetFileName().ToStdString());
lines_ += ":";
lines_ += std::to_string(frame.GetLine());
lines_ += ")\n";
}
private:
std::string lines_;
};
StackWalker walker;
std::string trace = walker.TakeStackTrace();
if (!trace.empty()) {
Logger::Instance().Log(std::string("Stack trace:\n") + trace);
}
#endif
}
} // namespace
// Logs recoverable main-loop exceptions and keeps the app running when possible.
bool MyApp::OnExceptionInMainLoop() {
try {
throw;
} catch (const std::exception &ex) {
if (dynamic_cast<const std::bad_alloc *>(&ex)) {
Logger::Instance().Log("Unhandled exception in main loop: bad allocation.");
if (!last_event_summary_.empty()) {
Logger::Instance().Log(last_event_summary_);
}
LogExceptionWithStack(ex, "Unhandled exception in main loop: ");
return true;
}
if (!last_event_summary_.empty()) {
Logger::Instance().Log(last_event_summary_);
}
LogExceptionWithStack(ex, "Unhandled exception in main loop: ");
return true;
} catch (...) {
Logger::Instance().Log("Unhandled exception in main loop: unknown error.");
}
return false;
}
// Logs non-recoverable unhandled exceptions for post-mortem diagnostics.
void MyApp::OnUnhandledException() {
try {
throw;
} catch (const std::exception &ex) {
if (dynamic_cast<const std::bad_alloc *>(&ex)) {
Logger::Instance().Log("Unhandled exception: bad allocation.");
if (!last_event_summary_.empty()) {
Logger::Instance().Log(last_event_summary_);
}
return;
}
if (!last_event_summary_.empty()) {
Logger::Instance().Log(last_event_summary_);
}
LogExceptionWithStack(ex, "Unhandled exception: ");
} catch (...) {
Logger::Instance().Log("Unhandled exception: unknown error.");
}
}