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