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