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