]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiPrefs.cpp
'using namespace std' instead of 'using std::xxx'
[lyx.git] / src / frontends / qt4 / GuiPrefs.cpp
1 /**
2  * \file GuiPrefs.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author John Levon
7  * \author Bo Peng
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "GuiPrefs.h"
15
16 #include "qt_helpers.h"
17 #include "GuiApplication.h"
18 #include "GuiFontLoader.h"
19
20 #include "BufferList.h"
21 #include "Color.h"
22 #include "ConverterCache.h"
23 #include "support/debug.h"
24 #include "FuncRequest.h"
25 #include "support/gettext.h"
26 #include "GuiFontExample.h"
27 #include "GuiKeySymbol.h"
28 #include "KeyMap.h"
29 #include "KeySequence.h"
30 #include "LyXAction.h"
31 #include "PanelStack.h"
32 #include "paper.h"
33 #include "Session.h"
34
35 #include "support/FileName.h"
36 #include "support/filetools.h"
37 #include "support/lstrings.h"
38 #include "support/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 "frontends/alert.h"
46 #include "frontends/Application.h"
47
48 #include <QCheckBox>
49 #include <QColorDialog>
50 #include <QFontDatabase>
51 #include <QHeaderView>
52 #include <QLineEdit>
53 #include <QPixmapCache>
54 #include <QPushButton>
55 #include <QSpinBox>
56 #include <QString>
57 #include <QTreeWidget>
58 #include <QTreeWidgetItem>
59 #include <QValidator>
60 #include <QCloseEvent>
61
62 #include <iomanip>
63 #include <sstream>
64 #include <algorithm>
65
66 using namespace Ui;
67
68 using namespace std;
69
70 namespace lyx {
71 namespace frontend {
72
73 using support::compare_ascii_no_case;
74 using support::os::external_path;
75 using support::os::external_path_list;
76 using support::os::internal_path;
77 using support::os::internal_path_list;
78 using support::FileName;
79 using support::FileFilterList;
80 using support::addPath;
81 using support::addName;
82 using support::mkdir;
83 using support::package;
84
85
86 /////////////////////////////////////////////////////////////////////
87 //
88 // Helpers
89 //
90 /////////////////////////////////////////////////////////////////////
91
92 template<class A>
93 static size_t findPos_helper(std::vector<A> const & vec, A const & val)
94 {
95         typedef typename std::vector<A>::const_iterator Cit;
96
97         Cit it = std::find(vec.begin(), vec.end(), val);
98         if (it == vec.end())
99                 return 0;
100         return std::distance(vec.begin(), it);
101 }
102
103
104 static void parseFontName(QString const & mangled0,
105         string & name, string & foundry)
106 {
107         std::string mangled = fromqstr(mangled0);
108         size_t const idx = mangled.find('[');
109         if (idx == string::npos || idx == 0) {
110                 name = mangled;
111                 foundry.clear();
112         } else {
113                 name = mangled.substr(0, idx - 1),
114                 foundry = mangled.substr(idx + 1, mangled.size() - idx - 2);
115         }
116 }
117
118
119 static void setComboxFont(QComboBox * cb, string const & family,
120         string const & foundry)
121 {
122         QString fontname = toqstr(family);
123         if (!foundry.empty())
124                 fontname += " [" + toqstr(foundry) + ']';
125
126         for (int i = 0; i < cb->count(); ++i) {
127                 if (cb->itemText(i) == fontname) {
128                         cb->setCurrentIndex(i);
129                         return;
130                 }
131         }
132
133         // Try matching without foundry name
134
135         // We count in reverse in order to prefer the Xft foundry
136         for (int i = cb->count(); --i >= 0;) {
137                 string name, foundry;
138                 parseFontName(cb->itemText(i), name, foundry);
139                 if (compare_ascii_no_case(name, family) == 0) {
140                         cb->setCurrentIndex(i);
141                         return;
142                 }
143         }
144
145         // family alone can contain e.g. "Helvetica [Adobe]"
146         string tmpname, tmpfoundry;
147         parseFontName(toqstr(family), tmpname, tmpfoundry);
148
149         // We count in reverse in order to prefer the Xft foundry
150         for (int i = cb->count(); --i >= 0; ) {
151                 string name, foundry;
152                 parseFontName(cb->itemText(i), name, foundry);
153                 if (compare_ascii_no_case(name, foundry) == 0) {
154                         cb->setCurrentIndex(i);
155                         return;
156                 }
157         }
158
159         // Bleh, default fonts, and the names couldn't be found. Hack
160         // for bug 1063.
161
162         QFont font;
163         font.setKerning(false);
164
165         QString const font_family = toqstr(family);
166         if (font_family == guiApp->romanFontName()) {
167                 font.setStyleHint(QFont::Serif);
168                 font.setFamily(font_family);
169         } else if (font_family == guiApp->sansFontName()) {
170                 font.setStyleHint(QFont::SansSerif);
171                 font.setFamily(font_family);
172         } else if (font_family == guiApp->typewriterFontName()) {
173                 font.setStyleHint(QFont::TypeWriter);
174                 font.setFamily(font_family);
175         } else {
176                 lyxerr << "FAILED to find the default font: '"
177                        << foundry << "', '" << family << '\''<< endl;
178                 return;
179         }
180
181         QFontInfo info(font);
182         string default_font_name, dummyfoundry;
183         parseFontName(info.family(), default_font_name, dummyfoundry);
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         parseFontName(screenRomanCO->currentText(),
470                 rc.roman_font_name, rc.roman_font_foundry);
471         parseFontName(screenSansCO->currentText(),
472                 rc.sans_font_name, rc.sans_font_foundry);
473         parseFontName(screenTypewriterCO->currentText(),
474                 rc.typewriter_font_name, rc.typewriter_font_foundry);
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         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(exampleDirPB, SIGNAL(clicked()), this, SLOT(select_exampledir()));
741         connect(templateDirPB, SIGNAL(clicked()), this, SLOT(select_templatedir()));
742         connect(tempDirPB, SIGNAL(clicked()), this, SLOT(select_tempdir()));
743         connect(backupDirPB, SIGNAL(clicked()), this, SLOT(select_backupdir()));
744         connect(workingDirPB, SIGNAL(clicked()), this, SLOT(select_workingdir()));
745         connect(lyxserverDirPB, SIGNAL(clicked()), this, SLOT(select_lyxpipe()));
746         connect(workingDirED, SIGNAL(textChanged(QString)),
747                 this, SIGNAL(changed()));
748         connect(exampleDirED, SIGNAL(textChanged(QString)),
749                 this, SIGNAL(changed()));
750         connect(templateDirED, SIGNAL(textChanged(QString)),
751                 this, SIGNAL(changed()));
752         connect(backupDirED, SIGNAL(textChanged(QString)),
753                 this, SIGNAL(changed()));
754         connect(tempDirED, SIGNAL(textChanged(QString)),
755                 this, SIGNAL(changed()));
756         connect(lyxserverDirED, SIGNAL(textChanged(QString)),
757                 this, SIGNAL(changed()));
758         connect(pathPrefixED, SIGNAL(textChanged(QString)),
759                 this, SIGNAL(changed()));
760 }
761
762
763 void PrefPaths::apply(LyXRC & rc) const
764 {
765         rc.document_path = internal_path(fromqstr(workingDirED->text()));
766         rc.example_path = internal_path(fromqstr(exampleDirED->text()));
767         rc.template_path = internal_path(fromqstr(templateDirED->text()));
768         rc.backupdir_path = internal_path(fromqstr(backupDirED->text()));
769         rc.tempdir_path = internal_path(fromqstr(tempDirED->text()));
770         rc.path_prefix = internal_path_list(fromqstr(pathPrefixED->text()));
771         // FIXME: should be a checkbox only
772         rc.lyxpipes = internal_path(fromqstr(lyxserverDirED->text()));
773 }
774
775
776 void PrefPaths::update(LyXRC const & rc)
777 {
778         workingDirED->setText(toqstr(external_path(rc.document_path)));
779         exampleDirED->setText(toqstr(external_path(rc.example_path)));
780         templateDirED->setText(toqstr(external_path(rc.template_path)));
781         backupDirED->setText(toqstr(external_path(rc.backupdir_path)));
782         tempDirED->setText(toqstr(external_path(rc.tempdir_path)));
783         pathPrefixED->setText(toqstr(external_path_list(rc.path_prefix)));
784         // FIXME: should be a checkbox only
785         lyxserverDirED->setText(toqstr(external_path(rc.lyxpipes)));
786 }
787
788
789 void PrefPaths::select_exampledir()
790 {
791         docstring file(form_->browsedir(
792                 from_utf8(internal_path(fromqstr(exampleDirED->text()))),
793                 _("Select directory for example files")));
794         if (!file.empty())
795                 exampleDirED->setText(toqstr(file));
796 }
797
798
799 void PrefPaths::select_templatedir()
800 {
801         docstring file(form_->browsedir(
802                 from_utf8(internal_path(fromqstr(templateDirED->text()))),
803                 _("Select a document templates directory")));
804         if (!file.empty())
805                 templateDirED->setText(toqstr(file));
806 }
807
808
809 void PrefPaths::select_tempdir()
810 {
811         docstring file(form_->browsedir(
812                 from_utf8(internal_path(fromqstr(tempDirED->text()))),
813                 _("Select a temporary directory")));
814         if (!file.empty())
815                 tempDirED->setText(toqstr(file));
816 }
817
818
819 void PrefPaths::select_backupdir()
820 {
821         docstring file(form_->browsedir(
822                 from_utf8(internal_path(fromqstr(backupDirED->text()))),
823                 _("Select a backups directory")));
824         if (!file.empty())
825                 backupDirED->setText(toqstr(file));
826 }
827
828
829 void PrefPaths::select_workingdir()
830 {
831         docstring file(form_->browsedir(
832                 from_utf8(internal_path(fromqstr(workingDirED->text()))),
833                 _("Select a document directory")));
834         if (!file.empty())
835                 workingDirED->setText(toqstr(file));
836 }
837
838
839 void PrefPaths::select_lyxpipe()
840 {
841         docstring file(form_->browse(
842                 from_utf8(internal_path(fromqstr(lyxserverDirED->text()))),
843                 _("Give a filename for the LyX server pipe")));
844         if (!file.empty())
845                 lyxserverDirED->setText(toqstr(file));
846 }
847
848
849 /////////////////////////////////////////////////////////////////////
850 //
851 // PrefSpellchecker
852 //
853 /////////////////////////////////////////////////////////////////////
854
855 PrefSpellchecker::PrefSpellchecker(GuiPreferences * form, QWidget * parent)
856         : PrefModule(_("Spellchecker"), form, parent)
857 {
858         setupUi(this);
859
860         connect(persDictionaryPB, SIGNAL(clicked()), this, SLOT(select_dict()));
861 #if defined (USE_ISPELL)
862         connect(spellCommandCO, SIGNAL(activated(int)),
863                 this, SIGNAL(changed()));
864 #else
865         spellCommandCO->setEnabled(false);
866 #endif
867         connect(altLanguageED, SIGNAL(textChanged(QString)),
868                 this, SIGNAL(changed()));
869         connect(escapeCharactersED, SIGNAL(textChanged(QString)),
870                 this, SIGNAL(changed()));
871         connect(persDictionaryED, SIGNAL(textChanged(QString)),
872                 this, SIGNAL(changed()));
873         connect(compoundWordCB, SIGNAL(clicked()),
874                 this, SIGNAL(changed()));
875         connect(inputEncodingCB, SIGNAL(clicked()),
876                 this, SIGNAL(changed()));
877
878         spellCommandCO->addItem(qt_("ispell"));
879         spellCommandCO->addItem(qt_("aspell"));
880         spellCommandCO->addItem(qt_("hspell"));
881 #ifdef USE_PSPELL
882         spellCommandCO->addItem(qt_("pspell (library)"));
883 #else
884 #ifdef USE_ASPELL
885         spellCommandCO->addItem(qt_("aspell (library)"));
886 #endif
887 #endif
888 }
889
890
891 void PrefSpellchecker::apply(LyXRC & rc) const
892 {
893         switch (spellCommandCO->currentIndex()) {
894                 case 0:
895                 case 1:
896                 case 2:
897                         rc.use_spell_lib = false;
898                         rc.isp_command = fromqstr(spellCommandCO->currentText());
899                         break;
900                 case 3:
901                         rc.use_spell_lib = true;
902                         break;
903         }
904
905         // FIXME: remove isp_use_alt_lang
906         rc.isp_alt_lang = fromqstr(altLanguageED->text());
907         rc.isp_use_alt_lang = !rc.isp_alt_lang.empty();
908         // FIXME: remove isp_use_esc_chars
909         rc.isp_esc_chars = fromqstr(escapeCharactersED->text());
910         rc.isp_use_esc_chars = !rc.isp_esc_chars.empty();
911         // FIXME: remove isp_use_pers_dict
912         rc.isp_pers_dict = internal_path(fromqstr(persDictionaryED->text()));
913         rc.isp_use_pers_dict = !rc.isp_pers_dict.empty();
914         rc.isp_accept_compound = compoundWordCB->isChecked();
915         rc.isp_use_input_encoding = inputEncodingCB->isChecked();
916 }
917
918
919 void PrefSpellchecker::update(LyXRC const & rc)
920 {
921         spellCommandCO->setCurrentIndex(0);
922
923         if (rc.isp_command == "ispell") {
924                 spellCommandCO->setCurrentIndex(0);
925         } else if (rc.isp_command == "aspell") {
926                 spellCommandCO->setCurrentIndex(1);
927         } else if (rc.isp_command == "hspell") {
928                 spellCommandCO->setCurrentIndex(2);
929         }
930
931         if (rc.use_spell_lib) {
932 #if defined(USE_ASPELL) || defined(USE_PSPELL)
933                 spellCommandCO->setCurrentIndex(3);
934 #endif
935         }
936
937         // FIXME: remove isp_use_alt_lang
938         altLanguageED->setText(toqstr(rc.isp_alt_lang));
939         // FIXME: remove isp_use_esc_chars
940         escapeCharactersED->setText(toqstr(rc.isp_esc_chars));
941         // FIXME: remove isp_use_pers_dict
942         persDictionaryED->setText(toqstr(external_path(rc.isp_pers_dict)));
943         compoundWordCB->setChecked(rc.isp_accept_compound);
944         inputEncodingCB->setChecked(rc.isp_use_input_encoding);
945 }
946
947
948 void PrefSpellchecker::select_dict()
949 {
950         docstring file(form_->browsedict(
951                 from_utf8(internal_path(fromqstr(persDictionaryED->text())))));
952         if (!file.empty())
953                 persDictionaryED->setText(toqstr(file));
954 }
955
956
957
958 /////////////////////////////////////////////////////////////////////
959 //
960 // PrefConverters
961 //
962 /////////////////////////////////////////////////////////////////////
963
964
965 PrefConverters::PrefConverters(GuiPreferences * form, QWidget * parent)
966         : PrefModule(_("Converters"), form, parent)
967 {
968         setupUi(this);
969
970         connect(converterNewPB, SIGNAL(clicked()),
971                 this, SLOT(update_converter()));
972         connect(converterRemovePB, SIGNAL(clicked()),
973                 this, SLOT(remove_converter()));
974         connect(converterModifyPB, SIGNAL(clicked()),
975                 this, SLOT(update_converter()));
976         connect(convertersLW, SIGNAL(currentRowChanged(int)),
977                 this, SLOT(switch_converter()));
978         connect(converterFromCO, SIGNAL(activated(QString)),
979                 this, SLOT(converter_changed()));
980         connect(converterToCO, SIGNAL(activated(QString)),
981                 this, SLOT(converter_changed()));
982         connect(converterED, SIGNAL(textEdited(QString)),
983                 this, SLOT(converter_changed()));
984         connect(converterFlagED, SIGNAL(textEdited(QString)),
985                 this, SLOT(converter_changed()));
986         connect(converterNewPB, SIGNAL(clicked()),
987                 this, SIGNAL(changed()));
988         connect(converterRemovePB, SIGNAL(clicked()),
989                 this, SIGNAL(changed()));
990         connect(converterModifyPB, SIGNAL(clicked()),
991                 this, SIGNAL(changed()));
992         connect(maxAgeLE, SIGNAL(textEdited(QString)),
993                 this, SIGNAL(changed()));
994
995         maxAgeLE->setValidator(new QDoubleValidator(maxAgeLE));
996         //converterDefGB->setFocusProxy(convertersLW);
997 }
998
999
1000 void PrefConverters::apply(LyXRC & rc) const
1001 {
1002         rc.use_converter_cache = cacheCB->isChecked();
1003         rc.converter_cache_maxage = int(maxAgeLE->text().toDouble() * 86400.0);
1004 }
1005
1006
1007 void PrefConverters::update(LyXRC const & rc)
1008 {
1009         cacheCB->setChecked(rc.use_converter_cache);
1010         QString max_age;
1011         max_age.setNum(double(rc.converter_cache_maxage) / 86400.0, 'g', 6);
1012         maxAgeLE->setText(max_age);
1013         updateGui();
1014 }
1015
1016
1017 void PrefConverters::updateGui()
1018 {
1019         form_->formats().sort();
1020         form_->converters().update(form_->formats());
1021         // save current selection
1022         QString current = converterFromCO->currentText()
1023                 + " -> " + converterToCO->currentText();
1024
1025         converterFromCO->clear();
1026         converterToCO->clear();
1027
1028         Formats::const_iterator cit = form_->formats().begin();
1029         Formats::const_iterator end = form_->formats().end();
1030         for (; cit != end; ++cit) {
1031                 converterFromCO->addItem(toqstr(cit->prettyname()));
1032                 converterToCO->addItem(toqstr(cit->prettyname()));
1033         }
1034
1035         // currentRowChanged(int) is also triggered when updating the listwidget
1036         // block signals to avoid unnecessary calls to switch_converter()
1037         convertersLW->blockSignals(true);
1038         convertersLW->clear();
1039
1040         Converters::const_iterator ccit = form_->converters().begin();
1041         Converters::const_iterator cend = form_->converters().end();
1042         for (; ccit != cend; ++ccit) {
1043                 std::string const name =
1044                         ccit->From->prettyname() + " -> " + ccit->To->prettyname();
1045                 int type = form_->converters().getNumber(ccit->From->name(), ccit->To->name());
1046                 new QListWidgetItem(toqstr(name), convertersLW, type);
1047         }
1048         convertersLW->sortItems(Qt::AscendingOrder);
1049         convertersLW->blockSignals(false);
1050
1051         // restore selection
1052         if (!current.isEmpty()) {
1053                 QList<QListWidgetItem *> const item =
1054                         convertersLW->findItems(current, Qt::MatchExactly);
1055                 if (!item.isEmpty())
1056                         convertersLW->setCurrentItem(item.at(0));
1057         }
1058
1059         // select first element if restoring failed
1060         if (convertersLW->currentRow() == -1)
1061                 convertersLW->setCurrentRow(0);
1062
1063         updateButtons();
1064 }
1065
1066
1067 void PrefConverters::switch_converter()
1068 {
1069         int const cnr = convertersLW->currentItem()->type();
1070         Converter const & c(form_->converters().get(cnr));
1071         converterFromCO->setCurrentIndex(form_->formats().getNumber(c.from));
1072         converterToCO->setCurrentIndex(form_->formats().getNumber(c.to));
1073         converterED->setText(toqstr(c.command));
1074         converterFlagED->setText(toqstr(c.flags));
1075
1076         updateButtons();
1077 }
1078
1079
1080 void PrefConverters::converter_changed()
1081 {
1082         updateButtons();
1083 }
1084
1085
1086 void PrefConverters::updateButtons()
1087 {
1088         Format const & from = form_->formats().get(converterFromCO->currentIndex());
1089         Format const & to = form_->formats().get(converterToCO->currentIndex());
1090         int const sel = form_->converters().getNumber(from.name(), to.name());
1091         bool const known = sel >= 0;
1092         bool const valid = !(converterED->text().isEmpty()
1093                 || from.name() == to.name());
1094
1095         int const cnr = convertersLW->currentItem()->type();
1096         Converter const & c(form_->converters().get(cnr));
1097         string const old_command = c.command;
1098         string const old_flag = c.flags;
1099         string const new_command(fromqstr(converterED->text()));
1100         string const new_flag(fromqstr(converterFlagED->text()));
1101
1102         bool modified = (old_command != new_command) || (old_flag != new_flag);
1103
1104         converterModifyPB->setEnabled(valid && known && modified);
1105         converterNewPB->setEnabled(valid && !known);
1106         converterRemovePB->setEnabled(known);
1107
1108         maxAgeLE->setEnabled(cacheCB->isChecked());
1109         maxAgeLA->setEnabled(cacheCB->isChecked());
1110 }
1111
1112
1113 // FIXME: user must
1114 // specify unique from/to or it doesn't appear. This is really bad UI
1115 // this is why we can use the same function for both new and modify
1116 void PrefConverters::update_converter()
1117 {
1118         Format const & from = form_->formats().get(converterFromCO->currentIndex());
1119         Format const & to = form_->formats().get(converterToCO->currentIndex());
1120         string const flags = fromqstr(converterFlagED->text());
1121         string const command = fromqstr(converterED->text());
1122
1123         Converter const * old =
1124                 form_->converters().getConverter(from.name(), to.name());
1125         form_->converters().add(from.name(), to.name(), command, flags);
1126
1127         if (!old)
1128                 form_->converters().updateLast(form_->formats());
1129
1130         updateGui();
1131
1132         // Remove all files created by this converter from the cache, since
1133         // the modified converter might create different files.
1134         ConverterCache::get().remove_all(from.name(), to.name());
1135 }
1136
1137
1138 void PrefConverters::remove_converter()
1139 {
1140         Format const & from = form_->formats().get(converterFromCO->currentIndex());
1141         Format const & to = form_->formats().get(converterToCO->currentIndex());
1142         form_->converters().erase(from.name(), to.name());
1143
1144         updateGui();
1145
1146         // Remove all files created by this converter from the cache, since
1147         // a possible new converter might create different files.
1148         ConverterCache::get().remove_all(from.name(), to.name());
1149 }
1150
1151
1152 void PrefConverters::on_cacheCB_stateChanged(int state)
1153 {
1154         maxAgeLE->setEnabled(state == Qt::Checked);
1155         maxAgeLA->setEnabled(state == Qt::Checked);
1156         changed();
1157 }
1158
1159
1160 /////////////////////////////////////////////////////////////////////
1161 //
1162 // PrefFileformats
1163 //
1164 /////////////////////////////////////////////////////////////////////
1165 //
1166 FormatValidator::FormatValidator(QWidget * parent, Formats const & f) 
1167         : QValidator(parent), formats_(f)
1168 {
1169 }
1170
1171
1172 void FormatValidator::fixup(QString & input) const
1173 {
1174         Formats::const_iterator cit = formats_.begin();
1175         Formats::const_iterator end = formats_.end();
1176         for (; cit != end; ++cit) {
1177                 string const name = str(cit);
1178                 if (distance(formats_.begin(), cit) == nr()) {
1179                         input = toqstr(name);
1180                         return;
1181
1182                 }
1183         }
1184 }
1185
1186
1187 QValidator::State FormatValidator::validate(QString & input, int & /*pos*/) const
1188 {
1189         Formats::const_iterator cit = formats_.begin();
1190         Formats::const_iterator end = formats_.end();
1191         bool unknown = true;
1192         for (; unknown && cit != end; ++cit) {
1193                 string const name = str(cit);
1194                 if (distance(formats_.begin(), cit) != nr())
1195                         unknown = toqstr(name) != input;
1196         }
1197
1198         if (unknown && !input.isEmpty()) 
1199                 return QValidator::Acceptable;
1200         else
1201                 return QValidator::Intermediate;
1202 }
1203
1204
1205 int FormatValidator::nr() const
1206 {
1207         QComboBox * p = qobject_cast<QComboBox *>(parent());
1208         return p->itemData(p->currentIndex()).toInt();
1209 }
1210
1211
1212 FormatNameValidator::FormatNameValidator(QWidget * parent, Formats const & f) 
1213         : FormatValidator(parent, f)
1214 {
1215 }
1216
1217 std::string FormatNameValidator::str(Formats::const_iterator it) const
1218 {
1219         return it->name();
1220 }
1221
1222
1223 FormatPrettynameValidator::FormatPrettynameValidator(QWidget * parent, Formats const & f) 
1224         : FormatValidator(parent, f)
1225 {
1226 }
1227
1228
1229 std::string FormatPrettynameValidator::str(Formats::const_iterator it) const
1230 {
1231         return it->prettyname();
1232 }
1233
1234
1235 PrefFileformats::PrefFileformats(GuiPreferences * form, QWidget * parent)
1236         : PrefModule(_("File formats"), form, parent)
1237 {
1238         setupUi(this);
1239         formatED->setValidator(new FormatNameValidator(formatsCB, form_->formats()));
1240         formatsCB->setValidator(new FormatPrettynameValidator(formatsCB, form_->formats()));
1241
1242         connect(documentCB, SIGNAL(clicked()),
1243                 this, SLOT(setFlags()));
1244         connect(vectorCB, SIGNAL(clicked()),
1245                 this, SLOT(setFlags()));
1246         connect(formatsCB->lineEdit(), SIGNAL(editingFinished()),
1247                 this, SLOT(updatePrettyname()));
1248         connect(formatsCB->lineEdit(), SIGNAL(textEdited(QString)),
1249                 this, SIGNAL(changed()));
1250 }
1251
1252
1253 void PrefFileformats::apply(LyXRC & /*rc*/) const
1254 {
1255 }
1256
1257
1258 void PrefFileformats::update(LyXRC const & /*rc*/)
1259 {
1260         updateView();
1261 }
1262
1263
1264 void PrefFileformats::updateView()
1265 {
1266         QString const current = formatsCB->currentText();
1267
1268         // update combobox with formats
1269         formatsCB->blockSignals(true);
1270         formatsCB->clear();
1271         form_->formats().sort();
1272         Formats::const_iterator cit = form_->formats().begin();
1273         Formats::const_iterator end = form_->formats().end();
1274         for (; cit != end; ++cit)
1275                 formatsCB->addItem(toqstr(cit->prettyname()),
1276                                                         QVariant(form_->formats().getNumber(cit->name())) );
1277
1278         // restore selection
1279         int const item = formatsCB->findText(current, Qt::MatchExactly);
1280         formatsCB->setCurrentIndex(item < 0 ? 0 : item);
1281         on_formatsCB_currentIndexChanged(item < 0 ? 0 : item);
1282         formatsCB->blockSignals(false);
1283 }
1284
1285
1286 void PrefFileformats::on_formatsCB_currentIndexChanged(int i)
1287 {
1288         int const nr = formatsCB->itemData(i).toInt();
1289         Format const f = form_->formats().get(nr);
1290
1291         formatED->setText(toqstr(f.name()));
1292         copierED->setText(toqstr(form_->movers().command(f.name())));
1293         extensionED->setText(toqstr(f.extension()));
1294         shortcutED->setText(toqstr(f.shortcut()));
1295         viewerED->setText(toqstr(f.viewer()));
1296         editorED->setText(toqstr(f.editor()));
1297         documentCB->setChecked((f.documentFormat()));
1298         vectorCB->setChecked((f.vectorFormat()));
1299 }
1300
1301
1302 void PrefFileformats::setFlags()
1303 {
1304         int flags = Format::none;
1305         if (documentCB->isChecked())
1306                 flags |= Format::document;
1307         if (vectorCB->isChecked())
1308                 flags |= Format::vector;
1309         currentFormat().setFlags(flags);
1310         changed();
1311 }
1312
1313
1314 void PrefFileformats::on_copierED_textEdited(const QString & s)
1315 {
1316         string const fmt = fromqstr(formatED->text());
1317         form_->movers().set(fmt, fromqstr(s));
1318         changed();
1319 }
1320
1321
1322 void PrefFileformats::on_extensionED_textEdited(const QString & s)
1323 {
1324         currentFormat().setExtension(fromqstr(s));
1325         changed();
1326 }
1327
1328 void PrefFileformats::on_viewerED_textEdited(const QString & s)
1329 {
1330         currentFormat().setViewer(fromqstr(s));
1331         changed();
1332 }
1333
1334
1335 void PrefFileformats::on_editorED_textEdited(const QString & s)
1336 {
1337         currentFormat().setEditor(fromqstr(s));
1338         changed();
1339 }
1340
1341
1342 void PrefFileformats::on_shortcutED_textEdited(const QString & s)
1343 {
1344         currentFormat().setShortcut(fromqstr(s));
1345         changed();
1346 }
1347
1348
1349 void PrefFileformats::on_formatED_editingFinished()
1350 {
1351         string const newname = fromqstr(formatED->displayText());
1352         if (newname == currentFormat().name())
1353                 return;
1354
1355         currentFormat().setName(newname);
1356         changed();
1357 }
1358
1359
1360 void PrefFileformats::on_formatED_textChanged(const QString &)
1361 {
1362         QString t = formatED->text();
1363         int p = 0;
1364         bool valid = formatED->validator()->validate(t, p) == QValidator::Acceptable;
1365         setValid(formatLA, valid);
1366 }
1367
1368
1369 void PrefFileformats::on_formatsCB_editTextChanged(const QString &)
1370 {
1371         QString t = formatsCB->currentText();
1372         int p = 0;
1373         bool valid = formatsCB->validator()->validate(t, p) == QValidator::Acceptable;
1374         setValid(formatsLA, valid);
1375 }
1376
1377
1378 void PrefFileformats::updatePrettyname()
1379 {
1380         string const newname = fromqstr(formatsCB->currentText());
1381         if (newname == currentFormat().prettyname())
1382                 return;
1383
1384         currentFormat().setPrettyname(newname);
1385         formatsChanged();
1386         updateView();
1387         changed();
1388 }
1389
1390
1391 Format & PrefFileformats::currentFormat()
1392 {
1393         int const i = formatsCB->currentIndex();
1394         int const nr = formatsCB->itemData(i).toInt();
1395         return form_->formats().get(nr);
1396 }
1397
1398
1399 void PrefFileformats::on_formatNewPB_clicked()
1400 {
1401         form_->formats().add("", "", "", "", "", "", Format::none);
1402         updateView();
1403         formatsCB->setCurrentIndex(0);
1404         formatsCB->setFocus(Qt::OtherFocusReason);
1405 }
1406
1407
1408 void PrefFileformats::on_formatRemovePB_clicked()
1409 {
1410         int const i = formatsCB->currentIndex();
1411         int const nr = formatsCB->itemData(i).toInt();
1412         string const current_text = form_->formats().get(nr).name();
1413         if (form_->converters().formatIsUsed(current_text)) {
1414                 Alert::error(_("Format in use"),
1415                              _("Cannot remove a Format used by a Converter. "
1416                                             "Remove the converter first."));
1417                 return;
1418         }
1419
1420         form_->formats().erase(current_text);
1421         formatsChanged();
1422         updateView();
1423         on_formatsCB_editTextChanged(formatsCB->currentText());
1424         changed();
1425 }
1426
1427
1428 /////////////////////////////////////////////////////////////////////
1429 //
1430 // PrefLanguage
1431 //
1432 /////////////////////////////////////////////////////////////////////
1433
1434 PrefLanguage::PrefLanguage(QWidget * parent)
1435         : PrefModule(_("Language"), 0, parent)
1436 {
1437         setupUi(this);
1438
1439         connect(rtlCB, SIGNAL(clicked()),
1440                 this, SIGNAL(changed()));
1441         connect(markForeignCB, SIGNAL(clicked()),
1442                 this, SIGNAL(changed()));
1443         connect(autoBeginCB, SIGNAL(clicked()),
1444                 this, SIGNAL(changed()));
1445         connect(autoEndCB, SIGNAL(clicked()),
1446                 this, SIGNAL(changed()));
1447         connect(useBabelCB, SIGNAL(clicked()),
1448                 this, SIGNAL(changed()));
1449         connect(globalCB, SIGNAL(clicked()),
1450                 this, SIGNAL(changed()));
1451         connect(languagePackageED, SIGNAL(textChanged(QString)),
1452                 this, SIGNAL(changed()));
1453         connect(startCommandED, SIGNAL(textChanged(QString)),
1454                 this, SIGNAL(changed()));
1455         connect(endCommandED, SIGNAL(textChanged(QString)),
1456                 this, SIGNAL(changed()));
1457         connect(defaultLanguageCO, SIGNAL(activated(int)),
1458                 this, SIGNAL(changed()));
1459
1460         defaultLanguageCO->clear();
1461
1462         // store the lang identifiers for later
1463         std::vector<LanguagePair> const langs = getLanguageData(false);
1464         std::vector<LanguagePair>::const_iterator lit  = langs.begin();
1465         std::vector<LanguagePair>::const_iterator lend = langs.end();
1466         lang_.clear();
1467         for (; lit != lend; ++lit) {
1468                 defaultLanguageCO->addItem(toqstr(lit->first));
1469                 lang_.push_back(lit->second);
1470         }
1471 }
1472
1473
1474 void PrefLanguage::apply(LyXRC & rc) const
1475 {
1476         // FIXME: remove rtl_support bool
1477         rc.rtl_support = rtlCB->isChecked();
1478         rc.mark_foreign_language = markForeignCB->isChecked();
1479         rc.language_auto_begin = autoBeginCB->isChecked();
1480         rc.language_auto_end = autoEndCB->isChecked();
1481         rc.language_use_babel = useBabelCB->isChecked();
1482         rc.language_global_options = globalCB->isChecked();
1483         rc.language_package = fromqstr(languagePackageED->text());
1484         rc.language_command_begin = fromqstr(startCommandED->text());
1485         rc.language_command_end = fromqstr(endCommandED->text());
1486         rc.default_language = lang_[defaultLanguageCO->currentIndex()];
1487 }
1488
1489
1490 void PrefLanguage::update(LyXRC const & rc)
1491 {
1492         // FIXME: remove rtl_support bool
1493         rtlCB->setChecked(rc.rtl_support);
1494         markForeignCB->setChecked(rc.mark_foreign_language);
1495         autoBeginCB->setChecked(rc.language_auto_begin);
1496         autoEndCB->setChecked(rc.language_auto_end);
1497         useBabelCB->setChecked(rc.language_use_babel);
1498         globalCB->setChecked(rc.language_global_options);
1499         languagePackageED->setText(toqstr(rc.language_package));
1500         startCommandED->setText(toqstr(rc.language_command_begin));
1501         endCommandED->setText(toqstr(rc.language_command_end));
1502
1503         int const pos = int(findPos_helper(lang_, rc.default_language));
1504         defaultLanguageCO->setCurrentIndex(pos);
1505 }
1506
1507
1508 /////////////////////////////////////////////////////////////////////
1509 //
1510 // PrefPrinter
1511 //
1512 /////////////////////////////////////////////////////////////////////
1513
1514 PrefPrinter::PrefPrinter(QWidget * parent)
1515         : PrefModule(_("Printer"), 0, parent)
1516 {
1517         setupUi(this);
1518
1519         connect(printerAdaptCB, SIGNAL(clicked()),
1520                 this, SIGNAL(changed()));
1521         connect(printerCommandED, SIGNAL(textChanged(QString)),
1522                 this, SIGNAL(changed()));
1523         connect(printerNameED, SIGNAL(textChanged(QString)),
1524                 this, SIGNAL(changed()));
1525         connect(printerPageRangeED, SIGNAL(textChanged(QString)),
1526                 this, SIGNAL(changed()));
1527         connect(printerCopiesED, SIGNAL(textChanged(QString)),
1528                 this, SIGNAL(changed()));
1529         connect(printerReverseED, SIGNAL(textChanged(QString)),
1530                 this, SIGNAL(changed()));
1531         connect(printerToPrinterED, SIGNAL(textChanged(QString)),
1532                 this, SIGNAL(changed()));
1533         connect(printerExtensionED, SIGNAL(textChanged(QString)),
1534                 this, SIGNAL(changed()));
1535         connect(printerSpoolCommandED, SIGNAL(textChanged(QString)),
1536                 this, SIGNAL(changed()));
1537         connect(printerPaperTypeED, SIGNAL(textChanged(QString)),
1538                 this, SIGNAL(changed()));
1539         connect(printerEvenED, SIGNAL(textChanged(QString)),
1540                 this, SIGNAL(changed()));
1541         connect(printerOddED, SIGNAL(textChanged(QString)),
1542                 this, SIGNAL(changed()));
1543         connect(printerCollatedED, SIGNAL(textChanged(QString)),
1544                 this, SIGNAL(changed()));
1545         connect(printerLandscapeED, SIGNAL(textChanged(QString)),
1546                 this, SIGNAL(changed()));
1547         connect(printerToFileED, SIGNAL(textChanged(QString)),
1548                 this, SIGNAL(changed()));
1549         connect(printerExtraED, SIGNAL(textChanged(QString)),
1550                 this, SIGNAL(changed()));
1551         connect(printerSpoolPrefixED, SIGNAL(textChanged(QString)),
1552                 this, SIGNAL(changed()));
1553         connect(printerPaperSizeED, SIGNAL(textChanged(QString)),
1554                 this, SIGNAL(changed()));
1555 }
1556
1557
1558 void PrefPrinter::apply(LyXRC & rc) const
1559 {
1560         rc.print_adapt_output = printerAdaptCB->isChecked();
1561         rc.print_command = fromqstr(printerCommandED->text());
1562         rc.printer = fromqstr(printerNameED->text());
1563
1564         rc.print_pagerange_flag = fromqstr(printerPageRangeED->text());
1565         rc.print_copies_flag = fromqstr(printerCopiesED->text());
1566         rc.print_reverse_flag = fromqstr(printerReverseED->text());
1567         rc.print_to_printer = fromqstr(printerToPrinterED->text());
1568         rc.print_file_extension = fromqstr(printerExtensionED->text());
1569         rc.print_spool_command = fromqstr(printerSpoolCommandED->text());
1570         rc.print_paper_flag = fromqstr(printerPaperTypeED->text());
1571         rc.print_evenpage_flag = fromqstr(printerEvenED->text());
1572         rc.print_oddpage_flag = fromqstr(printerOddED->text());
1573         rc.print_collcopies_flag = fromqstr(printerCollatedED->text());
1574         rc.print_landscape_flag = fromqstr(printerLandscapeED->text());
1575         rc.print_to_file = internal_path(fromqstr(printerToFileED->text()));
1576         rc.print_extra_options = fromqstr(printerExtraED->text());
1577         rc.print_spool_printerprefix = fromqstr(printerSpoolPrefixED->text());
1578         rc.print_paper_dimension_flag = fromqstr(printerPaperSizeED->text());
1579 }
1580
1581
1582 void PrefPrinter::update(LyXRC const & rc)
1583 {
1584         printerAdaptCB->setChecked(rc.print_adapt_output);
1585         printerCommandED->setText(toqstr(rc.print_command));
1586         printerNameED->setText(toqstr(rc.printer));
1587
1588         printerPageRangeED->setText(toqstr(rc.print_pagerange_flag));
1589         printerCopiesED->setText(toqstr(rc.print_copies_flag));
1590         printerReverseED->setText(toqstr(rc.print_reverse_flag));
1591         printerToPrinterED->setText(toqstr(rc.print_to_printer));
1592         printerExtensionED->setText(toqstr(rc.print_file_extension));
1593         printerSpoolCommandED->setText(toqstr(rc.print_spool_command));
1594         printerPaperTypeED->setText(toqstr(rc.print_paper_flag));
1595         printerEvenED->setText(toqstr(rc.print_evenpage_flag));
1596         printerOddED->setText(toqstr(rc.print_oddpage_flag));
1597         printerCollatedED->setText(toqstr(rc.print_collcopies_flag));
1598         printerLandscapeED->setText(toqstr(rc.print_landscape_flag));
1599         printerToFileED->setText(toqstr(external_path(rc.print_to_file)));
1600         printerExtraED->setText(toqstr(rc.print_extra_options));
1601         printerSpoolPrefixED->setText(toqstr(rc.print_spool_printerprefix));
1602         printerPaperSizeED->setText(toqstr(rc.print_paper_dimension_flag));
1603 }
1604
1605
1606 /////////////////////////////////////////////////////////////////////
1607 //
1608 // PrefUserInterface
1609 //
1610 /////////////////////////////////////////////////////////////////////
1611
1612 PrefUserInterface::PrefUserInterface(GuiPreferences * form, QWidget * parent)
1613         : PrefModule(_("User interface"), form, parent)
1614 {
1615         setupUi(this);
1616
1617         connect(autoSaveCB, SIGNAL(toggled(bool)),
1618                 autoSaveSB, SLOT(setEnabled(bool)));
1619         connect(autoSaveCB, SIGNAL(toggled(bool)),
1620                 TextLabel1, SLOT(setEnabled(bool)));
1621         connect(uiFilePB, SIGNAL(clicked()),
1622                 this, SLOT(select_ui()));
1623         connect(uiFileED, SIGNAL(textChanged(QString)),
1624                 this, SIGNAL(changed()));
1625         connect(restoreCursorCB, SIGNAL(clicked()),
1626                 this, SIGNAL(changed()));
1627         connect(loadSessionCB, SIGNAL(clicked()),
1628                 this, SIGNAL(changed()));
1629         connect(allowGeometrySessionCB, SIGNAL(clicked()),
1630                 this, SIGNAL(changed()));
1631         connect(cursorFollowsCB, SIGNAL(clicked()),
1632                 this, SIGNAL(changed()));
1633         connect(sortEnvironmentsCB, SIGNAL(clicked()),
1634                 this, SIGNAL(changed()));
1635         connect(autoSaveSB, SIGNAL(valueChanged(int)),
1636                 this, SIGNAL(changed()));
1637         connect(autoSaveCB, SIGNAL(clicked()),
1638                 this, SIGNAL(changed()));
1639         connect(lastfilesSB, SIGNAL(valueChanged(int)),
1640                 this, SIGNAL(changed()));
1641         connect(pixmapCacheCB, SIGNAL(toggled(bool)),
1642                 this, SIGNAL(changed()));
1643         lastfilesSB->setMaximum(maxlastfiles);
1644 }
1645
1646
1647 void PrefUserInterface::apply(LyXRC & rc) const
1648 {
1649         rc.ui_file = internal_path(fromqstr(uiFileED->text()));
1650         rc.use_lastfilepos = restoreCursorCB->isChecked();
1651         rc.load_session = loadSessionCB->isChecked();
1652         rc.allow_geometry_session = allowGeometrySessionCB->isChecked();
1653         rc.cursor_follows_scrollbar = cursorFollowsCB->isChecked();
1654         rc.sort_layouts = sortEnvironmentsCB->isChecked();
1655         rc.autosave = autoSaveSB->value() * 60;
1656         rc.make_backup = autoSaveCB->isChecked();
1657         rc.num_lastfiles = lastfilesSB->value();
1658         rc.use_pixmap_cache = pixmapCacheCB->isChecked();
1659 }
1660
1661
1662 void PrefUserInterface::update(LyXRC const & rc)
1663 {
1664         uiFileED->setText(toqstr(external_path(rc.ui_file)));
1665         restoreCursorCB->setChecked(rc.use_lastfilepos);
1666         loadSessionCB->setChecked(rc.load_session);
1667         allowGeometrySessionCB->setChecked(rc.allow_geometry_session);
1668         cursorFollowsCB->setChecked(rc.cursor_follows_scrollbar);
1669         sortEnvironmentsCB->setChecked(rc.sort_layouts);
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 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 /////////////////////////////////////////////////////////////////////
1695 //
1696 // PrefShortcuts
1697 //
1698 /////////////////////////////////////////////////////////////////////
1699
1700
1701 GuiShortcutDialog::GuiShortcutDialog(QWidget * parent) : QDialog(parent)
1702 {
1703         Ui::shortcutUi::setupUi(this);
1704         QDialog::setModal(true);
1705 }
1706
1707
1708 PrefShortcuts::PrefShortcuts(GuiPreferences * form, QWidget * parent)
1709         : PrefModule(_("Shortcuts"), form, parent)
1710 {
1711         setupUi(this);
1712
1713         shortcutsTW->setColumnCount(2);
1714         shortcutsTW->headerItem()->setText(0, qt_("Function"));
1715         shortcutsTW->headerItem()->setText(1, qt_("Shortcut"));
1716         shortcutsTW->setSortingEnabled(true);
1717         // Multi-selection can be annoying.
1718         // shortcutsTW->setSelectionMode(QAbstractItemView::MultiSelection);
1719         shortcutsTW->header()->resizeSection(0, 200);
1720
1721         connect(bindFilePB, SIGNAL(clicked()),
1722                 this, SLOT(select_bind()));
1723         connect(bindFileED, SIGNAL(textChanged(QString)),
1724                 this, SIGNAL(changed()));
1725         connect(removePB, SIGNAL(clicked()), 
1726                 this, SIGNAL(changed()));
1727         
1728         shortcut_ = new GuiShortcutDialog(this);
1729         shortcut_bc_.setPolicy(ButtonPolicy::OkCancelPolicy);
1730         shortcut_bc_.setOK(shortcut_->okPB);
1731         shortcut_bc_.setCancel(shortcut_->cancelPB);
1732
1733         connect(shortcut_->okPB, SIGNAL(clicked()),
1734                 shortcut_, SLOT(accept()));
1735         connect(shortcut_->okPB, SIGNAL(clicked()), 
1736                 this, SIGNAL(changed()));
1737         connect(shortcut_->cancelPB, SIGNAL(clicked()), 
1738                 shortcut_, SLOT(reject()));
1739         connect(shortcut_->clearPB, SIGNAL(clicked()),
1740                 this, SLOT(shortcut_clearPB_pressed()));
1741         connect(shortcut_->okPB, SIGNAL(clicked()), 
1742                 this, SLOT(shortcut_okPB_pressed()));
1743 }
1744
1745
1746 void PrefShortcuts::apply(LyXRC & rc) const
1747 {
1748         rc.bind_file = internal_path(fromqstr(bindFileED->text()));
1749         // write user_bind and user_unbind to .lyx/bind/user.bind
1750         string bind_dir = addPath(package().user_support().absFilename(), "bind");
1751         if (!FileName(bind_dir).exists() && mkdir(FileName(bind_dir), 0777)) {
1752                 lyxerr << "LyX could not create the user bind directory '"
1753                        << bind_dir << "'. All user-defined key bindings will be lost." << endl;
1754                 return;
1755         }
1756         if (!FileName(bind_dir).isDirWritable()) {
1757                 lyxerr << "LyX could not write to the user bind directory '"
1758                        << bind_dir << "'. All user-defined key bindings will be lost." << endl;
1759                 return;
1760         }
1761         FileName user_bind_file = FileName(addName(bind_dir, "user.bind"));
1762         user_bind_.write(user_bind_file.toFilesystemEncoding(), false, false);
1763         user_unbind_.write(user_bind_file.toFilesystemEncoding(), true, true);
1764         // immediately apply the keybindings. Why this is not done before?
1765         // The good thing is that the menus are updated automatically.
1766         theTopLevelKeymap().clear();
1767         theTopLevelKeymap().read("site");
1768         theTopLevelKeymap().read(rc.bind_file);
1769         theTopLevelKeymap().read("user");
1770 }
1771
1772
1773 void PrefShortcuts::update(LyXRC const & rc)
1774 {
1775         bindFileED->setText(toqstr(external_path(rc.bind_file)));
1776         //
1777         system_bind_.clear();
1778         user_bind_.clear();
1779         user_unbind_.clear();
1780         system_bind_.read(rc.bind_file);
1781         // \unbind in user.bind is added to user_unbind_
1782         user_bind_.read("user", &user_unbind_);
1783         updateShortcutsTW();
1784 }
1785
1786
1787 void PrefShortcuts::updateShortcutsTW()
1788 {
1789         shortcutsTW->clear();
1790
1791         editItem_ = new QTreeWidgetItem(shortcutsTW);
1792         editItem_->setText(0, toqstr("Cursor, Mouse and Editing functions"));
1793         editItem_->setFlags(editItem_->flags() & ~Qt::ItemIsSelectable);
1794
1795         mathItem_ = new QTreeWidgetItem(shortcutsTW);
1796         mathItem_->setText(0, toqstr("Mathematical Symbols"));
1797         mathItem_->setFlags(mathItem_->flags() & ~Qt::ItemIsSelectable);
1798         
1799         bufferItem_ = new QTreeWidgetItem(shortcutsTW);
1800         bufferItem_->setText(0, toqstr("Buffer and Window"));
1801         bufferItem_->setFlags(bufferItem_->flags() & ~Qt::ItemIsSelectable);
1802         
1803         layoutItem_ = new QTreeWidgetItem(shortcutsTW);
1804         layoutItem_->setText(0, toqstr("Font, Layouts and Textclasses"));
1805         layoutItem_->setFlags(layoutItem_->flags() & ~Qt::ItemIsSelectable);
1806
1807         systemItem_ = new QTreeWidgetItem(shortcutsTW);
1808         systemItem_->setText(0, toqstr("System and Miscellaneous"));
1809         systemItem_->setFlags(systemItem_->flags() & ~Qt::ItemIsSelectable);
1810
1811         // listBindings(unbound=true) lists all bound and unbound lfuns
1812         // Items in this list is tagged by its source.
1813         KeyMap::BindingList bindinglist = system_bind_.listBindings(true, 
1814                 static_cast<int>(System));
1815         KeyMap::BindingList user_bindinglist = user_bind_.listBindings(false,
1816                 static_cast<int>(UserBind));
1817         KeyMap::BindingList user_unbindinglist = user_unbind_.listBindings(false,
1818                 static_cast<int>(UserUnbind));
1819         bindinglist.insert(bindinglist.end(), user_bindinglist.begin(),
1820                         user_bindinglist.end());
1821         bindinglist.insert(bindinglist.end(), user_unbindinglist.begin(),
1822                         user_unbindinglist.end());
1823
1824         KeyMap::BindingList::const_iterator it = bindinglist.begin();
1825         KeyMap::BindingList::const_iterator it_end = bindinglist.end();
1826         for (; it != it_end; ++it)
1827                 insertShortcutItem(it->request, it->sequence, item_type(it->tag));
1828
1829         shortcutsTW->sortItems(0, Qt::AscendingOrder);
1830         QList<QTreeWidgetItem*> items = shortcutsTW->selectedItems();
1831         removePB->setEnabled(!items.isEmpty() && !items[0]->text(1).isEmpty());
1832 }
1833
1834
1835 void PrefShortcuts::setItemType(QTreeWidgetItem * item, item_type tag)
1836 {
1837         item->setData(0, Qt::UserRole, QVariant(tag));
1838         QFont font;
1839
1840         switch (tag) {
1841         case System:
1842                 break;
1843         case UserBind:
1844                 font.setBold(true);
1845                 break;
1846         case UserUnbind:
1847                 font.setStrikeOut(true);
1848                 break;
1849         // this item is not displayed now.
1850         case UserExtraUnbind:
1851                 font.setStrikeOut(true);
1852                 break;
1853         }
1854
1855         item->setFont(1, font);
1856 }
1857
1858
1859 QTreeWidgetItem * PrefShortcuts::insertShortcutItem(FuncRequest const & lfun,
1860                 KeySequence const & seq, item_type tag)
1861 {
1862         kb_action action = lfun.action;
1863         string const action_name = lyxaction.getActionName(action);
1864         QString const lfun_name = toqstr(from_utf8(action_name) 
1865                         + " " + lfun.argument());
1866         QString const shortcut = toqstr(seq.print(KeySequence::ForGui));
1867         item_type item_tag = tag;
1868
1869         QTreeWidgetItem * newItem = NULL;
1870         // for unbind items, try to find an existing item in the system bind list
1871         if (tag == UserUnbind) {
1872                 QList<QTreeWidgetItem*> const items = shortcutsTW->findItems(lfun_name, 
1873                         Qt::MatchFlags(Qt::MatchExactly | Qt::MatchRecursive), 0);
1874                 for (int i = 0; i < items.size(); ++i) {
1875                         if (items[i]->text(1) == shortcut)
1876                                 newItem = items[i];
1877                                 break;
1878                         }
1879                 // if not found, this unbind item is UserExtraUnbind
1880                 // Such an item is not displayed to avoid confusion (what is 
1881                 // unmatched removed?).
1882                 if (!newItem) {
1883                         item_tag = UserExtraUnbind;
1884                         return NULL;
1885                 }
1886         }
1887         if (!newItem) {
1888                 switch(lyxaction.getActionType(action)) {
1889                 case LyXAction::Hidden:
1890                         return NULL;
1891                 case LyXAction::Edit:
1892                         newItem = new QTreeWidgetItem(editItem_);
1893                         break;
1894                 case LyXAction::Math:
1895                         newItem = new QTreeWidgetItem(mathItem_);
1896                         break;
1897                 case LyXAction::Buffer:
1898                         newItem = new QTreeWidgetItem(bufferItem_);
1899                         break;
1900                 case LyXAction::Layout:
1901                         newItem = new QTreeWidgetItem(layoutItem_);
1902                         break;
1903                 case LyXAction::System:
1904                         newItem = new QTreeWidgetItem(systemItem_);
1905                         break;
1906                 default:
1907                         // this should not happen
1908                         newItem = new QTreeWidgetItem(shortcutsTW);
1909                 }
1910         }
1911
1912         newItem->setText(0, lfun_name);
1913         newItem->setText(1, shortcut);
1914         // record BindFile representation to recover KeySequence when needed.
1915         newItem->setData(1, Qt::UserRole, toqstr(seq.print(KeySequence::BindFile)));
1916         setItemType(newItem, item_tag);
1917         return newItem;
1918 }
1919
1920
1921 void PrefShortcuts::on_shortcutsTW_itemSelectionChanged()
1922 {
1923         QList<QTreeWidgetItem*> items = shortcutsTW->selectedItems();
1924         removePB->setEnabled(!items.isEmpty() && !items[0]->text(1).isEmpty());
1925         if (items.isEmpty())
1926                 return;
1927         
1928         item_type tag = static_cast<item_type>(items[0]->data(0, Qt::UserRole).toInt());
1929         if (tag == UserUnbind)
1930                 removePB->setText(toqstr("Restore"));
1931         else
1932                 removePB->setText(toqstr("Remove"));
1933 }
1934
1935
1936 void PrefShortcuts::on_shortcutsTW_itemDoubleClicked()
1937 {
1938         QTreeWidgetItem * item = shortcutsTW->currentItem();
1939         if (item->flags() & Qt::ItemIsSelectable) {
1940                 shortcut_->lfunLE->setText(item->text(0));
1941                 // clear the shortcut because I assume that a user will enter
1942                 // a new shortcut.
1943                 shortcut_->shortcutLE->reset();
1944                 shortcut_->shortcutLE->setFocus();
1945                 shortcut_->exec();
1946         }
1947 }
1948
1949
1950 void PrefShortcuts::select_bind()
1951 {
1952         docstring const name =
1953                 from_utf8(internal_path(fromqstr(bindFileED->text())));
1954         docstring file = form_->browsebind(name);
1955         if (!file.empty()) {
1956                 bindFileED->setText(toqstr(file));
1957                 system_bind_ = KeyMap();
1958                 system_bind_.read(to_utf8(file));
1959                 updateShortcutsTW();
1960         }
1961 }
1962
1963
1964 void PrefShortcuts::on_newPB_pressed()
1965 {
1966         shortcut_->lfunLE->clear();
1967         shortcut_->shortcutLE->reset();
1968         shortcut_->exec();
1969 }
1970
1971
1972 void PrefShortcuts::on_removePB_pressed()
1973 {
1974         // it seems that only one item can be selected, but I am
1975         // removing all selected items anyway.
1976         QList<QTreeWidgetItem*> items = shortcutsTW->selectedItems();
1977         for (int i = 0; i < items.size(); ++i) {
1978                 string shortcut = fromqstr(items[i]->data(1, Qt::UserRole).toString());
1979                 string lfun = fromqstr(items[i]->text(0));
1980                 FuncRequest func = lyxaction.lookupFunc(lfun);
1981                 item_type tag = static_cast<item_type>(items[i]->data(0, Qt::UserRole).toInt());
1982                 
1983                 switch (tag) {
1984                 case System: {
1985                         // for system bind, we do not touch the item
1986                         // but add an user unbind item
1987                         user_unbind_.bind(shortcut, func);
1988                         setItemType(items[i], UserUnbind);
1989                         removePB->setText(toqstr("Restore"));
1990                         break;
1991                 }
1992                 case UserBind: {
1993                         // for user_bind, we remove this bind
1994                         QTreeWidgetItem * parent = items[i]->parent();
1995                         int itemIdx = parent->indexOfChild(items[i]);
1996                         parent->takeChild(itemIdx);
1997                         if (itemIdx > 0)
1998                                 shortcutsTW->scrollToItem(parent->child(itemIdx - 1));
1999                         else
2000                                 shortcutsTW->scrollToItem(parent);
2001                         user_bind_.unbind(shortcut, func);
2002                         break;
2003                 }
2004                 case UserUnbind: {
2005                         // for user_unbind, we remove the unbind, and the item
2006                         // become System again.
2007                         user_unbind_.unbind(shortcut, func);
2008                         setItemType(items[i], System);
2009                         removePB->setText(toqstr("Remove"));
2010                         break;
2011                 }
2012                 case UserExtraUnbind: {
2013                         // for user unbind that is not in system bind file,
2014                         // remove this unbind file
2015                         QTreeWidgetItem * parent = items[i]->parent();
2016                         parent->takeChild(parent->indexOfChild(items[i]));
2017                         user_unbind_.unbind(shortcut, func);
2018                 }
2019                 }
2020         }
2021 }
2022
2023
2024 void PrefShortcuts::on_searchLE_textEdited()
2025 {
2026         if (searchLE->text().isEmpty()) {
2027                 // show all hidden items
2028                 QTreeWidgetItemIterator it(shortcutsTW, QTreeWidgetItemIterator::Hidden);
2029                 while (*it)
2030                         shortcutsTW->setItemHidden(*it++, false);
2031                 return;
2032         }
2033         // search both columns
2034         QList<QTreeWidgetItem *> matched = shortcutsTW->findItems(searchLE->text(),
2035                 Qt::MatchFlags(Qt::MatchContains | Qt::MatchRecursive), 0);
2036         matched += shortcutsTW->findItems(searchLE->text(),
2037                 Qt::MatchFlags(Qt::MatchContains | Qt::MatchRecursive), 1);
2038         
2039         // hide everyone (to avoid searching in matched QList repeatedly
2040         QTreeWidgetItemIterator it(shortcutsTW, QTreeWidgetItemIterator::Selectable);
2041         while (*it)
2042                 shortcutsTW->setItemHidden(*it++, true);
2043         // show matched items
2044         for (int i = 0; i < matched.size(); ++i) {
2045                 shortcutsTW->setItemHidden(matched[i], false);
2046         shortcutsTW->setItemExpanded(matched[i]->parent(), true);
2047         }
2048 }
2049
2050
2051 void PrefShortcuts::shortcut_okPB_pressed()
2052 {
2053         string lfun = fromqstr(shortcut_->lfunLE->text());
2054         FuncRequest func = lyxaction.lookupFunc(lfun);
2055
2056         if (func.action == LFUN_UNKNOWN_ACTION) {
2057                 Alert::error(_("Failed to create shortcut"),
2058                         _("Unknown or invalid LyX function"));
2059                 return;
2060         }
2061
2062         KeySequence k = shortcut_->shortcutLE->getKeySequence();
2063         if (k.length() == 0) {
2064                 Alert::error(_("Failed to create shortcut"),
2065                         _("Invalid or empty key sequence"));
2066                 return;
2067         }
2068
2069         // if both lfun and shortcut is valid
2070         if (user_bind_.hasBinding(k, func) || system_bind_.hasBinding(k, func)) {
2071                 Alert::error(_("Failed to create shortcut"),
2072                         _("Shortcut is already defined"));
2073                 return;
2074         }
2075                 
2076         QTreeWidgetItem * item = insertShortcutItem(func, k, UserBind);
2077         if (item) {
2078                 user_bind_.bind(&k, func);
2079                 shortcutsTW->sortItems(0, Qt::AscendingOrder);
2080                 shortcutsTW->setItemExpanded(item->parent(), true);
2081                 shortcutsTW->scrollToItem(item);
2082         } else {
2083                 Alert::error(_("Failed to create shortcut"),
2084                         _("Can not insert shortcut to the list"));
2085                 return;
2086         }
2087 }
2088
2089
2090 void PrefShortcuts::shortcut_clearPB_pressed()
2091 {
2092         shortcut_->shortcutLE->reset();
2093         shortcut_->shortcutLE->setFocus();
2094 }
2095
2096
2097 /////////////////////////////////////////////////////////////////////
2098 //
2099 // PrefIdentity
2100 //
2101 /////////////////////////////////////////////////////////////////////
2102
2103 PrefIdentity::PrefIdentity(QWidget * parent)
2104         : PrefModule(_("Identity"), 0, parent)
2105 {
2106         setupUi(this);
2107
2108         connect(nameED, SIGNAL(textChanged(QString)),
2109                 this, SIGNAL(changed()));
2110         connect(emailED, SIGNAL(textChanged(QString)),
2111                 this, SIGNAL(changed()));
2112 }
2113
2114
2115 void PrefIdentity::apply(LyXRC & rc) const
2116 {
2117         rc.user_name = fromqstr(nameED->text());
2118         rc.user_email = fromqstr(emailED->text());
2119 }
2120
2121
2122 void PrefIdentity::update(LyXRC const & rc)
2123 {
2124         nameED->setText(toqstr(rc.user_name));
2125         emailED->setText(toqstr(rc.user_email));
2126 }
2127
2128
2129
2130 /////////////////////////////////////////////////////////////////////
2131 //
2132 // GuiPreferences
2133 //
2134 /////////////////////////////////////////////////////////////////////
2135
2136 GuiPreferences::GuiPreferences(GuiView & lv)
2137         : GuiDialog(lv, "prefs"), update_screen_font_(false)
2138 {
2139         setupUi(this);
2140         setViewTitle(_("Preferences"));
2141
2142         QDialog::setModal(false);
2143
2144         connect(savePB, SIGNAL(clicked()), this, SLOT(slotOK()));
2145         connect(applyPB, SIGNAL(clicked()), this, SLOT(slotApply()));
2146         connect(closePB, SIGNAL(clicked()), this, SLOT(slotClose()));
2147         connect(restorePB, SIGNAL(clicked()), this, SLOT(slotRestore()));
2148
2149         add(new PrefUserInterface(this));
2150         add(new PrefShortcuts(this));
2151         add(new PrefScreenFonts(this));
2152         add(new PrefColors(this));
2153         add(new PrefDisplay);
2154         add(new PrefKeyboard(this));
2155
2156         add(new PrefPaths(this));
2157
2158         add(new PrefIdentity);
2159
2160         add(new PrefLanguage);
2161         add(new PrefSpellchecker(this));
2162
2163         add(new PrefPrinter);
2164         add(new PrefDate);
2165         add(new PrefPlaintext);
2166         add(new PrefLatex(this));
2167
2168         PrefConverters * converters = new PrefConverters(this);
2169         PrefFileformats * formats = new PrefFileformats(this);
2170         connect(formats, SIGNAL(formatsChanged()),
2171                         converters, SLOT(updateGui()));
2172         add(converters);
2173         add(formats);
2174
2175         prefsPS->setCurrentPanel(_("User interface"));
2176 // FIXME: hack to work around resizing bug in Qt >= 4.2
2177 // bug verified with Qt 4.2.{0-3} (JSpitzm)
2178 #if QT_VERSION >= 0x040200
2179         prefsPS->updateGeometry();
2180 #endif
2181
2182         bc().setPolicy(ButtonPolicy::PreferencesPolicy);
2183         bc().setOK(savePB);
2184         bc().setApply(applyPB);
2185         bc().setCancel(closePB);
2186         bc().setRestore(restorePB);
2187 }
2188
2189
2190 void GuiPreferences::add(PrefModule * module)
2191 {
2192         BOOST_ASSERT(module);
2193         prefsPS->addPanel(module, module->title());
2194         connect(module, SIGNAL(changed()), this, SLOT(change_adaptor()));
2195         modules_.push_back(module);
2196 }
2197
2198
2199 void GuiPreferences::closeEvent(QCloseEvent * e)
2200 {
2201         slotClose();
2202         e->accept();
2203 }
2204
2205
2206 void GuiPreferences::change_adaptor()
2207 {
2208         changed();
2209 }
2210
2211
2212 void GuiPreferences::apply(LyXRC & rc) const
2213 {
2214         size_t end = modules_.size();
2215         for (size_t i = 0; i != end; ++i)
2216                 modules_[i]->apply(rc);
2217 }
2218
2219
2220 void GuiPreferences::updateRc(LyXRC const & rc)
2221 {
2222         size_t const end = modules_.size();
2223         for (size_t i = 0; i != end; ++i)
2224                 modules_[i]->update(rc);
2225 }
2226
2227
2228 void GuiPreferences::applyView()
2229 {
2230         apply(rc());
2231 }
2232
2233
2234 void GuiPreferences::updateContents()
2235 {
2236         updateRc(rc());
2237 }
2238
2239
2240 bool GuiPreferences::initialiseParams(std::string const &)
2241 {
2242         rc_ = lyxrc;
2243         formats_ = lyx::formats;
2244         converters_ = theConverters();
2245         converters_.update(formats_);
2246         movers_ = theMovers();
2247         colors_.clear();
2248         update_screen_font_ = false;
2249
2250         return true;
2251 }
2252
2253
2254 void GuiPreferences::dispatchParams()
2255 {
2256         ostringstream ss;
2257         rc_.write(ss, true);
2258         dispatch(FuncRequest(LFUN_LYXRC_APPLY, ss.str())); 
2259         // FIXME: these need lfuns
2260         // FIXME UNICODE
2261         theBufferList().setCurrentAuthor(from_utf8(rc_.user_name), from_utf8(rc_.user_email));
2262
2263         lyx::formats = formats_;
2264
2265         theConverters() = converters_;
2266         theConverters().update(lyx::formats);
2267         theConverters().buildGraph();
2268
2269         theMovers() = movers_;
2270
2271         vector<string>::const_iterator it = colors_.begin();
2272         vector<string>::const_iterator const end = colors_.end();
2273         for (; it != end; ++it)
2274                 dispatch(FuncRequest(LFUN_SET_COLOR, *it));
2275         colors_.clear();
2276
2277         if (update_screen_font_) {
2278                 dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2279                 update_screen_font_ = false;
2280         }
2281
2282         // The Save button has been pressed
2283         if (isClosing())
2284                 dispatch(FuncRequest(LFUN_PREFERENCES_SAVE));
2285 }
2286
2287
2288 void GuiPreferences::setColor(ColorCode col, string const & hex)
2289 {
2290         colors_.push_back(lcolor.getLyXName(col) + ' ' + hex);
2291 }
2292
2293
2294 void GuiPreferences::updateScreenFonts()
2295 {
2296         update_screen_font_ = true;
2297 }
2298
2299
2300 docstring const GuiPreferences::browsebind(docstring const & file) const
2301 {
2302         return browseLibFile(from_ascii("bind"), file, from_ascii("bind"),
2303                              _("Choose bind file"),
2304                              FileFilterList(_("LyX bind files (*.bind)")));
2305 }
2306
2307
2308 docstring const GuiPreferences::browseUI(docstring const & file) const
2309 {
2310         return browseLibFile(from_ascii("ui"), file, from_ascii("ui"),
2311                              _("Choose UI file"),
2312                              FileFilterList(_("LyX UI files (*.ui)")));
2313 }
2314
2315
2316 docstring const GuiPreferences::browsekbmap(docstring const & file) const
2317 {
2318         return browseLibFile(from_ascii("kbd"), file, from_ascii("kmap"),
2319                              _("Choose keyboard map"),
2320                              FileFilterList(_("LyX keyboard maps (*.kmap)")));
2321 }
2322
2323
2324 docstring const GuiPreferences::browsedict(docstring const & file) const
2325 {
2326         if (lyxrc.use_spell_lib)
2327                 return browseFile(file,
2328                                   _("Choose personal dictionary"),
2329                                   FileFilterList(_("*.pws")));
2330         else
2331                 return browseFile(file,
2332                                   _("Choose personal dictionary"),
2333                                   FileFilterList(_("*.ispell")));
2334 }
2335
2336
2337 docstring const GuiPreferences::browse(docstring const & file,
2338                                   docstring const & title) const
2339 {
2340         return browseFile(file, title, FileFilterList(), true);
2341 }
2342
2343
2344 docstring const GuiPreferences::browsedir(docstring const & path,
2345                                      docstring const & title) const
2346 {
2347         return browseDir(path, title);
2348 }
2349
2350
2351 // We support less paper sizes than the document dialog
2352 // Therefore this adjustment is needed.
2353 PAPER_SIZE GuiPreferences::toPaperSize(int i) const
2354 {
2355         switch (i) {
2356         case 0:
2357                 return PAPER_DEFAULT;
2358         case 1:
2359                 return PAPER_USLETTER;
2360         case 2:
2361                 return PAPER_USLEGAL;
2362         case 3:
2363                 return PAPER_USEXECUTIVE;
2364         case 4:
2365                 return PAPER_A3;
2366         case 5:
2367                 return PAPER_A4;
2368         case 6:
2369                 return PAPER_A5;
2370         case 7:
2371                 return PAPER_B5;
2372         default:
2373                 // should not happen
2374                 return PAPER_DEFAULT;
2375         }
2376 }
2377
2378
2379 int GuiPreferences::fromPaperSize(PAPER_SIZE papersize) const
2380 {
2381         switch (papersize) {
2382         case PAPER_DEFAULT:
2383                 return 0;
2384         case PAPER_USLETTER:
2385                 return 1;
2386         case PAPER_USLEGAL:
2387                 return 2;
2388         case PAPER_USEXECUTIVE:
2389                 return 3;
2390         case PAPER_A3:
2391                 return 4;
2392         case PAPER_A4:
2393                 return 5;
2394         case PAPER_A5:
2395                 return 6;
2396         case PAPER_B5:
2397                 return 7;
2398         default:
2399                 // should not happen
2400                 return 0;
2401         }
2402 }
2403
2404
2405 Dialog * createGuiPreferences(GuiView & lv) { return new GuiPreferences(lv); }
2406
2407
2408 } // namespace frontend
2409 } // namespace lyx
2410
2411 #include "GuiPrefs_moc.cpp"