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