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