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