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 "faviconscache_p.h"
10 #include "kioglobal_p.h"
11 
12 #include <KConfig>
13 #include <KConfigGroup>
14 #include <KFileUtils>
15 #include <KFormat>
16 #include <KLocalizedString>
17 #include <KSharedConfig>
18 #include <QMimeDatabase>
19 #include <QUrl>
20 #include <kfileitem.h>
21 #include <kprotocolinfo.h>
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, KIO::filesize_t processedSize, KIO::filesize_t speed)
63 {
64  if ((speed != 0) && (totalSize != 0)) {
65  return (totalSize - processedSize) / speed;
66  } else {
67  return 0;
68  }
69 }
70 
71 KIOCORE_EXPORT QString KIO::convertSeconds(unsigned int seconds)
72 {
73  unsigned int days = seconds / 86400;
74  unsigned int hours = (seconds - (days * 86400)) / 3600;
75  unsigned int mins = (seconds - (days * 86400) - (hours * 3600)) / 60;
76  seconds = (seconds - (days * 86400) - (hours * 3600) - (mins * 60));
77 
78  const QTime time(hours, mins, seconds);
79  const QString timeStr(time.toString(QStringLiteral("hh:mm:ss")));
80  if (days > 0) {
81  return i18np("1 day %2", "%1 days %2", days, timeStr);
82  } else {
83  return timeStr;
84  }
85 }
86 
87 #if KIOCORE_BUILD_DEPRECATED_SINCE(3, 4)
88 KIOCORE_EXPORT QTime KIO::calculateRemaining(KIO::filesize_t totalSize, KIO::filesize_t processedSize, KIO::filesize_t speed)
89 {
90  QTime remainingTime;
91 
92  if (speed != 0) {
93  KIO::filesize_t secs;
94  if (totalSize == 0) {
95  secs = 0;
96  } else {
97  secs = (totalSize - processedSize) / speed;
98  }
99  if (secs >= (24 * 60 * 60)) { // Limit to 23:59:59
100  secs = (24 * 60 * 60) - 1;
101  }
102  int hr = secs / (60 * 60);
103  int mn = (secs - hr * 60 * 60) / 60;
104  int sc = (secs - hr * 60 * 60 - mn * 60);
105 
106  remainingTime.setHMS(hr, mn, sc);
107  }
108 
109  return remainingTime;
110 }
111 #endif
112 
113 KIOCORE_EXPORT QString KIO::itemsSummaryString(uint items, uint files, uint dirs, KIO::filesize_t size, bool showSize)
114 {
115  if (files == 0 && dirs == 0 && items == 0) {
116  return i18np("%1 Item", "%1 Items", 0);
117  }
118 
119  QString summary;
120  const QString foldersText = i18np("1 Folder", "%1 Folders", dirs);
121  const QString filesText = i18np("1 File", "%1 Files", files);
122  if (files > 0 && dirs > 0) {
123  summary = showSize ? i18nc("folders, files (size)", "%1, %2 (%3)", foldersText, filesText, KIO::convertSize(size))
124  : i18nc("folders, files", "%1, %2", foldersText, filesText);
125  } else if (files > 0) {
126  summary = showSize ? i18nc("files (size)", "%1 (%2)", filesText, KIO::convertSize(size)) : filesText;
127  } else if (dirs > 0) {
128  summary = foldersText;
129  }
130 
131  if (items > dirs + files) {
132  const QString itemsText = i18np("%1 Item", "%1 Items", items);
133  summary = summary.isEmpty() ? itemsText : i18nc("items: folders, files (size)", "%1: %2", itemsText, summary);
134  }
135 
136  return summary;
137 }
138 
139 KIOCORE_EXPORT QString KIO::encodeFileName(const QString &_str)
140 {
141  QString str(_str);
142  str.replace(QLatin1Char('/'), QChar(0x2044)); // "Fraction slash"
143  return str;
144 }
145 
146 KIOCORE_EXPORT QString KIO::decodeFileName(const QString &_str)
147 {
148  // Nothing to decode. "Fraction slash" is fine in filenames.
149  return _str;
150 }
151 
152 /***************************************************************
153  *
154  * Utility functions
155  *
156  ***************************************************************/
157 
159 {
160  QString tmp = cacheControl.toLower();
161 
162  if (tmp == QLatin1String("cacheonly")) {
163  return KIO::CC_CacheOnly;
164  }
165  if (tmp == QLatin1String("cache")) {
166  return KIO::CC_Cache;
167  }
168  if (tmp == QLatin1String("verify")) {
169  return KIO::CC_Verify;
170  }
171  if (tmp == QLatin1String("refresh")) {
172  return KIO::CC_Refresh;
173  }
174  if (tmp == QLatin1String("reload")) {
175  return KIO::CC_Reload;
176  }
177 
178  qCDebug(KIO_CORE) << "unrecognized Cache control option:" << cacheControl;
179  return KIO::CC_Verify;
180 }
181 
183 {
184  if (cacheControl == KIO::CC_CacheOnly) {
185  return QStringLiteral("CacheOnly");
186  }
187  if (cacheControl == KIO::CC_Cache) {
188  return QStringLiteral("Cache");
189  }
190  if (cacheControl == KIO::CC_Verify) {
191  return QStringLiteral("Verify");
192  }
193  if (cacheControl == KIO::CC_Refresh) {
194  return QStringLiteral("Refresh");
195  }
196  if (cacheControl == KIO::CC_Reload) {
197  return QStringLiteral("Reload");
198  }
199  qCDebug(KIO_CORE) << "unrecognized Cache control enum value:" << cacheControl;
200  return QString();
201 }
202 
204 {
205  if (url.isLocalFile() || !url.scheme().startsWith(QLatin1String("http"))) {
206  return QString();
207  }
208 
209  return FavIconsCache::instance()->iconForUrl(url);
210 }
211 
213 {
214  if (url.scheme().isEmpty()) { // empty URL or relative URL (e.g. '~')
215  return QStringLiteral("unknown");
216  }
217  QMimeDatabase db;
218  const QMimeType mt = db.mimeTypeForUrl(url);
219  QString iconName;
220 
221  if (url.isLocalFile()) {
222  // Check to see whether it's an xdg location (e.g. Pictures folder)
223  if (mt.inherits(QStringLiteral("inode/directory"))) {
224  iconName = KIOPrivate::iconForStandardPath(url.toLocalFile());
225  }
226 
227  // Let KFileItem::iconName handle things for us
228  if (iconName.isEmpty()) {
229  const KFileItem item(url, mt.name());
230  iconName = item.iconName();
231  }
232 
233  } else {
234  // It's non-local and maybe on a slow filesystem
235 
236  // Look for a favicon
237  if (url.scheme().startsWith(QLatin1String("http"))) {
238  iconName = favIconForUrl(url);
239  }
240 
241  // Then handle the trash
242  else if (url.scheme() == QLatin1String("trash")) {
243  if (url.path().length() <= 1) { // trash:/ itself
244  KConfig trashConfig(QStringLiteral("trashrc"), KConfig::SimpleConfig);
245  iconName = trashConfig.group("Status").readEntry("Empty", true) ? QStringLiteral("user-trash") : QStringLiteral("user-trash-full");
246  } else { // url.path().length() > 1, it's a file/folder under trash:/
247  iconName = mt.iconName();
248  }
249  }
250 
251  // and other protocols
252  if (iconName.isEmpty() && (mt.isDefault() || url.path().size() <= 1)) {
253  iconName = KProtocolInfo::icon(url.scheme());
254  }
255  }
256  // if we found nothing, return QMimeType.iconName()
257  // (which fallbacks to "application-octet-stream" when no MIME type could be determined)
258  return !iconName.isEmpty() ? iconName : mt.iconName();
259 }
260 
261 QUrl KIO::upUrl(const QUrl &url)
262 {
263  if (!url.isValid() || url.isRelative()) {
264  return QUrl();
265  }
266 
267  QUrl u(url);
268  if (url.hasQuery()) {
269  u.setQuery(QString());
270  return u;
271  }
272  if (url.hasFragment()) {
273  u.setFragment(QString());
274  }
275  u = u.adjusted(QUrl::StripTrailingSlash); /// don't combine with the line below
276  return u.adjusted(QUrl::RemoveFilename);
277 }
278 
279 #if KIOCORE_BUILD_DEPRECATED_SINCE(5, 61)
280 QString KIO::suggestName(const QUrl &baseURL, const QString &oldName)
281 {
282  return KFileUtils::suggestName(baseURL, oldName);
283 }
284 #endif
StripTrailingSlash
Fail request if not in cache.
Definition: global.h:286
KIOCORE_EXPORT QString getCacheControlString(KIO::CacheControl cacheControl)
Returns a string representation of the given cache control method.
Definition: global.cpp:182
qulonglong filesize_t
64-bit file size
Definition: global.h:39
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:139
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:280
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:88
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:261
bool inherits(const QString &mimeTypeName) const const
Always fetch from remote site.
Definition: global.h:290
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:71
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:285
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:203
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:146
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:158
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:287
Always validate cached entry with remote site.
Definition: global.h:289
QUrl adjusted(QUrl::FormattingOptions options) const const
Validate cached entry with remote site if expired.
Definition: global.h:288
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:113
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:212
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:280
bool isLocalFile() const const
This file is part of the KDE documentation.
Documentation copyright © 1996-2021 The KDE developers.
Generated on Sat Apr 10 2021 23:00:46 by doxygen 1.8.11 written by Dimitri van Heesch, © 1997-2006

KDE's Doxygen guidelines are available online.