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