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