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