]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiPrefs.cpp
remove ispell and pspell
[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         spellCommandCO->setEnabled(false);
1043
1044         connect(altLanguageED, SIGNAL(textChanged(QString)),
1045                 this, SIGNAL(changed()));
1046         connect(escapeCharactersED, SIGNAL(textChanged(QString)),
1047                 this, SIGNAL(changed()));
1048         connect(persDictionaryED, SIGNAL(textChanged(QString)),
1049                 this, SIGNAL(changed()));
1050         connect(compoundWordCB, SIGNAL(clicked()),
1051                 this, SIGNAL(changed()));
1052         connect(inputEncodingCB, SIGNAL(clicked()),
1053                 this, SIGNAL(changed()));
1054
1055         spellCommandCO->addItem(qt_("aspell"));
1056 #ifdef USE_ASPELL
1057         spellCommandCO->addItem(qt_("aspell (library)"));
1058 #endif
1059 }
1060
1061
1062 void PrefSpellchecker::apply(LyXRC & rc) const
1063 {
1064         switch (spellCommandCO->currentIndex()) {
1065                 case 0:
1066                         rc.use_spell_lib = false;
1067                         rc.spellchecker_command = fromqstr(spellCommandCO->currentText());
1068                         break;
1069                 case 1:
1070                         rc.use_spell_lib = true;
1071                         break;
1072         }
1073
1074         // FIXME: remove spellchecker_use_alt_lang
1075         rc.spellchecker_alt_lang = fromqstr(altLanguageED->text());
1076         rc.spellchecker_use_alt_lang = !rc.spellchecker_alt_lang.empty();
1077         // FIXME: remove spellchecker_use_esc_chars
1078         rc.spellchecker_esc_chars = fromqstr(escapeCharactersED->text());
1079         rc.spellchecker_use_esc_chars = !rc.spellchecker_esc_chars.empty();
1080         // FIXME: remove spellchecker_use_pers_dict
1081         rc.spellchecker_pers_dict = internal_path(fromqstr(persDictionaryED->text()));
1082         rc.spellchecker_use_pers_dict = !rc.spellchecker_pers_dict.empty();
1083         rc.spellchecker_accept_compound = compoundWordCB->isChecked();
1084         rc.spellchecker_use_input_encoding = inputEncodingCB->isChecked();
1085 }
1086
1087
1088 void PrefSpellchecker::update(LyXRC const & rc)
1089 {
1090         spellCommandCO->setCurrentIndex(0);
1091
1092         if (rc.spellchecker_command == "aspell") 
1093                 spellCommandCO->setCurrentIndex(0);
1094
1095         if (rc.use_spell_lib) {
1096 #if defined(USE_ASPELL)
1097                 spellCommandCO->setCurrentIndex(1);
1098 #endif
1099         }
1100
1101         // FIXME: remove spellchecker_use_alt_lang
1102         altLanguageED->setText(toqstr(rc.spellchecker_alt_lang));
1103         // FIXME: remove spellchecker_use_esc_chars
1104         escapeCharactersED->setText(toqstr(rc.spellchecker_esc_chars));
1105         // FIXME: remove spellchecker_use_pers_dict
1106         persDictionaryED->setText(toqstr(external_path(rc.spellchecker_pers_dict)));
1107         compoundWordCB->setChecked(rc.spellchecker_accept_compound);
1108         inputEncodingCB->setChecked(rc.spellchecker_use_input_encoding);
1109 }
1110
1111
1112 void PrefSpellchecker::select_dict()
1113 {
1114         QString file = form_->browsedict(internalPath(persDictionaryED->text()));
1115         if (!file.isEmpty())
1116                 persDictionaryED->setText(file);
1117 }
1118
1119
1120
1121 /////////////////////////////////////////////////////////////////////
1122 //
1123 // PrefConverters
1124 //
1125 /////////////////////////////////////////////////////////////////////
1126
1127
1128 PrefConverters::PrefConverters(GuiPreferences * form)
1129         : PrefModule(qt_(catFiles), qt_("Converters"), form)
1130 {
1131         setupUi(this);
1132
1133         connect(converterNewPB, SIGNAL(clicked()),
1134                 this, SLOT(update_converter()));
1135         connect(converterRemovePB, SIGNAL(clicked()),
1136                 this, SLOT(remove_converter()));
1137         connect(converterModifyPB, SIGNAL(clicked()),
1138                 this, SLOT(update_converter()));
1139         connect(convertersLW, SIGNAL(currentRowChanged(int)),
1140                 this, SLOT(switch_converter()));
1141         connect(converterFromCO, SIGNAL(activated(QString)),
1142                 this, SLOT(converter_changed()));
1143         connect(converterToCO, SIGNAL(activated(QString)),
1144                 this, SLOT(converter_changed()));
1145         connect(converterED, SIGNAL(textEdited(QString)),
1146                 this, SLOT(converter_changed()));
1147         connect(converterFlagED, SIGNAL(textEdited(QString)),
1148                 this, SLOT(converter_changed()));
1149         connect(converterNewPB, SIGNAL(clicked()),
1150                 this, SIGNAL(changed()));
1151         connect(converterRemovePB, SIGNAL(clicked()),
1152                 this, SIGNAL(changed()));
1153         connect(converterModifyPB, SIGNAL(clicked()),
1154                 this, SIGNAL(changed()));
1155         connect(maxAgeLE, SIGNAL(textEdited(QString)),
1156                 this, SIGNAL(changed()));
1157
1158         maxAgeLE->setValidator(new QDoubleValidator(maxAgeLE));
1159         //converterDefGB->setFocusProxy(convertersLW);
1160 }
1161
1162
1163 void PrefConverters::apply(LyXRC & rc) const
1164 {
1165         rc.use_converter_cache = cacheCB->isChecked();
1166         rc.converter_cache_maxage = int(maxAgeLE->text().toDouble() * 86400.0);
1167 }
1168
1169
1170 void PrefConverters::update(LyXRC const & rc)
1171 {
1172         cacheCB->setChecked(rc.use_converter_cache);
1173         QString max_age;
1174         max_age.setNum(double(rc.converter_cache_maxage) / 86400.0, 'g', 6);
1175         maxAgeLE->setText(max_age);
1176         updateGui();
1177 }
1178
1179
1180 void PrefConverters::updateGui()
1181 {
1182         form_->formats().sort();
1183         form_->converters().update(form_->formats());
1184         // save current selection
1185         QString current = converterFromCO->currentText()
1186                 + " -> " + converterToCO->currentText();
1187
1188         converterFromCO->clear();
1189         converterToCO->clear();
1190
1191         Formats::const_iterator cit = form_->formats().begin();
1192         Formats::const_iterator end = form_->formats().end();
1193         for (; cit != end; ++cit) {
1194                 converterFromCO->addItem(qt_(cit->prettyname()));
1195                 converterToCO->addItem(qt_(cit->prettyname()));
1196         }
1197
1198         // currentRowChanged(int) is also triggered when updating the listwidget
1199         // block signals to avoid unnecessary calls to switch_converter()
1200         convertersLW->blockSignals(true);
1201         convertersLW->clear();
1202
1203         Converters::const_iterator ccit = form_->converters().begin();
1204         Converters::const_iterator cend = form_->converters().end();
1205         for (; ccit != cend; ++ccit) {
1206                 QString const name =
1207                         qt_(ccit->From->prettyname()) + " -> " + qt_(ccit->To->prettyname());
1208                 int type = form_->converters().getNumber(ccit->From->name(), ccit->To->name());
1209                 new QListWidgetItem(name, convertersLW, type);
1210         }
1211         convertersLW->sortItems(Qt::AscendingOrder);
1212         convertersLW->blockSignals(false);
1213
1214         // restore selection
1215         if (!current.isEmpty()) {
1216                 QList<QListWidgetItem *> const item =
1217                         convertersLW->findItems(current, Qt::MatchExactly);
1218                 if (!item.isEmpty())
1219                         convertersLW->setCurrentItem(item.at(0));
1220         }
1221
1222         // select first element if restoring failed
1223         if (convertersLW->currentRow() == -1)
1224                 convertersLW->setCurrentRow(0);
1225
1226         updateButtons();
1227 }
1228
1229
1230 void PrefConverters::switch_converter()
1231 {
1232         int const cnr = convertersLW->currentItem()->type();
1233         Converter const & c(form_->converters().get(cnr));
1234         converterFromCO->setCurrentIndex(form_->formats().getNumber(c.from));
1235         converterToCO->setCurrentIndex(form_->formats().getNumber(c.to));
1236         converterED->setText(toqstr(c.command));
1237         converterFlagED->setText(toqstr(c.flags));
1238
1239         updateButtons();
1240 }
1241
1242
1243 void PrefConverters::converter_changed()
1244 {
1245         updateButtons();
1246 }
1247
1248
1249 void PrefConverters::updateButtons()
1250 {
1251         Format const & from = form_->formats().get(converterFromCO->currentIndex());
1252         Format const & to = form_->formats().get(converterToCO->currentIndex());
1253         int const sel = form_->converters().getNumber(from.name(), to.name());
1254         bool const known = sel >= 0;
1255         bool const valid = !(converterED->text().isEmpty()
1256                 || from.name() == to.name());
1257
1258         int const cnr = convertersLW->currentItem()->type();
1259         Converter const & c = form_->converters().get(cnr);
1260         string const old_command = c.command;
1261         string const old_flag = c.flags;
1262         string const new_command = fromqstr(converterED->text());
1263         string const new_flag = fromqstr(converterFlagED->text());
1264
1265         bool modified = (old_command != new_command || old_flag != new_flag);
1266
1267         converterModifyPB->setEnabled(valid && known && modified);
1268         converterNewPB->setEnabled(valid && !known);
1269         converterRemovePB->setEnabled(known);
1270
1271         maxAgeLE->setEnabled(cacheCB->isChecked());
1272         maxAgeLA->setEnabled(cacheCB->isChecked());
1273 }
1274
1275
1276 // FIXME: user must
1277 // specify unique from/to or it doesn't appear. This is really bad UI
1278 // this is why we can use the same function for both new and modify
1279 void PrefConverters::update_converter()
1280 {
1281         Format const & from = form_->formats().get(converterFromCO->currentIndex());
1282         Format const & to = form_->formats().get(converterToCO->currentIndex());
1283         string const flags = fromqstr(converterFlagED->text());
1284         string const command = fromqstr(converterED->text());
1285
1286         Converter const * old =
1287                 form_->converters().getConverter(from.name(), to.name());
1288         form_->converters().add(from.name(), to.name(), command, flags);
1289
1290         if (!old)
1291                 form_->converters().updateLast(form_->formats());
1292
1293         updateGui();
1294
1295         // Remove all files created by this converter from the cache, since
1296         // the modified converter might create different files.
1297         ConverterCache::get().remove_all(from.name(), to.name());
1298 }
1299
1300
1301 void PrefConverters::remove_converter()
1302 {
1303         Format const & from = form_->formats().get(converterFromCO->currentIndex());
1304         Format const & to = form_->formats().get(converterToCO->currentIndex());
1305         form_->converters().erase(from.name(), to.name());
1306
1307         updateGui();
1308
1309         // Remove all files created by this converter from the cache, since
1310         // a possible new converter might create different files.
1311         ConverterCache::get().remove_all(from.name(), to.name());
1312 }
1313
1314
1315 void PrefConverters::on_cacheCB_stateChanged(int state)
1316 {
1317         maxAgeLE->setEnabled(state == Qt::Checked);
1318         maxAgeLA->setEnabled(state == Qt::Checked);
1319         changed();
1320 }
1321
1322
1323 /////////////////////////////////////////////////////////////////////
1324 //
1325 // FormatValidator
1326 //
1327 /////////////////////////////////////////////////////////////////////
1328
1329 class FormatValidator : public QValidator
1330 {
1331 public:
1332         FormatValidator(QWidget *, Formats const & f);
1333         void fixup(QString & input) const;
1334         QValidator::State validate(QString & input, int & pos) const;
1335 private:
1336         virtual QString toString(Format const & format) const = 0;
1337         int nr() const;
1338         Formats const & formats_;
1339 };
1340
1341
1342 FormatValidator::FormatValidator(QWidget * parent, Formats const & f)
1343         : QValidator(parent), formats_(f)
1344 {
1345 }
1346
1347
1348 void FormatValidator::fixup(QString & input) const
1349 {
1350         Formats::const_iterator cit = formats_.begin();
1351         Formats::const_iterator end = formats_.end();
1352         for (; cit != end; ++cit) {
1353                 QString const name = toString(*cit);
1354                 if (distance(formats_.begin(), cit) == nr()) {
1355                         input = name;
1356                         return;
1357                 }
1358         }
1359 }
1360
1361
1362 QValidator::State FormatValidator::validate(QString & input, int & /*pos*/) const
1363 {
1364         Formats::const_iterator cit = formats_.begin();
1365         Formats::const_iterator end = formats_.end();
1366         bool unknown = true;
1367         for (; unknown && cit != end; ++cit) {
1368                 QString const name = toString(*cit);
1369                 if (distance(formats_.begin(), cit) != nr())
1370                         unknown = name != input;
1371         }
1372
1373         if (unknown && !input.isEmpty())
1374                 return QValidator::Acceptable;
1375         else
1376                 return QValidator::Intermediate;
1377 }
1378
1379
1380 int FormatValidator::nr() const
1381 {
1382         QComboBox * p = qobject_cast<QComboBox *>(parent());
1383         return p->itemData(p->currentIndex()).toInt();
1384 }
1385
1386
1387 /////////////////////////////////////////////////////////////////////
1388 //
1389 // FormatNameValidator
1390 //
1391 /////////////////////////////////////////////////////////////////////
1392
1393 class FormatNameValidator : public FormatValidator
1394 {
1395 public:
1396         FormatNameValidator(QWidget * parent, Formats const & f)
1397                 : FormatValidator(parent, f)
1398         {}
1399 private:
1400         QString toString(Format const & format) const
1401         {
1402                 return toqstr(format.name());
1403         }
1404 };
1405
1406
1407 /////////////////////////////////////////////////////////////////////
1408 //
1409 // FormatPrettynameValidator
1410 //
1411 /////////////////////////////////////////////////////////////////////
1412
1413 class FormatPrettynameValidator : public FormatValidator
1414 {
1415 public:
1416         FormatPrettynameValidator(QWidget * parent, Formats const & f)
1417                 : FormatValidator(parent, f)
1418         {}
1419 private:
1420         QString toString(Format const & format) const
1421         {
1422                 return qt_(format.prettyname());
1423         }
1424 };
1425
1426
1427 /////////////////////////////////////////////////////////////////////
1428 //
1429 // PrefFileformats
1430 //
1431 /////////////////////////////////////////////////////////////////////
1432
1433 PrefFileformats::PrefFileformats(GuiPreferences * form)
1434         : PrefModule(qt_(catFiles), qt_("File formats"), form)
1435 {
1436         setupUi(this);
1437         formatED->setValidator(new FormatNameValidator(formatsCB, form_->formats()));
1438         formatsCB->setValidator(new FormatPrettynameValidator(formatsCB, form_->formats()));
1439
1440         connect(documentCB, SIGNAL(clicked()),
1441                 this, SLOT(setFlags()));
1442         connect(vectorCB, SIGNAL(clicked()),
1443                 this, SLOT(setFlags()));
1444         connect(formatsCB->lineEdit(), SIGNAL(editingFinished()),
1445                 this, SLOT(updatePrettyname()));
1446         connect(formatsCB->lineEdit(), SIGNAL(textEdited(QString)),
1447                 this, SIGNAL(changed()));
1448 }
1449
1450
1451 namespace {
1452
1453 string const l10n_shortcut(string const prettyname, string const shortcut)
1454 {
1455         if (shortcut.empty())
1456                 return string();
1457
1458         string l10n_format =
1459                 to_utf8(_(prettyname + '|' + shortcut));
1460         return split(l10n_format, '|');
1461 }
1462
1463 }; // namespace anon
1464
1465
1466 void PrefFileformats::apply(LyXRC & /*rc*/) const
1467 {
1468 }
1469
1470
1471 void PrefFileformats::update(LyXRC const & /*rc*/)
1472 {
1473         updateView();
1474 }
1475
1476
1477 void PrefFileformats::updateView()
1478 {
1479         QString const current = formatsCB->currentText();
1480
1481         // update combobox with formats
1482         formatsCB->blockSignals(true);
1483         formatsCB->clear();
1484         form_->formats().sort();
1485         Formats::const_iterator cit = form_->formats().begin();
1486         Formats::const_iterator end = form_->formats().end();
1487         for (; cit != end; ++cit)
1488                 formatsCB->addItem(qt_(cit->prettyname()),
1489                                    QVariant(form_->formats().getNumber(cit->name())));
1490
1491         // restore selection
1492         int const item = formatsCB->findText(current, Qt::MatchExactly);
1493         formatsCB->setCurrentIndex(item < 0 ? 0 : item);
1494         on_formatsCB_currentIndexChanged(item < 0 ? 0 : item);
1495         formatsCB->blockSignals(false);
1496 }
1497
1498
1499 void PrefFileformats::on_formatsCB_currentIndexChanged(int i)
1500 {
1501         int const nr = formatsCB->itemData(i).toInt();
1502         Format const f = form_->formats().get(nr);
1503
1504         formatED->setText(toqstr(f.name()));
1505         copierED->setText(toqstr(form_->movers().command(f.name())));
1506         extensionED->setText(toqstr(f.extension()));
1507         shortcutED->setText(
1508                 toqstr(l10n_shortcut(f.prettyname(), f.shortcut())));
1509         viewerED->setText(toqstr(f.viewer()));
1510         editorED->setText(toqstr(f.editor()));
1511         documentCB->setChecked((f.documentFormat()));
1512         vectorCB->setChecked((f.vectorFormat()));
1513 }
1514
1515
1516 void PrefFileformats::setFlags()
1517 {
1518         int flags = Format::none;
1519         if (documentCB->isChecked())
1520                 flags |= Format::document;
1521         if (vectorCB->isChecked())
1522                 flags |= Format::vector;
1523         currentFormat().setFlags(flags);
1524         changed();
1525 }
1526
1527
1528 void PrefFileformats::on_copierED_textEdited(const QString & s)
1529 {
1530         string const fmt = fromqstr(formatED->text());
1531         form_->movers().set(fmt, fromqstr(s));
1532         changed();
1533 }
1534
1535
1536 void PrefFileformats::on_extensionED_textEdited(const QString & s)
1537 {
1538         currentFormat().setExtension(fromqstr(s));
1539         changed();
1540 }
1541
1542 void PrefFileformats::on_viewerED_textEdited(const QString & s)
1543 {
1544         currentFormat().setViewer(fromqstr(s));
1545         changed();
1546 }
1547
1548
1549 void PrefFileformats::on_editorED_textEdited(const QString & s)
1550 {
1551         currentFormat().setEditor(fromqstr(s));
1552         changed();
1553 }
1554
1555
1556 void PrefFileformats::on_shortcutED_textEdited(const QString & s)
1557 {
1558         string const new_shortcut = fromqstr(s);
1559         if (new_shortcut == l10n_shortcut(currentFormat().prettyname(),
1560                                           currentFormat().shortcut()))
1561                 return;
1562         currentFormat().setShortcut(new_shortcut);
1563         changed();
1564 }
1565
1566
1567 void PrefFileformats::on_formatED_editingFinished()
1568 {
1569         string const newname = fromqstr(formatED->displayText());
1570         if (newname == currentFormat().name())
1571                 return;
1572
1573         currentFormat().setName(newname);
1574         changed();
1575 }
1576
1577
1578 void PrefFileformats::on_formatED_textChanged(const QString &)
1579 {
1580         QString t = formatED->text();
1581         int p = 0;
1582         bool valid = formatED->validator()->validate(t, p) == QValidator::Acceptable;
1583         setValid(formatLA, valid);
1584 }
1585
1586
1587 void PrefFileformats::on_formatsCB_editTextChanged(const QString &)
1588 {
1589         QString t = formatsCB->currentText();
1590         int p = 0;
1591         bool valid = formatsCB->validator()->validate(t, p) == QValidator::Acceptable;
1592         setValid(formatsLA, valid);
1593 }
1594
1595
1596 void PrefFileformats::updatePrettyname()
1597 {
1598         QString const newname = formatsCB->currentText();
1599         if (newname == qt_(currentFormat().prettyname()))
1600                 return;
1601
1602         currentFormat().setPrettyname(fromqstr(newname));
1603         formatsChanged();
1604         updateView();
1605         changed();
1606 }
1607
1608
1609 Format & PrefFileformats::currentFormat()
1610 {
1611         int const i = formatsCB->currentIndex();
1612         int const nr = formatsCB->itemData(i).toInt();
1613         return form_->formats().get(nr);
1614 }
1615
1616
1617 void PrefFileformats::on_formatNewPB_clicked()
1618 {
1619         form_->formats().add("", "", "", "", "", "", Format::none);
1620         updateView();
1621         formatsCB->setCurrentIndex(0);
1622         formatsCB->setFocus(Qt::OtherFocusReason);
1623 }
1624
1625
1626 void PrefFileformats::on_formatRemovePB_clicked()
1627 {
1628         int const i = formatsCB->currentIndex();
1629         int const nr = formatsCB->itemData(i).toInt();
1630         string const current_text = form_->formats().get(nr).name();
1631         if (form_->converters().formatIsUsed(current_text)) {
1632                 Alert::error(_("Format in use"),
1633                              _("Cannot remove a Format used by a Converter. "
1634                                             "Remove the converter first."));
1635                 return;
1636         }
1637
1638         form_->formats().erase(current_text);
1639         formatsChanged();
1640         updateView();
1641         on_formatsCB_editTextChanged(formatsCB->currentText());
1642         changed();
1643 }
1644
1645
1646 /////////////////////////////////////////////////////////////////////
1647 //
1648 // PrefLanguage
1649 //
1650 /////////////////////////////////////////////////////////////////////
1651
1652 PrefLanguage::PrefLanguage(GuiPreferences * form)
1653         : PrefModule(qt_(catLanguage), qt_("Language"), form)
1654 {
1655         setupUi(this);
1656
1657         connect(rtlGB, SIGNAL(clicked()),
1658                 this, SIGNAL(changed()));
1659         connect(visualCursorRB, SIGNAL(clicked()),
1660                 this, SIGNAL(changed()));
1661         connect(logicalCursorRB, SIGNAL(clicked()),
1662                 this, SIGNAL(changed()));
1663         connect(markForeignCB, SIGNAL(clicked()),
1664                 this, SIGNAL(changed()));
1665         connect(autoBeginCB, SIGNAL(clicked()),
1666                 this, SIGNAL(changed()));
1667         connect(autoEndCB, SIGNAL(clicked()),
1668                 this, SIGNAL(changed()));
1669         connect(useBabelCB, SIGNAL(clicked()),
1670                 this, SIGNAL(changed()));
1671         connect(globalCB, SIGNAL(clicked()),
1672                 this, SIGNAL(changed()));
1673         connect(languagePackageED, SIGNAL(textChanged(QString)),
1674                 this, SIGNAL(changed()));
1675         connect(startCommandED, SIGNAL(textChanged(QString)),
1676                 this, SIGNAL(changed()));
1677         connect(endCommandED, SIGNAL(textChanged(QString)),
1678                 this, SIGNAL(changed()));
1679         connect(defaultLanguageCO, SIGNAL(activated(int)),
1680                 this, SIGNAL(changed()));
1681         connect(uiLanguageCO, SIGNAL(activated(int)),
1682                 this, SIGNAL(changed()));
1683
1684         defaultLanguageCO->clear();
1685         uiLanguageCO->clear();
1686
1687         QAbstractItemModel * language_model = guiApp->languageModel();
1688         // FIXME: it would be nice if sorting was enabled/disabled via a checkbox.
1689         language_model->sort(0);
1690         defaultLanguageCO->setModel(language_model);
1691
1692         // FIXME: This is wrong, we need filter this list based on the available
1693         // translation.
1694         uiLanguageCO->blockSignals(true);
1695         uiLanguageCO->addItem(qt_("Default"), toqstr("auto"));
1696         for (int i = 0; i != language_model->rowCount(); ++i) {
1697                 QModelIndex index = language_model->index(i, 0);
1698                 uiLanguageCO->addItem(index.data(Qt::DisplayRole).toString(),
1699                         index.data(Qt::UserRole).toString());
1700         }
1701         uiLanguageCO->blockSignals(false);
1702 }
1703
1704
1705 void PrefLanguage::on_uiLanguageCO_currentIndexChanged(int)
1706 {
1707          QMessageBox::information(this, qt_("LyX needs to be restarted!"),
1708                  qt_("The change of user interface language will be fully "
1709                  "effective only after a restart."));
1710 }
1711
1712
1713 void PrefLanguage::apply(LyXRC & rc) const
1714 {
1715         // FIXME: remove rtl_support bool
1716         rc.rtl_support = rtlGB->isChecked();
1717         rc.visual_cursor = rtlGB->isChecked() && visualCursorRB->isChecked();
1718         rc.mark_foreign_language = markForeignCB->isChecked();
1719         rc.language_auto_begin = autoBeginCB->isChecked();
1720         rc.language_auto_end = autoEndCB->isChecked();
1721         rc.language_use_babel = useBabelCB->isChecked();
1722         rc.language_global_options = globalCB->isChecked();
1723         rc.language_package = fromqstr(languagePackageED->text());
1724         rc.language_command_begin = fromqstr(startCommandED->text());
1725         rc.language_command_end = fromqstr(endCommandED->text());
1726         rc.default_language = fromqstr(
1727                 defaultLanguageCO->itemData(defaultLanguageCO->currentIndex()).toString());
1728         rc.gui_language = fromqstr(
1729                 uiLanguageCO->itemData(uiLanguageCO->currentIndex()).toString());
1730 }
1731
1732
1733 void PrefLanguage::update(LyXRC const & rc)
1734 {
1735         // FIXME: remove rtl_support bool
1736         rtlGB->setChecked(rc.rtl_support);
1737         if (rc.visual_cursor)
1738                 visualCursorRB->setChecked(true);
1739         else
1740                 logicalCursorRB->setChecked(true);
1741         markForeignCB->setChecked(rc.mark_foreign_language);
1742         autoBeginCB->setChecked(rc.language_auto_begin);
1743         autoEndCB->setChecked(rc.language_auto_end);
1744         useBabelCB->setChecked(rc.language_use_babel);
1745         globalCB->setChecked(rc.language_global_options);
1746         languagePackageED->setText(toqstr(rc.language_package));
1747         startCommandED->setText(toqstr(rc.language_command_begin));
1748         endCommandED->setText(toqstr(rc.language_command_end));
1749
1750         int pos = defaultLanguageCO->findData(toqstr(rc.default_language));
1751         defaultLanguageCO->setCurrentIndex(pos);
1752         pos = uiLanguageCO->findData(toqstr(rc.gui_language));
1753         uiLanguageCO->blockSignals(true);
1754         uiLanguageCO->setCurrentIndex(pos);
1755         uiLanguageCO->blockSignals(false);
1756 }
1757
1758
1759 /////////////////////////////////////////////////////////////////////
1760 //
1761 // PrefPrinter
1762 //
1763 /////////////////////////////////////////////////////////////////////
1764
1765 PrefPrinter::PrefPrinter(GuiPreferences * form)
1766         : PrefModule(qt_(catOutput), qt_("Printer"), form)
1767 {
1768         setupUi(this);
1769
1770         connect(printerAdaptCB, SIGNAL(clicked()),
1771                 this, SIGNAL(changed()));
1772         connect(printerCommandED, SIGNAL(textChanged(QString)),
1773                 this, SIGNAL(changed()));
1774         connect(printerNameED, SIGNAL(textChanged(QString)),
1775                 this, SIGNAL(changed()));
1776         connect(printerPageRangeED, SIGNAL(textChanged(QString)),
1777                 this, SIGNAL(changed()));
1778         connect(printerCopiesED, SIGNAL(textChanged(QString)),
1779                 this, SIGNAL(changed()));
1780         connect(printerReverseED, SIGNAL(textChanged(QString)),
1781                 this, SIGNAL(changed()));
1782         connect(printerToPrinterED, SIGNAL(textChanged(QString)),
1783                 this, SIGNAL(changed()));
1784         connect(printerExtensionED, SIGNAL(textChanged(QString)),
1785                 this, SIGNAL(changed()));
1786         connect(printerSpoolCommandED, SIGNAL(textChanged(QString)),
1787                 this, SIGNAL(changed()));
1788         connect(printerPaperTypeED, SIGNAL(textChanged(QString)),
1789                 this, SIGNAL(changed()));
1790         connect(printerEvenED, SIGNAL(textChanged(QString)),
1791                 this, SIGNAL(changed()));
1792         connect(printerOddED, SIGNAL(textChanged(QString)),
1793                 this, SIGNAL(changed()));
1794         connect(printerCollatedED, SIGNAL(textChanged(QString)),
1795                 this, SIGNAL(changed()));
1796         connect(printerLandscapeED, SIGNAL(textChanged(QString)),
1797                 this, SIGNAL(changed()));
1798         connect(printerToFileED, SIGNAL(textChanged(QString)),
1799                 this, SIGNAL(changed()));
1800         connect(printerExtraED, SIGNAL(textChanged(QString)),
1801                 this, SIGNAL(changed()));
1802         connect(printerSpoolPrefixED, SIGNAL(textChanged(QString)),
1803                 this, SIGNAL(changed()));
1804         connect(printerPaperSizeED, SIGNAL(textChanged(QString)),
1805                 this, SIGNAL(changed()));
1806 }
1807
1808
1809 void PrefPrinter::apply(LyXRC & rc) const
1810 {
1811         rc.print_adapt_output = printerAdaptCB->isChecked();
1812         rc.print_command = fromqstr(printerCommandED->text());
1813         rc.printer = fromqstr(printerNameED->text());
1814
1815         rc.print_pagerange_flag = fromqstr(printerPageRangeED->text());
1816         rc.print_copies_flag = fromqstr(printerCopiesED->text());
1817         rc.print_reverse_flag = fromqstr(printerReverseED->text());
1818         rc.print_to_printer = fromqstr(printerToPrinterED->text());
1819         rc.print_file_extension = fromqstr(printerExtensionED->text());
1820         rc.print_spool_command = fromqstr(printerSpoolCommandED->text());
1821         rc.print_paper_flag = fromqstr(printerPaperTypeED->text());
1822         rc.print_evenpage_flag = fromqstr(printerEvenED->text());
1823         rc.print_oddpage_flag = fromqstr(printerOddED->text());
1824         rc.print_collcopies_flag = fromqstr(printerCollatedED->text());
1825         rc.print_landscape_flag = fromqstr(printerLandscapeED->text());
1826         rc.print_to_file = internal_path(fromqstr(printerToFileED->text()));
1827         rc.print_extra_options = fromqstr(printerExtraED->text());
1828         rc.print_spool_printerprefix = fromqstr(printerSpoolPrefixED->text());
1829         rc.print_paper_dimension_flag = fromqstr(printerPaperSizeED->text());
1830 }
1831
1832
1833 void PrefPrinter::update(LyXRC const & rc)
1834 {
1835         printerAdaptCB->setChecked(rc.print_adapt_output);
1836         printerCommandED->setText(toqstr(rc.print_command));
1837         printerNameED->setText(toqstr(rc.printer));
1838
1839         printerPageRangeED->setText(toqstr(rc.print_pagerange_flag));
1840         printerCopiesED->setText(toqstr(rc.print_copies_flag));
1841         printerReverseED->setText(toqstr(rc.print_reverse_flag));
1842         printerToPrinterED->setText(toqstr(rc.print_to_printer));
1843         printerExtensionED->setText(toqstr(rc.print_file_extension));
1844         printerSpoolCommandED->setText(toqstr(rc.print_spool_command));
1845         printerPaperTypeED->setText(toqstr(rc.print_paper_flag));
1846         printerEvenED->setText(toqstr(rc.print_evenpage_flag));
1847         printerOddED->setText(toqstr(rc.print_oddpage_flag));
1848         printerCollatedED->setText(toqstr(rc.print_collcopies_flag));
1849         printerLandscapeED->setText(toqstr(rc.print_landscape_flag));
1850         printerToFileED->setText(toqstr(external_path(rc.print_to_file)));
1851         printerExtraED->setText(toqstr(rc.print_extra_options));
1852         printerSpoolPrefixED->setText(toqstr(rc.print_spool_printerprefix));
1853         printerPaperSizeED->setText(toqstr(rc.print_paper_dimension_flag));
1854 }
1855
1856
1857 /////////////////////////////////////////////////////////////////////
1858 //
1859 // PrefUserInterface
1860 //
1861 /////////////////////////////////////////////////////////////////////
1862
1863 PrefUserInterface::PrefUserInterface(GuiPreferences * form)
1864         : PrefModule(qt_(catLookAndFeel), qt_("User interface"), form)
1865 {
1866         setupUi(this);
1867
1868         connect(autoSaveCB, SIGNAL(toggled(bool)),
1869                 autoSaveSB, SLOT(setEnabled(bool)));
1870         connect(autoSaveCB, SIGNAL(toggled(bool)),
1871                 TextLabel1, SLOT(setEnabled(bool)));
1872         connect(openDocumentsInTabsCB, SIGNAL(clicked()),
1873                 this, SIGNAL(changed()));
1874         connect(uiFilePB, SIGNAL(clicked()),
1875                 this, SLOT(select_ui()));
1876         connect(uiFileED, SIGNAL(textChanged(QString)),
1877                 this, SIGNAL(changed()));
1878         connect(restoreCursorCB, SIGNAL(clicked()),
1879                 this, SIGNAL(changed()));
1880         connect(loadSessionCB, SIGNAL(clicked()),
1881                 this, SIGNAL(changed()));
1882         connect(allowGeometrySessionCB, SIGNAL(clicked()),
1883                 this, SIGNAL(changed()));
1884         connect(autoSaveSB, SIGNAL(valueChanged(int)),
1885                 this, SIGNAL(changed()));
1886         connect(autoSaveCB, SIGNAL(clicked()),
1887                 this, SIGNAL(changed()));
1888         connect(lastfilesSB, SIGNAL(valueChanged(int)),
1889                 this, SIGNAL(changed()));
1890         connect(tooltipCB, SIGNAL(toggled(bool)),
1891                 this, SIGNAL(changed()));
1892         lastfilesSB->setMaximum(maxlastfiles);
1893 }
1894
1895
1896 void PrefUserInterface::apply(LyXRC & rc) const
1897 {
1898         rc.ui_file = internal_path(fromqstr(uiFileED->text()));
1899         rc.use_lastfilepos = restoreCursorCB->isChecked();
1900         rc.load_session = loadSessionCB->isChecked();
1901         rc.allow_geometry_session = allowGeometrySessionCB->isChecked();
1902         rc.autosave = autoSaveSB->value() * 60;
1903         rc.make_backup = autoSaveCB->isChecked();
1904         rc.num_lastfiles = lastfilesSB->value();
1905         rc.use_tooltip = tooltipCB->isChecked();
1906         rc.open_buffers_in_tabs = openDocumentsInTabsCB->isChecked();
1907 }
1908
1909
1910 void PrefUserInterface::update(LyXRC const & rc)
1911 {
1912         uiFileED->setText(toqstr(external_path(rc.ui_file)));
1913         restoreCursorCB->setChecked(rc.use_lastfilepos);
1914         loadSessionCB->setChecked(rc.load_session);
1915         allowGeometrySessionCB->setChecked(rc.allow_geometry_session);
1916         // convert to minutes
1917         int mins(rc.autosave / 60);
1918         if (rc.autosave && !mins)
1919                 mins = 1;
1920         autoSaveSB->setValue(mins);
1921         autoSaveCB->setChecked(rc.make_backup);
1922         lastfilesSB->setValue(rc.num_lastfiles);
1923         tooltipCB->setChecked(rc.use_tooltip);
1924         openDocumentsInTabsCB->setChecked(rc.open_buffers_in_tabs);
1925 }
1926
1927
1928 void PrefUserInterface::select_ui()
1929 {
1930         QString file = form_->browseUI(internalPath(uiFileED->text()));
1931         if (!file.isEmpty())
1932                 uiFileED->setText(file);
1933 }
1934
1935
1936 void PrefUserInterface::on_clearSessionPB_clicked()
1937 {
1938         guiApp->clearSession();
1939 }
1940
1941
1942
1943 /////////////////////////////////////////////////////////////////////
1944 //
1945 // PrefEdit
1946 //
1947 /////////////////////////////////////////////////////////////////////
1948
1949 PrefEdit::PrefEdit(GuiPreferences * form)
1950         : PrefModule(qt_(catEditing), qt_("Control"), form)
1951 {
1952         setupUi(this);
1953
1954         connect(cursorFollowsCB, SIGNAL(clicked()),
1955                 this, SIGNAL(changed()));
1956         connect(sortEnvironmentsCB, SIGNAL(clicked()),
1957                 this, SIGNAL(changed()));
1958         connect(groupEnvironmentsCB, SIGNAL(clicked()),
1959                 this, SIGNAL(changed()));
1960         connect(macroEditStyleCO, SIGNAL(activated(int)),
1961                 this, SIGNAL(changed()));
1962         connect(fullscreenLimitGB, SIGNAL(clicked()),
1963                 this, SIGNAL(changed()));
1964         connect(fullscreenWidthSB, SIGNAL(valueChanged(int)),
1965                 this, SIGNAL(changed()));
1966         connect(toggleTabbarCB, SIGNAL(toggled(bool)),
1967                 this, SIGNAL(changed()));
1968         connect(toggleScrollbarCB, SIGNAL(toggled(bool)),
1969                 this, SIGNAL(changed()));
1970         connect(toggleToolbarsCB, SIGNAL(toggled(bool)),
1971                 this, SIGNAL(changed()));
1972 }
1973
1974
1975 void PrefEdit::apply(LyXRC & rc) const
1976 {
1977         rc.cursor_follows_scrollbar = cursorFollowsCB->isChecked();
1978         rc.sort_layouts = sortEnvironmentsCB->isChecked();
1979         rc.group_layouts = groupEnvironmentsCB->isChecked();
1980         switch (macroEditStyleCO->currentIndex()) {
1981                 case 0: rc.macro_edit_style = LyXRC::MACRO_EDIT_INLINE_BOX; break;
1982                 case 1: rc.macro_edit_style = LyXRC::MACRO_EDIT_INLINE; break;
1983                 case 2: rc.macro_edit_style = LyXRC::MACRO_EDIT_LIST;   break;
1984         }
1985         rc.full_screen_toolbars = toggleToolbarsCB->isChecked();
1986         rc.full_screen_scrollbar = toggleScrollbarCB->isChecked();
1987         rc.full_screen_tabbar = toggleTabbarCB->isChecked();
1988         rc.full_screen_width = fullscreenWidthSB->value();
1989         rc.full_screen_limit = fullscreenLimitGB->isChecked();
1990 }
1991
1992
1993 void PrefEdit::update(LyXRC const & rc)
1994 {
1995         cursorFollowsCB->setChecked(rc.cursor_follows_scrollbar);
1996         sortEnvironmentsCB->setChecked(rc.sort_layouts);
1997         groupEnvironmentsCB->setChecked(rc.group_layouts);
1998         macroEditStyleCO->setCurrentIndex(rc.macro_edit_style);
1999         toggleScrollbarCB->setChecked(rc.full_screen_scrollbar);
2000         toggleToolbarsCB->setChecked(rc.full_screen_toolbars);
2001         toggleTabbarCB->setChecked(rc.full_screen_tabbar);
2002         fullscreenWidthSB->setValue(rc.full_screen_width);
2003         fullscreenLimitGB->setChecked(rc.full_screen_limit);
2004 }
2005
2006
2007 /////////////////////////////////////////////////////////////////////
2008 //
2009 // PrefShortcuts
2010 //
2011 /////////////////////////////////////////////////////////////////////
2012
2013
2014 GuiShortcutDialog::GuiShortcutDialog(QWidget * parent) : QDialog(parent)
2015 {
2016         Ui::shortcutUi::setupUi(this);
2017         QDialog::setModal(true);
2018 }
2019
2020
2021 PrefShortcuts::PrefShortcuts(GuiPreferences * form)
2022         : PrefModule(qt_(catEditing), qt_("Shortcuts"), form)
2023 {
2024         setupUi(this);
2025
2026         shortcutsTW->setColumnCount(2);
2027         shortcutsTW->headerItem()->setText(0, qt_("Function"));
2028         shortcutsTW->headerItem()->setText(1, qt_("Shortcut"));
2029         shortcutsTW->setSortingEnabled(true);
2030         // Multi-selection can be annoying.
2031         // shortcutsTW->setSelectionMode(QAbstractItemView::MultiSelection);
2032
2033         connect(bindFilePB, SIGNAL(clicked()),
2034                 this, SLOT(select_bind()));
2035         connect(bindFileED, SIGNAL(textChanged(QString)),
2036                 this, SIGNAL(changed()));
2037         connect(removePB, SIGNAL(clicked()),
2038                 this, SIGNAL(changed()));
2039
2040         shortcut_ = new GuiShortcutDialog(this);
2041         shortcut_bc_.setPolicy(ButtonPolicy::OkCancelPolicy);
2042         shortcut_bc_.setOK(shortcut_->okPB);
2043         shortcut_bc_.setCancel(shortcut_->cancelPB);
2044
2045         connect(shortcut_->okPB, SIGNAL(clicked()),
2046                 shortcut_, SLOT(accept()));
2047         connect(shortcut_->okPB, SIGNAL(clicked()),
2048                 this, SIGNAL(changed()));
2049         connect(shortcut_->cancelPB, SIGNAL(clicked()),
2050                 shortcut_, SLOT(reject()));
2051         connect(shortcut_->clearPB, SIGNAL(clicked()),
2052                 this, SLOT(shortcut_clearPB_pressed()));
2053         connect(shortcut_->removePB, SIGNAL(clicked()),
2054                 this, SLOT(shortcut_removePB_pressed()));
2055         connect(shortcut_->okPB, SIGNAL(clicked()),
2056                 this, SLOT(shortcut_okPB_pressed()));
2057         connect(shortcut_->cancelPB, SIGNAL(clicked()),
2058                 this, SLOT(shortcut_cancelPB_pressed()));
2059 }
2060
2061
2062 void PrefShortcuts::apply(LyXRC & rc) const
2063 {
2064         rc.bind_file = internal_path(fromqstr(bindFileED->text()));
2065         // write user_bind and user_unbind to .lyx/bind/user.bind
2066         FileName bind_dir(addPath(package().user_support().absFilename(), "bind"));
2067         if (!bind_dir.exists() && !bind_dir.createDirectory(0777)) {
2068                 lyxerr << "LyX could not create the user bind directory '"
2069                        << bind_dir << "'. All user-defined key bindings will be lost." << endl;
2070                 return;
2071         }
2072         if (!bind_dir.isDirWritable()) {
2073                 lyxerr << "LyX could not write to the user bind directory '"
2074                        << bind_dir << "'. All user-defined key bindings will be lost." << endl;
2075                 return;
2076         }
2077         FileName user_bind_file(bind_dir.absFilename() + "/user.bind");
2078         user_bind_.write(user_bind_file.toFilesystemEncoding(), false, false);
2079         user_unbind_.write(user_bind_file.toFilesystemEncoding(), true, true);
2080         // immediately apply the keybindings. Why this is not done before?
2081         // The good thing is that the menus are updated automatically.
2082         theTopLevelKeymap().clear();
2083         theTopLevelKeymap().read("site");
2084         theTopLevelKeymap().read(rc.bind_file);
2085         theTopLevelKeymap().read("user");
2086 }
2087
2088
2089 void PrefShortcuts::update(LyXRC const & rc)
2090 {
2091         bindFileED->setText(toqstr(external_path(rc.bind_file)));
2092         //
2093         system_bind_.clear();
2094         user_bind_.clear();
2095         user_unbind_.clear();
2096         system_bind_.read("site");
2097         system_bind_.read(rc.bind_file);
2098         // \unbind in user.bind is added to user_unbind_
2099         user_bind_.read("user", &user_unbind_);
2100         updateShortcutsTW();
2101 }
2102
2103
2104 void PrefShortcuts::updateShortcutsTW()
2105 {
2106         shortcutsTW->clear();
2107
2108         editItem_ = new QTreeWidgetItem(shortcutsTW);
2109         editItem_->setText(0, qt_("Cursor, Mouse and Editing functions"));
2110         editItem_->setFlags(editItem_->flags() & ~Qt::ItemIsSelectable);
2111
2112         mathItem_ = new QTreeWidgetItem(shortcutsTW);
2113         mathItem_->setText(0, qt_("Mathematical Symbols"));
2114         mathItem_->setFlags(mathItem_->flags() & ~Qt::ItemIsSelectable);
2115
2116         bufferItem_ = new QTreeWidgetItem(shortcutsTW);
2117         bufferItem_->setText(0, qt_("Document and Window"));
2118         bufferItem_->setFlags(bufferItem_->flags() & ~Qt::ItemIsSelectable);
2119
2120         layoutItem_ = new QTreeWidgetItem(shortcutsTW);
2121         layoutItem_->setText(0, qt_("Font, Layouts and Textclasses"));
2122         layoutItem_->setFlags(layoutItem_->flags() & ~Qt::ItemIsSelectable);
2123
2124         systemItem_ = new QTreeWidgetItem(shortcutsTW);
2125         systemItem_->setText(0, qt_("System and Miscellaneous"));
2126         systemItem_->setFlags(systemItem_->flags() & ~Qt::ItemIsSelectable);
2127
2128         // listBindings(unbound=true) lists all bound and unbound lfuns
2129         // Items in this list is tagged by its source.
2130         KeyMap::BindingList bindinglist = system_bind_.listBindings(true,
2131                 KeyMap::System);
2132         KeyMap::BindingList user_bindinglist = user_bind_.listBindings(false,
2133                 KeyMap::UserBind);
2134         KeyMap::BindingList user_unbindinglist = user_unbind_.listBindings(false,
2135                 KeyMap::UserUnbind);
2136         bindinglist.insert(bindinglist.end(), user_bindinglist.begin(),
2137                         user_bindinglist.end());
2138         bindinglist.insert(bindinglist.end(), user_unbindinglist.begin(),
2139                         user_unbindinglist.end());
2140
2141         KeyMap::BindingList::const_iterator it = bindinglist.begin();
2142         KeyMap::BindingList::const_iterator it_end = bindinglist.end();
2143         for (; it != it_end; ++it)
2144                 insertShortcutItem(it->request, it->sequence, KeyMap::ItemType(it->tag));
2145
2146         shortcutsTW->sortItems(0, Qt::AscendingOrder);
2147         QList<QTreeWidgetItem*> items = shortcutsTW->selectedItems();
2148         removePB->setEnabled(!items.isEmpty() && !items[0]->text(1).isEmpty());
2149         modifyPB->setEnabled(!items.isEmpty());
2150
2151         shortcutsTW->resizeColumnToContents(0);
2152 }
2153
2154
2155 void PrefShortcuts::setItemType(QTreeWidgetItem * item, KeyMap::ItemType tag)
2156 {
2157         item->setData(0, Qt::UserRole, QVariant(tag));
2158         QFont font;
2159
2160         switch (tag) {
2161         case KeyMap::System:
2162                 break;
2163         case KeyMap::UserBind:
2164                 font.setBold(true);
2165                 break;
2166         case KeyMap::UserUnbind:
2167                 font.setStrikeOut(true);
2168                 break;
2169         // this item is not displayed now.
2170         case KeyMap::UserExtraUnbind:
2171                 font.setStrikeOut(true);
2172                 break;
2173         }
2174
2175         item->setFont(1, font);
2176 }
2177
2178
2179 QTreeWidgetItem * PrefShortcuts::insertShortcutItem(FuncRequest const & lfun,
2180                 KeySequence const & seq, KeyMap::ItemType tag)
2181 {
2182         FuncCode action = lfun.action;
2183         string const action_name = lyxaction.getActionName(action);
2184         QString const lfun_name = toqstr(from_utf8(action_name)
2185                         + ' ' + lfun.argument());
2186         QString const shortcut = toqstr(seq.print(KeySequence::ForGui));
2187         KeyMap::ItemType item_tag = tag;
2188
2189         QTreeWidgetItem * newItem = 0;
2190         // for unbind items, try to find an existing item in the system bind list
2191         if (tag == KeyMap::UserUnbind) {
2192                 QList<QTreeWidgetItem*> const items = shortcutsTW->findItems(lfun_name,
2193                         Qt::MatchFlags(Qt::MatchExactly | Qt::MatchRecursive), 0);
2194                 for (int i = 0; i < items.size(); ++i) {
2195                         if (items[i]->text(1) == shortcut)
2196                                 newItem = items[i];
2197                                 break;
2198                         }
2199                 // if not found, this unbind item is KeyMap::UserExtraUnbind
2200                 // Such an item is not displayed to avoid confusion (what is
2201                 // unmatched removed?).
2202                 if (!newItem) {
2203                         item_tag = KeyMap::UserExtraUnbind;
2204                         return 0;
2205                 }
2206         }
2207         if (!newItem) {
2208                 switch(lyxaction.getActionType(action)) {
2209                 case LyXAction::Hidden:
2210                         return 0;
2211                 case LyXAction::Edit:
2212                         newItem = new QTreeWidgetItem(editItem_);
2213                         break;
2214                 case LyXAction::Math:
2215                         newItem = new QTreeWidgetItem(mathItem_);
2216                         break;
2217                 case LyXAction::Buffer:
2218                         newItem = new QTreeWidgetItem(bufferItem_);
2219                         break;
2220                 case LyXAction::Layout:
2221                         newItem = new QTreeWidgetItem(layoutItem_);
2222                         break;
2223                 case LyXAction::System:
2224                         newItem = new QTreeWidgetItem(systemItem_);
2225                         break;
2226                 default:
2227                         // this should not happen
2228                         newItem = new QTreeWidgetItem(shortcutsTW);
2229                 }
2230         }
2231
2232         newItem->setText(0, lfun_name);
2233         newItem->setText(1, shortcut);
2234         // record BindFile representation to recover KeySequence when needed.
2235         newItem->setData(1, Qt::UserRole, toqstr(seq.print(KeySequence::BindFile)));
2236         setItemType(newItem, item_tag);
2237         return newItem;
2238 }
2239
2240
2241 void PrefShortcuts::on_shortcutsTW_itemSelectionChanged()
2242 {
2243         QList<QTreeWidgetItem*> items = shortcutsTW->selectedItems();
2244         removePB->setEnabled(!items.isEmpty() && !items[0]->text(1).isEmpty());
2245         modifyPB->setEnabled(!items.isEmpty());
2246         if (items.isEmpty())
2247                 return;
2248
2249         KeyMap::ItemType tag = 
2250                 static_cast<KeyMap::ItemType>(items[0]->data(0, Qt::UserRole).toInt());
2251         if (tag == KeyMap::UserUnbind)
2252                 removePB->setText(qt_("Res&tore"));
2253         else
2254                 removePB->setText(qt_("Remo&ve"));
2255 }
2256
2257
2258 void PrefShortcuts::on_shortcutsTW_itemDoubleClicked()
2259 {
2260         modifyShortcut();
2261 }
2262
2263
2264 void PrefShortcuts::modifyShortcut()
2265 {
2266         QTreeWidgetItem * item = shortcutsTW->currentItem();
2267         if (item->flags() & Qt::ItemIsSelectable) {
2268                 shortcut_->lfunLE->setText(item->text(0));
2269                 save_lfun_ = item->text(0);
2270                 shortcut_->shortcutWG->setText(item->text(1));
2271                 KeySequence seq;
2272                 seq.parse(fromqstr(item->data(1, Qt::UserRole).toString()));
2273                 shortcut_->shortcutWG->setKeySequence(seq);
2274                 shortcut_->shortcutWG->setFocus();
2275                 shortcut_->exec();
2276         }
2277 }
2278
2279
2280 void PrefShortcuts::removeShortcut()
2281 {
2282         // it seems that only one item can be selected, but I am
2283         // removing all selected items anyway.
2284         QList<QTreeWidgetItem*> items = shortcutsTW->selectedItems();
2285         for (int i = 0; i < items.size(); ++i) {
2286                 string shortcut = fromqstr(items[i]->data(1, Qt::UserRole).toString());
2287                 string lfun = fromqstr(items[i]->text(0));
2288                 FuncRequest func = lyxaction.lookupFunc(lfun);
2289                 KeyMap::ItemType tag = 
2290                         static_cast<KeyMap::ItemType>(items[i]->data(0, Qt::UserRole).toInt());
2291
2292                 switch (tag) {
2293                 case KeyMap::System: {
2294                         // for system bind, we do not touch the item
2295                         // but add an user unbind item
2296                         user_unbind_.bind(shortcut, func);
2297                         setItemType(items[i], KeyMap::UserUnbind);
2298                         removePB->setText(qt_("Res&tore"));
2299                         break;
2300                 }
2301                 case KeyMap::UserBind: {
2302                         // for user_bind, we remove this bind
2303                         QTreeWidgetItem * parent = items[i]->parent();
2304                         int itemIdx = parent->indexOfChild(items[i]);
2305                         parent->takeChild(itemIdx);
2306                         if (itemIdx > 0)
2307                                 shortcutsTW->scrollToItem(parent->child(itemIdx - 1));
2308                         else
2309                                 shortcutsTW->scrollToItem(parent);
2310                         user_bind_.unbind(shortcut, func);
2311                         break;
2312                 }
2313                 case KeyMap::UserUnbind: {
2314                         // for user_unbind, we remove the unbind, and the item
2315                         // become KeyMap::System again.
2316                         user_unbind_.unbind(shortcut, func);
2317                         setItemType(items[i], KeyMap::System);
2318                         removePB->setText(qt_("Remo&ve"));
2319                         break;
2320                 }
2321                 case KeyMap::UserExtraUnbind: {
2322                         // for user unbind that is not in system bind file,
2323                         // remove this unbind file
2324                         QTreeWidgetItem * parent = items[i]->parent();
2325                         parent->takeChild(parent->indexOfChild(items[i]));
2326                         user_unbind_.unbind(shortcut, func);
2327                 }
2328                 }
2329         }
2330 }
2331
2332
2333 void PrefShortcuts::select_bind()
2334 {
2335         QString file = form_->browsebind(internalPath(bindFileED->text()));
2336         if (!file.isEmpty()) {
2337                 bindFileED->setText(file);
2338                 system_bind_ = KeyMap();
2339                 system_bind_.read(fromqstr(file));
2340                 updateShortcutsTW();
2341         }
2342 }
2343
2344
2345 void PrefShortcuts::on_modifyPB_pressed()
2346 {
2347         modifyShortcut();
2348 }
2349
2350
2351 void PrefShortcuts::on_newPB_pressed()
2352 {
2353         shortcut_->lfunLE->clear();
2354         shortcut_->shortcutWG->reset();
2355         save_lfun_ = QString();
2356         shortcut_->exec();
2357 }
2358
2359
2360 void PrefShortcuts::on_removePB_pressed()
2361 {
2362         removeShortcut();
2363 }
2364
2365
2366 void PrefShortcuts::on_searchLE_textEdited()
2367 {
2368         if (searchLE->text().isEmpty()) {
2369                 // show all hidden items
2370                 QTreeWidgetItemIterator it(shortcutsTW, QTreeWidgetItemIterator::Hidden);
2371                 while (*it)
2372                         shortcutsTW->setItemHidden(*it++, false);
2373                 return;
2374         }
2375         // search both columns
2376         QList<QTreeWidgetItem *> matched = shortcutsTW->findItems(searchLE->text(),
2377                 Qt::MatchFlags(Qt::MatchContains | Qt::MatchRecursive), 0);
2378         matched += shortcutsTW->findItems(searchLE->text(),
2379                 Qt::MatchFlags(Qt::MatchContains | Qt::MatchRecursive), 1);
2380
2381         // hide everyone (to avoid searching in matched QList repeatedly
2382         QTreeWidgetItemIterator it(shortcutsTW, QTreeWidgetItemIterator::Selectable);
2383         while (*it)
2384                 shortcutsTW->setItemHidden(*it++, true);
2385         // show matched items
2386         for (int i = 0; i < matched.size(); ++i) {
2387                 shortcutsTW->setItemHidden(matched[i], false);
2388         shortcutsTW->setItemExpanded(matched[i]->parent(), true);
2389         }
2390 }
2391
2392
2393 docstring makeCmdString(FuncRequest const & f)
2394 {
2395         docstring actionStr = from_ascii(lyxaction.getActionName(f.action));
2396         if (!f.argument().empty())
2397                 actionStr += " " + f.argument();
2398         return actionStr;
2399 }
2400
2401
2402 void PrefShortcuts::shortcut_okPB_pressed()
2403 {
2404         QString const new_lfun = shortcut_->lfunLE->text();
2405         FuncRequest func = lyxaction.lookupFunc(fromqstr(new_lfun));
2406
2407         if (func.action == LFUN_UNKNOWN_ACTION) {
2408                 Alert::error(_("Failed to create shortcut"),
2409                         _("Unknown or invalid LyX function"));
2410                 return;
2411         }
2412
2413         KeySequence k = shortcut_->shortcutWG->getKeySequence();
2414         if (k.length() == 0) {
2415                 Alert::error(_("Failed to create shortcut"),
2416                         _("Invalid or empty key sequence"));
2417                 return;
2418         }
2419
2420         // check to see if there's been any change
2421         FuncRequest oldBinding = system_bind_.getBinding(k);
2422         if (oldBinding.action == LFUN_UNKNOWN_ACTION)
2423                 oldBinding = user_bind_.getBinding(k);
2424         if (oldBinding == func) {
2425                 docstring const actionStr = makeCmdString(func);
2426                 Alert::error(_("Failed to create shortcut"),
2427                         bformat(_("Shortcut `%1$s' is already bound to:\n%2$s"), 
2428                         k.print(KeySequence::ForGui), actionStr));
2429                 return;
2430         }
2431         
2432         // make sure this key isn't already bound---and, if so, not unbound
2433         FuncCode const unbind = user_unbind_.getBinding(k).action;
2434         if (oldBinding.action != LFUN_UNKNOWN_ACTION && unbind == LFUN_UNKNOWN_ACTION)
2435         {
2436                 // FIXME Perhaps we should offer to over-write the old shortcut?
2437                 // If so, we'll need to remove it from our list, etc.
2438                 docstring const actionStr = makeCmdString(oldBinding);
2439                 Alert::error(_("Failed to create shortcut"),
2440                         bformat(_("Shortcut `%1$s' is already bound to:\n%2$s\n"
2441                           "You need to remove that binding before creating a new one."), 
2442                         k.print(KeySequence::ForGui), actionStr));
2443                 return;
2444         }
2445
2446         if (!save_lfun_.isEmpty() && new_lfun == save_lfun_)
2447                 // real modification of the lfun's shortcut,
2448                 // so remove the previous one
2449                 removeShortcut();
2450
2451         QTreeWidgetItem * item = insertShortcutItem(func, k, KeyMap::UserBind);
2452         if (item) {
2453                 user_bind_.bind(&k, func);
2454                 shortcutsTW->sortItems(0, Qt::AscendingOrder);
2455                 shortcutsTW->setItemExpanded(item->parent(), true);
2456                 shortcutsTW->scrollToItem(item);
2457         } else {
2458                 Alert::error(_("Failed to create shortcut"),
2459                         _("Can not insert shortcut to the list"));
2460                 return;
2461         }
2462 }
2463
2464
2465 void PrefShortcuts::shortcut_cancelPB_pressed()
2466 {
2467         shortcut_->shortcutWG->reset();
2468 }
2469
2470
2471 void PrefShortcuts::shortcut_clearPB_pressed()
2472 {
2473         shortcut_->shortcutWG->reset();
2474 }
2475
2476
2477 void PrefShortcuts::shortcut_removePB_pressed()
2478 {
2479         shortcut_->shortcutWG->removeFromSequence();
2480 }
2481
2482
2483 /////////////////////////////////////////////////////////////////////
2484 //
2485 // PrefIdentity
2486 //
2487 /////////////////////////////////////////////////////////////////////
2488
2489 PrefIdentity::PrefIdentity(GuiPreferences * form)
2490         : PrefModule(QString(), qt_("Identity"), form)
2491 {
2492         setupUi(this);
2493
2494         connect(nameED, SIGNAL(textChanged(QString)),
2495                 this, SIGNAL(changed()));
2496         connect(emailED, SIGNAL(textChanged(QString)),
2497                 this, SIGNAL(changed()));
2498 }
2499
2500
2501 void PrefIdentity::apply(LyXRC & rc) const
2502 {
2503         rc.user_name = fromqstr(nameED->text());
2504         rc.user_email = fromqstr(emailED->text());
2505 }
2506
2507
2508 void PrefIdentity::update(LyXRC const & rc)
2509 {
2510         nameED->setText(toqstr(rc.user_name));
2511         emailED->setText(toqstr(rc.user_email));
2512 }
2513
2514
2515
2516 /////////////////////////////////////////////////////////////////////
2517 //
2518 // GuiPreferences
2519 //
2520 /////////////////////////////////////////////////////////////////////
2521
2522 GuiPreferences::GuiPreferences(GuiView & lv)
2523         : GuiDialog(lv, "prefs", qt_("Preferences")), update_screen_font_(false)
2524 {
2525         setupUi(this);
2526
2527         QDialog::setModal(false);
2528
2529         connect(savePB, SIGNAL(clicked()), this, SLOT(slotOK()));
2530         connect(applyPB, SIGNAL(clicked()), this, SLOT(slotApply()));
2531         connect(closePB, SIGNAL(clicked()), this, SLOT(slotClose()));
2532         connect(restorePB, SIGNAL(clicked()), this, SLOT(slotRestore()));
2533
2534         addModule(new PrefUserInterface(this));
2535         addModule(new PrefEdit(this));
2536         addModule(new PrefShortcuts(this));
2537         addModule(new PrefScreenFonts(this));
2538         addModule(new PrefColors(this));
2539         addModule(new PrefDisplay(this));
2540         addModule(new PrefInput(this));
2541         addModule(new PrefCompletion(this));
2542
2543         addModule(new PrefPaths(this));
2544
2545         addModule(new PrefIdentity(this));
2546
2547         addModule(new PrefLanguage(this));
2548         addModule(new PrefSpellchecker(this));
2549
2550         addModule(new PrefPrinter(this));
2551         addModule(new PrefDate(this));
2552         addModule(new PrefPlaintext(this));
2553         addModule(new PrefLatex(this));
2554
2555         PrefConverters * converters = new PrefConverters(this);
2556         PrefFileformats * formats = new PrefFileformats(this);
2557         connect(formats, SIGNAL(formatsChanged()),
2558                         converters, SLOT(updateGui()));
2559         addModule(converters);
2560         addModule(formats);
2561
2562         prefsPS->setCurrentPanel(qt_("User interface"));
2563 // FIXME: hack to work around resizing bug in Qt >= 4.2
2564 // bug verified with Qt 4.2.{0-3} (JSpitzm)
2565 #if QT_VERSION >= 0x040200
2566         prefsPS->updateGeometry();
2567 #endif
2568
2569         bc().setPolicy(ButtonPolicy::PreferencesPolicy);
2570         bc().setOK(savePB);
2571         bc().setApply(applyPB);
2572         bc().setCancel(closePB);
2573         bc().setRestore(restorePB);
2574 }
2575
2576
2577 void GuiPreferences::addModule(PrefModule * module)
2578 {
2579         LASSERT(module, /**/);
2580         if (module->category().isEmpty())
2581                 prefsPS->addPanel(module, module->title());
2582         else
2583                 prefsPS->addPanel(module, module->title(), module->category());
2584         connect(module, SIGNAL(changed()), this, SLOT(change_adaptor()));
2585         modules_.push_back(module);
2586 }
2587
2588
2589 void GuiPreferences::change_adaptor()
2590 {
2591         changed();
2592 }
2593
2594
2595 void GuiPreferences::apply(LyXRC & rc) const
2596 {
2597         size_t end = modules_.size();
2598         for (size_t i = 0; i != end; ++i)
2599                 modules_[i]->apply(rc);
2600 }
2601
2602
2603 void GuiPreferences::updateRc(LyXRC const & rc)
2604 {
2605         size_t const end = modules_.size();
2606         for (size_t i = 0; i != end; ++i)
2607                 modules_[i]->update(rc);
2608 }
2609
2610
2611 void GuiPreferences::applyView()
2612 {
2613         apply(rc());
2614 }
2615
2616 bool GuiPreferences::initialiseParams(string const &)
2617 {
2618         rc_ = lyxrc;
2619         formats_ = lyx::formats;
2620         converters_ = theConverters();
2621         converters_.update(formats_);
2622         movers_ = theMovers();
2623         colors_.clear();
2624         update_screen_font_ = false;
2625         updateRc(rc_);
2626
2627         return true;
2628 }
2629
2630
2631 void GuiPreferences::dispatchParams()
2632 {
2633         ostringstream ss;
2634         rc_.write(ss, true);
2635         dispatch(FuncRequest(LFUN_LYXRC_APPLY, ss.str()));
2636         // FIXME: these need lfuns
2637         // FIXME UNICODE
2638         theBufferList().setCurrentAuthor(from_utf8(rc_.user_name), from_utf8(rc_.user_email));
2639
2640         lyx::formats = formats_;
2641
2642         theConverters() = converters_;
2643         theConverters().update(lyx::formats);
2644         theConverters().buildGraph();
2645
2646         theMovers() = movers_;
2647
2648         vector<string>::const_iterator it = colors_.begin();
2649         vector<string>::const_iterator const end = colors_.end();
2650         for (; it != end; ++it)
2651                 dispatch(FuncRequest(LFUN_SET_COLOR, *it));
2652         colors_.clear();
2653
2654         if (update_screen_font_) {
2655                 dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2656                 update_screen_font_ = false;
2657         }
2658
2659         // The Save button has been pressed
2660         if (isClosing())
2661                 dispatch(FuncRequest(LFUN_PREFERENCES_SAVE));
2662 }
2663
2664
2665 void GuiPreferences::setColor(ColorCode col, QString const & hex)
2666 {
2667         colors_.push_back(lcolor.getLyXName(col) + ' ' + fromqstr(hex));
2668 }
2669
2670
2671 void GuiPreferences::updateScreenFonts()
2672 {
2673         update_screen_font_ = true;
2674 }
2675
2676
2677 QString GuiPreferences::browsebind(QString const & file) const
2678 {
2679         return browseLibFile("bind", file, "bind", qt_("Choose bind file"),
2680                              QStringList(qt_("LyX bind files (*.bind)")));
2681 }
2682
2683
2684 QString GuiPreferences::browseUI(QString const & file) const
2685 {
2686         return browseLibFile("ui", file, "ui", qt_("Choose UI file"),
2687                              QStringList(qt_("LyX UI files (*.ui)")));
2688 }
2689
2690
2691 QString GuiPreferences::browsekbmap(QString const & file) const
2692 {
2693         return browseLibFile("kbd", file, "kmap", qt_("Choose keyboard map"),
2694                              QStringList(qt_("LyX keyboard maps (*.kmap)")));
2695 }
2696
2697
2698 QString GuiPreferences::browsedict(QString const & file) const
2699 {
2700         return browseFile(file, qt_("Choose personal dictionary"),
2701                 QStringList(lyxrc.use_spell_lib ? qt_("*.pws") : qt_("*.ispell")));
2702 }
2703
2704
2705 QString GuiPreferences::browse(QString const & file,
2706                                   QString const & title) const
2707 {
2708         return browseFile(file, title, QStringList(), true);
2709 }
2710
2711
2712 // We support less paper sizes than the document dialog
2713 // Therefore this adjustment is needed.
2714 PAPER_SIZE GuiPreferences::toPaperSize(int i) const
2715 {
2716         switch (i) {
2717         case 0:
2718                 return PAPER_DEFAULT;
2719         case 1:
2720                 return PAPER_USLETTER;
2721         case 2:
2722                 return PAPER_USLEGAL;
2723         case 3:
2724                 return PAPER_USEXECUTIVE;
2725         case 4:
2726                 return PAPER_A3;
2727         case 5:
2728                 return PAPER_A4;
2729         case 6:
2730                 return PAPER_A5;
2731         case 7:
2732                 return PAPER_B5;
2733         default:
2734                 // should not happen
2735                 return PAPER_DEFAULT;
2736         }
2737 }
2738
2739
2740 int GuiPreferences::fromPaperSize(PAPER_SIZE papersize) const
2741 {
2742         switch (papersize) {
2743         case PAPER_DEFAULT:
2744                 return 0;
2745         case PAPER_USLETTER:
2746                 return 1;
2747         case PAPER_USLEGAL:
2748                 return 2;
2749         case PAPER_USEXECUTIVE:
2750                 return 3;
2751         case PAPER_A3:
2752                 return 4;
2753         case PAPER_A4:
2754                 return 5;
2755         case PAPER_A5:
2756                 return 6;
2757         case PAPER_B5:
2758                 return 7;
2759         default:
2760                 // should not happen
2761                 return 0;
2762         }
2763 }
2764
2765
2766 Dialog * createGuiPreferences(GuiView & lv) { return new GuiPreferences(lv); }
2767
2768
2769 } // namespace frontend
2770 } // namespace lyx
2771
2772 #include "moc_GuiPrefs.cpp"