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