]> git.lyx.org Git - features.git/blob - src/frontends/qt4/GuiPrefs.cpp
Fix bug #2844: Need option to overwrite without dialog popup
[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         Format const & from = form_->formats().get(converterFromCO->currentIndex());
1527         Format const & to = form_->formats().get(converterToCO->currentIndex());
1528         int const sel = form_->converters().getNumber(from.name(), to.name());
1529         bool const known = sel >= 0;
1530         bool const valid = !(converterED->text().isEmpty()
1531                 || from.name() == to.name());
1532
1533         int const cnr = convertersLW->currentItem()->type();
1534         Converter const & c = form_->converters().get(cnr);
1535         string const old_command = c.command;
1536         string const old_flag = c.flags;
1537         string const new_command = fromqstr(converterED->text());
1538         string const new_flag = fromqstr(converterFlagED->text());
1539
1540         bool modified = (old_command != new_command || old_flag != new_flag);
1541
1542         converterModifyPB->setEnabled(valid && known && modified);
1543         converterNewPB->setEnabled(valid && !known);
1544         converterRemovePB->setEnabled(known);
1545
1546         maxAgeLE->setEnabled(cacheCB->isChecked());
1547         maxAgeLA->setEnabled(cacheCB->isChecked());
1548 }
1549
1550
1551 // FIXME: user must
1552 // specify unique from/to or it doesn't appear. This is really bad UI
1553 // this is why we can use the same function for both new and modify
1554 void PrefConverters::updateConverter()
1555 {
1556         Format const & from = form_->formats().get(converterFromCO->currentIndex());
1557         Format const & to = form_->formats().get(converterToCO->currentIndex());
1558         string const flags = fromqstr(converterFlagED->text());
1559         string const command = fromqstr(converterED->text());
1560
1561         Converter const * old =
1562                 form_->converters().getConverter(from.name(), to.name());
1563         form_->converters().add(from.name(), to.name(), command, flags);
1564
1565         if (!old)
1566                 form_->converters().updateLast(form_->formats());
1567
1568         updateGui();
1569
1570         // Remove all files created by this converter from the cache, since
1571         // the modified converter might create different files.
1572         ConverterCache::get().remove_all(from.name(), to.name());
1573 }
1574
1575
1576 void PrefConverters::removeConverter()
1577 {
1578         Format const & from = form_->formats().get(converterFromCO->currentIndex());
1579         Format const & to = form_->formats().get(converterToCO->currentIndex());
1580         form_->converters().erase(from.name(), to.name());
1581
1582         updateGui();
1583
1584         // Remove all files created by this converter from the cache, since
1585         // a possible new converter might create different files.
1586         ConverterCache::get().remove_all(from.name(), to.name());
1587 }
1588
1589
1590 void PrefConverters::on_cacheCB_stateChanged(int state)
1591 {
1592         maxAgeLE->setEnabled(state == Qt::Checked);
1593         maxAgeLA->setEnabled(state == Qt::Checked);
1594         changed();
1595 }
1596
1597
1598 /////////////////////////////////////////////////////////////////////
1599 //
1600 // FormatValidator
1601 //
1602 /////////////////////////////////////////////////////////////////////
1603
1604 class FormatValidator : public QValidator
1605 {
1606 public:
1607         FormatValidator(QWidget *, Formats const & f);
1608         void fixup(QString & input) const;
1609         QValidator::State validate(QString & input, int & pos) const;
1610 private:
1611         virtual QString toString(Format const & format) const = 0;
1612         int nr() const;
1613         Formats const & formats_;
1614 };
1615
1616
1617 FormatValidator::FormatValidator(QWidget * parent, Formats const & f)
1618         : QValidator(parent), formats_(f)
1619 {
1620 }
1621
1622
1623 void FormatValidator::fixup(QString & input) const
1624 {
1625         Formats::const_iterator cit = formats_.begin();
1626         Formats::const_iterator end = formats_.end();
1627         for (; cit != end; ++cit) {
1628                 QString const name = toString(*cit);
1629                 if (distance(formats_.begin(), cit) == nr()) {
1630                         input = name;
1631                         return;
1632                 }
1633         }
1634 }
1635
1636
1637 QValidator::State FormatValidator::validate(QString & input, int & /*pos*/) const
1638 {
1639         Formats::const_iterator cit = formats_.begin();
1640         Formats::const_iterator end = formats_.end();
1641         bool unknown = true;
1642         for (; unknown && cit != end; ++cit) {
1643                 QString const name = toString(*cit);
1644                 if (distance(formats_.begin(), cit) != nr())
1645                         unknown = name != input;
1646         }
1647
1648         if (unknown && !input.isEmpty())
1649                 return QValidator::Acceptable;
1650         else
1651                 return QValidator::Intermediate;
1652 }
1653
1654
1655 int FormatValidator::nr() const
1656 {
1657         QComboBox * p = qobject_cast<QComboBox *>(parent());
1658         return p->itemData(p->currentIndex()).toInt();
1659 }
1660
1661
1662 /////////////////////////////////////////////////////////////////////
1663 //
1664 // FormatNameValidator
1665 //
1666 /////////////////////////////////////////////////////////////////////
1667
1668 class FormatNameValidator : public FormatValidator
1669 {
1670 public:
1671         FormatNameValidator(QWidget * parent, Formats const & f)
1672                 : FormatValidator(parent, f)
1673         {}
1674 private:
1675         QString toString(Format const & format) const
1676         {
1677                 return toqstr(format.name());
1678         }
1679 };
1680
1681
1682 /////////////////////////////////////////////////////////////////////
1683 //
1684 // FormatPrettynameValidator
1685 //
1686 /////////////////////////////////////////////////////////////////////
1687
1688 class FormatPrettynameValidator : public FormatValidator
1689 {
1690 public:
1691         FormatPrettynameValidator(QWidget * parent, Formats const & f)
1692                 : FormatValidator(parent, f)
1693         {}
1694 private:
1695         QString toString(Format const & format) const
1696         {
1697                 return qt_(format.prettyname());
1698         }
1699 };
1700
1701
1702 /////////////////////////////////////////////////////////////////////
1703 //
1704 // PrefFileformats
1705 //
1706 /////////////////////////////////////////////////////////////////////
1707
1708 PrefFileformats::PrefFileformats(GuiPreferences * form)
1709         : PrefModule(qt_(catFiles), qt_("File formats"), form)
1710 {
1711         setupUi(this);
1712         formatED->setValidator(new FormatNameValidator(formatsCB, form_->formats()));
1713         formatsCB->setValidator(new FormatPrettynameValidator(formatsCB, form_->formats()));
1714
1715         connect(documentCB, SIGNAL(clicked()),
1716                 this, SLOT(setFlags()));
1717         connect(vectorCB, SIGNAL(clicked()),
1718                 this, SLOT(setFlags()));
1719         connect(formatsCB->lineEdit(), SIGNAL(editingFinished()),
1720                 this, SLOT(updatePrettyname()));
1721         connect(formatsCB->lineEdit(), SIGNAL(textEdited(QString)),
1722                 this, SIGNAL(changed()));
1723         connect(defaultFormatCB, SIGNAL(activated(QString)),
1724                 this, SIGNAL(changed()));
1725         connect(viewerCO, SIGNAL(activated(int)),
1726                 this, SIGNAL(changed()));
1727         connect(editorCO, SIGNAL(activated(int)),
1728                 this, SIGNAL(changed()));
1729 }
1730
1731
1732 namespace {
1733
1734 string const l10n_shortcut(string const prettyname, string const shortcut)
1735 {
1736         if (shortcut.empty())
1737                 return string();
1738
1739         string l10n_format =
1740                 to_utf8(_(prettyname + '|' + shortcut));
1741         return split(l10n_format, '|');
1742 }
1743
1744 }; // namespace anon
1745
1746
1747 void PrefFileformats::apply(LyXRC & rc) const
1748 {
1749         QString const default_format = defaultFormatCB->itemData(
1750                 defaultFormatCB->currentIndex()).toString();
1751         rc.default_view_format = fromqstr(default_format);
1752 }
1753
1754
1755 void PrefFileformats::update(LyXRC const & rc)
1756 {
1757         viewer_alternatives = rc.viewer_alternatives;
1758         editor_alternatives = rc.editor_alternatives;
1759         bool const init = defaultFormatCB->currentText().isEmpty();
1760         updateView();
1761         if (init) {
1762                 int const pos =
1763                         defaultFormatCB->findData(toqstr(rc.default_view_format));
1764                 defaultFormatCB->setCurrentIndex(pos);
1765         }
1766 }
1767
1768
1769 void PrefFileformats::updateView()
1770 {
1771         QString const current = formatsCB->currentText();
1772         QString const current_def = defaultFormatCB->currentText();
1773
1774         // update comboboxes with formats
1775         formatsCB->blockSignals(true);
1776         defaultFormatCB->blockSignals(true);
1777         formatsCB->clear();
1778         defaultFormatCB->clear();
1779         form_->formats().sort();
1780         Formats::const_iterator cit = form_->formats().begin();
1781         Formats::const_iterator end = form_->formats().end();
1782         for (; cit != end; ++cit) {
1783                 formatsCB->addItem(qt_(cit->prettyname()),
1784                                 QVariant(form_->formats().getNumber(cit->name())));
1785                 if (form_->converters().isReachable("latex", cit->name())
1786                     || form_->converters().isReachable("pdflatex", cit->name()))
1787                         defaultFormatCB->addItem(qt_(cit->prettyname()),
1788                                         QVariant(toqstr(cit->name())));
1789         }
1790
1791         // restore selection
1792         int item = formatsCB->findText(current, Qt::MatchExactly);
1793         formatsCB->setCurrentIndex(item < 0 ? 0 : item);
1794         on_formatsCB_currentIndexChanged(item < 0 ? 0 : item);
1795         item = defaultFormatCB->findText(current_def, Qt::MatchExactly);
1796         defaultFormatCB->setCurrentIndex(item < 0 ? 0 : item);
1797         formatsCB->blockSignals(false);
1798         defaultFormatCB->blockSignals(false);
1799 }
1800
1801
1802 void PrefFileformats::on_formatsCB_currentIndexChanged(int i)
1803 {
1804         int const nr = formatsCB->itemData(i).toInt();
1805         Format const f = form_->formats().get(nr);
1806
1807         formatED->setText(toqstr(f.name()));
1808         copierED->setText(toqstr(form_->movers().command(f.name())));
1809         extensionED->setText(toqstr(f.extension()));
1810         shortcutED->setText(
1811                 toqstr(l10n_shortcut(f.prettyname(), f.shortcut())));
1812         documentCB->setChecked((f.documentFormat()));
1813         vectorCB->setChecked((f.vectorFormat()));
1814         updateViewers();
1815         updateEditors();
1816 }
1817
1818
1819 void PrefFileformats::setFlags()
1820 {
1821         int flags = Format::none;
1822         if (documentCB->isChecked())
1823                 flags |= Format::document;
1824         if (vectorCB->isChecked())
1825                 flags |= Format::vector;
1826         currentFormat().setFlags(flags);
1827         changed();
1828 }
1829
1830
1831 void PrefFileformats::on_copierED_textEdited(const QString & s)
1832 {
1833         string const fmt = fromqstr(formatED->text());
1834         form_->movers().set(fmt, fromqstr(s));
1835         changed();
1836 }
1837
1838
1839 void PrefFileformats::on_extensionED_textEdited(const QString & s)
1840 {
1841         currentFormat().setExtension(fromqstr(s));
1842         changed();
1843 }
1844
1845 void PrefFileformats::on_viewerED_textEdited(const QString & s)
1846 {
1847         currentFormat().setViewer(fromqstr(s));
1848         changed();
1849 }
1850
1851
1852 void PrefFileformats::on_editorED_textEdited(const QString & s)
1853 {
1854         currentFormat().setEditor(fromqstr(s));
1855         changed();
1856 }
1857
1858
1859 void PrefFileformats::on_shortcutED_textEdited(const QString & s)
1860 {
1861         string const new_shortcut = fromqstr(s);
1862         if (new_shortcut == l10n_shortcut(currentFormat().prettyname(),
1863                                           currentFormat().shortcut()))
1864                 return;
1865         currentFormat().setShortcut(new_shortcut);
1866         changed();
1867 }
1868
1869
1870 void PrefFileformats::on_formatED_editingFinished()
1871 {
1872         string const newname = fromqstr(formatED->displayText());
1873         if (newname == currentFormat().name())
1874                 return;
1875
1876         currentFormat().setName(newname);
1877         changed();
1878 }
1879
1880
1881 void PrefFileformats::on_formatED_textChanged(const QString &)
1882 {
1883         QString t = formatED->text();
1884         int p = 0;
1885         bool valid = formatED->validator()->validate(t, p) == QValidator::Acceptable;
1886         setValid(formatLA, valid);
1887 }
1888
1889
1890 void PrefFileformats::on_formatsCB_editTextChanged(const QString &)
1891 {
1892         QString t = formatsCB->currentText();
1893         int p = 0;
1894         bool valid = formatsCB->validator()->validate(t, p) == QValidator::Acceptable;
1895         setValid(formatsLA, valid);
1896 }
1897
1898
1899 void PrefFileformats::updatePrettyname()
1900 {
1901         QString const newname = formatsCB->currentText();
1902         if (newname == qt_(currentFormat().prettyname()))
1903                 return;
1904
1905         currentFormat().setPrettyname(fromqstr(newname));
1906         formatsChanged();
1907         updateView();
1908         changed();
1909 }
1910
1911
1912 namespace {
1913         void updateComboBox(LyXRC::Alternatives const & alts,
1914                             string const & fmt, QComboBox * combo)
1915         {
1916                 LyXRC::Alternatives::const_iterator it = 
1917                                 alts.find(fmt);
1918                 if (it != alts.end()) {
1919                         LyXRC::CommandSet const & cmds = it->second;
1920                         LyXRC::CommandSet::const_iterator sit = 
1921                                         cmds.begin();
1922                         LyXRC::CommandSet::const_iterator const sen = 
1923                                         cmds.end();
1924                         for (; sit != sen; ++sit) {
1925                                 QString const qcmd = toqstr(*sit);
1926                                 combo->addItem(qcmd, qcmd);
1927                         }
1928                 }
1929         }
1930 }
1931
1932
1933 void PrefFileformats::updateViewers()
1934 {
1935         Format const f = currentFormat();
1936         viewerCO->blockSignals(true);
1937         viewerCO->clear();
1938         viewerCO->addItem(qt_("None"), QString());
1939         updateComboBox(viewer_alternatives, f.name(), viewerCO);
1940         viewerCO->addItem(qt_("Custom"), QString("custom viewer"));
1941         viewerCO->blockSignals(false);
1942
1943         int pos = viewerCO->findData(toqstr(f.viewer()));
1944         if (pos != -1) {
1945                 viewerED->clear();
1946                 viewerED->setEnabled(false);
1947                 viewerCO->setCurrentIndex(pos);
1948         } else {
1949                 viewerED->setEnabled(true);
1950                 viewerED->setText(toqstr(f.viewer()));
1951                 viewerCO->setCurrentIndex(viewerCO->findData(toqstr("custom viewer")));
1952         }
1953 }
1954
1955
1956 void PrefFileformats::updateEditors()
1957 {
1958         Format const f = currentFormat();
1959         editorCO->blockSignals(true);
1960         editorCO->clear();
1961         editorCO->addItem(qt_("None"), QString());
1962         updateComboBox(editor_alternatives, f.name(), editorCO);
1963         editorCO->addItem(qt_("Custom"), QString("custom editor"));
1964         editorCO->blockSignals(false);
1965
1966         int pos = editorCO->findData(toqstr(f.editor()));
1967         if (pos != -1) {
1968                 editorED->clear();
1969                 editorED->setEnabled(false);
1970                 editorCO->setCurrentIndex(pos);
1971         } else {
1972                 editorED->setEnabled(true);
1973                 editorED->setText(toqstr(f.editor()));
1974                 editorCO->setCurrentIndex(editorCO->findData(toqstr("custom editor")));
1975         }
1976 }
1977
1978
1979 void PrefFileformats::on_viewerCO_currentIndexChanged(int i)
1980 {
1981         bool const custom = viewerCO->itemData(i).toString() == "custom viewer";
1982         viewerED->setEnabled(custom);
1983         if (!custom)
1984                 currentFormat().setViewer(fromqstr(viewerCO->itemData(i).toString()));
1985 }
1986
1987
1988 void PrefFileformats::on_editorCO_currentIndexChanged(int i)
1989 {
1990         bool const custom = editorCO->itemData(i).toString() == "custom editor";
1991         editorED->setEnabled(custom);
1992         if (!custom)
1993                 currentFormat().setEditor(fromqstr(editorCO->itemData(i).toString()));
1994 }
1995
1996
1997 Format & PrefFileformats::currentFormat()
1998 {
1999         int const i = formatsCB->currentIndex();
2000         int const nr = formatsCB->itemData(i).toInt();
2001         return form_->formats().get(nr);
2002 }
2003
2004
2005 void PrefFileformats::on_formatNewPB_clicked()
2006 {
2007         form_->formats().add("", "", "", "", "", "", Format::none);
2008         updateView();
2009         formatsCB->setCurrentIndex(0);
2010         formatsCB->setFocus(Qt::OtherFocusReason);
2011 }
2012
2013
2014 void PrefFileformats::on_formatRemovePB_clicked()
2015 {
2016         int const i = formatsCB->currentIndex();
2017         int const nr = formatsCB->itemData(i).toInt();
2018         string const current_text = form_->formats().get(nr).name();
2019         if (form_->converters().formatIsUsed(current_text)) {
2020                 Alert::error(_("Format in use"),
2021                              _("Cannot remove a Format used by a Converter. "
2022                                             "Remove the converter first."));
2023                 return;
2024         }
2025
2026         form_->formats().erase(current_text);
2027         formatsChanged();
2028         updateView();
2029         on_formatsCB_editTextChanged(formatsCB->currentText());
2030         changed();
2031 }
2032
2033
2034 /////////////////////////////////////////////////////////////////////
2035 //
2036 // PrefLanguage
2037 //
2038 /////////////////////////////////////////////////////////////////////
2039
2040 PrefLanguage::PrefLanguage(GuiPreferences * form)
2041         : PrefModule(qt_(catLanguage), qt_("Language"), form)
2042 {
2043         setupUi(this);
2044
2045         connect(rtlGB, SIGNAL(clicked()),
2046                 this, SIGNAL(changed()));
2047         connect(visualCursorRB, SIGNAL(clicked()),
2048                 this, SIGNAL(changed()));
2049         connect(logicalCursorRB, SIGNAL(clicked()),
2050                 this, SIGNAL(changed()));
2051         connect(markForeignCB, SIGNAL(clicked()),
2052                 this, SIGNAL(changed()));
2053         connect(autoBeginCB, SIGNAL(clicked()),
2054                 this, SIGNAL(changed()));
2055         connect(autoEndCB, SIGNAL(clicked()),
2056                 this, SIGNAL(changed()));
2057         connect(useBabelCB, SIGNAL(clicked()),
2058                 this, SIGNAL(changed()));
2059         connect(globalCB, SIGNAL(clicked()),
2060                 this, SIGNAL(changed()));
2061         connect(languagePackageED, SIGNAL(textChanged(QString)),
2062                 this, SIGNAL(changed()));
2063         connect(startCommandED, SIGNAL(textChanged(QString)),
2064                 this, SIGNAL(changed()));
2065         connect(endCommandED, SIGNAL(textChanged(QString)),
2066                 this, SIGNAL(changed()));
2067         connect(uiLanguageCO, SIGNAL(activated(int)),
2068                 this, SIGNAL(changed()));
2069
2070         uiLanguageCO->clear();
2071
2072         QAbstractItemModel * language_model = guiApp->languageModel();
2073         // FIXME: it would be nice if sorting was enabled/disabled via a checkbox.
2074         language_model->sort(0);
2075
2076         // FIXME: This is wrong, we need filter this list based on the available
2077         // translation.
2078         uiLanguageCO->blockSignals(true);
2079         uiLanguageCO->addItem(qt_("Default"), toqstr("auto"));
2080         for (int i = 0; i != language_model->rowCount(); ++i) {
2081                 QModelIndex index = language_model->index(i, 0);
2082                 uiLanguageCO->addItem(index.data(Qt::DisplayRole).toString(),
2083                         index.data(Qt::UserRole).toString());
2084         }
2085         uiLanguageCO->blockSignals(false);
2086 }
2087
2088
2089 void PrefLanguage::on_uiLanguageCO_currentIndexChanged(int)
2090 {
2091          QMessageBox::information(this, qt_("LyX needs to be restarted!"),
2092                  qt_("The change of user interface language will be fully "
2093                  "effective only after a restart."));
2094 }
2095
2096
2097 void PrefLanguage::apply(LyXRC & rc) const
2098 {
2099         // FIXME: remove rtl_support bool
2100         rc.rtl_support = rtlGB->isChecked();
2101         rc.visual_cursor = rtlGB->isChecked() && visualCursorRB->isChecked();
2102         rc.mark_foreign_language = markForeignCB->isChecked();
2103         rc.language_auto_begin = autoBeginCB->isChecked();
2104         rc.language_auto_end = autoEndCB->isChecked();
2105         rc.language_use_babel = useBabelCB->isChecked();
2106         rc.language_global_options = globalCB->isChecked();
2107         rc.language_package = fromqstr(languagePackageED->text());
2108         rc.language_command_begin = fromqstr(startCommandED->text());
2109         rc.language_command_end = fromqstr(endCommandED->text());
2110         rc.gui_language = fromqstr(
2111                 uiLanguageCO->itemData(uiLanguageCO->currentIndex()).toString());
2112 }
2113
2114
2115 void PrefLanguage::update(LyXRC const & rc)
2116 {
2117         // FIXME: remove rtl_support bool
2118         rtlGB->setChecked(rc.rtl_support);
2119         if (rc.visual_cursor)
2120                 visualCursorRB->setChecked(true);
2121         else
2122                 logicalCursorRB->setChecked(true);
2123         markForeignCB->setChecked(rc.mark_foreign_language);
2124         autoBeginCB->setChecked(rc.language_auto_begin);
2125         autoEndCB->setChecked(rc.language_auto_end);
2126         useBabelCB->setChecked(rc.language_use_babel);
2127         globalCB->setChecked(rc.language_global_options);
2128         languagePackageED->setText(toqstr(rc.language_package));
2129         startCommandED->setText(toqstr(rc.language_command_begin));
2130         endCommandED->setText(toqstr(rc.language_command_end));
2131
2132         int pos = uiLanguageCO->findData(toqstr(rc.gui_language));
2133         uiLanguageCO->blockSignals(true);
2134         uiLanguageCO->setCurrentIndex(pos);
2135         uiLanguageCO->blockSignals(false);
2136 }
2137
2138
2139 /////////////////////////////////////////////////////////////////////
2140 //
2141 // PrefPrinter
2142 //
2143 /////////////////////////////////////////////////////////////////////
2144
2145 PrefPrinter::PrefPrinter(GuiPreferences * form)
2146         : PrefModule(qt_(catOutput), qt_("Printer"), form)
2147 {
2148         setupUi(this);
2149
2150         connect(printerAdaptCB, SIGNAL(clicked()),
2151                 this, SIGNAL(changed()));
2152         connect(printerCommandED, SIGNAL(textChanged(QString)),
2153                 this, SIGNAL(changed()));
2154         connect(printerNameED, SIGNAL(textChanged(QString)),
2155                 this, SIGNAL(changed()));
2156         connect(printerPageRangeED, SIGNAL(textChanged(QString)),
2157                 this, SIGNAL(changed()));
2158         connect(printerCopiesED, SIGNAL(textChanged(QString)),
2159                 this, SIGNAL(changed()));
2160         connect(printerReverseED, SIGNAL(textChanged(QString)),
2161                 this, SIGNAL(changed()));
2162         connect(printerToPrinterED, SIGNAL(textChanged(QString)),
2163                 this, SIGNAL(changed()));
2164         connect(printerExtensionED, SIGNAL(textChanged(QString)),
2165                 this, SIGNAL(changed()));
2166         connect(printerSpoolCommandED, SIGNAL(textChanged(QString)),
2167                 this, SIGNAL(changed()));
2168         connect(printerPaperTypeED, SIGNAL(textChanged(QString)),
2169                 this, SIGNAL(changed()));
2170         connect(printerEvenED, SIGNAL(textChanged(QString)),
2171                 this, SIGNAL(changed()));
2172         connect(printerOddED, SIGNAL(textChanged(QString)),
2173                 this, SIGNAL(changed()));
2174         connect(printerCollatedED, SIGNAL(textChanged(QString)),
2175                 this, SIGNAL(changed()));
2176         connect(printerLandscapeED, SIGNAL(textChanged(QString)),
2177                 this, SIGNAL(changed()));
2178         connect(printerToFileED, SIGNAL(textChanged(QString)),
2179                 this, SIGNAL(changed()));
2180         connect(printerExtraED, SIGNAL(textChanged(QString)),
2181                 this, SIGNAL(changed()));
2182         connect(printerSpoolPrefixED, SIGNAL(textChanged(QString)),
2183                 this, SIGNAL(changed()));
2184         connect(printerPaperSizeED, SIGNAL(textChanged(QString)),
2185                 this, SIGNAL(changed()));
2186 }
2187
2188
2189 void PrefPrinter::apply(LyXRC & rc) const
2190 {
2191         rc.print_adapt_output = printerAdaptCB->isChecked();
2192         rc.print_command = fromqstr(printerCommandED->text());
2193         rc.printer = fromqstr(printerNameED->text());
2194
2195         rc.print_pagerange_flag = fromqstr(printerPageRangeED->text());
2196         rc.print_copies_flag = fromqstr(printerCopiesED->text());
2197         rc.print_reverse_flag = fromqstr(printerReverseED->text());
2198         rc.print_to_printer = fromqstr(printerToPrinterED->text());
2199         rc.print_file_extension = fromqstr(printerExtensionED->text());
2200         rc.print_spool_command = fromqstr(printerSpoolCommandED->text());
2201         rc.print_paper_flag = fromqstr(printerPaperTypeED->text());
2202         rc.print_evenpage_flag = fromqstr(printerEvenED->text());
2203         rc.print_oddpage_flag = fromqstr(printerOddED->text());
2204         rc.print_collcopies_flag = fromqstr(printerCollatedED->text());
2205         rc.print_landscape_flag = fromqstr(printerLandscapeED->text());
2206         rc.print_to_file = internal_path(fromqstr(printerToFileED->text()));
2207         rc.print_extra_options = fromqstr(printerExtraED->text());
2208         rc.print_spool_printerprefix = fromqstr(printerSpoolPrefixED->text());
2209         rc.print_paper_dimension_flag = fromqstr(printerPaperSizeED->text());
2210 }
2211
2212
2213 void PrefPrinter::update(LyXRC const & rc)
2214 {
2215         printerAdaptCB->setChecked(rc.print_adapt_output);
2216         printerCommandED->setText(toqstr(rc.print_command));
2217         printerNameED->setText(toqstr(rc.printer));
2218
2219         printerPageRangeED->setText(toqstr(rc.print_pagerange_flag));
2220         printerCopiesED->setText(toqstr(rc.print_copies_flag));
2221         printerReverseED->setText(toqstr(rc.print_reverse_flag));
2222         printerToPrinterED->setText(toqstr(rc.print_to_printer));
2223         printerExtensionED->setText(toqstr(rc.print_file_extension));
2224         printerSpoolCommandED->setText(toqstr(rc.print_spool_command));
2225         printerPaperTypeED->setText(toqstr(rc.print_paper_flag));
2226         printerEvenED->setText(toqstr(rc.print_evenpage_flag));
2227         printerOddED->setText(toqstr(rc.print_oddpage_flag));
2228         printerCollatedED->setText(toqstr(rc.print_collcopies_flag));
2229         printerLandscapeED->setText(toqstr(rc.print_landscape_flag));
2230         printerToFileED->setText(toqstr(external_path(rc.print_to_file)));
2231         printerExtraED->setText(toqstr(rc.print_extra_options));
2232         printerSpoolPrefixED->setText(toqstr(rc.print_spool_printerprefix));
2233         printerPaperSizeED->setText(toqstr(rc.print_paper_dimension_flag));
2234 }
2235
2236
2237 /////////////////////////////////////////////////////////////////////
2238 //
2239 // PrefUserInterface
2240 //
2241 /////////////////////////////////////////////////////////////////////
2242
2243 PrefUserInterface::PrefUserInterface(GuiPreferences * form)
2244         : PrefModule(qt_(catLookAndFeel), qt_("User interface"), form)
2245 {
2246         setupUi(this);
2247
2248         connect(autoSaveCB, SIGNAL(toggled(bool)),
2249                 autoSaveSB, SLOT(setEnabled(bool)));
2250         connect(autoSaveCB, SIGNAL(toggled(bool)),
2251                 TextLabel1, SLOT(setEnabled(bool)));
2252         connect(openDocumentsInTabsCB, SIGNAL(clicked()),
2253                 this, SIGNAL(changed()));
2254 #if QT_VERSION < 0x040500
2255         singleCloseTabButtonCB->setEnabled(false);
2256 #endif
2257         connect(singleCloseTabButtonCB, SIGNAL(clicked()),
2258                 this, SIGNAL(changed()));
2259         connect(uiFilePB, SIGNAL(clicked()),
2260                 this, SLOT(selectUi()));
2261         connect(uiFileED, SIGNAL(textChanged(QString)),
2262                 this, SIGNAL(changed()));
2263         connect(restoreCursorCB, SIGNAL(clicked()),
2264                 this, SIGNAL(changed()));
2265         connect(loadSessionCB, SIGNAL(clicked()),
2266                 this, SIGNAL(changed()));
2267         connect(allowGeometrySessionCB, SIGNAL(clicked()),
2268                 this, SIGNAL(changed()));
2269         connect(autoSaveSB, SIGNAL(valueChanged(int)),
2270                 this, SIGNAL(changed()));
2271         connect(autoSaveCB, SIGNAL(clicked()),
2272                 this, SIGNAL(changed()));
2273         connect(backupCB, SIGNAL(clicked()),
2274                 this, SIGNAL(changed()));
2275         connect(saveCompressedCB, SIGNAL(clicked()),
2276                 this, SIGNAL(changed()));
2277         connect(lastfilesSB, SIGNAL(valueChanged(int)),
2278                 this, SIGNAL(changed()));
2279         connect(tooltipCB, SIGNAL(toggled(bool)),
2280                 this, SIGNAL(changed()));
2281         lastfilesSB->setMaximum(maxlastfiles);
2282 }
2283
2284
2285 void PrefUserInterface::apply(LyXRC & rc) const
2286 {
2287         rc.ui_file = internal_path(fromqstr(uiFileED->text()));
2288         rc.use_lastfilepos = restoreCursorCB->isChecked();
2289         rc.load_session = loadSessionCB->isChecked();
2290         rc.allow_geometry_session = allowGeometrySessionCB->isChecked();
2291         rc.autosave = autoSaveCB->isChecked() ?  autoSaveSB->value() * 60 : 0;
2292         rc.make_backup = backupCB->isChecked();
2293         rc.save_compressed = saveCompressedCB->isChecked();
2294         rc.num_lastfiles = lastfilesSB->value();
2295         rc.use_tooltip = tooltipCB->isChecked();
2296         rc.open_buffers_in_tabs = openDocumentsInTabsCB->isChecked();
2297         rc.single_close_tab_button = singleCloseTabButtonCB->isChecked();
2298 #if QT_VERSION < 0x040500
2299         rc.single_close_tab_button = true;
2300 #endif
2301 }
2302
2303
2304 void PrefUserInterface::update(LyXRC const & rc)
2305 {
2306         uiFileED->setText(toqstr(external_path(rc.ui_file)));
2307         restoreCursorCB->setChecked(rc.use_lastfilepos);
2308         loadSessionCB->setChecked(rc.load_session);
2309         allowGeometrySessionCB->setChecked(rc.allow_geometry_session);
2310         // convert to minutes
2311         bool autosave = rc.autosave > 0;
2312         int mins = rc.autosave / 60;
2313         if (!mins)
2314                 mins = 5;
2315         autoSaveSB->setValue(mins);
2316         autoSaveCB->setChecked(autosave);
2317         autoSaveSB->setEnabled(autosave);
2318         backupCB->setChecked(rc.make_backup);
2319         saveCompressedCB->setChecked(rc.save_compressed);
2320         lastfilesSB->setValue(rc.num_lastfiles);
2321         tooltipCB->setChecked(rc.use_tooltip);
2322         openDocumentsInTabsCB->setChecked(rc.open_buffers_in_tabs);
2323         singleCloseTabButtonCB->setChecked(rc.single_close_tab_button);
2324 }
2325
2326
2327 void PrefUserInterface::selectUi()
2328 {
2329         QString file = form_->browseUI(internalPath(uiFileED->text()));
2330         if (!file.isEmpty())
2331                 uiFileED->setText(file);
2332 }
2333
2334
2335 void PrefUserInterface::on_clearSessionPB_clicked()
2336 {
2337         guiApp->clearSession();
2338 }
2339
2340
2341
2342 /////////////////////////////////////////////////////////////////////
2343 //
2344 // PrefEdit
2345 //
2346 /////////////////////////////////////////////////////////////////////
2347
2348 PrefEdit::PrefEdit(GuiPreferences * form)
2349         : PrefModule(qt_(catEditing), qt_("Control"), form)
2350 {
2351         setupUi(this);
2352
2353         connect(cursorFollowsCB, SIGNAL(clicked()),
2354                 this, SIGNAL(changed()));
2355         connect(scrollBelowCB, SIGNAL(clicked()),
2356                 this, SIGNAL(changed()));
2357         connect(sortEnvironmentsCB, SIGNAL(clicked()),
2358                 this, SIGNAL(changed()));
2359         connect(groupEnvironmentsCB, SIGNAL(clicked()),
2360                 this, SIGNAL(changed()));
2361         connect(macroEditStyleCO, SIGNAL(activated(int)),
2362                 this, SIGNAL(changed()));
2363         connect(fullscreenLimitGB, SIGNAL(clicked()),
2364                 this, SIGNAL(changed()));
2365         connect(fullscreenWidthSB, SIGNAL(valueChanged(int)),
2366                 this, SIGNAL(changed()));
2367         connect(toggleTabbarCB, SIGNAL(toggled(bool)),
2368                 this, SIGNAL(changed()));
2369         connect(toggleMenubarCB, SIGNAL(toggled(bool)),
2370                 this, SIGNAL(changed()));
2371         connect(toggleScrollbarCB, SIGNAL(toggled(bool)),
2372                 this, SIGNAL(changed()));
2373         connect(toggleToolbarsCB, SIGNAL(toggled(bool)),
2374                 this, SIGNAL(changed()));
2375 }
2376
2377
2378 void PrefEdit::apply(LyXRC & rc) const
2379 {
2380         rc.cursor_follows_scrollbar = cursorFollowsCB->isChecked();
2381         rc.scroll_below_document = scrollBelowCB->isChecked();
2382         rc.sort_layouts = sortEnvironmentsCB->isChecked();
2383         rc.group_layouts = groupEnvironmentsCB->isChecked();
2384         switch (macroEditStyleCO->currentIndex()) {
2385                 case 0: rc.macro_edit_style = LyXRC::MACRO_EDIT_INLINE_BOX; break;
2386                 case 1: rc.macro_edit_style = LyXRC::MACRO_EDIT_INLINE; break;
2387                 case 2: rc.macro_edit_style = LyXRC::MACRO_EDIT_LIST;   break;
2388         }
2389         rc.full_screen_toolbars = toggleToolbarsCB->isChecked();
2390         rc.full_screen_scrollbar = toggleScrollbarCB->isChecked();
2391         rc.full_screen_tabbar = toggleTabbarCB->isChecked();
2392         rc.full_screen_menubar = toggleMenubarCB->isChecked();
2393         rc.full_screen_width = fullscreenWidthSB->value();
2394         rc.full_screen_limit = fullscreenLimitGB->isChecked();
2395 }
2396
2397
2398 void PrefEdit::update(LyXRC const & rc)
2399 {
2400         cursorFollowsCB->setChecked(rc.cursor_follows_scrollbar);
2401         scrollBelowCB->setChecked(rc.scroll_below_document);
2402         sortEnvironmentsCB->setChecked(rc.sort_layouts);
2403         groupEnvironmentsCB->setChecked(rc.group_layouts);
2404         macroEditStyleCO->setCurrentIndex(rc.macro_edit_style);
2405         toggleScrollbarCB->setChecked(rc.full_screen_scrollbar);
2406         toggleToolbarsCB->setChecked(rc.full_screen_toolbars);
2407         toggleTabbarCB->setChecked(rc.full_screen_tabbar);
2408         toggleMenubarCB->setChecked(rc.full_screen_menubar);
2409         fullscreenWidthSB->setValue(rc.full_screen_width);
2410         fullscreenLimitGB->setChecked(rc.full_screen_limit);
2411 }
2412
2413
2414 /////////////////////////////////////////////////////////////////////
2415 //
2416 // PrefShortcuts
2417 //
2418 /////////////////////////////////////////////////////////////////////
2419
2420
2421 GuiShortcutDialog::GuiShortcutDialog(QWidget * parent) : QDialog(parent)
2422 {
2423         Ui::shortcutUi::setupUi(this);
2424         QDialog::setModal(true);
2425 }
2426
2427
2428 PrefShortcuts::PrefShortcuts(GuiPreferences * form)
2429         : PrefModule(qt_(catEditing), qt_("Shortcuts"), form)
2430 {
2431         setupUi(this);
2432
2433         shortcutsTW->setColumnCount(2);
2434         shortcutsTW->headerItem()->setText(0, qt_("Function"));
2435         shortcutsTW->headerItem()->setText(1, qt_("Shortcut"));
2436         shortcutsTW->setSortingEnabled(true);
2437         // Multi-selection can be annoying.
2438         // shortcutsTW->setSelectionMode(QAbstractItemView::MultiSelection);
2439
2440         connect(bindFilePB, SIGNAL(clicked()),
2441                 this, SLOT(selectBind()));
2442         connect(bindFileED, SIGNAL(textChanged(QString)),
2443                 this, SIGNAL(changed()));
2444
2445         shortcut_ = new GuiShortcutDialog(this);
2446         shortcut_bc_.setPolicy(ButtonPolicy::OkCancelPolicy);
2447         shortcut_bc_.setOK(shortcut_->okPB);
2448         shortcut_bc_.setCancel(shortcut_->cancelPB);
2449
2450         connect(shortcut_->okPB, SIGNAL(clicked()),
2451                 shortcut_, SLOT(accept()));
2452         connect(shortcut_->okPB, SIGNAL(clicked()),
2453                 this, SIGNAL(changed()));
2454         connect(shortcut_->cancelPB, SIGNAL(clicked()),
2455                 shortcut_, SLOT(reject()));
2456         connect(shortcut_->clearPB, SIGNAL(clicked()),
2457                 this, SLOT(shortcutClearPressed()));
2458         connect(shortcut_->removePB, SIGNAL(clicked()),
2459                 this, SLOT(shortcutRemovePressed()));
2460         connect(shortcut_->okPB, SIGNAL(clicked()),
2461                 this, SLOT(shortcutOkPressed()));
2462         connect(shortcut_->cancelPB, SIGNAL(clicked()),
2463                 this, SLOT(shortcutCancelPressed()));
2464 }
2465
2466
2467 void PrefShortcuts::apply(LyXRC & rc) const
2468 {
2469         rc.bind_file = internal_path(fromqstr(bindFileED->text()));
2470         // write user_bind and user_unbind to .lyx/bind/user.bind
2471         FileName bind_dir(addPath(package().user_support().absFilename(), "bind"));
2472         if (!bind_dir.exists() && !bind_dir.createDirectory(0777)) {
2473                 lyxerr << "LyX could not create the user bind directory '"
2474                        << bind_dir << "'. All user-defined key bindings will be lost." << endl;
2475                 return;
2476         }
2477         if (!bind_dir.isDirWritable()) {
2478                 lyxerr << "LyX could not write to the user bind directory '"
2479                        << bind_dir << "'. All user-defined key bindings will be lost." << endl;
2480                 return;
2481         }
2482         FileName user_bind_file(bind_dir.absFilename() + "/user.bind");
2483         user_unbind_.write(user_bind_file.toFilesystemEncoding(), false, true);
2484         user_bind_.write(user_bind_file.toFilesystemEncoding(), true, false);
2485         // immediately apply the keybindings. Why this is not done before?
2486         // The good thing is that the menus are updated automatically.
2487         theTopLevelKeymap().clear();
2488         theTopLevelKeymap().read("site");
2489         theTopLevelKeymap().read(rc.bind_file, 0, KeyMap::Fallback);
2490         theTopLevelKeymap().read("user", 0, KeyMap::MissingOK);
2491 }
2492
2493
2494 void PrefShortcuts::update(LyXRC const & rc)
2495 {
2496         bindFileED->setText(toqstr(external_path(rc.bind_file)));
2497         //
2498         system_bind_.clear();
2499         user_bind_.clear();
2500         user_unbind_.clear();
2501         system_bind_.read("site");
2502         system_bind_.read(rc.bind_file);
2503         // \unbind in user.bind is added to user_unbind_
2504         user_bind_.read("user", &user_unbind_, KeyMap::MissingOK);
2505         updateShortcutsTW();
2506 }
2507
2508
2509 void PrefShortcuts::updateShortcutsTW()
2510 {
2511         shortcutsTW->clear();
2512
2513         editItem_ = new QTreeWidgetItem(shortcutsTW);
2514         editItem_->setText(0, qt_("Cursor, Mouse and Editing functions"));
2515         editItem_->setFlags(editItem_->flags() & ~Qt::ItemIsSelectable);
2516
2517         mathItem_ = new QTreeWidgetItem(shortcutsTW);
2518         mathItem_->setText(0, qt_("Mathematical Symbols"));
2519         mathItem_->setFlags(mathItem_->flags() & ~Qt::ItemIsSelectable);
2520
2521         bufferItem_ = new QTreeWidgetItem(shortcutsTW);
2522         bufferItem_->setText(0, qt_("Document and Window"));
2523         bufferItem_->setFlags(bufferItem_->flags() & ~Qt::ItemIsSelectable);
2524
2525         layoutItem_ = new QTreeWidgetItem(shortcutsTW);
2526         layoutItem_->setText(0, qt_("Font, Layouts and Textclasses"));
2527         layoutItem_->setFlags(layoutItem_->flags() & ~Qt::ItemIsSelectable);
2528
2529         systemItem_ = new QTreeWidgetItem(shortcutsTW);
2530         systemItem_->setText(0, qt_("System and Miscellaneous"));
2531         systemItem_->setFlags(systemItem_->flags() & ~Qt::ItemIsSelectable);
2532
2533         // listBindings(unbound=true) lists all bound and unbound lfuns
2534         // Items in this list is tagged by its source.
2535         KeyMap::BindingList bindinglist = system_bind_.listBindings(true,
2536                 KeyMap::System);
2537         KeyMap::BindingList user_bindinglist = user_bind_.listBindings(false,
2538                 KeyMap::UserBind);
2539         KeyMap::BindingList user_unbindinglist = user_unbind_.listBindings(false,
2540                 KeyMap::UserUnbind);
2541         bindinglist.insert(bindinglist.end(), user_bindinglist.begin(),
2542                         user_bindinglist.end());
2543         bindinglist.insert(bindinglist.end(), user_unbindinglist.begin(),
2544                         user_unbindinglist.end());
2545
2546         KeyMap::BindingList::const_iterator it = bindinglist.begin();
2547         KeyMap::BindingList::const_iterator it_end = bindinglist.end();
2548         for (; it != it_end; ++it)
2549                 insertShortcutItem(it->request, it->sequence, KeyMap::ItemType(it->tag));
2550
2551         shortcutsTW->sortItems(0, Qt::AscendingOrder);
2552         QList<QTreeWidgetItem*> items = shortcutsTW->selectedItems();
2553         removePB->setEnabled(!items.isEmpty() && !items[0]->text(1).isEmpty());
2554         modifyPB->setEnabled(!items.isEmpty());
2555
2556         shortcutsTW->resizeColumnToContents(0);
2557 }
2558
2559
2560 void PrefShortcuts::setItemType(QTreeWidgetItem * item, KeyMap::ItemType tag)
2561 {
2562         item->setData(0, Qt::UserRole, QVariant(tag));
2563         QFont font;
2564
2565         switch (tag) {
2566         case KeyMap::System:
2567                 break;
2568         case KeyMap::UserBind:
2569                 font.setBold(true);
2570                 break;
2571         case KeyMap::UserUnbind:
2572                 font.setStrikeOut(true);
2573                 break;
2574         // this item is not displayed now.
2575         case KeyMap::UserExtraUnbind:
2576                 font.setStrikeOut(true);
2577                 break;
2578         }
2579
2580         item->setFont(1, font);
2581 }
2582
2583
2584 QTreeWidgetItem * PrefShortcuts::insertShortcutItem(FuncRequest const & lfun,
2585                 KeySequence const & seq, KeyMap::ItemType tag)
2586 {
2587         FuncCode const action = lfun.action();
2588         string const action_name = lyxaction.getActionName(action);
2589         QString const lfun_name = toqstr(from_utf8(action_name)
2590                         + ' ' + lfun.argument());
2591         QString const shortcut = toqstr(seq.print(KeySequence::ForGui));
2592         KeyMap::ItemType item_tag = tag;
2593
2594         QTreeWidgetItem * newItem = 0;
2595         // for unbind items, try to find an existing item in the system bind list
2596         if (tag == KeyMap::UserUnbind) {
2597                 QList<QTreeWidgetItem*> const items = shortcutsTW->findItems(lfun_name,
2598                         Qt::MatchFlags(Qt::MatchExactly | Qt::MatchRecursive), 0);
2599                 for (int i = 0; i < items.size(); ++i) {
2600                         if (items[i]->text(1) == shortcut)
2601                                 newItem = items[i];
2602                                 break;
2603                         }
2604                 // if not found, this unbind item is KeyMap::UserExtraUnbind
2605                 // Such an item is not displayed to avoid confusion (what is
2606                 // unmatched removed?).
2607                 if (!newItem) {
2608                         item_tag = KeyMap::UserExtraUnbind;
2609                         return 0;
2610                 }
2611         }
2612         if (!newItem) {
2613                 switch(lyxaction.getActionType(action)) {
2614                 case LyXAction::Hidden:
2615                         return 0;
2616                 case LyXAction::Edit:
2617                         newItem = new QTreeWidgetItem(editItem_);
2618                         break;
2619                 case LyXAction::Math:
2620                         newItem = new QTreeWidgetItem(mathItem_);
2621                         break;
2622                 case LyXAction::Buffer:
2623                         newItem = new QTreeWidgetItem(bufferItem_);
2624                         break;
2625                 case LyXAction::Layout:
2626                         newItem = new QTreeWidgetItem(layoutItem_);
2627                         break;
2628                 case LyXAction::System:
2629                         newItem = new QTreeWidgetItem(systemItem_);
2630                         break;
2631                 default:
2632                         // this should not happen
2633                         newItem = new QTreeWidgetItem(shortcutsTW);
2634                 }
2635         }
2636
2637         newItem->setText(0, lfun_name);
2638         newItem->setText(1, shortcut);
2639         // record BindFile representation to recover KeySequence when needed.
2640         newItem->setData(1, Qt::UserRole, toqstr(seq.print(KeySequence::BindFile)));
2641         setItemType(newItem, item_tag);
2642         return newItem;
2643 }
2644
2645
2646 void PrefShortcuts::on_shortcutsTW_itemSelectionChanged()
2647 {
2648         QList<QTreeWidgetItem*> items = shortcutsTW->selectedItems();
2649         removePB->setEnabled(!items.isEmpty() && !items[0]->text(1).isEmpty());
2650         modifyPB->setEnabled(!items.isEmpty());
2651         if (items.isEmpty())
2652                 return;
2653
2654         KeyMap::ItemType tag = 
2655                 static_cast<KeyMap::ItemType>(items[0]->data(0, Qt::UserRole).toInt());
2656         if (tag == KeyMap::UserUnbind)
2657                 removePB->setText(qt_("Res&tore"));
2658         else
2659                 removePB->setText(qt_("Remo&ve"));
2660 }
2661
2662
2663 void PrefShortcuts::on_shortcutsTW_itemDoubleClicked()
2664 {
2665         modifyShortcut();
2666 }
2667
2668
2669 void PrefShortcuts::modifyShortcut()
2670 {
2671         QTreeWidgetItem * item = shortcutsTW->currentItem();
2672         if (item->flags() & Qt::ItemIsSelectable) {
2673                 shortcut_->lfunLE->setText(item->text(0));
2674                 save_lfun_ = item->text(0).trimmed();
2675                 shortcut_->shortcutWG->setText(item->text(1));
2676                 KeySequence seq;
2677                 seq.parse(fromqstr(item->data(1, Qt::UserRole).toString()));
2678                 shortcut_->shortcutWG->setKeySequence(seq);
2679                 shortcut_->shortcutWG->setFocus();
2680                 shortcut_->exec();
2681         }
2682 }
2683
2684
2685 void PrefShortcuts::removeShortcut()
2686 {
2687         // it seems that only one item can be selected, but I am
2688         // removing all selected items anyway.
2689         QList<QTreeWidgetItem*> items = shortcutsTW->selectedItems();
2690         for (int i = 0; i < items.size(); ++i) {
2691                 string shortcut = fromqstr(items[i]->data(1, Qt::UserRole).toString());
2692                 string lfun = fromqstr(items[i]->text(0));
2693                 FuncRequest func = lyxaction.lookupFunc(lfun);
2694                 KeyMap::ItemType tag = 
2695                         static_cast<KeyMap::ItemType>(items[i]->data(0, Qt::UserRole).toInt());
2696
2697                 switch (tag) {
2698                 case KeyMap::System: {
2699                         // for system bind, we do not touch the item
2700                         // but add an user unbind item
2701                         user_unbind_.bind(shortcut, func);
2702                         setItemType(items[i], KeyMap::UserUnbind);
2703                         removePB->setText(qt_("Res&tore"));
2704                         break;
2705                 }
2706                 case KeyMap::UserBind: {
2707                         // for user_bind, we remove this bind
2708                         QTreeWidgetItem * parent = items[i]->parent();
2709                         int itemIdx = parent->indexOfChild(items[i]);
2710                         parent->takeChild(itemIdx);
2711                         if (itemIdx > 0)
2712                                 shortcutsTW->scrollToItem(parent->child(itemIdx - 1));
2713                         else
2714                                 shortcutsTW->scrollToItem(parent);
2715                         user_bind_.unbind(shortcut, func);
2716                         break;
2717                 }
2718                 case KeyMap::UserUnbind: {
2719                         // for user_unbind, we remove the unbind, and the item
2720                         // become KeyMap::System again.
2721                         user_unbind_.unbind(shortcut, func);
2722                         setItemType(items[i], KeyMap::System);
2723                         removePB->setText(qt_("Remo&ve"));
2724                         break;
2725                 }
2726                 case KeyMap::UserExtraUnbind: {
2727                         // for user unbind that is not in system bind file,
2728                         // remove this unbind file
2729                         QTreeWidgetItem * parent = items[i]->parent();
2730                         parent->takeChild(parent->indexOfChild(items[i]));
2731                         user_unbind_.unbind(shortcut, func);
2732                 }
2733                 }
2734         }
2735 }
2736
2737
2738 void PrefShortcuts::selectBind()
2739 {
2740         QString file = form_->browsebind(internalPath(bindFileED->text()));
2741         if (!file.isEmpty()) {
2742                 bindFileED->setText(file);
2743                 system_bind_ = KeyMap();
2744                 system_bind_.read(fromqstr(file));
2745                 updateShortcutsTW();
2746         }
2747 }
2748
2749
2750 void PrefShortcuts::on_modifyPB_pressed()
2751 {
2752         modifyShortcut();
2753 }
2754
2755
2756 void PrefShortcuts::on_newPB_pressed()
2757 {
2758         shortcut_->lfunLE->clear();
2759         shortcut_->shortcutWG->reset();
2760         save_lfun_ = QString();
2761         shortcut_->exec();
2762 }
2763
2764
2765 void PrefShortcuts::on_removePB_pressed()
2766 {
2767         changed();
2768         removeShortcut();
2769 }
2770
2771
2772 void PrefShortcuts::on_searchLE_textEdited()
2773 {
2774         if (searchLE->text().isEmpty()) {
2775                 // show all hidden items
2776                 QTreeWidgetItemIterator it(shortcutsTW, QTreeWidgetItemIterator::Hidden);
2777                 while (*it)
2778                         shortcutsTW->setItemHidden(*it++, false);
2779                 return;
2780         }
2781         // search both columns
2782         QList<QTreeWidgetItem *> matched = shortcutsTW->findItems(searchLE->text(),
2783                 Qt::MatchFlags(Qt::MatchContains | Qt::MatchRecursive), 0);
2784         matched += shortcutsTW->findItems(searchLE->text(),
2785                 Qt::MatchFlags(Qt::MatchContains | Qt::MatchRecursive), 1);
2786
2787         // hide everyone (to avoid searching in matched QList repeatedly
2788         QTreeWidgetItemIterator it(shortcutsTW, QTreeWidgetItemIterator::Selectable);
2789         while (*it)
2790                 shortcutsTW->setItemHidden(*it++, true);
2791         // show matched items
2792         for (int i = 0; i < matched.size(); ++i) {
2793                 shortcutsTW->setItemHidden(matched[i], false);
2794         shortcutsTW->setItemExpanded(matched[i]->parent(), true);
2795         }
2796 }
2797
2798
2799 docstring makeCmdString(FuncRequest const & f)
2800 {
2801         docstring actionStr = from_ascii(lyxaction.getActionName(f.action()));
2802         if (!f.argument().empty())
2803                 actionStr += " " + f.argument();
2804         return actionStr;
2805 }
2806
2807
2808 void PrefShortcuts::shortcutOkPressed()
2809 {
2810         QString const new_lfun = shortcut_->lfunLE->text();
2811         FuncRequest func = lyxaction.lookupFunc(fromqstr(new_lfun));
2812
2813         if (func.action() == LFUN_UNKNOWN_ACTION) {
2814                 Alert::error(_("Failed to create shortcut"),
2815                         _("Unknown or invalid LyX function"));
2816                 return;
2817         }
2818
2819         KeySequence k = shortcut_->shortcutWG->getKeySequence();
2820         if (k.length() == 0) {
2821                 Alert::error(_("Failed to create shortcut"),
2822                         _("Invalid or empty key sequence"));
2823                 return;
2824         }
2825
2826         // check to see if there's been any change
2827         FuncRequest oldBinding = system_bind_.getBinding(k);
2828         if (oldBinding.action() == LFUN_UNKNOWN_ACTION)
2829                 oldBinding = user_bind_.getBinding(k);
2830         if (oldBinding == func)
2831                 // nothing has changed
2832                 return;
2833         
2834         // make sure this key isn't already bound---and, if so, not unbound
2835         FuncCode const unbind = user_unbind_.getBinding(k).action();
2836         docstring const action_string = makeCmdString(oldBinding);
2837         if (oldBinding.action() > LFUN_NOACTION && unbind == LFUN_UNKNOWN_ACTION
2838                   && save_lfun_ != toqstr(action_string)) {
2839                 // FIXME Perhaps we should offer to over-write the old shortcut?
2840                 // If so, we'll need to remove it from our list, etc.
2841                 Alert::error(_("Failed to create shortcut"),
2842                         bformat(_("Shortcut `%1$s' is already bound to:\n%2$s\n"
2843                           "You need to remove that binding before creating a new one."), 
2844                         k.print(KeySequence::ForGui), action_string));
2845                 return;
2846         }
2847
2848         if (!save_lfun_.isEmpty())
2849                 // real modification of the lfun's shortcut,
2850                 // so remove the previous one
2851                 removeShortcut();
2852
2853         QTreeWidgetItem * item = insertShortcutItem(func, k, KeyMap::UserBind);
2854         if (item) {
2855                 user_bind_.bind(&k, func);
2856                 shortcutsTW->sortItems(0, Qt::AscendingOrder);
2857                 shortcutsTW->setItemExpanded(item->parent(), true);
2858                 shortcutsTW->scrollToItem(item);
2859         } else {
2860                 Alert::error(_("Failed to create shortcut"),
2861                         _("Can not insert shortcut to the list"));
2862                 return;
2863         }
2864 }
2865
2866
2867 void PrefShortcuts::shortcutCancelPressed()
2868 {
2869         shortcut_->shortcutWG->reset();
2870 }
2871
2872
2873 void PrefShortcuts::shortcutClearPressed()
2874 {
2875         shortcut_->shortcutWG->reset();
2876 }
2877
2878
2879 void PrefShortcuts::shortcutRemovePressed()
2880 {
2881         shortcut_->shortcutWG->removeFromSequence();
2882 }
2883
2884
2885 /////////////////////////////////////////////////////////////////////
2886 //
2887 // PrefIdentity
2888 //
2889 /////////////////////////////////////////////////////////////////////
2890
2891 PrefIdentity::PrefIdentity(GuiPreferences * form)
2892         : PrefModule(QString(), qt_("Identity"), form)
2893 {
2894         setupUi(this);
2895
2896         connect(nameED, SIGNAL(textChanged(QString)),
2897                 this, SIGNAL(changed()));
2898         connect(emailED, SIGNAL(textChanged(QString)),
2899                 this, SIGNAL(changed()));
2900 }
2901
2902
2903 void PrefIdentity::apply(LyXRC & rc) const
2904 {
2905         rc.user_name = fromqstr(nameED->text());
2906         rc.user_email = fromqstr(emailED->text());
2907 }
2908
2909
2910 void PrefIdentity::update(LyXRC const & rc)
2911 {
2912         nameED->setText(toqstr(rc.user_name));
2913         emailED->setText(toqstr(rc.user_email));
2914 }
2915
2916
2917
2918 /////////////////////////////////////////////////////////////////////
2919 //
2920 // GuiPreferences
2921 //
2922 /////////////////////////////////////////////////////////////////////
2923
2924 GuiPreferences::GuiPreferences(GuiView & lv)
2925         : GuiDialog(lv, "prefs", qt_("Preferences")), update_screen_font_(false)
2926 {
2927         setupUi(this);
2928
2929         QDialog::setModal(false);
2930
2931         connect(savePB, SIGNAL(clicked()), this, SLOT(slotOK()));
2932         connect(applyPB, SIGNAL(clicked()), this, SLOT(slotApply()));
2933         connect(closePB, SIGNAL(clicked()), this, SLOT(slotClose()));
2934         connect(restorePB, SIGNAL(clicked()), this, SLOT(slotRestore()));
2935
2936         addModule(new PrefUserInterface(this));
2937         addModule(new PrefEdit(this));
2938         addModule(new PrefShortcuts(this));
2939         addModule(new PrefScreenFonts(this));
2940         addModule(new PrefColors(this));
2941         addModule(new PrefDisplay(this));
2942         addModule(new PrefInput(this));
2943         addModule(new PrefCompletion(this));
2944
2945         addModule(new PrefPaths(this));
2946
2947         addModule(new PrefIdentity(this));
2948
2949         addModule(new PrefLanguage(this));
2950         addModule(new PrefSpellchecker(this));
2951
2952         //for strftime validator
2953         PrefOutput * output = new PrefOutput(this); 
2954         addModule(output);
2955         addModule(new PrefPrinter(this));
2956         addModule(new PrefLatex(this));
2957
2958         PrefConverters * converters = new PrefConverters(this);
2959         PrefFileformats * formats = new PrefFileformats(this);
2960         connect(formats, SIGNAL(formatsChanged()),
2961                         converters, SLOT(updateGui()));
2962         addModule(converters);
2963         addModule(formats);
2964
2965         prefsPS->setCurrentPanel(qt_("User interface"));
2966 // FIXME: hack to work around resizing bug in Qt >= 4.2
2967 // bug verified with Qt 4.2.{0-3} (JSpitzm)
2968 #if QT_VERSION >= 0x040200
2969         prefsPS->updateGeometry();
2970 #endif
2971
2972         bc().setPolicy(ButtonPolicy::PreferencesPolicy);
2973         bc().setOK(savePB);
2974         bc().setApply(applyPB);
2975         bc().setCancel(closePB);
2976         bc().setRestore(restorePB);
2977
2978         // initialize the strftime validator
2979         bc().addCheckedLineEdit(output->DateED);
2980 }
2981
2982
2983 void GuiPreferences::addModule(PrefModule * module)
2984 {
2985         LASSERT(module, return);
2986         if (module->category().isEmpty())
2987                 prefsPS->addPanel(module, module->title());
2988         else
2989                 prefsPS->addPanel(module, module->title(), module->category());
2990         connect(module, SIGNAL(changed()), this, SLOT(change_adaptor()));
2991         modules_.push_back(module);
2992 }
2993
2994
2995 void GuiPreferences::change_adaptor()
2996 {
2997         changed();
2998 }
2999
3000
3001 void GuiPreferences::apply(LyXRC & rc) const
3002 {
3003         size_t end = modules_.size();
3004         for (size_t i = 0; i != end; ++i)
3005                 modules_[i]->apply(rc);
3006 }
3007
3008
3009 void GuiPreferences::updateRc(LyXRC const & rc)
3010 {
3011         size_t const end = modules_.size();
3012         for (size_t i = 0; i != end; ++i)
3013                 modules_[i]->update(rc);
3014 }
3015
3016
3017 void GuiPreferences::applyView()
3018 {
3019         apply(rc());
3020 }
3021
3022 bool GuiPreferences::initialiseParams(string const &)
3023 {
3024         rc_ = lyxrc;
3025         formats_ = lyx::formats;
3026         converters_ = theConverters();
3027         converters_.update(formats_);
3028         movers_ = theMovers();
3029         colors_.clear();
3030         update_screen_font_ = false;
3031         
3032         updateRc(rc_);
3033         // Make sure that the bc is in the INITIAL state  
3034         if (bc().policy().buttonStatus(ButtonPolicy::RESTORE))  
3035                 bc().restore();  
3036
3037         return true;
3038 }
3039
3040
3041 void GuiPreferences::dispatchParams()
3042 {
3043         ostringstream ss;
3044         rc_.write(ss, true);
3045         dispatch(FuncRequest(LFUN_LYXRC_APPLY, ss.str()));
3046         // FIXME: these need lfuns
3047         // FIXME UNICODE
3048         theBufferList().setCurrentAuthor(from_utf8(rc_.user_name), from_utf8(rc_.user_email));
3049
3050         lyx::formats = formats_;
3051
3052         theConverters() = converters_;
3053         theConverters().update(lyx::formats);
3054         theConverters().buildGraph();
3055
3056         theMovers() = movers_;
3057
3058         vector<string>::const_iterator it = colors_.begin();
3059         vector<string>::const_iterator const end = colors_.end();
3060         for (; it != end; ++it)
3061                 dispatch(FuncRequest(LFUN_SET_COLOR, *it));
3062         colors_.clear();
3063
3064         if (update_screen_font_) {
3065                 dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3066                 update_screen_font_ = false;
3067         }
3068
3069         // The Save button has been pressed
3070         if (isClosing())
3071                 dispatch(FuncRequest(LFUN_PREFERENCES_SAVE));
3072 }
3073
3074
3075 void GuiPreferences::setColor(ColorCode col, QString const & hex)
3076 {
3077         colors_.push_back(lcolor.getLyXName(col) + ' ' + fromqstr(hex));
3078 }
3079
3080
3081 void GuiPreferences::updateScreenFonts()
3082 {
3083         update_screen_font_ = true;
3084 }
3085
3086
3087 QString GuiPreferences::browsebind(QString const & file) const
3088 {
3089         return browseLibFile("bind", file, "bind", qt_("Choose bind file"),
3090                              QStringList(qt_("LyX bind files (*.bind)")));
3091 }
3092
3093
3094 QString GuiPreferences::browseUI(QString const & file) const
3095 {
3096         return browseLibFile("ui", file, "ui", qt_("Choose UI file"),
3097                              QStringList(qt_("LyX UI files (*.ui)")));
3098 }
3099
3100
3101 QString GuiPreferences::browsekbmap(QString const & file) const
3102 {
3103         return browseLibFile("kbd", file, "kmap", qt_("Choose keyboard map"),
3104                              QStringList(qt_("LyX keyboard maps (*.kmap)")));
3105 }
3106
3107
3108 QString GuiPreferences::browse(QString const & file,
3109         QString const & title) const
3110 {
3111         return browseFile(file, title, QStringList(), true);
3112 }
3113
3114
3115 // We support less paper sizes than the document dialog
3116 // Therefore this adjustment is needed.
3117 PAPER_SIZE GuiPreferences::toPaperSize(int i) const
3118 {
3119         switch (i) {
3120         case 0:
3121                 return PAPER_DEFAULT;
3122         case 1:
3123                 return PAPER_USLETTER;
3124         case 2:
3125                 return PAPER_USLEGAL;
3126         case 3:
3127                 return PAPER_USEXECUTIVE;
3128         case 4:
3129                 return PAPER_A3;
3130         case 5:
3131                 return PAPER_A4;
3132         case 6:
3133                 return PAPER_A5;
3134         case 7:
3135                 return PAPER_B5;
3136         default:
3137                 // should not happen
3138                 return PAPER_DEFAULT;
3139         }
3140 }
3141
3142
3143 int GuiPreferences::fromPaperSize(PAPER_SIZE papersize) const
3144 {
3145         switch (papersize) {
3146         case PAPER_DEFAULT:
3147                 return 0;
3148         case PAPER_USLETTER:
3149                 return 1;
3150         case PAPER_USLEGAL:
3151                 return 2;
3152         case PAPER_USEXECUTIVE:
3153                 return 3;
3154         case PAPER_A3:
3155                 return 4;
3156         case PAPER_A4:
3157                 return 5;
3158         case PAPER_A5:
3159                 return 6;
3160         case PAPER_B5:
3161                 return 7;
3162         default:
3163                 // should not happen
3164                 return 0;
3165         }
3166 }
3167
3168
3169 Dialog * createGuiPreferences(GuiView & lv) { return new GuiPreferences(lv); }
3170
3171
3172 } // namespace frontend
3173 } // namespace lyx
3174
3175 #include "moc_GuiPrefs.cpp"