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