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