1 //*********************************************************************************
2 // SUIT_FileDlg class is the extension of the Qt's Open/Save file dialog box.
3 // To get the file/directory name(s) call static methods:
5 // to invoke "Open file" or "Save file" dialog box
6 // static QString getFileName(QWidget* parent, const QString& initial, const QStringList& filters,
7 // const QString& caption, const bool open, const bool showQuickDir = true,
8 // SUIT_FileValidator* validator = 0);
10 // to invoke "Open files" dialog box (to get the multiple file selection)
11 // static QStringList getOpenFileNames(QWidget* parent, const QString& initial, const QStringList& filters,
12 // const QString& caption, bool showQuickDir = true,
13 // SUIT_FileValidator* validator = 0);
15 // to invoke "Select directory" dialog box
16 // static QString getExistingDirectory(QWidget* parent, const QString& initial,
17 // const QString& caption, const bool showQuickDir = true);
20 // - parent parent widget (if 0, the current desktop is used)
21 // - initial starting directory or file name (if null, last visited directory is used)
22 // - filters file filters list; patterns inside the filter can be separated by ';','|' or ' '
24 // - caption dialog box's caption: if null, the default one is used
25 // - open open flag - true for "Open File" and false for "Save File" dialog box
26 // - showQuickDir this flag enables/disables "Quick directory list" controls
27 // - validator you can provide custom file validator with this parameter
32 // flist.append( "Image files (*.bmp *.gif *.jpg )" );
33 // flist.append( "All files (*.*)" );
34 // QMyFileValidator* v = new QMyFileValidator( 0 );
35 // QString fileName = SUIT_FileDlg::getFileName( 0, QString::null, flist, "Dump view", false, true, v );
36 // if ( !fileName.isEmpty() ) {
37 // ... writing image to the file
41 // flist.append( "*.cpp | *.cxx | *.c++" );
42 // flist.append( "*.h | *.hpp | *.hxx" );
43 // QString fileName = SUIT_FileDlg::getFileName( desktop(), QString::null, flist, QString::null, true, true );
45 //*********************************************************************************
47 #include "SUIT_FileDlg.h"
49 #include "SUIT_Tools.h"
50 #include "SUIT_Session.h"
51 #include "SUIT_Desktop.h"
52 #include "SUIT_MessageBox.h"
53 #include "SUIT_ResourceMgr.h"
54 #include "SUIT_FileValidator.h"
60 #include <qobjectlist.h>
61 #include <qcombobox.h>
62 #include <qpushbutton.h>
63 #include <qapplication.h>
65 #define MIN_COMBO_SIZE 100
67 /*! If the selected file name has extension which does not match the selected filter
68 * this extension is ignored (and new one will be added). See below for details.
70 const bool IGNORE_NON_MATCHING_EXTENSION = true;
72 QString SUIT_FileDlg::myLastVisitedPath;
75 SUIT_FileDlg::SUIT_FileDlg( QWidget* parent, bool open, bool showQuickDir, bool modal ) :
76 QFileDialog( parent, 0, modal ),
78 myQuickCombo( 0 ), myQuickButton( 0 ), myQuickLab( 0 ),
82 const QObjectList* child = children();
83 QObjectList::const_iterator anIt = child->begin(), aLast = child->end();
84 for( ; anIt!=aLast; anIt++ )
85 if( (*anIt)->inherits( "QPushButton" ) )
87 QPushButton* bt = ( QPushButton* )( *anIt );
88 bt->setDefault( false );
89 bt->setAutoDefault( false );
93 setIcon( *parent->icon() );
94 setSizeGripEnabled( true );
97 // inserting quick dir combo box
98 myQuickLab = new QLabel(tr("LAB_QUICK_PATH"), this);
99 myQuickCombo = new QComboBox(false, this);
100 myQuickCombo->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed));
101 myQuickCombo->setMinimumSize(MIN_COMBO_SIZE, 0);
103 myQuickButton = new QPushButton(tr("BUT_ADD_PATH"), this);
105 connect(myQuickCombo, SIGNAL(activated(const QString&)), this, SLOT(quickDir(const QString&)));
106 connect(myQuickButton, SIGNAL(clicked()), this, SLOT(addQuickDir()));
107 addWidgets(myQuickLab, myQuickCombo, myQuickButton);
109 // getting dir list from settings
111 SUIT_ResourceMgr* resMgr = SUIT_Session::session()->resourceMgr();
113 dirs = resMgr->stringValue( "FileDlg", QString( "QuickDirList" ) );
115 QStringList dirList = QStringList::split(';', dirs, false);
116 if (dirList.count() > 0) {
117 for (unsigned i = 0; i < dirList.count(); i++)
118 myQuickCombo->insertItem(dirList[i]);
121 myQuickCombo->insertItem(QDir::homeDirPath());
124 setMode( myOpen ? ExistingFile : AnyFile );
125 setCaption( myOpen ? tr( "INF_DESK_DOC_OPEN" ) : tr( "INF_DESK_DOC_SAVE" ) );
127 // If last visited path doesn't exist -> switch to the first preferred path
128 if ( !myLastVisitedPath.isEmpty() ) {
129 if ( !processPath( myLastVisitedPath ) && showQuickDir )
130 processPath( myQuickCombo->text( 0 ) );
134 processPath(myQuickCombo->text( 0 ) );
137 // set default file validator
138 myValidator = new SUIT_FileValidator(this);
142 SUIT_FileDlg::~SUIT_FileDlg()
147 /*! Redefined from QFileDialog.*/
148 void SUIT_FileDlg::polish()
150 QFileDialog::polish();
151 if ( myQuickButton && myQuickLab ) {
152 // the following is a workaround for proper layouting of custom widgets
153 QValueList<QPushButton*> buttonList;
154 QValueList<QLabel*> labelList;
155 const QObjectList *list = children();
156 QObjectListIt it(*list);
157 int maxButWidth = myQuickLab->sizeHint().width();
158 int maxLabWidth = myQuickButton->sizeHint().width();
160 for (; it.current() ; ++it) {
161 if ( it.current()->isA( "QLabel" ) ) {
162 int tempW = ((QLabel*)it.current())->minimumWidth();
163 if ( maxLabWidth < tempW ) maxLabWidth = tempW;
164 labelList.append( (QLabel*)it.current() );
166 else if( it.current()->isA("QPushButton") ) {
167 int tempW = ((QPushButton*)it.current())->minimumWidth();
168 if ( maxButWidth < tempW ) maxButWidth = tempW;
169 buttonList.append( (QPushButton*)it.current() );
172 if (maxButWidth > 0) {
173 QValueList<QPushButton*>::Iterator bListIt;
174 for ( bListIt = buttonList.begin(); bListIt != buttonList.end(); ++bListIt )
175 (*bListIt)->setFixedWidth( maxButWidth );
177 if (maxLabWidth > 0) {
178 QValueList<QLabel*>::Iterator lListIt;
179 for ( lListIt = labelList.begin(); lListIt != labelList.end(); ++lListIt )
180 (*lListIt)->setFixedWidth( maxLabWidth );
185 /*! Sets validator for file names to open/save
186 * Deletes previous validator if the dialog owns it.
188 void SUIT_FileDlg::setValidator( SUIT_FileValidator* v )
190 if ( myValidator && myValidator->parent() == this )
195 /*! Returns the selected file */
196 QString SUIT_FileDlg::selectedFile() const
198 return mySelectedFile;
201 /*! Returns 'true' if this is 'Open File' dialog
202 * and 'false' if 'Save File' dialog
204 bool SUIT_FileDlg::isOpenDlg() const
209 /*! Closes this dialog and sets the return code to 'Accepted'
210 * if the selected name is valid ( see 'acceptData()' )
212 void SUIT_FileDlg::accept()
215 * flag is used to warkaround the Qt 2.2.2 BUG:
216 * accept() method is called twice if user presses 'Enter' key
217 * in file name editor while file name is not acceptable by acceptData()
218 * (e.g. permission denied)
220 // if ( !myAccepted ) {
221 if ( mode() != ExistingFiles ) {
222 mySelectedFile = QFileDialog::selectedFile();
226 if ( acceptData() ) {
227 myLastVisitedPath = dirPath();
228 QFileDialog::accept();
229 // myAccepted = true;
232 // myAccepted = !myAccepted;
235 /*! Closes this dialog and sets the return code to 'Rejected' */
236 void SUIT_FileDlg::reject()
238 mySelectedFile = QString::null;
239 QFileDialog::reject();
242 /*! Returns 'true' if selected file is valid.
243 * The validity is checked by a file validator,
244 * if there is no validator the file is always
245 * considered as valid
247 bool SUIT_FileDlg::acceptData()
252 if ( mode() == ExistingFiles ) {
253 QStringList fileNames = selectedFiles();
254 for ( int i = 0; i < fileNames.count(); i++ ) {
255 if ( !myValidator->canOpen( fileNames[i] ) )
261 return myValidator->canOpen( selectedFile() );
264 return myValidator->canSave( selectedFile() );
269 /*! Adds an extension to the selected file name
270 * if the file has not it.
271 * The extension is extracted from the active filter.
273 void SUIT_FileDlg::addExtension()
275 // check if file name entered is empty
276 if ( mySelectedFile.stripWhiteSpace().isEmpty() )
279 // current file extension
280 QString anExt = "." + SUIT_Tools::extension( mySelectedFile.stripWhiteSpace() ).stripWhiteSpace();
282 // If the file already has extension and it does not match the filter there are two choices:
283 // - to leave it 'as is'
285 // The behavior is defined by IGNORE_NON_MATCHING_EXTENSION constant
286 if ( anExt != "." && !IGNORE_NON_MATCHING_EXTENSION )
289 // get selected file filter
290 #if QT_VERSION < 0x030000
291 QRegExp r( QString::fromLatin1("(?[a-zA-Z0-9.*? +;#|]*)?$") );
292 int len, index = r.match( selectedFilter().stripWhiteSpace(), 0, &len );
294 QRegExp r( QString::fromLatin1("\\(?[a-zA-Z0-9.*? +;#|]*\\)?$") );
295 int index = r.search( selectedFilter().stripWhiteSpace() );
299 // Create wildcard regular expression basing on selected filter
300 // in order to validate a file extension.
301 // Due to transformations from the filter list (*.txt *.*xx *.c++ SUIT*.* ) we
302 // will have the pattern (\.txt|\..*xx|\.c\+\+|\..*) (as we validate extension only,
303 // we remove everything except extension mask from the pattern
304 #if QT_VERSION < 0x030000
305 QString wildcard = selectedFilter().mid( index, len ).stripWhiteSpace();
307 QString wildcard = selectedFilter().mid( index, r.matchedLength() ).stripWhiteSpace();
309 // replace '|' and ';' separators by space symbol and also brackets if there are some
310 wildcard.replace( QRegExp( "[\\|;|(|)]" )," " );
312 QString aPattern = wildcard.replace( QRegExp( "(^| )(\\s*)[0-9a-zA-Z*_?]*\\."), " \\." ).stripWhiteSpace().
313 replace( QRegExp( "\\s+" ), "|" ).replace( QRegExp( "[?]" ),".?" ).
314 replace( QRegExp( "[*]" ),".*" ).replace( QRegExp( "[+]" ),"\\+" );
316 // now we get the list of all extension masks and remove all which does not contain wildcard symbols
317 QStringList extList = QStringList::split( "|",aPattern );
318 for( int i = extList.count() - 1; i >= 0; i-- ) {
319 if ( !extList[i].contains( "." ) )
320 extList.remove( extList.at( i ) );
322 aPattern = extList.join( "|" );
325 QRegExp anExtRExp( "^("+ aPattern + ")$" );
327 // Check if the current file extension matches the pattern
328 if ( anExtRExp.match( anExt ) < 0 ) {
329 // find first appropriate extension in the selected filter
330 // (it should be without wildcard symbols)
331 for ( int i = 0; i < extList.count(); i++ ) {
332 QString newExt = extList[i].replace( QRegExp( "[\\\\][+]" ),"+" );
333 int res = newExt.findRev( '.' );
335 newExt = newExt.mid( res + 1 );
336 if ( newExt.find( QRegExp("[*|?]" ) ) < 0 ) {
337 mySelectedFile.stripWhiteSpace();
338 mySelectedFile += mySelectedFile.endsWith(".") ? newExt : QString(".") + newExt;
346 /*! Processes selection : tries to set given path or filename as selection */
347 bool SUIT_FileDlg::processPath( const QString& path )
349 if ( !path.isNull() ) {
350 QFileInfo fi( path );
353 setSelection( path );
354 else if ( fi.isDir() )
359 if ( QFileInfo( fi.dirPath() ).exists() ) {
360 setDir( fi.dirPath() );
361 setSelection( path );
368 /*! Called when user selects item from "Quick Dir" combo box */
369 void SUIT_FileDlg::quickDir(const QString& dirPath)
371 QString aPath = dirPath;
372 if ( !QDir(aPath).exists() ) {
373 aPath = QDir::homeDirPath();
374 SUIT_MessageBox::error1(this,
376 tr("ERR_DIR_NOT_EXIST").arg(dirPath),
383 Called when user presses "Add" button - adds current directory to quick directory
384 list and to the preferences
386 void SUIT_FileDlg::addQuickDir()
388 QString dp = dirPath();
389 if ( !dp.isEmpty() ) {
391 // getting dir list from settings
393 SUIT_ResourceMgr* resMgr = SUIT_Session::session()->resourceMgr();
395 dirs = resMgr->stringValue( "FileDlg", QString( "QuickDirList" ) );
396 QStringList dirList = QStringList::split(';', dirs, false);
398 bool emptyAndHome = false;
399 if ( dirList.count() > 0 ) {
400 for ( unsigned i = 0; i < dirList.count(); i++ ) {
401 QDir aDir( dirList[i] );
402 if ( aDir.canonicalPath().isNull() && dirList[i] == dir.absPath() ||
403 !aDir.canonicalPath().isNull() && aDir.exists() && aDir.canonicalPath() == dir.canonicalPath() ) {
410 emptyAndHome = dir.canonicalPath() == QDir(QDir::homeDirPath()).canonicalPath();
413 dirList.append( dp );
414 resMgr->setValue( "FileDlg", QString( "QuickDirList" ), dirList.join(";") );
416 myQuickCombo->insertItem( dp );
421 Returns the file name for Open/Save [ static ]
423 QString SUIT_FileDlg::getFileName( QWidget* parent,
424 const QString& initial,
425 const QStringList& filters,
426 const QString& caption,
429 SUIT_FileValidator* validator )
431 SUIT_FileDlg* fd = new SUIT_FileDlg( parent, open, showQuickDir, true );
432 if ( !caption.isEmpty() )
433 fd->setCaption( caption );
434 if ( !initial.isEmpty() ) {
435 fd->processPath( initial ); // VSR 24/03/03 check for existing of directory has been added to avoid QFileDialog's bug
437 fd->setFilters( filters );
439 fd->setValidator( validator );
441 QString filename = fd->selectedFile();
443 qApp->processEvents();
449 Returns the list of files to be opened [ static ]
451 QStringList SUIT_FileDlg::getOpenFileNames( QWidget* parent,
452 const QString& initial,
453 const QStringList& filters,
454 const QString& caption,
456 SUIT_FileValidator* validator )
458 SUIT_FileDlg* fd = new SUIT_FileDlg( parent, true, showQuickDir, true );
459 fd->setMode( ExistingFiles );
460 if ( !caption.isEmpty() )
461 fd->setCaption( caption );
462 if ( !initial.isEmpty() ) {
463 fd->processPath( initial ); // VSR 24/03/03 check for existing of directory has been added to avoid QFileDialog's bug
465 fd->setFilters( filters );
467 fd->setValidator( validator );
469 QStringList filenames = fd->selectedFiles();
471 qApp->processEvents();
476 Existing directory selection dialog [ static ]
478 QString SUIT_FileDlg::getExistingDirectory( QWidget* parent,
479 const QString& initial,
480 const QString& caption,
483 SUIT_FileDlg* fd = new SUIT_FileDlg( parent, true, showQuickDir, true);
484 if ( !caption.isEmpty() )
485 fd->setCaption( caption );
486 if ( !initial.isEmpty() ) {
487 fd->processPath( initial ); // VSR 24/03/03 check for existing of directory has been added to avoid QFileDialog's bug
489 fd->setMode( DirectoryOnly );
490 fd->setFilters(tr("INF_DIRECTORIES_FILTER"));
492 QString dirname = fd->selectedFile();
494 qApp->processEvents();