]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiPrefs.cpp
Fix the last clang warnings about overloaded virtual methods
[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 #include "Validator.h"
24
25 #include "Author.h"
26 #include "BufferList.h"
27 #include "Color.h"
28 #include "ColorSet.h"
29 #include "ConverterCache.h"
30 #include "FontEnums.h"
31 #include "FuncRequest.h"
32 #include "KeyMap.h"
33 #include "KeySequence.h"
34 #include "Language.h"
35 #include "LyXAction.h"
36 #include "LyX.h"
37 #include "PanelStack.h"
38 #include "paper.h"
39 #include "Session.h"
40 #include "SpellChecker.h"
41
42 #include "support/debug.h"
43 #include "support/FileName.h"
44 #include "support/filetools.h"
45 #include "support/foreach.h"
46 #include "support/gettext.h"
47 #include "support/lassert.h"
48 #include "support/lstrings.h"
49 #include "support/Messages.h"
50 #include "support/os.h"
51 #include "support/Package.h"
52
53 #include "graphics/GraphicsTypes.h"
54
55 #include "frontends/alert.h"
56 #include "frontends/Application.h"
57 #include "frontends/FontLoader.h"
58
59 #include <QAbstractItemModel>
60 #include <QCheckBox>
61 #include <QColorDialog>
62 #include <QFontDatabase>
63 #include <QHeaderView>
64 #include <QLineEdit>
65 #include <QMessageBox>
66 #include <QPixmapCache>
67 #include <QPushButton>
68 #include <QSpinBox>
69 #include <QString>
70 #include <QTreeWidget>
71 #include <QTreeWidgetItem>
72 #include <QValidator>
73
74 #include <iomanip>
75 #include <sstream>
76 #include <algorithm>
77
78 using namespace Ui;
79
80 using namespace std;
81 using namespace lyx::support;
82 using namespace lyx::support::os;
83
84 namespace lyx {
85 namespace frontend {
86
87 /////////////////////////////////////////////////////////////////////
88 //
89 // Browser Helpers
90 //
91 /////////////////////////////////////////////////////////////////////
92
93 /** Launch a file dialog and return the chosen file.
94         filename: a suggested filename.
95         title: the title of the dialog.
96         filters: *.ps etc.
97         dir1 = (name, dir), dir2 = (name, dir): extra buttons on the dialog.
98 */
99 QString browseFile(QString const & filename,
100         QString const & title,
101         QStringList const & filters,
102         bool save = false,
103         QString const & label1 = QString(),
104         QString const & dir1 = QString(),
105         QString const & label2 = QString(),
106         QString const & dir2 = QString(),
107         QString const & fallback_dir = QString())
108 {
109         QString lastPath = ".";
110         if (!filename.isEmpty())
111                 lastPath = onlyPath(filename);
112         else if(!fallback_dir.isEmpty())
113                 lastPath = fallback_dir;
114
115         FileDialog dlg(title);
116         dlg.setButton2(label1, dir1);
117         dlg.setButton2(label2, dir2);
118
119         FileDialog::Result result;
120
121         if (save)
122                 result = dlg.save(lastPath, filters, onlyFileName(filename));
123         else
124                 result = dlg.open(lastPath, filters, onlyFileName(filename));
125
126         return result.second;
127 }
128
129
130 /** Wrapper around browseFile which tries to provide a filename
131 *  relative to the user or system directory. The dir, name and ext
132 *  parameters have the same meaning as in the
133 *  support::LibFileSearch function.
134 */
135 QString browseLibFile(QString const & dir,
136         QString const & name,
137         QString const & ext,
138         QString const & title,
139         QStringList const & filters)
140 {
141         // FIXME UNICODE
142         QString const label1 = qt_("System files|#S#s");
143         QString const dir1 =
144                 toqstr(addName(package().system_support().absFileName(), fromqstr(dir)));
145
146         QString const label2 = qt_("User files|#U#u");
147         QString const dir2 =
148                 toqstr(addName(package().user_support().absFileName(), fromqstr(dir)));
149
150         QString const result = browseFile(toqstr(
151                 libFileSearch(dir, name, ext).absFileName()),
152                 title, filters, false, dir1, dir2, QString(), QString(), dir1);
153
154         // remove the extension if it is the default one
155         QString noextresult;
156         if (getExtension(result) == ext)
157                 noextresult = removeExtension(result);
158         else
159                 noextresult = result;
160
161         // remove the directory, if it is the default one
162         QString const file = onlyFileName(noextresult);
163         if (toqstr(libFileSearch(dir, file, ext).absFileName()) == result)
164                 return file;
165         else
166                 return noextresult;
167 }
168
169
170 /** Launch a file dialog and return the chosen directory.
171         pathname: a suggested pathname.
172         title: the title of the dialog.
173         dir1 = (name, dir), dir2 = (name, dir): extra buttons on the dialog.
174 */
175 QString browseDir(QString const & pathname,
176         QString const & title,
177         QString const & label1 = QString(),
178         QString const & dir1 = QString(),
179         QString const & label2 = QString(),
180         QString const & dir2 = QString())
181 {
182         QString lastPath = ".";
183         if (!pathname.isEmpty())
184                 lastPath = onlyPath(pathname);
185
186         FileDialog dlg(title);
187         dlg.setButton1(label1, dir1);
188         dlg.setButton2(label2, dir2);
189
190         FileDialog::Result const result =
191                 dlg.opendir(lastPath, onlyFileName(pathname));
192
193         return result.second;
194 }
195
196
197 } // namespace frontend
198
199
200 QString browseRelToParent(QString const & filename, QString const & relpath,
201         QString const & title, QStringList const & filters, bool save,
202         QString const & label1, QString const & dir1,
203         QString const & label2, QString const & dir2)
204 {
205         QString const fname = makeAbsPath(filename, relpath);
206
207         QString const outname =
208                 frontend::browseFile(fname, title, filters, save, label1, dir1, label2, dir2);
209
210         QString const reloutname =
211                 toqstr(makeRelPath(qstring_to_ucs4(outname), qstring_to_ucs4(relpath)));
212
213         if (reloutname.startsWith("../"))
214                 return outname;
215         else
216                 return reloutname;
217 }
218
219
220 QString browseRelToSub(QString const & filename, QString const & relpath,
221         QString const & title, QStringList const & filters, bool save,
222         QString const & label1, QString const & dir1,
223         QString const & label2, QString const & dir2)
224 {
225         QString const fname = makeAbsPath(filename, relpath);
226
227         QString const outname =
228                 frontend::browseFile(fname, title, filters, save, label1, dir1, label2, dir2);
229
230         QString const reloutname =
231                 toqstr(makeRelPath(qstring_to_ucs4(outname), qstring_to_ucs4(relpath)));
232
233         QString testname = reloutname;
234         testname.remove(QRegExp("^(\\.\\./)+"));
235
236         if (testname.contains("/"))
237                 return outname;
238         else
239                 return reloutname;
240 }
241
242
243
244 /////////////////////////////////////////////////////////////////////
245 //
246 // Helpers
247 //
248 /////////////////////////////////////////////////////////////////////
249
250 namespace frontend {
251
252 QString const catLookAndFeel = N_("Look & Feel");
253 QString const catEditing = N_("Editing");
254 QString const catLanguage = N_("Language Settings");
255 QString const catOutput = N_("Output");
256 QString const catFiles = N_("File Handling");
257
258 static void parseFontName(QString const & mangled0,
259         string & name, string & foundry)
260 {
261         string mangled = fromqstr(mangled0);
262         size_t const idx = mangled.find('[');
263         if (idx == string::npos || idx == 0) {
264                 name = mangled;
265                 foundry.clear();
266         } else {
267                 name = mangled.substr(0, idx - 1),
268                 foundry = mangled.substr(idx + 1, mangled.size() - idx - 2);
269         }
270 }
271
272
273 static void setComboxFont(QComboBox * cb, string const & family,
274         string const & foundry)
275 {
276         QString fontname = toqstr(family);
277         if (!foundry.empty())
278                 fontname += " [" + toqstr(foundry) + ']';
279
280         for (int i = 0; i != cb->count(); ++i) {
281                 if (cb->itemText(i) == fontname) {
282                         cb->setCurrentIndex(i);
283                         return;
284                 }
285         }
286
287         // Try matching without foundry name
288
289         // We count in reverse in order to prefer the Xft foundry
290         for (int i = cb->count(); --i >= 0;) {
291                 string name, foundry;
292                 parseFontName(cb->itemText(i), name, foundry);
293                 if (compare_ascii_no_case(name, family) == 0) {
294                         cb->setCurrentIndex(i);
295                         return;
296                 }
297         }
298
299         // family alone can contain e.g. "Helvetica [Adobe]"
300         string tmpname, tmpfoundry;
301         parseFontName(toqstr(family), tmpname, tmpfoundry);
302
303         // We count in reverse in order to prefer the Xft foundry
304         for (int i = cb->count(); --i >= 0; ) {
305                 string name, foundry;
306                 parseFontName(cb->itemText(i), name, foundry);
307                 if (compare_ascii_no_case(name, foundry) == 0) {
308                         cb->setCurrentIndex(i);
309                         return;
310                 }
311         }
312
313         // Bleh, default fonts, and the names couldn't be found. Hack
314         // for bug 1063.
315
316         QFont font;
317
318         QString const font_family = toqstr(family);
319         if (font_family == guiApp->romanFontName()) {
320                 font.setStyleHint(QFont::Serif);
321                 font.setFamily(font_family);
322         } else if (font_family == guiApp->sansFontName()) {
323                 font.setStyleHint(QFont::SansSerif);
324                 font.setFamily(font_family);
325         } else if (font_family == guiApp->typewriterFontName()) {
326                 font.setStyleHint(QFont::TypeWriter);
327                 font.setFamily(font_family);
328         } else {
329                 LYXERR0("FAILED to find the default font: '"
330                        << foundry << "', '" << family << '\'');
331                 return;
332         }
333
334         QFontInfo info(font);
335         string default_font_name, dummyfoundry;
336         parseFontName(info.family(), default_font_name, dummyfoundry);
337         LYXERR0("Apparent font is " << default_font_name);
338
339         for (int i = 0; i < cb->count(); ++i) {
340                 LYXERR0("Looking at " << cb->itemText(i));
341                 if (compare_ascii_no_case(fromqstr(cb->itemText(i)),
342                                     default_font_name) == 0) {
343                         cb->setCurrentIndex(i);
344                         return;
345                 }
346         }
347
348         LYXERR0("FAILED to find the font: '"
349                << foundry << "', '" << family << '\'');
350 }
351
352
353 /////////////////////////////////////////////////////////////////////
354 //
355 // StrftimeValidator
356 //
357 /////////////////////////////////////////////////////////////////////
358
359 class StrftimeValidator : public QValidator
360 {
361 public:
362         StrftimeValidator(QWidget *);
363         QValidator::State validate(QString & input, int & pos) const;
364 };
365
366
367 StrftimeValidator::StrftimeValidator(QWidget * parent)
368         : QValidator(parent)
369 {
370 }
371
372
373 QValidator::State StrftimeValidator::validate(QString & input, int & /*pos*/) const
374 {
375         if (is_valid_strftime(fromqstr(input)))
376                 return QValidator::Acceptable;
377         else
378                 return QValidator::Intermediate;
379 }
380
381
382 /////////////////////////////////////////////////////////////////////
383 //
384 // PrefOutput
385 //
386 /////////////////////////////////////////////////////////////////////
387
388 PrefOutput::PrefOutput(GuiPreferences * form)
389         : PrefModule(catOutput, N_("General"), form)
390 {
391         setupUi(this);
392
393         DateED->setValidator(new StrftimeValidator(DateED));
394         dviCB->setValidator(new NoNewLineValidator(dviCB));
395         pdfCB->setValidator(new NoNewLineValidator(pdfCB));
396
397         connect(DateED, SIGNAL(textChanged(QString)),
398                 this, SIGNAL(changed()));
399         connect(plaintextLinelengthSB, SIGNAL(valueChanged(int)),
400                 this, SIGNAL(changed()));
401         connect(overwriteCO, SIGNAL(activated(int)),
402                 this, SIGNAL(changed()));
403         connect(dviCB, SIGNAL(editTextChanged(QString)),
404                 this, SIGNAL(changed()));
405         connect(pdfCB, SIGNAL(editTextChanged(QString)),
406                 this, SIGNAL(changed()));
407         dviCB->addItem("");
408         dviCB->addItem("xdvi -sourceposition '$$n:\\ $$t' $$o");
409         dviCB->addItem("yap -1 -s \"$$n $$t\" $$o");
410         dviCB->addItem("okular --unique \"$$o#src:$$n $$f\"");
411         dviCB->addItem("synctex view -i $$n:0:$$t -o $$o -x \"evince -i %{page+1} $$o\"");
412         pdfCB->addItem("");
413         pdfCB->addItem("CMCDDE SUMATRA control [ForwardSearch(\\\"$$o\\\",\\\"$$t\\\",$$n,0,0,1)]");
414         pdfCB->addItem("SumatraPDF -reuse-instance $$o -forward-search $$t $$n");
415         pdfCB->addItem("synctex view -i $$n:0:$$t -o $$o -x \"xpdf -raise -remote $$t.tmp $$o %{page+1}\"");
416         pdfCB->addItem("okular --unique \"$$o#src:$$n $$f\"");
417         pdfCB->addItem("qpdfview --unique \"$$o#src:$$f:$$n:0\"");
418         pdfCB->addItem("synctex view -i $$n:0:$$t -o $$o -x \"evince -i %{page+1} $$o\"");
419         pdfCB->addItem("/Applications/Skim.app/Contents/SharedSupport/displayline $$n $$o $$t");
420 }
421
422
423 void PrefOutput::on_DateED_textChanged(const QString &)
424 {
425         QString t = DateED->text();
426         int p = 0;
427         bool valid = DateED->validator()->validate(t, p)
428                      == QValidator::Acceptable;
429         setValid(DateLA, valid);
430 }
431
432
433 void PrefOutput::applyRC(LyXRC & rc) const
434 {
435         rc.date_insert_format = fromqstr(DateED->text());
436         rc.plaintext_linelen = plaintextLinelengthSB->value();
437         rc.forward_search_dvi = fromqstr(dviCB->currentText());
438         rc.forward_search_pdf = fromqstr(pdfCB->currentText());
439
440         switch (overwriteCO->currentIndex()) {
441         case 0:
442                 rc.export_overwrite = NO_FILES;
443                 break;
444         case 1:
445                 rc.export_overwrite = MAIN_FILE;
446                 break;
447         case 2:
448                 rc.export_overwrite = ALL_FILES;
449                 break;
450         }
451 }
452
453
454 void PrefOutput::updateRC(LyXRC const & rc)
455 {
456         DateED->setText(toqstr(rc.date_insert_format));
457         plaintextLinelengthSB->setValue(rc.plaintext_linelen);
458         dviCB->setEditText(toqstr(rc.forward_search_dvi));
459         pdfCB->setEditText(toqstr(rc.forward_search_pdf));
460
461         switch (rc.export_overwrite) {
462         case NO_FILES:
463                 overwriteCO->setCurrentIndex(0);
464                 break;
465         case MAIN_FILE:
466                 overwriteCO->setCurrentIndex(1);
467                 break;
468         case ALL_FILES:
469                 overwriteCO->setCurrentIndex(2);
470                 break;
471         }
472 }
473
474
475 /////////////////////////////////////////////////////////////////////
476 //
477 // PrefInput
478 //
479 /////////////////////////////////////////////////////////////////////
480
481 PrefInput::PrefInput(GuiPreferences * form)
482         : PrefModule(catEditing, N_("Keyboard/Mouse"), form)
483 {
484         setupUi(this);
485
486         connect(keymapCB, SIGNAL(clicked()),
487                 this, SIGNAL(changed()));
488         connect(firstKeymapED, SIGNAL(textChanged(QString)),
489                 this, SIGNAL(changed()));
490         connect(secondKeymapED, SIGNAL(textChanged(QString)),
491                 this, SIGNAL(changed()));
492         connect(mouseWheelSpeedSB, SIGNAL(valueChanged(double)),
493                 this, SIGNAL(changed()));
494         connect(scrollzoomEnableCB, SIGNAL(clicked()),
495                 this, SIGNAL(changed()));
496         connect(scrollzoomValueCO, SIGNAL(activated(int)),
497                 this, SIGNAL(changed()));
498         connect(dontswapCB, SIGNAL(toggled(bool)),
499                 this, SIGNAL(changed()));
500
501         // reveal checkbox for switching Ctrl and Meta on Mac:
502         bool swapcb = false;
503 #ifdef Q_OS_MAC
504 #if QT_VERSION > 0x040600
505         swapcb = true;
506 #endif
507 #endif
508         dontswapCB->setVisible(swapcb);
509 }
510
511
512 void PrefInput::applyRC(LyXRC & rc) const
513 {
514         // FIXME: can derive CB from the two EDs
515         rc.use_kbmap = keymapCB->isChecked();
516         rc.primary_kbmap = internal_path(fromqstr(firstKeymapED->text()));
517         rc.secondary_kbmap = internal_path(fromqstr(secondKeymapED->text()));
518         rc.mouse_wheel_speed = mouseWheelSpeedSB->value();
519         if (scrollzoomEnableCB->isChecked()) {
520                 switch (scrollzoomValueCO->currentIndex()) {
521                 case 0:
522                         rc.scroll_wheel_zoom = LyXRC::SCROLL_WHEEL_ZOOM_CTRL;
523                         break;
524                 case 1:
525                         rc.scroll_wheel_zoom = LyXRC::SCROLL_WHEEL_ZOOM_SHIFT;
526                         break;
527                 case 2:
528                         rc.scroll_wheel_zoom = LyXRC::SCROLL_WHEEL_ZOOM_ALT;
529                         break;
530                 }
531         } else {
532                 rc.scroll_wheel_zoom = LyXRC::SCROLL_WHEEL_ZOOM_OFF;
533         }
534         rc.mac_dontswap_ctrl_meta  = dontswapCB->isChecked();
535 }
536
537
538 void PrefInput::updateRC(LyXRC const & rc)
539 {
540         // FIXME: can derive CB from the two EDs
541         keymapCB->setChecked(rc.use_kbmap);
542         firstKeymapED->setText(toqstr(external_path(rc.primary_kbmap)));
543         secondKeymapED->setText(toqstr(external_path(rc.secondary_kbmap)));
544         mouseWheelSpeedSB->setValue(rc.mouse_wheel_speed);
545         switch (rc.scroll_wheel_zoom) {
546         case LyXRC::SCROLL_WHEEL_ZOOM_OFF:
547                 scrollzoomEnableCB->setChecked(false);
548                 break;
549         case LyXRC::SCROLL_WHEEL_ZOOM_CTRL:
550                 scrollzoomEnableCB->setChecked(true);
551                 scrollzoomValueCO->setCurrentIndex(0);
552                 break;
553         case LyXRC::SCROLL_WHEEL_ZOOM_SHIFT:
554                 scrollzoomEnableCB->setChecked(true);
555                 scrollzoomValueCO->setCurrentIndex(1);
556                 break;
557         case LyXRC::SCROLL_WHEEL_ZOOM_ALT:
558                 scrollzoomEnableCB->setChecked(true);
559                 scrollzoomValueCO->setCurrentIndex(2);
560                 break;
561         }
562         dontswapCB->setChecked(rc.mac_dontswap_ctrl_meta);
563 }
564
565
566 QString PrefInput::testKeymap(QString const & keymap)
567 {
568         return form_->browsekbmap(internalPath(keymap));
569 }
570
571
572 void PrefInput::on_firstKeymapPB_clicked(bool)
573 {
574         QString const file = testKeymap(firstKeymapED->text());
575         if (!file.isEmpty())
576                 firstKeymapED->setText(file);
577 }
578
579
580 void PrefInput::on_secondKeymapPB_clicked(bool)
581 {
582         QString const file = testKeymap(secondKeymapED->text());
583         if (!file.isEmpty())
584                 secondKeymapED->setText(file);
585 }
586
587
588 void PrefInput::on_keymapCB_toggled(bool keymap)
589 {
590         firstKeymapLA->setEnabled(keymap);
591         secondKeymapLA->setEnabled(keymap);
592         firstKeymapED->setEnabled(keymap);
593         secondKeymapED->setEnabled(keymap);
594         firstKeymapPB->setEnabled(keymap);
595         secondKeymapPB->setEnabled(keymap);
596 }
597
598
599 void PrefInput::on_scrollzoomEnableCB_toggled(bool enabled)
600 {
601         scrollzoomValueCO->setEnabled(enabled);
602 }
603
604
605 /////////////////////////////////////////////////////////////////////
606 //
607 // PrefCompletion
608 //
609 /////////////////////////////////////////////////////////////////////
610
611 PrefCompletion::PrefCompletion(GuiPreferences * form)
612         : PrefModule(catEditing, N_("Input Completion"), form)
613 {
614         setupUi(this);
615
616         connect(inlineDelaySB, SIGNAL(valueChanged(double)),
617                 this, SIGNAL(changed()));
618         connect(inlineMathCB, SIGNAL(clicked()),
619                 this, SIGNAL(changed()));
620         connect(inlineTextCB, SIGNAL(clicked()),
621                 this, SIGNAL(changed()));
622         connect(inlineDotsCB, SIGNAL(clicked()),
623                 this, SIGNAL(changed()));
624         connect(popupDelaySB, SIGNAL(valueChanged(double)),
625                 this, SIGNAL(changed()));
626         connect(popupMathCB, SIGNAL(clicked()),
627                 this, SIGNAL(changed()));
628         connect(autocorrectionCB, SIGNAL(clicked()),
629                 this, SIGNAL(changed()));
630         connect(popupTextCB, SIGNAL(clicked()),
631                 this, SIGNAL(changed()));
632         connect(popupAfterCompleteCB, SIGNAL(clicked()),
633                 this, SIGNAL(changed()));
634         connect(cursorTextCB, SIGNAL(clicked()),
635                 this, SIGNAL(changed()));
636         connect(minlengthSB, SIGNAL(valueChanged(int)),
637                         this, SIGNAL(changed()));
638 }
639
640
641 void PrefCompletion::on_inlineTextCB_clicked()
642 {
643         enableCB();
644 }
645
646
647 void PrefCompletion::on_popupTextCB_clicked()
648 {
649         enableCB();
650 }
651
652
653 void PrefCompletion::enableCB()
654 {
655         cursorTextCB->setEnabled(
656                 popupTextCB->isChecked() || inlineTextCB->isChecked());
657 }
658
659
660 void PrefCompletion::applyRC(LyXRC & rc) const
661 {
662         rc.completion_inline_delay = inlineDelaySB->value();
663         rc.completion_inline_math = inlineMathCB->isChecked();
664         rc.completion_inline_text = inlineTextCB->isChecked();
665         rc.completion_inline_dots = inlineDotsCB->isChecked() ? 13 : -1;
666         rc.completion_popup_delay = popupDelaySB->value();
667         rc.completion_popup_math = popupMathCB->isChecked();
668         rc.autocorrection_math = autocorrectionCB->isChecked();
669         rc.completion_popup_text = popupTextCB->isChecked();
670         rc.completion_cursor_text = cursorTextCB->isChecked();
671         rc.completion_popup_after_complete =
672                 popupAfterCompleteCB->isChecked();
673         rc.completion_minlength = minlengthSB->value();
674 }
675
676
677 void PrefCompletion::updateRC(LyXRC const & rc)
678 {
679         inlineDelaySB->setValue(rc.completion_inline_delay);
680         inlineMathCB->setChecked(rc.completion_inline_math);
681         inlineTextCB->setChecked(rc.completion_inline_text);
682         inlineDotsCB->setChecked(rc.completion_inline_dots != -1);
683         popupDelaySB->setValue(rc.completion_popup_delay);
684         popupMathCB->setChecked(rc.completion_popup_math);
685         autocorrectionCB->setChecked(rc.autocorrection_math);
686         popupTextCB->setChecked(rc.completion_popup_text);
687         cursorTextCB->setChecked(rc.completion_cursor_text);
688         popupAfterCompleteCB->setChecked(rc.completion_popup_after_complete);
689         enableCB();
690         minlengthSB->setValue(rc.completion_minlength);
691 }
692
693
694
695 /////////////////////////////////////////////////////////////////////
696 //
697 // PrefLatex
698 //
699 /////////////////////////////////////////////////////////////////////
700
701 PrefLatex::PrefLatex(GuiPreferences * form)
702         : PrefModule(catOutput, N_("LaTeX"), form)
703 {
704         setupUi(this);
705
706         latexEncodingED->setValidator(new NoNewLineValidator(latexEncodingED));
707         latexDviPaperED->setValidator(new NoNewLineValidator(latexDviPaperED));
708         latexBibtexED->setValidator(new NoNewLineValidator(latexBibtexED));
709         latexJBibtexED->setValidator(new NoNewLineValidator(latexJBibtexED));
710         latexIndexED->setValidator(new NoNewLineValidator(latexIndexED));
711         latexJIndexED->setValidator(new NoNewLineValidator(latexJIndexED));
712         latexNomenclED->setValidator(new NoNewLineValidator(latexNomenclED));
713         latexChecktexED->setValidator(new NoNewLineValidator(latexChecktexED));
714
715         connect(latexEncodingCB, SIGNAL(clicked()),
716                 this, SIGNAL(changed()));
717         connect(latexEncodingED, SIGNAL(textChanged(QString)),
718                 this, SIGNAL(changed()));
719         connect(latexChecktexED, SIGNAL(textChanged(QString)),
720                 this, SIGNAL(changed()));
721         connect(latexBibtexCO, SIGNAL(activated(int)),
722                 this, SIGNAL(changed()));
723         connect(latexBibtexED, SIGNAL(textChanged(QString)),
724                 this, SIGNAL(changed()));
725         connect(latexJBibtexED, SIGNAL(textChanged(QString)),
726                 this, SIGNAL(changed()));
727         connect(latexIndexCO, SIGNAL(activated(int)),
728                 this, SIGNAL(changed()));
729         connect(latexIndexED, SIGNAL(textChanged(QString)),
730                 this, SIGNAL(changed()));
731         connect(latexJIndexED, SIGNAL(textChanged(QString)),
732                 this, SIGNAL(changed()));
733         connect(latexAutoresetCB, SIGNAL(clicked()),
734                 this, SIGNAL(changed()));
735         connect(latexDviPaperED, SIGNAL(textChanged(QString)),
736                 this, SIGNAL(changed()));
737         connect(latexNomenclED, SIGNAL(textChanged(QString)),
738                 this, SIGNAL(changed()));
739
740 #if defined(__CYGWIN__) || defined(_WIN32)
741         pathCB->setVisible(true);
742         connect(pathCB, SIGNAL(clicked()),
743                 this, SIGNAL(changed()));
744 #else
745         pathCB->setVisible(false);
746 #endif
747 }
748
749
750 void PrefLatex::on_latexEncodingCB_stateChanged(int state)
751 {
752         latexEncodingED->setEnabled(state == Qt::Checked);
753 }
754
755
756 void PrefLatex::on_latexBibtexCO_activated(int n)
757 {
758         QString const bibtex = latexBibtexCO->itemData(n).toString();
759         if (bibtex.isEmpty()) {
760                 latexBibtexED->clear();
761                 latexBibtexOptionsLA->setText(qt_("Co&mmand:"));
762                 return;
763         }
764         for (LyXRC::CommandSet::const_iterator it = bibtex_alternatives.begin();
765              it != bibtex_alternatives.end(); ++it) {
766                 QString const bib = toqstr(*it);
767                 int ind = bib.indexOf(" ");
768                 QString sel_command = bib.left(ind);
769                 QString sel_options = ind < 0 ? QString() : bib.mid(ind + 1);
770                 if (bibtex == sel_command) {
771                         if (ind < 0)
772                                 latexBibtexED->clear();
773                         else
774                                 latexBibtexED->setText(sel_options.trimmed());
775                 }
776         }
777         latexBibtexOptionsLA->setText(qt_("&Options:"));
778 }
779
780
781 void PrefLatex::on_latexIndexCO_activated(int n)
782 {
783         QString const index = latexIndexCO->itemData(n).toString();
784         if (index.isEmpty()) {
785                 latexIndexED->clear();
786                 latexIndexOptionsLA->setText(qt_("Co&mmand:"));
787                 return;
788         }
789         for (LyXRC::CommandSet::const_iterator it = index_alternatives.begin();
790              it != index_alternatives.end(); ++it) {
791                 QString const idx = toqstr(*it);
792                 int ind = idx.indexOf(" ");
793                 QString sel_command = idx.left(ind);
794                 QString sel_options = ind < 0 ? QString() : idx.mid(ind + 1);
795                 if (index == sel_command) {
796                         if (ind < 0)
797                                 latexIndexED->clear();
798                         else
799                                 latexIndexED->setText(sel_options.trimmed());
800                 }
801         }
802         latexIndexOptionsLA->setText(qt_("Op&tions:"));
803 }
804
805
806 void PrefLatex::applyRC(LyXRC & rc) const
807 {
808         // If bibtex is not empty, bibopt contains the options, otherwise
809         // it is a customized bibtex command with options.
810         QString const bibtex = latexBibtexCO->itemData(
811                 latexBibtexCO->currentIndex()).toString();
812         QString const bibopt = latexBibtexED->text();
813         if (bibtex.isEmpty())
814                 rc.bibtex_command = fromqstr(bibopt);
815         else if (bibopt.isEmpty())
816                 rc.bibtex_command = fromqstr(bibtex);
817         else
818                 rc.bibtex_command = fromqstr(bibtex) + " " + fromqstr(bibopt);
819
820         // If index is not empty, idxopt contains the options, otherwise
821         // it is a customized index command with options.
822         QString const index = latexIndexCO->itemData(
823                 latexIndexCO->currentIndex()).toString();
824         QString const idxopt = latexIndexED->text();
825         if (index.isEmpty())
826                 rc.index_command = fromqstr(idxopt);
827         else if (idxopt.isEmpty())
828                 rc.index_command = fromqstr(index);
829         else
830                 rc.index_command = fromqstr(index) + " " + fromqstr(idxopt);
831
832         if (latexEncodingCB->isChecked())
833                 rc.fontenc = fromqstr(latexEncodingED->text());
834         else
835                 rc.fontenc = "default";
836         rc.chktex_command = fromqstr(latexChecktexED->text());
837         rc.jbibtex_command = fromqstr(latexJBibtexED->text());
838         rc.jindex_command = fromqstr(latexJIndexED->text());
839         rc.nomencl_command = fromqstr(latexNomenclED->text());
840         rc.auto_reset_options = latexAutoresetCB->isChecked();
841         rc.view_dvi_paper_option = fromqstr(latexDviPaperED->text());
842 #if defined(__CYGWIN__) || defined(_WIN32)
843         rc.windows_style_tex_paths = pathCB->isChecked();
844 #endif
845 }
846
847
848 void PrefLatex::updateRC(LyXRC const & rc)
849 {
850         latexBibtexCO->clear();
851
852         latexBibtexCO->addItem(qt_("Custom"), QString());
853         for (LyXRC::CommandSet::const_iterator it = rc.bibtex_alternatives.begin();
854                              it != rc.bibtex_alternatives.end(); ++it) {
855                 QString const command = toqstr(*it).left(toqstr(*it).indexOf(" "));
856                 latexBibtexCO->addItem(command, command);
857         }
858
859         bibtex_alternatives = rc.bibtex_alternatives;
860
861         QString const bib = toqstr(rc.bibtex_command);
862         int ind = bib.indexOf(" ");
863         QString sel_command = bib.left(ind);
864         QString sel_options = ind < 0 ? QString() : bib.mid(ind + 1);
865
866         int pos = latexBibtexCO->findData(sel_command);
867         if (pos != -1) {
868                 latexBibtexCO->setCurrentIndex(pos);
869                 latexBibtexED->setText(sel_options.trimmed());
870                 latexBibtexOptionsLA->setText(qt_("&Options:"));
871         } else {
872                 latexBibtexED->setText(toqstr(rc.bibtex_command));
873                 latexBibtexCO->setCurrentIndex(0);
874                 latexBibtexOptionsLA->setText(qt_("Co&mmand:"));
875         }
876
877         latexIndexCO->clear();
878
879         latexIndexCO->addItem(qt_("Custom"), QString());
880         for (LyXRC::CommandSet::const_iterator it = rc.index_alternatives.begin();
881                              it != rc.index_alternatives.end(); ++it) {
882                 QString const command = toqstr(*it).left(toqstr(*it).indexOf(" "));
883                 latexIndexCO->addItem(command, command);
884         }
885
886         index_alternatives = rc.index_alternatives;
887
888         QString const idx = toqstr(rc.index_command);
889         ind = idx.indexOf(" ");
890         sel_command = idx.left(ind);
891         sel_options = ind < 0 ? QString() : idx.mid(ind + 1);
892
893         pos = latexIndexCO->findData(sel_command);
894         if (pos != -1) {
895                 latexIndexCO->setCurrentIndex(pos);
896                 latexIndexED->setText(sel_options.trimmed());
897                 latexIndexOptionsLA->setText(qt_("Op&tions:"));
898         } else {
899                 latexIndexED->setText(toqstr(rc.index_command));
900                 latexIndexCO->setCurrentIndex(0);
901                 latexIndexOptionsLA->setText(qt_("Co&mmand:"));
902         }
903
904         if (rc.fontenc == "default") {
905                 latexEncodingCB->setChecked(false);
906                 latexEncodingED->setEnabled(false);
907         } else {
908                 latexEncodingCB->setChecked(true);
909                 latexEncodingED->setEnabled(true);
910                 latexEncodingED->setText(toqstr(rc.fontenc));
911         }
912         latexChecktexED->setText(toqstr(rc.chktex_command));
913         latexJBibtexED->setText(toqstr(rc.jbibtex_command));
914         latexJIndexED->setText(toqstr(rc.jindex_command));
915         latexNomenclED->setText(toqstr(rc.nomencl_command));
916         latexAutoresetCB->setChecked(rc.auto_reset_options);
917         latexDviPaperED->setText(toqstr(rc.view_dvi_paper_option));
918 #if defined(__CYGWIN__) || defined(_WIN32)
919         pathCB->setChecked(rc.windows_style_tex_paths);
920 #endif
921 }
922
923
924 /////////////////////////////////////////////////////////////////////
925 //
926 // PrefScreenFonts
927 //
928 /////////////////////////////////////////////////////////////////////
929
930 PrefScreenFonts::PrefScreenFonts(GuiPreferences * form)
931         : PrefModule(catLookAndFeel, N_("Screen Fonts"), form)
932 {
933         setupUi(this);
934
935         connect(screenRomanCO, SIGNAL(activated(QString)),
936                 this, SLOT(selectRoman(QString)));
937         connect(screenSansCO, SIGNAL(activated(QString)),
938                 this, SLOT(selectSans(QString)));
939         connect(screenTypewriterCO, SIGNAL(activated(QString)),
940                 this, SLOT(selectTypewriter(QString)));
941
942         QFontDatabase fontdb;
943         QStringList families(fontdb.families());
944         for (QStringList::Iterator it = families.begin(); it != families.end(); ++it) {
945                 screenRomanCO->addItem(*it);
946                 screenSansCO->addItem(*it);
947                 screenTypewriterCO->addItem(*it);
948         }
949         connect(screenRomanCO, SIGNAL(activated(QString)),
950                 this, SIGNAL(changed()));
951         connect(screenSansCO, SIGNAL(activated(QString)),
952                 this, SIGNAL(changed()));
953         connect(screenTypewriterCO, SIGNAL(activated(QString)),
954                 this, SIGNAL(changed()));
955         connect(screenZoomSB, SIGNAL(valueChanged(int)),
956                 this, SIGNAL(changed()));
957         connect(screenTinyED, SIGNAL(textChanged(QString)),
958                 this, SIGNAL(changed()));
959         connect(screenSmallestED, SIGNAL(textChanged(QString)),
960                 this, SIGNAL(changed()));
961         connect(screenSmallerED, SIGNAL(textChanged(QString)),
962                 this, SIGNAL(changed()));
963         connect(screenSmallED, SIGNAL(textChanged(QString)),
964                 this, SIGNAL(changed()));
965         connect(screenNormalED, SIGNAL(textChanged(QString)),
966                 this, SIGNAL(changed()));
967         connect(screenLargeED, SIGNAL(textChanged(QString)),
968                 this, SIGNAL(changed()));
969         connect(screenLargerED, SIGNAL(textChanged(QString)),
970                 this, SIGNAL(changed()));
971         connect(screenLargestED, SIGNAL(textChanged(QString)),
972                 this, SIGNAL(changed()));
973         connect(screenHugeED, SIGNAL(textChanged(QString)),
974                 this, SIGNAL(changed()));
975         connect(screenHugerED, SIGNAL(textChanged(QString)),
976                 this, SIGNAL(changed()));
977         connect(pixmapCacheCB, SIGNAL(toggled(bool)),
978                 this, SIGNAL(changed()));
979
980         screenTinyED->setValidator(new QDoubleValidator(screenTinyED));
981         screenSmallestED->setValidator(new QDoubleValidator(screenSmallestED));
982         screenSmallerED->setValidator(new QDoubleValidator(screenSmallerED));
983         screenSmallED->setValidator(new QDoubleValidator(screenSmallED));
984         screenNormalED->setValidator(new QDoubleValidator(screenNormalED));
985         screenLargeED->setValidator(new QDoubleValidator(screenLargeED));
986         screenLargerED->setValidator(new QDoubleValidator(screenLargerED));
987         screenLargestED->setValidator(new QDoubleValidator(screenLargestED));
988         screenHugeED->setValidator(new QDoubleValidator(screenHugeED));
989         screenHugerED->setValidator(new QDoubleValidator(screenHugerED));
990 }
991
992
993 void PrefScreenFonts::applyRC(LyXRC & rc) const
994 {
995         LyXRC const oldrc = rc;
996
997         parseFontName(screenRomanCO->currentText(),
998                 rc.roman_font_name, rc.roman_font_foundry);
999         parseFontName(screenSansCO->currentText(),
1000                 rc.sans_font_name, rc.sans_font_foundry);
1001         parseFontName(screenTypewriterCO->currentText(),
1002                 rc.typewriter_font_name, rc.typewriter_font_foundry);
1003
1004         rc.zoom = screenZoomSB->value();
1005         rc.font_sizes[FONT_SIZE_TINY] = widgetToDoubleStr(screenTinyED);
1006         rc.font_sizes[FONT_SIZE_SCRIPT] = widgetToDoubleStr(screenSmallestED);
1007         rc.font_sizes[FONT_SIZE_FOOTNOTE] = widgetToDoubleStr(screenSmallerED);
1008         rc.font_sizes[FONT_SIZE_SMALL] = widgetToDoubleStr(screenSmallED);
1009         rc.font_sizes[FONT_SIZE_NORMAL] = widgetToDoubleStr(screenNormalED);
1010         rc.font_sizes[FONT_SIZE_LARGE] = widgetToDoubleStr(screenLargeED);
1011         rc.font_sizes[FONT_SIZE_LARGER] = widgetToDoubleStr(screenLargerED);
1012         rc.font_sizes[FONT_SIZE_LARGEST] = widgetToDoubleStr(screenLargestED);
1013         rc.font_sizes[FONT_SIZE_HUGE] = widgetToDoubleStr(screenHugeED);
1014         rc.font_sizes[FONT_SIZE_HUGER] = widgetToDoubleStr(screenHugerED);
1015         rc.use_pixmap_cache = pixmapCacheCB->isChecked();
1016
1017         if (rc.font_sizes != oldrc.font_sizes
1018                 || rc.roman_font_name != oldrc.roman_font_name
1019                 || rc.sans_font_name != oldrc.sans_font_name
1020                 || rc.typewriter_font_name != oldrc.typewriter_font_name
1021                 || rc.zoom != oldrc.zoom) {
1022                 // The global QPixmapCache is used in GuiPainter to cache text
1023                 // painting so we must reset it in case any of the above
1024                 // parameter is changed.
1025                 QPixmapCache::clear();
1026                 guiApp->fontLoader().update();
1027                 form_->updateScreenFonts();
1028         }
1029 }
1030
1031
1032 void PrefScreenFonts::updateRC(LyXRC const & rc)
1033 {
1034         setComboxFont(screenRomanCO, rc.roman_font_name,
1035                         rc.roman_font_foundry);
1036         setComboxFont(screenSansCO, rc.sans_font_name,
1037                         rc.sans_font_foundry);
1038         setComboxFont(screenTypewriterCO, rc.typewriter_font_name,
1039                         rc.typewriter_font_foundry);
1040
1041         selectRoman(screenRomanCO->currentText());
1042         selectSans(screenSansCO->currentText());
1043         selectTypewriter(screenTypewriterCO->currentText());
1044
1045         screenZoomSB->setValue(rc.zoom);
1046         updateScreenFontSizes(rc);
1047
1048         pixmapCacheCB->setChecked(rc.use_pixmap_cache);
1049 #if defined(Q_WS_X11)
1050         pixmapCacheCB->setEnabled(false);
1051 #endif
1052
1053 }
1054
1055
1056 void PrefScreenFonts::updateScreenFontSizes(LyXRC const & rc)
1057 {
1058         doubleToWidget(screenTinyED, rc.font_sizes[FONT_SIZE_TINY]);
1059         doubleToWidget(screenSmallestED, rc.font_sizes[FONT_SIZE_SCRIPT]);
1060         doubleToWidget(screenSmallerED, rc.font_sizes[FONT_SIZE_FOOTNOTE]);
1061         doubleToWidget(screenSmallED, rc.font_sizes[FONT_SIZE_SMALL]);
1062         doubleToWidget(screenNormalED, rc.font_sizes[FONT_SIZE_NORMAL]);
1063         doubleToWidget(screenLargeED, rc.font_sizes[FONT_SIZE_LARGE]);
1064         doubleToWidget(screenLargerED, rc.font_sizes[FONT_SIZE_LARGER]);
1065         doubleToWidget(screenLargestED, rc.font_sizes[FONT_SIZE_LARGEST]);
1066         doubleToWidget(screenHugeED, rc.font_sizes[FONT_SIZE_HUGE]);
1067         doubleToWidget(screenHugerED, rc.font_sizes[FONT_SIZE_HUGER]);
1068 }
1069
1070
1071 void PrefScreenFonts::selectRoman(const QString & name)
1072 {
1073         screenRomanFE->set(QFont(name), name);
1074 }
1075
1076
1077 void PrefScreenFonts::selectSans(const QString & name)
1078 {
1079         screenSansFE->set(QFont(name), name);
1080 }
1081
1082
1083 void PrefScreenFonts::selectTypewriter(const QString & name)
1084 {
1085         screenTypewriterFE->set(QFont(name), name);
1086 }
1087
1088
1089 /////////////////////////////////////////////////////////////////////
1090 //
1091 // PrefColors
1092 //
1093 /////////////////////////////////////////////////////////////////////
1094
1095 namespace {
1096
1097 struct ColorSorter
1098 {
1099         bool operator()(ColorCode lhs, ColorCode rhs) const {
1100                 return
1101                         compare_no_case(lcolor.getGUIName(lhs), lcolor.getGUIName(rhs)) < 0;
1102         }
1103 };
1104
1105 } // namespace anon
1106
1107 PrefColors::PrefColors(GuiPreferences * form)
1108         : PrefModule(catLookAndFeel, N_("Colors"), form)
1109 {
1110         setupUi(this);
1111
1112         // FIXME: all of this initialization should be put into the controller.
1113         // See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg113301.html
1114         // for some discussion of why that is not trivial.
1115         QPixmap icon(32, 32);
1116         for (int i = 0; i < Color_ignore; ++i) {
1117                 ColorCode lc = static_cast<ColorCode>(i);
1118                 if (lc == Color_none
1119                     || lc == Color_black
1120                     || lc == Color_white
1121                     || lc == Color_red
1122                     || lc == Color_green
1123                     || lc == Color_blue
1124                     || lc == Color_cyan
1125                     || lc == Color_magenta
1126                     || lc == Color_yellow
1127                     || lc == Color_inherit
1128                     || lc == Color_ignore)
1129                         continue;
1130                 lcolors_.push_back(lc);
1131         }
1132         sort(lcolors_.begin(), lcolors_.end(), ColorSorter());
1133         vector<ColorCode>::const_iterator cit = lcolors_.begin();
1134         vector<ColorCode>::const_iterator const end = lcolors_.end();
1135         for (; cit != end; ++cit) {
1136                 (void) new QListWidgetItem(QIcon(icon),
1137                         toqstr(lcolor.getGUIName(*cit)), lyxObjectsLW);
1138         }
1139         curcolors_.resize(lcolors_.size());
1140         newcolors_.resize(lcolors_.size());
1141         // End initialization
1142
1143         connect(colorChangePB, SIGNAL(clicked()),
1144                 this, SLOT(changeColor()));
1145         connect(lyxObjectsLW, SIGNAL(itemSelectionChanged()),
1146                 this, SLOT(changeLyxObjectsSelection()));
1147         connect(lyxObjectsLW, SIGNAL(itemActivated(QListWidgetItem*)),
1148                 this, SLOT(changeColor()));
1149         connect(syscolorsCB, SIGNAL(toggled(bool)),
1150                 this, SIGNAL(changed()));
1151         connect(syscolorsCB, SIGNAL(toggled(bool)),
1152                 this, SLOT(changeSysColor()));
1153 }
1154
1155
1156 void PrefColors::applyRC(LyXRC & rc) const
1157 {
1158         LyXRC oldrc = rc;
1159
1160         for (unsigned int i = 0; i < lcolors_.size(); ++i)
1161                 if (curcolors_[i] != newcolors_[i])
1162                         form_->setColor(lcolors_[i], newcolors_[i]);
1163         rc.use_system_colors = syscolorsCB->isChecked();
1164
1165         if (oldrc.use_system_colors != rc.use_system_colors)
1166                 guiApp->colorCache().clear();
1167 }
1168
1169
1170 void PrefColors::updateRC(LyXRC const & rc)
1171 {
1172         for (unsigned int i = 0; i < lcolors_.size(); ++i) {
1173                 QColor color = QColor(guiApp->colorCache().get(lcolors_[i], false));
1174                 QPixmap coloritem(32, 32);
1175                 coloritem.fill(color);
1176                 lyxObjectsLW->item(i)->setIcon(QIcon(coloritem));
1177                 newcolors_[i] = curcolors_[i] = color.name();
1178         }
1179         syscolorsCB->setChecked(rc.use_system_colors);
1180         changeLyxObjectsSelection();
1181 }
1182
1183
1184 void PrefColors::changeColor()
1185 {
1186         int const row = lyxObjectsLW->currentRow();
1187
1188         // just to be sure
1189         if (row < 0)
1190                 return;
1191
1192         QString const color = newcolors_[row];
1193         QColor c = QColorDialog::getColor(QColor(color), qApp->focusWidget());
1194
1195         if (c.isValid() && c.name() != color) {
1196                 newcolors_[row] = c.name();
1197                 QPixmap coloritem(32, 32);
1198                 coloritem.fill(c);
1199                 lyxObjectsLW->currentItem()->setIcon(QIcon(coloritem));
1200                 // emit signal
1201                 changed();
1202         }
1203 }
1204
1205 void PrefColors::changeSysColor()
1206 {
1207         for (int row = 0 ; row < lyxObjectsLW->count() ; ++row) {
1208                 // skip colors that are taken from system palette
1209                 bool const hide = syscolorsCB->isChecked()
1210                         && guiApp->colorCache().isSystem(lcolors_[row]);
1211
1212                 lyxObjectsLW->item(row)->setHidden(hide);
1213         }
1214
1215 }
1216
1217 void PrefColors::changeLyxObjectsSelection()
1218 {
1219         colorChangePB->setDisabled(lyxObjectsLW->currentRow() < 0);
1220 }
1221
1222
1223 /////////////////////////////////////////////////////////////////////
1224 //
1225 // PrefDisplay
1226 //
1227 /////////////////////////////////////////////////////////////////////
1228
1229 PrefDisplay::PrefDisplay(GuiPreferences * form)
1230         : PrefModule(catLookAndFeel, N_("Display"), form)
1231 {
1232         setupUi(this);
1233         connect(displayGraphicsCB, SIGNAL(toggled(bool)), this, SIGNAL(changed()));
1234         connect(instantPreviewCO, SIGNAL(activated(int)), this, SIGNAL(changed()));
1235         connect(previewSizeSB, SIGNAL(valueChanged(double)), this, SIGNAL(changed()));
1236         connect(paragraphMarkerCB, SIGNAL(toggled(bool)), this, SIGNAL(changed()));
1237 }
1238
1239
1240 void PrefDisplay::on_instantPreviewCO_currentIndexChanged(int index)
1241 {
1242         previewSizeSB->setEnabled(index != 0);
1243 }
1244
1245
1246 void PrefDisplay::applyRC(LyXRC & rc) const
1247 {
1248         switch (instantPreviewCO->currentIndex()) {
1249                 case 0:
1250                         rc.preview = LyXRC::PREVIEW_OFF;
1251                         break;
1252                 case 1:
1253                         rc.preview = LyXRC::PREVIEW_NO_MATH;
1254                         break;
1255                 case 2:
1256                         rc.preview = LyXRC::PREVIEW_ON;
1257                         break;
1258         }
1259
1260         rc.display_graphics = displayGraphicsCB->isChecked();
1261         rc.preview_scale_factor = previewSizeSB->value();
1262         rc.paragraph_markers = paragraphMarkerCB->isChecked();
1263
1264         // FIXME!! The graphics cache no longer has a changeDisplay method.
1265 #if 0
1266         if (old_value != rc.display_graphics) {
1267                 graphics::GCache & gc = graphics::GCache::get();
1268                 gc.changeDisplay();
1269         }
1270 #endif
1271 }
1272
1273
1274 void PrefDisplay::updateRC(LyXRC const & rc)
1275 {
1276         switch (rc.preview) {
1277         case LyXRC::PREVIEW_OFF:
1278                 instantPreviewCO->setCurrentIndex(0);
1279                 break;
1280         case LyXRC::PREVIEW_NO_MATH :
1281                 instantPreviewCO->setCurrentIndex(1);
1282                 break;
1283         case LyXRC::PREVIEW_ON :
1284                 instantPreviewCO->setCurrentIndex(2);
1285                 break;
1286         }
1287
1288         displayGraphicsCB->setChecked(rc.display_graphics);
1289         previewSizeSB->setValue(rc.preview_scale_factor);
1290         paragraphMarkerCB->setChecked(rc.paragraph_markers);
1291         previewSizeSB->setEnabled(
1292                 rc.display_graphics
1293                 && rc.preview != LyXRC::PREVIEW_OFF);
1294 }
1295
1296
1297 /////////////////////////////////////////////////////////////////////
1298 //
1299 // PrefPaths
1300 //
1301 /////////////////////////////////////////////////////////////////////
1302
1303 PrefPaths::PrefPaths(GuiPreferences * form)
1304         : PrefModule(QString(), N_("Paths"), form)
1305 {
1306         setupUi(this);
1307
1308         connect(workingDirPB, SIGNAL(clicked()), this, SLOT(selectWorkingdir()));
1309         connect(workingDirED, SIGNAL(textChanged(QString)),
1310                 this, SIGNAL(changed()));
1311
1312         connect(templateDirPB, SIGNAL(clicked()), this, SLOT(selectTemplatedir()));
1313         connect(templateDirED, SIGNAL(textChanged(QString)),
1314                 this, SIGNAL(changed()));
1315
1316         connect(exampleDirPB, SIGNAL(clicked()), this, SLOT(selectExampledir()));
1317         connect(exampleDirED, SIGNAL(textChanged(QString)),
1318                 this, SIGNAL(changed()));
1319
1320         connect(backupDirPB, SIGNAL(clicked()), this, SLOT(selectBackupdir()));
1321         connect(backupDirED, SIGNAL(textChanged(QString)),
1322                 this, SIGNAL(changed()));
1323
1324         connect(lyxserverDirPB, SIGNAL(clicked()), this, SLOT(selectLyxPipe()));
1325         connect(lyxserverDirED, SIGNAL(textChanged(QString)),
1326                 this, SIGNAL(changed()));
1327
1328         connect(thesaurusDirPB, SIGNAL(clicked()), this, SLOT(selectThesaurusdir()));
1329         connect(thesaurusDirED, SIGNAL(textChanged(QString)),
1330                 this, SIGNAL(changed()));
1331
1332         connect(tempDirPB, SIGNAL(clicked()), this, SLOT(selectTempdir()));
1333         connect(tempDirED, SIGNAL(textChanged(QString)),
1334                 this, SIGNAL(changed()));
1335
1336 #if defined(USE_HUNSPELL)
1337         connect(hunspellDirPB, SIGNAL(clicked()), this, SLOT(selectHunspelldir()));
1338         connect(hunspellDirED, SIGNAL(textChanged(QString)),
1339                 this, SIGNAL(changed()));
1340 #else
1341         hunspellDirPB->setEnabled(false);
1342         hunspellDirED->setEnabled(false);
1343 #endif
1344
1345         connect(pathPrefixED, SIGNAL(textChanged(QString)),
1346                 this, SIGNAL(changed()));
1347
1348         connect(texinputsPrefixED, SIGNAL(textChanged(QString)),
1349                 this, SIGNAL(changed()));
1350
1351         pathPrefixED->setValidator(new NoNewLineValidator(pathPrefixED));
1352         texinputsPrefixED->setValidator(new NoNewLineValidator(texinputsPrefixED));
1353 }
1354
1355
1356 void PrefPaths::applyRC(LyXRC & rc) const
1357 {
1358         rc.document_path = internal_path(fromqstr(workingDirED->text()));
1359         rc.example_path = internal_path(fromqstr(exampleDirED->text()));
1360         rc.template_path = internal_path(fromqstr(templateDirED->text()));
1361         rc.backupdir_path = internal_path(fromqstr(backupDirED->text()));
1362         rc.tempdir_path = internal_path(fromqstr(tempDirED->text()));
1363         rc.thesaurusdir_path = internal_path(fromqstr(thesaurusDirED->text()));
1364         rc.hunspelldir_path = internal_path(fromqstr(hunspellDirED->text()));
1365         rc.path_prefix = internal_path_list(fromqstr(pathPrefixED->text()));
1366         rc.texinputs_prefix = internal_path_list(fromqstr(texinputsPrefixED->text()));
1367         // FIXME: should be a checkbox only
1368         rc.lyxpipes = internal_path(fromqstr(lyxserverDirED->text()));
1369 }
1370
1371
1372 void PrefPaths::updateRC(LyXRC const & rc)
1373 {
1374         workingDirED->setText(toqstr(external_path(rc.document_path)));
1375         exampleDirED->setText(toqstr(external_path(rc.example_path)));
1376         templateDirED->setText(toqstr(external_path(rc.template_path)));
1377         backupDirED->setText(toqstr(external_path(rc.backupdir_path)));
1378         tempDirED->setText(toqstr(external_path(rc.tempdir_path)));
1379         thesaurusDirED->setText(toqstr(external_path(rc.thesaurusdir_path)));
1380         hunspellDirED->setText(toqstr(external_path(rc.hunspelldir_path)));
1381         pathPrefixED->setText(toqstr(external_path_list(rc.path_prefix)));
1382         texinputsPrefixED->setText(toqstr(external_path_list(rc.texinputs_prefix)));
1383         // FIXME: should be a checkbox only
1384         lyxserverDirED->setText(toqstr(external_path(rc.lyxpipes)));
1385 }
1386
1387
1388 void PrefPaths::selectExampledir()
1389 {
1390         QString file = browseDir(internalPath(exampleDirED->text()),
1391                 qt_("Select directory for example files"));
1392         if (!file.isEmpty())
1393                 exampleDirED->setText(file);
1394 }
1395
1396
1397 void PrefPaths::selectTemplatedir()
1398 {
1399         QString file = browseDir(internalPath(templateDirED->text()),
1400                 qt_("Select a document templates directory"));
1401         if (!file.isEmpty())
1402                 templateDirED->setText(file);
1403 }
1404
1405
1406 void PrefPaths::selectTempdir()
1407 {
1408         QString file = browseDir(internalPath(tempDirED->text()),
1409                 qt_("Select a temporary directory"));
1410         if (!file.isEmpty())
1411                 tempDirED->setText(file);
1412 }
1413
1414
1415 void PrefPaths::selectBackupdir()
1416 {
1417         QString file = browseDir(internalPath(backupDirED->text()),
1418                 qt_("Select a backups directory"));
1419         if (!file.isEmpty())
1420                 backupDirED->setText(file);
1421 }
1422
1423
1424 void PrefPaths::selectWorkingdir()
1425 {
1426         QString file = browseDir(internalPath(workingDirED->text()),
1427                 qt_("Select a document directory"));
1428         if (!file.isEmpty())
1429                 workingDirED->setText(file);
1430 }
1431
1432
1433 void PrefPaths::selectThesaurusdir()
1434 {
1435         QString file = browseDir(internalPath(thesaurusDirED->text()),
1436                 qt_("Set the path to the thesaurus dictionaries"));
1437         if (!file.isEmpty())
1438                 thesaurusDirED->setText(file);
1439 }
1440
1441
1442 void PrefPaths::selectHunspelldir()
1443 {
1444         QString file = browseDir(internalPath(hunspellDirED->text()),
1445                 qt_("Set the path to the Hunspell dictionaries"));
1446         if (!file.isEmpty())
1447                 hunspellDirED->setText(file);
1448 }
1449
1450
1451 void PrefPaths::selectLyxPipe()
1452 {
1453         QString file = form_->browse(internalPath(lyxserverDirED->text()),
1454                 qt_("Give a filename for the LyX server pipe"));
1455         if (!file.isEmpty())
1456                 lyxserverDirED->setText(file);
1457 }
1458
1459
1460 /////////////////////////////////////////////////////////////////////
1461 //
1462 // PrefSpellchecker
1463 //
1464 /////////////////////////////////////////////////////////////////////
1465
1466 PrefSpellchecker::PrefSpellchecker(GuiPreferences * form)
1467         : PrefModule(catLanguage, N_("Spellchecker"), form)
1468 {
1469         setupUi(this);
1470
1471 // FIXME: this check should test the target platform (darwin)
1472 #if defined(USE_MACOSX_PACKAGING)
1473         spellcheckerCB->addItem(qt_("Native"), QString("native"));
1474 #define CONNECT_APPLESPELL
1475 #else
1476 #undef CONNECT_APPLESPELL
1477 #endif
1478 #if defined(USE_ASPELL)
1479         spellcheckerCB->addItem(qt_("Aspell"), QString("aspell"));
1480 #endif
1481 #if defined(USE_ENCHANT)
1482         spellcheckerCB->addItem(qt_("Enchant"), QString("enchant"));
1483 #endif
1484 #if defined(USE_HUNSPELL)
1485         spellcheckerCB->addItem(qt_("Hunspell"), QString("hunspell"));
1486 #endif
1487
1488         #if defined(CONNECT_APPLESPELL) || defined(USE_ASPELL) || defined(USE_ENCHANT) || defined(USE_HUNSPELL)
1489                 connect(spellcheckerCB, SIGNAL(currentIndexChanged(int)),
1490                         this, SIGNAL(changed()));
1491                 connect(altLanguageED, SIGNAL(textChanged(QString)),
1492                         this, SIGNAL(changed()));
1493                 connect(escapeCharactersED, SIGNAL(textChanged(QString)),
1494                         this, SIGNAL(changed()));
1495                 connect(compoundWordCB, SIGNAL(clicked()),
1496                         this, SIGNAL(changed()));
1497                 connect(spellcheckContinuouslyCB, SIGNAL(clicked()),
1498                         this, SIGNAL(changed()));
1499                 connect(spellcheckNotesCB, SIGNAL(clicked()),
1500                         this, SIGNAL(changed()));
1501
1502                 altLanguageED->setValidator(new NoNewLineValidator(altLanguageED));
1503                 escapeCharactersED->setValidator(new NoNewLineValidator(escapeCharactersED));
1504         #else
1505                 spellcheckerCB->setEnabled(false);
1506                 altLanguageED->setEnabled(false);
1507                 escapeCharactersED->setEnabled(false);
1508                 compoundWordCB->setEnabled(false);
1509                 spellcheckContinuouslyCB->setEnabled(false);
1510                 spellcheckNotesCB->setEnabled(false);
1511         #endif
1512 }
1513
1514
1515 void PrefSpellchecker::applyRC(LyXRC & rc) const
1516 {
1517         string const speller = fromqstr(spellcheckerCB->
1518                 itemData(spellcheckerCB->currentIndex()).toString());
1519         if (!speller.empty())
1520                 rc.spellchecker = speller;
1521         rc.spellchecker_alt_lang = fromqstr(altLanguageED->text());
1522         rc.spellchecker_esc_chars = fromqstr(escapeCharactersED->text());
1523         rc.spellchecker_accept_compound = compoundWordCB->isChecked();
1524         rc.spellcheck_continuously = spellcheckContinuouslyCB->isChecked();
1525         rc.spellcheck_notes = spellcheckNotesCB->isChecked();
1526 }
1527
1528
1529 void PrefSpellchecker::updateRC(LyXRC const & rc)
1530 {
1531         spellcheckerCB->setCurrentIndex(
1532                 spellcheckerCB->findData(toqstr(rc.spellchecker)));
1533         altLanguageED->setText(toqstr(rc.spellchecker_alt_lang));
1534         escapeCharactersED->setText(toqstr(rc.spellchecker_esc_chars));
1535         compoundWordCB->setChecked(rc.spellchecker_accept_compound);
1536         spellcheckContinuouslyCB->setChecked(rc.spellcheck_continuously);
1537         spellcheckNotesCB->setChecked(rc.spellcheck_notes);
1538 }
1539
1540
1541 void PrefSpellchecker::on_spellcheckerCB_currentIndexChanged(int index)
1542 {
1543         QString spellchecker = spellcheckerCB->itemData(index).toString();
1544
1545         compoundWordCB->setEnabled(spellchecker == QString("aspell"));
1546 }
1547
1548
1549
1550 /////////////////////////////////////////////////////////////////////
1551 //
1552 // PrefConverters
1553 //
1554 /////////////////////////////////////////////////////////////////////
1555
1556
1557 PrefConverters::PrefConverters(GuiPreferences * form)
1558         : PrefModule(catFiles, N_("Converters"), form)
1559 {
1560         setupUi(this);
1561
1562         connect(converterNewPB, SIGNAL(clicked()),
1563                 this, SLOT(updateConverter()));
1564         connect(converterRemovePB, SIGNAL(clicked()),
1565                 this, SLOT(removeConverter()));
1566         connect(converterModifyPB, SIGNAL(clicked()),
1567                 this, SLOT(updateConverter()));
1568         connect(convertersLW, SIGNAL(currentRowChanged(int)),
1569                 this, SLOT(switchConverter()));
1570         connect(converterFromCO, SIGNAL(activated(QString)),
1571                 this, SLOT(changeConverter()));
1572         connect(converterToCO, SIGNAL(activated(QString)),
1573                 this, SLOT(changeConverter()));
1574         connect(converterED, SIGNAL(textEdited(QString)),
1575                 this, SLOT(changeConverter()));
1576         connect(converterFlagED, SIGNAL(textEdited(QString)),
1577                 this, SLOT(changeConverter()));
1578         connect(converterNewPB, SIGNAL(clicked()),
1579                 this, SIGNAL(changed()));
1580         connect(converterRemovePB, SIGNAL(clicked()),
1581                 this, SIGNAL(changed()));
1582         connect(converterModifyPB, SIGNAL(clicked()),
1583                 this, SIGNAL(changed()));
1584         connect(maxAgeLE, SIGNAL(textEdited(QString)),
1585                 this, SIGNAL(changed()));
1586
1587         converterED->setValidator(new NoNewLineValidator(converterED));
1588         converterFlagED->setValidator(new NoNewLineValidator(converterFlagED));
1589         maxAgeLE->setValidator(new QDoubleValidator(maxAgeLE));
1590         //converterDefGB->setFocusProxy(convertersLW);
1591 }
1592
1593
1594 void PrefConverters::applyRC(LyXRC & rc) const
1595 {
1596         rc.use_converter_cache = cacheCB->isChecked();
1597         rc.converter_cache_maxage = int(widgetToDouble(maxAgeLE) * 86400.0);
1598 }
1599
1600
1601 void PrefConverters::updateRC(LyXRC const & rc)
1602 {
1603         cacheCB->setChecked(rc.use_converter_cache);
1604         QString max_age;
1605         doubleToWidget(maxAgeLE, (double(rc.converter_cache_maxage) / 86400.0), 'g', 6);
1606         updateGui();
1607 }
1608
1609
1610 void PrefConverters::updateGui()
1611 {
1612         form_->formats().sort();
1613         form_->converters().update(form_->formats());
1614         // save current selection
1615         QString current = converterFromCO->currentText()
1616                 + " -> " + converterToCO->currentText();
1617
1618         converterFromCO->clear();
1619         converterToCO->clear();
1620
1621         Formats::const_iterator cit = form_->formats().begin();
1622         Formats::const_iterator end = form_->formats().end();
1623         for (; cit != end; ++cit) {
1624                 converterFromCO->addItem(qt_(cit->prettyname()));
1625                 converterToCO->addItem(qt_(cit->prettyname()));
1626         }
1627
1628         // currentRowChanged(int) is also triggered when updating the listwidget
1629         // block signals to avoid unnecessary calls to switchConverter()
1630         convertersLW->blockSignals(true);
1631         convertersLW->clear();
1632
1633         Converters::const_iterator ccit = form_->converters().begin();
1634         Converters::const_iterator cend = form_->converters().end();
1635         for (; ccit != cend; ++ccit) {
1636                 QString const name =
1637                         qt_(ccit->From()->prettyname()) + " -> " + qt_(ccit->To()->prettyname());
1638                 int type = form_->converters().getNumber(ccit->From()->name(), ccit->To()->name());
1639                 new QListWidgetItem(name, convertersLW, type);
1640         }
1641         convertersLW->sortItems(Qt::AscendingOrder);
1642         convertersLW->blockSignals(false);
1643
1644         // restore selection
1645         if (!current.isEmpty()) {
1646                 QList<QListWidgetItem *> const item =
1647                         convertersLW->findItems(current, Qt::MatchExactly);
1648                 if (!item.isEmpty())
1649                         convertersLW->setCurrentItem(item.at(0));
1650         }
1651
1652         // select first element if restoring failed
1653         if (convertersLW->currentRow() == -1)
1654                 convertersLW->setCurrentRow(0);
1655
1656         updateButtons();
1657 }
1658
1659
1660 void PrefConverters::switchConverter()
1661 {
1662         int const cnr = convertersLW->currentItem()->type();
1663         Converter const & c(form_->converters().get(cnr));
1664         converterFromCO->setCurrentIndex(form_->formats().getNumber(c.from()));
1665         converterToCO->setCurrentIndex(form_->formats().getNumber(c.to()));
1666         converterED->setText(toqstr(c.command()));
1667         converterFlagED->setText(toqstr(c.flags()));
1668
1669         updateButtons();
1670 }
1671
1672
1673 void PrefConverters::changeConverter()
1674 {
1675         updateButtons();
1676 }
1677
1678
1679 void PrefConverters::updateButtons()
1680 {
1681         if (form_->formats().empty())
1682                 return;
1683         Format const & from = form_->formats().get(converterFromCO->currentIndex());
1684         Format const & to = form_->formats().get(converterToCO->currentIndex());
1685         int const sel = form_->converters().getNumber(from.name(), to.name());
1686         bool const known = sel >= 0;
1687         bool const valid = !(converterED->text().isEmpty()
1688                 || from.name() == to.name());
1689
1690         string old_command;
1691         string old_flag;
1692
1693         if (convertersLW->count() > 0) {
1694                 int const cnr = convertersLW->currentItem()->type();
1695                 Converter const & c = form_->converters().get(cnr);
1696                 old_command = c.command();
1697                 old_flag = c.flags();
1698         }
1699
1700         string const new_command = fromqstr(converterED->text());
1701         string const new_flag = fromqstr(converterFlagED->text());
1702
1703         bool modified = (old_command != new_command || old_flag != new_flag);
1704
1705         converterModifyPB->setEnabled(valid && known && modified);
1706         converterNewPB->setEnabled(valid && !known);
1707         converterRemovePB->setEnabled(known);
1708
1709         maxAgeLE->setEnabled(cacheCB->isChecked());
1710         maxAgeLA->setEnabled(cacheCB->isChecked());
1711 }
1712
1713
1714 // FIXME: user must
1715 // specify unique from/to or it doesn't appear. This is really bad UI
1716 // this is why we can use the same function for both new and modify
1717 void PrefConverters::updateConverter()
1718 {
1719         Format const & from = form_->formats().get(converterFromCO->currentIndex());
1720         Format const & to = form_->formats().get(converterToCO->currentIndex());
1721         string const flags = fromqstr(converterFlagED->text());
1722         string const command = fromqstr(converterED->text());
1723
1724         Converter const * old =
1725                 form_->converters().getConverter(from.name(), to.name());
1726         form_->converters().add(from.name(), to.name(), command, flags);
1727
1728         if (!old)
1729                 form_->converters().updateLast(form_->formats());
1730
1731         updateGui();
1732
1733         // Remove all files created by this converter from the cache, since
1734         // the modified converter might create different files.
1735         ConverterCache::get().remove_all(from.name(), to.name());
1736 }
1737
1738
1739 void PrefConverters::removeConverter()
1740 {
1741         Format const & from = form_->formats().get(converterFromCO->currentIndex());
1742         Format const & to = form_->formats().get(converterToCO->currentIndex());
1743         form_->converters().erase(from.name(), to.name());
1744
1745         updateGui();
1746
1747         // Remove all files created by this converter from the cache, since
1748         // a possible new converter might create different files.
1749         ConverterCache::get().remove_all(from.name(), to.name());
1750 }
1751
1752
1753 void PrefConverters::on_cacheCB_stateChanged(int state)
1754 {
1755         maxAgeLE->setEnabled(state == Qt::Checked);
1756         maxAgeLA->setEnabled(state == Qt::Checked);
1757         changed();
1758 }
1759
1760
1761 /////////////////////////////////////////////////////////////////////
1762 //
1763 // FormatValidator
1764 //
1765 /////////////////////////////////////////////////////////////////////
1766
1767 class FormatValidator : public QValidator
1768 {
1769 public:
1770         FormatValidator(QWidget *, Formats const & f);
1771         void fixup(QString & input) const;
1772         QValidator::State validate(QString & input, int & pos) const;
1773 private:
1774         virtual QString toString(Format const & format) const = 0;
1775         int nr() const;
1776         Formats const & formats_;
1777 };
1778
1779
1780 FormatValidator::FormatValidator(QWidget * parent, Formats const & f)
1781         : QValidator(parent), formats_(f)
1782 {
1783 }
1784
1785
1786 void FormatValidator::fixup(QString & input) const
1787 {
1788         Formats::const_iterator cit = formats_.begin();
1789         Formats::const_iterator end = formats_.end();
1790         for (; cit != end; ++cit) {
1791                 QString const name = toString(*cit);
1792                 if (distance(formats_.begin(), cit) == nr()) {
1793                         input = name;
1794                         return;
1795                 }
1796         }
1797 }
1798
1799
1800 QValidator::State FormatValidator::validate(QString & input, int & /*pos*/) const
1801 {
1802         Formats::const_iterator cit = formats_.begin();
1803         Formats::const_iterator end = formats_.end();
1804         bool unknown = true;
1805         for (; unknown && cit != end; ++cit) {
1806                 QString const name = toString(*cit);
1807                 if (distance(formats_.begin(), cit) != nr())
1808                         unknown = name != input;
1809         }
1810
1811         if (unknown && !input.isEmpty())
1812                 return QValidator::Acceptable;
1813         else
1814                 return QValidator::Intermediate;
1815 }
1816
1817
1818 int FormatValidator::nr() const
1819 {
1820         QComboBox * p = qobject_cast<QComboBox *>(parent());
1821         return p->itemData(p->currentIndex()).toInt();
1822 }
1823
1824
1825 /////////////////////////////////////////////////////////////////////
1826 //
1827 // FormatNameValidator
1828 //
1829 /////////////////////////////////////////////////////////////////////
1830
1831 class FormatNameValidator : public FormatValidator
1832 {
1833 public:
1834         FormatNameValidator(QWidget * parent, Formats const & f)
1835                 : FormatValidator(parent, f)
1836         {}
1837 private:
1838         QString toString(Format const & format) const
1839         {
1840                 return toqstr(format.name());
1841         }
1842 };
1843
1844
1845 /////////////////////////////////////////////////////////////////////
1846 //
1847 // FormatPrettynameValidator
1848 //
1849 /////////////////////////////////////////////////////////////////////
1850
1851 class FormatPrettynameValidator : public FormatValidator
1852 {
1853 public:
1854         FormatPrettynameValidator(QWidget * parent, Formats const & f)
1855                 : FormatValidator(parent, f)
1856         {}
1857 private:
1858         QString toString(Format const & format) const
1859         {
1860                 return qt_(format.prettyname());
1861         }
1862 };
1863
1864
1865 /////////////////////////////////////////////////////////////////////
1866 //
1867 // PrefFileformats
1868 //
1869 /////////////////////////////////////////////////////////////////////
1870
1871 PrefFileformats::PrefFileformats(GuiPreferences * form)
1872         : PrefModule(catFiles, N_("File Formats"), form)
1873 {
1874         setupUi(this);
1875
1876         formatED->setValidator(new FormatNameValidator(formatsCB, form_->formats()));
1877         formatsCB->setValidator(new FormatPrettynameValidator(formatsCB, form_->formats()));
1878         extensionsED->setValidator(new NoNewLineValidator(extensionsED));
1879         shortcutED->setValidator(new NoNewLineValidator(shortcutED));
1880         editorED->setValidator(new NoNewLineValidator(editorED));
1881         viewerED->setValidator(new NoNewLineValidator(viewerED));
1882         copierED->setValidator(new NoNewLineValidator(copierED));
1883
1884         connect(documentCB, SIGNAL(clicked()),
1885                 this, SLOT(setFlags()));
1886         connect(vectorCB, SIGNAL(clicked()),
1887                 this, SLOT(setFlags()));
1888         connect(exportMenuCB, SIGNAL(clicked()),
1889                 this, SLOT(setFlags()));
1890         connect(formatsCB->lineEdit(), SIGNAL(editingFinished()),
1891                 this, SLOT(updatePrettyname()));
1892         connect(formatsCB->lineEdit(), SIGNAL(textEdited(QString)),
1893                 this, SIGNAL(changed()));
1894         connect(defaultFormatCB, SIGNAL(activated(QString)),
1895                 this, SIGNAL(changed()));
1896         connect(defaultOTFFormatCB, SIGNAL(activated(QString)),
1897                 this, SIGNAL(changed()));
1898         connect(viewerCO, SIGNAL(activated(int)),
1899                 this, SIGNAL(changed()));
1900         connect(editorCO, SIGNAL(activated(int)),
1901                 this, SIGNAL(changed()));
1902 }
1903
1904
1905 namespace {
1906
1907 string const l10n_shortcut(string const & prettyname, string const & shortcut)
1908 {
1909         if (shortcut.empty())
1910                 return string();
1911
1912         string l10n_format =
1913                 to_utf8(_(prettyname + '|' + shortcut));
1914         return split(l10n_format, '|');
1915 }
1916
1917 } // namespace anon
1918
1919
1920 void PrefFileformats::applyRC(LyXRC & rc) const
1921 {
1922         QString const default_format = defaultFormatCB->itemData(
1923                 defaultFormatCB->currentIndex()).toString();
1924         rc.default_view_format = fromqstr(default_format);
1925         QString const default_otf_format = defaultOTFFormatCB->itemData(
1926                 defaultOTFFormatCB->currentIndex()).toString();
1927         rc.default_otf_view_format = fromqstr(default_otf_format);
1928 }
1929
1930
1931 void PrefFileformats::updateRC(LyXRC const & rc)
1932 {
1933         viewer_alternatives = rc.viewer_alternatives;
1934         editor_alternatives = rc.editor_alternatives;
1935         bool const init = defaultFormatCB->currentText().isEmpty();
1936         updateView();
1937         if (init) {
1938                 int pos =
1939                         defaultFormatCB->findData(toqstr(rc.default_view_format));
1940                 defaultFormatCB->setCurrentIndex(pos);
1941                 pos = defaultOTFFormatCB->findData(toqstr(rc.default_otf_view_format));
1942                                 defaultOTFFormatCB->setCurrentIndex(pos);
1943                 defaultOTFFormatCB->setCurrentIndex(pos);
1944         }
1945 }
1946
1947
1948 void PrefFileformats::updateView()
1949 {
1950         QString const current = formatsCB->currentText();
1951         QString const current_def = defaultFormatCB->currentText();
1952         QString const current_def_otf = defaultOTFFormatCB->currentText();
1953
1954         // update comboboxes with formats
1955         formatsCB->blockSignals(true);
1956         defaultFormatCB->blockSignals(true);
1957         defaultOTFFormatCB->blockSignals(true);
1958         formatsCB->clear();
1959         defaultFormatCB->clear();
1960         defaultOTFFormatCB->clear();
1961         form_->formats().sort();
1962         Formats::const_iterator cit = form_->formats().begin();
1963         Formats::const_iterator end = form_->formats().end();
1964         for (; cit != end; ++cit) {
1965                 formatsCB->addItem(qt_(cit->prettyname()),
1966                                 QVariant(form_->formats().getNumber(cit->name())));
1967                 if (cit->viewer().empty())
1968                         continue;
1969                 if (form_->converters().isReachable("xhtml", cit->name())
1970                     || form_->converters().isReachable("dviluatex", cit->name())
1971                     || form_->converters().isReachable("luatex", cit->name())
1972                     || form_->converters().isReachable("xetex", cit->name())) {
1973                         defaultFormatCB->addItem(qt_(cit->prettyname()),
1974                                         QVariant(toqstr(cit->name())));
1975                         defaultOTFFormatCB->addItem(qt_(cit->prettyname()),
1976                                         QVariant(toqstr(cit->name())));
1977                 } else if (form_->converters().isReachable("latex", cit->name())
1978                            || form_->converters().isReachable("pdflatex", cit->name()))
1979                         defaultFormatCB->addItem(qt_(cit->prettyname()),
1980                                         QVariant(toqstr(cit->name())));
1981         }
1982
1983         // restore selections
1984         int item = formatsCB->findText(current, Qt::MatchExactly);
1985         formatsCB->setCurrentIndex(item < 0 ? 0 : item);
1986         on_formatsCB_currentIndexChanged(item < 0 ? 0 : item);
1987         item = defaultFormatCB->findText(current_def, Qt::MatchExactly);
1988         defaultFormatCB->setCurrentIndex(item < 0 ? 0 : item);
1989         item = defaultOTFFormatCB->findText(current_def_otf, Qt::MatchExactly);
1990         defaultOTFFormatCB->setCurrentIndex(item < 0 ? 0 : item);
1991         formatsCB->blockSignals(false);
1992         defaultFormatCB->blockSignals(false);
1993         defaultOTFFormatCB->blockSignals(false);
1994 }
1995
1996
1997 void PrefFileformats::on_formatsCB_currentIndexChanged(int i)
1998 {
1999         if (form_->formats().empty())
2000                 return;
2001         int const nr = formatsCB->itemData(i).toInt();
2002         Format const f = form_->formats().get(nr);
2003
2004         formatED->setText(toqstr(f.name()));
2005         copierED->setText(toqstr(form_->movers().command(f.name())));
2006         extensionsED->setText(toqstr(f.extensions()));
2007         mimeED->setText(toqstr(f.mime()));
2008         shortcutED->setText(
2009                 toqstr(l10n_shortcut(f.prettyname(), f.shortcut())));
2010         documentCB->setChecked((f.documentFormat()));
2011         vectorCB->setChecked((f.vectorFormat()));
2012         exportMenuCB->setChecked((f.inExportMenu()));
2013         exportMenuCB->setEnabled((f.documentFormat()));
2014         updateViewers();
2015         updateEditors();
2016 }
2017
2018
2019 void PrefFileformats::setFlags()
2020 {
2021         int flags = Format::none;
2022         if (documentCB->isChecked())
2023                 flags |= Format::document;
2024         if (vectorCB->isChecked())
2025                 flags |= Format::vector;
2026         if (exportMenuCB->isChecked())
2027                 flags |= Format::export_menu;
2028         currentFormat().setFlags(flags);
2029         exportMenuCB->setEnabled(documentCB->isChecked());
2030         changed();
2031 }
2032
2033
2034 void PrefFileformats::on_copierED_textEdited(const QString & s)
2035 {
2036         string const fmt = fromqstr(formatED->text());
2037         form_->movers().set(fmt, fromqstr(s));
2038         changed();
2039 }
2040
2041
2042 void PrefFileformats::on_extensionsED_textEdited(const QString & s)
2043 {
2044         currentFormat().setExtensions(fromqstr(s));
2045         changed();
2046 }
2047
2048
2049 void PrefFileformats::on_viewerED_textEdited(const QString & s)
2050 {
2051         currentFormat().setViewer(fromqstr(s));
2052         changed();
2053 }
2054
2055
2056 void PrefFileformats::on_editorED_textEdited(const QString & s)
2057 {
2058         currentFormat().setEditor(fromqstr(s));
2059         changed();
2060 }
2061
2062
2063 void PrefFileformats::on_mimeED_textEdited(const QString & s)
2064 {
2065         currentFormat().setMime(fromqstr(s));
2066         changed();
2067 }
2068
2069
2070 void PrefFileformats::on_shortcutED_textEdited(const QString & s)
2071 {
2072         string const new_shortcut = fromqstr(s);
2073         if (new_shortcut == l10n_shortcut(currentFormat().prettyname(),
2074                                           currentFormat().shortcut()))
2075                 return;
2076         currentFormat().setShortcut(new_shortcut);
2077         changed();
2078 }
2079
2080
2081 void PrefFileformats::on_formatED_editingFinished()
2082 {
2083         string const newname = fromqstr(formatED->displayText());
2084         string const oldname = currentFormat().name();
2085         if (newname == oldname)
2086                 return;
2087         if (form_->converters().formatIsUsed(oldname)) {
2088                 Alert::error(_("Format in use"),
2089                              _("You cannot change a format's short name "
2090                                "if the format is used by a converter. "
2091                                "Please remove the converter first."));
2092                 updateView();
2093                 return;
2094         }
2095
2096         currentFormat().setName(newname);
2097         changed();
2098 }
2099
2100
2101 void PrefFileformats::on_formatED_textChanged(const QString &)
2102 {
2103         QString t = formatED->text();
2104         int p = 0;
2105         bool valid = formatED->validator()->validate(t, p) == QValidator::Acceptable;
2106         setValid(formatLA, valid);
2107 }
2108
2109
2110 void PrefFileformats::on_formatsCB_editTextChanged(const QString &)
2111 {
2112         QString t = formatsCB->currentText();
2113         int p = 0;
2114         bool valid = formatsCB->validator()->validate(t, p) == QValidator::Acceptable;
2115         setValid(formatsLA, valid);
2116 }
2117
2118
2119 void PrefFileformats::updatePrettyname()
2120 {
2121         QString const newname = formatsCB->currentText();
2122         if (newname == qt_(currentFormat().prettyname()))
2123                 return;
2124
2125         currentFormat().setPrettyname(fromqstr(newname));
2126         formatsChanged();
2127         updateView();
2128         changed();
2129 }
2130
2131
2132 namespace {
2133         void updateComboBox(LyXRC::Alternatives const & alts,
2134                             string const & fmt, QComboBox * combo)
2135         {
2136                 LyXRC::Alternatives::const_iterator it =
2137                                 alts.find(fmt);
2138                 if (it != alts.end()) {
2139                         LyXRC::CommandSet const & cmds = it->second;
2140                         LyXRC::CommandSet::const_iterator sit =
2141                                         cmds.begin();
2142                         LyXRC::CommandSet::const_iterator const sen =
2143                                         cmds.end();
2144                         for (; sit != sen; ++sit) {
2145                                 QString const qcmd = toqstr(*sit);
2146                                 combo->addItem(qcmd, qcmd);
2147                         }
2148                 }
2149         }
2150 }
2151
2152
2153 void PrefFileformats::updateViewers()
2154 {
2155         Format const f = currentFormat();
2156         viewerCO->blockSignals(true);
2157         viewerCO->clear();
2158         viewerCO->addItem(qt_("None"), QString());
2159         updateComboBox(viewer_alternatives, f.name(), viewerCO);
2160         viewerCO->addItem(qt_("Custom"), QString("custom viewer"));
2161         viewerCO->blockSignals(false);
2162
2163         int pos = viewerCO->findData(toqstr(f.viewer()));
2164         if (pos != -1) {
2165                 viewerED->clear();
2166                 viewerED->setEnabled(false);
2167                 viewerCO->setCurrentIndex(pos);
2168         } else {
2169                 viewerED->setEnabled(true);
2170                 viewerED->setText(toqstr(f.viewer()));
2171                 viewerCO->setCurrentIndex(viewerCO->findData(toqstr("custom viewer")));
2172         }
2173 }
2174
2175
2176 void PrefFileformats::updateEditors()
2177 {
2178         Format const f = currentFormat();
2179         editorCO->blockSignals(true);
2180         editorCO->clear();
2181         editorCO->addItem(qt_("None"), QString());
2182         updateComboBox(editor_alternatives, f.name(), editorCO);
2183         editorCO->addItem(qt_("Custom"), QString("custom editor"));
2184         editorCO->blockSignals(false);
2185
2186         int pos = editorCO->findData(toqstr(f.editor()));
2187         if (pos != -1) {
2188                 editorED->clear();
2189                 editorED->setEnabled(false);
2190                 editorCO->setCurrentIndex(pos);
2191         } else {
2192                 editorED->setEnabled(true);
2193                 editorED->setText(toqstr(f.editor()));
2194                 editorCO->setCurrentIndex(editorCO->findData(toqstr("custom editor")));
2195         }
2196 }
2197
2198
2199 void PrefFileformats::on_viewerCO_currentIndexChanged(int i)
2200 {
2201         bool const custom = viewerCO->itemData(i).toString() == "custom viewer";
2202         viewerED->setEnabled(custom);
2203         if (!custom)
2204                 currentFormat().setViewer(fromqstr(viewerCO->itemData(i).toString()));
2205 }
2206
2207
2208 void PrefFileformats::on_editorCO_currentIndexChanged(int i)
2209 {
2210         bool const custom = editorCO->itemData(i).toString() == "custom editor";
2211         editorED->setEnabled(custom);
2212         if (!custom)
2213                 currentFormat().setEditor(fromqstr(editorCO->itemData(i).toString()));
2214 }
2215
2216
2217 Format & PrefFileformats::currentFormat()
2218 {
2219         int const i = formatsCB->currentIndex();
2220         int const nr = formatsCB->itemData(i).toInt();
2221         return form_->formats().get(nr);
2222 }
2223
2224
2225 void PrefFileformats::on_formatNewPB_clicked()
2226 {
2227         form_->formats().add("", "", "", "", "", "", "", Format::none);
2228         updateView();
2229         formatsCB->setCurrentIndex(0);
2230         formatsCB->setFocus(Qt::OtherFocusReason);
2231 }
2232
2233
2234 void PrefFileformats::on_formatRemovePB_clicked()
2235 {
2236         int const i = formatsCB->currentIndex();
2237         int const nr = formatsCB->itemData(i).toInt();
2238         string const current_text = form_->formats().get(nr).name();
2239         if (form_->converters().formatIsUsed(current_text)) {
2240                 Alert::error(_("Format in use"),
2241                              _("Cannot remove a Format used by a Converter. "
2242                                             "Remove the converter first."));
2243                 return;
2244         }
2245
2246         form_->formats().erase(current_text);
2247         formatsChanged();
2248         updateView();
2249         on_formatsCB_editTextChanged(formatsCB->currentText());
2250         changed();
2251 }
2252
2253
2254 /////////////////////////////////////////////////////////////////////
2255 //
2256 // PrefLanguage
2257 //
2258 /////////////////////////////////////////////////////////////////////
2259
2260 PrefLanguage::PrefLanguage(GuiPreferences * form)
2261         : PrefModule(catLanguage, N_("Language"), form)
2262 {
2263         setupUi(this);
2264
2265         connect(visualCursorRB, SIGNAL(clicked()),
2266                 this, SIGNAL(changed()));
2267         connect(logicalCursorRB, SIGNAL(clicked()),
2268                 this, SIGNAL(changed()));
2269         connect(markForeignCB, SIGNAL(clicked()),
2270                 this, SIGNAL(changed()));
2271         connect(autoBeginCB, SIGNAL(clicked()),
2272                 this, SIGNAL(changed()));
2273         connect(autoEndCB, SIGNAL(clicked()),
2274                 this, SIGNAL(changed()));
2275         connect(languagePackageCO, SIGNAL(activated(int)),
2276                 this, SIGNAL(changed()));
2277         connect(languagePackageED, SIGNAL(textChanged(QString)),
2278                 this, SIGNAL(changed()));
2279         connect(globalCB, SIGNAL(clicked()),
2280                 this, SIGNAL(changed()));
2281         connect(startCommandED, SIGNAL(textChanged(QString)),
2282                 this, SIGNAL(changed()));
2283         connect(endCommandED, SIGNAL(textChanged(QString)),
2284                 this, SIGNAL(changed()));
2285         connect(uiLanguageCO, SIGNAL(activated(int)),
2286                 this, SIGNAL(changed()));
2287         connect(defaultDecimalPointLE, SIGNAL(textChanged(QString)),
2288                 this, SIGNAL(changed()));
2289         connect(defaultLengthUnitCO, SIGNAL(activated(int)),
2290                 this, SIGNAL(changed()));
2291
2292         languagePackageED->setValidator(new NoNewLineValidator(languagePackageED));
2293         startCommandED->setValidator(new NoNewLineValidator(startCommandED));
2294         endCommandED->setValidator(new NoNewLineValidator(endCommandED));
2295
2296         uiLanguageCO->clear();
2297
2298         QAbstractItemModel * language_model = guiApp->languageModel();
2299         // FIXME: it would be nice if sorting was enabled/disabled via a checkbox.
2300         language_model->sort(0);
2301         defaultDecimalPointLE->setInputMask("X; ");
2302         defaultDecimalPointLE->setMaxLength(1);
2303
2304         defaultLengthUnitCO->addItem(lyx::qt_(unit_name_gui[Length::CM]), Length::CM);
2305         defaultLengthUnitCO->addItem(lyx::qt_(unit_name_gui[Length::IN]), Length::IN);
2306
2307         set<string> added;
2308         uiLanguageCO->blockSignals(true);
2309         uiLanguageCO->addItem(qt_("Default"), toqstr("auto"));
2310         for (int i = 0; i != language_model->rowCount(); ++i) {
2311                 QModelIndex index = language_model->index(i, 0);
2312                 // Filter the list based on the available translation and add
2313                 // each language code only once
2314                 string const name = fromqstr(index.data(Qt::UserRole).toString());
2315                 Language const * lang = languages.getLanguage(name);
2316                 if (!lang)
2317                         continue;
2318                 // never remove the currently selected language
2319                 if (name != form->rc().gui_language
2320                     && name != lyxrc.gui_language
2321                     && (!Messages::available(lang->code())
2322                         || added.find(lang->code()) != added.end()))
2323                                 continue;
2324                 added.insert(lang->code());
2325                 uiLanguageCO->addItem(index.data(Qt::DisplayRole).toString(),
2326                         index.data(Qt::UserRole).toString());
2327         }
2328         uiLanguageCO->blockSignals(false);
2329 }
2330
2331
2332 void PrefLanguage::on_uiLanguageCO_currentIndexChanged(int)
2333 {
2334          QMessageBox::information(this, qt_("LyX needs to be restarted!"),
2335                  qt_("The change of user interface language will be fully "
2336                  "effective only after a restart."));
2337 }
2338
2339
2340 void PrefLanguage::on_languagePackageCO_currentIndexChanged(int i)
2341 {
2342          languagePackageED->setEnabled(i == 2);
2343 }
2344
2345
2346 void PrefLanguage::applyRC(LyXRC & rc) const
2347 {
2348         rc.visual_cursor = visualCursorRB->isChecked();
2349         rc.mark_foreign_language = markForeignCB->isChecked();
2350         rc.language_auto_begin = autoBeginCB->isChecked();
2351         rc.language_auto_end = autoEndCB->isChecked();
2352         int const p = languagePackageCO->currentIndex();
2353         if (p == 0)
2354                 rc.language_package_selection = LyXRC::LP_AUTO;
2355         else if (p == 1)
2356                 rc.language_package_selection = LyXRC::LP_BABEL;
2357         else if (p == 2)
2358                 rc.language_package_selection = LyXRC::LP_CUSTOM;
2359         else if (p == 3)
2360                 rc.language_package_selection = LyXRC::LP_NONE;
2361         rc.language_custom_package = fromqstr(languagePackageED->text());
2362         rc.language_global_options = globalCB->isChecked();
2363         rc.language_command_begin = fromqstr(startCommandED->text());
2364         rc.language_command_end = fromqstr(endCommandED->text());
2365         rc.gui_language = fromqstr(
2366                 uiLanguageCO->itemData(uiLanguageCO->currentIndex()).toString());
2367         rc.default_decimal_point = fromqstr(defaultDecimalPointLE->text());
2368         rc.default_length_unit = (Length::UNIT) defaultLengthUnitCO->itemData(defaultLengthUnitCO->currentIndex()).toInt();
2369 }
2370
2371
2372 void PrefLanguage::updateRC(LyXRC const & rc)
2373 {
2374         if (rc.visual_cursor)
2375                 visualCursorRB->setChecked(true);
2376         else
2377                 logicalCursorRB->setChecked(true);
2378         markForeignCB->setChecked(rc.mark_foreign_language);
2379         autoBeginCB->setChecked(rc.language_auto_begin);
2380         autoEndCB->setChecked(rc.language_auto_end);
2381         languagePackageCO->setCurrentIndex(rc.language_package_selection);
2382         languagePackageED->setText(toqstr(rc.language_custom_package));
2383         languagePackageED->setEnabled(languagePackageCO->currentIndex() == 2);
2384         globalCB->setChecked(rc.language_global_options);
2385         startCommandED->setText(toqstr(rc.language_command_begin));
2386         endCommandED->setText(toqstr(rc.language_command_end));
2387         defaultDecimalPointLE->setText(toqstr(rc.default_decimal_point));
2388         int pos = defaultLengthUnitCO->findData(int(rc.default_length_unit));
2389         defaultLengthUnitCO->setCurrentIndex(pos);
2390
2391         pos = uiLanguageCO->findData(toqstr(rc.gui_language));
2392         uiLanguageCO->blockSignals(true);
2393         uiLanguageCO->setCurrentIndex(pos);
2394         uiLanguageCO->blockSignals(false);
2395 }
2396
2397
2398 /////////////////////////////////////////////////////////////////////
2399 //
2400 // PrefPrinter
2401 //
2402 /////////////////////////////////////////////////////////////////////
2403
2404 PrefPrinter::PrefPrinter(GuiPreferences * form)
2405         : PrefModule(catOutput, N_("Printer"), form)
2406 {
2407         setupUi(this);
2408
2409         connect(printerAdaptCB, SIGNAL(clicked()),
2410                 this, SIGNAL(changed()));
2411         connect(printerCommandED, SIGNAL(textChanged(QString)),
2412                 this, SIGNAL(changed()));
2413         connect(printerNameED, SIGNAL(textChanged(QString)),
2414                 this, SIGNAL(changed()));
2415         connect(printerPageRangeED, SIGNAL(textChanged(QString)),
2416                 this, SIGNAL(changed()));
2417         connect(printerCopiesED, SIGNAL(textChanged(QString)),
2418                 this, SIGNAL(changed()));
2419         connect(printerReverseED, SIGNAL(textChanged(QString)),
2420                 this, SIGNAL(changed()));
2421         connect(printerToPrinterED, SIGNAL(textChanged(QString)),
2422                 this, SIGNAL(changed()));
2423         connect(printerExtensionED, SIGNAL(textChanged(QString)),
2424                 this, SIGNAL(changed()));
2425         connect(printerSpoolCommandED, SIGNAL(textChanged(QString)),
2426                 this, SIGNAL(changed()));
2427         connect(printerPaperTypeED, SIGNAL(textChanged(QString)),
2428                 this, SIGNAL(changed()));
2429         connect(printerEvenED, SIGNAL(textChanged(QString)),
2430                 this, SIGNAL(changed()));
2431         connect(printerOddED, SIGNAL(textChanged(QString)),
2432                 this, SIGNAL(changed()));
2433         connect(printerCollatedED, SIGNAL(textChanged(QString)),
2434                 this, SIGNAL(changed()));
2435         connect(printerLandscapeED, SIGNAL(textChanged(QString)),
2436                 this, SIGNAL(changed()));
2437         connect(printerToFileED, SIGNAL(textChanged(QString)),
2438                 this, SIGNAL(changed()));
2439         connect(printerExtraED, SIGNAL(textChanged(QString)),
2440                 this, SIGNAL(changed()));
2441         connect(printerSpoolPrefixED, SIGNAL(textChanged(QString)),
2442                 this, SIGNAL(changed()));
2443         connect(printerPaperSizeED, SIGNAL(textChanged(QString)),
2444                 this, SIGNAL(changed()));
2445
2446         printerNameED->setValidator(new NoNewLineValidator(printerNameED));
2447         printerCommandED->setValidator(new NoNewLineValidator(printerCommandED));
2448         printerEvenED->setValidator(new NoNewLineValidator(printerEvenED));
2449         printerPageRangeED->setValidator(new NoNewLineValidator(printerPageRangeED));
2450         printerCopiesED->setValidator(new NoNewLineValidator(printerCopiesED));
2451         printerReverseED->setValidator(new NoNewLineValidator(printerReverseED));
2452         printerToFileED->setValidator(new NoNewLineValidator(printerToFileED));
2453         printerPaperTypeED->setValidator(new NoNewLineValidator(printerPaperTypeED));
2454         printerExtraED->setValidator(new NoNewLineValidator(printerExtraED));
2455         printerOddED->setValidator(new NoNewLineValidator(printerOddED));
2456         printerCollatedED->setValidator(new NoNewLineValidator(printerCollatedED));
2457         printerLandscapeED->setValidator(new NoNewLineValidator(printerLandscapeED));
2458         printerToPrinterED->setValidator(new NoNewLineValidator(printerToPrinterED));
2459         printerExtensionED->setValidator(new NoNewLineValidator(printerExtensionED));
2460         printerPaperSizeED->setValidator(new NoNewLineValidator(printerPaperSizeED));
2461         printerSpoolCommandED->setValidator(new NoNewLineValidator(printerSpoolCommandED));
2462         printerSpoolPrefixED->setValidator(new NoNewLineValidator(printerSpoolPrefixED));
2463 }
2464
2465
2466 void PrefPrinter::applyRC(LyXRC & rc) const
2467 {
2468         rc.print_adapt_output = printerAdaptCB->isChecked();
2469         rc.print_command = fromqstr(printerCommandED->text());
2470         rc.printer = fromqstr(printerNameED->text());
2471
2472         rc.print_pagerange_flag = fromqstr(printerPageRangeED->text());
2473         rc.print_copies_flag = fromqstr(printerCopiesED->text());
2474         rc.print_reverse_flag = fromqstr(printerReverseED->text());
2475         rc.print_to_printer = fromqstr(printerToPrinterED->text());
2476         rc.print_file_extension = fromqstr(printerExtensionED->text());
2477         rc.print_spool_command = fromqstr(printerSpoolCommandED->text());
2478         rc.print_paper_flag = fromqstr(printerPaperTypeED->text());
2479         rc.print_evenpage_flag = fromqstr(printerEvenED->text());
2480         rc.print_oddpage_flag = fromqstr(printerOddED->text());
2481         rc.print_collcopies_flag = fromqstr(printerCollatedED->text());
2482         rc.print_landscape_flag = fromqstr(printerLandscapeED->text());
2483         rc.print_to_file = internal_path(fromqstr(printerToFileED->text()));
2484         rc.print_extra_options = fromqstr(printerExtraED->text());
2485         rc.print_spool_printerprefix = fromqstr(printerSpoolPrefixED->text());
2486         rc.print_paper_dimension_flag = fromqstr(printerPaperSizeED->text());
2487 }
2488
2489
2490 void PrefPrinter::updateRC(LyXRC const & rc)
2491 {
2492         printerAdaptCB->setChecked(rc.print_adapt_output);
2493         printerCommandED->setText(toqstr(rc.print_command));
2494         printerNameED->setText(toqstr(rc.printer));
2495
2496         printerPageRangeED->setText(toqstr(rc.print_pagerange_flag));
2497         printerCopiesED->setText(toqstr(rc.print_copies_flag));
2498         printerReverseED->setText(toqstr(rc.print_reverse_flag));
2499         printerToPrinterED->setText(toqstr(rc.print_to_printer));
2500         printerExtensionED->setText(toqstr(rc.print_file_extension));
2501         printerSpoolCommandED->setText(toqstr(rc.print_spool_command));
2502         printerPaperTypeED->setText(toqstr(rc.print_paper_flag));
2503         printerEvenED->setText(toqstr(rc.print_evenpage_flag));
2504         printerOddED->setText(toqstr(rc.print_oddpage_flag));
2505         printerCollatedED->setText(toqstr(rc.print_collcopies_flag));
2506         printerLandscapeED->setText(toqstr(rc.print_landscape_flag));
2507         printerToFileED->setText(toqstr(external_path(rc.print_to_file)));
2508         printerExtraED->setText(toqstr(rc.print_extra_options));
2509         printerSpoolPrefixED->setText(toqstr(rc.print_spool_printerprefix));
2510         printerPaperSizeED->setText(toqstr(rc.print_paper_dimension_flag));
2511 }
2512
2513
2514 /////////////////////////////////////////////////////////////////////
2515 //
2516 // PrefUserInterface
2517 //
2518 /////////////////////////////////////////////////////////////////////
2519
2520 PrefUserInterface::PrefUserInterface(GuiPreferences * form)
2521         : PrefModule(catLookAndFeel, N_("User Interface"), form)
2522 {
2523         setupUi(this);
2524
2525         connect(uiFilePB, SIGNAL(clicked()),
2526                 this, SLOT(selectUi()));
2527         connect(uiFileED, SIGNAL(textChanged(QString)),
2528                 this, SIGNAL(changed()));
2529         connect(iconSetCO, SIGNAL(activated(int)),
2530                 this, SIGNAL(changed()));
2531         connect(useSystemThemeIconsCB, SIGNAL(clicked()),
2532                 this, SIGNAL(changed()));
2533         connect(lastfilesSB, SIGNAL(valueChanged(int)),
2534                 this, SIGNAL(changed()));
2535         connect(tooltipCB, SIGNAL(toggled(bool)),
2536                 this, SIGNAL(changed()));
2537         lastfilesSB->setMaximum(maxlastfiles);
2538
2539         iconSetCO->addItem(qt_("Default"), QString());
2540         iconSetCO->addItem(qt_("Classic"), "classic");
2541         iconSetCO->addItem(qt_("Oxygen"), "oxygen");
2542
2543 #if (!defined Q_WS_X11 || QT_VERSION < 0x040600)
2544         useSystemThemeIconsCB->hide();
2545 #endif
2546 }
2547
2548
2549 void PrefUserInterface::applyRC(LyXRC & rc) const
2550 {
2551         rc.icon_set = fromqstr(iconSetCO->itemData(
2552                 iconSetCO->currentIndex()).toString());
2553
2554         rc.ui_file = internal_path(fromqstr(uiFileED->text()));
2555         rc.use_system_theme_icons = useSystemThemeIconsCB->isChecked();
2556         rc.num_lastfiles = lastfilesSB->value();
2557         rc.use_tooltip = tooltipCB->isChecked();
2558 }
2559
2560
2561 void PrefUserInterface::updateRC(LyXRC const & rc)
2562 {
2563         int iconset = iconSetCO->findData(toqstr(rc.icon_set));
2564         if (iconset < 0)
2565                 iconset = 0;
2566         iconSetCO->setCurrentIndex(iconset);
2567         useSystemThemeIconsCB->setChecked(rc.use_system_theme_icons);
2568         uiFileED->setText(toqstr(external_path(rc.ui_file)));
2569         lastfilesSB->setValue(rc.num_lastfiles);
2570         tooltipCB->setChecked(rc.use_tooltip);
2571 }
2572
2573
2574 void PrefUserInterface::selectUi()
2575 {
2576         QString file = form_->browseUI(internalPath(uiFileED->text()));
2577         if (!file.isEmpty())
2578                 uiFileED->setText(file);
2579 }
2580
2581
2582 /////////////////////////////////////////////////////////////////////
2583 //
2584 // PrefDocumentHandling
2585 //
2586 /////////////////////////////////////////////////////////////////////
2587
2588 PrefDocHandling::PrefDocHandling(GuiPreferences * form)
2589         : PrefModule(catLookAndFeel, N_("Document Handling"), form)
2590 {
2591         setupUi(this);
2592
2593         connect(autoSaveCB, SIGNAL(toggled(bool)),
2594                 autoSaveSB, SLOT(setEnabled(bool)));
2595         connect(autoSaveCB, SIGNAL(toggled(bool)),
2596                 TextLabel1, SLOT(setEnabled(bool)));
2597         connect(openDocumentsInTabsCB, SIGNAL(clicked()),
2598                 this, SIGNAL(changed()));
2599         connect(singleInstanceCB, SIGNAL(clicked()),
2600                 this, SIGNAL(changed()));
2601         connect(singleCloseTabButtonCB, SIGNAL(clicked()),
2602                 this, SIGNAL(changed()));
2603         connect(closeLastViewCO, SIGNAL(activated(int)),
2604                 this, SIGNAL(changed()));
2605         connect(restoreCursorCB, SIGNAL(clicked()),
2606                 this, SIGNAL(changed()));
2607         connect(loadSessionCB, SIGNAL(clicked()),
2608                 this, SIGNAL(changed()));
2609         connect(allowGeometrySessionCB, SIGNAL(clicked()),
2610                 this, SIGNAL(changed()));
2611         connect(autoSaveSB, SIGNAL(valueChanged(int)),
2612                 this, SIGNAL(changed()));
2613         connect(autoSaveCB, SIGNAL(clicked()),
2614                 this, SIGNAL(changed()));
2615         connect(backupCB, SIGNAL(clicked()),
2616                 this, SIGNAL(changed()));
2617         connect(saveCompressedCB, SIGNAL(clicked()),
2618                 this, SIGNAL(changed()));
2619 }
2620
2621
2622 void PrefDocHandling::applyRC(LyXRC & rc) const
2623 {
2624         rc.use_lastfilepos = restoreCursorCB->isChecked();
2625         rc.load_session = loadSessionCB->isChecked();
2626         rc.allow_geometry_session = allowGeometrySessionCB->isChecked();
2627         rc.autosave = autoSaveCB->isChecked() ?  autoSaveSB->value() * 60 : 0;
2628         rc.make_backup = backupCB->isChecked();
2629         rc.save_compressed = saveCompressedCB->isChecked();
2630         rc.open_buffers_in_tabs = openDocumentsInTabsCB->isChecked();
2631         rc.single_instance = singleInstanceCB->isChecked();
2632         rc.single_close_tab_button = singleCloseTabButtonCB->isChecked();
2633
2634         switch (closeLastViewCO->currentIndex()) {
2635         case 0:
2636                 rc.close_buffer_with_last_view = "yes";
2637                 break;
2638         case 1:
2639                 rc.close_buffer_with_last_view = "no";
2640                 break;
2641         case 2:
2642                 rc.close_buffer_with_last_view = "ask";
2643                 break;
2644         default:
2645                 ;
2646         }
2647 }
2648
2649
2650 void PrefDocHandling::updateRC(LyXRC const & rc)
2651 {
2652         restoreCursorCB->setChecked(rc.use_lastfilepos);
2653         loadSessionCB->setChecked(rc.load_session);
2654         allowGeometrySessionCB->setChecked(rc.allow_geometry_session);
2655         // convert to minutes
2656         bool autosave = rc.autosave > 0;
2657         int mins = rc.autosave / 60;
2658         if (!mins)
2659                 mins = 5;
2660         autoSaveSB->setValue(mins);
2661         autoSaveCB->setChecked(autosave);
2662         autoSaveSB->setEnabled(autosave);
2663         backupCB->setChecked(rc.make_backup);
2664         saveCompressedCB->setChecked(rc.save_compressed);
2665         openDocumentsInTabsCB->setChecked(rc.open_buffers_in_tabs);
2666         singleInstanceCB->setChecked(rc.single_instance && !rc.lyxpipes.empty());
2667         singleInstanceCB->setEnabled(!rc.lyxpipes.empty());
2668         singleCloseTabButtonCB->setChecked(rc.single_close_tab_button);
2669         if (rc.close_buffer_with_last_view == "yes")
2670                 closeLastViewCO->setCurrentIndex(0);
2671         else if (rc.close_buffer_with_last_view == "no")
2672                 closeLastViewCO->setCurrentIndex(1);
2673         else if (rc.close_buffer_with_last_view == "ask")
2674                 closeLastViewCO->setCurrentIndex(2);
2675 }
2676
2677
2678 void PrefDocHandling::on_clearSessionPB_clicked()
2679 {
2680         guiApp->clearSession();
2681 }
2682
2683
2684
2685 /////////////////////////////////////////////////////////////////////
2686 //
2687 // PrefEdit
2688 //
2689 /////////////////////////////////////////////////////////////////////
2690
2691 PrefEdit::PrefEdit(GuiPreferences * form)
2692         : PrefModule(catEditing, N_("Control"), form)
2693 {
2694         setupUi(this);
2695
2696         connect(cursorFollowsCB, SIGNAL(clicked()),
2697                 this, SIGNAL(changed()));
2698         connect(scrollBelowCB, SIGNAL(clicked()),
2699                 this, SIGNAL(changed()));
2700         connect(macLikeCursorMovementCB, SIGNAL(clicked()),
2701                 this, SIGNAL(changed()));
2702         connect(sortEnvironmentsCB, SIGNAL(clicked()),
2703                 this, SIGNAL(changed()));
2704         connect(groupEnvironmentsCB, SIGNAL(clicked()),
2705                 this, SIGNAL(changed()));
2706         connect(macroEditStyleCO, SIGNAL(activated(int)),
2707                 this, SIGNAL(changed()));
2708         connect(cursorWidthSB, SIGNAL(valueChanged(int)),
2709                 this, SIGNAL(changed()));
2710         connect(fullscreenLimitGB, SIGNAL(clicked()),
2711                 this, SIGNAL(changed()));
2712         connect(fullscreenWidthSB, SIGNAL(valueChanged(int)),
2713                 this, SIGNAL(changed()));
2714         connect(toggleTabbarCB, SIGNAL(toggled(bool)),
2715                 this, SIGNAL(changed()));
2716         connect(toggleMenubarCB, SIGNAL(toggled(bool)),
2717                 this, SIGNAL(changed()));
2718         connect(toggleScrollbarCB, SIGNAL(toggled(bool)),
2719                 this, SIGNAL(changed()));
2720         connect(toggleStatusbarCB, SIGNAL(toggled(bool)),
2721                 this, SIGNAL(changed()));
2722         connect(toggleToolbarsCB, SIGNAL(toggled(bool)),
2723                 this, SIGNAL(changed()));
2724 }
2725
2726
2727 void PrefEdit::applyRC(LyXRC & rc) const
2728 {
2729         rc.cursor_follows_scrollbar = cursorFollowsCB->isChecked();
2730         rc.scroll_below_document = scrollBelowCB->isChecked();
2731         rc.mac_like_cursor_movement = macLikeCursorMovementCB->isChecked();
2732         rc.sort_layouts = sortEnvironmentsCB->isChecked();
2733         rc.group_layouts = groupEnvironmentsCB->isChecked();
2734         switch (macroEditStyleCO->currentIndex()) {
2735                 case 0: rc.macro_edit_style = LyXRC::MACRO_EDIT_INLINE_BOX; break;
2736                 case 1: rc.macro_edit_style = LyXRC::MACRO_EDIT_INLINE; break;
2737                 case 2: rc.macro_edit_style = LyXRC::MACRO_EDIT_LIST;   break;
2738         }
2739         rc.cursor_width = cursorWidthSB->value();
2740         rc.full_screen_toolbars = toggleToolbarsCB->isChecked();
2741         rc.full_screen_scrollbar = toggleScrollbarCB->isChecked();
2742         rc.full_screen_statusbar = toggleStatusbarCB->isChecked();
2743         rc.full_screen_tabbar = toggleTabbarCB->isChecked();
2744         rc.full_screen_menubar = toggleMenubarCB->isChecked();
2745         rc.full_screen_width = fullscreenWidthSB->value();
2746         rc.full_screen_limit = fullscreenLimitGB->isChecked();
2747 }
2748
2749
2750 void PrefEdit::updateRC(LyXRC const & rc)
2751 {
2752         cursorFollowsCB->setChecked(rc.cursor_follows_scrollbar);
2753         scrollBelowCB->setChecked(rc.scroll_below_document);
2754         macLikeCursorMovementCB->setChecked(rc.mac_like_cursor_movement);
2755         sortEnvironmentsCB->setChecked(rc.sort_layouts);
2756         groupEnvironmentsCB->setChecked(rc.group_layouts);
2757         macroEditStyleCO->setCurrentIndex(rc.macro_edit_style);
2758         cursorWidthSB->setValue(rc.cursor_width);
2759         toggleScrollbarCB->setChecked(rc.full_screen_scrollbar);
2760         toggleScrollbarCB->setChecked(rc.full_screen_statusbar);
2761         toggleToolbarsCB->setChecked(rc.full_screen_toolbars);
2762         toggleTabbarCB->setChecked(rc.full_screen_tabbar);
2763         toggleMenubarCB->setChecked(rc.full_screen_menubar);
2764         fullscreenWidthSB->setValue(rc.full_screen_width);
2765         fullscreenLimitGB->setChecked(rc.full_screen_limit);
2766 }
2767
2768
2769 /////////////////////////////////////////////////////////////////////
2770 //
2771 // PrefShortcuts
2772 //
2773 /////////////////////////////////////////////////////////////////////
2774
2775
2776 GuiShortcutDialog::GuiShortcutDialog(QWidget * parent) : QDialog(parent)
2777 {
2778         Ui::shortcutUi::setupUi(this);
2779         QDialog::setModal(true);
2780 }
2781
2782
2783 PrefShortcuts::PrefShortcuts(GuiPreferences * form)
2784         : PrefModule(catEditing, N_("Shortcuts"), form)
2785 {
2786         setupUi(this);
2787
2788         shortcutsTW->setColumnCount(2);
2789         shortcutsTW->headerItem()->setText(0, qt_("Function"));
2790         shortcutsTW->headerItem()->setText(1, qt_("Shortcut"));
2791         shortcutsTW->setSortingEnabled(true);
2792         // Multi-selection can be annoying.
2793         // shortcutsTW->setSelectionMode(QAbstractItemView::MultiSelection);
2794
2795         connect(bindFilePB, SIGNAL(clicked()),
2796                 this, SLOT(selectBind()));
2797         connect(bindFileED, SIGNAL(textChanged(QString)),
2798                 this, SIGNAL(changed()));
2799
2800         shortcut_ = new GuiShortcutDialog(this);
2801         shortcut_bc_.setPolicy(ButtonPolicy::OkCancelPolicy);
2802         shortcut_bc_.setOK(shortcut_->okPB);
2803         shortcut_bc_.setCancel(shortcut_->cancelPB);
2804
2805         connect(shortcut_->okPB, SIGNAL(clicked()),
2806                 this, SIGNAL(changed()));
2807         connect(shortcut_->cancelPB, SIGNAL(clicked()),
2808                 shortcut_, SLOT(reject()));
2809         connect(shortcut_->clearPB, SIGNAL(clicked()),
2810                 this, SLOT(shortcutClearPressed()));
2811         connect(shortcut_->removePB, SIGNAL(clicked()),
2812                 this, SLOT(shortcutRemovePressed()));
2813         connect(shortcut_->okPB, SIGNAL(clicked()),
2814                 this, SLOT(shortcutOkPressed()));
2815         connect(shortcut_->cancelPB, SIGNAL(clicked()),
2816                 this, SLOT(shortcutCancelPressed()));
2817 }
2818
2819
2820 void PrefShortcuts::applyRC(LyXRC & rc) const
2821 {
2822         rc.bind_file = internal_path(fromqstr(bindFileED->text()));
2823         // write user_bind and user_unbind to .lyx/bind/user.bind
2824         FileName bind_dir(addPath(package().user_support().absFileName(), "bind"));
2825         if (!bind_dir.exists() && !bind_dir.createDirectory(0777)) {
2826                 lyxerr << "LyX could not create the user bind directory '"
2827                        << bind_dir << "'. All user-defined key bindings will be lost." << endl;
2828                 return;
2829         }
2830         if (!bind_dir.isDirWritable()) {
2831                 lyxerr << "LyX could not write to the user bind directory '"
2832                        << bind_dir << "'. All user-defined key bindings will be lost." << endl;
2833                 return;
2834         }
2835         FileName user_bind_file(bind_dir.absFileName() + "/user.bind");
2836         user_unbind_.write(user_bind_file.toFilesystemEncoding(), false, true);
2837         user_bind_.write(user_bind_file.toFilesystemEncoding(), true, false);
2838         // immediately apply the keybindings. Why this is not done before?
2839         // The good thing is that the menus are updated automatically.
2840         theTopLevelKeymap().clear();
2841         theTopLevelKeymap().read("site");
2842         theTopLevelKeymap().read(rc.bind_file, 0, KeyMap::Fallback);
2843         theTopLevelKeymap().read("user", 0, KeyMap::MissingOK);
2844 }
2845
2846
2847 void PrefShortcuts::updateRC(LyXRC const & rc)
2848 {
2849         bindFileED->setText(toqstr(external_path(rc.bind_file)));
2850         //
2851         system_bind_.clear();
2852         user_bind_.clear();
2853         user_unbind_.clear();
2854         system_bind_.read("site");
2855         system_bind_.read(rc.bind_file);
2856         // \unbind in user.bind is added to user_unbind_
2857         user_bind_.read("user", &user_unbind_, KeyMap::MissingOK);
2858         updateShortcutsTW();
2859 }
2860
2861
2862 void PrefShortcuts::updateShortcutsTW()
2863 {
2864         shortcutsTW->clear();
2865
2866         editItem_ = new QTreeWidgetItem(shortcutsTW);
2867         editItem_->setText(0, qt_("Cursor, Mouse and Editing Functions"));
2868         editItem_->setFlags(editItem_->flags() & ~Qt::ItemIsSelectable);
2869
2870         mathItem_ = new QTreeWidgetItem(shortcutsTW);
2871         mathItem_->setText(0, qt_("Mathematical Symbols"));
2872         mathItem_->setFlags(mathItem_->flags() & ~Qt::ItemIsSelectable);
2873
2874         bufferItem_ = new QTreeWidgetItem(shortcutsTW);
2875         bufferItem_->setText(0, qt_("Document and Window"));
2876         bufferItem_->setFlags(bufferItem_->flags() & ~Qt::ItemIsSelectable);
2877
2878         layoutItem_ = new QTreeWidgetItem(shortcutsTW);
2879         layoutItem_->setText(0, qt_("Font, Layouts and Textclasses"));
2880         layoutItem_->setFlags(layoutItem_->flags() & ~Qt::ItemIsSelectable);
2881
2882         systemItem_ = new QTreeWidgetItem(shortcutsTW);
2883         systemItem_->setText(0, qt_("System and Miscellaneous"));
2884         systemItem_->setFlags(systemItem_->flags() & ~Qt::ItemIsSelectable);
2885
2886         // listBindings(unbound=true) lists all bound and unbound lfuns
2887         // Items in this list is tagged by its source.
2888         KeyMap::BindingList bindinglist = system_bind_.listBindings(true,
2889                 KeyMap::System);
2890         KeyMap::BindingList user_bindinglist = user_bind_.listBindings(false,
2891                 KeyMap::UserBind);
2892         KeyMap::BindingList user_unbindinglist = user_unbind_.listBindings(false,
2893                 KeyMap::UserUnbind);
2894         bindinglist.insert(bindinglist.end(), user_bindinglist.begin(),
2895                         user_bindinglist.end());
2896         bindinglist.insert(bindinglist.end(), user_unbindinglist.begin(),
2897                         user_unbindinglist.end());
2898
2899         KeyMap::BindingList::const_iterator it = bindinglist.begin();
2900         KeyMap::BindingList::const_iterator it_end = bindinglist.end();
2901         for (; it != it_end; ++it)
2902                 insertShortcutItem(it->request, it->sequence, KeyMap::ItemType(it->tag));
2903
2904         shortcutsTW->sortItems(0, Qt::AscendingOrder);
2905         QList<QTreeWidgetItem*> items = shortcutsTW->selectedItems();
2906         removePB->setEnabled(!items.isEmpty() && !items[0]->text(1).isEmpty());
2907         modifyPB->setEnabled(!items.isEmpty());
2908
2909         shortcutsTW->resizeColumnToContents(0);
2910 }
2911
2912
2913 void PrefShortcuts::setItemType(QTreeWidgetItem * item, KeyMap::ItemType tag)
2914 {
2915         item->setData(0, Qt::UserRole, QVariant(tag));
2916         QFont font;
2917
2918         switch (tag) {
2919         case KeyMap::System:
2920                 break;
2921         case KeyMap::UserBind:
2922                 font.setBold(true);
2923                 break;
2924         case KeyMap::UserUnbind:
2925                 font.setStrikeOut(true);
2926                 break;
2927         // this item is not displayed now.
2928         case KeyMap::UserExtraUnbind:
2929                 font.setStrikeOut(true);
2930                 break;
2931         }
2932
2933         item->setFont(1, font);
2934 }
2935
2936
2937 QTreeWidgetItem * PrefShortcuts::insertShortcutItem(FuncRequest const & lfun,
2938                 KeySequence const & seq, KeyMap::ItemType tag)
2939 {
2940         FuncCode const action = lfun.action();
2941         string const action_name = lyxaction.getActionName(action);
2942         QString const lfun_name = toqstr(from_utf8(action_name)
2943                         + ' ' + lfun.argument());
2944         QString const shortcut = toqstr(seq.print(KeySequence::ForGui));
2945         KeyMap::ItemType item_tag = tag;
2946
2947         QTreeWidgetItem * newItem = 0;
2948         // for unbind items, try to find an existing item in the system bind list
2949         if (tag == KeyMap::UserUnbind) {
2950                 QList<QTreeWidgetItem*> const items = shortcutsTW->findItems(lfun_name,
2951                         Qt::MatchFlags(Qt::MatchExactly | Qt::MatchRecursive), 0);
2952                 for (int i = 0; i < items.size(); ++i) {
2953                         if (items[i]->text(1) == shortcut)
2954                                 newItem = items[i];
2955                                 break;
2956                         }
2957                 // if not found, this unbind item is KeyMap::UserExtraUnbind
2958                 // Such an item is not displayed to avoid confusion (what is
2959                 // unmatched removed?).
2960                 if (!newItem) {
2961                         item_tag = KeyMap::UserExtraUnbind;
2962                         return 0;
2963                 }
2964         }
2965         if (!newItem) {
2966                 switch(lyxaction.getActionType(action)) {
2967                 case LyXAction::Hidden:
2968                         return 0;
2969                 case LyXAction::Edit:
2970                         newItem = new QTreeWidgetItem(editItem_);
2971                         break;
2972                 case LyXAction::Math:
2973                         newItem = new QTreeWidgetItem(mathItem_);
2974                         break;
2975                 case LyXAction::Buffer:
2976                         newItem = new QTreeWidgetItem(bufferItem_);
2977                         break;
2978                 case LyXAction::Layout:
2979                         newItem = new QTreeWidgetItem(layoutItem_);
2980                         break;
2981                 case LyXAction::System:
2982                         newItem = new QTreeWidgetItem(systemItem_);
2983                         break;
2984                 default:
2985                         // this should not happen
2986                         newItem = new QTreeWidgetItem(shortcutsTW);
2987                 }
2988         }
2989
2990         newItem->setText(0, lfun_name);
2991         newItem->setText(1, shortcut);
2992         // record BindFile representation to recover KeySequence when needed.
2993         newItem->setData(1, Qt::UserRole, toqstr(seq.print(KeySequence::BindFile)));
2994         setItemType(newItem, item_tag);
2995         return newItem;
2996 }
2997
2998
2999 void PrefShortcuts::on_shortcutsTW_itemSelectionChanged()
3000 {
3001         QList<QTreeWidgetItem*> items = shortcutsTW->selectedItems();
3002         removePB->setEnabled(!items.isEmpty() && !items[0]->text(1).isEmpty());
3003         modifyPB->setEnabled(!items.isEmpty());
3004         if (items.isEmpty())
3005                 return;
3006
3007         KeyMap::ItemType tag =
3008                 static_cast<KeyMap::ItemType>(items[0]->data(0, Qt::UserRole).toInt());
3009         if (tag == KeyMap::UserUnbind)
3010                 removePB->setText(qt_("Res&tore"));
3011         else
3012                 removePB->setText(qt_("Remo&ve"));
3013 }
3014
3015
3016 void PrefShortcuts::on_shortcutsTW_itemDoubleClicked()
3017 {
3018         modifyShortcut();
3019 }
3020
3021
3022 void PrefShortcuts::modifyShortcut()
3023 {
3024         QTreeWidgetItem * item = shortcutsTW->currentItem();
3025         if (item->flags() & Qt::ItemIsSelectable) {
3026                 shortcut_->lfunLE->setText(item->text(0));
3027                 save_lfun_ = item->text(0).trimmed();
3028                 shortcut_->shortcutWG->setText(item->text(1));
3029                 KeySequence seq;
3030                 seq.parse(fromqstr(item->data(1, Qt::UserRole).toString()));
3031                 shortcut_->shortcutWG->setKeySequence(seq);
3032                 shortcut_->shortcutWG->setFocus();
3033                 shortcut_->exec();
3034         }
3035 }
3036
3037
3038 void PrefShortcuts::removeShortcut()
3039 {
3040         // it seems that only one item can be selected, but I am
3041         // removing all selected items anyway.
3042         QList<QTreeWidgetItem*> items = shortcutsTW->selectedItems();
3043         for (int i = 0; i < items.size(); ++i) {
3044                 string shortcut = fromqstr(items[i]->data(1, Qt::UserRole).toString());
3045                 string lfun = fromqstr(items[i]->text(0));
3046                 FuncRequest func = lyxaction.lookupFunc(lfun);
3047                 KeyMap::ItemType tag =
3048                         static_cast<KeyMap::ItemType>(items[i]->data(0, Qt::UserRole).toInt());
3049
3050                 switch (tag) {
3051                 case KeyMap::System: {
3052                         // for system bind, we do not touch the item
3053                         // but add an user unbind item
3054                         user_unbind_.bind(shortcut, func);
3055                         setItemType(items[i], KeyMap::UserUnbind);
3056                         removePB->setText(qt_("Res&tore"));
3057                         break;
3058                 }
3059                 case KeyMap::UserBind: {
3060                         // for user_bind, we remove this bind
3061                         QTreeWidgetItem * parent = items[i]->parent();
3062                         int itemIdx = parent->indexOfChild(items[i]);
3063                         parent->takeChild(itemIdx);
3064                         if (itemIdx > 0)
3065                                 shortcutsTW->scrollToItem(parent->child(itemIdx - 1));
3066                         else
3067                                 shortcutsTW->scrollToItem(parent);
3068                         user_bind_.unbind(shortcut, func);
3069                         break;
3070                 }
3071                 case KeyMap::UserUnbind: {
3072                         // for user_unbind, we remove the unbind, and the item
3073                         // become KeyMap::System again.
3074                         user_unbind_.unbind(shortcut, func);
3075                         setItemType(items[i], KeyMap::System);
3076                         removePB->setText(qt_("Remo&ve"));
3077                         break;
3078                 }
3079                 case KeyMap::UserExtraUnbind: {
3080                         // for user unbind that is not in system bind file,
3081                         // remove this unbind file
3082                         QTreeWidgetItem * parent = items[i]->parent();
3083                         parent->takeChild(parent->indexOfChild(items[i]));
3084                         user_unbind_.unbind(shortcut, func);
3085                 }
3086                 }
3087         }
3088 }
3089
3090
3091 void PrefShortcuts::selectBind()
3092 {
3093         QString file = form_->browsebind(internalPath(bindFileED->text()));
3094         if (!file.isEmpty()) {
3095                 bindFileED->setText(file);
3096                 system_bind_ = KeyMap();
3097                 system_bind_.read(fromqstr(file));
3098                 updateShortcutsTW();
3099         }
3100 }
3101
3102
3103 void PrefShortcuts::on_modifyPB_pressed()
3104 {
3105         modifyShortcut();
3106 }
3107
3108
3109 void PrefShortcuts::on_newPB_pressed()
3110 {
3111         shortcut_->lfunLE->clear();
3112         shortcut_->shortcutWG->reset();
3113         save_lfun_ = QString();
3114         shortcut_->exec();
3115 }
3116
3117
3118 void PrefShortcuts::on_removePB_pressed()
3119 {
3120         changed();
3121         removeShortcut();
3122 }
3123
3124
3125 void PrefShortcuts::on_searchLE_textEdited()
3126 {
3127         if (searchLE->text().isEmpty()) {
3128                 // show all hidden items
3129                 QTreeWidgetItemIterator it(shortcutsTW, QTreeWidgetItemIterator::Hidden);
3130                 while (*it)
3131                         shortcutsTW->setItemHidden(*it++, false);
3132                 return;
3133         }
3134         // search both columns
3135         QList<QTreeWidgetItem *> matched = shortcutsTW->findItems(searchLE->text(),
3136                 Qt::MatchFlags(Qt::MatchContains | Qt::MatchRecursive), 0);
3137         matched += shortcutsTW->findItems(searchLE->text(),
3138                 Qt::MatchFlags(Qt::MatchContains | Qt::MatchRecursive), 1);
3139
3140         // hide everyone (to avoid searching in matched QList repeatedly
3141         QTreeWidgetItemIterator it(shortcutsTW, QTreeWidgetItemIterator::Selectable);
3142         while (*it)
3143                 shortcutsTW->setItemHidden(*it++, true);
3144         // show matched items
3145         for (int i = 0; i < matched.size(); ++i) {
3146                 shortcutsTW->setItemHidden(matched[i], false);
3147         shortcutsTW->setItemExpanded(matched[i]->parent(), true);
3148         }
3149 }
3150
3151
3152 docstring makeCmdString(FuncRequest const & f)
3153 {
3154         docstring actionStr = from_ascii(lyxaction.getActionName(f.action()));
3155         if (!f.argument().empty())
3156                 actionStr += " " + f.argument();
3157         return actionStr;
3158 }
3159
3160
3161 void PrefShortcuts::shortcutOkPressed()
3162 {
3163         QString const new_lfun = shortcut_->lfunLE->text();
3164         FuncRequest func = lyxaction.lookupFunc(fromqstr(new_lfun));
3165
3166         if (func.action() == LFUN_UNKNOWN_ACTION) {
3167                 Alert::error(_("Failed to create shortcut"),
3168                         _("Unknown or invalid LyX function"));
3169                 return;
3170         }
3171
3172         KeySequence k = shortcut_->shortcutWG->getKeySequence();
3173         if (k.length() == 0) {
3174                 Alert::error(_("Failed to create shortcut"),
3175                         _("Invalid or empty key sequence"));
3176                 return;
3177         }
3178
3179         // check to see if there's been any change
3180         FuncRequest oldBinding = system_bind_.getBinding(k);
3181         if (oldBinding.action() == LFUN_UNKNOWN_ACTION)
3182                 oldBinding = user_bind_.getBinding(k);
3183         if (oldBinding == func)
3184                 // nothing has changed
3185                 return;
3186
3187         // make sure this key isn't already bound---and, if so, prompt user
3188         FuncCode const unbind = user_unbind_.getBinding(k).action();
3189         docstring const action_string = makeCmdString(oldBinding);
3190         if (oldBinding.action() > LFUN_NOACTION && unbind == LFUN_UNKNOWN_ACTION
3191                   && save_lfun_ != toqstr(action_string)) {
3192                 docstring const new_action_string = makeCmdString(func);
3193                 docstring const text = bformat(_("Shortcut `%1$s' is already bound to "
3194                                                  "%2$s.\n"
3195                                                  "Are you sure you want to unbind the "
3196                                                  "current shortcut and bind it to %3$s?"),
3197                                                k.print(KeySequence::ForGui), action_string,
3198                                                new_action_string);
3199                 int ret = Alert::prompt(_("Redefine shortcut?"),
3200                                         text, 0, 1, _("&Redefine"), _("&Cancel"));
3201                 if (ret != 0)
3202                         return;
3203                 QString const sequence_text = toqstr(k.print(KeySequence::ForGui));
3204                 QList<QTreeWidgetItem*> items = shortcutsTW->findItems(sequence_text,
3205                         Qt::MatchFlags(Qt::MatchExactly | Qt::MatchRecursive), 1);
3206                 if (items.size() > 0) {
3207                         // should always happen
3208                         bool expanded = items[0]->parent()->isExpanded();
3209                         shortcutsTW->setCurrentItem(items[0]);
3210                         removeShortcut();
3211                         shortcutsTW->setCurrentItem(0);
3212                         // make sure user doesn't see tree expansion if
3213                         // old binding wasn't in an expanded tree
3214                         if (!expanded)
3215                                 items[0]->parent()->setExpanded(false);
3216                 }
3217         }
3218
3219         shortcut_->accept();
3220
3221         if (!save_lfun_.isEmpty())
3222                 // real modification of the lfun's shortcut,
3223                 // so remove the previous one
3224                 removeShortcut();
3225
3226         QTreeWidgetItem * item = insertShortcutItem(func, k, KeyMap::UserBind);
3227         if (item) {
3228                 user_bind_.bind(&k, func);
3229                 shortcutsTW->sortItems(0, Qt::AscendingOrder);
3230                 shortcutsTW->setItemExpanded(item->parent(), true);
3231                 shortcutsTW->scrollToItem(item);
3232         } else {
3233                 Alert::error(_("Failed to create shortcut"),
3234                         _("Can not insert shortcut to the list"));
3235                 return;
3236         }
3237 }
3238
3239
3240 void PrefShortcuts::shortcutCancelPressed()
3241 {
3242         shortcut_->shortcutWG->reset();
3243 }
3244
3245
3246 void PrefShortcuts::shortcutClearPressed()
3247 {
3248         shortcut_->shortcutWG->reset();
3249 }
3250
3251
3252 void PrefShortcuts::shortcutRemovePressed()
3253 {
3254         shortcut_->shortcutWG->removeFromSequence();
3255 }
3256
3257
3258 /////////////////////////////////////////////////////////////////////
3259 //
3260 // PrefIdentity
3261 //
3262 /////////////////////////////////////////////////////////////////////
3263
3264 PrefIdentity::PrefIdentity(GuiPreferences * form)
3265         : PrefModule(QString(), N_("Identity"), form)
3266 {
3267         setupUi(this);
3268
3269         connect(nameED, SIGNAL(textChanged(QString)),
3270                 this, SIGNAL(changed()));
3271         connect(emailED, SIGNAL(textChanged(QString)),
3272                 this, SIGNAL(changed()));
3273
3274         nameED->setValidator(new NoNewLineValidator(nameED));
3275         emailED->setValidator(new NoNewLineValidator(emailED));
3276 }
3277
3278
3279 void PrefIdentity::applyRC(LyXRC & rc) const
3280 {
3281         rc.user_name = fromqstr(nameED->text());
3282         rc.user_email = fromqstr(emailED->text());
3283 }
3284
3285
3286 void PrefIdentity::updateRC(LyXRC const & rc)
3287 {
3288         nameED->setText(toqstr(rc.user_name));
3289         emailED->setText(toqstr(rc.user_email));
3290 }
3291
3292
3293
3294 /////////////////////////////////////////////////////////////////////
3295 //
3296 // GuiPreferences
3297 //
3298 /////////////////////////////////////////////////////////////////////
3299
3300 GuiPreferences::GuiPreferences(GuiView & lv)
3301         : GuiDialog(lv, "prefs", qt_("Preferences")), update_screen_font_(false)
3302 {
3303         setupUi(this);
3304
3305         QDialog::setModal(false);
3306
3307         connect(savePB, SIGNAL(clicked()), this, SLOT(slotOK()));
3308         connect(applyPB, SIGNAL(clicked()), this, SLOT(slotApplyRC()));
3309         connect(closePB, SIGNAL(clicked()), this, SLOT(slotClose()));
3310         connect(restorePB, SIGNAL(clicked()), this, SLOT(slotRestore()));
3311
3312         addModule(new PrefUserInterface(this));
3313         addModule(new PrefDocHandling(this));
3314         addModule(new PrefEdit(this));
3315         addModule(new PrefShortcuts(this));
3316         PrefScreenFonts * screenfonts = new PrefScreenFonts(this);
3317         connect(this, SIGNAL(prefsApplied(LyXRC const &)),
3318                         screenfonts, SLOT(updateScreenFontSizes(LyXRC const &)));
3319         addModule(screenfonts);
3320         addModule(new PrefColors(this));
3321         addModule(new PrefDisplay(this));
3322         addModule(new PrefInput(this));
3323         addModule(new PrefCompletion(this));
3324
3325         addModule(new PrefPaths(this));
3326
3327         addModule(new PrefIdentity(this));
3328
3329         addModule(new PrefLanguage(this));
3330         addModule(new PrefSpellchecker(this));
3331
3332         //for strftime validator
3333         PrefOutput * output = new PrefOutput(this);
3334         addModule(output);
3335         addModule(new PrefPrinter(this));
3336         addModule(new PrefLatex(this));
3337
3338         PrefConverters * converters = new PrefConverters(this);
3339         PrefFileformats * formats = new PrefFileformats(this);
3340         connect(formats, SIGNAL(formatsChanged()),
3341                         converters, SLOT(updateGui()));
3342         addModule(converters);
3343         addModule(formats);
3344
3345         prefsPS->setCurrentPanel("User Interface");
3346 // FIXME: hack to work around resizing bug in Qt >= 4.2
3347 // bug verified with Qt 4.2.{0-3} (JSpitzm)
3348 #if QT_VERSION >= 0x040200
3349         prefsPS->updateGeometry();
3350 #endif
3351
3352         bc().setPolicy(ButtonPolicy::PreferencesPolicy);
3353         bc().setOK(savePB);
3354         bc().setApply(applyPB);
3355         bc().setCancel(closePB);
3356         bc().setRestore(restorePB);
3357
3358         // initialize the strftime validator
3359         bc().addCheckedLineEdit(output->DateED);
3360 }
3361
3362
3363 void GuiPreferences::addModule(PrefModule * module)
3364 {
3365         LASSERT(module, return);
3366         if (module->category().isEmpty())
3367                 prefsPS->addPanel(module, module->title());
3368         else
3369                 prefsPS->addPanel(module, module->title(), module->category());
3370         connect(module, SIGNAL(changed()), this, SLOT(change_adaptor()));
3371         modules_.push_back(module);
3372 }
3373
3374
3375 void GuiPreferences::change_adaptor()
3376 {
3377         changed();
3378 }
3379
3380
3381 void GuiPreferences::applyRC(LyXRC & rc) const
3382 {
3383         size_t end = modules_.size();
3384         for (size_t i = 0; i != end; ++i)
3385                 modules_[i]->applyRC(rc);
3386 }
3387
3388
3389 void GuiPreferences::updateRC(LyXRC const & rc)
3390 {
3391         size_t const end = modules_.size();
3392         for (size_t i = 0; i != end; ++i)
3393                 modules_[i]->updateRC(rc);
3394 }
3395
3396
3397 void GuiPreferences::applyView()
3398 {
3399         applyRC(rc());
3400 }
3401
3402
3403 bool GuiPreferences::initialiseParams(string const &)
3404 {
3405         rc_ = lyxrc;
3406         formats_ = lyx::formats;
3407         converters_ = theConverters();
3408         converters_.update(formats_);
3409         movers_ = theMovers();
3410         colors_.clear();
3411         update_screen_font_ = false;
3412
3413         updateRC(rc_);
3414         // Make sure that the bc is in the INITIAL state
3415         if (bc().policy().buttonStatus(ButtonPolicy::RESTORE))
3416                 bc().restore();
3417
3418         return true;
3419 }
3420
3421
3422 void GuiPreferences::dispatchParams()
3423 {
3424         ostringstream ss;
3425         rc_.write(ss, true);
3426         dispatch(FuncRequest(LFUN_LYXRC_APPLY, ss.str()));
3427         // issue prefsApplied signal. This will update the
3428         // localized screen font sizes.
3429         prefsApplied(rc_);
3430         // FIXME: these need lfuns
3431         // FIXME UNICODE
3432         Author const & author =
3433                 Author(from_utf8(rc_.user_name), from_utf8(rc_.user_email));
3434         theBufferList().recordCurrentAuthor(author);
3435
3436         lyx::formats = formats_;
3437
3438         theConverters() = converters_;
3439         theConverters().update(lyx::formats);
3440         theConverters().buildGraph();
3441
3442         theMovers() = movers_;
3443
3444         vector<string>::const_iterator it = colors_.begin();
3445         vector<string>::const_iterator const end = colors_.end();
3446         for (; it != end; ++it)
3447                 dispatch(FuncRequest(LFUN_SET_COLOR, *it));
3448         colors_.clear();
3449
3450         if (update_screen_font_) {
3451                 dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3452                 update_screen_font_ = false;
3453         }
3454
3455         // The Save button has been pressed
3456         if (isClosing())
3457                 dispatch(FuncRequest(LFUN_PREFERENCES_SAVE));
3458 }
3459
3460
3461 void GuiPreferences::setColor(ColorCode col, QString const & hex)
3462 {
3463         colors_.push_back(lcolor.getLyXName(col) + ' ' + fromqstr(hex));
3464 }
3465
3466
3467 void GuiPreferences::updateScreenFonts()
3468 {
3469         update_screen_font_ = true;
3470 }
3471
3472
3473 QString GuiPreferences::browsebind(QString const & file) const
3474 {
3475         return browseLibFile("bind", file, "bind", qt_("Choose bind file"),
3476                              QStringList(qt_("LyX bind files (*.bind)")));
3477 }
3478
3479
3480 QString GuiPreferences::browseUI(QString const & file) const
3481 {
3482         return browseLibFile("ui", file, "ui", qt_("Choose UI file"),
3483                              QStringList(qt_("LyX UI files (*.ui)")));
3484 }
3485
3486
3487 QString GuiPreferences::browsekbmap(QString const & file) const
3488 {
3489         return browseLibFile("kbd", file, "kmap", qt_("Choose keyboard map"),
3490                              QStringList(qt_("LyX keyboard maps (*.kmap)")));
3491 }
3492
3493
3494 QString GuiPreferences::browse(QString const & file,
3495         QString const & title) const
3496 {
3497         return browseFile(file, title, QStringList(), true);
3498 }
3499
3500
3501 Dialog * createGuiPreferences(GuiView & lv) { return new GuiPreferences(lv); }
3502
3503
3504 } // namespace frontend
3505 } // namespace lyx
3506
3507 #include "moc_GuiPrefs.cpp"