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