• Skip to content
  • Skip to link menu
Trinity API Reference
  • Trinity API Reference
  • tdeio/tdefile
 

tdeio/tdefile

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

tdeio/tdefile

Skip menu "tdeio/tdefile"
  • Main Page
  • Class Hierarchy
  • Alphabetical List
  • Class List
  • File List
  • Class Members
  • Related Pages

tdeio/tdefile

Skip menu "tdeio/tdefile"
  • arts
  • dcop
  • dnssd
  • interfaces
  •   kspeech
  •     interface
  •     library
  •   tdetexteditor
  • kate
  • kded
  • kdoctools
  • kimgio
  • kjs
  • knewstuff
  • libtdemid
  • libtdescreensaver
  • tdeabc
  • tdecmshell
  • tdecore
  • tdefx
  • tdehtml
  • tdeinit
  • tdeio
  •   bookmarks
  •   httpfilter
  •   kpasswdserver
  •   kssl
  •   tdefile
  •   tdeio
  •   tdeioexec
  • tdeioslave
  •   http
  • tdemdi
  •   tdemdi
  • tdeparts
  • tdeprint
  • tderandr
  • tderesources
  • tdespell2
  • tdesu
  • tdeui
  • tdeunittest
  • tdeutils
  • tdewallet
Generated for tdeio/tdefile by doxygen 1.8.3.1
This website is maintained by Timothy Pearson.