Debian Codegraph @

src/Gui/BitmapFactory.cpp

raw
1 /***************************************************************************
2 * Copyright (c) 2004 Jürgen Riegel <[email protected]> *
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 <QApplication>
24 #include <QBitmap>
25 #include <QDir>
26 #include <QFile>
27 #include <QFileInfo>
28 #include <QMap>
29 #include <QImageReader>
30 #include <QPainter>
31 #include <QPalette>
32 #include <QScreen>
33 #include <QString>
34 #include <QSvgRenderer>
35 #include <QStyleOption>
36
37 #include <string>
38 #include <Inventor/fields/SoSFImage.h>
39
40 #include <App/Application.h>
41 #include <Base/Console.h>
42 #include <Base/ConsoleObserver.h>
43
44 #include "BitmapFactory.h"
45
46 using namespace Gui;
47
48 namespace Gui
49 {
50 class BitmapFactoryInstP
51 {
52 public:
53 QMap<std::string, QPixmap> xpmCache;
54
55 bool useIconTheme;
56 };
57 } // namespace Gui
58
59 BitmapFactoryInst* BitmapFactoryInst::_pcSingleton = nullptr;
60
61 BitmapFactoryInst& BitmapFactoryInst::instance()
62 {
63 if (!_pcSingleton) {
64 _pcSingleton = new BitmapFactoryInst;
65 std::map<std::string, std::string>::const_iterator it;
66 it = App::GetApplication().Config().find("ProgramIcons");
67 if (it != App::GetApplication().Config().end()) {
68 QString home = QString::fromStdString(App::Application::getHomePath());
69 QString path = QString::fromUtf8(it->second.c_str());
70 if (QDir(path).isRelative()) {
71 path = QFileInfo(QDir(home), path).absoluteFilePath();
72 }
73 _pcSingleton->addPath(path);
74 }
75 _pcSingleton->addPath(
76 QStringLiteral("%1/icons").arg(QString::fromStdString(App::Application::getHomePath()))
77 );
78 _pcSingleton->addPath(
79 QStringLiteral("%1/icons").arg(QString::fromStdString(App::Application::getUserAppDataDir()))
80 );
81 _pcSingleton->addPath(QLatin1String(":/icons/"));
82 _pcSingleton->addPath(QLatin1String(":/Icons/"));
83 }
84
85 return *_pcSingleton;
86 }
87
88 void BitmapFactoryInst::destruct()
89 {
90 if (_pcSingleton) {
91 delete _pcSingleton;
92 }
93 _pcSingleton = nullptr;
94 }
95
96 BitmapFactoryInst::BitmapFactoryInst()
97 {
98 d = new BitmapFactoryInstP;
99
100 restoreCustomPaths();
101 configureUseIconTheme();
102 }
103
104 BitmapFactoryInst::~BitmapFactoryInst()
105 {
106 delete d;
107 }
108
109 void BitmapFactoryInst::restoreCustomPaths()
110 {
111 Base::Reference<ParameterGrp> group = App::GetApplication().GetParameterGroupByPath(
112 "User parameter:BaseApp/Preferences/Bitmaps"
113 );
114 std::vector<std::string> paths = group->GetASCIIs("CustomPath");
115 for (auto& path : paths) {
116 addPath(QString::fromUtf8(path.c_str()));
117 }
118 }
119
120 void Gui::BitmapFactoryInst::configureUseIconTheme()
121 {
122 Base::Reference<ParameterGrp> group = App::GetApplication().GetParameterGroupByPath(
123 "User parameter:BaseApp/Preferences/Bitmaps/Theme"
124 );
125
126 d->useIconTheme = group->GetBool("UseIconTheme", group->GetBool("ThemeSearchPaths", false));
127 }
128
129 void BitmapFactoryInst::addPath(const QString& path)
130 {
131 QDir::addSearchPath(QStringLiteral("icons"), path);
132 }
133
134 void BitmapFactoryInst::removePath(const QString& path)
135 {
136 QStringList iconPaths = QDir::searchPaths(QStringLiteral("icons"));
137 int pos = iconPaths.indexOf(path);
138 if (pos != -1) {
139 iconPaths.removeAt(pos);
140 QDir::setSearchPaths(QStringLiteral("icons"), iconPaths);
141 }
142 }
143
144 QStringList BitmapFactoryInst::getPaths() const
145 {
146 return QDir::searchPaths(QStringLiteral("icons"));
147 }
148
149 QStringList BitmapFactoryInst::findIconFiles() const
150 {
151 QStringList files, filters;
152 QList<QByteArray> formats = QImageReader::supportedImageFormats();
153 for (QList<QByteArray>::iterator it = formats.begin(); it != formats.end(); ++it) {
154 filters << QStringLiteral("*.%1").arg(QString::fromLatin1(*it).toLower());
155 }
156
157 QStringList paths = QDir::searchPaths(QStringLiteral("icons"));
158 paths.removeDuplicates();
159 for (QStringList::Iterator pt = paths.begin(); pt != paths.end(); ++pt) {
160 QDir d(*pt);
161 d.setNameFilters(filters);
162 QFileInfoList fi = d.entryInfoList();
163 for (QFileInfoList::iterator it = fi.begin(); it != fi.end(); ++it) {
164 files << it->absoluteFilePath();
165 }
166 }
167
168 files.removeDuplicates();
169 return files;
170 }
171
172 void BitmapFactoryInst::addPixmapToCache(const char* name, const QPixmap& icon)
173 {
174 d->xpmCache[name] = icon;
175 }
176
177 bool BitmapFactoryInst::findPixmapInCache(const char* name, QPixmap& px) const
178 {
179 QMap<std::string, QPixmap>::Iterator it = d->xpmCache.find(name);
180 if (it != d->xpmCache.end()) {
181 px = it.value();
182 return true;
183 }
184 return false;
185 }
186
187 QIcon BitmapFactoryInst::iconFromTheme(const char* name, const QIcon& fallback)
188 {
189 if (!d->useIconTheme) {
190 return iconFromDefaultTheme(name, fallback);
191 }
192
193 QString iconName = QString::fromUtf8(name);
194 QIcon icon = QIcon::fromTheme(iconName, fallback);
195 if (icon.isNull()) {
196 QPixmap px = pixmap(name);
197 if (!px.isNull()) {
198 icon.addPixmap(px);
199 }
200 }
201
202 return icon;
203 }
204
205 bool BitmapFactoryInst::loadPixmap(const QString& filename, QPixmap& icon) const
206 {
207 QFileInfo fi(filename);
208 if (fi.exists()) {
209 // first check if it's an SVG because Qt's qsvg4 module shouldn't be used therefore
210 if (fi.suffix().toLower() == QLatin1String("svg")) {
211 QFile svgFile(fi.filePath());
212 if (svgFile.open(QFile::ReadOnly | QFile::Text)) {
213 QByteArray content = svgFile.readAll();
214 icon = pixmapFromSvg(content, QSize(64, 64));
215 }
216 }
217 else {
218 // try with Qt plugins
219 icon.load(fi.filePath());
220 }
221 }
222
223 return !icon.isNull();
224 }
225
226 QIcon Gui::BitmapFactoryInst::iconFromDefaultTheme(const char* name, const QIcon& fallback)
227 {
228 QIcon icon;
229 QPixmap px = pixmap(name);
230
231 if (!px.isNull()) {
232 icon.addPixmap(px);
233 return icon;
234 }
235 else {
236 return fallback;
237 }
238
239 return icon;
240 }
241
242 QPixmap BitmapFactoryInst::pixmap(const char* name) const
243 {
244 if (!name || *name == '\0') {
245 return {};
246 }
247
248 // as very first test check whether the pixmap is in the cache
249 QMap<std::string, QPixmap>::Iterator it = d->xpmCache.find(name);
250 if (it != d->xpmCache.end()) {
251 return it.value();
252 }
253
254 QPixmap icon;
255
256 // Try whether an absolute path is given
257 QString fn = QString::fromUtf8(name);
258 loadPixmap(fn, icon);
259
260 // try to find it in the 'icons' search paths
261 if (icon.isNull()) {
262 QList<QByteArray> formats = QImageReader::supportedImageFormats();
263 formats.prepend("SVG"); // check first for SVG to use special import mechanism
264
265 QString fileName = QStringLiteral("icons:") + fn;
266 if (!loadPixmap(fileName, icon)) {
267 // Go through supported file formats
268 for (QList<QByteArray>::iterator fm = formats.begin(); fm != formats.end(); ++fm) {
269 QString path = QStringLiteral("%1.%2").arg(
270 fileName,
271 QString::fromLatin1((*fm).toLower().constData())
272 );
273 if (loadPixmap(path, icon)) {
274 break;
275 }
276 }
277 }
278 }
279
280 if (!icon.isNull()) {
281 d->xpmCache[name] = icon;
282 return icon;
283 }
284
285 Base::Console().warning("Cannot find icon: %s\n", name);
286 return QPixmap(Gui::BitmapFactory().pixmapFromSvg("help-browser", QSize(16, 16)));
287 }
288
289 QPixmap BitmapFactoryInst::pixmapFromSvg(
290 const char* name,
291 const QSizeF& size,
292 const ColorMap& colorMapping
293 ) const
294 {
295 static qreal dpr = getMaximumDPR();
296
297 // If an absolute path is given
298 QPixmap icon;
299 QString iconPath;
300 QString fn = QString::fromUtf8(name);
301 if (QFile(fn).exists()) {
302 iconPath = fn;
303 }
304
305 // try to find it in the 'icons' search paths
306 if (iconPath.isEmpty()) {
307 QString fileName = QStringLiteral("icons:") + fn;
308 QFileInfo fi(fileName);
309 if (fi.exists()) {
310 iconPath = fi.filePath();
311 }
312 else {
313 fileName += QLatin1String(".svg");
314 fi.setFile(fileName);
315 if (fi.exists()) {
316 iconPath = fi.filePath();
317 }
318 }
319 }
320
321 if (!iconPath.isEmpty()) {
322 QFile file(iconPath);
323 if (file.open(QFile::ReadOnly | QFile::Text)) {
324 QByteArray content = file.readAll();
325 icon = pixmapFromSvg(content, size * dpr, colorMapping);
326 }
327 }
328
329 if (!icon.isNull()) {
330 icon.setDevicePixelRatio(dpr);
331 }
332
333 return icon;
334 }
335
336 QPixmap BitmapFactoryInst::pixmapFromSvg(
337 const QByteArray& originalContents,
338 const QSizeF& size,
339 const ColorMap& colorMapping
340 ) const
341 {
342 QString stringContents = QString::fromUtf8(originalContents);
343 for (const auto& colorToColor : colorMapping) {
344 ulong fromColor = colorToColor.first;
345 ulong toColor = colorToColor.second;
346 QString fromColorString = QStringLiteral("#%1").arg(fromColor, 6, 16, QChar::fromLatin1('0'));
347 QString toColorString = QStringLiteral("#%1").arg(toColor, 6, 16, QChar::fromLatin1('0'));
348 stringContents = stringContents.replace(fromColorString, toColorString);
349 }
350 QByteArray contents = stringContents.toUtf8();
351
352 QImage image(size.toSize(), QImage::Format_ARGB32_Premultiplied);
353 image.fill(0x00000000);
354
355 QPainter p(&image);
356 QSvgRenderer svg;
357 {
358 // tmp. disable the report window to suppress some bothering warnings
359 const Base::ILoggerBlocker blocker("ReportOutput", Base::ConsoleSingleton::MsgType_Wrn);
360 svg.load(contents);
361 }
362 svg.render(&p);
363 p.end();
364
365 return QPixmap::fromImage(image);
366 }
367
368 QStringList BitmapFactoryInst::pixmapNames() const
369 {
370 QStringList names;
371 for (QMap<std::string, QPixmap>::Iterator It = d->xpmCache.begin(); It != d->xpmCache.end();
372 ++It) {
373 QString item = QString::fromUtf8(It.key().c_str());
374 if (!names.contains(item)) {
375 names << item;
376 }
377 }
378 return names;
379 }
380
381 QPixmap BitmapFactoryInst::resize(int w, int h, const QPixmap& p, Qt::BGMode bgmode) const
382 {
383 if (bgmode == Qt::TransparentMode) {
384 if (p.width() == 0 || p.height() == 0) {
385 w = 1;
386 }
387
388 QPixmap pix = p;
389 int x = pix.width() > w ? 0 : (w - pix.width()) / 2;
390 int y = pix.height() > h ? 0 : (h - pix.height()) / 2;
391
392 if (x == 0 && y == 0) {
393 return pix;
394 }
395
396 QPixmap pm(w, h);
397 QBitmap mask(w, h);
398 mask.fill(Qt::color0);
399
400 QBitmap bm = pix.mask();
401 if (!bm.isNull()) {
402 QPainter painter(&mask);
403 painter.drawPixmap(QPoint(x, y), bm, QRect(0, 0, pix.width(), pix.height()));
404 pm.setMask(mask);
405 }
406 else {
407 pm.setMask(mask);
408 pm = fillRect(x, y, pix.width(), pix.height(), pm, Qt::OpaqueMode);
409 }
410
411 QPainter pt;
412 pt.begin(&pm);
413 pt.drawPixmap(x, y, pix);
414 pt.end();
415 return pm;
416 }
417 else { // Qt::OpaqueMode
418 QPixmap pix = p;
419
420 if (pix.width() == 0 || pix.height() == 0) {
421 return pix; // do not resize a null pixmap
422 }
423
424 QPalette pal = qApp->palette();
425 QColor dl = pal.color(QPalette::Disabled, QPalette::Light);
426 QColor dt = pal.color(QPalette::Disabled, QPalette::Text);
427
428 QPixmap pm(w, h);
429 pm.fill(dl);
430
431 QPainter pt;
432 pt.begin(&pm);
433 pt.setPen(dl);
434 pt.drawPixmap(1, 1, pix);
435 pt.setPen(dt);
436 pt.drawPixmap(0, 0, pix);
437 pt.end();
438 return pm;
439 }
440 }
441
442 QPixmap BitmapFactoryInst::fillRect(int x, int y, int w, int h, const QPixmap& p, Qt::BGMode bgmode) const
443 {
444 QBitmap b = p.mask();
445 if (b.isNull()) {
446 return p; // sorry, but cannot do anything
447 }
448
449 QPixmap pix = p;
450
451 // modify the mask
452 QPainter pt;
453 pt.begin(&b);
454 if (bgmode == Qt::OpaqueMode) {
455 pt.fillRect(x, y, w, h, Qt::color1); // make opaque
456 }
457 else { // Qt::TransparentMode
458 pt.fillRect(x, y, w, h, Qt::color0); // make transparent
459 }
460 pt.end();
461
462 pix.setMask(b);
463
464 return pix;
465 }
466
467 QPixmap BitmapFactoryInst::merge(const QPixmap& p1, const QPixmap& p2, bool vertical) const
468 {
469 int width = 0;
470 int height = 0;
471
472 int x = 0;
473 int y = 0;
474
475 // get the size for the new pixmap
476 if (vertical) {
477 y = p1.height();
478 width = qMax(p1.width(), p2.width());
479 height = p1.height() + p2.height();
480 }
481 else {
482 x = p1.width();
483 width = p1.width() + p2.width();
484 height = qMax(p1.height(), p2.height());
485 }
486
487 QPixmap res(width, height);
488 QBitmap mask(width, height);
489 QBitmap mask1 = p1.mask();
490 QBitmap mask2 = p2.mask();
491 mask.fill(Qt::color0);
492
493 auto* pt1 = new QPainter(&res);
494 pt1->drawPixmap(0, 0, p1);
495 pt1->drawPixmap(x, y, p2);
496 delete pt1;
497
498 auto* pt2 = new QPainter(&mask);
499 pt2->drawPixmap(0, 0, mask1);
500 pt2->drawPixmap(x, y, mask2);
501 delete pt2;
502
503 res.setMask(mask);
504 return res;
505 }
506
507 QPixmap BitmapFactoryInst::merge(const QPixmap& p1, const QPixmap& p2, Position pos) const
508 {
509 // does the similar as the method above except that this method does not resize the resulting pixmap
510 int x = 0, y = 0;
511 qreal dpr1 = p1.devicePixelRatio();
512 qreal dpr2 = p2.devicePixelRatio();
513
514 switch (pos) {
515 case TopLeft:
516 break;
517 case TopRight:
518 x = p1.width() / dpr1 - p2.width() / dpr2;
519 break;
520 case BottomLeft:
521 y = p1.height() / dpr1 - p2.height() / dpr2;
522 break;
523 case BottomRight:
524 x = p1.width() / dpr1 - p2.width() / dpr2;
525 y = p1.height() / dpr1 - p2.height() / dpr2;
526 break;
527 }
528
529 QPixmap p = p1;
530 p = fillRect(x, y, p2.width(), p2.height(), p, Qt::OpaqueMode);
531
532 QPainter pt;
533 pt.begin(&p);
534 pt.setPen(Qt::NoPen);
535 pt.drawRect(x, y, p2.width(), p2.height());
536 pt.drawPixmap(x, y, p2);
537 pt.end();
538
539 return p;
540 }
541
542 QPixmap BitmapFactoryInst::disabled(const QPixmap& p) const
543 {
544 QStyleOption opt;
545 opt.palette = QApplication::palette();
546 return QApplication::style()->generatedIconPixmap(QIcon::Disabled, p, &opt);
547 }
548
549 QPixmap BitmapFactoryInst::empty(QSize size) const
550 {
551 qreal dpr = getMaximumDPR();
552
553 QPixmap res(size * dpr);
554 res.fill(Qt::transparent);
555 res.setDevicePixelRatio(dpr);
556
557 return res;
558 }
559
560 void BitmapFactoryInst::convert(const QImage& p, SoSFImage& img) const
561 {
562 SbVec2s size;
563 size[0] = p.width();
564 size[1] = p.height();
565
566 int buffersize = static_cast<int>(p.sizeInBytes());
567
568 int numcomponents = 0;
569 QVector<QRgb> table = p.colorTable();
570 if (!table.isEmpty()) {
571 if (p.hasAlphaChannel()) {
572 if (p.allGray()) {
573 numcomponents = 2;
574 }
575 else {
576 numcomponents = 4;
577 }
578 }
579 else {
580 if (p.allGray()) {
581 numcomponents = 1;
582 }
583 else {
584 numcomponents = 3;
585 }
586 }
587 }
588 else {
589 numcomponents = buffersize / (size[0] * size[1]);
590 }
591
592 int depth = numcomponents;
593
594 // Coin3D only supports up to 32-bit images
595 if (numcomponents == 8) {
596 numcomponents = 4;
597 }
598
599 // allocate image data
600 img.setValue(size, numcomponents, nullptr);
601
602 unsigned char* bytes = img.startEditing(size, numcomponents);
603
604 int width = (int)size[0];
605 int height = (int)size[1];
606
607 for (int y = 0; y < height; y++) {
608 unsigned char* line = &bytes[width * numcomponents * (height - (y + 1))];
609 for (int x = 0; x < width; x++) {
610 QColor col = p.pixelColor(x, y);
611 switch (depth) {
612 default:
613 break;
614 case 1: {
615 QRgb rgb = col.rgb();
616 line[0] = qGray(rgb);
617 } break;
618 case 2: {
619 QRgb rgb = col.rgba();
620 line[0] = qGray(rgb);
621 line[1] = qAlpha(rgb);
622 } break;
623 case 3: {
624 QRgb rgb = col.rgb();
625 line[0] = qRed(rgb);
626 line[1] = qGreen(rgb);
627 line[2] = qBlue(rgb);
628 } break;
629 case 4: {
630 QRgb rgb = col.rgba();
631 line[0] = qRed(rgb);
632 line[1] = qGreen(rgb);
633 line[2] = qBlue(rgb);
634 line[3] = qAlpha(rgb);
635 } break;
636 case 8: {
637 QRgba64 rgb = col.rgba64();
638 line[0] = qRed(rgb);
639 line[1] = qGreen(rgb);
640 line[2] = qBlue(rgb);
641 line[3] = qAlpha(rgb);
642 } break;
643 }
644
645 line += numcomponents;
646 }
647 }
648
649 img.finishEditing();
650 }
651
652 void BitmapFactoryInst::convert(const SoSFImage& p, QImage& img) const
653 {
654 SbVec2s size;
655 int numcomponents;
656
657 const unsigned char* bytes = p.getValue(size, numcomponents);
658 if (!bytes) {
659 return;
660 }
661
662 int width = (int)size[0];
663 int height = (int)size[1];
664
665 img = QImage(width, height, QImage::Format_RGB32);
666 QRgb* bits = (QRgb*)img.bits();
667
668 for (int y = 0; y < height; y++) {
669 const unsigned char* line = &bytes[width * numcomponents * (height - (y + 1))];
670 for (int x = 0; x < width; x++) {
671 switch (numcomponents) {
672 default:
673 case 1:
674 *bits++ = qRgb(line[0], line[0], line[0]);
675 break;
676 case 2:
677 *bits++ = qRgba(line[0], line[0], line[0], line[1]);
678 break;
679 case 3:
680 *bits++ = qRgb(line[0], line[1], line[2]);
681 break;
682 case 4:
683 *bits++ = qRgba(line[0], line[1], line[2], line[3]);
684 break;
685 }
686
687 line += numcomponents;
688 }
689 }
690 }
691
692 QIcon BitmapFactoryInst::mergePixmap(
693 const QIcon& base,
694 const QPixmap& px,
695 Gui::BitmapFactoryInst::Position position
696 )
697 {
698 QIcon overlayedIcon;
699
700 int w = QApplication::style()->pixelMetric(QStyle::PM_ListViewIconSize);
701
702 overlayedIcon.addPixmap(
703 Gui::BitmapFactory().merge(base.pixmap(w, w, QIcon::Normal, QIcon::Off), px, position),
704 QIcon::Normal,
705 QIcon::Off
706 );
707
708 overlayedIcon.addPixmap(
709 Gui::BitmapFactory().merge(base.pixmap(w, w, QIcon::Normal, QIcon::On), px, position),
710 QIcon::Normal,
711 QIcon::Off
712 );
713
714 return overlayedIcon;
715 }
716
717 qreal BitmapFactoryInst::getMaximumDPR()
718 {
719 qreal dpr = 1.0F;
720
721 for (QScreen* screen : QGuiApplication::screens()) {
722 dpr = std::max(screen->devicePixelRatio(), dpr);
723 }
724
725 return dpr;
726 }