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