]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiPrefs.cpp
remove unneeded "default language" option
[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 lcolor.getGUIName(lhs) < lcolor.getGUIName(rhs);
761         }
762 };
763
764 } // namespace anon
765
766 PrefColors::PrefColors(GuiPreferences * form)
767         : PrefModule(qt_(catLookAndFeel), qt_("Colors"), form)
768 {
769         setupUi(this);
770
771         // FIXME: all of this initialization should be put into the controller.
772         // See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg113301.html
773         // for some discussion of why that is not trivial.
774         QPixmap icon(32, 32);
775         for (int i = 0; i < Color_ignore; ++i) {
776                 ColorCode lc = static_cast<ColorCode>(i);
777                 if (lc == Color_none
778                         || lc == Color_black
779                         || lc == Color_white
780                         || lc == Color_red
781                         || lc == Color_green
782                         || lc == Color_blue
783                         || lc == Color_cyan
784                         || lc == Color_magenta
785                         || lc == Color_yellow
786                         || lc == Color_inherit
787                         || lc == Color_ignore) continue;
788
789                 lcolors_.push_back(lc);
790         }
791         sort(lcolors_.begin(), lcolors_.end(), ColorSorter());
792         vector<ColorCode>::const_iterator cit = lcolors_.begin();
793         vector<ColorCode>::const_iterator const end = lcolors_.end();
794         for (; cit != end; ++cit) {
795                         (void) new QListWidgetItem(QIcon(icon),
796                         toqstr(lcolor.getGUIName(*cit)), lyxObjectsLW);
797         }
798         curcolors_.resize(lcolors_.size());
799         newcolors_.resize(lcolors_.size());
800         // End initialization
801
802         connect(colorChangePB, SIGNAL(clicked()),
803                 this, SLOT(change_color()));
804         connect(lyxObjectsLW, SIGNAL(itemSelectionChanged()),
805                 this, SLOT(change_lyxObjects_selection()));
806         connect(lyxObjectsLW, SIGNAL(itemActivated(QListWidgetItem*)),
807                 this, SLOT(change_color()));
808 }
809
810
811 void PrefColors::apply(LyXRC & /*rc*/) const
812 {
813         for (unsigned int i = 0; i < lcolors_.size(); ++i)
814                 if (curcolors_[i] != newcolors_[i])
815                         form_->setColor(lcolors_[i], newcolors_[i]);
816 }
817
818
819 void PrefColors::update(LyXRC const & /*rc*/)
820 {
821         for (unsigned int i = 0; i < lcolors_.size(); ++i) {
822                 QColor color = QColor(guiApp->colorCache().get(lcolors_[i]));
823                 QPixmap coloritem(32, 32);
824                 coloritem.fill(color);
825                 lyxObjectsLW->item(i)->setIcon(QIcon(coloritem));
826                 newcolors_[i] = curcolors_[i] = color.name();
827         }
828         change_lyxObjects_selection();
829 }
830
831
832 void PrefColors::change_color()
833 {
834         int const row = lyxObjectsLW->currentRow();
835
836         // just to be sure
837         if (row < 0)
838                 return;
839
840         QString const color = newcolors_[row];
841         QColor c = QColorDialog::getColor(QColor(color), qApp->focusWidget());
842
843         if (c.isValid() && c.name() != color) {
844                 newcolors_[row] = c.name();
845                 QPixmap coloritem(32, 32);
846                 coloritem.fill(c);
847                 lyxObjectsLW->currentItem()->setIcon(QIcon(coloritem));
848                 // emit signal
849                 changed();
850         }
851 }
852
853 void PrefColors::change_lyxObjects_selection()
854 {
855         colorChangePB->setDisabled(lyxObjectsLW->currentRow() < 0);
856 }
857
858
859 /////////////////////////////////////////////////////////////////////
860 //
861 // PrefDisplay
862 //
863 /////////////////////////////////////////////////////////////////////
864
865 PrefDisplay::PrefDisplay(GuiPreferences * form)
866         : PrefModule(qt_(catLookAndFeel), qt_("Graphics"), form)
867 {
868         setupUi(this);
869         connect(displayGraphicsCB, SIGNAL(toggled(bool)), this, SIGNAL(changed()));
870         connect(instantPreviewCO, SIGNAL(activated(int)), this, SIGNAL(changed()));
871 }
872
873
874 void PrefDisplay::apply(LyXRC & rc) const
875 {
876         switch (instantPreviewCO->currentIndex()) {
877                 case 0: rc.preview = LyXRC::PREVIEW_OFF; break;
878                 case 1: rc.preview = LyXRC::PREVIEW_NO_MATH; break;
879                 case 2: rc.preview = LyXRC::PREVIEW_ON; break;
880         }
881
882         rc.display_graphics = displayGraphicsCB->isChecked();
883
884         // FIXME!! The graphics cache no longer has a changeDisplay method.
885 #if 0
886         if (old_value != rc.display_graphics) {
887                 graphics::GCache & gc = graphics::GCache::get();
888                 gc.changeDisplay();
889         }
890 #endif
891 }
892
893
894 void PrefDisplay::update(LyXRC const & rc)
895 {
896         switch (rc.preview) {
897         case LyXRC::PREVIEW_OFF:
898                 instantPreviewCO->setCurrentIndex(0);
899                 break;
900         case LyXRC::PREVIEW_NO_MATH :
901                 instantPreviewCO->setCurrentIndex(1);
902                 break;
903         case LyXRC::PREVIEW_ON :
904                 instantPreviewCO->setCurrentIndex(2);
905                 break;
906         }
907
908         displayGraphicsCB->setChecked(rc.display_graphics);
909         instantPreviewCO->setEnabled(rc.display_graphics);
910 }
911
912
913 /////////////////////////////////////////////////////////////////////
914 //
915 // PrefPaths
916 //
917 /////////////////////////////////////////////////////////////////////
918
919 PrefPaths::PrefPaths(GuiPreferences * form)
920         : PrefModule(QString(), qt_("Paths"), form)
921 {
922         setupUi(this);
923         connect(exampleDirPB, SIGNAL(clicked()), this, SLOT(select_exampledir()));
924         connect(templateDirPB, SIGNAL(clicked()), this, SLOT(select_templatedir()));
925         connect(tempDirPB, SIGNAL(clicked()), this, SLOT(select_tempdir()));
926         connect(backupDirPB, SIGNAL(clicked()), this, SLOT(select_backupdir()));
927         connect(workingDirPB, SIGNAL(clicked()), this, SLOT(select_workingdir()));
928         connect(lyxserverDirPB, SIGNAL(clicked()), this, SLOT(select_lyxpipe()));
929         connect(thesaurusDirPB, SIGNAL(clicked()), this, SLOT(select_thesaurusdir()));
930         connect(workingDirED, SIGNAL(textChanged(QString)),
931                 this, SIGNAL(changed()));
932         connect(exampleDirED, SIGNAL(textChanged(QString)),
933                 this, SIGNAL(changed()));
934         connect(templateDirED, SIGNAL(textChanged(QString)),
935                 this, SIGNAL(changed()));
936         connect(backupDirED, SIGNAL(textChanged(QString)),
937                 this, SIGNAL(changed()));
938         connect(tempDirED, SIGNAL(textChanged(QString)),
939                 this, SIGNAL(changed()));
940         connect(lyxserverDirED, SIGNAL(textChanged(QString)),
941                 this, SIGNAL(changed()));
942         connect(thesaurusDirED, SIGNAL(textChanged(QString)),
943                 this, SIGNAL(changed()));
944         connect(pathPrefixED, SIGNAL(textChanged(QString)),
945                 this, SIGNAL(changed()));
946 }
947
948
949 void PrefPaths::apply(LyXRC & rc) const
950 {
951         rc.document_path = internal_path(fromqstr(workingDirED->text()));
952         rc.example_path = internal_path(fromqstr(exampleDirED->text()));
953         rc.template_path = internal_path(fromqstr(templateDirED->text()));
954         rc.backupdir_path = internal_path(fromqstr(backupDirED->text()));
955         rc.tempdir_path = internal_path(fromqstr(tempDirED->text()));
956         rc.thesaurusdir_path = internal_path(fromqstr(thesaurusDirED->text()));
957         rc.path_prefix = internal_path_list(fromqstr(pathPrefixED->text()));
958         // FIXME: should be a checkbox only
959         rc.lyxpipes = internal_path(fromqstr(lyxserverDirED->text()));
960 }
961
962
963 void PrefPaths::update(LyXRC const & rc)
964 {
965         workingDirED->setText(toqstr(external_path(rc.document_path)));
966         exampleDirED->setText(toqstr(external_path(rc.example_path)));
967         templateDirED->setText(toqstr(external_path(rc.template_path)));
968         backupDirED->setText(toqstr(external_path(rc.backupdir_path)));
969         tempDirED->setText(toqstr(external_path(rc.tempdir_path)));
970         thesaurusDirED->setText(toqstr(external_path(rc.thesaurusdir_path)));
971         pathPrefixED->setText(toqstr(external_path_list(rc.path_prefix)));
972         // FIXME: should be a checkbox only
973         lyxserverDirED->setText(toqstr(external_path(rc.lyxpipes)));
974 }
975
976
977 void PrefPaths::select_exampledir()
978 {
979         QString file = browseDir(internalPath(exampleDirED->text()),
980                 qt_("Select directory for example files"));
981         if (!file.isEmpty())
982                 exampleDirED->setText(file);
983 }
984
985
986 void PrefPaths::select_templatedir()
987 {
988         QString file = browseDir(internalPath(templateDirED->text()),
989                 qt_("Select a document templates directory"));
990         if (!file.isEmpty())
991                 templateDirED->setText(file);
992 }
993
994
995 void PrefPaths::select_tempdir()
996 {
997         QString file = browseDir(internalPath(tempDirED->text()),
998                 qt_("Select a temporary directory"));
999         if (!file.isEmpty())
1000                 tempDirED->setText(file);
1001 }
1002
1003
1004 void PrefPaths::select_backupdir()
1005 {
1006         QString file = browseDir(internalPath(backupDirED->text()),
1007                 qt_("Select a backups directory"));
1008         if (!file.isEmpty())
1009                 backupDirED->setText(file);
1010 }
1011
1012
1013 void PrefPaths::select_workingdir()
1014 {
1015         QString file = browseDir(internalPath(workingDirED->text()),
1016                 qt_("Select a document directory"));
1017         if (!file.isEmpty())
1018                 workingDirED->setText(file);
1019 }
1020
1021
1022 void PrefPaths::select_thesaurusdir()
1023 {
1024         QString file = browseDir(internalPath(thesaurusDirED->text()),
1025                 qt_("Set the path to the thesaurus dictionaries"));
1026         if (!file.isEmpty())
1027                 thesaurusDirED->setText(file);
1028 }
1029
1030
1031 void PrefPaths::select_lyxpipe()
1032 {
1033         QString file = form_->browse(internalPath(lyxserverDirED->text()),
1034                 qt_("Give a filename for the LyX server pipe"));
1035         if (!file.isEmpty())
1036                 lyxserverDirED->setText(file);
1037 }
1038
1039
1040 /////////////////////////////////////////////////////////////////////
1041 //
1042 // PrefSpellchecker
1043 //
1044 /////////////////////////////////////////////////////////////////////
1045
1046 PrefSpellchecker::PrefSpellchecker(GuiPreferences * form)
1047         : PrefModule(qt_(catLanguage), qt_("Spellchecker"), form)
1048 {
1049         setupUi(this);
1050
1051         connect(persDictionaryPB, SIGNAL(clicked()), this, SLOT(select_dict()));
1052
1053         connect(altLanguageED, SIGNAL(textChanged(QString)),
1054                 this, SIGNAL(changed()));
1055         connect(escapeCharactersED, SIGNAL(textChanged(QString)),
1056                 this, SIGNAL(changed()));
1057         connect(persDictionaryED, SIGNAL(textChanged(QString)),
1058                 this, SIGNAL(changed()));
1059         connect(compoundWordCB, SIGNAL(clicked()),
1060                 this, SIGNAL(changed()));
1061         connect(inputEncodingCB, SIGNAL(clicked()),
1062                 this, SIGNAL(changed()));
1063 }
1064
1065
1066 void PrefSpellchecker::apply(LyXRC & rc) const
1067 {
1068         // FIXME: remove spellchecker_use_alt_lang
1069         rc.spellchecker_alt_lang = fromqstr(altLanguageED->text());
1070         rc.spellchecker_use_alt_lang = !rc.spellchecker_alt_lang.empty();
1071         // FIXME: remove spellchecker_use_esc_chars
1072         rc.spellchecker_esc_chars = fromqstr(escapeCharactersED->text());
1073         rc.spellchecker_use_esc_chars = !rc.spellchecker_esc_chars.empty();
1074         // FIXME: remove spellchecker_use_pers_dict
1075         rc.spellchecker_pers_dict = internal_path(fromqstr(persDictionaryED->text()));
1076         rc.spellchecker_use_pers_dict = !rc.spellchecker_pers_dict.empty();
1077         rc.spellchecker_accept_compound = compoundWordCB->isChecked();
1078         rc.spellchecker_use_input_encoding = inputEncodingCB->isChecked();
1079 }
1080
1081
1082 void PrefSpellchecker::update(LyXRC const & rc)
1083 {
1084         // FIXME: remove spellchecker_use_alt_lang
1085         altLanguageED->setText(toqstr(rc.spellchecker_alt_lang));
1086         // FIXME: remove spellchecker_use_esc_chars
1087         escapeCharactersED->setText(toqstr(rc.spellchecker_esc_chars));
1088         // FIXME: remove spellchecker_use_pers_dict
1089         persDictionaryED->setText(toqstr(external_path(rc.spellchecker_pers_dict)));
1090         compoundWordCB->setChecked(rc.spellchecker_accept_compound);
1091         inputEncodingCB->setChecked(rc.spellchecker_use_input_encoding);
1092 }
1093
1094
1095 void PrefSpellchecker::select_dict()
1096 {
1097         QString file = form_->browsedict(internalPath(persDictionaryED->text()));
1098         if (!file.isEmpty())
1099                 persDictionaryED->setText(file);
1100 }
1101
1102
1103
1104 /////////////////////////////////////////////////////////////////////
1105 //
1106 // PrefConverters
1107 //
1108 /////////////////////////////////////////////////////////////////////
1109
1110
1111 PrefConverters::PrefConverters(GuiPreferences * form)
1112         : PrefModule(qt_(catFiles), qt_("Converters"), form)
1113 {
1114         setupUi(this);
1115
1116         connect(converterNewPB, SIGNAL(clicked()),
1117                 this, SLOT(update_converter()));
1118         connect(converterRemovePB, SIGNAL(clicked()),
1119                 this, SLOT(remove_converter()));
1120         connect(converterModifyPB, SIGNAL(clicked()),
1121                 this, SLOT(update_converter()));
1122         connect(convertersLW, SIGNAL(currentRowChanged(int)),
1123                 this, SLOT(switch_converter()));
1124         connect(converterFromCO, SIGNAL(activated(QString)),
1125                 this, SLOT(converter_changed()));
1126         connect(converterToCO, SIGNAL(activated(QString)),
1127                 this, SLOT(converter_changed()));
1128         connect(converterED, SIGNAL(textEdited(QString)),
1129                 this, SLOT(converter_changed()));
1130         connect(converterFlagED, SIGNAL(textEdited(QString)),
1131                 this, SLOT(converter_changed()));
1132         connect(converterNewPB, SIGNAL(clicked()),
1133                 this, SIGNAL(changed()));
1134         connect(converterRemovePB, SIGNAL(clicked()),
1135                 this, SIGNAL(changed()));
1136         connect(converterModifyPB, SIGNAL(clicked()),
1137                 this, SIGNAL(changed()));
1138         connect(maxAgeLE, SIGNAL(textEdited(QString)),
1139                 this, SIGNAL(changed()));
1140
1141         maxAgeLE->setValidator(new QDoubleValidator(maxAgeLE));
1142         //converterDefGB->setFocusProxy(convertersLW);
1143 }
1144
1145
1146 void PrefConverters::apply(LyXRC & rc) const
1147 {
1148         rc.use_converter_cache = cacheCB->isChecked();
1149         rc.converter_cache_maxage = int(maxAgeLE->text().toDouble() * 86400.0);
1150 }
1151
1152
1153 void PrefConverters::update(LyXRC const & rc)
1154 {
1155         cacheCB->setChecked(rc.use_converter_cache);
1156         QString max_age;
1157         max_age.setNum(double(rc.converter_cache_maxage) / 86400.0, 'g', 6);
1158         maxAgeLE->setText(max_age);
1159         updateGui();
1160 }
1161
1162
1163 void PrefConverters::updateGui()
1164 {
1165         form_->formats().sort();
1166         form_->converters().update(form_->formats());
1167         // save current selection
1168         QString current = converterFromCO->currentText()
1169                 + " -> " + converterToCO->currentText();
1170
1171         converterFromCO->clear();
1172         converterToCO->clear();
1173
1174         Formats::const_iterator cit = form_->formats().begin();
1175         Formats::const_iterator end = form_->formats().end();
1176         for (; cit != end; ++cit) {
1177                 converterFromCO->addItem(qt_(cit->prettyname()));
1178                 converterToCO->addItem(qt_(cit->prettyname()));
1179         }
1180
1181         // currentRowChanged(int) is also triggered when updating the listwidget
1182         // block signals to avoid unnecessary calls to switch_converter()
1183         convertersLW->blockSignals(true);
1184         convertersLW->clear();
1185
1186         Converters::const_iterator ccit = form_->converters().begin();
1187         Converters::const_iterator cend = form_->converters().end();
1188         for (; ccit != cend; ++ccit) {
1189                 QString const name =
1190                         qt_(ccit->From->prettyname()) + " -> " + qt_(ccit->To->prettyname());
1191                 int type = form_->converters().getNumber(ccit->From->name(), ccit->To->name());
1192                 new QListWidgetItem(name, convertersLW, type);
1193         }
1194         convertersLW->sortItems(Qt::AscendingOrder);
1195         convertersLW->blockSignals(false);
1196
1197         // restore selection
1198         if (!current.isEmpty()) {
1199                 QList<QListWidgetItem *> const item =
1200                         convertersLW->findItems(current, Qt::MatchExactly);
1201                 if (!item.isEmpty())
1202                         convertersLW->setCurrentItem(item.at(0));
1203         }
1204
1205         // select first element if restoring failed
1206         if (convertersLW->currentRow() == -1)
1207                 convertersLW->setCurrentRow(0);
1208
1209         updateButtons();
1210 }
1211
1212
1213 void PrefConverters::switch_converter()
1214 {
1215         int const cnr = convertersLW->currentItem()->type();
1216         Converter const & c(form_->converters().get(cnr));
1217         converterFromCO->setCurrentIndex(form_->formats().getNumber(c.from));
1218         converterToCO->setCurrentIndex(form_->formats().getNumber(c.to));
1219         converterED->setText(toqstr(c.command));
1220         converterFlagED->setText(toqstr(c.flags));
1221
1222         updateButtons();
1223 }
1224
1225
1226 void PrefConverters::converter_changed()
1227 {
1228         updateButtons();
1229 }
1230
1231
1232 void PrefConverters::updateButtons()
1233 {
1234         Format const & from = form_->formats().get(converterFromCO->currentIndex());
1235         Format const & to = form_->formats().get(converterToCO->currentIndex());
1236         int const sel = form_->converters().getNumber(from.name(), to.name());
1237         bool const known = sel >= 0;
1238         bool const valid = !(converterED->text().isEmpty()
1239                 || from.name() == to.name());
1240
1241         int const cnr = convertersLW->currentItem()->type();
1242         Converter const & c = form_->converters().get(cnr);
1243         string const old_command = c.command;
1244         string const old_flag = c.flags;
1245         string const new_command = fromqstr(converterED->text());
1246         string const new_flag = fromqstr(converterFlagED->text());
1247
1248         bool modified = (old_command != new_command || old_flag != new_flag);
1249
1250         converterModifyPB->setEnabled(valid && known && modified);
1251         converterNewPB->setEnabled(valid && !known);
1252         converterRemovePB->setEnabled(known);
1253
1254         maxAgeLE->setEnabled(cacheCB->isChecked());
1255         maxAgeLA->setEnabled(cacheCB->isChecked());
1256 }
1257
1258
1259 // FIXME: user must
1260 // specify unique from/to or it doesn't appear. This is really bad UI
1261 // this is why we can use the same function for both new and modify
1262 void PrefConverters::update_converter()
1263 {
1264         Format const & from = form_->formats().get(converterFromCO->currentIndex());
1265         Format const & to = form_->formats().get(converterToCO->currentIndex());
1266         string const flags = fromqstr(converterFlagED->text());
1267         string const command = fromqstr(converterED->text());
1268
1269         Converter const * old =
1270                 form_->converters().getConverter(from.name(), to.name());
1271         form_->converters().add(from.name(), to.name(), command, flags);
1272
1273         if (!old)
1274                 form_->converters().updateLast(form_->formats());
1275
1276         updateGui();
1277
1278         // Remove all files created by this converter from the cache, since
1279         // the modified converter might create different files.
1280         ConverterCache::get().remove_all(from.name(), to.name());
1281 }
1282
1283
1284 void PrefConverters::remove_converter()
1285 {
1286         Format const & from = form_->formats().get(converterFromCO->currentIndex());
1287         Format const & to = form_->formats().get(converterToCO->currentIndex());
1288         form_->converters().erase(from.name(), to.name());
1289
1290         updateGui();
1291
1292         // Remove all files created by this converter from the cache, since
1293         // a possible new converter might create different files.
1294         ConverterCache::get().remove_all(from.name(), to.name());
1295 }
1296
1297
1298 void PrefConverters::on_cacheCB_stateChanged(int state)
1299 {
1300         maxAgeLE->setEnabled(state == Qt::Checked);
1301         maxAgeLA->setEnabled(state == Qt::Checked);
1302         changed();
1303 }
1304
1305
1306 /////////////////////////////////////////////////////////////////////
1307 //
1308 // FormatValidator
1309 //
1310 /////////////////////////////////////////////////////////////////////
1311
1312 class FormatValidator : public QValidator
1313 {
1314 public:
1315         FormatValidator(QWidget *, Formats const & f);
1316         void fixup(QString & input) const;
1317         QValidator::State validate(QString & input, int & pos) const;
1318 private:
1319         virtual QString toString(Format const & format) const = 0;
1320         int nr() const;
1321         Formats const & formats_;
1322 };
1323
1324
1325 FormatValidator::FormatValidator(QWidget * parent, Formats const & f)
1326         : QValidator(parent), formats_(f)
1327 {
1328 }
1329
1330
1331 void FormatValidator::fixup(QString & input) const
1332 {
1333         Formats::const_iterator cit = formats_.begin();
1334         Formats::const_iterator end = formats_.end();
1335         for (; cit != end; ++cit) {
1336                 QString const name = toString(*cit);
1337                 if (distance(formats_.begin(), cit) == nr()) {
1338                         input = name;
1339                         return;
1340                 }
1341         }
1342 }
1343
1344
1345 QValidator::State FormatValidator::validate(QString & input, int & /*pos*/) const
1346 {
1347         Formats::const_iterator cit = formats_.begin();
1348         Formats::const_iterator end = formats_.end();
1349         bool unknown = true;
1350         for (; unknown && cit != end; ++cit) {
1351                 QString const name = toString(*cit);
1352                 if (distance(formats_.begin(), cit) != nr())
1353                         unknown = name != input;
1354         }
1355
1356         if (unknown && !input.isEmpty())
1357                 return QValidator::Acceptable;
1358         else
1359                 return QValidator::Intermediate;
1360 }
1361
1362
1363 int FormatValidator::nr() const
1364 {
1365         QComboBox * p = qobject_cast<QComboBox *>(parent());
1366         return p->itemData(p->currentIndex()).toInt();
1367 }
1368
1369
1370 /////////////////////////////////////////////////////////////////////
1371 //
1372 // FormatNameValidator
1373 //
1374 /////////////////////////////////////////////////////////////////////
1375
1376 class FormatNameValidator : public FormatValidator
1377 {
1378 public:
1379         FormatNameValidator(QWidget * parent, Formats const & f)
1380                 : FormatValidator(parent, f)
1381         {}
1382 private:
1383         QString toString(Format const & format) const
1384         {
1385                 return toqstr(format.name());
1386         }
1387 };
1388
1389
1390 /////////////////////////////////////////////////////////////////////
1391 //
1392 // FormatPrettynameValidator
1393 //
1394 /////////////////////////////////////////////////////////////////////
1395
1396 class FormatPrettynameValidator : public FormatValidator
1397 {
1398 public:
1399         FormatPrettynameValidator(QWidget * parent, Formats const & f)
1400                 : FormatValidator(parent, f)
1401         {}
1402 private:
1403         QString toString(Format const & format) const
1404         {
1405                 return qt_(format.prettyname());
1406         }
1407 };
1408
1409
1410 /////////////////////////////////////////////////////////////////////
1411 //
1412 // PrefFileformats
1413 //
1414 /////////////////////////////////////////////////////////////////////
1415
1416 PrefFileformats::PrefFileformats(GuiPreferences * form)
1417         : PrefModule(qt_(catFiles), qt_("File formats"), form)
1418 {
1419         setupUi(this);
1420         formatED->setValidator(new FormatNameValidator(formatsCB, form_->formats()));
1421         formatsCB->setValidator(new FormatPrettynameValidator(formatsCB, form_->formats()));
1422
1423         connect(documentCB, SIGNAL(clicked()),
1424                 this, SLOT(setFlags()));
1425         connect(vectorCB, SIGNAL(clicked()),
1426                 this, SLOT(setFlags()));
1427         connect(formatsCB->lineEdit(), SIGNAL(editingFinished()),
1428                 this, SLOT(updatePrettyname()));
1429         connect(formatsCB->lineEdit(), SIGNAL(textEdited(QString)),
1430                 this, SIGNAL(changed()));
1431 }
1432
1433
1434 namespace {
1435
1436 string const l10n_shortcut(string const prettyname, string const shortcut)
1437 {
1438         if (shortcut.empty())
1439                 return string();
1440
1441         string l10n_format =
1442                 to_utf8(_(prettyname + '|' + shortcut));
1443         return split(l10n_format, '|');
1444 }
1445
1446 }; // namespace anon
1447
1448
1449 void PrefFileformats::apply(LyXRC & /*rc*/) const
1450 {
1451 }
1452
1453
1454 void PrefFileformats::update(LyXRC const & /*rc*/)
1455 {
1456         updateView();
1457 }
1458
1459
1460 void PrefFileformats::updateView()
1461 {
1462         QString const current = formatsCB->currentText();
1463
1464         // update combobox with formats
1465         formatsCB->blockSignals(true);
1466         formatsCB->clear();
1467         form_->formats().sort();
1468         Formats::const_iterator cit = form_->formats().begin();
1469         Formats::const_iterator end = form_->formats().end();
1470         for (; cit != end; ++cit)
1471                 formatsCB->addItem(qt_(cit->prettyname()),
1472                                    QVariant(form_->formats().getNumber(cit->name())));
1473
1474         // restore selection
1475         int const item = formatsCB->findText(current, Qt::MatchExactly);
1476         formatsCB->setCurrentIndex(item < 0 ? 0 : item);
1477         on_formatsCB_currentIndexChanged(item < 0 ? 0 : item);
1478         formatsCB->blockSignals(false);
1479 }
1480
1481
1482 void PrefFileformats::on_formatsCB_currentIndexChanged(int i)
1483 {
1484         int const nr = formatsCB->itemData(i).toInt();
1485         Format const f = form_->formats().get(nr);
1486
1487         formatED->setText(toqstr(f.name()));
1488         copierED->setText(toqstr(form_->movers().command(f.name())));
1489         extensionED->setText(toqstr(f.extension()));
1490         shortcutED->setText(
1491                 toqstr(l10n_shortcut(f.prettyname(), f.shortcut())));
1492         viewerED->setText(toqstr(f.viewer()));
1493         editorED->setText(toqstr(f.editor()));
1494         documentCB->setChecked((f.documentFormat()));
1495         vectorCB->setChecked((f.vectorFormat()));
1496 }
1497
1498
1499 void PrefFileformats::setFlags()
1500 {
1501         int flags = Format::none;
1502         if (documentCB->isChecked())
1503                 flags |= Format::document;
1504         if (vectorCB->isChecked())
1505                 flags |= Format::vector;
1506         currentFormat().setFlags(flags);
1507         changed();
1508 }
1509
1510
1511 void PrefFileformats::on_copierED_textEdited(const QString & s)
1512 {
1513         string const fmt = fromqstr(formatED->text());
1514         form_->movers().set(fmt, fromqstr(s));
1515         changed();
1516 }
1517
1518
1519 void PrefFileformats::on_extensionED_textEdited(const QString & s)
1520 {
1521         currentFormat().setExtension(fromqstr(s));
1522         changed();
1523 }
1524
1525 void PrefFileformats::on_viewerED_textEdited(const QString & s)
1526 {
1527         currentFormat().setViewer(fromqstr(s));
1528         changed();
1529 }
1530
1531
1532 void PrefFileformats::on_editorED_textEdited(const QString & s)
1533 {
1534         currentFormat().setEditor(fromqstr(s));
1535         changed();
1536 }
1537
1538
1539 void PrefFileformats::on_shortcutED_textEdited(const QString & s)
1540 {
1541         string const new_shortcut = fromqstr(s);
1542         if (new_shortcut == l10n_shortcut(currentFormat().prettyname(),
1543                                           currentFormat().shortcut()))
1544                 return;
1545         currentFormat().setShortcut(new_shortcut);
1546         changed();
1547 }
1548
1549
1550 void PrefFileformats::on_formatED_editingFinished()
1551 {
1552         string const newname = fromqstr(formatED->displayText());
1553         if (newname == currentFormat().name())
1554                 return;
1555
1556         currentFormat().setName(newname);
1557         changed();
1558 }
1559
1560
1561 void PrefFileformats::on_formatED_textChanged(const QString &)
1562 {
1563         QString t = formatED->text();
1564         int p = 0;
1565         bool valid = formatED->validator()->validate(t, p) == QValidator::Acceptable;
1566         setValid(formatLA, valid);
1567 }
1568
1569
1570 void PrefFileformats::on_formatsCB_editTextChanged(const QString &)
1571 {
1572         QString t = formatsCB->currentText();
1573         int p = 0;
1574         bool valid = formatsCB->validator()->validate(t, p) == QValidator::Acceptable;
1575         setValid(formatsLA, valid);
1576 }
1577
1578
1579 void PrefFileformats::updatePrettyname()
1580 {
1581         QString const newname = formatsCB->currentText();
1582         if (newname == qt_(currentFormat().prettyname()))
1583                 return;
1584
1585         currentFormat().setPrettyname(fromqstr(newname));
1586         formatsChanged();
1587         updateView();
1588         changed();
1589 }
1590
1591
1592 Format & PrefFileformats::currentFormat()
1593 {
1594         int const i = formatsCB->currentIndex();
1595         int const nr = formatsCB->itemData(i).toInt();
1596         return form_->formats().get(nr);
1597 }
1598
1599
1600 void PrefFileformats::on_formatNewPB_clicked()
1601 {
1602         form_->formats().add("", "", "", "", "", "", Format::none);
1603         updateView();
1604         formatsCB->setCurrentIndex(0);
1605         formatsCB->setFocus(Qt::OtherFocusReason);
1606 }
1607
1608
1609 void PrefFileformats::on_formatRemovePB_clicked()
1610 {
1611         int const i = formatsCB->currentIndex();
1612         int const nr = formatsCB->itemData(i).toInt();
1613         string const current_text = form_->formats().get(nr).name();
1614         if (form_->converters().formatIsUsed(current_text)) {
1615                 Alert::error(_("Format in use"),
1616                              _("Cannot remove a Format used by a Converter. "
1617                                             "Remove the converter first."));
1618                 return;
1619         }
1620
1621         form_->formats().erase(current_text);
1622         formatsChanged();
1623         updateView();
1624         on_formatsCB_editTextChanged(formatsCB->currentText());
1625         changed();
1626 }
1627
1628
1629 /////////////////////////////////////////////////////////////////////
1630 //
1631 // PrefLanguage
1632 //
1633 /////////////////////////////////////////////////////////////////////
1634
1635 PrefLanguage::PrefLanguage(GuiPreferences * form)
1636         : PrefModule(qt_(catLanguage), qt_("Language"), form)
1637 {
1638         setupUi(this);
1639
1640         connect(rtlGB, SIGNAL(clicked()),
1641                 this, SIGNAL(changed()));
1642         connect(visualCursorRB, SIGNAL(clicked()),
1643                 this, SIGNAL(changed()));
1644         connect(logicalCursorRB, SIGNAL(clicked()),
1645                 this, SIGNAL(changed()));
1646         connect(markForeignCB, SIGNAL(clicked()),
1647                 this, SIGNAL(changed()));
1648         connect(autoBeginCB, SIGNAL(clicked()),
1649                 this, SIGNAL(changed()));
1650         connect(autoEndCB, SIGNAL(clicked()),
1651                 this, SIGNAL(changed()));
1652         connect(useBabelCB, SIGNAL(clicked()),
1653                 this, SIGNAL(changed()));
1654         connect(globalCB, SIGNAL(clicked()),
1655                 this, SIGNAL(changed()));
1656         connect(languagePackageED, SIGNAL(textChanged(QString)),
1657                 this, SIGNAL(changed()));
1658         connect(startCommandED, SIGNAL(textChanged(QString)),
1659                 this, SIGNAL(changed()));
1660         connect(endCommandED, SIGNAL(textChanged(QString)),
1661                 this, SIGNAL(changed()));
1662         connect(uiLanguageCO, SIGNAL(activated(int)),
1663                 this, SIGNAL(changed()));
1664
1665         uiLanguageCO->clear();
1666
1667         QAbstractItemModel * language_model = guiApp->languageModel();
1668         // FIXME: it would be nice if sorting was enabled/disabled via a checkbox.
1669         language_model->sort(0);
1670
1671         // FIXME: This is wrong, we need filter this list based on the available
1672         // translation.
1673         uiLanguageCO->blockSignals(true);
1674         uiLanguageCO->addItem(qt_("Default"), toqstr("auto"));
1675         for (int i = 0; i != language_model->rowCount(); ++i) {
1676                 QModelIndex index = language_model->index(i, 0);
1677                 uiLanguageCO->addItem(index.data(Qt::DisplayRole).toString(),
1678                         index.data(Qt::UserRole).toString());
1679         }
1680         uiLanguageCO->blockSignals(false);
1681 }
1682
1683
1684 void PrefLanguage::on_uiLanguageCO_currentIndexChanged(int)
1685 {
1686          QMessageBox::information(this, qt_("LyX needs to be restarted!"),
1687                  qt_("The change of user interface language will be fully "
1688                  "effective only after a restart."));
1689 }
1690
1691
1692 void PrefLanguage::apply(LyXRC & rc) const
1693 {
1694         // FIXME: remove rtl_support bool
1695         rc.rtl_support = rtlGB->isChecked();
1696         rc.visual_cursor = rtlGB->isChecked() && visualCursorRB->isChecked();
1697         rc.mark_foreign_language = markForeignCB->isChecked();
1698         rc.language_auto_begin = autoBeginCB->isChecked();
1699         rc.language_auto_end = autoEndCB->isChecked();
1700         rc.language_use_babel = useBabelCB->isChecked();
1701         rc.language_global_options = globalCB->isChecked();
1702         rc.language_package = fromqstr(languagePackageED->text());
1703         rc.language_command_begin = fromqstr(startCommandED->text());
1704         rc.language_command_end = fromqstr(endCommandED->text());
1705         rc.gui_language = fromqstr(
1706                 uiLanguageCO->itemData(uiLanguageCO->currentIndex()).toString());
1707 }
1708
1709
1710 void PrefLanguage::update(LyXRC const & rc)
1711 {
1712         // FIXME: remove rtl_support bool
1713         rtlGB->setChecked(rc.rtl_support);
1714         if (rc.visual_cursor)
1715                 visualCursorRB->setChecked(true);
1716         else
1717                 logicalCursorRB->setChecked(true);
1718         markForeignCB->setChecked(rc.mark_foreign_language);
1719         autoBeginCB->setChecked(rc.language_auto_begin);
1720         autoEndCB->setChecked(rc.language_auto_end);
1721         useBabelCB->setChecked(rc.language_use_babel);
1722         globalCB->setChecked(rc.language_global_options);
1723         languagePackageED->setText(toqstr(rc.language_package));
1724         startCommandED->setText(toqstr(rc.language_command_begin));
1725         endCommandED->setText(toqstr(rc.language_command_end));
1726
1727         int pos = uiLanguageCO->findData(toqstr(rc.gui_language));
1728         uiLanguageCO->blockSignals(true);
1729         uiLanguageCO->setCurrentIndex(pos);
1730         uiLanguageCO->blockSignals(false);
1731 }
1732
1733
1734 /////////////////////////////////////////////////////////////////////
1735 //
1736 // PrefPrinter
1737 //
1738 /////////////////////////////////////////////////////////////////////
1739
1740 PrefPrinter::PrefPrinter(GuiPreferences * form)
1741         : PrefModule(qt_(catOutput), qt_("Printer"), form)
1742 {
1743         setupUi(this);
1744
1745         connect(printerAdaptCB, SIGNAL(clicked()),
1746                 this, SIGNAL(changed()));
1747         connect(printerCommandED, SIGNAL(textChanged(QString)),
1748                 this, SIGNAL(changed()));
1749         connect(printerNameED, SIGNAL(textChanged(QString)),
1750                 this, SIGNAL(changed()));
1751         connect(printerPageRangeED, SIGNAL(textChanged(QString)),
1752                 this, SIGNAL(changed()));
1753         connect(printerCopiesED, SIGNAL(textChanged(QString)),
1754                 this, SIGNAL(changed()));
1755         connect(printerReverseED, SIGNAL(textChanged(QString)),
1756                 this, SIGNAL(changed()));
1757         connect(printerToPrinterED, SIGNAL(textChanged(QString)),
1758                 this, SIGNAL(changed()));
1759         connect(printerExtensionED, SIGNAL(textChanged(QString)),
1760                 this, SIGNAL(changed()));
1761         connect(printerSpoolCommandED, SIGNAL(textChanged(QString)),
1762                 this, SIGNAL(changed()));
1763         connect(printerPaperTypeED, SIGNAL(textChanged(QString)),
1764                 this, SIGNAL(changed()));
1765         connect(printerEvenED, SIGNAL(textChanged(QString)),
1766                 this, SIGNAL(changed()));
1767         connect(printerOddED, SIGNAL(textChanged(QString)),
1768                 this, SIGNAL(changed()));
1769         connect(printerCollatedED, SIGNAL(textChanged(QString)),
1770                 this, SIGNAL(changed()));
1771         connect(printerLandscapeED, SIGNAL(textChanged(QString)),
1772                 this, SIGNAL(changed()));
1773         connect(printerToFileED, SIGNAL(textChanged(QString)),
1774                 this, SIGNAL(changed()));
1775         connect(printerExtraED, SIGNAL(textChanged(QString)),
1776                 this, SIGNAL(changed()));
1777         connect(printerSpoolPrefixED, SIGNAL(textChanged(QString)),
1778                 this, SIGNAL(changed()));
1779         connect(printerPaperSizeED, SIGNAL(textChanged(QString)),
1780                 this, SIGNAL(changed()));
1781 }
1782
1783
1784 void PrefPrinter::apply(LyXRC & rc) const
1785 {
1786         rc.print_adapt_output = printerAdaptCB->isChecked();
1787         rc.print_command = fromqstr(printerCommandED->text());
1788         rc.printer = fromqstr(printerNameED->text());
1789
1790         rc.print_pagerange_flag = fromqstr(printerPageRangeED->text());
1791         rc.print_copies_flag = fromqstr(printerCopiesED->text());
1792         rc.print_reverse_flag = fromqstr(printerReverseED->text());
1793         rc.print_to_printer = fromqstr(printerToPrinterED->text());
1794         rc.print_file_extension = fromqstr(printerExtensionED->text());
1795         rc.print_spool_command = fromqstr(printerSpoolCommandED->text());
1796         rc.print_paper_flag = fromqstr(printerPaperTypeED->text());
1797         rc.print_evenpage_flag = fromqstr(printerEvenED->text());
1798         rc.print_oddpage_flag = fromqstr(printerOddED->text());
1799         rc.print_collcopies_flag = fromqstr(printerCollatedED->text());
1800         rc.print_landscape_flag = fromqstr(printerLandscapeED->text());
1801         rc.print_to_file = internal_path(fromqstr(printerToFileED->text()));
1802         rc.print_extra_options = fromqstr(printerExtraED->text());
1803         rc.print_spool_printerprefix = fromqstr(printerSpoolPrefixED->text());
1804         rc.print_paper_dimension_flag = fromqstr(printerPaperSizeED->text());
1805 }
1806
1807
1808 void PrefPrinter::update(LyXRC const & rc)
1809 {
1810         printerAdaptCB->setChecked(rc.print_adapt_output);
1811         printerCommandED->setText(toqstr(rc.print_command));
1812         printerNameED->setText(toqstr(rc.printer));
1813
1814         printerPageRangeED->setText(toqstr(rc.print_pagerange_flag));
1815         printerCopiesED->setText(toqstr(rc.print_copies_flag));
1816         printerReverseED->setText(toqstr(rc.print_reverse_flag));
1817         printerToPrinterED->setText(toqstr(rc.print_to_printer));
1818         printerExtensionED->setText(toqstr(rc.print_file_extension));
1819         printerSpoolCommandED->setText(toqstr(rc.print_spool_command));
1820         printerPaperTypeED->setText(toqstr(rc.print_paper_flag));
1821         printerEvenED->setText(toqstr(rc.print_evenpage_flag));
1822         printerOddED->setText(toqstr(rc.print_oddpage_flag));
1823         printerCollatedED->setText(toqstr(rc.print_collcopies_flag));
1824         printerLandscapeED->setText(toqstr(rc.print_landscape_flag));
1825         printerToFileED->setText(toqstr(external_path(rc.print_to_file)));
1826         printerExtraED->setText(toqstr(rc.print_extra_options));
1827         printerSpoolPrefixED->setText(toqstr(rc.print_spool_printerprefix));
1828         printerPaperSizeED->setText(toqstr(rc.print_paper_dimension_flag));
1829 }
1830
1831
1832 /////////////////////////////////////////////////////////////////////
1833 //
1834 // PrefUserInterface
1835 //
1836 /////////////////////////////////////////////////////////////////////
1837
1838 PrefUserInterface::PrefUserInterface(GuiPreferences * form)
1839         : PrefModule(qt_(catLookAndFeel), qt_("User interface"), form)
1840 {
1841         setupUi(this);
1842
1843         connect(autoSaveCB, SIGNAL(toggled(bool)),
1844                 autoSaveSB, SLOT(setEnabled(bool)));
1845         connect(autoSaveCB, SIGNAL(toggled(bool)),
1846                 TextLabel1, SLOT(setEnabled(bool)));
1847         connect(openDocumentsInTabsCB, SIGNAL(clicked()),
1848                 this, SIGNAL(changed()));
1849         connect(uiFilePB, SIGNAL(clicked()),
1850                 this, SLOT(select_ui()));
1851         connect(uiFileED, SIGNAL(textChanged(QString)),
1852                 this, SIGNAL(changed()));
1853         connect(restoreCursorCB, SIGNAL(clicked()),
1854                 this, SIGNAL(changed()));
1855         connect(loadSessionCB, SIGNAL(clicked()),
1856                 this, SIGNAL(changed()));
1857         connect(allowGeometrySessionCB, SIGNAL(clicked()),
1858                 this, SIGNAL(changed()));
1859         connect(autoSaveSB, SIGNAL(valueChanged(int)),
1860                 this, SIGNAL(changed()));
1861         connect(autoSaveCB, SIGNAL(clicked()),
1862                 this, SIGNAL(changed()));
1863         connect(lastfilesSB, SIGNAL(valueChanged(int)),
1864                 this, SIGNAL(changed()));
1865         connect(tooltipCB, SIGNAL(toggled(bool)),
1866                 this, SIGNAL(changed()));
1867         lastfilesSB->setMaximum(maxlastfiles);
1868 }
1869
1870
1871 void PrefUserInterface::apply(LyXRC & rc) const
1872 {
1873         rc.ui_file = internal_path(fromqstr(uiFileED->text()));
1874         rc.use_lastfilepos = restoreCursorCB->isChecked();
1875         rc.load_session = loadSessionCB->isChecked();
1876         rc.allow_geometry_session = allowGeometrySessionCB->isChecked();
1877         rc.autosave = autoSaveSB->value() * 60;
1878         rc.make_backup = autoSaveCB->isChecked();
1879         rc.num_lastfiles = lastfilesSB->value();
1880         rc.use_tooltip = tooltipCB->isChecked();
1881         rc.open_buffers_in_tabs = openDocumentsInTabsCB->isChecked();
1882 }
1883
1884
1885 void PrefUserInterface::update(LyXRC const & rc)
1886 {
1887         uiFileED->setText(toqstr(external_path(rc.ui_file)));
1888         restoreCursorCB->setChecked(rc.use_lastfilepos);
1889         loadSessionCB->setChecked(rc.load_session);
1890         allowGeometrySessionCB->setChecked(rc.allow_geometry_session);
1891         // convert to minutes
1892         int mins(rc.autosave / 60);
1893         if (rc.autosave && !mins)
1894                 mins = 1;
1895         autoSaveSB->setValue(mins);
1896         autoSaveCB->setChecked(rc.make_backup);
1897         lastfilesSB->setValue(rc.num_lastfiles);
1898         tooltipCB->setChecked(rc.use_tooltip);
1899         openDocumentsInTabsCB->setChecked(rc.open_buffers_in_tabs);
1900 }
1901
1902
1903 void PrefUserInterface::select_ui()
1904 {
1905         QString file = form_->browseUI(internalPath(uiFileED->text()));
1906         if (!file.isEmpty())
1907                 uiFileED->setText(file);
1908 }
1909
1910
1911 void PrefUserInterface::on_clearSessionPB_clicked()
1912 {
1913         guiApp->clearSession();
1914 }
1915
1916
1917
1918 /////////////////////////////////////////////////////////////////////
1919 //
1920 // PrefEdit
1921 //
1922 /////////////////////////////////////////////////////////////////////
1923
1924 PrefEdit::PrefEdit(GuiPreferences * form)
1925         : PrefModule(qt_(catEditing), qt_("Control"), form)
1926 {
1927         setupUi(this);
1928
1929         connect(cursorFollowsCB, SIGNAL(clicked()),
1930                 this, SIGNAL(changed()));
1931         connect(sortEnvironmentsCB, SIGNAL(clicked()),
1932                 this, SIGNAL(changed()));
1933         connect(groupEnvironmentsCB, SIGNAL(clicked()),
1934                 this, SIGNAL(changed()));
1935         connect(macroEditStyleCO, SIGNAL(activated(int)),
1936                 this, SIGNAL(changed()));
1937         connect(fullscreenLimitGB, SIGNAL(clicked()),
1938                 this, SIGNAL(changed()));
1939         connect(fullscreenWidthSB, SIGNAL(valueChanged(int)),
1940                 this, SIGNAL(changed()));
1941         connect(toggleTabbarCB, SIGNAL(toggled(bool)),
1942                 this, SIGNAL(changed()));
1943         connect(toggleScrollbarCB, SIGNAL(toggled(bool)),
1944                 this, SIGNAL(changed()));
1945         connect(toggleToolbarsCB, SIGNAL(toggled(bool)),
1946                 this, SIGNAL(changed()));
1947 }
1948
1949
1950 void PrefEdit::apply(LyXRC & rc) const
1951 {
1952         rc.cursor_follows_scrollbar = cursorFollowsCB->isChecked();
1953         rc.sort_layouts = sortEnvironmentsCB->isChecked();
1954         rc.group_layouts = groupEnvironmentsCB->isChecked();
1955         switch (macroEditStyleCO->currentIndex()) {
1956                 case 0: rc.macro_edit_style = LyXRC::MACRO_EDIT_INLINE_BOX; break;
1957                 case 1: rc.macro_edit_style = LyXRC::MACRO_EDIT_INLINE; break;
1958                 case 2: rc.macro_edit_style = LyXRC::MACRO_EDIT_LIST;   break;
1959         }
1960         rc.full_screen_toolbars = toggleToolbarsCB->isChecked();
1961         rc.full_screen_scrollbar = toggleScrollbarCB->isChecked();
1962         rc.full_screen_tabbar = toggleTabbarCB->isChecked();
1963         rc.full_screen_width = fullscreenWidthSB->value();
1964         rc.full_screen_limit = fullscreenLimitGB->isChecked();
1965 }
1966
1967
1968 void PrefEdit::update(LyXRC const & rc)
1969 {
1970         cursorFollowsCB->setChecked(rc.cursor_follows_scrollbar);
1971         sortEnvironmentsCB->setChecked(rc.sort_layouts);
1972         groupEnvironmentsCB->setChecked(rc.group_layouts);
1973         macroEditStyleCO->setCurrentIndex(rc.macro_edit_style);
1974         toggleScrollbarCB->setChecked(rc.full_screen_scrollbar);
1975         toggleToolbarsCB->setChecked(rc.full_screen_toolbars);
1976         toggleTabbarCB->setChecked(rc.full_screen_tabbar);
1977         fullscreenWidthSB->setValue(rc.full_screen_width);
1978         fullscreenLimitGB->setChecked(rc.full_screen_limit);
1979 }
1980
1981
1982 /////////////////////////////////////////////////////////////////////
1983 //
1984 // PrefShortcuts
1985 //
1986 /////////////////////////////////////////////////////////////////////
1987
1988
1989 GuiShortcutDialog::GuiShortcutDialog(QWidget * parent) : QDialog(parent)
1990 {
1991         Ui::shortcutUi::setupUi(this);
1992         QDialog::setModal(true);
1993 }
1994
1995
1996 PrefShortcuts::PrefShortcuts(GuiPreferences * form)
1997         : PrefModule(qt_(catEditing), qt_("Shortcuts"), form)
1998 {
1999         setupUi(this);
2000
2001         shortcutsTW->setColumnCount(2);
2002         shortcutsTW->headerItem()->setText(0, qt_("Function"));
2003         shortcutsTW->headerItem()->setText(1, qt_("Shortcut"));
2004         shortcutsTW->setSortingEnabled(true);
2005         // Multi-selection can be annoying.
2006         // shortcutsTW->setSelectionMode(QAbstractItemView::MultiSelection);
2007
2008         connect(bindFilePB, SIGNAL(clicked()),
2009                 this, SLOT(select_bind()));
2010         connect(bindFileED, SIGNAL(textChanged(QString)),
2011                 this, SIGNAL(changed()));
2012         connect(removePB, SIGNAL(clicked()),
2013                 this, SIGNAL(changed()));
2014
2015         shortcut_ = new GuiShortcutDialog(this);
2016         shortcut_bc_.setPolicy(ButtonPolicy::OkCancelPolicy);
2017         shortcut_bc_.setOK(shortcut_->okPB);
2018         shortcut_bc_.setCancel(shortcut_->cancelPB);
2019
2020         connect(shortcut_->okPB, SIGNAL(clicked()),
2021                 shortcut_, SLOT(accept()));
2022         connect(shortcut_->okPB, SIGNAL(clicked()),
2023                 this, SIGNAL(changed()));
2024         connect(shortcut_->cancelPB, SIGNAL(clicked()),
2025                 shortcut_, SLOT(reject()));
2026         connect(shortcut_->clearPB, SIGNAL(clicked()),
2027                 this, SLOT(shortcut_clearPB_pressed()));
2028         connect(shortcut_->removePB, SIGNAL(clicked()),
2029                 this, SLOT(shortcut_removePB_pressed()));
2030         connect(shortcut_->okPB, SIGNAL(clicked()),
2031                 this, SLOT(shortcut_okPB_pressed()));
2032         connect(shortcut_->cancelPB, SIGNAL(clicked()),
2033                 this, SLOT(shortcut_cancelPB_pressed()));
2034 }
2035
2036
2037 void PrefShortcuts::apply(LyXRC & rc) const
2038 {
2039         rc.bind_file = internal_path(fromqstr(bindFileED->text()));
2040         // write user_bind and user_unbind to .lyx/bind/user.bind
2041         FileName bind_dir(addPath(package().user_support().absFilename(), "bind"));
2042         if (!bind_dir.exists() && !bind_dir.createDirectory(0777)) {
2043                 lyxerr << "LyX could not create the user bind directory '"
2044                        << bind_dir << "'. All user-defined key bindings will be lost." << endl;
2045                 return;
2046         }
2047         if (!bind_dir.isDirWritable()) {
2048                 lyxerr << "LyX could not write to the user bind directory '"
2049                        << bind_dir << "'. All user-defined key bindings will be lost." << endl;
2050                 return;
2051         }
2052         FileName user_bind_file(bind_dir.absFilename() + "/user.bind");
2053         user_bind_.write(user_bind_file.toFilesystemEncoding(), false, false);
2054         user_unbind_.write(user_bind_file.toFilesystemEncoding(), true, true);
2055         // immediately apply the keybindings. Why this is not done before?
2056         // The good thing is that the menus are updated automatically.
2057         theTopLevelKeymap().clear();
2058         theTopLevelKeymap().read("site");
2059         theTopLevelKeymap().read(rc.bind_file);
2060         theTopLevelKeymap().read("user");
2061 }
2062
2063
2064 void PrefShortcuts::update(LyXRC const & rc)
2065 {
2066         bindFileED->setText(toqstr(external_path(rc.bind_file)));
2067         //
2068         system_bind_.clear();
2069         user_bind_.clear();
2070         user_unbind_.clear();
2071         system_bind_.read("site");
2072         system_bind_.read(rc.bind_file);
2073         // \unbind in user.bind is added to user_unbind_
2074         user_bind_.read("user", &user_unbind_);
2075         updateShortcutsTW();
2076 }
2077
2078
2079 void PrefShortcuts::updateShortcutsTW()
2080 {
2081         shortcutsTW->clear();
2082
2083         editItem_ = new QTreeWidgetItem(shortcutsTW);
2084         editItem_->setText(0, qt_("Cursor, Mouse and Editing functions"));
2085         editItem_->setFlags(editItem_->flags() & ~Qt::ItemIsSelectable);
2086
2087         mathItem_ = new QTreeWidgetItem(shortcutsTW);
2088         mathItem_->setText(0, qt_("Mathematical Symbols"));
2089         mathItem_->setFlags(mathItem_->flags() & ~Qt::ItemIsSelectable);
2090
2091         bufferItem_ = new QTreeWidgetItem(shortcutsTW);
2092         bufferItem_->setText(0, qt_("Document and Window"));
2093         bufferItem_->setFlags(bufferItem_->flags() & ~Qt::ItemIsSelectable);
2094
2095         layoutItem_ = new QTreeWidgetItem(shortcutsTW);
2096         layoutItem_->setText(0, qt_("Font, Layouts and Textclasses"));
2097         layoutItem_->setFlags(layoutItem_->flags() & ~Qt::ItemIsSelectable);
2098
2099         systemItem_ = new QTreeWidgetItem(shortcutsTW);
2100         systemItem_->setText(0, qt_("System and Miscellaneous"));
2101         systemItem_->setFlags(systemItem_->flags() & ~Qt::ItemIsSelectable);
2102
2103         // listBindings(unbound=true) lists all bound and unbound lfuns
2104         // Items in this list is tagged by its source.
2105         KeyMap::BindingList bindinglist = system_bind_.listBindings(true,
2106                 KeyMap::System);
2107         KeyMap::BindingList user_bindinglist = user_bind_.listBindings(false,
2108                 KeyMap::UserBind);
2109         KeyMap::BindingList user_unbindinglist = user_unbind_.listBindings(false,
2110                 KeyMap::UserUnbind);
2111         bindinglist.insert(bindinglist.end(), user_bindinglist.begin(),
2112                         user_bindinglist.end());
2113         bindinglist.insert(bindinglist.end(), user_unbindinglist.begin(),
2114                         user_unbindinglist.end());
2115
2116         KeyMap::BindingList::const_iterator it = bindinglist.begin();
2117         KeyMap::BindingList::const_iterator it_end = bindinglist.end();
2118         for (; it != it_end; ++it)
2119                 insertShortcutItem(it->request, it->sequence, KeyMap::ItemType(it->tag));
2120
2121         shortcutsTW->sortItems(0, Qt::AscendingOrder);
2122         QList<QTreeWidgetItem*> items = shortcutsTW->selectedItems();
2123         removePB->setEnabled(!items.isEmpty() && !items[0]->text(1).isEmpty());
2124         modifyPB->setEnabled(!items.isEmpty());
2125
2126         shortcutsTW->resizeColumnToContents(0);
2127 }
2128
2129
2130 void PrefShortcuts::setItemType(QTreeWidgetItem * item, KeyMap::ItemType tag)
2131 {
2132         item->setData(0, Qt::UserRole, QVariant(tag));
2133         QFont font;
2134
2135         switch (tag) {
2136         case KeyMap::System:
2137                 break;
2138         case KeyMap::UserBind:
2139                 font.setBold(true);
2140                 break;
2141         case KeyMap::UserUnbind:
2142                 font.setStrikeOut(true);
2143                 break;
2144         // this item is not displayed now.
2145         case KeyMap::UserExtraUnbind:
2146                 font.setStrikeOut(true);
2147                 break;
2148         }
2149
2150         item->setFont(1, font);
2151 }
2152
2153
2154 QTreeWidgetItem * PrefShortcuts::insertShortcutItem(FuncRequest const & lfun,
2155                 KeySequence const & seq, KeyMap::ItemType tag)
2156 {
2157         FuncCode action = lfun.action;
2158         string const action_name = lyxaction.getActionName(action);
2159         QString const lfun_name = toqstr(from_utf8(action_name)
2160                         + ' ' + lfun.argument());
2161         QString const shortcut = toqstr(seq.print(KeySequence::ForGui));
2162         KeyMap::ItemType item_tag = tag;
2163
2164         QTreeWidgetItem * newItem = 0;
2165         // for unbind items, try to find an existing item in the system bind list
2166         if (tag == KeyMap::UserUnbind) {
2167                 QList<QTreeWidgetItem*> const items = shortcutsTW->findItems(lfun_name,
2168                         Qt::MatchFlags(Qt::MatchExactly | Qt::MatchRecursive), 0);
2169                 for (int i = 0; i < items.size(); ++i) {
2170                         if (items[i]->text(1) == shortcut)
2171                                 newItem = items[i];
2172                                 break;
2173                         }
2174                 // if not found, this unbind item is KeyMap::UserExtraUnbind
2175                 // Such an item is not displayed to avoid confusion (what is
2176                 // unmatched removed?).
2177                 if (!newItem) {
2178                         item_tag = KeyMap::UserExtraUnbind;
2179                         return 0;
2180                 }
2181         }
2182         if (!newItem) {
2183                 switch(lyxaction.getActionType(action)) {
2184                 case LyXAction::Hidden:
2185                         return 0;
2186                 case LyXAction::Edit:
2187                         newItem = new QTreeWidgetItem(editItem_);
2188                         break;
2189                 case LyXAction::Math:
2190                         newItem = new QTreeWidgetItem(mathItem_);
2191                         break;
2192                 case LyXAction::Buffer:
2193                         newItem = new QTreeWidgetItem(bufferItem_);
2194                         break;
2195                 case LyXAction::Layout:
2196                         newItem = new QTreeWidgetItem(layoutItem_);
2197                         break;
2198                 case LyXAction::System:
2199                         newItem = new QTreeWidgetItem(systemItem_);
2200                         break;
2201                 default:
2202                         // this should not happen
2203                         newItem = new QTreeWidgetItem(shortcutsTW);
2204                 }
2205         }
2206
2207         newItem->setText(0, lfun_name);
2208         newItem->setText(1, shortcut);
2209         // record BindFile representation to recover KeySequence when needed.
2210         newItem->setData(1, Qt::UserRole, toqstr(seq.print(KeySequence::BindFile)));
2211         setItemType(newItem, item_tag);
2212         return newItem;
2213 }
2214
2215
2216 void PrefShortcuts::on_shortcutsTW_itemSelectionChanged()
2217 {
2218         QList<QTreeWidgetItem*> items = shortcutsTW->selectedItems();
2219         removePB->setEnabled(!items.isEmpty() && !items[0]->text(1).isEmpty());
2220         modifyPB->setEnabled(!items.isEmpty());
2221         if (items.isEmpty())
2222                 return;
2223
2224         KeyMap::ItemType tag = 
2225                 static_cast<KeyMap::ItemType>(items[0]->data(0, Qt::UserRole).toInt());
2226         if (tag == KeyMap::UserUnbind)
2227                 removePB->setText(qt_("Res&tore"));
2228         else
2229                 removePB->setText(qt_("Remo&ve"));
2230 }
2231
2232
2233 void PrefShortcuts::on_shortcutsTW_itemDoubleClicked()
2234 {
2235         modifyShortcut();
2236 }
2237
2238
2239 void PrefShortcuts::modifyShortcut()
2240 {
2241         QTreeWidgetItem * item = shortcutsTW->currentItem();
2242         if (item->flags() & Qt::ItemIsSelectable) {
2243                 shortcut_->lfunLE->setText(item->text(0));
2244                 save_lfun_ = item->text(0);
2245                 shortcut_->shortcutWG->setText(item->text(1));
2246                 KeySequence seq;
2247                 seq.parse(fromqstr(item->data(1, Qt::UserRole).toString()));
2248                 shortcut_->shortcutWG->setKeySequence(seq);
2249                 shortcut_->shortcutWG->setFocus();
2250                 shortcut_->exec();
2251         }
2252 }
2253
2254
2255 void PrefShortcuts::removeShortcut()
2256 {
2257         // it seems that only one item can be selected, but I am
2258         // removing all selected items anyway.
2259         QList<QTreeWidgetItem*> items = shortcutsTW->selectedItems();
2260         for (int i = 0; i < items.size(); ++i) {
2261                 string shortcut = fromqstr(items[i]->data(1, Qt::UserRole).toString());
2262                 string lfun = fromqstr(items[i]->text(0));
2263                 FuncRequest func = lyxaction.lookupFunc(lfun);
2264                 KeyMap::ItemType tag = 
2265                         static_cast<KeyMap::ItemType>(items[i]->data(0, Qt::UserRole).toInt());
2266
2267                 switch (tag) {
2268                 case KeyMap::System: {
2269                         // for system bind, we do not touch the item
2270                         // but add an user unbind item
2271                         user_unbind_.bind(shortcut, func);
2272                         setItemType(items[i], KeyMap::UserUnbind);
2273                         removePB->setText(qt_("Res&tore"));
2274                         break;
2275                 }
2276                 case KeyMap::UserBind: {
2277                         // for user_bind, we remove this bind
2278                         QTreeWidgetItem * parent = items[i]->parent();
2279                         int itemIdx = parent->indexOfChild(items[i]);
2280                         parent->takeChild(itemIdx);
2281                         if (itemIdx > 0)
2282                                 shortcutsTW->scrollToItem(parent->child(itemIdx - 1));
2283                         else
2284                                 shortcutsTW->scrollToItem(parent);
2285                         user_bind_.unbind(shortcut, func);
2286                         break;
2287                 }
2288                 case KeyMap::UserUnbind: {
2289                         // for user_unbind, we remove the unbind, and the item
2290                         // become KeyMap::System again.
2291                         user_unbind_.unbind(shortcut, func);
2292                         setItemType(items[i], KeyMap::System);
2293                         removePB->setText(qt_("Remo&ve"));
2294                         break;
2295                 }
2296                 case KeyMap::UserExtraUnbind: {
2297                         // for user unbind that is not in system bind file,
2298                         // remove this unbind file
2299                         QTreeWidgetItem * parent = items[i]->parent();
2300                         parent->takeChild(parent->indexOfChild(items[i]));
2301                         user_unbind_.unbind(shortcut, func);
2302                 }
2303                 }
2304         }
2305 }
2306
2307
2308 void PrefShortcuts::select_bind()
2309 {
2310         QString file = form_->browsebind(internalPath(bindFileED->text()));
2311         if (!file.isEmpty()) {
2312                 bindFileED->setText(file);
2313                 system_bind_ = KeyMap();
2314                 system_bind_.read(fromqstr(file));
2315                 updateShortcutsTW();
2316         }
2317 }
2318
2319
2320 void PrefShortcuts::on_modifyPB_pressed()
2321 {
2322         modifyShortcut();
2323 }
2324
2325
2326 void PrefShortcuts::on_newPB_pressed()
2327 {
2328         shortcut_->lfunLE->clear();
2329         shortcut_->shortcutWG->reset();
2330         save_lfun_ = QString();
2331         shortcut_->exec();
2332 }
2333
2334
2335 void PrefShortcuts::on_removePB_pressed()
2336 {
2337         removeShortcut();
2338 }
2339
2340
2341 void PrefShortcuts::on_searchLE_textEdited()
2342 {
2343         if (searchLE->text().isEmpty()) {
2344                 // show all hidden items
2345                 QTreeWidgetItemIterator it(shortcutsTW, QTreeWidgetItemIterator::Hidden);
2346                 while (*it)
2347                         shortcutsTW->setItemHidden(*it++, false);
2348                 return;
2349         }
2350         // search both columns
2351         QList<QTreeWidgetItem *> matched = shortcutsTW->findItems(searchLE->text(),
2352                 Qt::MatchFlags(Qt::MatchContains | Qt::MatchRecursive), 0);
2353         matched += shortcutsTW->findItems(searchLE->text(),
2354                 Qt::MatchFlags(Qt::MatchContains | Qt::MatchRecursive), 1);
2355
2356         // hide everyone (to avoid searching in matched QList repeatedly
2357         QTreeWidgetItemIterator it(shortcutsTW, QTreeWidgetItemIterator::Selectable);
2358         while (*it)
2359                 shortcutsTW->setItemHidden(*it++, true);
2360         // show matched items
2361         for (int i = 0; i < matched.size(); ++i) {
2362                 shortcutsTW->setItemHidden(matched[i], false);
2363         shortcutsTW->setItemExpanded(matched[i]->parent(), true);
2364         }
2365 }
2366
2367
2368 docstring makeCmdString(FuncRequest const & f)
2369 {
2370         docstring actionStr = from_ascii(lyxaction.getActionName(f.action));
2371         if (!f.argument().empty())
2372                 actionStr += " " + f.argument();
2373         return actionStr;
2374 }
2375
2376
2377 void PrefShortcuts::shortcut_okPB_pressed()
2378 {
2379         QString const new_lfun = shortcut_->lfunLE->text();
2380         FuncRequest func = lyxaction.lookupFunc(fromqstr(new_lfun));
2381
2382         if (func.action == LFUN_UNKNOWN_ACTION) {
2383                 Alert::error(_("Failed to create shortcut"),
2384                         _("Unknown or invalid LyX function"));
2385                 return;
2386         }
2387
2388         KeySequence k = shortcut_->shortcutWG->getKeySequence();
2389         if (k.length() == 0) {
2390                 Alert::error(_("Failed to create shortcut"),
2391                         _("Invalid or empty key sequence"));
2392                 return;
2393         }
2394
2395         // check to see if there's been any change
2396         FuncRequest oldBinding = system_bind_.getBinding(k);
2397         if (oldBinding.action == LFUN_UNKNOWN_ACTION)
2398                 oldBinding = user_bind_.getBinding(k);
2399         if (oldBinding == func) {
2400                 docstring const actionStr = makeCmdString(func);
2401                 Alert::error(_("Failed to create shortcut"),
2402                         bformat(_("Shortcut `%1$s' is already bound to:\n%2$s"), 
2403                         k.print(KeySequence::ForGui), actionStr));
2404                 return;
2405         }
2406         
2407         // make sure this key isn't already bound---and, if so, not unbound
2408         FuncCode const unbind = user_unbind_.getBinding(k).action;
2409         if (oldBinding.action != LFUN_UNKNOWN_ACTION && unbind == LFUN_UNKNOWN_ACTION)
2410         {
2411                 // FIXME Perhaps we should offer to over-write the old shortcut?
2412                 // If so, we'll need to remove it from our list, etc.
2413                 docstring const actionStr = makeCmdString(oldBinding);
2414                 Alert::error(_("Failed to create shortcut"),
2415                         bformat(_("Shortcut `%1$s' is already bound to:\n%2$s\n"
2416                           "You need to remove that binding before creating a new one."), 
2417                         k.print(KeySequence::ForGui), actionStr));
2418                 return;
2419         }
2420
2421         if (!save_lfun_.isEmpty() && new_lfun == save_lfun_)
2422                 // real modification of the lfun's shortcut,
2423                 // so remove the previous one
2424                 removeShortcut();
2425
2426         QTreeWidgetItem * item = insertShortcutItem(func, k, KeyMap::UserBind);
2427         if (item) {
2428                 user_bind_.bind(&k, func);
2429                 shortcutsTW->sortItems(0, Qt::AscendingOrder);
2430                 shortcutsTW->setItemExpanded(item->parent(), true);
2431                 shortcutsTW->scrollToItem(item);
2432         } else {
2433                 Alert::error(_("Failed to create shortcut"),
2434                         _("Can not insert shortcut to the list"));
2435                 return;
2436         }
2437 }
2438
2439
2440 void PrefShortcuts::shortcut_cancelPB_pressed()
2441 {
2442         shortcut_->shortcutWG->reset();
2443 }
2444
2445
2446 void PrefShortcuts::shortcut_clearPB_pressed()
2447 {
2448         shortcut_->shortcutWG->reset();
2449 }
2450
2451
2452 void PrefShortcuts::shortcut_removePB_pressed()
2453 {
2454         shortcut_->shortcutWG->removeFromSequence();
2455 }
2456
2457
2458 /////////////////////////////////////////////////////////////////////
2459 //
2460 // PrefIdentity
2461 //
2462 /////////////////////////////////////////////////////////////////////
2463
2464 PrefIdentity::PrefIdentity(GuiPreferences * form)
2465         : PrefModule(QString(), qt_("Identity"), form)
2466 {
2467         setupUi(this);
2468
2469         connect(nameED, SIGNAL(textChanged(QString)),
2470                 this, SIGNAL(changed()));
2471         connect(emailED, SIGNAL(textChanged(QString)),
2472                 this, SIGNAL(changed()));
2473 }
2474
2475
2476 void PrefIdentity::apply(LyXRC & rc) const
2477 {
2478         rc.user_name = fromqstr(nameED->text());
2479         rc.user_email = fromqstr(emailED->text());
2480 }
2481
2482
2483 void PrefIdentity::update(LyXRC const & rc)
2484 {
2485         nameED->setText(toqstr(rc.user_name));
2486         emailED->setText(toqstr(rc.user_email));
2487 }
2488
2489
2490
2491 /////////////////////////////////////////////////////////////////////
2492 //
2493 // GuiPreferences
2494 //
2495 /////////////////////////////////////////////////////////////////////
2496
2497 GuiPreferences::GuiPreferences(GuiView & lv)
2498         : GuiDialog(lv, "prefs", qt_("Preferences")), update_screen_font_(false)
2499 {
2500         setupUi(this);
2501
2502         QDialog::setModal(false);
2503
2504         connect(savePB, SIGNAL(clicked()), this, SLOT(slotOK()));
2505         connect(applyPB, SIGNAL(clicked()), this, SLOT(slotApply()));
2506         connect(closePB, SIGNAL(clicked()), this, SLOT(slotClose()));
2507         connect(restorePB, SIGNAL(clicked()), this, SLOT(slotRestore()));
2508
2509         addModule(new PrefUserInterface(this));
2510         addModule(new PrefEdit(this));
2511         addModule(new PrefShortcuts(this));
2512         addModule(new PrefScreenFonts(this));
2513         addModule(new PrefColors(this));
2514         addModule(new PrefDisplay(this));
2515         addModule(new PrefInput(this));
2516         addModule(new PrefCompletion(this));
2517
2518         addModule(new PrefPaths(this));
2519
2520         addModule(new PrefIdentity(this));
2521
2522         addModule(new PrefLanguage(this));
2523         addModule(new PrefSpellchecker(this));
2524
2525         addModule(new PrefPrinter(this));
2526         addModule(new PrefDate(this));
2527         addModule(new PrefPlaintext(this));
2528         addModule(new PrefLatex(this));
2529
2530         PrefConverters * converters = new PrefConverters(this);
2531         PrefFileformats * formats = new PrefFileformats(this);
2532         connect(formats, SIGNAL(formatsChanged()),
2533                         converters, SLOT(updateGui()));
2534         addModule(converters);
2535         addModule(formats);
2536
2537         prefsPS->setCurrentPanel(qt_("User interface"));
2538 // FIXME: hack to work around resizing bug in Qt >= 4.2
2539 // bug verified with Qt 4.2.{0-3} (JSpitzm)
2540 #if QT_VERSION >= 0x040200
2541         prefsPS->updateGeometry();
2542 #endif
2543
2544         bc().setPolicy(ButtonPolicy::PreferencesPolicy);
2545         bc().setOK(savePB);
2546         bc().setApply(applyPB);
2547         bc().setCancel(closePB);
2548         bc().setRestore(restorePB);
2549 }
2550
2551
2552 void GuiPreferences::addModule(PrefModule * module)
2553 {
2554         LASSERT(module, return);
2555         if (module->category().isEmpty())
2556                 prefsPS->addPanel(module, module->title());
2557         else
2558                 prefsPS->addPanel(module, module->title(), module->category());
2559         connect(module, SIGNAL(changed()), this, SLOT(change_adaptor()));
2560         modules_.push_back(module);
2561 }
2562
2563
2564 void GuiPreferences::change_adaptor()
2565 {
2566         changed();
2567 }
2568
2569
2570 void GuiPreferences::apply(LyXRC & rc) const
2571 {
2572         size_t end = modules_.size();
2573         for (size_t i = 0; i != end; ++i)
2574                 modules_[i]->apply(rc);
2575 }
2576
2577
2578 void GuiPreferences::updateRc(LyXRC const & rc)
2579 {
2580         size_t const end = modules_.size();
2581         for (size_t i = 0; i != end; ++i)
2582                 modules_[i]->update(rc);
2583 }
2584
2585
2586 void GuiPreferences::applyView()
2587 {
2588         apply(rc());
2589 }
2590
2591 bool GuiPreferences::initialiseParams(string const &)
2592 {
2593         rc_ = lyxrc;
2594         formats_ = lyx::formats;
2595         converters_ = theConverters();
2596         converters_.update(formats_);
2597         movers_ = theMovers();
2598         colors_.clear();
2599         update_screen_font_ = false;
2600         updateRc(rc_);
2601
2602         return true;
2603 }
2604
2605
2606 void GuiPreferences::dispatchParams()
2607 {
2608         ostringstream ss;
2609         rc_.write(ss, true);
2610         dispatch(FuncRequest(LFUN_LYXRC_APPLY, ss.str()));
2611         // FIXME: these need lfuns
2612         // FIXME UNICODE
2613         theBufferList().setCurrentAuthor(from_utf8(rc_.user_name), from_utf8(rc_.user_email));
2614
2615         lyx::formats = formats_;
2616
2617         theConverters() = converters_;
2618         theConverters().update(lyx::formats);
2619         theConverters().buildGraph();
2620
2621         theMovers() = movers_;
2622
2623         vector<string>::const_iterator it = colors_.begin();
2624         vector<string>::const_iterator const end = colors_.end();
2625         for (; it != end; ++it)
2626                 dispatch(FuncRequest(LFUN_SET_COLOR, *it));
2627         colors_.clear();
2628
2629         if (update_screen_font_) {
2630                 dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2631                 update_screen_font_ = false;
2632         }
2633
2634         // The Save button has been pressed
2635         if (isClosing())
2636                 dispatch(FuncRequest(LFUN_PREFERENCES_SAVE));
2637 }
2638
2639
2640 void GuiPreferences::setColor(ColorCode col, QString const & hex)
2641 {
2642         colors_.push_back(lcolor.getLyXName(col) + ' ' + fromqstr(hex));
2643 }
2644
2645
2646 void GuiPreferences::updateScreenFonts()
2647 {
2648         update_screen_font_ = true;
2649 }
2650
2651
2652 QString GuiPreferences::browsebind(QString const & file) const
2653 {
2654         return browseLibFile("bind", file, "bind", qt_("Choose bind file"),
2655                              QStringList(qt_("LyX bind files (*.bind)")));
2656 }
2657
2658
2659 QString GuiPreferences::browseUI(QString const & file) const
2660 {
2661         return browseLibFile("ui", file, "ui", qt_("Choose UI file"),
2662                              QStringList(qt_("LyX UI files (*.ui)")));
2663 }
2664
2665
2666 QString GuiPreferences::browsekbmap(QString const & file) const
2667 {
2668         return browseLibFile("kbd", file, "kmap", qt_("Choose keyboard map"),
2669                              QStringList(qt_("LyX keyboard maps (*.kmap)")));
2670 }
2671
2672
2673 QString GuiPreferences::browsedict(QString const & file) const
2674 {
2675         return browseFile(file, qt_("Choose personal dictionary"),
2676                 QStringList(qt_("*.pws")));
2677 }
2678
2679
2680 QString GuiPreferences::browse(QString const & file,
2681         QString const & title) const
2682 {
2683         return browseFile(file, title, QStringList(), true);
2684 }
2685
2686
2687 // We support less paper sizes than the document dialog
2688 // Therefore this adjustment is needed.
2689 PAPER_SIZE GuiPreferences::toPaperSize(int i) const
2690 {
2691         switch (i) {
2692         case 0:
2693                 return PAPER_DEFAULT;
2694         case 1:
2695                 return PAPER_USLETTER;
2696         case 2:
2697                 return PAPER_USLEGAL;
2698         case 3:
2699                 return PAPER_USEXECUTIVE;
2700         case 4:
2701                 return PAPER_A3;
2702         case 5:
2703                 return PAPER_A4;
2704         case 6:
2705                 return PAPER_A5;
2706         case 7:
2707                 return PAPER_B5;
2708         default:
2709                 // should not happen
2710                 return PAPER_DEFAULT;
2711         }
2712 }
2713
2714
2715 int GuiPreferences::fromPaperSize(PAPER_SIZE papersize) const
2716 {
2717         switch (papersize) {
2718         case PAPER_DEFAULT:
2719                 return 0;
2720         case PAPER_USLETTER:
2721                 return 1;
2722         case PAPER_USLEGAL:
2723                 return 2;
2724         case PAPER_USEXECUTIVE:
2725                 return 3;
2726         case PAPER_A3:
2727                 return 4;
2728         case PAPER_A4:
2729                 return 5;
2730         case PAPER_A5:
2731                 return 6;
2732         case PAPER_B5:
2733                 return 7;
2734         default:
2735                 // should not happen
2736                 return 0;
2737         }
2738 }
2739
2740
2741 Dialog * createGuiPreferences(GuiView & lv) { return new GuiPreferences(lv); }
2742
2743
2744 } // namespace frontend
2745 } // namespace lyx
2746
2747 #include "moc_GuiPrefs.cpp"