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