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