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