• Skip to content
  • Skip to link menu
  • KDE API Reference
  • kdelibs-4.9.4 API Reference
  • KDE Home
  • Contact Us
 

KIO

  • kio
  • kio
kdirlister.cpp
Go to the documentation of this file.
1 /* This file is part of the KDE project
2  Copyright (C) 1998, 1999 Torben Weis <weis@kde.org>
3  2000 Carsten Pfeiffer <pfeiffer@kde.org>
4  2003-2005 David Faure <faure@kde.org>
5  2001-2006 Michael Brade <brade@kde.org>
6 
7  This library is free software; you can redistribute it and/or
8  modify it under the terms of the GNU Library General Public
9  License as published by the Free Software Foundation; either
10  version 2 of the License, or (at your option) any later version.
11 
12  This library is distributed in the hope that it will be useful,
13  but WITHOUT ANY WARRANTY; without even the implied warranty of
14  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15  Library General Public License for more details.
16 
17  You should have received a copy of the GNU Library General Public License
18  along with this library; see the file COPYING.LIB. If not, write to
19  the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
20  Boston, MA 02110-1301, USA.
21 */
22 
23 #include "kdirlister.h"
24 #include "kdirlister_p.h"
25 
26 #include <QtCore/QRegExp>
27 
28 #include <kdebug.h>
29 #include <kde_file.h>
30 #include <klocale.h>
31 #include <kio/job.h>
32 #include <kio/jobuidelegate.h>
33 #include <kmessagebox.h>
34 #include "kprotocolmanager.h"
35 #include "kmountpoint.h"
36 
37 #include <QFile>
38 
39 // Enable this to get printDebug() called often, to see the contents of the cache
40 //#define DEBUG_CACHE
41 
42 // Make really sure it doesn't get activated in the final build
43 #ifdef NDEBUG
44 #undef DEBUG_CACHE
45 #endif
46 
47 K_GLOBAL_STATIC(KDirListerCache, kDirListerCache)
48 
49 KDirListerCache::KDirListerCache()
50  : itemsCached( 10 ) // keep the last 10 directories around
51 {
52  //kDebug(7004);
53 
54  connect( &pendingUpdateTimer, SIGNAL(timeout()), this, SLOT(processPendingUpdates()) );
55  pendingUpdateTimer.setSingleShot( true );
56 
57  connect( KDirWatch::self(), SIGNAL(dirty(QString)),
58  this, SLOT(slotFileDirty(QString)) );
59  connect( KDirWatch::self(), SIGNAL(created(QString)),
60  this, SLOT(slotFileCreated(QString)) );
61  connect( KDirWatch::self(), SIGNAL(deleted(QString)),
62  this, SLOT(slotFileDeleted(QString)) );
63 
64  kdirnotify = new org::kde::KDirNotify(QString(), QString(), QDBusConnection::sessionBus(), this);
65  connect(kdirnotify, SIGNAL(FileRenamed(QString,QString)), SLOT(slotFileRenamed(QString,QString)));
66  connect(kdirnotify, SIGNAL(FilesAdded(QString)), SLOT(slotFilesAdded(QString)));
67  connect(kdirnotify, SIGNAL(FilesChanged(QStringList)), SLOT(slotFilesChanged(QStringList)));
68  connect(kdirnotify, SIGNAL(FilesRemoved(QStringList)), SLOT(slotFilesRemoved(QStringList)));
69 
70  // The use of KUrl::url() in ~DirItem (sendSignal) crashes if the static for QRegExpEngine got deleted already,
71  // so we need to destroy the KDirListerCache before that.
72  qAddPostRoutine(kDirListerCache.destroy);
73 }
74 
75 KDirListerCache::~KDirListerCache()
76 {
77  //kDebug(7004);
78 
79  qDeleteAll(itemsInUse);
80  itemsInUse.clear();
81 
82  itemsCached.clear();
83  directoryData.clear();
84 
85  if ( KDirWatch::exists() )
86  KDirWatch::self()->disconnect( this );
87 }
88 
89 // setting _reload to true will emit the old files and
90 // call updateDirectory
91 bool KDirListerCache::listDir( KDirLister *lister, const KUrl& _u,
92  bool _keep, bool _reload )
93 {
94  KUrl _url(_u);
95  _url.cleanPath(); // kill consecutive slashes
96 
97  if (!_url.host().isEmpty() && KProtocolInfo::protocolClass(_url.protocol()) == ":local"
98  && _url.protocol() != "file") {
99  // ":local" protocols ignore the hostname, so strip it out preventively - #160057
100  // kio_file is special cased since it does honor the hostname (by redirecting to e.g. smb)
101  _url.setHost(QString());
102  if (_keep == false)
103  emit lister->redirection(_url);
104  }
105 
106  // like this we don't have to worry about trailing slashes any further
107  _url.adjustPath(KUrl::RemoveTrailingSlash);
108 
109  const QString urlStr = _url.url();
110 
111  QString resolved;
112  if (_url.isLocalFile()) {
113  // Resolve symlinks (#213799)
114  const QString local = _url.toLocalFile();
115  resolved = QFileInfo(local).canonicalFilePath();
116  if (local != resolved)
117  canonicalUrls[resolved].append(urlStr);
118  // TODO: remove entry from canonicalUrls again in forgetDirs
119  // Note: this is why we use a QStringList value in there rather than a QSet:
120  // we can just remove one entry and not have to worry about other dirlisters
121  // (the non-unicity of the stringlist gives us the refcounting, basically).
122  }
123 
124  if (!validUrl(lister, _url)) {
125  kDebug(7004) << lister << "url=" << _url << "not a valid url";
126  return false;
127  }
128 
129  //kDebug(7004) << lister << "url=" << _url << "keep=" << _keep << "reload=" << _reload;
130 #ifdef DEBUG_CACHE
131  printDebug();
132 #endif
133 
134  if (!_keep) {
135  // stop any running jobs for lister
136  stop(lister, true /*silent*/);
137 
138  // clear our internal list for lister
139  forgetDirs(lister);
140 
141  lister->d->rootFileItem = KFileItem();
142  } else if (lister->d->lstDirs.contains(_url)) {
143  // stop the job listing _url for this lister
144  stopListingUrl(lister, _url, true /*silent*/);
145 
146  // remove the _url as well, it will be added in a couple of lines again!
147  // forgetDirs with three args does not do this
148  // TODO: think about moving this into forgetDirs
149  lister->d->lstDirs.removeAll(_url);
150 
151  // clear _url for lister
152  forgetDirs(lister, _url, true);
153 
154  if (lister->d->url == _url)
155  lister->d->rootFileItem = KFileItem();
156  }
157 
158  lister->d->complete = false;
159 
160  lister->d->lstDirs.append(_url);
161 
162  if (lister->d->url.isEmpty() || !_keep) // set toplevel URL only if not set yet
163  lister->d->url = _url;
164 
165  DirItem *itemU = itemsInUse.value(urlStr);
166 
167  KDirListerCacheDirectoryData& dirData = directoryData[urlStr]; // find or insert
168 
169  if (dirData.listersCurrentlyListing.isEmpty()) {
170  // if there is an update running for _url already we get into
171  // the following case - it will just be restarted by updateDirectory().
172 
173  dirData.listersCurrentlyListing.append(lister);
174 
175  DirItem *itemFromCache = 0;
176  if (itemU || (!_reload && (itemFromCache = itemsCached.take(urlStr)) ) ) {
177  if (itemU) {
178  kDebug(7004) << "Entry already in use:" << _url;
179  // if _reload is set, then we'll emit cached items and then updateDirectory.
180  } else {
181  kDebug(7004) << "Entry in cache:" << _url;
182  itemsInUse.insert(urlStr, itemFromCache);
183  itemU = itemFromCache;
184  }
185  if (lister->d->autoUpdate) {
186  itemU->incAutoUpdate();
187  }
188  if (itemFromCache && itemFromCache->watchedWhileInCache) {
189  itemFromCache->watchedWhileInCache = false;;
190  itemFromCache->decAutoUpdate();
191  }
192 
193  emit lister->started(_url);
194 
195  // List items from the cache in a delayed manner, just like things would happen
196  // if we were not using the cache.
197  new KDirLister::Private::CachedItemsJob(lister, _url, _reload);
198 
199  } else {
200  // dir not in cache or _reload is true
201  if (_reload) {
202  kDebug(7004) << "Reloading directory:" << _url;
203  itemsCached.remove(urlStr);
204  } else {
205  kDebug(7004) << "Listing directory:" << _url;
206  }
207 
208  itemU = new DirItem(_url, resolved);
209  itemsInUse.insert(urlStr, itemU);
210  if (lister->d->autoUpdate)
211  itemU->incAutoUpdate();
212 
213 // // we have a limit of MAX_JOBS_PER_LISTER concurrently running jobs
214 // if ( lister->d->numJobs() >= MAX_JOBS_PER_LISTER )
215 // {
216 // pendingUpdates.insert( _url );
217 // }
218 // else
219  {
220  KIO::ListJob* job = KIO::listDir(_url, KIO::HideProgressInfo);
221  runningListJobs.insert(job, KIO::UDSEntryList());
222 
223  lister->d->jobStarted(job);
224  lister->d->connectJob(job);
225 
226  if (lister->d->window)
227  job->ui()->setWindow(lister->d->window);
228 
229  connect(job, SIGNAL(entries(KIO::Job*,KIO::UDSEntryList)),
230  this, SLOT(slotEntries(KIO::Job*,KIO::UDSEntryList)));
231  connect(job, SIGNAL(result(KJob*)),
232  this, SLOT(slotResult(KJob*)));
233  connect(job, SIGNAL(redirection(KIO::Job*,KUrl)),
234  this, SLOT(slotRedirection(KIO::Job*,KUrl)));
235 
236  emit lister->started(_url);
237  }
238  //kDebug(7004) << "Entry now being listed by" << dirData.listersCurrentlyListing;
239  }
240  } else {
241 
242  kDebug(7004) << "Entry currently being listed:" << _url << "by" << dirData.listersCurrentlyListing;
243 #ifdef DEBUG_CACHE
244  printDebug();
245 #endif
246 
247  emit lister->started( _url );
248 
249  // Maybe listersCurrentlyListing/listersCurrentlyHolding should be QSets?
250  Q_ASSERT(!dirData.listersCurrentlyListing.contains(lister));
251  dirData.listersCurrentlyListing.append( lister );
252 
253  KIO::ListJob *job = jobForUrl( urlStr );
254  // job will be 0 if we were listing from cache rather than listing from a kio job.
255  if( job ) {
256  lister->d->jobStarted( job );
257  lister->d->connectJob( job );
258  }
259  Q_ASSERT( itemU );
260 
261  // List existing items in a delayed manner, just like things would happen
262  // if we were not using the cache.
263  if (!itemU->lstItems.isEmpty()) {
264  kDebug() << "Listing" << itemU->lstItems.count() << "cached items soon";
265  new KDirLister::Private::CachedItemsJob(lister, _url, _reload);
266  } else {
267  // The other lister hasn't emitted anything yet. Good, we'll just listen to it.
268  // One problem could be if we have _reload=true and the existing job doesn't, though.
269  }
270 
271 #ifdef DEBUG_CACHE
272  printDebug();
273 #endif
274  }
275 
276  return true;
277 }
278 
279 KDirLister::Private::CachedItemsJob* KDirLister::Private::cachedItemsJobForUrl(const KUrl& url) const
280 {
281  Q_FOREACH(CachedItemsJob* job, m_cachedItemsJobs) {
282  if (job->url() == url)
283  return job;
284  }
285  return 0;
286 }
287 
288 KDirLister::Private::CachedItemsJob::CachedItemsJob(KDirLister* lister, const KUrl& url, bool reload)
289  : KJob(lister),
290  m_lister(lister), m_url(url),
291  m_reload(reload), m_emitCompleted(true)
292 {
293  //kDebug() << "Creating CachedItemsJob" << this << "for lister" << lister << url;
294  if (lister->d->cachedItemsJobForUrl(url)) {
295  kWarning(7004) << "Lister" << lister << "has a cached items job already for" << url;
296  }
297  lister->d->m_cachedItemsJobs.append(this);
298  setAutoDelete(true);
299  start();
300 }
301 
302 // Called by start() via QueuedConnection
303 void KDirLister::Private::CachedItemsJob::done()
304 {
305  if (!m_lister) // job was already killed, but waiting deletion due to deleteLater
306  return;
307  kDirListerCache->emitItemsFromCache(this, m_lister, m_url, m_reload, m_emitCompleted);
308  emitResult();
309 }
310 
311 bool KDirLister::Private::CachedItemsJob::doKill()
312 {
313  //kDebug(7004) << this;
314  kDirListerCache->forgetCachedItemsJob(this, m_lister, m_url);
315  if (!property("_kdlc_silent").toBool()) {
316  emit m_lister->canceled(m_url);
317  emit m_lister->canceled();
318  }
319  m_lister = 0;
320  return true;
321 }
322 
323 void KDirListerCache::emitItemsFromCache(KDirLister::Private::CachedItemsJob* cachedItemsJob, KDirLister* lister, const KUrl& _url, bool _reload, bool _emitCompleted)
324 {
325  const QString urlStr = _url.url();
326  KDirLister::Private* kdl = lister->d;
327  kdl->complete = false;
328 
329  DirItem *itemU = kDirListerCache->itemsInUse.value(urlStr);
330  if (!itemU) {
331  kWarning(7004) << "Can't find item for directory" << urlStr << "anymore";
332  } else {
333  const KFileItemList items = itemU->lstItems;
334  const KFileItem rootItem = itemU->rootItem;
335  _reload = _reload || !itemU->complete;
336 
337  if (kdl->rootFileItem.isNull() && !rootItem.isNull() && kdl->url == _url) {
338  kdl->rootFileItem = rootItem;
339  }
340  if (!items.isEmpty()) {
341  //kDebug(7004) << "emitting" << items.count() << "for lister" << lister;
342  kdl->addNewItems(_url, items);
343  kdl->emitItems();
344  }
345  }
346 
347  forgetCachedItemsJob(cachedItemsJob, lister, _url);
348 
349  // Emit completed, unless we were told not to,
350  // or if listDir() was called while another directory listing for this dir was happening,
351  // so we "joined" it. We detect that using jobForUrl to ensure it's a real ListJob,
352  // not just a lister-specific CachedItemsJob (which wouldn't emit completed for us).
353  if (_emitCompleted) {
354 
355  kdl->complete = true;
356  emit lister->completed( _url );
357  emit lister->completed();
358 
359  if ( _reload ) {
360  updateDirectory( _url );
361  }
362  }
363 }
364 
365 void KDirListerCache::forgetCachedItemsJob(KDirLister::Private::CachedItemsJob* cachedItemsJob, KDirLister* lister, const KUrl& _url)
366 {
367  // Modifications to data structures only below this point;
368  // so that addNewItems is called with a consistent state
369 
370  const QString urlStr = _url.url();
371  lister->d->m_cachedItemsJobs.removeAll(cachedItemsJob);
372 
373  KDirListerCacheDirectoryData& dirData = directoryData[urlStr];
374  Q_ASSERT(dirData.listersCurrentlyListing.contains(lister));
375 
376  KIO::ListJob *listJob = jobForUrl(urlStr);
377  if (!listJob) {
378  Q_ASSERT(!dirData.listersCurrentlyHolding.contains(lister));
379  //kDebug(7004) << "Moving from listing to holding, because no more job" << lister << urlStr;
380  dirData.listersCurrentlyHolding.append( lister );
381  dirData.listersCurrentlyListing.removeAll( lister );
382  } else {
383  //kDebug(7004) << "Still having a listjob" << listJob << ", so not moving to currently-holding.";
384  }
385 }
386 
387 bool KDirListerCache::validUrl( const KDirLister *lister, const KUrl& url ) const
388 {
389  if ( !url.isValid() )
390  {
391  if ( lister->d->autoErrorHandling )
392  {
393  QString tmp = i18n("Malformed URL\n%1", url.prettyUrl() );
394  KMessageBox::error( lister->d->errorParent, tmp );
395  }
396  return false;
397  }
398 
399  if ( !KProtocolManager::supportsListing( url ) )
400  {
401  if ( lister->d->autoErrorHandling )
402  {
403  QString tmp = i18n("URL cannot be listed\n%1", url.prettyUrl() );
404  KMessageBox::error( lister->d->errorParent, tmp );
405  }
406  return false;
407  }
408 
409  return true;
410 }
411 
412 void KDirListerCache::stop( KDirLister *lister, bool silent )
413 {
414 #ifdef DEBUG_CACHE
415  //printDebug();
416 #endif
417  //kDebug(7004) << "lister:" << lister << "silent=" << silent;
418 
419  const KUrl::List urls = lister->d->lstDirs;
420  Q_FOREACH(const KUrl& url, urls) {
421  stopListingUrl(lister, url, silent);
422  }
423 
424 #if 0 // test code
425  QHash<QString,KDirListerCacheDirectoryData>::iterator dirit = directoryData.begin();
426  const QHash<QString,KDirListerCacheDirectoryData>::iterator dirend = directoryData.end();
427  for( ; dirit != dirend ; ++dirit ) {
428  KDirListerCacheDirectoryData& dirData = dirit.value();
429  if (dirData.listersCurrentlyListing.contains(lister)) {
430  kDebug(7004) << "ERROR: found lister" << lister << "in list - for" << dirit.key();
431  Q_ASSERT(false);
432  }
433  }
434 #endif
435 }
436 
437 void KDirListerCache::stopListingUrl(KDirLister *lister, const KUrl& _u, bool silent)
438 {
439  KUrl url(_u);
440  url.adjustPath( KUrl::RemoveTrailingSlash );
441  const QString urlStr = url.url();
442 
443  KDirLister::Private::CachedItemsJob* cachedItemsJob = lister->d->cachedItemsJobForUrl(url);
444  if (cachedItemsJob) {
445  if (silent) {
446  cachedItemsJob->setProperty("_kdlc_silent", true);
447  }
448  cachedItemsJob->kill(); // removes job from list, too
449  }
450 
451  // TODO: consider to stop all the "child jobs" of url as well
452  kDebug(7004) << lister << " url=" << url;
453 
454  QHash<QString,KDirListerCacheDirectoryData>::iterator dirit = directoryData.find(urlStr);
455  if (dirit == directoryData.end())
456  return;
457  KDirListerCacheDirectoryData& dirData = dirit.value();
458  if (dirData.listersCurrentlyListing.contains(lister)) {
459  //kDebug(7004) << " found lister" << lister << "in list - for" << urlStr;
460  if (dirData.listersCurrentlyListing.count() == 1) {
461  // This was the only dirlister interested in the list job -> kill the job
462  stopListJob(urlStr, silent);
463  } else {
464  // Leave the job running for the other dirlisters, just unsubscribe us.
465  dirData.listersCurrentlyListing.removeAll(lister);
466  if (!silent) {
467  emit lister->canceled();
468  emit lister->canceled(url);
469  }
470  }
471  }
472 }
473 
474 // Helper for stop() and stopListingUrl()
475 void KDirListerCache::stopListJob(const QString& url, bool silent)
476 {
477  // Old idea: if it's an update job, let's just leave the job running.
478  // After all, update jobs do run for "listersCurrentlyHolding",
479  // so there's no reason to kill them just because @p lister is now a holder.
480 
481  // However it could be a long-running non-local job (e.g. filenamesearch), which
482  // the user wants to abort, and which will never be used for updating...
483  // And in any case slotEntries/slotResult is not meant to be called by update jobs.
484  // So, change of plan, let's kill it after all, in a way that triggers slotResult/slotUpdateResult.
485 
486  KIO::ListJob *job = jobForUrl(url);
487  if (job) {
488  //kDebug() << "Killing list job" << job << "for" << url;
489  if (silent) {
490  job->setProperty("_kdlc_silent", true);
491  }
492  job->kill(KJob::EmitResult);
493  }
494 }
495 
496 void KDirListerCache::setAutoUpdate( KDirLister *lister, bool enable )
497 {
498  // IMPORTANT: this method does not check for the current autoUpdate state!
499 
500  for ( KUrl::List::const_iterator it = lister->d->lstDirs.constBegin();
501  it != lister->d->lstDirs.constEnd(); ++it ) {
502  DirItem* dirItem = itemsInUse.value((*it).url());
503  Q_ASSERT(dirItem);
504  if ( enable )
505  dirItem->incAutoUpdate();
506  else
507  dirItem->decAutoUpdate();
508  }
509 }
510 
511 void KDirListerCache::forgetDirs( KDirLister *lister )
512 {
513  //kDebug(7004) << lister;
514 
515  emit lister->clear();
516  // clear lister->d->lstDirs before calling forgetDirs(), so that
517  // it doesn't contain things that itemsInUse doesn't. When emitting
518  // the canceled signals, lstDirs must not contain anything that
519  // itemsInUse does not contain. (otherwise it might crash in findByName()).
520  const KUrl::List lstDirsCopy = lister->d->lstDirs;
521  lister->d->lstDirs.clear();
522 
523  //kDebug() << "Iterating over dirs" << lstDirsCopy;
524  for ( KUrl::List::const_iterator it = lstDirsCopy.begin();
525  it != lstDirsCopy.end(); ++it ) {
526  forgetDirs( lister, *it, false );
527  }
528 }
529 
530 static bool manually_mounted(const QString& path, const KMountPoint::List& possibleMountPoints)
531 {
532  KMountPoint::Ptr mp = possibleMountPoints.findByPath(path);
533  if (!mp) // not listed in fstab -> yes, manually mounted
534  return true;
535  const bool supermount = mp->mountType() == "supermount";
536  if (supermount) {
537  return true;
538  }
539  // noauto -> manually mounted. Otherwise, mounted at boot time, won't be unmounted any time soon hopefully.
540  return mp->mountOptions().contains("noauto");
541 }
542 
543 
544 void KDirListerCache::forgetDirs( KDirLister *lister, const KUrl& _url, bool notify )
545 {
546  //kDebug(7004) << lister << " _url: " << _url;
547 
548  KUrl url( _url );
549  url.adjustPath( KUrl::RemoveTrailingSlash );
550  const QString urlStr = url.url();
551 
552  DirectoryDataHash::iterator dit = directoryData.find(urlStr);
553  if (dit == directoryData.end())
554  return;
555  KDirListerCacheDirectoryData& dirData = *dit;
556  dirData.listersCurrentlyHolding.removeAll(lister);
557 
558  // This lister doesn't care for updates running in <url> anymore
559  KIO::ListJob *job = jobForUrl(urlStr);
560  if (job)
561  lister->d->jobDone(job);
562 
563  DirItem *item = itemsInUse.value(urlStr);
564  Q_ASSERT(item);
565  bool insertIntoCache = false;
566 
567  if ( dirData.listersCurrentlyHolding.isEmpty() && dirData.listersCurrentlyListing.isEmpty() ) {
568  // item not in use anymore -> move into cache if complete
569  directoryData.erase(dit);
570  itemsInUse.remove( urlStr );
571 
572  // this job is a running update which nobody cares about anymore
573  if ( job ) {
574  killJob( job );
575  kDebug(7004) << "Killing update job for " << urlStr;
576 
577  // Well, the user of KDirLister doesn't really care that we're stopping
578  // a background-running job from a previous URL (in listDir) -> commented out.
579  // stop() already emitted canceled.
580  //emit lister->canceled( url );
581  if ( lister->d->numJobs() == 0 ) {
582  lister->d->complete = true;
583  //emit lister->canceled();
584  }
585  }
586 
587  if ( notify ) {
588  lister->d->lstDirs.removeAll( url );
589  emit lister->clear( url );
590  }
591 
592  insertIntoCache = item->complete;
593  if (insertIntoCache) {
594  // TODO(afiestas): remove use of KMountPoint+manually_mounted and port to Solid:
595  // 1) find Volume for the local path "item->url.toLocalFile()" (which could be anywhere
596  // under the mount point) -- probably needs a new operator in libsolid query parser
597  // 2) [**] becomes: if (Drive is hotpluggable or Volume is removable) "set to dirty" else "keep watch"
598  const KMountPoint::List possibleMountPoints = KMountPoint::possibleMountPoints(KMountPoint::NeedMountOptions);
599 
600  // Should we forget the dir for good, or keep a watch on it?
601  // Generally keep a watch, except when it would prevent
602  // unmounting a removable device (#37780)
603  const bool isLocal = item->url.isLocalFile();
604  bool isManuallyMounted = false;
605  bool containsManuallyMounted = false;
606  if (isLocal) {
607  isManuallyMounted = manually_mounted( item->url.toLocalFile(), possibleMountPoints );
608  if ( !isManuallyMounted ) {
609  // Look for a manually-mounted directory inside
610  // If there's one, we can't keep a watch either, FAM would prevent unmounting the CDROM
611  // I hope this isn't too slow
612  KFileItemList::const_iterator kit = item->lstItems.constBegin();
613  KFileItemList::const_iterator kend = item->lstItems.constEnd();
614  for ( ; kit != kend && !containsManuallyMounted; ++kit )
615  if ( (*kit).isDir() && manually_mounted((*kit).url().toLocalFile(), possibleMountPoints) )
616  containsManuallyMounted = true;
617  }
618  }
619 
620  if ( isManuallyMounted || containsManuallyMounted ) // [**]
621  {
622  kDebug(7004) << "Not adding a watch on " << item->url << " because it " <<
623  ( isManuallyMounted ? "is manually mounted" : "contains a manually mounted subdir" );
624  item->complete = false; // set to "dirty"
625  } else {
626  item->incAutoUpdate(); // keep watch
627  item->watchedWhileInCache = true;
628  }
629  }
630  else
631  {
632  delete item;
633  item = 0;
634  }
635  }
636 
637  if ( item && lister->d->autoUpdate )
638  item->decAutoUpdate();
639 
640  // Inserting into QCache must be done last, since it might delete the item
641  if (item && insertIntoCache) {
642  kDebug(7004) << lister << "item moved into cache:" << url;
643  itemsCached.insert(urlStr, item);
644  }
645 }
646 
647 void KDirListerCache::updateDirectory( const KUrl& _dir )
648 {
649  kDebug(7004) << _dir;
650 
651  QString urlStr = _dir.url(KUrl::RemoveTrailingSlash);
652  if ( !checkUpdate( urlStr ) )
653  return;
654 
655  // A job can be running to
656  // - only list a new directory: the listers are in listersCurrentlyListing
657  // - only update a directory: the listers are in listersCurrentlyHolding
658  // - update a currently running listing: the listers are in both
659 
660  KDirListerCacheDirectoryData& dirData = directoryData[urlStr];
661  QList<KDirLister *> listers = dirData.listersCurrentlyListing;
662  QList<KDirLister *> holders = dirData.listersCurrentlyHolding;
663 
664  //kDebug(7004) << urlStr << "listers=" << listers << "holders=" << holders;
665 
666  // restart the job for _dir if it is running already
667  bool killed = false;
668  QWidget *window = 0;
669  KIO::ListJob *job = jobForUrl( urlStr );
670  if (job) {
671  window = job->ui()->window();
672 
673  killJob( job );
674  killed = true;
675 
676  foreach ( KDirLister *kdl, listers )
677  kdl->d->jobDone( job );
678 
679  foreach ( KDirLister *kdl, holders )
680  kdl->d->jobDone( job );
681  } else {
682  // Emit any cached items.
683  // updateDirectory() is about the diff compared to the cached items...
684  Q_FOREACH(KDirLister *kdl, listers) {
685  KDirLister::Private::CachedItemsJob* cachedItemsJob = kdl->d->cachedItemsJobForUrl(_dir);
686  if (cachedItemsJob) {
687  cachedItemsJob->setEmitCompleted(false);
688  cachedItemsJob->done(); // removes from cachedItemsJobs list
689  delete cachedItemsJob;
690  killed = true;
691  }
692  }
693  }
694  //kDebug(7004) << "Killed=" << killed;
695 
696  // we don't need to emit canceled signals since we only replaced the job,
697  // the listing is continuing.
698 
699  if (!(listers.isEmpty() || killed)) {
700  kWarning() << "The unexpected happened.";
701  kWarning() << "listers for" << _dir << "=" << listers;
702  kWarning() << "job=" << job;
703  Q_FOREACH(KDirLister *kdl, listers) {
704  kDebug() << "lister" << kdl << "m_cachedItemsJobs=" << kdl->d->m_cachedItemsJobs;
705  }
706 #ifndef NDEBUG
707  printDebug();
708 #endif
709  }
710  Q_ASSERT( listers.isEmpty() || killed );
711 
712  job = KIO::listDir( _dir, KIO::HideProgressInfo );
713  runningListJobs.insert( job, KIO::UDSEntryList() );
714 
715  connect( job, SIGNAL(entries(KIO::Job*,KIO::UDSEntryList)),
716  this, SLOT(slotUpdateEntries(KIO::Job*,KIO::UDSEntryList)) );
717  connect( job, SIGNAL(result(KJob*)),
718  this, SLOT(slotUpdateResult(KJob*)) );
719 
720  kDebug(7004) << "update started in" << _dir;
721 
722  foreach ( KDirLister *kdl, listers ) {
723  kdl->d->jobStarted( job );
724  }
725 
726  if ( !holders.isEmpty() ) {
727  if ( !killed ) {
728  bool first = true;
729  foreach ( KDirLister *kdl, holders ) {
730  kdl->d->jobStarted( job );
731  if ( first && kdl->d->window ) {
732  first = false;
733  job->ui()->setWindow( kdl->d->window );
734  }
735  emit kdl->started( _dir );
736  }
737  } else {
738  job->ui()->setWindow( window );
739 
740  foreach ( KDirLister *kdl, holders ) {
741  kdl->d->jobStarted( job );
742  }
743  }
744  }
745 }
746 
747 bool KDirListerCache::checkUpdate( const QString& _dir )
748 {
749  if ( !itemsInUse.contains(_dir) )
750  {
751  DirItem *item = itemsCached[_dir];
752  if ( item && item->complete )
753  {
754  // Stop watching items once they are only in the cache and not used anymore.
755  // We'll trigger an update when listing that dir again later.
756  item->complete = false;
757  item->watchedWhileInCache = false;
758  item->decAutoUpdate();
759  // Hmm, this debug output might include login/password from the _dir URL.
760  //kDebug(7004) << "directory " << _dir << " not in use, marked dirty.";
761  }
762  //else
763  //kDebug(7004) << "aborted, directory " << _dir << " not in cache.";
764 
765  return false;
766  }
767  else
768  return true;
769 }
770 
771 KFileItem KDirListerCache::itemForUrl( const KUrl& url ) const
772 {
773  KFileItem *item = findByUrl( 0, url );
774  if (item) {
775  return *item;
776  } else {
777  return KFileItem();
778  }
779 }
780 
781 KDirListerCache::DirItem *KDirListerCache::dirItemForUrl(const KUrl& dir) const
782 {
783  const QString urlStr = dir.url(KUrl::RemoveTrailingSlash);
784  DirItem *item = itemsInUse.value(urlStr);
785  if ( !item )
786  item = itemsCached[urlStr];
787  return item;
788 }
789 
790 KFileItemList *KDirListerCache::itemsForDir(const KUrl& dir) const
791 {
792  DirItem *item = dirItemForUrl(dir);
793  return item ? &item->lstItems : 0;
794 }
795 
796 KFileItem KDirListerCache::findByName( const KDirLister *lister, const QString& _name ) const
797 {
798  Q_ASSERT(lister);
799 
800  for (KUrl::List::const_iterator it = lister->d->lstDirs.constBegin();
801  it != lister->d->lstDirs.constEnd(); ++it) {
802  DirItem* dirItem = itemsInUse.value((*it).url());
803  Q_ASSERT(dirItem);
804  const KFileItem item = dirItem->lstItems.findByName(_name);
805  if (!item.isNull())
806  return item;
807  }
808 
809  return KFileItem();
810 }
811 
812 KFileItem *KDirListerCache::findByUrl( const KDirLister *lister, const KUrl& _u ) const
813 {
814  KUrl url(_u);
815  url.adjustPath(KUrl::RemoveTrailingSlash);
816 
817  KUrl parentDir(url);
818  parentDir.setPath( parentDir.directory() );
819 
820  DirItem* dirItem = dirItemForUrl(parentDir);
821  if (dirItem) {
822  // If lister is set, check that it contains this dir
823  if (!lister || lister->d->lstDirs.contains(parentDir)) {
824  KFileItemList::iterator it = dirItem->lstItems.begin();
825  const KFileItemList::iterator end = dirItem->lstItems.end();
826  for (; it != end ; ++it) {
827  if ((*it).url() == url) {
828  return &*it;
829  }
830  }
831  }
832  }
833 
834  // Maybe _u is a directory itself? (see KDirModelTest::testChmodDirectory)
835  // We check this last, though, we prefer returning a kfileitem with an actual
836  // name if possible (and we make it '.' for root items later).
837  dirItem = dirItemForUrl(url);
838  if (dirItem && !dirItem->rootItem.isNull() && dirItem->rootItem.url() == url) {
839  // If lister is set, check that it contains this dir
840  if (!lister || lister->d->lstDirs.contains(url)) {
841  return &dirItem->rootItem;
842  }
843  }
844 
845  return 0;
846 }
847 
848 void KDirListerCache::slotFilesAdded( const QString &dir /*url*/ ) // from KDirNotify signals
849 {
850  KUrl urlDir(dir);
851  kDebug(7004) << urlDir; // output urls, not qstrings, since they might contain a password
852  if (urlDir.isLocalFile()) {
853  Q_FOREACH(const QString& u, directoriesForCanonicalPath(urlDir.toLocalFile())) {
854  updateDirectory(KUrl(u));
855  }
856  } else {
857  updateDirectory(urlDir);
858  }
859 }
860 
861 void KDirListerCache::slotFilesRemoved( const QStringList &fileList ) // from KDirNotify signals
862 {
863  // TODO: handling of symlinks-to-directories isn't done here,
864  // because I'm not sure how to do it and keep the performance ok...
865  slotFilesRemoved(KUrl::List(fileList));
866 }
867 
868 void KDirListerCache::slotFilesRemoved(const KUrl::List& fileList)
869 {
870  //kDebug(7004) << fileList.count();
871  // Group notifications by parent dirs (usually there would be only one parent dir)
872  QMap<QString, KFileItemList> removedItemsByDir;
873  KUrl::List deletedSubdirs;
874 
875  for (KUrl::List::const_iterator it = fileList.begin(); it != fileList.end() ; ++it) {
876  const KUrl url(*it);
877  DirItem* dirItem = dirItemForUrl(url); // is it a listed directory?
878  if (dirItem) {
879  deletedSubdirs.append(url);
880  if (!dirItem->rootItem.isNull()) {
881  removedItemsByDir[url.url()].append(dirItem->rootItem);
882  }
883  }
884 
885  KUrl parentDir(url);
886  parentDir.setPath(parentDir.directory());
887  dirItem = dirItemForUrl(parentDir);
888  if (!dirItem)
889  continue;
890  for (KFileItemList::iterator fit = dirItem->lstItems.begin(), fend = dirItem->lstItems.end(); fit != fend ; ++fit) {
891  if ((*fit).url() == url) {
892  const KFileItem fileitem = *fit;
893  removedItemsByDir[parentDir.url()].append(fileitem);
894  // If we found a fileitem, we can test if it's a dir. If not, we'll go to deleteDir just in case.
895  if (fileitem.isNull() || fileitem.isDir()) {
896  deletedSubdirs.append(url);
897  }
898  dirItem->lstItems.erase(fit); // remove fileitem from list
899  break;
900  }
901  }
902  }
903 
904  QMap<QString, KFileItemList>::const_iterator rit = removedItemsByDir.constBegin();
905  for(; rit != removedItemsByDir.constEnd(); ++rit) {
906  // Tell the views about it before calling deleteDir.
907  // They might need the subdirs' file items (see the dirtree).
908  DirectoryDataHash::const_iterator dit = directoryData.constFind(rit.key());
909  if (dit != directoryData.constEnd()) {
910  itemsDeleted((*dit).listersCurrentlyHolding, rit.value());
911  }
912  }
913 
914  Q_FOREACH(const KUrl& url, deletedSubdirs) {
915  // in case of a dir, check if we have any known children, there's much to do in that case
916  // (stopping jobs, removing dirs from cache etc.)
917  deleteDir(url);
918  }
919 }
920 
921 void KDirListerCache::slotFilesChanged( const QStringList &fileList ) // from KDirNotify signals
922 {
923  //kDebug(7004) << fileList;
924  KUrl::List dirsToUpdate;
925  QStringList::const_iterator it = fileList.begin();
926  for (; it != fileList.end() ; ++it) {
927  KUrl url( *it );
928  KFileItem *fileitem = findByUrl(0, url);
929  if (!fileitem) {
930  kDebug(7004) << "item not found for" << url;
931  continue;
932  }
933  if (url.isLocalFile()) {
934  pendingUpdates.insert(url.toLocalFile()); // delegate the work to processPendingUpdates
935  } else {
936  pendingRemoteUpdates.insert(fileitem);
937  // For remote files, we won't be able to figure out the new information,
938  // we have to do a update (directory listing)
939  KUrl dir(url);
940  dir.setPath(dir.directory());
941  if (!dirsToUpdate.contains(dir))
942  dirsToUpdate.prepend(dir);
943  }
944  }
945 
946  KUrl::List::const_iterator itdir = dirsToUpdate.constBegin();
947  for (; itdir != dirsToUpdate.constEnd() ; ++itdir)
948  updateDirectory( *itdir );
949  // ## TODO problems with current jobs listing/updating that dir
950  // ( see kde-2.2.2's kdirlister )
951 
952  processPendingUpdates();
953 }
954 
955 void KDirListerCache::slotFileRenamed( const QString &_src, const QString &_dst ) // from KDirNotify signals
956 {
957  KUrl src( _src );
958  KUrl dst( _dst );
959  kDebug(7004) << src << "->" << dst;
960 #ifdef DEBUG_CACHE
961  printDebug();
962 #endif
963 
964  KUrl oldurl(src);
965  oldurl.adjustPath( KUrl::RemoveTrailingSlash );
966  KFileItem *fileitem = findByUrl(0, oldurl);
967  if (!fileitem) {
968  kDebug(7004) << "Item not found:" << oldurl;
969  return;
970  }
971 
972  const KFileItem oldItem = *fileitem;
973 
974  // Dest already exists? Was overwritten then (testcase: #151851)
975  // We better emit it as deleted -before- doing the renaming, otherwise
976  // the "update" mechanism will emit the old one as deleted and
977  // kdirmodel will delete the new (renamed) one!
978  KFileItem* existingDestItem = findByUrl(0, dst);
979  if (existingDestItem) {
980  //kDebug() << dst << "already existed, let's delete it";
981  slotFilesRemoved(dst);
982  }
983 
984  // If the item had a UDS_URL as well as UDS_NAME set, the user probably wants
985  // to be updating the name only (since they can't see the URL).
986  // Check to see if a URL exists, and if so, if only the file part has changed,
987  // only update the name and not the underlying URL.
988  bool nameOnly = !fileitem->entry().stringValue( KIO::UDSEntry::UDS_URL ).isEmpty();
989  nameOnly &= src.directory( KUrl::IgnoreTrailingSlash | KUrl::AppendTrailingSlash ) ==
990  dst.directory( KUrl::IgnoreTrailingSlash | KUrl::AppendTrailingSlash );
991 
992  if (!nameOnly && fileitem->isDir()) {
993  renameDir( src, dst );
994  // #172945 - if the fileitem was the root item of a DirItem that was just removed from the cache,
995  // then it's a dangling pointer now...
996  fileitem = findByUrl(0, oldurl);
997  if (!fileitem) //deleted from cache altogether, #188807
998  return;
999  }
1000 
1001  // Now update the KFileItem representing that file or dir (not exclusive with the above!)
1002  if (!oldItem.isLocalFile() && !oldItem.localPath().isEmpty()) { // it uses UDS_LOCAL_PATH? ouch, needs an update then
1003  slotFilesChanged( QStringList() << src.url() );
1004  } else {
1005  if( nameOnly )
1006  fileitem->setName( dst.fileName() );
1007  else
1008  fileitem->setUrl( dst );
1009  fileitem->refreshMimeType();
1010  fileitem->determineMimeType();
1011  QSet<KDirLister*> listers = emitRefreshItem( oldItem, *fileitem );
1012  Q_FOREACH(KDirLister * kdl, listers) {
1013  kdl->d->emitItems();
1014  }
1015  }
1016 
1017 #ifdef DEBUG_CACHE
1018  printDebug();
1019 #endif
1020 }
1021 
1022 QSet<KDirLister*> KDirListerCache::emitRefreshItem(const KFileItem& oldItem, const KFileItem& fileitem)
1023 {
1024  //kDebug(7004) << "old:" << oldItem.name() << oldItem.url()
1025  // << "new:" << fileitem.name() << fileitem.url();
1026  // Look whether this item was shown in any view, i.e. held by any dirlister
1027  KUrl parentDir( oldItem.url() );
1028  parentDir.setPath( parentDir.directory() );
1029  const QString parentDirURL = parentDir.url();
1030  DirectoryDataHash::iterator dit = directoryData.find(parentDirURL);
1031  QList<KDirLister *> listers;
1032  // Also look in listersCurrentlyListing, in case the user manages to rename during a listing
1033  if (dit != directoryData.end())
1034  listers += (*dit).listersCurrentlyHolding + (*dit).listersCurrentlyListing;
1035  if (oldItem.isDir()) {
1036  // For a directory, look for dirlisters where it's the root item.
1037  dit = directoryData.find(oldItem.url().url());
1038  if (dit != directoryData.end())
1039  listers += (*dit).listersCurrentlyHolding + (*dit).listersCurrentlyListing;
1040  }
1041  QSet<KDirLister*> listersToRefresh;
1042  Q_FOREACH(KDirLister *kdl, listers) {
1043  // For a directory, look for dirlisters where it's the root item.
1044  KUrl directoryUrl(oldItem.url());
1045  if (oldItem.isDir() && kdl->d->rootFileItem == oldItem) {
1046  const KFileItem oldRootItem = kdl->d->rootFileItem;
1047  kdl->d->rootFileItem = fileitem;
1048  kdl->d->addRefreshItem(directoryUrl, oldRootItem, fileitem);
1049  } else {
1050  directoryUrl.setPath(directoryUrl.directory());
1051  kdl->d->addRefreshItem(directoryUrl, oldItem, fileitem);
1052  }
1053  listersToRefresh.insert(kdl);
1054  }
1055  return listersToRefresh;
1056 }
1057 
1058 QStringList KDirListerCache::directoriesForCanonicalPath(const QString& dir) const
1059 {
1060  QStringList dirs;
1061  dirs << dir;
1062  dirs << canonicalUrls.value(dir).toSet().toList(); /* make unique; there are faster ways, but this is really small anyway */
1063 
1064  if (dirs.count() > 1)
1065  kDebug() << dir << "known as" << dirs;
1066 
1067  return dirs;
1068 }
1069 
1070 // private slots
1071 
1072 // Called by KDirWatch - usually when a dir we're watching has been modified,
1073 // but it can also be called for a file.
1074 void KDirListerCache::slotFileDirty( const QString& path )
1075 {
1076  kDebug(7004) << path;
1077  // File or dir?
1078  KDE_struct_stat buff;
1079  if ( KDE::stat( path, &buff ) != 0 )
1080  return; // error
1081  const bool isDir = S_ISDIR(buff.st_mode);
1082  KUrl url(path);
1083  url.adjustPath(KUrl::RemoveTrailingSlash);
1084  if (isDir) {
1085  Q_FOREACH(const QString& dir, directoriesForCanonicalPath(url.toLocalFile())) {
1086  handleDirDirty(dir);
1087  }
1088  } else {
1089  Q_FOREACH(const QString& dir, directoriesForCanonicalPath(url.directory())) {
1090  KUrl aliasUrl(dir);
1091  aliasUrl.addPath(url.fileName());
1092  handleFileDirty(aliasUrl);
1093  }
1094  }
1095 }
1096 
1097 // Called by slotFileDirty
1098 void KDirListerCache::handleDirDirty(const KUrl& url)
1099 {
1100  // A dir: launch an update job if anyone cares about it
1101 
1102  // This also means we can forget about pending updates to individual files in that dir
1103  const QString dirPath = url.toLocalFile(KUrl::AddTrailingSlash);
1104  QMutableSetIterator<QString> pendingIt(pendingUpdates);
1105  while (pendingIt.hasNext()) {
1106  const QString updPath = pendingIt.next();
1107  //kDebug(7004) << "had pending update" << updPath;
1108  if (updPath.startsWith(dirPath) &&
1109  updPath.indexOf('/', dirPath.length()) == -1) { // direct child item
1110  kDebug(7004) << "forgetting about individual update to" << updPath;
1111  pendingIt.remove();
1112  }
1113  }
1114 
1115  updateDirectory(url);
1116 }
1117 
1118 // Called by slotFileDirty
1119 void KDirListerCache::handleFileDirty(const KUrl& url)
1120 {
1121  // A file: do we know about it already?
1122  KFileItem* existingItem = findByUrl(0, url);
1123  if (!existingItem) {
1124  // No - update the parent dir then
1125  KUrl dir(url);
1126  dir.setPath(url.directory());
1127  updateDirectory(dir);
1128  } else {
1129  // A known file: delay updating it, FAM is flooding us with events
1130  const QString filePath = url.toLocalFile();
1131  if (!pendingUpdates.contains(filePath)) {
1132  KUrl dir(url);
1133  dir.setPath(dir.directory());
1134  if (checkUpdate(dir.url())) {
1135  pendingUpdates.insert(filePath);
1136  if (!pendingUpdateTimer.isActive())
1137  pendingUpdateTimer.start(500);
1138  }
1139  }
1140  }
1141 }
1142 
1143 void KDirListerCache::slotFileCreated( const QString& path ) // from KDirWatch
1144 {
1145  kDebug(7004) << path;
1146  // XXX: how to avoid a complete rescan here?
1147  // We'd need to stat that one file separately and refresh the item(s) for it.
1148  KUrl fileUrl(path);
1149  slotFilesAdded(fileUrl.directory());
1150 }
1151 
1152 void KDirListerCache::slotFileDeleted( const QString& path ) // from KDirWatch
1153 {
1154  kDebug(7004) << path;
1155  KUrl u( path );
1156  QStringList fileUrls;
1157  Q_FOREACH(KUrl url, directoriesForCanonicalPath(u.directory())) {
1158  url.addPath(u.fileName());
1159  fileUrls << url.url();
1160  }
1161  slotFilesRemoved(fileUrls);
1162 }
1163 
1164 void KDirListerCache::slotEntries( KIO::Job *job, const KIO::UDSEntryList &entries )
1165 {
1166  KUrl url(joburl( static_cast<KIO::ListJob *>(job) ));
1167  url.adjustPath(KUrl::RemoveTrailingSlash);
1168  QString urlStr = url.url();
1169 
1170  //kDebug(7004) << "new entries for " << url;
1171 
1172  DirItem *dir = itemsInUse.value(urlStr);
1173  if (!dir) {
1174  kError(7004) << "Internal error: job is listing" << url << "but itemsInUse only knows about" << itemsInUse.keys();
1175  Q_ASSERT( dir );
1176  return;
1177  }
1178 
1179  DirectoryDataHash::iterator dit = directoryData.find(urlStr);
1180  if (dit == directoryData.end()) {
1181  kError(7004) << "Internal error: job is listing" << url << "but directoryData doesn't know about that url, only about:" << directoryData.keys();
1182  Q_ASSERT(dit != directoryData.end());
1183  return;
1184  }
1185  KDirListerCacheDirectoryData& dirData = *dit;
1186  if (dirData.listersCurrentlyListing.isEmpty()) {
1187  kError(7004) << "Internal error: job is listing" << url << "but directoryData says no listers are currently listing " << urlStr;
1188 #ifndef NDEBUG
1189  printDebug();
1190 #endif
1191  Q_ASSERT( !dirData.listersCurrentlyListing.isEmpty() );
1192  return;
1193  }
1194 
1195  // check if anyone wants the mimetypes immediately
1196  bool delayedMimeTypes = true;
1197  foreach ( KDirLister *kdl, dirData.listersCurrentlyListing )
1198  delayedMimeTypes &= kdl->d->delayedMimeTypes;
1199 
1200  KIO::UDSEntryList::const_iterator it = entries.begin();
1201  const KIO::UDSEntryList::const_iterator end = entries.end();
1202  for ( ; it != end; ++it )
1203  {
1204  const QString name = (*it).stringValue( KIO::UDSEntry::UDS_NAME );
1205 
1206  Q_ASSERT( !name.isEmpty() );
1207  if ( name.isEmpty() )
1208  continue;
1209 
1210  if ( name == "." )
1211  {
1212  Q_ASSERT( dir->rootItem.isNull() );
1213  // Try to reuse an existing KFileItem (if we listed the parent dir)
1214  // rather than creating a new one. There are many reasons:
1215  // 1) renames and permission changes to the item would have to emit the signals
1216  // twice, otherwise, so that both views manage to recognize the item.
1217  // 2) with kio_ftp we can only know that something is a symlink when
1218  // listing the parent, so prefer that item, which has more info.
1219  // Note that it gives a funky name() to the root item, rather than "." ;)
1220  dir->rootItem = itemForUrl(url);
1221  if (dir->rootItem.isNull())
1222  dir->rootItem = KFileItem( *it, url, delayedMimeTypes, true );
1223 
1224  foreach ( KDirLister *kdl, dirData.listersCurrentlyListing )
1225  if ( kdl->d->rootFileItem.isNull() && kdl->d->url == url )
1226  kdl->d->rootFileItem = dir->rootItem;
1227  }
1228  else if ( name != ".." )
1229  {
1230  KFileItem item( *it, url, delayedMimeTypes, true );
1231 
1232  //kDebug(7004)<< "Adding item: " << item.url();
1233  dir->lstItems.append( item );
1234 
1235  foreach ( KDirLister *kdl, dirData.listersCurrentlyListing )
1236  kdl->d->addNewItem(url, item);
1237  }
1238  }
1239 
1240  foreach ( KDirLister *kdl, dirData.listersCurrentlyListing )
1241  kdl->d->emitItems();
1242 }
1243 
1244 void KDirListerCache::slotResult( KJob *j )
1245 {
1246 #ifdef DEBUG_CACHE
1247  //printDebug();
1248 #endif
1249 
1250  Q_ASSERT( j );
1251  KIO::ListJob *job = static_cast<KIO::ListJob *>( j );
1252  runningListJobs.remove( job );
1253 
1254  KUrl jobUrl(joburl( job ));
1255  jobUrl.adjustPath(KUrl::RemoveTrailingSlash); // need remove trailing slashes again, in case of redirections
1256  QString jobUrlStr = jobUrl.url();
1257 
1258  kDebug(7004) << "finished listing" << jobUrl;
1259 
1260  DirectoryDataHash::iterator dit = directoryData.find(jobUrlStr);
1261  if (dit == directoryData.end()) {
1262  kError() << "Nothing found in directoryData for URL" << jobUrlStr;
1263 #ifndef NDEBUG
1264  printDebug();
1265 #endif
1266  Q_ASSERT(dit != directoryData.end());
1267  return;
1268  }
1269  KDirListerCacheDirectoryData& dirData = *dit;
1270  if ( dirData.listersCurrentlyListing.isEmpty() ) {
1271  kError() << "OOOOPS, nothing in directoryData.listersCurrentlyListing for" << jobUrlStr;
1272  // We're about to assert; dump the current state...
1273 #ifndef NDEBUG
1274  printDebug();
1275 #endif
1276  Q_ASSERT( !dirData.listersCurrentlyListing.isEmpty() );
1277  }
1278  QList<KDirLister *> listers = dirData.listersCurrentlyListing;
1279 
1280  // move all listers to the holding list, do it before emitting
1281  // the signals to make sure it exists in KDirListerCache in case someone
1282  // calls listDir during the signal emission
1283  Q_ASSERT( dirData.listersCurrentlyHolding.isEmpty() );
1284  dirData.moveListersWithoutCachedItemsJob(jobUrl);
1285 
1286  if ( job->error() )
1287  {
1288  foreach ( KDirLister *kdl, listers )
1289  {
1290  kdl->d->jobDone( job );
1291  if (job->error() != KJob::KilledJobError) {
1292  kdl->handleError( job );
1293  }
1294  const bool silent = job->property("_kdlc_silent").toBool();
1295  if (!silent) {
1296  emit kdl->canceled( jobUrl );
1297  }
1298 
1299  if (kdl->d->numJobs() == 0) {
1300  kdl->d->complete = true;
1301  if (!silent) {
1302  emit kdl->canceled();
1303  }
1304  }
1305  }
1306  }
1307  else
1308  {
1309  DirItem *dir = itemsInUse.value(jobUrlStr);
1310  Q_ASSERT( dir );
1311  dir->complete = true;
1312 
1313  foreach ( KDirLister* kdl, listers )
1314  {
1315  kdl->d->jobDone( job );
1316  emit kdl->completed( jobUrl );
1317  if ( kdl->d->numJobs() == 0 )
1318  {
1319  kdl->d->complete = true;
1320  emit kdl->completed();
1321  }
1322  }
1323  }
1324 
1325  // TODO: hmm, if there was an error and job is a parent of one or more
1326  // of the pending urls we should cancel it/them as well
1327  processPendingUpdates();
1328 
1329 #ifdef DEBUG_CACHE
1330  printDebug();
1331 #endif
1332 }
1333 
1334 void KDirListerCache::slotRedirection( KIO::Job *j, const KUrl& url )
1335 {
1336  Q_ASSERT( j );
1337  KIO::ListJob *job = static_cast<KIO::ListJob *>( j );
1338 
1339  KUrl oldUrl(job->url()); // here we really need the old url!
1340  KUrl newUrl(url);
1341 
1342  // strip trailing slashes
1343  oldUrl.adjustPath(KUrl::RemoveTrailingSlash);
1344  newUrl.adjustPath(KUrl::RemoveTrailingSlash);
1345 
1346  if ( oldUrl == newUrl ) {
1347  kDebug(7004) << "New redirection url same as old, giving up.";
1348  return;
1349  } else if (newUrl.isEmpty()) {
1350  kDebug(7004) << "New redirection url is empty, giving up.";
1351  return;
1352  }
1353 
1354  const QString oldUrlStr = oldUrl.url();
1355  const QString newUrlStr = newUrl.url();
1356 
1357  kDebug(7004) << oldUrl << "->" << newUrl;
1358 
1359 #ifdef DEBUG_CACHE
1360  // Can't do that here. KDirListerCache::joburl() will use the new url already,
1361  // while our data structures haven't been updated yet -> assert fail.
1362  //printDebug();
1363 #endif
1364 
1365  // I don't think there can be dirItems that are children of oldUrl.
1366  // Am I wrong here? And even if so, we don't need to delete them, right?
1367  // DF: redirection happens before listDir emits any item. Makes little sense otherwise.
1368 
1369  // oldUrl cannot be in itemsCached because only completed items are moved there
1370  DirItem *dir = itemsInUse.take(oldUrlStr);
1371  Q_ASSERT( dir );
1372 
1373  DirectoryDataHash::iterator dit = directoryData.find(oldUrlStr);
1374  Q_ASSERT(dit != directoryData.end());
1375  KDirListerCacheDirectoryData oldDirData = *dit;
1376  directoryData.erase(dit);
1377  Q_ASSERT( !oldDirData.listersCurrentlyListing.isEmpty() );
1378  const QList<KDirLister *> listers = oldDirData.listersCurrentlyListing;
1379  Q_ASSERT( !listers.isEmpty() );
1380 
1381  foreach ( KDirLister *kdl, listers ) {
1382  kdl->d->redirect(oldUrlStr, newUrl, false /*clear items*/);
1383  }
1384 
1385  // when a lister was stopped before the job emits the redirection signal, the old url will
1386  // also be in listersCurrentlyHolding
1387  const QList<KDirLister *> holders = oldDirData.listersCurrentlyHolding;
1388  foreach ( KDirLister *kdl, holders ) {
1389  kdl->d->jobStarted( job );
1390  // do it like when starting a new list-job that will redirect later
1391  // TODO: maybe don't emit started if there's an update running for newUrl already?
1392  emit kdl->started( oldUrl );
1393 
1394  kdl->d->redirect(oldUrl, newUrl, false /*clear items*/);
1395  }
1396 
1397  DirItem *newDir = itemsInUse.value(newUrlStr);
1398  if ( newDir ) {
1399  kDebug(7004) << newUrl << "already in use";
1400 
1401  // only in this case there can newUrl already be in listersCurrentlyListing or listersCurrentlyHolding
1402  delete dir;
1403 
1404  // get the job if one's running for newUrl already (can be a list-job or an update-job), but
1405  // do not return this 'job', which would happen because of the use of redirectionURL()
1406  KIO::ListJob *oldJob = jobForUrl( newUrlStr, job );
1407 
1408  // listers of newUrl with oldJob: forget about the oldJob and use the already running one
1409  // which will be converted to an updateJob
1410  KDirListerCacheDirectoryData& newDirData = directoryData[newUrlStr];
1411 
1412  QList<KDirLister *>& curListers = newDirData.listersCurrentlyListing;
1413  if ( !curListers.isEmpty() ) {
1414  kDebug(7004) << "and it is currently listed";
1415 
1416  Q_ASSERT( oldJob ); // ?!
1417 
1418  foreach ( KDirLister *kdl, curListers ) { // listers of newUrl
1419  kdl->d->jobDone( oldJob );
1420 
1421  kdl->d->jobStarted( job );
1422  kdl->d->connectJob( job );
1423  }
1424 
1425  // append listers of oldUrl with newJob to listers of newUrl with oldJob
1426  foreach ( KDirLister *kdl, listers )
1427  curListers.append( kdl );
1428  } else {
1429  curListers = listers;
1430  }
1431 
1432  if ( oldJob ) // kill the old job, be it a list-job or an update-job
1433  killJob( oldJob );
1434 
1435  // holders of newUrl: use the already running job which will be converted to an updateJob
1436  QList<KDirLister *>& curHolders = newDirData.listersCurrentlyHolding;
1437  if ( !curHolders.isEmpty() ) {
1438  kDebug(7004) << "and it is currently held.";
1439 
1440  foreach ( KDirLister *kdl, curHolders ) { // holders of newUrl
1441  kdl->d->jobStarted( job );
1442  emit kdl->started( newUrl );
1443  }
1444 
1445  // append holders of oldUrl to holders of newUrl
1446  foreach ( KDirLister *kdl, holders )
1447  curHolders.append( kdl );
1448  } else {
1449  curHolders = holders;
1450  }
1451 
1452 
1453  // emit old items: listers, holders. NOT: newUrlListers/newUrlHolders, they already have them listed
1454  // TODO: make this a separate method?
1455  foreach ( KDirLister *kdl, listers + holders ) {
1456  if ( kdl->d->rootFileItem.isNull() && kdl->d->url == newUrl )
1457  kdl->d->rootFileItem = newDir->rootItem;
1458 
1459  kdl->d->addNewItems(newUrl, newDir->lstItems);
1460  kdl->d->emitItems();
1461  }
1462  } else if ( (newDir = itemsCached.take( newUrlStr )) ) {
1463  kDebug(7004) << newUrl << "is unused, but already in the cache.";
1464 
1465  delete dir;
1466  itemsInUse.insert( newUrlStr, newDir );
1467  KDirListerCacheDirectoryData& newDirData = directoryData[newUrlStr];
1468  newDirData.listersCurrentlyListing = listers;
1469  newDirData.listersCurrentlyHolding = holders;
1470 
1471  // emit old items: listers, holders
1472  foreach ( KDirLister *kdl, listers + holders ) {
1473  if ( kdl->d->rootFileItem.isNull() && kdl->d->url == newUrl )
1474  kdl->d->rootFileItem = newDir->rootItem;
1475 
1476  kdl->d->addNewItems(newUrl, newDir->lstItems);
1477  kdl->d->emitItems();
1478  }
1479  } else {
1480  kDebug(7004) << newUrl << "has not been listed yet.";
1481 
1482  dir->rootItem = KFileItem();
1483  dir->lstItems.clear();
1484  dir->redirect( newUrl );
1485  itemsInUse.insert( newUrlStr, dir );
1486  KDirListerCacheDirectoryData& newDirData = directoryData[newUrlStr];
1487  newDirData.listersCurrentlyListing = listers;
1488  newDirData.listersCurrentlyHolding = holders;
1489 
1490  if ( holders.isEmpty() ) {
1491 #ifdef DEBUG_CACHE
1492  printDebug();
1493 #endif
1494  return; // only in this case the job doesn't need to be converted,
1495  }
1496  }
1497 
1498  // make the job an update job
1499  job->disconnect( this );
1500 
1501  connect( job, SIGNAL(entries(KIO::Job*,KIO::UDSEntryList)),
1502  this, SLOT(slotUpdateEntries(KIO::Job*,KIO::UDSEntryList)) );
1503  connect( job, SIGNAL(result(KJob*)),
1504  this, SLOT(slotUpdateResult(KJob*)) );
1505 
1506  // FIXME: autoUpdate-Counts!!
1507 
1508 #ifdef DEBUG_CACHE
1509  printDebug();
1510 #endif
1511 }
1512 
1513 struct KDirListerCache::ItemInUseChange
1514 {
1515  ItemInUseChange(const QString& old, const QString& newU, DirItem* di)
1516  : oldUrl(old), newUrl(newU), dirItem(di) {}
1517  QString oldUrl;
1518  QString newUrl;
1519  DirItem* dirItem;
1520 };
1521 
1522 void KDirListerCache::renameDir( const KUrl &oldUrl, const KUrl &newUrl )
1523 {
1524  kDebug(7004) << oldUrl << "->" << newUrl;
1525  const QString oldUrlStr = oldUrl.url(KUrl::RemoveTrailingSlash);
1526  const QString newUrlStr = newUrl.url(KUrl::RemoveTrailingSlash);
1527 
1528  // Not enough. Also need to look at any child dir, even sub-sub-sub-dir.
1529  //DirItem *dir = itemsInUse.take( oldUrlStr );
1530  //emitRedirections( oldUrl, url );
1531 
1532  QLinkedList<ItemInUseChange> itemsToChange;
1533  QSet<KDirLister *> listers;
1534 
1535  // Look at all dirs being listed/shown
1536  QHash<QString, DirItem *>::iterator itu = itemsInUse.begin();
1537  const QHash<QString, DirItem *>::iterator ituend = itemsInUse.end();
1538  for (; itu != ituend ; ++itu) {
1539  DirItem *dir = itu.value();
1540  KUrl oldDirUrl ( itu.key() );
1541  //kDebug(7004) << "itemInUse:" << oldDirUrl;
1542  // Check if this dir is oldUrl, or a subfolder of it
1543  if ( oldUrl.isParentOf( oldDirUrl ) ) {
1544  // TODO should use KUrl::cleanpath like isParentOf does
1545  QString relPath = oldDirUrl.path().mid( oldUrl.path().length() );
1546 
1547  KUrl newDirUrl( newUrl ); // take new base
1548  if ( !relPath.isEmpty() )
1549  newDirUrl.addPath( relPath ); // add unchanged relative path
1550  //kDebug(7004) << "new url=" << newDirUrl;
1551 
1552  // Update URL in dir item and in itemsInUse
1553  dir->redirect( newDirUrl );
1554 
1555  itemsToChange.append(ItemInUseChange(oldDirUrl.url(KUrl::RemoveTrailingSlash),
1556  newDirUrl.url(KUrl::RemoveTrailingSlash),
1557  dir));
1558  // Rename all items under that dir
1559 
1560  for ( KFileItemList::iterator kit = dir->lstItems.begin(), kend = dir->lstItems.end();
1561  kit != kend ; ++kit )
1562  {
1563  const KFileItem oldItem = *kit;
1564 
1565  const KUrl oldItemUrl ((*kit).url());
1566  const QString oldItemUrlStr( oldItemUrl.url(KUrl::RemoveTrailingSlash) );
1567  KUrl newItemUrl( oldItemUrl );
1568  newItemUrl.setPath( newDirUrl.path() );
1569  newItemUrl.addPath( oldItemUrl.fileName() );
1570  kDebug(7004) << "renaming" << oldItemUrl << "to" << newItemUrl;
1571  (*kit).setUrl(newItemUrl);
1572 
1573  listers |= emitRefreshItem(oldItem, *kit);
1574  }
1575  emitRedirections( oldDirUrl, newDirUrl );
1576  }
1577  }
1578 
1579  Q_FOREACH(KDirLister * kdl, listers) {
1580  kdl->d->emitItems();
1581  }
1582 
1583  // Do the changes to itemsInUse out of the loop to avoid messing up iterators,
1584  // and so that emitRefreshItem can find the stuff in the hash.
1585  foreach(const ItemInUseChange& i, itemsToChange) {
1586  itemsInUse.remove(i.oldUrl);
1587  itemsInUse.insert(i.newUrl, i.dirItem);
1588  }
1589 
1590  // Is oldUrl a directory in the cache?
1591  // Remove any child of oldUrl from the cache - even if the renamed dir itself isn't in it!
1592  removeDirFromCache( oldUrl );
1593  // TODO rename, instead.
1594 }
1595 
1596 // helper for renameDir, not used for redirections from KIO::listDir().
1597 void KDirListerCache::emitRedirections( const KUrl &oldUrl, const KUrl &newUrl )
1598 {
1599  kDebug(7004) << oldUrl << "->" << newUrl;
1600  const QString oldUrlStr = oldUrl.url(KUrl::RemoveTrailingSlash);
1601  const QString newUrlStr = newUrl.url(KUrl::RemoveTrailingSlash);
1602 
1603  KIO::ListJob *job = jobForUrl( oldUrlStr );
1604  if ( job )
1605  killJob( job );
1606 
1607  // Check if we were listing this dir. Need to abort and restart with new name in that case.
1608  DirectoryDataHash::iterator dit = directoryData.find(oldUrlStr);
1609  if ( dit == directoryData.end() )
1610  return;
1611  const QList<KDirLister *> listers = (*dit).listersCurrentlyListing;
1612  const QList<KDirLister *> holders = (*dit).listersCurrentlyHolding;
1613 
1614  KDirListerCacheDirectoryData& newDirData = directoryData[newUrlStr];
1615 
1616  // Tell the world that the job listing the old url is dead.
1617  foreach ( KDirLister *kdl, listers ) {
1618  if ( job )
1619  kdl->d->jobDone( job );
1620 
1621  emit kdl->canceled( oldUrl );
1622  }
1623  newDirData.listersCurrentlyListing += listers;
1624 
1625  // Check if we are currently displaying this directory (odds opposite wrt above)
1626  foreach ( KDirLister *kdl, holders ) {
1627  if ( job )
1628  kdl->d->jobDone( job );
1629  }
1630  newDirData.listersCurrentlyHolding += holders;
1631  directoryData.erase(dit);
1632 
1633  if ( !listers.isEmpty() ) {
1634  updateDirectory( newUrl );
1635 
1636  // Tell the world about the new url
1637  foreach ( KDirLister *kdl, listers )
1638  emit kdl->started( newUrl );
1639  }
1640 
1641  // And notify the dirlisters of the redirection
1642  foreach ( KDirLister *kdl, holders ) {
1643  kdl->d->redirect(oldUrl, newUrl, true /*keep items*/);
1644  }
1645 }
1646 
1647 void KDirListerCache::removeDirFromCache( const KUrl& dir )
1648 {
1649  kDebug(7004) << dir;
1650  const QList<QString> cachedDirs = itemsCached.keys(); // seems slow, but there's no qcache iterator...
1651  foreach(const QString& cachedDir, cachedDirs) {
1652  if ( dir.isParentOf( KUrl( cachedDir ) ) )
1653  itemsCached.remove( cachedDir );
1654  }
1655 }
1656 
1657 void KDirListerCache::slotUpdateEntries( KIO::Job* job, const KIO::UDSEntryList& list )
1658 {
1659  runningListJobs[static_cast<KIO::ListJob*>(job)] += list;
1660 }
1661 
1662 void KDirListerCache::slotUpdateResult( KJob * j )
1663 {
1664  Q_ASSERT( j );
1665  KIO::ListJob *job = static_cast<KIO::ListJob *>( j );
1666 
1667  KUrl jobUrl (joburl( job ));
1668  jobUrl.adjustPath(KUrl::RemoveTrailingSlash); // need remove trailing slashes again, in case of redirections
1669  QString jobUrlStr (jobUrl.url());
1670 
1671  kDebug(7004) << "finished update" << jobUrl;
1672 
1673  KDirListerCacheDirectoryData& dirData = directoryData[jobUrlStr];
1674  // Collect the dirlisters which were listing the URL using that ListJob
1675  // plus those that were already holding that URL - they all get updated.
1676  dirData.moveListersWithoutCachedItemsJob(jobUrl);
1677  QList<KDirLister *> listers = dirData.listersCurrentlyHolding;
1678  listers += dirData.listersCurrentlyListing;
1679 
1680  // once we are updating dirs that are only in the cache this will fail!
1681  Q_ASSERT( !listers.isEmpty() );
1682 
1683  if ( job->error() ) {
1684  foreach ( KDirLister* kdl, listers ) {
1685  kdl->d->jobDone( job );
1686 
1687  //don't bother the user
1688  //kdl->handleError( job );
1689 
1690  const bool silent = job->property("_kdlc_silent").toBool();
1691  if (!silent) {
1692  emit kdl->canceled( jobUrl );
1693  }
1694  if ( kdl->d->numJobs() == 0 ) {
1695  kdl->d->complete = true;
1696  if (!silent) {
1697  emit kdl->canceled();
1698  }
1699  }
1700  }
1701 
1702  runningListJobs.remove( job );
1703 
1704  // TODO: if job is a parent of one or more
1705  // of the pending urls we should cancel them
1706  processPendingUpdates();
1707  return;
1708  }
1709 
1710  DirItem *dir = itemsInUse.value(jobUrlStr, 0);
1711  if (!dir) {
1712  kError(7004) << "Internal error: itemsInUse did not contain" << jobUrlStr;
1713 #ifndef NDEBUG
1714  printDebug();
1715 #endif
1716  Q_ASSERT(dir);
1717  } else {
1718  dir->complete = true;
1719  }
1720 
1721  // check if anyone wants the mimetypes immediately
1722  bool delayedMimeTypes = true;
1723  foreach ( KDirLister *kdl, listers )
1724  delayedMimeTypes &= kdl->d->delayedMimeTypes;
1725 
1726  QHash<QString, KFileItem*> fileItems; // fileName -> KFileItem*
1727 
1728  // Unmark all items in url
1729  for ( KFileItemList::iterator kit = dir->lstItems.begin(), kend = dir->lstItems.end() ; kit != kend ; ++kit )
1730  {
1731  (*kit).unmark();
1732  fileItems.insert( (*kit).name(), &*kit );
1733  }
1734 
1735  const KIO::UDSEntryList& buf = runningListJobs.value( job );
1736  KIO::UDSEntryList::const_iterator it = buf.constBegin();
1737  const KIO::UDSEntryList::const_iterator end = buf.constEnd();
1738  for ( ; it != end; ++it )
1739  {
1740  // Form the complete url
1741  KFileItem item( *it, jobUrl, delayedMimeTypes, true );
1742 
1743  const QString name = item.name();
1744  Q_ASSERT( !name.isEmpty() );
1745 
1746  // we duplicate the check for dotdot here, to avoid iterating over
1747  // all items again and checking in matchesFilter() that way.
1748  if ( name.isEmpty() || name == ".." )
1749  continue;
1750 
1751  if ( name == "." )
1752  {
1753  // if the update was started before finishing the original listing
1754  // there is no root item yet
1755  if ( dir->rootItem.isNull() )
1756  {
1757  dir->rootItem = item;
1758 
1759  foreach ( KDirLister *kdl, listers )
1760  if ( kdl->d->rootFileItem.isNull() && kdl->d->url == jobUrl )
1761  kdl->d->rootFileItem = dir->rootItem;
1762  }
1763  continue;
1764  }
1765 
1766  // Find this item
1767  if (KFileItem* tmp = fileItems.value(item.name()))
1768  {
1769  QSet<KFileItem*>::iterator pru_it = pendingRemoteUpdates.find(tmp);
1770  const bool inPendingRemoteUpdates = (pru_it != pendingRemoteUpdates.end());
1771 
1772  // check if something changed for this file, using KFileItem::cmp()
1773  if (!tmp->cmp( item ) || inPendingRemoteUpdates) {
1774 
1775  if (inPendingRemoteUpdates) {
1776  pendingRemoteUpdates.erase(pru_it);
1777  }
1778 
1779  //kDebug(7004) << "file changed:" << tmp->name();
1780 
1781  const KFileItem oldItem = *tmp;
1782  *tmp = item;
1783  foreach ( KDirLister *kdl, listers )
1784  kdl->d->addRefreshItem(jobUrl, oldItem, *tmp);
1785  }
1786  //kDebug(7004) << "marking" << tmp;
1787  tmp->mark();
1788  }
1789  else // this is a new file
1790  {
1791  //kDebug(7004) << "new file:" << name;
1792 
1793  KFileItem pitem(item);
1794  pitem.mark();
1795  dir->lstItems.append( pitem );
1796 
1797  foreach ( KDirLister *kdl, listers )
1798  kdl->d->addNewItem(jobUrl, pitem);
1799  }
1800  }
1801 
1802  runningListJobs.remove( job );
1803 
1804  deleteUnmarkedItems( listers, dir->lstItems );
1805 
1806  foreach ( KDirLister *kdl, listers ) {
1807  kdl->d->emitItems();
1808 
1809  kdl->d->jobDone( job );
1810 
1811  emit kdl->completed( jobUrl );
1812  if ( kdl->d->numJobs() == 0 )
1813  {
1814  kdl->d->complete = true;
1815  emit kdl->completed();
1816  }
1817  }
1818 
1819  // TODO: hmm, if there was an error and job is a parent of one or more
1820  // of the pending urls we should cancel it/them as well
1821  processPendingUpdates();
1822 }
1823 
1824 // private
1825 
1826 KIO::ListJob *KDirListerCache::jobForUrl( const QString& url, KIO::ListJob *not_job )
1827 {
1828  QMap< KIO::ListJob *, KIO::UDSEntryList >::const_iterator it = runningListJobs.constBegin();
1829  while ( it != runningListJobs.constEnd() )
1830  {
1831  KIO::ListJob *job = it.key();
1832  if ( joburl( job ).url(KUrl::RemoveTrailingSlash) == url && job != not_job )
1833  return job;
1834  ++it;
1835  }
1836  return 0;
1837 }
1838 
1839 const KUrl& KDirListerCache::joburl( KIO::ListJob *job )
1840 {
1841  if ( job->redirectionUrl().isValid() )
1842  return job->redirectionUrl();
1843  else
1844  return job->url();
1845 }
1846 
1847 void KDirListerCache::killJob( KIO::ListJob *job )
1848 {
1849  runningListJobs.remove( job );
1850  job->disconnect( this );
1851  job->kill();
1852 }
1853 
1854 void KDirListerCache::deleteUnmarkedItems( const QList<KDirLister *>& listers, KFileItemList &lstItems )
1855 {
1856  KFileItemList deletedItems;
1857  // Find all unmarked items and delete them
1858  QMutableListIterator<KFileItem> kit(lstItems);
1859  while (kit.hasNext()) {
1860  const KFileItem& item = kit.next();
1861  if (!item.isMarked()) {
1862  //kDebug(7004) << "deleted:" << item.name() << &item;
1863  deletedItems.append(item);
1864  kit.remove();
1865  }
1866  }
1867  if (!deletedItems.isEmpty())
1868  itemsDeleted(listers, deletedItems);
1869 }
1870 
1871 void KDirListerCache::itemsDeleted(const QList<KDirLister *>& listers, const KFileItemList& deletedItems)
1872 {
1873  Q_FOREACH(KDirLister *kdl, listers) {
1874  kdl->d->emitItemsDeleted(deletedItems);
1875  }
1876 
1877  Q_FOREACH(const KFileItem& item, deletedItems) {
1878  if (item.isDir())
1879  deleteDir(item.url());
1880  }
1881 }
1882 
1883 void KDirListerCache::deleteDir( const KUrl& dirUrl )
1884 {
1885  //kDebug() << dirUrl;
1886  // unregister and remove the children of the deleted item.
1887  // Idea: tell all the KDirListers that they should forget the dir
1888  // and then remove it from the cache.
1889 
1890  // Separate itemsInUse iteration and calls to forgetDirs (which modify itemsInUse)
1891  KUrl::List affectedItems;
1892 
1893  QHash<QString, DirItem *>::iterator itu = itemsInUse.begin();
1894  const QHash<QString, DirItem *>::iterator ituend = itemsInUse.end();
1895  for ( ; itu != ituend; ++itu ) {
1896  const KUrl deletedUrl( itu.key() );
1897  if ( dirUrl.isParentOf( deletedUrl ) ) {
1898  affectedItems.append(deletedUrl);
1899  }
1900  }
1901 
1902  foreach(const KUrl& deletedUrl, affectedItems) {
1903  const QString deletedUrlStr = deletedUrl.url();
1904  // stop all jobs for deletedUrlStr
1905  DirectoryDataHash::iterator dit = directoryData.find(deletedUrlStr);
1906  if (dit != directoryData.end()) {
1907  // we need a copy because stop modifies the list
1908  QList<KDirLister *> listers = (*dit).listersCurrentlyListing;
1909  foreach ( KDirLister *kdl, listers )
1910  stopListingUrl( kdl, deletedUrl );
1911  // tell listers holding deletedUrl to forget about it
1912  // this will stop running updates for deletedUrl as well
1913 
1914  // we need a copy because forgetDirs modifies the list
1915  QList<KDirLister *> holders = (*dit).listersCurrentlyHolding;
1916  foreach ( KDirLister *kdl, holders ) {
1917  // lister's root is the deleted item
1918  if ( kdl->d->url == deletedUrl )
1919  {
1920  // tell the view first. It might need the subdirs' items (which forgetDirs will delete)
1921  if ( !kdl->d->rootFileItem.isNull() ) {
1922  emit kdl->deleteItem( kdl->d->rootFileItem );
1923  emit kdl->itemsDeleted(KFileItemList() << kdl->d->rootFileItem);
1924  }
1925  forgetDirs( kdl );
1926  kdl->d->rootFileItem = KFileItem();
1927  }
1928  else
1929  {
1930  const bool treeview = kdl->d->lstDirs.count() > 1;
1931  if ( !treeview )
1932  {
1933  emit kdl->clear();
1934  kdl->d->lstDirs.clear();
1935  }
1936  else
1937  kdl->d->lstDirs.removeAll( deletedUrl );
1938 
1939  forgetDirs( kdl, deletedUrl, treeview );
1940  }
1941  }
1942  }
1943 
1944  // delete the entry for deletedUrl - should not be needed, it's in
1945  // items cached now
1946  int count = itemsInUse.remove( deletedUrlStr );
1947  Q_ASSERT( count == 0 );
1948  Q_UNUSED( count ); //keep gcc "unused variable" complaining quiet when in release mode
1949  }
1950 
1951  // remove the children from the cache
1952  removeDirFromCache( dirUrl );
1953 }
1954 
1955 // delayed updating of files, FAM is flooding us with events
1956 void KDirListerCache::processPendingUpdates()
1957 {
1958  QSet<KDirLister *> listers;
1959  foreach(const QString& file, pendingUpdates) { // always a local path
1960  kDebug(7004) << file;
1961  KUrl u(file);
1962  KFileItem *item = findByUrl( 0, u ); // search all items
1963  if ( item ) {
1964  // we need to refresh the item, because e.g. the permissions can have changed.
1965  KFileItem oldItem = *item;
1966  item->refresh();
1967  listers |= emitRefreshItem( oldItem, *item );
1968  }
1969  }
1970  pendingUpdates.clear();
1971  Q_FOREACH(KDirLister * kdl, listers) {
1972  kdl->d->emitItems();
1973  }
1974 }
1975 
1976 #ifndef NDEBUG
1977 void KDirListerCache::printDebug()
1978 {
1979  kDebug(7004) << "Items in use:";
1980  QHash<QString, DirItem *>::const_iterator itu = itemsInUse.constBegin();
1981  const QHash<QString, DirItem *>::const_iterator ituend = itemsInUse.constEnd();
1982  for ( ; itu != ituend ; ++itu ) {
1983  kDebug(7004) << " " << itu.key() << "URL:" << itu.value()->url
1984  << "rootItem:" << ( !itu.value()->rootItem.isNull() ? itu.value()->rootItem.url() : KUrl() )
1985  << "autoUpdates refcount:" << itu.value()->autoUpdates
1986  << "complete:" << itu.value()->complete
1987  << QString("with %1 items.").arg(itu.value()->lstItems.count());
1988  }
1989 
1990  QList<KDirLister*> listersWithoutJob;
1991  kDebug(7004) << "Directory data:";
1992  DirectoryDataHash::const_iterator dit = directoryData.constBegin();
1993  for ( ; dit != directoryData.constEnd(); ++dit )
1994  {
1995  QString list;
1996  foreach ( KDirLister* listit, (*dit).listersCurrentlyListing )
1997  list += " 0x" + QString::number( (qlonglong)listit, 16 );
1998  kDebug(7004) << " " << dit.key() << (*dit).listersCurrentlyListing.count() << "listers:" << list;
1999  foreach ( KDirLister* listit, (*dit).listersCurrentlyListing ) {
2000  if (!listit->d->m_cachedItemsJobs.isEmpty()) {
2001  kDebug(7004) << " Lister" << listit << "has CachedItemsJobs" << listit->d->m_cachedItemsJobs;
2002  } else if (KIO::ListJob* listJob = jobForUrl(dit.key())) {
2003  kDebug(7004) << " Lister" << listit << "has ListJob" << listJob;
2004  } else {
2005  listersWithoutJob.append(listit);
2006  }
2007  }
2008 
2009  list.clear();
2010  foreach ( KDirLister* listit, (*dit).listersCurrentlyHolding )
2011  list += " 0x" + QString::number( (qlonglong)listit, 16 );
2012  kDebug(7004) << " " << dit.key() << (*dit).listersCurrentlyHolding.count() << "holders:" << list;
2013  }
2014 
2015  QMap< KIO::ListJob *, KIO::UDSEntryList >::Iterator jit = runningListJobs.begin();
2016  kDebug(7004) << "Jobs:";
2017  for ( ; jit != runningListJobs.end() ; ++jit )
2018  kDebug(7004) << " " << jit.key() << "listing" << joburl( jit.key() ) << ":" << (*jit).count() << "entries.";
2019 
2020  kDebug(7004) << "Items in cache:";
2021  const QList<QString> cachedDirs = itemsCached.keys();
2022  foreach(const QString& cachedDir, cachedDirs) {
2023  DirItem* dirItem = itemsCached.object(cachedDir);
2024  kDebug(7004) << " " << cachedDir << "rootItem:"
2025  << (!dirItem->rootItem.isNull() ? dirItem->rootItem.url().prettyUrl() : QString("NULL") )
2026  << "with" << dirItem->lstItems.count() << "items.";
2027  }
2028 
2029  // Abort on listers without jobs -after- showing the full dump. Easier debugging.
2030  Q_FOREACH(KDirLister* listit, listersWithoutJob) {
2031  kFatal() << "HUH? Lister" << listit << "is supposed to be listing, but has no job!";
2032  }
2033 }
2034 #endif
2035 
2036 
2037 KDirLister::KDirLister( QObject* parent )
2038  : QObject(parent), d(new Private(this))
2039 {
2040  //kDebug(7003) << "+KDirLister";
2041 
2042  d->complete = true;
2043 
2044  setAutoUpdate( true );
2045  setDirOnlyMode( false );
2046  setShowingDotFiles( false );
2047 
2048  setAutoErrorHandlingEnabled( true, 0 );
2049 }
2050 
2051 KDirLister::~KDirLister()
2052 {
2053  //kDebug(7003) << "~KDirLister" << this;
2054 
2055  // Stop all running jobs, remove lister from lists
2056  if (!kDirListerCache.isDestroyed()) {
2057  stop();
2058  kDirListerCache->forgetDirs( this );
2059  }
2060 
2061  delete d;
2062 }
2063 
2064 bool KDirLister::openUrl( const KUrl& _url, OpenUrlFlags _flags )
2065 {
2066  // emit the current changes made to avoid an inconsistent treeview
2067  if (d->hasPendingChanges && (_flags & Keep))
2068  emitChanges();
2069 
2070  d->hasPendingChanges = false;
2071 
2072  return kDirListerCache->listDir( this, _url, _flags & Keep, _flags & Reload );
2073 }
2074 
2075 void KDirLister::stop()
2076 {
2077  kDirListerCache->stop( this );
2078 }
2079 
2080 void KDirLister::stop( const KUrl& _url )
2081 {
2082  kDirListerCache->stopListingUrl( this, _url );
2083 }
2084 
2085 bool KDirLister::autoUpdate() const
2086 {
2087  return d->autoUpdate;
2088 }
2089 
2090 void KDirLister::setAutoUpdate( bool _enable )
2091 {
2092  if ( d->autoUpdate == _enable )
2093  return;
2094 
2095  d->autoUpdate = _enable;
2096  kDirListerCache->setAutoUpdate( this, _enable );
2097 }
2098 
2099 bool KDirLister::showingDotFiles() const
2100 {
2101  return d->settings.isShowingDotFiles;
2102 }
2103 
2104 void KDirLister::setShowingDotFiles( bool _showDotFiles )
2105 {
2106  if ( d->settings.isShowingDotFiles == _showDotFiles )
2107  return;
2108 
2109  d->prepareForSettingsChange();
2110  d->settings.isShowingDotFiles = _showDotFiles;
2111 }
2112 
2113 bool KDirLister::dirOnlyMode() const
2114 {
2115  return d->settings.dirOnlyMode;
2116 }
2117 
2118 void KDirLister::setDirOnlyMode( bool _dirsOnly )
2119 {
2120  if ( d->settings.dirOnlyMode == _dirsOnly )
2121  return;
2122 
2123  d->prepareForSettingsChange();
2124  d->settings.dirOnlyMode = _dirsOnly;
2125 }
2126 
2127 bool KDirLister::autoErrorHandlingEnabled() const
2128 {
2129  return d->autoErrorHandling;
2130 }
2131 
2132 void KDirLister::setAutoErrorHandlingEnabled( bool enable, QWidget* parent )
2133 {
2134  d->autoErrorHandling = enable;
2135  d->errorParent = parent;
2136 }
2137 
2138 KUrl KDirLister::url() const
2139 {
2140  return d->url;
2141 }
2142 
2143 KUrl::List KDirLister::directories() const
2144 {
2145  return d->lstDirs;
2146 }
2147 
2148 void KDirLister::emitChanges()
2149 {
2150  d->emitChanges();
2151 }
2152 
2153 void KDirLister::Private::emitChanges()
2154 {
2155  if (!hasPendingChanges)
2156  return;
2157 
2158  // reset 'hasPendingChanges' now, in case of recursion
2159  // (testcase: enabling recursive scan in ktorrent, #174920)
2160  hasPendingChanges = false;
2161 
2162  const Private::FilterSettings newSettings = settings;
2163  settings = oldSettings; // temporarily
2164 
2165  // Mark all items that are currently visible
2166  Q_FOREACH(const KUrl& dir, lstDirs) {
2167  KFileItemList* itemList = kDirListerCache->itemsForDir(dir);
2168  if (!itemList) {
2169  continue;
2170  }
2171 
2172  KFileItemList::iterator kit = itemList->begin();
2173  const KFileItemList::iterator kend = itemList->end();
2174  for (; kit != kend; ++kit) {
2175  if (isItemVisible(*kit) && m_parent->matchesMimeFilter(*kit))
2176  (*kit).mark();
2177  else
2178  (*kit).unmark();
2179  }
2180  }
2181 
2182  settings = newSettings;
2183 
2184  Q_FOREACH(const KUrl& dir, lstDirs) {
2185  KFileItemList deletedItems;
2186 
2187  KFileItemList* itemList = kDirListerCache->itemsForDir(dir);
2188  if (!itemList) {
2189  continue;
2190  }
2191 
2192  KFileItemList::iterator kit = itemList->begin();
2193  const KFileItemList::iterator kend = itemList->end();
2194  for (; kit != kend; ++kit) {
2195  KFileItem& item = *kit;
2196  const QString text = item.text();
2197  if (text == "." || text == "..")
2198  continue;
2199  const bool nowVisible = isItemVisible(item) && m_parent->matchesMimeFilter(item);
2200  if (nowVisible && !item.isMarked())
2201  addNewItem(dir, item); // takes care of emitting newItem or itemsFilteredByMime
2202  else if (!nowVisible && item.isMarked())
2203  deletedItems.append(*kit);
2204  }
2205  if (!deletedItems.isEmpty()) {
2206  emit m_parent->itemsDeleted(deletedItems);
2207  // for compat
2208  Q_FOREACH(const KFileItem& item, deletedItems)
2209  emit m_parent->deleteItem(item);
2210  }
2211  emitItems();
2212  }
2213  oldSettings = settings;
2214 }
2215 
2216 void KDirLister::updateDirectory( const KUrl& _u )
2217 {
2218  kDirListerCache->updateDirectory( _u );
2219 }
2220 
2221 bool KDirLister::isFinished() const
2222 {
2223  return d->complete;
2224 }
2225 
2226 KFileItem KDirLister::rootItem() const
2227 {
2228  return d->rootFileItem;
2229 }
2230 
2231 KFileItem KDirLister::findByUrl( const KUrl& _url ) const
2232 {
2233  KFileItem *item = kDirListerCache->findByUrl( this, _url );
2234  if (item) {
2235  return *item;
2236  } else {
2237  return KFileItem();
2238  }
2239 }
2240 
2241 KFileItem KDirLister::findByName( const QString& _name ) const
2242 {
2243  return kDirListerCache->findByName( this, _name );
2244 }
2245 
2246 
2247 // ================ public filter methods ================ //
2248 
2249 void KDirLister::setNameFilter( const QString& nameFilter )
2250 {
2251  if (d->nameFilter == nameFilter)
2252  return;
2253 
2254  d->prepareForSettingsChange();
2255 
2256  d->settings.lstFilters.clear();
2257  d->nameFilter = nameFilter;
2258  // Split on white space
2259  const QStringList list = nameFilter.split( ' ', QString::SkipEmptyParts );
2260  for (QStringList::const_iterator it = list.begin(); it != list.end(); ++it)
2261  d->settings.lstFilters.append(QRegExp(*it, Qt::CaseInsensitive, QRegExp::Wildcard));
2262 }
2263 
2264 QString KDirLister::nameFilter() const
2265 {
2266  return d->nameFilter;
2267 }
2268 
2269 void KDirLister::setMimeFilter( const QStringList& mimeFilter )
2270 {
2271  if (d->settings.mimeFilter == mimeFilter)
2272  return;
2273 
2274  d->prepareForSettingsChange();
2275  if (mimeFilter.contains(QLatin1String("application/octet-stream")) || mimeFilter.contains(QLatin1String("all/allfiles"))) // all files
2276  d->settings.mimeFilter.clear();
2277  else
2278  d->settings.mimeFilter = mimeFilter;
2279 }
2280 
2281 void KDirLister::setMimeExcludeFilter( const QStringList& mimeExcludeFilter )
2282 {
2283  if (d->settings.mimeExcludeFilter == mimeExcludeFilter)
2284  return;
2285 
2286  d->prepareForSettingsChange();
2287  d->settings.mimeExcludeFilter = mimeExcludeFilter;
2288 }
2289 
2290 
2291 void KDirLister::clearMimeFilter()
2292 {
2293  d->prepareForSettingsChange();
2294  d->settings.mimeFilter.clear();
2295  d->settings.mimeExcludeFilter.clear();
2296 }
2297 
2298 QStringList KDirLister::mimeFilters() const
2299 {
2300  return d->settings.mimeFilter;
2301 }
2302 
2303 bool KDirLister::matchesFilter( const QString& name ) const
2304 {
2305  return doNameFilter(name, d->settings.lstFilters);
2306 }
2307 
2308 bool KDirLister::matchesMimeFilter( const QString& mime ) const
2309 {
2310  return doMimeFilter(mime, d->settings.mimeFilter) &&
2311  d->doMimeExcludeFilter(mime, d->settings.mimeExcludeFilter);
2312 }
2313 
2314 // ================ protected methods ================ //
2315 
2316 bool KDirLister::matchesFilter( const KFileItem& item ) const
2317 {
2318  Q_ASSERT( !item.isNull() );
2319 
2320  if ( item.text() == ".." )
2321  return false;
2322 
2323  if ( !d->settings.isShowingDotFiles && item.isHidden() )
2324  return false;
2325 
2326  if ( item.isDir() || d->settings.lstFilters.isEmpty() )
2327  return true;
2328 
2329  return matchesFilter( item.text() );
2330 }
2331 
2332 bool KDirLister::matchesMimeFilter( const KFileItem& item ) const
2333 {
2334  Q_ASSERT(!item.isNull());
2335  // Don't lose time determining the mimetype if there is no filter
2336  if (d->settings.mimeFilter.isEmpty() && d->settings.mimeExcludeFilter.isEmpty())
2337  return true;
2338  return matchesMimeFilter(item.mimetype());
2339 }
2340 
2341 bool KDirLister::doNameFilter( const QString& name, const QList<QRegExp>& filters ) const
2342 {
2343  for ( QList<QRegExp>::const_iterator it = filters.begin(); it != filters.end(); ++it )
2344  if ( (*it).exactMatch( name ) )
2345  return true;
2346 
2347  return false;
2348 }
2349 
2350 bool KDirLister::doMimeFilter( const QString& mime, const QStringList& filters ) const
2351 {
2352  if ( filters.isEmpty() )
2353  return true;
2354 
2355  const KMimeType::Ptr mimeptr = KMimeType::mimeType(mime);
2356  if ( !mimeptr )
2357  return false;
2358 
2359  //kDebug(7004) << "doMimeFilter: investigating: "<<mimeptr->name();
2360  QStringList::const_iterator it = filters.begin();
2361  for ( ; it != filters.end(); ++it )
2362  if ( mimeptr->is(*it) )
2363  return true;
2364  //else kDebug(7004) << "doMimeFilter: compared without result to "<<*it;
2365 
2366  return false;
2367 }
2368 
2369 bool KDirLister::Private::doMimeExcludeFilter( const QString& mime, const QStringList& filters ) const
2370 {
2371  if ( filters.isEmpty() )
2372  return true;
2373 
2374  QStringList::const_iterator it = filters.begin();
2375  for ( ; it != filters.end(); ++it )
2376  if ( (*it) == mime )
2377  return false;
2378 
2379  return true;
2380 }
2381 
2382 void KDirLister::handleError( KIO::Job *job )
2383 {
2384  if ( d->autoErrorHandling )
2385  job->uiDelegate()->showErrorMessage();
2386 }
2387 
2388 
2389 // ================= private methods ================= //
2390 
2391 void KDirLister::Private::addNewItem(const KUrl& directoryUrl, const KFileItem &item)
2392 {
2393  if (!isItemVisible(item))
2394  return; // No reason to continue... bailing out here prevents a mimetype scan.
2395 
2396  //kDebug(7004) << "in" << directoryUrl << "item:" << item.url();
2397 
2398  if ( m_parent->matchesMimeFilter( item ) )
2399  {
2400  if ( !lstNewItems )
2401  {
2402  lstNewItems = new NewItemsHash;
2403  }
2404 
2405  Q_ASSERT( !item.isNull() );
2406  (*lstNewItems)[directoryUrl].append( item ); // items not filtered
2407  }
2408  else
2409  {
2410  if ( !lstMimeFilteredItems ) {
2411  lstMimeFilteredItems = new KFileItemList;
2412  }
2413 
2414  Q_ASSERT( !item.isNull() );
2415  lstMimeFilteredItems->append( item ); // only filtered by mime
2416  }
2417 }
2418 
2419 void KDirLister::Private::addNewItems(const KUrl& directoryUrl, const KFileItemList& items)
2420 {
2421  // TODO: make this faster - test if we have a filter at all first
2422  // DF: was this profiled? The matchesFoo() functions should be fast, w/o filters...
2423  // Of course if there is no filter and we can do a range-insertion instead of a loop, that might be good.
2424  KFileItemList::const_iterator kit = items.begin();
2425  const KFileItemList::const_iterator kend = items.end();
2426  for ( ; kit != kend; ++kit )
2427  addNewItem(directoryUrl, *kit);
2428 }
2429 
2430 void KDirLister::Private::addRefreshItem(const KUrl& directoryUrl, const KFileItem& oldItem, const KFileItem& item)
2431 {
2432  const bool refreshItemWasFiltered = !isItemVisible(oldItem) ||
2433  !m_parent->matchesMimeFilter(oldItem);
2434  if (isItemVisible(item) && m_parent->matchesMimeFilter(item)) {
2435  if ( refreshItemWasFiltered )
2436  {
2437  if ( !lstNewItems ) {
2438  lstNewItems = new NewItemsHash;
2439  }
2440 
2441  Q_ASSERT( !item.isNull() );
2442  (*lstNewItems)[directoryUrl].append( item );
2443  }
2444  else
2445  {
2446  if ( !lstRefreshItems ) {
2447  lstRefreshItems = new QList<QPair<KFileItem,KFileItem> >;
2448  }
2449 
2450  Q_ASSERT( !item.isNull() );
2451  lstRefreshItems->append( qMakePair(oldItem, item) );
2452  }
2453  }
2454  else if ( !refreshItemWasFiltered )
2455  {
2456  if ( !lstRemoveItems ) {
2457  lstRemoveItems = new KFileItemList;
2458  }
2459 
2460  // notify the user that the mimetype of a file changed that doesn't match
2461  // a filter or does match an exclude filter
2462  // This also happens when renaming foo to .foo and dot files are hidden (#174721)
2463  Q_ASSERT(!oldItem.isNull());
2464  lstRemoveItems->append(oldItem);
2465  }
2466 }
2467 
2468 void KDirLister::Private::emitItems()
2469 {
2470  NewItemsHash *tmpNew = lstNewItems;
2471  lstNewItems = 0;
2472 
2473  KFileItemList *tmpMime = lstMimeFilteredItems;
2474  lstMimeFilteredItems = 0;
2475 
2476  QList<QPair<KFileItem, KFileItem> > *tmpRefresh = lstRefreshItems;
2477  lstRefreshItems = 0;
2478 
2479  KFileItemList *tmpRemove = lstRemoveItems;
2480  lstRemoveItems = 0;
2481 
2482  if (tmpNew) {
2483  QHashIterator<KUrl, KFileItemList> it(*tmpNew);
2484  while (it.hasNext()) {
2485  it.next();
2486  emit m_parent->itemsAdded(it.key(), it.value());
2487  emit m_parent->newItems(it.value()); // compat
2488  }
2489  delete tmpNew;
2490  }
2491 
2492  if ( tmpMime )
2493  {
2494  emit m_parent->itemsFilteredByMime( *tmpMime );
2495  delete tmpMime;
2496  }
2497 
2498  if ( tmpRefresh )
2499  {
2500  emit m_parent->refreshItems( *tmpRefresh );
2501  delete tmpRefresh;
2502  }
2503 
2504  if ( tmpRemove )
2505  {
2506  emit m_parent->itemsDeleted( *tmpRemove );
2507  delete tmpRemove;
2508  }
2509 }
2510 
2511 bool KDirLister::Private::isItemVisible(const KFileItem& item) const
2512 {
2513  // Note that this doesn't include mime filters, because
2514  // of the itemsFilteredByMime signal. Filtered-by-mime items are
2515  // considered "visible", they are just visible via a different signal...
2516  return (!settings.dirOnlyMode || item.isDir())
2517  && m_parent->matchesFilter(item);
2518 }
2519 
2520 void KDirLister::Private::emitItemsDeleted(const KFileItemList &_items)
2521 {
2522  KFileItemList items = _items;
2523  QMutableListIterator<KFileItem> it(items);
2524  while (it.hasNext()) {
2525  const KFileItem& item = it.next();
2526  if (isItemVisible(item) && m_parent->matchesMimeFilter(item)) {
2527  // for compat
2528  emit m_parent->deleteItem(item);
2529  } else {
2530  it.remove();
2531  }
2532  }
2533  if (!items.isEmpty())
2534  emit m_parent->itemsDeleted(items);
2535 }
2536 
2537 // ================ private slots ================ //
2538 
2539 void KDirLister::Private::_k_slotInfoMessage( KJob *, const QString& message )
2540 {
2541  emit m_parent->infoMessage( message );
2542 }
2543 
2544 void KDirLister::Private::_k_slotPercent( KJob *job, unsigned long pcnt )
2545 {
2546  jobData[static_cast<KIO::ListJob *>(job)].percent = pcnt;
2547 
2548  int result = 0;
2549 
2550  KIO::filesize_t size = 0;
2551 
2552  QMap< KIO::ListJob *, Private::JobData >::Iterator dataIt = jobData.begin();
2553  while ( dataIt != jobData.end() )
2554  {
2555  result += (*dataIt).percent * (*dataIt).totalSize;
2556  size += (*dataIt).totalSize;
2557  ++dataIt;
2558  }
2559 
2560  if ( size != 0 )
2561  result /= size;
2562  else
2563  result = 100;
2564  emit m_parent->percent( result );
2565 }
2566 
2567 void KDirLister::Private::_k_slotTotalSize( KJob *job, qulonglong size )
2568 {
2569  jobData[static_cast<KIO::ListJob *>(job)].totalSize = size;
2570 
2571  KIO::filesize_t result = 0;
2572  QMap< KIO::ListJob *, Private::JobData >::Iterator dataIt = jobData.begin();
2573  while ( dataIt != jobData.end() )
2574  {
2575  result += (*dataIt).totalSize;
2576  ++dataIt;
2577  }
2578 
2579  emit m_parent->totalSize( result );
2580 }
2581 
2582 void KDirLister::Private::_k_slotProcessedSize( KJob *job, qulonglong size )
2583 {
2584  jobData[static_cast<KIO::ListJob *>(job)].processedSize = size;
2585 
2586  KIO::filesize_t result = 0;
2587  QMap< KIO::ListJob *, Private::JobData >::Iterator dataIt = jobData.begin();
2588  while ( dataIt != jobData.end() )
2589  {
2590  result += (*dataIt).processedSize;
2591  ++dataIt;
2592  }
2593 
2594  emit m_parent->processedSize( result );
2595 }
2596 
2597 void KDirLister::Private::_k_slotSpeed( KJob *job, unsigned long spd )
2598 {
2599  jobData[static_cast<KIO::ListJob *>(job)].speed = spd;
2600 
2601  int result = 0;
2602  QMap< KIO::ListJob *, Private::JobData >::Iterator dataIt = jobData.begin();
2603  while ( dataIt != jobData.end() )
2604  {
2605  result += (*dataIt).speed;
2606  ++dataIt;
2607  }
2608 
2609  emit m_parent->speed( result );
2610 }
2611 
2612 uint KDirLister::Private::numJobs()
2613 {
2614 #ifdef DEBUG_CACHE
2615  // This code helps detecting stale entries in the jobData map.
2616  qDebug() << m_parent << "numJobs:" << jobData.count();
2617  QMapIterator<KIO::ListJob *, JobData> it(jobData);
2618  while (it.hasNext()) {
2619  it.next();
2620  qDebug() << (void*)it.key();
2621  qDebug() << it.key();
2622  }
2623 #endif
2624 
2625  return jobData.count();
2626 }
2627 
2628 void KDirLister::Private::jobDone( KIO::ListJob *job )
2629 {
2630  jobData.remove( job );
2631 }
2632 
2633 void KDirLister::Private::jobStarted( KIO::ListJob *job )
2634 {
2635  Private::JobData data;
2636  data.speed = 0;
2637  data.percent = 0;
2638  data.processedSize = 0;
2639  data.totalSize = 0;
2640 
2641  jobData.insert( job, data );
2642  complete = false;
2643 }
2644 
2645 void KDirLister::Private::connectJob( KIO::ListJob *job )
2646 {
2647  m_parent->connect( job, SIGNAL(infoMessage(KJob*,QString,QString)),
2648  m_parent, SLOT(_k_slotInfoMessage(KJob*,QString)) );
2649  m_parent->connect( job, SIGNAL(percent(KJob*,ulong)),
2650  m_parent, SLOT(_k_slotPercent(KJob*,ulong)) );
2651  m_parent->connect( job, SIGNAL(totalSize(KJob*,qulonglong)),
2652  m_parent, SLOT(_k_slotTotalSize(KJob*,qulonglong)) );
2653  m_parent->connect( job, SIGNAL(processedSize(KJob*,qulonglong)),
2654  m_parent, SLOT(_k_slotProcessedSize(KJob*,qulonglong)) );
2655  m_parent->connect( job, SIGNAL(speed(KJob*,ulong)),
2656  m_parent, SLOT(_k_slotSpeed(KJob*,ulong)) );
2657 }
2658 
2659 void KDirLister::setMainWindow( QWidget *window )
2660 {
2661  d->window = window;
2662 }
2663 
2664 QWidget *KDirLister::mainWindow()
2665 {
2666  return d->window;
2667 }
2668 
2669 KFileItemList KDirLister::items( WhichItems which ) const
2670 {
2671  return itemsForDir( url(), which );
2672 }
2673 
2674 KFileItemList KDirLister::itemsForDir( const KUrl& dir, WhichItems which ) const
2675 {
2676  KFileItemList *allItems = kDirListerCache->itemsForDir( dir );
2677  if ( !allItems )
2678  return KFileItemList();
2679 
2680  if ( which == AllItems )
2681  return *allItems;
2682  else // only items passing the filters
2683  {
2684  KFileItemList result;
2685  KFileItemList::const_iterator kit = allItems->constBegin();
2686  const KFileItemList::const_iterator kend = allItems->constEnd();
2687  for ( ; kit != kend; ++kit )
2688  {
2689  const KFileItem& item = *kit;
2690  if (d->isItemVisible(item) && matchesMimeFilter(item)) {
2691  result.append(item);
2692  }
2693  }
2694  return result;
2695  }
2696 }
2697 
2698 bool KDirLister::delayedMimeTypes() const
2699 {
2700  return d->delayedMimeTypes;
2701 }
2702 
2703 void KDirLister::setDelayedMimeTypes( bool delayedMimeTypes )
2704 {
2705  d->delayedMimeTypes = delayedMimeTypes;
2706 }
2707 
2708 // called by KDirListerCache::slotRedirection
2709 void KDirLister::Private::redirect(const KUrl& oldUrl, const KUrl& newUrl, bool keepItems)
2710 {
2711  if ( url.equals( oldUrl, KUrl::CompareWithoutTrailingSlash ) ) {
2712  if (!keepItems)
2713  rootFileItem = KFileItem();
2714  url = newUrl;
2715  }
2716 
2717  const int idx = lstDirs.indexOf( oldUrl );
2718  if (idx == -1) {
2719  kWarning(7004) << "Unexpected redirection from" << oldUrl << "to" << newUrl
2720  << "but this dirlister is currently listing/holding" << lstDirs;
2721  } else {
2722  lstDirs[ idx ] = newUrl;
2723  }
2724 
2725  if ( lstDirs.count() == 1 ) {
2726  if (!keepItems)
2727  emit m_parent->clear();
2728  emit m_parent->redirection( newUrl );
2729  } else {
2730  if (!keepItems)
2731  emit m_parent->clear( oldUrl );
2732  }
2733  emit m_parent->redirection( oldUrl, newUrl );
2734 }
2735 
2736 void KDirListerCacheDirectoryData::moveListersWithoutCachedItemsJob(const KUrl& url)
2737 {
2738  // Move dirlisters from listersCurrentlyListing to listersCurrentlyHolding,
2739  // but not those that are still waiting on a CachedItemsJob...
2740  // Unit-testing note:
2741  // Run kdirmodeltest in valgrind to hit the case where an update
2742  // is triggered while a lister has a CachedItemsJob (different timing...)
2743  QMutableListIterator<KDirLister *> lister_it(listersCurrentlyListing);
2744  while (lister_it.hasNext()) {
2745  KDirLister* kdl = lister_it.next();
2746  if (!kdl->d->cachedItemsJobForUrl(url)) {
2747  // OK, move this lister from "currently listing" to "currently holding".
2748 
2749  // Huh? The KDirLister was present twice in listersCurrentlyListing, or was in both lists?
2750  Q_ASSERT(!listersCurrentlyHolding.contains(kdl));
2751  if (!listersCurrentlyHolding.contains(kdl)) {
2752  listersCurrentlyHolding.append(kdl);
2753  }
2754  lister_it.remove();
2755  } else {
2756  //kDebug(7004) << "Not moving" << kdl << "to listersCurrentlyHolding because it still has job" << kdl->d->m_cachedItemsJobs;
2757  }
2758  }
2759 }
2760 
2761 KFileItem KDirLister::cachedItemForUrl(const KUrl& url)
2762 {
2763  return kDirListerCache->itemForUrl(url);
2764 }
2765 
2766 #include "kdirlister.moc"
2767 #include "kdirlister_p.moc"
This file is part of the KDE documentation.
Documentation copyright © 1996-2012 The KDE developers.
Generated on Mon Dec 10 2012 13:56:43 by doxygen 1.8.1.2 written by Dimitri van Heesch, © 1997-2006

