Debian Codegraph @

src/Main/MainGui.cpp

raw
1 // SPDX-License-Identifier: LGPL-2.1-or-later
2 /***************************************************************************
3 * Copyright (c) 2008 Jürgen Riegel <[email protected]> *
4 * *
5 * This file is part of the FreeCAD CAx development system. *
6 * *
7 * This program is free software; you can redistribute it and/or modify *
8 * it under the terms of the GNU Library General Public License (LGPL) *
9 * as published by the Free Software Foundation; either version 2 of *
10 * the License, or (at your option) any later version. *
11 * for detail see the LICENCE text file. *
12 * *
13 * FreeCAD is distributed in the hope that it will be useful, *
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
16 * GNU Library General Public License for more details. *
17 * *
18 * You should have received a copy of the GNU Library General Public *
19 * License along with FreeCAD; if not, write to the Free Software *
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
21 * USA *
22 * *
23 ***************************************************************************/
24
25 #include <FCConfig.h>
26
27 #if defined(_MSC_VER)
28 # include <windows.h>
29 # include <dbghelp.h>
30 #endif
31
32 #if HAVE_CONFIG_H
33 # include <config.h>
34 #endif // HAVE_CONFIG_H
35
36 #include <Build/Version.h> // For FCCopyrightYear
37
38 #include <cstdio>
39 #include <map>
40 #include <stdexcept>
41
42 #include <QApplication>
43 #include <QLocale>
44 #include <QMessageBox>
45
46 // FreeCAD header
47 #include <App/Application.h>
48 #include <Base/ConsoleObserver.h>
49 #include <Base/Interpreter.h>
50 #include <Base/Parameter.h>
51 #include <Base/Exception.h>
52 #include <Gui/Application.h>
53
54
55 void PrintInitHelp();
56
57 const auto sBanner = fmt::format(
58 "(C) 2001-{} FreeCAD contributors\n"
59 "FreeCAD is free and open-source software licensed under the terms of LGPL2+ license.\n\n",
60 FCCopyrightYear
61 );
62
63 #if defined(_MSC_VER)
64 void InitMiniDumpWriter(const std::string&);
65 #endif
66
67 class Redirection
68 {
69 public:
70 Redirection(FILE* f)
71 : fi(Base::FileInfo::getTempFileName())
72 , file(f)
73 {
74 #ifdef WIN32
75 FILE* ptr = _wfreopen(fi.toStdWString().c_str(), L"w", file);
76 #else
77 FILE* ptr = freopen(fi.filePath().c_str(), "w", file);
78 #endif
79 if (!ptr) {
80 std::cerr << "Failed to reopen file" << std::endl;
81 }
82 }
83 ~Redirection()
84 {
85 fclose(file);
86 fi.deleteFile();
87 }
88
89 private:
90 Base::FileInfo fi;
91 FILE* file;
92 };
93
94 static bool inGuiMode()
95 {
96 // if console option is set then run in cmd mode
97 if (App::Application::Config()["Console"] == "1") {
98 return false;
99 }
100 return App::Application::Config()["RunMode"] == "Gui"
101 || App::Application::Config()["RunMode"] == "Internal";
102 }
103
104 static void displayInfo(const QString& msg, bool preformatted = true)
105 {
106 if (inGuiMode()) {
107 QString appName = QString::fromStdString(App::Application::Config()["ExeName"]);
108 QMessageBox msgBox;
109 msgBox.setIcon(QMessageBox::Information);
110 msgBox.setWindowTitle(appName);
111 msgBox.setDetailedText(msg);
112 msgBox.setText(preformatted ? QStringLiteral("<pre>%1</pre>").arg(msg) : msg);
113 msgBox.exec();
114 }
115 else {
116 std::cout << msg.toStdString();
117 }
118 }
119
120 static void displayCritical(const QString& msg, bool preformatted = true)
121 {
122 if (inGuiMode()) {
123 QString appName = QString::fromStdString(App::Application::Config()["ExeName"]);
124 QString title = QObject::tr("Initialization of %1 failed").arg(appName);
125 QString text = preformatted ? QStringLiteral("<pre>%1</pre>").arg(msg) : msg;
126 QMessageBox::critical(nullptr, title, text);
127 }
128 else {
129 std::cerr << msg.toStdString();
130 }
131 }
132
133 int main(int argc, char** argv)
134 {
135 #if defined(FC_OS_LINUX) || defined(FC_OS_BSD)
136 setlocale(LC_ALL, ""); // use native environment settings
137 setlocale(LC_NUMERIC, "C"); // except for numbers to not break XML import
138 // See https://github.com/FreeCAD/FreeCAD/issues/16724
139
140 // Make sure to setup the Qt locale system before setting LANG and LC_ALL to C.
141 // which is needed to use the system locale settings.
142 (void)QLocale::system();
143 // See https://forum.freecad.org/viewtopic.php?f=18&t=20600
144 // See Gui::Application::runApplication()
145 putenv("LC_NUMERIC=C");
146 putenv("PYTHONPATH=");
147 #elif defined(FC_OS_MACOSX)
148 (void)QLocale::system();
149 putenv("PYTHONPATH=");
150 #elif defined(__MINGW32__)
151 const char* mingw_prefix = getenv("MINGW_PREFIX");
152 const char* py_home = getenv("PYTHONHOME");
153 if (!py_home && mingw_prefix) {
154 _putenv_s("PYTHONHOME", mingw_prefix);
155 }
156 #else
157 _putenv("PYTHONPATH=");
158 // https://forum.freecad.org/viewtopic.php?f=4&t=18288
159 // https://forum.freecad.org/viewtopic.php?f=3&t=20515
160 const char* fc_py_home = getenv("FC_PYTHONHOME");
161 if (fc_py_home) {
162 _putenv_s("PYTHONHOME", fc_py_home);
163 }
164 else {
165 _putenv("PYTHONHOME=");
166 }
167 #endif
168
169 #if defined(FC_OS_WIN32)
170 // we need to force Coin not to use Freetype in order to find installed fonts on Windows
171 // see https://forum.freecad.org/viewtopic.php?p=485142#p485016
172 _putenv("COIN_FORCE_FREETYPE_OFF=1");
173
174 int argc_ = argc;
175 QVector<QByteArray> data;
176 QVector<char*> argv_;
177
178 // get the command line arguments as unicode string
179 {
180 QCoreApplication app(argc, argv);
181 QStringList args = app.arguments();
182 for (QStringList::iterator it = args.begin(); it != args.end(); ++it) {
183 data.push_back(it->toUtf8());
184 argv_.push_back(data.back().data());
185 }
186 argv_.push_back(0); // 0-terminated string
187 }
188 #endif
189
190 // Name and Version of the Application
191 App::Application::Config()["ExeName"] = "FreeCAD";
192 App::Application::Config()["ExeVendor"] = "FreeCAD";
193 App::Application::Config()["AppDataSkipVendor"] = "true";
194 App::Application::Config()["MaintainerUrl"] = "https://freecad.org";
195
196 // set the banner (for logging and console)
197 App::Application::Config()["CopyrightInfo"] = sBanner;
198 App::Application::Config()["AppIcon"] = "freecad";
199 App::Application::Config()["SplashScreen"] = "freecadsplash";
200 App::Application::Config()["AboutImage"] = App::Application::isDevelopmentVersion()
201 ? "freecadaboutdev"
202 : "freecadabout";
203 App::Application::Config()["StartWorkbench"] = "PartDesignWorkbench";
204 // App::Application::Config()["HiddenDockWindow"] = "Property editor";
205 App::Application::Config()["SplashAlignment"] = "Bottom|Left";
206 App::Application::Config()["SplashTextColor"] = "#418FDE";
207 App::Application::Config()["SplashWarningColor"] = "#CA333B";
208 App::Application::Config()["SplashInfoColor"] = "#000000";
209 App::Application::Config()["SplashInfoPosition"] = "6,75";
210 App::Application::Config()["DesktopFileName"] = "org.freecad.FreeCAD";
211
212 try {
213 // Init phase ===========================================================
214 // sets the default run mode for FC, starts with gui if not overridden in InitConfig...
215 App::Application::Config()["RunMode"] = "Gui";
216 App::Application::Config()["Console"] = "0";
217 App::Application::Config()["LoggingConsole"] = "1";
218
219 // Inits the Application
220 #if defined(FC_OS_WIN32)
221 App::Application::init(argc_, argv_.data());
222 #else
223 App::Application::init(argc, argv);
224 #endif
225 // to set window icon on wayland, the desktop file has to be available to the compositor
226 QGuiApplication::setDesktopFileName(
227 QString::fromStdString(App::Application::Config()["DesktopFileName"])
228 );
229
230 #if defined(_MSC_VER)
231 // create a dump file when the application crashes
232 std::string dmpfile = App::Application::getUserAppDataDir();
233 dmpfile += "crash.dmp";
234 InitMiniDumpWriter(dmpfile);
235 #endif
236 std::map<std::string, std::string>::iterator it = App::Application::Config().find(
237 "NavigationStyle"
238 );
239 if (it != App::Application::Config().end()) {
240 ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath(
241 "User parameter:BaseApp/Preferences/View"
242 );
243 // if not already defined do it now (for the very first start)
244 std::string style = hGrp->GetASCII("NavigationStyle", it->second.c_str());
245 hGrp->SetASCII("NavigationStyle", style.c_str());
246 }
247
248 Gui::Application::initApplication();
249
250 // Only if 'RunMode' is set to 'Gui' do the replacement
251 if (App::Application::Config()["RunMode"] == "Gui") {
252 Base::Interpreter().replaceStdOutput();
253 }
254 }
255 catch (const Base::UnknownProgramOption& e) {
256 QApplication app(argc, argv);
257 QString msg = QString::fromLatin1(e.what());
258 displayCritical(msg);
259 exit(1);
260 }
261 catch (const Base::ProgramInformation& e) {
262 QApplication app(argc, argv);
263 QString msg = QString::fromUtf8(e.what());
264 if (msg == QLatin1String(App::Application::verboseVersionEmitMessage)) {
265 QString data;
266 QTextStream str(&data);
267 const std::map<std::string, std::string> config = App::Application::Config();
268
269 App::Application::getVerboseCommonInfo(str, config);
270 Gui::Application::getVerboseDPIStyleInfo(str);
271 App::Application::getVerboseAddOnsInfo(str, config);
272
273 msg = data;
274 }
275 displayInfo(msg);
276 exit(0);
277 }
278 catch (const Base::Exception& e) {
279 // Popup an own dialog box instead of that one of Windows
280 QApplication app(argc, argv);
281 QString appName = QString::fromStdString(App::Application::Config()["ExeName"]);
282 QString msg;
283 msg = QObject::tr(
284 "While initializing %1 the following exception occurred: '%2'\n\n"
285 "Python is searching for its files in the following directories:\n%3\n\n"
286 "Python version information:\n%4\n"
287 )
288 .arg(
289 appName,
290 QString::fromUtf8(e.what()),
291 QString::fromStdString(Base::Interpreter().getPythonPath()),
292 QString::fromLatin1(Py_GetVersion())
293 );
294 const char* pythonhome = getenv("PYTHONHOME");
295 if (pythonhome) {
296 msg += QObject::tr("\nThe environment variable PYTHONHOME is set to '%1'.")
297 .arg(QString::fromUtf8(pythonhome));
298 msg += QObject::tr(
299 "\nSetting this environment variable might cause Python to fail. "
300 "Please contact your administrator to unset it on your system.\n\n"
301 );
302 }
303 else {
304 msg += QObject::tr(
305 "\nPlease contact the application's support team for more information.\n\n"
306 );
307 }
308
309 displayCritical(msg, false);
310 exit(100);
311 }
312 catch (...) {
313 // Popup an own dialog box instead of that one of Windows
314 QApplication app(argc, argv);
315 QString appName = QString::fromStdString(App::Application::Config()["ExeName"]);
316 QString msg = QObject::tr(
317 "Unknown runtime error occurred while initializing %1.\n\n"
318 "Please contact the application's support team for more information.\n\n"
319 )
320 .arg(appName);
321 displayCritical(msg, false);
322 exit(101);
323 }
324
325 // Run phase ===========================================================
326 Base::RedirectStdOutput stdcout;
327 Base::RedirectStdLog stdclog;
328 Base::RedirectStdError stdcerr;
329 std::streambuf* oldcout = std::cout.rdbuf(&stdcout);
330 std::streambuf* oldclog = std::clog.rdbuf(&stdclog);
331 std::streambuf* oldcerr = std::cerr.rdbuf(&stdcerr);
332
333 try {
334 if (inGuiMode()) {
335 Gui::Application::runApplication();
336 }
337 else {
338 App::Application::runApplication();
339 }
340 }
341 catch (const Base::SystemExitException& e) {
342 exit(e.getExitCode());
343 }
344 catch (const Base::Exception& e) {
345 e.reportException();
346 exit(1);
347 }
348 catch (const std::exception& e) {
349 Base::Console().error("Application unexpectedly terminated: %s\n", e.what());
350 exit(1);
351 }
352 catch (...) {
353 Base::Console().error("Application unexpectedly terminated\n");
354 exit(1);
355 }
356
357 std::cout.rdbuf(oldcout);
358 std::clog.rdbuf(oldclog);
359 std::cerr.rdbuf(oldcerr);
360
361 // Destruction phase ===========================================================
362 Base::Console().log("%s terminating...\n", App::Application::Config()["ExeName"].c_str());
363
364 // cleans up
365 App::Application::destruct();
366
367 Base::Console().log("%s completely terminated\n", App::Application::Config()["ExeName"].c_str());
368
369 return 0;
370 }
371
372 #if defined(_MSC_VER)
373
374 typedef BOOL(__stdcall* tMDWD)(
375 IN HANDLE hProcess,
376 IN DWORD ProcessId,
377 IN HANDLE hFile,
378 IN MINIDUMP_TYPE DumpType,
379 IN CONST PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam,
380 OPTIONAL IN CONST PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam,
381 OPTIONAL IN CONST PMINIDUMP_CALLBACK_INFORMATION CallbackParam OPTIONAL
382 );
383
384 static tMDWD s_pMDWD;
385 static HMODULE s_hDbgHelpMod;
386 static MINIDUMP_TYPE s_dumpTyp = MiniDumpNormal;
387 static std::wstring s_szMiniDumpFileName; // initialize with whatever appropriate...
388
389 # include <Base/StackWalker.h>
390 class MyStackWalker: public StackWalker
391 {
392 DWORD threadId;
393
394 public:
395 MyStackWalker()
396 : StackWalker()
397 , threadId(GetCurrentThreadId())
398 {
399 std::string name = App::Application::Config()["UserAppData"] + "crash.log";
400 Base::Console().attachObserver(new Base::ConsoleObserverFile(name.c_str()));
401 }
402 MyStackWalker(DWORD dwProcessId, HANDLE hProcess)
403 : StackWalker(dwProcessId, hProcess)
404 {}
405 virtual void OnOutput(LPCSTR szText)
406 {
407 Base::Console().log("Id: %ld: %s", threadId, szText);
408 // StackWalker::OnOutput(szText);
409 }
410 };
411
412 static LONG __stdcall MyCrashHandlerExceptionFilter(EXCEPTION_POINTERS* pEx)
413 {
414 # ifdef _M_IX86
415 if (pEx->ExceptionRecord->ExceptionCode == EXCEPTION_STACK_OVERFLOW) {
416 // be sure that we have enough space...
417 static char MyStack[1024 * 128];
418 // it assumes that DS and SS are the same!!! (this is the case for Win32)
419 // change the stack only if the selectors are the same (this is the case for Win32)
420 //__asm push offset MyStack[1024*128];
421 //__asm pop esp;
422 __asm mov eax, offset MyStack[1024 * 128];
423 __asm mov esp, eax;
424 }
425 # endif
426 MyStackWalker sw;
427 sw.ShowCallstack(GetCurrentThread(), pEx->ContextRecord);
428 Base::Console().log("*** Unhandled Exception!\n");
429 Base::Console().log(" ExpCode: 0x%8.8X\n", pEx->ExceptionRecord->ExceptionCode);
430 Base::Console().log(" ExpFlags: %d\n", pEx->ExceptionRecord->ExceptionFlags);
431 Base::Console().log(" ExpAddress: 0x%8.8X\n", pEx->ExceptionRecord->ExceptionAddress);
432
433 bool bFailed = true;
434 HANDLE hFile;
435 hFile = CreateFileW(
436 s_szMiniDumpFileName.c_str(),
437 GENERIC_WRITE,
438 0,
439 NULL,
440 CREATE_ALWAYS,
441 FILE_ATTRIBUTE_NORMAL,
442 NULL
443 );
444 if (hFile != INVALID_HANDLE_VALUE) {
445 MINIDUMP_EXCEPTION_INFORMATION stMDEI;
446 stMDEI.ThreadId = GetCurrentThreadId();
447 stMDEI.ExceptionPointers = pEx;
448 stMDEI.ClientPointers = true;
449 // try to create a miniDump:
450 if (s_pMDWD(GetCurrentProcess(), GetCurrentProcessId(), hFile, s_dumpTyp, &stMDEI, NULL, NULL)) {
451 bFailed = false; // succeeded
452 }
453 CloseHandle(hFile);
454 }
455
456 if (bFailed) {
457 return EXCEPTION_CONTINUE_SEARCH;
458 }
459
460 // Optional display an error message
461 // FatalAppExit(-1, ("Application failed!"));
462
463
464 // or return one of the following:
465 // - EXCEPTION_CONTINUE_SEARCH
466 // - EXCEPTION_CONTINUE_EXECUTION
467 // - EXCEPTION_EXECUTE_HANDLER
468 return EXCEPTION_CONTINUE_SEARCH; // this will trigger the "normal" OS error-dialog
469 }
470
471 void InitMiniDumpWriter(const std::string& filename)
472 {
473 if (s_hDbgHelpMod != NULL) {
474 return;
475 }
476 Base::FileInfo fi(filename);
477 s_szMiniDumpFileName = fi.toStdWString();
478
479 // Initialize the member, so we do not load the dll after the exception has occurred
480 // which might be not possible anymore...
481 s_hDbgHelpMod = LoadLibraryA(("dbghelp.dll"));
482 if (s_hDbgHelpMod != NULL) {
483 s_pMDWD = (tMDWD)GetProcAddress(s_hDbgHelpMod, "MiniDumpWriteDump");
484 }
485
486 // Register Unhandled Exception-Filter:
487 SetUnhandledExceptionFilter(MyCrashHandlerExceptionFilter);
488
489 // Additional call "PreventSetUnhandledExceptionFilter"...
490 // See also: "SetUnhandledExceptionFilter" and VC8 (and later)
491 // http://blog.kalmbachnet.de/?postid=75
492 }
493 #endif