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