1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
|
/**
* QtAwesome - use font-awesome (or other font icons) in your c++ / Qt Application
*
* MIT Licensed
*
* Copyright 2013-2024 - Reliable Bits Software by Blommers IT. All Rights Reserved.
* Author Rick Blommers
*/
#include "QtAwesome.h"
#include "QtAwesomeAnim.h"
#include <QApplication>
#include <QDebug>
#include <QFile>
#include <QFontDatabase>
#include <QFontMetrics>
#include <QPalette>
#include <QString>
#if (QT_VERSION >= QT_VERSION_CHECK(6, 5, 0))
#define USE_COLOR_SCHEME
#include <QStyleHints>
#include <QSvgRenderer>
#endif
#ifdef Q_OS_MAC
#include "osxstyle.h"
#endif
// Initializing namespaces need to happen outside a namespace
static void qtawesome_init_resources()
{
#ifdef BUNDLED_FONTAWESOME
Q_INIT_RESOURCE(QtAwesomeFree);
#endif
}
namespace fa {
#include "QtAwesomeStringGenerated.h"
QtAwesomeIconPainter::~QtAwesomeIconPainter()
{
}
/// The font-awesome icon painter
class QtAwesomeCharIconPainter : public QtAwesomeIconPainter {
protected:
virtual ~QtAwesomeCharIconPainter()
{
}
QStringList optionKeysForModeAndState(const QString& key, QIcon::Mode mode, QIcon::State state)
{
QString modePostfix;
switch (mode) {
case QIcon::Disabled:
modePostfix = "-disabled";
break;
case QIcon::Active:
modePostfix = "-active";
break;
case QIcon::Selected:
modePostfix = "-selected";
break;
default:
break;
}
QString statePostfix;
if (state == QIcon::Off) {
statePostfix = "-off";
}
// the keys that need to bet tested: key-mode-state | key-mode | key-state | key
QStringList result;
if (!modePostfix.isEmpty()) {
if (!statePostfix.isEmpty()) {
result.push_back(key + modePostfix + statePostfix);
}
result.push_back(key + modePostfix);
}
if (!statePostfix.isEmpty()) {
result.push_back(key + statePostfix);
}
return result;
}
QVariant optionValueForModeAndState(const QString& baseKey, QIcon::Mode mode, QIcon::State state,
const QVariantMap& options, const QtAwesome* awesome)
{
for (const QString& key : optionKeysForModeAndState(baseKey, mode, state)) {
if (options.contains(key) && !(options.value(key).toString().isEmpty())) {
return options.value(key);
}
}
if (options.contains(baseKey) && !(options.value(baseKey).toString().isEmpty())) {
return options.value(baseKey);
}
for (const QString& key : optionKeysForModeAndState(baseKey, mode, state)) {
if (awesome->hasDefaultOption(key) && !(awesome->defaultOption(key).toString().isEmpty())) {
return awesome->defaultOption(key);
}
}
return awesome->defaultOption(baseKey);
}
public:
void paint(QtAwesome* awesome, QPainter* painter, const QRect& rect, QIcon::Mode mode, QIcon::State state,
const QVariantMap& options) override
{
painter->save();
painter->setRenderHint(QPainter::Antialiasing);
#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
painter->setRenderHint(QPainter::HighQualityAntialiasing);
#endif
QVariant var = options.value("anim");
QtAwesomeAnimation* anim = var.value<QtAwesomeAnimation*>();
if (anim) {
anim->setup(*painter, rect);
}
// set the default options
QColor color = optionValueForModeAndState("color", mode, state, options, awesome).value<QColor>();
QString text = optionValueForModeAndState("text", mode, state, options, awesome).toString();
QString filename = optionValueForModeAndState("filename", mode, state, options, awesome).toString();
int st = optionValueForModeAndState("style", mode, state, options, awesome).toInt();
double scaleFactor = optionValueForModeAndState("scale-factor", mode, state, options, awesome).toDouble();
bool rtl = optionValueForModeAndState("rtl", mode, state, options, awesome).toBool();
Q_ASSERT(color.isValid());
Q_ASSERT(!text.isEmpty() || !filename.isEmpty());
// Setting RTL makes the icon RTL-aware and will flip it if
// needed.
if (rtl && QApplication::isRightToLeft()) {
painter->translate(rect.width(), 0);
painter->scale(-1, 1);
}
if (filename.isEmpty()) {
painter->setPen(color);
QRectF textRect(rect);
int flags = Qt::AlignHCenter | Qt::AlignVCenter;
// ajust font size depending on the rectangle
int drawSize = qRound(textRect.height() * scaleFactor);
QFont ft = awesome->font(st, drawSize);
QFontMetricsF fm(ft);
QRectF tbr = fm.boundingRect(textRect, flags, text);
if (tbr.width() > textRect.width()) {
drawSize = static_cast<int>(ft.pixelSize() * qMin(textRect.width() * 0.95 / tbr.width(), textRect.height() * 0.95 / tbr.height()));
ft.setPixelSize(drawSize);
}
painter->setFont(ft);
painter->drawText(textRect, flags, text);
}
else {
QSvgRenderer renderer;
QFile f(filename);
QByteArray bytes;
if (f.open(QIODevice::ReadOnly)) {
bytes = f.readAll();
}
if (!bytes.isEmpty()) {
bytes.replace("#000", color.name().toLatin1());
}
renderer.load(bytes);
renderer.render(painter, QRect(0, 0, rect.width(), rect.height()));
}
painter->restore();
}
};
//---------------------------------------------------------------------------------------
/// The painter icon engine.
class QtAwesomeIconPainterIconEngine : public QIconEngine {
public:
QtAwesomeIconPainterIconEngine(QtAwesome* awesome, QtAwesomeIconPainter* painter, const QVariantMap& options)
: awesomeRef_(awesome), iconPainterRef_(painter), options_(options)
{
}
virtual ~QtAwesomeIconPainterIconEngine() {}
QtAwesomeIconPainterIconEngine* clone() const
{
return new QtAwesomeIconPainterIconEngine(awesomeRef_, iconPainterRef_, options_);
}
virtual void paint(QPainter* painter, const QRect& rect, QIcon::Mode mode, QIcon::State state)
{
Q_UNUSED(mode);
Q_UNUSED(state);
iconPainterRef_->paint(awesomeRef_, painter, rect, mode, state, options_);
}
virtual QPixmap pixmap(const QSize& size, QIcon::Mode mode, QIcon::State state)
{
QPixmap pm(size);
pm.fill(Qt::transparent);// we need transparency
{
QPainter p(&pm);
paint(&p, QRect(QPoint(0, 0), size), mode, state);
}
return pm;
}
private:
QtAwesome* awesomeRef_; ///< a reference to the QtAwesome instance
QtAwesomeIconPainter* iconPainterRef_;///< a reference to the icon painter
QVariantMap options_; ///< the options for this icon painter
};
//---------------------------------------------------------------------------------------
const QString QtAwesome::FA_BRANDS_FONT_FILENAME = "Font Awesome 6 Brands-Regular-400.otf";
const QString QtAwesome::FA_REGULAR_FONT_FILENAME = "Font Awesome 6 Free-Regular-400.otf";
const QString QtAwesome::FA_SOLID_FONT_FILENAME = "Font Awesome 6 Free-Solid-900.otf";
const QString QtAwesome::FA_BRANDS_FONT_STYLE = "Regular";
const QString QtAwesome::FA_REGULAR_FONT_STYLE = "Regular";
const QString QtAwesome::FA_SOLID_FONT_STYLE = "Solid";
/// The default icon colors
QtAwesome::QtAwesome(QObject* parent)
: QObject(parent), _namedCodepointsByStyle(), _namedCodepointsList()
{
hasInit = false;
resetDefaultOptions();
_fontIconPainter = new QtAwesomeCharIconPainter();
#ifdef BUNDLED_FONTAWESOME
_fontDetails.insert(fa::fa_solid, QtAwesomeFontData(FA_SOLID_FONT_FILENAME, FA_SOLID_FONT_WEIGHT, FA_SOLID_FONT_STYLE));
_fontDetails.insert(fa::fa_regular, QtAwesomeFontData(FA_REGULAR_FONT_FILENAME, FA_REGULAR_FONT_WEIGHT, FA_REGULAR_FONT_STYLE));
_fontDetails.insert(fa::fa_brands, QtAwesomeFontData(FA_BRANDS_FONT_FILENAME, FA_BRANDS_FONT_WEIGHT, FA_BRANDS_FONT_STYLE));
#else
// use "filename" to store font family name...
_fontDetails.insert(fa::fa_solid, QtAwesomeFontData("Font Awesome 6 Free Solid", FA_SOLID_FONT_WEIGHT, FA_SOLID_FONT_STYLE));
_fontDetails.insert(fa::fa_regular, QtAwesomeFontData("Font Awesome 6 Free Regular", FA_REGULAR_FONT_WEIGHT, FA_REGULAR_FONT_STYLE));
_fontDetails.insert(fa::fa_brands, QtAwesomeFontData("Font Awesome 6 Brands Regular", FA_BRANDS_FONT_WEIGHT, FA_BRANDS_FONT_STYLE));
#endif
#ifdef USE_COLOR_SCHEME
// support dark/light mode
QObject::connect(QApplication::styleHints(), &QStyleHints::colorSchemeChanged, this, [this](Qt::ColorScheme _) {
resetDefaultOptions();
});
#endif
}
void QtAwesome::resetDefaultOptions()
{
_defaultOptions.clear();
setDefaultOption("color", QApplication::palette().color(QPalette::Normal, QPalette::Text));
setDefaultOption("color-disabled", QApplication::palette().color(QPalette::Disabled, QPalette::Text));
setDefaultOption("color-active", QApplication::palette().color(QPalette::Active, QPalette::Text));
#ifdef Q_OS_MAC
setDefaultOption("color-selected", OSXStyle::self()->viewPalette().highlightedText().color());
#else
setDefaultOption("color-selected", QApplication::palette().color(QPalette::Active, QPalette::HighlightedText));// TODO: check how to get the correct highlighted color
#endif
setDefaultOption("scale-factor", 1.0);
setDefaultOption("text", QVariant());
setDefaultOption("text-disabled", QVariant());
setDefaultOption("text-active", QVariant());
setDefaultOption("text-selected", QVariant());
Q_EMIT defaultOptionsReset();
}
QtAwesome::~QtAwesome()
{
delete _fontIconPainter;
qDeleteAll(_painterMap);
qDeleteAll(_namedCodepointsList);
}
/// a specialized init function so font-awesome is loaded and initialized
/// this method return true on success, it will return false if the fnot cannot be initialized
/// To initialize QtAwesome with font-awesome you need to call this method
bool QtAwesome::initFontAwesome()
{
if (hasInit) return true;
bool success = true;
#ifdef BUNDLED_FONTAWESOME
// The macro below internally calls "qInitResources_QtAwesome()". this initializes
// the resource system. For a .pri project this isn't required, but when building and using a
// static library the resource need to initialized first.
///
// I've checked th qInitResource_* code and calling this method mutliple times shouldn't be any problem
// (More info about this subject: http://qt-project.org/wiki/QtResources)
qtawesome_init_resources();
for (QtAwesomeFontData& fd : _fontDetails) {
// only load font-awesome once
if (fd.fontId() < 0) {
// load the font file
QFile res(":/fonts/" + fd.fontFilename());
if (!res.open(QIODevice::ReadOnly)) {
qDebug() << "Font awesome font" << fd.fontFilename() << "could not be loaded!";
success = false;
continue;
}
QByteArray fontData(res.readAll());
res.close();
// fetch the given font
fd.setFontId(QFontDatabase::addApplicationFontFromData(fontData));
}
QStringList loadedFontFamilies = QFontDatabase::applicationFontFamilies(fd.fontId());
if (loadedFontFamilies.empty()) {
qDebug() << "Font awesome" << fd.fontFilename() << " font is empty?!";
fd.setFontId(-1);// restore the font-awesome id
return false;
}
else {
fd.setFontFamily(loadedFontFamilies.at(0));
}
}
#else
for (QtAwesomeFontData& fd : _fontDetails) {
fd.setFontFamily(fd.fontFilename()); // yes, what a great semantic use of the variable...
}
#endif
// intialize the brands icon map
addToNamedCodePoints(fa::fa_brands, faBrandsIconArray, sizeof(faBrandsIconArray) / sizeof(QtAwesomeNamedIcon));
addToNamedCodePoints(fa::fa_solid, faCommonIconArray, sizeof(faCommonIconArray) / sizeof(QtAwesomeNamedIcon));
//initialize others code icons maps
addToNamedCodePoints(fa::fa_regular, faRegularFreeIconArray, sizeof(faRegularFreeIconArray) / sizeof(QtAwesomeNamedIcon));
hasInit = success;
return success;
}
/// Add the given array as named codepoints
void QtAwesome::addToNamedCodePoints(int style, const QtAwesomeNamedIcon* QtAwesomeNamedIcons, int size)
{
QHash<QString, int>* namedCodepoints = _namedCodepointsByStyle.value(style, nullptr);
if (namedCodepoints == nullptr) {
namedCodepoints = new QHash<QString, int>();
_namedCodepointsList.append(namedCodepoints);
_namedCodepointsByStyle.insert(style, namedCodepoints);
}
for (int i = 0; i < size; ++i) {
namedCodepoints->insert(QtAwesomeNamedIcons[i].name, QtAwesomeNamedIcons[i].icon);
}
}
const QHash<QString, int> QtAwesome::namedCodePoints(int style) const
{
if (!_namedCodepointsByStyle.contains(style)) return QHash<QString, int>();
return *_namedCodepointsByStyle[style];
}
/// Sets a default option. These options are passed on to the icon painters
void QtAwesome::setDefaultOption(const QString& name, const QVariant& value)
{
_defaultOptions.insert(name, value);
}
/// Returns the default option for the given name
QVariant QtAwesome::defaultOption(const QString& name) const
{
return _defaultOptions.value(name);
}
bool QtAwesome::hasDefaultOption(const QString& name) const
{
return _defaultOptions.contains(name);
}
/// Creates an icon with the given code-point for given style
/// <code>
/// awesome->icon( icon_group )
/// </code>
QIcon QtAwesome::icon(int style, int character, const QVariantMap& options)
{
auto optionMap = options;
optionMap.insert("text", QString(QChar(character)));
optionMap.insert("style", style);
return icon(_fontIconPainter, optionMap);
}
/// Creates an icon with the given name
///
/// You can use the icon names as defined on https://fontawesome.com/cheatsheet/free and
/// https://fontawesome.com/cheatsheet/pro adding the style prefix, e.g. "fa-solid fa-address-book"
/// (The fa- prefix for the icon name is optional)
///
/// @param name the style and name of the icon.
/// @param options extra option to pass to the icon renderer
QIcon QtAwesome::icon(const QString& name, const QVariantMap& options)
{
// Filename
if (name.startsWith(":")) {
auto optionMap = options;
optionMap.insert("filename", name);
return icon(_fontIconPainter, optionMap);
}
// split the string in a style and icon name (and skip the fa- prefix if given)
int spaceIndex = name.indexOf(' ');
int style = fa::fa_solid;
QString iconName;
if (spaceIndex > 0) {
QString styleName = name.left(spaceIndex);
style = stringToStyleEnum(styleName.startsWith("fa-") ? styleName.mid(3) : name);
iconName = name.mid(spaceIndex + 1);
}
else {
iconName = name;
}
if (iconName.startsWith("fa-")) {
iconName = iconName.mid(3);
}
// when it's a named codepoint
if (_namedCodepointsByStyle.contains(style) && _namedCodepointsByStyle[style]->contains(iconName)) {
return icon(style, _namedCodepointsByStyle[style]->value(iconName), options);
}
auto optionMap = options;
optionMap.insert("style", style);
// this method first tries to retrieve the icon via the painter map
QtAwesomeIconPainter* painter = _painterMap.value(name);
if (!painter) return QIcon();
return icon(painter, optionMap);
}
/// Create a dynamic icon by simlpy supplying a painter object
/// The ownership of the painter is NOT transfered.
/// @param painter a dynamic painter that is going to paint the icon
/// @param optionmap the options to pass to the painter
QIcon QtAwesome::icon(QtAwesomeIconPainter* painter, const QVariantMap& optionMap)
{
// Warning, when you use memoryleak detection. You should turn it off for the next call
// QIcon's placed in gui items are often cached and not deleted when my memory-leak detection checks for leaks.
// I'm not sure if it's a Qt bug or something I do wrong
QtAwesomeIconPainterIconEngine* engine = new QtAwesomeIconPainterIconEngine(this, painter, optionMap);
return QIcon(engine);
}
/// Adds a named icon-painter to the QtAwesome icon map
/// As the name applies the ownership is passed over to QtAwesome
///
/// @param name the name of the icon including the style
/// @param painter the icon painter to add for this name
void QtAwesome::give(const QString& name, QtAwesomeIconPainter* painter)
{
delete _painterMap.value(name);// delete the old one
_painterMap.insert(name, painter);
}
/// \brief QtAwesome::font Creates/Gets the icon font with a given size in pixels. This can be usefull to use a label for displaying icons
///
/// \param style Font Awesome style such as fas, fal, fab, fad or far
/// \param size point size of the font
/// \return the corresponding font
/// Example:
///
/// QLabel* label = new QLabel(QChar( icon_group ));
/// label->setFont(awesome->font(style::fas, 16))
QFont QtAwesome::font(int style, int size) const
{
if (!_fontDetails.contains(style)) return QFont();
QFont font(_fontDetails[style].fontFamily());
font.setPixelSize(size);
font.setWeight(_fontDetails[style].fontWeight());
font.setStyleName(_fontDetails[style].fontStyle());
return font;
}
QString QtAwesome::fontName(int style) const
{
if (!_fontDetails.contains(style)) return "";
return _fontDetails[style].fontFamily();
}
int QtAwesome::stringToStyleEnum(const QString style) const
{
if (style == "fa-solid") return fa::fa_solid;
else if (style == "fa-regular")
return fa::fa_regular;
else if (style == "fa-brands")
return fa::fa_brands;
return fa::fa_solid;
}
const QString QtAwesome::styleEnumToString(int style) const
{
switch (style) {
case fa::fa_regular: return "fa-regular";
case fa::fa_solid: return "fa-solid";
case fa::fa_brands: return "fa-brands";
}
return "fa_solid";
}
//---------------------------------------------------------------------------------------
QtAwesomeFontData::QtAwesomeFontData(const QString& fontFileName, QFont::Weight fontWeight, const QString& fontStyle)
: _fontFamily(QString()),
_fontFilename(fontFileName),
_fontId(-1),
_fontWeight(fontWeight),
_fontStyle(fontStyle)
{
}
const QString& QtAwesomeFontData::fontFamily() const
{
return _fontFamily;
}
void QtAwesomeFontData::setFontFamily(const QString& family)
{
_fontFamily = family;
}
const QString& QtAwesomeFontData::fontFilename() const
{
return _fontFilename;
}
int QtAwesomeFontData::fontId() const
{
return _fontId;
}
void QtAwesomeFontData::setFontId(int id)
{
_fontId = id;
}
QFont::Weight QtAwesomeFontData::fontWeight() const
{
return _fontWeight;
}
const QString& QtAwesomeFontData::fontStyle() const {
return _fontStyle;
}
///
/// \brief setFontWeight set the font weight as QFont::weight
/// \param weight the weight value according to QFont::weight enum
/// This enum contains the predefined font weights:
/// \value Thin 0 #same as weight 100
/// \value ExtraLight 12 #same as weight 200
/// \value Light 25 #same as weight 300
/// \value Normal 50 #same as weight 400
/// \value Medium 57 #same as weight 500
/// \value DemiBold 63 #same as weight 600
/// \value Bold 75 #same as weight 700
/// \value ExtraBold 81 #same as weight 800
/// \value Black 87 #same as weight 900
void QtAwesomeFontData::setFontWeight(QFont::Weight weight)
{
_fontWeight = weight;
}
void QtAwesomeFontData::setFontStyle(const QString& style) {
_fontStyle = style;
}
}// namespace fa
|