3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Jürgen Spitzmüller
8 * \author Richard Kimberly Heck
10 * Full author contact details are available in file CREDITS.
15 #include "qt_helpers.h"
17 #include "LengthCombo.h"
20 #include "frontends/alert.h"
22 #include "support/convert.h"
23 #include "support/debug.h"
24 #include "support/gettext.h"
25 #include "support/lstrings.h"
26 #include "support/Package.h"
27 #include "support/PathChanger.h"
28 #include "support/Systemcall.h"
30 #include <QApplication>
33 #include <QDesktopServices>
39 #include <QTextLayout>
40 #include <QTextDocument>
53 using namespace lyx::support;
57 FileName libFileSearch(QString const & dir, QString const & name,
58 QString const & ext, search_mode mode)
60 return support::libFileSearch(fromqstr(dir), fromqstr(name), fromqstr(ext), mode);
64 FileName imageLibFileSearch(QString & dir, QString const & name,
65 QString const & ext, search_mode mode)
67 string tmp = fromqstr(dir);
68 FileName fn = support::imageLibFileSearch(tmp, fromqstr(name), fromqstr(ext), mode);
75 double locstringToDouble(QString const & str)
79 double res = loc.toDouble(str, &ok);
82 QLocale c(QLocale::C);
83 res = c.toDouble(str);
93 string widgetsToLength(QLineEdit const * input, LengthCombo const * combo)
95 QString const length = input->text();
99 // Don't return unit-from-choice if the input(field) contains a unit
100 if (isValidGlueLength(fromqstr(length)))
101 return fromqstr(length);
102 // Also try with localized version
103 if (isValidGlueLength(fromqstr(unlocLengthString(length))))
104 return fromqstr(unlocLengthString(length));
106 Length::UNIT const unit = combo->currentLengthItem();
108 return Length(locstringToDouble(length.trimmed()), unit).asString();
112 Length widgetsToLength(QLineEdit const * input, QComboBox const * combo)
114 QString const length = input->text();
115 if (length.isEmpty())
118 // don't return unit-from-choice if the input(field) contains a unit
119 if (isValidGlueLength(fromqstr(length)))
120 return Length(fromqstr(length));
121 // Also try with localized version
122 if (isValidGlueLength(fromqstr(unlocLengthString(length))))
123 return Length(fromqstr(unlocLengthString(length)));
125 Length::UNIT unit = Length::UNIT_NONE;
126 QString const item = combo->currentText();
127 for (int i = 0; i < num_units; i++) {
128 if (qt_(lyx::unit_name_gui[i]) == item) {
129 unit = unitFromString(unit_name[i]);
134 return Length(locstringToDouble(length.trimmed()), unit);
138 void lengthToWidgets(QLineEdit * input, LengthCombo * combo,
139 Length const & len, Length::UNIT /*defaultUnit*/)
142 // no length (UNIT_NONE)
143 combo->setCurrentItem(Length::defaultUnit());
146 combo->setCurrentItem(len.unit());
148 loc.setNumberOptions(QLocale::OmitGroupSeparator);
149 input->setText(formatLocFPNumber(Length(len).value()));
154 void lengthToWidgets(QLineEdit * input, LengthCombo * combo,
155 string const & len, Length::UNIT defaultUnit)
158 // no length (UNIT_NONE)
159 combo->setCurrentItem(defaultUnit);
161 } else if (!isValidLength(len) && !isStrDbl(len)) {
162 // use input field only for gluelengths
163 combo->setCurrentItem(defaultUnit);
164 input->setText(locLengthString(toqstr(len)));
166 lengthToWidgets(input, combo, Length(len), defaultUnit);
171 void lengthToWidgets(QLineEdit * input, LengthCombo * combo,
172 docstring const & len, Length::UNIT defaultUnit)
174 lengthToWidgets(input, combo, to_utf8(len), defaultUnit);
178 double widgetToDouble(QLineEdit const * input)
180 QString const text = input->text();
184 return locstringToDouble(text.trimmed());
188 string widgetToDoubleStr(QLineEdit const * input)
190 return convert<string>(widgetToDouble(input));
194 void doubleToWidget(QLineEdit * input, double value, char f, int prec)
197 loc.setNumberOptions(QLocale::OmitGroupSeparator);
198 input->setText(loc.toString(value, f, prec));
202 void doubleToWidget(QLineEdit * input, string const & value, char f, int prec)
204 doubleToWidget(input, convert<double>(value), f, prec);
208 QString formatLocFPNumber(double d)
210 QString result = toqstr(formatFPNumber(d));
212 result.replace('.', loc.decimalPoint());
217 bool SortLocaleAware(QString const & lhs, QString const & rhs)
219 return QString::localeAwareCompare(lhs, rhs) < 0;
223 bool ColorSorter(ColorCode lhs, ColorCode rhs)
225 return compare_no_case(lcolor.getGUIName(lhs), lcolor.getGUIName(rhs)) < 0;
229 void setValid(QWidget * widget, bool valid)
232 if (qobject_cast<QCheckBox*>(widget) != nullptr)
233 // Check boxes need to be treated differenty, see
234 // https://forum.qt.io/topic/93253/
235 widget->setStyleSheet("");
237 widget->setPalette(QPalette());
239 if (qobject_cast<QCheckBox*>(widget) != nullptr) {
240 // Check boxes need to be treated differenty, see
241 // https://forum.qt.io/topic/93253/
242 if (qobject_cast<QCheckBox*>(widget)->isChecked())
243 widget->setStyleSheet("QCheckBox:unchecked{ color: red; }QCheckBox:checked{ color: red; }");
245 QPalette pal = widget->palette();
246 pal.setColor(QPalette::Active, QPalette::WindowText, QColor(255, 0, 0));
247 pal.setColor(QPalette::Active, QPalette::Text, QColor(255, 0, 0));
248 widget->setPalette(pal);
254 void focusAndHighlight(QAbstractItemView * w)
257 w->setCurrentIndex(w->currentIndex());
258 w->scrollTo(w->currentIndex());
262 void setMessageColour(list<QWidget *> highlighted, list<QWidget *> plain)
264 QPalette pal = QApplication::palette();
265 QPalette newpal(pal.color(QPalette::Active, QPalette::HighlightedText),
266 pal.color(QPalette::Active, QPalette::Highlight));
267 for (QWidget * w : highlighted)
268 w->setPalette(newpal);
269 for (QWidget * w : plain)
274 void showDirectory(FileName const & directory)
276 if (!directory.exists())
278 QUrl qurl(QUrl::fromLocalFile(QDir::toNativeSeparators(toqstr(directory.absFileName()))));
279 // Give hints in case of bugs
280 if (!qurl.isValid()) {
281 frontend::Alert::error(_("Invalid URL"),
282 bformat(_("The URL `%1$s' could not be resolved."),
283 qstring_to_ucs4(qurl.toString())));
287 if (!QDesktopServices::openUrl(qurl))
288 frontend::Alert::error(_("URL could not be accessed"),
289 bformat(_("The URL `%1$s' could not be opened although it exists!"),
290 qstring_to_ucs4(qurl.toString())));
293 void showTarget(string const & target, string const & pdfv, string const & psv)
295 LYXERR(Debug::INSETS, "Showtarget:" << target << "\n");
296 if (prefixIs(target, "EXTERNAL ")) {
297 if (!lyxrc.citation_search)
299 string tmp, tar, opts;
300 tar = split(target, tmp, ' ');
302 opts = " -v " + pdfv;
304 opts += " -w " + psv;
308 string const command = lyxrc.citation_search_view + " " + opts + tar;
309 int const result = one.startscript(Systemcall::Wait, command);
312 frontend::Alert::error(_("Could not open file"),
313 _("The lyxpaperview script failed."));
314 else if (result == 2)
315 frontend::Alert::error(_("Could not open file"),
316 bformat(_("No file was found using the pattern `%1$s'."),
320 if (!QDesktopServices::openUrl(QUrl(toqstr(target), QUrl::TolerantMode)))
321 frontend::Alert::error(_("Could not open file"),
322 bformat(_("The target `%1$s' could not be resolved."),
325 } // namespace frontend
327 QString const qt_(char const * str, const char *)
329 return toqstr(_(str));
333 QString const qt_(string const & str)
335 return toqstr(_(str));
339 QString const qt_(QString const & qstr)
341 return toqstr(_(fromqstr(qstr)));
345 void rescanTexStyles(string const & arg)
347 // Run rescan in user lyx directory
348 PathChanger p(package().user_support());
349 FileName const prog = support::libFileSearch("scripts", "TeXFiles.py");
351 string const command = os::python() + ' ' +
352 quoteName(prog.toFilesystemEncoding()) + ' ' +
354 int const status = one.startscript(Systemcall::Wait, command);
358 frontend::Alert::error(_("Could not update TeX information"),
359 bformat(_("The script `%1$s' failed."), from_utf8(prog.absFileName())));
363 QStringList texFileList(QString const & filename)
366 FileName const file = libFileSearch(QString(), filename);
371 vector<docstring> doclist =
372 getVectorFromString(file.fileContents("UTF-8"), from_ascii("\n"));
374 // Normalise paths like /foo//bar ==> /foo/bar
376 for (size_t i = 0; i != doclist.size(); ++i) {
377 QString qfile = toqstr(doclist[i]);
378 qfile.replace("\r", "");
379 while (qfile.contains("//"))
380 qfile.replace("//", "/");
381 if (!qfile.isEmpty())
386 #if (QT_VERSION >= QT_VERSION_CHECK(5, 14, 0))
387 return QList<QString>(set.begin(), set.end());
389 return QList<QString>::fromSet(set);
393 QString const externalLineEnding(docstring const & str)
396 // The MAC clipboard uses \r for lineendings, and we use \n
397 return toqstr(subst(str, '\n', '\r'));
398 #elif defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
399 // Windows clipboard uses \r\n for lineendings, and we use \n
400 return toqstr(subst(str, from_ascii("\n"), from_ascii("\r\n")));
407 docstring const internalLineEnding(QString const & str)
409 docstring const s = subst(qstring_to_ucs4(str),
410 from_ascii("\r\n"), from_ascii("\n"));
411 return subst(s, '\r', '\n');
415 QString internalPath(const QString & str)
417 return toqstr(os::internal_path(fromqstr(str)));
421 QString onlyFileName(const QString & str)
423 return toqstr(support::onlyFileName(fromqstr(str)));
427 QString onlyPath(const QString & str)
429 return toqstr(support::onlyPath(fromqstr(str)));
433 QString changeExtension(QString const & oldname, QString const & ext)
435 return toqstr(support::changeExtension(fromqstr(oldname), fromqstr(ext)));
438 /// Remove the extension from \p name
439 QString removeExtension(QString const & name)
441 return toqstr(support::removeExtension(fromqstr(name)));
444 /** Add the extension \p ext to \p name.
445 Use this instead of changeExtension if you know that \p name is without
446 extension, because changeExtension would wrongly interpret \p name if it
449 QString addExtension(QString const & name, QString const & ext)
451 return toqstr(support::addExtension(fromqstr(name), fromqstr(ext)));
454 /// Return the extension of the file (not including the .)
455 QString getExtension(QString const & name)
457 return toqstr(support::getExtension(fromqstr(name)));
461 /** Convert relative path into absolute path based on a basepath.
462 If relpath is absolute, just use that.
463 If basepath doesn't exist use CWD.
465 QString makeAbsPath(QString const & relpath, QString const & base)
467 return toqstr(support::makeAbsPath(fromqstr(relpath),
468 fromqstr(base)).absFileName());
472 /////////////////////////////////////////////////////////////////////////
476 /////////////////////////////////////////////////////////////////////////
478 /** Given a string such as
479 * "<glob> <glob> ... *.{abc,def} <glob>",
480 * convert the csh-style brace expressions:
481 * "<glob> <glob> ... *.abc *.def <glob>".
482 * Requires no system support, so should work equally on Unix, Mac, Win32.
484 static string const convert_brace_glob(string const & glob)
486 // Matches " *.{abc,def,ghi}", storing "*." as group 1 and
487 // "abc,def,ghi" as group 2, while allowing spaces in group 2.
488 static regex const glob_re(" *([^ {]*)\\{([^}]+)\\}");
489 // Matches "abc" and "abc,", storing "abc" as group 1,
490 // while ignoring surrounding spaces.
491 static regex const block_re(" *([^ ,}]+) *,? *");
495 string::const_iterator it = glob.begin();
496 string::const_iterator const end = glob.end();
498 match_results<string::const_iterator> what;
499 if (!regex_search(it, end, what, glob_re)) {
500 // Ensure that no information is lost.
501 pattern += string(it, end);
505 // Everything from the start of the input to
506 // the start of the match.
507 pattern += string(what[-1].first, what[-1].second);
509 // Given " *.{abc,def}", head == "*." and tail == "abc,def".
510 string const head = string(what[1].first, what[1].second);
511 string const tail = string(what[2].first, what[2].second);
513 // Split the ','-separated chunks of tail so that
514 // $head{$chunk1,$chunk2} becomes "$head$chunk1 $head$chunk2".
515 string const fmt = " " + head + "$1";
516 pattern += regex_replace(tail, block_re, fmt);
518 // Increment the iterator to the end of the match.
519 it += distance(it, what[0].second);
528 /* \param description text describing the filters.
529 * \param one or more wildcard patterns, separated by
532 Filter(docstring const & description, std::string const & globs);
534 docstring const & description() const { return desc_; }
536 QString toString() const;
539 std::vector<std::string> globs_;
543 Filter::Filter(docstring const & description, string const & globs)
546 // Given "<glob> <glob> ... *.{abc,def} <glob>", expand to
547 // "<glob> <glob> ... *.abc *.def <glob>"
548 string const expanded_globs = convert_brace_glob(globs);
550 // Split into individual globs.
551 globs_ = getVectorFromString(expanded_globs, " ");
555 QString Filter::toString() const
559 bool const has_description = !desc_.empty();
561 if (has_description) {
566 s += toqstr(getStringFromVector(globs_, " "));
574 /** \c FileFilterList parses a Qt-style list of available file filters
575 * to generate the corresponding vector.
576 * For example "TeX documents (*.tex);;LyX Documents (*.lyx)"
577 * will be parsed to fill a vector of size 2, whilst "*.{p[bgp]m} *.pdf"
578 * will result in a vector of size 1 in which the description field is empty.
580 struct FileFilterList
582 // FIXME UNICODE: globs_ should be unicode...
583 /** \param qt_style_filter a list of available file filters.
584 * Eg. "TeX documents (*.tex);;LyX Documents (*.lyx)".
585 * The "All files (*)" filter is always added to the list.
587 explicit FileFilterList(docstring const & qt_style_filter =
590 typedef std::vector<Filter>::size_type size_type;
592 bool empty() const { return filters_.empty(); }
593 size_type size() const { return filters_.size(); }
594 Filter & operator[](size_type i) { return filters_[i]; }
595 Filter const & operator[](size_type i) const { return filters_[i]; }
597 void parse_filter(std::string const & filter);
598 std::vector<Filter> filters_;
602 FileFilterList::FileFilterList(docstring const & qt_style_filter)
605 string const filter = to_utf8(qt_style_filter)
606 + (qt_style_filter.empty() ? string() : ";;")
607 + to_utf8(_("All Files "))
614 // Split data such as "TeX documents (*.tex);;LyX Documents (*.lyx)"
615 // into individual filters.
616 static regex const separator_re(";;");
618 string::const_iterator it = filter.begin();
619 string::const_iterator const end = filter.end();
621 match_results<string::const_iterator> what;
623 if (!regex_search(it, end, what, separator_re)) {
624 parse_filter(string(it, end));
628 // Everything from the start of the input to
629 // the start of the match.
630 parse_filter(string(it, what[0].first));
632 // Increment the iterator to the end of the match.
633 it += distance(it, what[0].second);
638 void FileFilterList::parse_filter(string const & filter)
640 // Matches "TeX documents (plain) (*.tex)",
641 // storing "TeX documents (plain) " as group 1 and "*.tex" as group 2.
642 static regex const filter_re("(.*)\\(([^()]+)\\) *$");
644 match_results<string::const_iterator> what;
645 if (!regex_search(filter, what, filter_re)) {
646 // Just a glob, no description.
647 filters_.push_back(Filter(docstring(), trim(filter)));
650 docstring const desc = from_utf8(string(what[1].first, what[1].second));
651 string const globs = string(what[2].first, what[2].second);
652 filters_.push_back(Filter(trim(desc), trim(globs)));
657 /** \returns the equivalent of the string passed in
658 * although any brace expressions are expanded.
659 * (E.g. "*.{png,jpg}" -> "*.png *.jpg")
661 QStringList fileFilters(QString const & desc)
663 // we have: "*.{gif,png,jpg,bmp,pbm,ppm,tga,tif,xpm,xbm}"
664 // but need: "*.cpp;*.cc;*.C;*.cxx;*.c++"
665 FileFilterList filters(qstring_to_ucs4(desc));
666 //LYXERR0("DESC: " << desc);
668 for (size_t i = 0; i != filters.filters_.size(); ++i) {
669 QString f = filters.filters_[i].toString();
670 //LYXERR0("FILTER: " << f);
677 QString formatToolTip(QString text, int width)
679 // 1. QTooltip activates word wrapping only if mightBeRichText()
680 // is true. So we convert the text to rich text.
682 // 2. The default width is way too small. Setting the width is tricky; first
683 // one has to compute the ideal width, and then force it with special
686 // do nothing if empty or already formatted
687 if (text.isEmpty() || text.startsWith(QString("<html>")))
689 // Convert to rich text if it is not already
690 if (!Qt::mightBeRichText(text))
691 text = Qt::convertFromPlainText(text, Qt::WhiteSpaceNormal);
692 // Compute desired width in pixels
693 QFont const font = QToolTip::font();
694 #if (QT_VERSION >= QT_VERSION_CHECK(5, 11, 0))
695 int const px_width = width * QFontMetrics(font).horizontalAdvance("M");
697 int const px_width = width * QFontMetrics(font).width("M");
699 // Determine the ideal width of the tooltip
700 QTextDocument td("");
702 td.setDefaultFont(QToolTip::font());
703 td.setDocumentMargin(0);
704 td.setTextWidth(px_width);
705 double best_width = td.idealWidth();
706 // Set the line wrapping with appropriate width
707 return QString("<html><body><table><tr>"
708 "<td align=justify width=%1>%2</td>"
709 "</tr></table></body></html>")
710 .arg(QString::number(int(best_width) + 1), text);
714 QString qtHtmlToPlainText(QString const & text)
716 if (!Qt::mightBeRichText(text))
720 return td.toPlainText();