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