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