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

Skip menu "kdelibs-4.10.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