Debian Codegraph @

src/Gui/SplashScreen.cpp

raw
1 /***************************************************************************
2 * Copyright (c) 2004 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 #include <cstdlib>
24 #include <QApplication>
25 #include <QClipboard>
26 #include <QDir>
27 #include <QElapsedTimer>
28 #include <QFile>
29 #include <QFileInfo>
30 #include <QMutex>
31 #include <QPainter>
32 #include <QRegularExpression>
33 #include <QRegularExpressionMatch>
34 #include <QThread>
35 #include <QWaitCondition>
36 #include <QWindow>
37
38 #include <App/Application.h>
39 #include <App/Metadata.h>
40 #include <Base/Console.h>
41
42 #include "BitmapFactory.h"
43 #include "SplashScreen.h"
44 #include "Tools.h"
45
46 using namespace Gui;
47
48 namespace Gui
49 {
50
51 /** Displays all messages at startup inside the splash screen.
52 * \author Werner Mayer
53 */
54 class SplashObserver: public Base::ILogger
55 {
56 public:
57 SplashObserver(const SplashObserver&) = delete;
58 SplashObserver(SplashObserver&&) = delete;
59 SplashObserver& operator=(const SplashObserver&) = delete;
60 SplashObserver& operator=(SplashObserver&&) = delete;
61
62 explicit SplashObserver(QSplashScreen* splasher = nullptr)
63 : splash(splasher)
64 , alignment(Qt::AlignBottom | Qt::AlignLeft)
65 , textColor(Qt::black)
66 {
67 Base::Console().attachObserver(this);
68
69 // allow to customize text position and color
70 const std::map<std::string, std::string>& cfg = App::Application::Config();
71 auto al = cfg.find("SplashAlignment");
72 if (al != cfg.end()) {
73 QString alt = QString::fromLatin1(al->second.c_str());
74 int align = 0;
75 if (alt.startsWith(QLatin1String("VCenter"))) {
76 align = Qt::AlignVCenter;
77 }
78 else if (alt.startsWith(QLatin1String("Top"))) {
79 align = Qt::AlignTop;
80 }
81 else {
82 align = Qt::AlignBottom;
83 }
84
85 if (alt.endsWith(QLatin1String("HCenter"))) {
86 align += Qt::AlignHCenter;
87 }
88 else if (alt.endsWith(QLatin1String("Right"))) {
89 align += Qt::AlignRight;
90 }
91 else {
92 align += Qt::AlignLeft;
93 }
94
95 alignment = align;
96 }
97
98 // choose text color
99 auto tc = cfg.find("SplashTextColor");
100 if (tc != cfg.end()) {
101 QColor col(QString::fromStdString(tc->second));
102 if (col.isValid()) {
103 textColor = col;
104 }
105 }
106 }
107 ~SplashObserver() override
108 {
109 Base::Console().detachObserver(this);
110 }
111 const char* name() override
112 {
113 return "SplashObserver";
114 }
115 void sendLog(
116 const std::string& notifiername,
117 const std::string& msg,
118 Base::LogStyle level,
119 Base::IntendedRecipient recipient,
120 Base::ContentType content
121 ) override
122 {
123 Q_UNUSED(notifiername)
124 Q_UNUSED(recipient)
125 Q_UNUSED(content)
126
127 #ifdef FC_DEBUG
128 Q_UNUSED(level)
129 Log(msg);
130 #else
131 if (level == Base::LogStyle::Log) {
132 Log(msg);
133 }
134 #endif
135 }
136 void Log(const std::string& text)
137 {
138 QString msg(QString::fromStdString(text));
139 QRegularExpression rx;
140 // ignore 'Init:' and 'Mod:' prefixes
141 rx.setPattern(QLatin1String("^\\s*(Init:|Mod:)\\s*"));
142 auto match = rx.match(msg);
143 if (match.hasMatch()) {
144 msg = msg.mid(match.capturedLength());
145 }
146 else {
147 // ignore activation of commands
148 rx.setPattern(QLatin1String(R"(^\s*(\+App::|Create|CmdC:|CmdG:|Act:)\s*)"));
149 match = rx.match(msg);
150 if (match.hasMatch() && match.capturedStart() == 0) {
151 return;
152 }
153 }
154
155 splash->showMessage(msg.replace(QLatin1String("\n"), QString()), alignment, textColor);
156 QMutex mutex;
157 QMutexLocker ml(&mutex);
158 QWaitCondition().wait(&mutex, 50);
159 }
160
161 private:
162 QSplashScreen* splash;
163 int alignment;
164 QColor textColor;
165 };
166
167 /**
168 * Displays a warning about this being a developer build. Designed for display in the Splashscreen.
169 * \param painter The painter to draw the warning into
170 * \param startPosition The painter-space coordinates to start the warning box at.
171 * \param maxSize The maximum extents for the box that is drawn. If the text exceeds this size it
172 * will be scaled down to fit.
173 * \note The text string is translatable, so its length is somewhat unpredictable. It is always
174 * displayed as two lines, regardless of the length of the text (e.g. no wrapping is done). Only the
175 * width is considered, the height simply follows from the font size.
176 */
177 static void renderDevBuildWarning(
178 QPainter& painter,
179 const QPoint startPosition,
180 const QSize maxSize,
181 QColor color
182 )
183 {
184 // Create a background box that fades out the artwork for better legibility
185 QColor fader(Qt::white);
186 constexpr float halfDensity(0.65F);
187 fader.setAlphaF(halfDensity);
188 QBrush fillBrush(fader, Qt::BrushStyle::SolidPattern);
189 painter.setBrush(fillBrush);
190
191 // Construct the lines of text and figure out how much space they need
192 const auto devWarningLine1 = QObject::tr("WARNING: This is a development version.");
193 const auto devWarningLine2 = QObject::tr("Do not use it in a production environment.");
194 QFontMetrics fontMetrics(painter.font()); // Try to use the existing font
195 int padding = QtTools::horizontalAdvance(fontMetrics, QLatin1String("M")); // Arbitrary
196 int line1Width = QtTools::horizontalAdvance(fontMetrics, devWarningLine1);
197 int line2Width = QtTools::horizontalAdvance(fontMetrics, devWarningLine2);
198 int boxWidth = std::max(line1Width, line2Width) + 2 * padding;
199 int lineHeight = fontMetrics.lineSpacing();
200 if (boxWidth > maxSize.width()) {
201 // Especially if the text was translated, there is a chance that using the existing font
202 // will exceed the width of the Splashscreen graphic. Resize down so that it fits, no matter
203 // how long the text strings are.
204 float reductionFactor = static_cast<float>(maxSize.width()) / static_cast<float>(boxWidth);
205 int newFontSize = static_cast<int>(painter.font().pointSize() * reductionFactor);
206 padding *= reductionFactor;
207 QFont newFont = painter.font();
208 newFont.setPointSize(newFontSize);
209 painter.setFont(newFont);
210 lineHeight = painter.fontMetrics().lineSpacing();
211 boxWidth = maxSize.width();
212 }
213 constexpr float lineExpansionFactor(2.3F);
214 int boxHeight = static_cast<int>(lineHeight * lineExpansionFactor);
215
216 // Draw the background rectangle and the text
217 painter.setPen(color);
218 painter.drawRect(startPosition.x(), startPosition.y(), boxWidth, boxHeight);
219 painter.drawText(startPosition.x() + padding, startPosition.y() + lineHeight, devWarningLine1);
220 painter.drawText(startPosition.x() + padding, startPosition.y() + 2 * lineHeight, devWarningLine2);
221 }
222
223 } // namespace Gui
224
225 // ------------------------------------------------------------------------------
226
227 /**
228 * Constructs a splash screen that will display the pixmap.
229 */
230 SplashScreen::SplashScreen(const QPixmap& pixmap, Qt::WindowFlags f)
231 : QSplashScreen(pixmap, f)
232 {
233 // write the messages to splasher
234 messages = new SplashObserver(this);
235 }
236
237 /** Destruction. */
238 SplashScreen::~SplashScreen()
239 {
240 delete messages;
241 }
242
243 void SplashScreen::finish(QWidget* w)
244 {
245 Q_UNUSED(w);
246 close();
247 }
248
249 bool SplashScreen::event(QEvent* e)
250 {
251 if (e->type() == QEvent::Show) {
252 // Bypass QSplashScreen::event for Show events specifically
253 return QWidget::event(e); // NOLINT(bugprone-parent-virtual-call)
254 }
255 return QSplashScreen::event(e);
256 }
257
258 void SplashScreen::show()
259 {
260 QSplashScreen::show();
261
262 // Our repaint will call processEvents later on, no need to waste time here
263 if (messages->bErr) {
264 return;
265 }
266
267 // Show events are bypassed and splash window is already created by the above show()
268 // call. Now process pending events from underlying OS which actually brings splash
269 // into existence (such as X' MapNotify/Expose events or Wayland's xdg_surface
270 // configuration acknowledgement)
271 constexpr int TimeOut = 250;
272 constexpr int TimeSlice = 20;
273 QElapsedTimer timer;
274 timer.start();
275 while (timer.elapsed() < TimeOut) {
276 QCoreApplication::processEvents(QEventLoop::AllEvents, TimeSlice);
277 QCoreApplication::sendPostedEvents();
278 if (windowHandle()->isExposed()) {
279 break;
280 }
281 QThread::msleep(TimeSlice);
282 }
283 }
284
285 /**
286 * Draws the contents of the splash screen using painter \a painter. The default
287 * implementation draws the message passed by message().
288 */
289 void SplashScreen::drawContents(QPainter* painter)
290 {
291 QSplashScreen::drawContents(painter);
292 }
293
294 void SplashScreen::setShowMessages(bool on)
295 {
296 messages->bErr = on;
297 messages->bMsg = on;
298 messages->bLog = on;
299 messages->bWrn = on;
300 }
301
302 QPixmap SplashScreen::splashImage()
303 {
304 // search in the UserAppData dir as very first
305 QPixmap splash_image;
306 QFileInfo fi(QStringLiteral("images:splash_image.png"));
307 if (fi.isFile() && fi.exists()) {
308 splash_image.load(fi.filePath(), "PNG");
309 }
310
311 // if no image was found try the config
312 std::string splash_path = App::Application::Config()["SplashScreen"];
313 if (splash_image.isNull()) {
314 QString path = QString::fromStdString(splash_path);
315 if (QDir(path).isRelative()) {
316 QString home = QString::fromStdString(App::Application::getHomePath());
317 path = QFileInfo(QDir(home), path).absoluteFilePath();
318 }
319
320 splash_image.load(path);
321 }
322
323 // now try the icon paths
324 float pixelRatio(1.0);
325 if (splash_image.isNull()) {
326 // determine the count of splashes
327 QStringList pixmaps = Gui::BitmapFactory().findIconFiles().filter(
328 QString::fromStdString(splash_path)
329 );
330 // divide by 2 since there's two sets (normal and 2x)
331 // minus 1 to ignore the default splash that isn't numbered
332 int splash_count = pixmaps.count() / 2 - 1;
333
334 // set a random splash path
335 if (splash_count > 0) {
336 int random = rand() % splash_count;
337 splash_path += std::to_string(random);
338 }
339
340 if (qApp->devicePixelRatio() > 1.0) {
341 // For HiDPI screens, we have a double-resolution version of the splash image
342 splash_path += "_2x";
343 splash_image = Gui::BitmapFactory().pixmap(splash_path.c_str());
344 splash_image.setDevicePixelRatio(2.0);
345 pixelRatio = 2.0;
346 }
347 else {
348 splash_image = Gui::BitmapFactory().pixmap(splash_path.c_str());
349 }
350 }
351
352 // include application name and version number
353 std::map<std::string, std::string>::const_iterator tc = App::Application::Config().find(
354 "SplashInfoColor"
355 );
356 std::map<std::string, std::string>::const_iterator wc = App::Application::Config().find(
357 "SplashWarningColor"
358 );
359 if (tc != App::Application::Config().end() && wc != App::Application::Config().end()) {
360 QString title = qApp->applicationName();
361 QString major = QString::fromStdString(App::Application::Config()["BuildVersionMajor"]);
362 QString minor = QString::fromStdString(App::Application::Config()["BuildVersionMinor"]);
363 QString point = QString::fromStdString(App::Application::Config()["BuildVersionPoint"]);
364 QString suffix = QString::fromStdString(App::Application::Config()["BuildVersionSuffix"]);
365 QString version = QStringLiteral("%1.%2.%3%4").arg(major, minor, point, suffix);
366 QString position, fontFamily;
367
368 std::map<std::string, std::string>::const_iterator te = App::Application::Config().find(
369 "SplashInfoExeName"
370 );
371 std::map<std::string, std::string>::const_iterator tv = App::Application::Config().find(
372 "SplashInfoVersion"
373 );
374 std::map<std::string, std::string>::const_iterator tp = App::Application::Config().find(
375 "SplashInfoPosition"
376 );
377 std::map<std::string, std::string>::const_iterator tf = App::Application::Config().find(
378 "SplashInfoFont"
379 );
380 if (te != App::Application::Config().end()) {
381 title = QString::fromStdString(te->second);
382 }
383 if (tv != App::Application::Config().end()) {
384 version = QString::fromStdString(tv->second);
385 }
386 if (tp != App::Application::Config().end()) {
387 position = QString::fromStdString(tp->second);
388 }
389 if (tf != App::Application::Config().end()) {
390 fontFamily = QString::fromStdString(tf->second);
391 }
392
393 QPainter painter;
394 painter.begin(&splash_image);
395 if (!fontFamily.isEmpty()) {
396 QFont font = painter.font();
397 if (font.fromString(fontFamily)) {
398 painter.setFont(font);
399 }
400 }
401
402 QFont fontExe = painter.font();
403 fontExe.setPointSizeF(20.0);
404 QFontMetrics metricExe(fontExe);
405 int l = QtTools::horizontalAdvance(metricExe, title);
406 if (title == QLatin1String("FreeCAD")) {
407 l = 0.0; // "FreeCAD" text is already part of the splashscreen, version goes below it
408 }
409 int w = splash_image.width();
410 int h = splash_image.height();
411
412 QFont fontVer = painter.font();
413 fontVer.setPointSizeF(11.0);
414 QFontMetrics metricVer(fontVer);
415 int v = QtTools::horizontalAdvance(metricVer, version);
416
417 int x = -1, y = -1;
418 QRegularExpression rx(QLatin1String("(\\d+).(\\d+)"));
419 auto match = rx.match(position);
420 if (match.hasMatch()) {
421 x = match.captured(1).toInt();
422 y = match.captured(2).toInt();
423 }
424 else {
425 x = w - (l + v + 10);
426 y = h - 20;
427 }
428
429 QColor color(QString::fromStdString(tc->second));
430 if (color.isValid()) {
431 painter.setPen(color);
432 painter.setFont(fontExe);
433 if (title != QLatin1String("FreeCAD")) {
434 // FreeCAD's Splashscreen already contains the EXE name, no need to draw it
435 painter.drawText(x, y, title);
436 }
437 painter.setFont(fontVer);
438 painter.drawText(x + (l + 235), y - 7, version);
439 QColor warningColor(QString::fromStdString(wc->second));
440 if (suffix == QLatin1String("dev") && warningColor.isValid()) {
441 fontVer.setPointSizeF(14.0);
442 painter.setFont(fontVer);
443 const int lineHeight = metricVer.lineSpacing();
444 const int padding {45}; // Distance from the edge of the graphic's bounding box
445 QPoint startPosition(padding, y + lineHeight * 2);
446 QSize maxSize(w / pixelRatio - 2 * padding, lineHeight * 3);
447 renderDevBuildWarning(painter, startPosition, maxSize, warningColor);
448 }
449 painter.end();
450 }
451 }
452
453 return splash_image;
454 }