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