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