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