]> git.lyx.org Git - lyx.git/blob - src/frontends/qt/GuiLyXFiles.cpp
GuiLyXFiles: Hide empty categories on filtering (#12584)
[lyx.git] / src / frontends / qt / GuiLyXFiles.cpp
1 /**
2  * \file GuiLyXFiles.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Jürgen Spitzmüller
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "GuiLyXFiles.h"
14 #include "GuiApplication.h"
15 #include "qt_helpers.h"
16
17 #include "FileDialog.h"
18 #include "FuncRequest.h"
19 #include "Language.h"
20 #include "LyXRC.h"
21
22 #include "support/environment.h"
23 #include "support/gettext.h"
24 #include "support/lstrings.h"
25 #include "support/Messages.h"
26 #include "support/qstring_helpers.h"
27 #include "support/Package.h"
28
29 #include <QVector>
30 #include <QDirIterator>
31 #include <QTreeWidget>
32
33 using namespace std;
34 using namespace lyx::support;
35
36 namespace lyx {
37 namespace frontend {
38
39 namespace {
40
41 QString const guiString(QString const & in)
42 {
43         // recode specially encoded chars in file names (URL encoding and underbar)
44         return QString::fromUtf8(QByteArray::fromPercentEncoding(in.toUtf8())).replace('_', ' ');
45 }
46
47 } // namespace anon
48
49
50 QMap<QString, QString> GuiLyXFiles::getFiles()
51 {
52         QMap<QString, QString> result;
53         // We look for lyx files in the subdirectory dir of
54         //   1) user_lyxdir
55         //   2) build_lyxdir (if not empty)
56         //   3) system_lyxdir
57         // in this order. Files with a given sub-hierarchy will
58         // only be listed once.
59         // We also consider i18n subdirectories and store them separately.
60         QStringList dirs;
61         QStringList relpaths;
62
63         // The three locations to look at.
64         string const user = addPath(package().user_support().absFileName(), fromqstr(type_));
65         string const build = addPath(package().build_support().absFileName(), fromqstr(type_));
66         string const system = addPath(package().system_support().absFileName(), fromqstr(type_));
67
68         available_languages_.insert(toqstr("en"), qt_("English"));
69
70         QString const type = fileTypeCO->itemData(fileTypeCO->currentIndex()).toString();
71
72         // Search in the base paths
73         if (type == "all" || type == "user")
74                 dirs << toqstr(user);
75         if (type == "all" || type == "system")
76                 dirs << toqstr(build)
77                      << toqstr(system);
78
79         for (int i = 0; i < dirs.size(); ++i) {
80                 QString const & dir = dirs.at(i);
81                 QDirIterator it(dir, QDir::Files, QDirIterator::Subdirectories);
82                 while (it.hasNext()) {
83                         QString fn(QFile(it.next()).fileName());
84                         if (!fn.endsWith(getSuffix()))
85                                 continue;
86                         QString relpath = toqstr(makeRelPath(qstring_to_ucs4(fn),
87                                                              qstring_to_ucs4(dir)));
88                         // <cat>/
89                         int s = relpath.indexOf('/', 0);
90                         QString cat = qt_("General");
91                         QString localization = "en";
92                         if (s != -1) {
93                                 // <cat>/<subcat>/
94                                 cat = relpath.left(s);
95                                 if (all_languages_.contains(cat)
96                                     && !all_languages_.contains(dir.right(dir.lastIndexOf('/')))) {
97                                         QMap<QString, QString>::const_iterator li = all_languages_.find(cat);
98                                         // Skip i18n dir, but add language to the combo
99                                         if (!available_languages_.contains(li.key()))
100                                                 available_languages_.insert(li.key(), li.value());
101                                         localization = cat;
102                                         int sc = relpath.indexOf('/', s + 1);
103                                         cat = (sc == -1) ? qt_("General") : relpath.mid(s + 1, sc - s - 1);
104                                         s = sc;
105                                 }
106                                 if (s != -1) {
107                                         int sc = relpath.indexOf('/', s + 1);
108                                         QString const subcat = (sc == -1) ?
109                                                                 QString() : relpath.mid(s + 1, sc - s - 1);
110                                         if (!subcat.isEmpty())
111                                                 cat += '/' + subcat;
112                                 }
113                         }
114                         if (!relpaths.contains(relpath)) {
115                                 relpaths.append(relpath);
116                                 if (localization != "en")
117                                         // strip off lang/
118                                         relpath = relpath.mid(relpath.indexOf('/') + 1);
119                                 result.insert(relpath, cat);
120                                                                         
121                                 QMap<QString, QString> lm;
122                                 if (localizations_.contains(relpath))
123                                         lm = localizations_.find(relpath).value();
124                                 lm.insert(localization, fn);
125                                 localizations_.insert(relpath, lm);
126                         }
127                 }
128         }
129         // Find and store GUI language
130         for (auto const & l : guilangs_) {
131                 // First try with the full name
132                 // `en' files are not in a subdirectory
133                 if (available_languages_.contains(toqstr(l))) {
134                         guilang_ = toqstr(l);
135                         break;
136                 }
137                 // Then the name without country code
138                 string const shortl = token(l, '_', 0);
139                 if (available_languages_.contains(toqstr(shortl))) {
140                         guilang_ = toqstr(shortl);
141                         break;
142                 }
143         }
144         // pre-fill the language combo (it will be updated once an item 
145         // has been clicked)
146         languageCO->clear();
147         QMap<QString, QString>::const_iterator i =available_languages_.constBegin();
148         while (i != available_languages_.constEnd()) {
149                 languageCO->addItem(i.value(), i.key());
150                 ++i;
151         }
152         setLanguage();
153         return result;
154 }
155
156
157 GuiLyXFiles::GuiLyXFiles(GuiView & lv)
158         : GuiDialog(lv, "lyxfiles", qt_("New File From Template"))
159 {
160         setupUi(this);
161
162         // Get all supported languages (by code) in order to exclude those
163         // dirs later.
164         QAbstractItemModel * language_model = guiApp->languageModel();
165         language_model->sort(0);
166         for (int i = 0; i != language_model->rowCount(); ++i) {
167                 QModelIndex index = language_model->index(i, 0);
168                 Language const * lang =
169                         languages.getLanguage(fromqstr(index.data(Qt::UserRole).toString()));
170                 if (!lang)
171                         continue;
172                 QString const code = toqstr(lang->code());
173                 if (!all_languages_.contains(code))
174                         all_languages_.insert(code, qt_(lang->display()));
175                 // Also store code without country code
176                 QString const shortcode = code.left(code.indexOf('_'));
177                 if (shortcode != code && !all_languages_.contains(shortcode))
178                         all_languages_.insert(shortcode, qt_(lang->display()));
179         }
180         // Get GUI language
181         string lang = getGuiMessages().language();
182         string const language = getEnv("LANGUAGE");
183         if (!language.empty())
184                 lang += ":" + language;
185         guilangs_ =  getVectorFromString(lang, ":");
186
187         // The filter bar
188         filter_ = new FancyLineEdit(this);
189         filter_->setClearButton(true);
190         filter_->setPlaceholderText(qt_("All available files"));
191         filter_->setToolTip(qt_("Enter string to filter the list of available files"));
192 #if (QT_VERSION < 0x050000)
193         connect(filter_, SIGNAL(downPressed()),
194                 filesLW, SLOT(setFocus()));
195 #else
196         connect(filter_, &FancyLineEdit::downPressed,
197                 filesLW, [this](){ focusAndHighlight(filesLW); });
198 #endif
199
200         filterBarL->addWidget(filter_, 0);
201         findKeysLA->setBuddy(filter_);
202
203         connect(buttonBox, SIGNAL(clicked(QAbstractButton *)),
204                 this, SLOT(slotButtonBox(QAbstractButton *)));
205
206         connect(filesLW, SIGNAL(itemClicked(QTreeWidgetItem *, int)),
207                 this, SLOT(fileSelectionChanged()));
208         connect(filesLW, SIGNAL(itemSelectionChanged()),
209                 this, SLOT(fileSelectionChanged()));
210         connect(filter_, SIGNAL(textEdited(QString)),
211                 this, SLOT(filterLabels()));
212         connect(filter_, SIGNAL(rightButtonClicked()),
213                 this, SLOT(resetFilter()));
214
215         bc().setPolicy(ButtonPolicy::OkApplyCancelPolicy);
216         bc().setOK(buttonBox->button(QDialogButtonBox::Open));
217         bc().setCancel(buttonBox->button(QDialogButtonBox::Cancel));
218
219         //filesLW->setViewMode(QListView::ListMode);
220         filesLW->setIconSize(QSize(22, 22));
221
222         QIcon user_icon(getPixmap("images/", "lyxfiles-user", "svgz,png"));
223         QIcon system_icon(getPixmap("images/", "lyxfiles-system", "svgz,png"));
224         fileTypeCO->addItem(qt_("User and System Files"), toqstr("all"));
225         fileTypeCO->addItem(user_icon, qt_("User Files Only"), toqstr("user"));
226         fileTypeCO->addItem(system_icon, qt_("System Files Only"), toqstr("system"));
227
228         setFocusProxy(filter_);
229 }
230
231
232 QString const GuiLyXFiles::getSuffix()
233 {
234         if (type_ == "bind" || type_ == "ui")
235                 return toqstr(".") + type_;
236         else if (type_ == "kbd")
237                 return ".kmap";
238         
239         return ".lyx";
240 }
241
242
243 bool GuiLyXFiles::translateName() const
244 {
245         return (type_ == "templates" || type_ == "examples");
246 }
247
248
249 void GuiLyXFiles::fileSelectionChanged()
250 {
251         if (!filesLW->currentItem()
252             || !filesLW->currentItem()->data(0, Qt::UserRole).toString().endsWith(getSuffix())) {
253                 // not a file (probably a header)
254                 bc().setValid(false);
255                 return;
256         }
257         changed();
258 }
259
260
261 void GuiLyXFiles::on_fileTypeCO_activated(int)
262 {
263         updateContents();
264 }
265
266
267 void GuiLyXFiles::on_languageCO_activated(int i)
268 {
269         savelang_ = languageCO->itemData(i).toString();
270         if (!filesLW->currentItem())
271                 return;
272
273         filesLW->currentItem()->setData(0, Qt::ToolTipRole, getRealPath());
274         changed();
275 }
276
277
278 void GuiLyXFiles::on_filesLW_itemDoubleClicked(QTreeWidgetItem * item, int)
279 {
280         if (!item || !item->data(0, Qt::UserRole).toString().endsWith(getSuffix())) {
281                 // not a file (probably a header)
282                 bc().setValid(false);
283                 return;
284         }
285
286         applyView();
287         dispatchParams();
288         close();
289 }
290
291 void GuiLyXFiles::on_filesLW_itemClicked(QTreeWidgetItem * item, int)
292 {
293         if (!item) {
294                 bc().setValid(false);
295                 return;
296         }
297
298         QString const data = item->data(0, Qt::UserRole).toString();
299         if (!data.endsWith(getSuffix())) {
300                 // not a file (probably a header)
301                 bc().setValid(false);
302                 return;
303         }
304
305         languageCO->clear();
306         QMap<QString, QString>::const_iterator i =available_languages_.constBegin();
307         while (i != available_languages_.constEnd()) {
308                 if (localizations_.contains(data)
309                     && localizations_.find(data).value().contains(i.key()))
310                         languageCO->addItem(i.value(), i.key());
311                 ++i;
312         }
313         setLanguage();
314         QString const realpath = getRealPath();
315         filesLW->currentItem()->setData(0, Qt::ToolTipRole, realpath);
316         QIcon user_icon(getPixmap("images/", "lyxfiles-user", "svgz,png"));
317         QIcon system_icon(getPixmap("images/", "lyxfiles-system", "svgz,png"));
318         QIcon file_icon = (realpath.startsWith(toqstr(package().user_support().absFileName()))) ?
319                         user_icon : system_icon;
320         item->setIcon(0, file_icon);
321 }
322
323
324 void GuiLyXFiles::setLanguage()
325 {
326         // Enable language selection only if there is a selection.
327         bool const item_selected =  filesLW->currentItem();
328         bool const language_alternatives = languageCO->count() > 1;
329         languageCO->setEnabled(item_selected && language_alternatives);
330         languageLA->setEnabled(item_selected && language_alternatives);
331         if (item_selected && language_alternatives)
332                 languageCO->setToolTip(qt_("All available languages of the selected file are displayed here.\n"
333                                            "The selected language version will be opened."));
334         else if (item_selected)
335                 languageCO->setToolTip(qt_("No alternative language versions available for the selected file."));
336         else
337                 languageCO->setToolTip(qt_("If alternative languages are available for a given file,\n"
338                                            "they can be chosen here if a file is selected."));
339         // first try last setting
340         if (!savelang_.isEmpty()) {
341                 int index = languageCO->findData(savelang_);
342                 if (index != -1) {
343                         languageCO->setCurrentIndex(index);
344                         return;
345                 }
346         }
347         // next, try GUI lang
348         if (!guilang_.isEmpty()) {
349                 int index = languageCO->findData(guilang_);
350                 if (index != -1) {
351                         languageCO->setCurrentIndex(index);
352                         return;
353                 }
354         }
355         // Finally, fall back to English (which should be always there)
356         int index = languageCO->findData(toqstr("en"));
357         if (index != -1) {
358                 languageCO->setCurrentIndex(index);
359         }
360 }
361
362
363 void GuiLyXFiles::on_browsePB_pressed()
364 {
365         QString path1 = toqstr(lyxrc.document_path);
366         QString path2 = toqstr(lyxrc.example_path);
367         QString title = qt_("Select example file");
368         QString filter = qt_("LyX Documents (*.lyx)");
369         QString b1 = qt_("D&ocuments");
370         QString b2 = qt_("&Examples");
371
372         if (type_ == "templates") {
373                 path2 = toqstr(lyxrc.template_path);
374                 title = qt_("Select template file");
375                 b1 = qt_("D&ocuments");
376                 b2 = qt_("&Templates");
377         }
378         else if (type_ != "examples") {
379                 path1 = toqstr(addName(package().user_support().absFileName(), fromqstr(type_)));
380                 path2 = toqstr(addName(package().system_support().absFileName(), fromqstr(type_)));
381                 b1 = qt_("&User files");
382                 b2 = qt_("&System files");
383         }
384         if (type_ == "ui") {
385                 title = qt_("Chose UI file");
386                 filter = qt_("LyX UI Files (*.ui)");
387         }
388         if (type_ == "bind") {
389                 title = qt_("Chose bind file");
390                 filter = qt_("LyX Bind Files (*.bind)");
391         }
392         if (type_ == "kbd") {
393                 title = qt_("Chose keyboard map");
394                 filter = qt_("LyX Keymap Files (*.kmap)");
395         }
396
397         FileDialog dlg(title);
398         dlg.setButton1(b1, path1);
399         dlg.setButton2(b2, path2);
400
401         FileDialog::Result result = dlg.open(path2, QStringList(filter));
402
403         if (result.first != FileDialog::Later && !result.second.isEmpty()) {
404                 file_ = toqstr(FileName(fromqstr(result.second)).absFileName());
405                 dispatchParams();
406                 close();
407         }
408 }
409
410
411 void GuiLyXFiles::updateContents()
412 {
413         languageCO->clear();
414         QMap<QString, QString> files = getFiles();
415         languageCO->model()->sort(0);
416
417         filesLW->clear();
418         QIcon user_icon(getPixmap("images/", "lyxfiles-user", "svgz,png"));
419         QIcon system_icon(getPixmap("images/", "lyxfiles-system", "svgz,png"));
420         QIcon folder_icon(getPixmap("images/", "lyxfiles-folder", "svgz,png"));
421         QStringList cats;
422         QMap<QString, QString>::const_iterator it = files.constBegin();
423         QFont capfont;
424         capfont.setBold(true);
425         while (it != files.constEnd()) {
426                 QFileInfo const info = QFileInfo(it.key());
427                 QString const realpath = getRealPath(it.key());
428                 QString cat = it.value();
429                 QString subcat;
430                 QString catsave;
431                 if (cat.contains('/')) {
432                         catsave = cat;
433                         cat = catsave.left(catsave.indexOf('/'));
434                         subcat = toqstr(translateIfPossible(
435                                         qstring_to_ucs4(guiString(catsave.mid(catsave.indexOf('/') + 1)))));
436                 }
437                 cat =  toqstr(translateIfPossible(qstring_to_ucs4(guiString(cat))));
438                 QTreeWidgetItem * catItem;
439                 if (!cats.contains(cat)) {
440                         catItem = new QTreeWidgetItem();
441                         catItem->setText(0, cat);
442                         catItem->setFont(0, capfont);
443                         filesLW->insertTopLevelItem(0, catItem);
444                         catItem->setExpanded(true);
445                         cats << cat;
446                 } else
447                         catItem = filesLW->findItems(cat, Qt::MatchExactly).first();
448                 QTreeWidgetItem * item = new QTreeWidgetItem();
449                 QString const filename = info.fileName();
450                 QString guiname = filename.left(filename.lastIndexOf(getSuffix())).replace('_', ' ');
451                 // Special case: defaults.lyx
452                 if (type_ == "templates" && guiname == "defaults")
453                         guiname = qt_("Default Template");
454                 else if (translateName())
455                         guiname = toqstr(translateIfPossible(qstring_to_ucs4(guiString(guiname))));
456                 QIcon file_icon = (realpath.startsWith(toqstr(package().user_support().absFileName()))) ?
457                                 user_icon : system_icon;
458                 item->setIcon(0, file_icon);
459                 item->setData(0, Qt::UserRole, it.key());
460                 item->setData(0, Qt::DisplayRole, guiname);
461                 item->setData(0, Qt::ToolTipRole, realpath);
462                 if (subcat.isEmpty())
463                         catItem->addChild(item);
464                 else {
465                         QTreeWidgetItem * subcatItem = nullptr;
466                         if (cats.contains(catsave)) {
467                                 QList<QTreeWidgetItem *> pcats = filesLW->findItems(cat, Qt::MatchExactly);
468                                 for (auto const & pcat : pcats) {
469                                         for (int cit = 0; cit < pcat->childCount(); ++cit) {
470                                                 if (pcat->child(cit)->text(0) == subcat) {
471                                                         subcatItem = pcat->child(cit);
472                                                         break;
473                                                 }
474                                         }
475                                 }
476                         }
477                         if (!subcatItem) {
478                                 subcatItem = new QTreeWidgetItem();
479                                 subcatItem->setText(0, subcat);
480                                 subcatItem->setIcon(0, folder_icon);
481                                 cats << catsave;
482                         }
483                         subcatItem->addChild(item);
484                         catItem->addChild(subcatItem);
485                 }
486                 ++it;
487         }
488         filesLW->sortItems(0, Qt::AscendingOrder);
489         // redo filter
490         filterLabels();
491 }
492
493
494 void GuiLyXFiles::slotButtonBox(QAbstractButton * button)
495 {
496         switch (buttonBox->standardButton(button)) {
497         case QDialogButtonBox::Open:
498                 slotOK();
499                 break;
500         case QDialogButtonBox::Cancel:
501                 slotClose();
502                 break;
503         default:
504                 break;
505         }
506 }
507
508
509 void GuiLyXFiles::filterLabels()
510 {
511         Qt::CaseSensitivity cs = csFindCB->isChecked() ?
512                 Qt::CaseSensitive : Qt::CaseInsensitive;
513         // Collect "active" categories (containing entries
514         // that match the filter)
515         QVector<QTreeWidgetItem*> activeCats;
516         QTreeWidgetItemIterator it(filesLW);
517         while (*it) {
518                 if ((*it)->childCount() > 0) {
519                         // Unhide parents (will be hidden
520                         // below if necessary)
521                         (*it)->setHidden(false);
522                         ++it;
523                         continue;
524                 }
525                 bool const match = (*it)->text(0).contains(filter_->text(), cs);
526                 if (match) {
527                         // Register parents of matched entries
528                         // so we don't hide those later.
529                         QTreeWidgetItem * twi = *it;
530                         while (true) {
531                                 if (!twi->parent())
532                                         break;
533                                 activeCats << twi->parent();
534                                 // ascend further up if possible
535                                 twi = twi->parent();
536                         }
537                 }
538                 (*it)->setHidden(!match);
539                 ++it;
540         }
541         // Iterate through parents once more
542         // to hide empty categories
543         it = QTreeWidgetItemIterator(filesLW);
544         while (*it) {
545                 if ((*it)->childCount() == 0) {
546                         ++it;
547                         continue;
548                 }
549                 (*it)->setHidden(!activeCats.contains(*it));
550                 ++it;
551         }
552 }
553
554
555 void GuiLyXFiles::resetFilter()
556 {
557         filter_->setText(QString());
558         filterLabels();
559 }
560
561 QString const GuiLyXFiles::getRealPath(QString relpath)
562 {
563         if (relpath.isEmpty() && filesLW->currentItem() != nullptr)
564                 relpath = filesLW->currentItem()->data(0, Qt::UserRole).toString();
565         QString const language = languageCO->itemData(languageCO->currentIndex()).toString();
566         if (localizations_.contains(relpath)) {
567                 if (localizations_.find(relpath).value().contains(language))
568                         return localizations_.find(relpath).value().find(language).value();
569                 else if (localizations_.find(relpath).value().contains(guilang_))
570                         return localizations_.find(relpath).value().find(guilang_).value();
571                 else if (localizations_.find(relpath).value().contains(toqstr("en")))
572                         return localizations_.find(relpath).value().find(toqstr("en")).value();
573         }
574         return QString();
575 }
576
577
578 void GuiLyXFiles::applyView()
579 {
580         file_ = getRealPath();
581 }
582
583
584 bool GuiLyXFiles::isValid()
585 {
586         return filesLW->currentItem() && filesLW->currentItem()->isSelected();
587 }
588
589
590 bool GuiLyXFiles::initialiseParams(string const & type)
591 {
592         type_ = type.empty() ? toqstr("templates") : toqstr(type);
593         paramsToDialog();
594         return true;
595 }
596
597
598 void GuiLyXFiles::passParams(string const & data)
599 {
600         initialiseParams(data);
601         updateContents();
602 }
603
604
605 void GuiLyXFiles::selectItem(QString const & item)
606 {
607         /* Using an intermediary variable flags is needed up to at least
608          * Qt 5.5 because of a subtle namespace issue. See:
609          *   https://stackoverflow.com/questions/10755058/qflags-enum-type-conversion-fails-all-of-a-sudden
610          * for details.*/
611         Qt::MatchFlags const flags(Qt::MatchExactly|Qt::MatchRecursive);
612         QList<QTreeWidgetItem *> twi = filesLW->findItems(item, flags);
613         if (!twi.isEmpty())
614                 twi.first()->setSelected(true);
615 }
616
617
618 void GuiLyXFiles::paramsToDialog()
619 {
620         if (type_ == "examples")
621                 setTitle(qt_("Open Example File"));
622         else if (type_ == "templates")
623                 setTitle(qt_("New File From Template"));
624         else
625                 setTitle(qt_("Open File"));
626
627         bc().setValid(isValid());
628 }
629
630
631 void GuiLyXFiles::dispatchParams()
632 {
633         if (file_.isEmpty())
634                 return;
635
636         string arg;
637         if (type_ == "templates")
638                 arg = "newfile ";
639         arg += quoteName(fromqstr(file_));
640         FuncCode const lfun = getLfun();
641
642         if (lfun == LFUN_NOACTION)
643                 // emit signal
644                 fileSelected(file_);
645         else
646                 dispatch(FuncRequest(lfun, arg));
647 }
648
649
650 FuncCode GuiLyXFiles::getLfun() const
651 {
652         if (type_ == "examples")
653                 return LFUN_FILE_OPEN;
654         else if (type_ == "templates")
655                 return LFUN_BUFFER_NEW_TEMPLATE;
656         return LFUN_NOACTION;
657 }
658
659
660 } // namespace frontend
661 } // namespace lyx
662
663 #include "moc_GuiLyXFiles.cpp"