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