KDE's Doxygen guidelines are available online.

KIO

Skip menu "KIO"
  • Main Page
  • Namespace List
  • Namespace Members
  • Alphabetical List
  • Class List
  • Class Hierarchy
  • Class Members
  • File List
  • File Members
  • Related Pages

kdelibs-4.9.4 API Reference

Skip menu "kdelibs-4.9.4 API Reference"
  • DNSSD
  • Interfaces
  •   KHexEdit
  •   KMediaPlayer
  •   KSpeech
  •   KTextEditor
  • kconf_update
  • KDE3Support
  •   KUnitTest
  • KDECore
  • KDED
  • KDEsu
  • KDEUI
  • KDEWebKit
  • KDocTools
  • KFile
  • KHTML
  • KImgIO
  • KInit
  • kio
  • KIOSlave
  • KJS
  •   KJS-API
  •   WTF
  • kjsembed
  • KNewStuff
  • KParts
  • KPty
  • Kross
  • KUnitConversion
  • KUtils
  • Nepomuk
  • Plasma
  • Solid
  • Sonnet
  • ThreadWeaver
Report problems with this website to our bug tracking system.
Contact the specific authors with questions and comments about the page contents.

KDE® and the K Desktop Environment® logo are registered trademarks of KDE e.V. | Legal