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