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