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