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