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