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