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