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