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