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