aboutsummaryrefslogtreecommitdiff
path: root/libs/installer_fomod/src/scalelabel.cpp
blob: e654bf52fef75d401dca66eaaa31e029ee01b295 (plain)
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
#include "scalelabel.h"

#include <QResizeEvent>

static bool isResourceMovie(const QString& path)
{
  for (QByteArray format : QMovie::supportedFormats()) {
    QString fileExtension = "." + QString::fromUtf8(format);
    if (path.endsWith(fileExtension)) {
      return true;
    }
  }

  return false;
}

ScaleLabel::ScaleLabel(QWidget* parent) : QLabel(parent) {}

void ScaleLabel::setScalableResource(const QString& path)
{
  if (auto m = movie()) {
    setMovie(nullptr);
    delete m;
    m_OriginalMovieSize = QSize();
  }
  if (!pixmap().isNull()) {
    setPixmap(QPixmap());
    m_UnscaledImage = QImage();
  }

  if (path.isEmpty()) {
    return;
  }

  if (isResourceMovie(path)) {
    setScalableMovie(path);
  } else {
    setScalableImage(path);
  }
}

void ScaleLabel::setStatic(bool isStatic)
{
  m_isStatic = isStatic;

  if (auto m = movie()) {
    if (isStatic) {
      m->stop();
    } else {
      m->start();
    }
  }
}

void ScaleLabel::setScalableMovie(const QString& path)
{
  QMovie* m = new QMovie(path);
  if (!m->isValid()) {
    qWarning(">%s< is an invalid movie. Reason: %s", qUtf8Printable(path),
             m->lastErrorString().toStdString().c_str());
    delete m;
    return;
  }

  m->setParent(this);
  setMovie(m);
  m->start();
  m->stop();
  m_OriginalMovieSize = m->currentImage().size();

  m->setScaledSize(m_OriginalMovieSize.scaled(size(), Qt::KeepAspectRatio));
  if (!m_isStatic) {
    m->start();
  }
}

void ScaleLabel::setScalableImage(const QString& path)
{
  QImage image(path);
  if (image.isNull()) {
    qWarning(">%s< is a null image", qUtf8Printable(path));
  } else {
    m_UnscaledImage = image;
    setPixmap(QPixmap::fromImage(image).scaled(size(), Qt::KeepAspectRatio));
  }
}

void ScaleLabel::resizeEvent(QResizeEvent* event)
{
  if (auto m = movie()) {
    m->stop();
    m->setScaledSize(m_OriginalMovieSize.scaled(event->size(), Qt::KeepAspectRatio));
    m->start();

    // We can't just skip the start() above since that is what triggers the label to
    // resize the movie The only way to resize the movie but keep it paused is to start
    // and then re-stop it
    if (m_isStatic) {
      m->stop();
    }
  }
  auto p = pixmap();
  if (!p.isNull()) {
    setPixmap(
        QPixmap::fromImage(m_UnscaledImage).scaled(event->size(), Qt::KeepAspectRatio));
  }
}