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