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