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