Debian Codegraph @

src/Gui/GuiApplication.cpp

raw
1 /***************************************************************************
2 * Copyright (c) 2015 Werner Mayer <wmayer[at]users.sourceforge.net> *
3 * *
4 * This file is part of the FreeCAD CAx development system. *
5 * *
6 * This library is free software; you can redistribute it and/or *
7 * modify it under the terms of the GNU Library General Public *
8 * License as published by the Free Software Foundation; either *
9 * version 2 of the License, or (at your option) any later version. *
10 * *
11 * This library is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU Library General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU Library General Public *
17 * License along with this library; see the file COPYING.LIB. If not, *
18 * write to the Free Software Foundation, Inc., 59 Temple Place, *
19 * Suite 330, Boston, MA 02111-1307, USA *
20 * *
21 ***************************************************************************/
22
23
24 #include <FCConfig.h>
25
26 #ifdef FC_OS_WIN32
27 # include <Windows.h>
28 #elif defined(Q_OS_UNIX)
29 # include <sys/types.h>
30 # include <ctime>
31 # include <unistd.h>
32 #endif
33
34 #include <sstream>
35 #include <QAbstractSpinBox>
36 #include <QByteArray>
37 #include <QComboBox>
38 #include <QTextStream>
39 #include <QFileInfo>
40 #include <QFileOpenEvent>
41 #include <QSessionManager>
42 #include <QTimer>
43
44
45 #include <QLocalServer>
46 #include <QLocalSocket>
47
48
49 #include <App/Application.h>
50 #include <Base/Console.h>
51 #include <Base/Exception.h>
52
53 #include "GuiApplication.h"
54 #include "Application.h"
55 #include "MainWindow.h"
56 #include "SpaceballEvent.h"
57
58
59 using namespace Gui;
60
61 GUIApplication::GUIApplication(int& argc, char** argv)
62 : GUIApplicationNativeEventAware(argc, argv)
63 {
64 connect(
65 this,
66 &GUIApplication::commitDataRequest,
67 this,
68 &GUIApplication::commitData,
69 Qt::DirectConnection
70 );
71 #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
72 setFallbackSessionManagementEnabled(false);
73 #endif
74 }
75
76 GUIApplication::~GUIApplication() = default;
77
78 bool GUIApplication::notify(QObject* receiver, QEvent* event)
79 {
80 if (!receiver) {
81 Base::Console().log(
82 "GUIApplication::notify: Unexpected null receiver, event type: %d\n",
83 (int)event->type()
84 );
85 return false;
86 }
87
88 // https://github.com/FreeCAD/FreeCAD/issues/16905
89 std::string exceptionWarning =
90 #if FC_DEBUG
91 "Exceptions must be caught before they go through Qt."
92 " Ignoring this will cause crashes on some systems.\n";
93 #else
94 "";
95 #endif
96
97 try {
98 if (event->type() == Spaceball::ButtonEvent::ButtonEventType
99 || event->type() == Spaceball::MotionEvent::MotionEventType) {
100 return processSpaceballEvent(receiver, event);
101 }
102 else {
103 return QApplication::notify(receiver, event);
104 }
105 }
106 catch (const Base::SystemExitException& e) {
107 caughtException.reset(new Base::SystemExitException(e));
108 qApp->exit(e.getExitCode());
109 return true;
110 }
111 catch (const Base::Exception& e) {
112 Base::Console().error(
113 "Unhandled Base::Exception caught in GUIApplication::notify.\n"
114 "The error message is: %s\n%s",
115 e.what(),
116 exceptionWarning
117 );
118 }
119 catch (const std::exception& e) {
120 Base::Console().error(
121 "Unhandled std::exception caught in GUIApplication::notify.\n"
122 "The error message is: %s\n%s",
123 e.what(),
124 exceptionWarning
125 );
126 }
127 catch (...) {
128 Base::Console().error(
129 "Unhandled unknown exception caught in GUIApplication::notify.\n%s",
130 exceptionWarning
131 );
132 }
133
134 // Print some more information to the log file (if active) to ease bug fixing
135 try {
136 std::stringstream dump;
137 dump << "The event type " << (int)event->type() << " was sent to "
138 << receiver->metaObject()->className() << "\n";
139 dump << "Object tree:\n";
140 if (receiver->isWidgetType()) {
141 QWidget* w = qobject_cast<QWidget*>(receiver);
142 while (w) {
143 dump << "\t";
144 dump << w->metaObject()->className();
145 QString name = w->objectName();
146 if (!name.isEmpty()) {
147 dump << " (" << (const char*)name.toUtf8() << ")";
148 }
149 w = w->parentWidget();
150 if (w) {
151 dump << " is child of\n";
152 }
153 }
154 std::string str = dump.str();
155 Base::Console().log("%s", str.c_str());
156 }
157 }
158 catch (...) {
159 Base::Console().log("Invalid recipient and/or event in GUIApplication::notify\n");
160 }
161
162 return true;
163 }
164
165 void GUIApplication::commitData(QSessionManager& manager)
166 {
167 if (manager.allowsInteraction()) {
168 if (!Gui::getMainWindow()->close()) {
169 // cancel the shutdown
170 manager.release();
171 manager.cancel();
172 }
173 }
174 else {
175 // no user interaction allowed, thus close all documents and
176 // the main window
177 App::GetApplication().closeAllDocuments();
178 Gui::getMainWindow()->close();
179 }
180 }
181
182 bool GUIApplication::event(QEvent* ev)
183 {
184 if (ev->type() == QEvent::FileOpen) {
185 // (macOS workaround when opening FreeCAD by opening a .FCStd file in 1.0)
186 // With the current implementation of the splash screen boot procedure, Qt will
187 // start an event loop before FreeCAD is fully initialized. This event loop will
188 // process the QFileOpenEvent that is sent by macOS before the main window is ready.
189 if (!Gui::getMainWindow()->property("eventLoop").toBool()) {
190 // If we never reach this point when opening FreeCAD by double clicking an
191 // .FCStd file, then the workaround isn't needed anymore and can be removed
192 QEvent* eventCopy = new QFileOpenEvent(static_cast<QFileOpenEvent*>(ev)->file());
193 QTimer::singleShot(0, [eventCopy, this]() {
194 QCoreApplication::postEvent(this, eventCopy);
195 });
196 return true;
197 }
198
199 QString file = static_cast<QFileOpenEvent*>(ev)->file();
200 QFileInfo fi(file);
201 if (fi.suffix().toLower() == QLatin1String("fcstd")) {
202 QByteArray fn = file.toUtf8();
203 Application::Instance->open(fn, "FreeCAD");
204 return true;
205 }
206 }
207
208 return GUIApplicationNativeEventAware::event(ev);
209 }
210
211 // ----------------------------------------------------------------------------
212
213 class GUISingleApplication::Private
214 {
215 public:
216 explicit Private(GUISingleApplication* q_ptr)
217 : q_ptr(q_ptr)
218 , timer(new QTimer(q_ptr))
219 {
220 timer->setSingleShot(true);
221 std::string exeName = App::Application::getExecutableName();
222 serverName = QString::fromStdString(exeName);
223 }
224
225 ~Private()
226 {
227 if (server) {
228 server->close();
229 }
230 delete server;
231 }
232
233 void setupConnection()
234 {
235 QLocalSocket socket;
236 socket.connectToServer(serverName);
237 if (socket.waitForConnected(1000)) {
238 this->running = true;
239 }
240 else {
241 startServer();
242 }
243 }
244
245 void startServer()
246 {
247 // Start a QLocalServer to listen for connections
248 server = new QLocalServer();
249 QObject::connect(
250 server,
251 &QLocalServer::newConnection,
252 q_ptr,
253 &GUISingleApplication::receiveConnection
254 );
255 // first attempt
256 if (!server->listen(serverName)) {
257 if (server->serverError() == QAbstractSocket::AddressInUseError) {
258 // second attempt
259 server->removeServer(serverName);
260 server->listen(serverName);
261 }
262 }
263 if (server->isListening()) {
264 Base::Console().log("Local server '%s' started\n", qPrintable(serverName));
265 }
266 else {
267 Base::Console().log("Local server '%s' failed to start\n", qPrintable(serverName));
268 }
269 }
270
271 GUISingleApplication* q_ptr;
272 QTimer* timer;
273 QLocalServer* server {nullptr};
274 QString serverName;
275 QList<QString> messages;
276 bool running {false};
277 };
278
279 GUISingleApplication::GUISingleApplication(int& argc, char** argv)
280 : GUIApplication(argc, argv)
281 , d_ptr(new Private(this))
282 {
283 d_ptr->setupConnection();
284 connect(d_ptr->timer, &QTimer::timeout, this, &GUISingleApplication::processMessages);
285 }
286
287 GUISingleApplication::~GUISingleApplication() = default;
288
289 bool GUISingleApplication::isRunning() const
290 {
291 return d_ptr->running;
292 }
293
294 bool GUISingleApplication::sendMessage(const QString& message, int timeout)
295 {
296 QLocalSocket socket;
297 bool connected = false;
298 for (int i = 0; i < 2; i++) {
299 socket.connectToServer(d_ptr->serverName);
300 connected = socket.waitForConnected(timeout / 2);
301 if (connected || i > 0) {
302 break;
303 }
304 int ms = 250;
305 #if defined(Q_OS_WIN)
306 Sleep(DWORD(ms));
307 #else
308 usleep(ms * 1000);
309 #endif
310 }
311 if (!connected) {
312 return false;
313 }
314
315 QTextStream ts(&socket);
316 #if QT_VERSION <= QT_VERSION_CHECK(6, 0, 0)
317 ts.setCodec("UTF-8");
318 #else
319 ts.setEncoding(QStringConverter::Utf8);
320 #endif
321 #if QT_VERSION <= QT_VERSION_CHECK(5, 15, 0)
322 ts << message << endl;
323 #else
324 ts << message << Qt::endl;
325 #endif
326
327 return socket.waitForBytesWritten(timeout);
328 }
329
330 void GUISingleApplication::readFromSocket()
331 {
332 auto socket = qobject_cast<QLocalSocket*>(sender());
333 if (socket) {
334 QTextStream in(socket);
335 #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
336 in.setCodec("UTF-8");
337 #else
338 in.setEncoding(QStringConverter::Utf8);
339 #endif
340 while (socket->canReadLine()) {
341 d_ptr->timer->stop();
342 QString message = in.readLine();
343 Base::Console().log("Received message: %s\n", message.toStdString());
344 d_ptr->messages.push_back(message);
345 d_ptr->timer->start(1000);
346 }
347 }
348 }
349
350 void GUISingleApplication::receiveConnection()
351 {
352 QLocalSocket* socket = d_ptr->server->nextPendingConnection();
353 if (!socket) {
354 return;
355 }
356
357 connect(socket, &QLocalSocket::disconnected, socket, &QLocalSocket::deleteLater);
358 connect(socket, &QLocalSocket::readyRead, this, &GUISingleApplication::readFromSocket);
359 }
360
361 void GUISingleApplication::processMessages()
362 {
363 QList<QString> msg = d_ptr->messages;
364 d_ptr->messages.clear();
365 Q_EMIT messageReceived(msg);
366 }
367
368 // ----------------------------------------------------------------------------
369
370 WheelEventFilter::WheelEventFilter(QObject* parent)
371 : QObject(parent)
372 {}
373
374 bool WheelEventFilter::eventFilter(QObject* obj, QEvent* ev)
375 {
376 if (qobject_cast<QComboBox*>(obj) && ev->type() == QEvent::Wheel) {
377 return true;
378 }
379 auto sb = qobject_cast<QAbstractSpinBox*>(obj);
380 if (sb) {
381 if (ev->type() == QEvent::Show) {
382 sb->setFocusPolicy(Qt::StrongFocus);
383 }
384 else if (ev->type() == QEvent::Wheel) {
385 return !sb->hasFocus();
386 }
387 }
388 return false;
389 }
390
391 #include "moc_GuiApplication.cpp"