]> SALOME platform Git repositories - modules/shaper.git/blob - src/ModuleBase/ModuleBase_WidgetFileSelector.cpp
Salome HOME
Issue #2863: Use Utf8 string for file selector
[modules/shaper.git] / src / ModuleBase / ModuleBase_WidgetFileSelector.cpp
1 // Copyright (C) 2014-2017  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or
18 // email : webmaster.salome@opencascade.com<mailto:webmaster.salome@opencascade.com>
19 //
20
21 #include <ModelAPI_AttributeString.h>
22 #include <ModelAPI_Data.h>
23 #include <ModelAPI_Object.h>
24 #include <ModelAPI_Validator.h>
25 #include <ModelAPI_Session.h>
26 #include <ModuleBase_WidgetFileSelector.h>
27 #include <ModuleBase_Tools.h>
28
29 #include <Config_PropManager.h>
30 #include <Config_WidgetAPI.h>
31
32 #include <QFileDialog>
33 #include <QGridLayout>
34 #include <QLabel>
35 #include <QLineEdit>
36 #include <QList>
37 #include <QObject>
38 #include <QPushButton>
39 #include <QRegExp>
40 #include <QString>
41
42 #include <memory>
43 #include <string>
44
45
46 /// Default path
47 static QString myDefaultPath;
48
49
50 ModuleBase_WidgetFileSelector::ModuleBase_WidgetFileSelector(QWidget* theParent,
51                                                              const Config_WidgetAPI* theData)
52 : ModuleBase_ModelWidget(theParent, theData), myFileDialog(0)
53 {
54   myTitle = translate(theData->getProperty("title"));
55   myType = (theData->getProperty("type") == "save") ? WFS_SAVE : WFS_OPEN;
56   if (myDefaultPath.isNull() || myDefaultPath.isEmpty())
57     myDefaultPath = QString::fromStdString(theData->getProperty("path"));
58
59   if (myDefaultPath.isEmpty())
60     myDefaultPath = Config_PropManager::string("Plugins", "import_initial_path").c_str();
61
62   QGridLayout* aMainLay = new QGridLayout(this);
63   ModuleBase_Tools::adjustMargins(aMainLay);
64   QLabel* aTitleLabel = new QLabel(myTitle, this);
65   aTitleLabel->setIndent(1);
66   aMainLay->addWidget(aTitleLabel, 0, 0);
67   myPathField = new QLineEdit(this);
68   aMainLay->addWidget(myPathField, 1, 0);
69
70   QPushButton* aSelectPathBtn = new QPushButton("...", this);
71   aSelectPathBtn->setToolTip(tr("Select file..."));
72   aSelectPathBtn->setMaximumWidth(20);
73   aSelectPathBtn->setMaximumHeight(20);
74   aMainLay->addWidget(aSelectPathBtn, 1, 1);
75   aMainLay->setColumnStretch(0, 1);
76   myPathField->setMinimumHeight(20);
77   aMainLay->setHorizontalSpacing(1);
78   this->setLayout(aMainLay);
79
80   connect(myPathField, SIGNAL(textChanged(const QString&)),
81           this,        SLOT(onPathChanged()));
82   connect(aSelectPathBtn, SIGNAL(clicked()),
83           this,        SLOT(onPathSelectionBtn()));
84 }
85
86 ModuleBase_WidgetFileSelector::~ModuleBase_WidgetFileSelector()
87 {
88 }
89
90 bool ModuleBase_WidgetFileSelector::storeValueCustom()
91 {
92   // A rare case when plugin was not loaded.
93   if (!myFeature)
94     return false;
95   DataPtr aData = myFeature->data();
96   AttributeStringPtr aStringAttr = aData->string(attributeID());
97   QString aWidgetValue = myPathField->text();
98   aStringAttr->setValue(aWidgetValue.toStdWString());
99   updateObject(myFeature);
100   return true;
101 }
102
103 bool ModuleBase_WidgetFileSelector::restoreValueCustom()
104 {
105   // A rare case when plugin was not loaded.
106   if (!myFeature)
107     return false;
108   DataPtr aData = myFeature->data();
109   AttributeStringPtr aStringAttr = aData->string(attributeID());
110
111   std::wstring aUtfStr = aStringAttr->valueW();
112   QString aNewText = QString::fromStdWString(aUtfStr);
113   if (myPathField->text() != aNewText) {
114     bool isBlocked = myPathField->blockSignals(true);
115     myPathField->setText(aNewText);
116     myPathField->blockSignals(isBlocked);
117   }
118
119   return true;
120 }
121
122 QList<QWidget*> ModuleBase_WidgetFileSelector::getControls() const
123 {
124   QList<QWidget*> result;
125   result << myPathField;
126   return result;
127 }
128
129 bool ModuleBase_WidgetFileSelector::isCurrentPathValid()
130 {
131   QFileInfo aFile(myPathField->text());
132   return aFile.exists();
133 }
134
135 bool ModuleBase_WidgetFileSelector::processEscape()
136 {
137   if (myFileDialog) {
138     myFileDialog->reject();
139     return true;
140   }
141   return ModuleBase_ModelWidget::processEscape();
142 }
143
144
145 void ModuleBase_WidgetFileSelector::onPathSelectionBtn()
146 {
147   QString aDefaultPath = myPathField->text().isEmpty()
148       ? myDefaultPath
149       : QFileInfo(myPathField->text()).absolutePath();
150   QString aFilter = filterString();
151
152   // use Option prohibited native dialog using to have both lower/upper extensions of files
153   // satisfied to dialog filter on Linux(Calibre) Issue #2055
154   myFileDialog = new QFileDialog(this, myTitle, aDefaultPath, aFilter);
155   myFileDialog->setNameFilter(aFilter);
156   myFileDialog->setOptions(QFileDialog::DontUseNativeDialog);
157   myFileDialog->setAcceptMode(myType == WFS_SAVE ? QFileDialog::AcceptSave
158                                                  : QFileDialog::AcceptOpen);
159   if (myFileDialog->exec() == QDialog::Accepted)
160   {
161     mySelectedFilter = myFileDialog->selectedNameFilter();
162     QStringList aFileNames = myFileDialog->selectedFiles();
163     if (!aFileNames.empty()) {
164       QString aFileName = aFileNames.first();
165       if (!aFileName.isEmpty()) {
166         if (myType == WFS_SAVE)
167           aFileName = applyExtension(aFileName, mySelectedFilter);
168         myPathField->setText(aFileName.toUtf8());
169         myDefaultPath = QFileInfo(aFileName).absolutePath();
170         emit focusOutWidget(this);
171       }
172     }
173   }
174   myFileDialog = 0;
175 }
176
177 void ModuleBase_WidgetFileSelector::onPathChanged()
178 {
179   if (myType == WFS_OPEN && !isCurrentPathValid())
180     return;
181   storeValue();
182   emit valuesChanged();
183 }
184
185 QString ModuleBase_WidgetFileSelector::formatToFilter(const QString & theFormat)
186 {
187   if (theFormat.isEmpty() && !theFormat.contains(":"))
188     return QString();
189
190   QStringList aExtesionList = theFormat.section(':', 0, 0).split("|");
191   QString aFormat = theFormat.section(':', 1, 1);
192   return QString("%1 files (%2)").arg(aFormat)
193       .arg(QStringList(aExtesionList).replaceInStrings(QRegExp("^(.*)$"), "*.\\1").join(" "));
194 }
195
196 QString ModuleBase_WidgetFileSelector::filterToShortFormat(const QString & theFilter)
197 {
198   // Simplified implementation.
199   // It relies on theFilter was made by formatToFilter() function.
200   return theFilter.section(' ', 0, 0);
201 }
202
203 QStringList ModuleBase_WidgetFileSelector::filterToExtensions(const QString & theFilter)
204 {
205   // Simplified implementation.
206   // It relies on theFilter was made by formatToFilter() function.
207   QStringList anExtensions = theFilter.section("(", 1, 1).section(")", 0, 0).split(" ");
208   return anExtensions;
209 }
210
211 QStringList ModuleBase_WidgetFileSelector::getValidatorFormats() const
212 {
213   SessionPtr aMgr = ModelAPI_Session::get();
214   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
215
216   ModelAPI_ValidatorsFactory::Validators allValidators;
217   aFactory->validators(myFeature->getKind(), myAttributeID, allValidators);
218
219   QStringList aResult;
220   std::list<std::string> anArgumentList = allValidators.front().second;
221   std::list<std::string>::const_iterator it = anArgumentList.begin();
222   for (; it != anArgumentList.end(); ++it) {
223     QString aFormat = QString::fromStdString(*it);
224     if (!aFormat.isEmpty())
225       aResult << aFormat;
226   }
227   return aResult;
228 }
229
230 QString ModuleBase_WidgetFileSelector::filterString() const
231 {
232   QStringList aResult;
233   QStringList aValidatorFormats = getValidatorFormats();
234
235   foreach(const QString & eachFormat, aValidatorFormats) {
236     aResult << formatToFilter(eachFormat);
237   }
238   if (myType == WFS_OPEN)
239     aResult << QString("All files (*.*)");
240   return aResult.join(";;");
241 }
242
243 QString ModuleBase_WidgetFileSelector::applyExtension(const QString& theFileName,
244                                                       const QString& theFilter)
245 {
246   QString aResult = theFileName;
247   bool hasExtension = false;
248   QStringList anExtensions = filterToExtensions(theFilter);
249   foreach(const QString& anExtension, anExtensions) {
250     if (theFileName.endsWith(anExtension.section(".", 1, 1), Qt::CaseInsensitive)) {
251       hasExtension = true;
252       break;
253     }
254   }
255   if (!hasExtension && !anExtensions.isEmpty())
256     aResult = QString("%1.%2").arg(theFileName).arg(anExtensions[0].section(".", 1, 1));
257   return aResult;
258 }