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