]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiPrefs.cpp
Fix indentation
[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 PrefColors::PrefColors(GuiPreferences * form)
1100         : PrefModule(catLookAndFeel, N_("Colors"), form)
1101 {
1102         setupUi(this);
1103
1104         // FIXME: all of this initialization should be put into the controller.
1105         // See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg113301.html
1106         // for some discussion of why that is not trivial.
1107         QPixmap icon(32, 32);
1108         for (int i = 0; i < Color_ignore; ++i) {
1109                 ColorCode lc = static_cast<ColorCode>(i);
1110                 if (lc == Color_none
1111                     || lc == Color_black
1112                     || lc == Color_white
1113                     || lc == Color_blue
1114                     || lc == Color_brown
1115                     || lc == Color_cyan
1116                     || lc == Color_darkgray
1117                     || lc == Color_gray
1118                     || lc == Color_green
1119                     || lc == Color_lightgray
1120                     || lc == Color_lime
1121                     || lc == Color_magenta
1122                     || lc == Color_olive
1123                     || lc == Color_orange
1124                     || lc == Color_pink
1125                     || lc == Color_purple
1126                     || lc == Color_red
1127                     || lc == Color_teal
1128                     || lc == Color_violet
1129                     || lc == Color_yellow
1130                     || lc == Color_inherit
1131                     || lc == Color_ignore)
1132                         continue;
1133                 lcolors_.push_back(lc);
1134         }
1135         sort(lcolors_.begin(), lcolors_.end(), ColorSorter());
1136         vector<ColorCode>::const_iterator cit = lcolors_.begin();
1137         vector<ColorCode>::const_iterator const end = lcolors_.end();
1138         for (; cit != end; ++cit) {
1139                 (void) new QListWidgetItem(QIcon(icon),
1140                         toqstr(lcolor.getGUIName(*cit)), lyxObjectsLW);
1141         }
1142         curcolors_.resize(lcolors_.size());
1143         newcolors_.resize(lcolors_.size());
1144         // End initialization
1145
1146         connect(colorChangePB, SIGNAL(clicked()),
1147                 this, SLOT(changeColor()));
1148         connect(lyxObjectsLW, SIGNAL(itemSelectionChanged()),
1149                 this, SLOT(changeLyxObjectsSelection()));
1150         connect(lyxObjectsLW, SIGNAL(itemActivated(QListWidgetItem*)),
1151                 this, SLOT(changeColor()));
1152         connect(syscolorsCB, SIGNAL(toggled(bool)),
1153                 this, SIGNAL(changed()));
1154         connect(syscolorsCB, SIGNAL(toggled(bool)),
1155                 this, SLOT(changeSysColor()));
1156 }
1157
1158
1159 void PrefColors::applyRC(LyXRC & rc) const
1160 {
1161         LyXRC oldrc = rc;
1162
1163         for (unsigned int i = 0; i < lcolors_.size(); ++i)
1164                 if (curcolors_[i] != newcolors_[i])
1165                         form_->setColor(lcolors_[i], newcolors_[i]);
1166         rc.use_system_colors = syscolorsCB->isChecked();
1167
1168         if (oldrc.use_system_colors != rc.use_system_colors)
1169                 guiApp->colorCache().clear();
1170 }
1171
1172
1173 void PrefColors::updateRC(LyXRC const & rc)
1174 {
1175         for (unsigned int i = 0; i < lcolors_.size(); ++i) {
1176                 QColor color = QColor(guiApp->colorCache().get(lcolors_[i], false));
1177                 QPixmap coloritem(32, 32);
1178                 coloritem.fill(color);
1179                 lyxObjectsLW->item(i)->setIcon(QIcon(coloritem));
1180                 newcolors_[i] = curcolors_[i] = color.name();
1181         }
1182         syscolorsCB->setChecked(rc.use_system_colors);
1183         changeLyxObjectsSelection();
1184 }
1185
1186
1187 void PrefColors::changeColor()
1188 {
1189         int const row = lyxObjectsLW->currentRow();
1190
1191         // just to be sure
1192         if (row < 0)
1193                 return;
1194
1195         QString const color = newcolors_[row];
1196         QColor c = QColorDialog::getColor(QColor(color), qApp->focusWidget());
1197
1198         if (c.isValid() && c.name() != color) {
1199                 newcolors_[row] = c.name();
1200                 QPixmap coloritem(32, 32);
1201                 coloritem.fill(c);
1202                 lyxObjectsLW->currentItem()->setIcon(QIcon(coloritem));
1203                 // emit signal
1204                 changed();
1205         }
1206 }
1207
1208 void PrefColors::changeSysColor()
1209 {
1210         for (int row = 0 ; row < lyxObjectsLW->count() ; ++row) {
1211                 // skip colors that are taken from system palette
1212                 bool const hide = syscolorsCB->isChecked()
1213                         && guiApp->colorCache().isSystem(lcolors_[row]);
1214
1215                 lyxObjectsLW->item(row)->setHidden(hide);
1216         }
1217
1218 }
1219
1220 void PrefColors::changeLyxObjectsSelection()
1221 {
1222         colorChangePB->setDisabled(lyxObjectsLW->currentRow() < 0);
1223 }
1224
1225
1226 /////////////////////////////////////////////////////////////////////
1227 //
1228 // PrefDisplay
1229 //
1230 /////////////////////////////////////////////////////////////////////
1231
1232 PrefDisplay::PrefDisplay(GuiPreferences * form)
1233         : PrefModule(catLookAndFeel, N_("Display"), form)
1234 {
1235         setupUi(this);
1236         connect(displayGraphicsCB, SIGNAL(toggled(bool)), this, SIGNAL(changed()));
1237         connect(instantPreviewCO, SIGNAL(activated(int)), this, SIGNAL(changed()));
1238         connect(previewSizeSB, SIGNAL(valueChanged(double)), this, SIGNAL(changed()));
1239         connect(paragraphMarkerCB, SIGNAL(toggled(bool)), this, SIGNAL(changed()));
1240 }
1241
1242
1243 void PrefDisplay::on_instantPreviewCO_currentIndexChanged(int index)
1244 {
1245         previewSizeSB->setEnabled(index != 0);
1246 }
1247
1248
1249 void PrefDisplay::applyRC(LyXRC & rc) const
1250 {
1251         switch (instantPreviewCO->currentIndex()) {
1252                 case 0:
1253                         rc.preview = LyXRC::PREVIEW_OFF;
1254                         break;
1255                 case 1:
1256                         rc.preview = LyXRC::PREVIEW_NO_MATH;
1257                         break;
1258                 case 2:
1259                         rc.preview = LyXRC::PREVIEW_ON;
1260                         break;
1261         }
1262
1263         rc.display_graphics = displayGraphicsCB->isChecked();
1264         rc.preview_scale_factor = previewSizeSB->value();
1265         rc.paragraph_markers = paragraphMarkerCB->isChecked();
1266
1267         // FIXME!! The graphics cache no longer has a changeDisplay method.
1268 #if 0
1269         if (old_value != rc.display_graphics) {
1270                 graphics::GCache & gc = graphics::GCache::get();
1271                 gc.changeDisplay();
1272         }
1273 #endif
1274 }
1275
1276
1277 void PrefDisplay::updateRC(LyXRC const & rc)
1278 {
1279         switch (rc.preview) {
1280         case LyXRC::PREVIEW_OFF:
1281                 instantPreviewCO->setCurrentIndex(0);
1282                 break;
1283         case LyXRC::PREVIEW_NO_MATH :
1284                 instantPreviewCO->setCurrentIndex(1);
1285                 break;
1286         case LyXRC::PREVIEW_ON :
1287                 instantPreviewCO->setCurrentIndex(2);
1288                 break;
1289         }
1290
1291         displayGraphicsCB->setChecked(rc.display_graphics);
1292         previewSizeSB->setValue(rc.preview_scale_factor);
1293         paragraphMarkerCB->setChecked(rc.paragraph_markers);
1294         previewSizeSB->setEnabled(
1295                 rc.display_graphics
1296                 && rc.preview != LyXRC::PREVIEW_OFF);
1297 }
1298
1299
1300 /////////////////////////////////////////////////////////////////////
1301 //
1302 // PrefPaths
1303 //
1304 /////////////////////////////////////////////////////////////////////
1305
1306 PrefPaths::PrefPaths(GuiPreferences * form)
1307         : PrefModule(QString(), N_("Paths"), form)
1308 {
1309         setupUi(this);
1310
1311         connect(workingDirPB, SIGNAL(clicked()), this, SLOT(selectWorkingdir()));
1312         connect(workingDirED, SIGNAL(textChanged(QString)),
1313                 this, SIGNAL(changed()));
1314
1315         connect(templateDirPB, SIGNAL(clicked()), this, SLOT(selectTemplatedir()));
1316         connect(templateDirED, SIGNAL(textChanged(QString)),
1317                 this, SIGNAL(changed()));
1318
1319         connect(exampleDirPB, SIGNAL(clicked()), this, SLOT(selectExampledir()));
1320         connect(exampleDirED, SIGNAL(textChanged(QString)),
1321                 this, SIGNAL(changed()));
1322
1323         connect(backupDirPB, SIGNAL(clicked()), this, SLOT(selectBackupdir()));
1324         connect(backupDirED, SIGNAL(textChanged(QString)),
1325                 this, SIGNAL(changed()));
1326
1327         connect(lyxserverDirPB, SIGNAL(clicked()), this, SLOT(selectLyxPipe()));
1328         connect(lyxserverDirED, SIGNAL(textChanged(QString)),
1329                 this, SIGNAL(changed()));
1330
1331         connect(thesaurusDirPB, SIGNAL(clicked()), this, SLOT(selectThesaurusdir()));
1332         connect(thesaurusDirED, SIGNAL(textChanged(QString)),
1333                 this, SIGNAL(changed()));
1334
1335         connect(tempDirPB, SIGNAL(clicked()), this, SLOT(selectTempdir()));
1336         connect(tempDirED, SIGNAL(textChanged(QString)),
1337                 this, SIGNAL(changed()));
1338
1339 #if defined(USE_HUNSPELL)
1340         connect(hunspellDirPB, SIGNAL(clicked()), this, SLOT(selectHunspelldir()));
1341         connect(hunspellDirED, SIGNAL(textChanged(QString)),
1342                 this, SIGNAL(changed()));
1343 #else
1344         hunspellDirPB->setEnabled(false);
1345         hunspellDirED->setEnabled(false);
1346 #endif
1347
1348         connect(pathPrefixED, SIGNAL(textChanged(QString)),
1349                 this, SIGNAL(changed()));
1350
1351         connect(texinputsPrefixED, SIGNAL(textChanged(QString)),
1352                 this, SIGNAL(changed()));
1353
1354         pathPrefixED->setValidator(new NoNewLineValidator(pathPrefixED));
1355         texinputsPrefixED->setValidator(new NoNewLineValidator(texinputsPrefixED));
1356 }
1357
1358
1359 void PrefPaths::applyRC(LyXRC & rc) const
1360 {
1361         rc.document_path = internal_path(fromqstr(workingDirED->text()));
1362         rc.example_path = internal_path(fromqstr(exampleDirED->text()));
1363         rc.template_path = internal_path(fromqstr(templateDirED->text()));
1364         rc.backupdir_path = internal_path(fromqstr(backupDirED->text()));
1365         rc.tempdir_path = internal_path(fromqstr(tempDirED->text()));
1366         rc.thesaurusdir_path = internal_path(fromqstr(thesaurusDirED->text()));
1367         rc.hunspelldir_path = internal_path(fromqstr(hunspellDirED->text()));
1368         rc.path_prefix = internal_path_list(fromqstr(pathPrefixED->text()));
1369         rc.texinputs_prefix = internal_path_list(fromqstr(texinputsPrefixED->text()));
1370         // FIXME: should be a checkbox only
1371         rc.lyxpipes = internal_path(fromqstr(lyxserverDirED->text()));
1372 }
1373
1374
1375 void PrefPaths::updateRC(LyXRC const & rc)
1376 {
1377         workingDirED->setText(toqstr(external_path(rc.document_path)));
1378         exampleDirED->setText(toqstr(external_path(rc.example_path)));
1379         templateDirED->setText(toqstr(external_path(rc.template_path)));
1380         backupDirED->setText(toqstr(external_path(rc.backupdir_path)));
1381         tempDirED->setText(toqstr(external_path(rc.tempdir_path)));
1382         thesaurusDirED->setText(toqstr(external_path(rc.thesaurusdir_path)));
1383         hunspellDirED->setText(toqstr(external_path(rc.hunspelldir_path)));
1384         pathPrefixED->setText(toqstr(external_path_list(rc.path_prefix)));
1385         texinputsPrefixED->setText(toqstr(external_path_list(rc.texinputs_prefix)));
1386         // FIXME: should be a checkbox only
1387         lyxserverDirED->setText(toqstr(external_path(rc.lyxpipes)));
1388 }
1389
1390
1391 void PrefPaths::selectExampledir()
1392 {
1393         QString file = browseDir(internalPath(exampleDirED->text()),
1394                 qt_("Select directory for example files"));
1395         if (!file.isEmpty())
1396                 exampleDirED->setText(file);
1397 }
1398
1399
1400 void PrefPaths::selectTemplatedir()
1401 {
1402         QString file = browseDir(internalPath(templateDirED->text()),
1403                 qt_("Select a document templates directory"));
1404         if (!file.isEmpty())
1405                 templateDirED->setText(file);
1406 }
1407
1408
1409 void PrefPaths::selectTempdir()
1410 {
1411         QString file = browseDir(internalPath(tempDirED->text()),
1412                 qt_("Select a temporary directory"));
1413         if (!file.isEmpty())
1414                 tempDirED->setText(file);
1415 }
1416
1417
1418 void PrefPaths::selectBackupdir()
1419 {
1420         QString file = browseDir(internalPath(backupDirED->text()),
1421                 qt_("Select a backups directory"));
1422         if (!file.isEmpty())
1423                 backupDirED->setText(file);
1424 }
1425
1426
1427 void PrefPaths::selectWorkingdir()
1428 {
1429         QString file = browseDir(internalPath(workingDirED->text()),
1430                 qt_("Select a document directory"));
1431         if (!file.isEmpty())
1432                 workingDirED->setText(file);
1433 }
1434
1435
1436 void PrefPaths::selectThesaurusdir()
1437 {
1438         QString file = browseDir(internalPath(thesaurusDirED->text()),
1439                 qt_("Set the path to the thesaurus dictionaries"));
1440         if (!file.isEmpty())
1441                 thesaurusDirED->setText(file);
1442 }
1443
1444
1445 void PrefPaths::selectHunspelldir()
1446 {
1447         QString file = browseDir(internalPath(hunspellDirED->text()),
1448                 qt_("Set the path to the Hunspell dictionaries"));
1449         if (!file.isEmpty())
1450                 hunspellDirED->setText(file);
1451 }
1452
1453
1454 void PrefPaths::selectLyxPipe()
1455 {
1456         QString file = form_->browse(internalPath(lyxserverDirED->text()),
1457                 qt_("Give a filename for the LyX server pipe"));
1458         if (!file.isEmpty())
1459                 lyxserverDirED->setText(file);
1460 }
1461
1462
1463 /////////////////////////////////////////////////////////////////////
1464 //
1465 // PrefSpellchecker
1466 //
1467 /////////////////////////////////////////////////////////////////////
1468
1469 PrefSpellchecker::PrefSpellchecker(GuiPreferences * form)
1470         : PrefModule(catLanguage, N_("Spellchecker"), form)
1471 {
1472         setupUi(this);
1473
1474 // FIXME: this check should test the target platform (darwin)
1475 #if defined(USE_MACOSX_PACKAGING)
1476         spellcheckerCB->addItem(qt_("Native"), QString("native"));
1477 #define CONNECT_APPLESPELL
1478 #else
1479 #undef CONNECT_APPLESPELL
1480 #endif
1481 #if defined(USE_ASPELL)
1482         spellcheckerCB->addItem(qt_("Aspell"), QString("aspell"));
1483 #endif
1484 #if defined(USE_ENCHANT)
1485         spellcheckerCB->addItem(qt_("Enchant"), QString("enchant"));
1486 #endif
1487 #if defined(USE_HUNSPELL)
1488         spellcheckerCB->addItem(qt_("Hunspell"), QString("hunspell"));
1489 #endif
1490
1491         #if defined(CONNECT_APPLESPELL) || defined(USE_ASPELL) || defined(USE_ENCHANT) || defined(USE_HUNSPELL)
1492                 connect(spellcheckerCB, SIGNAL(currentIndexChanged(int)),
1493                         this, SIGNAL(changed()));
1494                 connect(altLanguageED, SIGNAL(textChanged(QString)),
1495                         this, SIGNAL(changed()));
1496                 connect(escapeCharactersED, SIGNAL(textChanged(QString)),
1497                         this, SIGNAL(changed()));
1498                 connect(compoundWordCB, SIGNAL(clicked()),
1499                         this, SIGNAL(changed()));
1500                 connect(spellcheckContinuouslyCB, SIGNAL(clicked()),
1501                         this, SIGNAL(changed()));
1502                 connect(spellcheckNotesCB, SIGNAL(clicked()),
1503                         this, SIGNAL(changed()));
1504
1505                 altLanguageED->setValidator(new NoNewLineValidator(altLanguageED));
1506                 escapeCharactersED->setValidator(new NoNewLineValidator(escapeCharactersED));
1507         #else
1508                 spellcheckerCB->setEnabled(false);
1509                 altLanguageED->setEnabled(false);
1510                 escapeCharactersED->setEnabled(false);
1511                 compoundWordCB->setEnabled(false);
1512                 spellcheckContinuouslyCB->setEnabled(false);
1513                 spellcheckNotesCB->setEnabled(false);
1514         #endif
1515 }
1516
1517
1518 void PrefSpellchecker::applyRC(LyXRC & rc) const
1519 {
1520         string const speller = fromqstr(spellcheckerCB->
1521                 itemData(spellcheckerCB->currentIndex()).toString());
1522         if (!speller.empty())
1523                 rc.spellchecker = speller;
1524         rc.spellchecker_alt_lang = fromqstr(altLanguageED->text());
1525         rc.spellchecker_esc_chars = fromqstr(escapeCharactersED->text());
1526         rc.spellchecker_accept_compound = compoundWordCB->isChecked();
1527         rc.spellcheck_continuously = spellcheckContinuouslyCB->isChecked();
1528         rc.spellcheck_notes = spellcheckNotesCB->isChecked();
1529 }
1530
1531
1532 void PrefSpellchecker::updateRC(LyXRC const & rc)
1533 {
1534         spellcheckerCB->setCurrentIndex(
1535                 spellcheckerCB->findData(toqstr(rc.spellchecker)));
1536         altLanguageED->setText(toqstr(rc.spellchecker_alt_lang));
1537         escapeCharactersED->setText(toqstr(rc.spellchecker_esc_chars));
1538         compoundWordCB->setChecked(rc.spellchecker_accept_compound);
1539         spellcheckContinuouslyCB->setChecked(rc.spellcheck_continuously);
1540         spellcheckNotesCB->setChecked(rc.spellcheck_notes);
1541 }
1542
1543
1544 void PrefSpellchecker::on_spellcheckerCB_currentIndexChanged(int index)
1545 {
1546         QString spellchecker = spellcheckerCB->itemData(index).toString();
1547
1548         compoundWordCB->setEnabled(spellchecker == QString("aspell"));
1549 }
1550
1551
1552
1553 /////////////////////////////////////////////////////////////////////
1554 //
1555 // PrefConverters
1556 //
1557 /////////////////////////////////////////////////////////////////////
1558
1559
1560 PrefConverters::PrefConverters(GuiPreferences * form)
1561         : PrefModule(catFiles, N_("Converters"), form)
1562 {
1563         setupUi(this);
1564
1565         connect(converterNewPB, SIGNAL(clicked()),
1566                 this, SLOT(updateConverter()));
1567         connect(converterRemovePB, SIGNAL(clicked()),
1568                 this, SLOT(removeConverter()));
1569         connect(converterModifyPB, SIGNAL(clicked()),
1570                 this, SLOT(updateConverter()));
1571         connect(convertersLW, SIGNAL(currentRowChanged(int)),
1572                 this, SLOT(switchConverter()));
1573         connect(converterFromCO, SIGNAL(activated(QString)),
1574                 this, SLOT(changeConverter()));
1575         connect(converterToCO, SIGNAL(activated(QString)),
1576                 this, SLOT(changeConverter()));
1577         connect(converterED, SIGNAL(textEdited(QString)),
1578                 this, SLOT(changeConverter()));
1579         connect(converterFlagED, SIGNAL(textEdited(QString)),
1580                 this, SLOT(changeConverter()));
1581         connect(converterNewPB, SIGNAL(clicked()),
1582                 this, SIGNAL(changed()));
1583         connect(converterRemovePB, SIGNAL(clicked()),
1584                 this, SIGNAL(changed()));
1585         connect(converterModifyPB, SIGNAL(clicked()),
1586                 this, SIGNAL(changed()));
1587         connect(maxAgeLE, SIGNAL(textEdited(QString)),
1588                 this, SIGNAL(changed()));
1589
1590         converterED->setValidator(new NoNewLineValidator(converterED));
1591         converterFlagED->setValidator(new NoNewLineValidator(converterFlagED));
1592         maxAgeLE->setValidator(new QDoubleValidator(maxAgeLE));
1593         //converterDefGB->setFocusProxy(convertersLW);
1594 }
1595
1596
1597 void PrefConverters::applyRC(LyXRC & rc) const
1598 {
1599         rc.use_converter_cache = cacheCB->isChecked();
1600         rc.converter_cache_maxage = int(widgetToDouble(maxAgeLE) * 86400.0);
1601 }
1602
1603
1604 void PrefConverters::updateRC(LyXRC const & rc)
1605 {
1606         cacheCB->setChecked(rc.use_converter_cache);
1607         QString max_age;
1608         doubleToWidget(maxAgeLE, (double(rc.converter_cache_maxage) / 86400.0), 'g', 6);
1609         updateGui();
1610 }
1611
1612
1613 void PrefConverters::updateGui()
1614 {
1615         form_->formats().sort();
1616         form_->converters().update(form_->formats());
1617         // save current selection
1618         QString current = converterFromCO->currentText()
1619                 + " -> " + converterToCO->currentText();
1620
1621         converterFromCO->clear();
1622         converterToCO->clear();
1623
1624         Formats::const_iterator cit = form_->formats().begin();
1625         Formats::const_iterator end = form_->formats().end();
1626         for (; cit != end; ++cit) {
1627                 converterFromCO->addItem(qt_(cit->prettyname()));
1628                 converterToCO->addItem(qt_(cit->prettyname()));
1629         }
1630
1631         // currentRowChanged(int) is also triggered when updating the listwidget
1632         // block signals to avoid unnecessary calls to switchConverter()
1633         convertersLW->blockSignals(true);
1634         convertersLW->clear();
1635
1636         Converters::const_iterator ccit = form_->converters().begin();
1637         Converters::const_iterator cend = form_->converters().end();
1638         for (; ccit != cend; ++ccit) {
1639                 QString const name =
1640                         qt_(ccit->From()->prettyname()) + " -> " + qt_(ccit->To()->prettyname());
1641                 int type = form_->converters().getNumber(ccit->From()->name(), ccit->To()->name());
1642                 new QListWidgetItem(name, convertersLW, type);
1643         }
1644         convertersLW->sortItems(Qt::AscendingOrder);
1645         convertersLW->blockSignals(false);
1646
1647         // restore selection
1648         if (!current.isEmpty()) {
1649                 QList<QListWidgetItem *> const item =
1650                         convertersLW->findItems(current, Qt::MatchExactly);
1651                 if (!item.isEmpty())
1652                         convertersLW->setCurrentItem(item.at(0));
1653         }
1654
1655         // select first element if restoring failed
1656         if (convertersLW->currentRow() == -1)
1657                 convertersLW->setCurrentRow(0);
1658
1659         updateButtons();
1660 }
1661
1662
1663 void PrefConverters::switchConverter()
1664 {
1665         int const cnr = convertersLW->currentItem()->type();
1666         Converter const & c(form_->converters().get(cnr));
1667         converterFromCO->setCurrentIndex(form_->formats().getNumber(c.from()));
1668         converterToCO->setCurrentIndex(form_->formats().getNumber(c.to()));
1669         converterED->setText(toqstr(c.command()));
1670         converterFlagED->setText(toqstr(c.flags()));
1671
1672         updateButtons();
1673 }
1674
1675
1676 void PrefConverters::changeConverter()
1677 {
1678         updateButtons();
1679 }
1680
1681
1682 void PrefConverters::updateButtons()
1683 {
1684         if (form_->formats().empty())
1685                 return;
1686         Format const & from = form_->formats().get(converterFromCO->currentIndex());
1687         Format const & to = form_->formats().get(converterToCO->currentIndex());
1688         int const sel = form_->converters().getNumber(from.name(), to.name());
1689         bool const known = sel >= 0;
1690         bool const valid = !(converterED->text().isEmpty()
1691                 || from.name() == to.name());
1692
1693         string old_command;
1694         string old_flag;
1695
1696         if (convertersLW->count() > 0) {
1697                 int const cnr = convertersLW->currentItem()->type();
1698                 Converter const & c = form_->converters().get(cnr);
1699                 old_command = c.command();
1700                 old_flag = c.flags();
1701         }
1702
1703         string const new_command = fromqstr(converterED->text());
1704         string const new_flag = fromqstr(converterFlagED->text());
1705
1706         bool modified = (old_command != new_command || old_flag != new_flag);
1707
1708         converterModifyPB->setEnabled(valid && known && modified);
1709         converterNewPB->setEnabled(valid && !known);
1710         converterRemovePB->setEnabled(known);
1711
1712         maxAgeLE->setEnabled(cacheCB->isChecked());
1713         maxAgeLA->setEnabled(cacheCB->isChecked());
1714 }
1715
1716
1717 // FIXME: user must
1718 // specify unique from/to or it doesn't appear. This is really bad UI
1719 // this is why we can use the same function for both new and modify
1720 void PrefConverters::updateConverter()
1721 {
1722         Format const & from = form_->formats().get(converterFromCO->currentIndex());
1723         Format const & to = form_->formats().get(converterToCO->currentIndex());
1724         string const flags = fromqstr(converterFlagED->text());
1725         string const command = fromqstr(converterED->text());
1726
1727         Converter const * old =
1728                 form_->converters().getConverter(from.name(), to.name());
1729         form_->converters().add(from.name(), to.name(), command, flags);
1730
1731         if (!old)
1732                 form_->converters().updateLast(form_->formats());
1733
1734         updateGui();
1735
1736         // Remove all files created by this converter from the cache, since
1737         // the modified converter might create different files.
1738         ConverterCache::get().remove_all(from.name(), to.name());
1739 }
1740
1741
1742 void PrefConverters::removeConverter()
1743 {
1744         Format const & from = form_->formats().get(converterFromCO->currentIndex());
1745         Format const & to = form_->formats().get(converterToCO->currentIndex());
1746         form_->converters().erase(from.name(), to.name());
1747
1748         updateGui();
1749
1750         // Remove all files created by this converter from the cache, since
1751         // a possible new converter might create different files.
1752         ConverterCache::get().remove_all(from.name(), to.name());
1753 }
1754
1755
1756 void PrefConverters::on_cacheCB_stateChanged(int state)
1757 {
1758         maxAgeLE->setEnabled(state == Qt::Checked);
1759         maxAgeLA->setEnabled(state == Qt::Checked);
1760         changed();
1761 }
1762
1763
1764 /////////////////////////////////////////////////////////////////////
1765 //
1766 // FormatValidator
1767 //
1768 /////////////////////////////////////////////////////////////////////
1769
1770 class FormatValidator : public QValidator
1771 {
1772 public:
1773         FormatValidator(QWidget *, Formats const & f);
1774         void fixup(QString & input) const;
1775         QValidator::State validate(QString & input, int & pos) const;
1776 private:
1777         virtual QString toString(Format const & format) const = 0;
1778         int nr() const;
1779         Formats const & formats_;
1780 };
1781
1782
1783 FormatValidator::FormatValidator(QWidget * parent, Formats const & f)
1784         : QValidator(parent), formats_(f)
1785 {
1786 }
1787
1788
1789 void FormatValidator::fixup(QString & input) const
1790 {
1791         Formats::const_iterator cit = formats_.begin();
1792         Formats::const_iterator end = formats_.end();
1793         for (; cit != end; ++cit) {
1794                 QString const name = toString(*cit);
1795                 if (distance(formats_.begin(), cit) == nr()) {
1796                         input = name;
1797                         return;
1798                 }
1799         }
1800 }
1801
1802
1803 QValidator::State FormatValidator::validate(QString & input, int & /*pos*/) const
1804 {
1805         Formats::const_iterator cit = formats_.begin();
1806         Formats::const_iterator end = formats_.end();
1807         bool unknown = true;
1808         for (; unknown && cit != end; ++cit) {
1809                 QString const name = toString(*cit);
1810                 if (distance(formats_.begin(), cit) != nr())
1811                         unknown = name != input;
1812         }
1813
1814         if (unknown && !input.isEmpty())
1815                 return QValidator::Acceptable;
1816         else
1817                 return QValidator::Intermediate;
1818 }
1819
1820
1821 int FormatValidator::nr() const
1822 {
1823         QComboBox * p = qobject_cast<QComboBox *>(parent());
1824         return p->itemData(p->currentIndex()).toInt();
1825 }
1826
1827
1828 /////////////////////////////////////////////////////////////////////
1829 //
1830 // FormatNameValidator
1831 //
1832 /////////////////////////////////////////////////////////////////////
1833
1834 class FormatNameValidator : public FormatValidator
1835 {
1836 public:
1837         FormatNameValidator(QWidget * parent, Formats const & f)
1838                 : FormatValidator(parent, f)
1839         {}
1840 private:
1841         QString toString(Format const & format) const
1842         {
1843                 return toqstr(format.name());
1844         }
1845 };
1846
1847
1848 /////////////////////////////////////////////////////////////////////
1849 //
1850 // FormatPrettynameValidator
1851 //
1852 /////////////////////////////////////////////////////////////////////
1853
1854 class FormatPrettynameValidator : public FormatValidator
1855 {
1856 public:
1857         FormatPrettynameValidator(QWidget * parent, Formats const & f)
1858                 : FormatValidator(parent, f)
1859         {}
1860 private:
1861         QString toString(Format const & format) const
1862         {
1863                 return qt_(format.prettyname());
1864         }
1865 };
1866
1867
1868 /////////////////////////////////////////////////////////////////////
1869 //
1870 // PrefFileformats
1871 //
1872 /////////////////////////////////////////////////////////////////////
1873
1874 PrefFileformats::PrefFileformats(GuiPreferences * form)
1875         : PrefModule(catFiles, N_("File Formats"), form)
1876 {
1877         setupUi(this);
1878
1879         formatED->setValidator(new FormatNameValidator(formatsCB, form_->formats()));
1880         formatsCB->setValidator(new FormatPrettynameValidator(formatsCB, form_->formats()));
1881         extensionsED->setValidator(new NoNewLineValidator(extensionsED));
1882         shortcutED->setValidator(new NoNewLineValidator(shortcutED));
1883         editorED->setValidator(new NoNewLineValidator(editorED));
1884         viewerED->setValidator(new NoNewLineValidator(viewerED));
1885         copierED->setValidator(new NoNewLineValidator(copierED));
1886
1887         connect(documentCB, SIGNAL(clicked()),
1888                 this, SLOT(setFlags()));
1889         connect(vectorCB, SIGNAL(clicked()),
1890                 this, SLOT(setFlags()));
1891         connect(exportMenuCB, SIGNAL(clicked()),
1892                 this, SLOT(setFlags()));
1893         connect(formatsCB->lineEdit(), SIGNAL(editingFinished()),
1894                 this, SLOT(updatePrettyname()));
1895         connect(formatsCB->lineEdit(), SIGNAL(textEdited(QString)),
1896                 this, SIGNAL(changed()));
1897         connect(defaultFormatCB, SIGNAL(activated(QString)),
1898                 this, SIGNAL(changed()));
1899         connect(defaultOTFFormatCB, SIGNAL(activated(QString)),
1900                 this, SIGNAL(changed()));
1901         connect(viewerCO, SIGNAL(activated(int)),
1902                 this, SIGNAL(changed()));
1903         connect(editorCO, SIGNAL(activated(int)),
1904                 this, SIGNAL(changed()));
1905 }
1906
1907
1908 namespace {
1909
1910 string const l10n_shortcut(string const & prettyname, string const & shortcut)
1911 {
1912         if (shortcut.empty())
1913                 return string();
1914
1915         string l10n_format =
1916                 to_utf8(_(prettyname + '|' + shortcut));
1917         return split(l10n_format, '|');
1918 }
1919
1920 } // namespace anon
1921
1922
1923 void PrefFileformats::applyRC(LyXRC & rc) const
1924 {
1925         QString const default_format = defaultFormatCB->itemData(
1926                 defaultFormatCB->currentIndex()).toString();
1927         rc.default_view_format = fromqstr(default_format);
1928         QString const default_otf_format = defaultOTFFormatCB->itemData(
1929                 defaultOTFFormatCB->currentIndex()).toString();
1930         rc.default_otf_view_format = fromqstr(default_otf_format);
1931 }
1932
1933
1934 void PrefFileformats::updateRC(LyXRC const & rc)
1935 {
1936         viewer_alternatives = rc.viewer_alternatives;
1937         editor_alternatives = rc.editor_alternatives;
1938         bool const init = defaultFormatCB->currentText().isEmpty();
1939         updateView();
1940         if (init) {
1941                 int pos =
1942                         defaultFormatCB->findData(toqstr(rc.default_view_format));
1943                 defaultFormatCB->setCurrentIndex(pos);
1944                 pos = defaultOTFFormatCB->findData(toqstr(rc.default_otf_view_format));
1945                                 defaultOTFFormatCB->setCurrentIndex(pos);
1946                 defaultOTFFormatCB->setCurrentIndex(pos);
1947         }
1948 }
1949
1950
1951 void PrefFileformats::updateView()
1952 {
1953         QString const current = formatsCB->currentText();
1954         QString const current_def = defaultFormatCB->currentText();
1955         QString const current_def_otf = defaultOTFFormatCB->currentText();
1956
1957         // update comboboxes with formats
1958         formatsCB->blockSignals(true);
1959         defaultFormatCB->blockSignals(true);
1960         defaultOTFFormatCB->blockSignals(true);
1961         formatsCB->clear();
1962         defaultFormatCB->clear();
1963         defaultOTFFormatCB->clear();
1964         form_->formats().sort();
1965         Formats::const_iterator cit = form_->formats().begin();
1966         Formats::const_iterator end = form_->formats().end();
1967         for (; cit != end; ++cit) {
1968                 formatsCB->addItem(qt_(cit->prettyname()),
1969                                 QVariant(form_->formats().getNumber(cit->name())));
1970                 if (cit->viewer().empty())
1971                         continue;
1972                 if (form_->converters().isReachable("xhtml", cit->name())
1973                     || form_->converters().isReachable("dviluatex", cit->name())
1974                     || form_->converters().isReachable("luatex", cit->name())
1975                     || form_->converters().isReachable("xetex", cit->name())) {
1976                         defaultFormatCB->addItem(qt_(cit->prettyname()),
1977                                         QVariant(toqstr(cit->name())));
1978                         defaultOTFFormatCB->addItem(qt_(cit->prettyname()),
1979                                         QVariant(toqstr(cit->name())));
1980                 } else if (form_->converters().isReachable("latex", cit->name())
1981                            || form_->converters().isReachable("pdflatex", cit->name()))
1982                         defaultFormatCB->addItem(qt_(cit->prettyname()),
1983                                         QVariant(toqstr(cit->name())));
1984         }
1985
1986         // restore selections
1987         int item = formatsCB->findText(current, Qt::MatchExactly);
1988         formatsCB->setCurrentIndex(item < 0 ? 0 : item);
1989         on_formatsCB_currentIndexChanged(item < 0 ? 0 : item);
1990         item = defaultFormatCB->findText(current_def, Qt::MatchExactly);
1991         defaultFormatCB->setCurrentIndex(item < 0 ? 0 : item);
1992         item = defaultOTFFormatCB->findText(current_def_otf, Qt::MatchExactly);
1993         defaultOTFFormatCB->setCurrentIndex(item < 0 ? 0 : item);
1994         formatsCB->blockSignals(false);
1995         defaultFormatCB->blockSignals(false);
1996         defaultOTFFormatCB->blockSignals(false);
1997 }
1998
1999
2000 void PrefFileformats::on_formatsCB_currentIndexChanged(int i)
2001 {
2002         if (form_->formats().empty())
2003                 return;
2004         int const nr = formatsCB->itemData(i).toInt();
2005         Format const f = form_->formats().get(nr);
2006
2007         formatED->setText(toqstr(f.name()));
2008         copierED->setText(toqstr(form_->movers().command(f.name())));
2009         extensionsED->setText(toqstr(f.extensions()));
2010         mimeED->setText(toqstr(f.mime()));
2011         shortcutED->setText(
2012                 toqstr(l10n_shortcut(f.prettyname(), f.shortcut())));
2013         documentCB->setChecked((f.documentFormat()));
2014         vectorCB->setChecked((f.vectorFormat()));
2015         exportMenuCB->setChecked((f.inExportMenu()));
2016         exportMenuCB->setEnabled((f.documentFormat()));
2017         updateViewers();
2018         updateEditors();
2019 }
2020
2021
2022 void PrefFileformats::setFlags()
2023 {
2024         int flags = Format::none;
2025         if (documentCB->isChecked())
2026                 flags |= Format::document;
2027         if (vectorCB->isChecked())
2028                 flags |= Format::vector;
2029         if (exportMenuCB->isChecked())
2030                 flags |= Format::export_menu;
2031         currentFormat().setFlags(flags);
2032         exportMenuCB->setEnabled(documentCB->isChecked());
2033         changed();
2034 }
2035
2036
2037 void PrefFileformats::on_copierED_textEdited(const QString & s)
2038 {
2039         string const fmt = fromqstr(formatED->text());
2040         form_->movers().set(fmt, fromqstr(s));
2041         changed();
2042 }
2043
2044
2045 void PrefFileformats::on_extensionsED_textEdited(const QString & s)
2046 {
2047         currentFormat().setExtensions(fromqstr(s));
2048         changed();
2049 }
2050
2051
2052 void PrefFileformats::on_viewerED_textEdited(const QString & s)
2053 {
2054         currentFormat().setViewer(fromqstr(s));
2055         changed();
2056 }
2057
2058
2059 void PrefFileformats::on_editorED_textEdited(const QString & s)
2060 {
2061         currentFormat().setEditor(fromqstr(s));
2062         changed();
2063 }
2064
2065
2066 void PrefFileformats::on_mimeED_textEdited(const QString & s)
2067 {
2068         currentFormat().setMime(fromqstr(s));
2069         changed();
2070 }
2071
2072
2073 void PrefFileformats::on_shortcutED_textEdited(const QString & s)
2074 {
2075         string const new_shortcut = fromqstr(s);
2076         if (new_shortcut == l10n_shortcut(currentFormat().prettyname(),
2077                                           currentFormat().shortcut()))
2078                 return;
2079         currentFormat().setShortcut(new_shortcut);
2080         changed();
2081 }
2082
2083
2084 void PrefFileformats::on_formatED_editingFinished()
2085 {
2086         string const newname = fromqstr(formatED->displayText());
2087         string const oldname = currentFormat().name();
2088         if (newname == oldname)
2089                 return;
2090         if (form_->converters().formatIsUsed(oldname)) {
2091                 Alert::error(_("Format in use"),
2092                              _("You cannot change a format's short name "
2093                                "if the format is used by a converter. "
2094                                "Please remove the converter first."));
2095                 updateView();
2096                 return;
2097         }
2098
2099         currentFormat().setName(newname);
2100         changed();
2101 }
2102
2103
2104 void PrefFileformats::on_formatED_textChanged(const QString &)
2105 {
2106         QString t = formatED->text();
2107         int p = 0;
2108         bool valid = formatED->validator()->validate(t, p) == QValidator::Acceptable;
2109         setValid(formatLA, valid);
2110 }
2111
2112
2113 void PrefFileformats::on_formatsCB_editTextChanged(const QString &)
2114 {
2115         QString t = formatsCB->currentText();
2116         int p = 0;
2117         bool valid = formatsCB->validator()->validate(t, p) == QValidator::Acceptable;
2118         setValid(formatsLA, valid);
2119 }
2120
2121
2122 void PrefFileformats::updatePrettyname()
2123 {
2124         QString const newname = formatsCB->currentText();
2125         if (newname == qt_(currentFormat().prettyname()))
2126                 return;
2127
2128         currentFormat().setPrettyname(fromqstr(newname));
2129         formatsChanged();
2130         updateView();
2131         changed();
2132 }
2133
2134
2135 namespace {
2136         void updateComboBox(LyXRC::Alternatives const & alts,
2137                             string const & fmt, QComboBox * combo)
2138         {
2139                 LyXRC::Alternatives::const_iterator it =
2140                                 alts.find(fmt);
2141                 if (it != alts.end()) {
2142                         LyXRC::CommandSet const & cmds = it->second;
2143                         LyXRC::CommandSet::const_iterator sit =
2144                                         cmds.begin();
2145                         LyXRC::CommandSet::const_iterator const sen =
2146                                         cmds.end();
2147                         for (; sit != sen; ++sit) {
2148                                 QString const qcmd = toqstr(*sit);
2149                                 combo->addItem(qcmd, qcmd);
2150                         }
2151                 }
2152         }
2153 }
2154
2155
2156 void PrefFileformats::updateViewers()
2157 {
2158         Format const f = currentFormat();
2159         viewerCO->blockSignals(true);
2160         viewerCO->clear();
2161         viewerCO->addItem(qt_("None"), QString());
2162         updateComboBox(viewer_alternatives, f.name(), viewerCO);
2163         viewerCO->addItem(qt_("Custom"), QString("custom viewer"));
2164         viewerCO->blockSignals(false);
2165
2166         int pos = viewerCO->findData(toqstr(f.viewer()));
2167         if (pos != -1) {
2168                 viewerED->clear();
2169                 viewerED->setEnabled(false);
2170                 viewerCO->setCurrentIndex(pos);
2171         } else {
2172                 viewerED->setEnabled(true);
2173                 viewerED->setText(toqstr(f.viewer()));
2174                 viewerCO->setCurrentIndex(viewerCO->findData(toqstr("custom viewer")));
2175         }
2176 }
2177
2178
2179 void PrefFileformats::updateEditors()
2180 {
2181         Format const f = currentFormat();
2182         editorCO->blockSignals(true);
2183         editorCO->clear();
2184         editorCO->addItem(qt_("None"), QString());
2185         updateComboBox(editor_alternatives, f.name(), editorCO);
2186         editorCO->addItem(qt_("Custom"), QString("custom editor"));
2187         editorCO->blockSignals(false);
2188
2189         int pos = editorCO->findData(toqstr(f.editor()));
2190         if (pos != -1) {
2191                 editorED->clear();
2192                 editorED->setEnabled(false);
2193                 editorCO->setCurrentIndex(pos);
2194         } else {
2195                 editorED->setEnabled(true);
2196                 editorED->setText(toqstr(f.editor()));
2197                 editorCO->setCurrentIndex(editorCO->findData(toqstr("custom editor")));
2198         }
2199 }
2200
2201
2202 void PrefFileformats::on_viewerCO_currentIndexChanged(int i)
2203 {
2204         bool const custom = viewerCO->itemData(i).toString() == "custom viewer";
2205         viewerED->setEnabled(custom);
2206         if (!custom)
2207                 currentFormat().setViewer(fromqstr(viewerCO->itemData(i).toString()));
2208 }
2209
2210
2211 void PrefFileformats::on_editorCO_currentIndexChanged(int i)
2212 {
2213         bool const custom = editorCO->itemData(i).toString() == "custom editor";
2214         editorED->setEnabled(custom);
2215         if (!custom)
2216                 currentFormat().setEditor(fromqstr(editorCO->itemData(i).toString()));
2217 }
2218
2219
2220 Format & PrefFileformats::currentFormat()
2221 {
2222         int const i = formatsCB->currentIndex();
2223         int const nr = formatsCB->itemData(i).toInt();
2224         return form_->formats().get(nr);
2225 }
2226
2227
2228 void PrefFileformats::on_formatNewPB_clicked()
2229 {
2230         form_->formats().add("", "", "", "", "", "", "", Format::none);
2231         updateView();
2232         formatsCB->setCurrentIndex(0);
2233         formatsCB->setFocus(Qt::OtherFocusReason);
2234 }
2235
2236
2237 void PrefFileformats::on_formatRemovePB_clicked()
2238 {
2239         int const i = formatsCB->currentIndex();
2240         int const nr = formatsCB->itemData(i).toInt();
2241         string const current_text = form_->formats().get(nr).name();
2242         if (form_->converters().formatIsUsed(current_text)) {
2243                 Alert::error(_("Format in use"),
2244                              _("Cannot remove a Format used by a Converter. "
2245                                             "Remove the converter first."));
2246                 return;
2247         }
2248
2249         form_->formats().erase(current_text);
2250         formatsChanged();
2251         updateView();
2252         on_formatsCB_editTextChanged(formatsCB->currentText());
2253         changed();
2254 }
2255
2256
2257 /////////////////////////////////////////////////////////////////////
2258 //
2259 // PrefLanguage
2260 //
2261 /////////////////////////////////////////////////////////////////////
2262
2263 PrefLanguage::PrefLanguage(GuiPreferences * form)
2264         : PrefModule(catLanguage, N_("Language"), form)
2265 {
2266         setupUi(this);
2267
2268         connect(visualCursorRB, SIGNAL(clicked()),
2269                 this, SIGNAL(changed()));
2270         connect(logicalCursorRB, SIGNAL(clicked()),
2271                 this, SIGNAL(changed()));
2272         connect(markForeignCB, SIGNAL(clicked()),
2273                 this, SIGNAL(changed()));
2274         connect(autoBeginCB, SIGNAL(clicked()),
2275                 this, SIGNAL(changed()));
2276         connect(autoEndCB, SIGNAL(clicked()),
2277                 this, SIGNAL(changed()));
2278         connect(languagePackageCO, SIGNAL(activated(int)),
2279                 this, SIGNAL(changed()));
2280         connect(languagePackageED, SIGNAL(textChanged(QString)),
2281                 this, SIGNAL(changed()));
2282         connect(globalCB, SIGNAL(clicked()),
2283                 this, SIGNAL(changed()));
2284         connect(startCommandED, SIGNAL(textChanged(QString)),
2285                 this, SIGNAL(changed()));
2286         connect(endCommandED, SIGNAL(textChanged(QString)),
2287                 this, SIGNAL(changed()));
2288         connect(uiLanguageCO, SIGNAL(activated(int)),
2289                 this, SIGNAL(changed()));
2290         connect(defaultDecimalPointLE, SIGNAL(textChanged(QString)),
2291                 this, SIGNAL(changed()));
2292         connect(defaultLengthUnitCO, SIGNAL(activated(int)),
2293                 this, SIGNAL(changed()));
2294
2295         languagePackageED->setValidator(new NoNewLineValidator(languagePackageED));
2296         startCommandED->setValidator(new NoNewLineValidator(startCommandED));
2297         endCommandED->setValidator(new NoNewLineValidator(endCommandED));
2298
2299         uiLanguageCO->clear();
2300
2301         QAbstractItemModel * language_model = guiApp->languageModel();
2302         // FIXME: it would be nice if sorting was enabled/disabled via a checkbox.
2303         language_model->sort(0);
2304         defaultDecimalPointLE->setInputMask("X; ");
2305         defaultDecimalPointLE->setMaxLength(1);
2306
2307         defaultLengthUnitCO->addItem(lyx::qt_(unit_name_gui[Length::CM]), Length::CM);
2308         defaultLengthUnitCO->addItem(lyx::qt_(unit_name_gui[Length::IN]), Length::IN);
2309
2310         set<string> added;
2311         uiLanguageCO->blockSignals(true);
2312         uiLanguageCO->addItem(qt_("Default"), toqstr("auto"));
2313         for (int i = 0; i != language_model->rowCount(); ++i) {
2314                 QModelIndex index = language_model->index(i, 0);
2315                 // Filter the list based on the available translation and add
2316                 // each language code only once
2317                 string const name = fromqstr(index.data(Qt::UserRole).toString());
2318                 Language const * lang = languages.getLanguage(name);
2319                 if (!lang)
2320                         continue;
2321                 // never remove the currently selected language
2322                 if (name != form->rc().gui_language
2323                     && name != lyxrc.gui_language
2324                     && (!Messages::available(lang->code())
2325                         || added.find(lang->code()) != added.end()))
2326                                 continue;
2327                 added.insert(lang->code());
2328                 uiLanguageCO->addItem(index.data(Qt::DisplayRole).toString(),
2329                         index.data(Qt::UserRole).toString());
2330         }
2331         uiLanguageCO->blockSignals(false);
2332 }
2333
2334
2335 void PrefLanguage::on_uiLanguageCO_currentIndexChanged(int)
2336 {
2337          QMessageBox::information(this, qt_("LyX needs to be restarted!"),
2338                  qt_("The change of user interface language will be fully "
2339                  "effective only after a restart."));
2340 }
2341
2342
2343 void PrefLanguage::on_languagePackageCO_currentIndexChanged(int i)
2344 {
2345          languagePackageED->setEnabled(i == 2);
2346 }
2347
2348
2349 void PrefLanguage::applyRC(LyXRC & rc) const
2350 {
2351         rc.visual_cursor = visualCursorRB->isChecked();
2352         rc.mark_foreign_language = markForeignCB->isChecked();
2353         rc.language_auto_begin = autoBeginCB->isChecked();
2354         rc.language_auto_end = autoEndCB->isChecked();
2355         int const p = languagePackageCO->currentIndex();
2356         if (p == 0)
2357                 rc.language_package_selection = LyXRC::LP_AUTO;
2358         else if (p == 1)
2359                 rc.language_package_selection = LyXRC::LP_BABEL;
2360         else if (p == 2)
2361                 rc.language_package_selection = LyXRC::LP_CUSTOM;
2362         else if (p == 3)
2363                 rc.language_package_selection = LyXRC::LP_NONE;
2364         rc.language_custom_package = fromqstr(languagePackageED->text());
2365         rc.language_global_options = globalCB->isChecked();
2366         rc.language_command_begin = fromqstr(startCommandED->text());
2367         rc.language_command_end = fromqstr(endCommandED->text());
2368         rc.gui_language = fromqstr(
2369                 uiLanguageCO->itemData(uiLanguageCO->currentIndex()).toString());
2370         rc.default_decimal_point = fromqstr(defaultDecimalPointLE->text());
2371         rc.default_length_unit = (Length::UNIT) defaultLengthUnitCO->itemData(defaultLengthUnitCO->currentIndex()).toInt();
2372 }
2373
2374
2375 void PrefLanguage::updateRC(LyXRC const & rc)
2376 {
2377         if (rc.visual_cursor)
2378                 visualCursorRB->setChecked(true);
2379         else
2380                 logicalCursorRB->setChecked(true);
2381         markForeignCB->setChecked(rc.mark_foreign_language);
2382         autoBeginCB->setChecked(rc.language_auto_begin);
2383         autoEndCB->setChecked(rc.language_auto_end);
2384         languagePackageCO->setCurrentIndex(rc.language_package_selection);
2385         languagePackageED->setText(toqstr(rc.language_custom_package));
2386         languagePackageED->setEnabled(languagePackageCO->currentIndex() == 2);
2387         globalCB->setChecked(rc.language_global_options);
2388         startCommandED->setText(toqstr(rc.language_command_begin));
2389         endCommandED->setText(toqstr(rc.language_command_end));
2390         defaultDecimalPointLE->setText(toqstr(rc.default_decimal_point));
2391         int pos = defaultLengthUnitCO->findData(int(rc.default_length_unit));
2392         defaultLengthUnitCO->setCurrentIndex(pos);
2393
2394         pos = uiLanguageCO->findData(toqstr(rc.gui_language));
2395         uiLanguageCO->blockSignals(true);
2396         uiLanguageCO->setCurrentIndex(pos);
2397         uiLanguageCO->blockSignals(false);
2398 }
2399
2400
2401 /////////////////////////////////////////////////////////////////////
2402 //
2403 // PrefPrinter
2404 //
2405 /////////////////////////////////////////////////////////////////////
2406
2407 PrefPrinter::PrefPrinter(GuiPreferences * form)
2408         : PrefModule(catOutput, N_("Printer"), form)
2409 {
2410         setupUi(this);
2411
2412         connect(printerAdaptCB, SIGNAL(clicked()),
2413                 this, SIGNAL(changed()));
2414         connect(printerCommandED, SIGNAL(textChanged(QString)),
2415                 this, SIGNAL(changed()));
2416         connect(printerNameED, SIGNAL(textChanged(QString)),
2417                 this, SIGNAL(changed()));
2418         connect(printerPageRangeED, SIGNAL(textChanged(QString)),
2419                 this, SIGNAL(changed()));
2420         connect(printerCopiesED, SIGNAL(textChanged(QString)),
2421                 this, SIGNAL(changed()));
2422         connect(printerReverseED, SIGNAL(textChanged(QString)),
2423                 this, SIGNAL(changed()));
2424         connect(printerToPrinterED, SIGNAL(textChanged(QString)),
2425                 this, SIGNAL(changed()));
2426         connect(printerExtensionED, SIGNAL(textChanged(QString)),
2427                 this, SIGNAL(changed()));
2428         connect(printerSpoolCommandED, SIGNAL(textChanged(QString)),
2429                 this, SIGNAL(changed()));
2430         connect(printerPaperTypeED, SIGNAL(textChanged(QString)),
2431                 this, SIGNAL(changed()));
2432         connect(printerEvenED, SIGNAL(textChanged(QString)),
2433                 this, SIGNAL(changed()));
2434         connect(printerOddED, SIGNAL(textChanged(QString)),
2435                 this, SIGNAL(changed()));
2436         connect(printerCollatedED, SIGNAL(textChanged(QString)),
2437                 this, SIGNAL(changed()));
2438         connect(printerLandscapeED, SIGNAL(textChanged(QString)),
2439                 this, SIGNAL(changed()));
2440         connect(printerToFileED, SIGNAL(textChanged(QString)),
2441                 this, SIGNAL(changed()));
2442         connect(printerExtraED, SIGNAL(textChanged(QString)),
2443                 this, SIGNAL(changed()));
2444         connect(printerSpoolPrefixED, SIGNAL(textChanged(QString)),
2445                 this, SIGNAL(changed()));
2446         connect(printerPaperSizeED, SIGNAL(textChanged(QString)),
2447                 this, SIGNAL(changed()));
2448
2449         printerNameED->setValidator(new NoNewLineValidator(printerNameED));
2450         printerCommandED->setValidator(new NoNewLineValidator(printerCommandED));
2451         printerEvenED->setValidator(new NoNewLineValidator(printerEvenED));
2452         printerPageRangeED->setValidator(new NoNewLineValidator(printerPageRangeED));
2453         printerCopiesED->setValidator(new NoNewLineValidator(printerCopiesED));
2454         printerReverseED->setValidator(new NoNewLineValidator(printerReverseED));
2455         printerToFileED->setValidator(new NoNewLineValidator(printerToFileED));
2456         printerPaperTypeED->setValidator(new NoNewLineValidator(printerPaperTypeED));
2457         printerExtraED->setValidator(new NoNewLineValidator(printerExtraED));
2458         printerOddED->setValidator(new NoNewLineValidator(printerOddED));
2459         printerCollatedED->setValidator(new NoNewLineValidator(printerCollatedED));
2460         printerLandscapeED->setValidator(new NoNewLineValidator(printerLandscapeED));
2461         printerToPrinterED->setValidator(new NoNewLineValidator(printerToPrinterED));
2462         printerExtensionED->setValidator(new NoNewLineValidator(printerExtensionED));
2463         printerPaperSizeED->setValidator(new NoNewLineValidator(printerPaperSizeED));
2464         printerSpoolCommandED->setValidator(new NoNewLineValidator(printerSpoolCommandED));
2465         printerSpoolPrefixED->setValidator(new NoNewLineValidator(printerSpoolPrefixED));
2466 }
2467
2468
2469 void PrefPrinter::applyRC(LyXRC & rc) const
2470 {
2471         rc.print_adapt_output = printerAdaptCB->isChecked();
2472         rc.print_command = fromqstr(printerCommandED->text());
2473         rc.printer = fromqstr(printerNameED->text());
2474
2475         rc.print_pagerange_flag = fromqstr(printerPageRangeED->text());
2476         rc.print_copies_flag = fromqstr(printerCopiesED->text());
2477         rc.print_reverse_flag = fromqstr(printerReverseED->text());
2478         rc.print_to_printer = fromqstr(printerToPrinterED->text());
2479         rc.print_file_extension = fromqstr(printerExtensionED->text());
2480         rc.print_spool_command = fromqstr(printerSpoolCommandED->text());
2481         rc.print_paper_flag = fromqstr(printerPaperTypeED->text());
2482         rc.print_evenpage_flag = fromqstr(printerEvenED->text());
2483         rc.print_oddpage_flag = fromqstr(printerOddED->text());
2484         rc.print_collcopies_flag = fromqstr(printerCollatedED->text());
2485         rc.print_landscape_flag = fromqstr(printerLandscapeED->text());
2486         rc.print_to_file = internal_path(fromqstr(printerToFileED->text()));
2487         rc.print_extra_options = fromqstr(printerExtraED->text());
2488         rc.print_spool_printerprefix = fromqstr(printerSpoolPrefixED->text());
2489         rc.print_paper_dimension_flag = fromqstr(printerPaperSizeED->text());
2490 }
2491
2492
2493 void PrefPrinter::updateRC(LyXRC const & rc)
2494 {
2495         printerAdaptCB->setChecked(rc.print_adapt_output);
2496         printerCommandED->setText(toqstr(rc.print_command));
2497         printerNameED->setText(toqstr(rc.printer));
2498
2499         printerPageRangeED->setText(toqstr(rc.print_pagerange_flag));
2500         printerCopiesED->setText(toqstr(rc.print_copies_flag));
2501         printerReverseED->setText(toqstr(rc.print_reverse_flag));
2502         printerToPrinterED->setText(toqstr(rc.print_to_printer));
2503         printerExtensionED->setText(toqstr(rc.print_file_extension));
2504         printerSpoolCommandED->setText(toqstr(rc.print_spool_command));
2505         printerPaperTypeED->setText(toqstr(rc.print_paper_flag));
2506         printerEvenED->setText(toqstr(rc.print_evenpage_flag));
2507         printerOddED->setText(toqstr(rc.print_oddpage_flag));
2508         printerCollatedED->setText(toqstr(rc.print_collcopies_flag));
2509         printerLandscapeED->setText(toqstr(rc.print_landscape_flag));
2510         printerToFileED->setText(toqstr(external_path(rc.print_to_file)));
2511         printerExtraED->setText(toqstr(rc.print_extra_options));
2512         printerSpoolPrefixED->setText(toqstr(rc.print_spool_printerprefix));
2513         printerPaperSizeED->setText(toqstr(rc.print_paper_dimension_flag));
2514 }
2515
2516
2517 /////////////////////////////////////////////////////////////////////
2518 //
2519 // PrefUserInterface
2520 //
2521 /////////////////////////////////////////////////////////////////////
2522
2523 PrefUserInterface::PrefUserInterface(GuiPreferences * form)
2524         : PrefModule(catLookAndFeel, N_("User Interface"), form)
2525 {
2526         setupUi(this);
2527
2528         connect(uiFilePB, SIGNAL(clicked()),
2529                 this, SLOT(selectUi()));
2530         connect(uiFileED, SIGNAL(textChanged(QString)),
2531                 this, SIGNAL(changed()));
2532         connect(iconSetCO, SIGNAL(activated(int)),
2533                 this, SIGNAL(changed()));
2534         connect(useSystemThemeIconsCB, SIGNAL(clicked()),
2535                 this, SIGNAL(changed()));
2536         connect(lastfilesSB, SIGNAL(valueChanged(int)),
2537                 this, SIGNAL(changed()));
2538         connect(tooltipCB, SIGNAL(toggled(bool)),
2539                 this, SIGNAL(changed()));
2540         lastfilesSB->setMaximum(maxlastfiles);
2541
2542         iconSetCO->addItem(qt_("Default"), QString());
2543         iconSetCO->addItem(qt_("Classic"), "classic");
2544         iconSetCO->addItem(qt_("Oxygen"), "oxygen");
2545
2546 #if (!(defined Q_WS_X11 || defined(QPA_XCB)) || QT_VERSION < 0x040600)
2547         useSystemThemeIconsCB->hide();
2548 #endif
2549 }
2550
2551
2552 void PrefUserInterface::applyRC(LyXRC & rc) const
2553 {
2554         rc.icon_set = fromqstr(iconSetCO->itemData(
2555                 iconSetCO->currentIndex()).toString());
2556
2557         rc.ui_file = internal_path(fromqstr(uiFileED->text()));
2558         rc.use_system_theme_icons = useSystemThemeIconsCB->isChecked();
2559         rc.num_lastfiles = lastfilesSB->value();
2560         rc.use_tooltip = tooltipCB->isChecked();
2561 }
2562
2563
2564 void PrefUserInterface::updateRC(LyXRC const & rc)
2565 {
2566         int iconset = iconSetCO->findData(toqstr(rc.icon_set));
2567         if (iconset < 0)
2568                 iconset = 0;
2569         iconSetCO->setCurrentIndex(iconset);
2570         useSystemThemeIconsCB->setChecked(rc.use_system_theme_icons);
2571         uiFileED->setText(toqstr(external_path(rc.ui_file)));
2572         lastfilesSB->setValue(rc.num_lastfiles);
2573         tooltipCB->setChecked(rc.use_tooltip);
2574 }
2575
2576
2577 void PrefUserInterface::selectUi()
2578 {
2579         QString file = form_->browseUI(internalPath(uiFileED->text()));
2580         if (!file.isEmpty())
2581                 uiFileED->setText(file);
2582 }
2583
2584
2585 /////////////////////////////////////////////////////////////////////
2586 //
2587 // PrefDocumentHandling
2588 //
2589 /////////////////////////////////////////////////////////////////////
2590
2591 PrefDocHandling::PrefDocHandling(GuiPreferences * form)
2592         : PrefModule(catLookAndFeel, N_("Document Handling"), form)
2593 {
2594         setupUi(this);
2595
2596         connect(autoSaveCB, SIGNAL(toggled(bool)),
2597                 autoSaveSB, SLOT(setEnabled(bool)));
2598         connect(autoSaveCB, SIGNAL(toggled(bool)),
2599                 TextLabel1, SLOT(setEnabled(bool)));
2600         connect(openDocumentsInTabsCB, SIGNAL(clicked()),
2601                 this, SIGNAL(changed()));
2602         connect(singleInstanceCB, SIGNAL(clicked()),
2603                 this, SIGNAL(changed()));
2604         connect(singleCloseTabButtonCB, SIGNAL(clicked()),
2605                 this, SIGNAL(changed()));
2606         connect(closeLastViewCO, SIGNAL(activated(int)),
2607                 this, SIGNAL(changed()));
2608         connect(restoreCursorCB, SIGNAL(clicked()),
2609                 this, SIGNAL(changed()));
2610         connect(loadSessionCB, SIGNAL(clicked()),
2611                 this, SIGNAL(changed()));
2612         connect(allowGeometrySessionCB, SIGNAL(clicked()),
2613                 this, SIGNAL(changed()));
2614         connect(autoSaveSB, SIGNAL(valueChanged(int)),
2615                 this, SIGNAL(changed()));
2616         connect(autoSaveCB, SIGNAL(clicked()),
2617                 this, SIGNAL(changed()));
2618         connect(backupCB, SIGNAL(clicked()),
2619                 this, SIGNAL(changed()));
2620         connect(saveCompressedCB, SIGNAL(clicked()),
2621                 this, SIGNAL(changed()));
2622 }
2623
2624
2625 void PrefDocHandling::applyRC(LyXRC & rc) const
2626 {
2627         rc.use_lastfilepos = restoreCursorCB->isChecked();
2628         rc.load_session = loadSessionCB->isChecked();
2629         rc.allow_geometry_session = allowGeometrySessionCB->isChecked();
2630         rc.autosave = autoSaveCB->isChecked() ?  autoSaveSB->value() * 60 : 0;
2631         rc.make_backup = backupCB->isChecked();
2632         rc.save_compressed = saveCompressedCB->isChecked();
2633         rc.open_buffers_in_tabs = openDocumentsInTabsCB->isChecked();
2634         rc.single_instance = singleInstanceCB->isChecked();
2635         rc.single_close_tab_button = singleCloseTabButtonCB->isChecked();
2636
2637         switch (closeLastViewCO->currentIndex()) {
2638         case 0:
2639                 rc.close_buffer_with_last_view = "yes";
2640                 break;
2641         case 1:
2642                 rc.close_buffer_with_last_view = "no";
2643                 break;
2644         case 2:
2645                 rc.close_buffer_with_last_view = "ask";
2646                 break;
2647         default:
2648                 ;
2649         }
2650 }
2651
2652
2653 void PrefDocHandling::updateRC(LyXRC const & rc)
2654 {
2655         restoreCursorCB->setChecked(rc.use_lastfilepos);
2656         loadSessionCB->setChecked(rc.load_session);
2657         allowGeometrySessionCB->setChecked(rc.allow_geometry_session);
2658         // convert to minutes
2659         bool autosave = rc.autosave > 0;
2660         int mins = rc.autosave / 60;
2661         if (!mins)
2662                 mins = 5;
2663         autoSaveSB->setValue(mins);
2664         autoSaveCB->setChecked(autosave);
2665         autoSaveSB->setEnabled(autosave);
2666         backupCB->setChecked(rc.make_backup);
2667         saveCompressedCB->setChecked(rc.save_compressed);
2668         openDocumentsInTabsCB->setChecked(rc.open_buffers_in_tabs);
2669         singleInstanceCB->setChecked(rc.single_instance && !rc.lyxpipes.empty());
2670         singleInstanceCB->setEnabled(!rc.lyxpipes.empty());
2671         singleCloseTabButtonCB->setChecked(rc.single_close_tab_button);
2672         if (rc.close_buffer_with_last_view == "yes")
2673                 closeLastViewCO->setCurrentIndex(0);
2674         else if (rc.close_buffer_with_last_view == "no")
2675                 closeLastViewCO->setCurrentIndex(1);
2676         else if (rc.close_buffer_with_last_view == "ask")
2677                 closeLastViewCO->setCurrentIndex(2);
2678 }
2679
2680
2681 void PrefDocHandling::on_clearSessionPB_clicked()
2682 {
2683         guiApp->clearSession();
2684 }
2685
2686
2687
2688 /////////////////////////////////////////////////////////////////////
2689 //
2690 // PrefEdit
2691 //
2692 /////////////////////////////////////////////////////////////////////
2693
2694 PrefEdit::PrefEdit(GuiPreferences * form)
2695         : PrefModule(catEditing, N_("Control"), form)
2696 {
2697         setupUi(this);
2698
2699         connect(cursorFollowsCB, SIGNAL(clicked()),
2700                 this, SIGNAL(changed()));
2701         connect(scrollBelowCB, SIGNAL(clicked()),
2702                 this, SIGNAL(changed()));
2703         connect(macLikeCursorMovementCB, SIGNAL(clicked()),
2704                 this, SIGNAL(changed()));
2705         connect(sortEnvironmentsCB, SIGNAL(clicked()),
2706                 this, SIGNAL(changed()));
2707         connect(groupEnvironmentsCB, SIGNAL(clicked()),
2708                 this, SIGNAL(changed()));
2709         connect(macroEditStyleCO, SIGNAL(activated(int)),
2710                 this, SIGNAL(changed()));
2711         connect(cursorWidthSB, SIGNAL(valueChanged(int)),
2712                 this, SIGNAL(changed()));
2713         connect(fullscreenLimitGB, SIGNAL(clicked()),
2714                 this, SIGNAL(changed()));
2715         connect(fullscreenWidthSB, SIGNAL(valueChanged(int)),
2716                 this, SIGNAL(changed()));
2717         connect(toggleTabbarCB, SIGNAL(toggled(bool)),
2718                 this, SIGNAL(changed()));
2719         connect(toggleMenubarCB, SIGNAL(toggled(bool)),
2720                 this, SIGNAL(changed()));
2721         connect(toggleScrollbarCB, SIGNAL(toggled(bool)),
2722                 this, SIGNAL(changed()));
2723         connect(toggleStatusbarCB, SIGNAL(toggled(bool)),
2724                 this, SIGNAL(changed()));
2725         connect(toggleToolbarsCB, SIGNAL(toggled(bool)),
2726                 this, SIGNAL(changed()));
2727 }
2728
2729
2730 void PrefEdit::applyRC(LyXRC & rc) const
2731 {
2732         rc.cursor_follows_scrollbar = cursorFollowsCB->isChecked();
2733         rc.scroll_below_document = scrollBelowCB->isChecked();
2734         rc.mac_like_cursor_movement = macLikeCursorMovementCB->isChecked();
2735         rc.sort_layouts = sortEnvironmentsCB->isChecked();
2736         rc.group_layouts = groupEnvironmentsCB->isChecked();
2737         switch (macroEditStyleCO->currentIndex()) {
2738                 case 0: rc.macro_edit_style = LyXRC::MACRO_EDIT_INLINE_BOX; break;
2739                 case 1: rc.macro_edit_style = LyXRC::MACRO_EDIT_INLINE; break;
2740                 case 2: rc.macro_edit_style = LyXRC::MACRO_EDIT_LIST;   break;
2741         }
2742         rc.cursor_width = cursorWidthSB->value();
2743         rc.full_screen_toolbars = toggleToolbarsCB->isChecked();
2744         rc.full_screen_scrollbar = toggleScrollbarCB->isChecked();
2745         rc.full_screen_statusbar = toggleStatusbarCB->isChecked();
2746         rc.full_screen_tabbar = toggleTabbarCB->isChecked();
2747         rc.full_screen_menubar = toggleMenubarCB->isChecked();
2748         rc.full_screen_width = fullscreenWidthSB->value();
2749         rc.full_screen_limit = fullscreenLimitGB->isChecked();
2750 }
2751
2752
2753 void PrefEdit::updateRC(LyXRC const & rc)
2754 {
2755         cursorFollowsCB->setChecked(rc.cursor_follows_scrollbar);
2756         scrollBelowCB->setChecked(rc.scroll_below_document);
2757         macLikeCursorMovementCB->setChecked(rc.mac_like_cursor_movement);
2758         sortEnvironmentsCB->setChecked(rc.sort_layouts);
2759         groupEnvironmentsCB->setChecked(rc.group_layouts);
2760         macroEditStyleCO->setCurrentIndex(rc.macro_edit_style);
2761         cursorWidthSB->setValue(rc.cursor_width);
2762         toggleScrollbarCB->setChecked(rc.full_screen_scrollbar);
2763         toggleScrollbarCB->setChecked(rc.full_screen_statusbar);
2764         toggleToolbarsCB->setChecked(rc.full_screen_toolbars);
2765         toggleTabbarCB->setChecked(rc.full_screen_tabbar);
2766         toggleMenubarCB->setChecked(rc.full_screen_menubar);
2767         fullscreenWidthSB->setValue(rc.full_screen_width);
2768         fullscreenLimitGB->setChecked(rc.full_screen_limit);
2769 }
2770
2771
2772 /////////////////////////////////////////////////////////////////////
2773 //
2774 // PrefShortcuts
2775 //
2776 /////////////////////////////////////////////////////////////////////
2777
2778
2779 GuiShortcutDialog::GuiShortcutDialog(QWidget * parent) : QDialog(parent)
2780 {
2781         Ui::shortcutUi::setupUi(this);
2782         QDialog::setModal(true);
2783 }
2784
2785
2786 PrefShortcuts::PrefShortcuts(GuiPreferences * form)
2787         : PrefModule(catEditing, N_("Shortcuts"), form)
2788 {
2789         setupUi(this);
2790
2791         shortcutsTW->setColumnCount(2);
2792         shortcutsTW->headerItem()->setText(0, qt_("Function"));
2793         shortcutsTW->headerItem()->setText(1, qt_("Shortcut"));
2794         shortcutsTW->setSortingEnabled(true);
2795         // Multi-selection can be annoying.
2796         // shortcutsTW->setSelectionMode(QAbstractItemView::MultiSelection);
2797
2798         connect(bindFilePB, SIGNAL(clicked()),
2799                 this, SLOT(selectBind()));
2800         connect(bindFileED, SIGNAL(textChanged(QString)),
2801                 this, SIGNAL(changed()));
2802
2803         shortcut_ = new GuiShortcutDialog(this);
2804         shortcut_bc_.setPolicy(ButtonPolicy::OkCancelPolicy);
2805         shortcut_bc_.setOK(shortcut_->okPB);
2806         shortcut_bc_.setCancel(shortcut_->cancelPB);
2807
2808         connect(shortcut_->okPB, SIGNAL(clicked()),
2809                 this, SIGNAL(changed()));
2810         connect(shortcut_->cancelPB, SIGNAL(clicked()),
2811                 shortcut_, SLOT(reject()));
2812         connect(shortcut_->clearPB, SIGNAL(clicked()),
2813                 this, SLOT(shortcutClearPressed()));
2814         connect(shortcut_->removePB, SIGNAL(clicked()),
2815                 this, SLOT(shortcutRemovePressed()));
2816         connect(shortcut_->okPB, SIGNAL(clicked()),
2817                 this, SLOT(shortcutOkPressed()));
2818         connect(shortcut_->cancelPB, SIGNAL(clicked()),
2819                 this, SLOT(shortcutCancelPressed()));
2820 }
2821
2822
2823 void PrefShortcuts::applyRC(LyXRC & rc) const
2824 {
2825         rc.bind_file = internal_path(fromqstr(bindFileED->text()));
2826         // write user_bind and user_unbind to .lyx/bind/user.bind
2827         FileName bind_dir(addPath(package().user_support().absFileName(), "bind"));
2828         if (!bind_dir.exists() && !bind_dir.createDirectory(0777)) {
2829                 lyxerr << "LyX could not create the user bind directory '"
2830                        << bind_dir << "'. All user-defined key bindings will be lost." << endl;
2831                 return;
2832         }
2833         if (!bind_dir.isDirWritable()) {
2834                 lyxerr << "LyX could not write to the user bind directory '"
2835                        << bind_dir << "'. All user-defined key bindings will be lost." << endl;
2836                 return;
2837         }
2838         FileName user_bind_file(bind_dir.absFileName() + "/user.bind");
2839         user_unbind_.write(user_bind_file.toFilesystemEncoding(), false, true);
2840         user_bind_.write(user_bind_file.toFilesystemEncoding(), true, false);
2841         // immediately apply the keybindings. Why this is not done before?
2842         // The good thing is that the menus are updated automatically.
2843         theTopLevelKeymap().clear();
2844         theTopLevelKeymap().read("site");
2845         theTopLevelKeymap().read(rc.bind_file, 0, KeyMap::Fallback);
2846         theTopLevelKeymap().read("user", 0, KeyMap::MissingOK);
2847 }
2848
2849
2850 void PrefShortcuts::updateRC(LyXRC const & rc)
2851 {
2852         bindFileED->setText(toqstr(external_path(rc.bind_file)));
2853         //
2854         system_bind_.clear();
2855         user_bind_.clear();
2856         user_unbind_.clear();
2857         system_bind_.read("site");
2858         system_bind_.read(rc.bind_file);
2859         // \unbind in user.bind is added to user_unbind_
2860         user_bind_.read("user", &user_unbind_, KeyMap::MissingOK);
2861         updateShortcutsTW();
2862 }
2863
2864
2865 void PrefShortcuts::updateShortcutsTW()
2866 {
2867         shortcutsTW->clear();
2868
2869         editItem_ = new QTreeWidgetItem(shortcutsTW);
2870         editItem_->setText(0, qt_("Cursor, Mouse and Editing Functions"));
2871         editItem_->setFlags(editItem_->flags() & ~Qt::ItemIsSelectable);
2872
2873         mathItem_ = new QTreeWidgetItem(shortcutsTW);
2874         mathItem_->setText(0, qt_("Mathematical Symbols"));
2875         mathItem_->setFlags(mathItem_->flags() & ~Qt::ItemIsSelectable);
2876
2877         bufferItem_ = new QTreeWidgetItem(shortcutsTW);
2878         bufferItem_->setText(0, qt_("Document and Window"));
2879         bufferItem_->setFlags(bufferItem_->flags() & ~Qt::ItemIsSelectable);
2880
2881         layoutItem_ = new QTreeWidgetItem(shortcutsTW);
2882         layoutItem_->setText(0, qt_("Font, Layouts and Textclasses"));
2883         layoutItem_->setFlags(layoutItem_->flags() & ~Qt::ItemIsSelectable);
2884
2885         systemItem_ = new QTreeWidgetItem(shortcutsTW);
2886         systemItem_->setText(0, qt_("System and Miscellaneous"));
2887         systemItem_->setFlags(systemItem_->flags() & ~Qt::ItemIsSelectable);
2888
2889         // listBindings(unbound=true) lists all bound and unbound lfuns
2890         // Items in this list is tagged by its source.
2891         KeyMap::BindingList bindinglist = system_bind_.listBindings(true,
2892                 KeyMap::System);
2893         KeyMap::BindingList user_bindinglist = user_bind_.listBindings(false,
2894                 KeyMap::UserBind);
2895         KeyMap::BindingList user_unbindinglist = user_unbind_.listBindings(false,
2896                 KeyMap::UserUnbind);
2897         bindinglist.insert(bindinglist.end(), user_bindinglist.begin(),
2898                         user_bindinglist.end());
2899         bindinglist.insert(bindinglist.end(), user_unbindinglist.begin(),
2900                         user_unbindinglist.end());
2901
2902         KeyMap::BindingList::const_iterator it = bindinglist.begin();
2903         KeyMap::BindingList::const_iterator it_end = bindinglist.end();
2904         for (; it != it_end; ++it)
2905                 insertShortcutItem(it->request, it->sequence, KeyMap::ItemType(it->tag));
2906
2907         shortcutsTW->sortItems(0, Qt::AscendingOrder);
2908         QList<QTreeWidgetItem*> items = shortcutsTW->selectedItems();
2909         removePB->setEnabled(!items.isEmpty() && !items[0]->text(1).isEmpty());
2910         modifyPB->setEnabled(!items.isEmpty());
2911
2912         shortcutsTW->resizeColumnToContents(0);
2913 }
2914
2915
2916 void PrefShortcuts::setItemType(QTreeWidgetItem * item, KeyMap::ItemType tag)
2917 {
2918         item->setData(0, Qt::UserRole, QVariant(tag));
2919         QFont font;
2920
2921         switch (tag) {
2922         case KeyMap::System:
2923                 break;
2924         case KeyMap::UserBind:
2925                 font.setBold(true);
2926                 break;
2927         case KeyMap::UserUnbind:
2928                 font.setStrikeOut(true);
2929                 break;
2930         // this item is not displayed now.
2931         case KeyMap::UserExtraUnbind:
2932                 font.setStrikeOut(true);
2933                 break;
2934         }
2935
2936         item->setFont(1, font);
2937 }
2938
2939
2940 QTreeWidgetItem * PrefShortcuts::insertShortcutItem(FuncRequest const & lfun,
2941                 KeySequence const & seq, KeyMap::ItemType tag)
2942 {
2943         FuncCode const action = lfun.action();
2944         string const action_name = lyxaction.getActionName(action);
2945         QString const lfun_name = toqstr(from_utf8(action_name)
2946                         + ' ' + lfun.argument());
2947         QString const shortcut = toqstr(seq.print(KeySequence::ForGui));
2948         KeyMap::ItemType item_tag = tag;
2949
2950         QTreeWidgetItem * newItem = 0;
2951         // for unbind items, try to find an existing item in the system bind list
2952         if (tag == KeyMap::UserUnbind) {
2953                 QList<QTreeWidgetItem*> const items = shortcutsTW->findItems(lfun_name,
2954                         Qt::MatchFlags(Qt::MatchExactly | Qt::MatchRecursive), 0);
2955                 for (int i = 0; i < items.size(); ++i) {
2956                         if (items[i]->text(1) == shortcut)
2957                                 newItem = items[i];
2958                                 break;
2959                         }
2960                 // if not found, this unbind item is KeyMap::UserExtraUnbind
2961                 // Such an item is not displayed to avoid confusion (what is
2962                 // unmatched removed?).
2963                 if (!newItem) {
2964                         item_tag = KeyMap::UserExtraUnbind;
2965                         return 0;
2966                 }
2967         }
2968         if (!newItem) {
2969                 switch(lyxaction.getActionType(action)) {
2970                 case LyXAction::Hidden:
2971                         return 0;
2972                 case LyXAction::Edit:
2973                         newItem = new QTreeWidgetItem(editItem_);
2974                         break;
2975                 case LyXAction::Math:
2976                         newItem = new QTreeWidgetItem(mathItem_);
2977                         break;
2978                 case LyXAction::Buffer:
2979                         newItem = new QTreeWidgetItem(bufferItem_);
2980                         break;
2981                 case LyXAction::Layout:
2982                         newItem = new QTreeWidgetItem(layoutItem_);
2983                         break;
2984                 case LyXAction::System:
2985                         newItem = new QTreeWidgetItem(systemItem_);
2986                         break;
2987                 default:
2988                         // this should not happen
2989                         newItem = new QTreeWidgetItem(shortcutsTW);
2990                 }
2991         }
2992
2993         newItem->setText(0, lfun_name);
2994         newItem->setText(1, shortcut);
2995         // record BindFile representation to recover KeySequence when needed.
2996         newItem->setData(1, Qt::UserRole, toqstr(seq.print(KeySequence::BindFile)));
2997         setItemType(newItem, item_tag);
2998         return newItem;
2999 }
3000
3001
3002 void PrefShortcuts::on_shortcutsTW_itemSelectionChanged()
3003 {
3004         QList<QTreeWidgetItem*> items = shortcutsTW->selectedItems();
3005         removePB->setEnabled(!items.isEmpty() && !items[0]->text(1).isEmpty());
3006         modifyPB->setEnabled(!items.isEmpty());
3007         if (items.isEmpty())
3008                 return;
3009
3010         KeyMap::ItemType tag =
3011                 static_cast<KeyMap::ItemType>(items[0]->data(0, Qt::UserRole).toInt());
3012         if (tag == KeyMap::UserUnbind)
3013                 removePB->setText(qt_("Res&tore"));
3014         else
3015                 removePB->setText(qt_("Remo&ve"));
3016 }
3017
3018
3019 void PrefShortcuts::on_shortcutsTW_itemDoubleClicked()
3020 {
3021         modifyShortcut();
3022 }
3023
3024
3025 void PrefShortcuts::modifyShortcut()
3026 {
3027         QTreeWidgetItem * item = shortcutsTW->currentItem();
3028         if (item->flags() & Qt::ItemIsSelectable) {
3029                 shortcut_->lfunLE->setText(item->text(0));
3030                 save_lfun_ = item->text(0).trimmed();
3031                 shortcut_->shortcutWG->setText(item->text(1));
3032                 KeySequence seq;
3033                 seq.parse(fromqstr(item->data(1, Qt::UserRole).toString()));
3034                 shortcut_->shortcutWG->setKeySequence(seq);
3035                 shortcut_->shortcutWG->setFocus();
3036                 shortcut_->exec();
3037         }
3038 }
3039
3040
3041 void PrefShortcuts::removeShortcut()
3042 {
3043         // it seems that only one item can be selected, but I am
3044         // removing all selected items anyway.
3045         QList<QTreeWidgetItem*> items = shortcutsTW->selectedItems();
3046         for (int i = 0; i < items.size(); ++i) {
3047                 string shortcut = fromqstr(items[i]->data(1, Qt::UserRole).toString());
3048                 string lfun = fromqstr(items[i]->text(0));
3049                 FuncRequest func = lyxaction.lookupFunc(lfun);
3050                 KeyMap::ItemType tag =
3051                         static_cast<KeyMap::ItemType>(items[i]->data(0, Qt::UserRole).toInt());
3052
3053                 switch (tag) {
3054                 case KeyMap::System: {
3055                         // for system bind, we do not touch the item
3056                         // but add an user unbind item
3057                         user_unbind_.bind(shortcut, func);
3058                         setItemType(items[i], KeyMap::UserUnbind);
3059                         removePB->setText(qt_("Res&tore"));
3060                         break;
3061                 }
3062                 case KeyMap::UserBind: {
3063                         // for user_bind, we remove this bind
3064                         QTreeWidgetItem * parent = items[i]->parent();
3065                         int itemIdx = parent->indexOfChild(items[i]);
3066                         parent->takeChild(itemIdx);
3067                         if (itemIdx > 0)
3068                                 shortcutsTW->scrollToItem(parent->child(itemIdx - 1));
3069                         else
3070                                 shortcutsTW->scrollToItem(parent);
3071                         user_bind_.unbind(shortcut, func);
3072                         break;
3073                 }
3074                 case KeyMap::UserUnbind: {
3075                         // for user_unbind, we remove the unbind, and the item
3076                         // become KeyMap::System again.
3077                         user_unbind_.unbind(shortcut, func);
3078                         setItemType(items[i], KeyMap::System);
3079                         removePB->setText(qt_("Remo&ve"));
3080                         break;
3081                 }
3082                 case KeyMap::UserExtraUnbind: {
3083                         // for user unbind that is not in system bind file,
3084                         // remove this unbind file
3085                         QTreeWidgetItem * parent = items[i]->parent();
3086                         parent->takeChild(parent->indexOfChild(items[i]));
3087                         user_unbind_.unbind(shortcut, func);
3088                 }
3089                 }
3090         }
3091 }
3092
3093
3094 void PrefShortcuts::selectBind()
3095 {
3096         QString file = form_->browsebind(internalPath(bindFileED->text()));
3097         if (!file.isEmpty()) {
3098                 bindFileED->setText(file);
3099                 system_bind_ = KeyMap();
3100                 system_bind_.read(fromqstr(file));
3101                 updateShortcutsTW();
3102         }
3103 }
3104
3105
3106 void PrefShortcuts::on_modifyPB_pressed()
3107 {
3108         modifyShortcut();
3109 }
3110
3111
3112 void PrefShortcuts::on_newPB_pressed()
3113 {
3114         shortcut_->lfunLE->clear();
3115         shortcut_->shortcutWG->reset();
3116         save_lfun_ = QString();
3117         shortcut_->exec();
3118 }
3119
3120
3121 void PrefShortcuts::on_removePB_pressed()
3122 {
3123         changed();
3124         removeShortcut();
3125 }
3126
3127
3128 void PrefShortcuts::on_searchLE_textEdited()
3129 {
3130         if (searchLE->text().isEmpty()) {
3131                 // show all hidden items
3132                 QTreeWidgetItemIterator it(shortcutsTW, QTreeWidgetItemIterator::Hidden);
3133                 while (*it)
3134                         shortcutsTW->setItemHidden(*it++, false);
3135                 return;
3136         }
3137         // search both columns
3138         QList<QTreeWidgetItem *> matched = shortcutsTW->findItems(searchLE->text(),
3139                 Qt::MatchFlags(Qt::MatchContains | Qt::MatchRecursive), 0);
3140         matched += shortcutsTW->findItems(searchLE->text(),
3141                 Qt::MatchFlags(Qt::MatchContains | Qt::MatchRecursive), 1);
3142
3143         // hide everyone (to avoid searching in matched QList repeatedly
3144         QTreeWidgetItemIterator it(shortcutsTW, QTreeWidgetItemIterator::Selectable);
3145         while (*it)
3146                 shortcutsTW->setItemHidden(*it++, true);
3147         // show matched items
3148         for (int i = 0; i < matched.size(); ++i) {
3149                 shortcutsTW->setItemHidden(matched[i], false);
3150                 shortcutsTW->setItemExpanded(matched[i]->parent(), true);
3151         }
3152 }
3153
3154
3155 docstring makeCmdString(FuncRequest const & f)
3156 {
3157         docstring actionStr = from_ascii(lyxaction.getActionName(f.action()));
3158         if (!f.argument().empty())
3159                 actionStr += " " + f.argument();
3160         return actionStr;
3161 }
3162
3163
3164 void PrefShortcuts::shortcutOkPressed()
3165 {
3166         QString const new_lfun = shortcut_->lfunLE->text();
3167         FuncRequest func = lyxaction.lookupFunc(fromqstr(new_lfun));
3168
3169         if (func.action() == LFUN_UNKNOWN_ACTION) {
3170                 Alert::error(_("Failed to create shortcut"),
3171                         _("Unknown or invalid LyX function"));
3172                 return;
3173         }
3174
3175         KeySequence k = shortcut_->shortcutWG->getKeySequence();
3176         if (k.length() == 0) {
3177                 Alert::error(_("Failed to create shortcut"),
3178                         _("Invalid or empty key sequence"));
3179                 return;
3180         }
3181
3182         // check to see if there's been any change
3183         FuncRequest oldBinding = system_bind_.getBinding(k);
3184         if (oldBinding.action() == LFUN_UNKNOWN_ACTION)
3185                 oldBinding = user_bind_.getBinding(k);
3186         if (oldBinding == func)
3187                 // nothing has changed
3188                 return;
3189
3190         // make sure this key isn't already bound---and, if so, prompt user
3191         FuncCode const unbind = user_unbind_.getBinding(k).action();
3192         docstring const action_string = makeCmdString(oldBinding);
3193         if (oldBinding.action() > LFUN_NOACTION && unbind == LFUN_UNKNOWN_ACTION
3194                   && save_lfun_ != toqstr(action_string)) {
3195                 docstring const new_action_string = makeCmdString(func);
3196                 docstring const text = bformat(_("Shortcut `%1$s' is already bound to "
3197                                                  "%2$s.\n"
3198                                                  "Are you sure you want to unbind the "
3199                                                  "current shortcut and bind it to %3$s?"),
3200                                                k.print(KeySequence::ForGui), action_string,
3201                                                new_action_string);
3202                 int ret = Alert::prompt(_("Redefine shortcut?"),
3203                                         text, 0, 1, _("&Redefine"), _("&Cancel"));
3204                 if (ret != 0)
3205                         return;
3206                 QString const sequence_text = toqstr(k.print(KeySequence::ForGui));
3207                 QList<QTreeWidgetItem*> items = shortcutsTW->findItems(sequence_text,
3208                         Qt::MatchFlags(Qt::MatchExactly | Qt::MatchRecursive), 1);
3209                 if (items.size() > 0) {
3210                         // should always happen
3211                         bool expanded = items[0]->parent()->isExpanded();
3212                         shortcutsTW->setCurrentItem(items[0]);
3213                         removeShortcut();
3214                         shortcutsTW->setCurrentItem(0);
3215                         // make sure user doesn't see tree expansion if
3216                         // old binding wasn't in an expanded tree
3217                         if (!expanded)
3218                                 items[0]->parent()->setExpanded(false);
3219                 }
3220         }
3221
3222         shortcut_->accept();
3223
3224         if (!save_lfun_.isEmpty())
3225                 // real modification of the lfun's shortcut,
3226                 // so remove the previous one
3227                 removeShortcut();
3228
3229         QTreeWidgetItem * item = insertShortcutItem(func, k, KeyMap::UserBind);
3230         if (item) {
3231                 user_bind_.bind(&k, func);
3232                 shortcutsTW->sortItems(0, Qt::AscendingOrder);
3233                 shortcutsTW->setItemExpanded(item->parent(), true);
3234                 shortcutsTW->scrollToItem(item);
3235         } else {
3236                 Alert::error(_("Failed to create shortcut"),
3237                         _("Can not insert shortcut to the list"));
3238                 return;
3239         }
3240 }
3241
3242
3243 void PrefShortcuts::shortcutCancelPressed()
3244 {
3245         shortcut_->shortcutWG->reset();
3246 }
3247
3248
3249 void PrefShortcuts::shortcutClearPressed()
3250 {
3251         shortcut_->shortcutWG->reset();
3252 }
3253
3254
3255 void PrefShortcuts::shortcutRemovePressed()
3256 {
3257         shortcut_->shortcutWG->removeFromSequence();
3258 }
3259
3260
3261 /////////////////////////////////////////////////////////////////////
3262 //
3263 // PrefIdentity
3264 //
3265 /////////////////////////////////////////////////////////////////////
3266
3267 PrefIdentity::PrefIdentity(GuiPreferences * form)
3268         : PrefModule(QString(), N_("Identity"), form)
3269 {
3270         setupUi(this);
3271
3272         connect(nameED, SIGNAL(textChanged(QString)),
3273                 this, SIGNAL(changed()));
3274         connect(emailED, SIGNAL(textChanged(QString)),
3275                 this, SIGNAL(changed()));
3276
3277         nameED->setValidator(new NoNewLineValidator(nameED));
3278         emailED->setValidator(new NoNewLineValidator(emailED));
3279 }
3280
3281
3282 void PrefIdentity::applyRC(LyXRC & rc) const
3283 {
3284         rc.user_name = fromqstr(nameED->text());
3285         rc.user_email = fromqstr(emailED->text());
3286 }
3287
3288
3289 void PrefIdentity::updateRC(LyXRC const & rc)
3290 {
3291         nameED->setText(toqstr(rc.user_name));
3292         emailED->setText(toqstr(rc.user_email));
3293 }
3294
3295
3296
3297 /////////////////////////////////////////////////////////////////////
3298 //
3299 // GuiPreferences
3300 //
3301 /////////////////////////////////////////////////////////////////////
3302
3303 GuiPreferences::GuiPreferences(GuiView & lv)
3304         : GuiDialog(lv, "prefs", qt_("Preferences")), update_screen_font_(false)
3305 {
3306         setupUi(this);
3307
3308         QDialog::setModal(false);
3309
3310         connect(savePB, SIGNAL(clicked()), this, SLOT(slotOK()));
3311         connect(applyPB, SIGNAL(clicked()), this, SLOT(slotApply()));
3312         connect(closePB, SIGNAL(clicked()), this, SLOT(slotClose()));
3313         connect(restorePB, SIGNAL(clicked()), this, SLOT(slotRestore()));
3314
3315         addModule(new PrefUserInterface(this));
3316         addModule(new PrefDocHandling(this));
3317         addModule(new PrefEdit(this));
3318         addModule(new PrefShortcuts(this));
3319         PrefScreenFonts * screenfonts = new PrefScreenFonts(this);
3320         connect(this, SIGNAL(prefsApplied(LyXRC const &)),
3321                         screenfonts, SLOT(updateScreenFontSizes(LyXRC const &)));
3322         addModule(screenfonts);
3323         addModule(new PrefColors(this));
3324         addModule(new PrefDisplay(this));
3325         addModule(new PrefInput(this));
3326         addModule(new PrefCompletion(this));
3327
3328         addModule(new PrefPaths(this));
3329
3330         addModule(new PrefIdentity(this));
3331
3332         addModule(new PrefLanguage(this));
3333         addModule(new PrefSpellchecker(this));
3334
3335         //for strftime validator
3336         PrefOutput * output = new PrefOutput(this);
3337         addModule(output);
3338         addModule(new PrefPrinter(this));
3339         addModule(new PrefLatex(this));
3340
3341         PrefConverters * converters = new PrefConverters(this);
3342         PrefFileformats * formats = new PrefFileformats(this);
3343         connect(formats, SIGNAL(formatsChanged()),
3344                         converters, SLOT(updateGui()));
3345         addModule(converters);
3346         addModule(formats);
3347
3348         prefsPS->setCurrentPanel("User Interface");
3349 // FIXME: hack to work around resizing bug in Qt >= 4.2
3350 // bug verified with Qt 4.2.{0-3} (JSpitzm)
3351 #if QT_VERSION >= 0x040200
3352         prefsPS->updateGeometry();
3353 #endif
3354
3355         bc().setPolicy(ButtonPolicy::PreferencesPolicy);
3356         bc().setOK(savePB);
3357         bc().setApply(applyPB);
3358         bc().setCancel(closePB);
3359         bc().setRestore(restorePB);
3360
3361         // initialize the strftime validator
3362         bc().addCheckedLineEdit(output->DateED);
3363 }
3364
3365
3366 void GuiPreferences::addModule(PrefModule * module)
3367 {
3368         LASSERT(module, return);
3369         if (module->category().isEmpty())
3370                 prefsPS->addPanel(module, module->title());
3371         else
3372                 prefsPS->addPanel(module, module->title(), module->category());
3373         connect(module, SIGNAL(changed()), this, SLOT(change_adaptor()));
3374         modules_.push_back(module);
3375 }
3376
3377
3378 void GuiPreferences::change_adaptor()
3379 {
3380         changed();
3381 }
3382
3383
3384 void GuiPreferences::applyRC(LyXRC & rc) const
3385 {
3386         size_t end = modules_.size();
3387         for (size_t i = 0; i != end; ++i)
3388                 modules_[i]->applyRC(rc);
3389 }
3390
3391
3392 void GuiPreferences::updateRC(LyXRC const & rc)
3393 {
3394         size_t const end = modules_.size();
3395         for (size_t i = 0; i != end; ++i)
3396                 modules_[i]->updateRC(rc);
3397 }
3398
3399
3400 void GuiPreferences::applyView()
3401 {
3402         applyRC(rc());
3403 }
3404
3405
3406 bool GuiPreferences::initialiseParams(string const &)
3407 {
3408         rc_ = lyxrc;
3409         formats_ = lyx::formats;
3410         converters_ = theConverters();
3411         converters_.update(formats_);
3412         movers_ = theMovers();
3413         colors_.clear();
3414         update_screen_font_ = false;
3415
3416         updateRC(rc_);
3417         // Make sure that the bc is in the INITIAL state
3418         if (bc().policy().buttonStatus(ButtonPolicy::RESTORE))
3419                 bc().restore();
3420
3421         return true;
3422 }
3423
3424
3425 void GuiPreferences::dispatchParams()
3426 {
3427         ostringstream ss;
3428         rc_.write(ss, true);
3429         dispatch(FuncRequest(LFUN_LYXRC_APPLY, ss.str()));
3430         // issue prefsApplied signal. This will update the
3431         // localized screen font sizes.
3432         prefsApplied(rc_);
3433         // FIXME: these need lfuns
3434         // FIXME UNICODE
3435         Author const & author =
3436                 Author(from_utf8(rc_.user_name), from_utf8(rc_.user_email));
3437         theBufferList().recordCurrentAuthor(author);
3438
3439         lyx::formats = formats_;
3440
3441         theConverters() = converters_;
3442         theConverters().update(lyx::formats);
3443         theConverters().buildGraph();
3444
3445         theMovers() = movers_;
3446
3447         vector<string>::const_iterator it = colors_.begin();
3448         vector<string>::const_iterator const end = colors_.end();
3449         for (; it != end; ++it)
3450                 dispatch(FuncRequest(LFUN_SET_COLOR, *it));
3451         colors_.clear();
3452
3453         if (update_screen_font_) {
3454                 dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3455                 update_screen_font_ = false;
3456         }
3457
3458         theBufferList().updatePreviews();
3459
3460         // The Save button has been pressed
3461         if (isClosing())
3462                 dispatch(FuncRequest(LFUN_PREFERENCES_SAVE));
3463 }
3464
3465
3466 void GuiPreferences::setColor(ColorCode col, QString const & hex)
3467 {
3468         colors_.push_back(lcolor.getLyXName(col) + ' ' + fromqstr(hex));
3469 }
3470
3471
3472 void GuiPreferences::updateScreenFonts()
3473 {
3474         update_screen_font_ = true;
3475 }
3476
3477
3478 QString GuiPreferences::browsebind(QString const & file) const
3479 {
3480         return browseLibFile("bind", file, "bind", qt_("Choose bind file"),
3481                              QStringList(qt_("LyX bind files (*.bind)")));
3482 }
3483
3484
3485 QString GuiPreferences::browseUI(QString const & file) const
3486 {
3487         return browseLibFile("ui", file, "ui", qt_("Choose UI file"),
3488                              QStringList(qt_("LyX UI files (*.ui)")));
3489 }
3490
3491
3492 QString GuiPreferences::browsekbmap(QString const & file) const
3493 {
3494         return browseLibFile("kbd", file, "kmap", qt_("Choose keyboard map"),
3495                              QStringList(qt_("LyX keyboard maps (*.kmap)")));
3496 }
3497
3498
3499 QString GuiPreferences::browse(QString const & file,
3500         QString const & title) const
3501 {
3502         return browseFile(file, title, QStringList(), true);
3503 }
3504
3505
3506 Dialog * createGuiPreferences(GuiView & lv) { return new GuiPreferences(lv); }
3507
3508
3509 } // namespace frontend
3510 } // namespace lyx
3511
3512 #include "moc_GuiPrefs.cpp"