]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiPrefs.cpp
Fix handling of the add branch textfield in GuiBranches
[lyx.git] / src / frontends / qt4 / GuiPrefs.cpp
1 /**
2  * \file GuiPrefs.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author John Levon
7  * \author Bo Peng
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "GuiPrefs.h"
15
16 #include "ColorCache.h"
17 #include "FileDialog.h"
18 #include "GuiApplication.h"
19 #include "GuiFontExample.h"
20 #include "GuiFontLoader.h"
21 #include "GuiKeySymbol.h"
22 #include "qt_helpers.h"
23 #include "Validator.h"
24
25 #include "Author.h"
26 #include "BufferList.h"
27 #include "Color.h"
28 #include "ColorSet.h"
29 #include "ConverterCache.h"
30 #include "FontEnums.h"
31 #include "FuncRequest.h"
32 #include "KeyMap.h"
33 #include "KeySequence.h"
34 #include "Language.h"
35 #include "LyXAction.h"
36 #include "LyX.h"
37 #include "PanelStack.h"
38 #include "paper.h"
39 #include "Session.h"
40 #include "SpellChecker.h"
41
42 #include "support/debug.h"
43 #include "support/FileName.h"
44 #include "support/filetools.h"
45 #include "support/foreach.h"
46 #include "support/gettext.h"
47 #include "support/lassert.h"
48 #include "support/lstrings.h"
49 #include "support/os.h"
50 #include "support/Package.h"
51
52 #include "graphics/GraphicsTypes.h"
53
54 #include "frontends/alert.h"
55 #include "frontends/Application.h"
56 #include "frontends/FontLoader.h"
57
58 #include <QAbstractItemModel>
59 #include <QCheckBox>
60 #include <QColorDialog>
61 #include <QFontDatabase>
62 #include <QHeaderView>
63 #include <QLineEdit>
64 #include <QMessageBox>
65 #include <QPixmapCache>
66 #include <QPushButton>
67 #include <QSpinBox>
68 #include <QString>
69 #include <QTreeWidget>
70 #include <QTreeWidgetItem>
71 #include <QValidator>
72
73 #include <iomanip>
74 #include <sstream>
75 #include <algorithm>
76
77 using namespace Ui;
78
79 using namespace std;
80 using namespace lyx::support;
81 using namespace lyx::support::os;
82
83 namespace lyx {
84 namespace frontend {
85
86 /////////////////////////////////////////////////////////////////////
87 //
88 // Browser Helpers
89 //
90 /////////////////////////////////////////////////////////////////////
91
92 /** Launch a file dialog and return the chosen file.
93         filename: a suggested filename.
94         title: the title of the dialog.
95         filters: *.ps etc.
96         dir1 = (name, dir), dir2 = (name, dir): extra buttons on the dialog.
97 */
98 QString browseFile(QString const & filename,
99         QString const & title,
100         QStringList const & filters,
101         bool save = false,
102         QString const & label1 = QString(),
103         QString const & dir1 = QString(),
104         QString const & label2 = QString(),
105         QString const & dir2 = QString(),
106         QString const & fallback_dir = QString())
107 {
108         QString lastPath = ".";
109         if (!filename.isEmpty())
110                 lastPath = onlyPath(filename);
111         else if(!fallback_dir.isEmpty())
112                 lastPath = fallback_dir;
113
114         FileDialog dlg(title, LFUN_SELECT_FILE_SYNC);
115         dlg.setButton2(label1, dir1);
116         dlg.setButton2(label2, dir2);
117
118         FileDialog::Result result;
119
120         if (save)
121                 result = dlg.save(lastPath, filters, onlyFileName(filename));
122         else
123                 result = dlg.open(lastPath, filters, onlyFileName(filename));
124
125         return result.second;
126 }
127
128
129 /** Wrapper around browseFile which tries to provide a filename
130 *  relative to the user or system directory. The dir, name and ext
131 *  parameters have the same meaning as in the
132 *  support::LibFileSearch function.
133 */
134 QString browseLibFile(QString const & dir,
135         QString const & name,
136         QString const & ext,
137         QString const & title,
138         QStringList const & filters)
139 {
140         // FIXME UNICODE
141         QString const label1 = qt_("System files|#S#s");
142         QString const dir1 =
143                 toqstr(addName(package().system_support().absFileName(), fromqstr(dir)));
144
145         QString const label2 = qt_("User files|#U#u");
146         QString const dir2 =
147                 toqstr(addName(package().user_support().absFileName(), fromqstr(dir)));
148
149         QString const result = browseFile(toqstr(
150                 libFileSearch(dir, name, ext).absFileName()),
151                 title, filters, false, dir1, dir2, QString(), QString(), dir1);
152
153         // remove the extension if it is the default one
154         QString noextresult;
155         if (getExtension(result) == ext)
156                 noextresult = removeExtension(result);
157         else
158                 noextresult = result;
159
160         // remove the directory, if it is the default one
161         QString const file = onlyFileName(noextresult);
162         if (toqstr(libFileSearch(dir, file, ext).absFileName()) == result)
163                 return file;
164         else
165                 return noextresult;
166 }
167
168
169 /** Launch a file dialog and return the chosen directory.
170         pathname: a suggested pathname.
171         title: the title of the dialog.
172         dir1 = (name, dir), dir2 = (name, dir): extra buttons on the dialog.
173 */
174 QString browseDir(QString const & pathname,
175         QString const & title,
176         QString const & label1 = QString(),
177         QString const & dir1 = QString(),
178         QString const & label2 = QString(),
179         QString const & dir2 = QString())
180 {
181         QString lastPath = ".";
182         if (!pathname.isEmpty())
183                 lastPath = onlyPath(pathname);
184
185         FileDialog dlg(title, LFUN_SELECT_FILE_SYNC);
186         dlg.setButton1(label1, dir1);
187         dlg.setButton2(label2, dir2);
188
189         FileDialog::Result const result =
190                 dlg.opendir(lastPath, onlyFileName(pathname));
191
192         return result.second;
193 }
194
195
196 } // namespace frontend
197
198
199 QString browseRelToParent(QString const & filename, QString const & relpath,
200         QString const & title, QStringList const & filters, bool save,
201         QString const & label1, QString const & dir1,
202         QString const & label2, QString const & dir2)
203 {
204         QString const fname = makeAbsPath(filename, relpath);
205
206         QString const outname =
207                 frontend::browseFile(fname, title, filters, save, label1, dir1, label2, dir2);
208
209         QString const reloutname =
210                 toqstr(makeRelPath(qstring_to_ucs4(outname), qstring_to_ucs4(relpath)));
211
212         if (reloutname.startsWith("../"))
213                 return outname;
214         else
215                 return reloutname;
216 }
217
218
219 QString browseRelToSub(QString const & filename, QString const & relpath,
220         QString const & title, QStringList const & filters, bool save,
221         QString const & label1, QString const & dir1,
222         QString const & label2, QString const & dir2)
223 {
224         QString const fname = makeAbsPath(filename, relpath);
225
226         QString const outname =
227                 frontend::browseFile(fname, title, filters, save, label1, dir1, label2, dir2);
228
229         QString const reloutname =
230                 toqstr(makeRelPath(qstring_to_ucs4(outname), qstring_to_ucs4(relpath)));
231
232         QString testname = reloutname;
233         testname.remove(QRegExp("^(\\.\\./)+"));
234         
235         if (testname.contains("/"))
236                 return outname;
237         else
238                 return reloutname;
239 }
240
241
242
243 /////////////////////////////////////////////////////////////////////
244 //
245 // Helpers
246 //
247 /////////////////////////////////////////////////////////////////////
248
249 namespace frontend {
250
251 string const catLookAndFeel = N_("Look & Feel");
252 string const catEditing = N_("Editing");
253 string const catLanguage = N_("Language Settings");
254 string const catOutput = N_("Output");
255 string const catFiles = N_("File Handling");
256
257 static void parseFontName(QString const & mangled0,
258         string & name, string & foundry)
259 {
260         string mangled = fromqstr(mangled0);
261         size_t const idx = mangled.find('[');
262         if (idx == string::npos || idx == 0) {
263                 name = mangled;
264                 foundry.clear();
265         } else {
266                 name = mangled.substr(0, idx - 1),
267                 foundry = mangled.substr(idx + 1, mangled.size() - idx - 2);
268         }
269 }
270
271
272 static void setComboxFont(QComboBox * cb, string const & family,
273         string const & foundry)
274 {
275         QString fontname = toqstr(family);
276         if (!foundry.empty())
277                 fontname += " [" + toqstr(foundry) + ']';
278
279         for (int i = 0; i != cb->count(); ++i) {
280                 if (cb->itemText(i) == fontname) {
281                         cb->setCurrentIndex(i);
282                         return;
283                 }
284         }
285
286         // Try matching without foundry name
287
288         // We count in reverse in order to prefer the Xft foundry
289         for (int i = cb->count(); --i >= 0;) {
290                 string name, foundry;
291                 parseFontName(cb->itemText(i), name, foundry);
292                 if (compare_ascii_no_case(name, family) == 0) {
293                         cb->setCurrentIndex(i);
294                         return;
295                 }
296         }
297
298         // family alone can contain e.g. "Helvetica [Adobe]"
299         string tmpname, tmpfoundry;
300         parseFontName(toqstr(family), tmpname, tmpfoundry);
301
302         // We count in reverse in order to prefer the Xft foundry
303         for (int i = cb->count(); --i >= 0; ) {
304                 string name, foundry;
305                 parseFontName(cb->itemText(i), name, foundry);
306                 if (compare_ascii_no_case(name, foundry) == 0) {
307                         cb->setCurrentIndex(i);
308                         return;
309                 }
310         }
311
312         // Bleh, default fonts, and the names couldn't be found. Hack
313         // for bug 1063.
314
315         QFont font;
316         font.setKerning(false);
317
318         QString const font_family = toqstr(family);
319         if (font_family == guiApp->romanFontName()) {
320                 font.setStyleHint(QFont::Serif);
321                 font.setFamily(font_family);
322         } else if (font_family == guiApp->sansFontName()) {
323                 font.setStyleHint(QFont::SansSerif);
324                 font.setFamily(font_family);
325         } else if (font_family == guiApp->typewriterFontName()) {
326                 font.setStyleHint(QFont::TypeWriter);
327                 font.setFamily(font_family);
328         } else {
329                 LYXERR0("FAILED to find the default font: '"
330                        << foundry << "', '" << family << '\'');
331                 return;
332         }
333
334         QFontInfo info(font);
335         string default_font_name, dummyfoundry;
336         parseFontName(info.family(), default_font_name, dummyfoundry);
337         LYXERR0("Apparent font is " << default_font_name);
338
339         for (int i = 0; i < cb->count(); ++i) {
340                 LYXERR0("Looking at " << cb->itemText(i));
341                 if (compare_ascii_no_case(fromqstr(cb->itemText(i)),
342                                     default_font_name) == 0) {
343                         cb->setCurrentIndex(i);
344                         return;
345                 }
346         }
347
348         LYXERR0("FAILED to find the font: '"
349                << foundry << "', '" << family << '\'');
350 }
351
352
353 /////////////////////////////////////////////////////////////////////
354 //
355 // StrftimeValidator
356 //
357 /////////////////////////////////////////////////////////////////////
358
359 class StrftimeValidator : public QValidator
360 {
361 public:
362         StrftimeValidator(QWidget *);
363         QValidator::State validate(QString & input, int & pos) const;
364 };
365
366
367 StrftimeValidator::StrftimeValidator(QWidget * parent)
368         : QValidator(parent)
369 {
370 }
371
372
373 QValidator::State StrftimeValidator::validate(QString & input, int & /*pos*/) const
374 {
375         if (is_valid_strftime(fromqstr(input)))
376                 return QValidator::Acceptable;
377         else
378                 return QValidator::Intermediate;
379 }
380
381
382 /////////////////////////////////////////////////////////////////////
383 //
384 // PrefOutput
385 //
386 /////////////////////////////////////////////////////////////////////
387
388 PrefOutput::PrefOutput(GuiPreferences * form)
389         : PrefModule(qt_(catOutput), qt_("General"), form)
390 {
391         setupUi(this);
392
393         DateED->setValidator(new StrftimeValidator(DateED));
394         dviCB->setValidator(new NoNewLineValidator(dviCB));
395         pdfCB->setValidator(new NoNewLineValidator(pdfCB));
396
397         connect(DateED, SIGNAL(textChanged(QString)),
398                 this, SIGNAL(changed()));
399         connect(plaintextLinelengthSB, SIGNAL(valueChanged(int)),
400                 this, SIGNAL(changed()));
401         connect(overwriteCO, SIGNAL(activated(int)),
402                 this, SIGNAL(changed()));
403         connect(dviCB, SIGNAL(editTextChanged(QString)),
404                 this, SIGNAL(changed()));
405         connect(pdfCB, SIGNAL(editTextChanged(QString)),
406                 this, SIGNAL(changed()));
407         dviCB->addItem("");
408         dviCB->addItem("xdvi -sourceposition '$$n:\\ $$t' $$o");
409         dviCB->addItem("yap -1 -s \"$$n $$t\" $$o");
410         dviCB->addItem("okular --unique \"file:$$o#src:$$n $$t\"");
411         dviCB->addItem("synctex view -i $$n:0:$$t -o $$o -x \"evince -i %{page+1} $$o\"");
412         pdfCB->addItem("");
413         pdfCB->addItem("CMCDDE SUMATRA control [ForwardSearch(\\\"$$o\\\",\\\"$$t\\\",$$n,0,0,1)]");
414         pdfCB->addItem("SumatraPDF -reuse-instance $$o -forward-search $$t $$n");
415         pdfCB->addItem("synctex view -i $$n:0:$$t -o $$o -x \"xpdf -raise -remote $$t.tmp $$o %{page+1}\"");
416         pdfCB->addItem("okular --unique \"file:$$o#src:$$n $$t\"");
417         pdfCB->addItem("synctex view -i $$n:0:$$t -o $$o -x \"evince -i %{page+1} $$o\"");
418         pdfCB->addItem("/Applications/Skim.app/Contents/SharedSupport/displayline $$n $$o $$t");
419 }
420
421
422 void PrefOutput::on_DateED_textChanged(const QString &)
423 {
424         QString t = DateED->text();
425         int p = 0;
426         bool valid = DateED->validator()->validate(t, p)
427                      == QValidator::Acceptable;
428         setValid(DateLA, valid);
429 }
430
431
432 void PrefOutput::apply(LyXRC & rc) const
433 {
434         rc.date_insert_format = fromqstr(DateED->text());
435         rc.plaintext_linelen = plaintextLinelengthSB->value();
436         rc.forward_search_dvi = fromqstr(dviCB->currentText());
437         rc.forward_search_pdf = fromqstr(pdfCB->currentText());
438
439         switch (overwriteCO->currentIndex()) {
440         case 0:
441                 rc.export_overwrite = NO_FILES;
442                 break;
443         case 1:
444                 rc.export_overwrite = MAIN_FILE;
445                 break;
446         case 2:
447                 rc.export_overwrite = ALL_FILES;
448                 break;
449         }
450 }
451
452
453 void PrefOutput::update(LyXRC const & rc)
454 {
455         DateED->setText(toqstr(rc.date_insert_format));
456         plaintextLinelengthSB->setValue(rc.plaintext_linelen);
457         dviCB->setEditText(toqstr(rc.forward_search_dvi));
458         pdfCB->setEditText(toqstr(rc.forward_search_pdf));
459
460         switch (rc.export_overwrite) {
461         case NO_FILES:
462                 overwriteCO->setCurrentIndex(0);
463                 break;
464         case MAIN_FILE:
465                 overwriteCO->setCurrentIndex(1);
466                 break;
467         case ALL_FILES:
468                 overwriteCO->setCurrentIndex(2);
469                 break;
470         }
471 }
472
473
474 /////////////////////////////////////////////////////////////////////
475 //
476 // PrefInput
477 //
478 /////////////////////////////////////////////////////////////////////
479
480 PrefInput::PrefInput(GuiPreferences * form)
481         : PrefModule(qt_(catEditing), qt_("Keyboard/Mouse"), form)
482 {
483         setupUi(this);
484
485         connect(keymapCB, SIGNAL(clicked()),
486                 this, SIGNAL(changed()));
487         connect(firstKeymapED, SIGNAL(textChanged(QString)),
488                 this, SIGNAL(changed()));
489         connect(secondKeymapED, SIGNAL(textChanged(QString)),
490                 this, SIGNAL(changed()));
491         connect(mouseWheelSpeedSB, SIGNAL(valueChanged(double)),
492                 this, SIGNAL(changed()));
493         connect(scrollzoomEnableCB, SIGNAL(clicked()),
494                 this, SIGNAL(changed()));
495         connect(scrollzoomValueCO, SIGNAL(activated(int)),
496                 this, SIGNAL(changed()));
497         connect(dontswapCB, SIGNAL(toggled(bool)),
498                 this, SIGNAL(changed()));
499
500         // reveal checkbox for switching Ctrl and Meta on Mac:
501         bool swapcb = false;
502 #ifdef Q_WS_MACX
503 #if QT_VERSION > 0x040600
504         swapcb = true;
505 #endif
506 #endif
507         dontswapCB->setVisible(swapcb);
508 }
509
510
511 void PrefInput::apply(LyXRC & rc) const
512 {
513         // FIXME: can derive CB from the two EDs
514         rc.use_kbmap = keymapCB->isChecked();
515         rc.primary_kbmap = internal_path(fromqstr(firstKeymapED->text()));
516         rc.secondary_kbmap = internal_path(fromqstr(secondKeymapED->text()));
517         rc.mouse_wheel_speed = mouseWheelSpeedSB->value();
518         if (scrollzoomEnableCB->isChecked()) {
519                 switch (scrollzoomValueCO->currentIndex()) {
520                 case 0:
521                         rc.scroll_wheel_zoom = LyXRC::SCROLL_WHEEL_ZOOM_CTRL;
522                         break;
523                 case 1:
524                         rc.scroll_wheel_zoom = LyXRC::SCROLL_WHEEL_ZOOM_SHIFT;
525                         break;
526                 case 2:
527                         rc.scroll_wheel_zoom = LyXRC::SCROLL_WHEEL_ZOOM_ALT;
528                         break;
529                 }
530         } else {
531                 rc.scroll_wheel_zoom = LyXRC::SCROLL_WHEEL_ZOOM_OFF;
532         }
533         rc.mac_dontswap_ctrl_meta  = dontswapCB->isChecked();
534 }
535
536
537 void PrefInput::update(LyXRC const & rc)
538 {
539         // FIXME: can derive CB from the two EDs
540         keymapCB->setChecked(rc.use_kbmap);
541         firstKeymapED->setText(toqstr(external_path(rc.primary_kbmap)));
542         secondKeymapED->setText(toqstr(external_path(rc.secondary_kbmap)));
543         mouseWheelSpeedSB->setValue(rc.mouse_wheel_speed);
544         switch (rc.scroll_wheel_zoom) {
545         case LyXRC::SCROLL_WHEEL_ZOOM_OFF:
546                 scrollzoomEnableCB->setChecked(false);
547                 break;
548         case LyXRC::SCROLL_WHEEL_ZOOM_CTRL:
549                 scrollzoomEnableCB->setChecked(true);
550                 scrollzoomValueCO->setCurrentIndex(0);
551                 break;
552         case LyXRC::SCROLL_WHEEL_ZOOM_SHIFT:
553                 scrollzoomEnableCB->setChecked(true);
554                 scrollzoomValueCO->setCurrentIndex(1);
555                 break;
556         case LyXRC::SCROLL_WHEEL_ZOOM_ALT:
557                 scrollzoomEnableCB->setChecked(true);
558                 scrollzoomValueCO->setCurrentIndex(2);
559                 break;
560         }
561         dontswapCB->setChecked(rc.mac_dontswap_ctrl_meta);
562 }
563
564
565 QString PrefInput::testKeymap(QString const & keymap)
566 {
567         return form_->browsekbmap(internalPath(keymap));
568 }
569
570
571 void PrefInput::on_firstKeymapPB_clicked(bool)
572 {
573         QString const file = testKeymap(firstKeymapED->text());
574         if (!file.isEmpty())
575                 firstKeymapED->setText(file);
576 }
577
578
579 void PrefInput::on_secondKeymapPB_clicked(bool)
580 {
581         QString const file = testKeymap(secondKeymapED->text());
582         if (!file.isEmpty())
583                 secondKeymapED->setText(file);
584 }
585
586
587 void PrefInput::on_keymapCB_toggled(bool keymap)
588 {
589         firstKeymapLA->setEnabled(keymap);
590         secondKeymapLA->setEnabled(keymap);
591         firstKeymapED->setEnabled(keymap);
592         secondKeymapED->setEnabled(keymap);
593         firstKeymapPB->setEnabled(keymap);
594         secondKeymapPB->setEnabled(keymap);
595 }
596
597
598 void PrefInput::on_scrollzoomEnableCB_toggled(bool enabled)
599 {
600         scrollzoomValueCO->setEnabled(enabled);
601 }
602         
603         
604 /////////////////////////////////////////////////////////////////////
605 //
606 // PrefCompletion
607 //
608 /////////////////////////////////////////////////////////////////////
609
610 PrefCompletion::PrefCompletion(GuiPreferences * form)
611         : PrefModule(qt_(catEditing), qt_("Input Completion"), form)
612 {
613         setupUi(this);
614
615         connect(inlineDelaySB, SIGNAL(valueChanged(double)),
616                 this, SIGNAL(changed()));
617         connect(inlineMathCB, SIGNAL(clicked()),
618                 this, SIGNAL(changed()));
619         connect(inlineTextCB, SIGNAL(clicked()),
620                 this, SIGNAL(changed()));
621         connect(inlineDotsCB, SIGNAL(clicked()),
622                 this, SIGNAL(changed()));
623         connect(popupDelaySB, SIGNAL(valueChanged(double)),
624                 this, SIGNAL(changed()));
625         connect(popupMathCB, SIGNAL(clicked()),
626                 this, SIGNAL(changed()));
627         connect(autocorrectionCB, SIGNAL(clicked()),
628                 this, SIGNAL(changed()));
629         connect(popupTextCB, SIGNAL(clicked()),
630                 this, SIGNAL(changed()));
631         connect(popupAfterCompleteCB, SIGNAL(clicked()),
632                 this, SIGNAL(changed()));
633         connect(cursorTextCB, SIGNAL(clicked()),
634                 this, SIGNAL(changed()));
635         connect(minlengthSB, SIGNAL(valueChanged(int)),
636                         this, SIGNAL(changed()));
637 }
638
639
640 void PrefCompletion::on_inlineTextCB_clicked()
641 {
642         enableCB();
643 }
644
645
646 void PrefCompletion::on_popupTextCB_clicked()
647 {
648         enableCB();
649 }
650
651
652 void PrefCompletion::enableCB()
653 {
654         cursorTextCB->setEnabled(
655                 popupTextCB->isChecked() || inlineTextCB->isChecked());
656 }
657
658
659 void PrefCompletion::apply(LyXRC & rc) const
660 {
661         rc.completion_inline_delay = inlineDelaySB->value();
662         rc.completion_inline_math = inlineMathCB->isChecked();
663         rc.completion_inline_text = inlineTextCB->isChecked();
664         rc.completion_inline_dots = inlineDotsCB->isChecked() ? 13 : -1;
665         rc.completion_popup_delay = popupDelaySB->value();
666         rc.completion_popup_math = popupMathCB->isChecked();
667         rc.autocorrection_math = autocorrectionCB->isChecked();
668         rc.completion_popup_text = popupTextCB->isChecked();
669         rc.completion_cursor_text = cursorTextCB->isChecked();
670         rc.completion_popup_after_complete =
671                 popupAfterCompleteCB->isChecked();
672         rc.completion_minlength = minlengthSB->value();
673 }
674
675
676 void PrefCompletion::update(LyXRC const & rc)
677 {
678         inlineDelaySB->setValue(rc.completion_inline_delay);
679         inlineMathCB->setChecked(rc.completion_inline_math);
680         inlineTextCB->setChecked(rc.completion_inline_text);
681         inlineDotsCB->setChecked(rc.completion_inline_dots != -1);
682         popupDelaySB->setValue(rc.completion_popup_delay);
683         popupMathCB->setChecked(rc.completion_popup_math);
684         autocorrectionCB->setChecked(rc.autocorrection_math);
685         popupTextCB->setChecked(rc.completion_popup_text);
686         cursorTextCB->setChecked(rc.completion_cursor_text);
687         popupAfterCompleteCB->setChecked(rc.completion_popup_after_complete);
688         enableCB();
689         minlengthSB->setValue(rc.completion_minlength);
690 }
691
692
693
694 /////////////////////////////////////////////////////////////////////
695 //
696 // PrefLatex
697 //
698 /////////////////////////////////////////////////////////////////////
699
700 PrefLatex::PrefLatex(GuiPreferences * form)
701         : PrefModule(qt_(catOutput), qt_("LaTeX"), form)
702 {
703         setupUi(this);
704
705         latexEncodingED->setValidator(new NoNewLineValidator(latexEncodingED));
706         latexDviPaperED->setValidator(new NoNewLineValidator(latexDviPaperED));
707         latexBibtexED->setValidator(new NoNewLineValidator(latexBibtexED));
708         latexJBibtexED->setValidator(new NoNewLineValidator(latexJBibtexED));
709         latexIndexED->setValidator(new NoNewLineValidator(latexIndexED));
710         latexJIndexED->setValidator(new NoNewLineValidator(latexJIndexED));
711         latexNomenclED->setValidator(new NoNewLineValidator(latexNomenclED));
712         latexChecktexED->setValidator(new NoNewLineValidator(latexChecktexED));
713
714         connect(latexEncodingCB, SIGNAL(clicked()),
715                 this, SIGNAL(changed()));
716         connect(latexEncodingED, SIGNAL(textChanged(QString)),
717                 this, SIGNAL(changed()));
718         connect(latexChecktexED, SIGNAL(textChanged(QString)),
719                 this, SIGNAL(changed()));
720         connect(latexBibtexCO, SIGNAL(activated(int)),
721                 this, SIGNAL(changed()));
722         connect(latexBibtexED, SIGNAL(textChanged(QString)),
723                 this, SIGNAL(changed()));
724         connect(latexJBibtexED, SIGNAL(textChanged(QString)),
725                 this, SIGNAL(changed()));
726         connect(latexIndexCO, SIGNAL(activated(int)),
727                 this, SIGNAL(changed()));
728         connect(latexIndexED, SIGNAL(textChanged(QString)),
729                 this, SIGNAL(changed()));
730         connect(latexJIndexED, SIGNAL(textChanged(QString)),
731                 this, SIGNAL(changed()));
732         connect(latexAutoresetCB, SIGNAL(clicked()),
733                 this, SIGNAL(changed()));
734         connect(latexDviPaperED, SIGNAL(textChanged(QString)),
735                 this, SIGNAL(changed()));
736         connect(latexNomenclED, SIGNAL(textChanged(QString)),
737                 this, SIGNAL(changed()));
738
739 #if defined(__CYGWIN__) || defined(_WIN32)
740         pathCB->setVisible(true);
741         connect(pathCB, SIGNAL(clicked()),
742                 this, SIGNAL(changed()));
743 #else
744         pathCB->setVisible(false);
745 #endif
746 }
747
748
749 void PrefLatex::on_latexEncodingCB_stateChanged(int state)
750 {
751         latexEncodingED->setEnabled(state == Qt::Checked);
752 }
753
754
755 void PrefLatex::on_latexBibtexCO_activated(int n)
756 {
757         QString const bibtex = latexBibtexCO->itemData(n).toString();
758         if (bibtex.isEmpty()) {
759                 latexBibtexED->clear();
760                 latexBibtexOptionsLA->setText(qt_("Co&mmand:"));
761                 return;
762         }
763         for (LyXRC::CommandSet::const_iterator it = bibtex_alternatives.begin();
764              it != bibtex_alternatives.end(); ++it) {
765                 QString const bib = toqstr(*it);
766                 int ind = bib.indexOf(" ");
767                 QString sel_command = bib.left(ind);
768                 QString sel_options = ind < 0 ? QString() : bib.mid(ind + 1);
769                 if (bibtex == sel_command) {
770                         if (ind < 0)
771                                 latexBibtexED->clear();
772                         else
773                                 latexBibtexED->setText(sel_options.trimmed());
774                 }
775         }
776         latexBibtexOptionsLA->setText(qt_("&Options:"));
777 }
778
779
780 void PrefLatex::on_latexIndexCO_activated(int n)
781 {
782         QString const index = latexIndexCO->itemData(n).toString();
783         if (index.isEmpty()) {
784                 latexIndexED->clear();
785                 latexIndexOptionsLA->setText(qt_("Co&mmand:"));
786                 return;
787         }
788         for (LyXRC::CommandSet::const_iterator it = index_alternatives.begin();
789              it != index_alternatives.end(); ++it) {
790                 QString const idx = toqstr(*it);
791                 int ind = idx.indexOf(" ");
792                 QString sel_command = idx.left(ind);
793                 QString sel_options = ind < 0 ? QString() : idx.mid(ind + 1);
794                 if (index == sel_command) {
795                         if (ind < 0)
796                                 latexIndexED->clear();
797                         else
798                                 latexIndexED->setText(sel_options.trimmed());
799                 }
800         }
801         latexIndexOptionsLA->setText(qt_("Op&tions:"));
802 }
803
804
805 void PrefLatex::apply(LyXRC & rc) const
806 {
807         // If bibtex is not empty, bibopt contains the options, otherwise
808         // it is a customized bibtex command with options.
809         QString const bibtex = latexBibtexCO->itemData(
810                 latexBibtexCO->currentIndex()).toString();
811         QString const bibopt = latexBibtexED->text();
812         if (bibtex.isEmpty())
813                 rc.bibtex_command = fromqstr(bibopt);
814         else if (bibopt.isEmpty())
815                 rc.bibtex_command = fromqstr(bibtex);
816         else
817                 rc.bibtex_command = fromqstr(bibtex) + " " + fromqstr(bibopt);
818
819         // If index is not empty, idxopt contains the options, otherwise
820         // it is a customized index command with options.
821         QString const index = latexIndexCO->itemData(
822                 latexIndexCO->currentIndex()).toString();
823         QString const idxopt = latexIndexED->text();
824         if (index.isEmpty())
825                 rc.index_command = fromqstr(idxopt);
826         else if (idxopt.isEmpty())
827                 rc.index_command = fromqstr(index);
828         else
829                 rc.index_command = fromqstr(index) + " " + fromqstr(idxopt);
830
831         if (latexEncodingCB->isChecked())
832                 rc.fontenc = fromqstr(latexEncodingED->text());
833         else
834                 rc.fontenc = "default";
835         rc.chktex_command = fromqstr(latexChecktexED->text());
836         rc.jbibtex_command = fromqstr(latexJBibtexED->text());
837         rc.jindex_command = fromqstr(latexJIndexED->text());
838         rc.nomencl_command = fromqstr(latexNomenclED->text());
839         rc.auto_reset_options = latexAutoresetCB->isChecked();
840         rc.view_dvi_paper_option = fromqstr(latexDviPaperED->text());
841 #if defined(__CYGWIN__) || defined(_WIN32)
842         rc.windows_style_tex_paths = pathCB->isChecked();
843 #endif
844 }
845
846
847 void PrefLatex::update(LyXRC const & rc)
848 {
849         latexBibtexCO->clear();
850
851         latexBibtexCO->addItem(qt_("Custom"), QString());
852         for (LyXRC::CommandSet::const_iterator it = rc.bibtex_alternatives.begin();
853                              it != rc.bibtex_alternatives.end(); ++it) {
854                 QString const command = toqstr(*it).left(toqstr(*it).indexOf(" "));
855                 latexBibtexCO->addItem(command, command);
856         }
857
858         bibtex_alternatives = rc.bibtex_alternatives;
859
860         QString const bib = toqstr(rc.bibtex_command);
861         int ind = bib.indexOf(" ");
862         QString sel_command = bib.left(ind);
863         QString sel_options = ind < 0 ? QString() : bib.mid(ind + 1);
864
865         int pos = latexBibtexCO->findData(sel_command);
866         if (pos != -1) {
867                 latexBibtexCO->setCurrentIndex(pos);
868                 latexBibtexED->setText(sel_options.trimmed());
869                 latexBibtexOptionsLA->setText(qt_("&Options:"));
870         } else {
871                 latexBibtexED->setText(toqstr(rc.bibtex_command));
872                 latexBibtexCO->setCurrentIndex(0);
873                 latexBibtexOptionsLA->setText(qt_("Co&mmand:"));
874         }
875
876         latexIndexCO->clear();
877
878         latexIndexCO->addItem(qt_("Custom"), QString());
879         for (LyXRC::CommandSet::const_iterator it = rc.index_alternatives.begin();
880                              it != rc.index_alternatives.end(); ++it) {
881                 QString const command = toqstr(*it).left(toqstr(*it).indexOf(" "));
882                 latexIndexCO->addItem(command, command);
883         }
884
885         index_alternatives = rc.index_alternatives;
886
887         QString const idx = toqstr(rc.index_command);
888         ind = idx.indexOf(" ");
889         sel_command = idx.left(ind);
890         sel_options = ind < 0 ? QString() : idx.mid(ind + 1);
891
892         pos = latexIndexCO->findData(sel_command);
893         if (pos != -1) {
894                 latexIndexCO->setCurrentIndex(pos);
895                 latexIndexED->setText(sel_options.trimmed());
896                 latexIndexOptionsLA->setText(qt_("Op&tions:"));
897         } else {
898                 latexIndexED->setText(toqstr(rc.index_command));
899                 latexIndexCO->setCurrentIndex(0);
900                 latexIndexOptionsLA->setText(qt_("Co&mmand:"));
901         }
902
903         if (rc.fontenc == "default") {
904                 latexEncodingCB->setChecked(false);
905                 latexEncodingED->setEnabled(false);
906         } else {
907                 latexEncodingCB->setChecked(true);
908                 latexEncodingED->setEnabled(true);
909                 latexEncodingED->setText(toqstr(rc.fontenc));
910         }
911         latexChecktexED->setText(toqstr(rc.chktex_command));
912         latexJBibtexED->setText(toqstr(rc.jbibtex_command));
913         latexJIndexED->setText(toqstr(rc.jindex_command));
914         latexNomenclED->setText(toqstr(rc.nomencl_command));
915         latexAutoresetCB->setChecked(rc.auto_reset_options);
916         latexDviPaperED->setText(toqstr(rc.view_dvi_paper_option));
917 #if defined(__CYGWIN__) || defined(_WIN32)
918         pathCB->setChecked(rc.windows_style_tex_paths);
919 #endif
920 }
921
922
923 /////////////////////////////////////////////////////////////////////
924 //
925 // PrefScreenFonts
926 //
927 /////////////////////////////////////////////////////////////////////
928
929 PrefScreenFonts::PrefScreenFonts(GuiPreferences * form)
930         : PrefModule(qt_(catLookAndFeel), qt_("Screen Fonts"), form)
931 {
932         setupUi(this);
933
934         connect(screenRomanCO, SIGNAL(activated(QString)),
935                 this, SLOT(selectRoman(QString)));
936         connect(screenSansCO, SIGNAL(activated(QString)),
937                 this, SLOT(selectSans(QString)));
938         connect(screenTypewriterCO, SIGNAL(activated(QString)),
939                 this, SLOT(selectTypewriter(QString)));
940
941         QFontDatabase fontdb;
942         QStringList families(fontdb.families());
943         for (QStringList::Iterator it = families.begin(); it != families.end(); ++it) {
944                 screenRomanCO->addItem(*it);
945                 screenSansCO->addItem(*it);
946                 screenTypewriterCO->addItem(*it);
947         }
948         connect(screenRomanCO, SIGNAL(activated(QString)),
949                 this, SIGNAL(changed()));
950         connect(screenSansCO, SIGNAL(activated(QString)),
951                 this, SIGNAL(changed()));
952         connect(screenTypewriterCO, SIGNAL(activated(QString)),
953                 this, SIGNAL(changed()));
954         connect(screenZoomSB, SIGNAL(valueChanged(int)),
955                 this, SIGNAL(changed()));
956         connect(screenTinyED, SIGNAL(textChanged(QString)),
957                 this, SIGNAL(changed()));
958         connect(screenSmallestED, SIGNAL(textChanged(QString)),
959                 this, SIGNAL(changed()));
960         connect(screenSmallerED, SIGNAL(textChanged(QString)),
961                 this, SIGNAL(changed()));
962         connect(screenSmallED, SIGNAL(textChanged(QString)),
963                 this, SIGNAL(changed()));
964         connect(screenNormalED, SIGNAL(textChanged(QString)),
965                 this, SIGNAL(changed()));
966         connect(screenLargeED, SIGNAL(textChanged(QString)),
967                 this, SIGNAL(changed()));
968         connect(screenLargerED, SIGNAL(textChanged(QString)),
969                 this, SIGNAL(changed()));
970         connect(screenLargestED, SIGNAL(textChanged(QString)),
971                 this, SIGNAL(changed()));
972         connect(screenHugeED, SIGNAL(textChanged(QString)),
973                 this, SIGNAL(changed()));
974         connect(screenHugerED, SIGNAL(textChanged(QString)),
975                 this, SIGNAL(changed()));
976         connect(pixmapCacheCB, SIGNAL(toggled(bool)),
977                 this, SIGNAL(changed()));
978
979         screenTinyED->setValidator(new QDoubleValidator(screenTinyED));
980         screenSmallestED->setValidator(new QDoubleValidator(screenSmallestED));
981         screenSmallerED->setValidator(new QDoubleValidator(screenSmallerED));
982         screenSmallED->setValidator(new QDoubleValidator(screenSmallED));
983         screenNormalED->setValidator(new QDoubleValidator(screenNormalED));
984         screenLargeED->setValidator(new QDoubleValidator(screenLargeED));
985         screenLargerED->setValidator(new QDoubleValidator(screenLargerED));
986         screenLargestED->setValidator(new QDoubleValidator(screenLargestED));
987         screenHugeED->setValidator(new QDoubleValidator(screenHugeED));
988         screenHugerED->setValidator(new QDoubleValidator(screenHugerED));
989 }
990
991
992 void PrefScreenFonts::apply(LyXRC & rc) const
993 {
994         LyXRC const oldrc = rc;
995
996         parseFontName(screenRomanCO->currentText(),
997                 rc.roman_font_name, rc.roman_font_foundry);
998         parseFontName(screenSansCO->currentText(),
999                 rc.sans_font_name, rc.sans_font_foundry);
1000         parseFontName(screenTypewriterCO->currentText(),
1001                 rc.typewriter_font_name, rc.typewriter_font_foundry);
1002
1003         rc.zoom = screenZoomSB->value();
1004         rc.font_sizes[FONT_SIZE_TINY] = widgetToDoubleStr(screenTinyED);
1005         rc.font_sizes[FONT_SIZE_SCRIPT] = widgetToDoubleStr(screenSmallestED);
1006         rc.font_sizes[FONT_SIZE_FOOTNOTE] = widgetToDoubleStr(screenSmallerED);
1007         rc.font_sizes[FONT_SIZE_SMALL] = widgetToDoubleStr(screenSmallED);
1008         rc.font_sizes[FONT_SIZE_NORMAL] = widgetToDoubleStr(screenNormalED);
1009         rc.font_sizes[FONT_SIZE_LARGE] = widgetToDoubleStr(screenLargeED);
1010         rc.font_sizes[FONT_SIZE_LARGER] = widgetToDoubleStr(screenLargerED);
1011         rc.font_sizes[FONT_SIZE_LARGEST] = widgetToDoubleStr(screenLargestED);
1012         rc.font_sizes[FONT_SIZE_HUGE] = widgetToDoubleStr(screenHugeED);
1013         rc.font_sizes[FONT_SIZE_HUGER] = widgetToDoubleStr(screenHugerED);
1014         rc.use_pixmap_cache = pixmapCacheCB->isChecked();
1015
1016         if (rc.font_sizes != oldrc.font_sizes
1017                 || rc.roman_font_name != oldrc.roman_font_name
1018                 || rc.sans_font_name != oldrc.sans_font_name
1019                 || rc.typewriter_font_name != oldrc.typewriter_font_name
1020                 || rc.zoom != oldrc.zoom) {
1021                 // The global QPixmapCache is used in GuiPainter to cache text
1022                 // painting so we must reset it in case any of the above
1023                 // parameter is changed.
1024                 QPixmapCache::clear();
1025                 guiApp->fontLoader().update();
1026                 form_->updateScreenFonts();
1027         }
1028 }
1029
1030
1031 void PrefScreenFonts::update(LyXRC const & rc)
1032 {
1033         setComboxFont(screenRomanCO, rc.roman_font_name,
1034                         rc.roman_font_foundry);
1035         setComboxFont(screenSansCO, rc.sans_font_name,
1036                         rc.sans_font_foundry);
1037         setComboxFont(screenTypewriterCO, rc.typewriter_font_name,
1038                         rc.typewriter_font_foundry);
1039
1040         selectRoman(screenRomanCO->currentText());
1041         selectSans(screenSansCO->currentText());
1042         selectTypewriter(screenTypewriterCO->currentText());
1043
1044         screenZoomSB->setValue(rc.zoom);
1045         updateScreenFontSizes(rc);
1046
1047         pixmapCacheCB->setChecked(rc.use_pixmap_cache);
1048 #if defined(Q_WS_X11)
1049         pixmapCacheCB->setEnabled(false);
1050 #endif
1051
1052 }
1053
1054
1055 void PrefScreenFonts::updateScreenFontSizes(LyXRC const & rc)
1056 {
1057         doubleToWidget(screenTinyED, rc.font_sizes[FONT_SIZE_TINY]);
1058         doubleToWidget(screenSmallestED, rc.font_sizes[FONT_SIZE_SCRIPT]);
1059         doubleToWidget(screenSmallerED, rc.font_sizes[FONT_SIZE_FOOTNOTE]);
1060         doubleToWidget(screenSmallED, rc.font_sizes[FONT_SIZE_SMALL]);
1061         doubleToWidget(screenNormalED, rc.font_sizes[FONT_SIZE_NORMAL]);
1062         doubleToWidget(screenLargeED, rc.font_sizes[FONT_SIZE_LARGE]);
1063         doubleToWidget(screenLargerED, rc.font_sizes[FONT_SIZE_LARGER]);
1064         doubleToWidget(screenLargestED, rc.font_sizes[FONT_SIZE_LARGEST]);
1065         doubleToWidget(screenHugeED, rc.font_sizes[FONT_SIZE_HUGE]);
1066         doubleToWidget(screenHugerED, rc.font_sizes[FONT_SIZE_HUGER]);
1067 }
1068
1069
1070 void PrefScreenFonts::selectRoman(const QString & name)
1071 {
1072         screenRomanFE->set(QFont(name), name);
1073 }
1074
1075
1076 void PrefScreenFonts::selectSans(const QString & name)
1077 {
1078         screenSansFE->set(QFont(name), name);
1079 }
1080
1081
1082 void PrefScreenFonts::selectTypewriter(const QString & name)
1083 {
1084         screenTypewriterFE->set(QFont(name), name);
1085 }
1086
1087
1088 /////////////////////////////////////////////////////////////////////
1089 //
1090 // PrefColors
1091 //
1092 /////////////////////////////////////////////////////////////////////
1093
1094 namespace {
1095
1096 struct ColorSorter
1097 {
1098         bool operator()(ColorCode lhs, ColorCode rhs) const {
1099                 return 
1100                         compare_no_case(lcolor.getGUIName(lhs), lcolor.getGUIName(rhs)) < 0;
1101         }
1102 };
1103
1104 } // namespace anon
1105
1106 PrefColors::PrefColors(GuiPreferences * form)
1107         : PrefModule(qt_(catLookAndFeel), qt_("Colors"), form)
1108 {
1109         setupUi(this);
1110
1111         // FIXME: all of this initialization should be put into the controller.
1112         // See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg113301.html
1113         // for some discussion of why that is not trivial.
1114         QPixmap icon(32, 32);
1115         for (int i = 0; i < Color_ignore; ++i) {
1116                 ColorCode lc = static_cast<ColorCode>(i);
1117                 if (lc == Color_none
1118                     || lc == Color_black
1119                     || lc == Color_white
1120                     || lc == Color_red
1121                     || lc == Color_green
1122                     || lc == Color_blue
1123                     || lc == Color_cyan
1124                     || lc == Color_magenta
1125                     || lc == Color_yellow
1126                     || lc == Color_inherit
1127                     || lc == Color_ignore)
1128                         continue;
1129                 lcolors_.push_back(lc);
1130         }
1131         sort(lcolors_.begin(), lcolors_.end(), ColorSorter());
1132         vector<ColorCode>::const_iterator cit = lcolors_.begin();
1133         vector<ColorCode>::const_iterator const end = lcolors_.end();
1134         for (; cit != end; ++cit) {
1135                 (void) new QListWidgetItem(QIcon(icon),
1136                         toqstr(lcolor.getGUIName(*cit)), lyxObjectsLW);
1137         }
1138         curcolors_.resize(lcolors_.size());
1139         newcolors_.resize(lcolors_.size());
1140         // End initialization
1141
1142         connect(colorChangePB, SIGNAL(clicked()),
1143                 this, SLOT(changeColor()));
1144         connect(lyxObjectsLW, SIGNAL(itemSelectionChanged()),
1145                 this, SLOT(changeLyxObjectsSelection()));
1146         connect(lyxObjectsLW, SIGNAL(itemActivated(QListWidgetItem*)),
1147                 this, SLOT(changeColor()));
1148         connect(syscolorsCB, SIGNAL(toggled(bool)),
1149                 this, SIGNAL(changed()));
1150         connect(syscolorsCB, SIGNAL(toggled(bool)),
1151                 this, SLOT(changeSysColor()));
1152 }
1153
1154
1155 void PrefColors::apply(LyXRC & rc) const
1156 {
1157         LyXRC oldrc = rc;
1158
1159         for (unsigned int i = 0; i < lcolors_.size(); ++i)
1160                 if (curcolors_[i] != newcolors_[i])
1161                         form_->setColor(lcolors_[i], newcolors_[i]);
1162         rc.use_system_colors = syscolorsCB->isChecked();
1163
1164         if (oldrc.use_system_colors != rc.use_system_colors)
1165                 guiApp->colorCache().clear();
1166 }
1167
1168
1169 void PrefColors::update(LyXRC const & rc)
1170 {
1171         for (unsigned int i = 0; i < lcolors_.size(); ++i) {
1172                 QColor color = QColor(guiApp->colorCache().get(lcolors_[i], false));
1173                 QPixmap coloritem(32, 32);
1174                 coloritem.fill(color);
1175                 lyxObjectsLW->item(i)->setIcon(QIcon(coloritem));
1176                 newcolors_[i] = curcolors_[i] = color.name();
1177         }
1178         syscolorsCB->setChecked(rc.use_system_colors);
1179         changeLyxObjectsSelection();
1180 }
1181
1182
1183 void PrefColors::changeColor()
1184 {
1185         int const row = lyxObjectsLW->currentRow();
1186
1187         // just to be sure
1188         if (row < 0)
1189                 return;
1190
1191         QString const color = newcolors_[row];
1192         QColor c = QColorDialog::getColor(QColor(color), qApp->focusWidget());
1193
1194         if (c.isValid() && c.name() != color) {
1195                 newcolors_[row] = c.name();
1196                 QPixmap coloritem(32, 32);
1197                 coloritem.fill(c);
1198                 lyxObjectsLW->currentItem()->setIcon(QIcon(coloritem));
1199                 // emit signal
1200                 changed();
1201         }
1202 }
1203
1204 void PrefColors::changeSysColor()
1205 {
1206         for (int row = 0 ; row < lyxObjectsLW->count() ; ++row) {
1207                 // skip colors that are taken from system palette
1208                 bool const hide = syscolorsCB->isChecked()
1209                         && guiApp->colorCache().isSystem(lcolors_[row]);
1210
1211                 lyxObjectsLW->item(row)->setHidden(hide);
1212         }
1213
1214 }
1215
1216 void PrefColors::changeLyxObjectsSelection()
1217 {
1218         colorChangePB->setDisabled(lyxObjectsLW->currentRow() < 0);
1219 }
1220
1221
1222 /////////////////////////////////////////////////////////////////////
1223 //
1224 // PrefDisplay
1225 //
1226 /////////////////////////////////////////////////////////////////////
1227
1228 PrefDisplay::PrefDisplay(GuiPreferences * form)
1229         : PrefModule(qt_(catLookAndFeel), qt_("Display"), form)
1230 {
1231         setupUi(this);
1232         connect(displayGraphicsCB, SIGNAL(toggled(bool)), this, SIGNAL(changed()));
1233         connect(instantPreviewCO, SIGNAL(activated(int)), this, SIGNAL(changed()));
1234         connect(previewSizeSB, SIGNAL(valueChanged(double)), this, SIGNAL(changed()));
1235         connect(paragraphMarkerCB, SIGNAL(toggled(bool)), this, SIGNAL(changed()));
1236 }
1237
1238
1239 void PrefDisplay::on_instantPreviewCO_currentIndexChanged(int index)
1240 {
1241         previewSizeSB->setEnabled(index != 0);
1242 }
1243
1244
1245 void PrefDisplay::on_displayGraphicsCB_toggled(bool on)
1246 {
1247         instantPreviewCO->setEnabled(on);
1248         previewSizeSB->setEnabled(on && instantPreviewCO->currentIndex() > 0);
1249 }
1250
1251
1252 void PrefDisplay::apply(LyXRC & rc) const
1253 {
1254         switch (instantPreviewCO->currentIndex()) {
1255                 case 0:
1256                         rc.preview = LyXRC::PREVIEW_OFF;
1257                         break;
1258                 case 1:
1259                         rc.preview = LyXRC::PREVIEW_NO_MATH;
1260                         break;
1261                 case 2:
1262                         rc.preview = LyXRC::PREVIEW_ON;
1263                         break;
1264         }
1265
1266         rc.display_graphics = displayGraphicsCB->isChecked();
1267         rc.preview_scale_factor = previewSizeSB->value();
1268         rc.paragraph_markers = paragraphMarkerCB->isChecked();
1269
1270         // FIXME!! The graphics cache no longer has a changeDisplay method.
1271 #if 0
1272         if (old_value != rc.display_graphics) {
1273                 graphics::GCache & gc = graphics::GCache::get();
1274                 gc.changeDisplay();
1275         }
1276 #endif
1277 }
1278
1279
1280 void PrefDisplay::update(LyXRC const & rc)
1281 {
1282         switch (rc.preview) {
1283         case LyXRC::PREVIEW_OFF:
1284                 instantPreviewCO->setCurrentIndex(0);
1285                 break;
1286         case LyXRC::PREVIEW_NO_MATH :
1287                 instantPreviewCO->setCurrentIndex(1);
1288                 break;
1289         case LyXRC::PREVIEW_ON :
1290                 instantPreviewCO->setCurrentIndex(2);
1291                 break;
1292         }
1293
1294         displayGraphicsCB->setChecked(rc.display_graphics);
1295         instantPreviewCO->setEnabled(rc.display_graphics);
1296         previewSizeSB->setValue(rc.preview_scale_factor);
1297         paragraphMarkerCB->setChecked(rc.paragraph_markers);
1298         previewSizeSB->setEnabled(
1299                 rc.display_graphics
1300                 && rc.preview != LyXRC::PREVIEW_OFF);
1301 }
1302
1303
1304 /////////////////////////////////////////////////////////////////////
1305 //
1306 // PrefPaths
1307 //
1308 /////////////////////////////////////////////////////////////////////
1309
1310 PrefPaths::PrefPaths(GuiPreferences * form)
1311         : PrefModule(QString(), qt_("Paths"), form)
1312 {
1313         setupUi(this);
1314
1315         connect(workingDirPB, SIGNAL(clicked()), this, SLOT(selectWorkingdir()));
1316         connect(workingDirED, SIGNAL(textChanged(QString)),
1317                 this, SIGNAL(changed()));
1318
1319         connect(templateDirPB, SIGNAL(clicked()), this, SLOT(selectTemplatedir()));
1320         connect(templateDirED, SIGNAL(textChanged(QString)),
1321                 this, SIGNAL(changed()));
1322
1323         connect(exampleDirPB, SIGNAL(clicked()), this, SLOT(selectExampledir()));
1324         connect(exampleDirED, SIGNAL(textChanged(QString)),
1325                 this, SIGNAL(changed()));
1326
1327         connect(backupDirPB, SIGNAL(clicked()), this, SLOT(selectBackupdir()));
1328         connect(backupDirED, SIGNAL(textChanged(QString)),
1329                 this, SIGNAL(changed()));
1330
1331         connect(lyxserverDirPB, SIGNAL(clicked()), this, SLOT(selectLyxPipe()));
1332         connect(lyxserverDirED, SIGNAL(textChanged(QString)),
1333                 this, SIGNAL(changed()));
1334
1335         connect(thesaurusDirPB, SIGNAL(clicked()), this, SLOT(selectThesaurusdir()));
1336         connect(thesaurusDirED, SIGNAL(textChanged(QString)),
1337                 this, SIGNAL(changed()));
1338
1339         connect(tempDirPB, SIGNAL(clicked()), this, SLOT(selectTempdir()));
1340         connect(tempDirED, SIGNAL(textChanged(QString)),
1341                 this, SIGNAL(changed()));
1342
1343 #if defined(USE_HUNSPELL)
1344         connect(hunspellDirPB, SIGNAL(clicked()), this, SLOT(selectHunspelldir()));
1345         connect(hunspellDirED, SIGNAL(textChanged(QString)),
1346                 this, SIGNAL(changed()));
1347 #else
1348         hunspellDirPB->setEnabled(false);
1349         hunspellDirED->setEnabled(false);
1350 #endif
1351
1352         connect(pathPrefixED, SIGNAL(textChanged(QString)),
1353                 this, SIGNAL(changed()));
1354
1355         connect(texinputsPrefixED, SIGNAL(textChanged(QString)),
1356                 this, SIGNAL(changed()));
1357
1358         pathPrefixED->setValidator(new NoNewLineValidator(pathPrefixED));
1359         texinputsPrefixED->setValidator(new NoNewLineValidator(texinputsPrefixED));
1360 }
1361
1362
1363 void PrefPaths::apply(LyXRC & rc) const
1364 {
1365         rc.document_path = internal_path(fromqstr(workingDirED->text()));
1366         rc.example_path = internal_path(fromqstr(exampleDirED->text()));
1367         rc.template_path = internal_path(fromqstr(templateDirED->text()));
1368         rc.backupdir_path = internal_path(fromqstr(backupDirED->text()));
1369         rc.tempdir_path = internal_path(fromqstr(tempDirED->text()));
1370         rc.thesaurusdir_path = internal_path(fromqstr(thesaurusDirED->text()));
1371         rc.hunspelldir_path = internal_path(fromqstr(hunspellDirED->text()));
1372         rc.path_prefix = internal_path_list(fromqstr(pathPrefixED->text()));
1373         rc.texinputs_prefix = internal_path_list(fromqstr(texinputsPrefixED->text()));
1374         // FIXME: should be a checkbox only
1375         rc.lyxpipes = internal_path(fromqstr(lyxserverDirED->text()));
1376 }
1377
1378
1379 void PrefPaths::update(LyXRC const & rc)
1380 {
1381         workingDirED->setText(toqstr(external_path(rc.document_path)));
1382         exampleDirED->setText(toqstr(external_path(rc.example_path)));
1383         templateDirED->setText(toqstr(external_path(rc.template_path)));
1384         backupDirED->setText(toqstr(external_path(rc.backupdir_path)));
1385         tempDirED->setText(toqstr(external_path(rc.tempdir_path)));
1386         thesaurusDirED->setText(toqstr(external_path(rc.thesaurusdir_path)));
1387         hunspellDirED->setText(toqstr(external_path(rc.hunspelldir_path)));
1388         pathPrefixED->setText(toqstr(external_path_list(rc.path_prefix)));
1389         texinputsPrefixED->setText(toqstr(external_path_list(rc.texinputs_prefix)));
1390         // FIXME: should be a checkbox only
1391         lyxserverDirED->setText(toqstr(external_path(rc.lyxpipes)));
1392 }
1393
1394
1395 void PrefPaths::selectExampledir()
1396 {
1397         QString file = browseDir(internalPath(exampleDirED->text()),
1398                 qt_("Select directory for example files"));
1399         if (!file.isEmpty())
1400                 exampleDirED->setText(file);
1401 }
1402
1403
1404 void PrefPaths::selectTemplatedir()
1405 {
1406         QString file = browseDir(internalPath(templateDirED->text()),
1407                 qt_("Select a document templates directory"));
1408         if (!file.isEmpty())
1409                 templateDirED->setText(file);
1410 }
1411
1412
1413 void PrefPaths::selectTempdir()
1414 {
1415         QString file = browseDir(internalPath(tempDirED->text()),
1416                 qt_("Select a temporary directory"));
1417         if (!file.isEmpty())
1418                 tempDirED->setText(file);
1419 }
1420
1421
1422 void PrefPaths::selectBackupdir()
1423 {
1424         QString file = browseDir(internalPath(backupDirED->text()),
1425                 qt_("Select a backups directory"));
1426         if (!file.isEmpty())
1427                 backupDirED->setText(file);
1428 }
1429
1430
1431 void PrefPaths::selectWorkingdir()
1432 {
1433         QString file = browseDir(internalPath(workingDirED->text()),
1434                 qt_("Select a document directory"));
1435         if (!file.isEmpty())
1436                 workingDirED->setText(file);
1437 }
1438
1439
1440 void PrefPaths::selectThesaurusdir()
1441 {
1442         QString file = browseDir(internalPath(thesaurusDirED->text()),
1443                 qt_("Set the path to the thesaurus dictionaries"));
1444         if (!file.isEmpty())
1445                 thesaurusDirED->setText(file);
1446 }
1447
1448
1449 void PrefPaths::selectHunspelldir()
1450 {
1451         QString file = browseDir(internalPath(hunspellDirED->text()),
1452                 qt_("Set the path to the Hunspell dictionaries"));
1453         if (!file.isEmpty())
1454                 hunspellDirED->setText(file);
1455 }
1456
1457
1458 void PrefPaths::selectLyxPipe()
1459 {
1460         QString file = form_->browse(internalPath(lyxserverDirED->text()),
1461                 qt_("Give a filename for the LyX server pipe"));
1462         if (!file.isEmpty())
1463                 lyxserverDirED->setText(file);
1464 }
1465
1466
1467 /////////////////////////////////////////////////////////////////////
1468 //
1469 // PrefSpellchecker
1470 //
1471 /////////////////////////////////////////////////////////////////////
1472
1473 PrefSpellchecker::PrefSpellchecker(GuiPreferences * form)
1474         : PrefModule(qt_(catLanguage), qt_("Spellchecker"), form)
1475 {
1476         setupUi(this);
1477
1478 // FIXME: this check should test the target platform (darwin)
1479 #if defined(USE_MACOSX_PACKAGING)
1480         spellcheckerCB->addItem(qt_("Native"), QString("native"));
1481 #define CONNECT_APPLESPELL
1482 #else
1483 #undef CONNECT_APPLESPELL
1484 #endif
1485 #if defined(USE_ASPELL)
1486         spellcheckerCB->addItem(qt_("Aspell"), QString("aspell"));
1487 #endif
1488 #if defined(USE_ENCHANT)
1489         spellcheckerCB->addItem(qt_("Enchant"), QString("enchant"));
1490 #endif
1491 #if defined(USE_HUNSPELL)
1492         spellcheckerCB->addItem(qt_("Hunspell"), QString("hunspell"));
1493 #endif
1494
1495         #if defined(CONNECT_APPLESPELL) || defined(USE_ASPELL) || defined(USE_ENCHANT) || defined(USE_HUNSPELL)
1496                 connect(spellcheckerCB, SIGNAL(currentIndexChanged(int)),
1497                         this, SIGNAL(changed()));
1498                 connect(altLanguageED, SIGNAL(textChanged(QString)),
1499                         this, SIGNAL(changed()));
1500                 connect(escapeCharactersED, SIGNAL(textChanged(QString)),
1501                         this, SIGNAL(changed()));
1502                 connect(compoundWordCB, SIGNAL(clicked()),
1503                         this, SIGNAL(changed()));
1504                 connect(spellcheckContinuouslyCB, SIGNAL(clicked()),
1505                         this, SIGNAL(changed()));
1506                 connect(spellcheckNotesCB, SIGNAL(clicked()),
1507                         this, SIGNAL(changed()));
1508
1509                 altLanguageED->setValidator(new NoNewLineValidator(altLanguageED));
1510                 escapeCharactersED->setValidator(new NoNewLineValidator(escapeCharactersED));
1511         #else
1512                 spellcheckerCB->setEnabled(false);
1513                 altLanguageED->setEnabled(false);
1514                 escapeCharactersED->setEnabled(false);
1515                 compoundWordCB->setEnabled(false);
1516                 spellcheckContinuouslyCB->setEnabled(false);
1517                 spellcheckNotesCB->setEnabled(false);
1518         #endif
1519 }
1520
1521
1522 void PrefSpellchecker::apply(LyXRC & rc) const
1523 {
1524         string const speller = fromqstr(spellcheckerCB->
1525                 itemData(spellcheckerCB->currentIndex()).toString());
1526         if (!speller.empty())
1527                 rc.spellchecker = speller;
1528         rc.spellchecker_alt_lang = fromqstr(altLanguageED->text());
1529         rc.spellchecker_esc_chars = fromqstr(escapeCharactersED->text());
1530         rc.spellchecker_accept_compound = compoundWordCB->isChecked();
1531         rc.spellcheck_continuously = spellcheckContinuouslyCB->isChecked();
1532         rc.spellcheck_notes = spellcheckNotesCB->isChecked();
1533 }
1534
1535
1536 void PrefSpellchecker::update(LyXRC const & rc)
1537 {
1538         spellcheckerCB->setCurrentIndex(
1539                 spellcheckerCB->findData(toqstr(rc.spellchecker)));
1540         altLanguageED->setText(toqstr(rc.spellchecker_alt_lang));
1541         escapeCharactersED->setText(toqstr(rc.spellchecker_esc_chars));
1542         compoundWordCB->setChecked(rc.spellchecker_accept_compound);
1543         spellcheckContinuouslyCB->setChecked(rc.spellcheck_continuously);
1544         spellcheckNotesCB->setChecked(rc.spellcheck_notes);
1545 }
1546
1547
1548 void PrefSpellchecker::on_spellcheckerCB_currentIndexChanged(int index)
1549 {
1550         QString spellchecker = spellcheckerCB->itemData(index).toString();
1551         
1552         compoundWordCB->setEnabled(spellchecker == QString("aspell"));
1553 }
1554         
1555         
1556         
1557 /////////////////////////////////////////////////////////////////////
1558 //
1559 // PrefConverters
1560 //
1561 /////////////////////////////////////////////////////////////////////
1562
1563
1564 PrefConverters::PrefConverters(GuiPreferences * form)
1565         : PrefModule(qt_(catFiles), qt_("Converters"), form)
1566 {
1567         setupUi(this);
1568
1569         connect(converterNewPB, SIGNAL(clicked()),
1570                 this, SLOT(updateConverter()));
1571         connect(converterRemovePB, SIGNAL(clicked()),
1572                 this, SLOT(removeConverter()));
1573         connect(converterModifyPB, SIGNAL(clicked()),
1574                 this, SLOT(updateConverter()));
1575         connect(convertersLW, SIGNAL(currentRowChanged(int)),
1576                 this, SLOT(switchConverter()));
1577         connect(converterFromCO, SIGNAL(activated(QString)),
1578                 this, SLOT(changeConverter()));
1579         connect(converterToCO, SIGNAL(activated(QString)),
1580                 this, SLOT(changeConverter()));
1581         connect(converterED, SIGNAL(textEdited(QString)),
1582                 this, SLOT(changeConverter()));
1583         connect(converterFlagED, SIGNAL(textEdited(QString)),
1584                 this, SLOT(changeConverter()));
1585         connect(converterNewPB, SIGNAL(clicked()),
1586                 this, SIGNAL(changed()));
1587         connect(converterRemovePB, SIGNAL(clicked()),
1588                 this, SIGNAL(changed()));
1589         connect(converterModifyPB, SIGNAL(clicked()),
1590                 this, SIGNAL(changed()));
1591         connect(maxAgeLE, SIGNAL(textEdited(QString)),
1592                 this, SIGNAL(changed()));
1593
1594         converterED->setValidator(new NoNewLineValidator(converterED));
1595         converterFlagED->setValidator(new NoNewLineValidator(converterFlagED));
1596         maxAgeLE->setValidator(new QDoubleValidator(maxAgeLE));
1597         //converterDefGB->setFocusProxy(convertersLW);
1598 }
1599
1600
1601 void PrefConverters::apply(LyXRC & rc) const
1602 {
1603         rc.use_converter_cache = cacheCB->isChecked();
1604         rc.converter_cache_maxage = int(widgetToDouble(maxAgeLE) * 86400.0);
1605 }
1606
1607
1608 void PrefConverters::update(LyXRC const & rc)
1609 {
1610         cacheCB->setChecked(rc.use_converter_cache);
1611         QString max_age;
1612         doubleToWidget(maxAgeLE, (double(rc.converter_cache_maxage) / 86400.0), 'g', 6);
1613         updateGui();
1614 }
1615
1616
1617 void PrefConverters::updateGui()
1618 {
1619         form_->formats().sort();
1620         form_->converters().update(form_->formats());
1621         // save current selection
1622         QString current = converterFromCO->currentText()
1623                 + " -> " + converterToCO->currentText();
1624
1625         converterFromCO->clear();
1626         converterToCO->clear();
1627
1628         Formats::const_iterator cit = form_->formats().begin();
1629         Formats::const_iterator end = form_->formats().end();
1630         for (; cit != end; ++cit) {
1631                 converterFromCO->addItem(qt_(cit->prettyname()));
1632                 converterToCO->addItem(qt_(cit->prettyname()));
1633         }
1634
1635         // currentRowChanged(int) is also triggered when updating the listwidget
1636         // block signals to avoid unnecessary calls to switchConverter()
1637         convertersLW->blockSignals(true);
1638         convertersLW->clear();
1639
1640         Converters::const_iterator ccit = form_->converters().begin();
1641         Converters::const_iterator cend = form_->converters().end();
1642         for (; ccit != cend; ++ccit) {
1643                 QString const name =
1644                         qt_(ccit->From->prettyname()) + " -> " + qt_(ccit->To->prettyname());
1645                 int type = form_->converters().getNumber(ccit->From->name(), ccit->To->name());
1646                 new QListWidgetItem(name, convertersLW, type);
1647         }
1648         convertersLW->sortItems(Qt::AscendingOrder);
1649         convertersLW->blockSignals(false);
1650
1651         // restore selection
1652         if (!current.isEmpty()) {
1653                 QList<QListWidgetItem *> const item =
1654                         convertersLW->findItems(current, Qt::MatchExactly);
1655                 if (!item.isEmpty())
1656                         convertersLW->setCurrentItem(item.at(0));
1657         }
1658
1659         // select first element if restoring failed
1660         if (convertersLW->currentRow() == -1)
1661                 convertersLW->setCurrentRow(0);
1662
1663         updateButtons();
1664 }
1665
1666
1667 void PrefConverters::switchConverter()
1668 {
1669         int const cnr = convertersLW->currentItem()->type();
1670         Converter const & c(form_->converters().get(cnr));
1671         converterFromCO->setCurrentIndex(form_->formats().getNumber(c.from));
1672         converterToCO->setCurrentIndex(form_->formats().getNumber(c.to));
1673         converterED->setText(toqstr(c.command));
1674         converterFlagED->setText(toqstr(c.flags));
1675
1676         updateButtons();
1677 }
1678
1679
1680 void PrefConverters::changeConverter()
1681 {
1682         updateButtons();
1683 }
1684
1685
1686 void PrefConverters::updateButtons()
1687 {
1688         if (form_->formats().size() == 0)
1689                 return;
1690         Format const & from = form_->formats().get(converterFromCO->currentIndex());
1691         Format const & to = form_->formats().get(converterToCO->currentIndex());
1692         int const sel = form_->converters().getNumber(from.name(), to.name());
1693         bool const known = sel >= 0;
1694         bool const valid = !(converterED->text().isEmpty()
1695                 || from.name() == to.name());
1696
1697         int const cnr = convertersLW->currentItem()->type();
1698         Converter const & c = form_->converters().get(cnr);
1699         string const old_command = c.command;
1700         string const old_flag = c.flags;
1701         string const new_command = fromqstr(converterED->text());
1702         string const new_flag = fromqstr(converterFlagED->text());
1703
1704         bool modified = (old_command != new_command || old_flag != new_flag);
1705
1706         converterModifyPB->setEnabled(valid && known && modified);
1707         converterNewPB->setEnabled(valid && !known);
1708         converterRemovePB->setEnabled(known);
1709
1710         maxAgeLE->setEnabled(cacheCB->isChecked());
1711         maxAgeLA->setEnabled(cacheCB->isChecked());
1712 }
1713
1714
1715 // FIXME: user must
1716 // specify unique from/to or it doesn't appear. This is really bad UI
1717 // this is why we can use the same function for both new and modify
1718 void PrefConverters::updateConverter()
1719 {
1720         Format const & from = form_->formats().get(converterFromCO->currentIndex());
1721         Format const & to = form_->formats().get(converterToCO->currentIndex());
1722         string const flags = fromqstr(converterFlagED->text());
1723         string const command = fromqstr(converterED->text());
1724
1725         Converter const * old =
1726                 form_->converters().getConverter(from.name(), to.name());
1727         form_->converters().add(from.name(), to.name(), command, flags);
1728
1729         if (!old)
1730                 form_->converters().updateLast(form_->formats());
1731
1732         updateGui();
1733
1734         // Remove all files created by this converter from the cache, since
1735         // the modified converter might create different files.
1736         ConverterCache::get().remove_all(from.name(), to.name());
1737 }
1738
1739
1740 void PrefConverters::removeConverter()
1741 {
1742         Format const & from = form_->formats().get(converterFromCO->currentIndex());
1743         Format const & to = form_->formats().get(converterToCO->currentIndex());
1744         form_->converters().erase(from.name(), to.name());
1745
1746         updateGui();
1747
1748         // Remove all files created by this converter from the cache, since
1749         // a possible new converter might create different files.
1750         ConverterCache::get().remove_all(from.name(), to.name());
1751 }
1752
1753
1754 void PrefConverters::on_cacheCB_stateChanged(int state)
1755 {
1756         maxAgeLE->setEnabled(state == Qt::Checked);
1757         maxAgeLA->setEnabled(state == Qt::Checked);
1758         changed();
1759 }
1760
1761
1762 /////////////////////////////////////////////////////////////////////
1763 //
1764 // FormatValidator
1765 //
1766 /////////////////////////////////////////////////////////////////////
1767
1768 class FormatValidator : public QValidator
1769 {
1770 public:
1771         FormatValidator(QWidget *, Formats const & f);
1772         void fixup(QString & input) const;
1773         QValidator::State validate(QString & input, int & pos) const;
1774 private:
1775         virtual QString toString(Format const & format) const = 0;
1776         int nr() const;
1777         Formats const & formats_;
1778 };
1779
1780
1781 FormatValidator::FormatValidator(QWidget * parent, Formats const & f)
1782         : QValidator(parent), formats_(f)
1783 {
1784 }
1785
1786
1787 void FormatValidator::fixup(QString & input) const
1788 {
1789         Formats::const_iterator cit = formats_.begin();
1790         Formats::const_iterator end = formats_.end();
1791         for (; cit != end; ++cit) {
1792                 QString const name = toString(*cit);
1793                 if (distance(formats_.begin(), cit) == nr()) {
1794                         input = name;
1795                         return;
1796                 }
1797         }
1798 }
1799
1800
1801 QValidator::State FormatValidator::validate(QString & input, int & /*pos*/) const
1802 {
1803         Formats::const_iterator cit = formats_.begin();
1804         Formats::const_iterator end = formats_.end();
1805         bool unknown = true;
1806         for (; unknown && cit != end; ++cit) {
1807                 QString const name = toString(*cit);
1808                 if (distance(formats_.begin(), cit) != nr())
1809                         unknown = name != input;
1810         }
1811
1812         if (unknown && !input.isEmpty())
1813                 return QValidator::Acceptable;
1814         else
1815                 return QValidator::Intermediate;
1816 }
1817
1818
1819 int FormatValidator::nr() const
1820 {
1821         QComboBox * p = qobject_cast<QComboBox *>(parent());
1822         return p->itemData(p->currentIndex()).toInt();
1823 }
1824
1825
1826 /////////////////////////////////////////////////////////////////////
1827 //
1828 // FormatNameValidator
1829 //
1830 /////////////////////////////////////////////////////////////////////
1831
1832 class FormatNameValidator : public FormatValidator
1833 {
1834 public:
1835         FormatNameValidator(QWidget * parent, Formats const & f)
1836                 : FormatValidator(parent, f)
1837         {}
1838 private:
1839         QString toString(Format const & format) const
1840         {
1841                 return toqstr(format.name());
1842         }
1843 };
1844
1845
1846 /////////////////////////////////////////////////////////////////////
1847 //
1848 // FormatPrettynameValidator
1849 //
1850 /////////////////////////////////////////////////////////////////////
1851
1852 class FormatPrettynameValidator : public FormatValidator
1853 {
1854 public:
1855         FormatPrettynameValidator(QWidget * parent, Formats const & f)
1856                 : FormatValidator(parent, f)
1857         {}
1858 private:
1859         QString toString(Format const & format) const
1860         {
1861                 return qt_(format.prettyname());
1862         }
1863 };
1864
1865
1866 /////////////////////////////////////////////////////////////////////
1867 //
1868 // PrefFileformats
1869 //
1870 /////////////////////////////////////////////////////////////////////
1871
1872 PrefFileformats::PrefFileformats(GuiPreferences * form)
1873         : PrefModule(qt_(catFiles), qt_("File Formats"), form)
1874 {
1875         setupUi(this);
1876
1877         formatED->setValidator(new FormatNameValidator(formatsCB, form_->formats()));
1878         formatsCB->setValidator(new FormatPrettynameValidator(formatsCB, form_->formats()));
1879         extensionsED->setValidator(new NoNewLineValidator(extensionsED));
1880         shortcutED->setValidator(new NoNewLineValidator(shortcutED));
1881         editorED->setValidator(new NoNewLineValidator(editorED));
1882         viewerED->setValidator(new NoNewLineValidator(viewerED));
1883         copierED->setValidator(new NoNewLineValidator(copierED));
1884
1885         connect(documentCB, SIGNAL(clicked()),
1886                 this, SLOT(setFlags()));
1887         connect(vectorCB, SIGNAL(clicked()),
1888                 this, SLOT(setFlags()));
1889         connect(exportMenuCB, SIGNAL(clicked()),
1890                 this, SLOT(setFlags()));
1891         connect(formatsCB->lineEdit(), SIGNAL(editingFinished()),
1892                 this, SLOT(updatePrettyname()));
1893         connect(formatsCB->lineEdit(), SIGNAL(textEdited(QString)),
1894                 this, SIGNAL(changed()));
1895         connect(defaultFormatCB, SIGNAL(activated(QString)),
1896                 this, SIGNAL(changed()));
1897         connect(viewerCO, SIGNAL(activated(int)),
1898                 this, SIGNAL(changed()));
1899         connect(editorCO, SIGNAL(activated(int)),
1900                 this, SIGNAL(changed()));
1901 }
1902
1903
1904 namespace {
1905
1906 string const l10n_shortcut(string const prettyname, string const shortcut)
1907 {
1908         if (shortcut.empty())
1909                 return string();
1910
1911         string l10n_format =
1912                 to_utf8(_(prettyname + '|' + shortcut));
1913         return split(l10n_format, '|');
1914 }
1915
1916 } // namespace anon
1917
1918
1919 void PrefFileformats::apply(LyXRC & rc) const
1920 {
1921         QString const default_format = defaultFormatCB->itemData(
1922                 defaultFormatCB->currentIndex()).toString();
1923         rc.default_view_format = fromqstr(default_format);
1924 }
1925
1926
1927 void PrefFileformats::update(LyXRC const & rc)
1928 {
1929         viewer_alternatives = rc.viewer_alternatives;
1930         editor_alternatives = rc.editor_alternatives;
1931         bool const init = defaultFormatCB->currentText().isEmpty();
1932         updateView();
1933         if (init) {
1934                 int const pos =
1935                         defaultFormatCB->findData(toqstr(rc.default_view_format));
1936                 defaultFormatCB->setCurrentIndex(pos);
1937         }
1938 }
1939
1940
1941 void PrefFileformats::updateView()
1942 {
1943         QString const current = formatsCB->currentText();
1944         QString const current_def = defaultFormatCB->currentText();
1945
1946         // update comboboxes with formats
1947         formatsCB->blockSignals(true);
1948         defaultFormatCB->blockSignals(true);
1949         formatsCB->clear();
1950         defaultFormatCB->clear();
1951         form_->formats().sort();
1952         Formats::const_iterator cit = form_->formats().begin();
1953         Formats::const_iterator end = form_->formats().end();
1954         for (; cit != end; ++cit) {
1955                 formatsCB->addItem(qt_(cit->prettyname()),
1956                                 QVariant(form_->formats().getNumber(cit->name())));
1957                 if (form_->converters().isReachable("latex", cit->name())
1958                     || form_->converters().isReachable("dviluatex", cit->name())
1959                     || form_->converters().isReachable("pdflatex", cit->name())
1960                     || form_->converters().isReachable("luatex", cit->name())
1961                     || form_->converters().isReachable("xetex", cit->name()))
1962                         defaultFormatCB->addItem(qt_(cit->prettyname()),
1963                                         QVariant(toqstr(cit->name())));
1964         }
1965
1966         // restore selection
1967         int item = formatsCB->findText(current, Qt::MatchExactly);
1968         formatsCB->setCurrentIndex(item < 0 ? 0 : item);
1969         on_formatsCB_currentIndexChanged(item < 0 ? 0 : item);
1970         item = defaultFormatCB->findText(current_def, Qt::MatchExactly);
1971         defaultFormatCB->setCurrentIndex(item < 0 ? 0 : item);
1972         formatsCB->blockSignals(false);
1973         defaultFormatCB->blockSignals(false);
1974 }
1975
1976
1977 void PrefFileformats::on_formatsCB_currentIndexChanged(int i)
1978 {
1979         if (form_->formats().size() == 0)
1980                 return;
1981         int const nr = formatsCB->itemData(i).toInt();
1982         Format const f = form_->formats().get(nr);
1983
1984         formatED->setText(toqstr(f.name()));
1985         copierED->setText(toqstr(form_->movers().command(f.name())));
1986         extensionsED->setText(toqstr(f.extensions()));
1987         mimeED->setText(toqstr(f.mime()));
1988         shortcutED->setText(
1989                 toqstr(l10n_shortcut(f.prettyname(), f.shortcut())));
1990         documentCB->setChecked((f.documentFormat()));
1991         vectorCB->setChecked((f.vectorFormat()));
1992         exportMenuCB->setChecked((f.inExportMenu()));
1993         exportMenuCB->setEnabled((f.documentFormat()));
1994         updateViewers();
1995         updateEditors();
1996 }
1997
1998
1999 void PrefFileformats::setFlags()
2000 {
2001         int flags = Format::none;
2002         if (documentCB->isChecked())
2003                 flags |= Format::document;
2004         if (vectorCB->isChecked())
2005                 flags |= Format::vector;
2006         if (exportMenuCB->isChecked())
2007                 flags |= Format::export_menu;
2008         currentFormat().setFlags(flags);
2009         exportMenuCB->setEnabled(documentCB->isChecked());
2010         changed();
2011 }
2012
2013
2014 void PrefFileformats::on_copierED_textEdited(const QString & s)
2015 {
2016         string const fmt = fromqstr(formatED->text());
2017         form_->movers().set(fmt, fromqstr(s));
2018         changed();
2019 }
2020
2021
2022 void PrefFileformats::on_extensionsED_textEdited(const QString & s)
2023 {
2024         currentFormat().setExtensions(fromqstr(s));
2025         changed();
2026 }
2027
2028
2029 void PrefFileformats::on_viewerED_textEdited(const QString & s)
2030 {
2031         currentFormat().setViewer(fromqstr(s));
2032         changed();
2033 }
2034
2035
2036 void PrefFileformats::on_editorED_textEdited(const QString & s)
2037 {
2038         currentFormat().setEditor(fromqstr(s));
2039         changed();
2040 }
2041
2042
2043 void PrefFileformats::on_mimeED_textEdited(const QString & s)
2044 {
2045         currentFormat().setMime(fromqstr(s));
2046         changed();
2047 }
2048
2049
2050 void PrefFileformats::on_shortcutED_textEdited(const QString & s)
2051 {
2052         string const new_shortcut = fromqstr(s);
2053         if (new_shortcut == l10n_shortcut(currentFormat().prettyname(),
2054                                           currentFormat().shortcut()))
2055                 return;
2056         currentFormat().setShortcut(new_shortcut);
2057         changed();
2058 }
2059
2060
2061 void PrefFileformats::on_formatED_editingFinished()
2062 {
2063         string const newname = fromqstr(formatED->displayText());
2064         string const oldname = currentFormat().name();
2065         if (newname == oldname)
2066                 return;
2067         if (form_->converters().formatIsUsed(oldname)) {
2068                 Alert::error(_("Format in use"),
2069                              _("You cannot change a format's short name "
2070                                "if the format is used by a converter. "
2071                                "Please remove the converter first."));
2072                 updateView();
2073                 return;
2074         }
2075
2076         currentFormat().setName(newname);
2077         changed();
2078 }
2079
2080
2081 void PrefFileformats::on_formatED_textChanged(const QString &)
2082 {
2083         QString t = formatED->text();
2084         int p = 0;
2085         bool valid = formatED->validator()->validate(t, p) == QValidator::Acceptable;
2086         setValid(formatLA, valid);
2087 }
2088
2089
2090 void PrefFileformats::on_formatsCB_editTextChanged(const QString &)
2091 {
2092         QString t = formatsCB->currentText();
2093         int p = 0;
2094         bool valid = formatsCB->validator()->validate(t, p) == QValidator::Acceptable;
2095         setValid(formatsLA, valid);
2096 }
2097
2098
2099 void PrefFileformats::updatePrettyname()
2100 {
2101         QString const newname = formatsCB->currentText();
2102         if (newname == qt_(currentFormat().prettyname()))
2103                 return;
2104
2105         currentFormat().setPrettyname(fromqstr(newname));
2106         formatsChanged();
2107         updateView();
2108         changed();
2109 }
2110
2111
2112 namespace {
2113         void updateComboBox(LyXRC::Alternatives const & alts,
2114                             string const & fmt, QComboBox * combo)
2115         {
2116                 LyXRC::Alternatives::const_iterator it = 
2117                                 alts.find(fmt);
2118                 if (it != alts.end()) {
2119                         LyXRC::CommandSet const & cmds = it->second;
2120                         LyXRC::CommandSet::const_iterator sit = 
2121                                         cmds.begin();
2122                         LyXRC::CommandSet::const_iterator const sen = 
2123                                         cmds.end();
2124                         for (; sit != sen; ++sit) {
2125                                 QString const qcmd = toqstr(*sit);
2126                                 combo->addItem(qcmd, qcmd);
2127                         }
2128                 }
2129         }
2130 }
2131
2132
2133 void PrefFileformats::updateViewers()
2134 {
2135         Format const f = currentFormat();
2136         viewerCO->blockSignals(true);
2137         viewerCO->clear();
2138         viewerCO->addItem(qt_("None"), QString());
2139         updateComboBox(viewer_alternatives, f.name(), viewerCO);
2140         viewerCO->addItem(qt_("Custom"), QString("custom viewer"));
2141         viewerCO->blockSignals(false);
2142
2143         int pos = viewerCO->findData(toqstr(f.viewer()));
2144         if (pos != -1) {
2145                 viewerED->clear();
2146                 viewerED->setEnabled(false);
2147                 viewerCO->setCurrentIndex(pos);
2148         } else {
2149                 viewerED->setEnabled(true);
2150                 viewerED->setText(toqstr(f.viewer()));
2151                 viewerCO->setCurrentIndex(viewerCO->findData(toqstr("custom viewer")));
2152         }
2153 }
2154
2155
2156 void PrefFileformats::updateEditors()
2157 {
2158         Format const f = currentFormat();
2159         editorCO->blockSignals(true);
2160         editorCO->clear();
2161         editorCO->addItem(qt_("None"), QString());
2162         updateComboBox(editor_alternatives, f.name(), editorCO);
2163         editorCO->addItem(qt_("Custom"), QString("custom editor"));
2164         editorCO->blockSignals(false);
2165
2166         int pos = editorCO->findData(toqstr(f.editor()));
2167         if (pos != -1) {
2168                 editorED->clear();
2169                 editorED->setEnabled(false);
2170                 editorCO->setCurrentIndex(pos);
2171         } else {
2172                 editorED->setEnabled(true);
2173                 editorED->setText(toqstr(f.editor()));
2174                 editorCO->setCurrentIndex(editorCO->findData(toqstr("custom editor")));
2175         }
2176 }
2177
2178
2179 void PrefFileformats::on_viewerCO_currentIndexChanged(int i)
2180 {
2181         bool const custom = viewerCO->itemData(i).toString() == "custom viewer";
2182         viewerED->setEnabled(custom);
2183         if (!custom)
2184                 currentFormat().setViewer(fromqstr(viewerCO->itemData(i).toString()));
2185 }
2186
2187
2188 void PrefFileformats::on_editorCO_currentIndexChanged(int i)
2189 {
2190         bool const custom = editorCO->itemData(i).toString() == "custom editor";
2191         editorED->setEnabled(custom);
2192         if (!custom)
2193                 currentFormat().setEditor(fromqstr(editorCO->itemData(i).toString()));
2194 }
2195
2196
2197 Format & PrefFileformats::currentFormat()
2198 {
2199         int const i = formatsCB->currentIndex();
2200         int const nr = formatsCB->itemData(i).toInt();
2201         return form_->formats().get(nr);
2202 }
2203
2204
2205 void PrefFileformats::on_formatNewPB_clicked()
2206 {
2207         form_->formats().add("", "", "", "", "", "", "", Format::none);
2208         updateView();
2209         formatsCB->setCurrentIndex(0);
2210         formatsCB->setFocus(Qt::OtherFocusReason);
2211 }
2212
2213
2214 void PrefFileformats::on_formatRemovePB_clicked()
2215 {
2216         int const i = formatsCB->currentIndex();
2217         int const nr = formatsCB->itemData(i).toInt();
2218         string const current_text = form_->formats().get(nr).name();
2219         if (form_->converters().formatIsUsed(current_text)) {
2220                 Alert::error(_("Format in use"),
2221                              _("Cannot remove a Format used by a Converter. "
2222                                             "Remove the converter first."));
2223                 return;
2224         }
2225
2226         form_->formats().erase(current_text);
2227         formatsChanged();
2228         updateView();
2229         on_formatsCB_editTextChanged(formatsCB->currentText());
2230         changed();
2231 }
2232
2233
2234 /////////////////////////////////////////////////////////////////////
2235 //
2236 // PrefLanguage
2237 //
2238 /////////////////////////////////////////////////////////////////////
2239
2240 PrefLanguage::PrefLanguage(GuiPreferences * form)
2241         : PrefModule(qt_(catLanguage), qt_("Language"), form)
2242 {
2243         setupUi(this);
2244
2245         connect(rtlGB, SIGNAL(clicked()),
2246                 this, SIGNAL(changed()));
2247         connect(visualCursorRB, SIGNAL(clicked()),
2248                 this, SIGNAL(changed()));
2249         connect(logicalCursorRB, SIGNAL(clicked()),
2250                 this, SIGNAL(changed()));
2251         connect(markForeignCB, SIGNAL(clicked()),
2252                 this, SIGNAL(changed()));
2253         connect(autoBeginCB, SIGNAL(clicked()),
2254                 this, SIGNAL(changed()));
2255         connect(autoEndCB, SIGNAL(clicked()),
2256                 this, SIGNAL(changed()));
2257         connect(languagePackageCO, SIGNAL(activated(int)),
2258                 this, SIGNAL(changed()));
2259         connect(languagePackageED, SIGNAL(textChanged(QString)),
2260                 this, SIGNAL(changed()));
2261         connect(globalCB, SIGNAL(clicked()),
2262                 this, SIGNAL(changed()));
2263         connect(startCommandED, SIGNAL(textChanged(QString)),
2264                 this, SIGNAL(changed()));
2265         connect(endCommandED, SIGNAL(textChanged(QString)),
2266                 this, SIGNAL(changed()));
2267         connect(uiLanguageCO, SIGNAL(activated(int)),
2268                 this, SIGNAL(changed()));
2269         connect(defaultDecimalPointLE, SIGNAL(textChanged(QString)),
2270                 this, SIGNAL(changed()));
2271         connect(defaultLengthUnitCO, SIGNAL(activated(int)),
2272                 this, SIGNAL(changed()));
2273
2274         languagePackageED->setValidator(new NoNewLineValidator(languagePackageED));
2275         startCommandED->setValidator(new NoNewLineValidator(startCommandED));
2276         endCommandED->setValidator(new NoNewLineValidator(endCommandED));
2277
2278         uiLanguageCO->clear();
2279
2280         QAbstractItemModel * language_model = guiApp->languageModel();
2281         // FIXME: it would be nice if sorting was enabled/disabled via a checkbox.
2282         language_model->sort(0);
2283         defaultDecimalPointLE->setInputMask("X; ");
2284         defaultDecimalPointLE->setMaxLength(1);
2285
2286         defaultLengthUnitCO->addItem(lyx::qt_(unit_name_gui[Length::CM]), Length::CM);
2287         defaultLengthUnitCO->addItem(lyx::qt_(unit_name_gui[Length::IN]), Length::IN);
2288
2289         set<string> added;
2290         uiLanguageCO->blockSignals(true);
2291         uiLanguageCO->addItem(qt_("Default"), toqstr("auto"));
2292         for (int i = 0; i != language_model->rowCount(); ++i) {
2293                 QModelIndex index = language_model->index(i, 0);
2294                 // Filter the list based on the available translation and add
2295                 // each language code only once
2296                 string const name = fromqstr(index.data(Qt::UserRole).toString());
2297                 Language const * lang = languages.getLanguage(name);
2298                 // never remove the currently selected language
2299                 if (lang && name != form->rc().gui_language && name != lyxrc.gui_language)
2300                         if (!lang->translated() || added.find(lang->code()) != added.end())
2301                                 continue;
2302                 added.insert(lang->code());
2303                 uiLanguageCO->addItem(index.data(Qt::DisplayRole).toString(),
2304                         index.data(Qt::UserRole).toString());
2305         }
2306         uiLanguageCO->blockSignals(false);
2307 }
2308
2309
2310 void PrefLanguage::on_uiLanguageCO_currentIndexChanged(int)
2311 {
2312          QMessageBox::information(this, qt_("LyX needs to be restarted!"),
2313                  qt_("The change of user interface language will be fully "
2314                  "effective only after a restart."));
2315 }
2316
2317
2318 void PrefLanguage::on_languagePackageCO_currentIndexChanged(int i)
2319 {
2320          languagePackageED->setEnabled(i == 2);
2321 }
2322
2323
2324 void PrefLanguage::apply(LyXRC & rc) const
2325 {
2326         // FIXME: remove rtl_support bool
2327         rc.rtl_support = rtlGB->isChecked();
2328         rc.visual_cursor = rtlGB->isChecked() && visualCursorRB->isChecked();
2329         rc.mark_foreign_language = markForeignCB->isChecked();
2330         rc.language_auto_begin = autoBeginCB->isChecked();
2331         rc.language_auto_end = autoEndCB->isChecked();
2332         int const p = languagePackageCO->currentIndex();
2333         if (p == 0)
2334                 rc.language_package_selection = LyXRC::LP_AUTO;
2335         else if (p == 1)
2336                 rc.language_package_selection = LyXRC::LP_BABEL;
2337         else if (p == 2)
2338                 rc.language_package_selection = LyXRC::LP_CUSTOM;
2339         else if (p == 3)
2340                 rc.language_package_selection = LyXRC::LP_NONE;
2341         rc.language_custom_package = fromqstr(languagePackageED->text());
2342         rc.language_global_options = globalCB->isChecked();
2343         rc.language_command_begin = fromqstr(startCommandED->text());
2344         rc.language_command_end = fromqstr(endCommandED->text());
2345         rc.gui_language = fromqstr(
2346                 uiLanguageCO->itemData(uiLanguageCO->currentIndex()).toString());
2347         rc.default_decimal_point = fromqstr(defaultDecimalPointLE->text());
2348         rc.default_length_unit = (Length::UNIT) defaultLengthUnitCO->itemData(defaultLengthUnitCO->currentIndex()).toInt();
2349 }
2350
2351
2352 void PrefLanguage::update(LyXRC const & rc)
2353 {
2354         // FIXME: remove rtl_support bool
2355         rtlGB->setChecked(rc.rtl_support);
2356         if (rc.visual_cursor)
2357                 visualCursorRB->setChecked(true);
2358         else
2359                 logicalCursorRB->setChecked(true);
2360         markForeignCB->setChecked(rc.mark_foreign_language);
2361         autoBeginCB->setChecked(rc.language_auto_begin);
2362         autoEndCB->setChecked(rc.language_auto_end);
2363         languagePackageCO->setCurrentIndex(rc.language_package_selection);
2364         languagePackageED->setText(toqstr(rc.language_custom_package));
2365         languagePackageED->setEnabled(languagePackageCO->currentIndex() == 2);
2366         globalCB->setChecked(rc.language_global_options);
2367         startCommandED->setText(toqstr(rc.language_command_begin));
2368         endCommandED->setText(toqstr(rc.language_command_end));
2369         defaultDecimalPointLE->setText(toqstr(rc.default_decimal_point));
2370         int pos = defaultLengthUnitCO->findData(int(rc.default_length_unit));
2371         defaultLengthUnitCO->setCurrentIndex(pos);
2372
2373         pos = uiLanguageCO->findData(toqstr(rc.gui_language));
2374         uiLanguageCO->blockSignals(true);
2375         uiLanguageCO->setCurrentIndex(pos);
2376         uiLanguageCO->blockSignals(false);
2377 }
2378
2379
2380 /////////////////////////////////////////////////////////////////////
2381 //
2382 // PrefPrinter
2383 //
2384 /////////////////////////////////////////////////////////////////////
2385
2386 PrefPrinter::PrefPrinter(GuiPreferences * form)
2387         : PrefModule(qt_(catOutput), qt_("Printer"), form)
2388 {
2389         setupUi(this);
2390
2391         connect(printerAdaptCB, SIGNAL(clicked()),
2392                 this, SIGNAL(changed()));
2393         connect(printerCommandED, SIGNAL(textChanged(QString)),
2394                 this, SIGNAL(changed()));
2395         connect(printerNameED, SIGNAL(textChanged(QString)),
2396                 this, SIGNAL(changed()));
2397         connect(printerPageRangeED, SIGNAL(textChanged(QString)),
2398                 this, SIGNAL(changed()));
2399         connect(printerCopiesED, SIGNAL(textChanged(QString)),
2400                 this, SIGNAL(changed()));
2401         connect(printerReverseED, SIGNAL(textChanged(QString)),
2402                 this, SIGNAL(changed()));
2403         connect(printerToPrinterED, SIGNAL(textChanged(QString)),
2404                 this, SIGNAL(changed()));
2405         connect(printerExtensionED, SIGNAL(textChanged(QString)),
2406                 this, SIGNAL(changed()));
2407         connect(printerSpoolCommandED, SIGNAL(textChanged(QString)),
2408                 this, SIGNAL(changed()));
2409         connect(printerPaperTypeED, SIGNAL(textChanged(QString)),
2410                 this, SIGNAL(changed()));
2411         connect(printerEvenED, SIGNAL(textChanged(QString)),
2412                 this, SIGNAL(changed()));
2413         connect(printerOddED, SIGNAL(textChanged(QString)),
2414                 this, SIGNAL(changed()));
2415         connect(printerCollatedED, SIGNAL(textChanged(QString)),
2416                 this, SIGNAL(changed()));
2417         connect(printerLandscapeED, SIGNAL(textChanged(QString)),
2418                 this, SIGNAL(changed()));
2419         connect(printerToFileED, SIGNAL(textChanged(QString)),
2420                 this, SIGNAL(changed()));
2421         connect(printerExtraED, SIGNAL(textChanged(QString)),
2422                 this, SIGNAL(changed()));
2423         connect(printerSpoolPrefixED, SIGNAL(textChanged(QString)),
2424                 this, SIGNAL(changed()));
2425         connect(printerPaperSizeED, SIGNAL(textChanged(QString)),
2426                 this, SIGNAL(changed()));
2427
2428         printerNameED->setValidator(new NoNewLineValidator(printerNameED));
2429         printerCommandED->setValidator(new NoNewLineValidator(printerCommandED));
2430         printerEvenED->setValidator(new NoNewLineValidator(printerEvenED));
2431         printerPageRangeED->setValidator(new NoNewLineValidator(printerPageRangeED));
2432         printerCopiesED->setValidator(new NoNewLineValidator(printerCopiesED));
2433         printerReverseED->setValidator(new NoNewLineValidator(printerReverseED));
2434         printerToFileED->setValidator(new NoNewLineValidator(printerToFileED));
2435         printerPaperTypeED->setValidator(new NoNewLineValidator(printerPaperTypeED));
2436         printerExtraED->setValidator(new NoNewLineValidator(printerExtraED));
2437         printerOddED->setValidator(new NoNewLineValidator(printerOddED));
2438         printerCollatedED->setValidator(new NoNewLineValidator(printerCollatedED));
2439         printerLandscapeED->setValidator(new NoNewLineValidator(printerLandscapeED));
2440         printerToPrinterED->setValidator(new NoNewLineValidator(printerToPrinterED));
2441         printerExtensionED->setValidator(new NoNewLineValidator(printerExtensionED));
2442         printerPaperSizeED->setValidator(new NoNewLineValidator(printerPaperSizeED));
2443         printerSpoolCommandED->setValidator(new NoNewLineValidator(printerSpoolCommandED));
2444         printerSpoolPrefixED->setValidator(new NoNewLineValidator(printerSpoolPrefixED));
2445 }
2446
2447
2448 void PrefPrinter::apply(LyXRC & rc) const
2449 {
2450         rc.print_adapt_output = printerAdaptCB->isChecked();
2451         rc.print_command = fromqstr(printerCommandED->text());
2452         rc.printer = fromqstr(printerNameED->text());
2453
2454         rc.print_pagerange_flag = fromqstr(printerPageRangeED->text());
2455         rc.print_copies_flag = fromqstr(printerCopiesED->text());
2456         rc.print_reverse_flag = fromqstr(printerReverseED->text());
2457         rc.print_to_printer = fromqstr(printerToPrinterED->text());
2458         rc.print_file_extension = fromqstr(printerExtensionED->text());
2459         rc.print_spool_command = fromqstr(printerSpoolCommandED->text());
2460         rc.print_paper_flag = fromqstr(printerPaperTypeED->text());
2461         rc.print_evenpage_flag = fromqstr(printerEvenED->text());
2462         rc.print_oddpage_flag = fromqstr(printerOddED->text());
2463         rc.print_collcopies_flag = fromqstr(printerCollatedED->text());
2464         rc.print_landscape_flag = fromqstr(printerLandscapeED->text());
2465         rc.print_to_file = internal_path(fromqstr(printerToFileED->text()));
2466         rc.print_extra_options = fromqstr(printerExtraED->text());
2467         rc.print_spool_printerprefix = fromqstr(printerSpoolPrefixED->text());
2468         rc.print_paper_dimension_flag = fromqstr(printerPaperSizeED->text());
2469 }
2470
2471
2472 void PrefPrinter::update(LyXRC const & rc)
2473 {
2474         printerAdaptCB->setChecked(rc.print_adapt_output);
2475         printerCommandED->setText(toqstr(rc.print_command));
2476         printerNameED->setText(toqstr(rc.printer));
2477
2478         printerPageRangeED->setText(toqstr(rc.print_pagerange_flag));
2479         printerCopiesED->setText(toqstr(rc.print_copies_flag));
2480         printerReverseED->setText(toqstr(rc.print_reverse_flag));
2481         printerToPrinterED->setText(toqstr(rc.print_to_printer));
2482         printerExtensionED->setText(toqstr(rc.print_file_extension));
2483         printerSpoolCommandED->setText(toqstr(rc.print_spool_command));
2484         printerPaperTypeED->setText(toqstr(rc.print_paper_flag));
2485         printerEvenED->setText(toqstr(rc.print_evenpage_flag));
2486         printerOddED->setText(toqstr(rc.print_oddpage_flag));
2487         printerCollatedED->setText(toqstr(rc.print_collcopies_flag));
2488         printerLandscapeED->setText(toqstr(rc.print_landscape_flag));
2489         printerToFileED->setText(toqstr(external_path(rc.print_to_file)));
2490         printerExtraED->setText(toqstr(rc.print_extra_options));
2491         printerSpoolPrefixED->setText(toqstr(rc.print_spool_printerprefix));
2492         printerPaperSizeED->setText(toqstr(rc.print_paper_dimension_flag));
2493 }
2494
2495
2496 /////////////////////////////////////////////////////////////////////
2497 //
2498 // PrefUserInterface
2499 //
2500 /////////////////////////////////////////////////////////////////////
2501
2502 PrefUserInterface::PrefUserInterface(GuiPreferences * form)
2503         : PrefModule(qt_(catLookAndFeel), qt_("User Interface"), form)
2504 {
2505         setupUi(this);
2506
2507         connect(autoSaveCB, SIGNAL(toggled(bool)),
2508                 autoSaveSB, SLOT(setEnabled(bool)));
2509         connect(autoSaveCB, SIGNAL(toggled(bool)),
2510                 TextLabel1, SLOT(setEnabled(bool)));
2511         connect(openDocumentsInTabsCB, SIGNAL(clicked()),
2512                 this, SIGNAL(changed()));
2513         connect(singleInstanceCB, SIGNAL(clicked()),
2514                 this, SIGNAL(changed()));
2515 #if QT_VERSION < 0x040500
2516         singleCloseTabButtonCB->setEnabled(false);
2517 #endif
2518         connect(singleCloseTabButtonCB, SIGNAL(clicked()),
2519                 this, SIGNAL(changed()));
2520         connect(uiFilePB, SIGNAL(clicked()),
2521                 this, SLOT(selectUi()));
2522         connect(uiFileED, SIGNAL(textChanged(QString)),
2523                 this, SIGNAL(changed()));
2524         connect(iconSetCO, SIGNAL(activated(int)),
2525                 this, SIGNAL(changed()));
2526         connect(restoreCursorCB, SIGNAL(clicked()),
2527                 this, SIGNAL(changed()));
2528         connect(loadSessionCB, SIGNAL(clicked()),
2529                 this, SIGNAL(changed()));
2530         connect(allowGeometrySessionCB, SIGNAL(clicked()),
2531                 this, SIGNAL(changed()));
2532         connect(autoSaveSB, SIGNAL(valueChanged(int)),
2533                 this, SIGNAL(changed()));
2534         connect(autoSaveCB, SIGNAL(clicked()),
2535                 this, SIGNAL(changed()));
2536         connect(backupCB, SIGNAL(clicked()),
2537                 this, SIGNAL(changed()));
2538         connect(saveCompressedCB, SIGNAL(clicked()),
2539                 this, SIGNAL(changed()));
2540         connect(lastfilesSB, SIGNAL(valueChanged(int)),
2541                 this, SIGNAL(changed()));
2542         connect(tooltipCB, SIGNAL(toggled(bool)),
2543                 this, SIGNAL(changed()));
2544         lastfilesSB->setMaximum(maxlastfiles);
2545
2546         iconSetCO->addItem(qt_("Default"), QString());
2547         iconSetCO->addItem(qt_("Classic"), "classic");
2548         iconSetCO->addItem(qt_("Oxygen"), "oxygen");
2549 }
2550
2551
2552 void PrefUserInterface::apply(LyXRC & rc) const
2553 {
2554         rc.icon_set = fromqstr(iconSetCO->itemData(
2555                 iconSetCO->currentIndex()).toString());
2556
2557         rc.ui_file = internal_path(fromqstr(uiFileED->text()));
2558         rc.use_lastfilepos = restoreCursorCB->isChecked();
2559         rc.load_session = loadSessionCB->isChecked();
2560         rc.allow_geometry_session = allowGeometrySessionCB->isChecked();
2561         rc.autosave = autoSaveCB->isChecked() ?  autoSaveSB->value() * 60 : 0;
2562         rc.make_backup = backupCB->isChecked();
2563         rc.save_compressed = saveCompressedCB->isChecked();
2564         rc.num_lastfiles = lastfilesSB->value();
2565         rc.use_tooltip = tooltipCB->isChecked();
2566         rc.open_buffers_in_tabs = openDocumentsInTabsCB->isChecked();
2567         rc.single_instance = singleInstanceCB->isChecked();
2568         rc.single_close_tab_button = singleCloseTabButtonCB->isChecked();
2569 #if QT_VERSION < 0x040500
2570         rc.single_close_tab_button = true;
2571 #endif
2572 }
2573
2574
2575 void PrefUserInterface::update(LyXRC const & rc)
2576 {
2577         int iconset = iconSetCO->findData(toqstr(rc.icon_set));
2578         if (iconset < 0)
2579                 iconset = 0;
2580         iconSetCO->setCurrentIndex(iconset);
2581         uiFileED->setText(toqstr(external_path(rc.ui_file)));
2582         restoreCursorCB->setChecked(rc.use_lastfilepos);
2583         loadSessionCB->setChecked(rc.load_session);
2584         allowGeometrySessionCB->setChecked(rc.allow_geometry_session);
2585         // convert to minutes
2586         bool autosave = rc.autosave > 0;
2587         int mins = rc.autosave / 60;
2588         if (!mins)
2589                 mins = 5;
2590         autoSaveSB->setValue(mins);
2591         autoSaveCB->setChecked(autosave);
2592         autoSaveSB->setEnabled(autosave);
2593         backupCB->setChecked(rc.make_backup);
2594         saveCompressedCB->setChecked(rc.save_compressed);
2595         lastfilesSB->setValue(rc.num_lastfiles);
2596         tooltipCB->setChecked(rc.use_tooltip);
2597         openDocumentsInTabsCB->setChecked(rc.open_buffers_in_tabs);
2598         singleInstanceCB->setChecked(rc.single_instance && !rc.lyxpipes.empty());
2599         singleInstanceCB->setEnabled(!rc.lyxpipes.empty());
2600         singleCloseTabButtonCB->setChecked(rc.single_close_tab_button);
2601 }
2602
2603
2604 void PrefUserInterface::selectUi()
2605 {
2606         QString file = form_->browseUI(internalPath(uiFileED->text()));
2607         if (!file.isEmpty())
2608                 uiFileED->setText(file);
2609 }
2610
2611
2612 void PrefUserInterface::on_clearSessionPB_clicked()
2613 {
2614         guiApp->clearSession();
2615 }
2616
2617
2618
2619 /////////////////////////////////////////////////////////////////////
2620 //
2621 // PrefEdit
2622 //
2623 /////////////////////////////////////////////////////////////////////
2624
2625 PrefEdit::PrefEdit(GuiPreferences * form)
2626         : PrefModule(qt_(catEditing), qt_("Control"), form)
2627 {
2628         setupUi(this);
2629
2630         connect(cursorFollowsCB, SIGNAL(clicked()),
2631                 this, SIGNAL(changed()));
2632         connect(scrollBelowCB, SIGNAL(clicked()),
2633                 this, SIGNAL(changed()));
2634         connect(macLikeWordMovementCB, SIGNAL(clicked()),
2635                 this, SIGNAL(changed()));
2636         connect(sortEnvironmentsCB, SIGNAL(clicked()),
2637                 this, SIGNAL(changed()));
2638         connect(groupEnvironmentsCB, SIGNAL(clicked()),
2639                 this, SIGNAL(changed()));
2640         connect(macroEditStyleCO, SIGNAL(activated(int)),
2641                 this, SIGNAL(changed()));
2642         connect(cursorWidthSB, SIGNAL(valueChanged(int)),
2643                 this, SIGNAL(changed()));
2644         connect(fullscreenLimitGB, SIGNAL(clicked()),
2645                 this, SIGNAL(changed()));
2646         connect(fullscreenWidthSB, SIGNAL(valueChanged(int)),
2647                 this, SIGNAL(changed()));
2648         connect(toggleTabbarCB, SIGNAL(toggled(bool)),
2649                 this, SIGNAL(changed()));
2650         connect(toggleMenubarCB, SIGNAL(toggled(bool)),
2651                 this, SIGNAL(changed()));
2652         connect(toggleScrollbarCB, SIGNAL(toggled(bool)),
2653                 this, SIGNAL(changed()));
2654         connect(toggleToolbarsCB, SIGNAL(toggled(bool)),
2655                 this, SIGNAL(changed()));
2656 }
2657
2658
2659 void PrefEdit::apply(LyXRC & rc) const
2660 {
2661         rc.cursor_follows_scrollbar = cursorFollowsCB->isChecked();
2662         rc.scroll_below_document = scrollBelowCB->isChecked();
2663         rc.mac_like_word_movement = macLikeWordMovementCB->isChecked();
2664         rc.sort_layouts = sortEnvironmentsCB->isChecked();
2665         rc.group_layouts = groupEnvironmentsCB->isChecked();
2666         switch (macroEditStyleCO->currentIndex()) {
2667                 case 0: rc.macro_edit_style = LyXRC::MACRO_EDIT_INLINE_BOX; break;
2668                 case 1: rc.macro_edit_style = LyXRC::MACRO_EDIT_INLINE; break;
2669                 case 2: rc.macro_edit_style = LyXRC::MACRO_EDIT_LIST;   break;
2670         }
2671         rc.cursor_width = cursorWidthSB->value();
2672         rc.full_screen_toolbars = toggleToolbarsCB->isChecked();
2673         rc.full_screen_scrollbar = toggleScrollbarCB->isChecked();
2674         rc.full_screen_tabbar = toggleTabbarCB->isChecked();
2675         rc.full_screen_menubar = toggleMenubarCB->isChecked();
2676         rc.full_screen_width = fullscreenWidthSB->value();
2677         rc.full_screen_limit = fullscreenLimitGB->isChecked();
2678 }
2679
2680
2681 void PrefEdit::update(LyXRC const & rc)
2682 {
2683         cursorFollowsCB->setChecked(rc.cursor_follows_scrollbar);
2684         scrollBelowCB->setChecked(rc.scroll_below_document);
2685         macLikeWordMovementCB->setChecked(rc.mac_like_word_movement);
2686         sortEnvironmentsCB->setChecked(rc.sort_layouts);
2687         groupEnvironmentsCB->setChecked(rc.group_layouts);
2688         macroEditStyleCO->setCurrentIndex(rc.macro_edit_style);
2689         cursorWidthSB->setValue(rc.cursor_width);
2690         toggleScrollbarCB->setChecked(rc.full_screen_scrollbar);
2691         toggleToolbarsCB->setChecked(rc.full_screen_toolbars);
2692         toggleTabbarCB->setChecked(rc.full_screen_tabbar);
2693         toggleMenubarCB->setChecked(rc.full_screen_menubar);
2694         fullscreenWidthSB->setValue(rc.full_screen_width);
2695         fullscreenLimitGB->setChecked(rc.full_screen_limit);
2696 }
2697
2698
2699 /////////////////////////////////////////////////////////////////////
2700 //
2701 // PrefShortcuts
2702 //
2703 /////////////////////////////////////////////////////////////////////
2704
2705
2706 GuiShortcutDialog::GuiShortcutDialog(QWidget * parent) : QDialog(parent)
2707 {
2708         Ui::shortcutUi::setupUi(this);
2709         QDialog::setModal(true);
2710 }
2711
2712
2713 PrefShortcuts::PrefShortcuts(GuiPreferences * form)
2714         : PrefModule(qt_(catEditing), qt_("Shortcuts"), form)
2715 {
2716         setupUi(this);
2717
2718         shortcutsTW->setColumnCount(2);
2719         shortcutsTW->headerItem()->setText(0, qt_("Function"));
2720         shortcutsTW->headerItem()->setText(1, qt_("Shortcut"));
2721         shortcutsTW->setSortingEnabled(true);
2722         // Multi-selection can be annoying.
2723         // shortcutsTW->setSelectionMode(QAbstractItemView::MultiSelection);
2724
2725         connect(bindFilePB, SIGNAL(clicked()),
2726                 this, SLOT(selectBind()));
2727         connect(bindFileED, SIGNAL(textChanged(QString)),
2728                 this, SIGNAL(changed()));
2729
2730         shortcut_ = new GuiShortcutDialog(this);
2731         shortcut_bc_.setPolicy(ButtonPolicy::OkCancelPolicy);
2732         shortcut_bc_.setOK(shortcut_->okPB);
2733         shortcut_bc_.setCancel(shortcut_->cancelPB);
2734
2735         connect(shortcut_->okPB, SIGNAL(clicked()),
2736                 shortcut_, SLOT(accept()));
2737         connect(shortcut_->okPB, SIGNAL(clicked()),
2738                 this, SIGNAL(changed()));
2739         connect(shortcut_->cancelPB, SIGNAL(clicked()),
2740                 shortcut_, SLOT(reject()));
2741         connect(shortcut_->clearPB, SIGNAL(clicked()),
2742                 this, SLOT(shortcutClearPressed()));
2743         connect(shortcut_->removePB, SIGNAL(clicked()),
2744                 this, SLOT(shortcutRemovePressed()));
2745         connect(shortcut_->okPB, SIGNAL(clicked()),
2746                 this, SLOT(shortcutOkPressed()));
2747         connect(shortcut_->cancelPB, SIGNAL(clicked()),
2748                 this, SLOT(shortcutCancelPressed()));
2749 }
2750
2751
2752 void PrefShortcuts::apply(LyXRC & rc) const
2753 {
2754         rc.bind_file = internal_path(fromqstr(bindFileED->text()));
2755         // write user_bind and user_unbind to .lyx/bind/user.bind
2756         FileName bind_dir(addPath(package().user_support().absFileName(), "bind"));
2757         if (!bind_dir.exists() && !bind_dir.createDirectory(0777)) {
2758                 lyxerr << "LyX could not create the user bind directory '"
2759                        << bind_dir << "'. All user-defined key bindings will be lost." << endl;
2760                 return;
2761         }
2762         if (!bind_dir.isDirWritable()) {
2763                 lyxerr << "LyX could not write to the user bind directory '"
2764                        << bind_dir << "'. All user-defined key bindings will be lost." << endl;
2765                 return;
2766         }
2767         FileName user_bind_file(bind_dir.absFileName() + "/user.bind");
2768         user_unbind_.write(user_bind_file.toFilesystemEncoding(), false, true);
2769         user_bind_.write(user_bind_file.toFilesystemEncoding(), true, false);
2770         // immediately apply the keybindings. Why this is not done before?
2771         // The good thing is that the menus are updated automatically.
2772         theTopLevelKeymap().clear();
2773         theTopLevelKeymap().read("site");
2774         theTopLevelKeymap().read(rc.bind_file, 0, KeyMap::Fallback);
2775         theTopLevelKeymap().read("user", 0, KeyMap::MissingOK);
2776 }
2777
2778
2779 void PrefShortcuts::update(LyXRC const & rc)
2780 {
2781         bindFileED->setText(toqstr(external_path(rc.bind_file)));
2782         //
2783         system_bind_.clear();
2784         user_bind_.clear();
2785         user_unbind_.clear();
2786         system_bind_.read("site");
2787         system_bind_.read(rc.bind_file);
2788         // \unbind in user.bind is added to user_unbind_
2789         user_bind_.read("user", &user_unbind_, KeyMap::MissingOK);
2790         updateShortcutsTW();
2791 }
2792
2793
2794 void PrefShortcuts::updateShortcutsTW()
2795 {
2796         shortcutsTW->clear();
2797
2798         editItem_ = new QTreeWidgetItem(shortcutsTW);
2799         editItem_->setText(0, qt_("Cursor, Mouse and Editing Functions"));
2800         editItem_->setFlags(editItem_->flags() & ~Qt::ItemIsSelectable);
2801
2802         mathItem_ = new QTreeWidgetItem(shortcutsTW);
2803         mathItem_->setText(0, qt_("Mathematical Symbols"));
2804         mathItem_->setFlags(mathItem_->flags() & ~Qt::ItemIsSelectable);
2805
2806         bufferItem_ = new QTreeWidgetItem(shortcutsTW);
2807         bufferItem_->setText(0, qt_("Document and Window"));
2808         bufferItem_->setFlags(bufferItem_->flags() & ~Qt::ItemIsSelectable);
2809
2810         layoutItem_ = new QTreeWidgetItem(shortcutsTW);
2811         layoutItem_->setText(0, qt_("Font, Layouts and Textclasses"));
2812         layoutItem_->setFlags(layoutItem_->flags() & ~Qt::ItemIsSelectable);
2813
2814         systemItem_ = new QTreeWidgetItem(shortcutsTW);
2815         systemItem_->setText(0, qt_("System and Miscellaneous"));
2816         systemItem_->setFlags(systemItem_->flags() & ~Qt::ItemIsSelectable);
2817
2818         // listBindings(unbound=true) lists all bound and unbound lfuns
2819         // Items in this list is tagged by its source.
2820         KeyMap::BindingList bindinglist = system_bind_.listBindings(true,
2821                 KeyMap::System);
2822         KeyMap::BindingList user_bindinglist = user_bind_.listBindings(false,
2823                 KeyMap::UserBind);
2824         KeyMap::BindingList user_unbindinglist = user_unbind_.listBindings(false,
2825                 KeyMap::UserUnbind);
2826         bindinglist.insert(bindinglist.end(), user_bindinglist.begin(),
2827                         user_bindinglist.end());
2828         bindinglist.insert(bindinglist.end(), user_unbindinglist.begin(),
2829                         user_unbindinglist.end());
2830
2831         KeyMap::BindingList::const_iterator it = bindinglist.begin();
2832         KeyMap::BindingList::const_iterator it_end = bindinglist.end();
2833         for (; it != it_end; ++it)
2834                 insertShortcutItem(it->request, it->sequence, KeyMap::ItemType(it->tag));
2835
2836         shortcutsTW->sortItems(0, Qt::AscendingOrder);
2837         QList<QTreeWidgetItem*> items = shortcutsTW->selectedItems();
2838         removePB->setEnabled(!items.isEmpty() && !items[0]->text(1).isEmpty());
2839         modifyPB->setEnabled(!items.isEmpty());
2840
2841         shortcutsTW->resizeColumnToContents(0);
2842 }
2843
2844
2845 void PrefShortcuts::setItemType(QTreeWidgetItem * item, KeyMap::ItemType tag)
2846 {
2847         item->setData(0, Qt::UserRole, QVariant(tag));
2848         QFont font;
2849
2850         switch (tag) {
2851         case KeyMap::System:
2852                 break;
2853         case KeyMap::UserBind:
2854                 font.setBold(true);
2855                 break;
2856         case KeyMap::UserUnbind:
2857                 font.setStrikeOut(true);
2858                 break;
2859         // this item is not displayed now.
2860         case KeyMap::UserExtraUnbind:
2861                 font.setStrikeOut(true);
2862                 break;
2863         }
2864
2865         item->setFont(1, font);
2866 }
2867
2868
2869 QTreeWidgetItem * PrefShortcuts::insertShortcutItem(FuncRequest const & lfun,
2870                 KeySequence const & seq, KeyMap::ItemType tag)
2871 {
2872         FuncCode const action = lfun.action();
2873         string const action_name = lyxaction.getActionName(action);
2874         QString const lfun_name = toqstr(from_utf8(action_name)
2875                         + ' ' + lfun.argument());
2876         QString const shortcut = toqstr(seq.print(KeySequence::ForGui));
2877         KeyMap::ItemType item_tag = tag;
2878
2879         QTreeWidgetItem * newItem = 0;
2880         // for unbind items, try to find an existing item in the system bind list
2881         if (tag == KeyMap::UserUnbind) {
2882                 QList<QTreeWidgetItem*> const items = shortcutsTW->findItems(lfun_name,
2883                         Qt::MatchFlags(Qt::MatchExactly | Qt::MatchRecursive), 0);
2884                 for (int i = 0; i < items.size(); ++i) {
2885                         if (items[i]->text(1) == shortcut)
2886                                 newItem = items[i];
2887                                 break;
2888                         }
2889                 // if not found, this unbind item is KeyMap::UserExtraUnbind
2890                 // Such an item is not displayed to avoid confusion (what is
2891                 // unmatched removed?).
2892                 if (!newItem) {
2893                         item_tag = KeyMap::UserExtraUnbind;
2894                         return 0;
2895                 }
2896         }
2897         if (!newItem) {
2898                 switch(lyxaction.getActionType(action)) {
2899                 case LyXAction::Hidden:
2900                         return 0;
2901                 case LyXAction::Edit:
2902                         newItem = new QTreeWidgetItem(editItem_);
2903                         break;
2904                 case LyXAction::Math:
2905                         newItem = new QTreeWidgetItem(mathItem_);
2906                         break;
2907                 case LyXAction::Buffer:
2908                         newItem = new QTreeWidgetItem(bufferItem_);
2909                         break;
2910                 case LyXAction::Layout:
2911                         newItem = new QTreeWidgetItem(layoutItem_);
2912                         break;
2913                 case LyXAction::System:
2914                         newItem = new QTreeWidgetItem(systemItem_);
2915                         break;
2916                 default:
2917                         // this should not happen
2918                         newItem = new QTreeWidgetItem(shortcutsTW);
2919                 }
2920         }
2921
2922         newItem->setText(0, lfun_name);
2923         newItem->setText(1, shortcut);
2924         // record BindFile representation to recover KeySequence when needed.
2925         newItem->setData(1, Qt::UserRole, toqstr(seq.print(KeySequence::BindFile)));
2926         setItemType(newItem, item_tag);
2927         return newItem;
2928 }
2929
2930
2931 void PrefShortcuts::on_shortcutsTW_itemSelectionChanged()
2932 {
2933         QList<QTreeWidgetItem*> items = shortcutsTW->selectedItems();
2934         removePB->setEnabled(!items.isEmpty() && !items[0]->text(1).isEmpty());
2935         modifyPB->setEnabled(!items.isEmpty());
2936         if (items.isEmpty())
2937                 return;
2938
2939         KeyMap::ItemType tag = 
2940                 static_cast<KeyMap::ItemType>(items[0]->data(0, Qt::UserRole).toInt());
2941         if (tag == KeyMap::UserUnbind)
2942                 removePB->setText(qt_("Res&tore"));
2943         else
2944                 removePB->setText(qt_("Remo&ve"));
2945 }
2946
2947
2948 void PrefShortcuts::on_shortcutsTW_itemDoubleClicked()
2949 {
2950         modifyShortcut();
2951 }
2952
2953
2954 void PrefShortcuts::modifyShortcut()
2955 {
2956         QTreeWidgetItem * item = shortcutsTW->currentItem();
2957         if (item->flags() & Qt::ItemIsSelectable) {
2958                 shortcut_->lfunLE->setText(item->text(0));
2959                 save_lfun_ = item->text(0).trimmed();
2960                 shortcut_->shortcutWG->setText(item->text(1));
2961                 KeySequence seq;
2962                 seq.parse(fromqstr(item->data(1, Qt::UserRole).toString()));
2963                 shortcut_->shortcutWG->setKeySequence(seq);
2964                 shortcut_->shortcutWG->setFocus();
2965                 shortcut_->exec();
2966         }
2967 }
2968
2969
2970 void PrefShortcuts::removeShortcut()
2971 {
2972         // it seems that only one item can be selected, but I am
2973         // removing all selected items anyway.
2974         QList<QTreeWidgetItem*> items = shortcutsTW->selectedItems();
2975         for (int i = 0; i < items.size(); ++i) {
2976                 string shortcut = fromqstr(items[i]->data(1, Qt::UserRole).toString());
2977                 string lfun = fromqstr(items[i]->text(0));
2978                 FuncRequest func = lyxaction.lookupFunc(lfun);
2979                 KeyMap::ItemType tag = 
2980                         static_cast<KeyMap::ItemType>(items[i]->data(0, Qt::UserRole).toInt());
2981
2982                 switch (tag) {
2983                 case KeyMap::System: {
2984                         // for system bind, we do not touch the item
2985                         // but add an user unbind item
2986                         user_unbind_.bind(shortcut, func);
2987                         setItemType(items[i], KeyMap::UserUnbind);
2988                         removePB->setText(qt_("Res&tore"));
2989                         break;
2990                 }
2991                 case KeyMap::UserBind: {
2992                         // for user_bind, we remove this bind
2993                         QTreeWidgetItem * parent = items[i]->parent();
2994                         int itemIdx = parent->indexOfChild(items[i]);
2995                         parent->takeChild(itemIdx);
2996                         if (itemIdx > 0)
2997                                 shortcutsTW->scrollToItem(parent->child(itemIdx - 1));
2998                         else
2999                                 shortcutsTW->scrollToItem(parent);
3000                         user_bind_.unbind(shortcut, func);
3001                         break;
3002                 }
3003                 case KeyMap::UserUnbind: {
3004                         // for user_unbind, we remove the unbind, and the item
3005                         // become KeyMap::System again.
3006                         user_unbind_.unbind(shortcut, func);
3007                         setItemType(items[i], KeyMap::System);
3008                         removePB->setText(qt_("Remo&ve"));
3009                         break;
3010                 }
3011                 case KeyMap::UserExtraUnbind: {
3012                         // for user unbind that is not in system bind file,
3013                         // remove this unbind file
3014                         QTreeWidgetItem * parent = items[i]->parent();
3015                         parent->takeChild(parent->indexOfChild(items[i]));
3016                         user_unbind_.unbind(shortcut, func);
3017                 }
3018                 }
3019         }
3020 }
3021
3022
3023 void PrefShortcuts::selectBind()
3024 {
3025         QString file = form_->browsebind(internalPath(bindFileED->text()));
3026         if (!file.isEmpty()) {
3027                 bindFileED->setText(file);
3028                 system_bind_ = KeyMap();
3029                 system_bind_.read(fromqstr(file));
3030                 updateShortcutsTW();
3031         }
3032 }
3033
3034
3035 void PrefShortcuts::on_modifyPB_pressed()
3036 {
3037         modifyShortcut();
3038 }
3039
3040
3041 void PrefShortcuts::on_newPB_pressed()
3042 {
3043         shortcut_->lfunLE->clear();
3044         shortcut_->shortcutWG->reset();
3045         save_lfun_ = QString();
3046         shortcut_->exec();
3047 }
3048
3049
3050 void PrefShortcuts::on_removePB_pressed()
3051 {
3052         changed();
3053         removeShortcut();
3054 }
3055
3056
3057 void PrefShortcuts::on_searchLE_textEdited()
3058 {
3059         if (searchLE->text().isEmpty()) {
3060                 // show all hidden items
3061                 QTreeWidgetItemIterator it(shortcutsTW, QTreeWidgetItemIterator::Hidden);
3062                 while (*it)
3063                         shortcutsTW->setItemHidden(*it++, false);
3064                 return;
3065         }
3066         // search both columns
3067         QList<QTreeWidgetItem *> matched = shortcutsTW->findItems(searchLE->text(),
3068                 Qt::MatchFlags(Qt::MatchContains | Qt::MatchRecursive), 0);
3069         matched += shortcutsTW->findItems(searchLE->text(),
3070                 Qt::MatchFlags(Qt::MatchContains | Qt::MatchRecursive), 1);
3071
3072         // hide everyone (to avoid searching in matched QList repeatedly
3073         QTreeWidgetItemIterator it(shortcutsTW, QTreeWidgetItemIterator::Selectable);
3074         while (*it)
3075                 shortcutsTW->setItemHidden(*it++, true);
3076         // show matched items
3077         for (int i = 0; i < matched.size(); ++i) {
3078                 shortcutsTW->setItemHidden(matched[i], false);
3079         shortcutsTW->setItemExpanded(matched[i]->parent(), true);
3080         }
3081 }
3082
3083
3084 docstring makeCmdString(FuncRequest const & f)
3085 {
3086         docstring actionStr = from_ascii(lyxaction.getActionName(f.action()));
3087         if (!f.argument().empty())
3088                 actionStr += " " + f.argument();
3089         return actionStr;
3090 }
3091
3092
3093 void PrefShortcuts::shortcutOkPressed()
3094 {
3095         QString const new_lfun = shortcut_->lfunLE->text();
3096         FuncRequest func = lyxaction.lookupFunc(fromqstr(new_lfun));
3097
3098         if (func.action() == LFUN_UNKNOWN_ACTION) {
3099                 Alert::error(_("Failed to create shortcut"),
3100                         _("Unknown or invalid LyX function"));
3101                 return;
3102         }
3103
3104         KeySequence k = shortcut_->shortcutWG->getKeySequence();
3105         if (k.length() == 0) {
3106                 Alert::error(_("Failed to create shortcut"),
3107                         _("Invalid or empty key sequence"));
3108                 return;
3109         }
3110
3111         // check to see if there's been any change
3112         FuncRequest oldBinding = system_bind_.getBinding(k);
3113         if (oldBinding.action() == LFUN_UNKNOWN_ACTION)
3114                 oldBinding = user_bind_.getBinding(k);
3115         if (oldBinding == func)
3116                 // nothing has changed
3117                 return;
3118         
3119         // make sure this key isn't already bound---and, if so, not unbound
3120         FuncCode const unbind = user_unbind_.getBinding(k).action();
3121         docstring const action_string = makeCmdString(oldBinding);
3122         if (oldBinding.action() > LFUN_NOACTION && unbind == LFUN_UNKNOWN_ACTION
3123                   && save_lfun_ != toqstr(action_string)) {
3124                 // FIXME Perhaps we should offer to over-write the old shortcut?
3125                 // If so, we'll need to remove it from our list, etc.
3126                 Alert::error(_("Failed to create shortcut"),
3127                         bformat(_("Shortcut `%1$s' is already bound to:\n%2$s\n"
3128                           "You need to remove that binding before creating a new one."), 
3129                         k.print(KeySequence::ForGui), action_string));
3130                 return;
3131         }
3132
3133         if (!save_lfun_.isEmpty())
3134                 // real modification of the lfun's shortcut,
3135                 // so remove the previous one
3136                 removeShortcut();
3137
3138         QTreeWidgetItem * item = insertShortcutItem(func, k, KeyMap::UserBind);
3139         if (item) {
3140                 user_bind_.bind(&k, func);
3141                 shortcutsTW->sortItems(0, Qt::AscendingOrder);
3142                 shortcutsTW->setItemExpanded(item->parent(), true);
3143                 shortcutsTW->scrollToItem(item);
3144         } else {
3145                 Alert::error(_("Failed to create shortcut"),
3146                         _("Can not insert shortcut to the list"));
3147                 return;
3148         }
3149 }
3150
3151
3152 void PrefShortcuts::shortcutCancelPressed()
3153 {
3154         shortcut_->shortcutWG->reset();
3155 }
3156
3157
3158 void PrefShortcuts::shortcutClearPressed()
3159 {
3160         shortcut_->shortcutWG->reset();
3161 }
3162
3163
3164 void PrefShortcuts::shortcutRemovePressed()
3165 {
3166         shortcut_->shortcutWG->removeFromSequence();
3167 }
3168
3169
3170 /////////////////////////////////////////////////////////////////////
3171 //
3172 // PrefIdentity
3173 //
3174 /////////////////////////////////////////////////////////////////////
3175
3176 PrefIdentity::PrefIdentity(GuiPreferences * form)
3177         : PrefModule(QString(), qt_("Identity"), form)
3178 {
3179         setupUi(this);
3180
3181         connect(nameED, SIGNAL(textChanged(QString)),
3182                 this, SIGNAL(changed()));
3183         connect(emailED, SIGNAL(textChanged(QString)),
3184                 this, SIGNAL(changed()));
3185
3186         nameED->setValidator(new NoNewLineValidator(nameED));
3187         emailED->setValidator(new NoNewLineValidator(emailED));
3188 }
3189
3190
3191 void PrefIdentity::apply(LyXRC & rc) const
3192 {
3193         rc.user_name = fromqstr(nameED->text());
3194         rc.user_email = fromqstr(emailED->text());
3195 }
3196
3197
3198 void PrefIdentity::update(LyXRC const & rc)
3199 {
3200         nameED->setText(toqstr(rc.user_name));
3201         emailED->setText(toqstr(rc.user_email));
3202 }
3203
3204
3205
3206 /////////////////////////////////////////////////////////////////////
3207 //
3208 // GuiPreferences
3209 //
3210 /////////////////////////////////////////////////////////////////////
3211
3212 GuiPreferences::GuiPreferences(GuiView & lv)
3213         : GuiDialog(lv, "prefs", qt_("Preferences")), update_screen_font_(false)
3214 {
3215         setupUi(this);
3216
3217         QDialog::setModal(false);
3218
3219         connect(savePB, SIGNAL(clicked()), this, SLOT(slotOK()));
3220         connect(applyPB, SIGNAL(clicked()), this, SLOT(slotApply()));
3221         connect(closePB, SIGNAL(clicked()), this, SLOT(slotClose()));
3222         connect(restorePB, SIGNAL(clicked()), this, SLOT(slotRestore()));
3223
3224         addModule(new PrefUserInterface(this));
3225         addModule(new PrefEdit(this));
3226         addModule(new PrefShortcuts(this));
3227         PrefScreenFonts * screenfonts = new PrefScreenFonts(this);
3228         connect(this, SIGNAL(prefsApplied(LyXRC const &)),
3229                         screenfonts, SLOT(updateScreenFontSizes(LyXRC const &)));
3230         addModule(screenfonts);
3231         addModule(new PrefColors(this));
3232         addModule(new PrefDisplay(this));
3233         addModule(new PrefInput(this));
3234         addModule(new PrefCompletion(this));
3235
3236         addModule(new PrefPaths(this));
3237
3238         addModule(new PrefIdentity(this));
3239
3240         addModule(new PrefLanguage(this));
3241         addModule(new PrefSpellchecker(this));
3242
3243         //for strftime validator
3244         PrefOutput * output = new PrefOutput(this); 
3245         addModule(output);
3246         addModule(new PrefPrinter(this));
3247         addModule(new PrefLatex(this));
3248
3249         PrefConverters * converters = new PrefConverters(this);
3250         PrefFileformats * formats = new PrefFileformats(this);
3251         connect(formats, SIGNAL(formatsChanged()),
3252                         converters, SLOT(updateGui()));
3253         addModule(converters);
3254         addModule(formats);
3255
3256         prefsPS->setCurrentPanel(qt_("User Interface"));
3257 // FIXME: hack to work around resizing bug in Qt >= 4.2
3258 // bug verified with Qt 4.2.{0-3} (JSpitzm)
3259 #if QT_VERSION >= 0x040200
3260         prefsPS->updateGeometry();
3261 #endif
3262
3263         bc().setPolicy(ButtonPolicy::PreferencesPolicy);
3264         bc().setOK(savePB);
3265         bc().setApply(applyPB);
3266         bc().setCancel(closePB);
3267         bc().setRestore(restorePB);
3268
3269         // initialize the strftime validator
3270         bc().addCheckedLineEdit(output->DateED);
3271 }
3272
3273
3274 void GuiPreferences::addModule(PrefModule * module)
3275 {
3276         LASSERT(module, return);
3277         if (module->category().isEmpty())
3278                 prefsPS->addPanel(module, module->title());
3279         else
3280                 prefsPS->addPanel(module, module->title(), module->category());
3281         connect(module, SIGNAL(changed()), this, SLOT(change_adaptor()));
3282         modules_.push_back(module);
3283 }
3284
3285
3286 void GuiPreferences::change_adaptor()
3287 {
3288         changed();
3289 }
3290
3291
3292 void GuiPreferences::apply(LyXRC & rc) const
3293 {
3294         size_t end = modules_.size();
3295         for (size_t i = 0; i != end; ++i)
3296                 modules_[i]->apply(rc);
3297 }
3298
3299
3300 void GuiPreferences::updateRc(LyXRC const & rc)
3301 {
3302         size_t const end = modules_.size();
3303         for (size_t i = 0; i != end; ++i)
3304                 modules_[i]->update(rc);
3305 }
3306
3307
3308 void GuiPreferences::applyView()
3309 {
3310         apply(rc());
3311 }
3312
3313
3314 bool GuiPreferences::initialiseParams(string const &)
3315 {
3316         rc_ = lyxrc;
3317         formats_ = lyx::formats;
3318         converters_ = theConverters();
3319         converters_.update(formats_);
3320         movers_ = theMovers();
3321         colors_.clear();
3322         update_screen_font_ = false;
3323         
3324         updateRc(rc_);
3325         // Make sure that the bc is in the INITIAL state  
3326         if (bc().policy().buttonStatus(ButtonPolicy::RESTORE))  
3327                 bc().restore();  
3328
3329         return true;
3330 }
3331
3332
3333 void GuiPreferences::dispatchParams()
3334 {
3335         ostringstream ss;
3336         rc_.write(ss, true);
3337         dispatch(FuncRequest(LFUN_LYXRC_APPLY, ss.str()));
3338         // issue prefsApplied signal. This will update the
3339         // localized screen font sizes.
3340         prefsApplied(rc_);
3341         // FIXME: these need lfuns
3342         // FIXME UNICODE
3343         Author const & author = 
3344                 Author(from_utf8(rc_.user_name), from_utf8(rc_.user_email));
3345         theBufferList().recordCurrentAuthor(author);
3346
3347         lyx::formats = formats_;
3348
3349         theConverters() = converters_;
3350         theConverters().update(lyx::formats);
3351         theConverters().buildGraph();
3352
3353         theMovers() = movers_;
3354
3355         vector<string>::const_iterator it = colors_.begin();
3356         vector<string>::const_iterator const end = colors_.end();
3357         for (; it != end; ++it)
3358                 dispatch(FuncRequest(LFUN_SET_COLOR, *it));
3359         colors_.clear();
3360
3361         if (update_screen_font_) {
3362                 dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3363                 update_screen_font_ = false;
3364         }
3365
3366         // The Save button has been pressed
3367         if (isClosing())
3368                 dispatch(FuncRequest(LFUN_PREFERENCES_SAVE));
3369 }
3370
3371
3372 void GuiPreferences::setColor(ColorCode col, QString const & hex)
3373 {
3374         colors_.push_back(lcolor.getLyXName(col) + ' ' + fromqstr(hex));
3375 }
3376
3377
3378 void GuiPreferences::updateScreenFonts()
3379 {
3380         update_screen_font_ = true;
3381 }
3382
3383
3384 QString GuiPreferences::browsebind(QString const & file) const
3385 {
3386         return browseLibFile("bind", file, "bind", qt_("Choose bind file"),
3387                              QStringList(qt_("LyX bind files (*.bind)")));
3388 }
3389
3390
3391 QString GuiPreferences::browseUI(QString const & file) const
3392 {
3393         return browseLibFile("ui", file, "ui", qt_("Choose UI file"),
3394                              QStringList(qt_("LyX UI files (*.ui)")));
3395 }
3396
3397
3398 QString GuiPreferences::browsekbmap(QString const & file) const
3399 {
3400         return browseLibFile("kbd", file, "kmap", qt_("Choose keyboard map"),
3401                              QStringList(qt_("LyX keyboard maps (*.kmap)")));
3402 }
3403
3404
3405 QString GuiPreferences::browse(QString const & file,
3406         QString const & title) const
3407 {
3408         return browseFile(file, title, QStringList(), true);
3409 }
3410
3411
3412 Dialog * createGuiPreferences(GuiView & lv) { return new GuiPreferences(lv); }
3413
3414
3415 } // namespace frontend
3416 } // namespace lyx
3417
3418 #include "moc_GuiPrefs.cpp"