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