]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiPrefs.cpp
Add a preference combo box for the preferred user interface language. The rc variable...
[lyx.git] / src / frontends / qt4 / GuiPrefs.cpp
1 /**
2  * \file GuiPrefs.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author John Levon
7  * \author Bo Peng
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "GuiPrefs.h"
15
16 #include "ColorCache.h"
17 #include "FileDialog.h"
18 #include "GuiApplication.h"
19 #include "GuiFontExample.h"
20 #include "GuiFontLoader.h"
21 #include "GuiKeySymbol.h"
22 #include "qt_helpers.h"
23
24 #include "BufferList.h"
25 #include "Color.h"
26 #include "ConverterCache.h"
27 #include "FontEnums.h"
28 #include "FuncRequest.h"
29 #include "KeyMap.h"
30 #include "KeySequence.h"
31 #include "Language.h"
32 #include "LyXAction.h"
33 #include "PanelStack.h"
34 #include "paper.h"
35 #include "Session.h"
36
37 #include "support/debug.h"
38 #include "support/FileName.h"
39 #include "support/filetools.h"
40 #include "support/foreach.h"
41 #include "support/gettext.h"
42 #include "support/lstrings.h"
43 #include "support/os.h"
44 #include "support/Package.h"
45
46 #include "graphics/GraphicsTypes.h"
47
48 #include "frontends/alert.h"
49 #include "frontends/Application.h"
50 #include "frontends/FontLoader.h"
51
52 #include <QAbstractItemModel>
53 #include <QCheckBox>
54 #include <QColorDialog>
55 #include <QFontDatabase>
56 #include <QHeaderView>
57 #include <QLineEdit>
58 #include <QPixmapCache>
59 #include <QPushButton>
60 #include <QSpinBox>
61 #include <QString>
62 #include <QTreeWidget>
63 #include <QTreeWidgetItem>
64 #include <QValidator>
65
66 #include <iomanip>
67 #include <sstream>
68 #include <algorithm>
69
70 using namespace Ui;
71
72 using namespace std;
73 using namespace lyx::support;
74 using namespace lyx::support::os;
75
76 namespace lyx {
77 namespace frontend {
78
79 /////////////////////////////////////////////////////////////////////
80 //
81 // Browser Helpers
82 //
83 /////////////////////////////////////////////////////////////////////
84
85 /** Launch a file dialog and return the chosen file.
86         filename: a suggested filename.
87         title: the title of the dialog.
88         pattern: *.ps etc.
89         dir1 = (name, dir), dir2 = (name, dir): extra buttons on the dialog.
90 */
91 QString browseFile(QString const & filename,
92         QString const & title,
93         QStringList const & filters,
94         bool save = false,
95         QString const & label1 = QString(),
96         QString const & dir1 = QString(),
97         QString const & label2 = QString(),
98         QString const & dir2 = QString())
99 {
100         QString lastPath = ".";
101         if (!filename.isEmpty())
102                 lastPath = onlyPath(filename);
103
104         FileDialog dlg(title, LFUN_SELECT_FILE_SYNC);
105         dlg.setButton2(label1, dir1);
106         dlg.setButton2(label2, dir2);
107
108         FileDialog::Result result;
109
110         if (save)
111                 result = dlg.save(lastPath, filters, onlyFilename(filename));
112         else
113                 result = dlg.open(lastPath, filters, onlyFilename(filename));
114
115         return result.second;
116 }
117
118
119 /** Wrapper around browseFile which tries to provide a filename
120 *  relative to the user or system directory. The dir, name and ext
121 *  parameters have the same meaning as in the
122 *  support::LibFileSearch function.
123 */
124 QString browseLibFile(QString const & dir,
125         QString const & name,
126         QString const & ext,
127         QString const & title,
128         QStringList const & filters)
129 {
130         // FIXME UNICODE
131         QString const label1 = qt_("System files|#S#s");
132         QString const dir1 =
133                 toqstr(addName(package().system_support().absFilename(), fromqstr(dir)));
134
135         QString const label2 = qt_("User files|#U#u");
136         QString const dir2 =
137                 toqstr(addName(package().user_support().absFilename(), fromqstr(dir)));
138
139         QString const result = browseFile(toqstr(
140                 libFileSearch(dir, name, ext).absFilename()),
141                 title, filters, false, dir1, dir2);
142
143         // remove the extension if it is the default one
144         QString noextresult;
145         if (getExtension(result) == ext)
146                 noextresult = removeExtension(result);
147         else
148                 noextresult = result;
149
150         // remove the directory, if it is the default one
151         QString const file = onlyFilename(noextresult);
152         if (toqstr(libFileSearch(dir, file, ext).absFilename()) == result)
153                 return file;
154         else
155                 return noextresult;
156 }
157
158
159 /** Launch a file dialog and return the chosen directory.
160         pathname: a suggested pathname.
161         title: the title of the dialog.
162         dir1 = (name, dir), dir2 = (name, dir): extra buttons on the dialog.
163 */
164 QString browseDir(QString const & pathname,
165         QString const & title,
166         QString const & label1 = QString(),
167         QString const & dir1 = QString(),
168         QString const & label2 = QString(),
169         QString const & dir2 = QString())
170 {
171         QString lastPath = ".";
172         if (!pathname.isEmpty())
173                 lastPath = onlyPath(pathname);
174
175         FileDialog dlg(title, LFUN_SELECT_FILE_SYNC);
176         dlg.setButton1(label1, dir1);
177         dlg.setButton2(label2, dir2);
178
179         FileDialog::Result const result =
180                 dlg.opendir(lastPath, onlyFilename(pathname));
181
182         return result.second;
183 }
184
185
186 } // namespace frontend
187
188
189 QString browseRelFile(QString const & filename, QString const & refpath,
190         QString const & title, QStringList const & filters, bool save,
191         QString const & label1, QString const & dir1,
192         QString const & label2, QString const & dir2)
193 {
194         QString const fname = makeAbsPath(filename, refpath);
195
196
197         QString const outname =
198                 frontend::browseFile(fname, title, filters, save, label1, dir1, label2, dir2);
199
200         QString const reloutname =
201                 toqstr(makeRelPath(qstring_to_ucs4(outname), qstring_to_ucs4(refpath)));
202
203         if (reloutname.startsWith("../"))
204                 return outname;
205         else
206                 return reloutname;
207 }
208
209
210
211 /////////////////////////////////////////////////////////////////////
212 //
213 // Helpers
214 //
215 /////////////////////////////////////////////////////////////////////
216
217 namespace frontend {
218
219 string const catLookAndFeel = N_("Look & Feel");
220 string const catEditing = N_("Editing");
221 string const catLanguage = N_("Language Settings");
222 string const catOutput = N_("Output");
223 string const catFiles = N_("File Handling");
224
225 static void parseFontName(QString const & mangled0,
226         string & name, string & foundry)
227 {
228         string mangled = fromqstr(mangled0);
229         size_t const idx = mangled.find('[');
230         if (idx == string::npos || idx == 0) {
231                 name = mangled;
232                 foundry.clear();
233         } else {
234                 name = mangled.substr(0, idx - 1),
235                 foundry = mangled.substr(idx + 1, mangled.size() - idx - 2);
236         }
237 }
238
239
240 static void setComboxFont(QComboBox * cb, string const & family,
241         string const & foundry)
242 {
243         QString fontname = toqstr(family);
244         if (!foundry.empty())
245                 fontname += " [" + toqstr(foundry) + ']';
246
247         for (int i = 0; i != cb->count(); ++i) {
248                 if (cb->itemText(i) == fontname) {
249                         cb->setCurrentIndex(i);
250                         return;
251                 }
252         }
253
254         // Try matching without foundry name
255
256         // We count in reverse in order to prefer the Xft foundry
257         for (int i = cb->count(); --i >= 0;) {
258                 string name, foundry;
259                 parseFontName(cb->itemText(i), name, foundry);
260                 if (compare_ascii_no_case(name, family) == 0) {
261                         cb->setCurrentIndex(i);
262                         return;
263                 }
264         }
265
266         // family alone can contain e.g. "Helvetica [Adobe]"
267         string tmpname, tmpfoundry;
268         parseFontName(toqstr(family), tmpname, tmpfoundry);
269
270         // We count in reverse in order to prefer the Xft foundry
271         for (int i = cb->count(); --i >= 0; ) {
272                 string name, foundry;
273                 parseFontName(cb->itemText(i), name, foundry);
274                 if (compare_ascii_no_case(name, foundry) == 0) {
275                         cb->setCurrentIndex(i);
276                         return;
277                 }
278         }
279
280         // Bleh, default fonts, and the names couldn't be found. Hack
281         // for bug 1063.
282
283         QFont font;
284         font.setKerning(false);
285
286         QString const font_family = toqstr(family);
287         if (font_family == guiApp->romanFontName()) {
288                 font.setStyleHint(QFont::Serif);
289                 font.setFamily(font_family);
290         } else if (font_family == guiApp->sansFontName()) {
291                 font.setStyleHint(QFont::SansSerif);
292                 font.setFamily(font_family);
293         } else if (font_family == guiApp->typewriterFontName()) {
294                 font.setStyleHint(QFont::TypeWriter);
295                 font.setFamily(font_family);
296         } else {
297                 LYXERR0("FAILED to find the default font: '"
298                        << foundry << "', '" << family << '\'');
299                 return;
300         }
301
302         QFontInfo info(font);
303         string default_font_name, dummyfoundry;
304         parseFontName(info.family(), default_font_name, dummyfoundry);
305         LYXERR0("Apparent font is " << default_font_name);
306
307         for (int i = 0; i < cb->count(); ++i) {
308                 LYXERR0("Looking at " << cb->itemText(i));
309                 if (compare_ascii_no_case(fromqstr(cb->itemText(i)),
310                                     default_font_name) == 0) {
311                         cb->setCurrentIndex(i);
312                         return;
313                 }
314         }
315
316         LYXERR0("FAILED to find the font: '"
317                << foundry << "', '" << family << '\'');
318 }
319
320
321
322 /////////////////////////////////////////////////////////////////////
323 //
324 // PrefPlaintext
325 //
326 /////////////////////////////////////////////////////////////////////
327
328 PrefPlaintext::PrefPlaintext(GuiPreferences * form)
329         : PrefModule(qt_(catOutput), qt_("Plain text"), form)
330 {
331         setupUi(this);
332         connect(plaintextLinelengthSB, SIGNAL(valueChanged(int)),
333                 this, SIGNAL(changed()));
334         connect(plaintextRoffED, SIGNAL(textChanged(QString)),
335                 this, SIGNAL(changed()));
336 }
337
338
339 void PrefPlaintext::apply(LyXRC & rc) const
340 {
341         rc.plaintext_linelen = plaintextLinelengthSB->value();
342         rc.plaintext_roff_command = fromqstr(plaintextRoffED->text());
343 }
344
345
346 void PrefPlaintext::update(LyXRC const & rc)
347 {
348         plaintextLinelengthSB->setValue(rc.plaintext_linelen);
349         plaintextRoffED->setText(toqstr(rc.plaintext_roff_command));
350 }
351
352
353 /////////////////////////////////////////////////////////////////////
354 //
355 // PrefDate
356 //
357 /////////////////////////////////////////////////////////////////////
358
359 PrefDate::PrefDate(GuiPreferences * form)
360         : PrefModule(qt_(catOutput), qt_("Date format"), form)
361 {
362         setupUi(this);
363         connect(DateED, SIGNAL(textChanged(QString)),
364                 this, SIGNAL(changed()));
365 }
366
367
368 void PrefDate::apply(LyXRC & rc) const
369 {
370         rc.date_insert_format = fromqstr(DateED->text());
371 }
372
373
374 void PrefDate::update(LyXRC const & rc)
375 {
376         DateED->setText(toqstr(rc.date_insert_format));
377 }
378
379
380 /////////////////////////////////////////////////////////////////////
381 //
382 // PrefInput
383 //
384 /////////////////////////////////////////////////////////////////////
385
386 PrefInput::PrefInput(GuiPreferences * form)
387         : PrefModule(qt_(catEditing), qt_("Keyboard/Mouse"), form)
388 {
389         setupUi(this);
390
391         connect(keymapCB, SIGNAL(clicked()),
392                 this, SIGNAL(changed()));
393         connect(firstKeymapED, SIGNAL(textChanged(QString)),
394                 this, SIGNAL(changed()));
395         connect(secondKeymapED, SIGNAL(textChanged(QString)),
396                 this, SIGNAL(changed()));
397         connect(mouseWheelSpeedSB, SIGNAL(valueChanged(double)),
398                 this, SIGNAL(changed()));
399 }
400
401
402 void PrefInput::apply(LyXRC & rc) const
403 {
404         // FIXME: can derive CB from the two EDs
405         rc.use_kbmap = keymapCB->isChecked();
406         rc.primary_kbmap = internal_path(fromqstr(firstKeymapED->text()));
407         rc.secondary_kbmap = internal_path(fromqstr(secondKeymapED->text()));
408         rc.mouse_wheel_speed = mouseWheelSpeedSB->value();
409 }
410
411
412 void PrefInput::update(LyXRC const & rc)
413 {
414         // FIXME: can derive CB from the two EDs
415         keymapCB->setChecked(rc.use_kbmap);
416         firstKeymapED->setText(toqstr(external_path(rc.primary_kbmap)));
417         secondKeymapED->setText(toqstr(external_path(rc.secondary_kbmap)));
418         mouseWheelSpeedSB->setValue(rc.mouse_wheel_speed);
419 }
420
421
422 QString PrefInput::testKeymap(QString const & keymap)
423 {
424         return form_->browsekbmap(internalPath(keymap));
425 }
426
427
428 void PrefInput::on_firstKeymapPB_clicked(bool)
429 {
430         QString const file = testKeymap(firstKeymapED->text());
431         if (!file.isEmpty())
432                 firstKeymapED->setText(file);
433 }
434
435
436 void PrefInput::on_secondKeymapPB_clicked(bool)
437 {
438         QString const file = testKeymap(secondKeymapED->text());
439         if (!file.isEmpty())
440                 secondKeymapED->setText(file);
441 }
442
443
444 void PrefInput::on_keymapCB_toggled(bool keymap)
445 {
446         firstKeymapLA->setEnabled(keymap);
447         secondKeymapLA->setEnabled(keymap);
448         firstKeymapED->setEnabled(keymap);
449         secondKeymapED->setEnabled(keymap);
450         firstKeymapPB->setEnabled(keymap);
451         secondKeymapPB->setEnabled(keymap);
452 }
453
454
455 /////////////////////////////////////////////////////////////////////
456 //
457 // PrefCompletion
458 //
459 /////////////////////////////////////////////////////////////////////
460
461 PrefCompletion::PrefCompletion(GuiPreferences * form)
462         : PrefModule(qt_(catEditing), qt_("Input Completion"), form)
463 {
464         setupUi(this);
465
466         connect(inlineDelaySB, SIGNAL(valueChanged(double)),
467                 this, SIGNAL(changed()));
468         connect(inlineMathCB, SIGNAL(clicked()),
469                 this, SIGNAL(changed()));
470         connect(inlineTextCB, SIGNAL(clicked()),
471                 this, SIGNAL(changed()));
472         connect(inlineDotsCB, SIGNAL(clicked()),
473                 this, SIGNAL(changed()));
474         connect(popupDelaySB, SIGNAL(valueChanged(double)),
475                 this, SIGNAL(changed()));
476         connect(popupMathCB, SIGNAL(clicked()),
477                 this, SIGNAL(changed()));
478         connect(popupTextCB, SIGNAL(clicked()),
479                 this, SIGNAL(changed()));
480         connect(popupAfterCompleteCB, SIGNAL(clicked()),
481                 this, SIGNAL(changed()));
482         connect(cursorTextCB, SIGNAL(clicked()),
483                 this, SIGNAL(changed()));
484 }
485
486
487 void PrefCompletion::apply(LyXRC & rc) const
488 {
489         rc.completion_inline_delay = inlineDelaySB->value();
490         rc.completion_inline_math = inlineMathCB->isChecked();
491         rc.completion_inline_text = inlineTextCB->isChecked();
492         rc.completion_inline_dots = inlineDotsCB->isChecked() ? 13 : -1;
493         rc.completion_popup_delay = popupDelaySB->value();
494         rc.completion_popup_math = popupMathCB->isChecked();
495         rc.completion_popup_text = popupTextCB->isChecked();
496         rc.completion_cursor_text = cursorTextCB->isChecked();
497         rc.completion_popup_after_complete =
498                 popupAfterCompleteCB->isChecked();
499 }
500
501
502 void PrefCompletion::update(LyXRC const & rc)
503 {
504         inlineDelaySB->setValue(rc.completion_inline_delay);
505         inlineMathCB->setChecked(rc.completion_inline_math);
506         inlineTextCB->setChecked(rc.completion_inline_text);
507         inlineDotsCB->setChecked(rc.completion_inline_dots != -1);
508         popupDelaySB->setValue(rc.completion_popup_delay);
509         popupMathCB->setChecked(rc.completion_popup_math);
510         popupTextCB->setChecked(rc.completion_popup_text);
511         cursorTextCB->setChecked(rc.completion_cursor_text);
512         popupAfterCompleteCB->setChecked(rc.completion_popup_after_complete);
513 }
514
515
516
517 /////////////////////////////////////////////////////////////////////
518 //
519 // PrefLatex
520 //
521 /////////////////////////////////////////////////////////////////////
522
523 PrefLatex::PrefLatex(GuiPreferences * form)
524         : PrefModule(qt_(catOutput), qt_("LaTeX"), form)
525 {
526         setupUi(this);
527         connect(latexEncodingED, SIGNAL(textChanged(QString)),
528                 this, SIGNAL(changed()));
529         connect(latexChecktexED, SIGNAL(textChanged(QString)),
530                 this, SIGNAL(changed()));
531         connect(latexBibtexED, SIGNAL(textChanged(QString)),
532                 this, SIGNAL(changed()));
533         connect(latexIndexED, SIGNAL(textChanged(QString)),
534                 this, SIGNAL(changed()));
535         connect(latexAutoresetCB, SIGNAL(clicked()),
536                 this, SIGNAL(changed()));
537         connect(latexDviPaperED, SIGNAL(textChanged(QString)),
538                 this, SIGNAL(changed()));
539         connect(latexPaperSizeCO, SIGNAL(activated(int)),
540                 this, SIGNAL(changed()));
541
542 #if defined(__CYGWIN__) || defined(_WIN32)
543         pathCB->setVisible(true);
544         connect(pathCB, SIGNAL(clicked()), 
545                 this, SIGNAL(changed()));
546 #else
547         pathCB->setVisible(false);
548 #endif
549 }
550
551
552 void PrefLatex::apply(LyXRC & rc) const
553 {
554         rc.fontenc = fromqstr(latexEncodingED->text());
555         rc.chktex_command = fromqstr(latexChecktexED->text());
556         rc.bibtex_command = fromqstr(latexBibtexED->text());
557         rc.index_command = fromqstr(latexIndexED->text());
558         rc.auto_reset_options = latexAutoresetCB->isChecked();
559         rc.view_dvi_paper_option = fromqstr(latexDviPaperED->text());
560         rc.default_papersize =
561                 form_->toPaperSize(latexPaperSizeCO->currentIndex());
562 #if defined(__CYGWIN__) || defined(_WIN32)
563         rc.windows_style_tex_paths = pathCB->isChecked();
564 #endif
565 }
566
567
568 void PrefLatex::update(LyXRC const & rc)
569 {
570         latexEncodingED->setText(toqstr(rc.fontenc));
571         latexChecktexED->setText(toqstr(rc.chktex_command));
572         latexBibtexED->setText(toqstr(rc.bibtex_command));
573         latexIndexED->setText(toqstr(rc.index_command));
574         latexAutoresetCB->setChecked(rc.auto_reset_options);
575         latexDviPaperED->setText(toqstr(rc.view_dvi_paper_option));
576         latexPaperSizeCO->setCurrentIndex(
577                 form_->fromPaperSize(rc.default_papersize));
578 #if defined(__CYGWIN__) || defined(_WIN32)
579         pathCB->setChecked(rc.windows_style_tex_paths);
580 #endif
581 }
582
583
584 /////////////////////////////////////////////////////////////////////
585 //
586 // PrefScreenFonts
587 //
588 /////////////////////////////////////////////////////////////////////
589
590 PrefScreenFonts::PrefScreenFonts(GuiPreferences * form)
591         : PrefModule(qt_(catLookAndFeel), qt_("Screen fonts"), form)
592 {
593         setupUi(this);
594
595         connect(screenRomanCO, SIGNAL(activated(QString)),
596                 this, SLOT(select_roman(QString)));
597         connect(screenSansCO, SIGNAL(activated(QString)),
598                 this, SLOT(select_sans(QString)));
599         connect(screenTypewriterCO, SIGNAL(activated(QString)),
600                 this, SLOT(select_typewriter(QString)));
601
602         QFontDatabase fontdb;
603         QStringList families(fontdb.families());
604         for (QStringList::Iterator it = families.begin(); it != families.end(); ++it) {
605                 screenRomanCO->addItem(*it);
606                 screenSansCO->addItem(*it);
607                 screenTypewriterCO->addItem(*it);
608         }
609         connect(screenRomanCO, SIGNAL(activated(QString)),
610                 this, SIGNAL(changed()));
611         connect(screenSansCO, SIGNAL(activated(QString)),
612                 this, SIGNAL(changed()));
613         connect(screenTypewriterCO, SIGNAL(activated(QString)),
614                 this, SIGNAL(changed()));
615         connect(screenZoomSB, SIGNAL(valueChanged(int)),
616                 this, SIGNAL(changed()));
617         connect(screenDpiSB, SIGNAL(valueChanged(int)),
618                 this, SIGNAL(changed()));
619         connect(screenTinyED, SIGNAL(textChanged(QString)),
620                 this, SIGNAL(changed()));
621         connect(screenSmallestED, SIGNAL(textChanged(QString)),
622                 this, SIGNAL(changed()));
623         connect(screenSmallerED, SIGNAL(textChanged(QString)),
624                 this, SIGNAL(changed()));
625         connect(screenSmallED, SIGNAL(textChanged(QString)),
626                 this, SIGNAL(changed()));
627         connect(screenNormalED, SIGNAL(textChanged(QString)),
628                 this, SIGNAL(changed()));
629         connect(screenLargeED, SIGNAL(textChanged(QString)),
630                 this, SIGNAL(changed()));
631         connect(screenLargerED, SIGNAL(textChanged(QString)),
632                 this, SIGNAL(changed()));
633         connect(screenLargestED, SIGNAL(textChanged(QString)),
634                 this, SIGNAL(changed()));
635         connect(screenHugeED, SIGNAL(textChanged(QString)),
636                 this, SIGNAL(changed()));
637         connect(screenHugerED, SIGNAL(textChanged(QString)),
638                 this, SIGNAL(changed()));
639         connect(pixmapCacheCB, SIGNAL(toggled(bool)),
640                 this, SIGNAL(changed()));
641
642         screenTinyED->setValidator(new QDoubleValidator(screenTinyED));
643         screenSmallestED->setValidator(new QDoubleValidator(screenSmallestED));
644         screenSmallerED->setValidator(new QDoubleValidator(screenSmallerED));
645         screenSmallED->setValidator(new QDoubleValidator(screenSmallED));
646         screenNormalED->setValidator(new QDoubleValidator(screenNormalED));
647         screenLargeED->setValidator(new QDoubleValidator(screenLargeED));
648         screenLargerED->setValidator(new QDoubleValidator(screenLargerED));
649         screenLargestED->setValidator(new QDoubleValidator(screenLargestED));
650         screenHugeED->setValidator(new QDoubleValidator(screenHugeED));
651         screenHugerED->setValidator(new QDoubleValidator(screenHugerED));
652 }
653
654
655 void PrefScreenFonts::apply(LyXRC & rc) const
656 {
657         LyXRC const oldrc = rc;
658
659         parseFontName(screenRomanCO->currentText(),
660                 rc.roman_font_name, rc.roman_font_foundry);
661         parseFontName(screenSansCO->currentText(),
662                 rc.sans_font_name, rc.sans_font_foundry);
663         parseFontName(screenTypewriterCO->currentText(),
664                 rc.typewriter_font_name, rc.typewriter_font_foundry);
665
666         rc.zoom = screenZoomSB->value();
667         rc.dpi = screenDpiSB->value();
668         rc.font_sizes[FONT_SIZE_TINY] = fromqstr(screenTinyED->text());
669         rc.font_sizes[FONT_SIZE_SCRIPT] = fromqstr(screenSmallestED->text());
670         rc.font_sizes[FONT_SIZE_FOOTNOTE] = fromqstr(screenSmallerED->text());
671         rc.font_sizes[FONT_SIZE_SMALL] = fromqstr(screenSmallED->text());
672         rc.font_sizes[FONT_SIZE_NORMAL] = fromqstr(screenNormalED->text());
673         rc.font_sizes[FONT_SIZE_LARGE] = fromqstr(screenLargeED->text());
674         rc.font_sizes[FONT_SIZE_LARGER] = fromqstr(screenLargerED->text());
675         rc.font_sizes[FONT_SIZE_LARGEST] = fromqstr(screenLargestED->text());
676         rc.font_sizes[FONT_SIZE_HUGE] = fromqstr(screenHugeED->text());
677         rc.font_sizes[FONT_SIZE_HUGER] = fromqstr(screenHugerED->text());
678         rc.use_pixmap_cache = pixmapCacheCB->isChecked();
679
680         if (rc.font_sizes != oldrc.font_sizes
681                 || rc.roman_font_name != oldrc.roman_font_name
682                 || rc.sans_font_name != oldrc.sans_font_name
683                 || rc.typewriter_font_name != oldrc.typewriter_font_name
684                 || rc.zoom != oldrc.zoom || rc.dpi != oldrc.dpi) {
685                 // The global QPixmapCache is used in GuiPainter to cache text
686                 // painting so we must reset it in case any of the above
687                 // parameter is changed.
688                 QPixmapCache::clear();
689                 guiApp->fontLoader().update();
690                 form_->updateScreenFonts();
691         }
692 }
693
694
695 void PrefScreenFonts::update(LyXRC const & rc)
696 {
697         setComboxFont(screenRomanCO, rc.roman_font_name,
698                         rc.roman_font_foundry);
699         setComboxFont(screenSansCO, rc.sans_font_name,
700                         rc.sans_font_foundry);
701         setComboxFont(screenTypewriterCO, rc.typewriter_font_name,
702                         rc.typewriter_font_foundry);
703
704         select_roman(screenRomanCO->currentText());
705         select_sans(screenSansCO->currentText());
706         select_typewriter(screenTypewriterCO->currentText());
707
708         screenZoomSB->setValue(rc.zoom);
709         screenDpiSB->setValue(rc.dpi);
710         screenTinyED->setText(toqstr(rc.font_sizes[FONT_SIZE_TINY]));
711         screenSmallestED->setText(toqstr(rc.font_sizes[FONT_SIZE_SCRIPT]));
712         screenSmallerED->setText(toqstr(rc.font_sizes[FONT_SIZE_FOOTNOTE]));
713         screenSmallED->setText(toqstr(rc.font_sizes[FONT_SIZE_SMALL]));
714         screenNormalED->setText(toqstr(rc.font_sizes[FONT_SIZE_NORMAL]));
715         screenLargeED->setText(toqstr(rc.font_sizes[FONT_SIZE_LARGE]));
716         screenLargerED->setText(toqstr(rc.font_sizes[FONT_SIZE_LARGER]));
717         screenLargestED->setText(toqstr(rc.font_sizes[FONT_SIZE_LARGEST]));
718         screenHugeED->setText(toqstr(rc.font_sizes[FONT_SIZE_HUGE]));
719         screenHugerED->setText(toqstr(rc.font_sizes[FONT_SIZE_HUGER]));
720
721         pixmapCacheCB->setChecked(rc.use_pixmap_cache);
722 #if defined(Q_WS_X11)
723         pixmapCacheCB->setEnabled(false);
724 #endif
725         
726 }
727
728
729 void PrefScreenFonts::select_roman(const QString & name)
730 {
731         screenRomanFE->set(QFont(name), name);
732 }
733
734
735 void PrefScreenFonts::select_sans(const QString & name)
736 {
737         screenSansFE->set(QFont(name), name);
738 }
739
740
741 void PrefScreenFonts::select_typewriter(const QString & name)
742 {
743         screenTypewriterFE->set(QFont(name), name);
744 }
745
746
747 /////////////////////////////////////////////////////////////////////
748 //
749 // PrefColors
750 //
751 /////////////////////////////////////////////////////////////////////
752
753 namespace {
754
755 struct ColorSorter
756 {
757         bool operator()(ColorCode lhs, ColorCode rhs) const {
758                 return lcolor.getGUIName(lhs) < lcolor.getGUIName(rhs);
759         }
760 };
761
762 } // namespace anon
763
764 PrefColors::PrefColors(GuiPreferences * form)
765         : PrefModule(qt_(catLookAndFeel), qt_("Colors"), form)
766 {
767         setupUi(this);
768
769         // FIXME: all of this initialization should be put into the controller.
770         // See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg113301.html
771         // for some discussion of why that is not trivial.
772         QPixmap icon(32, 32);
773         for (int i = 0; i < Color_ignore; ++i) {
774                 ColorCode lc = static_cast<ColorCode>(i);
775                 if (lc == Color_none
776                         || lc == Color_black
777                         || lc == Color_white
778                         || lc == Color_red
779                         || lc == Color_green
780                         || lc == Color_blue
781                         || lc == Color_cyan
782                         || lc == Color_magenta
783                         || lc == Color_yellow
784                         || lc == Color_inherit
785                         || lc == Color_ignore) continue;
786
787                 lcolors_.push_back(lc);
788         }
789         sort(lcolors_.begin(), lcolors_.end(), ColorSorter());
790         vector<ColorCode>::const_iterator cit = lcolors_.begin();
791         vector<ColorCode>::const_iterator const end = lcolors_.end();
792         for (; cit != end; ++cit) {
793                         (void) new QListWidgetItem(QIcon(icon),
794                         toqstr(lcolor.getGUIName(*cit)), lyxObjectsLW);
795         }
796         curcolors_.resize(lcolors_.size());
797         newcolors_.resize(lcolors_.size());
798         // End initialization
799
800         connect(colorChangePB, SIGNAL(clicked()),
801                 this, SLOT(change_color()));
802         connect(lyxObjectsLW, SIGNAL(itemSelectionChanged()),
803                 this, SLOT(change_lyxObjects_selection()));
804         connect(lyxObjectsLW, SIGNAL(itemActivated(QListWidgetItem*)),
805                 this, SLOT(change_color()));
806 }
807
808
809 void PrefColors::apply(LyXRC & /*rc*/) const
810 {
811         for (unsigned int i = 0; i < lcolors_.size(); ++i)
812                 if (curcolors_[i] != newcolors_[i])
813                         form_->setColor(lcolors_[i], newcolors_[i]);
814 }
815
816
817 void PrefColors::update(LyXRC const & /*rc*/)
818 {
819         for (unsigned int i = 0; i < lcolors_.size(); ++i) {
820                 QColor color = QColor(guiApp->colorCache().get(lcolors_[i]));
821                 QPixmap coloritem(32, 32);
822                 coloritem.fill(color);
823                 lyxObjectsLW->item(i)->setIcon(QIcon(coloritem));
824                 newcolors_[i] = curcolors_[i] = color.name();
825         }
826         change_lyxObjects_selection();
827 }
828
829
830 void PrefColors::change_color()
831 {
832         int const row = lyxObjectsLW->currentRow();
833
834         // just to be sure
835         if (row < 0)
836                 return;
837
838         QString const color = newcolors_[row];
839         QColor c = QColorDialog::getColor(QColor(color), qApp->focusWidget());
840
841         if (c.isValid() && c.name() != color) {
842                 newcolors_[row] = c.name();
843                 QPixmap coloritem(32, 32);
844                 coloritem.fill(c);
845                 lyxObjectsLW->currentItem()->setIcon(QIcon(coloritem));
846                 // emit signal
847                 changed();
848         }
849 }
850
851 void PrefColors::change_lyxObjects_selection()
852 {
853         colorChangePB->setDisabled(lyxObjectsLW->currentRow() < 0);
854 }
855
856
857 /////////////////////////////////////////////////////////////////////
858 //
859 // PrefDisplay
860 //
861 /////////////////////////////////////////////////////////////////////
862
863 PrefDisplay::PrefDisplay(GuiPreferences * form)
864         : PrefModule(qt_(catLookAndFeel), qt_("Graphics"), form)
865 {
866         setupUi(this);
867         connect(displayGraphicsCB, SIGNAL(toggled(bool)), this, SIGNAL(changed()));
868         connect(instantPreviewCO, SIGNAL(activated(int)), this, SIGNAL(changed()));
869 }
870
871
872 void PrefDisplay::apply(LyXRC & rc) const
873 {
874         switch (instantPreviewCO->currentIndex()) {
875                 case 0: rc.preview = LyXRC::PREVIEW_OFF; break;
876                 case 1: rc.preview = LyXRC::PREVIEW_NO_MATH; break;
877                 case 2: rc.preview = LyXRC::PREVIEW_ON; break;
878         }
879
880         rc.display_graphics = displayGraphicsCB->isChecked();
881
882         // FIXME!! The graphics cache no longer has a changeDisplay method.
883 #if 0
884         if (old_value != rc.display_graphics) {
885                 graphics::GCache & gc = graphics::GCache::get();
886                 gc.changeDisplay();
887         }
888 #endif
889 }
890
891
892 void PrefDisplay::update(LyXRC const & rc)
893 {
894         switch (rc.preview) {
895         case LyXRC::PREVIEW_OFF:
896                 instantPreviewCO->setCurrentIndex(0);
897                 break;
898         case LyXRC::PREVIEW_NO_MATH :
899                 instantPreviewCO->setCurrentIndex(1);
900                 break;
901         case LyXRC::PREVIEW_ON :
902                 instantPreviewCO->setCurrentIndex(2);
903                 break;
904         }
905
906         displayGraphicsCB->setChecked(rc.display_graphics);
907         instantPreviewCO->setEnabled(rc.display_graphics);
908 }
909
910
911 /////////////////////////////////////////////////////////////////////
912 //
913 // PrefPaths
914 //
915 /////////////////////////////////////////////////////////////////////
916
917 PrefPaths::PrefPaths(GuiPreferences * form)
918         : PrefModule(QString(), qt_("Paths"), form)
919 {
920         setupUi(this);
921         connect(exampleDirPB, SIGNAL(clicked()), this, SLOT(select_exampledir()));
922         connect(templateDirPB, SIGNAL(clicked()), this, SLOT(select_templatedir()));
923         connect(tempDirPB, SIGNAL(clicked()), this, SLOT(select_tempdir()));
924         connect(backupDirPB, SIGNAL(clicked()), this, SLOT(select_backupdir()));
925         connect(workingDirPB, SIGNAL(clicked()), this, SLOT(select_workingdir()));
926         connect(lyxserverDirPB, SIGNAL(clicked()), this, SLOT(select_lyxpipe()));
927         connect(workingDirED, SIGNAL(textChanged(QString)),
928                 this, SIGNAL(changed()));
929         connect(exampleDirED, SIGNAL(textChanged(QString)),
930                 this, SIGNAL(changed()));
931         connect(templateDirED, SIGNAL(textChanged(QString)),
932                 this, SIGNAL(changed()));
933         connect(backupDirED, SIGNAL(textChanged(QString)),
934                 this, SIGNAL(changed()));
935         connect(tempDirED, SIGNAL(textChanged(QString)),
936                 this, SIGNAL(changed()));
937         connect(lyxserverDirED, SIGNAL(textChanged(QString)),
938                 this, SIGNAL(changed()));
939         connect(pathPrefixED, SIGNAL(textChanged(QString)),
940                 this, SIGNAL(changed()));
941 }
942
943
944 void PrefPaths::apply(LyXRC & rc) const
945 {
946         rc.document_path = internal_path(fromqstr(workingDirED->text()));
947         rc.example_path = internal_path(fromqstr(exampleDirED->text()));
948         rc.template_path = internal_path(fromqstr(templateDirED->text()));
949         rc.backupdir_path = internal_path(fromqstr(backupDirED->text()));
950         rc.tempdir_path = internal_path(fromqstr(tempDirED->text()));
951         rc.path_prefix = internal_path_list(fromqstr(pathPrefixED->text()));
952         // FIXME: should be a checkbox only
953         rc.lyxpipes = internal_path(fromqstr(lyxserverDirED->text()));
954 }
955
956
957 void PrefPaths::update(LyXRC const & rc)
958 {
959         workingDirED->setText(toqstr(external_path(rc.document_path)));
960         exampleDirED->setText(toqstr(external_path(rc.example_path)));
961         templateDirED->setText(toqstr(external_path(rc.template_path)));
962         backupDirED->setText(toqstr(external_path(rc.backupdir_path)));
963         tempDirED->setText(toqstr(external_path(rc.tempdir_path)));
964         pathPrefixED->setText(toqstr(external_path_list(rc.path_prefix)));
965         // FIXME: should be a checkbox only
966         lyxserverDirED->setText(toqstr(external_path(rc.lyxpipes)));
967 }
968
969
970 void PrefPaths::select_exampledir()
971 {
972         QString file = browseDir(internalPath(exampleDirED->text()),
973                 qt_("Select directory for example files"));
974         if (!file.isEmpty())
975                 exampleDirED->setText(file);
976 }
977
978
979 void PrefPaths::select_templatedir()
980 {
981         QString file = browseDir(internalPath(templateDirED->text()),
982                 qt_("Select a document templates directory"));
983         if (!file.isEmpty())
984                 templateDirED->setText(file);
985 }
986
987
988 void PrefPaths::select_tempdir()
989 {
990         QString file = browseDir(internalPath(tempDirED->text()),
991                 qt_("Select a temporary directory"));
992         if (!file.isEmpty())
993                 tempDirED->setText(file);
994 }
995
996
997 void PrefPaths::select_backupdir()
998 {
999         QString file = browseDir(internalPath(backupDirED->text()),
1000                 qt_("Select a backups directory"));
1001         if (!file.isEmpty())
1002                 backupDirED->setText(file);
1003 }
1004
1005
1006 void PrefPaths::select_workingdir()
1007 {
1008         QString file = browseDir(internalPath(workingDirED->text()),
1009                 qt_("Select a document directory"));
1010         if (!file.isEmpty())
1011                 workingDirED->setText(file);
1012 }
1013
1014
1015 void PrefPaths::select_lyxpipe()
1016 {
1017         QString file = form_->browse(internalPath(lyxserverDirED->text()),
1018                 qt_("Give a filename for the LyX server pipe"));
1019         if (!file.isEmpty())
1020                 lyxserverDirED->setText(file);
1021 }
1022
1023
1024 /////////////////////////////////////////////////////////////////////
1025 //
1026 // PrefSpellchecker
1027 //
1028 /////////////////////////////////////////////////////////////////////
1029
1030 PrefSpellchecker::PrefSpellchecker(GuiPreferences * form)
1031         : PrefModule(qt_(catLanguage), qt_("Spellchecker"), form)
1032 {
1033         setupUi(this);
1034
1035         connect(persDictionaryPB, SIGNAL(clicked()), this, SLOT(select_dict()));
1036 #if defined (USE_ISPELL)
1037         connect(spellCommandCO, SIGNAL(activated(int)),
1038                 this, SIGNAL(changed()));
1039 #else
1040         spellCommandCO->setEnabled(false);
1041 #endif
1042         connect(altLanguageED, SIGNAL(textChanged(QString)),
1043                 this, SIGNAL(changed()));
1044         connect(escapeCharactersED, SIGNAL(textChanged(QString)),
1045                 this, SIGNAL(changed()));
1046         connect(persDictionaryED, SIGNAL(textChanged(QString)),
1047                 this, SIGNAL(changed()));
1048         connect(compoundWordCB, SIGNAL(clicked()),
1049                 this, SIGNAL(changed()));
1050         connect(inputEncodingCB, SIGNAL(clicked()),
1051                 this, SIGNAL(changed()));
1052
1053         spellCommandCO->addItem(qt_("ispell"));
1054         spellCommandCO->addItem(qt_("aspell"));
1055         spellCommandCO->addItem(qt_("hspell"));
1056 #ifdef USE_PSPELL
1057         spellCommandCO->addItem(qt_("pspell (library)"));
1058 #else
1059 #ifdef USE_ASPELL
1060         spellCommandCO->addItem(qt_("aspell (library)"));
1061 #endif
1062 #endif
1063 }
1064
1065
1066 void PrefSpellchecker::apply(LyXRC & rc) const
1067 {
1068         switch (spellCommandCO->currentIndex()) {
1069                 case 0:
1070                 case 1:
1071                 case 2:
1072                         rc.use_spell_lib = false;
1073                         rc.isp_command = fromqstr(spellCommandCO->currentText());
1074                         break;
1075                 case 3:
1076                         rc.use_spell_lib = true;
1077                         break;
1078         }
1079
1080         // FIXME: remove isp_use_alt_lang
1081         rc.isp_alt_lang = fromqstr(altLanguageED->text());
1082         rc.isp_use_alt_lang = !rc.isp_alt_lang.empty();
1083         // FIXME: remove isp_use_esc_chars
1084         rc.isp_esc_chars = fromqstr(escapeCharactersED->text());
1085         rc.isp_use_esc_chars = !rc.isp_esc_chars.empty();
1086         // FIXME: remove isp_use_pers_dict
1087         rc.isp_pers_dict = internal_path(fromqstr(persDictionaryED->text()));
1088         rc.isp_use_pers_dict = !rc.isp_pers_dict.empty();
1089         rc.isp_accept_compound = compoundWordCB->isChecked();
1090         rc.isp_use_input_encoding = inputEncodingCB->isChecked();
1091 }
1092
1093
1094 void PrefSpellchecker::update(LyXRC const & rc)
1095 {
1096         spellCommandCO->setCurrentIndex(0);
1097
1098         if (rc.isp_command == "ispell") {
1099                 spellCommandCO->setCurrentIndex(0);
1100         } else if (rc.isp_command == "aspell") {
1101                 spellCommandCO->setCurrentIndex(1);
1102         } else if (rc.isp_command == "hspell") {
1103                 spellCommandCO->setCurrentIndex(2);
1104         }
1105
1106         if (rc.use_spell_lib) {
1107 #if defined(USE_ASPELL) || defined(USE_PSPELL)
1108                 spellCommandCO->setCurrentIndex(3);
1109 #endif
1110         }
1111
1112         // FIXME: remove isp_use_alt_lang
1113         altLanguageED->setText(toqstr(rc.isp_alt_lang));
1114         // FIXME: remove isp_use_esc_chars
1115         escapeCharactersED->setText(toqstr(rc.isp_esc_chars));
1116         // FIXME: remove isp_use_pers_dict
1117         persDictionaryED->setText(toqstr(external_path(rc.isp_pers_dict)));
1118         compoundWordCB->setChecked(rc.isp_accept_compound);
1119         inputEncodingCB->setChecked(rc.isp_use_input_encoding);
1120 }
1121
1122
1123 void PrefSpellchecker::select_dict()
1124 {
1125         QString file = form_->browsedict(internalPath(persDictionaryED->text()));
1126         if (!file.isEmpty())
1127                 persDictionaryED->setText(file);
1128 }
1129
1130
1131
1132 /////////////////////////////////////////////////////////////////////
1133 //
1134 // PrefConverters
1135 //
1136 /////////////////////////////////////////////////////////////////////
1137
1138
1139 PrefConverters::PrefConverters(GuiPreferences * form)
1140         : PrefModule(qt_(catFiles), qt_("Converters"), form)
1141 {
1142         setupUi(this);
1143
1144         connect(converterNewPB, SIGNAL(clicked()),
1145                 this, SLOT(update_converter()));
1146         connect(converterRemovePB, SIGNAL(clicked()),
1147                 this, SLOT(remove_converter()));
1148         connect(converterModifyPB, SIGNAL(clicked()),
1149                 this, SLOT(update_converter()));
1150         connect(convertersLW, SIGNAL(currentRowChanged(int)),
1151                 this, SLOT(switch_converter()));
1152         connect(converterFromCO, SIGNAL(activated(QString)),
1153                 this, SLOT(converter_changed()));
1154         connect(converterToCO, SIGNAL(activated(QString)),
1155                 this, SLOT(converter_changed()));
1156         connect(converterED, SIGNAL(textEdited(QString)),
1157                 this, SLOT(converter_changed()));
1158         connect(converterFlagED, SIGNAL(textEdited(QString)),
1159                 this, SLOT(converter_changed()));
1160         connect(converterNewPB, SIGNAL(clicked()),
1161                 this, SIGNAL(changed()));
1162         connect(converterRemovePB, SIGNAL(clicked()),
1163                 this, SIGNAL(changed()));
1164         connect(converterModifyPB, SIGNAL(clicked()),
1165                 this, SIGNAL(changed()));
1166         connect(maxAgeLE, SIGNAL(textEdited(QString)),
1167                 this, SIGNAL(changed()));
1168
1169         maxAgeLE->setValidator(new QDoubleValidator(maxAgeLE));
1170         //converterDefGB->setFocusProxy(convertersLW);
1171 }
1172
1173
1174 void PrefConverters::apply(LyXRC & rc) const
1175 {
1176         rc.use_converter_cache = cacheCB->isChecked();
1177         rc.converter_cache_maxage = int(maxAgeLE->text().toDouble() * 86400.0);
1178 }
1179
1180
1181 void PrefConverters::update(LyXRC const & rc)
1182 {
1183         cacheCB->setChecked(rc.use_converter_cache);
1184         QString max_age;
1185         max_age.setNum(double(rc.converter_cache_maxage) / 86400.0, 'g', 6);
1186         maxAgeLE->setText(max_age);
1187         updateGui();
1188 }
1189
1190
1191 void PrefConverters::updateGui()
1192 {
1193         form_->formats().sort();
1194         form_->converters().update(form_->formats());
1195         // save current selection
1196         QString current = converterFromCO->currentText()
1197                 + " -> " + converterToCO->currentText();
1198
1199         converterFromCO->clear();
1200         converterToCO->clear();
1201
1202         Formats::const_iterator cit = form_->formats().begin();
1203         Formats::const_iterator end = form_->formats().end();
1204         for (; cit != end; ++cit) {
1205                 converterFromCO->addItem(qt_(cit->prettyname()));
1206                 converterToCO->addItem(qt_(cit->prettyname()));
1207         }
1208
1209         // currentRowChanged(int) is also triggered when updating the listwidget
1210         // block signals to avoid unnecessary calls to switch_converter()
1211         convertersLW->blockSignals(true);
1212         convertersLW->clear();
1213
1214         Converters::const_iterator ccit = form_->converters().begin();
1215         Converters::const_iterator cend = form_->converters().end();
1216         for (; ccit != cend; ++ccit) {
1217                 QString const name =
1218                         qt_(ccit->From->prettyname()) + " -> " + qt_(ccit->To->prettyname());
1219                 int type = form_->converters().getNumber(ccit->From->name(), ccit->To->name());
1220                 new QListWidgetItem(name, convertersLW, type);
1221         }
1222         convertersLW->sortItems(Qt::AscendingOrder);
1223         convertersLW->blockSignals(false);
1224
1225         // restore selection
1226         if (!current.isEmpty()) {
1227                 QList<QListWidgetItem *> const item =
1228                         convertersLW->findItems(current, Qt::MatchExactly);
1229                 if (!item.isEmpty())
1230                         convertersLW->setCurrentItem(item.at(0));
1231         }
1232
1233         // select first element if restoring failed
1234         if (convertersLW->currentRow() == -1)
1235                 convertersLW->setCurrentRow(0);
1236
1237         updateButtons();
1238 }
1239
1240
1241 void PrefConverters::switch_converter()
1242 {
1243         int const cnr = convertersLW->currentItem()->type();
1244         Converter const & c(form_->converters().get(cnr));
1245         converterFromCO->setCurrentIndex(form_->formats().getNumber(c.from));
1246         converterToCO->setCurrentIndex(form_->formats().getNumber(c.to));
1247         converterED->setText(toqstr(c.command));
1248         converterFlagED->setText(toqstr(c.flags));
1249
1250         updateButtons();
1251 }
1252
1253
1254 void PrefConverters::converter_changed()
1255 {
1256         updateButtons();
1257 }
1258
1259
1260 void PrefConverters::updateButtons()
1261 {
1262         Format const & from = form_->formats().get(converterFromCO->currentIndex());
1263         Format const & to = form_->formats().get(converterToCO->currentIndex());
1264         int const sel = form_->converters().getNumber(from.name(), to.name());
1265         bool const known = sel >= 0;
1266         bool const valid = !(converterED->text().isEmpty()
1267                 || from.name() == to.name());
1268
1269         int const cnr = convertersLW->currentItem()->type();
1270         Converter const & c = form_->converters().get(cnr);
1271         string const old_command = c.command;
1272         string const old_flag = c.flags;
1273         string const new_command = fromqstr(converterED->text());
1274         string const new_flag = fromqstr(converterFlagED->text());
1275
1276         bool modified = (old_command != new_command || old_flag != new_flag);
1277
1278         converterModifyPB->setEnabled(valid && known && modified);
1279         converterNewPB->setEnabled(valid && !known);
1280         converterRemovePB->setEnabled(known);
1281
1282         maxAgeLE->setEnabled(cacheCB->isChecked());
1283         maxAgeLA->setEnabled(cacheCB->isChecked());
1284 }
1285
1286
1287 // FIXME: user must
1288 // specify unique from/to or it doesn't appear. This is really bad UI
1289 // this is why we can use the same function for both new and modify
1290 void PrefConverters::update_converter()
1291 {
1292         Format const & from = form_->formats().get(converterFromCO->currentIndex());
1293         Format const & to = form_->formats().get(converterToCO->currentIndex());
1294         string const flags = fromqstr(converterFlagED->text());
1295         string const command = fromqstr(converterED->text());
1296
1297         Converter const * old =
1298                 form_->converters().getConverter(from.name(), to.name());
1299         form_->converters().add(from.name(), to.name(), command, flags);
1300
1301         if (!old)
1302                 form_->converters().updateLast(form_->formats());
1303
1304         updateGui();
1305
1306         // Remove all files created by this converter from the cache, since
1307         // the modified converter might create different files.
1308         ConverterCache::get().remove_all(from.name(), to.name());
1309 }
1310
1311
1312 void PrefConverters::remove_converter()
1313 {
1314         Format const & from = form_->formats().get(converterFromCO->currentIndex());
1315         Format const & to = form_->formats().get(converterToCO->currentIndex());
1316         form_->converters().erase(from.name(), to.name());
1317
1318         updateGui();
1319
1320         // Remove all files created by this converter from the cache, since
1321         // a possible new converter might create different files.
1322         ConverterCache::get().remove_all(from.name(), to.name());
1323 }
1324
1325
1326 void PrefConverters::on_cacheCB_stateChanged(int state)
1327 {
1328         maxAgeLE->setEnabled(state == Qt::Checked);
1329         maxAgeLA->setEnabled(state == Qt::Checked);
1330         changed();
1331 }
1332
1333
1334 /////////////////////////////////////////////////////////////////////
1335 //
1336 // FormatValidator
1337 //
1338 /////////////////////////////////////////////////////////////////////
1339
1340 class FormatValidator : public QValidator
1341 {
1342 public:
1343         FormatValidator(QWidget *, Formats const & f);
1344         void fixup(QString & input) const;
1345         QValidator::State validate(QString & input, int & pos) const;
1346 private:
1347         virtual QString toString(Format const & format) const = 0;
1348         int nr() const;
1349         Formats const & formats_;
1350 };
1351
1352
1353 FormatValidator::FormatValidator(QWidget * parent, Formats const & f) 
1354         : QValidator(parent), formats_(f)
1355 {
1356 }
1357
1358
1359 void FormatValidator::fixup(QString & input) const
1360 {
1361         Formats::const_iterator cit = formats_.begin();
1362         Formats::const_iterator end = formats_.end();
1363         for (; cit != end; ++cit) {
1364                 QString const name = toString(*cit);
1365                 if (distance(formats_.begin(), cit) == nr()) {
1366                         input = name;
1367                         return;
1368                 }
1369         }
1370 }
1371
1372
1373 QValidator::State FormatValidator::validate(QString & input, int & /*pos*/) const
1374 {
1375         Formats::const_iterator cit = formats_.begin();
1376         Formats::const_iterator end = formats_.end();
1377         bool unknown = true;
1378         for (; unknown && cit != end; ++cit) {
1379                 QString const name = toString(*cit);
1380                 if (distance(formats_.begin(), cit) != nr())
1381                         unknown = name != input;
1382         }
1383
1384         if (unknown && !input.isEmpty()) 
1385                 return QValidator::Acceptable;
1386         else
1387                 return QValidator::Intermediate;
1388 }
1389
1390
1391 int FormatValidator::nr() const
1392 {
1393         QComboBox * p = qobject_cast<QComboBox *>(parent());
1394         return p->itemData(p->currentIndex()).toInt();
1395 }
1396
1397
1398 /////////////////////////////////////////////////////////////////////
1399 //
1400 // FormatNameValidator
1401 //
1402 /////////////////////////////////////////////////////////////////////
1403
1404 class FormatNameValidator : public FormatValidator
1405 {
1406 public:
1407         FormatNameValidator(QWidget * parent, Formats const & f)
1408                 : FormatValidator(parent, f)
1409         {}
1410 private:
1411         QString toString(Format const & format) const
1412         {
1413                 return toqstr(format.name());
1414         }
1415 };
1416
1417
1418 /////////////////////////////////////////////////////////////////////
1419 //
1420 // FormatPrettynameValidator
1421 //
1422 /////////////////////////////////////////////////////////////////////
1423
1424 class FormatPrettynameValidator : public FormatValidator
1425 {
1426 public:
1427         FormatPrettynameValidator(QWidget * parent, Formats const & f)
1428                 : FormatValidator(parent, f)
1429         {}
1430 private:
1431         QString toString(Format const & format) const
1432         {
1433                 return qt_(format.prettyname());
1434         }
1435 };
1436
1437
1438 /////////////////////////////////////////////////////////////////////
1439 //
1440 // PrefFileformats
1441 //
1442 /////////////////////////////////////////////////////////////////////
1443
1444 PrefFileformats::PrefFileformats(GuiPreferences * form)
1445         : PrefModule(qt_(catFiles), qt_("File formats"), form)
1446 {
1447         setupUi(this);
1448         formatED->setValidator(new FormatNameValidator(formatsCB, form_->formats()));
1449         formatsCB->setValidator(new FormatPrettynameValidator(formatsCB, form_->formats()));
1450
1451         connect(documentCB, SIGNAL(clicked()),
1452                 this, SLOT(setFlags()));
1453         connect(vectorCB, SIGNAL(clicked()),
1454                 this, SLOT(setFlags()));
1455         connect(formatsCB->lineEdit(), SIGNAL(editingFinished()),
1456                 this, SLOT(updatePrettyname()));
1457         connect(formatsCB->lineEdit(), SIGNAL(textEdited(QString)),
1458                 this, SIGNAL(changed()));
1459 }
1460
1461
1462 namespace {
1463
1464 string const l10n_shortcut(string const prettyname, string const shortcut)
1465 {
1466         if (shortcut.empty())
1467                 return string();
1468
1469         string l10n_format =
1470                 to_utf8(_(prettyname + '|' + shortcut));
1471         return split(l10n_format, '|');
1472 }
1473
1474 }; // namespace anon
1475
1476
1477 void PrefFileformats::apply(LyXRC & /*rc*/) const
1478 {
1479 }
1480
1481
1482 void PrefFileformats::update(LyXRC const & /*rc*/)
1483 {
1484         updateView();
1485 }
1486
1487
1488 void PrefFileformats::updateView()
1489 {
1490         QString const current = formatsCB->currentText();
1491
1492         // update combobox with formats
1493         formatsCB->blockSignals(true);
1494         formatsCB->clear();
1495         form_->formats().sort();
1496         Formats::const_iterator cit = form_->formats().begin();
1497         Formats::const_iterator end = form_->formats().end();
1498         for (; cit != end; ++cit)
1499                 formatsCB->addItem(qt_(cit->prettyname()),
1500                                    QVariant(form_->formats().getNumber(cit->name())));
1501
1502         // restore selection
1503         int const item = formatsCB->findText(current, Qt::MatchExactly);
1504         formatsCB->setCurrentIndex(item < 0 ? 0 : item);
1505         on_formatsCB_currentIndexChanged(item < 0 ? 0 : item);
1506         formatsCB->blockSignals(false);
1507 }
1508
1509
1510 void PrefFileformats::on_formatsCB_currentIndexChanged(int i)
1511 {
1512         int const nr = formatsCB->itemData(i).toInt();
1513         Format const f = form_->formats().get(nr);
1514
1515         formatED->setText(toqstr(f.name()));
1516         copierED->setText(toqstr(form_->movers().command(f.name())));
1517         extensionED->setText(toqstr(f.extension()));
1518         shortcutED->setText(
1519                 toqstr(l10n_shortcut(f.prettyname(), f.shortcut())));
1520         viewerED->setText(toqstr(f.viewer()));
1521         editorED->setText(toqstr(f.editor()));
1522         documentCB->setChecked((f.documentFormat()));
1523         vectorCB->setChecked((f.vectorFormat()));
1524 }
1525
1526
1527 void PrefFileformats::setFlags()
1528 {
1529         int flags = Format::none;
1530         if (documentCB->isChecked())
1531                 flags |= Format::document;
1532         if (vectorCB->isChecked())
1533                 flags |= Format::vector;
1534         currentFormat().setFlags(flags);
1535         changed();
1536 }
1537
1538
1539 void PrefFileformats::on_copierED_textEdited(const QString & s)
1540 {
1541         string const fmt = fromqstr(formatED->text());
1542         form_->movers().set(fmt, fromqstr(s));
1543         changed();
1544 }
1545
1546
1547 void PrefFileformats::on_extensionED_textEdited(const QString & s)
1548 {
1549         currentFormat().setExtension(fromqstr(s));
1550         changed();
1551 }
1552
1553 void PrefFileformats::on_viewerED_textEdited(const QString & s)
1554 {
1555         currentFormat().setViewer(fromqstr(s));
1556         changed();
1557 }
1558
1559
1560 void PrefFileformats::on_editorED_textEdited(const QString & s)
1561 {
1562         currentFormat().setEditor(fromqstr(s));
1563         changed();
1564 }
1565
1566
1567 void PrefFileformats::on_shortcutED_textEdited(const QString & s)
1568 {
1569         string const new_shortcut = fromqstr(s);
1570         if (new_shortcut == l10n_shortcut(currentFormat().prettyname(),
1571                                           currentFormat().shortcut()))
1572                 return;
1573         currentFormat().setShortcut(new_shortcut);
1574         changed();
1575 }
1576
1577
1578 void PrefFileformats::on_formatED_editingFinished()
1579 {
1580         string const newname = fromqstr(formatED->displayText());
1581         if (newname == currentFormat().name())
1582                 return;
1583
1584         currentFormat().setName(newname);
1585         changed();
1586 }
1587
1588
1589 void PrefFileformats::on_formatED_textChanged(const QString &)
1590 {
1591         QString t = formatED->text();
1592         int p = 0;
1593         bool valid = formatED->validator()->validate(t, p) == QValidator::Acceptable;
1594         setValid(formatLA, valid);
1595 }
1596
1597
1598 void PrefFileformats::on_formatsCB_editTextChanged(const QString &)
1599 {
1600         QString t = formatsCB->currentText();
1601         int p = 0;
1602         bool valid = formatsCB->validator()->validate(t, p) == QValidator::Acceptable;
1603         setValid(formatsLA, valid);
1604 }
1605
1606
1607 void PrefFileformats::updatePrettyname()
1608 {
1609         QString const newname = formatsCB->currentText();
1610         if (newname == qt_(currentFormat().prettyname()))
1611                 return;
1612
1613         currentFormat().setPrettyname(fromqstr(newname));
1614         formatsChanged();
1615         updateView();
1616         changed();
1617 }
1618
1619
1620 Format & PrefFileformats::currentFormat()
1621 {
1622         int const i = formatsCB->currentIndex();
1623         int const nr = formatsCB->itemData(i).toInt();
1624         return form_->formats().get(nr);
1625 }
1626
1627
1628 void PrefFileformats::on_formatNewPB_clicked()
1629 {
1630         form_->formats().add("", "", "", "", "", "", Format::none);
1631         updateView();
1632         formatsCB->setCurrentIndex(0);
1633         formatsCB->setFocus(Qt::OtherFocusReason);
1634 }
1635
1636
1637 void PrefFileformats::on_formatRemovePB_clicked()
1638 {
1639         int const i = formatsCB->currentIndex();
1640         int const nr = formatsCB->itemData(i).toInt();
1641         string const current_text = form_->formats().get(nr).name();
1642         if (form_->converters().formatIsUsed(current_text)) {
1643                 Alert::error(_("Format in use"),
1644                              _("Cannot remove a Format used by a Converter. "
1645                                             "Remove the converter first."));
1646                 return;
1647         }
1648
1649         form_->formats().erase(current_text);
1650         formatsChanged();
1651         updateView();
1652         on_formatsCB_editTextChanged(formatsCB->currentText());
1653         changed();
1654 }
1655
1656
1657 /////////////////////////////////////////////////////////////////////
1658 //
1659 // PrefLanguage
1660 //
1661 /////////////////////////////////////////////////////////////////////
1662
1663 PrefLanguage::PrefLanguage(GuiPreferences * form)
1664         : PrefModule(qt_(catLanguage), qt_("Language"), form)
1665 {
1666         setupUi(this);
1667
1668         connect(rtlGB, SIGNAL(clicked()),
1669                 this, SIGNAL(changed()));
1670         connect(visualCursorRB, SIGNAL(clicked()),
1671                 this, SIGNAL(changed()));
1672         connect(logicalCursorRB, SIGNAL(clicked()),
1673                 this, SIGNAL(changed()));
1674         connect(markForeignCB, SIGNAL(clicked()),
1675                 this, SIGNAL(changed()));
1676         connect(autoBeginCB, SIGNAL(clicked()),
1677                 this, SIGNAL(changed()));
1678         connect(autoEndCB, SIGNAL(clicked()),
1679                 this, SIGNAL(changed()));
1680         connect(useBabelCB, SIGNAL(clicked()),
1681                 this, SIGNAL(changed()));
1682         connect(globalCB, SIGNAL(clicked()),
1683                 this, SIGNAL(changed()));
1684         connect(languagePackageED, SIGNAL(textChanged(QString)),
1685                 this, SIGNAL(changed()));
1686         connect(startCommandED, SIGNAL(textChanged(QString)),
1687                 this, SIGNAL(changed()));
1688         connect(endCommandED, SIGNAL(textChanged(QString)),
1689                 this, SIGNAL(changed()));
1690         connect(defaultLanguageCO, SIGNAL(activated(int)),
1691                 this, SIGNAL(changed()));
1692         connect(uiLanguageCO, SIGNAL(activated(int)),
1693                 this, SIGNAL(changed()));
1694
1695         defaultLanguageCO->clear();
1696         uiLanguageCO->clear();
1697
1698         QAbstractItemModel * language_model = guiApp->languageModel();
1699         // FIXME: it would be nice if sorting was enabled/disabled via a checkbox.
1700         language_model->sort(0);
1701         defaultLanguageCO->setModel(language_model);
1702
1703         // FIXME: This is wrong, we need filter this list based on the available
1704         // translation.
1705         uiLanguageCO->blockSignals(true);
1706         uiLanguageCO->addItem(qt_("Default"), toqstr("auto"));
1707         for (int i = 0; i != language_model->rowCount(); ++i) {
1708                 QModelIndex index = language_model->index(i, 0);
1709                 uiLanguageCO->addItem(index.data(Qt::DisplayRole).toString(),
1710                         index.data(Qt::UserRole).toString());
1711         }
1712         uiLanguageCO->blockSignals(false);
1713 }
1714
1715
1716 void PrefLanguage::on_uiLanguageCO_currentIndexChanged(int)
1717 {
1718          QMessageBox::information(this, qt_("LyX needs to be restarted!"),
1719                  qt_("The change of user interface language will be fully "
1720                  "effective only after a restart."));
1721 }
1722
1723
1724 void PrefLanguage::apply(LyXRC & rc) const
1725 {
1726         // FIXME: remove rtl_support bool
1727         rc.rtl_support = rtlGB->isChecked();
1728         rc.visual_cursor = rtlGB->isChecked() && visualCursorRB->isChecked();
1729         rc.mark_foreign_language = markForeignCB->isChecked();
1730         rc.language_auto_begin = autoBeginCB->isChecked();
1731         rc.language_auto_end = autoEndCB->isChecked();
1732         rc.language_use_babel = useBabelCB->isChecked();
1733         rc.language_global_options = globalCB->isChecked();
1734         rc.language_package = fromqstr(languagePackageED->text());
1735         rc.language_command_begin = fromqstr(startCommandED->text());
1736         rc.language_command_end = fromqstr(endCommandED->text());
1737         rc.default_language = fromqstr(
1738                 defaultLanguageCO->itemData(defaultLanguageCO->currentIndex()).toString());
1739         rc.gui_language = fromqstr(
1740                 uiLanguageCO->itemData(uiLanguageCO->currentIndex()).toString());
1741 }
1742
1743
1744 void PrefLanguage::update(LyXRC const & rc)
1745 {
1746         // FIXME: remove rtl_support bool
1747         rtlGB->setChecked(rc.rtl_support);
1748         if (rc.visual_cursor)
1749                 visualCursorRB->setChecked(true);
1750         else
1751                 logicalCursorRB->setChecked(true);
1752         markForeignCB->setChecked(rc.mark_foreign_language);
1753         autoBeginCB->setChecked(rc.language_auto_begin);
1754         autoEndCB->setChecked(rc.language_auto_end);
1755         useBabelCB->setChecked(rc.language_use_babel);
1756         globalCB->setChecked(rc.language_global_options);
1757         languagePackageED->setText(toqstr(rc.language_package));
1758         startCommandED->setText(toqstr(rc.language_command_begin));
1759         endCommandED->setText(toqstr(rc.language_command_end));
1760
1761         int pos = defaultLanguageCO->findData(toqstr(rc.default_language));
1762         defaultLanguageCO->setCurrentIndex(pos);
1763         pos = uiLanguageCO->findData(toqstr(rc.gui_language));
1764         uiLanguageCO->blockSignals(true);
1765         uiLanguageCO->setCurrentIndex(pos);
1766         uiLanguageCO->blockSignals(false);
1767 }
1768
1769
1770 /////////////////////////////////////////////////////////////////////
1771 //
1772 // PrefPrinter
1773 //
1774 /////////////////////////////////////////////////////////////////////
1775
1776 PrefPrinter::PrefPrinter(GuiPreferences * form)
1777         : PrefModule(qt_(catOutput), qt_("Printer"), form)
1778 {
1779         setupUi(this);
1780
1781         connect(printerAdaptCB, SIGNAL(clicked()),
1782                 this, SIGNAL(changed()));
1783         connect(printerCommandED, SIGNAL(textChanged(QString)),
1784                 this, SIGNAL(changed()));
1785         connect(printerNameED, SIGNAL(textChanged(QString)),
1786                 this, SIGNAL(changed()));
1787         connect(printerPageRangeED, SIGNAL(textChanged(QString)),
1788                 this, SIGNAL(changed()));
1789         connect(printerCopiesED, SIGNAL(textChanged(QString)),
1790                 this, SIGNAL(changed()));
1791         connect(printerReverseED, SIGNAL(textChanged(QString)),
1792                 this, SIGNAL(changed()));
1793         connect(printerToPrinterED, SIGNAL(textChanged(QString)),
1794                 this, SIGNAL(changed()));
1795         connect(printerExtensionED, SIGNAL(textChanged(QString)),
1796                 this, SIGNAL(changed()));
1797         connect(printerSpoolCommandED, SIGNAL(textChanged(QString)),
1798                 this, SIGNAL(changed()));
1799         connect(printerPaperTypeED, SIGNAL(textChanged(QString)),
1800                 this, SIGNAL(changed()));
1801         connect(printerEvenED, SIGNAL(textChanged(QString)),
1802                 this, SIGNAL(changed()));
1803         connect(printerOddED, SIGNAL(textChanged(QString)),
1804                 this, SIGNAL(changed()));
1805         connect(printerCollatedED, SIGNAL(textChanged(QString)),
1806                 this, SIGNAL(changed()));
1807         connect(printerLandscapeED, SIGNAL(textChanged(QString)),
1808                 this, SIGNAL(changed()));
1809         connect(printerToFileED, SIGNAL(textChanged(QString)),
1810                 this, SIGNAL(changed()));
1811         connect(printerExtraED, SIGNAL(textChanged(QString)),
1812                 this, SIGNAL(changed()));
1813         connect(printerSpoolPrefixED, SIGNAL(textChanged(QString)),
1814                 this, SIGNAL(changed()));
1815         connect(printerPaperSizeED, SIGNAL(textChanged(QString)),
1816                 this, SIGNAL(changed()));
1817 }
1818
1819
1820 void PrefPrinter::apply(LyXRC & rc) const
1821 {
1822         rc.print_adapt_output = printerAdaptCB->isChecked();
1823         rc.print_command = fromqstr(printerCommandED->text());
1824         rc.printer = fromqstr(printerNameED->text());
1825
1826         rc.print_pagerange_flag = fromqstr(printerPageRangeED->text());
1827         rc.print_copies_flag = fromqstr(printerCopiesED->text());
1828         rc.print_reverse_flag = fromqstr(printerReverseED->text());
1829         rc.print_to_printer = fromqstr(printerToPrinterED->text());
1830         rc.print_file_extension = fromqstr(printerExtensionED->text());
1831         rc.print_spool_command = fromqstr(printerSpoolCommandED->text());
1832         rc.print_paper_flag = fromqstr(printerPaperTypeED->text());
1833         rc.print_evenpage_flag = fromqstr(printerEvenED->text());
1834         rc.print_oddpage_flag = fromqstr(printerOddED->text());
1835         rc.print_collcopies_flag = fromqstr(printerCollatedED->text());
1836         rc.print_landscape_flag = fromqstr(printerLandscapeED->text());
1837         rc.print_to_file = internal_path(fromqstr(printerToFileED->text()));
1838         rc.print_extra_options = fromqstr(printerExtraED->text());
1839         rc.print_spool_printerprefix = fromqstr(printerSpoolPrefixED->text());
1840         rc.print_paper_dimension_flag = fromqstr(printerPaperSizeED->text());
1841 }
1842
1843
1844 void PrefPrinter::update(LyXRC const & rc)
1845 {
1846         printerAdaptCB->setChecked(rc.print_adapt_output);
1847         printerCommandED->setText(toqstr(rc.print_command));
1848         printerNameED->setText(toqstr(rc.printer));
1849
1850         printerPageRangeED->setText(toqstr(rc.print_pagerange_flag));
1851         printerCopiesED->setText(toqstr(rc.print_copies_flag));
1852         printerReverseED->setText(toqstr(rc.print_reverse_flag));
1853         printerToPrinterED->setText(toqstr(rc.print_to_printer));
1854         printerExtensionED->setText(toqstr(rc.print_file_extension));
1855         printerSpoolCommandED->setText(toqstr(rc.print_spool_command));
1856         printerPaperTypeED->setText(toqstr(rc.print_paper_flag));
1857         printerEvenED->setText(toqstr(rc.print_evenpage_flag));
1858         printerOddED->setText(toqstr(rc.print_oddpage_flag));
1859         printerCollatedED->setText(toqstr(rc.print_collcopies_flag));
1860         printerLandscapeED->setText(toqstr(rc.print_landscape_flag));
1861         printerToFileED->setText(toqstr(external_path(rc.print_to_file)));
1862         printerExtraED->setText(toqstr(rc.print_extra_options));
1863         printerSpoolPrefixED->setText(toqstr(rc.print_spool_printerprefix));
1864         printerPaperSizeED->setText(toqstr(rc.print_paper_dimension_flag));
1865 }
1866
1867
1868 /////////////////////////////////////////////////////////////////////
1869 //
1870 // PrefUserInterface
1871 //
1872 /////////////////////////////////////////////////////////////////////
1873
1874 PrefUserInterface::PrefUserInterface(GuiPreferences * form)
1875         : PrefModule(qt_(catLookAndFeel), qt_("User interface"), form)
1876 {
1877         setupUi(this);
1878
1879         connect(autoSaveCB, SIGNAL(toggled(bool)),
1880                 autoSaveSB, SLOT(setEnabled(bool)));
1881         connect(autoSaveCB, SIGNAL(toggled(bool)),
1882                 TextLabel1, SLOT(setEnabled(bool)));
1883         connect(openDocumentsInTabsCB, SIGNAL(clicked()),
1884                 this, SIGNAL(changed()));
1885         connect(uiFilePB, SIGNAL(clicked()),
1886                 this, SLOT(select_ui()));
1887         connect(uiFileED, SIGNAL(textChanged(QString)),
1888                 this, SIGNAL(changed()));
1889         connect(restoreCursorCB, SIGNAL(clicked()),
1890                 this, SIGNAL(changed()));
1891         connect(loadSessionCB, SIGNAL(clicked()),
1892                 this, SIGNAL(changed()));
1893         connect(allowGeometrySessionCB, SIGNAL(clicked()),
1894                 this, SIGNAL(changed()));
1895         connect(autoSaveSB, SIGNAL(valueChanged(int)),
1896                 this, SIGNAL(changed()));
1897         connect(autoSaveCB, SIGNAL(clicked()),
1898                 this, SIGNAL(changed()));
1899         connect(lastfilesSB, SIGNAL(valueChanged(int)),
1900                 this, SIGNAL(changed()));
1901         connect(tooltipCB, SIGNAL(toggled(bool)),
1902                 this, SIGNAL(changed()));
1903         lastfilesSB->setMaximum(maxlastfiles);
1904 }
1905
1906
1907 void PrefUserInterface::apply(LyXRC & rc) const
1908 {
1909         rc.ui_file = internal_path(fromqstr(uiFileED->text()));
1910         rc.use_lastfilepos = restoreCursorCB->isChecked();
1911         rc.load_session = loadSessionCB->isChecked();
1912         rc.allow_geometry_session = allowGeometrySessionCB->isChecked();
1913         rc.autosave = autoSaveSB->value() * 60;
1914         rc.make_backup = autoSaveCB->isChecked();
1915         rc.num_lastfiles = lastfilesSB->value();
1916         rc.use_tooltip = tooltipCB->isChecked();
1917         rc.open_buffers_in_tabs = openDocumentsInTabsCB->isChecked();
1918 }
1919
1920
1921 void PrefUserInterface::update(LyXRC const & rc)
1922 {
1923         uiFileED->setText(toqstr(external_path(rc.ui_file)));
1924         restoreCursorCB->setChecked(rc.use_lastfilepos);
1925         loadSessionCB->setChecked(rc.load_session);
1926         allowGeometrySessionCB->setChecked(rc.allow_geometry_session);
1927         // convert to minutes
1928         int mins(rc.autosave / 60);
1929         if (rc.autosave && !mins)
1930                 mins = 1;
1931         autoSaveSB->setValue(mins);
1932         autoSaveCB->setChecked(rc.make_backup);
1933         lastfilesSB->setValue(rc.num_lastfiles);
1934         tooltipCB->setChecked(rc.use_tooltip);
1935         openDocumentsInTabsCB->setChecked(rc.open_buffers_in_tabs);
1936 }
1937
1938
1939 void PrefUserInterface::select_ui()
1940 {
1941         QString file = form_->browseUI(internalPath(uiFileED->text()));
1942         if (!file.isEmpty())
1943                 uiFileED->setText(file);
1944 }
1945
1946
1947 /////////////////////////////////////////////////////////////////////
1948 //
1949 // PrefEdit
1950 //
1951 /////////////////////////////////////////////////////////////////////
1952
1953 PrefEdit::PrefEdit(GuiPreferences * form)
1954         : PrefModule(qt_(catEditing), qt_("Control"), form)
1955 {
1956         setupUi(this);
1957
1958         connect(cursorFollowsCB, SIGNAL(clicked()),
1959                 this, SIGNAL(changed()));
1960         connect(sortEnvironmentsCB, SIGNAL(clicked()),
1961                 this, SIGNAL(changed()));
1962         connect(groupEnvironmentsCB, SIGNAL(clicked()),
1963                 this, SIGNAL(changed()));
1964         connect(macroEditStyleCO, SIGNAL(activated(int)),
1965                 this, SIGNAL(changed()));
1966         connect(fullscreenLimitGB, SIGNAL(clicked()),
1967                 this, SIGNAL(changed()));
1968         connect(fullscreenWidthSB, SIGNAL(valueChanged(int)),
1969                 this, SIGNAL(changed()));
1970         connect(toggleTabbarCB, SIGNAL(toggled(bool)),
1971                 this, SIGNAL(changed()));
1972         connect(toggleScrollbarCB, SIGNAL(toggled(bool)),
1973                 this, SIGNAL(changed()));
1974         connect(toggleToolbarsCB, SIGNAL(toggled(bool)),
1975                 this, SIGNAL(changed()));
1976 }
1977
1978
1979 void PrefEdit::apply(LyXRC & rc) const
1980 {
1981         rc.cursor_follows_scrollbar = cursorFollowsCB->isChecked();
1982         rc.sort_layouts = sortEnvironmentsCB->isChecked();
1983         rc.group_layouts = groupEnvironmentsCB->isChecked();
1984         switch (macroEditStyleCO->currentIndex()) {
1985                 case 0: rc.macro_edit_style = LyXRC::MACRO_EDIT_INLINE_BOX; break;
1986                 case 1: rc.macro_edit_style = LyXRC::MACRO_EDIT_INLINE; break;
1987                 case 2: rc.macro_edit_style = LyXRC::MACRO_EDIT_LIST;   break;
1988         }
1989         rc.full_screen_toolbars = toggleToolbarsCB->isChecked();
1990         rc.full_screen_scrollbar = toggleScrollbarCB->isChecked();
1991         rc.full_screen_tabbar = toggleTabbarCB->isChecked();
1992         rc.full_screen_width = fullscreenWidthSB->value();
1993         rc.full_screen_limit = fullscreenLimitGB->isChecked();
1994 }
1995
1996
1997 void PrefEdit::update(LyXRC const & rc)
1998 {
1999         cursorFollowsCB->setChecked(rc.cursor_follows_scrollbar);
2000         sortEnvironmentsCB->setChecked(rc.sort_layouts);
2001         groupEnvironmentsCB->setChecked(rc.group_layouts);
2002         macroEditStyleCO->setCurrentIndex(rc.macro_edit_style);
2003         toggleScrollbarCB->setChecked(rc.full_screen_scrollbar);
2004         toggleToolbarsCB->setChecked(rc.full_screen_toolbars);
2005         toggleTabbarCB->setChecked(rc.full_screen_tabbar);
2006         fullscreenWidthSB->setValue(rc.full_screen_width);
2007         fullscreenLimitGB->setChecked(rc.full_screen_limit);
2008 }
2009
2010
2011 /////////////////////////////////////////////////////////////////////
2012 //
2013 // PrefShortcuts
2014 //
2015 /////////////////////////////////////////////////////////////////////
2016
2017
2018 GuiShortcutDialog::GuiShortcutDialog(QWidget * parent) : QDialog(parent)
2019 {
2020         Ui::shortcutUi::setupUi(this);
2021         QDialog::setModal(true);
2022 }
2023
2024
2025 PrefShortcuts::PrefShortcuts(GuiPreferences * form)
2026         : PrefModule(qt_(catEditing), qt_("Shortcuts"), form)
2027 {
2028         setupUi(this);
2029
2030         shortcutsTW->setColumnCount(2);
2031         shortcutsTW->headerItem()->setText(0, qt_("Function"));
2032         shortcutsTW->headerItem()->setText(1, qt_("Shortcut"));
2033         shortcutsTW->setSortingEnabled(true);
2034         // Multi-selection can be annoying.
2035         // shortcutsTW->setSelectionMode(QAbstractItemView::MultiSelection);
2036
2037         connect(bindFilePB, SIGNAL(clicked()),
2038                 this, SLOT(select_bind()));
2039         connect(bindFileED, SIGNAL(textChanged(QString)),
2040                 this, SIGNAL(changed()));
2041         connect(removePB, SIGNAL(clicked()), 
2042                 this, SIGNAL(changed()));
2043         
2044         shortcut_ = new GuiShortcutDialog(this);
2045         shortcut_bc_.setPolicy(ButtonPolicy::OkCancelPolicy);
2046         shortcut_bc_.setOK(shortcut_->okPB);
2047         shortcut_bc_.setCancel(shortcut_->cancelPB);
2048
2049         connect(shortcut_->okPB, SIGNAL(clicked()),
2050                 shortcut_, SLOT(accept()));
2051         connect(shortcut_->okPB, SIGNAL(clicked()), 
2052                 this, SIGNAL(changed()));
2053         connect(shortcut_->cancelPB, SIGNAL(clicked()), 
2054                 shortcut_, SLOT(reject()));
2055         connect(shortcut_->clearPB, SIGNAL(clicked()),
2056                 this, SLOT(shortcut_clearPB_pressed()));
2057         connect(shortcut_->okPB, SIGNAL(clicked()), 
2058                 this, SLOT(shortcut_okPB_pressed()));
2059 }
2060
2061
2062 void PrefShortcuts::apply(LyXRC & rc) const
2063 {
2064         rc.bind_file = internal_path(fromqstr(bindFileED->text()));
2065         // write user_bind and user_unbind to .lyx/bind/user.bind
2066         FileName bind_dir(addPath(package().user_support().absFilename(), "bind"));
2067         if (!bind_dir.exists() && !bind_dir.createDirectory(0777)) {
2068                 lyxerr << "LyX could not create the user bind directory '"
2069                        << bind_dir << "'. All user-defined key bindings will be lost." << endl;
2070                 return;
2071         }
2072         if (!bind_dir.isDirWritable()) {
2073                 lyxerr << "LyX could not write to the user bind directory '"
2074                        << bind_dir << "'. All user-defined key bindings will be lost." << endl;
2075                 return;
2076         }
2077         FileName user_bind_file(bind_dir.absFilename() + "/user.bind");
2078         user_bind_.write(user_bind_file.toFilesystemEncoding(), false, false);
2079         user_unbind_.write(user_bind_file.toFilesystemEncoding(), true, true);
2080         // immediately apply the keybindings. Why this is not done before?
2081         // The good thing is that the menus are updated automatically.
2082         theTopLevelKeymap().clear();
2083         theTopLevelKeymap().read("site");
2084         theTopLevelKeymap().read(rc.bind_file);
2085         theTopLevelKeymap().read("user");
2086 }
2087
2088
2089 void PrefShortcuts::update(LyXRC const & rc)
2090 {
2091         bindFileED->setText(toqstr(external_path(rc.bind_file)));
2092         //
2093         system_bind_.clear();
2094         user_bind_.clear();
2095         user_unbind_.clear();
2096         system_bind_.read(rc.bind_file);
2097         // \unbind in user.bind is added to user_unbind_
2098         user_bind_.read("user", &user_unbind_);
2099         updateShortcutsTW();
2100 }
2101
2102
2103 void PrefShortcuts::updateShortcutsTW()
2104 {
2105         shortcutsTW->clear();
2106
2107         editItem_ = new QTreeWidgetItem(shortcutsTW);
2108         editItem_->setText(0, qt_("Cursor, Mouse and Editing functions"));
2109         editItem_->setFlags(editItem_->flags() & ~Qt::ItemIsSelectable);
2110
2111         mathItem_ = new QTreeWidgetItem(shortcutsTW);
2112         mathItem_->setText(0, qt_("Mathematical Symbols"));
2113         mathItem_->setFlags(mathItem_->flags() & ~Qt::ItemIsSelectable);
2114         
2115         bufferItem_ = new QTreeWidgetItem(shortcutsTW);
2116         bufferItem_->setText(0, qt_("Document and Window"));
2117         bufferItem_->setFlags(bufferItem_->flags() & ~Qt::ItemIsSelectable);
2118         
2119         layoutItem_ = new QTreeWidgetItem(shortcutsTW);
2120         layoutItem_->setText(0, qt_("Font, Layouts and Textclasses"));
2121         layoutItem_->setFlags(layoutItem_->flags() & ~Qt::ItemIsSelectable);
2122
2123         systemItem_ = new QTreeWidgetItem(shortcutsTW);
2124         systemItem_->setText(0, qt_("System and Miscellaneous"));
2125         systemItem_->setFlags(systemItem_->flags() & ~Qt::ItemIsSelectable);
2126
2127         // listBindings(unbound=true) lists all bound and unbound lfuns
2128         // Items in this list is tagged by its source.
2129         KeyMap::BindingList bindinglist = system_bind_.listBindings(true, 
2130                 static_cast<int>(System));
2131         KeyMap::BindingList user_bindinglist = user_bind_.listBindings(false,
2132                 static_cast<int>(UserBind));
2133         KeyMap::BindingList user_unbindinglist = user_unbind_.listBindings(false,
2134                 static_cast<int>(UserUnbind));
2135         bindinglist.insert(bindinglist.end(), user_bindinglist.begin(),
2136                         user_bindinglist.end());
2137         bindinglist.insert(bindinglist.end(), user_unbindinglist.begin(),
2138                         user_unbindinglist.end());
2139
2140         KeyMap::BindingList::const_iterator it = bindinglist.begin();
2141         KeyMap::BindingList::const_iterator it_end = bindinglist.end();
2142         for (; it != it_end; ++it)
2143                 insertShortcutItem(it->request, it->sequence, ItemType(it->tag));
2144
2145         shortcutsTW->sortItems(0, Qt::AscendingOrder);
2146         QList<QTreeWidgetItem*> items = shortcutsTW->selectedItems();
2147         removePB->setEnabled(!items.isEmpty() && !items[0]->text(1).isEmpty());
2148         modifyPB->setEnabled(!items.isEmpty());
2149
2150         shortcutsTW->resizeColumnToContents(0);
2151 }
2152
2153
2154 void PrefShortcuts::setItemType(QTreeWidgetItem * item, ItemType tag)
2155 {
2156         item->setData(0, Qt::UserRole, QVariant(tag));
2157         QFont font;
2158
2159         switch (tag) {
2160         case System:
2161                 break;
2162         case UserBind:
2163                 font.setBold(true);
2164                 break;
2165         case UserUnbind:
2166                 font.setStrikeOut(true);
2167                 break;
2168         // this item is not displayed now.
2169         case UserExtraUnbind:
2170                 font.setStrikeOut(true);
2171                 break;
2172         }
2173
2174         item->setFont(1, font);
2175 }
2176
2177
2178 QTreeWidgetItem * PrefShortcuts::insertShortcutItem(FuncRequest const & lfun,
2179                 KeySequence const & seq, ItemType tag)
2180 {
2181         FuncCode action = lfun.action;
2182         string const action_name = lyxaction.getActionName(action);
2183         QString const lfun_name = toqstr(from_utf8(action_name) 
2184                         + ' ' + lfun.argument());
2185         QString const shortcut = toqstr(seq.print(KeySequence::ForGui));
2186         ItemType item_tag = tag;
2187
2188         QTreeWidgetItem * newItem = 0;
2189         // for unbind items, try to find an existing item in the system bind list
2190         if (tag == UserUnbind) {
2191                 QList<QTreeWidgetItem*> const items = shortcutsTW->findItems(lfun_name, 
2192                         Qt::MatchFlags(Qt::MatchExactly | Qt::MatchRecursive), 0);
2193                 for (int i = 0; i < items.size(); ++i) {
2194                         if (items[i]->text(1) == shortcut)
2195                                 newItem = items[i];
2196                                 break;
2197                         }
2198                 // if not found, this unbind item is UserExtraUnbind
2199                 // Such an item is not displayed to avoid confusion (what is 
2200                 // unmatched removed?).
2201                 if (!newItem) {
2202                         item_tag = UserExtraUnbind;
2203                         return 0;
2204                 }
2205         }
2206         if (!newItem) {
2207                 switch(lyxaction.getActionType(action)) {
2208                 case LyXAction::Hidden:
2209                         return 0;
2210                 case LyXAction::Edit:
2211                         newItem = new QTreeWidgetItem(editItem_);
2212                         break;
2213                 case LyXAction::Math:
2214                         newItem = new QTreeWidgetItem(mathItem_);
2215                         break;
2216                 case LyXAction::Buffer:
2217                         newItem = new QTreeWidgetItem(bufferItem_);
2218                         break;
2219                 case LyXAction::Layout:
2220                         newItem = new QTreeWidgetItem(layoutItem_);
2221                         break;
2222                 case LyXAction::System:
2223                         newItem = new QTreeWidgetItem(systemItem_);
2224                         break;
2225                 default:
2226                         // this should not happen
2227                         newItem = new QTreeWidgetItem(shortcutsTW);
2228                 }
2229         }
2230
2231         newItem->setText(0, lfun_name);
2232         newItem->setText(1, shortcut);
2233         // record BindFile representation to recover KeySequence when needed.
2234         newItem->setData(1, Qt::UserRole, toqstr(seq.print(KeySequence::BindFile)));
2235         setItemType(newItem, item_tag);
2236         return newItem;
2237 }
2238
2239
2240 void PrefShortcuts::on_shortcutsTW_itemSelectionChanged()
2241 {
2242         QList<QTreeWidgetItem*> items = shortcutsTW->selectedItems();
2243         removePB->setEnabled(!items.isEmpty() && !items[0]->text(1).isEmpty());
2244         modifyPB->setEnabled(!items.isEmpty());
2245         if (items.isEmpty())
2246                 return;
2247         
2248         ItemType tag = static_cast<ItemType>(items[0]->data(0, Qt::UserRole).toInt());
2249         if (tag == UserUnbind)
2250                 removePB->setText(qt_("Res&tore"));
2251         else
2252                 removePB->setText(qt_("Remo&ve"));
2253 }
2254
2255
2256 void PrefShortcuts::on_shortcutsTW_itemDoubleClicked()
2257 {
2258         modifyShortcut();
2259 }
2260
2261
2262 void PrefShortcuts::modifyShortcut()
2263 {
2264         QTreeWidgetItem * item = shortcutsTW->currentItem();
2265         if (item->flags() & Qt::ItemIsSelectable) {
2266                 shortcut_->lfunLE->setText(item->text(0));
2267                 shortcut_->shortcutLE->setText(item->text(1));
2268                 shortcut_->shortcutLE->setFocus();
2269                 shortcut_->exec();
2270         }
2271 }
2272
2273
2274 void PrefShortcuts::select_bind()
2275 {
2276         QString file = form_->browsebind(internalPath(bindFileED->text()));
2277         if (!file.isEmpty()) {
2278                 bindFileED->setText(file);
2279                 system_bind_ = KeyMap();
2280                 system_bind_.read(fromqstr(file));
2281                 updateShortcutsTW();
2282         }
2283 }
2284
2285
2286 void PrefShortcuts::on_modifyPB_pressed()
2287 {
2288         modifyShortcut();
2289 }
2290
2291
2292 void PrefShortcuts::on_newPB_pressed()
2293 {
2294         shortcut_->lfunLE->clear();
2295         shortcut_->shortcutLE->reset();
2296         shortcut_->exec();
2297 }
2298
2299
2300 void PrefShortcuts::on_removePB_pressed()
2301 {
2302         // it seems that only one item can be selected, but I am
2303         // removing all selected items anyway.
2304         QList<QTreeWidgetItem*> items = shortcutsTW->selectedItems();
2305         for (int i = 0; i < items.size(); ++i) {
2306                 string shortcut = fromqstr(items[i]->data(1, Qt::UserRole).toString());
2307                 string lfun = fromqstr(items[i]->text(0));
2308                 FuncRequest func = lyxaction.lookupFunc(lfun);
2309                 ItemType tag = static_cast<ItemType>(items[i]->data(0, Qt::UserRole).toInt());
2310                 
2311                 switch (tag) {
2312                 case System: {
2313                         // for system bind, we do not touch the item
2314                         // but add an user unbind item
2315                         user_unbind_.bind(shortcut, func);
2316                         setItemType(items[i], UserUnbind);
2317                         removePB->setText(qt_("Res&tore"));
2318                         break;
2319                 }
2320                 case UserBind: {
2321                         // for user_bind, we remove this bind
2322                         QTreeWidgetItem * parent = items[i]->parent();
2323                         int itemIdx = parent->indexOfChild(items[i]);
2324                         parent->takeChild(itemIdx);
2325                         if (itemIdx > 0)
2326                                 shortcutsTW->scrollToItem(parent->child(itemIdx - 1));
2327                         else
2328                                 shortcutsTW->scrollToItem(parent);
2329                         user_bind_.unbind(shortcut, func);
2330                         break;
2331                 }
2332                 case UserUnbind: {
2333                         // for user_unbind, we remove the unbind, and the item
2334                         // become System again.
2335                         user_unbind_.unbind(shortcut, func);
2336                         setItemType(items[i], System);
2337                         removePB->setText(qt_("Remo&ve"));
2338                         break;
2339                 }
2340                 case UserExtraUnbind: {
2341                         // for user unbind that is not in system bind file,
2342                         // remove this unbind file
2343                         QTreeWidgetItem * parent = items[i]->parent();
2344                         parent->takeChild(parent->indexOfChild(items[i]));
2345                         user_unbind_.unbind(shortcut, func);
2346                 }
2347                 }
2348         }
2349 }
2350
2351
2352 void PrefShortcuts::on_searchLE_textEdited()
2353 {
2354         if (searchLE->text().isEmpty()) {
2355                 // show all hidden items
2356                 QTreeWidgetItemIterator it(shortcutsTW, QTreeWidgetItemIterator::Hidden);
2357                 while (*it)
2358                         shortcutsTW->setItemHidden(*it++, false);
2359                 return;
2360         }
2361         // search both columns
2362         QList<QTreeWidgetItem *> matched = shortcutsTW->findItems(searchLE->text(),
2363                 Qt::MatchFlags(Qt::MatchContains | Qt::MatchRecursive), 0);
2364         matched += shortcutsTW->findItems(searchLE->text(),
2365                 Qt::MatchFlags(Qt::MatchContains | Qt::MatchRecursive), 1);
2366         
2367         // hide everyone (to avoid searching in matched QList repeatedly
2368         QTreeWidgetItemIterator it(shortcutsTW, QTreeWidgetItemIterator::Selectable);
2369         while (*it)
2370                 shortcutsTW->setItemHidden(*it++, true);
2371         // show matched items
2372         for (int i = 0; i < matched.size(); ++i) {
2373                 shortcutsTW->setItemHidden(matched[i], false);
2374         shortcutsTW->setItemExpanded(matched[i]->parent(), true);
2375         }
2376 }
2377
2378
2379 void PrefShortcuts::shortcut_okPB_pressed()
2380 {
2381         string lfun = fromqstr(shortcut_->lfunLE->text());
2382         FuncRequest func = lyxaction.lookupFunc(lfun);
2383
2384         if (func.action == LFUN_UNKNOWN_ACTION) {
2385                 Alert::error(_("Failed to create shortcut"),
2386                         _("Unknown or invalid LyX function"));
2387                 return;
2388         }
2389
2390         KeySequence k = shortcut_->shortcutLE->getKeySequence();
2391         if (k.length() == 0) {
2392                 Alert::error(_("Failed to create shortcut"),
2393                         _("Invalid or empty key sequence"));
2394                 return;
2395         }
2396
2397         // if both lfun and shortcut is valid
2398         if (user_bind_.hasBinding(k, func) || system_bind_.hasBinding(k, func)) {
2399                 Alert::error(_("Failed to create shortcut"),
2400                         _("Shortcut is already defined"));
2401                 return;
2402         }
2403                 
2404         QTreeWidgetItem * item = insertShortcutItem(func, k, UserBind);
2405         if (item) {
2406                 user_bind_.bind(&k, func);
2407                 shortcutsTW->sortItems(0, Qt::AscendingOrder);
2408                 shortcutsTW->setItemExpanded(item->parent(), true);
2409                 shortcutsTW->scrollToItem(item);
2410         } else {
2411                 Alert::error(_("Failed to create shortcut"),
2412                         _("Can not insert shortcut to the list"));
2413                 return;
2414         }
2415 }
2416
2417
2418 void PrefShortcuts::shortcut_clearPB_pressed()
2419 {
2420         shortcut_->shortcutLE->reset();
2421         shortcut_->shortcutLE->setFocus();
2422 }
2423
2424
2425 /////////////////////////////////////////////////////////////////////
2426 //
2427 // PrefIdentity
2428 //
2429 /////////////////////////////////////////////////////////////////////
2430
2431 PrefIdentity::PrefIdentity(GuiPreferences * form)
2432         : PrefModule(QString(), qt_("Identity"), form)
2433 {
2434         setupUi(this);
2435
2436         connect(nameED, SIGNAL(textChanged(QString)),
2437                 this, SIGNAL(changed()));
2438         connect(emailED, SIGNAL(textChanged(QString)),
2439                 this, SIGNAL(changed()));
2440 }
2441
2442
2443 void PrefIdentity::apply(LyXRC & rc) const
2444 {
2445         rc.user_name = fromqstr(nameED->text());
2446         rc.user_email = fromqstr(emailED->text());
2447 }
2448
2449
2450 void PrefIdentity::update(LyXRC const & rc)
2451 {
2452         nameED->setText(toqstr(rc.user_name));
2453         emailED->setText(toqstr(rc.user_email));
2454 }
2455
2456
2457
2458 /////////////////////////////////////////////////////////////////////
2459 //
2460 // GuiPreferences
2461 //
2462 /////////////////////////////////////////////////////////////////////
2463
2464 GuiPreferences::GuiPreferences(GuiView & lv)
2465         : GuiDialog(lv, "prefs", qt_("Preferences")), update_screen_font_(false)
2466 {
2467         setupUi(this);
2468
2469         QDialog::setModal(false);
2470
2471         connect(savePB, SIGNAL(clicked()), this, SLOT(slotOK()));
2472         connect(applyPB, SIGNAL(clicked()), this, SLOT(slotApply()));
2473         connect(closePB, SIGNAL(clicked()), this, SLOT(slotClose()));
2474         connect(restorePB, SIGNAL(clicked()), this, SLOT(slotRestore()));
2475
2476         addModule(new PrefUserInterface(this));
2477         addModule(new PrefEdit(this));
2478         addModule(new PrefShortcuts(this));
2479         addModule(new PrefScreenFonts(this));
2480         addModule(new PrefColors(this));
2481         addModule(new PrefDisplay(this));
2482         addModule(new PrefInput(this));
2483         addModule(new PrefCompletion(this));
2484
2485         addModule(new PrefPaths(this));
2486
2487         addModule(new PrefIdentity(this));
2488
2489         addModule(new PrefLanguage(this));
2490         addModule(new PrefSpellchecker(this));
2491
2492         addModule(new PrefPrinter(this));
2493         addModule(new PrefDate(this));
2494         addModule(new PrefPlaintext(this));
2495         addModule(new PrefLatex(this));
2496
2497         PrefConverters * converters = new PrefConverters(this);
2498         PrefFileformats * formats = new PrefFileformats(this);
2499         connect(formats, SIGNAL(formatsChanged()),
2500                         converters, SLOT(updateGui()));
2501         addModule(converters);
2502         addModule(formats);
2503
2504         prefsPS->setCurrentPanel(qt_("User interface"));
2505 // FIXME: hack to work around resizing bug in Qt >= 4.2
2506 // bug verified with Qt 4.2.{0-3} (JSpitzm)
2507 #if QT_VERSION >= 0x040200
2508         prefsPS->updateGeometry();
2509 #endif
2510
2511         bc().setPolicy(ButtonPolicy::PreferencesPolicy);
2512         bc().setOK(savePB);
2513         bc().setApply(applyPB);
2514         bc().setCancel(closePB);
2515         bc().setRestore(restorePB);
2516 }
2517
2518
2519 void GuiPreferences::addModule(PrefModule * module)
2520 {
2521         LASSERT(module, /**/);
2522         if (module->category().isEmpty())
2523                 prefsPS->addPanel(module, module->title());
2524         else
2525                 prefsPS->addPanel(module, module->title(), module->category());
2526         connect(module, SIGNAL(changed()), this, SLOT(change_adaptor()));
2527         modules_.push_back(module);
2528 }
2529
2530
2531 void GuiPreferences::change_adaptor()
2532 {
2533         changed();
2534 }
2535
2536
2537 void GuiPreferences::apply(LyXRC & rc) const
2538 {
2539         size_t end = modules_.size();
2540         for (size_t i = 0; i != end; ++i)
2541                 modules_[i]->apply(rc);
2542 }
2543
2544
2545 void GuiPreferences::updateRc(LyXRC const & rc)
2546 {
2547         size_t const end = modules_.size();
2548         for (size_t i = 0; i != end; ++i)
2549                 modules_[i]->update(rc);
2550 }
2551
2552
2553 void GuiPreferences::applyView()
2554 {
2555         apply(rc());
2556 }
2557
2558
2559 void GuiPreferences::updateContents()
2560 {
2561         updateRc(rc());
2562 }
2563
2564
2565 bool GuiPreferences::initialiseParams(string const &)
2566 {
2567         rc_ = lyxrc;
2568         formats_ = lyx::formats;
2569         converters_ = theConverters();
2570         converters_.update(formats_);
2571         movers_ = theMovers();
2572         colors_.clear();
2573         update_screen_font_ = false;
2574
2575         return true;
2576 }
2577
2578
2579 void GuiPreferences::dispatchParams()
2580 {
2581         ostringstream ss;
2582         rc_.write(ss, true);
2583         dispatch(FuncRequest(LFUN_LYXRC_APPLY, ss.str())); 
2584         // FIXME: these need lfuns
2585         // FIXME UNICODE
2586         theBufferList().setCurrentAuthor(from_utf8(rc_.user_name), from_utf8(rc_.user_email));
2587
2588         lyx::formats = formats_;
2589
2590         theConverters() = converters_;
2591         theConverters().update(lyx::formats);
2592         theConverters().buildGraph();
2593
2594         theMovers() = movers_;
2595
2596         vector<string>::const_iterator it = colors_.begin();
2597         vector<string>::const_iterator const end = colors_.end();
2598         for (; it != end; ++it)
2599                 dispatch(FuncRequest(LFUN_SET_COLOR, *it));
2600         colors_.clear();
2601
2602         if (update_screen_font_) {
2603                 dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2604                 update_screen_font_ = false;
2605         }
2606
2607         // The Save button has been pressed
2608         if (isClosing())
2609                 dispatch(FuncRequest(LFUN_PREFERENCES_SAVE));
2610 }
2611
2612
2613 void GuiPreferences::setColor(ColorCode col, QString const & hex)
2614 {
2615         colors_.push_back(lcolor.getLyXName(col) + ' ' + fromqstr(hex));
2616 }
2617
2618
2619 void GuiPreferences::updateScreenFonts()
2620 {
2621         update_screen_font_ = true;
2622 }
2623
2624
2625 QString GuiPreferences::browsebind(QString const & file) const
2626 {
2627         return browseLibFile("bind", file, "bind", qt_("Choose bind file"),
2628                              QStringList(qt_("LyX bind files (*.bind)")));
2629 }
2630
2631
2632 QString GuiPreferences::browseUI(QString const & file) const
2633 {
2634         return browseLibFile("ui", file, "ui", qt_("Choose UI file"),
2635                              QStringList(qt_("LyX UI files (*.ui)")));
2636 }
2637
2638
2639 QString GuiPreferences::browsekbmap(QString const & file) const
2640 {
2641         return browseLibFile("kbd", file, "kmap", qt_("Choose keyboard map"),
2642                              QStringList(qt_("LyX keyboard maps (*.kmap)")));
2643 }
2644
2645
2646 QString GuiPreferences::browsedict(QString const & file) const
2647 {
2648         return browseFile(file, qt_("Choose personal dictionary"),
2649                 QStringList(lyxrc.use_spell_lib ? qt_("*.pws") : qt_("*.ispell")));
2650 }
2651
2652
2653 QString GuiPreferences::browse(QString const & file,
2654                                   QString const & title) const
2655 {
2656         return browseFile(file, title, QStringList(), true);
2657 }
2658
2659
2660 // We support less paper sizes than the document dialog
2661 // Therefore this adjustment is needed.
2662 PAPER_SIZE GuiPreferences::toPaperSize(int i) const
2663 {
2664         switch (i) {
2665         case 0:
2666                 return PAPER_DEFAULT;
2667         case 1:
2668                 return PAPER_USLETTER;
2669         case 2:
2670                 return PAPER_USLEGAL;
2671         case 3:
2672                 return PAPER_USEXECUTIVE;
2673         case 4:
2674                 return PAPER_A3;
2675         case 5:
2676                 return PAPER_A4;
2677         case 6:
2678                 return PAPER_A5;
2679         case 7:
2680                 return PAPER_B5;
2681         default:
2682                 // should not happen
2683                 return PAPER_DEFAULT;
2684         }
2685 }
2686
2687
2688 int GuiPreferences::fromPaperSize(PAPER_SIZE papersize) const
2689 {
2690         switch (papersize) {
2691         case PAPER_DEFAULT:
2692                 return 0;
2693         case PAPER_USLETTER:
2694                 return 1;
2695         case PAPER_USLEGAL:
2696                 return 2;
2697         case PAPER_USEXECUTIVE:
2698                 return 3;
2699         case PAPER_A3:
2700                 return 4;
2701         case PAPER_A4:
2702                 return 5;
2703         case PAPER_A5:
2704                 return 6;
2705         case PAPER_B5:
2706                 return 7;
2707         default:
2708                 // should not happen
2709                 return 0;
2710         }
2711 }
2712
2713
2714 Dialog * createGuiPreferences(GuiView & lv) { return new GuiPreferences(lv); }
2715
2716
2717 } // namespace frontend
2718 } // namespace lyx
2719
2720 #include "GuiPrefs_moc.cpp"