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