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