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