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