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