PageRenderTime 71ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 1ms

/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

Large files files are truncated, but you can click here to view the full file

  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 QFileDialo

Large files files are truncated, but you can click here to view the full file