KIO

global.cpp
1 /* This file is part of the KDE libraries
2  Copyright (C) 2000 David Faure <[email protected]>
3 
4  This library is free software; you can redistribute it and/or
5  modify it under the terms of the GNU Library General Public
6  License version 2 as published by the Free Software Foundation.
7 
8  This library is distributed in the hope that it will be useful,
9  but WITHOUT ANY WARRANTY; without even the implied warranty of
10  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11  Library General Public License for more details.
12 
13  You should have received a copy of the GNU Library General Public License
14  along with this library; see the file COPYING.LIB. If not, write to
15  the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
16  Boston, MA 02110-1301, USA.
17 */
18 
19 #include "global.h"
20 #include "kioglobal_p.h"
21 #include "faviconscache_p.h"
22 
23 #include <kprotocolinfo.h>
24 #include <KConfig>
25 #include <KConfigGroup>
26 #include <kfileitem.h>
27 #include <KLocalizedString>
28 #include <KSharedConfig>
29 #include <KFormat>
30 #include <KFileUtils>
31 #include <QMimeDatabase>
32 #include <QUrl>
33 
34 #include "kiocoredebug.h"
35 
36 KFormat::BinaryUnitDialect _k_loadBinaryDialect();
37 Q_GLOBAL_STATIC_WITH_ARGS(KFormat::BinaryUnitDialect, _k_defaultBinaryDialect, (_k_loadBinaryDialect()))
38 
39 KFormat::BinaryUnitDialect _k_loadBinaryDialect()
40 {
41  KConfigGroup mainGroup(KSharedConfig::openConfig(), "Locale");
42 
43  KFormat::BinaryUnitDialect dialect(KFormat::BinaryUnitDialect(mainGroup.readEntry("BinaryUnitDialect", int(KFormat::DefaultBinaryDialect))));
44  dialect = static_cast<KFormat::BinaryUnitDialect>(mainGroup.readEntry("BinaryUnitDialect", int(dialect)));
45 
46  // Error checking
47  if (dialect <= KFormat::DefaultBinaryDialect || dialect > KFormat::LastBinaryDialect) {
48  dialect = KFormat::IECBinaryDialect;
49  }
50 
51  return dialect;
52 }
53 
54 KIOCORE_EXPORT QString KIO::convertSize(KIO::filesize_t fileSize)
55 {
56  const KFormat::BinaryUnitDialect dialect = *_k_defaultBinaryDialect();
57 
58  return KFormat().formatByteSize(fileSize, 1, dialect);
59 }
60 
62 {
63  return convertSize(kibSize * 1024);
64 }
65 
66 KIOCORE_EXPORT QString KIO::number(KIO::filesize_t size)
67 {
68  char charbuf[256];
69  sprintf(charbuf, "%lld", size);
70  return QLatin1String(charbuf);
71 }
72 
73 KIOCORE_EXPORT unsigned int KIO::calculateRemainingSeconds(KIO::filesize_t totalSize,
74  KIO::filesize_t processedSize, KIO::filesize_t speed)
75 {
76  if ((speed != 0) && (totalSize != 0)) {
77  return (totalSize - processedSize) / speed;
78  } else {
79  return 0;
80  }
81 }
82 
83 KIOCORE_EXPORT QString KIO::convertSeconds(unsigned int seconds)
84 {
85  unsigned int days = seconds / 86400;
86  unsigned int hours = (seconds - (days * 86400)) / 3600;
87  unsigned int mins = (seconds - (days * 86400) - (hours * 3600)) / 60;
88  seconds = (seconds - (days * 86400) - (hours * 3600) - (mins * 60));
89 
90  const QTime time(hours, mins, seconds);
91  const QString timeStr(time.toString(QStringLiteral("hh:mm:ss")));
92  if (days > 0) {
93  return i18np("1 day %2", "%1 days %2", days, timeStr);
94  } else {
95  return timeStr;
96  }
97 }
98 
99 #if KIOCORE_BUILD_DEPRECATED_SINCE(3, 4)
100 KIOCORE_EXPORT QTime KIO::calculateRemaining(KIO::filesize_t totalSize, KIO::filesize_t processedSize, KIO::filesize_t speed)
101 {
102  QTime remainingTime;
103 
104  if (speed != 0) {
105  KIO::filesize_t secs;
106  if (totalSize == 0) {
107  secs = 0;
108  } else {
109  secs = (totalSize - processedSize) / speed;
110  }
111  if (secs >= (24 * 60 * 60)) { // Limit to 23:59:59
112  secs = (24 * 60 * 60) - 1;
113  }
114  int hr = secs / (60 * 60);
115  int mn = (secs - hr * 60 * 60) / 60;
116  int sc = (secs - hr * 60 * 60 - mn * 60);
117 
118  remainingTime.setHMS(hr, mn, sc);
119  }
120 
121  return remainingTime;
122 }
123 #endif
124 
125 KIOCORE_EXPORT QString KIO::itemsSummaryString(uint items, uint files, uint dirs, KIO::filesize_t size, bool showSize)
126 {
127  if (files == 0 && dirs == 0 && items == 0) {
128  return i18np("%1 Item", "%1 Items", 0);
129  }
130 
131  QString summary;
132  const QString foldersText = i18np("1 Folder", "%1 Folders", dirs);
133  const QString filesText = i18np("1 File", "%1 Files", files);
134  if (files > 0 && dirs > 0) {
135  summary = showSize ?
136  i18nc("folders, files (size)", "%1, %2 (%3)", foldersText, filesText, KIO::convertSize(size)) :
137  i18nc("folders, files", "%1, %2", foldersText, filesText);
138  } else if (files > 0) {
139  summary = showSize ? i18nc("files (size)", "%1 (%2)", filesText, KIO::convertSize(size)) : filesText;
140  } else if (dirs > 0) {
141  summary = foldersText;
142  }
143 
144  if (items > dirs + files) {
145  const QString itemsText = i18np("%1 Item", "%1 Items", items);
146  summary = summary.isEmpty() ? itemsText : i18nc("items: folders, files (size)", "%1: %2", itemsText, summary);
147  }
148 
149  return summary;
150 }
151 
152 KIOCORE_EXPORT QString KIO::encodeFileName(const QString &_str)
153 {
154  QString str(_str);
155  str.replace(QLatin1Char('/'), QChar(0x2044)); // "Fraction slash"
156  return str;
157 }
158 
159 KIOCORE_EXPORT QString KIO::decodeFileName(const QString &_str)
160 {
161  // Nothing to decode. "Fraction slash" is fine in filenames.
162  return _str;
163 }
164 
165 /***************************************************************
166  *
167  * Utility functions
168  *
169  ***************************************************************/
170 
172 {
173  QString tmp = cacheControl.toLower();
174 
175  if (tmp == QLatin1String("cacheonly")) {
176  return KIO::CC_CacheOnly;
177  }
178  if (tmp == QLatin1String("cache")) {
179  return KIO::CC_Cache;
180  }
181  if (tmp == QLatin1String("verify")) {
182  return KIO::CC_Verify;
183  }
184  if (tmp == QLatin1String("refresh")) {
185  return KIO::CC_Refresh;
186  }
187  if (tmp == QLatin1String("reload")) {
188  return KIO::CC_Reload;
189  }
190 
191  qCDebug(KIO_CORE) << "unrecognized Cache control option:" << cacheControl;
192  return KIO::CC_Verify;
193 }
194 
196 {
197  if (cacheControl == KIO::CC_CacheOnly) {
198  return QStringLiteral("CacheOnly");
199  }
200  if (cacheControl == KIO::CC_Cache) {
201  return QStringLiteral("Cache");
202  }
203  if (cacheControl == KIO::CC_Verify) {
204  return QStringLiteral("Verify");
205  }
206  if (cacheControl == KIO::CC_Refresh) {
207  return QStringLiteral("Refresh");
208  }
209  if (cacheControl == KIO::CC_Reload) {
210  return QStringLiteral("Reload");
211  }
212  qCDebug(KIO_CORE) << "unrecognized Cache control enum value:" << cacheControl;
213  return QString();
214 }
215 
217 {
218  if (url.isLocalFile()
219  || !url.scheme().startsWith(QLatin1String("http"))) {
220  return QString();
221  }
222 
223  return FavIconsCache::instance()->iconForUrl(url);
224 }
225 
227 {
228  if (url.scheme().isEmpty()) { // empty URL or relative URL (e.g. '~')
229  return QStringLiteral("unknown");
230  }
231  QMimeDatabase db;
232  const QMimeType mt = db.mimeTypeForUrl(url);
233  QString iconName;
234 
235  if (url.isLocalFile()) {
236  // Check to see whether it's an xdg location (e.g. Pictures folder)
237  if (mt.inherits(QStringLiteral("inode/directory"))) {
238  iconName = KIOPrivate::iconForStandardPath(url.toLocalFile());
239  }
240 
241  // Let KFileItem::iconName handle things for us
242  if (iconName.isEmpty()) {
243  const KFileItem item(url, mt.name());
244  iconName = item.iconName();
245  }
246 
247  } else {
248  // It's non-local and maybe on a slow filesystem
249 
250  // Look for a favicon
251  if (url.scheme().startsWith(QLatin1String("http"))) {
252  iconName = favIconForUrl(url);
253  }
254 
255  // Then handle the trash
256  else if (url.scheme() == QLatin1String("trash")) {
257  if (url.path().length() <= 1) { // trash:/ itself
258  KConfig trashConfig(QStringLiteral("trashrc"), KConfig::SimpleConfig);
259  iconName = trashConfig.group("Status").readEntry("Empty", true) ?
260  QStringLiteral("user-trash") : QStringLiteral("user-trash-full");
261  } else { // url.path().length() > 1, it's a file/folder under trash:/
262  iconName = mt.iconName();
263  }
264  }
265 
266  // and other protocols
267  if (iconName.isEmpty()) {
268  iconName = KProtocolInfo::icon(url.scheme());
269  }
270  }
271  // if we found nothing, return QMimeType.iconName()
272  // (which fallbacks to "application-octet-stream" when no mimetype could be determined)
273  return !iconName.isEmpty() ? iconName : mt.iconName();
274 }
275 
276 QUrl KIO::upUrl(const QUrl &url)
277 {
278  if (!url.isValid() || url.isRelative()) {
279  return QUrl();
280  }
281 
282  QUrl u(url);
283  if (url.hasQuery()) {
284  u.setQuery(QString());
285  return u;
286  }
287  if (url.hasFragment()) {
288  u.setFragment(QString());
289  }
291  return u.adjusted(QUrl::RemoveFilename);
292 }
293 
294 #if KIOCORE_BUILD_DEPRECATED_SINCE(5, 61)
295 QString KIO::suggestName(const QUrl &baseURL, const QString &oldName)
296 {
297  return KFileUtils::suggestName(baseURL, oldName);
298 }
299 #endif
StripTrailingSlash
Fail request if not in cache.
Definition: global.h:298
KIOCORE_EXPORT QString getCacheControlString(KIO::CacheControl cacheControl)
Returns a string representation of the given cache control method.
Definition: global.cpp:195
qulonglong filesize_t
64-bit file size
Definition: global.h:51
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:152
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:295
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:100
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:276
bool inherits(const QString &mimeTypeName) const const
Always fetch from remote site.
Definition: global.h:302
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:54
KIOCORE_EXPORT QString convertSeconds(unsigned int seconds)
Convert seconds to a string representing number of days, hours, minutes and seconds.
Definition: global.cpp:83
KIOCORE_EXPORT QString number(KIO::filesize_t size)
Converts a size to a string representation Not unlike QString::number(...)
Definition: global.cpp:66
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:73
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:61
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:297
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:216
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:159
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:171
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:299
Always validate cached entry with remote site.
Definition: global.h:301
QUrl adjusted(QUrl::FormattingOptions options) const const
Validate cached entry with remote site if expired.
Definition: global.h:300
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:125
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:47
KIOCORE_EXPORT QString iconNameForUrl(const QUrl &url)
Return the icon name for a URL.
Definition: global.cpp:226
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:295
bool isLocalFile() const const
This file is part of the KDE documentation.
Documentation copyright © 1996-2020 The KDE developers.
Generated on Fri Aug 7 2020 22:58:55 by doxygen 1.8.11 written by Dimitri van Heesch, © 1997-2006

KDE's Doxygen guidelines are available online.