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