PageRenderTime 71ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/src/gui/dialogs/qfiledialog.cpp

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