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