swift
Loading...
Searching...
No Matches
stylesheetutility.cpp
1// SPDX-FileCopyrightText: Copyright (C) 2013 swift Project Community / Contributors
2// SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-swift-pilot-client-1
3
5
6#include <QAbstractScrollArea>
7#include <QDir>
8#include <QFile>
9#include <QFileInfo>
10#include <QFileInfoList>
11#include <QFlags>
12#include <QFont>
13#include <QIODevice>
14#include <QRegularExpression>
15#include <QStringBuilder>
16#include <QStyleOption>
17#include <QStylePainter>
18#include <QTextStream>
19#include <QWidget>
20#include <QtGlobal>
21
22#include "config/buildconfig.h"
23#include "misc/fileutils.h"
24#include "misc/logmessage.h"
26
27using namespace swift::config;
28using namespace swift::misc;
29
30namespace swift::gui
31{
33 {
34 this->read();
35 connect(&m_fileWatcher, &QFileSystemWatcher::directoryChanged, this, &CStyleSheetUtility::qssDirectoryChanged);
36 connect(&m_fileWatcher, &QFileSystemWatcher::fileChanged, this, &CStyleSheetUtility::qssDirectoryChanged);
37 }
38
40 {
41 static const QStringList cats { CLogCategories::guiComponent() };
42 return cats;
43 }
44
46 {
47 static const QString n("normal");
48 static const QString i("italic");
49 static const QString o("oblique");
50 static const QString e;
51
52 switch (font.style())
53 {
54 case QFont::StyleNormal: return n;
55 case QFont::StyleItalic: return i;
56 case QFont::StyleOblique: return o;
57 default: return e;
58 }
59 }
60
62 {
63 if (font.weight() < static_cast<int>(QFont::Normal))
64 {
65 static const QString l("light");
66 return l;
67 }
68 else if (font.weight() < static_cast<int>(QFont::DemiBold))
69 {
70 static const QString n("normal");
71 return n;
72 }
73 else if (font.weight() < static_cast<int>(QFont::Bold))
74 {
75 static const QString d("demibold");
76 return d;
77 }
78 else if (font.weight() < static_cast<int>(QFont::Black))
79 {
80 static const QString b("bold");
81 return b;
82 }
83 else
84 {
85 static const QString b("black");
86 return b;
87 }
88 }
89
91 {
93 QString s = fontStyleAsString(font);
94 if (w == s) return w; // avoid "normal" "normal"
95 if (w.isEmpty() && s.isEmpty()) return "normal";
96 if (w.isEmpty()) return s;
97 if (s.isEmpty()) return w;
98 if (s == "normal") return w;
99 return w.append(" ").append(s);
100 }
101
102 QString CStyleSheetUtility::asStylesheet(const QString &fontFamily, const QString &fontSize,
103 const QString &fontStyle, const QString &fontWeight,
104 const QString &fontColor)
105 {
106 static const QString indent(" ");
107 static const QString lf("\n");
108 static const QString fontStyleSheet(
109 "%1font-family: \"%3\";%2%1font-size: %4;%2%1font-style: %5;%2%1font-weight: %6;%2%1color: %7;%2");
110 static const QString fontStyleSheetNoColor(
111 "%1font-family: \"%3\";%2%1font-size: %4;%2%1font-style: %5;%2%1font-weight: %6;%2");
112
113 return fontColor.isEmpty() ?
114 fontStyleSheetNoColor.arg(indent, lf, fontFamily, fontSize, fontStyle, fontWeight) :
115 fontStyleSheet.arg(indent, lf, fontFamily, fontSize, fontStyle, fontWeight, fontColor);
116 }
117
119 {
120 Q_ASSERT_X(widget, Q_FUNC_INFO, "Missing widget");
121 const QFont f = widget->font();
123 f.family(), QStringLiteral("%1pt").arg(pointSize < 0 ? f.pointSize() : pointSize),
125 }
126
128 {
129 const QString s = this->style(fileNameFonts()).toLower();
130 if (!s.contains("color:")) return "";
131 thread_local const QRegularExpression rx("color:\\s*(#*\\w+);");
132 const QString c = rx.match(s).captured(1);
133 return c.isEmpty() ? "" : c;
134 }
135
137 {
139 if (!directory.exists())
140 {
141 return false;
142 }
143
144 // qss/css files
145 const bool needsWatcher = m_fileWatcher.files().isEmpty();
146 if (needsWatcher)
147 {
148 m_fileWatcher.addPath(CSwiftDirectories::stylesheetsDirectory());
149 } // directory to deleted file watching
150 directory.setNameFilters({ "*.qss", "*.css" });
152
153 QMap<QString, QString> newStyleSheets;
154 const QFileInfoList fileInfoList = directory.entryInfoList();
155
156 // here we generate the style sheets
157 for (const QFileInfo &fileInfo : fileInfoList)
158 {
159 const QString absolutePath = fileInfo.absoluteFilePath();
160 QFile file(absolutePath);
161 if (file.open(QFile::QIODevice::ReadOnly | QIODevice::Text))
162 {
163 if (needsWatcher)
164 {
165 m_fileWatcher.addPath(absolutePath);
166 }
167 QTextStream in(&file);
168 const QString c = removeComments(in.readAll(), true, true);
169 const QString f = fileInfo.fileName().toLower();
170
171 // save files for debugging
173 {
176 }
177
178 // keep even empty files as placeholders
179 newStyleSheets.insert(f, c); // set an empty string here to disable all stylesheet
180 }
181 file.close();
182 }
183
184 // ignore redundant re-reads
185 if (newStyleSheets != m_styleSheets)
186 {
187 m_styleSheets = newStyleSheets;
188 emit this->styleSheetsChanged();
189 }
190 return true;
191 }
192
194 {
195 if (!this->containsStyle(fileName))
196 {
197 return {};
198 }
199 return m_styleSheets[fileName.toLower()].trimmed();
200 }
201
203 {
204 const bool hasModifiedFont = this->containsStyle(fileNameFontsModified());
205 bool fontAdded = false;
206
208 for (const QString &fileName : fileNames)
209 {
210 const QString key = fileName.toLower().trimmed();
211 if (!this->containsStyle(key))
212 {
213 continue;
214 }
215
216 QString s;
217 if (fileName == fileNameFonts() || fileName == fileNameFontsModified())
218 {
219 if (fontAdded)
220 {
221 continue;
222 }
223 fontAdded = true;
224 s = hasModifiedFont ? m_styleSheets[fileNameFontsModified().toLower()] : m_styleSheets[fileNameFonts()];
225 }
226 else
227 {
228 s = m_styleSheets[key];
229 }
230 if (s.isEmpty())
231 {
232 continue;
233 }
234
235 style += (style.isEmpty() ? QString() : "\n\n") % u"/** file: " % fileName % " **/\n" % s;
236 }
237 return style;
238 }
239
240 bool CStyleSheetUtility::containsStyle(const QString &fileName) const
241 {
242 if (fileName.isEmpty()) return false;
243 return m_styleSheets.contains(fileName.toLower().trimmed());
244 }
245
247 {
248 QString fs;
249 if (font.pixelSize() >= 0)
250 {
251 fs.append(QString::number(font.pixelSize())).append("px");
252 }
253 else
254 {
255 fs.append(QString::number(font.pointSizeF())).append("pt");
256 }
257 return updateFont(font.family(), fs, fontStyleAsString(font), fontWeightAsString(font), "white");
258 }
259
260 bool CStyleSheetUtility::updateFont(const QString &fontFamily, const QString &fontSize, const QString &fontStyle,
261 const QString &fontWeight, const QString &fontColor)
262 {
263 const QString qss = CStyleSheetUtility::asStylesheet(fontFamily, fontSize, fontStyle, fontWeight, fontColor);
265 }
266
268 {
269 const QString qssWidget(u"QWidget {\n" % qss % u"}\n");
270 const QString fn =
272 QFile fontFile(fn);
273 bool ok = fontFile.open(QFile::Text | QFile::WriteOnly);
274 if (ok)
275 {
276 QTextStream out(&fontFile);
277 out << qssWidget;
278 fontFile.close();
279 ok = this->read();
280 }
281 else
282 {
283 CLogMessage(static_cast<CStyleSheetUtility *>(nullptr)).warning(u"Cannot open file '%1' for writing") << fn;
284 }
285 return ok;
286 }
287
293
294 QString CStyleSheetUtility::fontStyle(const QString &combinedStyleAndWeight)
295 {
296 static const QString n("normal");
297 const QString c = combinedStyleAndWeight.toLower();
298 for (const QString &s : fontStyles())
299 {
300 if (c.contains(s))
301 {
302 return s;
303 }
304 }
305 return n;
306 }
307
308 QString CStyleSheetUtility::fontWeight(const QString &combinedStyleAndWeight)
309 {
310 static const QString n("normal");
311 const QString c = combinedStyleAndWeight.toLower();
312 for (const QString &w : fontWeights())
313 {
314 if (c.contains(w))
315 {
316 return w;
317 }
318 }
319 return n;
320 }
321
323 {
324 static const QString f(getQssFileName("fonts"));
325 return f;
326 }
327
329 {
330 static const QString f("fonts.modified.qss");
331 return f;
332 }
333
335 {
336 const QString fn =
338 QFile file(fn);
339 if (!file.exists())
340 {
341 return false;
342 }
343 bool r = file.remove();
344 if (!r)
345 {
346 return false;
347 }
348 this->read();
349 return true;
350 }
351
353 {
354 static const QString f(getQssFileName("swiftstdgui"));
355 return f;
356 }
357
364
366 {
367 static const QString f(getQssFileName("infobar"));
368 return f;
369 }
370
372 {
373 static const QString f(getQssFileName("navigator"));
374 return f;
375 }
376
378 {
379 static const QString f(getQssFileName("dockwidgettab"));
380 return f;
381 }
382
384 {
385 static const QString f(getQssFileName("stdwidget"));
386 return f;
387 }
388
395
397 {
398 static const QString f("textmessage.css");
399 return f;
400 }
401
403 {
404 static const QString f(getQssFileName("filterdialog"));
405 return f;
406 }
407
409 {
410 static const QString f(getQssFileName("swiftcore"));
411 return f;
412 }
413
415 {
416 static const QString f(getQssFileName("swiftdata"));
417 return f;
418 }
419
421 {
422 static const QString f(getQssFileName("swiftlauncher"));
423 return f;
424 }
425
427 {
428 static const QStringList w({ "bold", "semibold", "light", "black", "normal" });
429 return w;
430 }
431
433 {
434 static const QStringList s({ "italic", "oblique", "normal" });
435 return s;
436 }
437
439 {
440 static const QString t = "background-color: transparent;";
441 return t;
442 }
443
445 {
446 Q_ASSERT(usedWidget);
447 if (!usedWidget)
448 {
449 return false;
450 }
451
452 Q_ASSERT(usedWidget->style());
453 QStyle *style = usedWidget->style();
454 if (!style)
455 {
456 return false;
457 }
458
459 // 1) QStylePainter: modern version of
460 // usedWidget->style()->drawPrimitive(element, &opt, &p, usedWidget);
461 // 2) With viewport based widgets viewport has to be used
462 // see http://stackoverflow.com/questions/37952348/enable-own-widget-for-stylesheet
463 auto *sa = qobject_cast<QAbstractScrollArea *>(usedWidget);
464 QStylePainter p(sa ? sa->viewport() : usedWidget);
465 if (!p.isActive())
466 {
467 return false;
468 }
469
470 QStyleOption opt;
471 opt.initFrom(usedWidget);
472 p.drawPrimitive(element, opt);
473 return true;
474 }
475
476 QString CStyleSheetUtility::styleForIconCheckBox(const QString &checkedIcon, const QString &uncheckedIcon,
477 const QString &width, const QString &height)
478 {
479 Q_ASSERT(!checkedIcon.isEmpty());
480 Q_ASSERT(!uncheckedIcon.isEmpty());
481
482 static const QString st = "QCheckBox::indicator { width: %1; height: %2; } QCheckBox::indicator:checked { "
483 "image: url(%3); } QCheckBox::indicator:unchecked { image: url(%4); }";
484 return st.arg(width, height, checkedIcon, uncheckedIcon);
485 }
486
488 {
489 QString s1(style1.trimmed());
490 QString s2(style2.trimmed());
491 if (s1.isEmpty())
492 {
493 return s2;
494 }
495 if (s2.isEmpty())
496 {
497 return s1;
498 }
499 if (!s1.endsWith(";"))
500 {
501 s1 = s1.append("; ");
502 }
503 s1.append(s2);
504 if (!s1.endsWith(";"))
505 {
506 s1 = s1.append(";");
507 }
508 return s1;
509 }
510
511 void CStyleSheetUtility::setQSysInfoProperties(QWidget *widget, bool withChildWidgets)
512 {
513 Q_ASSERT_X(widget, Q_FUNC_INFO, "Missing widget");
514 if (!widget->property("qsysKernelType").isValid())
515 {
516 widget->setProperty("qsysKernelType", QSysInfo::kernelType());
517 widget->setProperty("qsysCurrentCpuArchitecture", QSysInfo::currentCpuArchitecture());
518 widget->setProperty("qsysBuildCpuArchitecture", QSysInfo::buildCpuArchitecture());
519 widget->setProperty("qsysProductType", QSysInfo::productType());
520 }
521
522 if (withChildWidgets)
523 {
525 {
527 }
528 }
529 }
530
531 void CStyleSheetUtility::qssDirectoryChanged(const QString &file)
532 {
533 Q_UNUSED(file);
534 this->read();
535 }
536
537 QString CStyleSheetUtility::getQssFileName(const QString &fileName)
538 {
539 static const QString qss(".qss");
540 QString fn(fileName);
541 if (fn.endsWith(qss))
542 {
543 fn.chop(qss.length());
544 }
545
546 QString specific;
548 {
549 specific = fn % u".win" % qss;
550 }
552 {
553 specific = fn % u".mac" % qss;
554 }
556 {
557 specific = fn % u".linux" % qss;
558 }
559 return qssFileExists(specific) ? specific : fn + qss;
560 }
561
562 bool CStyleSheetUtility::qssFileExists(const QString &filename)
563 {
564 if (filename.isEmpty())
565 {
566 return false;
567 }
569 return f.exists() && f.isReadable();
570 }
571} // namespace swift::gui
static constexpr bool isRunningOnMacOSPlatform()
Running on MacOS platform?
static bool isLocalDeveloperDebugBuild()
Local build for developers.
static constexpr bool isRunningOnWindowsNtPlatform()
Running on Windows NT platform?
static constexpr bool isRunningOnLinuxPlatform()
Running on Linux platform?
bool containsStyle(const QString &fileName) const
Contains style for name.
static const QString & fileNameDockWidgetTab()
File name dockwidgettab.qss.
static const QString & fontWeightAsString(const QFont &font)
Font weight as string.
static QString asStylesheet(const QString &fontFamily, const QString &fontSize, const QString &fontStyle, const QString &fontWeight, const QString &fontColorString={})
Parameters as stylesheet.
static bool useStyleSheetInDerivedWidget(QWidget *derivedWidget, QStyle::PrimitiveElement element=QStyle::PE_Widget)
Use style sheets in derived widgets.
static const QString & fileNameSwiftData()
File name swiftcore.qss.
static const QString & fileNameSwiftStandardGui()
File name swift standard GUI.
static const QStringList & fontStyles()
Font styles.
static const QString & fontStyleAsString(const QFont &font)
Font style as string.
static const QString & fileNameSwiftCore()
File name swiftcore.qss.
static const QString & fileNameInfoBar()
File name infobar.qss.
static const QString & fileNameStandardWidget()
File name for standard widgets.
static const QString & fileNameTextMessage()
File name textmessage.qss.
static const QString & transparentBackgroundColor()
Transparent background color.
static QString fontStyle(const QString &combinedStyleAndWeight)
Get the font style.
static const QStringList & fontWeights()
Font weights.
static const QString & fileNameSwiftLauncher()
File name swiftlauncher.qss.
static QString styleForIconCheckBox(const QString &checkedIcon, const QString &uncheckedIcon, const QString &width="16px", const QString &height="16px")
Stylesheet string for a checkbox displayed as 2 icons.
bool updateFont(const QFont &font)
Update the fonts.
static const QStringList & getLogCategories()
Log cats.
static QString fontAsCombinedWeightStyle(const QFont &font)
Font as combined weight and style.
static QString concatStyles(const QString &style1, const QString &style2)
Concatenate 2 styles.
static const QString & fileNameFilterDialog()
File name maininfoarea.qss.
static void setQSysInfoProperties(QWidget *widget, bool withChildWidgets)
Set QSysInfo properties for given widget (which can be used in stylesheet).
QString fontColorString() const
Current font color from style sheet.
bool read()
Read the *.qss files.
QString style(const QString &fileName) const
Style for given file name.
static const QString & fileNameAndPathStandardWidget()
Full file path and name for standard widgets.
void styleSheetsChanged()
Sheets have been changed.
static const QString & fileNameFontsModified()
Name for user modified file.
QString styles(const QStringList &fileNames) const
Multiple styles concatenated.
static const QString & fileNameNavigator()
File name navigator.qss.
static QString fontWeight(const QString &combinedStyleAndWeight)
Get the font weight.
static const QString & fileNameFonts()
File name fonts.qss.
static const QString & fileNameAndPathSwiftStandardGui()
Full file path and name for swift standard GUI.
CStyleSheetUtility(QObject *parent=nullptr)
Constructor.
bool deleteModifiedFontFile()
Delete the modified file for fonts.
static bool writeStringToFile(const QString &content, const QString &fileNameAndPath)
Write string to text file.
Definition fileutils.cpp:40
static QString appendFilePaths(const QString &path1, const QString &path2)
Append file paths.
static const QString & guiComponent()
GUI components.
Class for emitting a log message.
Definition logmessage.h:27
Derived & warning(const char16_t(&format)[N])
Set the severity to warning, providing a format string.
static const QString & stylesheetsDirectory()
Where qss files are located.
static const QString & logDirectory()
Directory for log files.
GUI related classes.
Free functions in swift::misc.
SWIFT_MISC_EXPORT QString removeComments(const QString &in, bool removeSlash, bool removeDoubleSlash)
Remove comments such as /‍** **‍/ or //.
QFileInfoList entryInfoList(QDir::Filters filters, QDir::SortFlags sort) const const
bool exists() const const
void setFilter(QDir::Filters filters)
void setNameFilters(const QStringList &nameFilters)
bool exists(const QString &fileName)
bool open(FILE *fh, QIODeviceBase::OpenMode mode, QFileDevice::FileHandleFlags handleFlags)
bool remove()
virtual void close() override
void directoryChanged(const QString &path)
void fileChanged(const QString &path)
QString family() const const
int pixelSize() const const
int pointSize() const const
qreal pointSizeF() const const
QFont::Style style() const const
QFont::Weight weight() const const
QMap< Key, T >::iterator insert(QMap< Key, T >::const_iterator pos, const Key &key, const T &value)
QObject(QObject *parent)
QMetaObject::Connection connect(const QObject *sender, PointerToMemberFunction signal, Functor functor)
QList< T > findChildren(QAnyStringView name, Qt::FindChildOptions options) const const
QObject * parent() const const
QVariant property(const char *name) const const
T qobject_cast(QObject *object)
bool setProperty(const char *name, QVariant &&value)
bool isActive() const const
QRegularExpressionMatch match(QStringView subjectView, qsizetype offset, QRegularExpression::MatchType matchType, QRegularExpression::MatchOptions matchOptions) const const
QString captured(QAnyStringView name) const const
QString & append(QChar ch)
QString arg(Args &&... args) const const
bool contains(QChar ch, Qt::CaseSensitivity cs) const const
bool endsWith(QChar c, Qt::CaseSensitivity cs) const const
bool isEmpty() const const
QString number(double n, char format, int precision)
QString toLower() const const
QString trimmed() const const
PrimitiveElement
void initFrom(const QWidget *widget)
void drawPrimitive(QStyle::PrimitiveElement pe, const QStyleOption &option)
QString buildCpuArchitecture()
QString currentCpuArchitecture()
QString kernelType()
QString productType()
FindDirectChildrenOnly
QString readAll()
bool isValid() const const
QStyle * style() const const