LeechCraft  0.6.70-6645-gcd10d7e
Modular cross-platform feature rich live environment.
util.cpp
Go to the documentation of this file.
1 /**********************************************************************
2  * LeechCraft - modular cross-platform feature rich internet client.
3  * Copyright (C) 2006-2014 Georg Rudoy
4  *
5  * Boost Software License - Version 1.0 - August 17th, 2003
6  *
7  * Permission is hereby granted, free of charge, to any person or organization
8  * obtaining a copy of the software and accompanying documentation covered by
9  * this license (the "Software") to use, reproduce, display, distribute,
10  * execute, and transmit the Software, and to prepare derivative works of the
11  * Software, and to permit third-parties to whom the Software is furnished to
12  * do so, all subject to the following:
13  *
14  * The copyright notices in the Software and this entire statement, including
15  * the above license grant, this restriction and the following disclaimer,
16  * must be included in all copies of the Software, in whole or in part, and
17  * all derivative works of the Software, unless such copies or derivative
18  * works are solely in the form of machine-executable object code generated by
19  * a source language processor.
20  *
21  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23  * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
24  * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
25  * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
26  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
27  * DEALINGS IN THE SOFTWARE.
28  **********************************************************************/
29 
30 #include "util.h"
31 #include <functional>
32 #include <stdexcept>
33 #include <type_traits>
34 #include <QString>
35 #include <QApplication>
36 #include <QTranslator>
37 #include <QLocale>
38 #include <QFile>
39 #include <QDir>
40 #include <QTime>
41 #include <QSettings>
42 #include <QTextCodec>
43 #include <QUrl>
44 #include <QAction>
45 #include <QBuffer>
46 #include <QPainter>
47 #include <QAction>
48 #include <QtDebug>
49 
50 #if QT_VERSION < 0x050500
52 #endif
53 
54 QString LeechCraft::Util::GetAsBase64Src (const QImage& pix)
55 {
56  QBuffer buf;
57  buf.open (QIODevice::ReadWrite);
58  pix.save (&buf, "PNG", 100);
59  return QString ("data:image/png;base64,%1")
60  .arg (QString (buf.buffer ().toBase64 ()));
61 }
62 
64 {
65  QString string = QObject::tr ("Too long to show");
66  if (p.Additional_.contains ("UserVisibleName") &&
67  p.Additional_ ["UserVisibleName"].canConvert<QString> ())
68  string = p.Additional_ ["UserVisibleName"].toString ();
69  else if (p.Entity_.canConvert<QByteArray> ())
70  {
71  QByteArray entity = p.Entity_.toByteArray ();
72  if (entity.size () < 100)
73  string = QTextCodec::codecForName ("UTF-8")->toUnicode (entity);
74  }
75  else if (p.Entity_.canConvert<QUrl> ())
76  {
77  string = p.Entity_.toUrl ().toString ();
78  if (string.size () > 100)
79  string = string.left (97) + "...";
80  }
81  else
82  string = QObject::tr ("Binary entity");
83 
84  if (!p.Mime_.isEmpty ())
85  string += QObject::tr ("<br /><br />of type <code>%1</code>").arg (p.Mime_);
86 
87  if (!p.Additional_ ["SourceURL"].toUrl ().isEmpty ())
88  {
89  QString urlStr = p.Additional_ ["SourceURL"].toUrl ().toString ();
90  if (urlStr.size () > 63)
91  urlStr = urlStr.left (60) + "...";
92  string += QObject::tr ("<br />from %1")
93  .arg (urlStr);
94  }
95 
96  return string;
97 }
98 
99 namespace
100 {
101  QString MakePrettySizeWith (qint64 sourceSize, const QStringList& units)
102  {
103  int strNum = 0;
104  long double size = sourceSize;
105 
106  for (; strNum < 3 && size >= 1024; ++strNum, size /= 1024)
107  ;
108 
109  return QString::number (size, 'f', 1) + units.value (strNum);
110  }
111 }
112 
113 QString LeechCraft::Util::MakePrettySize (qint64 sourcesize)
114 {
115  static QStringList units
116  {
117  QObject::tr (" b"),
118  QObject::tr (" KiB"),
119  QObject::tr (" MiB"),
120  QObject::tr (" GiB")
121  };
122 
123  return MakePrettySizeWith (sourcesize, units);
124 }
125 
126 QString LeechCraft::Util::MakePrettySizeShort (qint64 sourcesize)
127 {
128  static const QStringList units
129  {
130  QObject::tr ("b", "Short one-character unit for bytes."),
131  QObject::tr ("K", "Short one-character unit for kilobytes."),
132  QObject::tr ("M", "Short one-character unit for megabytes."),
133  QObject::tr ("G", "Short one-character unit for gigabytes.")
134  };
135 
136  return MakePrettySizeWith (sourcesize, units);
137 }
138 
140 {
141  int d = time / 86400;
142  time -= d * 86400;
143  QString result;
144  if (d)
145  result += QObject::tr ("%n day(s), ", "", d);
146  result += QTime (0, 0, 0).addSecs (time).toString ();
147  return result;
148 }
149 
150 QTranslator* LeechCraft::Util::LoadTranslator (const QString& baseName,
151  const QString& localeName,
152  const QString& prefix,
153  const QString& appName)
154 {
155  auto filename = prefix;
156  filename.append ("_");
157  if (!baseName.isEmpty ())
158  filename.append (baseName).append ("_");
159  filename.append (localeName);
160 
161  auto transl = new QTranslator;
162 #ifdef Q_OS_WIN32
163  if (transl->load (filename, ":/") ||
164  transl->load (filename,
165  QCoreApplication::applicationDirPath () + "/translations"))
166 #elif defined (Q_OS_MAC) && !defined (USE_UNIX_LAYOUT)
167  if (transl->load (filename, ":/") ||
168  transl->load (filename,
169  QCoreApplication::applicationDirPath () + "/../Resources/translations"))
170 #elif defined (INSTALL_PREFIX)
171  if (transl->load (filename, ":/") ||
172  transl->load (filename,
173  QString (INSTALL_PREFIX "/share/%1/translations").arg (appName)))
174 #else
175  if (transl->load (filename, ":/") ||
176  transl->load (filename,
177  QString ("/usr/local/share/%1/translations").arg (appName)) ||
178  transl->load (filename,
179  QString ("/usr/share/%1/translations").arg (appName)))
180 #endif
181  return transl;
182 
183  delete transl;
184 
185  return nullptr;
186 }
187 
188 QTranslator* LeechCraft::Util::InstallTranslator (const QString& baseName,
189  const QString& prefix,
190  const QString& appName)
191 {
192  const auto& localeName = GetLocaleName ();
193  if (auto transl = LoadTranslator (baseName, localeName, prefix, appName))
194  {
195  qApp->installTranslator (transl);
196  return transl;
197  }
198 
199  qWarning () << Q_FUNC_INFO
200  << "could not load translation file for locale"
201  << localeName
202  << baseName
203  << prefix
204  << appName;
205  return nullptr;
206 }
207 
209 {
210  QSettings settings (QCoreApplication::organizationName (),
211  QCoreApplication::applicationName ());
212  QString localeName = settings.value ("Language", "system").toString ();
213 
214  if (localeName == "system")
215  {
216  localeName = QString (::getenv ("LANG")).left (5);
217 
218  if (localeName == "C" || localeName.isEmpty ())
219  localeName = "en_US";
220 
221  if (localeName.isEmpty () || localeName.size () != 5)
222  localeName = QLocale::system ().name ();
223  localeName = localeName.left (5);
224  }
225 
226  if (localeName.size () == 2)
227  {
228  auto lang = QLocale (localeName).language ();
229  const auto& cs = QLocale::countriesForLanguage (lang);
230  if (cs.isEmpty ())
231  localeName += "_00";
232  else
233  localeName = QLocale (lang, cs.at (0)).name ();
234  }
235 
236  return localeName;
237 }
238 
239 QString LeechCraft::Util::GetInternetLocaleName (const QLocale& locale)
240 {
241  if (locale.language () == QLocale::AnyLanguage)
242  return "*";
243 
244  auto locStr = locale.name ();
245  locStr.replace ('_', '-');
246  return locStr;
247 }
248 
250 {
251  return GetLocaleName ().left (2);
252 }
253 
254 QModelIndexList LeechCraft::Util::GetSummarySelectedRows (QObject *sender)
255 {
256  QAction *senderAct = qobject_cast<QAction*> (sender);
257  if (!senderAct)
258  {
259  QString debugString;
260  {
261  QDebug d (&debugString);
262  d << "sender is not a QAction*"
263  << sender;
264  }
265  throw std::runtime_error (qPrintable (debugString));
266  }
267 
268  return senderAct->
269  property ("SelectedRows").value<QList<QModelIndex>> ();
270 }
271 
272 QAction* LeechCraft::Util::CreateSeparator (QObject *parent)
273 {
274  QAction *result = new QAction (parent);
275  result->setSeparator (true);
276  return result;
277 }
278 
280  const QString& text, QFont font, const QPen& pen, const QBrush& brush)
281 {
282  const auto& iconSize = px.size ();
283 
284  const auto fontHeight = px.height () * 0.45;
285  font.setPixelSize (std::max (6., fontHeight));
286 
287  const QFontMetrics fm (font);
288  const auto width = fm.width (text) + 2. * px.width () / 10.;
289  const auto height = fm.height () + 2. * px.height () / 10.;
290  const bool tooSmall = width > iconSize.width ();
291 
292  const QRect textRect (iconSize.width () - width, iconSize.height () - height, width, height);
293 
294  QPainter p (&px);
295  p.setBrush (brush);
296  p.setFont (font);
297  p.setPen (pen);
298  p.setRenderHint (QPainter::Antialiasing);
299  p.setRenderHint (QPainter::TextAntialiasing);
300  p.setRenderHint (QPainter::HighQualityAntialiasing);
301  p.drawRoundedRect (textRect, 4, 4);
302  p.drawText (textRect,
303  Qt::AlignCenter,
304  tooSmall ? "#" : text);
305  p.end ();
306 
307  return px;
308 }
Q_DECLARE_METATYPE(QList< QModelIndex >)
UTIL_API QString MakePrettySize(qint64 sourceSize)
Makes a formatted size from number.
Definition: util.cpp:113
UTIL_API QTranslator * LoadTranslator(const QString &base, const QString &locale, const QString &prefix="leechcraft", const QString &appname="leechcraft")
Definition: util.cpp:150
UTIL_API QString MakePrettySizeShort(qint64 size)
Converts a bytes count to a string representation with appropriately chosen units.
Definition: util.cpp:126
UTIL_API QString GetLocaleName()
Returns the current locale name, like en_US.
Definition: util.cpp:208
UTIL_API QString MakeTimeFromLong(ulong time)
Makes a formatted time from number.
Definition: util.cpp:139
UTIL_API QString GetLanguage()
Returns the current language name.
Definition: util.cpp:249
UTIL_API QString GetInternetLocaleName(const QLocale &)
Definition: util.cpp:239
UTIL_API QTranslator * InstallTranslator(const QString &base, const QString &prefix="leechcraft", const QString &appname="leechcraft")
Loads and installs a translator.
Definition: util.cpp:188
UTIL_API QAction * CreateSeparator(QObject *parent)
Returns the action that is set to act as a separator.
Definition: util.cpp:272
UTIL_API QString GetUserText(const Entity &entity)
Return the user-readable representation of the entity.
Definition: util.cpp:63
UTIL_API QPixmap DrawOverlayText(QPixmap px, const QString &text, QFont font, const QPen &pen, const QBrush &brush)
Definition: util.cpp:279
UTIL_API QString GetAsBase64Src(const QImage &image)
Returns the given image in a Base64-encoded form.
Definition: util.cpp:54
UTIL_API QModelIndexList GetSummarySelectedRows(QObject *sender)
Definition: util.cpp:254
QMap< QString, QVariant > Additional_
Additional parameters.
Definition: structures.h:223
QString Mime_
MIME type of the entity.
Definition: structures.h:207
QVariant Entity_
The entity that this object represents.
Definition: structures.h:171
Describes parameters of an entity.
Definition: structures.h:154