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