7 #include <QApplication>
9 #include <QCommandLineParser>
10 #include <QDesktopServices>
14 #include <QGuiApplication>
16 #include <QKeySequence>
17 #include <QMainWindow>
19 #include <QMessageBox>
21 #include <QStringBuilder>
22 #include <QStringList>
24 #include <QStyleFactory>
43 #include "gui/registermetadata.h"
56 using namespace swift::config;
58 using namespace swift::misc::db;
59 using namespace swift::misc::network;
63 using namespace swift::core::context;
69 CGuiApplication *CGuiApplication::instance() {
return qobject_cast<CGuiApplication *>(CApplication::instance()); }
73 static const QStringList l(CApplication::getLogCategories() +
QStringList { CLogCategories::guiComponent() });
77 const QString &CGuiApplication::settingsOrganization()
79 static const QString o(
"swift-project.org");
83 bool CGuiApplication::removeAllWindowsSwiftRegistryEntries()
115 CApplication::init(
false);
116 CGuiApplication::adjustPalette();
118 this->settingsChanged();
119 this->setCurrentFontValues();
133 CApplication::registerMetadata();
173 else {
return CEnableForFramelessWindow::WindowNormal; }
180 m_splashScreen.reset();
190 m_splashScreen->show();
191 m_splashScreen->showStatusMessage(
"Version " + CBuildConfig::getVersionString());
209 if (this->
getGlobalSetup().isSwiftVersionMinimumMappingVersion()) {
return true; }
212 QStringLiteral(
"Your are using swift version: '%1'.\nCreating mappings requires at least '%2'.")
213 .
arg(CBuildConfig::getVersionString(), this->
getGlobalSetup().getMappingMinimumVersionString());
231 if (!mainWidget) {
return; }
232 if (m_uiSetupCompleted) {
return; }
233 m_uiSetupCompleted =
true;
250 windowFlags |= flags;
257 if (!myself) {
return; }
266 if (!extraInfo.
isEmpty()) { name = extraInfo % u
' ' % name; }
267 if (!mainWindowWidget) {
return name; }
307 const QString &CGuiApplication::fileForWindowGeometryAndStateSettings()
309 static const QString filename = [] {
311 CFileUtils::appendFilePaths(CSwiftDirectories::normalizedApplicationDataDirectory(),
"settings/qgeom");
312 return CFileUtils::appendFilePaths(
318 int CGuiApplication::hashForStateSettingsSchema(
const QMainWindow *window)
323 hash ^=
qHash(obj->objectName());
327 hash ^=
qHash(obj->objectName());
329 return static_cast<int>((hash & 0xffff) ^ (hash >> 16));
334 if (!window) {
return false; }
337 settings.
setValue(
"windowState", window->
saveState(hashForStateSettingsSchema(window)));
346 settings.
setValue(
"windowState", ba);
351 if (!window) {
return false; }
368 QStringLiteral(
"Restoring the window state/geometry failed!\n"
369 "You need to reset the window size (command -%1).\n\n"
370 "Original msg: %2\n\n"
371 "We can try to reset the values and restart\n"
372 "Do you want to try?")
385 window->
restoreState(s, hashForStateSettingsSchema(window));
392 CApplication::onStartUpCompleted();
393 this->setCurrentFontValues();
399 if (m_minWidthChars > 0 || m_minHeightChars > 0)
407 if (m_minWidthChars > 0) { cs.
setWidth(qRound(fontMetricEstSize.
width())); }
408 if (m_minHeightChars > 0) { cs.
setHeight(qRound(fontMetricEstSize.
height())); }
412 if (m_saveMainWidgetState && !this->
isSet(m_cmdWindowSizeReset))
421 m_splashScreen->close();
422 m_splashScreen.reset();
429 if (informativeText.
length() < 300)
441 if (msgs.
isEmpty()) {
return; }
445 { CStatusMessage::IndexSeverityAsString, CStatusMessage::IndexMessage });
446 const QString msgsHtml = msgs.
toHtml(msgs.
size() > 1 ? propertiesMulti : propertiesSingle);
458 if (!m) {
return false; }
464 if (message.
isEmpty()) {
return false; }
473 if (messages.
isEmpty()) {
return false; }
482 if (html.
isEmpty()) {
return false; }
491 QMenu *sm = menu.
addMenu(CIcons::appSettings16(),
"Settings");
492 sm->
setIcon(CIcons::appSettings16());
499 Q_ASSERT_X(c, Q_FUNC_INFO,
"Connect failed");
504 CSettingsCache::instance()->clearAllValues();
507 Q_ASSERT_X(c, Q_FUNC_INFO,
"Connect failed");
509 a = sm->
addAction(
"List settings files");
512 const QStringList files(CSettingsCache::instance()->enumerateStore());
515 Q_ASSERT_X(c, Q_FUNC_INFO,
"Connect failed");
518 sm->
setIcon(CIcons::appSettings16());
519 a = sm->
addAction(CIcons::disk16(),
"Cache directory");
524 Q_ASSERT_X(c, Q_FUNC_INFO,
"Connect failed");
529 const QStringList files = CApplication::clearCaches();
532 Q_ASSERT_X(c, Q_FUNC_INFO,
"Connect failed");
537 const QStringList files(CDataCache::instance()->enumerateStore());
540 Q_ASSERT_X(c, Q_FUNC_INFO,
"Connect failed");
542 a = menu.
addAction(CIcons::disk16(),
"Log directory");
545 this->openStandardLogDirectory();
547 Q_ASSERT_X(c, Q_FUNC_INFO,
"Connect failed");
549 a = menu.
addAction(CIcons::disk16(),
"Crash dumps directory");
552 this->openStandardCrashDumpDirectory();
554 Q_ASSERT_X(c, Q_FUNC_INFO,
"Connect failed");
556 a = menu.
addAction(CIcons::swift24(),
"Check for updates");
558 Q_ASSERT_X(c, Q_FUNC_INFO,
"Connect failed");
568 this->reloadStyleSheets();
570 Q_ASSERT_X(c, Q_FUNC_INFO,
"Connect failed");
575 this->openStandardWidgetStyleSheet();
577 Q_ASSERT_X(c, Q_FUNC_INFO,
"Connect failed");
604 Q_ASSERT_X(c, Q_FUNC_INFO,
"Connect failed");
620 Q_ASSERT_X(c, Q_FUNC_INFO,
"Connect failed");
622 a = sm->
addAction(
"JSON version update info (for info only)");
631 Q_ASSERT_X(c, Q_FUNC_INFO,
"Connect failed");
635 a = menu.
addAction(
"Services log.(console)");
643 Q_ASSERT_X(c, Q_FUNC_INFO,
"Connect failed");
645 a = sm->
addAction(
"JSON DB info (for info only)");
655 Q_ASSERT_X(c, Q_FUNC_INFO,
"Connect failed");
657 a = sm->
addAction(
"JSON shared info (for info only)");
667 Q_ASSERT_X(c, Q_FUNC_INFO,
"Connect failed");
678 Q_ASSERT_X(c, Q_FUNC_INFO,
"Connect failed");
686 const QSize iconSize = CIcons::empty16().size();
695 Q_ASSERT_X(c, Q_FUNC_INFO,
"Connect failed");
703 Q_ASSERT_X(c, Q_FUNC_INFO,
"Connect failed");
711 Q_ASSERT_X(c, Q_FUNC_INFO,
"Connect failed");
713 a = menu.
addAction(
"Toggle stay on top");
718 Q_ASSERT_X(c, Q_FUNC_INFO,
"Connect failed");
720 a = menu.
addAction(
"Toggle to front or back");
722 Q_ASSERT_X(c, Q_FUNC_INFO,
"connect failed");
726 Q_ASSERT_X(c, Q_FUNC_INFO,
"connect failed");
730 Q_ASSERT_X(c, Q_FUNC_INFO,
"connect failed");
732 a = menu.
addAction(
"Toggle normal or minimized");
737 Q_ASSERT_X(c, Q_FUNC_INFO,
"Connect failed");
743 if (url.
isEmpty() || this->isShuttingDown()) {
return; }
757 Q_ASSERT_X(c, Q_FUNC_INFO,
"Connect failed");
765 Q_ASSERT_X(c, Q_FUNC_INFO,
"Connect failed");
771 Q_ASSERT_X(c, Q_FUNC_INFO,
"Connect failed");
788 if (currentWidgetStyle.
startsWith(
'Q')) { currentWidgetStyle.
remove(0, 1); }
789 return currentWidgetStyle.
replace(
"Style",
"");
803 if (!
QDir(path).exists()) {
return false; }
810 if (!
QDir(path).exists()) {
return false; }
817 return m_styleSheetUtility.
updateFont(fontFamily, fontSize, fontStyle, fontWeight, fontColor);
826 m_minWidthChars = widthChars;
827 m_minHeightChars = heightChars;
854 if (mainWindow && !mainWindow->
windowTitle().isEmpty())
868 if (closeEvent) { closeEvent->
ignore(); }
891 const int result = m_updateDialog->
exec();
898 if (!w) {
return QStringLiteral(
"Font info not available"); }
899 return QStringLiteral(
"Family: '%1', average width: %2")
900 .arg(w->
font().family())
907 if (!w) {
return false; }
909 CLogMessage(w).
info(onTop ? QStringLiteral(
"Window on top") : QStringLiteral(
"Window not always on top"));
981 m_normalizeMinimize = !m_normalizeMinimize;
986 if (!m_updateSetting.get()) {
return; }
989 if (m_updateDialog) {
return; }
999 CLogMessage(
this).
info(u
"Graceful shutdown of GUI application started");
1000 if (m_saveMainWidgetState)
1007 CApplication::gracefulShutdown();
1011 if (modals.
count() > 0)
1014 CLogMessage(
this).
info(u
"Graceful shutdown, still %1 modal widget(s), closed: %2")
1022 if (docks.
count() > 0)
1025 CLogMessage(
this).
warning(u
"Graceful shutdown, still %1 floating dock widget(s), closed: %2")
1030 void CGuiApplication::settingsChanged()
1033 const QString widgetStyle = m_guiSettings.get().getWidgetStyle();
1035 Q_ASSERT_X(CThreadUtils::thisIsMainThread(), Q_FUNC_INFO,
"Wrong thread");
1039 if (availableStyles.
contains(widgetStyle))
1057 else {
CLogMessage(
this).
error(u
"Unable to set requested style '%1'") << widgetStyle; }
1063 void CGuiApplication::checkNewVersionMenu() { this->
checkNewVersion(
false); }
1065 void CGuiApplication::adjustPalette()
1070 QPalette newPalette(qApp->palette());
1071 const QColor linkColor(135, 206, 250);
1074 qApp->setPalette(newPalette);
1077 void CGuiApplication::onStyleSheetsChanged()
1088 void CGuiApplication::setCurrentFontValues()
1091 m_fontFamily = font.
family();
static constexpr bool isRunningOnWindowsNtPlatform()
Running on Windows NT platform?
QString getParserValue(const QString &option) const
Delegates to QCommandLineParser::value.
std::atomic_bool m_shutdown
Is being shutdown?
void restartApplication(const QStringList &newArguments={}, const QStringList &removeArguments={})
Stop and restart application.
bool isParserOptionSet(const QString &option) const
Delegates to QCommandLineParser::isSet.
data::CGlobalSetup getGlobalSetup() const
Global setup.
QCommandLineParser m_parser
cmd parser
bool hasUnsavedSettings() const
Unsaved settings.
bool hasWebDataServices() const
Web data services available?
const context::IContextNetwork * getIContextNetwork() const
Direct access to contexts if a CCoreFacade has been initialized.
bool addParserOption(const QCommandLineOption &option)
bool isShuttingDown() const
Is application shutting down?
bool isSet(const QCommandLineOption &option) const
Flag set or explicitly set to true.
std::atomic_bool m_shutdownInProgress
shutdown in progress?
const QString & getApplicationNameVersionDetailed() const
Version, name beta and dev info.
CWebDataServices * getWebDataServices() const
Get the web data services.
const QString & getApplicationNameAndVersion() const
Application name and version.
void saveSettingsOnShutdown(bool saveSettings)
Save settings on shutdown.
void startUpCompleted(bool success)
Startup has been completed Will be triggered shortly before starting the event loop.
swift::core::db::CInfoDataReader * getDbInfoDataReader() const
DB info data reader.
swift::core::db::CInfoDataReader * getSharedInfoDataReader() const
Shared info data reader.
Global settings for readers, debug flags, etc.
swift::misc::network::CUrl getHelpPageUrl() const
Help page URL.
swift::misc::db::CDbInfoList getInfoObjects() const
Get info list (either shared or from DB)
static WindowMode stringToWindowMode(const QString &s)
String to window mode.
GUI application, a specialized version of swift::core::CApplication for GUI applications.
bool openStandardWidgetStyleSheet()
Opens the standard stylesheet.
static void modalWindowToFront()
Bring any modal dialog to front.
bool isCmdWindowSizeResetSet() const
Window size reset mode set.
QString setExtraWindowTitle(const QString &extraInfo, QWidget *mainWindowWidget=mainApplicationWidget()) const
Set window title.
QString getFontInfo() const
Info about font.
static swift::gui::IMainWindowAccess * mainWindowAccess()
Main window access interface.
void onCoreFacadeStarted()
Called when facade/contexts have been started.
void registerMainApplicationWidget(QWidget *mainWidget)
Register main application window widget if this is known.
void addWindowResetSizeOption()
CMD line arguments (reset size store)
void addWindowStateOption()
CMD line arguments.
void processEventsToRefreshGui() const
Allow the GUI to refresh by processing events, call the event loop.
Qt::WindowState getWindowState() const
Window state.
bool hasMinimumMappingVersion() const
Minimum mapping version check.
void addWindowModeOption()
CMD line arguments.
static QRect currentScreenGeometry()
Current screen resolution.
void triggerNewVersionCheck(int delayedMs)
Trigger new version check.
bool openStandardCrashDumpDirectory()
Opens the standard dumps directory.
static CGuiApplication * instance()
Similar to.
void windowToFront()
Window to front/back.
CEnableForFramelessWindow::WindowMode getWindowMode() const
Window mode (window flags)
void addMenuHelp(QMenu &menu)
Help operations.
void addMenuForStyleSheets(QMenu &menu)
Add menu for style sheets.
~CGuiApplication()
Destructor.
bool reloadStyleSheets()
Reload style sheets.
void cmdLineErrorMessage(const QString &text, const QString &informativeText) const
print messages generated during parsing / cmd handling
static void exit(int retcode=0)
Exit application, perform graceful shutdown and exit.
void addMenuFile(QMenu &menu)
File menu.
void addMenuInternals(QMenu &menu)
Internals menu.
bool displayInOverlayWindow(const swift::misc::CStatusMessage &message, std::chrono::milliseconds timeout=std::chrono::milliseconds(0))
direct access to main application window
void checkNewVersion(bool onlyIfNew)
Check for a new version (update)
void splashScreen(const QPixmap &pixmap)
Add a splash screen based on resource, empty means remove splash screen.
bool restoreWindowGeometryAndState(QMainWindow *window=CGuiApplication::mainApplicationWindow())
Restore widget's geometry and state.
void fontChanged()
Font has been changed.
const CStyleSheetUtility & getStyleSheetUtility() const
Style sheet handling.
bool saveWindowGeometryAndState(const QMainWindow *window=CGuiApplication::mainApplicationWindow()) const
Save widget's geometry and state.
QDialog::DialogCode showCloseDialog(QMainWindow *mainWindow, QCloseEvent *closeEvent)
Show close dialog.
void windowToBack()
Window to front/back.
void gracefulShutdown()
Graceful shutdown.
void onStartUpCompleted()
Startup completed.
bool toggleStayOnTop()
Toggle stay on top.
void windowToFrontBackToggle()
Window to front/back.
static void registerMetadata()
Register metadata.
static void setWindowIcon(const QPixmap &icon)
Set icon.
bool resetFont()
Reset the font to default.
void displaySetupLoadFailure(swift::misc::CStatusMessageList msgs)
Display the failures caused by loading the setup file.
void windowMinimizeNormalToggle()
Window minimize/normalize.
void addMenuForSettingsAndCache(QMenu &menu)
Add menu items for settings and cache.
bool updateFont(const QString &fontFamily, const QString &fontSize, const QString &fontStyle, const QString &fontWeight, const QString &fontColor)
Update the fonts.
void showHelp(const QString &subpath={}) const
Show help page (online help)
bool displayInStatusBar(const swift::misc::CStatusMessage &message)
direct access to main application window
void alwaysOnTop(bool onTop)
always on top
static QWidget * mainApplicationWidget()
Main application window widget.
static QMainWindow * mainApplicationWindow()
Main application window.
bool parsingHookIn()
Handle parsing of special GUI cmd arguments.
void uiObjectTreeReady()
Object tree ready (means ui->setupUi() completed)
void openUrl(const swift::misc::network::CUrl &url)
Open a given URL.
bool openStandardLogDirectory()
Opens the standard log directory.
void addMenuWindow(QMenu &menu)
Window operations.
void initMainApplicationWidget(QWidget *mainWidget)
Init the main application window based on information in this application.
static QScreen * currentScreen()
Current screen.
void addWindowFlags(Qt::WindowFlags flags)
Set window flag on main application window.
QString getWidgetStyle() const
Current widget style.
void styleSheetsChanged()
Style sheet changed.
void setMinimumSizeInCharacters(int widthChars, int heightChars)
Set minimum width/height in characters.
void resetWindowGeometryAndState()
Reset the saved values.
static bool stayOnTop(bool onTop, QWidget *widget)
Window flags / stay on top.
static QStringList deleteLaterAllDockWidgetsGetTitles(QWidget *parent, bool floatingOnly)
"deleteLater" all dock widgets
static bool staysOnTop(QWidget *widget)
Window on top?
static void registerMainApplicationWidget(QWidget *mainWidget)
Register main application window widget if this is known.
static QSizeF fontMetricsEstimateSize(int xCharacters, int yCharacters, bool withRatio=false)
Estimate size based on current font.
static void superviseMainWindowMinSizes(qreal wRatio=0.85, qreal hRatio=0.85)
Make sure that the min.sizes to not exceed the screen resolution.
static QString metricsInfo()
Some info about font metrics.
static QWidget * mainApplicationWidget()
Main application window widget.
static QStringList closeAllModalWidgetsGetTitles()
Close all modal widgets and get titles.
static QFont currentFont()
Main window font or default font.
static bool toggleStayOnTop(QWidget *widget)
Toggle window flags / stay on top.
Reads and provides style sheets.
static const QString & fileNameStandardWidget()
File name for standard widgets.
bool updateFont(const QFont &font)
Update the fonts.
static void setQSysInfoProperties(QWidget *widget, bool withChildWidgets)
Set QSysInfo properties for given widget (which can be used in stylesheet)
bool read()
Read the *.qss files.
static const QString & fileNameAndPathStandardWidget()
Full file path and name for standard widgets.
void styleSheetsChanged()
Sheets have been changed.
QString styles(const QStringList &fileNames) const
Multiple styles concatenated.
bool resetFont()
Reset font.
static const QString & fileNameFonts()
File name fonts.qss.
Direct acccess to main window`s status bar, info bar and such.
virtual bool displayInOverlayWindow(const swift::misc::CStatusMessage &message, std::chrono::milliseconds timeout=std::chrono::milliseconds(0))
Display in overlay window.
virtual bool displayInStatusBar(const swift::misc::CStatusMessage &message)
Display in status bar.
Close dialog for application.
Setup dialog, if loading the boostrap file fails.
Download and install swift.
bool isNewVersionAvailable() const
A new version existing?
Application
Enumeration of application roles.
QString toJsonString(QJsonDocument::JsonFormat format=QJsonDocument::Indented) const
Convenience function JSON as string.
Class for emitting a log message.
Value class for matching log messages based on their categories.
CLogPattern withSeverity(CStatusMessage::StatusSeverity severity) const
Returns a CLogPattern which will match the same messages as this one, but only with a given severity.
A helper class for subscribing to log messages matching a particular pattern, with the ability to cha...
void changeSubscription(const CLogPattern &pattern)
Change the pattern which you want to subscribe to.
Derived & warning(const char16_t(&format)[N])
Set the severity to warning, providing a format string.
bool isEmpty() const
Message empty.
Derived & validationError(const char16_t(&format)[N])
Set the severity to error, providing a format string, and adding the validation category.
Derived & error(const char16_t(&format)[N])
Set the severity to error, providing a format string.
Derived & info(const char16_t(&format)[N])
Set the severity to info, providing a format string.
Value object encapsulating a list of property indexes.
size_type size() const
Returns number of elements in the sequence.
bool isEmpty() const
Synonym for empty.
Streamable status message, e.g.
QString getMessage() const
Message.
Status messages, e.g. from Core -> GUI.
QString toHtml(const CPropertyIndexList &indexes=simpleHtmlOutput()) const
Specialized version to convert to HTML.
bool hasErrorMessages() const
Error messages.
Value object encapsulating a list of info objects.
Update info, i.e. artifacts and distributions.
Value object encapsulating information of a location, kind of simplified CValueObject compliant versi...
bool isEmpty() const
Empty.
CUrl withAppendedPath(const QString &path) const
Append path.
SWIFT_GUI_EXPORT swift::gui::CGuiApplication * sGui
Single instance of GUI application object.
Core data traits (aka cached values) and classes.
Backend services of the swift project, like dealing with the network or the simulators.
High level reusable GUI components.
void registerMetadata()
Register metadata for GUI.
Free functions in swift::misc.
QString getAllUserMetatypesTypes(const QString &separator)
Get all user metatypes.
QMetaObject::Connection connectOnce(T *sender, F signal, U *receiver, G &&slot, Qt::ConnectionType type=Qt::AutoConnection)
Wrapper around QObject::connect which disconnects after the signal has been emitted once.
SWIFT_MISC_EXPORT bool stringCompare(const QString &c1, const QString &c2, Qt::CaseSensitivity cs)
String compare.
QString className(const QObject *object)
Class name as from QMetaObject::className with namespace.
QString applicationName()
Get application name.
void triggered(bool checked)
QStyle * setStyle(const QString &style)
bool isEmpty() const const
QStringList names() const const
QString valueName() const const
bool isSet(const QCommandLineOption &option) const const
QString applicationFilePath()
void processEvents(QEventLoop::ProcessEventsFlags flags)
QString translate(const char *context, const char *sourceText, const char *disambiguation, int n)
bool openUrl(const QUrl &url)
void setModal(bool modal)
QString toNativeSeparators(const QString &pathName)
QString family() const const
int pointSize() const const
void setFamily(const QString &family)
void setPointSize(int pointSize)
void setStretch(int factor)
int averageCharWidth() const const
Qt::KeyboardModifiers queryKeyboardModifiers()
void setWindowIcon(const QIcon &icon)
qsizetype count() const const
bool restoreState(const QByteArray &state, int version)
QByteArray saveState(int version) const const
QMessageBox::StandardButton critical(QWidget *parent, const QString &title, const QString &text, QMessageBox::StandardButtons buttons, QMessageBox::StandardButton defaultButton)
void setDetailedText(const QString &text)
virtual int exec() override
void setInformativeText(const QString &text)
QMessageBox::StandardButton warning(QWidget *parent, const QString &title, const QString &text, QMessageBox::StandardButtons buttons, QMessageBox::StandardButton defaultButton)
QMetaObject::Connection connect(const QObject *sender, PointerToMemberFunction signal, Functor functor)
QList< T > findChildren(QAnyStringView name, Qt::FindChildOptions options) const const
void setObjectName(QAnyStringView name)
bool isNull() const const
QPixmap scaled(const QSize &size, Qt::AspectRatioMode aspectRatioMode, Qt::TransformationMode transformMode) const const
QString fileName() const const
void remove(QAnyStringView key)
void setValue(QAnyStringView key, const QVariant &value)
QVariant value(QAnyStringView key) const const
void setHeight(int height)
qreal height() const const
qreal width() const const
QString arg(Args &&... args) const const
bool isEmpty() const const
qsizetype length() const const
QString number(double n, char format, int precision)
QString & remove(QChar ch, Qt::CaseSensitivity cs)
QString & replace(QChar before, QChar after, Qt::CaseSensitivity cs)
bool startsWith(QChar c, Qt::CaseSensitivity cs) const const
bool contains(QLatin1StringView str, Qt::CaseSensitivity cs) const const
QString join(QChar separator) const const
QStyle * create(const QString &key)
typedef KeyboardModifiers
QUrl fromLocalFile(const QString &localFile)
QByteArray toByteArray() const const
void setWindowIconText(const QString &)
QScreen * screen() const const
#define SWIFT_VERIFY_X(COND, WHERE, WHAT)
A weaker kind of assert.