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