]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiPrefs.cpp
Account for old versions of Pygments
[lyx.git] / src / frontends / qt4 / GuiPrefs.cpp
1 /**
2  * \file GuiPrefs.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author John Levon
7  * \author Bo Peng
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "GuiPrefs.h"
15
16 #include "ColorCache.h"
17 #include "FileDialog.h"
18 #include "GuiApplication.h"
19 #include "GuiFontExample.h"
20 #include "GuiFontLoader.h"
21 #include "GuiKeySymbol.h"
22 #include "qt_helpers.h"
23 #include "Validator.h"
24
25 #include "Author.h"
26 #include "BufferList.h"
27 #include "Color.h"
28 #include "ColorSet.h"
29 #include "ConverterCache.h"
30 #include "FontEnums.h"
31 #include "FuncRequest.h"
32 #include "KeyMap.h"
33 #include "KeySequence.h"
34 #include "Language.h"
35 #include "LyXAction.h"
36 #include "LyX.h"
37 #include "PanelStack.h"
38 #include "Session.h"
39 #include "SpellChecker.h"
40
41 #include "support/debug.h"
42 #include "support/FileName.h"
43 #include "support/filetools.h"
44 #include "support/gettext.h"
45 #include "support/lassert.h"
46 #include "support/lstrings.h"
47 #include "support/Messages.h"
48 #include "support/os.h"
49 #include "support/Package.h"
50
51 #include "graphics/GraphicsTypes.h"
52
53 #include "frontends/alert.h"
54 #include "frontends/Application.h"
55 #include "frontends/FontLoader.h"
56
57 #include <QAbstractItemModel>
58 #include <QCheckBox>
59 #include <QColorDialog>
60 #include <QFontDatabase>
61 #include <QHeaderView>
62 #include <QLineEdit>
63 #include <QMessageBox>
64 #include <QPixmapCache>
65 #include <QPushButton>
66 #include <QSpinBox>
67 #include <QString>
68 #include <QTreeWidget>
69 #include <QTreeWidgetItem>
70 #include <QValidator>
71
72 #include <iomanip>
73 #include <sstream>
74 #include <algorithm>
75 #include <math.h>
76
77 using namespace Ui;
78
79 using namespace std;
80 using namespace lyx::support;
81 using namespace lyx::support::os;
82
83 namespace lyx {
84 namespace frontend {
85
86 /////////////////////////////////////////////////////////////////////
87 //
88 // Browser Helpers
89 //
90 /////////////////////////////////////////////////////////////////////
91
92 /** Launch a file dialog and return the chosen file.
93         filename: a suggested filename.
94         title: the title of the dialog.
95         filters: *.ps etc.
96         dir1 = (name, dir), dir2 = (name, dir): extra buttons on the dialog.
97 */
98 QString browseFile(QString const & filename,
99         QString const & title,
100         QStringList const & filters,
101         bool save = false,
102         QString const & label1 = QString(),
103         QString const & dir1 = QString(),
104         QString const & label2 = QString(),
105         QString const & dir2 = QString(),
106         QString const & fallback_dir = QString())
107 {
108         QString lastPath = ".";
109         if (!filename.isEmpty())
110                 lastPath = onlyPath(filename);
111         else if(!fallback_dir.isEmpty())
112                 lastPath = fallback_dir;
113
114         FileDialog dlg(title);
115         dlg.setButton2(label1, dir1);
116         dlg.setButton2(label2, dir2);
117
118         FileDialog::Result result;
119
120         if (save)
121                 result = dlg.save(lastPath, filters, onlyFileName(filename));
122         else
123                 result = dlg.open(lastPath, filters, onlyFileName(filename));
124
125         return result.second;
126 }
127
128
129 /** Wrapper around browseFile which tries to provide a filename
130 *  relative to the user or system directory. The dir, name and ext
131 *  parameters have the same meaning as in the
132 *  support::LibFileSearch function.
133 */
134 QString browseLibFile(QString const & dir,
135         QString const & name,
136         QString const & ext,
137         QString const & title,
138         QStringList const & filters)
139 {
140         // FIXME UNICODE
141         QString const label1 = qt_("System files|#S#s");
142         QString const dir1 =
143                 toqstr(addName(package().system_support().absFileName(), fromqstr(dir)));
144
145         QString const label2 = qt_("User files|#U#u");
146         QString const dir2 =
147                 toqstr(addName(package().user_support().absFileName(), fromqstr(dir)));
148
149         QString const result = browseFile(toqstr(
150                 libFileSearch(dir, name, ext).absFileName()),
151                 title, filters, false, dir1, dir2, QString(), QString(), dir1);
152
153         // remove the extension if it is the default one
154         QString noextresult;
155         if (getExtension(result) == ext)
156                 noextresult = removeExtension(result);
157         else
158                 noextresult = result;
159
160         // remove the directory, if it is the default one
161         QString const file = onlyFileName(noextresult);
162         if (toqstr(libFileSearch(dir, file, ext).absFileName()) == result)
163                 return file;
164         else
165                 return noextresult;
166 }
167
168
169 /** Launch a file dialog and return the chosen directory.
170         pathname: a suggested pathname.
171         title: the title of the dialog.
172         dir1 = (name, dir), dir2 = (name, dir): extra buttons on the dialog.
173 */
174 QString browseDir(QString const & pathname,
175         QString const & title,
176         QString const & label1 = QString(),
177         QString const & dir1 = QString(),
178         QString const & label2 = QString(),
179         QString const & dir2 = QString())
180 {
181         QString lastPath = ".";
182         if (!pathname.isEmpty())
183                 lastPath = onlyPath(pathname);
184
185         FileDialog dlg(title);
186         dlg.setButton1(label1, dir1);
187         dlg.setButton2(label2, dir2);
188
189         FileDialog::Result const result =
190                 dlg.opendir(lastPath, onlyFileName(pathname));
191
192         return result.second;
193 }
194
195
196 } // namespace frontend
197
198
199 QString browseRelToParent(QString const & filename, QString const & relpath,
200         QString const & title, QStringList const & filters, bool save,
201         QString const & label1, QString const & dir1,
202         QString const & label2, QString const & dir2)
203 {
204         QString const fname = makeAbsPath(filename, relpath);
205
206         QString const outname =
207                 frontend::browseFile(fname, title, filters, save, label1, dir1, label2, dir2);
208
209         QString const reloutname =
210                 toqstr(makeRelPath(qstring_to_ucs4(outname), qstring_to_ucs4(relpath)));
211
212         if (reloutname.startsWith("../"))
213                 return outname;
214         else
215                 return reloutname;
216 }
217
218
219 QString browseRelToSub(QString const & filename, QString const & relpath,
220         QString const & title, QStringList const & filters, bool save,
221         QString const & label1, QString const & dir1,
222         QString const & label2, QString const & dir2)
223 {
224         QString const fname = makeAbsPath(filename, relpath);
225
226         QString const outname =
227                 frontend::browseFile(fname, title, filters, save, label1, dir1, label2, dir2);
228
229         QString const reloutname =
230                 toqstr(makeRelPath(qstring_to_ucs4(outname), qstring_to_ucs4(relpath)));
231
232         QString testname = reloutname;
233         testname.remove(QRegExp("^(\\.\\./)+"));
234
235         if (testname.contains("/"))
236                 return outname;
237         else
238                 return reloutname;
239 }
240
241
242
243 /////////////////////////////////////////////////////////////////////
244 //
245 // Helpers
246 //
247 /////////////////////////////////////////////////////////////////////
248
249 namespace frontend {
250
251 QString const catLookAndFeel = N_("Look & Feel");
252 QString const catEditing = N_("Editing");
253 QString const catLanguage = N_("Language Settings");
254 QString const catOutput = N_("Output");
255 QString const catFiles = N_("File Handling");
256
257 static void parseFontName(QString const & mangled0,
258         string & name, string & foundry)
259 {
260         string mangled = fromqstr(mangled0);
261         size_t const idx = mangled.find('[');
262         if (idx == string::npos || idx == 0) {
263                 name = mangled;
264                 foundry.clear();
265         } else {
266                 name = mangled.substr(0, idx - 1),
267                 foundry = mangled.substr(idx + 1, mangled.size() - idx - 2);
268         }
269 }
270
271
272 static void setComboxFont(QComboBox * cb, string const & family,
273         string const & foundry)
274 {
275         QString fontname = toqstr(family);
276         if (!foundry.empty())
277                 fontname += " [" + toqstr(foundry) + ']';
278
279         for (int i = 0; i != cb->count(); ++i) {
280                 if (cb->itemText(i) == fontname) {
281                         cb->setCurrentIndex(i);
282                         return;
283                 }
284         }
285
286         // Try matching without foundry name
287
288         // We count in reverse in order to prefer the Xft foundry
289         for (int i = cb->count(); --i >= 0;) {
290                 string name, foundry;
291                 parseFontName(cb->itemText(i), name, foundry);
292                 if (compare_ascii_no_case(name, family) == 0) {
293                         cb->setCurrentIndex(i);
294                         return;
295                 }
296         }
297
298         // family alone can contain e.g. "Helvetica [Adobe]"
299         string tmpname, tmpfoundry;
300         parseFontName(toqstr(family), tmpname, tmpfoundry);
301
302         // We count in reverse in order to prefer the Xft foundry
303         for (int i = cb->count(); --i >= 0; ) {
304                 string name, foundry;
305                 parseFontName(cb->itemText(i), name, foundry);
306                 if (compare_ascii_no_case(name, foundry) == 0) {
307                         cb->setCurrentIndex(i);
308                         return;
309                 }
310         }
311
312         // Bleh, default fonts, and the names couldn't be found. Hack
313         // for bug 1063.
314
315         QFont font;
316
317         QString const font_family = toqstr(family);
318         if (font_family == guiApp->romanFontName()) {
319                 font.setStyleHint(QFont::Serif);
320                 font.setFamily(font_family);
321         } else if (font_family == guiApp->sansFontName()) {
322                 font.setStyleHint(QFont::SansSerif);
323                 font.setFamily(font_family);
324         } else if (font_family == guiApp->typewriterFontName()) {
325                 font.setStyleHint(QFont::TypeWriter);
326                 font.setFamily(font_family);
327         } else {
328                 LYXERR0("FAILED to find the default font: '"
329                        << foundry << "', '" << family << '\'');
330                 return;
331         }
332
333         QFontInfo info(font);
334         string default_font_name, dummyfoundry;
335         parseFontName(info.family(), default_font_name, dummyfoundry);
336         LYXERR0("Apparent font is " << default_font_name);
337
338         for (int i = 0; i < cb->count(); ++i) {
339                 LYXERR0("Looking at " << cb->itemText(i));
340                 if (compare_ascii_no_case(fromqstr(cb->itemText(i)),
341                                     default_font_name) == 0) {
342                         cb->setCurrentIndex(i);
343                         return;
344                 }
345         }
346
347         LYXERR0("FAILED to find the font: '"
348                << foundry << "', '" << family << '\'');
349 }
350
351
352 /////////////////////////////////////////////////////////////////////
353 //
354 // StrftimeValidator
355 //
356 /////////////////////////////////////////////////////////////////////
357
358 class StrftimeValidator : public QValidator
359 {
360 public:
361         StrftimeValidator(QWidget *);
362         QValidator::State validate(QString & input, int & pos) const;
363 };
364
365
366 StrftimeValidator::StrftimeValidator(QWidget * parent)
367         : QValidator(parent)
368 {
369 }
370
371
372 QValidator::State StrftimeValidator::validate(QString & input, int & /*pos*/) const
373 {
374         if (is_valid_strftime(fromqstr(input)))
375                 return QValidator::Acceptable;
376         else
377                 return QValidator::Intermediate;
378 }
379
380
381 /////////////////////////////////////////////////////////////////////
382 //
383 // PrefOutput
384 //
385 /////////////////////////////////////////////////////////////////////
386
387 PrefOutput::PrefOutput(GuiPreferences * form)
388         : PrefModule(catOutput, N_("General"), form)
389 {
390         setupUi(this);
391
392         DateED->setValidator(new StrftimeValidator(DateED));
393         dviCB->setValidator(new NoNewLineValidator(dviCB));
394         pdfCB->setValidator(new NoNewLineValidator(pdfCB));
395
396         connect(DateED, SIGNAL(textChanged(QString)),
397                 this, SIGNAL(changed()));
398         connect(plaintextLinelengthSB, SIGNAL(valueChanged(int)),
399                 this, SIGNAL(changed()));
400         connect(overwriteCO, SIGNAL(activated(int)),
401                 this, SIGNAL(changed()));
402         connect(dviCB, SIGNAL(editTextChanged(QString)),
403                 this, SIGNAL(changed()));
404         connect(pdfCB, SIGNAL(editTextChanged(QString)),
405                 this, SIGNAL(changed()));
406         connect(printerPaperTypeED, SIGNAL(textChanged(QString)),
407                 this, SIGNAL(changed()));
408         connect(printerLandscapeED, SIGNAL(textChanged(QString)),
409                 this, SIGNAL(changed()));
410         connect(printerPaperSizeED, SIGNAL(textChanged(QString)),
411                 this, SIGNAL(changed()));
412
413         printerPaperTypeED->setValidator(new NoNewLineValidator(printerPaperTypeED));
414         printerLandscapeED->setValidator(new NoNewLineValidator(printerLandscapeED));
415         printerPaperSizeED->setValidator(new NoNewLineValidator(printerPaperSizeED));
416
417         dviCB->addItem("");
418         dviCB->addItem("xdvi -sourceposition '$$n:\\ $$t' $$o");
419         dviCB->addItem("yap -1 -s \"$$n $$t\" $$o");
420         dviCB->addItem("okular --unique \"$$o#src:$$n $$f\"");
421         dviCB->addItem("synctex view -i $$n:0:$$t -o $$o -x \"evince -i %{page+1} $$o\"");
422         pdfCB->addItem("");
423         pdfCB->addItem("CMCDDE SUMATRA control [ForwardSearch(\\\"$$o\\\",\\\"$$t\\\",$$n,0,0,1)]");
424         pdfCB->addItem("SumatraPDF -reuse-instance \"$$o\" -forward-search \"$$t\" $$n");
425         pdfCB->addItem("synctex view -i $$n:0:$$t -o $$o -x \"xpdf -raise -remote $$t.tmp $$o %{page+1}\"");
426         pdfCB->addItem("okular --unique \"$$o#src:$$n $$f\"");
427         pdfCB->addItem("qpdfview --unique \"$$o#src:$$f:$$n:0\"");
428         pdfCB->addItem("synctex view -i $$n:0:$$t -o $$o -x \"evince -i %{page+1} $$o\"");
429         pdfCB->addItem("/Applications/Skim.app/Contents/SharedSupport/displayline $$n $$o $$t");
430 }
431
432
433 void PrefOutput::on_DateED_textChanged(const QString &)
434 {
435         QString t = DateED->text();
436         int p = 0;
437         bool valid = DateED->validator()->validate(t, p)
438                      == QValidator::Acceptable;
439         setValid(DateLA, valid);
440 }
441
442
443 void PrefOutput::applyRC(LyXRC & rc) const
444 {
445         rc.date_insert_format = fromqstr(DateED->text());
446         rc.plaintext_linelen = plaintextLinelengthSB->value();
447         rc.forward_search_dvi = fromqstr(dviCB->currentText());
448         rc.forward_search_pdf = fromqstr(pdfCB->currentText());
449
450         switch (overwriteCO->currentIndex()) {
451         case 0:
452                 rc.export_overwrite = NO_FILES;
453                 break;
454         case 1:
455                 rc.export_overwrite = MAIN_FILE;
456                 break;
457         case 2:
458                 rc.export_overwrite = ALL_FILES;
459                 break;
460         }
461
462         rc.print_paper_flag = fromqstr(printerPaperTypeED->text());
463         rc.print_landscape_flag = fromqstr(printerLandscapeED->text());
464         rc.print_paper_dimension_flag = fromqstr(printerPaperSizeED->text());
465 }
466
467
468 void PrefOutput::updateRC(LyXRC const & rc)
469 {
470         DateED->setText(toqstr(rc.date_insert_format));
471         plaintextLinelengthSB->setValue(rc.plaintext_linelen);
472         dviCB->setEditText(toqstr(rc.forward_search_dvi));
473         pdfCB->setEditText(toqstr(rc.forward_search_pdf));
474
475         switch (rc.export_overwrite) {
476         case NO_FILES:
477                 overwriteCO->setCurrentIndex(0);
478                 break;
479         case MAIN_FILE:
480                 overwriteCO->setCurrentIndex(1);
481                 break;
482         case ALL_FILES:
483                 overwriteCO->setCurrentIndex(2);
484                 break;
485         }
486
487         printerPaperTypeED->setText(toqstr(rc.print_paper_flag));
488         printerLandscapeED->setText(toqstr(rc.print_landscape_flag));
489         printerPaperSizeED->setText(toqstr(rc.print_paper_dimension_flag));
490 }
491
492
493 /////////////////////////////////////////////////////////////////////
494 //
495 // PrefInput
496 //
497 /////////////////////////////////////////////////////////////////////
498
499 PrefInput::PrefInput(GuiPreferences * form)
500         : PrefModule(catEditing, N_("Keyboard/Mouse"), form)
501 {
502         setupUi(this);
503
504         connect(keymapCB, SIGNAL(clicked()),
505                 this, SIGNAL(changed()));
506         connect(firstKeymapED, SIGNAL(textChanged(QString)),
507                 this, SIGNAL(changed()));
508         connect(secondKeymapED, SIGNAL(textChanged(QString)),
509                 this, SIGNAL(changed()));
510         connect(mouseWheelSpeedSB, SIGNAL(valueChanged(double)),
511                 this, SIGNAL(changed()));
512         connect(scrollzoomEnableCB, SIGNAL(clicked()),
513                 this, SIGNAL(changed()));
514         connect(scrollzoomValueCO, SIGNAL(activated(int)),
515                 this, SIGNAL(changed()));
516         connect(dontswapCB, SIGNAL(toggled(bool)),
517                 this, SIGNAL(changed()));
518         connect(mmPasteCB, SIGNAL(toggled(bool)),
519                 this, SIGNAL(changed()));
520
521         // reveal checkbox for switching Ctrl and Meta on Mac:
522         bool swapcb = false;
523 #ifdef Q_OS_MAC
524 #if QT_VERSION > 0x040600
525         swapcb = true;
526 #endif
527 #endif
528         dontswapCB->setVisible(swapcb);
529 }
530
531
532 void PrefInput::applyRC(LyXRC & rc) const
533 {
534         // FIXME: can derive CB from the two EDs
535         rc.use_kbmap = keymapCB->isChecked();
536         rc.primary_kbmap = internal_path(fromqstr(firstKeymapED->text()));
537         rc.secondary_kbmap = internal_path(fromqstr(secondKeymapED->text()));
538         rc.mouse_wheel_speed = mouseWheelSpeedSB->value();
539         if (scrollzoomEnableCB->isChecked()) {
540                 switch (scrollzoomValueCO->currentIndex()) {
541                 case 0:
542                         rc.scroll_wheel_zoom = LyXRC::SCROLL_WHEEL_ZOOM_CTRL;
543                         break;
544                 case 1:
545                         rc.scroll_wheel_zoom = LyXRC::SCROLL_WHEEL_ZOOM_SHIFT;
546                         break;
547                 case 2:
548                         rc.scroll_wheel_zoom = LyXRC::SCROLL_WHEEL_ZOOM_ALT;
549                         break;
550                 }
551         } else {
552                 rc.scroll_wheel_zoom = LyXRC::SCROLL_WHEEL_ZOOM_OFF;
553         }
554         rc.mac_dontswap_ctrl_meta  = dontswapCB->isChecked();
555         rc.mouse_middlebutton_paste = mmPasteCB->isChecked();
556 }
557
558
559 void PrefInput::updateRC(LyXRC const & rc)
560 {
561         // FIXME: can derive CB from the two EDs
562         keymapCB->setChecked(rc.use_kbmap);
563         firstKeymapED->setText(toqstr(external_path(rc.primary_kbmap)));
564         secondKeymapED->setText(toqstr(external_path(rc.secondary_kbmap)));
565         mouseWheelSpeedSB->setValue(rc.mouse_wheel_speed);
566         switch (rc.scroll_wheel_zoom) {
567         case LyXRC::SCROLL_WHEEL_ZOOM_OFF:
568                 scrollzoomEnableCB->setChecked(false);
569                 break;
570         case LyXRC::SCROLL_WHEEL_ZOOM_CTRL:
571                 scrollzoomEnableCB->setChecked(true);
572                 scrollzoomValueCO->setCurrentIndex(0);
573                 break;
574         case LyXRC::SCROLL_WHEEL_ZOOM_SHIFT:
575                 scrollzoomEnableCB->setChecked(true);
576                 scrollzoomValueCO->setCurrentIndex(1);
577                 break;
578         case LyXRC::SCROLL_WHEEL_ZOOM_ALT:
579                 scrollzoomEnableCB->setChecked(true);
580                 scrollzoomValueCO->setCurrentIndex(2);
581                 break;
582         }
583         dontswapCB->setChecked(rc.mac_dontswap_ctrl_meta);
584         mmPasteCB->setChecked(rc.mouse_middlebutton_paste);
585 }
586
587
588 QString PrefInput::testKeymap(QString const & keymap)
589 {
590         return form_->browsekbmap(internalPath(keymap));
591 }
592
593
594 void PrefInput::on_firstKeymapPB_clicked(bool)
595 {
596         QString const file = testKeymap(firstKeymapED->text());
597         if (!file.isEmpty())
598                 firstKeymapED->setText(file);
599 }
600
601
602 void PrefInput::on_secondKeymapPB_clicked(bool)
603 {
604         QString const file = testKeymap(secondKeymapED->text());
605         if (!file.isEmpty())
606                 secondKeymapED->setText(file);
607 }
608
609
610 void PrefInput::on_keymapCB_toggled(bool keymap)
611 {
612         firstKeymapLA->setEnabled(keymap);
613         secondKeymapLA->setEnabled(keymap);
614         firstKeymapED->setEnabled(keymap);
615         secondKeymapED->setEnabled(keymap);
616         firstKeymapPB->setEnabled(keymap);
617         secondKeymapPB->setEnabled(keymap);
618 }
619
620
621 void PrefInput::on_scrollzoomEnableCB_toggled(bool enabled)
622 {
623         scrollzoomValueCO->setEnabled(enabled);
624 }
625
626
627 /////////////////////////////////////////////////////////////////////
628 //
629 // PrefCompletion
630 //
631 /////////////////////////////////////////////////////////////////////
632
633 PrefCompletion::PrefCompletion(GuiPreferences * form)
634         : PrefModule(catEditing, N_("Input Completion"), form)
635 {
636         setupUi(this);
637
638         connect(inlineDelaySB, SIGNAL(valueChanged(double)),
639                 this, SIGNAL(changed()));
640         connect(inlineMathCB, SIGNAL(clicked()),
641                 this, SIGNAL(changed()));
642         connect(inlineTextCB, SIGNAL(clicked()),
643                 this, SIGNAL(changed()));
644         connect(inlineDotsCB, SIGNAL(clicked()),
645                 this, SIGNAL(changed()));
646         connect(popupDelaySB, SIGNAL(valueChanged(double)),
647                 this, SIGNAL(changed()));
648         connect(popupMathCB, SIGNAL(clicked()),
649                 this, SIGNAL(changed()));
650         connect(autocorrectionCB, SIGNAL(clicked()),
651                 this, SIGNAL(changed()));
652         connect(popupTextCB, SIGNAL(clicked()),
653                 this, SIGNAL(changed()));
654         connect(popupAfterCompleteCB, SIGNAL(clicked()),
655                 this, SIGNAL(changed()));
656         connect(cursorTextCB, SIGNAL(clicked()),
657                 this, SIGNAL(changed()));
658         connect(minlengthSB, SIGNAL(valueChanged(int)),
659                         this, SIGNAL(changed()));
660 }
661
662
663 void PrefCompletion::on_inlineTextCB_clicked()
664 {
665         enableCB();
666 }
667
668
669 void PrefCompletion::on_popupTextCB_clicked()
670 {
671         enableCB();
672 }
673
674
675 void PrefCompletion::enableCB()
676 {
677         cursorTextCB->setEnabled(
678                 popupTextCB->isChecked() || inlineTextCB->isChecked());
679 }
680
681
682 void PrefCompletion::applyRC(LyXRC & rc) const
683 {
684         rc.completion_inline_delay = inlineDelaySB->value();
685         rc.completion_inline_math = inlineMathCB->isChecked();
686         rc.completion_inline_text = inlineTextCB->isChecked();
687         rc.completion_inline_dots = inlineDotsCB->isChecked() ? 13 : -1;
688         rc.completion_popup_delay = popupDelaySB->value();
689         rc.completion_popup_math = popupMathCB->isChecked();
690         rc.autocorrection_math = autocorrectionCB->isChecked();
691         rc.completion_popup_text = popupTextCB->isChecked();
692         rc.completion_cursor_text = cursorTextCB->isChecked();
693         rc.completion_popup_after_complete =
694                 popupAfterCompleteCB->isChecked();
695         rc.completion_minlength = minlengthSB->value();
696 }
697
698
699 void PrefCompletion::updateRC(LyXRC const & rc)
700 {
701         inlineDelaySB->setValue(rc.completion_inline_delay);
702         inlineMathCB->setChecked(rc.completion_inline_math);
703         inlineTextCB->setChecked(rc.completion_inline_text);
704         inlineDotsCB->setChecked(rc.completion_inline_dots != -1);
705         popupDelaySB->setValue(rc.completion_popup_delay);
706         popupMathCB->setChecked(rc.completion_popup_math);
707         autocorrectionCB->setChecked(rc.autocorrection_math);
708         popupTextCB->setChecked(rc.completion_popup_text);
709         cursorTextCB->setChecked(rc.completion_cursor_text);
710         popupAfterCompleteCB->setChecked(rc.completion_popup_after_complete);
711         enableCB();
712         minlengthSB->setValue(rc.completion_minlength);
713 }
714
715
716
717 /////////////////////////////////////////////////////////////////////
718 //
719 // PrefLatex
720 //
721 /////////////////////////////////////////////////////////////////////
722
723 PrefLatex::PrefLatex(GuiPreferences * form)
724         : PrefModule(catOutput, N_("LaTeX"), form)
725 {
726         setupUi(this);
727
728         latexEncodingED->setValidator(new NoNewLineValidator(latexEncodingED));
729         latexDviPaperED->setValidator(new NoNewLineValidator(latexDviPaperED));
730         latexBibtexED->setValidator(new NoNewLineValidator(latexBibtexED));
731         latexJBibtexED->setValidator(new NoNewLineValidator(latexJBibtexED));
732         latexIndexED->setValidator(new NoNewLineValidator(latexIndexED));
733         latexJIndexED->setValidator(new NoNewLineValidator(latexJIndexED));
734         latexNomenclED->setValidator(new NoNewLineValidator(latexNomenclED));
735         latexChecktexED->setValidator(new NoNewLineValidator(latexChecktexED));
736
737         connect(latexEncodingCB, SIGNAL(clicked()),
738                 this, SIGNAL(changed()));
739         connect(latexEncodingED, SIGNAL(textChanged(QString)),
740                 this, SIGNAL(changed()));
741         connect(latexChecktexED, SIGNAL(textChanged(QString)),
742                 this, SIGNAL(changed()));
743         connect(latexBibtexCO, SIGNAL(activated(int)),
744                 this, SIGNAL(changed()));
745         connect(latexBibtexED, SIGNAL(textChanged(QString)),
746                 this, SIGNAL(changed()));
747         connect(latexJBibtexCO, SIGNAL(activated(int)),
748                 this, SIGNAL(changed()));
749         connect(latexJBibtexED, SIGNAL(textChanged(QString)),
750                 this, SIGNAL(changed()));
751         connect(latexIndexCO, SIGNAL(activated(int)),
752                 this, SIGNAL(changed()));
753         connect(latexIndexED, SIGNAL(textChanged(QString)),
754                 this, SIGNAL(changed()));
755         connect(latexJIndexED, SIGNAL(textChanged(QString)),
756                 this, SIGNAL(changed()));
757         connect(latexAutoresetCB, SIGNAL(clicked()),
758                 this, SIGNAL(changed()));
759         connect(latexDviPaperED, SIGNAL(textChanged(QString)),
760                 this, SIGNAL(changed()));
761         connect(latexNomenclED, SIGNAL(textChanged(QString)),
762                 this, SIGNAL(changed()));
763
764 #if defined(__CYGWIN__) || defined(_WIN32)
765         pathCB->setVisible(true);
766         connect(pathCB, SIGNAL(clicked()),
767                 this, SIGNAL(changed()));
768 #else
769         pathCB->setVisible(false);
770 #endif
771 }
772
773
774 void PrefLatex::on_latexEncodingCB_stateChanged(int state)
775 {
776         latexEncodingED->setEnabled(state == Qt::Checked);
777 }
778
779
780 void PrefLatex::on_latexBibtexCO_activated(int n)
781 {
782         QString const bibtex = latexBibtexCO->itemData(n).toString();
783         if (bibtex.isEmpty()) {
784                 latexBibtexED->clear();
785                 latexBibtexOptionsLA->setText(qt_("C&ommand:"));
786                 return;
787         }
788         for (LyXRC::CommandSet::const_iterator it = bibtex_alternatives.begin();
789              it != bibtex_alternatives.end(); ++it) {
790                 QString const bib = toqstr(*it);
791                 int ind = bib.indexOf(" ");
792                 QString sel_command = bib.left(ind);
793                 QString sel_options = ind < 0 ? QString() : bib.mid(ind + 1);
794                 if (bibtex == sel_command) {
795                         if (ind < 0)
796                                 latexBibtexED->clear();
797                         else
798                                 latexBibtexED->setText(sel_options.trimmed());
799                 }
800         }
801         latexBibtexOptionsLA->setText(qt_("&Options:"));
802 }
803
804
805 void PrefLatex::on_latexJBibtexCO_activated(int n)
806 {
807         QString const jbibtex = latexJBibtexCO->itemData(n).toString();
808         if (jbibtex.isEmpty()) {
809                 latexJBibtexED->clear();
810                 latexJBibtexOptionsLA->setText(qt_("Co&mmand:"));
811                 return;
812         }
813         for (LyXRC::CommandSet::const_iterator it = jbibtex_alternatives.begin();
814              it != jbibtex_alternatives.end(); ++it) {
815                 QString const bib = toqstr(*it);
816                 int ind = bib.indexOf(" ");
817                 QString sel_command = bib.left(ind);
818                 QString sel_options = ind < 0 ? QString() : bib.mid(ind + 1);
819                 if (jbibtex == sel_command) {
820                         if (ind < 0)
821                                 latexJBibtexED->clear();
822                         else
823                                 latexJBibtexED->setText(sel_options.trimmed());
824                 }
825         }
826         latexJBibtexOptionsLA->setText(qt_("Opt&ions:"));
827 }
828
829
830 void PrefLatex::on_latexIndexCO_activated(int n)
831 {
832         QString const index = latexIndexCO->itemData(n).toString();
833         if (index.isEmpty()) {
834                 latexIndexED->clear();
835                 latexIndexOptionsLA->setText(qt_("Co&mmand:"));
836                 return;
837         }
838         for (LyXRC::CommandSet::const_iterator it = index_alternatives.begin();
839              it != index_alternatives.end(); ++it) {
840                 QString const idx = toqstr(*it);
841                 int ind = idx.indexOf(" ");
842                 QString sel_command = idx.left(ind);
843                 QString sel_options = ind < 0 ? QString() : idx.mid(ind + 1);
844                 if (index == sel_command) {
845                         if (ind < 0)
846                                 latexIndexED->clear();
847                         else
848                                 latexIndexED->setText(sel_options.trimmed());
849                 }
850         }
851         latexIndexOptionsLA->setText(qt_("Op&tions:"));
852 }
853
854
855 void PrefLatex::applyRC(LyXRC & rc) const
856 {
857         // If bibtex is not empty, bibopt contains the options, otherwise
858         // it is a customized bibtex command with options.
859         QString const bibtex = latexBibtexCO->itemData(
860                 latexBibtexCO->currentIndex()).toString();
861         QString const bibopt = latexBibtexED->text();
862         if (bibtex.isEmpty())
863                 rc.bibtex_command = fromqstr(bibopt);
864         else if (bibopt.isEmpty())
865                 rc.bibtex_command = fromqstr(bibtex);
866         else
867                 rc.bibtex_command = fromqstr(bibtex) + " " + fromqstr(bibopt);
868
869         // If jbibtex is not empty, jbibopt contains the options, otherwise
870         // it is a customized bibtex command with options.
871         QString const jbibtex = latexJBibtexCO->itemData(
872                 latexJBibtexCO->currentIndex()).toString();
873         QString const jbibopt = latexJBibtexED->text();
874         if (jbibtex.isEmpty())
875                 rc.jbibtex_command = fromqstr(jbibopt);
876         else if (jbibopt.isEmpty())
877                 rc.jbibtex_command = fromqstr(jbibtex);
878         else
879                 rc.jbibtex_command = fromqstr(jbibtex) + " " + fromqstr(jbibopt);
880
881         // If index is not empty, idxopt contains the options, otherwise
882         // it is a customized index command with options.
883         QString const index = latexIndexCO->itemData(
884                 latexIndexCO->currentIndex()).toString();
885         QString const idxopt = latexIndexED->text();
886         if (index.isEmpty())
887                 rc.index_command = fromqstr(idxopt);
888         else if (idxopt.isEmpty())
889                 rc.index_command = fromqstr(index);
890         else
891                 rc.index_command = fromqstr(index) + " " + fromqstr(idxopt);
892
893         if (latexEncodingCB->isChecked())
894                 rc.fontenc = fromqstr(latexEncodingED->text());
895         else
896                 rc.fontenc = "default";
897         rc.chktex_command = fromqstr(latexChecktexED->text());
898         rc.jindex_command = fromqstr(latexJIndexED->text());
899         rc.nomencl_command = fromqstr(latexNomenclED->text());
900         rc.auto_reset_options = latexAutoresetCB->isChecked();
901         rc.view_dvi_paper_option = fromqstr(latexDviPaperED->text());
902 #if defined(__CYGWIN__) || defined(_WIN32)
903         rc.windows_style_tex_paths = pathCB->isChecked();
904 #endif
905 }
906
907
908 void PrefLatex::updateRC(LyXRC const & rc)
909 {
910         latexBibtexCO->clear();
911
912         latexBibtexCO->addItem(qt_("Automatic"), "automatic");
913         latexBibtexCO->addItem(qt_("Custom"), QString());
914         for (LyXRC::CommandSet::const_iterator it = rc.bibtex_alternatives.begin();
915                              it != rc.bibtex_alternatives.end(); ++it) {
916                 QString const command = toqstr(*it).left(toqstr(*it).indexOf(" "));
917                 latexBibtexCO->addItem(command, command);
918         }
919
920         bibtex_alternatives = rc.bibtex_alternatives;
921
922         QString const bib = toqstr(rc.bibtex_command);
923         int ind = bib.indexOf(" ");
924         QString sel_command = bib.left(ind);
925         QString sel_options = ind < 0 ? QString() : bib.mid(ind + 1);
926
927         int pos = latexBibtexCO->findData(sel_command);
928         if (pos != -1) {
929                 latexBibtexCO->setCurrentIndex(pos);
930                 latexBibtexED->setText(sel_options.trimmed());
931                 latexBibtexOptionsLA->setText(qt_("&Options:"));
932         } else {
933                 latexBibtexED->setText(toqstr(rc.bibtex_command));
934                 latexBibtexCO->setCurrentIndex(0);
935                 latexBibtexOptionsLA->setText(qt_("C&ommand:"));
936         }
937
938         latexJBibtexCO->clear();
939
940         latexJBibtexCO->addItem(qt_("Automatic"), "automatic");
941         latexJBibtexCO->addItem(qt_("Custom"), QString());
942         for (LyXRC::CommandSet::const_iterator it = rc.jbibtex_alternatives.begin();
943                              it != rc.jbibtex_alternatives.end(); ++it) {
944                 QString const command = toqstr(*it).left(toqstr(*it).indexOf(" "));
945                 latexJBibtexCO->addItem(command, command);
946         }
947
948         jbibtex_alternatives = rc.jbibtex_alternatives;
949
950         QString const jbib = toqstr(rc.jbibtex_command);
951         ind = jbib.indexOf(" ");
952         sel_command = jbib.left(ind);
953         sel_options = ind < 0 ? QString() : jbib.mid(ind + 1);
954
955         pos = latexJBibtexCO->findData(sel_command);
956         if (pos != -1) {
957                 latexJBibtexCO->setCurrentIndex(pos);
958                 latexJBibtexED->setText(sel_options.trimmed());
959                 latexJBibtexOptionsLA->setText(qt_("Opt&ions:"));
960         } else {
961                 latexJBibtexED->setText(toqstr(rc.bibtex_command));
962                 latexJBibtexCO->setCurrentIndex(0);
963                 latexJBibtexOptionsLA->setText(qt_("Co&mmand:"));
964         }
965
966         latexIndexCO->clear();
967
968         latexIndexCO->addItem(qt_("Custom"), QString());
969         for (LyXRC::CommandSet::const_iterator it = rc.index_alternatives.begin();
970                              it != rc.index_alternatives.end(); ++it) {
971                 QString const command = toqstr(*it).left(toqstr(*it).indexOf(" "));
972                 latexIndexCO->addItem(command, command);
973         }
974
975         index_alternatives = rc.index_alternatives;
976
977         QString const idx = toqstr(rc.index_command);
978         ind = idx.indexOf(" ");
979         sel_command = idx.left(ind);
980         sel_options = ind < 0 ? QString() : idx.mid(ind + 1);
981
982         pos = latexIndexCO->findData(sel_command);
983         if (pos != -1) {
984                 latexIndexCO->setCurrentIndex(pos);
985                 latexIndexED->setText(sel_options.trimmed());
986                 latexIndexOptionsLA->setText(qt_("Op&tions:"));
987         } else {
988                 latexIndexED->setText(toqstr(rc.index_command));
989                 latexIndexCO->setCurrentIndex(0);
990                 latexIndexOptionsLA->setText(qt_("Co&mmand:"));
991         }
992
993         if (rc.fontenc == "default") {
994                 latexEncodingCB->setChecked(false);
995                 latexEncodingED->setEnabled(false);
996         } else {
997                 latexEncodingCB->setChecked(true);
998                 latexEncodingED->setEnabled(true);
999                 latexEncodingED->setText(toqstr(rc.fontenc));
1000         }
1001         latexChecktexED->setText(toqstr(rc.chktex_command));
1002         latexJIndexED->setText(toqstr(rc.jindex_command));
1003         latexNomenclED->setText(toqstr(rc.nomencl_command));
1004         latexAutoresetCB->setChecked(rc.auto_reset_options);
1005         latexDviPaperED->setText(toqstr(rc.view_dvi_paper_option));
1006 #if defined(__CYGWIN__) || defined(_WIN32)
1007         pathCB->setChecked(rc.windows_style_tex_paths);
1008 #endif
1009 }
1010
1011
1012 /////////////////////////////////////////////////////////////////////
1013 //
1014 // PrefScreenFonts
1015 //
1016 /////////////////////////////////////////////////////////////////////
1017
1018 PrefScreenFonts::PrefScreenFonts(GuiPreferences * form)
1019         : PrefModule(catLookAndFeel, N_("Screen Fonts"), form)
1020 {
1021         setupUi(this);
1022
1023         connect(screenRomanCO, SIGNAL(activated(QString)),
1024                 this, SLOT(selectRoman(QString)));
1025         connect(screenSansCO, SIGNAL(activated(QString)),
1026                 this, SLOT(selectSans(QString)));
1027         connect(screenTypewriterCO, SIGNAL(activated(QString)),
1028                 this, SLOT(selectTypewriter(QString)));
1029
1030         QFontDatabase fontdb;
1031         QStringList families(fontdb.families());
1032         for (QStringList::Iterator it = families.begin(); it != families.end(); ++it) {
1033                 screenRomanCO->addItem(*it);
1034                 screenSansCO->addItem(*it);
1035                 screenTypewriterCO->addItem(*it);
1036         }
1037         connect(screenRomanCO, SIGNAL(activated(QString)),
1038                 this, SIGNAL(changed()));
1039         connect(screenSansCO, SIGNAL(activated(QString)),
1040                 this, SIGNAL(changed()));
1041         connect(screenTypewriterCO, SIGNAL(activated(QString)),
1042                 this, SIGNAL(changed()));
1043         connect(screenZoomSB, SIGNAL(valueChanged(int)),
1044                 this, SIGNAL(changed()));
1045         connect(screenTinyED, SIGNAL(textChanged(QString)),
1046                 this, SIGNAL(changed()));
1047         connect(screenSmallestED, SIGNAL(textChanged(QString)),
1048                 this, SIGNAL(changed()));
1049         connect(screenSmallerED, SIGNAL(textChanged(QString)),
1050                 this, SIGNAL(changed()));
1051         connect(screenSmallED, SIGNAL(textChanged(QString)),
1052                 this, SIGNAL(changed()));
1053         connect(screenNormalED, SIGNAL(textChanged(QString)),
1054                 this, SIGNAL(changed()));
1055         connect(screenLargeED, SIGNAL(textChanged(QString)),
1056                 this, SIGNAL(changed()));
1057         connect(screenLargerED, SIGNAL(textChanged(QString)),
1058                 this, SIGNAL(changed()));
1059         connect(screenLargestED, SIGNAL(textChanged(QString)),
1060                 this, SIGNAL(changed()));
1061         connect(screenHugeED, SIGNAL(textChanged(QString)),
1062                 this, SIGNAL(changed()));
1063         connect(screenHugerED, SIGNAL(textChanged(QString)),
1064                 this, SIGNAL(changed()));
1065         connect(pixmapCacheCB, SIGNAL(toggled(bool)),
1066                 this, SIGNAL(changed()));
1067
1068         screenTinyED->setValidator(new QDoubleValidator(screenTinyED));
1069         screenSmallestED->setValidator(new QDoubleValidator(screenSmallestED));
1070         screenSmallerED->setValidator(new QDoubleValidator(screenSmallerED));
1071         screenSmallED->setValidator(new QDoubleValidator(screenSmallED));
1072         screenNormalED->setValidator(new QDoubleValidator(screenNormalED));
1073         screenLargeED->setValidator(new QDoubleValidator(screenLargeED));
1074         screenLargerED->setValidator(new QDoubleValidator(screenLargerED));
1075         screenLargestED->setValidator(new QDoubleValidator(screenLargestED));
1076         screenHugeED->setValidator(new QDoubleValidator(screenHugeED));
1077         screenHugerED->setValidator(new QDoubleValidator(screenHugerED));
1078 }
1079
1080
1081 void PrefScreenFonts::applyRC(LyXRC & rc) const
1082 {
1083         LyXRC const oldrc = rc;
1084
1085         parseFontName(screenRomanCO->currentText(),
1086                 rc.roman_font_name, rc.roman_font_foundry);
1087         parseFontName(screenSansCO->currentText(),
1088                 rc.sans_font_name, rc.sans_font_foundry);
1089         parseFontName(screenTypewriterCO->currentText(),
1090                 rc.typewriter_font_name, rc.typewriter_font_foundry);
1091
1092         rc.zoom = screenZoomSB->value();
1093         rc.font_sizes[FONT_SIZE_TINY] = widgetToDoubleStr(screenTinyED);
1094         rc.font_sizes[FONT_SIZE_SCRIPT] = widgetToDoubleStr(screenSmallestED);
1095         rc.font_sizes[FONT_SIZE_FOOTNOTE] = widgetToDoubleStr(screenSmallerED);
1096         rc.font_sizes[FONT_SIZE_SMALL] = widgetToDoubleStr(screenSmallED);
1097         rc.font_sizes[FONT_SIZE_NORMAL] = widgetToDoubleStr(screenNormalED);
1098         rc.font_sizes[FONT_SIZE_LARGE] = widgetToDoubleStr(screenLargeED);
1099         rc.font_sizes[FONT_SIZE_LARGER] = widgetToDoubleStr(screenLargerED);
1100         rc.font_sizes[FONT_SIZE_LARGEST] = widgetToDoubleStr(screenLargestED);
1101         rc.font_sizes[FONT_SIZE_HUGE] = widgetToDoubleStr(screenHugeED);
1102         rc.font_sizes[FONT_SIZE_HUGER] = widgetToDoubleStr(screenHugerED);
1103         rc.use_pixmap_cache = pixmapCacheCB->isChecked();
1104
1105         if (rc.font_sizes != oldrc.font_sizes
1106                 || rc.roman_font_name != oldrc.roman_font_name
1107                 || rc.sans_font_name != oldrc.sans_font_name
1108                 || rc.typewriter_font_name != oldrc.typewriter_font_name
1109                 || rc.zoom != oldrc.zoom) {
1110                 // The global QPixmapCache is used in GuiPainter to cache text
1111                 // painting so we must reset it in case any of the above
1112                 // parameter is changed.
1113                 QPixmapCache::clear();
1114                 guiApp->fontLoader().update();
1115                 form_->updateScreenFonts();
1116         }
1117 }
1118
1119
1120 void PrefScreenFonts::updateRC(LyXRC const & rc)
1121 {
1122         setComboxFont(screenRomanCO, rc.roman_font_name,
1123                         rc.roman_font_foundry);
1124         setComboxFont(screenSansCO, rc.sans_font_name,
1125                         rc.sans_font_foundry);
1126         setComboxFont(screenTypewriterCO, rc.typewriter_font_name,
1127                         rc.typewriter_font_foundry);
1128
1129         selectRoman(screenRomanCO->currentText());
1130         selectSans(screenSansCO->currentText());
1131         selectTypewriter(screenTypewriterCO->currentText());
1132
1133         screenZoomSB->setValue(rc.zoom);
1134         updateScreenFontSizes(rc);
1135
1136         pixmapCacheCB->setChecked(rc.use_pixmap_cache);
1137 #if defined(Q_WS_X11) || defined(QPA_XCB)
1138         pixmapCacheCB->setEnabled(false);
1139 #endif
1140
1141 }
1142
1143
1144 void PrefScreenFonts::updateScreenFontSizes(LyXRC const & rc)
1145 {
1146         doubleToWidget(screenTinyED, rc.font_sizes[FONT_SIZE_TINY]);
1147         doubleToWidget(screenSmallestED, rc.font_sizes[FONT_SIZE_SCRIPT]);
1148         doubleToWidget(screenSmallerED, rc.font_sizes[FONT_SIZE_FOOTNOTE]);
1149         doubleToWidget(screenSmallED, rc.font_sizes[FONT_SIZE_SMALL]);
1150         doubleToWidget(screenNormalED, rc.font_sizes[FONT_SIZE_NORMAL]);
1151         doubleToWidget(screenLargeED, rc.font_sizes[FONT_SIZE_LARGE]);
1152         doubleToWidget(screenLargerED, rc.font_sizes[FONT_SIZE_LARGER]);
1153         doubleToWidget(screenLargestED, rc.font_sizes[FONT_SIZE_LARGEST]);
1154         doubleToWidget(screenHugeED, rc.font_sizes[FONT_SIZE_HUGE]);
1155         doubleToWidget(screenHugerED, rc.font_sizes[FONT_SIZE_HUGER]);
1156 }
1157
1158
1159 void PrefScreenFonts::selectRoman(const QString & name)
1160 {
1161         screenRomanFE->set(QFont(name), name);
1162 }
1163
1164
1165 void PrefScreenFonts::selectSans(const QString & name)
1166 {
1167         screenSansFE->set(QFont(name), name);
1168 }
1169
1170
1171 void PrefScreenFonts::selectTypewriter(const QString & name)
1172 {
1173         screenTypewriterFE->set(QFont(name), name);
1174 }
1175
1176
1177 /////////////////////////////////////////////////////////////////////
1178 //
1179 // PrefColors
1180 //
1181 /////////////////////////////////////////////////////////////////////
1182
1183
1184 PrefColors::PrefColors(GuiPreferences * form)
1185         : PrefModule(catLookAndFeel, N_("Colors"), form)
1186 {
1187         setupUi(this);
1188
1189         // FIXME: all of this initialization should be put into the controller.
1190         // See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg113301.html
1191         // for some discussion of why that is not trivial.
1192         QPixmap icon(32, 32);
1193         for (int i = 0; i < Color_ignore; ++i) {
1194                 ColorCode lc = static_cast<ColorCode>(i);
1195                 if (lc == Color_none
1196                     || lc == Color_black
1197                     || lc == Color_white
1198                     || lc == Color_blue
1199                     || lc == Color_brown
1200                     || lc == Color_cyan
1201                     || lc == Color_darkgray
1202                     || lc == Color_gray
1203                     || lc == Color_green
1204                     || lc == Color_lightgray
1205                     || lc == Color_lime
1206                     || lc == Color_magenta
1207                     || lc == Color_olive
1208                     || lc == Color_orange
1209                     || lc == Color_pink
1210                     || lc == Color_purple
1211                     || lc == Color_red
1212                     || lc == Color_teal
1213                     || lc == Color_violet
1214                     || lc == Color_yellow
1215                     || lc == Color_inherit
1216                     || lc == Color_ignore)
1217                         continue;
1218                 lcolors_.push_back(lc);
1219         }
1220         qSort(lcolors_.begin(), lcolors_.end(), ColorSorter);
1221         vector<ColorCode>::const_iterator cit = lcolors_.begin();
1222         vector<ColorCode>::const_iterator const end = lcolors_.end();
1223         for (; cit != end; ++cit) {
1224                 (void) new QListWidgetItem(QIcon(icon),
1225                         toqstr(lcolor.getGUIName(*cit)), lyxObjectsLW);
1226         }
1227         curcolors_.resize(lcolors_.size());
1228         newcolors_.resize(lcolors_.size());
1229         // End initialization
1230
1231         connect(colorChangePB, SIGNAL(clicked()),
1232                 this, SLOT(changeColor()));
1233         connect(lyxObjectsLW, SIGNAL(itemSelectionChanged()),
1234                 this, SLOT(changeLyxObjectsSelection()));
1235         connect(lyxObjectsLW, SIGNAL(itemActivated(QListWidgetItem*)),
1236                 this, SLOT(changeColor()));
1237         connect(syscolorsCB, SIGNAL(toggled(bool)),
1238                 this, SIGNAL(changed()));
1239         connect(syscolorsCB, SIGNAL(toggled(bool)),
1240                 this, SLOT(changeSysColor()));
1241 }
1242
1243
1244 void PrefColors::applyRC(LyXRC & rc) const
1245 {
1246         LyXRC oldrc = rc;
1247
1248         for (unsigned int i = 0; i < lcolors_.size(); ++i)
1249                 if (curcolors_[i] != newcolors_[i])
1250                         form_->setColor(lcolors_[i], newcolors_[i]);
1251         rc.use_system_colors = syscolorsCB->isChecked();
1252
1253         if (oldrc.use_system_colors != rc.use_system_colors)
1254                 guiApp->colorCache().clear();
1255 }
1256
1257
1258 void PrefColors::updateRC(LyXRC const & rc)
1259 {
1260         for (unsigned int i = 0; i < lcolors_.size(); ++i) {
1261                 QColor color = QColor(guiApp->colorCache().get(lcolors_[i], false));
1262                 QPixmap coloritem(32, 32);
1263                 coloritem.fill(color);
1264                 lyxObjectsLW->item(i)->setIcon(QIcon(coloritem));
1265                 newcolors_[i] = curcolors_[i] = color.name();
1266         }
1267         syscolorsCB->setChecked(rc.use_system_colors);
1268         changeLyxObjectsSelection();
1269 }
1270
1271
1272 void PrefColors::changeColor()
1273 {
1274         int const row = lyxObjectsLW->currentRow();
1275
1276         // just to be sure
1277         if (row < 0)
1278                 return;
1279
1280         QString const color = newcolors_[row];
1281         QColor c = QColorDialog::getColor(QColor(color), qApp->focusWidget());
1282
1283         if (c.isValid() && c.name() != color) {
1284                 newcolors_[row] = c.name();
1285                 QPixmap coloritem(32, 32);
1286                 coloritem.fill(c);
1287                 lyxObjectsLW->currentItem()->setIcon(QIcon(coloritem));
1288                 // emit signal
1289                 changed();
1290         }
1291 }
1292
1293 void PrefColors::changeSysColor()
1294 {
1295         for (int row = 0 ; row < lyxObjectsLW->count() ; ++row) {
1296                 // skip colors that are taken from system palette
1297                 bool const disable = syscolorsCB->isChecked()
1298                         && guiApp->colorCache().isSystem(lcolors_[row]);
1299
1300                 QListWidgetItem * const item = lyxObjectsLW->item(row);
1301                 Qt::ItemFlags const flags = item->flags();
1302
1303                 if (disable)
1304                         item->setFlags(flags & ~Qt::ItemIsEnabled);
1305                 else
1306                         item->setFlags(flags | Qt::ItemIsEnabled);
1307         }
1308 }
1309
1310 void PrefColors::changeLyxObjectsSelection()
1311 {
1312         colorChangePB->setDisabled(lyxObjectsLW->currentRow() < 0);
1313 }
1314
1315
1316 /////////////////////////////////////////////////////////////////////
1317 //
1318 // PrefDisplay
1319 //
1320 /////////////////////////////////////////////////////////////////////
1321
1322 PrefDisplay::PrefDisplay(GuiPreferences * form)
1323         : PrefModule(catLookAndFeel, N_("Display"), form)
1324 {
1325         setupUi(this);
1326         connect(displayGraphicsCB, SIGNAL(toggled(bool)), this, SIGNAL(changed()));
1327         connect(instantPreviewCO, SIGNAL(activated(int)), this, SIGNAL(changed()));
1328         connect(previewSizeSB, SIGNAL(valueChanged(double)), this, SIGNAL(changed()));
1329         connect(paragraphMarkerCB, SIGNAL(toggled(bool)), this, SIGNAL(changed()));
1330 }
1331
1332
1333 void PrefDisplay::on_instantPreviewCO_currentIndexChanged(int index)
1334 {
1335         previewSizeSB->setEnabled(index != 0);
1336 }
1337
1338
1339 void PrefDisplay::applyRC(LyXRC & rc) const
1340 {
1341         switch (instantPreviewCO->currentIndex()) {
1342                 case 0:
1343                         rc.preview = LyXRC::PREVIEW_OFF;
1344                         break;
1345                 case 1:
1346                         if (rc.preview != LyXRC::PREVIEW_NO_MATH) {
1347                                 rc.preview = LyXRC::PREVIEW_NO_MATH;
1348                                 form_->updatePreviews();
1349                         }
1350                         break;
1351                 case 2:
1352                         if (rc.preview != LyXRC::PREVIEW_ON) {
1353                                 rc.preview = LyXRC::PREVIEW_ON;
1354                                 form_->updatePreviews();
1355                         }
1356                         break;
1357         }
1358
1359         rc.display_graphics = displayGraphicsCB->isChecked();
1360         rc.preview_scale_factor = previewSizeSB->value();
1361         rc.paragraph_markers = paragraphMarkerCB->isChecked();
1362
1363         // FIXME!! The graphics cache no longer has a changeDisplay method.
1364 #if 0
1365         if (old_value != rc.display_graphics) {
1366                 graphics::GCache & gc = graphics::GCache::get();
1367                 gc.changeDisplay();
1368         }
1369 #endif
1370 }
1371
1372
1373 void PrefDisplay::updateRC(LyXRC const & rc)
1374 {
1375         switch (rc.preview) {
1376         case LyXRC::PREVIEW_OFF:
1377                 instantPreviewCO->setCurrentIndex(0);
1378                 break;
1379         case LyXRC::PREVIEW_NO_MATH :
1380                 instantPreviewCO->setCurrentIndex(1);
1381                 break;
1382         case LyXRC::PREVIEW_ON :
1383                 instantPreviewCO->setCurrentIndex(2);
1384                 break;
1385         }
1386
1387         displayGraphicsCB->setChecked(rc.display_graphics);
1388         previewSizeSB->setValue(rc.preview_scale_factor);
1389         paragraphMarkerCB->setChecked(rc.paragraph_markers);
1390         previewSizeSB->setEnabled(
1391                 rc.display_graphics
1392                 && rc.preview != LyXRC::PREVIEW_OFF);
1393 }
1394
1395
1396 /////////////////////////////////////////////////////////////////////
1397 //
1398 // PrefPaths
1399 //
1400 /////////////////////////////////////////////////////////////////////
1401
1402 PrefPaths::PrefPaths(GuiPreferences * form)
1403         : PrefModule(QString(), N_("Paths"), form)
1404 {
1405         setupUi(this);
1406
1407         connect(workingDirPB, SIGNAL(clicked()), this, SLOT(selectWorkingdir()));
1408         connect(workingDirED, SIGNAL(textChanged(QString)),
1409                 this, SIGNAL(changed()));
1410
1411         connect(templateDirPB, SIGNAL(clicked()), this, SLOT(selectTemplatedir()));
1412         connect(templateDirED, SIGNAL(textChanged(QString)),
1413                 this, SIGNAL(changed()));
1414
1415         connect(exampleDirPB, SIGNAL(clicked()), this, SLOT(selectExampledir()));
1416         connect(exampleDirED, SIGNAL(textChanged(QString)),
1417                 this, SIGNAL(changed()));
1418
1419         connect(backupDirPB, SIGNAL(clicked()), this, SLOT(selectBackupdir()));
1420         connect(backupDirED, SIGNAL(textChanged(QString)),
1421                 this, SIGNAL(changed()));
1422
1423         connect(lyxserverDirPB, SIGNAL(clicked()), this, SLOT(selectLyxPipe()));
1424         connect(lyxserverDirED, SIGNAL(textChanged(QString)),
1425                 this, SIGNAL(changed()));
1426
1427         connect(thesaurusDirPB, SIGNAL(clicked()), this, SLOT(selectThesaurusdir()));
1428         connect(thesaurusDirED, SIGNAL(textChanged(QString)),
1429                 this, SIGNAL(changed()));
1430
1431         connect(tempDirPB, SIGNAL(clicked()), this, SLOT(selectTempdir()));
1432         connect(tempDirED, SIGNAL(textChanged(QString)),
1433                 this, SIGNAL(changed()));
1434
1435 #if defined(USE_HUNSPELL)
1436         connect(hunspellDirPB, SIGNAL(clicked()), this, SLOT(selectHunspelldir()));
1437         connect(hunspellDirED, SIGNAL(textChanged(QString)),
1438                 this, SIGNAL(changed()));
1439 #else
1440         hunspellDirPB->setEnabled(false);
1441         hunspellDirED->setEnabled(false);
1442 #endif
1443
1444         connect(pathPrefixED, SIGNAL(textChanged(QString)),
1445                 this, SIGNAL(changed()));
1446
1447         connect(texinputsPrefixED, SIGNAL(textChanged(QString)),
1448                 this, SIGNAL(changed()));
1449
1450         pathPrefixED->setValidator(new NoNewLineValidator(pathPrefixED));
1451         texinputsPrefixED->setValidator(new NoNewLineValidator(texinputsPrefixED));
1452 }
1453
1454
1455 void PrefPaths::applyRC(LyXRC & rc) const
1456 {
1457         rc.document_path = internal_path(fromqstr(workingDirED->text()));
1458         rc.example_path = internal_path(fromqstr(exampleDirED->text()));
1459         rc.template_path = internal_path(fromqstr(templateDirED->text()));
1460         rc.backupdir_path = internal_path(fromqstr(backupDirED->text()));
1461         rc.tempdir_path = internal_path(fromqstr(tempDirED->text()));
1462         rc.thesaurusdir_path = internal_path(fromqstr(thesaurusDirED->text()));
1463         rc.hunspelldir_path = internal_path(fromqstr(hunspellDirED->text()));
1464         rc.path_prefix = internal_path_list(fromqstr(pathPrefixED->text()));
1465         rc.texinputs_prefix = internal_path_list(fromqstr(texinputsPrefixED->text()));
1466         // FIXME: should be a checkbox only
1467         rc.lyxpipes = internal_path(fromqstr(lyxserverDirED->text()));
1468 }
1469
1470
1471 void PrefPaths::updateRC(LyXRC const & rc)
1472 {
1473         workingDirED->setText(toqstr(external_path(rc.document_path)));
1474         exampleDirED->setText(toqstr(external_path(rc.example_path)));
1475         templateDirED->setText(toqstr(external_path(rc.template_path)));
1476         backupDirED->setText(toqstr(external_path(rc.backupdir_path)));
1477         tempDirED->setText(toqstr(external_path(rc.tempdir_path)));
1478         thesaurusDirED->setText(toqstr(external_path(rc.thesaurusdir_path)));
1479         hunspellDirED->setText(toqstr(external_path(rc.hunspelldir_path)));
1480         pathPrefixED->setText(toqstr(external_path_list(rc.path_prefix)));
1481         texinputsPrefixED->setText(toqstr(external_path_list(rc.texinputs_prefix)));
1482         // FIXME: should be a checkbox only
1483         lyxserverDirED->setText(toqstr(external_path(rc.lyxpipes)));
1484 }
1485
1486
1487 void PrefPaths::selectExampledir()
1488 {
1489         QString file = browseDir(internalPath(exampleDirED->text()),
1490                 qt_("Select directory for example files"));
1491         if (!file.isEmpty())
1492                 exampleDirED->setText(file);
1493 }
1494
1495
1496 void PrefPaths::selectTemplatedir()
1497 {
1498         QString file = browseDir(internalPath(templateDirED->text()),
1499                 qt_("Select a document templates directory"));
1500         if (!file.isEmpty())
1501                 templateDirED->setText(file);
1502 }
1503
1504
1505 void PrefPaths::selectTempdir()
1506 {
1507         QString file = browseDir(internalPath(tempDirED->text()),
1508                 qt_("Select a temporary directory"));
1509         if (!file.isEmpty())
1510                 tempDirED->setText(file);
1511 }
1512
1513
1514 void PrefPaths::selectBackupdir()
1515 {
1516         QString file = browseDir(internalPath(backupDirED->text()),
1517                 qt_("Select a backups directory"));
1518         if (!file.isEmpty())
1519                 backupDirED->setText(file);
1520 }
1521
1522
1523 void PrefPaths::selectWorkingdir()
1524 {
1525         QString file = browseDir(internalPath(workingDirED->text()),
1526                 qt_("Select a document directory"));
1527         if (!file.isEmpty())
1528                 workingDirED->setText(file);
1529 }
1530
1531
1532 void PrefPaths::selectThesaurusdir()
1533 {
1534         QString file = browseDir(internalPath(thesaurusDirED->text()),
1535                 qt_("Set the path to the thesaurus dictionaries"));
1536         if (!file.isEmpty())
1537                 thesaurusDirED->setText(file);
1538 }
1539
1540
1541 void PrefPaths::selectHunspelldir()
1542 {
1543         QString file = browseDir(internalPath(hunspellDirED->text()),
1544                 qt_("Set the path to the Hunspell dictionaries"));
1545         if (!file.isEmpty())
1546                 hunspellDirED->setText(file);
1547 }
1548
1549
1550 void PrefPaths::selectLyxPipe()
1551 {
1552         QString file = form_->browse(internalPath(lyxserverDirED->text()),
1553                 qt_("Give a filename for the LyX server pipe"));
1554         if (!file.isEmpty())
1555                 lyxserverDirED->setText(file);
1556 }
1557
1558
1559 /////////////////////////////////////////////////////////////////////
1560 //
1561 // PrefSpellchecker
1562 //
1563 /////////////////////////////////////////////////////////////////////
1564
1565 PrefSpellchecker::PrefSpellchecker(GuiPreferences * form)
1566         : PrefModule(catLanguage, N_("Spellchecker"), form)
1567 {
1568         setupUi(this);
1569
1570 // FIXME: this check should test the target platform (darwin)
1571 #if defined(USE_MACOSX_PACKAGING)
1572         spellcheckerCB->addItem(qt_("Native"), QString("native"));
1573 #define CONNECT_APPLESPELL
1574 #else
1575 #undef CONNECT_APPLESPELL
1576 #endif
1577 #if defined(USE_ASPELL)
1578         spellcheckerCB->addItem(qt_("Aspell"), QString("aspell"));
1579 #endif
1580 #if defined(USE_ENCHANT)
1581         spellcheckerCB->addItem(qt_("Enchant"), QString("enchant"));
1582 #endif
1583 #if defined(USE_HUNSPELL)
1584         spellcheckerCB->addItem(qt_("Hunspell"), QString("hunspell"));
1585 #endif
1586
1587         #if defined(CONNECT_APPLESPELL) || defined(USE_ASPELL) || defined(USE_ENCHANT) || defined(USE_HUNSPELL)
1588                 connect(spellcheckerCB, SIGNAL(currentIndexChanged(int)),
1589                         this, SIGNAL(changed()));
1590                 connect(altLanguageED, SIGNAL(textChanged(QString)),
1591                         this, SIGNAL(changed()));
1592                 connect(escapeCharactersED, SIGNAL(textChanged(QString)),
1593                         this, SIGNAL(changed()));
1594                 connect(compoundWordCB, SIGNAL(clicked()),
1595                         this, SIGNAL(changed()));
1596                 connect(spellcheckContinuouslyCB, SIGNAL(clicked()),
1597                         this, SIGNAL(changed()));
1598                 connect(spellcheckNotesCB, SIGNAL(clicked()),
1599                         this, SIGNAL(changed()));
1600
1601                 altLanguageED->setValidator(new NoNewLineValidator(altLanguageED));
1602                 escapeCharactersED->setValidator(new NoNewLineValidator(escapeCharactersED));
1603         #else
1604                 spellcheckerCB->setEnabled(false);
1605                 altLanguageED->setEnabled(false);
1606                 escapeCharactersED->setEnabled(false);
1607                 compoundWordCB->setEnabled(false);
1608                 spellcheckContinuouslyCB->setEnabled(false);
1609                 spellcheckNotesCB->setEnabled(false);
1610         #endif
1611 }
1612
1613
1614 void PrefSpellchecker::applyRC(LyXRC & rc) const
1615 {
1616         string const speller = fromqstr(spellcheckerCB->
1617                 itemData(spellcheckerCB->currentIndex()).toString());
1618         if (!speller.empty())
1619                 rc.spellchecker = speller;
1620         rc.spellchecker_alt_lang = fromqstr(altLanguageED->text());
1621         rc.spellchecker_esc_chars = fromqstr(escapeCharactersED->text());
1622         rc.spellchecker_accept_compound = compoundWordCB->isChecked();
1623         rc.spellcheck_continuously = spellcheckContinuouslyCB->isChecked();
1624         rc.spellcheck_notes = spellcheckNotesCB->isChecked();
1625 }
1626
1627
1628 void PrefSpellchecker::updateRC(LyXRC const & rc)
1629 {
1630         spellcheckerCB->setCurrentIndex(
1631                 spellcheckerCB->findData(toqstr(rc.spellchecker)));
1632         altLanguageED->setText(toqstr(rc.spellchecker_alt_lang));
1633         escapeCharactersED->setText(toqstr(rc.spellchecker_esc_chars));
1634         compoundWordCB->setChecked(rc.spellchecker_accept_compound);
1635         spellcheckContinuouslyCB->setChecked(rc.spellcheck_continuously);
1636         spellcheckNotesCB->setChecked(rc.spellcheck_notes);
1637 }
1638
1639
1640 void PrefSpellchecker::on_spellcheckerCB_currentIndexChanged(int index)
1641 {
1642         QString spellchecker = spellcheckerCB->itemData(index).toString();
1643
1644         compoundWordCB->setEnabled(spellchecker == QString("aspell"));
1645 }
1646
1647
1648
1649 /////////////////////////////////////////////////////////////////////
1650 //
1651 // PrefConverters
1652 //
1653 /////////////////////////////////////////////////////////////////////
1654
1655
1656 PrefConverters::PrefConverters(GuiPreferences * form)
1657         : PrefModule(catFiles, N_("Converters"), form)
1658 {
1659         setupUi(this);
1660
1661         connect(converterNewPB, SIGNAL(clicked()),
1662                 this, SLOT(updateConverter()));
1663         connect(converterRemovePB, SIGNAL(clicked()),
1664                 this, SLOT(removeConverter()));
1665         connect(converterModifyPB, SIGNAL(clicked()),
1666                 this, SLOT(updateConverter()));
1667         connect(convertersLW, SIGNAL(currentRowChanged(int)),
1668                 this, SLOT(switchConverter()));
1669         connect(converterFromCO, SIGNAL(activated(QString)),
1670                 this, SLOT(changeConverter()));
1671         connect(converterToCO, SIGNAL(activated(QString)),
1672                 this, SLOT(changeConverter()));
1673         connect(converterED, SIGNAL(textEdited(QString)),
1674                 this, SLOT(changeConverter()));
1675         connect(converterFlagED, SIGNAL(textEdited(QString)),
1676                 this, SLOT(changeConverter()));
1677         connect(converterNewPB, SIGNAL(clicked()),
1678                 this, SIGNAL(changed()));
1679         connect(converterRemovePB, SIGNAL(clicked()),
1680                 this, SIGNAL(changed()));
1681         connect(converterModifyPB, SIGNAL(clicked()),
1682                 this, SIGNAL(changed()));
1683         connect(maxAgeLE, SIGNAL(textEdited(QString)),
1684                 this, SIGNAL(changed()));
1685         connect(needauthForbiddenCB, SIGNAL(toggled(bool)),
1686                 this, SIGNAL(changed()));
1687         connect(needauthCB, SIGNAL(toggled(bool)),
1688                 this, SIGNAL(changed()));
1689
1690         converterED->setValidator(new NoNewLineValidator(converterED));
1691         converterFlagED->setValidator(new NoNewLineValidator(converterFlagED));
1692         maxAgeLE->setValidator(new QDoubleValidator(0, HUGE_VAL, 6, maxAgeLE));
1693         //converterDefGB->setFocusProxy(convertersLW);
1694 }
1695
1696
1697 void PrefConverters::applyRC(LyXRC & rc) const
1698 {
1699         rc.use_converter_cache = cacheCB->isChecked();
1700         rc.use_converter_needauth_forbidden = needauthForbiddenCB->isChecked();
1701         rc.use_converter_needauth = needauthCB->isChecked();
1702         rc.converter_cache_maxage = int(widgetToDouble(maxAgeLE) * 86400.0);
1703 }
1704
1705
1706 void PrefConverters::updateRC(LyXRC const & rc)
1707 {
1708         cacheCB->setChecked(rc.use_converter_cache);
1709         needauthForbiddenCB->setChecked(rc.use_converter_needauth_forbidden);
1710         needauthCB->setChecked(rc.use_converter_needauth);
1711         QString max_age;
1712         doubleToWidget(maxAgeLE, (double(rc.converter_cache_maxage) / 86400.0), 'g', 6);
1713         updateGui();
1714 }
1715
1716
1717 void PrefConverters::updateGui()
1718 {
1719         QString const pattern("%1 -> %2");
1720         form_->formats().sort();
1721         form_->converters().update(form_->formats());
1722         // save current selection
1723         QString current =
1724                 pattern
1725                 .arg(converterFromCO->currentText())
1726                 .arg(converterToCO->currentText());
1727
1728         converterFromCO->clear();
1729         converterToCO->clear();
1730
1731         for (Format const & f : form_->formats()) {
1732                 QString const name = toqstr(translateIfPossible(f.prettyname()));
1733                 converterFromCO->addItem(name);
1734                 converterToCO->addItem(name);
1735         }
1736
1737         // currentRowChanged(int) is also triggered when updating the listwidget
1738         // block signals to avoid unnecessary calls to switchConverter()
1739         convertersLW->blockSignals(true);
1740         convertersLW->clear();
1741
1742         for (Converter const & c : form_->converters()) {
1743                 QString const name =
1744                         pattern
1745                         .arg(toqstr(translateIfPossible(c.From()->prettyname())))
1746                         .arg(toqstr(translateIfPossible(c.To()->prettyname())));
1747                 int type = form_->converters().getNumber(c.From()->name(),
1748                                                          c.To()->name());
1749                 new QListWidgetItem(name, convertersLW, type);
1750         }
1751         convertersLW->sortItems(Qt::AscendingOrder);
1752         convertersLW->blockSignals(false);
1753
1754         // restore selection
1755         if (current != pattern.arg(QString()).arg(QString())) {
1756                 QList<QListWidgetItem *> const item =
1757                         convertersLW->findItems(current, Qt::MatchExactly);
1758                 if (!item.isEmpty())
1759                         convertersLW->setCurrentItem(item.at(0));
1760         }
1761
1762         // select first element if restoring failed
1763         if (convertersLW->currentRow() == -1)
1764                 convertersLW->setCurrentRow(0);
1765
1766         updateButtons();
1767 }
1768
1769
1770 void PrefConverters::switchConverter()
1771 {
1772         int const cnr = convertersLW->currentItem()->type();
1773         Converter const & c(form_->converters().get(cnr));
1774         converterFromCO->setCurrentIndex(form_->formats().getNumber(c.from()));
1775         converterToCO->setCurrentIndex(form_->formats().getNumber(c.to()));
1776         converterED->setText(toqstr(c.command()));
1777         converterFlagED->setText(toqstr(c.flags()));
1778
1779         updateButtons();
1780 }
1781
1782
1783 void PrefConverters::changeConverter()
1784 {
1785         updateButtons();
1786 }
1787
1788
1789 void PrefConverters::updateButtons()
1790 {
1791         if (form_->formats().empty())
1792                 return;
1793         Format const & from = form_->formats().get(converterFromCO->currentIndex());
1794         Format const & to = form_->formats().get(converterToCO->currentIndex());
1795         int const sel = form_->converters().getNumber(from.name(), to.name());
1796         bool const known = sel >= 0;
1797         bool const valid = !(converterED->text().isEmpty()
1798                 || from.name() == to.name());
1799
1800         string old_command;
1801         string old_flag;
1802
1803         if (convertersLW->count() > 0) {
1804                 int const cnr = convertersLW->currentItem()->type();
1805                 Converter const & c = form_->converters().get(cnr);
1806                 old_command = c.command();
1807                 old_flag = c.flags();
1808         }
1809
1810         string const new_command = fromqstr(converterED->text());
1811         string const new_flag = fromqstr(converterFlagED->text());
1812
1813         bool modified = (old_command != new_command || old_flag != new_flag);
1814
1815         converterModifyPB->setEnabled(valid && known && modified);
1816         converterNewPB->setEnabled(valid && !known);
1817         converterRemovePB->setEnabled(known);
1818
1819         maxAgeLE->setEnabled(cacheCB->isChecked());
1820         maxAgeLA->setEnabled(cacheCB->isChecked());
1821 }
1822
1823
1824 // FIXME: user must
1825 // specify unique from/to or it doesn't appear. This is really bad UI
1826 // this is why we can use the same function for both new and modify
1827 void PrefConverters::updateConverter()
1828 {
1829         Format const & from = form_->formats().get(converterFromCO->currentIndex());
1830         Format const & to = form_->formats().get(converterToCO->currentIndex());
1831         string const flags = fromqstr(converterFlagED->text());
1832         string const command = fromqstr(converterED->text());
1833
1834         Converter const * old =
1835                 form_->converters().getConverter(from.name(), to.name());
1836         form_->converters().add(from.name(), to.name(), command, flags);
1837
1838         if (!old)
1839                 form_->converters().updateLast(form_->formats());
1840
1841         updateGui();
1842
1843         // Remove all files created by this converter from the cache, since
1844         // the modified converter might create different files.
1845         ConverterCache::get().remove_all(from.name(), to.name());
1846 }
1847
1848
1849 void PrefConverters::removeConverter()
1850 {
1851         Format const & from = form_->formats().get(converterFromCO->currentIndex());
1852         Format const & to = form_->formats().get(converterToCO->currentIndex());
1853         form_->converters().erase(from.name(), to.name());
1854
1855         updateGui();
1856
1857         // Remove all files created by this converter from the cache, since
1858         // a possible new converter might create different files.
1859         ConverterCache::get().remove_all(from.name(), to.name());
1860 }
1861
1862
1863 void PrefConverters::on_cacheCB_stateChanged(int state)
1864 {
1865         maxAgeLE->setEnabled(state == Qt::Checked);
1866         maxAgeLA->setEnabled(state == Qt::Checked);
1867         changed();
1868 }
1869
1870
1871 void PrefConverters::on_needauthForbiddenCB_toggled(bool checked)
1872 {
1873         needauthCB->setEnabled(!checked);
1874 }
1875
1876
1877 /////////////////////////////////////////////////////////////////////
1878 //
1879 // FormatValidator
1880 //
1881 /////////////////////////////////////////////////////////////////////
1882
1883 class FormatValidator : public QValidator
1884 {
1885 public:
1886         FormatValidator(QWidget *, Formats const & f);
1887         void fixup(QString & input) const;
1888         QValidator::State validate(QString & input, int & pos) const;
1889 private:
1890         virtual QString toString(Format const & format) const = 0;
1891         int nr() const;
1892         Formats const & formats_;
1893 };
1894
1895
1896 FormatValidator::FormatValidator(QWidget * parent, Formats const & f)
1897         : QValidator(parent), formats_(f)
1898 {
1899 }
1900
1901
1902 void FormatValidator::fixup(QString & input) const
1903 {
1904         Formats::const_iterator cit = formats_.begin();
1905         Formats::const_iterator end = formats_.end();
1906         for (; cit != end; ++cit) {
1907                 QString const name = toString(*cit);
1908                 if (distance(formats_.begin(), cit) == nr()) {
1909                         input = name;
1910                         return;
1911                 }
1912         }
1913 }
1914
1915
1916 QValidator::State FormatValidator::validate(QString & input, int & /*pos*/) const
1917 {
1918         Formats::const_iterator cit = formats_.begin();
1919         Formats::const_iterator end = formats_.end();
1920         bool unknown = true;
1921         for (; unknown && cit != end; ++cit) {
1922                 QString const name = toString(*cit);
1923                 if (distance(formats_.begin(), cit) != nr())
1924                         unknown = name != input;
1925         }
1926
1927         if (unknown && !input.isEmpty())
1928                 return QValidator::Acceptable;
1929         else
1930                 return QValidator::Intermediate;
1931 }
1932
1933
1934 int FormatValidator::nr() const
1935 {
1936         QComboBox * p = qobject_cast<QComboBox *>(parent());
1937         return p->itemData(p->currentIndex()).toInt();
1938 }
1939
1940
1941 /////////////////////////////////////////////////////////////////////
1942 //
1943 // FormatNameValidator
1944 //
1945 /////////////////////////////////////////////////////////////////////
1946
1947 class FormatNameValidator : public FormatValidator
1948 {
1949 public:
1950         FormatNameValidator(QWidget * parent, Formats const & f)
1951                 : FormatValidator(parent, f)
1952         {}
1953 private:
1954         QString toString(Format const & format) const
1955         {
1956                 return toqstr(format.name());
1957         }
1958 };
1959
1960
1961 /////////////////////////////////////////////////////////////////////
1962 //
1963 // FormatPrettynameValidator
1964 //
1965 /////////////////////////////////////////////////////////////////////
1966
1967 class FormatPrettynameValidator : public FormatValidator
1968 {
1969 public:
1970         FormatPrettynameValidator(QWidget * parent, Formats const & f)
1971                 : FormatValidator(parent, f)
1972         {}
1973 private:
1974         QString toString(Format const & format) const
1975         {
1976                 return toqstr(translateIfPossible(format.prettyname()));
1977         }
1978 };
1979
1980
1981 /////////////////////////////////////////////////////////////////////
1982 //
1983 // PrefFileformats
1984 //
1985 /////////////////////////////////////////////////////////////////////
1986
1987 PrefFileformats::PrefFileformats(GuiPreferences * form)
1988         : PrefModule(catFiles, N_("File Formats"), form)
1989 {
1990         setupUi(this);
1991
1992         formatED->setValidator(new FormatNameValidator(formatsCB, form_->formats()));
1993         formatsCB->setValidator(new FormatPrettynameValidator(formatsCB, form_->formats()));
1994         extensionsED->setValidator(new NoNewLineValidator(extensionsED));
1995         shortcutED->setValidator(new NoNewLineValidator(shortcutED));
1996         editorED->setValidator(new NoNewLineValidator(editorED));
1997         viewerED->setValidator(new NoNewLineValidator(viewerED));
1998         copierED->setValidator(new NoNewLineValidator(copierED));
1999
2000         connect(documentCB, SIGNAL(clicked()),
2001                 this, SLOT(setFlags()));
2002         connect(vectorCB, SIGNAL(clicked()),
2003                 this, SLOT(setFlags()));
2004         connect(exportMenuCB, SIGNAL(clicked()),
2005                 this, SLOT(setFlags()));
2006         connect(formatsCB->lineEdit(), SIGNAL(editingFinished()),
2007                 this, SLOT(updatePrettyname()));
2008         connect(formatsCB->lineEdit(), SIGNAL(textEdited(QString)),
2009                 this, SIGNAL(changed()));
2010         connect(defaultFormatCB, SIGNAL(activated(QString)),
2011                 this, SIGNAL(changed()));
2012         connect(defaultOTFFormatCB, SIGNAL(activated(QString)),
2013                 this, SIGNAL(changed()));
2014         connect(viewerCO, SIGNAL(activated(int)),
2015                 this, SIGNAL(changed()));
2016         connect(editorCO, SIGNAL(activated(int)),
2017                 this, SIGNAL(changed()));
2018 }
2019
2020
2021 namespace {
2022
2023 string const l10n_shortcut(docstring const & prettyname, string const & shortcut)
2024 {
2025         if (shortcut.empty())
2026                 return string();
2027
2028         string l10n_format =
2029                 to_utf8(_(to_utf8(prettyname) + '|' + shortcut));
2030         return split(l10n_format, '|');
2031 }
2032
2033 } // namespace anon
2034
2035
2036 void PrefFileformats::applyRC(LyXRC & rc) const
2037 {
2038         QString const default_format = defaultFormatCB->itemData(
2039                 defaultFormatCB->currentIndex()).toString();
2040         rc.default_view_format = fromqstr(default_format);
2041         QString const default_otf_format = defaultOTFFormatCB->itemData(
2042                 defaultOTFFormatCB->currentIndex()).toString();
2043         rc.default_otf_view_format = fromqstr(default_otf_format);
2044 }
2045
2046
2047 void PrefFileformats::updateRC(LyXRC const & rc)
2048 {
2049         viewer_alternatives = rc.viewer_alternatives;
2050         editor_alternatives = rc.editor_alternatives;
2051         bool const init = defaultFormatCB->currentText().isEmpty();
2052         updateView();
2053         if (init) {
2054                 int pos =
2055                         defaultFormatCB->findData(toqstr(rc.default_view_format));
2056                 defaultFormatCB->setCurrentIndex(pos);
2057                 pos = defaultOTFFormatCB->findData(toqstr(rc.default_otf_view_format));
2058                                 defaultOTFFormatCB->setCurrentIndex(pos);
2059                 defaultOTFFormatCB->setCurrentIndex(pos);
2060         }
2061 }
2062
2063
2064 void PrefFileformats::updateView()
2065 {
2066         QString const current = formatsCB->currentText();
2067         QString const current_def = defaultFormatCB->currentText();
2068         QString const current_def_otf = defaultOTFFormatCB->currentText();
2069
2070         // update comboboxes with formats
2071         formatsCB->blockSignals(true);
2072         defaultFormatCB->blockSignals(true);
2073         defaultOTFFormatCB->blockSignals(true);
2074         formatsCB->clear();
2075         defaultFormatCB->clear();
2076         defaultOTFFormatCB->clear();
2077         form_->formats().sort();
2078         for (Format const & f : form_->formats()) {
2079                 QString const prettyname = toqstr(translateIfPossible(f.prettyname()));
2080                 formatsCB->addItem(prettyname,
2081                                    QVariant(form_->formats().getNumber(f.name())));
2082                 if (f.viewer().empty())
2083                         continue;
2084                 if (form_->converters().isReachable("xhtml", f.name())
2085                     || form_->converters().isReachable("dviluatex", f.name())
2086                     || form_->converters().isReachable("luatex", f.name())
2087                     || form_->converters().isReachable("xetex", f.name())) {
2088                         defaultFormatCB->addItem(prettyname,
2089                                         QVariant(toqstr(f.name())));
2090                         defaultOTFFormatCB->addItem(prettyname,
2091                                         QVariant(toqstr(f.name())));
2092                 } else if (form_->converters().isReachable("latex", f.name())
2093                            || form_->converters().isReachable("pdflatex", f.name()))
2094                         defaultFormatCB->addItem(prettyname,
2095                                         QVariant(toqstr(f.name())));
2096         }
2097
2098         // restore selections
2099         int item = formatsCB->findText(current, Qt::MatchExactly);
2100         formatsCB->setCurrentIndex(item < 0 ? 0 : item);
2101         on_formatsCB_currentIndexChanged(item < 0 ? 0 : item);
2102         item = defaultFormatCB->findText(current_def, Qt::MatchExactly);
2103         defaultFormatCB->setCurrentIndex(item < 0 ? 0 : item);
2104         item = defaultOTFFormatCB->findText(current_def_otf, Qt::MatchExactly);
2105         defaultOTFFormatCB->setCurrentIndex(item < 0 ? 0 : item);
2106         formatsCB->blockSignals(false);
2107         defaultFormatCB->blockSignals(false);
2108         defaultOTFFormatCB->blockSignals(false);
2109 }
2110
2111
2112 void PrefFileformats::on_formatsCB_currentIndexChanged(int i)
2113 {
2114         if (form_->formats().empty())
2115                 return;
2116         int const nr = formatsCB->itemData(i).toInt();
2117         Format const f = form_->formats().get(nr);
2118
2119         formatED->setText(toqstr(f.name()));
2120         copierED->setText(toqstr(form_->movers().command(f.name())));
2121         extensionsED->setText(toqstr(f.extensions()));
2122         mimeED->setText(toqstr(f.mime()));
2123         shortcutED->setText(
2124                 toqstr(l10n_shortcut(f.prettyname(), f.shortcut())));
2125         documentCB->setChecked((f.documentFormat()));
2126         vectorCB->setChecked((f.vectorFormat()));
2127         exportMenuCB->setChecked((f.inExportMenu()));
2128         exportMenuCB->setEnabled((f.documentFormat()));
2129         updateViewers();
2130         updateEditors();
2131 }
2132
2133
2134 void PrefFileformats::setFlags()
2135 {
2136         int flags = Format::none;
2137         if (documentCB->isChecked())
2138                 flags |= Format::document;
2139         if (vectorCB->isChecked())
2140                 flags |= Format::vector;
2141         if (exportMenuCB->isChecked())
2142                 flags |= Format::export_menu;
2143         currentFormat().setFlags(flags);
2144         exportMenuCB->setEnabled(documentCB->isChecked());
2145         changed();
2146 }
2147
2148
2149 void PrefFileformats::on_copierED_textEdited(const QString & s)
2150 {
2151         string const fmt = fromqstr(formatED->text());
2152         form_->movers().set(fmt, fromqstr(s));
2153         changed();
2154 }
2155
2156
2157 void PrefFileformats::on_extensionsED_textEdited(const QString & s)
2158 {
2159         currentFormat().setExtensions(fromqstr(s));
2160         changed();
2161 }
2162
2163
2164 void PrefFileformats::on_viewerED_textEdited(const QString & s)
2165 {
2166         currentFormat().setViewer(fromqstr(s));
2167         changed();
2168 }
2169
2170
2171 void PrefFileformats::on_editorED_textEdited(const QString & s)
2172 {
2173         currentFormat().setEditor(fromqstr(s));
2174         changed();
2175 }
2176
2177
2178 void PrefFileformats::on_mimeED_textEdited(const QString & s)
2179 {
2180         currentFormat().setMime(fromqstr(s));
2181         changed();
2182 }
2183
2184
2185 void PrefFileformats::on_shortcutED_textEdited(const QString & s)
2186 {
2187         string const new_shortcut = fromqstr(s);
2188         if (new_shortcut == l10n_shortcut(currentFormat().prettyname(),
2189                                           currentFormat().shortcut()))
2190                 return;
2191         currentFormat().setShortcut(new_shortcut);
2192         changed();
2193 }
2194
2195
2196 void PrefFileformats::on_formatED_editingFinished()
2197 {
2198         string const newname = fromqstr(formatED->displayText());
2199         string const oldname = currentFormat().name();
2200         if (newname == oldname)
2201                 return;
2202         if (form_->converters().formatIsUsed(oldname)) {
2203                 Alert::error(_("Format in use"),
2204                              _("You cannot change a format's short name "
2205                                "if the format is used by a converter. "
2206                                "Please remove the converter first."));
2207                 updateView();
2208                 return;
2209         }
2210
2211         currentFormat().setName(newname);
2212         changed();
2213 }
2214
2215
2216 void PrefFileformats::on_formatED_textChanged(const QString &)
2217 {
2218         QString t = formatED->text();
2219         int p = 0;
2220         bool valid = formatED->validator()->validate(t, p) == QValidator::Acceptable;
2221         setValid(formatLA, valid);
2222 }
2223
2224
2225 void PrefFileformats::on_formatsCB_editTextChanged(const QString &)
2226 {
2227         QString t = formatsCB->currentText();
2228         int p = 0;
2229         bool valid = formatsCB->validator()->validate(t, p) == QValidator::Acceptable;
2230         setValid(formatsLA, valid);
2231 }
2232
2233
2234 void PrefFileformats::updatePrettyname()
2235 {
2236         QString const newname = formatsCB->currentText();
2237         if (newname == toqstr(translateIfPossible(currentFormat().prettyname())))
2238                 return;
2239
2240         currentFormat().setPrettyname(qstring_to_ucs4(newname));
2241         formatsChanged();
2242         updateView();
2243         changed();
2244 }
2245
2246
2247 namespace {
2248         void updateComboBox(LyXRC::Alternatives const & alts,
2249                             string const & fmt, QComboBox * combo)
2250         {
2251                 LyXRC::Alternatives::const_iterator it =
2252                                 alts.find(fmt);
2253                 if (it != alts.end()) {
2254                         LyXRC::CommandSet const & cmds = it->second;
2255                         LyXRC::CommandSet::const_iterator sit =
2256                                         cmds.begin();
2257                         LyXRC::CommandSet::const_iterator const sen =
2258                                         cmds.end();
2259                         for (; sit != sen; ++sit) {
2260                                 QString const qcmd = toqstr(*sit);
2261                                 combo->addItem(qcmd, qcmd);
2262                         }
2263                 }
2264         }
2265 }
2266
2267
2268 void PrefFileformats::updateViewers()
2269 {
2270         Format const f = currentFormat();
2271         viewerCO->blockSignals(true);
2272         viewerCO->clear();
2273         viewerCO->addItem(qt_("None"), QString());
2274         updateComboBox(viewer_alternatives, f.name(), viewerCO);
2275         viewerCO->addItem(qt_("Custom"), QString("custom viewer"));
2276         viewerCO->blockSignals(false);
2277
2278         int pos = viewerCO->findData(toqstr(f.viewer()));
2279         if (pos != -1) {
2280                 viewerED->clear();
2281                 viewerED->setEnabled(false);
2282                 viewerCO->setCurrentIndex(pos);
2283         } else {
2284                 viewerED->setEnabled(true);
2285                 viewerED->setText(toqstr(f.viewer()));
2286                 viewerCO->setCurrentIndex(viewerCO->findData(toqstr("custom viewer")));
2287         }
2288 }
2289
2290
2291 void PrefFileformats::updateEditors()
2292 {
2293         Format const f = currentFormat();
2294         editorCO->blockSignals(true);
2295         editorCO->clear();
2296         editorCO->addItem(qt_("None"), QString());
2297         updateComboBox(editor_alternatives, f.name(), editorCO);
2298         editorCO->addItem(qt_("Custom"), QString("custom editor"));
2299         editorCO->blockSignals(false);
2300
2301         int pos = editorCO->findData(toqstr(f.editor()));
2302         if (pos != -1) {
2303                 editorED->clear();
2304                 editorED->setEnabled(false);
2305                 editorCO->setCurrentIndex(pos);
2306         } else {
2307                 editorED->setEnabled(true);
2308                 editorED->setText(toqstr(f.editor()));
2309                 editorCO->setCurrentIndex(editorCO->findData(toqstr("custom editor")));
2310         }
2311 }
2312
2313
2314 void PrefFileformats::on_viewerCO_currentIndexChanged(int i)
2315 {
2316         bool const custom = viewerCO->itemData(i).toString() == "custom viewer";
2317         viewerED->setEnabled(custom);
2318         if (!custom)
2319                 currentFormat().setViewer(fromqstr(viewerCO->itemData(i).toString()));
2320 }
2321
2322
2323 void PrefFileformats::on_editorCO_currentIndexChanged(int i)
2324 {
2325         bool const custom = editorCO->itemData(i).toString() == "custom editor";
2326         editorED->setEnabled(custom);
2327         if (!custom)
2328                 currentFormat().setEditor(fromqstr(editorCO->itemData(i).toString()));
2329 }
2330
2331
2332 Format & PrefFileformats::currentFormat()
2333 {
2334         int const i = formatsCB->currentIndex();
2335         int const nr = formatsCB->itemData(i).toInt();
2336         return form_->formats().get(nr);
2337 }
2338
2339
2340 void PrefFileformats::on_formatNewPB_clicked()
2341 {
2342         form_->formats().add("", "", docstring(), "", "", "", "", Format::none);
2343         updateView();
2344         formatsCB->setCurrentIndex(0);
2345         formatsCB->setFocus(Qt::OtherFocusReason);
2346 }
2347
2348
2349 void PrefFileformats::on_formatRemovePB_clicked()
2350 {
2351         int const i = formatsCB->currentIndex();
2352         int const nr = formatsCB->itemData(i).toInt();
2353         string const current_text = form_->formats().get(nr).name();
2354         if (form_->converters().formatIsUsed(current_text)) {
2355                 Alert::error(_("Format in use"),
2356                              _("Cannot remove a Format used by a Converter. "
2357                                             "Remove the converter first."));
2358                 return;
2359         }
2360
2361         form_->formats().erase(current_text);
2362         formatsChanged();
2363         updateView();
2364         on_formatsCB_editTextChanged(formatsCB->currentText());
2365         changed();
2366 }
2367
2368
2369 /////////////////////////////////////////////////////////////////////
2370 //
2371 // PrefLanguage
2372 //
2373 /////////////////////////////////////////////////////////////////////
2374
2375 PrefLanguage::PrefLanguage(GuiPreferences * form)
2376         : PrefModule(catLanguage, N_("Language"), form)
2377 {
2378         setupUi(this);
2379
2380         connect(visualCursorRB, SIGNAL(clicked()),
2381                 this, SIGNAL(changed()));
2382         connect(logicalCursorRB, SIGNAL(clicked()),
2383                 this, SIGNAL(changed()));
2384         connect(markForeignCB, SIGNAL(clicked()),
2385                 this, SIGNAL(changed()));
2386         connect(autoBeginCB, SIGNAL(clicked()),
2387                 this, SIGNAL(changed()));
2388         connect(autoEndCB, SIGNAL(clicked()),
2389                 this, SIGNAL(changed()));
2390         connect(languagePackageCO, SIGNAL(activated(int)),
2391                 this, SIGNAL(changed()));
2392         connect(languagePackageED, SIGNAL(textChanged(QString)),
2393                 this, SIGNAL(changed()));
2394         connect(globalCB, SIGNAL(clicked()),
2395                 this, SIGNAL(changed()));
2396         connect(startCommandED, SIGNAL(textChanged(QString)),
2397                 this, SIGNAL(changed()));
2398         connect(endCommandED, SIGNAL(textChanged(QString)),
2399                 this, SIGNAL(changed()));
2400         connect(uiLanguageCO, SIGNAL(activated(int)),
2401                 this, SIGNAL(changed()));
2402         connect(defaultDecimalPointLE, SIGNAL(textChanged(QString)),
2403                 this, SIGNAL(changed()));
2404         connect(defaultLengthUnitCO, SIGNAL(activated(int)),
2405                 this, SIGNAL(changed()));
2406
2407         languagePackageED->setValidator(new NoNewLineValidator(languagePackageED));
2408         startCommandED->setValidator(new NoNewLineValidator(startCommandED));
2409         endCommandED->setValidator(new NoNewLineValidator(endCommandED));
2410
2411         defaultDecimalPointLE->setInputMask("X; ");
2412         defaultDecimalPointLE->setMaxLength(1);
2413
2414         defaultLengthUnitCO->addItem(lyx::qt_(unit_name_gui[Length::CM]), Length::CM);
2415         defaultLengthUnitCO->addItem(lyx::qt_(unit_name_gui[Length::IN]), Length::IN);
2416
2417         QAbstractItemModel * language_model = guiApp->languageModel();
2418         language_model->sort(0);
2419         uiLanguageCO->blockSignals(true);
2420         uiLanguageCO->clear();
2421         uiLanguageCO->addItem(qt_("Default"), toqstr("auto"));
2422         for (int i = 0; i != language_model->rowCount(); ++i) {
2423                 QModelIndex index = language_model->index(i, 0);
2424                 // Filter the list based on the available translation and add
2425                 // each language code only once
2426                 string const name = fromqstr(index.data(Qt::UserRole).toString());
2427                 Language const * lang = languages.getLanguage(name);
2428                 if (!lang)
2429                         continue;
2430                 // never remove the currently selected language
2431                 if (name != form->rc().gui_language
2432                     && name != lyxrc.gui_language
2433                     && (!Messages::available(lang->code())
2434                         || !lang->hasGuiSupport()))
2435                         continue;
2436                 uiLanguageCO->addItem(index.data(Qt::DisplayRole).toString(),
2437                                       index.data(Qt::UserRole).toString());
2438         }
2439         uiLanguageCO->blockSignals(false);
2440 }
2441
2442
2443 void PrefLanguage::on_uiLanguageCO_currentIndexChanged(int)
2444 {
2445          QMessageBox::information(this, qt_("LyX needs to be restarted!"),
2446                  qt_("The change of user interface language will be fully "
2447                  "effective only after a restart."));
2448 }
2449
2450
2451 void PrefLanguage::on_languagePackageCO_currentIndexChanged(int i)
2452 {
2453          languagePackageED->setEnabled(i == 2);
2454 }
2455
2456
2457 void PrefLanguage::applyRC(LyXRC & rc) const
2458 {
2459         rc.visual_cursor = visualCursorRB->isChecked();
2460         rc.mark_foreign_language = markForeignCB->isChecked();
2461         rc.language_auto_begin = autoBeginCB->isChecked();
2462         rc.language_auto_end = autoEndCB->isChecked();
2463         int const p = languagePackageCO->currentIndex();
2464         if (p == 0)
2465                 rc.language_package_selection = LyXRC::LP_AUTO;
2466         else if (p == 1)
2467                 rc.language_package_selection = LyXRC::LP_BABEL;
2468         else if (p == 2)
2469                 rc.language_package_selection = LyXRC::LP_CUSTOM;
2470         else if (p == 3)
2471                 rc.language_package_selection = LyXRC::LP_NONE;
2472         rc.language_custom_package = fromqstr(languagePackageED->text());
2473         rc.language_global_options = globalCB->isChecked();
2474         rc.language_command_begin = fromqstr(startCommandED->text());
2475         rc.language_command_end = fromqstr(endCommandED->text());
2476         rc.gui_language = fromqstr(
2477                 uiLanguageCO->itemData(uiLanguageCO->currentIndex()).toString());
2478         rc.default_decimal_point = fromqstr(defaultDecimalPointLE->text());
2479         rc.default_length_unit = (Length::UNIT) defaultLengthUnitCO->itemData(defaultLengthUnitCO->currentIndex()).toInt();
2480 }
2481
2482
2483 void PrefLanguage::updateRC(LyXRC const & rc)
2484 {
2485         if (rc.visual_cursor)
2486                 visualCursorRB->setChecked(true);
2487         else
2488                 logicalCursorRB->setChecked(true);
2489         markForeignCB->setChecked(rc.mark_foreign_language);
2490         autoBeginCB->setChecked(rc.language_auto_begin);
2491         autoEndCB->setChecked(rc.language_auto_end);
2492         languagePackageCO->setCurrentIndex(rc.language_package_selection);
2493         languagePackageED->setText(toqstr(rc.language_custom_package));
2494         languagePackageED->setEnabled(languagePackageCO->currentIndex() == 2);
2495         globalCB->setChecked(rc.language_global_options);
2496         startCommandED->setText(toqstr(rc.language_command_begin));
2497         endCommandED->setText(toqstr(rc.language_command_end));
2498         defaultDecimalPointLE->setText(toqstr(rc.default_decimal_point));
2499         int pos = defaultLengthUnitCO->findData(int(rc.default_length_unit));
2500         defaultLengthUnitCO->setCurrentIndex(pos);
2501
2502         pos = uiLanguageCO->findData(toqstr(rc.gui_language));
2503         uiLanguageCO->blockSignals(true);
2504         uiLanguageCO->setCurrentIndex(pos);
2505         uiLanguageCO->blockSignals(false);
2506 }
2507
2508
2509 /////////////////////////////////////////////////////////////////////
2510 //
2511 // PrefUserInterface
2512 //
2513 /////////////////////////////////////////////////////////////////////
2514
2515 PrefUserInterface::PrefUserInterface(GuiPreferences * form)
2516         : PrefModule(catLookAndFeel, N_("User Interface"), form)
2517 {
2518         setupUi(this);
2519
2520         connect(uiFilePB, SIGNAL(clicked()),
2521                 this, SLOT(selectUi()));
2522         connect(uiFileED, SIGNAL(textChanged(QString)),
2523                 this, SIGNAL(changed()));
2524         connect(iconSetCO, SIGNAL(activated(int)),
2525                 this, SIGNAL(changed()));
2526         connect(useSystemThemeIconsCB, SIGNAL(clicked()),
2527                 this, SIGNAL(changed()));
2528         connect(lastfilesSB, SIGNAL(valueChanged(int)),
2529                 this, SIGNAL(changed()));
2530         connect(tooltipCB, SIGNAL(toggled(bool)),
2531                 this, SIGNAL(changed()));
2532         lastfilesSB->setMaximum(maxlastfiles);
2533
2534         iconSetCO->addItem(qt_("Default"), QString());
2535         iconSetCO->addItem(qt_("Classic"), "classic");
2536         iconSetCO->addItem(qt_("Oxygen"), "oxygen");
2537
2538 #if (!(defined Q_WS_X11 || defined(QPA_XCB)) || QT_VERSION < 0x040600)
2539         useSystemThemeIconsCB->hide();
2540 #endif
2541 }
2542
2543
2544 void PrefUserInterface::applyRC(LyXRC & rc) const
2545 {
2546         rc.icon_set = fromqstr(iconSetCO->itemData(
2547                 iconSetCO->currentIndex()).toString());
2548
2549         rc.ui_file = internal_path(fromqstr(uiFileED->text()));
2550         rc.use_system_theme_icons = useSystemThemeIconsCB->isChecked();
2551         rc.num_lastfiles = lastfilesSB->value();
2552         rc.use_tooltip = tooltipCB->isChecked();
2553 }
2554
2555
2556 void PrefUserInterface::updateRC(LyXRC const & rc)
2557 {
2558         int iconset = iconSetCO->findData(toqstr(rc.icon_set));
2559         if (iconset < 0)
2560                 iconset = 0;
2561         iconSetCO->setCurrentIndex(iconset);
2562         useSystemThemeIconsCB->setChecked(rc.use_system_theme_icons);
2563         uiFileED->setText(toqstr(external_path(rc.ui_file)));
2564         lastfilesSB->setValue(rc.num_lastfiles);
2565         tooltipCB->setChecked(rc.use_tooltip);
2566 }
2567
2568
2569 void PrefUserInterface::selectUi()
2570 {
2571         QString file = form_->browseUI(internalPath(uiFileED->text()));
2572         if (!file.isEmpty())
2573                 uiFileED->setText(file);
2574 }
2575
2576
2577 /////////////////////////////////////////////////////////////////////
2578 //
2579 // PrefDocumentHandling
2580 //
2581 /////////////////////////////////////////////////////////////////////
2582
2583 PrefDocHandling::PrefDocHandling(GuiPreferences * form)
2584         : PrefModule(catLookAndFeel, N_("Document Handling"), form)
2585 {
2586         setupUi(this);
2587
2588         connect(autoSaveCB, SIGNAL(toggled(bool)),
2589                 autoSaveSB, SLOT(setEnabled(bool)));
2590         connect(autoSaveCB, SIGNAL(toggled(bool)),
2591                 TextLabel1, SLOT(setEnabled(bool)));
2592         connect(openDocumentsInTabsCB, SIGNAL(clicked()),
2593                 this, SIGNAL(changed()));
2594         connect(singleInstanceCB, SIGNAL(clicked()),
2595                 this, SIGNAL(changed()));
2596         connect(singleCloseTabButtonCB, SIGNAL(clicked()),
2597                 this, SIGNAL(changed()));
2598         connect(closeLastViewCO, SIGNAL(activated(int)),
2599                 this, SIGNAL(changed()));
2600         connect(restoreCursorCB, SIGNAL(clicked()),
2601                 this, SIGNAL(changed()));
2602         connect(loadSessionCB, SIGNAL(clicked()),
2603                 this, SIGNAL(changed()));
2604         connect(allowGeometrySessionCB, SIGNAL(clicked()),
2605                 this, SIGNAL(changed()));
2606         connect(autoSaveSB, SIGNAL(valueChanged(int)),
2607                 this, SIGNAL(changed()));
2608         connect(autoSaveCB, SIGNAL(clicked()),
2609                 this, SIGNAL(changed()));
2610         connect(backupCB, SIGNAL(clicked()),
2611                 this, SIGNAL(changed()));
2612         connect(saveCompressedCB, SIGNAL(clicked()),
2613                 this, SIGNAL(changed()));
2614         connect(saveOriginCB, SIGNAL(clicked()),
2615                 this, SIGNAL(changed()));
2616 }
2617
2618
2619 void PrefDocHandling::applyRC(LyXRC & rc) const
2620 {
2621         rc.use_lastfilepos = restoreCursorCB->isChecked();
2622         rc.load_session = loadSessionCB->isChecked();
2623         rc.allow_geometry_session = allowGeometrySessionCB->isChecked();
2624         rc.autosave = autoSaveCB->isChecked() ?  autoSaveSB->value() * 60 : 0;
2625         rc.make_backup = backupCB->isChecked();
2626         rc.save_compressed = saveCompressedCB->isChecked();
2627         rc.save_origin = saveOriginCB->isChecked();
2628         rc.open_buffers_in_tabs = openDocumentsInTabsCB->isChecked();
2629         rc.single_instance = singleInstanceCB->isChecked();
2630         rc.single_close_tab_button = singleCloseTabButtonCB->isChecked();
2631
2632         switch (closeLastViewCO->currentIndex()) {
2633         case 0:
2634                 rc.close_buffer_with_last_view = "yes";
2635                 break;
2636         case 1:
2637                 rc.close_buffer_with_last_view = "no";
2638                 break;
2639         case 2:
2640                 rc.close_buffer_with_last_view = "ask";
2641                 break;
2642         default:
2643                 ;
2644         }
2645 }
2646
2647
2648 void PrefDocHandling::updateRC(LyXRC const & rc)
2649 {
2650         restoreCursorCB->setChecked(rc.use_lastfilepos);
2651         loadSessionCB->setChecked(rc.load_session);
2652         allowGeometrySessionCB->setChecked(rc.allow_geometry_session);
2653         // convert to minutes
2654         bool autosave = rc.autosave > 0;
2655         int mins = rc.autosave / 60;
2656         if (!mins)
2657                 mins = 5;
2658         autoSaveSB->setValue(mins);
2659         autoSaveCB->setChecked(autosave);
2660         autoSaveSB->setEnabled(autosave);
2661         backupCB->setChecked(rc.make_backup);
2662         saveCompressedCB->setChecked(rc.save_compressed);
2663         saveOriginCB->setChecked(rc.save_origin);
2664         openDocumentsInTabsCB->setChecked(rc.open_buffers_in_tabs);
2665         singleInstanceCB->setChecked(rc.single_instance && !rc.lyxpipes.empty());
2666         singleInstanceCB->setEnabled(!rc.lyxpipes.empty());
2667         singleCloseTabButtonCB->setChecked(rc.single_close_tab_button);
2668         if (rc.close_buffer_with_last_view == "yes")
2669                 closeLastViewCO->setCurrentIndex(0);
2670         else if (rc.close_buffer_with_last_view == "no")
2671                 closeLastViewCO->setCurrentIndex(1);
2672         else if (rc.close_buffer_with_last_view == "ask")
2673                 closeLastViewCO->setCurrentIndex(2);
2674 }
2675
2676
2677 void PrefDocHandling::on_clearSessionPB_clicked()
2678 {
2679         guiApp->clearSession();
2680 }
2681
2682
2683
2684 /////////////////////////////////////////////////////////////////////
2685 //
2686 // PrefEdit
2687 //
2688 /////////////////////////////////////////////////////////////////////
2689
2690 PrefEdit::PrefEdit(GuiPreferences * form)
2691         : PrefModule(catEditing, N_("Control"), form)
2692 {
2693         setupUi(this);
2694
2695         connect(cursorFollowsCB, SIGNAL(clicked()),
2696                 this, SIGNAL(changed()));
2697         connect(scrollBelowCB, SIGNAL(clicked()),
2698                 this, SIGNAL(changed()));
2699         connect(macLikeCursorMovementCB, SIGNAL(clicked()),
2700                 this, SIGNAL(changed()));
2701         connect(sortEnvironmentsCB, SIGNAL(clicked()),
2702                 this, SIGNAL(changed()));
2703         connect(groupEnvironmentsCB, SIGNAL(clicked()),
2704                 this, SIGNAL(changed()));
2705         connect(macroEditStyleCO, SIGNAL(activated(int)),
2706                 this, SIGNAL(changed()));
2707         connect(cursorWidthSB, SIGNAL(valueChanged(int)),
2708                 this, SIGNAL(changed()));
2709         connect(fullscreenLimitGB, SIGNAL(clicked()),
2710                 this, SIGNAL(changed()));
2711         connect(fullscreenWidthSB, SIGNAL(valueChanged(int)),
2712                 this, SIGNAL(changed()));
2713         connect(toggleTabbarCB, SIGNAL(toggled(bool)),
2714                 this, SIGNAL(changed()));
2715         connect(toggleMenubarCB, SIGNAL(toggled(bool)),
2716                 this, SIGNAL(changed()));
2717         connect(toggleScrollbarCB, SIGNAL(toggled(bool)),
2718                 this, SIGNAL(changed()));
2719         connect(toggleStatusbarCB, SIGNAL(toggled(bool)),
2720                 this, SIGNAL(changed()));
2721         connect(toggleToolbarsCB, SIGNAL(toggled(bool)),
2722                 this, SIGNAL(changed()));
2723 }
2724
2725
2726 void PrefEdit::applyRC(LyXRC & rc) const
2727 {
2728         rc.cursor_follows_scrollbar = cursorFollowsCB->isChecked();
2729         rc.scroll_below_document = scrollBelowCB->isChecked();
2730         rc.mac_like_cursor_movement = macLikeCursorMovementCB->isChecked();
2731         rc.sort_layouts = sortEnvironmentsCB->isChecked();
2732         rc.group_layouts = groupEnvironmentsCB->isChecked();
2733         switch (macroEditStyleCO->currentIndex()) {
2734                 case 0: rc.macro_edit_style = LyXRC::MACRO_EDIT_INLINE_BOX; break;
2735                 case 1: rc.macro_edit_style = LyXRC::MACRO_EDIT_INLINE; break;
2736                 case 2: rc.macro_edit_style = LyXRC::MACRO_EDIT_LIST;   break;
2737         }
2738         rc.cursor_width = cursorWidthSB->value();
2739         rc.full_screen_toolbars = toggleToolbarsCB->isChecked();
2740         rc.full_screen_scrollbar = toggleScrollbarCB->isChecked();
2741         rc.full_screen_statusbar = toggleStatusbarCB->isChecked();
2742         rc.full_screen_tabbar = toggleTabbarCB->isChecked();
2743         rc.full_screen_menubar = toggleMenubarCB->isChecked();
2744         rc.full_screen_width = fullscreenWidthSB->value();
2745         rc.full_screen_limit = fullscreenLimitGB->isChecked();
2746 }
2747
2748
2749 void PrefEdit::updateRC(LyXRC const & rc)
2750 {
2751         cursorFollowsCB->setChecked(rc.cursor_follows_scrollbar);
2752         scrollBelowCB->setChecked(rc.scroll_below_document);
2753         macLikeCursorMovementCB->setChecked(rc.mac_like_cursor_movement);
2754         sortEnvironmentsCB->setChecked(rc.sort_layouts);
2755         groupEnvironmentsCB->setChecked(rc.group_layouts);
2756         macroEditStyleCO->setCurrentIndex(rc.macro_edit_style);
2757         cursorWidthSB->setValue(rc.cursor_width);
2758         toggleScrollbarCB->setChecked(rc.full_screen_scrollbar);
2759         toggleStatusbarCB->setChecked(rc.full_screen_statusbar);
2760         toggleToolbarsCB->setChecked(rc.full_screen_toolbars);
2761         toggleTabbarCB->setChecked(rc.full_screen_tabbar);
2762         toggleMenubarCB->setChecked(rc.full_screen_menubar);
2763         fullscreenWidthSB->setValue(rc.full_screen_width);
2764         fullscreenLimitGB->setChecked(rc.full_screen_limit);
2765 }
2766
2767
2768 /////////////////////////////////////////////////////////////////////
2769 //
2770 // PrefShortcuts
2771 //
2772 /////////////////////////////////////////////////////////////////////
2773
2774
2775 GuiShortcutDialog::GuiShortcutDialog(QWidget * parent) : QDialog(parent)
2776 {
2777         Ui::shortcutUi::setupUi(this);
2778         QDialog::setModal(true);
2779 }
2780
2781
2782 PrefShortcuts::PrefShortcuts(GuiPreferences * form)
2783         : PrefModule(catEditing, N_("Shortcuts"), form),
2784           editItem_(0), mathItem_(0), bufferItem_(0), layoutItem_(0),
2785           systemItem_(0)
2786 {
2787         setupUi(this);
2788
2789         shortcutsTW->setColumnCount(2);
2790         shortcutsTW->headerItem()->setText(0, qt_("Function"));
2791         shortcutsTW->headerItem()->setText(1, qt_("Shortcut"));
2792         shortcutsTW->setSortingEnabled(true);
2793         // Multi-selection can be annoying.
2794         // shortcutsTW->setSelectionMode(QAbstractItemView::MultiSelection);
2795
2796         connect(bindFilePB, SIGNAL(clicked()),
2797                 this, SLOT(selectBind()));
2798         connect(bindFileED, SIGNAL(textChanged(QString)),
2799                 this, SIGNAL(changed()));
2800
2801         shortcut_ = new GuiShortcutDialog(this);
2802         shortcut_bc_.setPolicy(ButtonPolicy::OkCancelPolicy);
2803         shortcut_bc_.setOK(shortcut_->okPB);
2804         shortcut_bc_.setCancel(shortcut_->cancelPB);
2805
2806         connect(shortcut_->okPB, SIGNAL(clicked()),
2807                 this, SIGNAL(changed()));
2808         connect(shortcut_->cancelPB, SIGNAL(clicked()),
2809                 shortcut_, SLOT(reject()));
2810         connect(shortcut_->clearPB, SIGNAL(clicked()),
2811                 this, SLOT(shortcutClearPressed()));
2812         connect(shortcut_->removePB, SIGNAL(clicked()),
2813                 this, SLOT(shortcutRemovePressed()));
2814         connect(shortcut_->okPB, SIGNAL(clicked()),
2815                 this, SLOT(shortcutOkPressed()));
2816         connect(shortcut_->cancelPB, SIGNAL(clicked()),
2817                 this, SLOT(shortcutCancelPressed()));
2818 }
2819
2820
2821 void PrefShortcuts::applyRC(LyXRC & rc) const
2822 {
2823         rc.bind_file = internal_path(fromqstr(bindFileED->text()));
2824         // write user_bind and user_unbind to .lyx/bind/user.bind
2825         FileName bind_dir(addPath(package().user_support().absFileName(), "bind"));
2826         if (!bind_dir.exists() && !bind_dir.createDirectory(0777)) {
2827                 lyxerr << "LyX could not create the user bind directory '"
2828                        << bind_dir << "'. All user-defined key bindings will be lost." << endl;
2829                 return;
2830         }
2831         if (!bind_dir.isDirWritable()) {
2832                 lyxerr << "LyX could not write to the user bind directory '"
2833                        << bind_dir << "'. All user-defined key bindings will be lost." << endl;
2834                 return;
2835         }
2836         FileName user_bind_file(bind_dir.absFileName() + "/user.bind");
2837         user_unbind_.write(user_bind_file.toFilesystemEncoding(), false, true);
2838         user_bind_.write(user_bind_file.toFilesystemEncoding(), true, false);
2839         // immediately apply the keybindings. Why this is not done before?
2840         // The good thing is that the menus are updated automatically.
2841         theTopLevelKeymap().clear();
2842         theTopLevelKeymap().read("site");
2843         theTopLevelKeymap().read(rc.bind_file, 0, KeyMap::Fallback);
2844         theTopLevelKeymap().read("user", 0, KeyMap::MissingOK);
2845 }
2846
2847
2848 void PrefShortcuts::updateRC(LyXRC const & rc)
2849 {
2850         bindFileED->setText(toqstr(external_path(rc.bind_file)));
2851         //
2852         system_bind_.clear();
2853         user_bind_.clear();
2854         user_unbind_.clear();
2855         system_bind_.read("site");
2856         system_bind_.read(rc.bind_file);
2857         // \unbind in user.bind is added to user_unbind_
2858         user_bind_.read("user", &user_unbind_, KeyMap::MissingOK);
2859         updateShortcutsTW();
2860 }
2861
2862
2863 void PrefShortcuts::updateShortcutsTW()
2864 {
2865         shortcutsTW->clear();
2866
2867         editItem_ = new QTreeWidgetItem(shortcutsTW);
2868         editItem_->setText(0, qt_("Cursor, Mouse and Editing Functions"));
2869         editItem_->setFlags(editItem_->flags() & ~Qt::ItemIsSelectable);
2870
2871         mathItem_ = new QTreeWidgetItem(shortcutsTW);
2872         mathItem_->setText(0, qt_("Mathematical Symbols"));
2873         mathItem_->setFlags(mathItem_->flags() & ~Qt::ItemIsSelectable);
2874
2875         bufferItem_ = new QTreeWidgetItem(shortcutsTW);
2876         bufferItem_->setText(0, qt_("Document and Window"));
2877         bufferItem_->setFlags(bufferItem_->flags() & ~Qt::ItemIsSelectable);
2878
2879         layoutItem_ = new QTreeWidgetItem(shortcutsTW);
2880         layoutItem_->setText(0, qt_("Font, Layouts and Textclasses"));
2881         layoutItem_->setFlags(layoutItem_->flags() & ~Qt::ItemIsSelectable);
2882
2883         systemItem_ = new QTreeWidgetItem(shortcutsTW);
2884         systemItem_->setText(0, qt_("System and Miscellaneous"));
2885         systemItem_->setFlags(systemItem_->flags() & ~Qt::ItemIsSelectable);
2886
2887         // listBindings(unbound=true) lists all bound and unbound lfuns
2888         // Items in this list is tagged by its source.
2889         KeyMap::BindingList bindinglist = system_bind_.listBindings(true,
2890                 KeyMap::System);
2891         KeyMap::BindingList user_bindinglist = user_bind_.listBindings(false,
2892                 KeyMap::UserBind);
2893         KeyMap::BindingList user_unbindinglist = user_unbind_.listBindings(false,
2894                 KeyMap::UserUnbind);
2895         bindinglist.insert(bindinglist.end(), user_bindinglist.begin(),
2896                         user_bindinglist.end());
2897         bindinglist.insert(bindinglist.end(), user_unbindinglist.begin(),
2898                         user_unbindinglist.end());
2899
2900         KeyMap::BindingList::const_iterator it = bindinglist.begin();
2901         KeyMap::BindingList::const_iterator it_end = bindinglist.end();
2902         for (; it != it_end; ++it)
2903                 insertShortcutItem(it->request, it->sequence, it->tag);
2904
2905         shortcutsTW->sortItems(0, Qt::AscendingOrder);
2906         on_shortcutsTW_itemSelectionChanged();
2907         on_searchLE_textEdited();
2908         shortcutsTW->resizeColumnToContents(0);
2909 }
2910
2911
2912 //static
2913 KeyMap::ItemType PrefShortcuts::itemType(QTreeWidgetItem & item)
2914 {
2915         return static_cast<KeyMap::ItemType>(item.data(0, Qt::UserRole).toInt());
2916 }
2917
2918
2919 //static
2920 bool PrefShortcuts::isAlwaysHidden(QTreeWidgetItem & item)
2921 {
2922         // Hide rebound system settings that are empty
2923         return itemType(item) == KeyMap::UserUnbind && item.text(1).isEmpty();
2924 }
2925
2926
2927 void PrefShortcuts::setItemType(QTreeWidgetItem * item, KeyMap::ItemType tag)
2928 {
2929         item->setData(0, Qt::UserRole, QVariant(tag));
2930         QFont font;
2931
2932         switch (tag) {
2933         case KeyMap::System:
2934                 break;
2935         case KeyMap::UserBind:
2936                 font.setBold(true);
2937                 break;
2938         case KeyMap::UserUnbind:
2939                 font.setStrikeOut(true);
2940                 break;
2941         // this item is not displayed now.
2942         case KeyMap::UserExtraUnbind:
2943                 font.setStrikeOut(true);
2944                 break;
2945         }
2946         item->setHidden(isAlwaysHidden(*item));
2947         item->setFont(1, font);
2948 }
2949
2950
2951 QTreeWidgetItem * PrefShortcuts::insertShortcutItem(FuncRequest const & lfun,
2952                 KeySequence const & seq, KeyMap::ItemType tag)
2953 {
2954         FuncCode const action = lfun.action();
2955         string const action_name = lyxaction.getActionName(action);
2956         QString const lfun_name = toqstr(from_utf8(action_name)
2957                         + ' ' + lfun.argument());
2958         QString const shortcut = toqstr(seq.print(KeySequence::ForGui));
2959
2960         QTreeWidgetItem * newItem = 0;
2961         // for unbind items, try to find an existing item in the system bind list
2962         if (tag == KeyMap::UserUnbind) {
2963                 QList<QTreeWidgetItem*> const items = shortcutsTW->findItems(lfun_name,
2964                         Qt::MatchFlags(Qt::MatchExactly | Qt::MatchRecursive), 0);
2965                 for (int i = 0; i < items.size(); ++i) {
2966                         if (items[i]->text(1) == shortcut) {
2967                                 newItem = items[i];
2968                                 break;
2969                         }
2970                 }
2971                 // if not found, this unbind item is KeyMap::UserExtraUnbind
2972                 // Such an item is not displayed to avoid confusion (what is
2973                 // unmatched removed?).
2974                 if (!newItem) {
2975                         return 0;
2976                 }
2977         }
2978         if (!newItem) {
2979                 switch(lyxaction.getActionType(action)) {
2980                 case LyXAction::Hidden:
2981                         return 0;
2982                 case LyXAction::Edit:
2983                         newItem = new QTreeWidgetItem(editItem_);
2984                         break;
2985                 case LyXAction::Math:
2986                         newItem = new QTreeWidgetItem(mathItem_);
2987                         break;
2988                 case LyXAction::Buffer:
2989                         newItem = new QTreeWidgetItem(bufferItem_);
2990                         break;
2991                 case LyXAction::Layout:
2992                         newItem = new QTreeWidgetItem(layoutItem_);
2993                         break;
2994                 case LyXAction::System:
2995                         newItem = new QTreeWidgetItem(systemItem_);
2996                         break;
2997                 default:
2998                         // this should not happen
2999                         newItem = new QTreeWidgetItem(shortcutsTW);
3000                 }
3001         }
3002
3003         newItem->setText(0, lfun_name);
3004         newItem->setText(1, shortcut);
3005         // record BindFile representation to recover KeySequence when needed.
3006         newItem->setData(1, Qt::UserRole, toqstr(seq.print(KeySequence::BindFile)));
3007         setItemType(newItem, tag);
3008         return newItem;
3009 }
3010
3011
3012 void PrefShortcuts::on_shortcutsTW_itemSelectionChanged()
3013 {
3014         QList<QTreeWidgetItem*> items = shortcutsTW->selectedItems();
3015         removePB->setEnabled(!items.isEmpty() && !items[0]->text(1).isEmpty());
3016         modifyPB->setEnabled(!items.isEmpty());
3017         if (items.isEmpty())
3018                 return;
3019
3020         if (itemType(*items[0]) == KeyMap::UserUnbind)
3021                 removePB->setText(qt_("Res&tore"));
3022         else
3023                 removePB->setText(qt_("Remo&ve"));
3024 }
3025
3026
3027 void PrefShortcuts::on_shortcutsTW_itemDoubleClicked()
3028 {
3029         modifyShortcut();
3030 }
3031
3032
3033 void PrefShortcuts::modifyShortcut()
3034 {
3035         QTreeWidgetItem * item = shortcutsTW->currentItem();
3036         if (item->flags() & Qt::ItemIsSelectable) {
3037                 shortcut_->lfunLE->setText(item->text(0));
3038                 save_lfun_ = item->text(0).trimmed();
3039                 shortcut_->shortcutWG->setText(item->text(1));
3040                 KeySequence seq;
3041                 seq.parse(fromqstr(item->data(1, Qt::UserRole).toString()));
3042                 shortcut_->shortcutWG->setKeySequence(seq);
3043                 shortcut_->shortcutWG->setFocus();
3044                 shortcut_->exec();
3045         }
3046 }
3047
3048
3049 void PrefShortcuts::unhideEmpty(QString const & lfun, bool select)
3050 {
3051         // list of items that match lfun
3052         QList<QTreeWidgetItem*> items = shortcutsTW->findItems(lfun,
3053              Qt::MatchFlags(Qt::MatchExactly | Qt::MatchRecursive), 0);
3054         for (int i = 0; i < items.size(); ++i) {
3055                 QTreeWidgetItem * item = items[i];
3056                 if (isAlwaysHidden(*item)) {
3057                         setItemType(item, KeyMap::System);
3058                         if (select)
3059                                 shortcutsTW->setCurrentItem(item);
3060                         return;
3061                 }
3062         }
3063 }
3064
3065
3066 void PrefShortcuts::removeShortcut()
3067 {
3068         // it seems that only one item can be selected, but I am
3069         // removing all selected items anyway.
3070         QList<QTreeWidgetItem*> items = shortcutsTW->selectedItems();
3071         for (int i = 0; i < items.size(); ++i) {
3072                 string shortcut = fromqstr(items[i]->data(1, Qt::UserRole).toString());
3073                 string lfun = fromqstr(items[i]->text(0));
3074                 FuncRequest func = lyxaction.lookupFunc(lfun);
3075
3076                 switch (itemType(*items[i])) {
3077                 case KeyMap::System: {
3078                         // for system bind, we do not touch the item
3079                         // but add an user unbind item
3080                         user_unbind_.bind(shortcut, func);
3081                         setItemType(items[i], KeyMap::UserUnbind);
3082                         removePB->setText(qt_("Res&tore"));
3083                         break;
3084                 }
3085                 case KeyMap::UserBind: {
3086                         // for user_bind, we remove this bind
3087                         QTreeWidgetItem * parent = items[i]->parent();
3088                         int itemIdx = parent->indexOfChild(items[i]);
3089                         parent->takeChild(itemIdx);
3090                         if (itemIdx > 0)
3091                                 shortcutsTW->scrollToItem(parent->child(itemIdx - 1));
3092                         else
3093                                 shortcutsTW->scrollToItem(parent);
3094                         user_bind_.unbind(shortcut, func);
3095                         // If this user binding hid an empty system binding, unhide the
3096                         // latter and select it.
3097                         unhideEmpty(items[i]->text(0), true);
3098                         break;
3099                 }
3100                 case KeyMap::UserUnbind: {
3101                         // for user_unbind, we remove the unbind, and the item
3102                         // become KeyMap::System again.
3103                         KeySequence seq;
3104                         seq.parse(shortcut);
3105                         // Ask the user to replace current binding
3106                         if (!validateNewShortcut(func, seq, QString()))
3107                                 break;
3108                         user_unbind_.unbind(shortcut, func);
3109                         setItemType(items[i], KeyMap::System);
3110                         removePB->setText(qt_("Remo&ve"));
3111                         break;
3112                 }
3113                 case KeyMap::UserExtraUnbind: {
3114                         // for user unbind that is not in system bind file,
3115                         // remove this unbind file
3116                         QTreeWidgetItem * parent = items[i]->parent();
3117                         parent->takeChild(parent->indexOfChild(items[i]));
3118                         user_unbind_.unbind(shortcut, func);
3119                 }
3120                 }
3121         }
3122 }
3123
3124
3125 void PrefShortcuts::deactivateShortcuts(QList<QTreeWidgetItem*> const & items)
3126 {
3127         for (int i = 0; i < items.size(); ++i) {
3128                 string shortcut = fromqstr(items[i]->data(1, Qt::UserRole).toString());
3129                 string lfun = fromqstr(items[i]->text(0));
3130                 FuncRequest func = lyxaction.lookupFunc(lfun);
3131
3132                 switch (itemType(*items[i])) {
3133                 case KeyMap::System:
3134                         // for system bind, we do not touch the item
3135                         // but add an user unbind item
3136                         user_unbind_.bind(shortcut, func);
3137                         setItemType(items[i], KeyMap::UserUnbind);
3138                         break;
3139
3140                 case KeyMap::UserBind: {
3141                         // for user_bind, we remove this bind
3142                         QTreeWidgetItem * parent = items[i]->parent();
3143                         int itemIdx = parent->indexOfChild(items[i]);
3144                         parent->takeChild(itemIdx);
3145                         user_bind_.unbind(shortcut, func);
3146                         unhideEmpty(items[i]->text(0), false);
3147                         break;
3148                 }
3149                 default:
3150                         break;
3151                 }
3152         }
3153 }
3154
3155
3156 void PrefShortcuts::selectBind()
3157 {
3158         QString file = form_->browsebind(internalPath(bindFileED->text()));
3159         if (!file.isEmpty()) {
3160                 bindFileED->setText(file);
3161                 system_bind_ = KeyMap();
3162                 system_bind_.read(fromqstr(file));
3163                 updateShortcutsTW();
3164         }
3165 }
3166
3167
3168 void PrefShortcuts::on_modifyPB_pressed()
3169 {
3170         modifyShortcut();
3171 }
3172
3173
3174 void PrefShortcuts::on_newPB_pressed()
3175 {
3176         shortcut_->lfunLE->clear();
3177         shortcut_->shortcutWG->reset();
3178         save_lfun_ = QString();
3179         shortcut_->exec();
3180 }
3181
3182
3183 void PrefShortcuts::on_removePB_pressed()
3184 {
3185         changed();
3186         removeShortcut();
3187 }
3188
3189
3190 void PrefShortcuts::on_searchLE_textEdited()
3191 {
3192         if (searchLE->text().isEmpty()) {
3193                 // show all hidden items
3194                 QTreeWidgetItemIterator it(shortcutsTW, QTreeWidgetItemIterator::Hidden);
3195                 for (; *it; ++it)
3196                         shortcutsTW->setItemHidden(*it, isAlwaysHidden(**it));
3197                 // close all categories
3198                 for (int i = 0; i < shortcutsTW->topLevelItemCount(); ++i)
3199                         shortcutsTW->collapseItem(shortcutsTW->topLevelItem(i));
3200                 return;
3201         }
3202         // search both columns
3203         QList<QTreeWidgetItem *> matched = shortcutsTW->findItems(searchLE->text(),
3204                 Qt::MatchFlags(Qt::MatchContains | Qt::MatchRecursive), 0);
3205         matched += shortcutsTW->findItems(searchLE->text(),
3206                 Qt::MatchFlags(Qt::MatchContains | Qt::MatchRecursive), 1);
3207
3208         // hide everyone (to avoid searching in matched QList repeatedly
3209         QTreeWidgetItemIterator it(shortcutsTW, QTreeWidgetItemIterator::Selectable);
3210         while (*it)
3211                 shortcutsTW->setItemHidden(*it++, true);
3212         // show matched items
3213         for (int i = 0; i < matched.size(); ++i)
3214                 if (!isAlwaysHidden(*matched[i])) {
3215                         shortcutsTW->setItemHidden(matched[i], false);
3216                         shortcutsTW->setItemExpanded(matched[i]->parent(), true);
3217                 }
3218 }
3219
3220
3221 docstring makeCmdString(FuncRequest const & f)
3222 {
3223         docstring actionStr = from_ascii(lyxaction.getActionName(f.action()));
3224         if (!f.argument().empty())
3225                 actionStr += " " + f.argument();
3226         return actionStr;
3227 }
3228
3229
3230 FuncRequest PrefShortcuts::currentBinding(KeySequence const & k)
3231 {
3232         FuncRequest res = user_bind_.getBinding(k);
3233         if (res.action() != LFUN_UNKNOWN_ACTION)
3234                 return res;
3235         res = system_bind_.getBinding(k);
3236         // Check if it is unbound. Note: user_unbind_ can only unbind one
3237         // FuncRequest per key sequence.
3238         if (user_unbind_.getBinding(k) == res)
3239                 return FuncRequest::unknown;
3240         return res;
3241 }
3242
3243
3244 bool PrefShortcuts::validateNewShortcut(FuncRequest const & func,
3245                                         KeySequence const & k,
3246                                         QString const & lfun_to_modify)
3247 {
3248         if (func.action() == LFUN_UNKNOWN_ACTION) {
3249                 Alert::error(_("Failed to create shortcut"),
3250                         _("Unknown or invalid LyX function"));
3251                 return false;
3252         }
3253
3254         // It is not currently possible to bind Hidden lfuns such as self-insert. In
3255         // the future, to remove this limitation, see GuiPrefs::insertShortcutItem
3256         // and how it is used in GuiPrefs::shortcutOkPressed.
3257         if (lyxaction.getActionType(func.action()) == LyXAction::Hidden) {
3258                 Alert::error(_("Failed to create shortcut"),
3259                         _("This LyX function is hidden and cannot be bound."));
3260                 return false;
3261         }
3262
3263         if (k.length() == 0) {
3264                 Alert::error(_("Failed to create shortcut"),
3265                         _("Invalid or empty key sequence"));
3266                 return false;
3267         }
3268
3269         FuncRequest oldBinding = currentBinding(k);
3270         if (oldBinding == func)
3271                 // nothing to change
3272                 return false;
3273
3274         // make sure this key isn't already bound---and, if so, prompt user
3275         // (exclude the lfun the user already wants to modify)
3276         docstring const action_string = makeCmdString(oldBinding);
3277         if (oldBinding.action() != LFUN_UNKNOWN_ACTION
3278             && lfun_to_modify != toqstr(action_string)) {
3279                 docstring const new_action_string = makeCmdString(func);
3280                 docstring const text = bformat(_("Shortcut `%1$s' is already bound to "
3281                                                  "%2$s.\n"
3282                                                  "Are you sure you want to unbind the "
3283                                                  "current shortcut and bind it to %3$s?"),
3284                                                k.print(KeySequence::ForGui), action_string,
3285                                                new_action_string);
3286                 int ret = Alert::prompt(_("Redefine shortcut?"),
3287                                         text, 0, 1, _("&Redefine"), _("&Cancel"));
3288                 if (ret != 0)
3289                         return false;
3290                 QString const sequence_text = toqstr(k.print(KeySequence::ForGui));
3291                 QList<QTreeWidgetItem*> items = shortcutsTW->findItems(sequence_text,
3292                         Qt::MatchFlags(Qt::MatchExactly | Qt::MatchRecursive), 1);
3293                 deactivateShortcuts(items);
3294         }
3295         return true;
3296 }
3297
3298
3299 void PrefShortcuts::shortcutOkPressed()
3300 {
3301         QString const new_lfun = shortcut_->lfunLE->text();
3302         FuncRequest func = lyxaction.lookupFunc(fromqstr(new_lfun));
3303         KeySequence k = shortcut_->shortcutWG->getKeySequence();
3304
3305         // save_lfun_ contains the text of the lfun to modify, if the user clicked
3306         // "modify", or is empty if they clicked "new" (which I do not really like)
3307         if (!validateNewShortcut(func, k, save_lfun_))
3308                 return;
3309
3310         if (!save_lfun_.isEmpty()) {
3311                 // real modification of the lfun's shortcut,
3312                 // so remove the previous one
3313                 QList<QTreeWidgetItem*> to_modify = shortcutsTW->selectedItems();
3314                 deactivateShortcuts(to_modify);
3315         }
3316
3317         shortcut_->accept();
3318
3319         QTreeWidgetItem * item = insertShortcutItem(func, k, KeyMap::UserBind);
3320         if (item) {
3321                 user_bind_.bind(&k, func);
3322                 shortcutsTW->sortItems(0, Qt::AscendingOrder);
3323                 shortcutsTW->setItemExpanded(item->parent(), true);
3324                 shortcutsTW->setCurrentItem(item);
3325                 shortcutsTW->scrollToItem(item);
3326         } else {
3327                 Alert::error(_("Failed to create shortcut"),
3328                         _("Can not insert shortcut to the list"));
3329                 return;
3330         }
3331 }
3332
3333
3334 void PrefShortcuts::shortcutCancelPressed()
3335 {
3336         shortcut_->shortcutWG->reset();
3337 }
3338
3339
3340 void PrefShortcuts::shortcutClearPressed()
3341 {
3342         shortcut_->shortcutWG->reset();
3343 }
3344
3345
3346 void PrefShortcuts::shortcutRemovePressed()
3347 {
3348         shortcut_->shortcutWG->removeFromSequence();
3349 }
3350
3351
3352 /////////////////////////////////////////////////////////////////////
3353 //
3354 // PrefIdentity
3355 //
3356 /////////////////////////////////////////////////////////////////////
3357
3358 PrefIdentity::PrefIdentity(GuiPreferences * form)
3359         : PrefModule(QString(), N_("Identity"), form)
3360 {
3361         setupUi(this);
3362
3363         connect(nameED, SIGNAL(textChanged(QString)),
3364                 this, SIGNAL(changed()));
3365         connect(emailED, SIGNAL(textChanged(QString)),
3366                 this, SIGNAL(changed()));
3367
3368         nameED->setValidator(new NoNewLineValidator(nameED));
3369         emailED->setValidator(new NoNewLineValidator(emailED));
3370 }
3371
3372
3373 void PrefIdentity::applyRC(LyXRC & rc) const
3374 {
3375         rc.user_name = fromqstr(nameED->text());
3376         rc.user_email = fromqstr(emailED->text());
3377 }
3378
3379
3380 void PrefIdentity::updateRC(LyXRC const & rc)
3381 {
3382         nameED->setText(toqstr(rc.user_name));
3383         emailED->setText(toqstr(rc.user_email));
3384 }
3385
3386
3387
3388 /////////////////////////////////////////////////////////////////////
3389 //
3390 // GuiPreferences
3391 //
3392 /////////////////////////////////////////////////////////////////////
3393
3394 GuiPreferences::GuiPreferences(GuiView & lv)
3395         : GuiDialog(lv, "prefs", qt_("Preferences")), update_screen_font_(false),
3396           update_previews_(false)
3397 {
3398         setupUi(this);
3399
3400         QDialog::setModal(false);
3401
3402         connect(savePB, SIGNAL(clicked()), this, SLOT(slotOK()));
3403         connect(applyPB, SIGNAL(clicked()), this, SLOT(slotApply()));
3404         connect(closePB, SIGNAL(clicked()), this, SLOT(slotClose()));
3405         connect(restorePB, SIGNAL(clicked()), this, SLOT(slotRestore()));
3406
3407         addModule(new PrefUserInterface(this));
3408         addModule(new PrefDocHandling(this));
3409         addModule(new PrefEdit(this));
3410         addModule(new PrefShortcuts(this));
3411         PrefScreenFonts * screenfonts = new PrefScreenFonts(this);
3412         connect(this, SIGNAL(prefsApplied(LyXRC const &)),
3413                         screenfonts, SLOT(updateScreenFontSizes(LyXRC const &)));
3414         addModule(screenfonts);
3415         addModule(new PrefColors(this));
3416         addModule(new PrefDisplay(this));
3417         addModule(new PrefInput(this));
3418         addModule(new PrefCompletion(this));
3419
3420         addModule(new PrefPaths(this));
3421
3422         addModule(new PrefIdentity(this));
3423
3424         addModule(new PrefLanguage(this));
3425         addModule(new PrefSpellchecker(this));
3426
3427         //for strftime validator
3428         PrefOutput * output = new PrefOutput(this);
3429         addModule(output);
3430         addModule(new PrefLatex(this));
3431
3432         PrefConverters * converters = new PrefConverters(this);
3433         PrefFileformats * formats = new PrefFileformats(this);
3434         connect(formats, SIGNAL(formatsChanged()),
3435                         converters, SLOT(updateGui()));
3436         addModule(converters);
3437         addModule(formats);
3438
3439         prefsPS->setCurrentPanel("User Interface");
3440 // FIXME: hack to work around resizing bug in Qt >= 4.2
3441 // bug verified with Qt 4.2.{0-3} (JSpitzm)
3442 #if QT_VERSION >= 0x040200
3443         prefsPS->updateGeometry();
3444 #endif
3445
3446         bc().setPolicy(ButtonPolicy::PreferencesPolicy);
3447         bc().setOK(savePB);
3448         bc().setApply(applyPB);
3449         bc().setCancel(closePB);
3450         bc().setRestore(restorePB);
3451
3452         // initialize the strftime validator
3453         bc().addCheckedLineEdit(output->DateED);
3454 }
3455
3456
3457 void GuiPreferences::addModule(PrefModule * module)
3458 {
3459         LASSERT(module, return);
3460         if (module->category().isEmpty())
3461                 prefsPS->addPanel(module, module->title());
3462         else
3463                 prefsPS->addPanel(module, module->title(), module->category());
3464         connect(module, SIGNAL(changed()), this, SLOT(change_adaptor()));
3465         modules_.push_back(module);
3466 }
3467
3468
3469 void GuiPreferences::change_adaptor()
3470 {
3471         changed();
3472 }
3473
3474
3475 void GuiPreferences::applyRC(LyXRC & rc) const
3476 {
3477         size_t end = modules_.size();
3478         for (size_t i = 0; i != end; ++i)
3479                 modules_[i]->applyRC(rc);
3480 }
3481
3482
3483 void GuiPreferences::updateRC(LyXRC const & rc)
3484 {
3485         size_t const end = modules_.size();
3486         for (size_t i = 0; i != end; ++i)
3487                 modules_[i]->updateRC(rc);
3488 }
3489
3490
3491 void GuiPreferences::applyView()
3492 {
3493         applyRC(rc());
3494 }
3495
3496
3497 bool GuiPreferences::initialiseParams(string const &)
3498 {
3499         rc_ = lyxrc;
3500         formats_ = theFormats();
3501         converters_ = theConverters();
3502         converters_.update(formats_);
3503         movers_ = theMovers();
3504         colors_.clear();
3505         update_screen_font_ = false;
3506         update_previews_ = false;
3507
3508         updateRC(rc_);
3509         // Make sure that the bc is in the INITIAL state
3510         if (bc().policy().buttonStatus(ButtonPolicy::RESTORE))
3511                 bc().restore();
3512
3513         return true;
3514 }
3515
3516
3517 void GuiPreferences::dispatchParams()
3518 {
3519         ostringstream ss;
3520         rc_.write(ss, true);
3521         dispatch(FuncRequest(LFUN_LYXRC_APPLY, ss.str()));
3522         // issue prefsApplied signal. This will update the
3523         // localized screen font sizes.
3524         prefsApplied(rc_);
3525         // FIXME: these need lfuns
3526         // FIXME UNICODE
3527         Author const & author =
3528                 Author(from_utf8(rc_.user_name), from_utf8(rc_.user_email));
3529         theBufferList().recordCurrentAuthor(author);
3530
3531         theFormats() = formats_;
3532
3533         theConverters() = converters_;
3534         theConverters().update(formats_);
3535         theConverters().buildGraph();
3536         theBufferList().invalidateConverterCache();
3537         
3538         theMovers() = movers_;
3539
3540         vector<string>::const_iterator it = colors_.begin();
3541         vector<string>::const_iterator const end = colors_.end();
3542         for (; it != end; ++it)
3543                 dispatch(FuncRequest(LFUN_SET_COLOR, *it));
3544         colors_.clear();
3545
3546         if (update_screen_font_) {
3547                 dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3548                 // resets flag in case second apply in same dialog
3549                 update_screen_font_ = false;
3550         }
3551
3552         if (update_previews_) {
3553                 // resets flag in case second apply in same dialog
3554                 theBufferList().updatePreviews();
3555                 update_previews_ = false;
3556         }
3557
3558         // The Save button has been pressed
3559         if (isClosing())
3560                 dispatch(FuncRequest(LFUN_PREFERENCES_SAVE));
3561 }
3562
3563
3564 void GuiPreferences::setColor(ColorCode col, QString const & hex)
3565 {
3566         colors_.push_back(lcolor.getLyXName(col) + ' ' + fromqstr(hex));
3567 }
3568
3569
3570 void GuiPreferences::updateScreenFonts()
3571 {
3572         update_screen_font_ = true;
3573 }
3574
3575
3576 void GuiPreferences::updatePreviews()
3577 {
3578         update_previews_ = true;
3579 }
3580
3581
3582 QString GuiPreferences::browsebind(QString const & file) const
3583 {
3584         return browseLibFile("bind", file, "bind", qt_("Choose bind file"),
3585                              QStringList(qt_("LyX bind files (*.bind)")));
3586 }
3587
3588
3589 QString GuiPreferences::browseUI(QString const & file) const
3590 {
3591         return browseLibFile("ui", file, "ui", qt_("Choose UI file"),
3592                              QStringList(qt_("LyX UI files (*.ui)")));
3593 }
3594
3595
3596 QString GuiPreferences::browsekbmap(QString const & file) const
3597 {
3598         return browseLibFile("kbd", file, "kmap", qt_("Choose keyboard map"),
3599                              QStringList(qt_("LyX keyboard maps (*.kmap)")));
3600 }
3601
3602
3603 QString GuiPreferences::browse(QString const & file,
3604         QString const & title) const
3605 {
3606         return browseFile(file, title, QStringList(), true);
3607 }
3608
3609
3610 Dialog * createGuiPreferences(GuiView & lv) { return new GuiPreferences(lv); }
3611
3612
3613 } // namespace frontend
3614 } // namespace lyx
3615
3616 #include "moc_GuiPrefs.cpp"