KIO

global.cpp
1 /*
2  This file is part of the KDE libraries
3  SPDX-FileCopyrightText: 2000 David Faure <[email protected]>
4 
5  SPDX-License-Identifier: LGPL-2.0-only
6 */
7 
8 #include "global.h"
9 #include "kioglobal_p.h"
10 #include "faviconscache_p.h"
11 
12 #include <kprotocolinfo.h>
13 #include <KConfig>
14 #include <KConfigGroup>
15 #include <kfileitem.h>
16 #include <KLocalizedString>
17 #include <KSharedConfig>
18 #include <KFormat>
19 #include <KFileUtils>
20 #include <QMimeDatabase>
21 #include <QUrl>
22 
23 #include "kiocoredebug.h"
24 
25 KFormat::BinaryUnitDialect _k_loadBinaryDialect();
26 Q_GLOBAL_STATIC_WITH_ARGS(KFormat::BinaryUnitDialect, _k_defaultBinaryDialect, (_k_loadBinaryDialect()))
27 
28 KFormat::BinaryUnitDialect _k_loadBinaryDialect()
29 {
30  KConfigGroup mainGroup(KSharedConfig::openConfig(), "Locale");
31 
32  KFormat::BinaryUnitDialect dialect(KFormat::BinaryUnitDialect(mainGroup.readEntry("BinaryUnitDialect", int(KFormat::DefaultBinaryDialect))));
33  dialect = static_cast<KFormat::BinaryUnitDialect>(mainGroup.readEntry("BinaryUnitDialect", int(dialect)));
34 
35  // Error checking
36  if (dialect <= KFormat::DefaultBinaryDialect || dialect > KFormat::LastBinaryDialect) {
37  dialect = KFormat::IECBinaryDialect;
38  }
39 
40  return dialect;
41 }
42 
43 KIOCORE_EXPORT QString KIO::convertSize(KIO::filesize_t fileSize)
44 {
45  const KFormat::BinaryUnitDialect dialect = *_k_defaultBinaryDialect();
46 
47  return KFormat().formatByteSize(fileSize, 1, dialect);
48 }
49 
51 {
52  return convertSize(kibSize * 1024);
53 }
54 
55 KIOCORE_EXPORT QString KIO::number(KIO::filesize_t size)
56 {
57  char charbuf[256];
58  sprintf(charbuf, "%lld", size);
59  return QLatin1String(charbuf);
60 }
61 
62 KIOCORE_EXPORT unsigned int KIO::calculateRemainingSeconds(KIO::filesize_t totalSize,
63  KIO::filesize_t processedSize, KIO::filesize_t speed)
64 {
65  if ((speed != 0) && (totalSize != 0)) {
66  return (totalSize - processedSize) / speed;
67  } else {
68  return 0;
69  }
70 }
71 
72 KIOCORE_EXPORT QString KIO::convertSeconds(unsigned int seconds)
73 {
74  unsigned int days = seconds / 86400;
75  unsigned int hours = (seconds - (days * 86400)) / 3600;
76  unsigned int mins = (seconds - (days * 86400) - (hours * 3600)) / 60;
77  seconds = (seconds - (days * 86400) - (hours * 3600) - (mins * 60));
78 
79  const QTime time(hours, mins, seconds);
80  const QString timeStr(time.toString(QStringLiteral("hh:mm:ss")));
81  if (days > 0) {
82  return i18np("1 day %2", "%1 days %2", days, timeStr);
83  } else {
84  return timeStr;
85  }
86 }
87 
88 #if KIOCORE_BUILD_DEPRECATED_SINCE(3, 4)
89 KIOCORE_EXPORT QTime KIO::calculateRemaining(KIO::filesize_t totalSize, KIO::filesize_t processedSize, KIO::filesize_t speed)
90 {
91  QTime remainingTime;
92 
93  if (speed != 0) {
94  KIO::filesize_t secs;
95  if (totalSize == 0) {
96  secs = 0;
97  } else {
98  secs = (totalSize - processedSize) / speed;
99  }
100  if (secs >= (24 * 60 * 60)) { // Limit to 23:59:59
101  secs = (24 * 60 * 60) - 1;
102  }
103  int hr = secs / (60 * 60);
104  int mn = (secs - hr * 60 * 60) / 60;
105  int sc = (secs - hr * 60 * 60 - mn * 60);
106 
107  remainingTime.setHMS(hr, mn, sc);
108  }
109 
110  return remainingTime;
111 }
112 #endif
113 
114 KIOCORE_EXPORT QString KIO::itemsSummaryString(uint items, uint files, uint dirs, KIO::filesize_t size, bool showSize)
115 {
116  if (files == 0 && dirs == 0 && items == 0) {
117  return i18np("%1 Item", "%1 Items", 0);
118  }
119 
120  QString summary;
121  const QString foldersText = i18np("1 Folder", "%1 Folders", dirs);
122  const QString filesText = i18np("1 File", "%1 Files", files);
123  if (files > 0 && dirs > 0) {
124  summary = showSize ?
125  i18nc("folders, files (size)", "%1, %2 (%3)", foldersText, filesText, KIO::convertSize(size)) :
126  i18nc("folders, files", "%1, %2", foldersText, filesText);
127  } else if (files > 0) {
128  summary = showSize ? i18nc("files (size)", "%1 (%2)", filesText, KIO::convertSize(size)) : filesText;
129  } else if (dirs > 0) {
130  summary = foldersText;
131  }
132 
133  if (items > dirs + files) {
134  const QString itemsText = i18np("%1 Item", "%1 Items", items);
135  summary = summary.isEmpty() ? itemsText : i18nc("items: folders, files (size)", "%1: %2", itemsText, summary);
136  }
137 
138  return summary;
139 }
140 
141 KIOCORE_EXPORT QString KIO::encodeFileName(const QString &_str)
142 {
143  QString str(_str);
144  str.replace(QLatin1Char('/'), QChar(0x2044)); // "Fraction slash"
145  return str;
146 }
147 
148 KIOCORE_EXPORT QString KIO::decodeFileName(const QString &_str)
149 {
150  // Nothing to decode. "Fraction slash" is fine in filenames.
151  return _str;
152 }
153 
154 /***************************************************************
155  *
156  * Utility functions
157  *
158  ***************************************************************/
159 
161 {
162  QString tmp = cacheControl.toLower();
163 
164  if (tmp == QLatin1String("cacheonly")) {
165  return KIO::CC_CacheOnly;
166  }
167  if (tmp == QLatin1String("cache")) {
168  return KIO::CC_Cache;
169  }
170  if (tmp == QLatin1String("verify")) {
171  return KIO::CC_Verify;
172  }
173  if (tmp == QLatin1String("refresh")) {
174  return KIO::CC_Refresh;
175  }
176  if (tmp == QLatin1String("reload")) {
177  return KIO::CC_Reload;
178  }
179 
180  qCDebug(KIO_CORE) << "unrecognized Cache control option:" << cacheControl;
181  return KIO::CC_Verify;
182 }
183 
185 {
186  if (cacheControl == KIO::CC_CacheOnly) {
187  return QStringLiteral("CacheOnly");
188  }
189  if (cacheControl == KIO::CC_Cache) {
190  return QStringLiteral("Cache");
191  }
192  if (cacheControl == KIO::CC_Verify) {
193  return QStringLiteral("Verify");
194  }
195  if (cacheControl == KIO::CC_Refresh) {
196  return QStringLiteral("Refresh");
197  }
198  if (cacheControl == KIO::CC_Reload) {
199  return QStringLiteral("Reload");
200  }
201  qCDebug(KIO_CORE) << "unrecognized Cache control enum value:" << cacheControl;
202  return QString();
203 }
204 
206 {
207  if (url.isLocalFile()
208  || !url.scheme().startsWith(QLatin1String("http"))) {
209  return QString();
210  }
211 
212  return FavIconsCache::instance()->iconForUrl(url);
213 }
214 
216 {
217  if (url.scheme().isEmpty()) { // empty URL or relative URL (e.g. '~')
218  return QStringLiteral("unknown");
219  }
220  QMimeDatabase db;
221  const QMimeType mt = db.mimeTypeForUrl(url);
222  QString iconName;
223 
224  if (url.isLocalFile()) {
225  // Check to see whether it's an xdg location (e.g. Pictures folder)
226  if (mt.inherits(QStringLiteral("inode/directory"))) {
227  iconName = KIOPrivate::iconForStandardPath(url.toLocalFile());
228  }
229 
230  // Let KFileItem::iconName handle things for us
231  if (iconName.isEmpty()) {
232  const KFileItem item(url, mt.name());
233  iconName = item.iconName();
234  }
235 
236  } else {
237  // It's non-local and maybe on a slow filesystem
238 
239  // Look for a favicon
240  if (url.scheme().startsWith(QLatin1String("http"))) {
241  iconName = favIconForUrl(url);
242  }
243 
244  // Then handle the trash
245  else if (url.scheme() == QLatin1String("trash")) {
246  if (url.path().length() <= 1) { // trash:/ itself
247  KConfig trashConfig(QStringLiteral("trashrc"), KConfig::SimpleConfig);
248  iconName = trashConfig.group("Status").readEntry("Empty", true) ?
249  QStringLiteral("user-trash") : QStringLiteral("user-trash-full");
250  } else { // url.path().length() > 1, it's a file/folder under trash:/
251  iconName = mt.iconName();
252  }
253  }
254 
255  // and other protocols
256  if (iconName.isEmpty() && (mt.isDefault() || url.path().size() <= 1)) {
257  iconName = KProtocolInfo::icon(url.scheme());
258  }
259  }
260  // if we found nothing, return QMimeType.iconName()
261  // (which fallbacks to "application-octet-stream" when no MIME type could be determined)
262  return !iconName.isEmpty() ? iconName : mt.iconName();
263 }
264 
265 QUrl KIO::upUrl(const QUrl &url)
266 {
267  if (!url.isValid() || url.isRelative()) {
268  return QUrl();
269  }
270 
271  QUrl u(url);
272  if (url.hasQuery()) {
273  u.setQuery(QString());
274  return u;
275  }
276  if (url.hasFragment()) {
277  u.setFragment(QString());
278  }
280  return u.adjusted(QUrl::RemoveFilename);
281 }
282 
283 #if KIOCORE_BUILD_DEPRECATED_SINCE(5, 61)
284 QString KIO::suggestName(const QUrl &baseURL, const QString &oldName)
285 {
286  return KFileUtils::suggestName(baseURL, oldName);
287 }
288 #endif
StripTrailingSlash
Fail request if not in cache.
Definition: global.h:287
KIOCORE_EXPORT QString getCacheControlString(KIO::CacheControl cacheControl)
Returns a string representation of the given cache control method.
Definition: global.cpp:184
qulonglong filesize_t
64-bit file size
Definition: global.h:40
void setFragment(const QString &fragment, QUrl::ParsingMode mode)
KIOCORE_EXPORT QString encodeFileName(const QString &str)
Encodes (from the text displayed to the real filename) This translates &#39;/&#39; into a "unicode fraction s...
Definition: global.cpp:141
KCOREADDONS_EXPORT QString suggestName(const QUrl &baseURL, const QString &oldName)
Given a directory path and a filename (which usually exists already), this function returns a suggest...
Definition: global.cpp:284
QString toString(Qt::DateFormat format) const const
bool setHMS(int h, int m, int s, int ms)
KIOCORE_EXPORT QTime calculateRemaining(KIO::filesize_t totalSize, KIO::filesize_t processedSize, KIO::filesize_t speed)
Calculates remaining time from total size, processed size and speed.
Definition: global.cpp:89
int size() const const
KIOCORE_EXPORT QUrl upUrl(const QUrl &url)
This function is useful to implement the "Up" button in a file manager for example.
Definition: global.cpp:265
bool inherits(const QString &mimeTypeName) const const
Always fetch from remote site.
Definition: global.h:291
QString i18np(const char *singular, const char *plural, const TYPE &arg...)
KIOCORE_EXPORT QString convertSize(KIO::filesize_t size)
Converts size from bytes to the string representation.
Definition: global.cpp:43
KIOCORE_EXPORT QString convertSeconds(unsigned int seconds)
Convert seconds to a string representing number of days, hours, minutes and seconds.
Definition: global.cpp:72
KIOCORE_EXPORT QString number(KIO::filesize_t size)
Converts a size to a string representation Not unlike QString::number(...)
Definition: global.cpp:55
KIOCORE_EXPORT unsigned int calculateRemainingSeconds(KIO::filesize_t totalSize, KIO::filesize_t processedSize, KIO::filesize_t speed)
Calculates remaining time in seconds from total size, processed size and speed.
Definition: global.cpp:62
static QString icon(const QString &protocol)
Returns the name of the icon, associated with the specified protocol.
KIOCORE_EXPORT QString convertSizeFromKiB(KIO::filesize_t kibSize)
Converts size from kibi-bytes (2^10) to the string representation.
Definition: global.cpp:50
QMimeType mimeTypeForUrl(const QUrl &url) const const
QString i18nc(const char *context, const char *text, const TYPE &arg...)
bool isEmpty() const const
bool startsWith(const QString &s, Qt::CaseSensitivity cs) const const
CacheControl
Specifies how to use the cache.
Definition: global.h:286
QString path(QUrl::ComponentFormattingOptions options) const const
KIOCORE_EXPORT QString favIconForUrl(const QUrl &url)
Return the "favicon" (see http://www.favicon.com) for the given url, if available.
Definition: global.cpp:205
KIOCORE_EXPORT QString decodeFileName(const QString &str)
Decodes (from the filename to the text displayed) This doesn&#39;t do anything anymore, it used to do the opposite of encodeFileName when encodeFileName was using %2F for &#39;/&#39;.
Definition: global.cpp:148
QString scheme() const const
QString toLocalFile() const const
KIOCORE_EXPORT KIO::CacheControl parseCacheControl(const QString &cacheControl)
Parses the string representation of the cache control option.
Definition: global.cpp:160
QString toLower() const const
QString formatByteSize(double size, int precision=1, KFormat::BinaryUnitDialect dialect=KFormat::DefaultBinaryDialect, KFormat::BinarySizeUnits units=KFormat::DefaultBinaryUnits) const
static KSharedConfig::Ptr openConfig(const QString &fileName=QString(), OpenFlags mode=FullConfig, QStandardPaths::StandardLocation type=QStandardPaths::GenericConfigLocation)
KConfigGroup group(const QString &group)
QString & replace(int position, int n, QChar after)
bool isValid() const const
Use cached entry if available.
Definition: global.h:288
Always validate cached entry with remote site.
Definition: global.h:290
QUrl adjusted(QUrl::FormattingOptions options) const const
Validate cached entry with remote site if expired.
Definition: global.h:289
bool isRelative() const const
int length() const const
KIOCORE_EXPORT QString itemsSummaryString(uint items, uint files, uint dirs, KIO::filesize_t size, bool showSize)
Helper for showing information about a set of files and directories.
Definition: global.cpp:114
void setQuery(const QString &query, QUrl::ParsingMode mode)
bool hasFragment() const const
bool hasQuery() const const
T readEntry(const QString &key, const T &aDefault) const
DefaultBinaryDialect
A KFileItem is a generic class to handle a file, local or remote.
Definition: kfileitem.h:35
KIOCORE_EXPORT QString iconNameForUrl(const QUrl &url)
Return the icon name for a URL.
Definition: global.cpp:215
KIOCORE_EXPORT QString suggestName(const QUrl &baseURL, const QString &oldName)
Given a directory path and a filename (which usually exists already), this function returns a suggest...
Definition: global.cpp:284
bool isLocalFile() const const
This file is part of the KDE documentation.
Documentation copyright © 1996-2021 The KDE developers.
Generated on Tue Jan 19 2021 23:03:32 by doxygen 1.8.11 written by Dimitri van Heesch, © 1997-2006

KDE's Doxygen guidelines are available online.