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