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