PageRenderTime 69ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/src/gui/dialogs/qfiledialog.cpp

https://bitbucket.org/gcubar/qt
C++ | 3577 lines | 2206 code | 319 blank | 1052 comment | 478 complexity | 6dbc36e5eadc382b041a69ed7b9d8ce1 MD5 | raw file
Possible License(s): CC0-1.0, CC-BY-SA-4.0, LGPL-2.1, GPL-3.0, Apache-2.0, LGPL-2.0, LGPL-3.0, BSD-3-Clause
  1. /****************************************************************************
  2. **
  3. ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
  4. ** Contact: http://www.qt-project.org/legal
  5. **
  6. ** This file is part of the QtGui module of the Qt Toolkit.
  7. **
  8. ** $QT_BEGIN_LICENSE:LGPL$
  9. ** Commercial License Usage
  10. ** Licensees holding valid commercial Qt licenses may use this file in
  11. ** accordance with the commercial license agreement provided with the
  12. ** Software or, alternatively, in accordance with the terms contained in
  13. ** a written agreement between you and Digia. For licensing terms and
  14. ** conditions see http://qt.digia.com/licensing. For further information
  15. ** use the contact form at http://qt.digia.com/contact-us.
  16. **
  17. ** GNU Lesser General Public License Usage
  18. ** Alternatively, this file may be used under the terms of the GNU Lesser
  19. ** General Public License version 2.1 as published by the Free Software
  20. ** Foundation and appearing in the file LICENSE.LGPL included in the
  21. ** packaging of this file. Please review the following information to
  22. ** ensure the GNU Lesser General Public License version 2.1 requirements
  23. ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
  24. **
  25. ** In addition, as a special exception, Digia gives you certain additional
  26. ** rights. These rights are described in the Digia Qt LGPL Exception
  27. ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
  28. **
  29. ** GNU General Public License Usage
  30. ** Alternatively, this file may be used under the terms of the GNU
  31. ** General Public License version 3.0 as published by the Free Software
  32. ** Foundation and appearing in the file LICENSE.GPL included in the
  33. ** packaging of this file. Please review the following information to
  34. ** ensure the GNU General Public License version 3.0 requirements will be
  35. ** met: http://www.gnu.org/copyleft/gpl.html.
  36. **
  37. **
  38. ** $QT_END_LICENSE$
  39. **
  40. ****************************************************************************/
  41. #include <qvariant.h>
  42. #include <private/qwidgetitemdata_p.h>
  43. #include "qfiledialog.h"
  44. #ifndef QT_NO_FILEDIALOG
  45. #include "qfiledialog_p.h"
  46. #include <qfontmetrics.h>
  47. #include <qaction.h>
  48. #include <qheaderview.h>
  49. #include <qshortcut.h>
  50. #include <qgridlayout.h>
  51. #include <qmenu.h>
  52. #include <qmessagebox.h>
  53. #include <qinputdialog.h>
  54. #include <stdlib.h>
  55. #include <qsettings.h>
  56. #include <qdebug.h>
  57. #include <qapplication.h>
  58. #include <qstylepainter.h>
  59. #if !defined(Q_WS_WINCE) && !defined(Q_OS_SYMBIAN)
  60. #include "ui_qfiledialog.h"
  61. #else
  62. #define Q_EMBEDDED_SMALLSCREEN
  63. #include "ui_qfiledialog_embedded.h"
  64. #if defined(Q_OS_WINCE)
  65. extern bool qt_priv_ptr_valid;
  66. #endif
  67. #if defined(Q_OS_UNIX)
  68. #include <pwd.h>
  69. #endif
  70. #endif
  71. QT_BEGIN_NAMESPACE
  72. Q_GLOBAL_STATIC(QString, lastVisitedDir)
  73. /*
  74. \internal
  75. Exported hooks that can be used to customize the static functions.
  76. */
  77. typedef QString (*_qt_filedialog_existing_directory_hook)(QWidget *parent, const QString &caption, const QString &dir, QFileDialog::Options options);
  78. Q_GUI_EXPORT _qt_filedialog_existing_directory_hook qt_filedialog_existing_directory_hook = 0;
  79. typedef QString (*_qt_filedialog_open_filename_hook)(QWidget * parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedFilter, QFileDialog::Options options);
  80. Q_GUI_EXPORT _qt_filedialog_open_filename_hook qt_filedialog_open_filename_hook = 0;
  81. typedef QStringList (*_qt_filedialog_open_filenames_hook)(QWidget * parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedFilter, QFileDialog::Options options);
  82. Q_GUI_EXPORT _qt_filedialog_open_filenames_hook qt_filedialog_open_filenames_hook = 0;
  83. typedef QString (*_qt_filedialog_save_filename_hook)(QWidget * parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedFilter, QFileDialog::Options options);
  84. Q_GUI_EXPORT _qt_filedialog_save_filename_hook qt_filedialog_save_filename_hook = 0;
  85. /*!
  86. \class QFileDialog
  87. \brief The QFileDialog class provides a dialog that allow users to select files or directories.
  88. \ingroup standard-dialogs
  89. The QFileDialog class enables a user to traverse the file system in
  90. order to select one or many files or a directory.
  91. The easiest way to create a QFileDialog is to use the static
  92. functions. On Windows, Mac OS X, KDE and GNOME, these static functions will
  93. call the native file dialog when possible.
  94. \snippet doc/src/snippets/code/src_gui_dialogs_qfiledialog.cpp 0
  95. In the above example, a modal QFileDialog is created using a static
  96. function. The dialog initially displays the contents of the "/home/jana"
  97. directory, and displays files matching the patterns given in the
  98. string "Image Files (*.png *.jpg *.bmp)". The parent of the file dialog
  99. is set to \e this, and the window title is set to "Open Image".
  100. If you want to use multiple filters, separate each one with
  101. \e two semicolons. For example:
  102. \snippet doc/src/snippets/code/src_gui_dialogs_qfiledialog.cpp 1
  103. You can create your own QFileDialog without using the static
  104. functions. By calling setFileMode(), you can specify what the user must
  105. select in the dialog:
  106. \snippet doc/src/snippets/code/src_gui_dialogs_qfiledialog.cpp 2
  107. In the above example, the mode of the file dialog is set to
  108. AnyFile, meaning that the user can select any file, or even specify a
  109. file that doesn't exist. This mode is useful for creating a
  110. "Save As" file dialog. Use ExistingFile if the user must select an
  111. existing file, or \l Directory if only a directory may be selected.
  112. See the \l QFileDialog::FileMode enum for the complete list of modes.
  113. The fileMode property contains the mode of operation for the dialog;
  114. this indicates what types of objects the user is expected to select.
  115. Use setNameFilter() to set the dialog's file filter. For example:
  116. \snippet doc/src/snippets/code/src_gui_dialogs_qfiledialog.cpp 3
  117. In the above example, the filter is set to \c{"Images (*.png *.xpm *.jpg)"},
  118. this means that only files with the extension \c png, \c xpm,
  119. or \c jpg will be shown in the QFileDialog. You can apply
  120. several filters by using setNameFilters(). Use selectNameFilter() to select
  121. one of the filters you've given as the file dialog's default filter.
  122. The file dialog has two view modes: \l{QFileDialog::}{List} and
  123. \l{QFileDialog::}{Detail}.
  124. \l{QFileDialog::}{List} presents the contents of the current directory
  125. as a list of file and directory names. \l{QFileDialog::}{Detail} also
  126. displays a list of file and directory names, but provides additional
  127. information alongside each name, such as the file size and modification
  128. date. Set the mode with setViewMode():
  129. \snippet doc/src/snippets/code/src_gui_dialogs_qfiledialog.cpp 4
  130. The last important function you will need to use when creating your
  131. own file dialog is selectedFiles().
  132. \snippet doc/src/snippets/code/src_gui_dialogs_qfiledialog.cpp 5
  133. In the above example, a modal file dialog is created and shown. If
  134. the user clicked OK, the file they selected is put in \c fileName.
  135. The dialog's working directory can be set with setDirectory().
  136. Each file in the current directory can be selected using
  137. the selectFile() function.
  138. The \l{dialogs/standarddialogs}{Standard Dialogs} example shows
  139. how to use QFileDialog as well as other built-in Qt dialogs.
  140. \sa QDir, QFileInfo, QFile, QPrintDialog, QColorDialog, QFontDialog, {Standard Dialogs Example},
  141. {Application Example}
  142. */
  143. /*!
  144. \enum QFileDialog::AcceptMode
  145. \value AcceptOpen
  146. \value AcceptSave
  147. */
  148. /*!
  149. \enum QFileDialog::ViewMode
  150. This enum describes the view mode of the file dialog; i.e. what
  151. information about each file will be displayed.
  152. \value Detail Displays an icon, a name, and details for each item in
  153. the directory.
  154. \value List Displays only an icon and a name for each item in the
  155. directory.
  156. \sa setViewMode()
  157. */
  158. /*!
  159. \enum QFileDialog::FileMode
  160. This enum is used to indicate what the user may select in the file
  161. dialog; i.e. what the dialog will return if the user clicks OK.
  162. \value AnyFile The name of a file, whether it exists or not.
  163. \value ExistingFile The name of a single existing file.
  164. \value Directory The name of a directory. Both files and
  165. directories are displayed.
  166. \value ExistingFiles The names of zero or more existing files.
  167. This value is obsolete since Qt 4.5:
  168. \value DirectoryOnly Use \c Directory and setOption(ShowDirsOnly, true) instead.
  169. \sa setFileMode()
  170. */
  171. /*!
  172. \enum QFileDialog::Option
  173. \value ShowDirsOnly Only show directories in the file dialog. By
  174. default both files and directories are shown. (Valid only in the
  175. \l Directory file mode.)
  176. \value DontResolveSymlinks Don't resolve symlinks in the file
  177. dialog. By default symlinks are resolved.
  178. \value DontConfirmOverwrite Don't ask for confirmation if an
  179. existing file is selected. By default confirmation is requested.
  180. \value DontUseNativeDialog Don't use the native file dialog. By
  181. default, the native file dialog is used unless you use a subclass
  182. of QFileDialog that contains the Q_OBJECT macro.
  183. \value ReadOnly Indicates that the model is readonly.
  184. \value HideNameFilterDetails Indicates if the file name filter details are
  185. hidden or not.
  186. \value DontUseSheet In previous versions of Qt, the static
  187. functions would create a sheet by default if the static function
  188. was given a parent. This is no longer supported and does nothing in Qt 4.5, The
  189. static functions will always be an application modal dialog. If
  190. you want to use sheets, use QFileDialog::open() instead.
  191. */
  192. /*!
  193. \enum QFileDialog::DialogLabel
  194. \value LookIn
  195. \value FileName
  196. \value FileType
  197. \value Accept
  198. \value Reject
  199. */
  200. /*!
  201. \fn void QFileDialog::filesSelected(const QStringList &selected)
  202. When the selection changes and the dialog is accepted, this signal is
  203. emitted with the (possibly empty) list of \a selected files.
  204. \sa currentChanged(), QDialog::Accepted
  205. */
  206. /*!
  207. \fn void QFileDialog::fileSelected(const QString &file)
  208. When the selection changes and the dialog is accepted, this signal is
  209. emitted with the (possibly empty) selected \a file.
  210. \sa currentChanged(), QDialog::Accepted
  211. */
  212. /*!
  213. \fn void QFileDialog::currentChanged(const QString &path)
  214. When the current file changes, this signal is emitted with the
  215. new file name as the \a path parameter.
  216. \sa filesSelected()
  217. */
  218. /*!
  219. \fn void QFileDialog::directoryEntered(const QString &directory)
  220. \since 4.3
  221. This signal is emitted when the user enters a \a directory.
  222. */
  223. /*!
  224. \fn void QFileDialog::filterSelected(const QString &filter)
  225. \since 4.3
  226. This signal is emitted when the user selects a \a filter.
  227. */
  228. #if defined(Q_WS_WIN) || defined(Q_WS_MAC)
  229. bool Q_GUI_EXPORT qt_use_native_dialogs = true; // for the benefit of testing tools, until we have a proper API
  230. #endif
  231. QT_BEGIN_INCLUDE_NAMESPACE
  232. #ifdef Q_WS_WIN
  233. #include <qwindowsstyle.h>
  234. #endif
  235. #include <qshortcut.h>
  236. #ifdef Q_WS_MAC
  237. #include <qmacstyle_mac.h>
  238. #endif
  239. QT_END_INCLUDE_NAMESPACE
  240. /*!
  241. \fn QFileDialog::QFileDialog(QWidget *parent, Qt::WindowFlags flags)
  242. Constructs a file dialog with the given \a parent and widget \a flags.
  243. */
  244. QFileDialog::QFileDialog(QWidget *parent, Qt::WindowFlags f)
  245. : QDialog(*new QFileDialogPrivate, parent, f)
  246. {
  247. Q_D(QFileDialog);
  248. d->init();
  249. d->lineEdit()->selectAll();
  250. }
  251. /*!
  252. Constructs a file dialog with the given \a parent and \a caption that
  253. initially displays the contents of the specified \a directory.
  254. The contents of the directory are filtered before being shown in the
  255. dialog, using a semicolon-separated list of filters specified by
  256. \a filter.
  257. */
  258. QFileDialog::QFileDialog(QWidget *parent,
  259. const QString &caption,
  260. const QString &directory,
  261. const QString &filter)
  262. : QDialog(*new QFileDialogPrivate, parent, 0)
  263. {
  264. Q_D(QFileDialog);
  265. d->init(directory, filter, caption);
  266. d->lineEdit()->selectAll();
  267. }
  268. /*!
  269. \internal
  270. */
  271. QFileDialog::QFileDialog(const QFileDialogArgs &args)
  272. : QDialog(*new QFileDialogPrivate, args.parent, 0)
  273. {
  274. Q_D(QFileDialog);
  275. d->init(args.directory, args.filter, args.caption);
  276. setFileMode(args.mode);
  277. setOptions(args.options);
  278. selectFile(args.selection);
  279. d->lineEdit()->selectAll();
  280. }
  281. /*!
  282. Destroys the file dialog.
  283. */
  284. QFileDialog::~QFileDialog()
  285. {
  286. Q_D(QFileDialog);
  287. #ifndef QT_NO_SETTINGS
  288. QSettings settings(QSettings::UserScope, QLatin1String("Trolltech"));
  289. settings.beginGroup(QLatin1String("Qt"));
  290. settings.setValue(QLatin1String("filedialog"), saveState());
  291. #endif
  292. d->deleteNativeDialog_sys();
  293. }
  294. /*!
  295. \since 4.3
  296. Sets the \a urls that are located in the sidebar.
  297. For instance:
  298. \snippet doc/src/snippets/filedialogurls.cpp 0
  299. The file dialog will then look like this:
  300. \image filedialogurls.png
  301. \sa sidebarUrls()
  302. */
  303. void QFileDialog::setSidebarUrls(const QList<QUrl> &urls)
  304. {
  305. Q_D(QFileDialog);
  306. d->qFileDialogUi->sidebar->setUrls(urls);
  307. }
  308. /*!
  309. \since 4.3
  310. Returns a list of urls that are currently in the sidebar
  311. */
  312. QList<QUrl> QFileDialog::sidebarUrls() const
  313. {
  314. Q_D(const QFileDialog);
  315. return d->qFileDialogUi->sidebar->urls();
  316. }
  317. static const qint32 QFileDialogMagic = 0xbe;
  318. const char *qt_file_dialog_filter_reg_exp =
  319. "^(.*)\\(([a-zA-Z0-9_.*? +;#\\-\\[\\]@\\{\\}/!<>\\$%&=^~:\\|]*)\\)$";
  320. /*!
  321. \since 4.3
  322. Saves the state of the dialog's layout, history and current directory.
  323. Typically this is used in conjunction with QSettings to remember the size
  324. for a future session. A version number is stored as part of the data.
  325. */
  326. QByteArray QFileDialog::saveState() const
  327. {
  328. Q_D(const QFileDialog);
  329. int version = 3;
  330. QByteArray data;
  331. QDataStream stream(&data, QIODevice::WriteOnly);
  332. stream << qint32(QFileDialogMagic);
  333. stream << qint32(version);
  334. stream << d->qFileDialogUi->splitter->saveState();
  335. stream << d->qFileDialogUi->sidebar->urls();
  336. stream << history();
  337. stream << *lastVisitedDir();
  338. stream << d->qFileDialogUi->treeView->header()->saveState();
  339. stream << qint32(viewMode());
  340. return data;
  341. }
  342. /*!
  343. \since 4.3
  344. Restores the dialogs's layout, history and current directory to the \a state specified.
  345. Typically this is used in conjunction with QSettings to restore the size
  346. from a past session.
  347. Returns false if there are errors
  348. */
  349. bool QFileDialog::restoreState(const QByteArray &state)
  350. {
  351. Q_D(QFileDialog);
  352. int version = 3;
  353. QByteArray sd = state;
  354. QDataStream stream(&sd, QIODevice::ReadOnly);
  355. if (stream.atEnd())
  356. return false;
  357. QByteArray splitterState;
  358. QByteArray headerData;
  359. QList<QUrl> bookmarks;
  360. QStringList history;
  361. QString currentDirectory;
  362. qint32 marker;
  363. qint32 v;
  364. qint32 viewMode;
  365. stream >> marker;
  366. stream >> v;
  367. if (marker != QFileDialogMagic || v != version)
  368. return false;
  369. stream >> splitterState
  370. >> bookmarks
  371. >> history
  372. >> currentDirectory
  373. >> headerData
  374. >> viewMode;
  375. if (!d->qFileDialogUi->splitter->restoreState(splitterState))
  376. return false;
  377. QList<int> list = d->qFileDialogUi->splitter->sizes();
  378. if (list.count() >= 2 && list.at(0) == 0 && list.at(1) == 0) {
  379. for (int i = 0; i < list.count(); ++i)
  380. list[i] = d->qFileDialogUi->splitter->widget(i)->sizeHint().width();
  381. d->qFileDialogUi->splitter->setSizes(list);
  382. }
  383. d->qFileDialogUi->sidebar->setUrls(bookmarks);
  384. while (history.count() > 5)
  385. history.pop_front();
  386. setHistory(history);
  387. setDirectory(lastVisitedDir()->isEmpty() ? currentDirectory : *lastVisitedDir());
  388. QHeaderView *headerView = d->qFileDialogUi->treeView->header();
  389. if (!headerView->restoreState(headerData))
  390. return false;
  391. QList<QAction*> actions = headerView->actions();
  392. QAbstractItemModel *abstractModel = d->model;
  393. #ifndef QT_NO_PROXYMODEL
  394. if (d->proxyModel)
  395. abstractModel = d->proxyModel;
  396. #endif
  397. int total = qMin(abstractModel->columnCount(QModelIndex()), actions.count() + 1);
  398. for (int i = 1; i < total; ++i)
  399. actions.at(i - 1)->setChecked(!headerView->isSectionHidden(i));
  400. setViewMode(ViewMode(viewMode));
  401. return true;
  402. }
  403. /*!
  404. \reimp
  405. */
  406. void QFileDialog::changeEvent(QEvent *e)
  407. {
  408. Q_D(QFileDialog);
  409. if (e->type() == QEvent::LanguageChange) {
  410. d->retranslateWindowTitle();
  411. d->retranslateStrings();
  412. }
  413. QDialog::changeEvent(e);
  414. }
  415. QFileDialogPrivate::QFileDialogPrivate()
  416. :
  417. #ifndef QT_NO_PROXYMODEL
  418. proxyModel(0),
  419. #endif
  420. model(0),
  421. fileMode(QFileDialog::AnyFile),
  422. acceptMode(QFileDialog::AcceptOpen),
  423. currentHistoryLocation(-1),
  424. renameAction(0),
  425. deleteAction(0),
  426. showHiddenAction(0),
  427. useDefaultCaption(true),
  428. defaultFileTypes(true),
  429. fileNameLabelExplicitlySat(false),
  430. nativeDialogInUse(false),
  431. #ifdef Q_WS_MAC
  432. mDelegate(0),
  433. #ifndef QT_MAC_USE_COCOA
  434. mDialog(0),
  435. mDialogStarted(false),
  436. mDialogClosed(true),
  437. #endif
  438. #endif
  439. qFileDialogUi(0)
  440. {
  441. }
  442. QFileDialogPrivate::~QFileDialogPrivate()
  443. {
  444. }
  445. void QFileDialogPrivate::retranslateWindowTitle()
  446. {
  447. Q_Q(QFileDialog);
  448. if (!useDefaultCaption || setWindowTitle != q->windowTitle())
  449. return;
  450. if (acceptMode == QFileDialog::AcceptOpen) {
  451. if (fileMode == QFileDialog::DirectoryOnly || fileMode == QFileDialog::Directory)
  452. q->setWindowTitle(QFileDialog::tr("Find Directory"));
  453. else
  454. q->setWindowTitle(QFileDialog::tr("Open"));
  455. } else
  456. q->setWindowTitle(QFileDialog::tr("Save As"));
  457. setWindowTitle = q->windowTitle();
  458. }
  459. void QFileDialogPrivate::setLastVisitedDirectory(const QString &dir)
  460. {
  461. *lastVisitedDir() = dir;
  462. }
  463. void QFileDialogPrivate::retranslateStrings()
  464. {
  465. Q_Q(QFileDialog);
  466. /* WIDGETS */
  467. if (defaultFileTypes)
  468. q->setNameFilter(QFileDialog::tr("All Files (*)"));
  469. QList<QAction*> actions = qFileDialogUi->treeView->header()->actions();
  470. QAbstractItemModel *abstractModel = model;
  471. #ifndef QT_NO_PROXYMODEL
  472. if (proxyModel)
  473. abstractModel = proxyModel;
  474. #endif
  475. int total = qMin(abstractModel->columnCount(QModelIndex()), actions.count() + 1);
  476. for (int i = 1; i < total; ++i) {
  477. actions.at(i - 1)->setText(QFileDialog::tr("Show ") + abstractModel->headerData(i, Qt::Horizontal, Qt::DisplayRole).toString());
  478. }
  479. /* MENU ACTIONS */
  480. renameAction->setText(QFileDialog::tr("&Rename"));
  481. deleteAction->setText(QFileDialog::tr("&Delete"));
  482. showHiddenAction->setText(QFileDialog::tr("Show &hidden files"));
  483. newFolderAction->setText(QFileDialog::tr("&New Folder"));
  484. qFileDialogUi->retranslateUi(q);
  485. if (!fileNameLabelExplicitlySat){
  486. if (fileMode == QFileDialog::DirectoryOnly || fileMode == QFileDialog::Directory) {
  487. q->setLabelText(QFileDialog::FileName, QFileDialog::tr("Directory:"));
  488. } else {
  489. q->setLabelText(QFileDialog::FileName, QFileDialog::tr("File &name:"));
  490. }
  491. fileNameLabelExplicitlySat = false;
  492. }
  493. }
  494. void QFileDialogPrivate::emitFilesSelected(const QStringList &files)
  495. {
  496. Q_Q(QFileDialog);
  497. emit q->filesSelected(files);
  498. if (files.count() == 1)
  499. emit q->fileSelected(files.first());
  500. }
  501. bool QFileDialogPrivate::canBeNativeDialog()
  502. {
  503. Q_Q(QFileDialog);
  504. if (nativeDialogInUse)
  505. return true;
  506. if (q->testAttribute(Qt::WA_DontShowOnScreen))
  507. return false;
  508. if (opts & QFileDialog::DontUseNativeDialog)
  509. return false;
  510. QLatin1String staticName(QFileDialog::staticMetaObject.className());
  511. QLatin1String dynamicName(q->metaObject()->className());
  512. return (staticName == dynamicName);
  513. }
  514. /*!
  515. \since 4.5
  516. Sets the given \a option to be enabled if \a on is true; otherwise,
  517. clears the given \a option.
  518. \sa options, testOption()
  519. */
  520. void QFileDialog::setOption(Option option, bool on)
  521. {
  522. Q_D(QFileDialog);
  523. if (!(d->opts & option) != !on)
  524. setOptions(d->opts ^ option);
  525. }
  526. /*!
  527. \since 4.5
  528. Returns true if the given \a option is enabled; otherwise, returns
  529. false.
  530. \sa options, setOption()
  531. */
  532. bool QFileDialog::testOption(Option option) const
  533. {
  534. Q_D(const QFileDialog);
  535. return (d->opts & option) != 0;
  536. }
  537. /*!
  538. \property QFileDialog::options
  539. \brief the various options that affect the look and feel of the dialog
  540. \since 4.5
  541. By default, all options are disabled.
  542. Options should be set before showing the dialog. Setting them while the
  543. dialog is visible is not guaranteed to have an immediate effect on the
  544. dialog (depending on the option and on the platform).
  545. \sa setOption(), testOption()
  546. */
  547. void QFileDialog::setOptions(Options options)
  548. {
  549. Q_D(QFileDialog);
  550. Options changed = (options ^ d->opts);
  551. if (!changed)
  552. return;
  553. d->opts = options;
  554. if (changed & DontResolveSymlinks)
  555. d->model->setResolveSymlinks(!(options & DontResolveSymlinks));
  556. if (changed & ReadOnly) {
  557. bool ro = (options & ReadOnly);
  558. d->model->setReadOnly(ro);
  559. d->qFileDialogUi->newFolderButton->setEnabled(!ro);
  560. d->renameAction->setEnabled(!ro);
  561. d->deleteAction->setEnabled(!ro);
  562. }
  563. if (changed & HideNameFilterDetails)
  564. setNameFilters(d->nameFilters);
  565. if (changed & ShowDirsOnly)
  566. setFilter((options & ShowDirsOnly) ? filter() & ~QDir::Files : filter() | QDir::Files);
  567. }
  568. QFileDialog::Options QFileDialog::options() const
  569. {
  570. Q_D(const QFileDialog);
  571. return d->opts;
  572. }
  573. /*!
  574. \overload
  575. \since 4.5
  576. This function connects one of its signals to the slot specified by \a receiver
  577. and \a member. The specific signal depends is filesSelected() if fileMode is
  578. ExistingFiles and fileSelected() if fileMode is anything else.
  579. The signal will be disconnected from the slot when the dialog is closed.
  580. */
  581. void QFileDialog::open(QObject *receiver, const char *member)
  582. {
  583. Q_D(QFileDialog);
  584. const char *signal = (fileMode() == ExistingFiles) ? SIGNAL(filesSelected(QStringList))
  585. : SIGNAL(fileSelected(QString));
  586. connect(this, signal, receiver, member);
  587. d->signalToDisconnectOnClose = signal;
  588. d->receiverToDisconnectOnClose = receiver;
  589. d->memberToDisconnectOnClose = member;
  590. QDialog::open();
  591. }
  592. /*!
  593. \reimp
  594. */
  595. void QFileDialog::setVisible(bool visible)
  596. {
  597. Q_D(QFileDialog);
  598. if (visible){
  599. if (testAttribute(Qt::WA_WState_ExplicitShowHide) && !testAttribute(Qt::WA_WState_Hidden))
  600. return;
  601. } else if (testAttribute(Qt::WA_WState_ExplicitShowHide) && testAttribute(Qt::WA_WState_Hidden))
  602. return;
  603. if (d->canBeNativeDialog()){
  604. if (d->setVisible_sys(visible)){
  605. d->nativeDialogInUse = true;
  606. // Set WA_DontShowOnScreen so that QDialog::setVisible(visible) below
  607. // updates the state correctly, but skips showing the non-native version:
  608. setAttribute(Qt::WA_DontShowOnScreen);
  609. #ifndef QT_NO_FSCOMPLETER
  610. //So the completer don't try to complete and therefore to show a popup
  611. d->completer->setModel(0);
  612. #endif
  613. } else {
  614. d->nativeDialogInUse = false;
  615. setAttribute(Qt::WA_DontShowOnScreen, false);
  616. #ifndef QT_NO_FSCOMPLETER
  617. if (d->proxyModel != 0)
  618. d->completer->setModel(d->proxyModel);
  619. else
  620. d->completer->setModel(d->model);
  621. #endif
  622. }
  623. }
  624. if (!d->nativeDialogInUse)
  625. d->qFileDialogUi->fileNameEdit->setFocus();
  626. QDialog::setVisible(visible);
  627. }
  628. /*!
  629. \internal
  630. set the directory to url
  631. */
  632. void QFileDialogPrivate::_q_goToUrl(const QUrl &url)
  633. {
  634. //The shortcut in the side bar may have a parent that is not fetched yet (e.g. an hidden file)
  635. //so we force the fetching
  636. QFileSystemModelPrivate::QFileSystemNode *node = model->d_func()->node(url.toLocalFile(), true);
  637. QModelIndex idx = model->d_func()->index(node);
  638. _q_enterDirectory(idx);
  639. }
  640. /*!
  641. \fn void QFileDialog::setDirectory(const QDir &directory)
  642. \overload
  643. */
  644. /*!
  645. Sets the file dialog's current \a directory.
  646. */
  647. void QFileDialog::setDirectory(const QString &directory)
  648. {
  649. Q_D(QFileDialog);
  650. QString newDirectory = directory;
  651. QFileInfo info(directory);
  652. //we remove .. and . from the given path if exist
  653. if (!directory.isEmpty())
  654. newDirectory = QDir::cleanPath(directory);
  655. if (!directory.isEmpty() && newDirectory.isEmpty())
  656. return;
  657. d->setLastVisitedDirectory(newDirectory);
  658. if (d->nativeDialogInUse){
  659. d->setDirectory_sys(newDirectory);
  660. return;
  661. }
  662. if (d->rootPath() == newDirectory)
  663. return;
  664. QModelIndex root = d->model->setRootPath(newDirectory);
  665. d->qFileDialogUi->newFolderButton->setEnabled(d->model->flags(root) & Qt::ItemIsDropEnabled);
  666. if (root != d->rootIndex()) {
  667. #ifndef QT_NO_FSCOMPLETER
  668. if (directory.endsWith(QLatin1Char('/')))
  669. d->completer->setCompletionPrefix(newDirectory);
  670. else
  671. d->completer->setCompletionPrefix(newDirectory + QLatin1Char('/'));
  672. #endif
  673. d->setRootIndex(root);
  674. }
  675. d->qFileDialogUi->listView->selectionModel()->clear();
  676. }
  677. /*!
  678. Returns the directory currently being displayed in the dialog.
  679. */
  680. QDir QFileDialog::directory() const
  681. {
  682. Q_D(const QFileDialog);
  683. return QDir(d->nativeDialogInUse ? d->directory_sys() : d->rootPath());
  684. }
  685. /*!
  686. Selects the given \a filename in the file dialog.
  687. \sa selectedFiles()
  688. */
  689. void QFileDialog::selectFile(const QString &filename)
  690. {
  691. Q_D(QFileDialog);
  692. if (filename.isEmpty())
  693. return;
  694. if (d->nativeDialogInUse){
  695. d->selectFile_sys(filename);
  696. return;
  697. }
  698. if (!QDir::isRelativePath(filename)) {
  699. QFileInfo info(filename);
  700. QString filenamePath = info.absoluteDir().path();
  701. if (d->model->rootPath() != filenamePath)
  702. setDirectory(filenamePath);
  703. }
  704. QModelIndex index = d->model->index(filename);
  705. QString file;
  706. if (!index.isValid()) {
  707. // save as dialog where we want to input a default value
  708. QString text = filename;
  709. if (QFileInfo(filename).isAbsolute()) {
  710. QString current = d->rootPath();
  711. text.remove(current);
  712. if (text.at(0) == QDir::separator()
  713. #ifdef Q_OS_WIN
  714. //On Windows both cases can happen
  715. || text.at(0) == QLatin1Char('/')
  716. #endif
  717. )
  718. text = text.remove(0,1);
  719. }
  720. file = text;
  721. } else {
  722. file = index.data().toString();
  723. }
  724. d->qFileDialogUi->listView->selectionModel()->clear();
  725. if (!isVisible() || !d->lineEdit()->hasFocus())
  726. d->lineEdit()->setText(file);
  727. }
  728. #ifdef Q_OS_UNIX
  729. Q_AUTOTEST_EXPORT QString qt_tildeExpansion(const QString &path, bool *expanded = 0)
  730. {
  731. if (expanded != 0)
  732. *expanded = false;
  733. if (!path.startsWith(QLatin1Char('~')))
  734. return path;
  735. QString ret = path;
  736. #if !defined(Q_OS_INTEGRITY)
  737. QStringList tokens = ret.split(QDir::separator());
  738. if (tokens.first() == QLatin1String("~")) {
  739. ret.replace(0, 1, QDir::homePath());
  740. } else {
  741. QString userName = tokens.first();
  742. userName.remove(0, 1);
  743. #if defined(_POSIX_THREAD_SAFE_FUNCTIONS) && !defined(Q_OS_OPENBSD)
  744. passwd pw;
  745. passwd *tmpPw;
  746. char buf[200];
  747. const int bufSize = sizeof(buf);
  748. int err = 0;
  749. #if defined(Q_OS_SOLARIS) && (_POSIX_C_SOURCE - 0 < 199506L)
  750. tmpPw = getpwnam_r(userName.toLocal8Bit().constData(), &pw, buf, bufSize);
  751. #else
  752. err = getpwnam_r(userName.toLocal8Bit().constData(), &pw, buf, bufSize, &tmpPw);
  753. #endif
  754. if (err || !tmpPw)
  755. return ret;
  756. const QString homePath = QString::fromLocal8Bit(pw.pw_dir);
  757. #else
  758. passwd *pw = getpwnam(userName.toLocal8Bit().constData());
  759. if (!pw)
  760. return ret;
  761. const QString homePath = QString::fromLocal8Bit(pw->pw_dir);
  762. #endif
  763. ret.replace(0, tokens.first().length(), homePath);
  764. }
  765. if (expanded != 0)
  766. *expanded = true;
  767. #endif
  768. return ret;
  769. }
  770. #endif
  771. /**
  772. Returns the text in the line edit which can be one or more file names
  773. */
  774. QStringList QFileDialogPrivate::typedFiles() const
  775. {
  776. #ifdef Q_OS_UNIX
  777. Q_Q(const QFileDialog);
  778. #endif
  779. QStringList files;
  780. QString editText = lineEdit()->text();
  781. if (!editText.contains(QLatin1Char('"'))) {
  782. #ifdef Q_OS_UNIX
  783. const QString prefix = q->directory().absolutePath() + QDir::separator();
  784. if (QFile::exists(prefix + editText))
  785. files << editText;
  786. else
  787. files << qt_tildeExpansion(editText);
  788. #else
  789. files << editText;
  790. #endif
  791. } else {
  792. // " is used to separate files like so: "file1" "file2" "file3" ...
  793. // ### need escape character for filenames with quotes (")
  794. QStringList tokens = editText.split(QLatin1Char('\"'));
  795. for (int i=0; i<tokens.size(); ++i) {
  796. if ((i % 2) == 0)
  797. continue; // Every even token is a separator
  798. #ifdef Q_OS_UNIX
  799. const QString token = tokens.at(i);
  800. const QString prefix = q->directory().absolutePath() + QDir::separator();
  801. if (QFile::exists(prefix + token))
  802. files << token;
  803. else
  804. files << qt_tildeExpansion(token);
  805. #else
  806. files << toInternal(tokens.at(i));
  807. #endif
  808. }
  809. }
  810. return addDefaultSuffixToFiles(files);
  811. }
  812. QStringList QFileDialogPrivate::addDefaultSuffixToFiles(const QStringList filesToFix) const
  813. {
  814. QStringList files;
  815. for (int i=0; i<filesToFix.size(); ++i) {
  816. QString name = toInternal(filesToFix.at(i));
  817. QFileInfo info(name);
  818. // if the filename has no suffix, add the default suffix
  819. if (!defaultSuffix.isEmpty() && !info.isDir() && name.lastIndexOf(QLatin1Char('.')) == -1)
  820. name += QLatin1Char('.') + defaultSuffix;
  821. if (info.isAbsolute()) {
  822. files.append(name);
  823. } else {
  824. // at this point the path should only have Qt path separators.
  825. // This check is needed since we might be at the root directory
  826. // and on Windows it already ends with slash.
  827. QString path = rootPath();
  828. if (!path.endsWith(QLatin1Char('/')))
  829. path += QLatin1Char('/');
  830. path += name;
  831. files.append(path);
  832. }
  833. }
  834. return files;
  835. }
  836. /*!
  837. Returns a list of strings containing the absolute paths of the
  838. selected files in the dialog. If no files are selected, or
  839. the mode is not ExistingFiles or ExistingFile, selectedFiles() contains the current path in the viewport.
  840. \sa selectedNameFilter(), selectFile()
  841. */
  842. QStringList QFileDialog::selectedFiles() const
  843. {
  844. Q_D(const QFileDialog);
  845. if (d->nativeDialogInUse)
  846. return d->addDefaultSuffixToFiles(d->selectedFiles_sys());
  847. QModelIndexList indexes = d->qFileDialogUi->listView->selectionModel()->selectedRows();
  848. QStringList files;
  849. for (int i = 0; i < indexes.count(); ++i)
  850. files.append(indexes.at(i).data(QFileSystemModel::FilePathRole).toString());
  851. if (files.isEmpty() && !d->lineEdit()->text().isEmpty())
  852. files = d->typedFiles();
  853. if (files.isEmpty() && !(d->fileMode == ExistingFile || d->fileMode == ExistingFiles))
  854. files.append(d->rootIndex().data(QFileSystemModel::FilePathRole).toString());
  855. return files;
  856. }
  857. /*
  858. Makes a list of filters from ;;-separated text.
  859. Used by the mac and windows implementations
  860. */
  861. QStringList qt_make_filter_list(const QString &filter)
  862. {
  863. QString f(filter);
  864. if (f.isEmpty())
  865. return QStringList();
  866. QString sep(QLatin1String(";;"));
  867. int i = f.indexOf(sep, 0);
  868. if (i == -1) {
  869. if (f.indexOf(QLatin1Char('\n'), 0) != -1) {
  870. sep = QLatin1Char('\n');
  871. i = f.indexOf(sep, 0);
  872. }
  873. }
  874. return f.split(sep);
  875. }
  876. /*!
  877. \since 4.4
  878. Sets the filter used in the file dialog to the given \a filter.
  879. If \a filter contains a pair of parentheses containing one or more
  880. of \bold{anything*something}, separated by spaces, then only the
  881. text contained in the parentheses is used as the filter. This means
  882. that these calls are all equivalent:
  883. \snippet doc/src/snippets/code/src_gui_dialogs_qfiledialog.cpp 6
  884. \sa setNameFilters()
  885. */
  886. void QFileDialog::setNameFilter(const QString &filter)
  887. {
  888. setNameFilters(qt_make_filter_list(filter));
  889. }
  890. /*!
  891. \obsolete
  892. Use setNameFilter() instead.
  893. */
  894. void QFileDialog::setFilter(const QString &filter)
  895. {
  896. setNameFilter(filter);
  897. }
  898. /*!
  899. \property QFileDialog::nameFilterDetailsVisible
  900. \obsolete
  901. \brief This property holds whether the filter details is shown or not.
  902. \since 4.4
  903. When this property is true (the default), the filter details are shown
  904. in the combo box. When the property is set to false, these are hidden.
  905. Use setOption(HideNameFilterDetails, !\e enabled) or
  906. !testOption(HideNameFilterDetails).
  907. */
  908. void QFileDialog::setNameFilterDetailsVisible(bool enabled)
  909. {
  910. setOption(HideNameFilterDetails, !enabled);
  911. }
  912. bool QFileDialog::isNameFilterDetailsVisible() const
  913. {
  914. return !testOption(HideNameFilterDetails);
  915. }
  916. /*
  917. Strip the filters by removing the details, e.g. (*.*).
  918. */
  919. QStringList qt_strip_filters(const QStringList &filters)
  920. {
  921. QStringList strippedFilters;
  922. QRegExp r(QString::fromLatin1(qt_file_dialog_filter_reg_exp));
  923. for (int i = 0; i < filters.count(); ++i) {
  924. QString filterName;
  925. int index = r.indexIn(filters[i]);
  926. if (index >= 0)
  927. filterName = r.cap(1);
  928. strippedFilters.append(filterName.simplified());
  929. }
  930. return strippedFilters;
  931. }
  932. /*!
  933. \since 4.4
  934. Sets the \a filters used in the file dialog.
  935. \snippet doc/src/snippets/code/src_gui_dialogs_qfiledialog.cpp 7
  936. */
  937. void QFileDialog::setNameFilters(const QStringList &filters)
  938. {
  939. Q_D(QFileDialog);
  940. d->defaultFileTypes = (filters == QStringList(QFileDialog::tr("All Files (*)")));
  941. QStringList cleanedFilters;
  942. for (int i = 0; i < filters.count(); ++i) {
  943. cleanedFilters << filters[i].simplified();
  944. }
  945. d->nameFilters = cleanedFilters;
  946. if (d->nativeDialogInUse){
  947. d->setNameFilters_sys(cleanedFilters);
  948. return;
  949. }
  950. d->qFileDialogUi->fileTypeCombo->clear();
  951. if (cleanedFilters.isEmpty())
  952. return;
  953. if (testOption(HideNameFilterDetails))
  954. d->qFileDialogUi->fileTypeCombo->addItems(qt_strip_filters(cleanedFilters));
  955. else
  956. d->qFileDialogUi->fileTypeCombo->addItems(cleanedFilters);
  957. d->_q_useNameFilter(0);
  958. }
  959. /*!
  960. \obsolete
  961. Use setNameFilters() instead.
  962. */
  963. void QFileDialog::setFilters(const QStringList &filters)
  964. {
  965. setNameFilters(filters);
  966. }
  967. /*!
  968. \since 4.4
  969. Returns the file type filters that are in operation on this file
  970. dialog.
  971. */
  972. QStringList QFileDialog::nameFilters() const
  973. {
  974. return d_func()->nameFilters;
  975. }
  976. /*!
  977. \obsolete
  978. Use nameFilters() instead.
  979. */
  980. QStringList QFileDialog::filters() const
  981. {
  982. return nameFilters();
  983. }
  984. /*!
  985. \since 4.4
  986. Sets the current file type \a filter. Multiple filters can be
  987. passed in \a filter by separating them with semicolons or spaces.
  988. \sa setNameFilter(), setNameFilters(), selectedNameFilter()
  989. */
  990. void QFileDialog::selectNameFilter(const QString &filter)
  991. {
  992. Q_D(QFileDialog);
  993. if (d->nativeDialogInUse) {
  994. d->selectNameFilter_sys(filter);
  995. return;
  996. }
  997. int i = -1;
  998. if (testOption(HideNameFilterDetails)) {
  999. const QStringList filters = qt_strip_filters(qt_make_filter_list(filter));
  1000. if (!filters.isEmpty())
  1001. i = d->qFileDialogUi->fileTypeCombo->findText(filters.first());
  1002. } else {
  1003. i = d->qFileDialogUi->fileTypeCombo->findText(filter);
  1004. }
  1005. if (i >= 0) {
  1006. d->qFileDialogUi->fileTypeCombo->setCurrentIndex(i);
  1007. d->_q_useNameFilter(d->qFileDialogUi->fileTypeCombo->currentIndex());
  1008. }
  1009. }
  1010. /*!
  1011. \obsolete
  1012. Use selectNameFilter() instead.
  1013. */
  1014. void QFileDialog::selectFilter(const QString &filter)
  1015. {
  1016. selectNameFilter(filter);
  1017. }
  1018. /*!
  1019. \since 4.4
  1020. Returns the filter that the user selected in the file dialog.
  1021. \sa selectedFiles()
  1022. */
  1023. QString QFileDialog::selectedNameFilter() const
  1024. {
  1025. Q_D(const QFileDialog);
  1026. if (d->nativeDialogInUse)
  1027. return d->selectedNameFilter_sys();
  1028. return d->qFileDialogUi->fileTypeCombo->currentText();
  1029. }
  1030. /*!
  1031. \obsolete
  1032. Use selectedNameFilter() instead.
  1033. */
  1034. QString QFileDialog::selectedFilter() const
  1035. {
  1036. return selectedNameFilter();
  1037. }
  1038. /*!
  1039. \since 4.4
  1040. Returns the filter that is used when displaying files.
  1041. \sa setFilter()
  1042. */
  1043. QDir::Filters QFileDialog::filter() const
  1044. {
  1045. Q_D(const QFileDialog);
  1046. return d->model->filter();
  1047. }
  1048. /*!
  1049. \since 4.4
  1050. Sets the filter used by the model to \a filters. The filter is used
  1051. to specify the kind of files that should be shown.
  1052. \sa filter()
  1053. */
  1054. void QFileDialog::setFilter(QDir::Filters filters)
  1055. {
  1056. Q_D(QFileDialog);
  1057. d->model->setFilter(filters);
  1058. if (d->nativeDialogInUse){
  1059. d->setFilter_sys();
  1060. return;
  1061. }
  1062. d->showHiddenAction->setChecked((filters & QDir::Hidden));
  1063. }
  1064. /*!
  1065. \property QFileDialog::viewMode
  1066. \brief the way files and directories are displayed in the dialog
  1067. By default, the \c Detail mode is used to display information about
  1068. files and directories.
  1069. \sa ViewMode
  1070. */
  1071. void QFileDialog::setViewMode(QFileDialog::ViewMode mode)
  1072. {
  1073. Q_D(QFileDialog);
  1074. if (mode == Detail)
  1075. d->_q_showDetailsView();
  1076. else
  1077. d->_q_showListView();
  1078. }
  1079. QFileDialog::ViewMode QFileDialog::viewMode() const
  1080. {
  1081. Q_D(const QFileDialog);
  1082. return (d->qFileDialogUi->stackedWidget->currentWidget() == d->qFileDialogUi->listView->parent() ? QFileDialog::List : QFileDialog::Detail);
  1083. }
  1084. /*!
  1085. \property QFileDialog::fileMode
  1086. \brief the file mode of the dialog
  1087. The file mode defines the number and type of items that the user is
  1088. expected to select in the dialog.
  1089. By default, this property is set to AnyFile.
  1090. This function will set the labels for the FileName and
  1091. \l{QFileDialog::}{Accept} \l{DialogLabel}s. It is possible to set
  1092. custom text after the call to setFileMode().
  1093. \sa FileMode
  1094. */
  1095. void QFileDialog::setFileMode(QFileDialog::FileMode mode)
  1096. {
  1097. Q_D(QFileDialog);
  1098. d->fileMode = mode;
  1099. d->retranslateWindowTitle();
  1100. // keep ShowDirsOnly option in sync with fileMode (BTW, DirectoryOnly is obsolete)
  1101. setOption(ShowDirsOnly, mode == DirectoryOnly);
  1102. // set selection mode and behavior
  1103. QAbstractItemView::SelectionMode selectionMode;
  1104. if (mode == QFileDialog::ExistingFiles)
  1105. selectionMode = QAbstractItemView::ExtendedSelection;
  1106. else
  1107. selectionMode = QAbstractItemView::SingleSelection;
  1108. d->qFileDialogUi->listView->setSelectionMode(selectionMode);
  1109. d->qFileDialogUi->treeView->setSelectionMode(selectionMode);
  1110. // set filter
  1111. d->model->setFilter(d->filterForMode(filter()));
  1112. // setup file type for directory
  1113. QString buttonText = (d->acceptMode == AcceptOpen ? tr("&Open") : tr("&Save"));
  1114. if (mode == DirectoryOnly || mode == Directory) {
  1115. d->qFileDialogUi->fileTypeCombo->clear();
  1116. d->qFileDialogUi->fileTypeCombo->addItem(tr("Directories"));
  1117. d->qFileDialogUi->fileTypeCombo->setEnabled(false);
  1118. if (!d->fileNameLabelExplicitlySat){
  1119. setLabelText(FileName, tr("Directory:"));
  1120. d->fileNameLabelExplicitlySat = false;
  1121. }
  1122. buttonText = tr("&Choose");
  1123. } else {
  1124. if (!d->fileNameLabelExplicitlySat){
  1125. setLabelText(FileName, tr("File &name:"));
  1126. d->fileNameLabelExplicitlySat = false;
  1127. }
  1128. }
  1129. setLabelText(Accept, buttonText);
  1130. if (d->nativeDialogInUse){
  1131. d->setFilter_sys();
  1132. return;
  1133. }
  1134. d->qFileDialogUi->fileTypeCombo->setEnabled(!testOption(ShowDirsOnly));
  1135. d->_q_updateOkButton();
  1136. }
  1137. QFileDialog::FileMode QFileDialog::fileMode() const
  1138. {
  1139. Q_D(const QFileDialog);
  1140. return d->fileMode;
  1141. }
  1142. /*!
  1143. \property QFileDialog::acceptMode
  1144. \brief the accept mode of the dialog
  1145. The action mode defines whether the dialog is for opening or saving files.
  1146. By default, this property is set to \l{AcceptOpen}.
  1147. \sa AcceptMode
  1148. */
  1149. void QFileDialog::setAcceptMode(QFileDialog::AcceptMode mode)
  1150. {
  1151. Q_D(QFileDialog);
  1152. d->acceptMode = mode;
  1153. bool directoryMode = (d->fileMode == Directory || d->fileMode == DirectoryOnly);
  1154. QDialogButtonBox::StandardButton button = (mode == AcceptOpen ? QDialogButtonBox::Open : QDialogButtonBox::Save);
  1155. d->qFileDialogUi->buttonBox->setStandardButtons(button | QDialogButtonBox::Cancel);
  1156. d->qFileDialogUi->buttonBox->button(button)->setEnabled(false);
  1157. d->_q_updateOkButton();
  1158. if (mode == AcceptOpen && directoryMode)
  1159. setLabelText(Accept, tr("&Choose"));
  1160. else
  1161. setLabelText(Accept, (mode == AcceptOpen ? tr("&Open") : tr("&Save")));
  1162. if (mode == AcceptSave) {
  1163. d->qFileDialogUi->lookInCombo->setEditable(false);
  1164. }
  1165. d->retranslateWindowTitle();
  1166. #if defined(Q_WS_MAC)
  1167. d->deleteNativeDialog_sys();
  1168. setAttribute(Qt::WA_DontShowOnScreen, false);
  1169. #endif
  1170. }
  1171. /*
  1172. Returns the file system model index that is the root index in the
  1173. views
  1174. */
  1175. QModelIndex QFileDialogPrivate::rootIndex() const {
  1176. return mapToSource(qFileDialogUi->listView->rootIndex());
  1177. }
  1178. QAbstractItemView *QFileDialogPrivate::currentView() const {
  1179. if (!qFileDialogUi->stackedWidget)
  1180. return 0;
  1181. if (qFileDialogUi->stackedWidget->currentWidget() == qFileDialogUi->listView->parent())
  1182. return qFileDialogUi->listView;
  1183. return qFileDialogUi->treeView;
  1184. }
  1185. QLineEdit *QFileDialogPrivate::lineEdit() const {
  1186. return (QLineEdit*)qFileDialogUi->fileNameEdit;
  1187. }
  1188. /*
  1189. Sets the view root index to be the file system model index
  1190. */
  1191. void QFileDialogPrivate::setRootIndex(const QModelIndex &index) const {
  1192. Q_ASSERT(index.isValid() ? index.model() == model : true);
  1193. QModelIndex idx = mapFromSource(index);
  1194. qFileDialogUi->treeView->setRootIndex(idx);
  1195. qFileDialogUi->listView->setRootIndex(idx);
  1196. }
  1197. /*
  1198. Select a file system model index
  1199. returns the index that was selected (or not depending upon sortfilterproxymodel)
  1200. */
  1201. QModelIndex QFileDialogPrivate::select(const QModelIndex &index) const {
  1202. Q_ASSERT(index.isValid() ? index.model() == model : true);
  1203. QModelIndex idx = mapFromSource(index);
  1204. if (idx.isValid() && !qFileDialogUi->listView->selectionModel()->isSelected(idx))
  1205. qFileDialogUi->listView->selectionModel()->select(idx,
  1206. QItemSelectionModel::Select | QItemSelectionModel::Rows);
  1207. return idx;
  1208. }
  1209. QFileDialog::AcceptMode QFileDialog::acceptMode() const
  1210. {
  1211. Q_D(const QFileDialog);
  1212. return d->acceptMode;
  1213. }
  1214. /*!
  1215. \property QFileDialog::readOnly
  1216. \obsolete
  1217. \brief Whether the filedialog is read-only
  1218. If this property is set to false, the file dialog will allow renaming,
  1219. and deleting of files and directories and creating directories.
  1220. Use setOption(ReadOnly, \e enabled) or testOption(ReadOnly) instead.
  1221. */
  1222. void QFileDialog::setReadOnly(bool enabled)
  1223. {
  1224. setOption(ReadOnly, enabled);
  1225. }
  1226. bool QFileDialog::isReadOnly() const
  1227. {
  1228. return testOption(ReadOnly);
  1229. }
  1230. /*!
  1231. \property QFileDialog::resolveSymlinks
  1232. \obsolete
  1233. \brief whether the filedialog should resolve shortcuts
  1234. If this property is set to true, the file dialog will resolve
  1235. shortcuts or symbolic links.
  1236. Use setOption(DontResolveSymlinks, !\a enabled) or
  1237. !testOption(DontResolveSymlinks).
  1238. */
  1239. void QFileDialog::setResolveSymlinks(bool enabled)
  1240. {
  1241. setOption(DontResolveSymlinks, !enabled);
  1242. }
  1243. bool QFileDialog::resolveSymlinks() const
  1244. {
  1245. return !testOption(DontResolveSymlinks);
  1246. }
  1247. /*!
  1248. \property QFileDialog::confirmOverwrite
  1249. \obsolete
  1250. \brief whether the filedialog should ask before accepting a selected file,
  1251. when the accept mode is AcceptSave
  1252. Use setOption(DontConfirmOverwrite, !\e enabled) or
  1253. !testOption(DontConfirmOverwrite) instead.
  1254. */
  1255. void QFileDialog::setConfirmOverwrite(bool enabled)
  1256. {
  1257. setOption(DontConfirmOverwrite, !enabled);
  1258. }
  1259. bool QFileDialog::confirmOverwrite() const
  1260. {
  1261. return !testOption(DontConfirmOverwrite);
  1262. }
  1263. /*!
  1264. \property QFileDialog::defaultSuffix
  1265. \brief suffix added to the filename if no other suffix was specified
  1266. This property specifies a string that will be added to the
  1267. filename if it has no suffix already. The suffix is typically
  1268. used to indicate the file type (e.g. "txt" indicates a text
  1269. file).
  1270. */
  1271. void QFileDialog::setDefaultSuffix(const QString &suffix)
  1272. {
  1273. Q_D(QFileDialog);
  1274. d->defaultSuffix = suffix;
  1275. }
  1276. QString QFileDialog::defaultSuffix() const
  1277. {
  1278. Q_D(const QFileDialog);
  1279. return d->defaultSuffix;
  1280. }
  1281. /*!
  1282. Sets the browsing history of the filedialog to contain the given
  1283. \a paths.
  1284. */
  1285. void QFileDialog::setHistory(const QStringList &paths)
  1286. {
  1287. Q_D(QFileDialog);
  1288. d->qFileDialogUi->lookInCombo->setHistory(paths);
  1289. }
  1290. void QFileDialogComboBox::setHistory(const QStringList &paths)
  1291. {
  1292. m_history = paths;
  1293. // Only populate the first item, showPopup will populate the rest if needed
  1294. QList<QUrl> list;
  1295. QModelIndex idx = d_ptr->model->index(d_ptr->rootPath());
  1296. //On windows the popup display the "C:\", convert to nativeSeparators
  1297. QUrl url = QUrl::fromLocalFile(QDir::toNativeSeparators(idx.data(QFileSystemModel::FilePathRole).toString()));
  1298. if (url.isValid())
  1299. list.append(url);
  1300. urlModel->setUrls(list);
  1301. }
  1302. /*!
  1303. Returns the browsing history of the filedialog as a list of paths.
  1304. */
  1305. QStringList QFileDialog::history() const
  1306. {
  1307. Q_D(const QFileDialog);
  1308. QStringList currentHistory = d->qFileDialogUi->lookInCombo->history();
  1309. //On windows the popup display the "C:\", convert to nativeSeparators
  1310. QString newHistory = QDir::toNativeSeparators(d->rootIndex().data(QFileSystemModel::FilePathRole).toString());
  1311. if (!currentHistory.contains(newHistory))
  1312. currentHistory << newHistory;
  1313. return currentHistory;
  1314. }
  1315. /*!
  1316. Sets the item delegate used to render items in the views in the
  1317. file dialog to the given \a delegate.
  1318. \warning You should not share the same instance of a delegate between views.
  1319. Doing so can cause incorrect or unintuitive editing behavior since each
  1320. view connected to a given delegate may receive the \l{QAbstractItemDelegate::}{closeEditor()}
  1321. signal, and attempt to access, modify or close an editor that has already been closed.
  1322. Note that the model used is QFileSystemModel. It has custom item data roles, which is
  1323. described by the \l{QFileSystemModel::}{Roles} enum. You can use a QFileIconProvider if
  1324. you only want custom icons.
  1325. \sa itemDelegate(), setIconProvider(), QFileSystemModel
  1326. */
  1327. void QFileDialog::setItemDelegate(QAbstractItemDelegate *delegate)
  1328. {
  1329. Q_D(QFileDialog);
  1330. d->qFileDialogUi->listView->setItemDelegate(delegate);
  1331. d->qFileDialogUi->treeView->setItemDelegate(delegate);
  1332. }
  1333. /*!
  1334. Returns the item delegate used to render the items in the views in the filedialog.
  1335. */
  1336. QAbstractItemDelegate *QFileDialog::itemDelegate() const
  1337. {
  1338. Q_D(const QFileDialog);
  1339. return d->qFileDialogUi->listView->itemDelegate();
  1340. }
  1341. /*!
  1342. Sets the icon provider used by the filedialog to the specified \a provider.
  1343. */
  1344. void QFileDialog::setIconProvider(QFileIconProvider *provider)
  1345. {
  1346. Q_D(QFileDialog);
  1347. d->model->setIconProvider(provider);
  1348. //It forces the refresh of all entries in the side bar, then we can get new icons
  1349. d->qFileDialogUi->sidebar->setUrls(d->qFileDialogUi->sidebar->urls());
  1350. }
  1351. /*!
  1352. Returns the icon provider used by the filedialog.
  1353. */
  1354. QFileIconProvider *QFileDialog::iconProvider() const
  1355. {
  1356. Q_D(const QFileDialog);
  1357. return d->model->iconProvider();
  1358. }
  1359. /*!
  1360. Sets the \a text shown in the filedialog in the specified \a label.
  1361. */
  1362. void QFileDialog::setLabelText(DialogLabel label, const QString &text)
  1363. {
  1364. Q_D(QFileDialog);
  1365. QPushButton *button;
  1366. switch (label) {
  1367. case LookIn:
  1368. d->qFileDialogUi->lookInLabel->setText(text);
  1369. break;
  1370. case FileName:
  1371. d->qFileDialogUi->fileNameLabel->setText(text);
  1372. d->fileNameLabelExplicitlySat = true;
  1373. break;
  1374. case FileType:
  1375. d->qFileDialogUi->fileTypeLabel->setText(text);
  1376. break;
  1377. case Accept:
  1378. d->acceptLabel = text;
  1379. if (acceptMode() == AcceptOpen)
  1380. button = d->qFileDialogUi->buttonBox->button(QDialogButtonBox::Open);
  1381. else
  1382. button = d->qFileDialogUi->buttonBox->button(QDialogButtonBox::Save);
  1383. if (button)
  1384. button->setText(text);
  1385. break;
  1386. case Reject:
  1387. button = d->qFileDialogUi->buttonBox->button(QDialogButtonBox::Cancel);
  1388. if (button)
  1389. button->setText(text);
  1390. break;
  1391. }
  1392. }
  1393. /*!
  1394. Returns the text shown in the filedialog in the specified \a label.
  1395. */
  1396. QString QFileDialog::labelText(DialogLabel label) const
  1397. {
  1398. QPushButton *button;
  1399. Q_D(const QFileDialog);
  1400. switch (label) {
  1401. case LookIn:
  1402. return d->qFileDialogUi->lookInLabel->text();
  1403. case FileName:
  1404. return d->qFileDialogUi->fileNameLabel->text();
  1405. case FileType:
  1406. return d->qFileDialogUi->fileTypeLabel->text();
  1407. case Accept:
  1408. if (acceptMode() == AcceptOpen)
  1409. button = d->qFileDialogUi->buttonBox->button(QDialogButtonBox::Open);
  1410. else
  1411. button = d->qFileDialogUi->buttonBox->button(QDialogButtonBox::Save);
  1412. if (button)
  1413. return button->text();
  1414. case Reject:
  1415. button = d->qFileDialogUi->buttonBox->button(QDialogButtonBox::Cancel);
  1416. if (button)
  1417. return button->text();
  1418. }
  1419. return QString();
  1420. }
  1421. /*
  1422. For the native file dialogs
  1423. */
  1424. #if defined(Q_WS_WIN)
  1425. extern QString qt_win_get_open_file_name(const QFileDialogArgs &args,
  1426. QString *initialDirectory,
  1427. QString *selectedFilter);
  1428. extern QString qt_win_get_save_file_name(const QFileDialogArgs &args,
  1429. QString *initialDirectory,
  1430. QString *selectedFilter);
  1431. extern QStringList qt_win_get_open_file_names(const QFileDialogArgs &args,
  1432. QString *initialDirectory,
  1433. QString *selectedFilter);
  1434. extern QString qt_win_get_existing_directory(const QFileDialogArgs &args);
  1435. #endif
  1436. /*
  1437. For Symbian file dialogs
  1438. */
  1439. #if defined(Q_WS_S60)
  1440. extern QString qtSymbianGetOpenFileName(const QString &caption,
  1441. const QString &dir,
  1442. const QString &filter);
  1443. extern QStringList qtSymbianGetOpenFileNames(const QString &caption,
  1444. const QString &dir,
  1445. const QString &filter);
  1446. extern QString qtSymbianGetSaveFileName(const QString &caption,
  1447. const QString &dir);
  1448. extern QString qtSymbianGetExistingDirectory(const QString &caption,
  1449. const QString &dir);
  1450. #endif
  1451. /*!
  1452. This is a convenience static function that returns an existing file
  1453. selected by the user. If the user presses Cancel, it returns a null string.
  1454. \snippet doc/src/snippets/code/src_gui_dialogs_qfiledialog.cpp 8
  1455. The function creates a modal file dialog with the given \a parent widget.
  1456. If \a parent is not 0, the dialog will be shown centered over the parent
  1457. widget.
  1458. The file dialog's working directory will be set to \a dir. If \a dir
  1459. includes a file name, the file will be selected. Only files that match the
  1460. given \a filter are shown. The filter selected is set to \a selectedFilter.
  1461. The parameters \a dir, \a selectedFilter, and \a filter may be empty
  1462. strings. If you want multiple filters, separate them with ';;', for
  1463. example:
  1464. \code
  1465. "Images (*.png *.xpm *.jpg);;Text files (*.txt);;XML files (*.xml)"
  1466. \endcode
  1467. The \a options argument holds various options about how to run the dialog,
  1468. see the QFileDialog::Option enum for more information on the flags you can
  1469. pass.
  1470. The dialog's caption is set to \a caption. If \a caption is not specified
  1471. then a default caption will be used.
  1472. On Windows, Mac OS X and Symbian^3, this static function will use the
  1473. native file dialog and not a QFileDialog.
  1474. On Windows the dialog will spin a blocking modal event loop that will not
  1475. dispatch any QTimers, and if \a parent is not 0 then it will position the
  1476. dialog just below the parent's title bar.
  1477. On Unix/X11, the normal behavior of the file dialog is to resolve and
  1478. follow symlinks. For example, if \c{/usr/tmp} is a symlink to \c{/var/tmp},
  1479. the file dialog will change to \c{/var/tmp} after entering \c{/usr/tmp}. If
  1480. \a options includes DontResolveSymlinks, the file dialog will treat
  1481. symlinks as regular directories.
  1482. On Symbian^3 the parameter \a selectedFilter has no meaning and the
  1483. \a options parameter is only used to define if the native file dialog is
  1484. used.
  1485. \warning Do not delete \a parent during the execution of the dialog. If you
  1486. want to do this, you should create the dialog yourself using one of the
  1487. QFileDialog constructors.
  1488. \sa getOpenFileNames(), getSaveFileName(), getExistingDirectory()
  1489. */
  1490. QString QFileDialog::getOpenFileName(QWidget *parent,
  1491. const QString &caption,
  1492. const QString &dir,
  1493. const QString &filter,
  1494. QString *selectedFilter,
  1495. Options options)
  1496. {
  1497. if (qt_filedialog_open_filename_hook && !(options & DontUseNativeDialog))
  1498. return qt_filedialog_open_filename_hook(parent, caption, dir, filter, selectedFilter, options);
  1499. #if defined(Q_WS_S60)
  1500. if (QSysInfo::s60Version() > QSysInfo::SV_S60_5_0 && !(options & DontUseNativeDialog))
  1501. return qtSymbianGetOpenFileName(caption, dir, filter);
  1502. #endif
  1503. QFileDialogArgs args;
  1504. args.parent = parent;
  1505. args.caption = caption;
  1506. args.directory = QFileDialogPrivate::workingDirectory(dir);
  1507. args.selection = QFileDialogPrivate::initialSelection(dir);
  1508. args.filter = filter;
  1509. args.mode = ExistingFile;
  1510. args.options = options;
  1511. #if defined(Q_WS_WIN)
  1512. if (qt_use_native_dialogs && !(args.options & DontUseNativeDialog)) {
  1513. return qt_win_get_open_file_name(args, &(args.directory), selectedFilter);
  1514. }
  1515. #endif
  1516. // create a qt dialog
  1517. QFileDialog dialog(args);
  1518. if (selectedFilter && !selectedFilter->isEmpty())
  1519. dialog.selectNameFilter(*selectedFilter);
  1520. if (dialog.exec() == QDialog::Accepted) {
  1521. if (selectedFilter)
  1522. *selectedFilter = dialog.selectedFilter();
  1523. return dialog.selectedFiles().value(0);
  1524. }
  1525. return QString();
  1526. }
  1527. /*!
  1528. This is a convenience static function that will return one or more existing
  1529. files selected by the user.
  1530. \snippet doc/src/snippets/code/src_gui_dialogs_qfiledialog.cpp 9
  1531. This function creates a modal file dialog with the given \a parent widget.
  1532. If \a parent is not 0, the dialog will be shown centered over the parent
  1533. widget.
  1534. The file dialog's working directory will be set to \a dir. If \a dir
  1535. includes a file name, the file will be selected. The filter is set to
  1536. \a filter so that only those files which match the filter are shown. The
  1537. filter selected is set to \a selectedFilter. The parameters \a dir,
  1538. \a selectedFilter and \a filter may be empty strings. If you need multiple
  1539. filters, separate them with ';;', for instance:
  1540. \code
  1541. "Images (*.png *.xpm *.jpg);;Text files (*.txt);;XML files (*.xml)"
  1542. \endcode
  1543. The dialog's caption is set to \a caption. If \a caption is not specified
  1544. then a default caption will be used.
  1545. On Windows, Mac OS X and Symbian^3, this static function will use the
  1546. native file dialog and not a QFileDialog.
  1547. On Windows the dialog will spin a blocking modal event loop that will not
  1548. dispatch any QTimers, and if \a parent is not 0 then it will position the
  1549. dialog just below the parent's title bar.
  1550. On Unix/X11, the normal behavior of the file dialog is to resolve and
  1551. follow symlinks. For example, if \c{/usr/tmp} is a symlink to \c{/var/tmp},
  1552. the file dialog will change to \c{/var/tmp} after entering \c{/usr/tmp}.
  1553. The \a options argument holds various options about how to run the dialog,
  1554. see the QFileDialog::Option enum for more information on the flags you can
  1555. pass.
  1556. \note If you want to iterate over the list of files, you should iterate
  1557. over a copy. For example:
  1558. \snippet doc/src/snippets/code/src_gui_dialogs_qfiledialog.cpp 10
  1559. On Symbian^3 the parameter \a selectedFilter has no meaning and the
  1560. \a options parameter is only used to define if the native file dialog is
  1561. used. On Symbian^3, this function can only return a single filename.
  1562. \warning Do not delete \a parent during the execution of the dialog. If you
  1563. want to do this, you should create the dialog yourself using one of the
  1564. QFileDialog constructors.
  1565. \sa getOpenFileName(), getSaveFileName(), getExistingDirectory()
  1566. */
  1567. QStringList QFileDialog::getOpenFileNames(QWidget *parent,
  1568. const QString &caption,
  1569. const QString &dir,
  1570. const QString &filter,
  1571. QString *selectedFilter,
  1572. Options options)
  1573. {
  1574. if (qt_filedialog_open_filenames_hook && !(options & DontUseNativeDialog))
  1575. return qt_filedialog_open_filenames_hook(parent, caption, dir, filter, selectedFilter, options);
  1576. #if defined(Q_WS_S60)
  1577. if (QSysInfo::s60Version() > QSysInfo::SV_S60_5_0 && !(options & DontUseNativeDialog))
  1578. return qtSymbianGetOpenFileNames(caption, dir, filter);
  1579. #endif
  1580. QFileDialogArgs args;
  1581. args.parent = parent;
  1582. args.caption = caption;
  1583. args.directory = QFileDialogPrivate::workingDirectory(dir);
  1584. args.selection = QFileDialogPrivate::initialSelection(dir);
  1585. args.filter = filter;
  1586. args.mode = ExistingFiles;
  1587. args.options = options;
  1588. #if defined(Q_WS_WIN)
  1589. if (qt_use_native_dialogs && !(args.options & DontUseNativeDialog)) {
  1590. return qt_win_get_open_file_names(args, &(args.directory), selectedFilter);
  1591. }
  1592. #endif
  1593. // create a qt dialog
  1594. QFileDialog dialog(args);
  1595. if (selectedFilter && !selectedFilter->isEmpty())
  1596. dialog.selectNameFilter(*selectedFilter);
  1597. if (dialog.exec() == QDialog::Accepted) {
  1598. if (selectedFilter)
  1599. *selectedFilter = dialog.selectedFilter();
  1600. return dialog.selectedFiles();
  1601. }
  1602. return QStringList();
  1603. }
  1604. /*!
  1605. This is a convenience static function that will return a file name selected
  1606. by the user. The file does not have to exist.
  1607. It creates a modal file dialog with the given \a parent widget. If
  1608. \a parent is not 0, the dialog will be shown centered over the parent
  1609. widget.
  1610. \snippet doc/src/snippets/code/src_gui_dialogs_qfiledialog.cpp 11
  1611. The file dialog's working directory will be set to \a dir. If \a dir
  1612. includes a file name, the file will be selected. Only files that match the
  1613. \a filter are shown. The filter selected is set to \a selectedFilter. The
  1614. parameters \a dir, \a selectedFilter, and \a filter may be empty strings.
  1615. Multiple filters are separated with ';;'. For instance:
  1616. \code
  1617. "Images (*.png *.xpm *.jpg);;Text files (*.txt);;XML files (*.xml)"
  1618. \endcode
  1619. The \a options argument holds various options about how to run the dialog,
  1620. see the QFileDialog::Option enum for more information on the flags you can
  1621. pass.
  1622. The default filter can be chosen by setting \a selectedFilter to the
  1623. desired value.
  1624. The dialog's caption is set to \a caption. If \a caption is not specified,
  1625. a default caption will be used.
  1626. On Windows, Mac OS X and Symbian^3, this static function will use the
  1627. native file dialog and not a QFileDialog.
  1628. On Windows the dialog will spin a blocking modal event loop that will not
  1629. dispatch any QTimers, and if \a parent is not 0 then it will position the
  1630. dialog just below the parent's title bar. On Mac OS X, with its native file
  1631. dialog, the filter argument is ignored.
  1632. On Unix/X11, the normal behavior of the file dialog is to resolve and
  1633. follow symlinks. For example, if \c{/usr/tmp} is a symlink to \c{/var/tmp},
  1634. the file dialog will change to \c{/var/tmp} after entering \c{/usr/tmp}. If
  1635. \a options includes DontResolveSymlinks the file dialog will treat symlinks
  1636. as regular directories.
  1637. On Symbian^3 the parameters \a filter and \a selectedFilter have no
  1638. meaning. The \a options parameter is only used to define if the native file
  1639. dialog is used.
  1640. \warning Do not delete \a parent during the execution of the dialog. If you
  1641. want to do this, you should create the dialog yourself using one of the
  1642. QFileDialog constructors.
  1643. \sa getOpenFileName(), getOpenFileNames(), getExistingDirectory()
  1644. */
  1645. QString QFileDialog::getSaveFileName(QWidget *parent,
  1646. const QString &caption,
  1647. const QString &dir,
  1648. const QString &filter,
  1649. QString *selectedFilter,
  1650. Options options)
  1651. {
  1652. if (qt_filedialog_save_filename_hook && !(options & DontUseNativeDialog))
  1653. return qt_filedialog_save_filename_hook(parent, caption, dir, filter, selectedFilter, options);
  1654. #if defined(Q_WS_S60)
  1655. if (QSysInfo::s60Version() > QSysInfo::SV_S60_5_0 && !(options & DontUseNativeDialog))
  1656. return qtSymbianGetSaveFileName(caption, dir);
  1657. #endif
  1658. QFileDialogArgs args;
  1659. args.parent = parent;
  1660. args.caption = caption;
  1661. args.directory = QFileDialogPrivate::workingDirectory(dir);
  1662. args.selection = QFileDialogPrivate::initialSelection(dir);
  1663. args.filter = filter;
  1664. args.mode = AnyFile;
  1665. args.options = options;
  1666. #if defined(Q_WS_WIN)
  1667. if (qt_use_native_dialogs && !(args.options & DontUseNativeDialog)) {
  1668. return qt_win_get_save_file_name(args, &(args.directory), selectedFilter);
  1669. }
  1670. #endif
  1671. // create a qt dialog
  1672. QFileDialog dialog(args);
  1673. dialog.setAcceptMode(AcceptSave);
  1674. if (selectedFilter && !selectedFilter->isEmpty())
  1675. dialog.selectNameFilter(*selectedFilter);
  1676. if (dialog.exec() == QDialog::Accepted) {
  1677. if (selectedFilter)
  1678. *selectedFilter = dialog.selectedFilter();
  1679. return dialog.selectedFiles().value(0);
  1680. }
  1681. return QString();
  1682. }
  1683. /*!
  1684. This is a convenience static function that will return an existing
  1685. directory selected by the user.
  1686. \snippet doc/src/snippets/code/src_gui_dialogs_qfiledialog.cpp 12
  1687. This function creates a modal file dialog with the given \a parent widget.
  1688. If \a parent is not 0, the dialog will be shown centered over the parent
  1689. widget.
  1690. The dialog's working directory is set to \a dir, and the caption is set to
  1691. \a caption. Either of these may be an empty string in which case the
  1692. current directory and a default caption will be used respectively.
  1693. The \a options argument holds various options about how to run the dialog,
  1694. see the QFileDialog::Option enum for more information on the flags you can
  1695. pass. To ensure a native file dialog, \l{QFileDialog::}{ShowDirsOnly} must
  1696. be set.
  1697. On Windows, Mac OS X and Symbian^3, this static function will use the
  1698. native file dialog and not a QFileDialog. On Windows CE, if the device has
  1699. no native file dialog, a QFileDialog will be used.
  1700. On Unix/X11, the normal behavior of the file dialog is to resolve and
  1701. follow symlinks. For example, if \c{/usr/tmp} is a symlink to \c{/var/tmp},
  1702. the file dialog will change to \c{/var/tmp} after entering \c{/usr/tmp}. If
  1703. \a options includes DontResolveSymlinks, the file dialog will treat
  1704. symlinks as regular directories.
  1705. On Windows the dialog will spin a blocking modal event loop that will not
  1706. dispatch any QTimers, and if \a parent is not 0 then it will position the
  1707. dialog just below the parent's title bar.
  1708. On Symbian^3 the \a options parameter is only used to define if the native
  1709. file dialog is used.
  1710. \warning Do not delete \a parent during the execution of the dialog. If you
  1711. want to do this, you should create the dialog yourself using one of the
  1712. QFileDialog constructors.
  1713. \sa getOpenFileName(), getOpenFileNames(), getSaveFileName()
  1714. */
  1715. QString QFileDialog::getExistingDirectory(QWidget *parent,
  1716. const QString &caption,
  1717. const QString &dir,
  1718. Options options)
  1719. {
  1720. if (qt_filedialog_existing_directory_hook && !(options & DontUseNativeDialog))
  1721. return qt_filedialog_existing_directory_hook(parent, caption, dir, options);
  1722. #if defined(Q_WS_S60)
  1723. if (QSysInfo::s60Version() > QSysInfo::SV_S60_5_0 && !(options & DontUseNativeDialog))
  1724. return qtSymbianGetExistingDirectory(caption, dir);
  1725. #endif
  1726. QFileDialogArgs args;
  1727. args.parent = parent;
  1728. args.caption = caption;
  1729. args.directory = QFileDialogPrivate::workingDirectory(dir);
  1730. args.mode = (options & ShowDirsOnly ? DirectoryOnly : Directory);
  1731. args.options = options;
  1732. #if defined(Q_WS_WIN)
  1733. if (qt_use_native_dialogs && !(args.options & DontUseNativeDialog) && (options & ShowDirsOnly)
  1734. #if defined(Q_WS_WINCE)
  1735. && qt_priv_ptr_valid
  1736. #endif
  1737. ) {
  1738. return qt_win_get_existing_directory(args);
  1739. }
  1740. #endif
  1741. // create a qt dialog
  1742. QFileDialog dialog(args);
  1743. if (dialog.exec() == QDialog::Accepted) {
  1744. return dialog.selectedFiles().value(0);
  1745. }
  1746. return QString();
  1747. }
  1748. inline static QString _qt_get_directory(const QString &path)
  1749. {
  1750. QFileInfo info = QFileInfo(QDir::current(), path);
  1751. if (info.exists() && info.isDir())
  1752. return QDir::cleanPath(info.absoluteFilePath());
  1753. info.setFile(info.absolutePath());
  1754. if (info.exists() && info.isDir())
  1755. return info.absoluteFilePath();
  1756. return QString();
  1757. }
  1758. /*
  1759. Get the initial directory path
  1760. \sa initialSelection()
  1761. */
  1762. QString QFileDialogPrivate::workingDirectory(const QString &path)
  1763. {
  1764. if (!path.isEmpty()) {
  1765. QString directory = _qt_get_directory(path);
  1766. if (!directory.isEmpty())
  1767. return directory;
  1768. }
  1769. QString directory = _qt_get_directory(*lastVisitedDir());
  1770. if (!directory.isEmpty())
  1771. return directory;
  1772. return QDir::currentPath();
  1773. }
  1774. /*
  1775. Get the initial selection given a path. The initial directory
  1776. can contain both the initial directory and initial selection
  1777. /home/user/foo.txt
  1778. \sa workingDirectory()
  1779. */
  1780. QString QFileDialogPrivate::initialSelection(const QString &path)
  1781. {
  1782. if (!path.isEmpty()) {
  1783. QFileInfo info(path);
  1784. if (!info.isDir())
  1785. return info.fileName();
  1786. }
  1787. return QString();
  1788. }
  1789. /*!
  1790. \reimp
  1791. */
  1792. void QFileDialog::done(int result)
  1793. {
  1794. Q_D(QFileDialog);
  1795. QDialog::done(result);
  1796. if (d->receiverToDisconnectOnClose) {
  1797. disconnect(this, d->signalToDisconnectOnClose,
  1798. d->receiverToDisconnectOnClose, d->memberToDisconnectOnClose);
  1799. d->receiverToDisconnectOnClose = 0;
  1800. }
  1801. d->memberToDisconnectOnClose.clear();
  1802. d->signalToDisconnectOnClose.clear();
  1803. }
  1804. /*!
  1805. \reimp
  1806. */
  1807. void QFileDialog::accept()
  1808. {
  1809. Q_D(QFileDialog);
  1810. QStringList files = selectedFiles();
  1811. if (files.isEmpty())
  1812. return;
  1813. if (d->nativeDialogInUse){
  1814. d->emitFilesSelected(files);
  1815. QDialog::accept();
  1816. return;
  1817. }
  1818. QString lineEditText = d->lineEdit()->text();
  1819. // "hidden feature" type .. and then enter, and it will move up a dir
  1820. // special case for ".."
  1821. if (lineEditText == QLatin1String("..")) {
  1822. d->_q_navigateToParent();
  1823. bool block = d->qFileDialogUi->fileNameEdit->blockSignals(true);
  1824. d->lineEdit()->selectAll();
  1825. d->qFileDialogUi->fileNameEdit->blockSignals(block);
  1826. return;
  1827. }
  1828. switch (d->fileMode) {
  1829. case DirectoryOnly:
  1830. case Directory: {
  1831. QString fn = files.first();
  1832. QFileInfo info(fn);
  1833. if (!info.exists())
  1834. info = QFileInfo(d->getEnvironmentVariable(fn));
  1835. if (!info.exists()) {
  1836. #ifndef QT_NO_MESSAGEBOX
  1837. QString message = tr("%1\nDirectory not found.\nPlease verify the "
  1838. "correct directory name was given.");
  1839. QMessageBox::warning(this, windowTitle(), message.arg(info.fileName()));
  1840. #endif // QT_NO_MESSAGEBOX
  1841. return;
  1842. }
  1843. if (info.isDir()) {
  1844. d->emitFilesSelected(files);
  1845. QDialog::accept();
  1846. }
  1847. return;
  1848. }
  1849. case AnyFile: {
  1850. QString fn = files.first();
  1851. QFileInfo info(fn);
  1852. if (info.isDir()) {
  1853. setDirectory(info.absoluteFilePath());
  1854. return;
  1855. }
  1856. if (!info.exists()) {
  1857. int maxNameLength = d->maxNameLength(info.path());
  1858. if (maxNameLength >= 0 && info.fileName().length() > maxNameLength)
  1859. return;
  1860. }
  1861. // check if we have to ask for permission to overwrite the file
  1862. if (!info.exists() || !confirmOverwrite() || acceptMode() == AcceptOpen) {
  1863. d->emitFilesSelected(QStringList(fn));
  1864. QDialog::accept();
  1865. #ifndef QT_NO_MESSAGEBOX
  1866. } else {
  1867. if (QMessageBox::warning(this, windowTitle(),
  1868. tr("%1 already exists.\nDo you want to replace it?")
  1869. .arg(info.fileName()),
  1870. QMessageBox::Yes | QMessageBox::No, QMessageBox::No)
  1871. == QMessageBox::Yes) {
  1872. d->emitFilesSelected(QStringList(fn));
  1873. QDialog::accept();
  1874. }
  1875. #endif
  1876. }
  1877. return;
  1878. }
  1879. case ExistingFile:
  1880. case ExistingFiles:
  1881. for (int i = 0; i < files.count(); ++i) {
  1882. QFileInfo info(files.at(i));
  1883. if (!info.exists())
  1884. info = QFileInfo(d->getEnvironmentVariable(files.at(i)));
  1885. if (!info.exists()) {
  1886. #ifndef QT_NO_MESSAGEBOX
  1887. QString message = tr("%1\nFile not found.\nPlease verify the "
  1888. "correct file name was given.");
  1889. QMessageBox::warning(this, windowTitle(), message.arg(info.fileName()));
  1890. #endif // QT_NO_MESSAGEBOX
  1891. return;
  1892. }
  1893. if (info.isDir()) {
  1894. setDirectory(info.absoluteFilePath());
  1895. d->lineEdit()->clear();
  1896. return;
  1897. }
  1898. }
  1899. d->emitFilesSelected(files);
  1900. QDialog::accept();
  1901. return;
  1902. }
  1903. }
  1904. /*!
  1905. \internal
  1906. Create widgets, layout and set default values
  1907. */
  1908. void QFileDialogPrivate::init(const QString &directory, const QString &nameFilter,
  1909. const QString &caption)
  1910. {
  1911. Q_Q(QFileDialog);
  1912. if (!caption.isEmpty()) {
  1913. useDefaultCaption = false;
  1914. setWindowTitle = caption;
  1915. q->setWindowTitle(caption);
  1916. }
  1917. createWidgets();
  1918. createMenuActions();
  1919. retranslateStrings();
  1920. q->setFileMode(fileMode);
  1921. #ifndef QT_NO_SETTINGS
  1922. QSettings settings(QSettings::UserScope, QLatin1String("Trolltech"));
  1923. settings.beginGroup(QLatin1String("Qt"));
  1924. if (!directory.isEmpty())
  1925. setLastVisitedDirectory(workingDirectory(directory));
  1926. q->restoreState(settings.value(QLatin1String("filedialog")).toByteArray());
  1927. #endif
  1928. #if defined(Q_EMBEDDED_SMALLSCREEN)
  1929. qFileDialogUi->lookInLabel->setVisible(false);
  1930. qFileDialogUi->fileNameLabel->setVisible(false);
  1931. qFileDialogUi->fileTypeLabel->setVisible(false);
  1932. qFileDialogUi->sidebar->hide();
  1933. #endif
  1934. // Default case
  1935. if (!nameFilter.isEmpty())
  1936. q->setNameFilter(nameFilter);
  1937. q->setAcceptMode(QFileDialog::AcceptOpen);
  1938. q->setDirectory(workingDirectory(directory));
  1939. q->selectFile(initialSelection(directory));
  1940. _q_updateOkButton();
  1941. q->resize(q->sizeHint());
  1942. }
  1943. /*!
  1944. \internal
  1945. Create the widgets, set properties and connections
  1946. */
  1947. void QFileDialogPrivate::createWidgets()
  1948. {
  1949. Q_Q(QFileDialog);
  1950. model = new QFileSystemModel(q);
  1951. model->setObjectName(QLatin1String("qt_filesystem_model"));
  1952. #ifdef Q_WS_MAC
  1953. model->setNameFilterDisables(true);
  1954. #else
  1955. model->setNameFilterDisables(false);
  1956. #endif
  1957. model->d_func()->disableRecursiveSort = true;
  1958. QFileDialog::connect(model, SIGNAL(fileRenamed(QString,QString,QString)), q, SLOT(_q_fileRenamed(QString,QString,QString)));
  1959. QFileDialog::connect(model, SIGNAL(rootPathChanged(QString)),
  1960. q, SLOT(_q_pathChanged(QString)));
  1961. QFileDialog::connect(model, SIGNAL(rowsInserted(QModelIndex,int,int)),
  1962. q, SLOT(_q_rowsInserted(QModelIndex)));
  1963. model->setReadOnly(false);
  1964. qFileDialogUi.reset(new Ui_QFileDialog());
  1965. qFileDialogUi->setupUi(q);
  1966. QList<QUrl> initialBookmarks;
  1967. initialBookmarks << QUrl::fromLocalFile(QLatin1String(""))
  1968. << QUrl::fromLocalFile(QDir::homePath());
  1969. qFileDialogUi->sidebar->init(model, initialBookmarks);
  1970. QFileDialog::connect(qFileDialogUi->sidebar, SIGNAL(goToUrl(QUrl)),
  1971. q, SLOT(_q_goToUrl(QUrl)));
  1972. QObject::connect(qFileDialogUi->buttonBox, SIGNAL(accepted()), q, SLOT(accept()));
  1973. QObject::connect(qFileDialogUi->buttonBox, SIGNAL(rejected()), q, SLOT(reject()));
  1974. qFileDialogUi->lookInCombo->init(this);
  1975. QObject::connect(qFileDialogUi->lookInCombo, SIGNAL(activated(QString)), q, SLOT(_q_goToDirectory(QString)));
  1976. qFileDialogUi->lookInCombo->setInsertPolicy(QComboBox::NoInsert);
  1977. qFileDialogUi->lookInCombo->setDuplicatesEnabled(false);
  1978. // filename
  1979. qFileDialogUi->fileNameEdit->init(this);
  1980. #ifndef QT_NO_SHORTCUT
  1981. qFileDialogUi->fileNameLabel->setBuddy(qFileDialogUi->fileNameEdit);
  1982. #endif
  1983. #ifndef QT_NO_FSCOMPLETER
  1984. completer = new QFSCompleter(model, q);
  1985. qFileDialogUi->fileNameEdit->setCompleter(completer);
  1986. #endif // QT_NO_FSCOMPLETER
  1987. QObject::connect(qFileDialogUi->fileNameEdit, SIGNAL(textChanged(QString)),
  1988. q, SLOT(_q_autoCompleteFileName(QString)));
  1989. QObject::connect(qFileDialogUi->fileNameEdit, SIGNAL(textChanged(QString)),
  1990. q, SLOT(_q_updateOkButton()));
  1991. QObject::connect(qFileDialogUi->fileNameEdit, SIGNAL(returnPressed()), q, SLOT(accept()));
  1992. // filetype
  1993. qFileDialogUi->fileTypeCombo->setDuplicatesEnabled(false);
  1994. qFileDialogUi->fileTypeCombo->setSizeAdjustPolicy(QComboBox::AdjustToMinimumContentsLength);
  1995. qFileDialogUi->fileTypeCombo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
  1996. QObject::connect(qFileDialogUi->fileTypeCombo, SIGNAL(activated(int)),
  1997. q, SLOT(_q_useNameFilter(int)));
  1998. QObject::connect(qFileDialogUi->fileTypeCombo, SIGNAL(activated(QString)),
  1999. q, SIGNAL(filterSelected(QString)));
  2000. qFileDialogUi->listView->init(this);
  2001. qFileDialogUi->listView->setModel(model);
  2002. QObject::connect(qFileDialogUi->listView, SIGNAL(activated(QModelIndex)),
  2003. q, SLOT(_q_enterDirectory(QModelIndex)));
  2004. QObject::connect(qFileDialogUi->listView, SIGNAL(customContextMenuRequested(QPoint)),
  2005. q, SLOT(_q_showContextMenu(QPoint)));
  2006. #ifndef QT_NO_SHORTCUT
  2007. QShortcut *shortcut = new QShortcut(qFileDialogUi->listView);
  2008. shortcut->setKey(QKeySequence(QLatin1String("Delete")));
  2009. QObject::connect(shortcut, SIGNAL(activated()), q, SLOT(_q_deleteCurrent()));
  2010. #endif
  2011. qFileDialogUi->treeView->init(this);
  2012. qFileDialogUi->treeView->setModel(model);
  2013. QHeaderView *treeHeader = qFileDialogUi->treeView->header();
  2014. QFontMetrics fm(q->font());
  2015. treeHeader->resizeSection(0, fm.width(QLatin1String("wwwwwwwwwwwwwwwwwwwwwwwwww")));
  2016. treeHeader->resizeSection(1, fm.width(QLatin1String("128.88 GB")));
  2017. treeHeader->resizeSection(2, fm.width(QLatin1String("mp3Folder")));
  2018. treeHeader->resizeSection(3, fm.width(QLatin1String("10/29/81 02:02PM")));
  2019. treeHeader->setContextMenuPolicy(Qt::ActionsContextMenu);
  2020. QActionGroup *showActionGroup = new QActionGroup(q);
  2021. showActionGroup->setExclusive(false);
  2022. QObject::connect(showActionGroup, SIGNAL(triggered(QAction*)),
  2023. q, SLOT(_q_showHeader(QAction*)));;
  2024. QAbstractItemModel *abstractModel = model;
  2025. #ifndef QT_NO_PROXYMODEL
  2026. if (proxyModel)
  2027. abstractModel = proxyModel;
  2028. #endif
  2029. for (int i = 1; i < abstractModel->columnCount(QModelIndex()); ++i) {
  2030. QAction *showHeader = new QAction(showActionGroup);
  2031. showHeader->setCheckable(true);
  2032. showHeader->setChecked(true);
  2033. treeHeader->addAction(showHeader);
  2034. }
  2035. QScopedPointer<QItemSelectionModel> selModel(qFileDialogUi->treeView->selectionModel());
  2036. qFileDialogUi->treeView->setSelectionModel(qFileDialogUi->listView->selectionModel());
  2037. QObject::connect(qFileDialogUi->treeView, SIGNAL(activated(QModelIndex)),
  2038. q, SLOT(_q_enterDirectory(QModelIndex)));
  2039. QObject::connect(qFileDialogUi->treeView, SIGNAL(customContextMenuRequested(QPoint)),
  2040. q, SLOT(_q_showContextMenu(QPoint)));
  2041. #ifndef QT_NO_SHORTCUT
  2042. shortcut = new QShortcut(qFileDialogUi->treeView);
  2043. shortcut->setKey(QKeySequence(QLatin1String("Delete")));
  2044. QObject::connect(shortcut, SIGNAL(activated()), q, SLOT(_q_deleteCurrent()));
  2045. #endif
  2046. // Selections
  2047. QItemSelectionModel *selections = qFileDialogUi->listView->selectionModel();
  2048. QObject::connect(selections, SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
  2049. q, SLOT(_q_selectionChanged()));
  2050. QObject::connect(selections, SIGNAL(currentChanged(QModelIndex,QModelIndex)),
  2051. q, SLOT(_q_currentChanged(QModelIndex)));
  2052. qFileDialogUi->splitter->setStretchFactor(qFileDialogUi->splitter->indexOf(qFileDialogUi->splitter->widget(1)), QSizePolicy::Expanding);
  2053. createToolButtons();
  2054. }
  2055. void QFileDialogPrivate::_q_showHeader(QAction *action)
  2056. {
  2057. Q_Q(QFileDialog);
  2058. QActionGroup *actionGroup = qobject_cast<QActionGroup*>(q->sender());
  2059. qFileDialogUi->treeView->header()->setSectionHidden(actionGroup->actions().indexOf(action) + 1, !action->isChecked());
  2060. }
  2061. #ifndef QT_NO_PROXYMODEL
  2062. /*!
  2063. \since 4.3
  2064. Sets the model for the views to the given \a proxyModel. This is useful if you
  2065. want to modify the underlying model; for example, to add columns, filter
  2066. data or add drives.
  2067. Any existing proxy model will be removed, but not deleted. The file dialog
  2068. will take ownership of the \a proxyModel.
  2069. \sa proxyModel()
  2070. */
  2071. void QFileDialog::setProxyModel(QAbstractProxyModel *proxyModel)
  2072. {
  2073. Q_D(QFileDialog);
  2074. if ((!proxyModel && !d->proxyModel)
  2075. || (proxyModel == d->proxyModel))
  2076. return;
  2077. QModelIndex idx = d->rootIndex();
  2078. if (d->proxyModel) {
  2079. disconnect(d->proxyModel, SIGNAL(rowsInserted(QModelIndex,int,int)),
  2080. this, SLOT(_q_rowsInserted(QModelIndex)));
  2081. } else {
  2082. disconnect(d->model, SIGNAL(rowsInserted(QModelIndex,int,int)),
  2083. this, SLOT(_q_rowsInserted(QModelIndex)));
  2084. }
  2085. if (proxyModel != 0) {
  2086. proxyModel->setParent(this);
  2087. d->proxyModel = proxyModel;
  2088. proxyModel->setSourceModel(d->model);
  2089. d->qFileDialogUi->listView->setModel(d->proxyModel);
  2090. d->qFileDialogUi->treeView->setModel(d->proxyModel);
  2091. #ifndef QT_NO_FSCOMPLETER
  2092. d->completer->setModel(d->proxyModel);
  2093. d->completer->proxyModel = d->proxyModel;
  2094. #endif
  2095. connect(d->proxyModel, SIGNAL(rowsInserted(QModelIndex,int,int)),
  2096. this, SLOT(_q_rowsInserted(QModelIndex)));
  2097. } else {
  2098. d->proxyModel = 0;
  2099. d->qFileDialogUi->listView->setModel(d->model);
  2100. d->qFileDialogUi->treeView->setModel(d->model);
  2101. #ifndef QT_NO_FSCOMPLETER
  2102. d->completer->setModel(d->model);
  2103. d->completer->sourceModel = d->model;
  2104. d->completer->proxyModel = 0;
  2105. #endif
  2106. connect(d->model, SIGNAL(rowsInserted(QModelIndex,int,int)),
  2107. this, SLOT(_q_rowsInserted(QModelIndex)));
  2108. }
  2109. QScopedPointer<QItemSelectionModel> selModel(d->qFileDialogUi->treeView->selectionModel());
  2110. d->qFileDialogUi->treeView->setSelectionModel(d->qFileDialogUi->listView->selectionModel());
  2111. d->setRootIndex(idx);
  2112. // reconnect selection
  2113. QItemSelectionModel *selections = d->qFileDialogUi->listView->selectionModel();
  2114. QObject::connect(selections, SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
  2115. this, SLOT(_q_selectionChanged()));
  2116. QObject::connect(selections, SIGNAL(currentChanged(QModelIndex,QModelIndex)),
  2117. this, SLOT(_q_currentChanged(QModelIndex)));
  2118. }
  2119. /*!
  2120. Returns the proxy model used by the file dialog. By default no proxy is set.
  2121. \sa setProxyModel()
  2122. */
  2123. QAbstractProxyModel *QFileDialog::proxyModel() const
  2124. {
  2125. Q_D(const QFileDialog);
  2126. return d->proxyModel;
  2127. }
  2128. #endif // QT_NO_PROXYMODEL
  2129. /*!
  2130. \internal
  2131. Create tool buttons, set properties and connections
  2132. */
  2133. void QFileDialogPrivate::createToolButtons()
  2134. {
  2135. Q_Q(QFileDialog);
  2136. qFileDialogUi->backButton->setIcon(q->style()->standardIcon(QStyle::SP_ArrowBack, 0, q));
  2137. qFileDialogUi->backButton->setAutoRaise(true);
  2138. qFileDialogUi->backButton->setEnabled(false);
  2139. QObject::connect(qFileDialogUi->backButton, SIGNAL(clicked()), q, SLOT(_q_navigateBackward()));
  2140. qFileDialogUi->forwardButton->setIcon(q->style()->standardIcon(QStyle::SP_ArrowForward, 0, q));
  2141. qFileDialogUi->forwardButton->setAutoRaise(true);
  2142. qFileDialogUi->forwardButton->setEnabled(false);
  2143. QObject::connect(qFileDialogUi->forwardButton, SIGNAL(clicked()), q, SLOT(_q_navigateForward()));
  2144. qFileDialogUi->toParentButton->setIcon(q->style()->standardIcon(QStyle::SP_FileDialogToParent, 0, q));
  2145. qFileDialogUi->toParentButton->setAutoRaise(true);
  2146. qFileDialogUi->toParentButton->setEnabled(false);
  2147. QObject::connect(qFileDialogUi->toParentButton, SIGNAL(clicked()), q, SLOT(_q_navigateToParent()));
  2148. qFileDialogUi->listModeButton->setIcon(q->style()->standardIcon(QStyle::SP_FileDialogListView, 0, q));
  2149. qFileDialogUi->listModeButton->setAutoRaise(true);
  2150. qFileDialogUi->listModeButton->setDown(true);
  2151. QObject::connect(qFileDialogUi->listModeButton, SIGNAL(clicked()), q, SLOT(_q_showListView()));
  2152. qFileDialogUi->detailModeButton->setIcon(q->style()->standardIcon(QStyle::SP_FileDialogDetailedView, 0, q));
  2153. qFileDialogUi->detailModeButton->setAutoRaise(true);
  2154. QObject::connect(qFileDialogUi->detailModeButton, SIGNAL(clicked()), q, SLOT(_q_showDetailsView()));
  2155. QSize toolSize(qFileDialogUi->fileNameEdit->sizeHint().height(), qFileDialogUi->fileNameEdit->sizeHint().height());
  2156. qFileDialogUi->backButton->setFixedSize(toolSize);
  2157. qFileDialogUi->listModeButton->setFixedSize(toolSize);
  2158. qFileDialogUi->detailModeButton->setFixedSize(toolSize);
  2159. qFileDialogUi->forwardButton->setFixedSize(toolSize);
  2160. qFileDialogUi->toParentButton->setFixedSize(toolSize);
  2161. qFileDialogUi->newFolderButton->setIcon(q->style()->standardIcon(QStyle::SP_FileDialogNewFolder, 0, q));
  2162. qFileDialogUi->newFolderButton->setFixedSize(toolSize);
  2163. qFileDialogUi->newFolderButton->setAutoRaise(true);
  2164. qFileDialogUi->newFolderButton->setEnabled(false);
  2165. QObject::connect(qFileDialogUi->newFolderButton, SIGNAL(clicked()), q, SLOT(_q_createDirectory()));
  2166. }
  2167. /*!
  2168. \internal
  2169. Create actions which will be used in the right click.
  2170. */
  2171. void QFileDialogPrivate::createMenuActions()
  2172. {
  2173. Q_Q(QFileDialog);
  2174. QAction *goHomeAction = new QAction(q);
  2175. #ifndef QT_NO_SHORTCUT
  2176. goHomeAction->setShortcut(Qt::CTRL + Qt::Key_H + Qt::SHIFT);
  2177. #endif
  2178. QObject::connect(goHomeAction, SIGNAL(triggered()), q, SLOT(_q_goHome()));
  2179. q->addAction(goHomeAction);
  2180. // ### TODO add Desktop & Computer actions
  2181. QAction *goToParent = new QAction(q);
  2182. goToParent->setObjectName(QLatin1String("qt_goto_parent_action"));
  2183. #ifndef QT_NO_SHORTCUT
  2184. goToParent->setShortcut(Qt::CTRL + Qt::UpArrow);
  2185. #endif
  2186. QObject::connect(goToParent, SIGNAL(triggered()), q, SLOT(_q_navigateToParent()));
  2187. q->addAction(goToParent);
  2188. renameAction = new QAction(q);
  2189. renameAction->setEnabled(false);
  2190. renameAction->setObjectName(QLatin1String("qt_rename_action"));
  2191. QObject::connect(renameAction, SIGNAL(triggered()), q, SLOT(_q_renameCurrent()));
  2192. deleteAction = new QAction(q);
  2193. deleteAction->setEnabled(false);
  2194. deleteAction->setObjectName(QLatin1String("qt_delete_action"));
  2195. QObject::connect(deleteAction, SIGNAL(triggered()), q, SLOT(_q_deleteCurrent()));
  2196. showHiddenAction = new QAction(q);
  2197. showHiddenAction->setObjectName(QLatin1String("qt_show_hidden_action"));
  2198. showHiddenAction->setCheckable(true);
  2199. QObject::connect(showHiddenAction, SIGNAL(triggered()), q, SLOT(_q_showHidden()));
  2200. newFolderAction = new QAction(q);
  2201. newFolderAction->setObjectName(QLatin1String("qt_new_folder_action"));
  2202. QObject::connect(newFolderAction, SIGNAL(triggered()), q, SLOT(_q_createDirectory()));
  2203. }
  2204. void QFileDialogPrivate::_q_goHome()
  2205. {
  2206. Q_Q(QFileDialog);
  2207. q->setDirectory(QDir::homePath());
  2208. }
  2209. /*!
  2210. \internal
  2211. Update history with new path, buttons, and combo
  2212. */
  2213. void QFileDialogPrivate::_q_pathChanged(const QString &newPath)
  2214. {
  2215. Q_Q(QFileDialog);
  2216. QDir dir(model->rootDirectory());
  2217. qFileDialogUi->toParentButton->setEnabled(dir.exists());
  2218. qFileDialogUi->sidebar->selectUrl(QUrl::fromLocalFile(newPath));
  2219. q->setHistory(qFileDialogUi->lookInCombo->history());
  2220. if (currentHistoryLocation < 0 || currentHistory.value(currentHistoryLocation) != QDir::toNativeSeparators(newPath)) {
  2221. while (currentHistoryLocation >= 0 && currentHistoryLocation + 1 < currentHistory.count()) {
  2222. currentHistory.removeLast();
  2223. }
  2224. currentHistory.append(QDir::toNativeSeparators(newPath));
  2225. ++currentHistoryLocation;
  2226. }
  2227. qFileDialogUi->forwardButton->setEnabled(currentHistory.size() - currentHistoryLocation > 1);
  2228. qFileDialogUi->backButton->setEnabled(currentHistoryLocation > 0);
  2229. }
  2230. /*!
  2231. \internal
  2232. Navigates to the last directory viewed in the dialog.
  2233. */
  2234. void QFileDialogPrivate::_q_navigateBackward()
  2235. {
  2236. Q_Q(QFileDialog);
  2237. if (!currentHistory.isEmpty() && currentHistoryLocation > 0) {
  2238. --currentHistoryLocation;
  2239. QString previousHistory = currentHistory.at(currentHistoryLocation);
  2240. q->setDirectory(previousHistory);
  2241. }
  2242. }
  2243. /*!
  2244. \internal
  2245. Navigates to the last directory viewed in the dialog.
  2246. */
  2247. void QFileDialogPrivate::_q_navigateForward()
  2248. {
  2249. Q_Q(QFileDialog);
  2250. if (!currentHistory.isEmpty() && currentHistoryLocation < currentHistory.size() - 1) {
  2251. ++currentHistoryLocation;
  2252. QString nextHistory = currentHistory.at(currentHistoryLocation);
  2253. q->setDirectory(nextHistory);
  2254. }
  2255. }
  2256. /*!
  2257. \internal
  2258. Navigates to the parent directory of the currently displayed directory
  2259. in the dialog.
  2260. */
  2261. void QFileDialogPrivate::_q_navigateToParent()
  2262. {
  2263. Q_Q(QFileDialog);
  2264. QDir dir(model->rootDirectory());
  2265. QString newDirectory;
  2266. if (dir.isRoot()) {
  2267. newDirectory = model->myComputer().toString();
  2268. } else {
  2269. dir.cdUp();
  2270. newDirectory = dir.absolutePath();
  2271. }
  2272. q->setDirectory(newDirectory);
  2273. emit q->directoryEntered(newDirectory);
  2274. }
  2275. /*!
  2276. \internal
  2277. Creates a new directory, first asking the user for a suitable name.
  2278. */
  2279. void QFileDialogPrivate::_q_createDirectory()
  2280. {
  2281. Q_Q(QFileDialog);
  2282. qFileDialogUi->listView->clearSelection();
  2283. QString newFolderString = QFileDialog::tr("New Folder");
  2284. QString folderName = newFolderString;
  2285. QString prefix = q->directory().absolutePath() + QDir::separator();
  2286. if (QFile::exists(prefix + folderName)) {
  2287. qlonglong suffix = 2;
  2288. while (QFile::exists(prefix + folderName)) {
  2289. folderName = newFolderString + QString::number(suffix++);
  2290. }
  2291. }
  2292. QModelIndex parent = rootIndex();
  2293. QModelIndex index = model->mkdir(parent, folderName);
  2294. if (!index.isValid())
  2295. return;
  2296. index = select(index);
  2297. if (index.isValid()) {
  2298. qFileDialogUi->treeView->setCurrentIndex(index);
  2299. currentView()->edit(index);
  2300. }
  2301. }
  2302. void QFileDialogPrivate::_q_showListView()
  2303. {
  2304. qFileDialogUi->listModeButton->setDown(true);
  2305. qFileDialogUi->detailModeButton->setDown(false);
  2306. qFileDialogUi->treeView->hide();
  2307. qFileDialogUi->listView->show();
  2308. qFileDialogUi->stackedWidget->setCurrentWidget(qFileDialogUi->listView->parentWidget());
  2309. qFileDialogUi->listView->doItemsLayout();
  2310. }
  2311. void QFileDialogPrivate::_q_showDetailsView()
  2312. {
  2313. qFileDialogUi->listModeButton->setDown(false);
  2314. qFileDialogUi->detailModeButton->setDown(true);
  2315. qFileDialogUi->listView->hide();
  2316. qFileDialogUi->treeView->show();
  2317. qFileDialogUi->stackedWidget->setCurrentWidget(qFileDialogUi->treeView->parentWidget());
  2318. qFileDialogUi->treeView->doItemsLayout();
  2319. }
  2320. /*!
  2321. \internal
  2322. Show the context menu for the file/dir under position
  2323. */
  2324. void QFileDialogPrivate::_q_showContextMenu(const QPoint &position)
  2325. {
  2326. #ifdef QT_NO_MENU
  2327. Q_UNUSED(position);
  2328. #else
  2329. Q_Q(QFileDialog);
  2330. QAbstractItemView *view = 0;
  2331. if (q->viewMode() == QFileDialog::Detail)
  2332. view = qFileDialogUi->treeView;
  2333. else
  2334. view = qFileDialogUi->listView;
  2335. QModelIndex index = view->indexAt(position);
  2336. index = mapToSource(index.sibling(index.row(), 0));
  2337. QMenu menu(view);
  2338. if (index.isValid()) {
  2339. // file context menu
  2340. QFile::Permissions p(index.parent().data(QFileSystemModel::FilePermissions).toInt());
  2341. renameAction->setEnabled(p & QFile::WriteUser);
  2342. menu.addAction(renameAction);
  2343. deleteAction->setEnabled(p & QFile::WriteUser);
  2344. menu.addAction(deleteAction);
  2345. menu.addSeparator();
  2346. }
  2347. menu.addAction(showHiddenAction);
  2348. if (qFileDialogUi->newFolderButton->isVisible()) {
  2349. newFolderAction->setEnabled(qFileDialogUi->newFolderButton->isEnabled());
  2350. menu.addAction(newFolderAction);
  2351. }
  2352. menu.exec(view->viewport()->mapToGlobal(position));
  2353. #endif // QT_NO_MENU
  2354. }
  2355. /*!
  2356. \internal
  2357. */
  2358. void QFileDialogPrivate::_q_renameCurrent()
  2359. {
  2360. Q_Q(QFileDialog);
  2361. QModelIndex index = qFileDialogUi->listView->currentIndex();
  2362. index = index.sibling(index.row(), 0);
  2363. if (q->viewMode() == QFileDialog::List)
  2364. qFileDialogUi->listView->edit(index);
  2365. else
  2366. qFileDialogUi->treeView->edit(index);
  2367. }
  2368. bool QFileDialogPrivate::removeDirectory(const QString &path)
  2369. {
  2370. QModelIndex modelIndex = model->index(path);
  2371. return model->remove(modelIndex);
  2372. }
  2373. /*!
  2374. \internal
  2375. Deletes the currently selected item in the dialog.
  2376. */
  2377. void QFileDialogPrivate::_q_deleteCurrent()
  2378. {
  2379. if (model->isReadOnly())
  2380. return;
  2381. QModelIndexList list = qFileDialogUi->listView->selectionModel()->selectedRows();
  2382. for (int i = list.count() - 1; i >= 0; --i) {
  2383. QModelIndex index = list.at(i);
  2384. if (index == qFileDialogUi->listView->rootIndex())
  2385. continue;
  2386. index = mapToSource(index.sibling(index.row(), 0));
  2387. if (!index.isValid())
  2388. continue;
  2389. QString fileName = index.data(QFileSystemModel::FileNameRole).toString();
  2390. QString filePath = index.data(QFileSystemModel::FilePathRole).toString();
  2391. bool isDir = model->isDir(index);
  2392. QFile::Permissions p(index.parent().data(QFileSystemModel::FilePermissions).toInt());
  2393. #ifndef QT_NO_MESSAGEBOX
  2394. Q_Q(QFileDialog);
  2395. if (!(p & QFile::WriteUser) && (QMessageBox::warning(q_func(), q_func()->windowTitle(),
  2396. QFileDialog::tr("'%1' is write protected.\nDo you want to delete it anyway?")
  2397. .arg(fileName),
  2398. QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::No))
  2399. return;
  2400. else if (QMessageBox::warning(q_func(), q_func()->windowTitle(),
  2401. QFileDialog::tr("Are sure you want to delete '%1'?")
  2402. .arg(fileName),
  2403. QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::No)
  2404. return;
  2405. #else
  2406. if (!(p & QFile::WriteUser))
  2407. return;
  2408. #endif // QT_NO_MESSAGEBOX
  2409. // the event loop has run, we can NOT reuse index because the model might have removed it.
  2410. if (isDir) {
  2411. if (!removeDirectory(filePath)) {
  2412. #ifndef QT_NO_MESSAGEBOX
  2413. QMessageBox::warning(q, q->windowTitle(),
  2414. QFileDialog::tr("Could not delete directory."));
  2415. #endif
  2416. }
  2417. } else {
  2418. model->remove(index);
  2419. }
  2420. }
  2421. }
  2422. void QFileDialogPrivate::_q_autoCompleteFileName(const QString &text)
  2423. {
  2424. if (text.startsWith(QLatin1String("//")) || text.startsWith(QLatin1Char('\\'))) {
  2425. qFileDialogUi->listView->selectionModel()->clearSelection();
  2426. return;
  2427. }
  2428. QStringList multipleFiles = typedFiles();
  2429. if (multipleFiles.count() > 0) {
  2430. QModelIndexList oldFiles = qFileDialogUi->listView->selectionModel()->selectedRows();
  2431. QModelIndexList newFiles;
  2432. for (int i = 0; i < multipleFiles.count(); ++i) {
  2433. QModelIndex idx = model->index(multipleFiles.at(i));
  2434. if (oldFiles.contains(idx))
  2435. oldFiles.removeAll(idx);
  2436. else
  2437. newFiles.append(idx);
  2438. }
  2439. for (int i = 0; i < newFiles.count(); ++i)
  2440. select(newFiles.at(i));
  2441. if (lineEdit()->hasFocus())
  2442. for (int i = 0; i < oldFiles.count(); ++i)
  2443. qFileDialogUi->listView->selectionModel()->select(oldFiles.at(i),
  2444. QItemSelectionModel::Toggle | QItemSelectionModel::Rows);
  2445. }
  2446. }
  2447. /*!
  2448. \internal
  2449. */
  2450. void QFileDialogPrivate::_q_updateOkButton()
  2451. {
  2452. Q_Q(QFileDialog);
  2453. QPushButton *button = qFileDialogUi->buttonBox->button((acceptMode == QFileDialog::AcceptOpen)
  2454. ? QDialogButtonBox::Open : QDialogButtonBox::Save);
  2455. if (!button)
  2456. return;
  2457. bool enableButton = true;
  2458. bool isOpenDirectory = false;
  2459. QStringList files = q->selectedFiles();
  2460. QString lineEditText = lineEdit()->text();
  2461. if (lineEditText.startsWith(QLatin1String("//")) || lineEditText.startsWith(QLatin1Char('\\'))) {
  2462. button->setEnabled(true);
  2463. if (acceptMode == QFileDialog::AcceptSave)
  2464. button->setText(acceptLabel);
  2465. return;
  2466. }
  2467. if (files.isEmpty()) {
  2468. enableButton = false;
  2469. } else if (lineEditText == QLatin1String("..")) {
  2470. isOpenDirectory = true;
  2471. } else {
  2472. switch (fileMode) {
  2473. case QFileDialog::DirectoryOnly:
  2474. case QFileDialog::Directory: {
  2475. QString fn = files.first();
  2476. QModelIndex idx = model->index(fn);
  2477. if (!idx.isValid())
  2478. idx = model->index(getEnvironmentVariable(fn));
  2479. if (!idx.isValid() || !model->isDir(idx))
  2480. enableButton = false;
  2481. break;
  2482. }
  2483. case QFileDialog::AnyFile: {
  2484. QString fn = files.first();
  2485. QFileInfo info(fn);
  2486. QModelIndex idx = model->index(fn);
  2487. QString fileDir;
  2488. QString fileName;
  2489. if (info.isDir()) {
  2490. fileDir = info.canonicalFilePath();
  2491. } else {
  2492. fileDir = fn.mid(0, fn.lastIndexOf(QLatin1Char('/')));
  2493. fileName = fn.mid(fileDir.length() + 1);
  2494. }
  2495. if (lineEditText.contains(QLatin1String(".."))) {
  2496. fileDir = info.canonicalFilePath();
  2497. fileName = info.fileName();
  2498. }
  2499. if (fileDir == q->directory().canonicalPath() && fileName.isEmpty()) {
  2500. enableButton = false;
  2501. break;
  2502. }
  2503. if (idx.isValid() && model->isDir(idx)) {
  2504. isOpenDirectory = true;
  2505. enableButton = true;
  2506. break;
  2507. }
  2508. if (!idx.isValid()) {
  2509. int maxLength = maxNameLength(fileDir);
  2510. enableButton = maxLength < 0 || fileName.length() <= maxLength;
  2511. }
  2512. break;
  2513. }
  2514. case QFileDialog::ExistingFile:
  2515. case QFileDialog::ExistingFiles:
  2516. for (int i = 0; i < files.count(); ++i) {
  2517. QModelIndex idx = model->index(files.at(i));
  2518. if (!idx.isValid())
  2519. idx = model->index(getEnvironmentVariable(files.at(i)));
  2520. if (!idx.isValid()) {
  2521. enableButton = false;
  2522. break;
  2523. }
  2524. if (idx.isValid() && model->isDir(idx)) {
  2525. isOpenDirectory = true;
  2526. break;
  2527. }
  2528. }
  2529. break;
  2530. default:
  2531. break;
  2532. }
  2533. }
  2534. button->setEnabled(enableButton);
  2535. if (acceptMode == QFileDialog::AcceptSave)
  2536. button->setText(isOpenDirectory ? QFileDialog::tr("&Open") : acceptLabel);
  2537. }
  2538. /*!
  2539. \internal
  2540. */
  2541. void QFileDialogPrivate::_q_currentChanged(const QModelIndex &index)
  2542. {
  2543. _q_updateOkButton();
  2544. emit q_func()->currentChanged(index.data(QFileSystemModel::FilePathRole).toString());
  2545. }
  2546. /*!
  2547. \internal
  2548. This is called when the user double clicks on a file with the corresponding
  2549. model item \a index.
  2550. */
  2551. void QFileDialogPrivate::_q_enterDirectory(const QModelIndex &index)
  2552. {
  2553. Q_Q(QFileDialog);
  2554. // My Computer or a directory
  2555. QModelIndex sourceIndex = index.model() == proxyModel ? mapToSource(index) : index;
  2556. QString path = sourceIndex.data(QFileSystemModel::FilePathRole).toString();
  2557. if (path.isEmpty() || model->isDir(sourceIndex)) {
  2558. q->setDirectory(path);
  2559. emit q->directoryEntered(path);
  2560. if (fileMode == QFileDialog::Directory
  2561. || fileMode == QFileDialog::DirectoryOnly) {
  2562. // ### find out why you have to do both of these.
  2563. lineEdit()->setText(QString());
  2564. lineEdit()->clear();
  2565. }
  2566. } else {
  2567. q->accept();
  2568. }
  2569. }
  2570. /*!
  2571. \internal
  2572. Changes the file dialog's current directory to the one specified
  2573. by \a path.
  2574. */
  2575. void QFileDialogPrivate::_q_goToDirectory(const QString &path)
  2576. {
  2577. #ifndef QT_NO_MESSAGEBOX
  2578. Q_Q(QFileDialog);
  2579. #endif
  2580. QModelIndex index = qFileDialogUi->lookInCombo->model()->index(qFileDialogUi->lookInCombo->currentIndex(),
  2581. qFileDialogUi->lookInCombo->modelColumn(),
  2582. qFileDialogUi->lookInCombo->rootModelIndex());
  2583. QString path2 = path;
  2584. if (!index.isValid())
  2585. index = mapFromSource(model->index(getEnvironmentVariable(path)));
  2586. else {
  2587. path2 = index.data(UrlRole).toUrl().toLocalFile();
  2588. index = mapFromSource(model->index(path2));
  2589. }
  2590. QDir dir(path2);
  2591. if (!dir.exists())
  2592. dir = getEnvironmentVariable(path2);
  2593. if (dir.exists() || path2.isEmpty() || path2 == model->myComputer().toString()) {
  2594. _q_enterDirectory(index);
  2595. #ifndef QT_NO_MESSAGEBOX
  2596. } else {
  2597. QString message = QFileDialog::tr("%1\nDirectory not found.\nPlease verify the "
  2598. "correct directory name was given.");
  2599. QMessageBox::warning(q, q->windowTitle(), message.arg(path2));
  2600. #endif // QT_NO_MESSAGEBOX
  2601. }
  2602. }
  2603. // Makes a list of filters from a normal filter string "Image Files (*.png *.jpg)"
  2604. QStringList qt_clean_filter_list(const QString &filter)
  2605. {
  2606. QRegExp regexp(QString::fromLatin1(qt_file_dialog_filter_reg_exp));
  2607. QString f = filter;
  2608. int i = regexp.indexIn(f);
  2609. if (i >= 0)
  2610. f = regexp.cap(2);
  2611. return f.split(QLatin1Char(' '), QString::SkipEmptyParts);
  2612. }
  2613. /*!
  2614. \internal
  2615. Sets the current name filter to be nameFilter and
  2616. update the qFileDialogUi->fileNameEdit when in AcceptSave mode with the new extension.
  2617. */
  2618. void QFileDialogPrivate::_q_useNameFilter(int index)
  2619. {
  2620. if (index == nameFilters.size()) {
  2621. QAbstractItemModel *comboModel = qFileDialogUi->fileTypeCombo->model();
  2622. nameFilters.append(comboModel->index(comboModel->rowCount() - 1, 0).data().toString());
  2623. }
  2624. QString nameFilter = nameFilters.at(index);
  2625. QStringList newNameFilters = qt_clean_filter_list(nameFilter);
  2626. if (acceptMode == QFileDialog::AcceptSave) {
  2627. QString newNameFilterExtension;
  2628. if (newNameFilters.count() > 0)
  2629. newNameFilterExtension = QFileInfo(newNameFilters.at(0)).suffix();
  2630. QString fileName = lineEdit()->text();
  2631. const QString fileNameExtension = QFileInfo(fileName).suffix();
  2632. if (!fileNameExtension.isEmpty() && !newNameFilterExtension.isEmpty()) {
  2633. const int fileNameExtensionLength = fileNameExtension.count();
  2634. fileName.replace(fileName.count() - fileNameExtensionLength,
  2635. fileNameExtensionLength, newNameFilterExtension);
  2636. qFileDialogUi->listView->clearSelection();
  2637. lineEdit()->setText(fileName);
  2638. }
  2639. }
  2640. model->setNameFilters(newNameFilters);
  2641. }
  2642. /*!
  2643. \internal
  2644. This is called when the model index corresponding to the current file is changed
  2645. from \a index to \a current.
  2646. */
  2647. void QFileDialogPrivate::_q_selectionChanged()
  2648. {
  2649. QModelIndexList indexes = qFileDialogUi->listView->selectionModel()->selectedRows();
  2650. bool stripDirs = (fileMode != QFileDialog::DirectoryOnly && fileMode != QFileDialog::Directory);
  2651. QStringList allFiles;
  2652. for (int i = 0; i < indexes.count(); ++i) {
  2653. if (stripDirs && model->isDir(mapToSource(indexes.at(i))))
  2654. continue;
  2655. allFiles.append(indexes.at(i).data().toString());
  2656. }
  2657. if (allFiles.count() > 1)
  2658. for (int i = 0; i < allFiles.count(); ++i) {
  2659. allFiles.replace(i, QString(QLatin1Char('"') + allFiles.at(i) + QLatin1Char('"')));
  2660. }
  2661. QString finalFiles = allFiles.join(QLatin1String(" "));
  2662. if (!finalFiles.isEmpty() && !lineEdit()->hasFocus() && lineEdit()->isVisible())
  2663. lineEdit()->setText(finalFiles);
  2664. else
  2665. _q_updateOkButton();
  2666. }
  2667. /*!
  2668. \internal
  2669. Includes hidden files and directories in the items displayed in the dialog.
  2670. */
  2671. void QFileDialogPrivate::_q_showHidden()
  2672. {
  2673. Q_Q(QFileDialog);
  2674. QDir::Filters dirFilters = q->filter();
  2675. if (showHiddenAction->isChecked())
  2676. dirFilters |= QDir::Hidden;
  2677. else
  2678. dirFilters &= ~QDir::Hidden;
  2679. q->setFilter(dirFilters);
  2680. }
  2681. /*!
  2682. \internal
  2683. When parent is root and rows have been inserted when none was there before
  2684. then select the first one.
  2685. */
  2686. void QFileDialogPrivate::_q_rowsInserted(const QModelIndex &parent)
  2687. {
  2688. if (!qFileDialogUi->treeView
  2689. || parent != qFileDialogUi->treeView->rootIndex()
  2690. || !qFileDialogUi->treeView->selectionModel()
  2691. || qFileDialogUi->treeView->selectionModel()->hasSelection()
  2692. || qFileDialogUi->treeView->model()->rowCount(parent) == 0)
  2693. return;
  2694. }
  2695. void QFileDialogPrivate::_q_fileRenamed(const QString &path, const QString oldName, const QString newName)
  2696. {
  2697. if (fileMode == QFileDialog::Directory || fileMode == QFileDialog::DirectoryOnly) {
  2698. if (path == rootPath() && lineEdit()->text() == oldName)
  2699. lineEdit()->setText(newName);
  2700. }
  2701. }
  2702. /*!
  2703. \internal
  2704. For the list and tree view watch keys to goto parent and back in the history
  2705. returns true if handled
  2706. */
  2707. bool QFileDialogPrivate::itemViewKeyboardEvent(QKeyEvent *event) {
  2708. Q_Q(QFileDialog);
  2709. switch (event->key()) {
  2710. case Qt::Key_Backspace:
  2711. _q_navigateToParent();
  2712. return true;
  2713. case Qt::Key_Back:
  2714. #ifdef QT_KEYPAD_NAVIGATION
  2715. if (QApplication::keypadNavigationEnabled())
  2716. return false;
  2717. #endif
  2718. case Qt::Key_Left:
  2719. if (event->key() == Qt::Key_Back || event->modifiers() == Qt::AltModifier) {
  2720. _q_navigateBackward();
  2721. return true;
  2722. }
  2723. break;
  2724. case Qt::Key_Escape:
  2725. q->hide();
  2726. return true;
  2727. default:
  2728. break;
  2729. }
  2730. return false;
  2731. }
  2732. QString QFileDialogPrivate::getEnvironmentVariable(const QString &string)
  2733. {
  2734. #ifdef Q_OS_UNIX
  2735. if (string.size() > 1 && string.startsWith(QLatin1Char('$'))) {
  2736. return QString::fromLocal8Bit(getenv(string.mid(1).toLatin1().constData()));
  2737. }
  2738. #else
  2739. if (string.size() > 2 && string.startsWith(QLatin1Char('%')) && string.endsWith(QLatin1Char('%'))) {
  2740. return QString::fromLocal8Bit(qgetenv(string.mid(1, string.size() - 2).toLatin1().constData()));
  2741. }
  2742. #endif
  2743. return string;
  2744. }
  2745. void QFileDialogComboBox::init(QFileDialogPrivate *d_pointer) {
  2746. d_ptr = d_pointer;
  2747. urlModel = new QUrlModel(this);
  2748. urlModel->showFullPath = true;
  2749. urlModel->setFileSystemModel(d_ptr->model);
  2750. setModel(urlModel);
  2751. }
  2752. void QFileDialogComboBox::showPopup()
  2753. {
  2754. if (model()->rowCount() > 1)
  2755. QComboBox::showPopup();
  2756. urlModel->setUrls(QList<QUrl>());
  2757. QList<QUrl> list;
  2758. QModelIndex idx = d_ptr->model->index(d_ptr->rootPath());
  2759. while (idx.isValid()) {
  2760. QUrl url = QUrl::fromLocalFile(idx.data(QFileSystemModel::FilePathRole).toString());
  2761. if (url.isValid())
  2762. list.append(url);
  2763. idx = idx.parent();
  2764. }
  2765. // add "my computer"
  2766. list.append(QUrl::fromLocalFile(QLatin1String("")));
  2767. urlModel->addUrls(list, 0);
  2768. idx = model()->index(model()->rowCount() - 1, 0);
  2769. // append history
  2770. QList<QUrl> urls;
  2771. for (int i = 0; i < m_history.count(); ++i) {
  2772. QUrl path = QUrl::fromLocalFile(m_history.at(i));
  2773. if (!urls.contains(path))
  2774. urls.prepend(path);
  2775. }
  2776. if (urls.count() > 0) {
  2777. model()->insertRow(model()->rowCount());
  2778. idx = model()->index(model()->rowCount()-1, 0);
  2779. // ### TODO maybe add a horizontal line before this
  2780. model()->setData(idx, QFileDialog::tr("Recent Places"));
  2781. QStandardItemModel *m = qobject_cast<QStandardItemModel*>(model());
  2782. if (m) {
  2783. Qt::ItemFlags flags = m->flags(idx);
  2784. flags &= ~Qt::ItemIsEnabled;
  2785. m->item(idx.row(), idx.column())->setFlags(flags);
  2786. }
  2787. urlModel->addUrls(urls, -1, false);
  2788. }
  2789. setCurrentIndex(0);
  2790. QComboBox::showPopup();
  2791. }
  2792. // Exact same as QComboBox::paintEvent(), except we elide the text.
  2793. void QFileDialogComboBox::paintEvent(QPaintEvent *)
  2794. {
  2795. QStylePainter painter(this);
  2796. painter.setPen(palette().color(QPalette::Text));
  2797. // draw the combobox frame, focusrect and selected etc.
  2798. QStyleOptionComboBox opt;
  2799. initStyleOption(&opt);
  2800. QRect editRect = style()->subControlRect(QStyle::CC_ComboBox, &opt,
  2801. QStyle::SC_ComboBoxEditField, this);
  2802. int size = editRect.width() - opt.iconSize.width() - 4;
  2803. opt.currentText = opt.fontMetrics.elidedText(opt.currentText, Qt::ElideMiddle, size);
  2804. painter.drawComplexControl(QStyle::CC_ComboBox, opt);
  2805. // draw the icon and text
  2806. painter.drawControl(QStyle::CE_ComboBoxLabel, opt);
  2807. }
  2808. QFileDialogListView::QFileDialogListView(QWidget *parent) : QListView(parent)
  2809. {
  2810. }
  2811. void QFileDialogListView::init(QFileDialogPrivate *d_pointer)
  2812. {
  2813. d_ptr = d_pointer;
  2814. setSelectionBehavior(QAbstractItemView::SelectRows);
  2815. setWrapping(true);
  2816. setResizeMode(QListView::Adjust);
  2817. setEditTriggers(QAbstractItemView::EditKeyPressed);
  2818. setContextMenuPolicy(Qt::CustomContextMenu);
  2819. #ifndef QT_NO_DRAGANDDROP
  2820. setDragDropMode(QAbstractItemView::InternalMove);
  2821. #endif
  2822. }
  2823. QSize QFileDialogListView::sizeHint() const
  2824. {
  2825. int height = qMax(10, sizeHintForRow(0));
  2826. return QSize(QListView::sizeHint().width() * 2, height * 30);
  2827. }
  2828. void QFileDialogListView::keyPressEvent(QKeyEvent *e)
  2829. {
  2830. #ifdef QT_KEYPAD_NAVIGATION
  2831. if (QApplication::navigationMode() == Qt::NavigationModeKeypadDirectional) {
  2832. QListView::keyPressEvent(e);
  2833. return;
  2834. }
  2835. #endif // QT_KEYPAD_NAVIGATION
  2836. if (!d_ptr->itemViewKeyboardEvent(e))
  2837. QListView::keyPressEvent(e);
  2838. e->accept();
  2839. }
  2840. QFileDialogTreeView::QFileDialogTreeView(QWidget *parent) : QTreeView(parent)
  2841. {
  2842. }
  2843. void QFileDialogTreeView::init(QFileDialogPrivate *d_pointer)
  2844. {
  2845. d_ptr = d_pointer;
  2846. setSelectionBehavior(QAbstractItemView::SelectRows);
  2847. setRootIsDecorated(false);
  2848. setItemsExpandable(false);
  2849. setSortingEnabled(true);
  2850. header()->setSortIndicator(0, Qt::AscendingOrder);
  2851. header()->setStretchLastSection(false);
  2852. setTextElideMode(Qt::ElideMiddle);
  2853. setEditTriggers(QAbstractItemView::EditKeyPressed);
  2854. setContextMenuPolicy(Qt::CustomContextMenu);
  2855. #ifndef QT_NO_DRAGANDDROP
  2856. setDragDropMode(QAbstractItemView::InternalMove);
  2857. #endif
  2858. }
  2859. void QFileDialogTreeView::keyPressEvent(QKeyEvent *e)
  2860. {
  2861. #ifdef QT_KEYPAD_NAVIGATION
  2862. if (QApplication::navigationMode() == Qt::NavigationModeKeypadDirectional) {
  2863. QTreeView::keyPressEvent(e);
  2864. return;
  2865. }
  2866. #endif // QT_KEYPAD_NAVIGATION
  2867. if (!d_ptr->itemViewKeyboardEvent(e))
  2868. QTreeView::keyPressEvent(e);
  2869. e->accept();
  2870. }
  2871. QSize QFileDialogTreeView::sizeHint() const
  2872. {
  2873. int height = qMax(10, sizeHintForRow(0));
  2874. QSize sizeHint = header()->sizeHint();
  2875. return QSize(sizeHint.width() * 4, height * 30);
  2876. }
  2877. /*!
  2878. // FIXME: this is a hack to avoid propagating key press events
  2879. // to the dialog and from there to the "Ok" button
  2880. */
  2881. void QFileDialogLineEdit::keyPressEvent(QKeyEvent *e)
  2882. {
  2883. #ifdef QT_KEYPAD_NAVIGATION
  2884. if (QApplication::navigationMode() == Qt::NavigationModeKeypadDirectional) {
  2885. QLineEdit::keyPressEvent(e);
  2886. return;
  2887. }
  2888. #endif // QT_KEYPAD_NAVIGATION
  2889. int key = e->key();
  2890. QLineEdit::keyPressEvent(e);
  2891. if (key != Qt::Key_Escape)
  2892. e->accept();
  2893. if (hideOnEsc && (key == Qt::Key_Escape || key == Qt::Key_Return || key == Qt::Key_Enter)) {
  2894. e->accept();
  2895. hide();
  2896. d_ptr->currentView()->setFocus(Qt::ShortcutFocusReason);
  2897. }
  2898. }
  2899. #ifndef QT_NO_FSCOMPLETER
  2900. QString QFSCompleter::pathFromIndex(const QModelIndex &index) const
  2901. {
  2902. const QFileSystemModel *dirModel;
  2903. if (proxyModel)
  2904. dirModel = qobject_cast<const QFileSystemModel *>(proxyModel->sourceModel());
  2905. else
  2906. dirModel = sourceModel;
  2907. QString currentLocation = dirModel->rootPath();
  2908. QString path = index.data(QFileSystemModel::FilePathRole).toString();
  2909. if (!currentLocation.isEmpty() && path.startsWith(currentLocation)) {
  2910. #if defined(Q_OS_UNIX) || defined(Q_OS_WINCE)
  2911. if (currentLocation == QDir::separator())
  2912. return path.mid(currentLocation.length());
  2913. #endif
  2914. if (currentLocation.endsWith(QLatin1Char('/')))
  2915. return path.mid(currentLocation.length());
  2916. else
  2917. return path.mid(currentLocation.length()+1);
  2918. }
  2919. return index.data(QFileSystemModel::FilePathRole).toString();
  2920. }
  2921. QStringList QFSCompleter::splitPath(const QString &path) const
  2922. {
  2923. if (path.isEmpty())
  2924. return QStringList(completionPrefix());
  2925. QString pathCopy = QDir::toNativeSeparators(path);
  2926. QString sep = QDir::separator();
  2927. #if defined(Q_OS_SYMBIAN)
  2928. if (pathCopy == QLatin1String("\\"))
  2929. return QStringList(pathCopy);
  2930. #elif defined(Q_OS_WIN)
  2931. if (pathCopy == QLatin1String("\\") || pathCopy == QLatin1String("\\\\"))
  2932. return QStringList(pathCopy);
  2933. QString doubleSlash(QLatin1String("\\\\"));
  2934. if (pathCopy.startsWith(doubleSlash))
  2935. pathCopy = pathCopy.mid(2);
  2936. else
  2937. doubleSlash.clear();
  2938. #elif defined(Q_OS_UNIX)
  2939. bool expanded;
  2940. pathCopy = qt_tildeExpansion(pathCopy, &expanded);
  2941. if (expanded) {
  2942. QFileSystemModel *dirModel;
  2943. if (proxyModel)
  2944. dirModel = qobject_cast<QFileSystemModel *>(proxyModel->sourceModel());
  2945. else
  2946. dirModel = sourceModel;
  2947. dirModel->fetchMore(dirModel->index(pathCopy));
  2948. }
  2949. #endif
  2950. QRegExp re(QLatin1Char('[') + QRegExp::escape(sep) + QLatin1Char(']'));
  2951. #if defined(Q_OS_SYMBIAN)
  2952. QStringList parts = pathCopy.split(re, QString::SkipEmptyParts);
  2953. if (pathCopy.endsWith(sep))
  2954. parts.append(QString());
  2955. #elif defined(Q_OS_WIN)
  2956. QStringList parts = pathCopy.split(re, QString::SkipEmptyParts);
  2957. if (!doubleSlash.isEmpty() && !parts.isEmpty())
  2958. parts[0].prepend(doubleSlash);
  2959. if (pathCopy.endsWith(sep))
  2960. parts.append(QString());
  2961. #else
  2962. QStringList parts = pathCopy.split(re);
  2963. if (pathCopy[0] == sep[0]) // read the "/" at the beginning as the split removed it
  2964. parts[0] = sep[0];
  2965. #endif
  2966. #if defined(Q_OS_WIN) || defined(Q_OS_SYMBIAN)
  2967. bool startsFromRoot = !parts.isEmpty() && parts[0].endsWith(QLatin1Char(':'));
  2968. #else
  2969. bool startsFromRoot = pathCopy[0] == sep[0];
  2970. #endif
  2971. if (parts.count() == 1 || (parts.count() > 1 && !startsFromRoot)) {
  2972. const QFileSystemModel *dirModel;
  2973. if (proxyModel)
  2974. dirModel = qobject_cast<const QFileSystemModel *>(proxyModel->sourceModel());
  2975. else
  2976. dirModel = sourceModel;
  2977. QString currentLocation = QDir::toNativeSeparators(dirModel->rootPath());
  2978. #if defined(Q_OS_WIN) || defined(Q_OS_SYMBIAN)
  2979. if (currentLocation.endsWith(QLatin1Char(':')))
  2980. currentLocation.append(sep);
  2981. #endif
  2982. if (currentLocation.contains(sep) && path != currentLocation) {
  2983. QStringList currentLocationList = splitPath(currentLocation);
  2984. while (!currentLocationList.isEmpty()
  2985. && parts.count() > 0
  2986. && parts.at(0) == QLatin1String("..")) {
  2987. parts.removeFirst();
  2988. currentLocationList.removeLast();
  2989. }
  2990. if (!currentLocationList.isEmpty() && currentLocationList.last().isEmpty())
  2991. currentLocationList.removeLast();
  2992. return currentLocationList + parts;
  2993. }
  2994. }
  2995. return parts;
  2996. }
  2997. #endif // QT_NO_COMPLETER
  2998. #ifdef QT3_SUPPORT
  2999. /*!
  3000. Use selectedFiles() instead.
  3001. \oldcode
  3002. QString selected = dialog->selectedFile();
  3003. \newcode
  3004. QStringList files = dialog->selectedFiles();
  3005. QString selected;
  3006. if (!files.isEmpty())
  3007. selected = files[0];
  3008. \endcode
  3009. */
  3010. QString QFileDialog::selectedFile() const
  3011. {
  3012. QStringList files = selectedFiles();
  3013. return files.size() ? files.at(0) : QString();
  3014. }
  3015. /*!
  3016. \typedef QFileDialog::Mode
  3017. Use QFileDialog::FileMode instead.
  3018. */
  3019. /*!
  3020. \fn void QFileDialog::setMode(FileMode m)
  3021. Use setFileMode() instead.
  3022. */
  3023. /*!
  3024. \fn FileMode QFileDialog::mode() const
  3025. Use fileMode() instead.
  3026. */
  3027. /*!
  3028. \fn void QFileDialog::setDir(const QString &directory)
  3029. Use setDirectory() instead.
  3030. */
  3031. /*!
  3032. \fn void QFileDialog::setDir( const QDir &directory )
  3033. Use setDirectory() instead.
  3034. */
  3035. /*!
  3036. \fn QStringList QFileDialog::getOpenFileNames(const QString &filter,
  3037. const QString &dir, QWidget *parent, const char* name,
  3038. const QString &caption, QString *selectedFilter, bool resolveSymlinks)
  3039. Use the getOpenFileNames() overload that takes \a parent as the first
  3040. argument instead.
  3041. */
  3042. /*!
  3043. \fn QString QFileDialog::getOpenFileName(const QString &dir,
  3044. const QString &filter, QWidget *parent = 0, const char *name,
  3045. const QString &caption, QString *selectedFilter, bool resolveSymlinks)
  3046. Use the getOpenFileName() overload that takes \a parent as the first
  3047. argument instead.
  3048. */
  3049. /*!
  3050. \fn QString QFileDialog::getSaveFileName(const QString &dir,
  3051. const QString &filter, QWidget *parent, const char *name,
  3052. const QString &caption, QString *selectedFilter, bool resolveSymlinks)
  3053. Use the getSaveFileName() overload that takes \a parent as the first
  3054. argument instead.
  3055. */
  3056. /*!
  3057. \fn QString QFileDialog::getExistingDirectory(const QString &dir,
  3058. QWidget *parent, const char *name, const QString &caption,
  3059. bool dirOnly, bool resolveSymlinks)
  3060. Use the getExistingDirectory() overload that takes \a parent as
  3061. the first argument instead.
  3062. */
  3063. #endif // QT3_SUPPORT
  3064. QT_END_NAMESPACE
  3065. #include "moc_qfiledialog.cpp"
  3066. #endif // QT_NO_FILEDIALOG