forked from wxFormBuilder/wxFormBuilder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmaingui.cpp
434 lines (373 loc) · 13.5 KB
/
maingui.cpp
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
///////////////////////////////////////////////////////////////////////////////
//
// wxFormBuilder - A Visual Dialog Editor for wxWidgets.
// Copyright (C) 2005 José Antonio Hurtado
//
// This program 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 2
// of the License, or (at your option) any later version.
//
// This program 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 this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
// Written by
// José Antonio Hurtado - [email protected]
// Juan Antonio Ortega - [email protected]
//
///////////////////////////////////////////////////////////////////////////////
#include "maingui.h"
#include <wx/clipbrd.h>
#include <wx/cmdline.h>
#include <wx/config.h>
#include <wx/stdpaths.h>
#include <wx/sysopt.h>
#include "model/objectbase.h"
#include "rad/appdata.h"
#include "rad/mainframe.h"
#include "rad/revision.h"
#include "rad/version.h"
#include "utils/typeconv.h"
#include "utils/wxfbexception.h"
#if wxVERSION_NUMBER >= 2905 && wxVERSION_NUMBER <= 3100
#include <wx/xrc/xh_auinotbk.h>
#elif wxVERSION_NUMBER > 3100
#include <wx/xrc/xh_aui.h>
#endif
// Abnormal Termination Handling
#if wxUSE_ON_FATAL_EXCEPTION && wxUSE_STACKWALKER
#include <wx/stackwalk.h>
#elif defined(_WIN32) && defined(__MINGW32__)
#include <stack_trace/stack.hpp>
#include <sstream>
#include <excpt.h>
#if defined __MINGW64_VERSION_MAJOR && defined __MINGW64_VERSION_MINOR /* MinGW-w64 required */
__stdcall EXCEPTION_DISPOSITION StructuredExceptionHandler(
struct _EXCEPTION_RECORD* ExceptionRecord, /* breaks build with MinGW 32 */
void* EstablisherFrame, struct _CONTEXT* ContextRecord, void* DispatcherContext);
#else
EXCEPTION_DISPOSITION StructuredExceptionHandler(
struct _EXCEPTION_RECORD* ExceptionRecord, void* EstablisherFrame, struct _CONTEXT* ContextRecord,
void* DispatcherContext);
#endif
#endif
void LogStack();
static const wxCmdLineEntryDesc s_cmdLineDesc[] = {
{wxCMD_LINE_SWITCH, "g", "generate", "Generate code from passed file.", wxCMD_LINE_VAL_STRING, 0},
{wxCMD_LINE_OPTION, "l", "language",
"Override the code_generation property from the passed file and generate the passed "
"languages. Separate multiple languages with commas.",
wxCMD_LINE_VAL_STRING, 0},
{wxCMD_LINE_SWITCH, "h", "help", "Show this help message.", wxCMD_LINE_VAL_STRING, wxCMD_LINE_OPTION_HELP},
{wxCMD_LINE_SWITCH, "v", "version", "Print version information.", wxCMD_LINE_VAL_STRING, 0},
{wxCMD_LINE_PARAM, nullptr, nullptr, "File to open.", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL},
{wxCMD_LINE_NONE, nullptr, nullptr, nullptr, wxCMD_LINE_VAL_NONE, 0}};
IMPLEMENT_APP(MyApp)
int MyApp::OnRun()
{
// Abnormal Termination Handling
#if wxUSE_ON_FATAL_EXCEPTION && wxUSE_STACKWALKER
::wxHandleFatalExceptions(true);
#elif defined(_WIN32) && defined(__MINGW32__)
// Structured Exception handlers are stored in a linked list at FS:[0] for 32-bit and GS:[0] for 64-bit
// https://github.com/wine-mirror/wine/blob/1aff1e6a370ee8c0213a0fd4b220d121da8527aa/include/winternl.h#L347
// THIS MUST BE A LOCAL VARIABLE - windows won't use an object outside of the thread's stack frame
EXCEPTION_REGISTRATION ex;
ex.handler = StructuredExceptionHandler;
#if defined(__amd64__) || defined(__x86_64__) // 64-bit
asm volatile("movq %%gs:0, %0" : "=r"(ex.prev));
asm volatile("movq %0, %%gs:0" : : "r"(&ex));
#elif defined(__i386__) || defined(_X86_) // 32-bit
asm volatile("movl %%fs:0, %0" : "=r"(ex.prev));
asm volatile("movl %0, %%fs:0" : : "r"(&ex));
#endif
#endif
// Using a space so the initial 'w' will not be capitalized in wxLogGUI dialogs
wxApp::SetAppName(wxT(" wxFormBuilder"));
// Creating the wxConfig manually so there will be no space
// The old config (if any) is returned, delete it
delete wxConfigBase::Set(new wxConfig(wxT("wxFormBuilder")));
// Get the data directory
auto& stdPaths = wxStandardPaths::Get();
#if defined(__WINDOWS__)
// The CMake stage build roots the whole directory structure at the build directory
// so don't ignore that one
stdPaths.DontIgnoreAppSubDir();
#endif
wxString dataDir = stdPaths.GetDataDir();
dataDir.Replace(GetAppName(), wxT("wxformbuilder"));
// Log to stderr while working on the command line
delete wxLog::SetActiveTarget(new wxLogStderr);
// Message output to the same as the log target
delete wxMessageOutput::Set(new wxMessageOutputLog);
// Parse command line
wxCmdLineParser parser(s_cmdLineDesc, argc, argv);
if (0 != parser.Parse()) {
return 1;
}
if (parser.Found("v")) {
std::cout << "wxFormBuilder " << getVersion() << getPostfixRevision(getVersion()) << getReleaseBranch(getBranch()) << std::endl;
return EXIT_SUCCESS;
}
// Get project to load
wxString projectToLoad = wxEmptyString;
if (parser.GetParamCount() > 0) {
projectToLoad = parser.GetParam();
}
bool justGenerate = false;
wxString language;
bool hasLanguage = parser.Found(wxT("l"), &language);
if (parser.Found(wxT("g"))) {
if (projectToLoad.empty()) {
wxLogError(_("You must pass a path to a project file. Nothing to generate."));
return 2;
}
if (hasLanguage) {
if (language.empty()) {
wxLogError(_("Empty language option. Nothing generated."));
return 3;
}
language.Replace(wxT(","), wxT("|"), true);
}
// generate code
justGenerate = true;
} else {
delete wxLog::SetActiveTarget(new wxLogGui);
}
// Create singleton AppData - wait to initialize until sure that this is not the second
// instance of a project file.
ApplicationData::Get(dataDir);
// Make passed project name absolute
try {
if (!projectToLoad.empty()) {
wxFileName projectPath(projectToLoad);
if (!projectPath.IsOk()) {
THROW_WXFBEX(wxT("This path is invalid: ") << projectToLoad);
}
if (!projectPath.IsAbsolute()) {
if (!projectPath.MakeAbsolute()) {
THROW_WXFBEX(wxT("Could not make path absolute: ") << projectToLoad);
}
}
projectToLoad = projectPath.GetFullPath();
}
} catch (wxFBException& ex) {
wxLogError(ex.what());
}
// If the project is already loaded in another instance, switch to that instance and quit
if (!projectToLoad.empty() && !justGenerate) {
if (::wxFileExists(projectToLoad)) {
if (!AppData()->VerifySingleInstance(projectToLoad)) {
return 4;
}
}
}
// Init handlers
wxInitAllImageHandlers();
wxXmlResource::Get()->InitAllHandlers();
#if wxVERSION_NUMBER >= 2905 && wxVERSION_NUMBER <= 3100
wxXmlResource::Get()->AddHandler(new wxAuiNotebookXmlHandler);
#elif wxVERSION_NUMBER > 3100
wxXmlResource::Get()->AddHandler(new wxAuiXmlHandler);
#endif
// Init AppData
try {
ApplicationData::Initialize();
} catch (wxFBException& ex) {
wxLogError(_("Error loading application: %s\nwxFormBuilder cannot continue."), ex.what());
wxLog::FlushActive();
return 5;
}
wxSystemOptions::SetOption(wxT("msw.remap"), 0);
wxSystemOptions::SetOption(wxT("msw.staticbox.optimized-paint"), 0);
m_frame = NULL;
wxYield();
// Read size and position from config file
wxConfigBase* config = wxConfigBase::Get();
config->SetPath(wxT("/mainframe"));
int x, y, w, h;
x = y = w = h = -1;
config->Read(wxT("PosX"), &x);
config->Read(wxT("PosY"), &y);
config->Read(wxT("SizeW"), &w);
config->Read(wxT("SizeH"), &h);
long style = config->Read(wxT("style"), wxFB_WIDE_GUI);
if (style != wxFB_CLASSIC_GUI) {
style = wxFB_WIDE_GUI;
}
config->SetPath(wxT("/"));
m_frame = new MainFrame(NULL, wxID_ANY, (int)style, wxPoint(x, y), wxSize(w, h));
if (!justGenerate) {
m_frame->Show(TRUE);
SetTopWindow(m_frame);
#ifdef __WXFB_DEBUG__
wxLogWindow* log = dynamic_cast<wxLogWindow*>(AppData()->GetDebugLogTarget());
if (log) {
m_frame->AddChild(log->GetFrame());
}
#endif //__WXFB_DEBUG__
}
// This is not necessary for wxFB to work. However, Windows sets the Current Working Directory
// to the directory from which a .fbp file was opened, if opened from Windows Explorer.
// This puts an unnecessary lock on the directory.
// This changes the CWD to the already locked app directory as a workaround
#ifdef __WXMSW__
::wxSetWorkingDirectory(dataDir);
#endif
if (!projectToLoad.empty()) {
if (AppData()->LoadProject(projectToLoad, justGenerate)) {
if (justGenerate) {
if (hasLanguage) {
PObjectBase project = AppData()->GetProjectData();
PProperty codeGen = project->GetProperty(_("code_generation"));
if (codeGen) {
codeGen->SetValue(language);
}
}
AppData()->GenerateCode(false, true);
return 0;
} else {
m_frame->InsertRecentProject(projectToLoad);
return wxApp::OnRun();
}
} else {
wxLogError(wxT("Unable to load project: %s"), projectToLoad);
}
}
if (justGenerate) {
return 6;
}
AppData()->NewProject();
#ifdef __WXMAC__
// document to open on startup
if (!m_mac_file_name.IsEmpty()) {
if (AppData()->LoadProject(m_mac_file_name))
m_frame->InsertRecentProject(m_mac_file_name);
}
#endif
return wxApp::OnRun();
}
bool MyApp::OnInit()
{
// Initialization is done in OnRun, so MinGW SEH works for all code (it needs a local variable, OnInit is called
// before OnRun)
return true;
}
int MyApp::OnExit()
{
MacroDictionary::Destroy();
ApplicationData::Destroy();
if (!wxTheClipboard->IsOpened()) {
if (!wxTheClipboard->Open()) {
return wxApp::OnExit();
}
}
// Allow clipboard data to persist after close
wxTheClipboard->Flush();
wxTheClipboard->Close();
return wxApp::OnExit();
}
#ifdef __WXMAC__
void MyApp::MacOpenFile(const wxString& fileName)
{
if (m_frame == NULL)
m_mac_file_name = fileName;
else {
if (!m_frame->SaveWarning())
return;
if (AppData()->LoadProject(fileName))
m_frame->InsertRecentProject(fileName);
}
}
#endif
#if wxUSE_ON_FATAL_EXCEPTION && wxUSE_STACKWALKER
class StackLogger : public wxStackWalker
{
protected:
void OnStackFrame(const wxStackFrame& frame) override
{
// Build param string
wxString params;
size_t paramCount = frame.GetParamCount();
if (paramCount > 0) {
params << wxT("( ");
for (size_t i = 0; i < paramCount; ++i) {
wxString type, name, value;
if (frame.GetParam(i, &type, &name, &value)) {
params << type << wxT(" ") << name << wxT(" = ") << value << wxT(", ");
}
}
params << wxT(")");
}
wxString source;
if (frame.HasSourceLocation()) {
source.Printf(wxT("%s@%i"), frame.GetFileName(), frame.GetLine());
}
wxLogError(
wxT("%03i %i %s %s %s %s"), frame.GetLevel(), frame.GetAddress(), frame.GetModule(), frame.GetName(), params,
source);
}
};
void MyApp::OnFatalException()
{
LogStack();
}
#elif defined(_WIN32) && defined(__MINGW32__)
static _CONTEXT* context = 0;
EXCEPTION_DISPOSITION StructuredExceptionHandler(
struct _EXCEPTION_RECORD* ExceptionRecord, void* EstablisherFrame, struct _CONTEXT* ContextRecord,
void* DispatcherContext)
{
context = ContextRecord;
LogStack();
return ExceptionContinueSearch;
}
class StackLogger
{
public:
virtual ~StackLogger() = default;
void WalkFromException()
{
try {
std::stringstream output;
dbg::stack s(0, context);
dbg::stack::const_iterator frame;
for (frame = s.begin(); frame != s.end(); ++frame) {
output << *frame;
wxLogError(wxString(output.str().c_str(), *wxConvCurrent));
output.str("");
}
} catch (std::exception& ex) {
wxLogError(wxString(ex.what(), *wxConvCurrent));
}
}
};
#endif
#if (wxUSE_ON_FATAL_EXCEPTION && wxUSE_STACKWALKER) || (defined(_WIN32) && defined(__MINGW32__))
class LoggingStackWalker : public StackLogger
{
public:
LoggingStackWalker() { wxLog::Suspend(); }
~LoggingStackWalker() override
{
wxLogError(wxT("A Fatal Error Occurred. Click Details for a backtrace."));
wxLog::Resume();
wxLog* logger = wxLog::GetActiveTarget();
if (0 != logger) {
logger->Flush();
}
exit(1);
}
};
void LogStack()
{
LoggingStackWalker walker;
walker.WalkFromException();
}
#endif