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