Salome HOME
DCQ : Merge with Ecole_ete_a6.
[modules/kernel.git] / src / SALOMEGUI / QAD_FileDlg.cxx
1 //  SALOME SALOMEGUI : implementation of desktop and GUI kernel
2 //
3 //  Copyright (C) 2003  CEA/DEN, EDF R&D
4 //
5 //
6 //
7 //  File   : QAD_FileDlg.cxx
8 //  Author : 
9 //  Module : SALOME
10 //  $Header$
11
12 using namespace std;
13 #include <qapplication.h>
14 #include <qdir.h>
15 #include <qlabel.h>
16 #include <qobjectlist.h>
17 #include <qpalette.h>
18 #include <qpushbutton.h>
19 #include <qregexp.h>
20 #include "QAD_Config.h"
21 #include "QAD_Desktop.h"   
22 #include "QAD_FileDlg.h"
23 #include "QAD_MessageBox.h"
24 #include "QAD_Tools.h"   
25
26 #define MIN_COMBO_SIZE     100
27
28 QString QAD_FileDlg::myLastVisitedPath;
29
30 /*!
31 Constructor
32 */
33 QAD_FileDlg::QAD_FileDlg( QWidget* parent, bool open, bool showQuickDir, bool modal ) :
34 QFileDialog( parent, 0, modal ),
35 myValidator( 0 ),
36 myQuickCombo( 0 ),
37 myOpen( open )
38 {    
39   if ( parent->icon() )
40     setIcon( *parent->icon() );       
41   setSizeGripEnabled( true );
42   
43   if (showQuickDir) {
44     // inserting quick dir combo box
45     QLabel* lab  = new QLabel(tr("Quick path:"), this);
46     myQuickCombo = new QComboBox(false, this);
47     myQuickCombo->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed));
48     myQuickCombo->setMinimumSize(MIN_COMBO_SIZE, 0);
49     
50     // the following is a workaround for proper layouting of custom widgets ===========
51     QPushButton* btn = new QPushButton(this);
52     btn->setEnabled(false);
53     QPalette pal = btn->palette();
54     QColorGroup ca = pal.active();
55     ca.setColor(QColorGroup::Light,    palette().active().background());
56     ca.setColor(QColorGroup::Midlight, palette().active().background());
57     ca.setColor(QColorGroup::Dark,     palette().active().background());
58     ca.setColor(QColorGroup::Mid,      palette().active().background());
59     ca.setColor(QColorGroup::Shadow,   palette().active().background());
60     QColorGroup ci = pal.inactive();
61     ci.setColor(QColorGroup::Light,    palette().inactive().background());
62     ci.setColor(QColorGroup::Midlight, palette().inactive().background());
63     ci.setColor(QColorGroup::Dark,     palette().inactive().background());
64     ci.setColor(QColorGroup::Mid,      palette().inactive().background());
65     ci.setColor(QColorGroup::Shadow,   palette().inactive().background());
66     QColorGroup cd = pal.disabled();
67     cd.setColor(QColorGroup::Light,    palette().disabled().background());
68     cd.setColor(QColorGroup::Midlight, palette().disabled().background());
69     cd.setColor(QColorGroup::Dark,     palette().disabled().background());
70     cd.setColor(QColorGroup::Mid,      palette().disabled().background());
71     cd.setColor(QColorGroup::Shadow,   palette().disabled().background());
72     pal.setActive(ca); pal.setInactive(ci); pal.setDisabled(cd);
73     btn->setPalette(pal);
74     // ================================================================================
75
76     connect(myQuickCombo, SIGNAL(activated(const QString&)), this, SLOT(quickDir(const QString&)));
77     addWidgets(lab, myQuickCombo, btn);
78
79     // getting dir list from settings
80     QString dirs = QAD_CONFIG->getSetting("FileDlg:QuickDirList");
81     QStringList dirList = QStringList::split(';', dirs, false);
82     if (dirList.count() > 0) {
83       for (unsigned i = 0; i < dirList.count(); i++)
84         myQuickCombo->insertItem(dirList[i]);
85     }
86     else {
87       myQuickCombo->insertItem(QDir::homeDirPath());
88     }
89
90     // the following is a workaround for proper layouting of custom widgets ===========
91     QValueList<QPushButton*> buttonList;
92     QValueList<QLabel*> labelList;
93     const QObjectList *list = children();
94     QObjectListIt it(*list);
95     int maxButWidth = lab->sizeHint().width();
96     int maxLabWidth = btn->sizeHint().width();
97     
98     for (; it.current() ; ++it) {
99       if ( it.current()->isA( "QLabel" ) ) {
100         int tempW = ((QLabel*)it.current())->minimumWidth();
101         if ( maxLabWidth < tempW ) maxLabWidth = tempW;
102         labelList.append( (QLabel*)it.current() );
103       }
104       else if( it.current()->isA("QPushButton") ) {
105         int tempW = ((QPushButton*)it.current())->minimumWidth();
106         if ( maxButWidth < tempW ) maxButWidth = tempW;
107         buttonList.append( (QPushButton*)it.current() );
108       }
109     }
110     if (maxButWidth > 0) {
111       QValueList<QPushButton*>::Iterator bListIt;
112       for ( bListIt = buttonList.begin(); bListIt != buttonList.end(); ++bListIt )
113         (*bListIt)->setFixedWidth( maxButWidth );
114     }
115     if (maxLabWidth > 0) {
116       QValueList<QLabel*>::Iterator lListIt;
117       for ( lListIt = labelList.begin(); lListIt != labelList.end(); ++lListIt )
118         (*lListIt)->setFixedWidth( maxLabWidth );
119     }
120     // ================================================================================
121   }
122   setMode( myOpen ? ExistingFile : AnyFile );     
123   setCaption( myOpen ? tr( "INF_DESK_DOC_OPEN" ) : tr( "INF_DESK_DOC_SAVE" ) );
124   if (myLastVisitedPath.isNull() || myLastVisitedPath.isEmpty()) {
125     // If no last visited path exists -> switch to the first preferred path
126     processPath(myQuickCombo->text(0));
127   } 
128   else if ( !processPath(myLastVisitedPath) ) {
129     // If last visited path doesn't exist -> switch to the first preferred path
130     processPath(myQuickCombo->text(0));
131   }
132   myValidator = new QAD_FileValidator(this);
133   
134 }
135
136 /*!
137 Destructor
138 */
139 QAD_FileDlg::~QAD_FileDlg() 
140 {
141 }
142
143 /*!
144 Sets validator for file names to open/save
145 Deletes previous validator
146 */
147 void QAD_FileDlg::setValidator( QAD_FileValidator* v )
148 {
149   if (myValidator)
150     delete myValidator;
151   myValidator = v;
152 }
153
154 /*!
155 Returns the selected file
156 */
157 QString QAD_FileDlg::selectedFile() const
158 {
159   return mySelectedFile;
160 }
161
162 /*!
163 Returns 'true' if this is 'Open File' dialog 
164 and 'false' if 'Save File' dialog
165 */
166 bool QAD_FileDlg::isOpenDlg() const
167 {
168   return myOpen;
169 }
170
171 /*!
172 Closes this dialog and sets the return code to 'Accepted'
173 if the selected name is valid ( see 'acceptData()' )
174 */
175 void QAD_FileDlg::accept()
176 {
177 //  mySelectedFile = QFileDialog::selectedFile().simplifyWhiteSpace(); //VSR- 06/12/02
178   mySelectedFile = QFileDialog::selectedFile(); //VSR+ 06/12/02
179   addExtension();
180 //  mySelectedFile = mySelectedFile.simplifyWhiteSpace(); //VSR- 06/12/02
181
182   /* Qt 2.2.2 BUG: accept() is called twice if you validate 
183   the selected file name by pressing 'Return' key in file 
184   name editor but this name is not acceptable for acceptData()
185   */
186   if ( acceptData() ) {
187     myLastVisitedPath = dirPath();
188     QFileDialog::accept();        
189   }
190 }
191
192 /*!
193 Closes this dialog and sets the return code to 'Rejected'    
194 */
195 void QAD_FileDlg::reject()
196 {
197   mySelectedFile = QString::null;
198   QFileDialog::reject();        
199 }
200
201 /*!
202 Returns 'true' if selected file is valid.
203 The validity is checked by a file validator, 
204 if there is no validator the file is always
205 considered as valid    
206 */
207 bool QAD_FileDlg::acceptData()
208 {    
209   if ( myValidator )
210   {
211     if ( isOpenDlg() )
212       return myValidator->canOpen( selectedFile() );
213     else 
214       return myValidator->canSave( selectedFile() );
215   }
216   return true;
217 }
218
219 /*!
220 Adds an extension to the selected file name
221 if the file has not it.
222 The extension is extracted from the active filter.
223 */
224 void QAD_FileDlg::addExtension()
225 {
226 //  mySelectedFile.stripWhiteSpace();//VSR- 06/12/02
227 //  if ( mySelectedFile.isEmpty() )//VSR- 06/12/02
228   if ( mySelectedFile.stripWhiteSpace().isEmpty() )//VSR+ 06/12/02
229     return;
230
231 //  if ( QAD_Tools::getFileExtensionFromPath( mySelectedFile ).isEmpty() ) //VSR- 06/12/02
232 //ota :   16/12/03  if ( QAD_Tools::getFileExtensionFromPath( mySelectedFile ).isEmpty() ) //VSR+ 06/12/02
233 //  {
234
235 #if QT_VERSION < 0x030000
236     QRegExp r( QString::fromLatin1("([a-zA-Z0-9.*? +;#]*)$") );
237     int len, index = r.match( selectedFilter(), 0, &len );
238 #else
239     QRegExp r( QString::fromLatin1("\\([a-zA-Z0-9.*? +;#]*\\)$") );
240     int index = r.search(selectedFilter());
241 #endif
242     if ( index >= 0 ) 
243     {            
244 #if QT_VERSION < 0x030000
245 //      QString wildcard = selectedFilter().mid( index + 1, len-2 ); //VSR- 06/12/02
246       QString wildcard = selectedFilter().mid( index + 1, len-2 ).stripWhiteSpace(); //VSR+ 06/12/02
247 #else
248 //      QString wildcard = selectedFilter().mid( index + 1, r.matchedLength()-2 ); //VSR- 06/12/02
249       QString wildcard = selectedFilter().mid( index + 1, r.matchedLength()-2 ).stripWhiteSpace(); //VSR+ 06/12/02
250 #endif
251       if ( mySelectedFile[mySelectedFile.length() - 1] == '.')
252         //if the file name ends with the point remove it
253         mySelectedFile.truncate(mySelectedFile.length() - 1);
254       QString anExt = "." + QAD_Tools::getFileExtensionFromPath( mySelectedFile ).stripWhiteSpace();
255       // From the filters list make a pattern to validate a file extension
256       // Due to transformations from the filter list (*.txt *.*xx *.c++ QAD*.* ) we 
257       // will have the pattern (\.txt|\..*xx|\.c\+\+|\..*) (as we validate extension only we remove
258       // stay extension mask only in the pattern
259       QString aPattern(wildcard);
260       QRegExp anExtRExp("("+aPattern.replace(QRegExp("(^| )[0-9a-zA-Z*_?]*\\."), " \\.").
261                         stripWhiteSpace().replace(QRegExp("\\s+"), "|").
262                         replace(QRegExp("[*]"),".*").replace(QRegExp("[+]"),"\\+") + ")");
263       
264       if ( anExtRExp.match(anExt) == -1 ) //if a selected file extension does not match to filter's list
265         { //remove a point if it is at the word end
266           if (anExt[ anExt.length() - 1 ] == '.')  anExt.truncate( anExt.length() - 1 );
267           index = wildcard.findRev( '.' );    
268           if ( index >= 0 ) 
269             mySelectedFile += wildcard.mid( index ); //add the extension
270         }
271     }
272   //  }
273 }
274
275 /*!
276   Processes selection : tries to set given path or filename as selection
277 */
278 bool QAD_FileDlg::processPath( const QString& path )
279 {
280   if ( !path.isNull() ) {
281     QFileInfo fi( path );
282     if ( fi.exists() ) {
283       if ( fi.isFile() )
284         setSelection( path );
285       else if ( fi.isDir() )
286         setDir( path );
287       return true;
288     }
289     else {
290       if ( QFileInfo( fi.dirPath() ).exists() ) {
291         setDir( fi.dirPath() );
292         return true;
293       }
294     }
295   }
296   return false;
297 }
298 /*!
299   Called when user selects item from "Quick Dir" combo box
300 */
301 void QAD_FileDlg::quickDir(const QString& dirPath)
302 {
303   if ( !QDir(dirPath).exists() ) {
304     QAD_MessageBox::error1(this, 
305                            tr("ERR_ERROR"),
306                            tr("ERR_DIR_NOT_EXIST").arg(dirPath), 
307                            tr("BUT_OK"));
308     
309   }
310   else {
311     processPath(dirPath);
312   }
313 }
314
315 /*!
316   Returns the file name for Open/Save [ static ]
317 */
318 QString QAD_FileDlg::getFileName( QWidget*           parent, 
319                                   const QString&     initial, 
320                                   const QStringList& filters, 
321                                   const QString&     caption,
322                                   bool               open,
323                                   bool               showQuickDir, 
324                                   QAD_FileValidator* validator )
325 {            
326   QAD_FileDlg* fd = new QAD_FileDlg( parent, open, showQuickDir, true );    
327   if ( !caption.isEmpty() )
328     fd->setCaption( caption );
329   if ( !initial.isEmpty() ) { 
330     fd->processPath( initial ); // VSR 24/03/03 check for existing of directory has been added to avoid QFileDialog's bug
331   }
332   fd->setFilters( filters );        
333   if ( validator )
334     fd->setValidator( validator );
335   fd->exec();
336   QString filename = fd->selectedFile();
337   delete fd;
338   qApp->processEvents();
339   return filename;
340 }
341
342 /*!
343   Existing directory selection dialog [ static ]
344 */
345 QString QAD_FileDlg::getExistingDirectory ( QWidget*       parent,
346                                             const QString& initial,
347                                             const QString& caption, 
348                                             bool           showQuickDir )
349 {
350   QAD_FileDlg* fd = new QAD_FileDlg( parent, true, showQuickDir, true);
351   if ( !caption.isEmpty() )
352     fd->setCaption( caption );
353   if ( !initial.isEmpty() ) {
354     fd->processPath( initial ); // VSR 24/03/03 check for existing of directory has been added to avoid QFileDialog's bug
355   }
356   fd->setMode( DirectoryOnly );
357   fd->setFilters(tr("DIRECTORIES_FILTER"));
358   fd->exec();
359   QString dirname = fd->selectedFile();
360   delete fd;
361   qApp->processEvents();
362   return dirname;
363   
364 }