Salome HOME
NRI : Add KERNEL_ROOT_DIR in addition to SALOME_[ROOT, SITE]_DIR.
[modules/kernel.git] / src / SALOMEGUI / QAD_FileDlg.cxx
1 using namespace std;
2 //  File      : QAD_FileDlg.cxx
3 //  Created   : UI team, 17.09.02
4 //  Descr     : Open/Save File dialog
5
6 //  Modified  : Tue Sep 17 11:15:23 2002
7 //  Author    : 
8 //  Project   : SALOME
9 //  Module    : SALOMEGUI
10 //  Copyright : Open CASCADE 2001
11 //  $Header$
12
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   if ( QAD_Tools::getFileExtensionFromPath( mySelectedFile ).isEmpty() && !mySelectedFile.contains(".") ) //VSR+ 06/12/02
233   {
234 #if QT_VERSION < 0x030000
235     QRegExp r( QString::fromLatin1("([a-zA-Z0-9.*? +;#]*)$") );
236     int len, index = r.match( selectedFilter(), 0, &len );
237 #else
238     QRegExp r( QString::fromLatin1("\\([a-zA-Z0-9.*? +;#]*\\)$") );
239     int index = r.search(selectedFilter());
240 #endif
241     if ( index >= 0 ) 
242     {            
243 #if QT_VERSION < 0x030000
244 //      QString wildcard = selectedFilter().mid( index + 1, len-2 ); //VSR- 06/12/02
245       QString wildcard = selectedFilter().mid( index + 1, len-2 ).stripWhiteSpace(); //VSR+ 06/12/02
246 #else
247 //      QString wildcard = selectedFilter().mid( index + 1, r.matchedLength()-2 ); //VSR- 06/12/02
248       QString wildcard = selectedFilter().mid( index + 1, r.matchedLength()-2 ).stripWhiteSpace(); //VSR+ 06/12/02
249 #endif
250       index = wildcard.findRev( '.' );    
251       if ( index >= 0 ) 
252         mySelectedFile += wildcard.mid( index );
253     }
254   }
255 }
256
257 /*!
258   Processes selection : tries to set given path or filename as selection
259 */
260 bool QAD_FileDlg::processPath( const QString& path )
261 {
262   if ( !path.isNull() ) {
263     QFileInfo fi( path );
264     if ( fi.exists() ) {
265       if ( fi.isFile() )
266         setSelection( path );
267       else if ( fi.isDir() )
268         setDir( path );
269       return true;
270     }
271     else {
272       if ( QFileInfo( fi.dirPath() ).exists() ) {
273         setDir( fi.dirPath() );
274         return true;
275       }
276     }
277   }
278   return false;
279 }
280 /*!
281   Called when user selects item from "Quick Dir" combo box
282 */
283 void QAD_FileDlg::quickDir(const QString& dirPath)
284 {
285   if ( !QDir(dirPath).exists() ) {
286     QAD_MessageBox::error1(this, 
287                            tr("ERR_ERROR"),
288                            tr("ERR_DIR_NOT_EXIST").arg(dirPath), 
289                            tr("BUT_OK"));
290     
291   }
292   else {
293     processPath(dirPath);
294   }
295 }
296
297 /*!
298   Returns the file name for Open/Save [ static ]
299 */
300 QString QAD_FileDlg::getFileName( QWidget*           parent, 
301                                   const QString&     initial, 
302                                   const QStringList& filters, 
303                                   const QString&     caption,
304                                   bool               open,
305                                   bool               showQuickDir, 
306                                   QAD_FileValidator* validator )
307 {            
308   QAD_FileDlg* fd = new QAD_FileDlg( parent, open, showQuickDir, true );    
309   if ( !caption.isEmpty() )
310     fd->setCaption( caption );
311   if ( !initial.isEmpty() ) { 
312     fd->processPath( initial ); // VSR 24/03/03 check for existing of directory has been added to avoid QFileDialog's bug
313   }
314   fd->setFilters( filters );        
315   if ( validator )
316     fd->setValidator( validator );
317   fd->exec();
318   QString filename = fd->selectedFile();
319   delete fd;
320   qApp->processEvents();
321   return filename;
322 }
323
324 /*!
325   Existing directory selection dialog [ static ]
326 */
327 QString QAD_FileDlg::getExistingDirectory ( QWidget*       parent,
328                                             const QString& initial,
329                                             const QString& caption, 
330                                             bool           showQuickDir )
331 {
332   QAD_FileDlg* fd = new QAD_FileDlg( parent, true, showQuickDir, true);
333   if ( !caption.isEmpty() )
334     fd->setCaption( caption );
335   if ( !initial.isEmpty() ) {
336     fd->processPath( initial ); // VSR 24/03/03 check for existing of directory has been added to avoid QFileDialog's bug
337   }
338   fd->setMode( DirectoryOnly );
339   fd->setFilters(tr("DIRECTORIES_FILTER"));
340   fd->exec();
341   QString dirname = fd->selectedFile();
342   delete fd;
343   qApp->processEvents();
344   return dirname;
345   
346 }