• Skip to content
  • Skip to link menu
Trinity API Reference
  • Trinity API Reference
  • kio/kfile
 

kio/kfile

  • kio
  • kfile
kfiledialog.cpp
1 // -*- c++ -*-
2 /* This file is part of the KDE libraries
3  Copyright (C) 1997, 1998 Richard Moore <rich@kde.org>
4  1998 Stephan Kulow <coolo@kde.org>
5  1998 Daniel Grana <grana@ie.iwi.unibe.ch>
6  1999,2000,2001,2002,2003 Carsten Pfeiffer <pfeiffer@kde.org>
7  2003 Clarence Dang <dang@kde.org>
8 
9  This library is free software; you can redistribute it and/or
10  modify it under the terms of the GNU Library General Public
11  License as published by the Free Software Foundation; either
12  version 2 of the License, or (at your option) any later version.
13 
14  This library is distributed in the hope that it will be useful,
15  but WITHOUT ANY WARRANTY; without even the implied warranty of
16  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17  Library General Public License for more details.
18 
19  You should have received a copy of the GNU Library General Public License
20  along with this library; see the file COPYING.LIB. If not, write to
21  the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
22  Boston, MA 02110-1301, USA.
23 */
24 
25 #include "kfiledialog.h"
26 
27 #include <unistd.h>
28 #include <stdlib.h>
29 #include <stdio.h>
30 
31 #include <tqptrcollection.h>
32 #include <tqcheckbox.h>
33 #include <tqcombobox.h>
34 #include <tqlabel.h>
35 #include <tqlayout.h>
36 #include <tqlineedit.h>
37 #include <tqptrlist.h>
38 #include <tqpixmap.h>
39 #include <tqtextcodec.h>
40 #include <tqtooltip.h>
41 #include <tqtimer.h>
42 #include <tqwhatsthis.h>
43 #include <tqfiledialog.h>
44 
45 #include <kaccel.h>
46 #include <kaction.h>
47 #include <kapplication.h>
48 #include <kcharsets.h>
49 #include <kcmdlineargs.h>
50 #include <kcompletionbox.h>
51 #include <kconfig.h>
52 #include <kdebug.h>
53 #include <kglobal.h>
54 #include <kglobalsettings.h>
55 #include <kiconloader.h>
56 #include <kimageio.h>
57 #include <kio/job.h>
58 #include <kio/netaccess.h>
59 #include <kio/scheduler.h>
60 #include <kio/kservicetypefactory.h>
61 #include <klocale.h>
62 #include <kmessagebox.h>
63 #include <kmimetype.h>
64 #include <kpopupmenu.h>
65 #include <kprotocolinfo.h>
66 #include <kpushbutton.h>
67 #include <krecentdirs.h>
68 #include <kshell.h>
69 #include <kstandarddirs.h>
70 #include <kstdguiitem.h>
71 #include <kstaticdeleter.h>
72 #include <ktoolbar.h>
73 #include <ktoolbarbutton.h>
74 #include <kurl.h>
75 #include <kurlcombobox.h>
76 #include <kurlcompletion.h>
77 #include <kuser.h>
78 
79 #include "config-kfile.h"
80 #include "kpreviewwidgetbase.h"
81 
82 #include <kdirselectdialog.h>
83 #include <kfileview.h>
84 #include <krecentdocument.h>
85 #include <kfilefiltercombo.h>
86 #include <kdiroperator.h>
87 #include <kimagefilepreview.h>
88 
89 #include <kfilespeedbar.h>
90 #include <kfilebookmarkhandler.h>
91 
92 #ifdef Q_WS_X11
93 #include <X11/Xlib.h>
94 #include <fixx11h.h>
95 #endif
96 
97 enum Buttons { HOTLIST_BUTTON,
98  PATH_COMBO, CONFIGURE_BUTTON };
99 
100 template class TQPtrList<KIO::StatJob>;
101 
102 namespace {
103  static void silenceQToolBar(TQtMsgType, const char *)
104  {
105  }
106 }
107 
108 struct KFileDialogPrivate
109 {
110  // the last selected url
111  KURL url;
112 
113  // the selected filenames in multiselection mode -- FIXME
114  TQString filenames;
115 
116  // the name of the filename set by setSelection
117  TQString selection;
118 
119  // now following all kind of widgets, that I need to rebuild
120  // the geometry management
121  TQBoxLayout *boxLayout;
122  TQWidget *mainWidget;
123 
124  TQLabel *locationLabel;
125 
126  // @deprecated remove in KDE4
127  TQLabel *filterLabel;
128  KURLComboBox *pathCombo;
129  KPushButton *okButton, *cancelButton;
130  KFileSpeedBar *urlBar;
131  TQHBoxLayout *urlBarLayout;
132  TQWidget *customWidget;
133 
134  // Automatically Select Extension stuff
135  TQCheckBox *autoSelectExtCheckBox;
136  bool autoSelectExtChecked; // whether or not the _user_ has checked the above box
137  TQString extension; // current extension for this filter
138 
139  TQPtrList<KIO::StatJob> statJobs;
140 
141  KURL::List urlList; //the list of selected urls
142 
143  TQStringList mimetypes; //the list of possible mimetypes to save as
144 
145  // indicates if the location edit should be kept or cleared when changing
146  // directories
147  bool keepLocation :1;
148 
149  // the KDirOperators view is set in KFileDialog::show(), so to avoid
150  // setting it again and again, we have this nice little boolean :)
151  bool hasView :1;
152 
153  bool hasDefaultFilter :1; // necessary for the operationMode
154  KFileDialog::OperationMode operationMode;
155 
156  // The file class used for KRecentDirs
157  TQString fileClass;
158 
159  KFileBookmarkHandler *bookmarkHandler;
160 
161  // the ID of the path drop down so subclasses can place their custom widgets properly
162  int m_pathComboIndex;
163 };
164 
165 KURL *KFileDialog::lastDirectory; // to set the start path
166 
167 static KStaticDeleter<KURL> ldd;
168 
169 KFileDialog::KFileDialog(const TQString& startDir, const TQString& filter,
170  TQWidget *parent, const char* name, bool modal)
171  : KDialogBase( parent, name, modal, TQString::null, 0 )
172 {
173  init( startDir, filter, 0 );
174 }
175 
176 KFileDialog::KFileDialog(const TQString& startDir, const TQString& filter,
177  TQWidget *parent, const char* name, bool modal, TQWidget* widget)
178  : KDialogBase( parent, name, modal, TQString::null, 0 )
179 {
180  init( startDir, filter, widget );
181 }
182 
183 
184 KFileDialog::~KFileDialog()
185 {
186  hide();
187 
188  KConfig *config = KGlobal::config();
189 
190  if (d->urlBar)
191  d->urlBar->save( config );
192 
193  config->sync();
194 
195  delete d->bookmarkHandler; // Should be deleted before ops!
196  delete ops;
197  delete d;
198 }
199 
200 void KFileDialog::setLocationLabel(const TQString& text)
201 {
202  d->locationLabel->setText(text);
203 }
204 
205 void KFileDialog::setFilter(const TQString& filter)
206 {
207  int pos = filter.find('/');
208 
209  // Check for an un-escaped '/', if found
210  // interpret as a MIME filter.
211 
212  if (pos > 0 && filter[pos - 1] != '\\') {
213  TQStringList filters = TQStringList::split( " ", filter );
214  setMimeFilter( filters );
215  return;
216  }
217 
218  // Strip the escape characters from
219  // escaped '/' characters.
220 
221  TQString copy (filter);
222  for (pos = 0; (pos = copy.find("\\/", pos)) != -1; ++pos)
223  copy.remove(pos, 1);
224 
225  ops->clearFilter();
226  filterWidget->setFilter(copy);
227  ops->setNameFilter(filterWidget->currentFilter());
228  d->hasDefaultFilter = false;
229  filterWidget->setEditable( true );
230 
231  updateAutoSelectExtension ();
232 }
233 
234 TQString KFileDialog::currentFilter() const
235 {
236  return filterWidget->currentFilter();
237 }
238 
239 // deprecated
240 void KFileDialog::setFilterMimeType(const TQString &label,
241  const KMimeType::List &types,
242  const KMimeType::Ptr &defaultType)
243 {
244  d->mimetypes.clear();
245  d->filterLabel->setText(label);
246 
247  KMimeType::List::ConstIterator it;
248  for( it = types.begin(); it != types.end(); ++it)
249  d->mimetypes.append( (*it)->name() );
250 
251  setMimeFilter( d->mimetypes, defaultType->name() );
252 }
253 
254 void KFileDialog::setMimeFilter( const TQStringList& mimeTypes,
255  const TQString& defaultType )
256 {
257  d->mimetypes = mimeTypes;
258  filterWidget->setMimeFilter( mimeTypes, defaultType );
259 
260  TQStringList types = TQStringList::split(" ", filterWidget->currentFilter());
261  types.append( TQString::fromLatin1( "inode/directory" ));
262  ops->clearFilter();
263  ops->setMimeFilter( types );
264  d->hasDefaultFilter = !defaultType.isEmpty();
265  filterWidget->setEditable( !d->hasDefaultFilter ||
266  d->operationMode != Saving );
267 
268  updateAutoSelectExtension ();
269 }
270 
271 void KFileDialog::clearFilter()
272 {
273  d->mimetypes.clear();
274  filterWidget->setFilter( TQString::null );
275  ops->clearFilter();
276  d->hasDefaultFilter = false;
277  filterWidget->setEditable( true );
278 
279  updateAutoSelectExtension ();
280 }
281 
282 TQString KFileDialog::currentMimeFilter() const
283 {
284  int i = filterWidget->currentItem();
285  if (filterWidget->showsAllTypes())
286  i--;
287 
288  if ((i >= 0) && (i < (int) d->mimetypes.count()))
289  return d->mimetypes[i];
290  return TQString::null; // The "all types" item has no mimetype
291 }
292 
293 KMimeType::Ptr KFileDialog::currentFilterMimeType()
294 {
295  return KMimeType::mimeType( currentMimeFilter() );
296 }
297 
298 void KFileDialog::setPreviewWidget(const TQWidget *w) {
299  ops->setPreviewWidget(w);
300  ops->clearHistory();
301  d->hasView = true;
302 }
303 
304 void KFileDialog::setPreviewWidget(const KPreviewWidgetBase *w) {
305  ops->setPreviewWidget(w);
306  ops->clearHistory();
307  d->hasView = true;
308 }
309 
310 KURL KFileDialog::getCompleteURL(const TQString &_url)
311 {
312  TQString url = KShell::tildeExpand(_url);
313  KURL u;
314 
315  if ( KURL::isRelativeURL(url) ) // only a full URL isn't relative. Even /path is.
316  {
317  if (!url.isEmpty() && !TQDir::isRelativePath(url) ) // absolute path
318  u.setPath( url );
319  else
320  {
321  u = ops->url();
322  u.addPath( url ); // works for filenames and relative paths
323  u.cleanPath(); // fix "dir/.."
324  }
325  }
326  else // complete URL
327  u = url;
328 
329  return u;
330 }
331 
332 // FIXME: check for "existing" flag here?
333 void KFileDialog::slotOk()
334 {
335  kdDebug(kfile_area) << "slotOK\n";
336 
337  if (locationEdit->lineEdit()->edited())
338  {
339  enterURL(d->pathCombo->lineEdit()->text());
340  }
341  // a list of all selected files/directories (if any)
342  // can only be used if the user didn't type any filenames/urls himself
343  const KFileItemList *items = ops->selectedItems();
344 
345  if ( (mode() & KFile::Directory) != KFile::Directory ) {
346  if ( locationEdit->currentText().stripWhiteSpace().isEmpty() ) {
347  if ( !items || items->isEmpty() )
348  {
349  TQString msg;
350  if ( d->operationMode == Saving )
351  msg = i18n("Please specify the filename to save to.");
352  else
353  msg = i18n("Please select the file to open.");
354  KMessageBox::information(this, msg);
355  return;
356  }
357 
358  // weird case: the location edit is empty, but there are
359  // highlighted files
360  else {
361 
362  bool multi = (mode() & KFile::Files) != 0;
363  KFileItemListIterator it( *items );
364  TQString endQuote = TQString::fromLatin1("\" ");
365  TQString name, files;
366  while ( it.current() ) {
367  name = (*it)->name();
368  if ( multi ) {
369  name.prepend( '"' );
370  name.append( endQuote );
371  }
372 
373  files.append( name );
374  ++it;
375  }
376  setLocationText( files );
377  return;
378  }
379  }
380  }
381 
382  bool dirOnly = ops->dirOnlyMode();
383 
384  // we can use our kfileitems, no need to parse anything
385  if ( items && !locationEdit->lineEdit()->edited() &&
386  !(items->isEmpty() && !dirOnly) ) {
387 
388  d->urlList.clear();
389  d->filenames = TQString::null;
390 
391  if ( dirOnly ) {
392  d->url = ops->url();
393  }
394  else {
395  if ( !(mode() & KFile::Files) ) {// single selection
396  d->url = items->getFirst()->url();
397  }
398 
399  else { // multi (dirs and/or files)
400  d->url = ops->url();
401  KFileItemListIterator it( *items );
402  while ( it.current() ) {
403  d->urlList.append( (*it)->url() );
404  ++it;
405  }
406  }
407  }
408 
409  KURL url = KIO::NetAccess::mostLocalURL(d->url,topLevelWidget());
410  if ( (mode() & KFile::LocalOnly) == KFile::LocalOnly &&
411  !url.isLocalFile() ) {
412 // ### after message freeze, add message for directories!
413  KMessageBox::sorry( d->mainWidget,
414  i18n("You can only select local files."),
415  i18n("Remote Files Not Accepted") );
416  return;
417  }
418 
419  d->url = url;
420  accept();
421  return;
422  }
423 
424 
425  KURL selectedURL;
426 
427  if ( (mode() & KFile::Files) == KFile::Files ) {// multiselection mode
428  TQString locationText = locationEdit->currentText();
429  if ( locationText.contains( '/' )) {
430  // relative path? -> prepend the current directory
431  KURL u( ops->url(), KShell::tildeExpand(locationText));
432  if ( u.isValid() )
433  selectedURL = u;
434  else
435  selectedURL = ops->url();
436  }
437  else // simple filename -> just use the current URL
438  selectedURL = ops->url();
439  }
440 
441  else {
442  selectedURL = getCompleteURL(locationEdit->currentText());
443 
444  // appendExtension() may change selectedURL
445  appendExtension (selectedURL);
446  }
447 
448  if ( !selectedURL.isValid() ) {
449  KMessageBox::sorry( d->mainWidget, i18n("%1\ndoes not appear to be a valid URL.\n").arg(d->url.url()), i18n("Invalid URL") );
450  return;
451  }
452 
453  KURL url = KIO::NetAccess::mostLocalURL(selectedURL,topLevelWidget());
454  if ( (mode() & KFile::LocalOnly) == KFile::LocalOnly &&
455  !url.isLocalFile() ) {
456  KMessageBox::sorry( d->mainWidget,
457  i18n("You can only select local files."),
458  i18n("Remote Files Not Accepted") );
459  return;
460  }
461 
462  d->url = url;
463 
464  // d->url is a correct URL now
465 
466  if ( (mode() & KFile::Directory) == KFile::Directory ) {
467  kdDebug(kfile_area) << "Directory" << endl;
468  bool done = true;
469  if ( d->url.isLocalFile() ) {
470  if ( locationEdit->currentText().stripWhiteSpace().isEmpty() ) {
471  TQFileInfo info( d->url.path() );
472  if ( info.isDir() ) {
473  d->filenames = TQString::null;
474  d->urlList.clear();
475  d->urlList.append( d->url );
476  accept();
477  }
478  else if (!info.exists() && (mode() & KFile::File) != KFile::File) {
479  // directory doesn't exist, create and enter it
480  if ( ops->mkdir( d->url.url(), true ))
481  return;
482  else
483  accept();
484  }
485  else { // d->url is not a directory,
486  // maybe we are in File(s) | Directory mode
487  if ( (mode() & KFile::File) == KFile::File ||
488  (mode() & KFile::Files) == KFile::Files )
489  done = false;
490  }
491  }
492  else // Directory mode, with file[s]/dir[s] selected
493  {
494  if ( mode() & KFile::ExistingOnly )
495  {
496  if ( ops->dirOnlyMode() )
497  {
498  KURL fullURL(d->url, locationEdit->currentText());
499  if ( TQFile::exists( fullURL.path() ) )
500  {
501  d->url = fullURL;
502  d->filenames = TQString::null;
503  d->urlList.clear();
504  accept();
505  return;
506  }
507  else // doesn't exist -> reject
508  return;
509  }
510  }
511 
512  d->filenames = locationEdit->currentText();
513  accept(); // what can we do?
514  }
515 
516  }
517  else { // FIXME: remote directory, should we allow that?
518 // qDebug( "**** Selected remote directory: %s", d->url.url().latin1());
519  d->filenames = TQString::null;
520  d->urlList.clear();
521  d->urlList.append( d->url );
522 
523  if ( mode() & KFile::ExistingOnly )
524  done = false;
525  else
526  accept();
527  }
528 
529  if ( done )
530  return;
531  }
532 
533  if (!kapp->authorizeURLAction("open", KURL(), d->url))
534  {
535  TQString msg = KIO::buildErrorString(KIO::ERR_ACCESS_DENIED, d->url.prettyURL());
536  KMessageBox::error( d->mainWidget, msg);
537  return;
538  }
539 
540  KIO::StatJob *job = 0L;
541  d->statJobs.clear();
542  d->filenames = KShell::tildeExpand(locationEdit->currentText());
543 
544  if ( (mode() & KFile::Files) == KFile::Files &&
545  !locationEdit->currentText().contains( '/' )) {
546  kdDebug(kfile_area) << "Files\n";
547  KURL::List list = parseSelectedURLs();
548  for ( KURL::List::ConstIterator it = list.begin();
549  it != list.end(); ++it )
550  {
551  if (!kapp->authorizeURLAction("open", KURL(), *it))
552  {
553  TQString msg = KIO::buildErrorString(KIO::ERR_ACCESS_DENIED, (*it).prettyURL());
554  KMessageBox::error( d->mainWidget, msg);
555  return;
556  }
557  }
558  for ( KURL::List::ConstIterator it = list.begin();
559  it != list.end(); ++it )
560  {
561  job = KIO::stat( *it, !(*it).isLocalFile() );
562  job->setWindow (topLevelWidget());
563  KIO::Scheduler::scheduleJob( job );
564  d->statJobs.append( job );
565  connect( job, TQT_SIGNAL( result(KIO::Job *) ),
566  TQT_SLOT( slotStatResult( KIO::Job *) ));
567  }
568  return;
569  }
570 
571  job = KIO::stat(d->url,!d->url.isLocalFile());
572  job->setWindow (topLevelWidget());
573  d->statJobs.append( job );
574  connect(job, TQT_SIGNAL(result(KIO::Job*)), TQT_SLOT(slotStatResult(KIO::Job*)));
575 }
576 
577 
578 static bool isDirectory (const KIO::UDSEntry &t)
579 {
580  bool isDir = false;
581 
582  for (KIO::UDSEntry::ConstIterator it = t.begin();
583  it != t.end();
584  it++)
585  {
586  if ((*it).m_uds == KIO::UDS_FILE_TYPE)
587  {
588  isDir = S_ISDIR ((mode_t) ((*it).m_long));
589  break;
590  }
591  }
592 
593  return isDir;
594 }
595 
596 // FIXME : count all errors and show messagebox when d->statJobs.count() == 0
597 // in case of an error, we cancel the whole operation (clear d->statJobs and
598 // don't call accept)
599 void KFileDialog::slotStatResult(KIO::Job* job)
600 {
601  kdDebug(kfile_area) << "slotStatResult" << endl;
602  KIO::StatJob *sJob = static_cast<KIO::StatJob *>( job );
603 
604  if ( !d->statJobs.removeRef( sJob ) ) {
605  return;
606  }
607 
608  int count = d->statJobs.count();
609 
610  // errors mean in general, the location is no directory ;/
611  // Can we be sure that it is exististant at all? (pfeiffer)
612  if (sJob->error() && count == 0 && !ops->dirOnlyMode())
613  {
614  accept();
615  return;
616  }
617 
618  KIO::UDSEntry t = sJob->statResult();
619  if (isDirectory (t))
620  {
621  if ( ops->dirOnlyMode() )
622  {
623  d->filenames = TQString::null;
624  d->urlList.clear();
625  accept();
626  }
627  else // in File[s] mode, directory means error -> cd into it
628  {
629  if ( count == 0 ) {
630  locationEdit->clearEdit();
631  locationEdit->lineEdit()->setEdited( false );
632  setURL( sJob->url() );
633  }
634  }
635  d->statJobs.clear();
636  return;
637  }
638  else if ( ops->dirOnlyMode() )
639  {
640  return; // ### error message?
641  }
642 
643  kdDebug(kfile_area) << "filename " << sJob->url().url() << endl;
644 
645  if ( count == 0 )
646  accept();
647 }
648 
649 void KFileDialog::accept()
650 {
651  setResult( TQDialog::Accepted ); // parseSelectedURLs() checks that
652 
653  *lastDirectory = ops->url();
654  if (!d->fileClass.isEmpty())
655  KRecentDirs::add(d->fileClass, ops->url().url());
656 
657  // clear the topmost item, we insert it as full path later on as item 1
658  locationEdit->changeItem( TQString::null, 0 );
659 
660  KURL::List list = selectedURLs();
661  TQValueListConstIterator<KURL> it = list.begin();
662  for ( ; it != list.end(); ++it ) {
663  const KURL& url = *it;
664  // we strip the last slash (-1) because KURLComboBox does that as well
665  // when operating in file-mode. If we wouldn't , dupe-finding wouldn't
666  // work.
667  TQString file = url.isLocalFile() ? url.path(-1) : url.prettyURL(-1);
668 
669  // remove dupes
670  for ( int i = 1; i < locationEdit->count(); i++ ) {
671  if ( locationEdit->text( i ) == file ) {
672  locationEdit->removeItem( i-- );
673  break;
674  }
675  }
676  locationEdit->insertItem( file, 1 );
677  }
678 
679  KConfig *config = KGlobal::config();
680  config->setForceGlobal( true );
681  writeConfig( config, ConfigGroup );
682  config->setForceGlobal( false );
683 
684  saveRecentFiles( config );
685  config->sync();
686 
687  KDialogBase::accept();
688 
689  addToRecentDocuments();
690 
691  if ( (mode() & KFile::Files) != KFile::Files ) // single selection
692  emit fileSelected(d->url.url());
693 
694  ops->close();
695  emit okClicked();
696 }
697 
698 
699 void KFileDialog::fileHighlighted(const KFileItem *i)
700 {
701  if (i && i->isDir())
702  return;
703 
704 
705  if ( (ops->mode() & KFile::Files) != KFile::Files ) {
706  if ( !i )
707  return;
708 
709  d->url = i->url();
710 
711  if ( !locationEdit->hasFocus() ) { // don't disturb while editing
712  setLocationText( i->name() );
713  }
714  emit fileHighlighted(d->url.url());
715  }
716 
717  else {
718  multiSelectionChanged();
719  emit selectionChanged();
720  }
721 }
722 
723 void KFileDialog::fileSelected(const KFileItem *i)
724 {
725  if (i && i->isDir())
726  return;
727 
728  if ( (ops->mode() & KFile::Files) != KFile::Files ) {
729  if ( !i )
730  return;
731 
732  d->url = i->url();
733  setLocationText( i->name() );
734  }
735  else {
736  multiSelectionChanged();
737  emit selectionChanged();
738  }
739  slotOk();
740 }
741 
742 
743 // I know it's slow to always iterate thru the whole filelist
744 // (ops->selectedItems()), but what can we do?
745 void KFileDialog::multiSelectionChanged()
746 {
747  if ( locationEdit->hasFocus() ) // don't disturb
748  return;
749 
750  locationEdit->lineEdit()->setEdited( false );
751  KFileItem *item;
752  const KFileItemList *list = ops->selectedItems();
753  if ( !list ) {
754  locationEdit->clearEdit();
755  return;
756  }
757 
758  static const TQString &begin = KGlobal::staticQString(" \"");
759  KFileItemListIterator it ( *list );
760  TQString text;
761  while ( (item = it.current()) ) {
762  text.append( begin ).append( item->name() ).append( '\"' );
763  ++it;
764  }
765 
766  setLocationText( text.stripWhiteSpace() );
767 }
768 
769 void KFileDialog::setLocationText( const TQString& text )
770 {
771  // setCurrentItem() will cause textChanged() being emitted,
772  // so slotLocationChanged() will be called. Make sure we don't clear
773  // the KDirOperator's view-selection in there
774  disconnect( locationEdit, TQT_SIGNAL( textChanged( const TQString& ) ),
775  this, TQT_SLOT( slotLocationChanged( const TQString& ) ) );
776  locationEdit->setCurrentItem( 0 );
777  connect( locationEdit, TQT_SIGNAL( textChanged( const TQString& ) ),
778  TQT_SLOT( slotLocationChanged( const TQString& )) );
779  locationEdit->setEditText( text );
780 
781  // don't change selection when user has clicked on an item
782  if ( d->operationMode == Saving && !locationEdit->isVisible())
783  setNonExtSelection();
784 }
785 
786 static const char autocompletionWhatsThisText[] = I18N_NOOP("<p>While typing in the text area, you may be presented "
787  "with possible matches. "
788  "This feature can be controlled by clicking with the right mouse button "
789  "and selecting a preferred mode from the <b>Text Completion</b> menu.") "</qt>";
790 void KFileDialog::updateLocationWhatsThis (void)
791 {
792  TQString whatsThisText;
793  if (d->operationMode == KFileDialog::Saving)
794  {
795  whatsThisText = "<qt>" + i18n("This is the name to save the file as.") +
796  i18n (autocompletionWhatsThisText);
797  }
798  else if (ops->mode() & KFile::Files)
799  {
800  whatsThisText = "<qt>" + i18n("This is the list of files to open. More than "
801  "one file can be specified by listing several "
802  "files, separated by spaces.") +
803  i18n (autocompletionWhatsThisText);
804  }
805  else
806  {
807  whatsThisText = "<qt>" + i18n("This is the name of the file to open.") +
808  i18n (autocompletionWhatsThisText);
809  }
810 
811  TQWhatsThis::add(d->locationLabel, whatsThisText);
812  TQWhatsThis::add(locationEdit, whatsThisText);
813 }
814 
815 void KFileDialog::init(const TQString& startDir, const TQString& filter, TQWidget* widget)
816 {
817  initStatic();
818  d = new KFileDialogPrivate();
819 
820  d->boxLayout = 0;
821  d->keepLocation = false;
822  d->operationMode = Opening;
823  d->bookmarkHandler = 0;
824  d->hasDefaultFilter = false;
825  d->hasView = false;
826  d->mainWidget = new TQWidget( this, "KFileDialog::mainWidget");
827  setMainWidget( d->mainWidget );
828  d->okButton = new KPushButton( KStdGuiItem::ok(), d->mainWidget );
829  d->okButton->setDefault( true );
830  d->cancelButton = new KPushButton(KStdGuiItem::cancel(), d->mainWidget);
831  connect( d->okButton, TQT_SIGNAL( clicked() ), TQT_SLOT( slotOk() ));
832  connect( d->cancelButton, TQT_SIGNAL( clicked() ), TQT_SLOT( slotCancel() ));
833  d->customWidget = widget;
834  d->autoSelectExtCheckBox = 0; // delayed loading
835  d->autoSelectExtChecked = false;
836  d->urlBar = 0; // delayed loading
837 
838  TQtMsgHandler oldHandler = tqInstallMsgHandler( silenceQToolBar );
839  toolbar = new KToolBar( d->mainWidget, "KFileDialog::toolbar", true);
840  toolbar->setFlat(true);
841  tqInstallMsgHandler( oldHandler );
842 
843  d->pathCombo = new KURLComboBox( KURLComboBox::Directories, true,
844  toolbar, "path combo" );
845  TQToolTip::add( d->pathCombo, i18n("Current location") );
846  TQWhatsThis::add( d->pathCombo, "<qt>" + i18n("This is the currently listed location. "
847  "The drop-down list also lists commonly used locations. "
848  "This includes standard locations, such as your home folder, as well as "
849  "locations that have been visited recently.") + i18n (autocompletionWhatsThisText));
850 
851  KURL u;
852  u.setPath( TQDir::rootDirPath() );
853  TQString text = i18n("Root Folder: %1").arg( u.path() );
854  d->pathCombo->addDefaultURL( u,
855  KMimeType::pixmapForURL( u, 0, KIcon::Small ),
856  text );
857 
858  u.setPath( TQDir::homeDirPath() );
859  text = i18n("Home Folder: %1").arg( u.path( +1 ) );
860  d->pathCombo->addDefaultURL( u, KMimeType::pixmapForURL( u, 0, KIcon::Small ),
861  text );
862 
863  KURL docPath;
864  docPath.setPath( KGlobalSettings::documentPath() );
865  if ( (u.path(+1) != docPath.path(+1)) &&
866  TQDir(docPath.path(+1)).exists() )
867  {
868  text = i18n("Documents: %1").arg( docPath.path( +1 ) );
869  d->pathCombo->addDefaultURL( docPath,
870  KMimeType::pixmapForURL( docPath, 0, KIcon::Small ),
871  text );
872  }
873 
874  u.setPath( KGlobalSettings::desktopPath() );
875  text = i18n("Desktop: %1").arg( u.path( +1 ) );
876  d->pathCombo->addDefaultURL( u,
877  KMimeType::pixmapForURL( u, 0, KIcon::Small ),
878  text );
879 
880  d->url = getStartURL( startDir, d->fileClass );
881  d->selection = d->url.url();
882 
883  // If local, check it exists. If not, go up until it exists.
884  if ( d->url.isLocalFile() )
885  {
886  if ( !TQFile::exists( d->url.path() ) )
887  {
888  d->url = d->url.upURL();
889  TQDir dir( d->url.path() );
890  while ( !dir.exists() )
891  {
892  d->url = d->url.upURL();
893  dir.setPath( d->url.path() );
894  }
895  }
896  }
897 
898  ops = new KDirOperator(d->url, d->mainWidget, "KFileDialog::ops");
899  ops->setOnlyDoubleClickSelectsFiles( true );
900  connect(ops, TQT_SIGNAL(urlEntered(const KURL&)),
901  TQT_SLOT(urlEntered(const KURL&)));
902  connect(ops, TQT_SIGNAL(fileHighlighted(const KFileItem *)),
903  TQT_SLOT(fileHighlighted(const KFileItem *)));
904  connect(ops, TQT_SIGNAL(fileSelected(const KFileItem *)),
905  TQT_SLOT(fileSelected(const KFileItem *)));
906  connect(ops, TQT_SIGNAL(finishedLoading()),
907  TQT_SLOT(slotLoadingFinished()));
908 
909  ops->setupMenu(KDirOperator::SortActions |
910  KDirOperator::FileActions |
911  KDirOperator::ViewActions);
912  KActionCollection *coll = ops->actionCollection();
913 
914  // plug nav items into the toolbar
915  coll->action( "up" )->plug( toolbar );
916  coll->action( "up" )->setWhatsThis(i18n("<qt>Click this button to enter the parent folder.<p>"
917  "For instance, if the current location is file:/home/%1 clicking this "
918  "button will take you to file:/home.</qt>").arg( KUser().loginName() ));
919  coll->action( "back" )->plug( toolbar );
920  coll->action( "back" )->setWhatsThis(i18n("Click this button to move backwards one step in the browsing history."));
921  coll->action( "forward" )->plug( toolbar );
922  coll->action( "forward" )->setWhatsThis(i18n("Click this button to move forward one step in the browsing history."));
923  coll->action( "reload" )->plug( toolbar );
924  coll->action( "reload" )->setWhatsThis(i18n("Click this button to reload the contents of the current location."));
925  coll->action( "mkdir" )->setShortcut(Key_F10);
926  coll->action( "mkdir" )->plug( toolbar );
927  coll->action( "mkdir" )->setWhatsThis(i18n("Click this button to create a new folder."));
928 
929  KToggleAction *showSidebarAction =
930  new KToggleAction(i18n("Show Quick Access Navigation Panel"), Key_F9, coll,"toggleSpeedbar");
931  showSidebarAction->setCheckedState(i18n("Hide Quick Access Navigation Panel"));
932  connect( showSidebarAction, TQT_SIGNAL( toggled( bool ) ),
933  TQT_SLOT( toggleSpeedbar( bool )) );
934 
935  KToggleAction *showBookmarksAction =
936  new KToggleAction(i18n("Show Bookmarks"), 0, coll, "toggleBookmarks");
937  showBookmarksAction->setCheckedState(i18n("Hide Bookmarks"));
938  connect( showBookmarksAction, TQT_SIGNAL( toggled( bool ) ),
939  TQT_SLOT( toggleBookmarks( bool )) );
940 
941  KActionMenu *menu = new KActionMenu( i18n("Configure"), "configure", TQT_TQOBJECT(this), "extra menu" );
942  menu->setWhatsThis(i18n("<qt>This is the configuration menu for the file dialog. "
943  "Various options can be accessed from this menu including: <ul>"
944  "<li>how files are sorted in the list</li>"
945  "<li>types of view, including icon and list</li>"
946  "<li>showing of hidden files</li>"
947  "<li>the Quick Access navigation panel</li>"
948  "<li>file previews</li>"
949  "<li>separating folders from files</li></ul></qt>"));
950  menu->insert( coll->action( "sorting menu" ));
951  menu->insert( coll->action( "separator" ));
952  coll->action( "short view" )->setShortcut(Key_F6);
953  menu->insert( coll->action( "short view" ));
954  coll->action( "detailed view" )->setShortcut(Key_F7);
955  menu->insert( coll->action( "detailed view" ));
956  menu->insert( coll->action( "separator" ));
957  coll->action( "show hidden" )->setShortcut(Key_F8);
958  menu->insert( coll->action( "show hidden" ));
959  menu->insert( showSidebarAction );
960  menu->insert( showBookmarksAction );
961  coll->action( "preview" )->setShortcut(Key_F11);
962  menu->insert( coll->action( "preview" ));
963  coll->action( "separate dirs" )->setShortcut(Key_F12);
964  menu->insert( coll->action( "separate dirs" ));
965 
966  menu->setDelayed( false );
967  connect( menu->popupMenu(), TQT_SIGNAL( aboutToShow() ),
968  ops, TQT_SLOT( updateSelectionDependentActions() ));
969  menu->plug( toolbar );
970 
971  //Insert a separator.
972  KToolBarSeparator* spacerWidget = new KToolBarSeparator(Qt::Horizontal, false /*no line*/,
973  toolbar);
974  d->m_pathComboIndex = toolbar->insertWidget(-1, -1, spacerWidget);
975  toolbar->insertWidget(PATH_COMBO, 0, d->pathCombo);
976 
977 
978  toolbar->setItemAutoSized (PATH_COMBO);
979  toolbar->setIconText(KToolBar::IconOnly);
980  toolbar->setBarPos(KToolBar::Top);
981  toolbar->setMovingEnabled(false);
982  toolbar->adjustSize();
983 
984  KURLCompletion *pathCompletionObj = new KURLCompletion( KURLCompletion::DirCompletion );
985  d->pathCombo->setCompletionObject( pathCompletionObj );
986  d->pathCombo->setAutoDeleteCompletionObject( true );
987 
988  connect( d->pathCombo, TQT_SIGNAL( urlActivated( const KURL& )),
989  this, TQT_SLOT( enterURL( const KURL& ) ));
990  connect( d->pathCombo, TQT_SIGNAL( returnPressed( const TQString& )),
991  this, TQT_SLOT( enterURL( const TQString& ) ));
992  connect( d->pathCombo, TQT_SIGNAL( activated( const TQString& )),
993  this, TQT_SLOT( enterURL( const TQString& ) ));
994 
995  TQString whatsThisText;
996 
997  // the Location label/edit
998  d->locationLabel = new TQLabel(i18n("&Location:"), d->mainWidget);
999  locationEdit = new KURLComboBox(KURLComboBox::Files, true,
1000  d->mainWidget, "LocationEdit");
1001  connect( locationEdit, TQT_SIGNAL( textChanged( const TQString& ) ),
1002  TQT_SLOT( slotLocationChanged( const TQString& )) );
1003 
1004  updateLocationWhatsThis ();
1005  d->locationLabel->setBuddy(locationEdit);
1006 
1007  locationEdit->setFocus();
1008  KURLCompletion *fileCompletionObj = new KURLCompletion( KURLCompletion::FileCompletion );
1009  TQString dir = d->url.url(+1);
1010  pathCompletionObj->setDir( dir );
1011  fileCompletionObj->setDir( dir );
1012  locationEdit->setCompletionObject( fileCompletionObj );
1013  locationEdit->setAutoDeleteCompletionObject( true );
1014  connect( fileCompletionObj, TQT_SIGNAL( match( const TQString& ) ),
1015  TQT_SLOT( fileCompletion( const TQString& )) );
1016 
1017  connect( locationEdit, TQT_SIGNAL( returnPressed() ),
1018  this, TQT_SLOT( slotOk()));
1019  connect(locationEdit, TQT_SIGNAL( activated( const TQString& )),
1020  this, TQT_SLOT( locationActivated( const TQString& ) ));
1021 
1022  // the Filter label/edit
1023  whatsThisText = i18n("<qt>This is the filter to apply to the file list. "
1024  "File names that do not match the filter will not be shown.<p>"
1025  "You may select from one of the preset filters in the "
1026  "drop down menu, or you may enter a custom filter "
1027  "directly into the text area.<p>"
1028  "Wildcards such as * and ? are allowed.</qt>");
1029  d->filterLabel = new TQLabel(i18n("&Filter:"), d->mainWidget);
1030  TQWhatsThis::add(d->filterLabel, whatsThisText);
1031  filterWidget = new KFileFilterCombo(d->mainWidget,
1032  "KFileDialog::filterwidget");
1033  TQWhatsThis::add(filterWidget, whatsThisText);
1034  setFilter(filter);
1035  d->filterLabel->setBuddy(filterWidget);
1036  connect(filterWidget, TQT_SIGNAL(filterChanged()), TQT_SLOT(slotFilterChanged()));
1037 
1038  // the Automatically Select Extension checkbox
1039  // (the text, visibility etc. is set in updateAutoSelectExtension(), which is called by readConfig())
1040  d->autoSelectExtCheckBox = new TQCheckBox (d->mainWidget);
1041  connect(d->autoSelectExtCheckBox, TQT_SIGNAL(clicked()), TQT_SLOT(slotAutoSelectExtClicked()));
1042 
1043  initGUI(); // activate GM
1044 
1045  KConfig* config = KGlobal::config();
1046  readRecentFiles( config );
1047 
1048  adjustSize();
1049 
1050  ops->setViewConfig( config, ConfigGroup );
1051  readConfig( config, ConfigGroup );
1052  setSelection(d->selection);
1053 }
1054 
1055 void KFileDialog::initSpeedbar()
1056 {
1057  d->urlBar = new KFileSpeedBar( d->mainWidget, "url bar" );
1058  connect( d->urlBar, TQT_SIGNAL( activated( const KURL& )),
1059  TQT_SLOT( enterURL( const KURL& )) );
1060 
1061  // need to set the current url of the urlbar manually (not via urlEntered()
1062  // here, because the initial url of KDirOperator might be the same as the
1063  // one that will be set later (and then urlEntered() won't be emitted).
1064  // ### REMOVE THIS when KDirOperator's initial URL (in the c'tor) is gone.
1065  d->urlBar->setCurrentItem( d->url );
1066 
1067  d->urlBarLayout->insertWidget( 0, d->urlBar );
1068 }
1069 
1070 void KFileDialog::initGUI()
1071 {
1072  delete d->boxLayout; // deletes all sub layouts
1073 
1074  d->boxLayout = new TQVBoxLayout( d->mainWidget, 0, KDialog::spacingHint());
1075  d->boxLayout->addWidget(toolbar, AlignTop);
1076 
1077  d->urlBarLayout = new TQHBoxLayout( d->boxLayout ); // needed for the urlBar that may appear
1078  TQVBoxLayout *vbox = new TQVBoxLayout( d->urlBarLayout );
1079 
1080  vbox->addWidget(ops, 4);
1081  vbox->addSpacing(3);
1082 
1083  TQGridLayout* lafBox= new TQGridLayout(2, 3, KDialog::spacingHint());
1084 
1085  lafBox->addWidget(d->locationLabel, 0, 0, Qt::AlignVCenter);
1086  lafBox->addWidget(locationEdit, 0, 1, Qt::AlignVCenter);
1087  lafBox->addWidget(d->okButton, 0, 2, Qt::AlignVCenter);
1088 
1089  lafBox->addWidget(d->filterLabel, 1, 0, Qt::AlignVCenter);
1090  lafBox->addWidget(filterWidget, 1, 1, Qt::AlignVCenter);
1091  lafBox->addWidget(d->cancelButton, 1, 2, Qt::AlignVCenter);
1092 
1093  lafBox->setColStretch(1, 4);
1094 
1095  vbox->addLayout(TQT_TQLAYOUT(lafBox), 0);
1096  vbox->addSpacing(3);
1097 
1098  // add the Automatically Select Extension checkbox
1099  vbox->addWidget (d->autoSelectExtCheckBox);
1100  vbox->addSpacing (3);
1101 
1102  setTabOrder(ops, d->autoSelectExtCheckBox);
1103  setTabOrder (d->autoSelectExtCheckBox, locationEdit);
1104  setTabOrder(locationEdit, filterWidget);
1105  setTabOrder(filterWidget, d->okButton);
1106  setTabOrder(d->okButton, d->cancelButton);
1107  setTabOrder(d->cancelButton, d->pathCombo);
1108  setTabOrder(d->pathCombo, ops);
1109 
1110  // If a custom widget was specified...
1111  if ( d->customWidget != 0 )
1112  {
1113  // ...add it to the dialog, below the filter list box.
1114 
1115  // Change the parent so that this widget is a child of the main widget
1116  d->customWidget->reparent( d->mainWidget, TQPoint() );
1117 
1118  vbox->addWidget( d->customWidget );
1119  vbox->addSpacing(3);
1120 
1121  // FIXME: This should adjust the tab orders so that the custom widget
1122  // comes after the Cancel button. The code appears to do this, but the result
1123  // somehow screws up the tab order of the file path combo box. Not a major
1124  // problem, but ideally the tab order with a custom widget should be
1125  // the same as the order without one.
1126  setTabOrder(d->cancelButton, d->customWidget);
1127  setTabOrder(d->customWidget, d->pathCombo);
1128  }
1129  else
1130  {
1131  setTabOrder(d->cancelButton, d->pathCombo);
1132  }
1133 
1134  setTabOrder(d->pathCombo, ops);
1135 }
1136 
1137 void KFileDialog::slotFilterChanged()
1138 {
1139  TQString filter = filterWidget->currentFilter();
1140  ops->clearFilter();
1141 
1142  if ( filter.find( '/' ) > -1 ) {
1143  TQStringList types = TQStringList::split( " ", filter );
1144  types.prepend( "inode/directory" );
1145  ops->setMimeFilter( types );
1146  }
1147  else
1148  ops->setNameFilter( filter );
1149 
1150  ops->updateDir();
1151 
1152  updateAutoSelectExtension ();
1153 
1154  emit filterChanged( filter );
1155 }
1156 
1157 
1158 void KFileDialog::setURL(const KURL& url, bool clearforward)
1159 {
1160  d->selection = TQString::null;
1161  ops->setURL( url, clearforward);
1162 }
1163 
1164 // Protected
1165 void KFileDialog::urlEntered(const KURL& url)
1166 {
1167  TQString filename = locationEdit->currentText();
1168  d->selection = TQString::null;
1169 
1170  if ( d->pathCombo->count() != 0 ) { // little hack
1171  d->pathCombo->setURL( url );
1172  }
1173 
1174  locationEdit->blockSignals( true );
1175  locationEdit->setCurrentItem( 0 );
1176  if ( d->keepLocation )
1177  locationEdit->setEditText( filename );
1178 
1179  locationEdit->blockSignals( false );
1180 
1181  TQString dir = url.url(+1);
1182  static_cast<KURLCompletion*>( d->pathCombo->completionObject() )->setDir( dir );
1183  static_cast<KURLCompletion*>( locationEdit->completionObject() )->setDir( dir );
1184 
1185  if ( d->urlBar )
1186  d->urlBar->setCurrentItem( url );
1187 }
1188 
1189 void KFileDialog::locationActivated( const TQString& url )
1190 {
1191  // This guard prevents any URL _typed_ by the user from being interpreted
1192  // twice (by returnPressed/slotOk and here, activated/locationActivated)
1193  // after the user presses Enter. Without this, _both_ setSelection and
1194  // slotOk would "u.addPath( url )" ...so instead we leave it up to just
1195  // slotOk....
1196  if (!locationEdit->lineEdit()->edited())
1197  setSelection( url );
1198 }
1199 
1200 void KFileDialog::enterURL( const KURL& url)
1201 {
1202  setURL( url );
1203 }
1204 
1205 void KFileDialog::enterURL( const TQString& url )
1206 {
1207  setURL( KURL::fromPathOrURL( KURLCompletion::replacedPath( url, true, true )) );
1208 }
1209 
1210 void KFileDialog::toolbarCallback(int) // SLOT
1211 {
1212  /*
1213  * yes, nothing uses this anymore.
1214  * it used to be used to show the configure dialog
1215  */
1216 }
1217 
1218 
1219 void KFileDialog::setSelection(const TQString& url)
1220 {
1221  kdDebug(kfile_area) << "setSelection " << url << endl;
1222 
1223  if (url.isEmpty()) {
1224  d->selection = TQString::null;
1225  return;
1226  }
1227 
1228  KURL u = getCompleteURL(url);
1229  if (!u.isValid()) { // if it still is
1230  kdWarning() << url << " is not a correct argument for setSelection!" << endl;
1231  return;
1232  }
1233 
1234  if (!KProtocolInfo::supportsListing(u)) {
1235  locationEdit->lineEdit()->setEdited( true );
1236  return;
1237  }
1238 
1239  /* we strip the first / from the path to avoid file://usr which means
1240  * / on host usr
1241  */
1242  KFileItem i(KFileItem::Unknown, KFileItem::Unknown, u, true );
1243  // KFileItem i(u.path());
1244  if ( i.isDir() && u.isLocalFile() && TQFile::exists( u.path() ) ) {
1245  // trust isDir() only if the file is
1246  // local (we cannot stat non-local urls) and if it exists!
1247  // (as KFileItem does not check if the file exists or not
1248  // -> the statbuffer is undefined -> isDir() is unreliable) (Simon)
1249  setURL(u, true);
1250  }
1251  else {
1252  TQString filename = u.url();
1253  int sep = filename.findRev('/');
1254  if (sep >= 0) { // there is a / in it
1255  if ( KProtocolInfo::supportsListing( u )) {
1256  KURL dir(u);
1257  dir.setQuery( TQString::null );
1258  dir.setFileName( TQString::null );
1259  setURL(dir, true );
1260  }
1261 
1262  // filename must be decoded, or "name with space" would become
1263  // "name%20with%20space", so we use KURL::fileName()
1264  filename = u.fileName();
1265  kdDebug(kfile_area) << "filename " << filename << endl;
1266  d->selection = filename;
1267  setLocationText( filename );
1268 
1269  // tell the line edit that it has been edited
1270  // otherwise we won't know this was set by the user
1271  // and it will be ignored if there has been an
1272  // auto completion. this caused bugs where automcompletion
1273  // would start, the user would pick something from the
1274  // history and then hit Ok only to get the autocompleted
1275  // selection. OOOPS.
1276  locationEdit->lineEdit()->setEdited( true );
1277  }
1278 
1279  d->url = ops->url();
1280  d->url.addPath(filename);
1281  }
1282 }
1283 
1284 void KFileDialog::slotLoadingFinished()
1285 {
1286  if ( !d->selection.isNull() )
1287  ops->setCurrentItem( d->selection );
1288 }
1289 
1290 // ### remove in KDE4
1291 void KFileDialog::pathComboChanged( const TQString& )
1292 {
1293 }
1294 void KFileDialog::dirCompletion( const TQString& ) // SLOT
1295 {
1296 }
1297 void KFileDialog::fileCompletion( const TQString& match )
1298 {
1299  if ( match.isEmpty() && ops->view() )
1300  ops->view()->clearSelection();
1301  else
1302  ops->setCurrentItem( match );
1303 }
1304 
1305 void KFileDialog::slotLocationChanged( const TQString& text )
1306 {
1307  if ( text.isEmpty() && ops->view() )
1308  ops->view()->clearSelection();
1309 
1310  updateFilter();
1311 }
1312 
1313 void KFileDialog::updateStatusLine(int /* dirs */, int /* files */)
1314 {
1315  kdWarning() << "KFileDialog::updateStatusLine is deprecated! The status line no longer exists. Do not try and use it!" << endl;
1316 }
1317 
1318 TQString KFileDialog::getOpenFileName(const TQString& startDir,
1319  const TQString& filter,
1320  TQWidget *parent, const TQString& caption)
1321 {
1322  KFileDialog dlg(startDir, filter, parent, "filedialog", true);
1323  dlg.setOperationMode( Opening );
1324 
1325  dlg.setMode( KFile::File | KFile::LocalOnly );
1326  dlg.setCaption(caption.isNull() ? i18n("Open") : caption);
1327 
1328  dlg.ops->clearHistory();
1329  dlg.exec();
1330 
1331  return dlg.selectedFile();
1332 }
1333 
1334 TQString KFileDialog::getOpenFileNameWId(const TQString& startDir,
1335  const TQString& filter,
1336  WId parent_id, const TQString& caption)
1337 {
1338  TQWidget* parent = TQT_TQWIDGET(TQWidget::find( parent_id ));
1339  KFileDialog dlg(startDir, filter, parent, "filedialog", true);
1340 #ifdef Q_WS_X11
1341  if( parent == NULL && parent_id != 0 )
1342  XSetTransientForHint( qt_xdisplay(), dlg.winId(), parent_id );
1343 #else
1344  // TODO
1345 #endif
1346 
1347  dlg.setOperationMode( KFileDialog::Opening );
1348 
1349  dlg.setMode( KFile::File | KFile::LocalOnly );
1350  dlg.setCaption(caption.isNull() ? i18n("Open") : caption);
1351 
1352  dlg.ops->clearHistory();
1353  dlg.exec();
1354 
1355  return dlg.selectedFile();
1356 }
1357 
1358 TQStringList KFileDialog::getOpenFileNames(const TQString& startDir,
1359  const TQString& filter,
1360  TQWidget *parent,
1361  const TQString& caption)
1362 {
1363  KFileDialog dlg(startDir, filter, parent, "filedialog", true);
1364  dlg.setOperationMode( Opening );
1365 
1366  dlg.setCaption(caption.isNull() ? i18n("Open") : caption);
1367  dlg.setMode(KFile::Files | KFile::LocalOnly);
1368  dlg.ops->clearHistory();
1369  dlg.exec();
1370 
1371  return dlg.selectedFiles();
1372 }
1373 
1374 KURL KFileDialog::getOpenURL(const TQString& startDir, const TQString& filter,
1375  TQWidget *parent, const TQString& caption)
1376 {
1377  KFileDialog dlg(startDir, filter, parent, "filedialog", true);
1378  dlg.setOperationMode( Opening );
1379 
1380  dlg.setCaption(caption.isNull() ? i18n("Open") : caption);
1381  dlg.setMode( KFile::File );
1382  dlg.ops->clearHistory();
1383  dlg.exec();
1384 
1385  return dlg.selectedURL();
1386 }
1387 
1388 KURL::List KFileDialog::getOpenURLs(const TQString& startDir,
1389  const TQString& filter,
1390  TQWidget *parent,
1391  const TQString& caption)
1392 {
1393  KFileDialog dlg(startDir, filter, parent, "filedialog", true);
1394  dlg.setOperationMode( Opening );
1395 
1396  dlg.setCaption(caption.isNull() ? i18n("Open") : caption);
1397  dlg.setMode(KFile::Files);
1398  dlg.ops->clearHistory();
1399  dlg.exec();
1400 
1401  return dlg.selectedURLs();
1402 }
1403 
1404 KURL KFileDialog::getExistingURL(const TQString& startDir,
1405  TQWidget *parent,
1406  const TQString& caption)
1407 {
1408  return KDirSelectDialog::selectDirectory(startDir, false, parent, caption);
1409 }
1410 
1411 TQString KFileDialog::getExistingDirectory(const TQString& startDir,
1412  TQWidget *parent,
1413  const TQString& caption)
1414 {
1415 #ifdef Q_WS_WIN
1416  return TQFileDialog::getExistingDirectory(startDir, parent, "getExistingDirectory",
1417  caption, true, true);
1418 #else
1419  KURL url = KDirSelectDialog::selectDirectory(startDir, true, parent,
1420  caption);
1421  if ( url.isValid() )
1422  return url.path();
1423 
1424  return TQString::null;
1425 #endif
1426 }
1427 
1428 KURL KFileDialog::getImageOpenURL( const TQString& startDir, TQWidget *parent,
1429  const TQString& caption)
1430 {
1431  TQStringList mimetypes = KImageIO::mimeTypes( KImageIO::Reading );
1432  KFileDialog dlg(startDir,
1433  mimetypes.join(" "),
1434  parent, "filedialog", true);
1435  dlg.setOperationMode( Opening );
1436  dlg.setCaption( caption.isNull() ? i18n("Open") : caption );
1437  dlg.setMode( KFile::File );
1438 
1439  KImageFilePreview *ip = new KImageFilePreview( &dlg );
1440  dlg.setPreviewWidget( ip );
1441  dlg.exec();
1442 
1443  return dlg.selectedURL();
1444 }
1445 
1446 KURL KFileDialog::selectedURL() const
1447 {
1448  if ( result() == TQDialog::Accepted )
1449  return d->url;
1450  else
1451  return KURL();
1452 }
1453 
1454 KURL::List KFileDialog::selectedURLs() const
1455 {
1456  KURL::List list;
1457  if ( result() == TQDialog::Accepted ) {
1458  if ( (ops->mode() & KFile::Files) == KFile::Files )
1459  list = parseSelectedURLs();
1460  else
1461  list.append( d->url );
1462  }
1463  return list;
1464 }
1465 
1466 
1467 KURL::List& KFileDialog::parseSelectedURLs() const
1468 {
1469  if ( d->filenames.isEmpty() ) {
1470  return d->urlList;
1471  }
1472 
1473  d->urlList.clear();
1474  if ( d->filenames.contains( '/' )) { // assume _one_ absolute filename
1475  static const TQString &prot = KGlobal::staticQString(":/");
1476  KURL u;
1477  if ( d->filenames.find( prot ) != -1 )
1478  u = d->filenames;
1479  else
1480  u.setPath( d->filenames );
1481 
1482  if ( u.isValid() )
1483  d->urlList.append( u );
1484  else
1485  KMessageBox::error( d->mainWidget,
1486  i18n("The chosen filenames do not\n"
1487  "appear to be valid."),
1488  i18n("Invalid Filenames") );
1489  }
1490 
1491  else
1492  d->urlList = tokenize( d->filenames );
1493 
1494  d->filenames = TQString::null; // indicate that we parsed that one
1495 
1496  return d->urlList;
1497 }
1498 
1499 
1500 // FIXME: current implementation drawback: a filename can't contain quotes
1501 KURL::List KFileDialog::tokenize( const TQString& line ) const
1502 {
1503  KURL::List urls;
1504  KURL u( ops->url() );
1505  TQString name;
1506 
1507  int count = line.contains( '"' );
1508  if ( count == 0 ) { // no " " -> assume one single file
1509  u.setFileName( line );
1510  if ( u.isValid() )
1511  urls.append( u );
1512 
1513  return urls;
1514  }
1515 
1516  if ( (count % 2) == 1 ) { // odd number of " -> error
1517  TQWidget *that = const_cast<KFileDialog *>(this);
1518  KMessageBox::sorry(that, i18n("The requested filenames\n"
1519  "%1\n"
1520  "do not appear to be valid;\n"
1521  "make sure every filename is enclosed in double quotes.").arg(line),
1522  i18n("Filename Error"));
1523  return urls;
1524  }
1525 
1526  int start = 0;
1527  int index1 = -1, index2 = -1;
1528  while ( true ) {
1529  index1 = line.find( '"', start );
1530  index2 = line.find( '"', index1 + 1 );
1531 
1532  if ( index1 < 0 )
1533  break;
1534 
1535  // get everything between the " "
1536  name = line.mid( index1 + 1, index2 - index1 - 1 );
1537  u.setFileName( name );
1538  if ( u.isValid() )
1539  urls.append( u );
1540 
1541  start = index2 + 1;
1542  }
1543  return urls;
1544 }
1545 
1546 
1547 TQString KFileDialog::selectedFile() const
1548 {
1549  if ( result() == TQDialog::Accepted )
1550  {
1551  KURL url = KIO::NetAccess::mostLocalURL(d->url,topLevelWidget());
1552  if (url.isLocalFile())
1553  return url.path();
1554  else {
1555  KMessageBox::sorry( d->mainWidget,
1556  i18n("You can only select local files."),
1557  i18n("Remote Files Not Accepted") );
1558  }
1559  }
1560  return TQString::null;
1561 }
1562 
1563 TQStringList KFileDialog::selectedFiles() const
1564 {
1565  TQStringList list;
1566  KURL url;
1567 
1568  if ( result() == TQDialog::Accepted ) {
1569  if ( (ops->mode() & KFile::Files) == KFile::Files ) {
1570  KURL::List urls = parseSelectedURLs();
1571  TQValueListConstIterator<KURL> it = urls.begin();
1572  while ( it != urls.end() ) {
1573  url = KIO::NetAccess::mostLocalURL(*it,topLevelWidget());
1574  if ( url.isLocalFile() )
1575  list.append( url.path() );
1576  ++it;
1577  }
1578  }
1579 
1580  else { // single-selection mode
1581  if ( d->url.isLocalFile() )
1582  list.append( d->url.path() );
1583  }
1584  }
1585 
1586  return list;
1587 }
1588 
1589 KURL KFileDialog::baseURL() const
1590 {
1591  return ops->url();
1592 }
1593 
1594 TQString KFileDialog::getSaveFileName(const TQString& dir, const TQString& filter,
1595  TQWidget *parent,
1596  const TQString& caption)
1597 {
1598  bool specialDir = dir.at(0) == ':';
1599  KFileDialog dlg( specialDir ? dir : TQString::null, filter, parent, "filedialog", true);
1600  if ( !specialDir )
1601  dlg.setSelection( dir ); // may also be a filename
1602 
1603  dlg.setOperationMode( Saving );
1604  dlg.setCaption(caption.isNull() ? i18n("Save As") : caption);
1605 
1606  dlg.exec();
1607 
1608  TQString filename = dlg.selectedFile();
1609  if (!filename.isEmpty())
1610  KRecentDocument::add(filename);
1611 
1612  return filename;
1613 }
1614 
1615 TQString KFileDialog::getSaveFileNameWId(const TQString& dir, const TQString& filter,
1616  WId parent_id,
1617  const TQString& caption)
1618 {
1619  bool specialDir = dir.at(0) == ':';
1620  TQWidget* parent = TQT_TQWIDGET(TQWidget::find( parent_id ));
1621  KFileDialog dlg( specialDir ? dir : TQString::null, filter, parent, "filedialog", true);
1622 #ifdef Q_WS_X11
1623  if( parent == NULL && parent_id != 0 )
1624  XSetTransientForHint(qt_xdisplay(), dlg.winId(), parent_id);
1625 #else
1626  // TODO
1627 #endif
1628 
1629  if ( !specialDir )
1630  dlg.setSelection( dir ); // may also be a filename
1631 
1632  dlg.setOperationMode( KFileDialog::Saving);
1633  dlg.setCaption(caption.isNull() ? i18n("Save As") : caption);
1634 
1635  dlg.exec();
1636 
1637  TQString filename = dlg.selectedFile();
1638  if (!filename.isEmpty())
1639  KRecentDocument::add(filename);
1640 
1641  return filename;
1642 }
1643 
1644 KURL KFileDialog::getSaveURL(const TQString& dir, const TQString& filter,
1645  TQWidget *parent, const TQString& caption)
1646 {
1647  bool specialDir = dir.at(0) == ':';
1648  KFileDialog dlg(specialDir ? dir : TQString::null, filter, parent, "filedialog", true);
1649  if ( !specialDir )
1650  dlg.setSelection( dir ); // may also be a filename
1651 
1652  dlg.setCaption(caption.isNull() ? i18n("Save As") : caption);
1653  dlg.setOperationMode( Saving );
1654 
1655  dlg.exec();
1656 
1657  KURL url = dlg.selectedURL();
1658  if (url.isValid())
1659  KRecentDocument::add( url );
1660 
1661  return url;
1662 }
1663 
1664 void KFileDialog::show()
1665 {
1666  if ( !d->hasView ) { // delayed view-creation
1667  ops->setView(KFile::Default);
1668  ops->clearHistory();
1669  d->hasView = true;
1670  }
1671 
1672  KDialogBase::show();
1673 }
1674 
1675 void KFileDialog::setMode( KFile::Mode m )
1676 {
1677  ops->setMode(m);
1678  if ( ops->dirOnlyMode() ) {
1679  filterWidget->setDefaultFilter( i18n("*|All Folders") );
1680  }
1681  else {
1682  filterWidget->setDefaultFilter( i18n("*|All Files") );
1683  }
1684 
1685  updateAutoSelectExtension ();
1686 }
1687 
1688 void KFileDialog::setMode( unsigned int m )
1689 {
1690  setMode(static_cast<KFile::Mode>( m ));
1691 }
1692 
1693 KFile::Mode KFileDialog::mode() const
1694 {
1695  return ops->mode();
1696 }
1697 
1698 
1699 void KFileDialog::readConfig( KConfig *kc, const TQString& group )
1700 {
1701  if ( !kc )
1702  return;
1703 
1704  TQString oldGroup = kc->group();
1705  if ( !group.isEmpty() )
1706  kc->setGroup( group );
1707 
1708  ops->readConfig( kc, group );
1709 
1710  KURLComboBox *combo = d->pathCombo;
1711  combo->setURLs( kc->readPathListEntry( RecentURLs ), KURLComboBox::RemoveTop );
1712  combo->setMaxItems( kc->readNumEntry( RecentURLsNumber,
1713  DefaultRecentURLsNumber ) );
1714  combo->setURL( ops->url() );
1715  autoDirectoryFollowing = kc->readBoolEntry( AutoDirectoryFollowing,
1716  DefaultDirectoryFollowing );
1717 
1718  KGlobalSettings::Completion cm = (KGlobalSettings::Completion)
1719  kc->readNumEntry( PathComboCompletionMode,
1720  KGlobalSettings::completionMode() );
1721  if ( cm != KGlobalSettings::completionMode() )
1722  combo->setCompletionMode( cm );
1723 
1724  cm = (KGlobalSettings::Completion)
1725  kc->readNumEntry( LocationComboCompletionMode,
1726  KGlobalSettings::completionMode() );
1727  if ( cm != KGlobalSettings::completionMode() )
1728  locationEdit->setCompletionMode( cm );
1729 
1730  // show or don't show the speedbar
1731  toggleSpeedbar( kc->readBoolEntry(ShowSpeedbar, true) );
1732 
1733  // show or don't show the bookmarks
1734  toggleBookmarks( kc->readBoolEntry(ShowBookmarks, false) );
1735 
1736  // does the user want Automatically Select Extension?
1737  d->autoSelectExtChecked = kc->readBoolEntry (AutoSelectExtChecked, DefaultAutoSelectExtChecked);
1738  updateAutoSelectExtension ();
1739 
1740  int w1 = minimumSize().width();
1741  int w2 = toolbar->sizeHint().width() + 10;
1742  if (w1 < w2)
1743  setMinimumWidth(w2);
1744 
1745  TQSize size = configDialogSize( group );
1746  resize( size );
1747  kc->setGroup( oldGroup );
1748 }
1749 
1750 void KFileDialog::writeConfig( KConfig *kc, const TQString& group )
1751 {
1752  if ( !kc )
1753  return;
1754 
1755  TQString oldGroup = kc->group();
1756  if ( !group.isEmpty() )
1757  kc->setGroup( group );
1758 
1759  kc->writePathEntry( RecentURLs, d->pathCombo->urls() );
1760  saveDialogSize( group, true );
1761  kc->writeEntry( PathComboCompletionMode, static_cast<int>(d->pathCombo->completionMode()) );
1762  kc->writeEntry( LocationComboCompletionMode, static_cast<int>(locationEdit->completionMode()) );
1763  kc->writeEntry( ShowSpeedbar, d->urlBar && !d->urlBar->isHidden() );
1764  kc->writeEntry( ShowBookmarks, d->bookmarkHandler != 0 );
1765  kc->writeEntry( AutoSelectExtChecked, d->autoSelectExtChecked );
1766 
1767  ops->writeConfig( kc, group );
1768  kc->setGroup( oldGroup );
1769 }
1770 
1771 
1772 void KFileDialog::readRecentFiles( KConfig *kc )
1773 {
1774  TQString oldGroup = kc->group();
1775  kc->setGroup( ConfigGroup );
1776 
1777  locationEdit->setMaxItems( kc->readNumEntry( RecentFilesNumber,
1778  DefaultRecentURLsNumber ) );
1779  locationEdit->setURLs( kc->readPathListEntry( RecentFiles ),
1780  KURLComboBox::RemoveBottom );
1781  locationEdit->insertItem( TQString::null, 0 ); // dummy item without pixmap
1782  locationEdit->setCurrentItem( 0 );
1783 
1784  kc->setGroup( oldGroup );
1785 }
1786 
1787 void KFileDialog::saveRecentFiles( KConfig *kc )
1788 {
1789  TQString oldGroup = kc->group();
1790  kc->setGroup( ConfigGroup );
1791 
1792  kc->writePathEntry( RecentFiles, locationEdit->urls() );
1793 
1794  kc->setGroup( oldGroup );
1795 }
1796 
1797 KPushButton * KFileDialog::okButton() const
1798 {
1799  return d->okButton;
1800 }
1801 
1802 KPushButton * KFileDialog::cancelButton() const
1803 {
1804  return d->cancelButton;
1805 }
1806 
1807 KURLBar * KFileDialog::speedBar()
1808 {
1809  return d->urlBar;
1810 }
1811 
1812 void KFileDialog::slotCancel()
1813 {
1814  ops->close();
1815  KDialogBase::slotCancel();
1816 
1817  KConfig *config = KGlobal::config();
1818  config->setForceGlobal( true );
1819  writeConfig( config, ConfigGroup );
1820  config->setForceGlobal( false );
1821 }
1822 
1823 void KFileDialog::setKeepLocation( bool keep )
1824 {
1825  d->keepLocation = keep;
1826 }
1827 
1828 bool KFileDialog::keepsLocation() const
1829 {
1830  return d->keepLocation;
1831 }
1832 
1833 void KFileDialog::setOperationMode( OperationMode mode )
1834 {
1835  d->operationMode = mode;
1836  d->keepLocation = (mode == Saving);
1837  filterWidget->setEditable( !d->hasDefaultFilter || mode != Saving );
1838  if ( mode == Opening )
1839  d->okButton->setGuiItem( KGuiItem( i18n("&Open"), "fileopen") );
1840  else if ( mode == Saving ) {
1841  d->okButton->setGuiItem( KStdGuiItem::save() );
1842  setNonExtSelection();
1843  }
1844  else
1845  d->okButton->setGuiItem( KStdGuiItem::ok() );
1846  updateLocationWhatsThis ();
1847  updateAutoSelectExtension ();
1848 }
1849 
1850 KFileDialog::OperationMode KFileDialog::operationMode() const
1851 {
1852  return d->operationMode;
1853 }
1854 
1855 void KFileDialog::slotAutoSelectExtClicked()
1856 {
1857  kdDebug (kfile_area) << "slotAutoSelectExtClicked(): "
1858  << d->autoSelectExtCheckBox->isChecked () << endl;
1859 
1860  // whether the _user_ wants it on/off
1861  d->autoSelectExtChecked = d->autoSelectExtCheckBox->isChecked ();
1862 
1863  // update the current filename's extension
1864  updateLocationEditExtension (d->extension /* extension hasn't changed */);
1865 }
1866 
1867 static TQString getExtensionFromPatternList (const TQStringList &patternList)
1868 {
1869  TQString ret;
1870  kdDebug (kfile_area) << "\tgetExtension " << patternList << endl;
1871 
1872  TQStringList::ConstIterator patternListEnd = patternList.end ();
1873  for (TQStringList::ConstIterator it = patternList.begin ();
1874  it != patternListEnd;
1875  it++)
1876  {
1877  kdDebug (kfile_area) << "\t\ttry: \'" << (*it) << "\'" << endl;
1878 
1879  // is this pattern like "*.BMP" rather than useless things like:
1880  //
1881  // README
1882  // *.
1883  // *.*
1884  // *.JP*G
1885  // *.JP?
1886  if ((*it).startsWith ("*.") &&
1887  (*it).length () > 2 &&
1888  (*it).find ('*', 2) < 0 && (*it).find ('?', 2) < 0)
1889  {
1890  ret = (*it).mid (1);
1891  break;
1892  }
1893  }
1894 
1895  return ret;
1896 }
1897 
1898 static TQString stripUndisplayable (const TQString &string)
1899 {
1900  TQString ret = string;
1901 
1902  ret.remove (':');
1903  ret.remove ('&');
1904 
1905  return ret;
1906 }
1907 
1908 
1909 TQString KFileDialog::currentFilterExtension (void)
1910 {
1911  return d->extension;
1912 }
1913 
1914 void KFileDialog::updateAutoSelectExtension (void)
1915 {
1916  if (!d->autoSelectExtCheckBox) return;
1917 
1918  //
1919  // Figure out an extension for the Automatically Select Extension thing
1920  // (some Windows users apparently don't know what to do when confronted
1921  // with a text file called "COPYING" but do know what to do with
1922  // COPYING.txt ...)
1923  //
1924 
1925  kdDebug (kfile_area) << "Figure out an extension: " << endl;
1926  TQString lastExtension = d->extension;
1927  d->extension = TQString::null;
1928 
1929  // Automatically Select Extension is only valid if the user is _saving_ a _file_
1930  if ((operationMode () == Saving) && (mode () & KFile::File))
1931  {
1932  //
1933  // Get an extension from the filter
1934  //
1935 
1936  TQString filter = currentFilter ();
1937  if (!filter.isEmpty ())
1938  {
1939  // e.g. "*.cpp"
1940  if (filter.find ('/') < 0)
1941  {
1942  d->extension = getExtensionFromPatternList (TQStringList::split (" ", filter)).lower ();
1943  kdDebug (kfile_area) << "\tsetFilter-style: pattern ext=\'"
1944  << d->extension << "\'" << endl;
1945  }
1946  // e.g. "text/html"
1947  else
1948  {
1949  KMimeType::Ptr mime = KMimeType::mimeType (filter);
1950 
1951  // first try X-KDE-NativeExtension
1952  TQString nativeExtension = mime->property ("X-KDE-NativeExtension").toString ();
1953  if (nativeExtension.at (0) == '.')
1954  {
1955  d->extension = nativeExtension.lower ();
1956  kdDebug (kfile_area) << "\tsetMimeFilter-style: native ext=\'"
1957  << d->extension << "\'" << endl;
1958  }
1959 
1960  // no X-KDE-NativeExtension
1961  if (d->extension.isEmpty ())
1962  {
1963  d->extension = getExtensionFromPatternList (mime->patterns ()).lower ();
1964  kdDebug (kfile_area) << "\tsetMimeFilter-style: pattern ext=\'"
1965  << d->extension << "\'" << endl;
1966  }
1967  }
1968  }
1969 
1970 
1971  //
1972  // GUI: checkbox
1973  //
1974 
1975  TQString whatsThisExtension;
1976  if (!d->extension.isEmpty ())
1977  {
1978  // remember: sync any changes to the string with below
1979  d->autoSelectExtCheckBox->setText (i18n ("Automatically select filename e&xtension (%1)").arg (d->extension));
1980  whatsThisExtension = i18n ("the extension <b>%1</b>").arg (d->extension);
1981 
1982  d->autoSelectExtCheckBox->setEnabled (true);
1983  d->autoSelectExtCheckBox->setChecked (d->autoSelectExtChecked);
1984  }
1985  else
1986  {
1987  // remember: sync any changes to the string with above
1988  d->autoSelectExtCheckBox->setText (i18n ("Automatically select filename e&xtension"));
1989  whatsThisExtension = i18n ("a suitable extension");
1990 
1991  d->autoSelectExtCheckBox->setChecked (false);
1992  d->autoSelectExtCheckBox->setEnabled (false);
1993  }
1994 
1995  const TQString locationLabelText = stripUndisplayable (d->locationLabel->text ());
1996  const TQString filterLabelText = stripUndisplayable (d->filterLabel->text ());
1997  TQWhatsThis::add (d->autoSelectExtCheckBox,
1998  "<qt>" +
1999  i18n (
2000  "This option enables some convenient features for "
2001  "saving files with extensions:<br>"
2002  "<ol>"
2003  "<li>Any extension specified in the <b>%1</b> text "
2004  "area will be updated if you change the file type "
2005  "to save in.<br>"
2006  "<br></li>"
2007  "<li>If no extension is specified in the <b>%2</b> "
2008  "text area when you click "
2009  "<b>Save</b>, %3 will be added to the end of the "
2010  "filename (if the filename does not already exist). "
2011  "This extension is based on the file type that you "
2012  "have chosen to save in.<br>"
2013  "<br>"
2014  "If you do not want KDE to supply an extension for the "
2015  "filename, you can either turn this option off or you "
2016  "can suppress it by adding a period (.) to the end of "
2017  "the filename (the period will be automatically "
2018  "removed)."
2019  "</li>"
2020  "</ol>"
2021  "If unsure, keep this option enabled as it makes your "
2022  "files more manageable."
2023  )
2024  .arg (locationLabelText)
2025  .arg (locationLabelText)
2026  .arg (whatsThisExtension)
2027  + "</qt>"
2028  );
2029 
2030  d->autoSelectExtCheckBox->show ();
2031 
2032 
2033  // update the current filename's extension
2034  updateLocationEditExtension (lastExtension);
2035  }
2036  // Automatically Select Extension not valid
2037  else
2038  {
2039  d->autoSelectExtCheckBox->setChecked (false);
2040  d->autoSelectExtCheckBox->hide ();
2041  }
2042 }
2043 
2044 // Updates the extension of the filename specified in locationEdit if the
2045 // Automatically Select Extension feature is enabled.
2046 // (this prevents you from accidently saving "file.kwd" as RTF, for example)
2047 void KFileDialog::updateLocationEditExtension (const TQString &lastExtension)
2048 {
2049  if (!d->autoSelectExtCheckBox->isChecked () || d->extension.isEmpty ())
2050  return;
2051 
2052  TQString urlStr = locationEdit->currentText ();
2053  if (urlStr.isEmpty ())
2054  return;
2055 
2056  KURL url = getCompleteURL (urlStr);
2057  kdDebug (kfile_area) << "updateLocationEditExtension (" << url << ")" << endl;
2058 
2059  const int fileNameOffset = urlStr.findRev ('/') + 1;
2060  TQString fileName = urlStr.mid (fileNameOffset);
2061 
2062  const int dot = fileName.findRev ('.');
2063  const int len = fileName.length ();
2064  if (dot > 0 && // has an extension already and it's not a hidden file
2065  // like ".hidden" (but we do accept ".hidden.ext")
2066  dot != len - 1 // and not deliberately suppressing extension
2067  )
2068  {
2069  // exists?
2070  KIO::UDSEntry t;
2071  if (KIO::NetAccess::stat (url, t, topLevelWidget()))
2072  {
2073  kdDebug (kfile_area) << "\tfile exists" << endl;
2074 
2075  if (isDirectory (t))
2076  {
2077  kdDebug (kfile_area) << "\tisDir - won't alter extension" << endl;
2078  return;
2079  }
2080 
2081  // --- fall through ---
2082  }
2083 
2084 
2085  //
2086  // try to get rid of the current extension
2087  //
2088 
2089  // catch "double extensions" like ".tar.gz"
2090  if (lastExtension.length () && fileName.endsWith (lastExtension))
2091  fileName.truncate (len - lastExtension.length ());
2092  // can only handle "single extensions"
2093  else
2094  fileName.truncate (dot);
2095 
2096  // add extension
2097  const TQString newText = urlStr.left (fileNameOffset) + fileName + d->extension;
2098  if ( newText != locationEdit->currentText() )
2099  {
2100  locationEdit->setCurrentText (urlStr.left (fileNameOffset) + fileName + d->extension);
2101  locationEdit->lineEdit()->setEdited (true);
2102  }
2103  }
2104 }
2105 
2106 // Updates the filter if the extension of the filename specified in locationEdit is changed
2107 // (this prevents you from accidently saving "file.kwd" as RTF, for example)
2108 void KFileDialog::updateFilter ()
2109 {
2110  if ((operationMode() == Saving) && (mode() & KFile::File) ) {
2111  const TQString urlStr = locationEdit->currentText ();
2112  if (urlStr.isEmpty ())
2113  return;
2114 
2115  KMimeType::Ptr mime = KMimeType::findByPath(urlStr, 0, true);
2116  if (mime && mime->name() != KMimeType::defaultMimeType()) {
2117  if (filterWidget->currentFilter() != mime->name() &&
2118  filterWidget->filters.findIndex(mime->name()) != -1) {
2119  filterWidget->setCurrentFilter(mime->name());
2120  }
2121  }
2122  }
2123 }
2124 
2125 // applies only to a file that doesn't already exist
2126 void KFileDialog::appendExtension (KURL &url)
2127 {
2128  if (!d->autoSelectExtCheckBox->isChecked () || d->extension.isEmpty ())
2129  return;
2130 
2131  TQString fileName = url.fileName ();
2132  if (fileName.isEmpty ())
2133  return;
2134 
2135  kdDebug (kfile_area) << "appendExtension(" << url << ")" << endl;
2136 
2137  const int len = fileName.length ();
2138  const int dot = fileName.findRev ('.');
2139 
2140  const bool suppressExtension = (dot == len - 1);
2141  const bool unspecifiedExtension = (dot <= 0);
2142 
2143  // don't KIO::NetAccess::Stat if unnecessary
2144  if (!(suppressExtension || unspecifiedExtension))
2145  return;
2146 
2147  // exists?
2148  KIO::UDSEntry t;
2149  if (KIO::NetAccess::stat (url, t, topLevelWidget()))
2150  {
2151  kdDebug (kfile_area) << "\tfile exists - won't append extension" << endl;
2152  return;
2153  }
2154 
2155  // suppress automatically append extension?
2156  if (suppressExtension)
2157  {
2158  //
2159  // Strip trailing dot
2160  // This allows lazy people to have autoSelectExtCheckBox->isChecked
2161  // but don't want a file extension to be appended
2162  // e.g. "README." will make a file called "README"
2163  //
2164  // If you really want a name like "README.", then type "README.."
2165  // and the trailing dot will be removed (or just stop being lazy and
2166  // turn off this feature so that you can type "README.")
2167  //
2168  kdDebug (kfile_area) << "\tstrip trailing dot" << endl;
2169  url.setFileName (fileName.left (len - 1));
2170  }
2171  // evilmatically append extension :) if the user hasn't specified one
2172  else if (unspecifiedExtension)
2173  {
2174  kdDebug (kfile_area) << "\tappending extension \'" << d->extension << "\'..." << endl;
2175  url.setFileName (fileName + d->extension);
2176  kdDebug (kfile_area) << "\tsaving as \'" << url << "\'" << endl;
2177  }
2178 }
2179 
2180 
2181 // adds the selected files/urls to 'recent documents'
2182 void KFileDialog::addToRecentDocuments()
2183 {
2184  int m = ops->mode();
2185 
2186  if ( m & KFile::LocalOnly ) {
2187  TQStringList files = selectedFiles();
2188  TQStringList::ConstIterator it = files.begin();
2189  for ( ; it != files.end(); ++it )
2190  KRecentDocument::add( *it );
2191  }
2192 
2193  else { // urls
2194  KURL::List urls = selectedURLs();
2195  KURL::List::ConstIterator it = urls.begin();
2196  for ( ; it != urls.end(); ++it ) {
2197  if ( (*it).isValid() )
2198  KRecentDocument::add( *it );
2199  }
2200  }
2201 }
2202 
2203 KActionCollection * KFileDialog::actionCollection() const
2204 {
2205  return ops->actionCollection();
2206 }
2207 
2208 void KFileDialog::keyPressEvent( TQKeyEvent *e )
2209 {
2210  if ( e->key() == Key_Escape )
2211  {
2212  e->accept();
2213  d->cancelButton->animateClick();
2214  }
2215  else
2216  KDialogBase::keyPressEvent( e );
2217 }
2218 
2219 void KFileDialog::toggleSpeedbar( bool show )
2220 {
2221  if ( show )
2222  {
2223  if ( !d->urlBar )
2224  initSpeedbar();
2225 
2226  d->urlBar->show();
2227 
2228  // check to see if they have a home item defined, if not show the home button
2229  KURLBarItem *urlItem = static_cast<KURLBarItem*>( d->urlBar->listBox()->firstItem() );
2230  KURL homeURL;
2231  homeURL.setPath( TQDir::homeDirPath() );
2232  while ( urlItem )
2233  {
2234  if ( homeURL.equals( urlItem->url(), true ) )
2235  {
2236  ops->actionCollection()->action( "home" )->unplug( toolbar );
2237  break;
2238  }
2239 
2240  urlItem = static_cast<KURLBarItem*>( urlItem->next() );
2241  }
2242  }
2243  else
2244  {
2245  if (d->urlBar)
2246  d->urlBar->hide();
2247 
2248  if ( !ops->actionCollection()->action( "home" )->isPlugged( toolbar ) )
2249  ops->actionCollection()->action( "home" )->plug( toolbar, 3 );
2250  }
2251 
2252  static_cast<KToggleAction *>(actionCollection()->action("toggleSpeedbar"))->setChecked( show );
2253 }
2254 
2255 void KFileDialog::toggleBookmarks(bool show)
2256 {
2257  if (show)
2258  {
2259  if (d->bookmarkHandler)
2260  {
2261  return;
2262  }
2263 
2264  d->bookmarkHandler = new KFileBookmarkHandler( this );
2265  connect( d->bookmarkHandler, TQT_SIGNAL( openURL( const TQString& )),
2266  TQT_SLOT( enterURL( const TQString& )));
2267 
2268  toolbar->insertButton(TQString::fromLatin1("bookmark"),
2269  (int)HOTLIST_BUTTON, true,
2270  i18n("Bookmarks"), 5);
2271  toolbar->getButton(HOTLIST_BUTTON)->setPopup(d->bookmarkHandler->menu(),
2272  true);
2273  TQWhatsThis::add(toolbar->getButton(HOTLIST_BUTTON),
2274  i18n("<qt>This button allows you to bookmark specific locations. "
2275  "Click on this button to open the bookmark menu where you may add, "
2276  "edit or select a bookmark.<p>"
2277  "These bookmarks are specific to the file dialog, but otherwise operate "
2278  "like bookmarks elsewhere in KDE.</qt>"));
2279  }
2280  else if (d->bookmarkHandler)
2281  {
2282  delete d->bookmarkHandler;
2283  d->bookmarkHandler = 0;
2284  toolbar->removeItem(HOTLIST_BUTTON);
2285  }
2286 
2287  static_cast<KToggleAction *>(actionCollection()->action("toggleBookmarks"))->setChecked( show );
2288 }
2289 
2290 int KFileDialog::pathComboIndex()
2291 {
2292  return d->m_pathComboIndex;
2293 }
2294 
2295 // static
2296 void KFileDialog::initStatic()
2297 {
2298  if ( lastDirectory )
2299  return;
2300 
2301  lastDirectory = ldd.setObject(lastDirectory, new KURL());
2302 }
2303 
2304 // static
2305 KURL KFileDialog::getStartURL( const TQString& startDir,
2306  TQString& recentDirClass )
2307 {
2308  initStatic();
2309 
2310  recentDirClass = TQString::null;
2311  KURL ret;
2312 
2313  bool useDefaultStartDir = startDir.isEmpty();
2314  if ( !useDefaultStartDir )
2315  {
2316  if (startDir[0] == ':')
2317  {
2318  recentDirClass = startDir;
2319  ret = KURL::fromPathOrURL( KRecentDirs::dir(recentDirClass) );
2320  }
2321  else
2322  {
2323  ret = KCmdLineArgs::makeURL( TQFile::encodeName(startDir) );
2324  // If we won't be able to list it (e.g. http), then use default
2325  if ( !KProtocolInfo::supportsListing( ret ) )
2326  useDefaultStartDir = true;
2327  }
2328  }
2329 
2330  if ( useDefaultStartDir )
2331  {
2332  if (lastDirectory->isEmpty()) {
2333  lastDirectory->setPath(KGlobalSettings::documentPath());
2334  KURL home;
2335  home.setPath( TQDir::homeDirPath() );
2336  // if there is no docpath set (== home dir), we prefer the current
2337  // directory over it. We also prefer the homedir when our CWD is
2338  // different from our homedirectory or when the document dir
2339  // does not exist
2340  if ( lastDirectory->path(+1) == home.path(+1) ||
2341  TQDir::currentDirPath() != TQDir::homeDirPath() ||
2342  !TQDir(lastDirectory->path(+1)).exists() )
2343  lastDirectory->setPath(TQDir::currentDirPath());
2344  }
2345  ret = *lastDirectory;
2346  }
2347 
2348  return ret;
2349 }
2350 
2351 void KFileDialog::setStartDir( const KURL& directory )
2352 {
2353  initStatic();
2354  if ( directory.isValid() )
2355  *lastDirectory = directory;
2356 }
2357 
2358 void KFileDialog::setNonExtSelection()
2359 {
2360  // Enhanced rename: Don't highlight the file extension.
2361  TQString pattern, filename = locationEdit->currentText().stripWhiteSpace();
2362  KServiceTypeFactory::self()->findFromPattern( filename, &pattern );
2363 
2364  if ( !pattern.isEmpty() && pattern.at( 0 ) == '*' && pattern.find( '*' , 1 ) == -1 )
2365  locationEdit->lineEdit()->setSelection( 0, filename.length() - pattern.stripWhiteSpace().length()+1 );
2366  else
2367  {
2368  int lastDot = filename.findRev( '.' );
2369  if ( lastDot > 0 )
2370  locationEdit->lineEdit()->setSelection( 0, lastDot );
2371  }
2372 }
2373 
2374 void KFileDialog::virtual_hook( int id, void* data )
2375 { KDialogBase::virtual_hook( id, data ); }
2376 
2377 
2378 #include "kfiledialog.moc"

kio/kfile

Skip menu "kio/kfile"
  • Main Page
  • Class Hierarchy
  • Alphabetical List
  • Class List
  • File List
  • Class Members
  • Related Pages

kio/kfile

Skip menu "kio/kfile"
  • arts
  • dcop
  • dnssd
  • interfaces
  •     interface
  •     library
  •   kspeech
  •   ktexteditor
  • kabc
  • kate
  • kcmshell
  • kdecore
  • kded
  • kdefx
  • kdeprint
  • kdesu
  • kdeui
  • kdoctools
  • khtml
  • kimgio
  • kinit
  • kio
  •   bookmarks
  •   httpfilter
  •   kfile
  •   kio
  •   kioexec
  •   kpasswdserver
  •   kssl
  • kioslave
  •   http
  • kjs
  • kmdi
  •   kmdi
  • knewstuff
  • kparts
  • krandr
  • kresources
  • kspell2
  • kunittest
  • kutils
  • kwallet
  • libkmid
  • libkscreensaver
Generated for kio/kfile by doxygen 1.8.1.2
This website is maintained by Timothy Pearson.
KDE® and the K Desktop Environment® logo are registered trademarks of KDE e.V. |