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