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