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