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