]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiDocument.cpp
Load mathtools.sty automatically (bug #7949) and make lyx2lyx reversion
[lyx.git] / src / frontends / qt4 / GuiDocument.cpp
1 /**
2  * \file GuiDocument.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Edwin Leuven
7  * \author Richard Heck (modules)
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "GuiDocument.h"
15
16 #include "GuiApplication.h"
17 #include "GuiBranches.h"
18 #include "GuiIndices.h"
19 #include "GuiSelectionManager.h"
20 #include "LaTeXHighlighter.h"
21 #include "LengthCombo.h"
22 #include "PanelStack.h"
23 #include "Validator.h"
24
25 #include "LayoutFile.h"
26 #include "BranchList.h"
27 #include "buffer_funcs.h"
28 #include "Buffer.h"
29 #include "BufferParams.h"
30 #include "BufferView.h"
31 #include "Color.h"
32 #include "ColorCache.h"
33 #include "Encoding.h"
34 #include "FloatPlacement.h"
35 #include "Format.h"
36 #include "FuncRequest.h"
37 #include "HSpace.h"
38 #include "IndicesList.h"
39 #include "Language.h"
40 #include "LaTeXFeatures.h"
41 #include "Layout.h"
42 #include "LayoutModuleList.h"
43 #include "LyXRC.h"
44 #include "ModuleList.h"
45 #include "OutputParams.h"
46 #include "PDFOptions.h"
47 #include "qt_helpers.h"
48 #include "Spacing.h"
49 #include "TextClass.h"
50
51 #include "insets/InsetListingsParams.h"
52
53 #include "support/debug.h"
54 #include "support/FileName.h"
55 #include "support/filetools.h"
56 #include "support/gettext.h"
57 #include "support/lassert.h"
58 #include "support/lstrings.h"
59
60 #include "frontends/alert.h"
61
62 #include <QAbstractItemModel>
63 #include <QHeaderView>
64 #include <QColor>
65 #include <QColorDialog>
66 #include <QCloseEvent>
67 #include <QFontDatabase>
68 #include <QScrollBar>
69 #include <QTextCursor>
70
71 #include <sstream>
72 #include <vector>
73
74 #ifdef IN
75 #undef IN
76 #endif
77
78
79 // a style sheet for buttons
80 // this is for example used for the background color setting button
81 static inline QString colorButtonStyleSheet(QColor const & bgColor)
82 {
83         if (bgColor.isValid()) {
84                 QString rc = QLatin1String("background-color:");
85                 rc += bgColor.name();
86                 return rc;
87         }
88         return QString();
89 }
90
91
92 using namespace std;
93 using namespace lyx::support;
94
95
96 namespace {
97
98 char const * const tex_graphics[] =
99 {
100         "default", "dvialw", "dvilaser", "dvipdf", "dvipdfm", "dvipdfmx",
101         "dvips", "dvipsone", "dvitops", "dviwin", "dviwindo", "dvi2ps", "emtex",
102         "ln", "oztex", "pctexhp", "pctexps", "pctexwin", "pctex32", "pdftex",
103         "psprint", "pubps", "tcidvi", "textures", "truetex", "vtex", "xdvi",
104         "xetex", "none", ""
105 };
106
107
108 char const * const tex_graphics_gui[] =
109 {
110         N_("Default"), "dvialw", "DviLaser", "dvipdf", "DVIPDFM", "DVIPDFMx",
111         "Dvips", "DVIPSONE", "DVItoPS", "DVIWIN", "DVIWindo", "dvi2ps", "EmTeX",
112         "LN", "OzTeX", "pctexhp", "pctexps", "pctexwin", "PCTeX32", "pdfTeX",
113         "psprint", "pubps", "tcidvi", "Textures", "TrueTeX", "VTeX", "xdvi",
114         "XeTeX", N_("None"), ""
115 };
116
117
118 char const * const tex_fonts_roman[] =
119 {
120         "default", "cmr", "lmodern", "ae", "times", "palatino",
121         "charter", "newcent", "bookman", "utopia", "beraserif",
122         "ccfonts", "chancery", ""
123 };
124
125
126 char const * tex_fonts_roman_gui[] =
127 {
128         N_("Default"), N_("Computer Modern Roman"), N_("Latin Modern Roman"),
129         N_("AE (Almost European)"), N_("Times Roman"), N_("Palatino"),
130         N_("Bitstream Charter"), N_("New Century Schoolbook"), N_("Bookman"),
131         N_("Utopia"),  N_("Bera Serif"), N_("Concrete Roman"), N_("Zapf Chancery"),
132         ""
133 };
134
135
136 char const * const tex_fonts_sans[] =
137 {
138         "default", "cmss", "lmss", "helvet", "avant", "berasans", "cmbr", ""
139 };
140
141
142 char const * tex_fonts_sans_gui[] =
143 {
144         N_("Default"), N_("Computer Modern Sans"), N_("Latin Modern Sans"),
145         N_("Helvetica"), N_("Avant Garde"), N_("Bera Sans"), N_("CM Bright"), ""
146 };
147
148
149 char const * const tex_fonts_monospaced[] =
150 {
151         "default", "cmtt", "lmtt", "courier", "beramono", "luximono", "cmtl", ""
152 };
153
154
155 char const * tex_fonts_monospaced_gui[] =
156 {
157         N_("Default"), N_("Computer Modern Typewriter"),
158         N_("Latin Modern Typewriter"), N_("Courier"), N_("Bera Mono"),
159         N_("LuxiMono"), N_("CM Typewriter Light"), ""
160 };
161
162
163 char const * backref_opts[] =
164 {
165         "false", "section", "slide", "page", ""
166 };
167
168
169 char const * backref_opts_gui[] =
170 {
171         N_("Off"), N_("Section"), N_("Slide"), N_("Page"), ""
172 };
173
174
175 char const * packages_gui[][4] =
176 {
177         {"amsmath",
178          N_("&Use AMS math package automatically"),
179          N_("Use AMS &math package"),
180          N_("The AMS LaTeX packages are only used if symbols from the AMS math toolbars are inserted into formulas")},
181         {"esint",
182          N_("Use esint package &automatically"),
183          N_("Use &esint package"),
184          N_("The LaTeX package esint is only used if special integral symbols are inserted into formulas")},
185         {"mathdots",
186          N_("Use math&dots package automatically"),
187          N_("Use mathdo&ts package"),
188          N_("The LaTeX package mathdots is only used if the command \\iddots is inserted into formulas")},
189         {"mathtools",
190          N_("Use mathtools package automatically"),
191          N_("Use mathtools package"),
192          N_("The LaTeX package mathtools is only used if some mathematical relations are inserted into formulas")},
193         {"mhchem",
194          N_("Use mhchem &package automatically"),
195          N_("Use mh&chem package"),
196          N_("The LaTeX package mhchem is only used if either the command \\ce or \\cf is inserted into formulas")},
197         {"undertilde",
198          N_("Use u&ndertilde package automatically"),
199          N_("Use undertilde pac&kage"),
200          N_("The LaTeX package undertilde is only used if you use the math frame decoration 'utilde'")},
201         {"", "", "", ""}
202 };
203
204
205 vector<pair<string, QString> > pagestyles;
206
207
208 } // anonymous namespace
209
210 namespace lyx {
211
212 RGBColor set_backgroundcolor;
213 bool is_backgroundcolor;
214 RGBColor set_fontcolor;
215 bool is_fontcolor;
216 RGBColor set_notefontcolor;
217 RGBColor set_boxbgcolor;
218
219 namespace {
220 // used when sorting the textclass list.
221 class less_textclass_avail_desc
222         : public binary_function<string, string, int>
223 {
224 public:
225         bool operator()(string const & lhs, string const & rhs) const
226         {
227                 // Ordering criteria:
228                 //   1. Availability of text class
229                 //   2. Description (lexicographic)
230                 LayoutFile const & tc1 = LayoutFileList::get()[lhs];
231                 LayoutFile const & tc2 = LayoutFileList::get()[rhs];
232                 int const order = compare_no_case(
233                         translateIfPossible(from_utf8(tc1.description())),
234                         translateIfPossible(from_utf8(tc2.description())));
235                 return (tc1.isTeXClassAvailable() && !tc2.isTeXClassAvailable()) ||
236                         (tc1.isTeXClassAvailable() == tc2.isTeXClassAvailable() && order < 0);
237         }
238 };
239
240 }
241
242 namespace frontend {
243 namespace {
244
245 vector<string> getRequiredList(string const & modName)
246 {
247         LyXModule const * const mod = theModuleList[modName];
248         if (!mod)
249                 return vector<string>(); //empty such thing
250         return mod->getRequiredModules();
251 }
252
253
254 vector<string> getExcludedList(string const & modName)
255 {
256         LyXModule const * const mod = theModuleList[modName];
257         if (!mod)
258                 return vector<string>(); //empty such thing
259         return mod->getExcludedModules();
260 }
261
262
263 docstring getModuleDescription(string const & modName)
264 {
265         LyXModule const * const mod = theModuleList[modName];
266         if (!mod)
267                 return _("Module not found!");
268         // FIXME Unicode
269         return translateIfPossible(from_utf8(mod->getDescription()));
270 }
271
272
273 vector<string> getPackageList(string const & modName)
274 {
275         LyXModule const * const mod = theModuleList[modName];
276         if (!mod)
277                 return vector<string>(); //empty such thing
278         return mod->getPackageList();
279 }
280
281
282 bool isModuleAvailable(string const & modName)
283 {
284         LyXModule const * const mod = theModuleList[modName];
285         if (!mod)
286                 return false;
287         return mod->isAvailable();
288 }
289
290 } // anonymous namespace
291
292
293 /////////////////////////////////////////////////////////////////////
294 //
295 // ModuleSelectionManager
296 //
297 /////////////////////////////////////////////////////////////////////
298
299 /// SelectionManager for use with modules
300 class ModuleSelectionManager : public GuiSelectionManager
301 {
302 public:
303         ///
304         ModuleSelectionManager(
305                 QTreeView * availableLV,
306                 QListView * selectedLV,
307                 QPushButton * addPB,
308                 QPushButton * delPB,
309                 QPushButton * upPB,
310                 QPushButton * downPB,
311                 GuiIdListModel * availableModel,
312                 GuiIdListModel * selectedModel,
313                 GuiDocument const * container)
314         : GuiSelectionManager(availableLV, selectedLV, addPB, delPB,
315                                 upPB, downPB, availableModel, selectedModel), container_(container)
316                 {}
317         ///
318         void updateProvidedModules(LayoutModuleList const & pm)
319                         { provided_modules_ = pm.list(); }
320         ///
321         void updateExcludedModules(LayoutModuleList const & em)
322                         { excluded_modules_ = em.list(); }
323 private:
324         ///
325         virtual void updateAddPB();
326         ///
327         virtual void updateUpPB();
328         ///
329         virtual void updateDownPB();
330         ///
331         virtual void updateDelPB();
332         /// returns availableModel as a GuiIdListModel
333         GuiIdListModel * getAvailableModel()
334         {
335                 return dynamic_cast<GuiIdListModel *>(availableModel);
336         }
337         /// returns selectedModel as a GuiIdListModel
338         GuiIdListModel * getSelectedModel()
339         {
340                 return dynamic_cast<GuiIdListModel *>(selectedModel);
341         }
342         /// keeps a list of the modules the text class provides
343         list<string> provided_modules_;
344         /// similarly...
345         list<string> excluded_modules_;
346         ///
347         GuiDocument const * container_;
348 };
349
350 void ModuleSelectionManager::updateAddPB()
351 {
352         int const arows = availableModel->rowCount();
353         QModelIndexList const avail_sels =
354                         availableLV->selectionModel()->selectedIndexes();
355
356         // disable if there aren't any modules (?), if none of them is chosen
357         // in the dialog, or if the chosen one is already selected for use.
358         if (arows == 0 || avail_sels.isEmpty() || isSelected(avail_sels.first())) {
359                 addPB->setEnabled(false);
360                 return;
361         }
362
363         QModelIndex const & idx = availableLV->selectionModel()->currentIndex();
364         string const modname = getAvailableModel()->getIDString(idx.row());
365
366         bool const enable =
367                 container_->params().moduleCanBeAdded(modname);
368         addPB->setEnabled(enable);
369 }
370
371
372 void ModuleSelectionManager::updateDownPB()
373 {
374         int const srows = selectedModel->rowCount();
375         if (srows == 0) {
376                 downPB->setEnabled(false);
377                 return;
378         }
379         QModelIndex const & curidx = selectedLV->selectionModel()->currentIndex();
380         int const curRow = curidx.row();
381         if (curRow < 0 || curRow >= srows - 1) { // invalid or last item
382                 downPB->setEnabled(false);
383                 return;
384         }
385
386         // determine whether immediately succeding element requires this one
387         string const curmodname = getSelectedModel()->getIDString(curRow);
388         string const nextmodname = getSelectedModel()->getIDString(curRow + 1);
389
390         vector<string> reqs = getRequiredList(nextmodname);
391
392         // if it doesn't require anything....
393         if (reqs.empty()) {
394                 downPB->setEnabled(true);
395                 return;
396         }
397
398         // Enable it if this module isn't required.
399         // FIXME This should perhaps be more flexible and check whether, even
400         // if the next one is required, there is also an earlier one that will do.
401         downPB->setEnabled(
402                         find(reqs.begin(), reqs.end(), curmodname) == reqs.end());
403 }
404
405 void ModuleSelectionManager::updateUpPB()
406 {
407         int const srows = selectedModel->rowCount();
408         if (srows == 0) {
409                 upPB->setEnabled(false);
410                 return;
411         }
412
413         QModelIndex const & curIdx = selectedLV->selectionModel()->currentIndex();
414         int curRow = curIdx.row();
415         if (curRow <= 0 || curRow > srows - 1) { // first item or invalid
416                 upPB->setEnabled(false);
417                 return;
418         }
419         string const curmodname = getSelectedModel()->getIDString(curRow);
420
421         // determine whether immediately preceding element is required by this one
422         vector<string> reqs = getRequiredList(curmodname);
423
424         // if this one doesn't require anything....
425         if (reqs.empty()) {
426                 upPB->setEnabled(true);
427                 return;
428         }
429
430
431         // Enable it if the preceding module isn't required.
432         // NOTE This is less flexible than it might be. We could check whether, even
433         // if the previous one is required, there is an earlier one that would do.
434         string const premod = getSelectedModel()->getIDString(curRow - 1);
435         upPB->setEnabled(find(reqs.begin(), reqs.end(), premod) == reqs.end());
436 }
437
438 void ModuleSelectionManager::updateDelPB()
439 {
440         int const srows = selectedModel->rowCount();
441         if (srows == 0) {
442                 deletePB->setEnabled(false);
443                 return;
444         }
445
446         QModelIndex const & curidx =
447                 selectedLV->selectionModel()->currentIndex();
448         int const curRow = curidx.row();
449         if (curRow < 0 || curRow >= srows) { // invalid index?
450                 deletePB->setEnabled(false);
451                 return;
452         }
453
454         string const curmodname = getSelectedModel()->getIDString(curRow);
455
456         // We're looking here for a reason NOT to enable the button. If we
457         // find one, we disable it and return. If we don't, we'll end up at
458         // the end of the function, and then we enable it.
459         for (int i = curRow + 1; i < srows; ++i) {
460                 string const thisMod = getSelectedModel()->getIDString(i);
461                 vector<string> reqs = getRequiredList(thisMod);
462                 //does this one require us?
463                 if (find(reqs.begin(), reqs.end(), curmodname) == reqs.end())
464                         //no...
465                         continue;
466
467                 // OK, so this module requires us
468                 // is there an EARLIER module that also satisfies the require?
469                 // NOTE We demand that it be earlier to keep the list of modules
470                 // consistent with the rule that a module must be proceeded by a
471                 // required module. There would be more flexible ways to proceed,
472                 // but that would be a lot more complicated, and the logic here is
473                 // already complicated. (That's why I've left the debugging code.)
474                 // lyxerr << "Testing " << thisMod << endl;
475                 bool foundone = false;
476                 for (int j = 0; j < curRow; ++j) {
477                         string const mod = getSelectedModel()->getIDString(j);
478                         // lyxerr << "In loop: Testing " << mod << endl;
479                         // do we satisfy the require?
480                         if (find(reqs.begin(), reqs.end(), mod) != reqs.end()) {
481                                 // lyxerr << mod << " does the trick." << endl;
482                                 foundone = true;
483                                 break;
484                         }
485                 }
486                 // did we find a module to satisfy the require?
487                 if (!foundone) {
488                         // lyxerr << "No matching module found." << endl;
489                         deletePB->setEnabled(false);
490                         return;
491                 }
492         }
493         // lyxerr << "All's well that ends well." << endl;
494         deletePB->setEnabled(true);
495 }
496
497
498 /////////////////////////////////////////////////////////////////////
499 //
500 // PreambleModule
501 //
502 /////////////////////////////////////////////////////////////////////
503
504 PreambleModule::PreambleModule() : current_id_(0)
505 {
506         // This is not a memory leak. The object will be destroyed
507         // with this.
508         (void) new LaTeXHighlighter(preambleTE->document());
509         setFocusProxy(preambleTE);
510         connect(preambleTE, SIGNAL(textChanged()), this, SIGNAL(changed()));
511 }
512
513
514 void PreambleModule::update(BufferParams const & params, BufferId id)
515 {
516         QString preamble = toqstr(params.preamble);
517         // Nothing to do if the params and preamble are unchanged.
518         if (id == current_id_
519                 && preamble == preambleTE->document()->toPlainText())
520                 return;
521
522         QTextCursor cur = preambleTE->textCursor();
523         // Save the coords before switching to the new one.
524         preamble_coords_[current_id_] =
525                 make_pair(cur.position(), preambleTE->verticalScrollBar()->value());
526
527         // Save the params address for further use.
528         current_id_ = id;
529         preambleTE->document()->setPlainText(preamble);
530         Coords::const_iterator it = preamble_coords_.find(current_id_);
531         if (it == preamble_coords_.end())
532                 // First time we open this one.
533                 preamble_coords_[current_id_] = make_pair(0, 0);
534         else {
535                 // Restore saved coords.
536                 QTextCursor cur = preambleTE->textCursor();
537                 cur.setPosition(it->second.first);
538                 preambleTE->setTextCursor(cur);
539                 preambleTE->verticalScrollBar()->setValue(it->second.second);
540         }
541 }
542
543
544 void PreambleModule::apply(BufferParams & params)
545 {
546         params.preamble = fromqstr(preambleTE->document()->toPlainText());
547 }
548
549
550 void PreambleModule::closeEvent(QCloseEvent * e)
551 {
552         // Save the coords before closing.
553         QTextCursor cur = preambleTE->textCursor();
554         preamble_coords_[current_id_] =
555                 make_pair(cur.position(), preambleTE->verticalScrollBar()->value());
556         e->accept();
557 }
558
559
560 /////////////////////////////////////////////////////////////////////
561 //
562 // LocalLayout
563 //
564 /////////////////////////////////////////////////////////////////////
565
566
567 LocalLayout::LocalLayout() : current_id_(0), is_valid_(false)
568 {
569         connect(locallayoutTE, SIGNAL(textChanged()), this, SLOT(textChanged()));
570         connect(validatePB, SIGNAL(clicked()), this, SLOT(validatePressed()));
571         connect(convertPB, SIGNAL(clicked()), this, SLOT(convertPressed()));
572 }
573
574
575 void LocalLayout::update(BufferParams const & params, BufferId id)
576 {
577         QString layout = toqstr(params.local_layout);
578         // Nothing to do if the params and preamble are unchanged.
579         if (id == current_id_
580                 && layout == locallayoutTE->document()->toPlainText())
581                 return;
582
583         // Save the params address for further use.
584         current_id_ = id;
585         locallayoutTE->document()->setPlainText(layout);
586         validate();
587 }
588
589
590 void LocalLayout::apply(BufferParams & params)
591 {
592         string const layout = fromqstr(locallayoutTE->document()->toPlainText());
593         params.local_layout = layout;
594 }
595
596
597 void LocalLayout::textChanged()
598 {
599         static const QString unknown = qt_("Press button to check validity...");
600
601         is_valid_ = false;
602         validLB->setText(unknown);
603         validatePB->setEnabled(true);
604         convertPB->setEnabled(false);
605         changed();
606 }
607
608
609 void LocalLayout::convert() {
610         string const layout =
611                 fromqstr(locallayoutTE->document()->toPlainText().trimmed());
612         string const newlayout = TextClass::convert(layout);
613         LYXERR0(newlayout);
614         if (newlayout.empty()) {
615                 Alert::error(_("Conversion Failed!"),
616                       _("Failed to convert local layout to current format."));
617         } else {
618                 locallayoutTE->setPlainText(toqstr(newlayout));
619         }
620         validate();
621 }
622
623
624 void LocalLayout::convertPressed() {
625         convert();
626         changed();
627 }
628
629
630 void LocalLayout::validate() {
631         static const QString valid = qt_("Layout is valid!");
632         static const QString vtext =
633                 toqstr("<p style=\"font-weight: bold; \">")
634                   + valid + toqstr("</p>");
635         static const QString invalid = qt_("Layout is invalid!");
636         static const QString ivtext =
637                 toqstr("<p style=\"color: #c00000; font-weight: bold; \">")
638                   + invalid + toqstr("</p>");
639
640         string const layout =
641                 fromqstr(locallayoutTE->document()->toPlainText().trimmed());
642         if (layout.empty()) {
643                 is_valid_ = true;
644                 validatePB->setEnabled(false);
645                 validLB->setText("");
646                 convertPB->hide();
647                 convertLB->hide();
648         } else {
649                 TextClass::ReturnValues const ret = TextClass::validate(layout);
650                 is_valid_ = (ret == TextClass::OK) || (ret == TextClass::OK_OLDFORMAT);
651                 validatePB->setEnabled(false);
652                 validLB->setText(is_valid_ ? vtext : ivtext);
653                 if (ret == TextClass::OK_OLDFORMAT) {
654                         convertPB->show();
655                         convertPB->setEnabled(true);
656                         convertLB->setText(qt_("Convert to current format"));
657                         convertLB->show();
658                 } else {
659                         convertPB->hide();
660                         convertLB->hide();
661                 }
662         }
663 }
664
665
666 void LocalLayout::validatePressed() {
667         validate();
668         changed();
669 }
670
671
672 /////////////////////////////////////////////////////////////////////
673 //
674 // DocumentDialog
675 //
676 /////////////////////////////////////////////////////////////////////
677
678
679 GuiDocument::GuiDocument(GuiView & lv)
680         : GuiDialog(lv, "document", qt_("Document Settings"))
681 {
682         setupUi(this);
683
684         connect(okPB, SIGNAL(clicked()), this, SLOT(slotOK()));
685         connect(applyPB, SIGNAL(clicked()), this, SLOT(slotApply()));
686         connect(closePB, SIGNAL(clicked()), this, SLOT(slotClose()));
687         connect(restorePB, SIGNAL(clicked()), this, SLOT(slotRestore()));
688
689         connect(savePB, SIGNAL(clicked()), this, SLOT(saveDefaultClicked()));
690         connect(defaultPB, SIGNAL(clicked()), this, SLOT(useDefaultsClicked()));
691
692         // Manage the restore, ok, apply, restore and cancel/close buttons
693         bc().setPolicy(ButtonPolicy::NoRepeatedApplyReadOnlyPolicy);
694         bc().setOK(okPB);
695         bc().setApply(applyPB);
696         bc().setCancel(closePB);
697         bc().setRestore(restorePB);
698
699
700         // text layout
701         textLayoutModule = new UiWidget<Ui::TextLayoutUi>;
702         connect(textLayoutModule->lspacingCO, SIGNAL(activated(int)),
703                 this, SLOT(change_adaptor()));
704         connect(textLayoutModule->lspacingCO, SIGNAL(activated(int)),
705                 this, SLOT(setLSpacing(int)));
706         connect(textLayoutModule->lspacingLE, SIGNAL(textChanged(const QString &)),
707                 this, SLOT(change_adaptor()));
708
709         connect(textLayoutModule->indentRB, SIGNAL(clicked()),
710                 this, SLOT(change_adaptor()));
711         connect(textLayoutModule->indentRB, SIGNAL(toggled(bool)),
712                 textLayoutModule->indentCO, SLOT(setEnabled(bool)));
713         connect(textLayoutModule->indentCO, SIGNAL(activated(int)),
714                 this, SLOT(change_adaptor()));
715         connect(textLayoutModule->indentCO, SIGNAL(activated(int)),
716                 this, SLOT(setIndent(int)));
717         connect(textLayoutModule->indentLE, SIGNAL(textChanged(const QString &)),
718                 this, SLOT(change_adaptor()));
719         connect(textLayoutModule->indentLengthCO, SIGNAL(activated(int)),
720                 this, SLOT(change_adaptor()));
721
722         connect(textLayoutModule->skipRB, SIGNAL(clicked()),
723                 this, SLOT(change_adaptor()));
724         connect(textLayoutModule->skipRB, SIGNAL(toggled(bool)),
725                 textLayoutModule->skipCO, SLOT(setEnabled(bool)));
726         connect(textLayoutModule->skipCO, SIGNAL(activated(int)),
727                 this, SLOT(change_adaptor()));
728         connect(textLayoutModule->skipCO, SIGNAL(activated(int)),
729                 this, SLOT(setSkip(int)));
730         connect(textLayoutModule->skipLE, SIGNAL(textChanged(const QString &)),
731                 this, SLOT(change_adaptor()));
732         connect(textLayoutModule->skipLengthCO, SIGNAL(activated(int)),
733                 this, SLOT(change_adaptor()));
734
735         connect(textLayoutModule->indentRB, SIGNAL(toggled(bool)),
736                 this, SLOT(enableIndent(bool)));
737         connect(textLayoutModule->skipRB, SIGNAL(toggled(bool)),
738                 this, SLOT(enableSkip(bool)));
739
740         connect(textLayoutModule->twoColumnCB, SIGNAL(clicked()),
741                 this, SLOT(change_adaptor()));
742         connect(textLayoutModule->twoColumnCB, SIGNAL(clicked()),
743                 this, SLOT(setColSep()));
744         connect(textLayoutModule->justCB, SIGNAL(clicked()),
745                 this, SLOT(change_adaptor()));
746
747         textLayoutModule->lspacingLE->setValidator(new QDoubleValidator(
748                 textLayoutModule->lspacingLE));
749         textLayoutModule->indentLE->setValidator(unsignedLengthValidator(
750                 textLayoutModule->indentLE));
751         textLayoutModule->skipLE->setValidator(unsignedGlueLengthValidator(
752                 textLayoutModule->skipLE));
753
754         textLayoutModule->indentCO->addItem(qt_("Default"));
755         textLayoutModule->indentCO->addItem(qt_("Custom"));
756         textLayoutModule->skipCO->addItem(qt_("SmallSkip"));
757         textLayoutModule->skipCO->addItem(qt_("MedSkip"));
758         textLayoutModule->skipCO->addItem(qt_("BigSkip"));
759         textLayoutModule->skipCO->addItem(qt_("Custom"));
760         textLayoutModule->lspacingCO->insertItem(
761                 Spacing::Single, qt_("Single"));
762         textLayoutModule->lspacingCO->insertItem(
763                 Spacing::Onehalf, qt_("OneHalf"));
764         textLayoutModule->lspacingCO->insertItem(
765                 Spacing::Double, qt_("Double"));
766         textLayoutModule->lspacingCO->insertItem(
767                 Spacing::Other, qt_("Custom"));
768         // initialize the length validator
769         bc().addCheckedLineEdit(textLayoutModule->indentLE);
770         bc().addCheckedLineEdit(textLayoutModule->skipLE);
771
772
773         // master/child handling
774         masterChildModule = new UiWidget<Ui::MasterChildUi>;
775
776         connect(masterChildModule->childrenTW, SIGNAL(itemDoubleClicked(QTreeWidgetItem *, int)),
777                 this, SLOT(includeonlyClicked(QTreeWidgetItem *, int)));
778         connect(masterChildModule->includeonlyRB, SIGNAL(toggled(bool)),
779                 masterChildModule->childrenTW, SLOT(setEnabled(bool)));
780         connect(masterChildModule->includeonlyRB, SIGNAL(toggled(bool)),
781                 masterChildModule->maintainAuxCB, SLOT(setEnabled(bool)));
782         connect(masterChildModule->includeallRB, SIGNAL(clicked()),
783                 this, SLOT(change_adaptor()));
784         connect(masterChildModule->includeonlyRB, SIGNAL(clicked()),
785                 this, SLOT(change_adaptor()));
786         connect(masterChildModule->maintainAuxCB, SIGNAL(clicked()),
787                 this, SLOT(change_adaptor()));
788         masterChildModule->childrenTW->setColumnCount(2);
789         masterChildModule->childrenTW->headerItem()->setText(0, qt_("Child Document"));
790         masterChildModule->childrenTW->headerItem()->setText(1, qt_("Include to Output"));
791         masterChildModule->childrenTW->resizeColumnToContents(1);
792         masterChildModule->childrenTW->resizeColumnToContents(2);
793
794
795         // output
796         outputModule = new UiWidget<Ui::OutputUi>;
797
798         connect(outputModule->defaultFormatCO, SIGNAL(activated(int)),
799                 this, SLOT(change_adaptor()));
800         connect(outputModule->mathimgSB, SIGNAL(valueChanged(double)),
801                 this, SLOT(change_adaptor()));
802         connect(outputModule->strictCB, SIGNAL(stateChanged(int)),
803                 this, SLOT(change_adaptor()));
804         connect(outputModule->cssCB, SIGNAL(stateChanged(int)),
805                 this, SLOT(change_adaptor()));
806         connect(outputModule->mathoutCB, SIGNAL(currentIndexChanged(int)),
807                 this, SLOT(change_adaptor()));
808
809         connect(outputModule->outputsyncCB, SIGNAL(clicked()),
810                 this, SLOT(change_adaptor()));
811         connect(outputModule->synccustomCB, SIGNAL(editTextChanged(QString)),
812                 this, SLOT(change_adaptor()));
813         outputModule->synccustomCB->addItem("");
814         outputModule->synccustomCB->addItem("\\synctex=1");
815         outputModule->synccustomCB->addItem("\\synctex=-1");
816         outputModule->synccustomCB->addItem("\\usepackage[active]{srcltx}");
817
818         outputModule->synccustomCB->setValidator(new NoNewLineValidator(
819                 outputModule->synccustomCB));
820
821         // fonts
822         fontModule = new UiWidget<Ui::FontUi>;
823         connect(fontModule->osFontsCB, SIGNAL(clicked()),
824                 this, SLOT(change_adaptor()));
825         connect(fontModule->osFontsCB, SIGNAL(toggled(bool)),
826                 this, SLOT(osFontsChanged(bool)));
827         connect(fontModule->fontsRomanCO, SIGNAL(activated(int)),
828                 this, SLOT(change_adaptor()));
829         connect(fontModule->fontsRomanCO, SIGNAL(activated(int)),
830                 this, SLOT(romanChanged(int)));
831         connect(fontModule->fontsSansCO, SIGNAL(activated(int)),
832                 this, SLOT(change_adaptor()));
833         connect(fontModule->fontsSansCO, SIGNAL(activated(int)),
834                 this, SLOT(sansChanged(int)));
835         connect(fontModule->fontsTypewriterCO, SIGNAL(activated(int)),
836                 this, SLOT(change_adaptor()));
837         connect(fontModule->fontsTypewriterCO, SIGNAL(activated(int)),
838                 this, SLOT(ttChanged(int)));
839         connect(fontModule->fontsDefaultCO, SIGNAL(activated(int)),
840                 this, SLOT(change_adaptor()));
841         connect(fontModule->fontencCO, SIGNAL(activated(int)),
842                 this, SLOT(change_adaptor()));
843         connect(fontModule->fontencCO, SIGNAL(activated(int)),
844                 this, SLOT(fontencChanged(int)));
845         connect(fontModule->fontencLE, SIGNAL(textChanged(const QString &)),
846                 this, SLOT(change_adaptor()));
847         connect(fontModule->fontsizeCO, SIGNAL(activated(int)),
848                 this, SLOT(change_adaptor()));
849         connect(fontModule->cjkFontLE, SIGNAL(textChanged(const QString &)),
850                 this, SLOT(change_adaptor()));
851         connect(fontModule->scaleSansSB, SIGNAL(valueChanged(int)),
852                 this, SLOT(change_adaptor()));
853         connect(fontModule->scaleTypewriterSB, SIGNAL(valueChanged(int)),
854                 this, SLOT(change_adaptor()));
855         connect(fontModule->fontScCB, SIGNAL(clicked()),
856                 this, SLOT(change_adaptor()));
857         connect(fontModule->fontOsfCB, SIGNAL(clicked()),
858                 this, SLOT(change_adaptor()));
859
860         fontModule->fontencLE->setValidator(new NoNewLineValidator(
861                 fontModule->fontencLE));
862         fontModule->cjkFontLE->setValidator(new NoNewLineValidator(
863                 fontModule->cjkFontLE));
864
865         updateFontlist();
866
867         fontModule->fontsizeCO->addItem(qt_("Default"));
868         fontModule->fontsizeCO->addItem(qt_("10"));
869         fontModule->fontsizeCO->addItem(qt_("11"));
870         fontModule->fontsizeCO->addItem(qt_("12"));
871
872         fontModule->fontencCO->addItem(qt_("Default"));
873         fontModule->fontencCO->addItem(qt_("Custom"));
874         fontModule->fontencCO->addItem(qt_("None (no fontenc)"));
875
876         for (int n = 0; GuiDocument::fontfamilies_gui[n][0]; ++n)
877                 fontModule->fontsDefaultCO->addItem(
878                         qt_(GuiDocument::fontfamilies_gui[n]));
879
880         if (!LaTeXFeatures::isAvailable("fontspec"))
881                 fontModule->osFontsCB->setToolTip(
882                         qt_("Use OpenType and TrueType fonts directly (requires XeTeX or LuaTeX)\n"
883                             "You need to install the package \"fontspec\" to use this feature"));
884
885
886         // page layout
887         pageLayoutModule = new UiWidget<Ui::PageLayoutUi>;
888         connect(pageLayoutModule->papersizeCO, SIGNAL(activated(int)),
889                 this, SLOT(papersizeChanged(int)));
890         connect(pageLayoutModule->papersizeCO, SIGNAL(activated(int)),
891                 this, SLOT(papersizeChanged(int)));
892         connect(pageLayoutModule->portraitRB, SIGNAL(clicked()),
893                 this, SLOT(change_adaptor()));
894         connect(pageLayoutModule->papersizeCO, SIGNAL(activated(int)),
895                 this, SLOT(change_adaptor()));
896         connect(pageLayoutModule->paperheightLE, SIGNAL(textChanged(const QString &)),
897                 this, SLOT(change_adaptor()));
898         connect(pageLayoutModule->paperwidthLE, SIGNAL(textChanged(const QString &)),
899                 this, SLOT(change_adaptor()));
900         connect(pageLayoutModule->paperwidthUnitCO, SIGNAL(activated(int)),
901                 this, SLOT(change_adaptor()));
902         connect(pageLayoutModule->paperheightUnitCO, SIGNAL(activated(int)),
903                 this, SLOT(change_adaptor()));
904         connect(pageLayoutModule->portraitRB, SIGNAL(clicked()),
905                 this, SLOT(change_adaptor()));
906         connect(pageLayoutModule->landscapeRB, SIGNAL(clicked()),
907                 this, SLOT(change_adaptor()));
908         connect(pageLayoutModule->facingPagesCB, SIGNAL(clicked()),
909                 this, SLOT(change_adaptor()));
910         connect(pageLayoutModule->pagestyleCO, SIGNAL(activated(int)),
911                 this, SLOT(change_adaptor()));
912
913         pageLayoutModule->pagestyleCO->addItem(qt_("Default"));
914         pageLayoutModule->pagestyleCO->addItem(qt_("empty"));
915         pageLayoutModule->pagestyleCO->addItem(qt_("plain"));
916         pageLayoutModule->pagestyleCO->addItem(qt_("headings"));
917         pageLayoutModule->pagestyleCO->addItem(qt_("fancy"));
918         bc().addCheckedLineEdit(pageLayoutModule->paperheightLE,
919                 pageLayoutModule->paperheightL);
920         bc().addCheckedLineEdit(pageLayoutModule->paperwidthLE,
921                 pageLayoutModule->paperwidthL);
922
923         QComboBox * cb = pageLayoutModule->papersizeCO;
924         cb->addItem(qt_("Default"));
925         cb->addItem(qt_("Custom"));
926         cb->addItem(qt_("US letter"));
927         cb->addItem(qt_("US legal"));
928         cb->addItem(qt_("US executive"));
929         cb->addItem(qt_("A0"));
930         cb->addItem(qt_("A1"));
931         cb->addItem(qt_("A2"));
932         cb->addItem(qt_("A3"));
933         cb->addItem(qt_("A4"));
934         cb->addItem(qt_("A5"));
935         cb->addItem(qt_("A6"));
936         cb->addItem(qt_("B0"));
937         cb->addItem(qt_("B1"));
938         cb->addItem(qt_("B2"));
939         cb->addItem(qt_("B3"));
940         cb->addItem(qt_("B4"));
941         cb->addItem(qt_("B5"));
942         cb->addItem(qt_("B6"));
943         cb->addItem(qt_("C0"));
944         cb->addItem(qt_("C1"));
945         cb->addItem(qt_("C2"));
946         cb->addItem(qt_("C3"));
947         cb->addItem(qt_("C4"));
948         cb->addItem(qt_("C5"));
949         cb->addItem(qt_("C6"));
950         cb->addItem(qt_("JIS B0"));
951         cb->addItem(qt_("JIS B1"));
952         cb->addItem(qt_("JIS B2"));
953         cb->addItem(qt_("JIS B3"));
954         cb->addItem(qt_("JIS B4"));
955         cb->addItem(qt_("JIS B5"));
956         cb->addItem(qt_("JIS B6"));
957         // remove the %-items from the unit choice
958         pageLayoutModule->paperwidthUnitCO->noPercents();
959         pageLayoutModule->paperheightUnitCO->noPercents();
960         pageLayoutModule->paperheightLE->setValidator(unsignedLengthValidator(
961                 pageLayoutModule->paperheightLE));
962         pageLayoutModule->paperwidthLE->setValidator(unsignedLengthValidator(
963                 pageLayoutModule->paperwidthLE));
964
965
966         // margins
967         marginsModule = new UiWidget<Ui::MarginsUi>;
968         connect(marginsModule->marginCB, SIGNAL(toggled(bool)),
969                 this, SLOT(setCustomMargins(bool)));
970         connect(marginsModule->marginCB, SIGNAL(clicked()),
971                 this, SLOT(change_adaptor()));
972         connect(marginsModule->topLE, SIGNAL(textChanged(QString)),
973                 this, SLOT(change_adaptor()));
974         connect(marginsModule->topUnit, SIGNAL(activated(int)),
975                 this, SLOT(change_adaptor()));
976         connect(marginsModule->bottomLE, SIGNAL(textChanged(QString)),
977                 this, SLOT(change_adaptor()));
978         connect(marginsModule->bottomUnit, SIGNAL(activated(int)),
979                 this, SLOT(change_adaptor()));
980         connect(marginsModule->innerLE, SIGNAL(textChanged(QString)),
981                 this, SLOT(change_adaptor()));
982         connect(marginsModule->innerUnit, SIGNAL(activated(int)),
983                 this, SLOT(change_adaptor()));
984         connect(marginsModule->outerLE, SIGNAL(textChanged(QString)),
985                 this, SLOT(change_adaptor()));
986         connect(marginsModule->outerUnit, SIGNAL(activated(int)),
987                 this, SLOT(change_adaptor()));
988         connect(marginsModule->headheightLE, SIGNAL(textChanged(QString)),
989                 this, SLOT(change_adaptor()));
990         connect(marginsModule->headheightUnit, SIGNAL(activated(int)),
991                 this, SLOT(change_adaptor()));
992         connect(marginsModule->headsepLE, SIGNAL(textChanged(QString)),
993                 this, SLOT(change_adaptor()));
994         connect(marginsModule->headsepUnit, SIGNAL(activated(int)),
995                 this, SLOT(change_adaptor()));
996         connect(marginsModule->footskipLE, SIGNAL(textChanged(QString)),
997                 this, SLOT(change_adaptor()));
998         connect(marginsModule->footskipUnit, SIGNAL(activated(int)),
999                 this, SLOT(change_adaptor()));
1000         connect(marginsModule->columnsepLE, SIGNAL(textChanged(QString)),
1001                 this, SLOT(change_adaptor()));
1002         connect(marginsModule->columnsepUnit, SIGNAL(activated(int)),
1003                 this, SLOT(change_adaptor()));
1004         marginsModule->topLE->setValidator(unsignedLengthValidator(
1005                 marginsModule->topLE));
1006         marginsModule->bottomLE->setValidator(unsignedLengthValidator(
1007                 marginsModule->bottomLE));
1008         marginsModule->innerLE->setValidator(unsignedLengthValidator(
1009                 marginsModule->innerLE));
1010         marginsModule->outerLE->setValidator(unsignedLengthValidator(
1011                 marginsModule->outerLE));
1012         marginsModule->headsepLE->setValidator(unsignedLengthValidator(
1013                 marginsModule->headsepLE));
1014         marginsModule->headheightLE->setValidator(unsignedLengthValidator(
1015                 marginsModule->headheightLE));
1016         marginsModule->footskipLE->setValidator(unsignedLengthValidator(
1017                 marginsModule->footskipLE));
1018         marginsModule->columnsepLE->setValidator(unsignedLengthValidator(
1019                 marginsModule->columnsepLE));
1020
1021         bc().addCheckedLineEdit(marginsModule->topLE,
1022                 marginsModule->topL);
1023         bc().addCheckedLineEdit(marginsModule->bottomLE,
1024                 marginsModule->bottomL);
1025         bc().addCheckedLineEdit(marginsModule->innerLE,
1026                 marginsModule->innerL);
1027         bc().addCheckedLineEdit(marginsModule->outerLE,
1028                 marginsModule->outerL);
1029         bc().addCheckedLineEdit(marginsModule->headsepLE,
1030                 marginsModule->headsepL);
1031         bc().addCheckedLineEdit(marginsModule->headheightLE,
1032                 marginsModule->headheightL);
1033         bc().addCheckedLineEdit(marginsModule->footskipLE,
1034                 marginsModule->footskipL);
1035         bc().addCheckedLineEdit(marginsModule->columnsepLE,
1036                 marginsModule->columnsepL);
1037
1038
1039         // language & quote
1040         langModule = new UiWidget<Ui::LanguageUi>;
1041         connect(langModule->languageCO, SIGNAL(activated(int)),
1042                 this, SLOT(change_adaptor()));
1043         connect(langModule->defaultencodingRB, SIGNAL(clicked()),
1044                 this, SLOT(change_adaptor()));
1045         connect(langModule->otherencodingRB, SIGNAL(clicked()),
1046                 this, SLOT(change_adaptor()));
1047         connect(langModule->encodingCO, SIGNAL(activated(int)),
1048                 this, SLOT(change_adaptor()));
1049         connect(langModule->quoteStyleCO, SIGNAL(activated(int)),
1050                 this, SLOT(change_adaptor()));
1051         connect(langModule->languagePackageCO, SIGNAL(activated(int)),
1052                 this, SLOT(change_adaptor()));
1053         connect(langModule->languagePackageLE, SIGNAL(textChanged(QString)),
1054                 this, SLOT(change_adaptor()));
1055         connect(langModule->languagePackageCO, SIGNAL(currentIndexChanged(int)),
1056                 this, SLOT(languagePackageChanged(int)));
1057
1058         langModule->languagePackageLE->setValidator(new NoNewLineValidator(
1059                 langModule->languagePackageLE));
1060
1061         QAbstractItemModel * language_model = guiApp->languageModel();
1062         // FIXME: it would be nice if sorting was enabled/disabled via a checkbox.
1063         language_model->sort(0);
1064         langModule->languageCO->setModel(language_model);
1065         langModule->languageCO->setModelColumn(0);
1066
1067         // Always put the default encoding in the first position.
1068         langModule->encodingCO->addItem(qt_("Language Default (no inputenc)"));
1069         QStringList encodinglist;
1070         Encodings::const_iterator it = encodings.begin();
1071         Encodings::const_iterator const end = encodings.end();
1072         for (; it != end; ++it)
1073                 encodinglist.append(qt_(it->guiName()));
1074         encodinglist.sort();
1075         langModule->encodingCO->addItems(encodinglist);
1076
1077         langModule->quoteStyleCO->addItem(qt_("``text''"));
1078         langModule->quoteStyleCO->addItem(qt_("''text''"));
1079         langModule->quoteStyleCO->addItem(qt_(",,text``"));
1080         langModule->quoteStyleCO->addItem(qt_(",,text''"));
1081         langModule->quoteStyleCO->addItem(qt_("<<text>>"));
1082         langModule->quoteStyleCO->addItem(qt_(">>text<<"));
1083
1084         langModule->languagePackageCO->addItem(
1085                 qt_("Default"), toqstr("default"));
1086         langModule->languagePackageCO->addItem(
1087                 qt_("Automatic"), toqstr("auto"));
1088         langModule->languagePackageCO->addItem(
1089                 qt_("Always Babel"), toqstr("babel"));
1090         langModule->languagePackageCO->addItem(
1091                 qt_("Custom"), toqstr("custom"));
1092         langModule->languagePackageCO->addItem(
1093                 qt_("None[[language package]]"), toqstr("none"));
1094
1095
1096         // color
1097         colorModule = new UiWidget<Ui::ColorUi>;
1098         connect(colorModule->fontColorPB, SIGNAL(clicked()),
1099                 this, SLOT(changeFontColor()));
1100         connect(colorModule->delFontColorTB, SIGNAL(clicked()),
1101                 this, SLOT(deleteFontColor()));
1102         connect(colorModule->noteFontColorPB, SIGNAL(clicked()),
1103                 this, SLOT(changeNoteFontColor()));
1104         connect(colorModule->delNoteFontColorTB, SIGNAL(clicked()),
1105                 this, SLOT(deleteNoteFontColor()));
1106         connect(colorModule->backgroundPB, SIGNAL(clicked()),
1107                 this, SLOT(changeBackgroundColor()));
1108         connect(colorModule->delBackgroundTB, SIGNAL(clicked()),
1109                 this, SLOT(deleteBackgroundColor()));
1110         connect(colorModule->boxBackgroundPB, SIGNAL(clicked()),
1111                 this, SLOT(changeBoxBackgroundColor()));
1112         connect(colorModule->delBoxBackgroundTB, SIGNAL(clicked()),
1113                 this, SLOT(deleteBoxBackgroundColor()));
1114
1115
1116         // numbering
1117         numberingModule = new UiWidget<Ui::NumberingUi>;
1118         connect(numberingModule->depthSL, SIGNAL(valueChanged(int)),
1119                 this, SLOT(change_adaptor()));
1120         connect(numberingModule->tocSL, SIGNAL(valueChanged(int)),
1121                 this, SLOT(change_adaptor()));
1122         connect(numberingModule->depthSL, SIGNAL(valueChanged(int)),
1123                 this, SLOT(updateNumbering()));
1124         connect(numberingModule->tocSL, SIGNAL(valueChanged(int)),
1125                 this, SLOT(updateNumbering()));
1126         numberingModule->tocTW->setColumnCount(3);
1127         numberingModule->tocTW->headerItem()->setText(0, qt_("Example"));
1128         numberingModule->tocTW->headerItem()->setText(1, qt_("Numbered"));
1129         numberingModule->tocTW->headerItem()->setText(2, qt_("Appears in TOC"));
1130         numberingModule->tocTW->header()->setResizeMode(QHeaderView::ResizeToContents);
1131
1132
1133         // biblio
1134         biblioModule = new UiWidget<Ui::BiblioUi>;
1135         connect(biblioModule->citeNatbibRB, SIGNAL(toggled(bool)),
1136                 biblioModule->citationStyleL, SLOT(setEnabled(bool)));
1137         connect(biblioModule->citeNatbibRB, SIGNAL(toggled(bool)),
1138                 biblioModule->citeStyleCO, SLOT(setEnabled(bool)));
1139         connect(biblioModule->citeDefaultRB, SIGNAL(clicked()),
1140                 this, SLOT(biblioChanged()));
1141         connect(biblioModule->citeNatbibRB, SIGNAL(clicked()),
1142                 this, SLOT(biblioChanged()));
1143         connect(biblioModule->citeStyleCO, SIGNAL(activated(int)),
1144                 this, SLOT(biblioChanged()));
1145         connect(biblioModule->citeJurabibRB, SIGNAL(clicked()),
1146                 this, SLOT(biblioChanged()));
1147         connect(biblioModule->bibtopicCB, SIGNAL(clicked()),
1148                 this, SLOT(biblioChanged()));
1149         connect(biblioModule->bibtexCO, SIGNAL(activated(int)),
1150                 this, SLOT(bibtexChanged(int)));
1151         connect(biblioModule->bibtexOptionsLE, SIGNAL(textChanged(QString)),
1152                 this, SLOT(biblioChanged()));
1153         connect(biblioModule->bibtexStyleLE, SIGNAL(textChanged(QString)),
1154                 this, SLOT(biblioChanged()));
1155
1156         biblioModule->bibtexOptionsLE->setValidator(new NoNewLineValidator(
1157                 biblioModule->bibtexOptionsLE));
1158         biblioModule->bibtexStyleLE->setValidator(new NoNewLineValidator(
1159                 biblioModule->bibtexStyleLE));
1160
1161         biblioModule->citeStyleCO->addItem(qt_("Author-year"));
1162         biblioModule->citeStyleCO->addItem(qt_("Numerical"));
1163         biblioModule->citeStyleCO->setCurrentIndex(0);
1164
1165         // NOTE: we do not provide "custom" here for security reasons!
1166         biblioModule->bibtexCO->clear();
1167         biblioModule->bibtexCO->addItem(qt_("Default"), QString("default"));
1168         for (set<string>::const_iterator it = lyxrc.bibtex_alternatives.begin();
1169                              it != lyxrc.bibtex_alternatives.end(); ++it) {
1170                 QString const command = toqstr(*it).left(toqstr(*it).indexOf(" "));
1171                 biblioModule->bibtexCO->addItem(command, command);
1172         }
1173
1174
1175         // indices
1176         indicesModule = new GuiIndices;
1177         connect(indicesModule, SIGNAL(changed()),
1178                 this, SLOT(change_adaptor()));
1179
1180
1181         // maths
1182         // FIXME This UI has problems:
1183         //       1) It is not generic, packages_gui needs to be changed for each new package
1184         //       2) Two checkboxes have 4 states, but one is invalid (both pressed)
1185         //       3) The auto cb is not disabled if the use cb is checked
1186         mathsModule = new UiWidget<Ui::MathsUi>;
1187         vector<string> const & packages = BufferParams::auto_packages();
1188         for (size_t i = 0; i < packages.size(); ++i) {
1189                 // Use the order of BufferParams::auto_packages() for easier
1190                 // access in applyView() and paramsToDialog()
1191                 int n = 0;
1192                 for (n = 0; packages_gui[n][0][0]; n++)
1193                         if (packages_gui[n][0] == packages[i])
1194                                 break;
1195                 // If this fires somebody changed
1196                 // BufferParams::auto_packages() without adjusting packages_gui
1197                 LASSERT(packages_gui[n][0][0], /**/);
1198                 QString autoText = qt_(packages_gui[n][1]);
1199                 QString alwaysText = qt_(packages_gui[n][2]);
1200                 QString autoTooltip = qt_(packages_gui[n][3]);
1201                 QString alwaysTooltip;
1202                 if (packages[i] == "amsmath")
1203                         alwaysTooltip =
1204                                 qt_("The AMS LaTeX packages are always used");
1205                 else
1206                         alwaysTooltip = toqstr(bformat(
1207                                 _("The LaTeX package %1$s is always used"),
1208                                 from_ascii(packages[i])));
1209                 QCheckBox * autoCB = new QCheckBox(autoText, mathsModule);
1210                 QCheckBox * alwaysCB = new QCheckBox(alwaysText, mathsModule);
1211                 mathsModule->gridLayout->addWidget(autoCB, 2 * i, 0);
1212                 mathsModule->gridLayout->addWidget(alwaysCB, 2 * i + 1, 0);
1213                 autoCB->setToolTip(autoTooltip);
1214                 alwaysCB->setToolTip(alwaysTooltip);
1215                 connect(autoCB, SIGNAL(toggled(bool)),
1216                         alwaysCB, SLOT(setDisabled(bool)));
1217                 connect(autoCB, SIGNAL(clicked()),
1218                         this, SLOT(change_adaptor()));
1219                 connect(alwaysCB, SIGNAL(clicked()),
1220                         this, SLOT(change_adaptor()));
1221         }
1222         QSpacerItem * spacer = new QSpacerItem(20, 20, QSizePolicy::Minimum,
1223                                                QSizePolicy::Expanding);
1224         mathsModule->gridLayout->addItem(spacer, 2 * packages.size(), 0);
1225
1226
1227         // latex class
1228         latexModule = new UiWidget<Ui::LaTeXUi>;
1229         connect(latexModule->optionsLE, SIGNAL(textChanged(QString)),
1230                 this, SLOT(change_adaptor()));
1231         connect(latexModule->defaultOptionsCB, SIGNAL(clicked()),
1232                 this, SLOT(change_adaptor()));
1233         connect(latexModule->psdriverCO, SIGNAL(activated(int)),
1234                 this, SLOT(change_adaptor()));
1235         connect(latexModule->classCO, SIGNAL(activated(int)),
1236                 this, SLOT(classChanged()));
1237         connect(latexModule->classCO, SIGNAL(activated(int)),
1238                 this, SLOT(change_adaptor()));
1239         connect(latexModule->layoutPB, SIGNAL(clicked()),
1240                 this, SLOT(browseLayout()));
1241         connect(latexModule->layoutPB, SIGNAL(clicked()),
1242                 this, SLOT(change_adaptor()));
1243         connect(latexModule->childDocGB, SIGNAL(clicked()),
1244                 this, SLOT(change_adaptor()));
1245         connect(latexModule->childDocLE, SIGNAL(textChanged(QString)),
1246                 this, SLOT(change_adaptor()));
1247         connect(latexModule->childDocPB, SIGNAL(clicked()),
1248                 this, SLOT(browseMaster()));
1249         connect(latexModule->suppressDateCB, SIGNAL(clicked()),
1250                 this, SLOT(change_adaptor()));
1251         connect(latexModule->refstyleCB, SIGNAL(clicked()),
1252                 this, SLOT(change_adaptor()));
1253
1254         latexModule->optionsLE->setValidator(new NoNewLineValidator(
1255                 latexModule->optionsLE));
1256         latexModule->childDocLE->setValidator(new NoNewLineValidator(
1257                 latexModule->childDocLE));
1258
1259         // postscript drivers
1260         for (int n = 0; tex_graphics[n][0]; ++n) {
1261                 QString enc = qt_(tex_graphics_gui[n]);
1262                 latexModule->psdriverCO->addItem(enc);
1263         }
1264         // latex classes
1265         latexModule->classCO->setModel(&classes_model_);
1266         LayoutFileList const & bcl = LayoutFileList::get();
1267         vector<LayoutFileIndex> classList = bcl.classList();
1268         sort(classList.begin(), classList.end(), less_textclass_avail_desc());
1269
1270         vector<LayoutFileIndex>::const_iterator cit  = classList.begin();
1271         vector<LayoutFileIndex>::const_iterator cen = classList.end();
1272         for (int i = 0; cit != cen; ++cit, ++i) {
1273                 LayoutFile const & tc = bcl[*cit];
1274                 docstring item = (tc.isTeXClassAvailable()) ?
1275                         from_utf8(tc.description()) :
1276                         bformat(_("Unavailable: %1$s"), from_utf8(tc.description()));
1277                 classes_model_.insertRow(i, toqstr(item), *cit);
1278         }
1279
1280
1281         // branches
1282         branchesModule = new GuiBranches;
1283         connect(branchesModule, SIGNAL(changed()),
1284                 this, SLOT(change_adaptor()));
1285         connect(branchesModule, SIGNAL(renameBranches(docstring const &, docstring const &)),
1286                 this, SLOT(branchesRename(docstring const &, docstring const &)));
1287         updateUnknownBranches();
1288
1289
1290         // preamble
1291         preambleModule = new PreambleModule;
1292         connect(preambleModule, SIGNAL(changed()),
1293                 this, SLOT(change_adaptor()));
1294
1295         localLayout = new LocalLayout;
1296         connect(localLayout, SIGNAL(changed()),
1297                 this, SLOT(change_adaptor()));
1298
1299
1300         // bullets
1301         bulletsModule = new BulletsModule;
1302         connect(bulletsModule, SIGNAL(changed()),
1303                 this, SLOT(change_adaptor()));
1304
1305
1306         // Modules
1307         modulesModule = new UiWidget<Ui::ModulesUi>;
1308         modulesModule->availableLV->header()->setVisible(false);
1309         modulesModule->availableLV->header()->setResizeMode(QHeaderView::ResizeToContents);
1310         modulesModule->availableLV->header()->setStretchLastSection(false);
1311         selectionManager =
1312                 new ModuleSelectionManager(modulesModule->availableLV,
1313                         modulesModule->selectedLV,
1314                         modulesModule->addPB, modulesModule->deletePB,
1315                         modulesModule->upPB, modulesModule->downPB,
1316                         availableModel(), selectedModel(), this);
1317         connect(selectionManager, SIGNAL(updateHook()),
1318                 this, SLOT(updateModuleInfo()));
1319         connect(selectionManager, SIGNAL(updateHook()),
1320                 this, SLOT(change_adaptor()));
1321         connect(selectionManager, SIGNAL(selectionChanged()),
1322                 this, SLOT(modulesChanged()));
1323
1324
1325         // PDF support
1326         pdfSupportModule = new UiWidget<Ui::PDFSupportUi>;
1327         connect(pdfSupportModule->use_hyperrefGB, SIGNAL(toggled(bool)),
1328                 this, SLOT(change_adaptor()));
1329         connect(pdfSupportModule->titleLE, SIGNAL(textChanged(QString)),
1330                 this, SLOT(change_adaptor()));
1331         connect(pdfSupportModule->authorLE, SIGNAL(textChanged(QString)),
1332                 this, SLOT(change_adaptor()));
1333         connect(pdfSupportModule->subjectLE, SIGNAL(textChanged(QString)),
1334                 this, SLOT(change_adaptor()));
1335         connect(pdfSupportModule->keywordsLE, SIGNAL(textChanged(QString)),
1336                 this, SLOT(change_adaptor()));
1337         connect(pdfSupportModule->bookmarksGB, SIGNAL(toggled(bool)),
1338                 this, SLOT(change_adaptor()));
1339         connect(pdfSupportModule->bookmarksnumberedCB, SIGNAL(toggled(bool)),
1340                 this, SLOT(change_adaptor()));
1341         connect(pdfSupportModule->bookmarksopenGB, SIGNAL(toggled(bool)),
1342                 this, SLOT(change_adaptor()));
1343         connect(pdfSupportModule->bookmarksopenlevelSB, SIGNAL(valueChanged(int)),
1344                 this, SLOT(change_adaptor()));
1345         connect(pdfSupportModule->breaklinksCB, SIGNAL(toggled(bool)),
1346                 this, SLOT(change_adaptor()));
1347         connect(pdfSupportModule->pdfborderCB, SIGNAL(toggled(bool)),
1348                 this, SLOT(change_adaptor()));
1349         connect(pdfSupportModule->colorlinksCB, SIGNAL(toggled(bool)),
1350                 this, SLOT(change_adaptor()));
1351         connect(pdfSupportModule->backrefCO, SIGNAL(activated(int)),
1352                 this, SLOT(change_adaptor()));
1353         connect(pdfSupportModule->pdfusetitleCB, SIGNAL(toggled(bool)),
1354                 this, SLOT(change_adaptor()));
1355         connect(pdfSupportModule->fullscreenCB, SIGNAL(toggled(bool)),
1356                 this, SLOT(change_adaptor()));
1357         connect(pdfSupportModule->optionsLE, SIGNAL(textChanged(QString)),
1358                 this, SLOT(change_adaptor()));
1359
1360         pdfSupportModule->titleLE->setValidator(new NoNewLineValidator(
1361                 pdfSupportModule->titleLE));
1362         pdfSupportModule->authorLE->setValidator(new NoNewLineValidator(
1363                 pdfSupportModule->authorLE));
1364         pdfSupportModule->subjectLE->setValidator(new NoNewLineValidator(
1365                 pdfSupportModule->subjectLE));
1366         pdfSupportModule->keywordsLE->setValidator(new NoNewLineValidator(
1367                 pdfSupportModule->keywordsLE));
1368         pdfSupportModule->optionsLE->setValidator(new NoNewLineValidator(
1369                 pdfSupportModule->optionsLE));
1370
1371         for (int i = 0; backref_opts[i][0]; ++i)
1372                 pdfSupportModule->backrefCO->addItem(qt_(backref_opts_gui[i]));
1373
1374
1375         // float
1376         floatModule = new FloatPlacement;
1377         connect(floatModule, SIGNAL(changed()),
1378                 this, SLOT(change_adaptor()));
1379
1380
1381         // listings
1382         listingsModule = new UiWidget<Ui::ListingsSettingsUi>;
1383         connect(listingsModule->listingsED, SIGNAL(textChanged()),
1384                 this, SLOT(change_adaptor()));
1385         connect(listingsModule->bypassCB, SIGNAL(clicked()),
1386                 this, SLOT(change_adaptor()));
1387         connect(listingsModule->bypassCB, SIGNAL(clicked()),
1388                 this, SLOT(setListingsMessage()));
1389         connect(listingsModule->listingsED, SIGNAL(textChanged()),
1390                 this, SLOT(setListingsMessage()));
1391         listingsModule->listingsTB->setPlainText(
1392                 qt_("Input listings parameters below. Enter ? for a list of parameters."));
1393
1394
1395         // add the panels
1396         docPS->addPanel(latexModule, qt_("Document Class"));
1397         docPS->addPanel(masterChildModule, qt_("Child Documents"));
1398         docPS->addPanel(modulesModule, qt_("Modules"));
1399         docPS->addPanel(localLayout, qt_("Local Layout"));
1400         docPS->addPanel(fontModule, qt_("Fonts"));
1401         docPS->addPanel(textLayoutModule, qt_("Text Layout"));
1402         docPS->addPanel(pageLayoutModule, qt_("Page Layout"));
1403         docPS->addPanel(marginsModule, qt_("Page Margins"));
1404         docPS->addPanel(langModule, qt_("Language"));
1405         docPS->addPanel(colorModule, qt_("Colors"));
1406         docPS->addPanel(numberingModule, qt_("Numbering & TOC"));
1407         docPS->addPanel(biblioModule, qt_("Bibliography"));
1408         docPS->addPanel(indicesModule, qt_("Indexes"));
1409         docPS->addPanel(pdfSupportModule, qt_("PDF Properties"));
1410         docPS->addPanel(mathsModule, qt_("Math Options"));
1411         docPS->addPanel(floatModule, qt_("Float Placement"));
1412         docPS->addPanel(listingsModule, qt_("Listings"));
1413         docPS->addPanel(bulletsModule, qt_("Bullets"));
1414         docPS->addPanel(branchesModule, qt_("Branches"));
1415         docPS->addPanel(outputModule, qt_("Output"));
1416         docPS->addPanel(preambleModule, qt_("LaTeX Preamble"));
1417         docPS->setCurrentPanel(qt_("Document Class"));
1418 // FIXME: hack to work around resizing bug in Qt >= 4.2
1419 // bug verified with Qt 4.2.{0-3} (JSpitzm)
1420 #if QT_VERSION >= 0x040200
1421         docPS->updateGeometry();
1422 #endif
1423 }
1424
1425
1426 void GuiDocument::saveDefaultClicked()
1427 {
1428         saveDocDefault();
1429 }
1430
1431
1432 void GuiDocument::useDefaultsClicked()
1433 {
1434         useClassDefaults();
1435 }
1436
1437
1438 void GuiDocument::change_adaptor()
1439 {
1440         changed();
1441 }
1442
1443
1444 void GuiDocument::includeonlyClicked(QTreeWidgetItem * item, int)
1445 {
1446         if (item == 0)
1447                 return;
1448
1449         string child = fromqstr(item->text(0));
1450         if (child.empty())
1451                 return;
1452
1453         if (std::find(includeonlys_.begin(),
1454                       includeonlys_.end(), child) != includeonlys_.end())
1455                 includeonlys_.remove(child);
1456         else
1457                 includeonlys_.push_back(child);
1458
1459         updateIncludeonlys();
1460         changed();
1461 }
1462
1463
1464 QString GuiDocument::validateListingsParameters()
1465 {
1466         // use a cache here to avoid repeated validation
1467         // of the same parameters
1468         static string param_cache;
1469         static QString msg_cache;
1470
1471         if (listingsModule->bypassCB->isChecked())
1472                 return QString();
1473
1474         string params = fromqstr(listingsModule->listingsED->toPlainText());
1475         if (params != param_cache) {
1476                 param_cache = params;
1477                 msg_cache = toqstr(InsetListingsParams(params).validate());
1478         }
1479         return msg_cache;
1480 }
1481
1482
1483 void GuiDocument::setListingsMessage()
1484 {
1485         static bool isOK = true;
1486         QString msg = validateListingsParameters();
1487         if (msg.isEmpty()) {
1488                 if (isOK)
1489                         return;
1490                 isOK = true;
1491                 // listingsTB->setTextColor("black");
1492                 listingsModule->listingsTB->setPlainText(
1493                         qt_("Input listings parameters below. "
1494                 "Enter ? for a list of parameters."));
1495         } else {
1496                 isOK = false;
1497                 // listingsTB->setTextColor("red");
1498                 listingsModule->listingsTB->setPlainText(msg);
1499         }
1500 }
1501
1502
1503 void GuiDocument::setLSpacing(int item)
1504 {
1505         textLayoutModule->lspacingLE->setEnabled(item == 3);
1506 }
1507
1508
1509 void GuiDocument::setIndent(int item)
1510 {
1511         bool const enable = (item == 1);
1512         textLayoutModule->indentLE->setEnabled(enable);
1513         textLayoutModule->indentLengthCO->setEnabled(enable);
1514         textLayoutModule->skipLE->setEnabled(false);
1515         textLayoutModule->skipLengthCO->setEnabled(false);
1516         isValid();
1517 }
1518
1519
1520 void GuiDocument::enableIndent(bool indent)
1521 {
1522         textLayoutModule->skipLE->setEnabled(!indent);
1523         textLayoutModule->skipLengthCO->setEnabled(!indent);
1524         if (indent)
1525                 setIndent(textLayoutModule->indentCO->currentIndex());
1526 }
1527
1528
1529 void GuiDocument::setSkip(int item)
1530 {
1531         bool const enable = (item == 3);
1532         textLayoutModule->skipLE->setEnabled(enable);
1533         textLayoutModule->skipLengthCO->setEnabled(enable);
1534         isValid();
1535 }
1536
1537
1538 void GuiDocument::enableSkip(bool skip)
1539 {
1540         textLayoutModule->indentLE->setEnabled(!skip);
1541         textLayoutModule->indentLengthCO->setEnabled(!skip);
1542         if (skip)
1543                 setSkip(textLayoutModule->skipCO->currentIndex());
1544 }
1545
1546
1547 void GuiDocument::setMargins()
1548 {
1549         bool const extern_geometry =
1550                 documentClass().provides("geometry");
1551         marginsModule->marginCB->setEnabled(!extern_geometry);
1552         if (extern_geometry) {
1553                 marginsModule->marginCB->setChecked(false);
1554                 setCustomMargins(true);
1555         } else {
1556                 marginsModule->marginCB->setChecked(!bp_.use_geometry);
1557                 setCustomMargins(!bp_.use_geometry);
1558         }
1559 }
1560
1561
1562 void GuiDocument::papersizeChanged(int paper_size)
1563 {
1564         setCustomPapersize(paper_size == 1);
1565 }
1566
1567
1568 void GuiDocument::setCustomPapersize(bool custom)
1569 {
1570         pageLayoutModule->paperwidthL->setEnabled(custom);
1571         pageLayoutModule->paperwidthLE->setEnabled(custom);
1572         pageLayoutModule->paperwidthUnitCO->setEnabled(custom);
1573         pageLayoutModule->paperheightL->setEnabled(custom);
1574         pageLayoutModule->paperheightLE->setEnabled(custom);
1575         pageLayoutModule->paperheightLE->setFocus();
1576         pageLayoutModule->paperheightUnitCO->setEnabled(custom);
1577 }
1578
1579
1580 void GuiDocument::setColSep()
1581 {
1582         setCustomMargins(marginsModule->marginCB->checkState() == Qt::Checked);
1583 }
1584
1585
1586 void GuiDocument::setCustomMargins(bool custom)
1587 {
1588         marginsModule->topL->setEnabled(!custom);
1589         marginsModule->topLE->setEnabled(!custom);
1590         marginsModule->topUnit->setEnabled(!custom);
1591
1592         marginsModule->bottomL->setEnabled(!custom);
1593         marginsModule->bottomLE->setEnabled(!custom);
1594         marginsModule->bottomUnit->setEnabled(!custom);
1595
1596         marginsModule->innerL->setEnabled(!custom);
1597         marginsModule->innerLE->setEnabled(!custom);
1598         marginsModule->innerUnit->setEnabled(!custom);
1599
1600         marginsModule->outerL->setEnabled(!custom);
1601         marginsModule->outerLE->setEnabled(!custom);
1602         marginsModule->outerUnit->setEnabled(!custom);
1603
1604         marginsModule->headheightL->setEnabled(!custom);
1605         marginsModule->headheightLE->setEnabled(!custom);
1606         marginsModule->headheightUnit->setEnabled(!custom);
1607
1608         marginsModule->headsepL->setEnabled(!custom);
1609         marginsModule->headsepLE->setEnabled(!custom);
1610         marginsModule->headsepUnit->setEnabled(!custom);
1611
1612         marginsModule->footskipL->setEnabled(!custom);
1613         marginsModule->footskipLE->setEnabled(!custom);
1614         marginsModule->footskipUnit->setEnabled(!custom);
1615
1616         bool const enableColSep = !custom &&
1617                         textLayoutModule->twoColumnCB->checkState() == Qt::Checked;
1618         marginsModule->columnsepL->setEnabled(enableColSep);
1619         marginsModule->columnsepLE->setEnabled(enableColSep);
1620         marginsModule->columnsepUnit->setEnabled(enableColSep);
1621 }
1622
1623
1624 void GuiDocument::changeBackgroundColor()
1625 {
1626         QColor const & newColor = QColorDialog::getColor(
1627                 rgb2qcolor(set_backgroundcolor), asQWidget());
1628         if (!newColor.isValid())
1629                 return;
1630         // set the button color and text
1631         colorModule->backgroundPB->setStyleSheet(
1632                 colorButtonStyleSheet(newColor));
1633         colorModule->backgroundPB->setText(qt_("&Change..."));
1634         // save color
1635         set_backgroundcolor = rgbFromHexName(fromqstr(newColor.name()));
1636         is_backgroundcolor = true;
1637         changed();
1638 }
1639
1640
1641 void GuiDocument::deleteBackgroundColor()
1642 {
1643         // set the button color back to default by setting an empty StyleSheet
1644         colorModule->backgroundPB->setStyleSheet(QLatin1String(""));
1645         // change button text
1646         colorModule->backgroundPB->setText(qt_("&Default..."));
1647         // save default color (white)
1648         set_backgroundcolor = rgbFromHexName("#ffffff");
1649         is_backgroundcolor = false;
1650         changed();
1651 }
1652
1653
1654 void GuiDocument::changeFontColor()
1655 {
1656         QColor const & newColor = QColorDialog::getColor(
1657                 rgb2qcolor(set_fontcolor), asQWidget());
1658         if (!newColor.isValid())
1659                 return;
1660         // set the button color and text
1661         colorModule->fontColorPB->setStyleSheet(
1662                 colorButtonStyleSheet(newColor));
1663         colorModule->fontColorPB->setText(qt_("&Change..."));
1664         // save color
1665         set_fontcolor = rgbFromHexName(fromqstr(newColor.name()));
1666         is_fontcolor = true;
1667         changed();
1668 }
1669
1670
1671 void GuiDocument::deleteFontColor()
1672 {
1673         // set the button color back to default by setting an empty StyleSheet
1674         colorModule->fontColorPB->setStyleSheet(QLatin1String(""));
1675         // change button text
1676         colorModule->fontColorPB->setText(qt_("&Default..."));
1677         // save default color (black)
1678         set_fontcolor = rgbFromHexName("#000000");
1679         is_fontcolor = false;
1680         changed();
1681 }
1682
1683
1684 void GuiDocument::changeNoteFontColor()
1685 {
1686         QColor const & newColor = QColorDialog::getColor(
1687                 rgb2qcolor(set_notefontcolor), asQWidget());
1688         if (!newColor.isValid())
1689                 return;
1690         // set the button color
1691         colorModule->noteFontColorPB->setStyleSheet(
1692                 colorButtonStyleSheet(newColor));
1693         // save color
1694         set_notefontcolor = rgbFromHexName(fromqstr(newColor.name()));
1695         changed();
1696 }
1697
1698
1699 void GuiDocument::deleteNoteFontColor()
1700 {
1701         // set the button color back to pref
1702         theApp()->getRgbColor(Color_greyedouttext, set_notefontcolor);
1703         colorModule->noteFontColorPB->setStyleSheet(
1704                 colorButtonStyleSheet(rgb2qcolor(set_notefontcolor)));
1705         changed();
1706 }
1707
1708
1709 void GuiDocument::changeBoxBackgroundColor()
1710 {
1711         QColor const & newColor = QColorDialog::getColor(
1712                 rgb2qcolor(set_boxbgcolor), asQWidget());
1713         if (!newColor.isValid())
1714                 return;
1715         // set the button color
1716         colorModule->boxBackgroundPB->setStyleSheet(
1717                 colorButtonStyleSheet(newColor));
1718         // save color
1719         set_boxbgcolor = rgbFromHexName(fromqstr(newColor.name()));
1720         changed();
1721 }
1722
1723
1724 void GuiDocument::deleteBoxBackgroundColor()
1725 {
1726         // set the button color back to pref
1727         theApp()->getRgbColor(Color_shadedbg, set_boxbgcolor);
1728         colorModule->boxBackgroundPB->setStyleSheet(
1729                 colorButtonStyleSheet(rgb2qcolor(set_boxbgcolor)));
1730         changed();
1731 }
1732
1733
1734 void GuiDocument::osFontsChanged(bool nontexfonts)
1735 {
1736         bool const tex_fonts = !nontexfonts;
1737         updateFontlist();
1738         updateDefaultFormat();
1739         langModule->encodingCO->setEnabled(tex_fonts &&
1740                 !langModule->defaultencodingRB->isChecked());
1741         langModule->defaultencodingRB->setEnabled(tex_fonts);
1742         langModule->otherencodingRB->setEnabled(tex_fonts);
1743
1744         fontModule->fontsDefaultCO->setEnabled(tex_fonts);
1745         fontModule->fontsDefaultLA->setEnabled(tex_fonts);
1746         fontModule->cjkFontLE->setEnabled(tex_fonts);
1747         fontModule->cjkFontLA->setEnabled(tex_fonts);
1748         string font;
1749         if (tex_fonts)
1750                 font = tex_fonts_sans[fontModule->fontsSansCO->currentIndex()];
1751         bool scaleable = providesScale(font);
1752         fontModule->scaleSansSB->setEnabled(scaleable);
1753         fontModule->scaleSansLA->setEnabled(scaleable);
1754         if (tex_fonts)
1755                 font = tex_fonts_monospaced[fontModule->fontsTypewriterCO->currentIndex()];
1756         scaleable = providesScale(font);
1757         fontModule->scaleTypewriterSB->setEnabled(scaleable);
1758         fontModule->scaleTypewriterLA->setEnabled(scaleable);
1759         if (tex_fonts)
1760                 font = tex_fonts_roman[fontModule->fontsRomanCO->currentIndex()];
1761         fontModule->fontScCB->setEnabled(providesSC(font));
1762         fontModule->fontOsfCB->setEnabled(providesOSF(font));
1763
1764         fontModule->fontencLA->setEnabled(tex_fonts);
1765         fontModule->fontencCO->setEnabled(tex_fonts);
1766         if (!tex_fonts)
1767                 fontModule->fontencLE->setEnabled(false);
1768         else
1769                 fontencChanged(fontModule->fontencCO->currentIndex());
1770 }
1771
1772
1773 void GuiDocument::updateFontsize(string const & items, string const & sel)
1774 {
1775         fontModule->fontsizeCO->clear();
1776         fontModule->fontsizeCO->addItem(qt_("Default"));
1777
1778         for (int n = 0; !token(items,'|',n).empty(); ++n)
1779                 fontModule->fontsizeCO->
1780                         addItem(toqstr(token(items,'|',n)));
1781
1782         for (int n = 0; n < fontModule->fontsizeCO->count(); ++n) {
1783                 if (fromqstr(fontModule->fontsizeCO->itemText(n)) == sel) {
1784                         fontModule->fontsizeCO->setCurrentIndex(n);
1785                         break;
1786                 }
1787         }
1788 }
1789
1790
1791 void GuiDocument::updateFontlist()
1792 {
1793         fontModule->fontsRomanCO->clear();
1794         fontModule->fontsSansCO->clear();
1795         fontModule->fontsTypewriterCO->clear();
1796
1797         // With XeTeX, we have access to all system fonts, but not the LaTeX fonts
1798         if (fontModule->osFontsCB->isChecked()) {
1799                 fontModule->fontsRomanCO->addItem(qt_("Default"), QString("default"));
1800                 fontModule->fontsSansCO->addItem(qt_("Default"), QString("default"));
1801                 fontModule->fontsTypewriterCO->addItem(qt_("Default"), QString("default"));
1802
1803                 QFontDatabase fontdb;
1804                 QStringList families(fontdb.families());
1805                 for (QStringList::Iterator it = families.begin(); it != families.end(); ++it) {
1806                         fontModule->fontsRomanCO->addItem(*it, *it);
1807                         fontModule->fontsSansCO->addItem(*it, *it);
1808                         fontModule->fontsTypewriterCO->addItem(*it, *it);
1809                 }
1810                 return;
1811         }
1812
1813         for (int n = 0; tex_fonts_roman[n][0]; ++n) {
1814                 QString font = qt_(tex_fonts_roman_gui[n]);
1815                 if (!isFontAvailable(tex_fonts_roman[n]))
1816                         font += qt_(" (not installed)");
1817                 fontModule->fontsRomanCO->addItem(font, qt_(tex_fonts_roman[n]));
1818         }
1819         for (int n = 0; tex_fonts_sans[n][0]; ++n) {
1820                 QString font = qt_(tex_fonts_sans_gui[n]);
1821                 if (!isFontAvailable(tex_fonts_sans[n]))
1822                         font += qt_(" (not installed)");
1823                 fontModule->fontsSansCO->addItem(font, qt_(tex_fonts_sans[n]));
1824         }
1825         for (int n = 0; tex_fonts_monospaced[n][0]; ++n) {
1826                 QString font = qt_(tex_fonts_monospaced_gui[n]);
1827                 if (!isFontAvailable(tex_fonts_monospaced[n]))
1828                         font += qt_(" (not installed)");
1829                 fontModule->fontsTypewriterCO->addItem(font, qt_(tex_fonts_monospaced[n]));
1830         }
1831 }
1832
1833
1834 void GuiDocument::fontencChanged(int item)
1835 {
1836         fontModule->fontencLE->setEnabled(item == 1);
1837 }
1838
1839
1840 void GuiDocument::romanChanged(int item)
1841 {
1842         if (fontModule->osFontsCB->isChecked())
1843                 return;
1844         string const font = tex_fonts_roman[item];
1845         fontModule->fontScCB->setEnabled(providesSC(font));
1846         fontModule->fontOsfCB->setEnabled(providesOSF(font));
1847 }
1848
1849
1850 void GuiDocument::sansChanged(int item)
1851 {
1852         if (fontModule->osFontsCB->isChecked())
1853                 return;
1854         string const font = tex_fonts_sans[item];
1855         bool scaleable = providesScale(font);
1856         fontModule->scaleSansSB->setEnabled(scaleable);
1857         fontModule->scaleSansLA->setEnabled(scaleable);
1858 }
1859
1860
1861 void GuiDocument::ttChanged(int item)
1862 {
1863         if (fontModule->osFontsCB->isChecked())
1864                 return;
1865         string const font = tex_fonts_monospaced[item];
1866         bool scaleable = providesScale(font);
1867         fontModule->scaleTypewriterSB->setEnabled(scaleable);
1868         fontModule->scaleTypewriterLA->setEnabled(scaleable);
1869 }
1870
1871
1872 void GuiDocument::updatePagestyle(string const & items, string const & sel)
1873 {
1874         pagestyles.clear();
1875         pageLayoutModule->pagestyleCO->clear();
1876         pageLayoutModule->pagestyleCO->addItem(qt_("Default"));
1877
1878         for (int n = 0; !token(items, '|', n).empty(); ++n) {
1879                 string style = token(items, '|', n);
1880                 QString style_gui = qt_(style);
1881                 pagestyles.push_back(pair<string, QString>(style, style_gui));
1882                 pageLayoutModule->pagestyleCO->addItem(style_gui);
1883         }
1884
1885         if (sel == "default") {
1886                 pageLayoutModule->pagestyleCO->setCurrentIndex(0);
1887                 return;
1888         }
1889
1890         int nn = 0;
1891
1892         for (size_t i = 0; i < pagestyles.size(); ++i)
1893                 if (pagestyles[i].first == sel)
1894                         nn = pageLayoutModule->pagestyleCO->findText(pagestyles[i].second);
1895
1896         if (nn > 0)
1897                 pageLayoutModule->pagestyleCO->setCurrentIndex(nn);
1898 }
1899
1900
1901 void GuiDocument::browseLayout()
1902 {
1903         QString const label1 = qt_("Layouts|#o#O");
1904         QString const dir1 = toqstr(lyxrc.document_path);
1905         QStringList const filter(qt_("LyX Layout (*.layout)"));
1906         QString file = browseRelToParent(QString(), bufferFilePath(),
1907                 qt_("Local layout file"), filter, false,
1908                 label1, dir1);
1909
1910         if (!file.endsWith(".layout"))
1911                 return;
1912
1913         FileName layoutFile = support::makeAbsPath(fromqstr(file),
1914                 fromqstr(bufferFilePath()));
1915
1916         int const ret = Alert::prompt(_("Local layout file"),
1917                 _("The layout file you have selected is a local layout\n"
1918                   "file, not one in the system or user directory. Your\n"
1919                   "document may not work with this layout if you do not\n"
1920                   "keep the layout file in the document directory."),
1921                   1, 1, _("&Set Layout"), _("&Cancel"));
1922         if (ret == 1)
1923                 return;
1924
1925         // load the layout file
1926         LayoutFileList & bcl = LayoutFileList::get();
1927         string classname = layoutFile.onlyFileName();
1928         // this will update an existing layout if that layout has been loaded before.
1929         LayoutFileIndex name = bcl.addLocalLayout(
1930                 classname.substr(0, classname.size() - 7),
1931                 layoutFile.onlyPath().absFileName());
1932
1933         if (name.empty()) {
1934                 Alert::error(_("Error"),
1935                         _("Unable to read local layout file."));
1936                 return;
1937         }
1938
1939         // do not trigger classChanged if there is no change.
1940         if (latexModule->classCO->currentText() == toqstr(name))
1941                 return;
1942
1943         // add to combo box
1944         int idx = latexModule->classCO->findText(toqstr(name));
1945         if (idx == -1) {
1946                 classes_model_.insertRow(0, toqstr(name), name);
1947                 latexModule->classCO->setCurrentIndex(0);
1948         } else
1949                 latexModule->classCO->setCurrentIndex(idx);
1950
1951         classChanged();
1952 }
1953
1954
1955 void GuiDocument::browseMaster()
1956 {
1957         QString const title = qt_("Select master document");
1958         QString const dir1 = toqstr(lyxrc.document_path);
1959         QString const old = latexModule->childDocLE->text();
1960         QString const docpath = toqstr(support::onlyPath(buffer().absFileName()));
1961         QStringList const filter(qt_("LyX Files (*.lyx)"));
1962         QString file = browseRelToSub(old, docpath, title, filter, false,
1963                 qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1964
1965         if (!file.isEmpty())
1966                 latexModule->childDocLE->setText(file);
1967 }
1968
1969
1970 void GuiDocument::classChanged()
1971 {
1972         int idx = latexModule->classCO->currentIndex();
1973         if (idx < 0)
1974                 return;
1975         string const classname = classes_model_.getIDString(idx);
1976
1977         // check whether the selected modules have changed.
1978         bool modules_changed = false;
1979         unsigned int const srows = selectedModel()->rowCount();
1980         if (srows != bp_.getModules().size())
1981                 modules_changed = true;
1982         else {
1983                 list<string>::const_iterator mit = bp_.getModules().begin();
1984                 list<string>::const_iterator men = bp_.getModules().end();
1985                 for (unsigned int i = 0; i < srows && mit != men; ++i, ++mit)
1986                         if (selectedModel()->getIDString(i) != *mit) {
1987                                 modules_changed = true;
1988                                 break;
1989                         }
1990         }
1991
1992         if (modules_changed || lyxrc.auto_reset_options) {
1993                 if (applyPB->isEnabled()) {
1994                         int const ret = Alert::prompt(_("Unapplied changes"),
1995                                         _("Some changes in the dialog were not yet applied.\n"
1996                                         "If you do not apply now, they will be lost after this action."),
1997                                         1, 1, _("&Apply"), _("&Dismiss"));
1998                         if (ret == 0)
1999                                 applyView();
2000                 }
2001         }
2002
2003         // We load the TextClass as soon as it is selected. This is
2004         // necessary so that other options in the dialog can be updated
2005         // according to the new class. Note, however, that, if you use
2006         // the scroll wheel when sitting on the combo box, we'll load a
2007         // lot of TextClass objects very quickly....
2008         if (!bp_.setBaseClass(classname)) {
2009                 Alert::error(_("Error"), _("Unable to set document class."));
2010                 return;
2011         }
2012         if (lyxrc.auto_reset_options)
2013                 bp_.useClassDefaults();
2014
2015         // With the introduction of modules came a distinction between the base
2016         // class and the document class. The former corresponds to the main layout
2017         // file; the latter is that plus the modules (or the document-specific layout,
2018         // or  whatever else there could be). Our parameters come from the document
2019         // class. So when we set the base class, we also need to recreate the document
2020         // class. Otherwise, we still have the old one.
2021         bp_.makeDocumentClass();
2022         paramsToDialog();
2023 }
2024
2025
2026 void GuiDocument::languagePackageChanged(int i)
2027 {
2028          langModule->languagePackageLE->setEnabled(
2029                 langModule->languagePackageCO->itemData(i).toString() == "custom");
2030 }
2031
2032
2033 void GuiDocument::biblioChanged()
2034 {
2035         biblioChanged_ = true;
2036         changed();
2037 }
2038
2039
2040 void GuiDocument::bibtexChanged(int n)
2041 {
2042         biblioModule->bibtexOptionsLE->setEnabled(
2043                 biblioModule->bibtexCO->itemData(n).toString() != "default");
2044         biblioChanged();
2045 }
2046
2047
2048 namespace {
2049         // FIXME unicode
2050         // both of these should take a vector<docstring>
2051
2052         // This is an insanely complicated attempt to make this sort of thing
2053         // work with RTL languages.
2054         docstring formatStrVec(vector<string> const & v, docstring const & s)
2055         {
2056                 //this mess formats the list as "v[0], v[1], ..., [s] v[n]"
2057                 if (v.size() == 0)
2058                         return docstring();
2059                 if (v.size() == 1)
2060                         return translateIfPossible(from_utf8(v[0]));
2061                 if (v.size() == 2) {
2062                         docstring retval = _("%1$s and %2$s");
2063                         retval = subst(retval, _("and"), s);
2064                         return bformat(retval, translateIfPossible(from_utf8(v[0])),
2065                                        translateIfPossible(from_utf8(v[1])));
2066                 }
2067                 // The idea here is to format all but the last two items...
2068                 int const vSize = v.size();
2069                 docstring t2 = _("%1$s, %2$s");
2070                 docstring retval = translateIfPossible(from_utf8(v[0]));
2071                 for (int i = 1; i < vSize - 2; ++i)
2072                         retval = bformat(t2, retval, translateIfPossible(from_utf8(v[i])));
2073                 //...and then to  plug them, and the last two, into this schema
2074                 docstring t = _("%1$s, %2$s, and %3$s");
2075                 t = subst(t, _("and"), s);
2076                 return bformat(t, retval, translateIfPossible(from_utf8(v[vSize - 2])),
2077                                translateIfPossible(from_utf8(v[vSize - 1])));
2078         }
2079
2080         vector<string> idsToNames(vector<string> const & idList)
2081         {
2082                 vector<string> retval;
2083                 vector<string>::const_iterator it  = idList.begin();
2084                 vector<string>::const_iterator end = idList.end();
2085                 for (; it != end; ++it) {
2086                         LyXModule const * const mod = theModuleList[*it];
2087                         if (!mod)
2088                                 retval.push_back(to_utf8(bformat(_("%1$s (unavailable)"),
2089                                                 translateIfPossible(from_utf8(*it)))));
2090                         else
2091                                 retval.push_back(mod->getName());
2092                 }
2093                 return retval;
2094         }
2095 } // end anonymous namespace
2096
2097
2098 void GuiDocument::modulesToParams(BufferParams & bp)
2099 {
2100         // update list of loaded modules
2101         bp.clearLayoutModules();
2102         int const srows = modules_sel_model_.rowCount();
2103         for (int i = 0; i < srows; ++i)
2104                 bp.addLayoutModule(modules_sel_model_.getIDString(i));
2105
2106         // update the list of removed modules
2107         bp.clearRemovedModules();
2108         LayoutModuleList const & reqmods = bp.baseClass()->defaultModules();
2109         list<string>::const_iterator rit = reqmods.begin();
2110         list<string>::const_iterator ren = reqmods.end();
2111
2112         // check each of the default modules
2113         for (; rit != ren; rit++) {
2114                 list<string>::const_iterator mit = bp.getModules().begin();
2115                 list<string>::const_iterator men = bp.getModules().end();
2116                 bool found = false;
2117                 for (; mit != men; mit++) {
2118                         if (*rit == *mit) {
2119                                 found = true;
2120                                 break;
2121                         }
2122                 }
2123                 if (!found) {
2124                         // the module isn't present so must have been removed by the user
2125                         bp.addRemovedModule(*rit);
2126                 }
2127         }
2128 }
2129
2130 void GuiDocument::modulesChanged()
2131 {
2132         modulesToParams(bp_);
2133         bp_.makeDocumentClass();
2134         paramsToDialog();
2135 }
2136
2137
2138 void GuiDocument::updateModuleInfo()
2139 {
2140         selectionManager->update();
2141
2142         //Module description
2143         bool const focus_on_selected = selectionManager->selectedFocused();
2144         QAbstractItemView * lv;
2145         if (focus_on_selected)
2146                 lv = modulesModule->selectedLV;
2147         else
2148                 lv= modulesModule->availableLV;
2149         if (lv->selectionModel()->selectedIndexes().isEmpty()) {
2150                 modulesModule->infoML->document()->clear();
2151                 return;
2152         }
2153         QModelIndex const & idx = lv->selectionModel()->currentIndex();
2154         GuiIdListModel const & id_model =
2155                         focus_on_selected  ? modules_sel_model_ : modules_av_model_;
2156         string const modName = id_model.getIDString(idx.row());
2157         docstring desc = getModuleDescription(modName);
2158
2159         LayoutModuleList const & provmods = bp_.baseClass()->providedModules();
2160         if (std::find(provmods.begin(), provmods.end(), modName) != provmods.end()) {
2161                 if (!desc.empty())
2162                         desc += "\n";
2163                 desc += _("Module provided by document class.");
2164         }
2165
2166         vector<string> pkglist = getPackageList(modName);
2167         docstring pkgdesc = formatStrVec(pkglist, _("and"));
2168         if (!pkgdesc.empty()) {
2169                 if (!desc.empty())
2170                         desc += "\n";
2171                 desc += bformat(_("Package(s) required: %1$s."), pkgdesc);
2172         }
2173
2174         pkglist = getRequiredList(modName);
2175         if (!pkglist.empty()) {
2176                 vector<string> const reqdescs = idsToNames(pkglist);
2177                 pkgdesc = formatStrVec(reqdescs, _("or"));
2178                 if (!desc.empty())
2179                         desc += "\n";
2180                 desc += bformat(_("Modules required: %1$s."), pkgdesc);
2181         }
2182
2183         pkglist = getExcludedList(modName);
2184         if (!pkglist.empty()) {
2185                 vector<string> const reqdescs = idsToNames(pkglist);
2186                 pkgdesc = formatStrVec(reqdescs, _( "and"));
2187                 if (!desc.empty())
2188                         desc += "\n";
2189                 desc += bformat(_("Modules excluded: %1$s."), pkgdesc);
2190         }
2191
2192         if (!isModuleAvailable(modName)) {
2193                 if (!desc.empty())
2194                         desc += "\n";
2195                 desc += _("WARNING: Some required packages are unavailable!");
2196         }
2197
2198         modulesModule->infoML->document()->setPlainText(toqstr(desc));
2199 }
2200
2201
2202 void GuiDocument::updateNumbering()
2203 {
2204         DocumentClass const & tclass = documentClass();
2205
2206         numberingModule->tocTW->setUpdatesEnabled(false);
2207         numberingModule->tocTW->clear();
2208
2209         int const depth = numberingModule->depthSL->value();
2210         int const toc = numberingModule->tocSL->value();
2211         QString const no = qt_("No");
2212         QString const yes = qt_("Yes");
2213         QTreeWidgetItem * item = 0;
2214
2215         DocumentClass::const_iterator lit = tclass.begin();
2216         DocumentClass::const_iterator len = tclass.end();
2217         for (; lit != len; ++lit) {
2218                 int const toclevel = lit->toclevel;
2219                 if (toclevel != Layout::NOT_IN_TOC && lit->labeltype == LABEL_COUNTER) {
2220                         item = new QTreeWidgetItem(numberingModule->tocTW);
2221                         item->setText(0, toqstr(translateIfPossible(lit->name())));
2222                         item->setText(1, (toclevel <= depth) ? yes : no);
2223                         item->setText(2, (toclevel <= toc) ? yes : no);
2224                 }
2225         }
2226
2227         numberingModule->tocTW->setUpdatesEnabled(true);
2228         numberingModule->tocTW->update();
2229 }
2230
2231
2232 void GuiDocument::updateDefaultFormat()
2233 {
2234         if (!bufferview())
2235                 return;
2236         // make a copy in order to consider unapplied changes
2237         BufferParams param_copy = buffer().params();
2238         param_copy.useNonTeXFonts = fontModule->osFontsCB->isChecked();
2239         int const idx = latexModule->classCO->currentIndex();
2240         if (idx >= 0) {
2241                 string const classname = classes_model_.getIDString(idx);
2242                 param_copy.setBaseClass(classname);
2243                 param_copy.makeDocumentClass();
2244         }
2245         outputModule->defaultFormatCO->blockSignals(true);
2246         outputModule->defaultFormatCO->clear();
2247         outputModule->defaultFormatCO->addItem(qt_("Default"),
2248                                 QVariant(QString("default")));
2249         typedef vector<Format const *> Formats;
2250         Formats formats = param_copy.exportableFormats(true);
2251         Formats::const_iterator cit = formats.begin();
2252         Formats::const_iterator end = formats.end();
2253         for (; cit != end; ++cit)
2254                 outputModule->defaultFormatCO->addItem(qt_((*cit)->prettyname()),
2255                                 QVariant(toqstr((*cit)->name())));
2256         outputModule->defaultFormatCO->blockSignals(false);
2257 }
2258
2259
2260 bool GuiDocument::isChildIncluded(string const & child)
2261 {
2262         if (includeonlys_.empty())
2263                 return false;
2264         return (std::find(includeonlys_.begin(),
2265                           includeonlys_.end(), child) != includeonlys_.end());
2266 }
2267
2268
2269 void GuiDocument::applyView()
2270 {
2271         // preamble
2272         preambleModule->apply(bp_);
2273         localLayout->apply(bp_);
2274
2275         // date
2276         bp_.suppress_date = latexModule->suppressDateCB->isChecked();
2277         bp_.use_refstyle  = latexModule->refstyleCB->isChecked();
2278
2279         // biblio
2280         bp_.setCiteEngine(ENGINE_BASIC);
2281
2282         if (biblioModule->citeNatbibRB->isChecked()) {
2283                 bool const use_numerical_citations =
2284                         biblioModule->citeStyleCO->currentIndex();
2285                 if (use_numerical_citations)
2286                         bp_.setCiteEngine(ENGINE_NATBIB_NUMERICAL);
2287                 else
2288                         bp_.setCiteEngine(ENGINE_NATBIB_AUTHORYEAR);
2289
2290         } else if (biblioModule->citeJurabibRB->isChecked())
2291                 bp_.setCiteEngine(ENGINE_JURABIB);
2292
2293         bp_.use_bibtopic =
2294                 biblioModule->bibtopicCB->isChecked();
2295
2296         bp_.biblio_style = fromqstr(biblioModule->bibtexStyleLE->text());
2297
2298         string const bibtex_command =
2299                 fromqstr(biblioModule->bibtexCO->itemData(
2300                         biblioModule->bibtexCO->currentIndex()).toString());
2301         string const bibtex_options =
2302                 fromqstr(biblioModule->bibtexOptionsLE->text());
2303         if (bibtex_command == "default" || bibtex_options.empty())
2304                 bp_.bibtex_command = bibtex_command;
2305         else
2306                 bp_.bibtex_command = bibtex_command + " " + bibtex_options;
2307
2308         if (biblioChanged_) {
2309                 buffer().invalidateBibinfoCache();
2310                 buffer().removeBiblioTempFiles();
2311         }
2312
2313         // Indices
2314         indicesModule->apply(bp_);
2315
2316         // language & quotes
2317         if (langModule->defaultencodingRB->isChecked()) {
2318                 bp_.inputenc = "auto";
2319         } else {
2320                 int i = langModule->encodingCO->currentIndex();
2321                 if (i == 0)
2322                         bp_.inputenc = "default";
2323                 else {
2324                         QString const enc_gui =
2325                                 langModule->encodingCO->currentText();
2326                         Encodings::const_iterator it = encodings.begin();
2327                         Encodings::const_iterator const end = encodings.end();
2328                         bool found = false;
2329                         for (; it != end; ++it) {
2330                                 if (qt_(it->guiName()) == enc_gui) {
2331                                         bp_.inputenc = it->latexName();
2332                                         found = true;
2333                                         break;
2334                                 }
2335                         }
2336                         if (!found) {
2337                                 // should not happen
2338                                 lyxerr << "GuiDocument::apply: Unknown encoding! Resetting to default" << endl;
2339                                 bp_.inputenc = "default";
2340                         }
2341                 }
2342         }
2343
2344         InsetQuotes::QuoteLanguage lga = InsetQuotes::EnglishQuotes;
2345         switch (langModule->quoteStyleCO->currentIndex()) {
2346         case 0:
2347                 lga = InsetQuotes::EnglishQuotes;
2348                 break;
2349         case 1:
2350                 lga = InsetQuotes::SwedishQuotes;
2351                 break;
2352         case 2:
2353                 lga = InsetQuotes::GermanQuotes;
2354                 break;
2355         case 3:
2356                 lga = InsetQuotes::PolishQuotes;
2357                 break;
2358         case 4:
2359                 lga = InsetQuotes::FrenchQuotes;
2360                 break;
2361         case 5:
2362                 lga = InsetQuotes::DanishQuotes;
2363                 break;
2364         }
2365         bp_.quotes_language = lga;
2366
2367         QString const lang = langModule->languageCO->itemData(
2368                 langModule->languageCO->currentIndex()).toString();
2369         bp_.language = lyx::languages.getLanguage(fromqstr(lang));
2370
2371         QString const pack = langModule->languagePackageCO->itemData(
2372                 langModule->languagePackageCO->currentIndex()).toString();
2373         if (pack == "custom")
2374                 bp_.lang_package =
2375                         fromqstr(langModule->languagePackageLE->text());
2376         else
2377                 bp_.lang_package = fromqstr(pack);
2378
2379         //color
2380         bp_.backgroundcolor = set_backgroundcolor;
2381         bp_.isbackgroundcolor = is_backgroundcolor;
2382         bp_.fontcolor = set_fontcolor;
2383         bp_.isfontcolor = is_fontcolor;
2384         bp_.notefontcolor = set_notefontcolor;
2385         bp_.boxbgcolor = set_boxbgcolor;
2386
2387         // numbering
2388         if (bp_.documentClass().hasTocLevels()) {
2389                 bp_.tocdepth = numberingModule->tocSL->value();
2390                 bp_.secnumdepth = numberingModule->depthSL->value();
2391         }
2392
2393         // bullets
2394         bp_.user_defined_bullet(0) = bulletsModule->bullet(0);
2395         bp_.user_defined_bullet(1) = bulletsModule->bullet(1);
2396         bp_.user_defined_bullet(2) = bulletsModule->bullet(2);
2397         bp_.user_defined_bullet(3) = bulletsModule->bullet(3);
2398
2399         // packages
2400         bp_.graphics_driver =
2401                 tex_graphics[latexModule->psdriverCO->currentIndex()];
2402
2403         // text layout
2404         int idx = latexModule->classCO->currentIndex();
2405         if (idx >= 0) {
2406                 string const classname = classes_model_.getIDString(idx);
2407                 bp_.setBaseClass(classname);
2408         }
2409
2410         // Modules
2411         modulesToParams(bp_);
2412
2413         // Math
2414         vector<string> const & packages = BufferParams::auto_packages();
2415         for (size_t n = 0; n < packages.size(); ++n) {
2416                 QCheckBox * autoCB = static_cast<QCheckBox *>(
2417                         mathsModule->gridLayout->itemAtPosition(2 * n, 0)->widget());
2418                 if (autoCB->isChecked())
2419                         bp_.use_package(packages[n], BufferParams::package_auto);
2420                 else {
2421                         QCheckBox * alwaysCB = static_cast<QCheckBox *>(
2422                                 mathsModule->gridLayout->itemAtPosition(2 * n + 1, 0)->widget());
2423                         if (alwaysCB->isChecked())
2424                                 bp_.use_package(packages[n], BufferParams::package_on);
2425                         else
2426                                 bp_.use_package(packages[n], BufferParams::package_off);
2427                 }
2428         }
2429
2430         // Page Layout
2431         if (pageLayoutModule->pagestyleCO->currentIndex() == 0)
2432                 bp_.pagestyle = "default";
2433         else {
2434                 QString style_gui = pageLayoutModule->pagestyleCO->currentText();
2435                 for (size_t i = 0; i != pagestyles.size(); ++i)
2436                         if (pagestyles[i].second == style_gui)
2437                                 bp_.pagestyle = pagestyles[i].first;
2438         }
2439
2440         // Text Layout
2441         switch (textLayoutModule->lspacingCO->currentIndex()) {
2442         case 0:
2443                 bp_.spacing().set(Spacing::Single);
2444                 break;
2445         case 1:
2446                 bp_.spacing().set(Spacing::Onehalf);
2447                 break;
2448         case 2:
2449                 bp_.spacing().set(Spacing::Double);
2450                 break;
2451         case 3: {
2452                 string s = widgetToDoubleStr(textLayoutModule->lspacingLE);
2453                 if (s.empty())
2454                         bp_.spacing().set(Spacing::Single);
2455                 else
2456                         bp_.spacing().set(Spacing::Other, s);
2457                 break;
2458                 }
2459         }
2460
2461         if (textLayoutModule->twoColumnCB->isChecked())
2462                 bp_.columns = 2;
2463         else
2464                 bp_.columns = 1;
2465
2466         bp_.justification = textLayoutModule->justCB->isChecked();
2467
2468         if (textLayoutModule->indentRB->isChecked()) {
2469                 // if paragraphs are separated by an indentation
2470                 bp_.paragraph_separation = BufferParams::ParagraphIndentSeparation;
2471                 switch (textLayoutModule->indentCO->currentIndex()) {
2472                 case 0:
2473                         bp_.setIndentation(HSpace(HSpace::DEFAULT));
2474                         break;
2475                 case 1: {
2476                         HSpace indent = HSpace(
2477                                 widgetsToLength(textLayoutModule->indentLE,
2478                                 textLayoutModule->indentLengthCO)
2479                                 );
2480                         bp_.setIndentation(indent);
2481                         break;
2482                         }
2483                 default:
2484                         // this should never happen
2485                         bp_.setIndentation(HSpace(HSpace::DEFAULT));
2486                         break;
2487                 }
2488         } else {
2489                 // if paragraphs are separated by a skip
2490                 bp_.paragraph_separation = BufferParams::ParagraphSkipSeparation;
2491                 switch (textLayoutModule->skipCO->currentIndex()) {
2492                 case 0:
2493                         bp_.setDefSkip(VSpace(VSpace::SMALLSKIP));
2494                         break;
2495                 case 1:
2496                         bp_.setDefSkip(VSpace(VSpace::MEDSKIP));
2497                         break;
2498                 case 2:
2499                         bp_.setDefSkip(VSpace(VSpace::BIGSKIP));
2500                         break;
2501                 case 3:
2502                         {
2503                         VSpace vs = VSpace(
2504                                 widgetsToLength(textLayoutModule->skipLE,
2505                                 textLayoutModule->skipLengthCO)
2506                                 );
2507                         bp_.setDefSkip(vs);
2508                         break;
2509                         }
2510                 default:
2511                         // this should never happen
2512                         bp_.setDefSkip(VSpace(VSpace::MEDSKIP));
2513                         break;
2514                 }
2515         }
2516
2517         bp_.options =
2518                 fromqstr(latexModule->optionsLE->text());
2519
2520         bp_.use_default_options =
2521                 latexModule->defaultOptionsCB->isChecked();
2522
2523         if (latexModule->childDocGB->isChecked())
2524                 bp_.master =
2525                         fromqstr(latexModule->childDocLE->text());
2526         else
2527                 bp_.master = string();
2528
2529         // Master/Child
2530         bp_.clearIncludedChildren();
2531         if (masterChildModule->includeonlyRB->isChecked()) {
2532                 list<string>::const_iterator it = includeonlys_.begin();
2533                 for (; it != includeonlys_.end() ; ++it) {
2534                         bp_.addIncludedChildren(*it);
2535                 }
2536         }
2537         bp_.maintain_unincluded_children =
2538                 masterChildModule->maintainAuxCB->isChecked();
2539
2540         // Float Placement
2541         bp_.float_placement = floatModule->get();
2542
2543         // Listings
2544         // text should have passed validation
2545         bp_.listings_params =
2546                 InsetListingsParams(fromqstr(listingsModule->listingsED->toPlainText())).params();
2547
2548         // output
2549         bp_.default_output_format = fromqstr(outputModule->defaultFormatCO->itemData(
2550                 outputModule->defaultFormatCO->currentIndex()).toString());
2551
2552         bool const nontexfonts = fontModule->osFontsCB->isChecked();
2553         bp_.useNonTeXFonts = nontexfonts;
2554
2555         bp_.output_sync = outputModule->outputsyncCB->isChecked();
2556         
2557         bp_.output_sync_macro = fromqstr(outputModule->synccustomCB->currentText());
2558
2559         int mathfmt = outputModule->mathoutCB->currentIndex();
2560         if (mathfmt == -1)
2561                 mathfmt = 0;
2562         BufferParams::MathOutput const mo =
2563                 static_cast<BufferParams::MathOutput>(mathfmt);
2564         bp_.html_math_output = mo;
2565         bp_.html_be_strict = outputModule->strictCB->isChecked();
2566         bp_.html_css_as_file = outputModule->cssCB->isChecked();
2567         bp_.html_math_img_scale = outputModule->mathimgSB->value();
2568
2569         // fonts
2570         bp_.fonts_roman =
2571                 fromqstr(fontModule->fontsRomanCO->
2572                         itemData(fontModule->fontsRomanCO->currentIndex()).toString());
2573
2574         bp_.fonts_sans =
2575                 fromqstr(fontModule->fontsSansCO->
2576                         itemData(fontModule->fontsSansCO->currentIndex()).toString());
2577
2578         bp_.fonts_typewriter =
2579                 fromqstr(fontModule->fontsTypewriterCO->
2580                         itemData(fontModule->fontsTypewriterCO->currentIndex()).toString());
2581
2582         if (fontModule->fontencCO->currentIndex() == 0)
2583                 bp_.fontenc = "global";
2584         else if (fontModule->fontencCO->currentIndex() == 1)
2585                 bp_.fontenc = fromqstr(fontModule->fontencLE->text());
2586         else if (fontModule->fontencCO->currentIndex() == 2)
2587                 bp_.fontenc = "default";
2588
2589         bp_.fonts_cjk =
2590                 fromqstr(fontModule->cjkFontLE->text());
2591
2592         bp_.fonts_sans_scale = fontModule->scaleSansSB->value();
2593
2594         bp_.fonts_typewriter_scale = fontModule->scaleTypewriterSB->value();
2595
2596         bp_.fonts_expert_sc = fontModule->fontScCB->isChecked();
2597
2598         bp_.fonts_old_figures = fontModule->fontOsfCB->isChecked();
2599
2600         if (nontexfonts)
2601                 bp_.fonts_default_family = "default";
2602         else
2603                 bp_.fonts_default_family = GuiDocument::fontfamilies[
2604                         fontModule->fontsDefaultCO->currentIndex()];
2605
2606         if (fontModule->fontsizeCO->currentIndex() == 0)
2607                 bp_.fontsize = "default";
2608         else
2609                 bp_.fontsize =
2610                         fromqstr(fontModule->fontsizeCO->currentText());
2611
2612         // paper
2613         bp_.papersize = PAPER_SIZE(
2614                 pageLayoutModule->papersizeCO->currentIndex());
2615
2616         bp_.paperwidth = widgetsToLength(pageLayoutModule->paperwidthLE,
2617                 pageLayoutModule->paperwidthUnitCO);
2618
2619         bp_.paperheight = widgetsToLength(pageLayoutModule->paperheightLE,
2620                 pageLayoutModule->paperheightUnitCO);
2621
2622         if (pageLayoutModule->facingPagesCB->isChecked())
2623                 bp_.sides = TwoSides;
2624         else
2625                 bp_.sides = OneSide;
2626
2627         if (pageLayoutModule->landscapeRB->isChecked())
2628                 bp_.orientation = ORIENTATION_LANDSCAPE;
2629         else
2630                 bp_.orientation = ORIENTATION_PORTRAIT;
2631
2632         // margins
2633         bp_.use_geometry = !marginsModule->marginCB->isChecked();
2634
2635         Ui::MarginsUi const * m = marginsModule;
2636
2637         bp_.leftmargin = widgetsToLength(m->innerLE, m->innerUnit);
2638         bp_.topmargin = widgetsToLength(m->topLE, m->topUnit);
2639         bp_.rightmargin = widgetsToLength(m->outerLE, m->outerUnit);
2640         bp_.bottommargin = widgetsToLength(m->bottomLE, m->bottomUnit);
2641         bp_.headheight = widgetsToLength(m->headheightLE, m->headheightUnit);
2642         bp_.headsep = widgetsToLength(m->headsepLE, m->headsepUnit);
2643         bp_.footskip = widgetsToLength(m->footskipLE, m->footskipUnit);
2644         bp_.columnsep = widgetsToLength(m->columnsepLE, m->columnsepUnit);
2645
2646         // branches
2647         branchesModule->apply(bp_);
2648
2649         // PDF support
2650         PDFOptions & pdf = bp_.pdfoptions();
2651         pdf.use_hyperref = pdfSupportModule->use_hyperrefGB->isChecked();
2652         pdf.title = fromqstr(pdfSupportModule->titleLE->text());
2653         pdf.author = fromqstr(pdfSupportModule->authorLE->text());
2654         pdf.subject = fromqstr(pdfSupportModule->subjectLE->text());
2655         pdf.keywords = fromqstr(pdfSupportModule->keywordsLE->text());
2656
2657         pdf.bookmarks = pdfSupportModule->bookmarksGB->isChecked();
2658         pdf.bookmarksnumbered = pdfSupportModule->bookmarksnumberedCB->isChecked();
2659         pdf.bookmarksopen = pdfSupportModule->bookmarksopenGB->isChecked();
2660         pdf.bookmarksopenlevel = pdfSupportModule->bookmarksopenlevelSB->value();
2661
2662         pdf.breaklinks = pdfSupportModule->breaklinksCB->isChecked();
2663         pdf.pdfborder = pdfSupportModule->pdfborderCB->isChecked();
2664         pdf.pdfusetitle = pdfSupportModule->pdfusetitleCB->isChecked();
2665         pdf.colorlinks = pdfSupportModule->colorlinksCB->isChecked();
2666         pdf.backref =
2667                 backref_opts[pdfSupportModule->backrefCO->currentIndex()];
2668         if (pdfSupportModule->fullscreenCB->isChecked())
2669                 pdf.pagemode = pdf.pagemode_fullscreen;
2670         else
2671                 pdf.pagemode.clear();
2672         pdf.quoted_options = pdf.quoted_options_check(
2673                                 fromqstr(pdfSupportModule->optionsLE->text()));
2674 }
2675
2676
2677 void GuiDocument::paramsToDialog()
2678 {
2679         // set the default unit
2680         Length::UNIT const default_unit = Length::defaultUnit();
2681
2682         // preamble
2683         preambleModule->update(bp_, id());
2684         localLayout->update(bp_, id());
2685
2686         // date
2687         latexModule->suppressDateCB->setChecked(bp_.suppress_date);
2688         latexModule->refstyleCB->setChecked(bp_.use_refstyle);
2689
2690         // biblio
2691         biblioModule->citeDefaultRB->setChecked(
2692                 bp_.citeEngine() == ENGINE_BASIC);
2693
2694         biblioModule->citeNatbibRB->setChecked(
2695                 bp_.citeEngine() == ENGINE_NATBIB_NUMERICAL ||
2696                 bp_.citeEngine() == ENGINE_NATBIB_AUTHORYEAR);
2697
2698         biblioModule->citeStyleCO->setCurrentIndex(
2699                 bp_.citeEngine() == ENGINE_NATBIB_NUMERICAL);
2700
2701         biblioModule->citeJurabibRB->setChecked(
2702                 bp_.citeEngine() == ENGINE_JURABIB);
2703
2704         biblioModule->bibtopicCB->setChecked(
2705                 bp_.use_bibtopic);
2706
2707         biblioModule->bibtexStyleLE->setText(toqstr(bp_.biblio_style));
2708
2709         string command;
2710         string options =
2711                 split(bp_.bibtex_command, command, ' ');
2712
2713         int const bpos = biblioModule->bibtexCO->findData(toqstr(command));
2714         if (bpos != -1) {
2715                 biblioModule->bibtexCO->setCurrentIndex(bpos);
2716                 biblioModule->bibtexOptionsLE->setText(toqstr(options).trimmed());
2717         } else {
2718                 // We reset to default if we do not know the specified compiler
2719                 // This is for security reasons
2720                 biblioModule->bibtexCO->setCurrentIndex(
2721                         biblioModule->bibtexCO->findData(toqstr("default")));
2722                 biblioModule->bibtexOptionsLE->clear();
2723         }
2724         biblioModule->bibtexOptionsLE->setEnabled(
2725                 biblioModule->bibtexCO->currentIndex() != 0);
2726
2727         biblioChanged_ = false;
2728
2729         // indices
2730         indicesModule->update(bp_);
2731
2732         // language & quotes
2733         int const pos = langModule->languageCO->findData(toqstr(
2734                 bp_.language->lang()));
2735         langModule->languageCO->setCurrentIndex(pos);
2736
2737         langModule->quoteStyleCO->setCurrentIndex(
2738                 bp_.quotes_language);
2739
2740         bool default_enc = true;
2741         if (bp_.inputenc != "auto") {
2742                 default_enc = false;
2743                 if (bp_.inputenc == "default") {
2744                         langModule->encodingCO->setCurrentIndex(0);
2745                 } else {
2746                         string enc_gui;
2747                         Encodings::const_iterator it = encodings.begin();
2748                         Encodings::const_iterator const end = encodings.end();
2749                         for (; it != end; ++it) {
2750                                 if (it->latexName() == bp_.inputenc) {
2751                                         enc_gui = it->guiName();
2752                                         break;
2753                                 }
2754                         }
2755                         int const i = langModule->encodingCO->findText(
2756                                         qt_(enc_gui));
2757                         if (i >= 0)
2758                                 langModule->encodingCO->setCurrentIndex(i);
2759                         else
2760                                 // unknown encoding. Set to default.
2761                                 default_enc = true;
2762                 }
2763         }
2764         langModule->defaultencodingRB->setChecked(default_enc);
2765         langModule->otherencodingRB->setChecked(!default_enc);
2766
2767         int const p = langModule->languagePackageCO->findData(toqstr(bp_.lang_package));
2768         if (p == -1) {
2769                 langModule->languagePackageCO->setCurrentIndex(
2770                           langModule->languagePackageCO->findData("custom"));
2771                 langModule->languagePackageLE->setText(toqstr(bp_.lang_package));
2772         } else {
2773                 langModule->languagePackageCO->setCurrentIndex(p);
2774                 langModule->languagePackageLE->clear();
2775         }
2776
2777         //color
2778         if (bp_.isfontcolor) {
2779                 colorModule->fontColorPB->setStyleSheet(
2780                         colorButtonStyleSheet(rgb2qcolor(bp_.fontcolor)));
2781         }
2782         set_fontcolor = bp_.fontcolor;
2783         is_fontcolor = bp_.isfontcolor;
2784
2785         colorModule->noteFontColorPB->setStyleSheet(
2786                 colorButtonStyleSheet(rgb2qcolor(bp_.notefontcolor)));
2787         set_notefontcolor = bp_.notefontcolor;
2788
2789         if (bp_.isbackgroundcolor) {
2790                 colorModule->backgroundPB->setStyleSheet(
2791                         colorButtonStyleSheet(rgb2qcolor(bp_.backgroundcolor)));
2792         }
2793         set_backgroundcolor = bp_.backgroundcolor;
2794         is_backgroundcolor = bp_.isbackgroundcolor;
2795
2796         colorModule->boxBackgroundPB->setStyleSheet(
2797                 colorButtonStyleSheet(rgb2qcolor(bp_.boxbgcolor)));
2798         set_boxbgcolor = bp_.boxbgcolor;
2799
2800         // numbering
2801         int const min_toclevel = documentClass().min_toclevel();
2802         int const max_toclevel = documentClass().max_toclevel();
2803         if (documentClass().hasTocLevels()) {
2804                 numberingModule->setEnabled(true);
2805                 numberingModule->depthSL->setMinimum(min_toclevel - 1);
2806                 numberingModule->depthSL->setMaximum(max_toclevel);
2807                 numberingModule->depthSL->setValue(bp_.secnumdepth);
2808                 numberingModule->tocSL->setMaximum(min_toclevel - 1);
2809                 numberingModule->tocSL->setMaximum(max_toclevel);
2810                 numberingModule->tocSL->setValue(bp_.tocdepth);
2811                 updateNumbering();
2812         } else {
2813                 numberingModule->setEnabled(false);
2814                 numberingModule->tocTW->clear();
2815         }
2816
2817         // bullets
2818         bulletsModule->setBullet(0, bp_.user_defined_bullet(0));
2819         bulletsModule->setBullet(1, bp_.user_defined_bullet(1));
2820         bulletsModule->setBullet(2, bp_.user_defined_bullet(2));
2821         bulletsModule->setBullet(3, bp_.user_defined_bullet(3));
2822         bulletsModule->init();
2823
2824         // packages
2825         int nitem = findToken(tex_graphics, bp_.graphics_driver);
2826         if (nitem >= 0)
2827                 latexModule->psdriverCO->setCurrentIndex(nitem);
2828         updateModuleInfo();
2829
2830         vector<string> const & packages = BufferParams::auto_packages();
2831         for (size_t n = 0; n < packages.size(); ++n) {
2832                 QCheckBox * alwaysCB = static_cast<QCheckBox *>(
2833                         mathsModule->gridLayout->itemAtPosition(2 * n + 1, 0)->widget());
2834                 alwaysCB->setChecked(bp_.use_package(packages[n]) == BufferParams::package_on);
2835                 QCheckBox * autoCB = static_cast<QCheckBox *>(
2836                         mathsModule->gridLayout->itemAtPosition(2 * n, 0)->widget());
2837                 autoCB->setChecked(bp_.use_package(packages[n]) == BufferParams::package_auto);
2838         }
2839
2840         switch (bp_.spacing().getSpace()) {
2841                 case Spacing::Other: nitem = 3; break;
2842                 case Spacing::Double: nitem = 2; break;
2843                 case Spacing::Onehalf: nitem = 1; break;
2844                 case Spacing::Default: case Spacing::Single: nitem = 0; break;
2845         }
2846
2847         // text layout
2848         string const & layoutID = bp_.baseClassID();
2849         setLayoutComboByIDString(layoutID);
2850
2851         updatePagestyle(documentClass().opt_pagestyle(),
2852                                  bp_.pagestyle);
2853
2854         textLayoutModule->lspacingCO->setCurrentIndex(nitem);
2855         if (bp_.spacing().getSpace() == Spacing::Other) {
2856                 doubleToWidget(textLayoutModule->lspacingLE,
2857                         bp_.spacing().getValueAsString());
2858         }
2859         setLSpacing(nitem);
2860
2861         if (bp_.paragraph_separation == BufferParams::ParagraphIndentSeparation) {
2862                 textLayoutModule->indentRB->setChecked(true);
2863                 string indentation = bp_.getIndentation().asLyXCommand();
2864                 int indent = 0;
2865                 if (indentation != "default") {
2866                         lengthToWidgets(textLayoutModule->indentLE,
2867                         textLayoutModule->indentLengthCO,
2868                         indentation, default_unit);
2869                         indent = 1;
2870                 }
2871                 textLayoutModule->indentCO->setCurrentIndex(indent);
2872                 setIndent(indent);
2873         } else {
2874                 textLayoutModule->skipRB->setChecked(true);
2875                 int skip = 0;
2876                 switch (bp_.getDefSkip().kind()) {
2877                 case VSpace::SMALLSKIP:
2878                         skip = 0;
2879                         break;
2880                 case VSpace::MEDSKIP:
2881                         skip = 1;
2882                         break;
2883                 case VSpace::BIGSKIP:
2884                         skip = 2;
2885                         break;
2886                 case VSpace::LENGTH:
2887                         {
2888                         skip = 3;
2889                         string const length = bp_.getDefSkip().asLyXCommand();
2890                         lengthToWidgets(textLayoutModule->skipLE,
2891                                 textLayoutModule->skipLengthCO,
2892                                 length, default_unit);
2893                         break;
2894                         }
2895                 default:
2896                         skip = 0;
2897                         break;
2898                 }
2899                 textLayoutModule->skipCO->setCurrentIndex(skip);
2900                 setSkip(skip);
2901         }
2902
2903         textLayoutModule->twoColumnCB->setChecked(
2904                 bp_.columns == 2);
2905         textLayoutModule->justCB->setChecked(bp_.justification);
2906
2907         if (!bp_.options.empty()) {
2908                 latexModule->optionsLE->setText(
2909                         toqstr(bp_.options));
2910         } else {
2911                 latexModule->optionsLE->setText(QString());
2912         }
2913
2914         // latex
2915         latexModule->defaultOptionsCB->setChecked(
2916                         bp_.use_default_options);
2917         updateSelectedModules();
2918         selectionManager->updateProvidedModules(
2919                         bp_.baseClass()->providedModules());
2920         selectionManager->updateExcludedModules(
2921                         bp_.baseClass()->excludedModules());
2922
2923         if (!documentClass().options().empty()) {
2924                 latexModule->defaultOptionsLE->setText(
2925                         toqstr(documentClass().options()));
2926         } else {
2927                 latexModule->defaultOptionsLE->setText(
2928                         toqstr(_("[No options predefined]")));
2929         }
2930
2931         latexModule->defaultOptionsLE->setEnabled(
2932                 bp_.use_default_options
2933                 && !documentClass().options().empty());
2934
2935         latexModule->defaultOptionsCB->setEnabled(
2936                 !documentClass().options().empty());
2937
2938         if (!bp_.master.empty()) {
2939                 latexModule->childDocGB->setChecked(true);
2940                 latexModule->childDocLE->setText(
2941                         toqstr(bp_.master));
2942         } else {
2943                 latexModule->childDocLE->setText(QString());
2944                 latexModule->childDocGB->setChecked(false);
2945         }
2946
2947         // Master/Child
2948         if (!bufferview() || !buffer().hasChildren()) {
2949                 masterChildModule->childrenTW->clear();
2950                 includeonlys_.clear();
2951                 docPS->showPanel(qt_("Child Documents"), false);
2952                 if (docPS->isCurrentPanel(qt_("Child Documents")))
2953                         docPS->setCurrentPanel(qt_("Document Class"));
2954         } else {
2955                 docPS->showPanel(qt_("Child Documents"), true);
2956                 masterChildModule->setEnabled(true);
2957                 includeonlys_ = bp_.getIncludedChildren();
2958                 updateIncludeonlys();
2959         }
2960         masterChildModule->maintainAuxCB->setChecked(
2961                 bp_.maintain_unincluded_children);
2962
2963         // Float Settings
2964         floatModule->set(bp_.float_placement);
2965
2966         // ListingsSettings
2967         // break listings_params to multiple lines
2968         string lstparams =
2969                 InsetListingsParams(bp_.listings_params).separatedParams();
2970         listingsModule->listingsED->setPlainText(toqstr(lstparams));
2971
2972         // Output
2973         // update combobox with formats
2974         updateDefaultFormat();
2975         int index = outputModule->defaultFormatCO->findData(toqstr(
2976                 bp_.default_output_format));
2977         // set to default if format is not found
2978         if (index == -1)
2979                 index = 0;
2980         outputModule->defaultFormatCO->setCurrentIndex(index);
2981         bool const os_fonts_available =
2982                 bp_.baseClass()->outputType() == lyx::LATEX
2983                 && LaTeXFeatures::isAvailable("fontspec");
2984         fontModule->osFontsCB->setEnabled(os_fonts_available);
2985         fontModule->osFontsCB->setChecked(
2986                 os_fonts_available && bp_.useNonTeXFonts);
2987
2988         outputModule->outputsyncCB->setChecked(bp_.output_sync);
2989         outputModule->synccustomCB->setEditText(toqstr(bp_.output_sync_macro));
2990
2991         outputModule->mathimgSB->setValue(bp_.html_math_img_scale);
2992         outputModule->mathoutCB->setCurrentIndex(bp_.html_math_output);
2993         outputModule->strictCB->setChecked(bp_.html_be_strict);
2994         outputModule->cssCB->setChecked(bp_.html_css_as_file);
2995
2996         // Fonts
2997         updateFontsize(documentClass().opt_fontsize(),
2998                         bp_.fontsize);
2999
3000         QString font = toqstr(bp_.fonts_roman);
3001         int rpos = fontModule->fontsRomanCO->findData(font);
3002         if (rpos == -1) {
3003                 rpos = fontModule->fontsRomanCO->count();
3004                 fontModule->fontsRomanCO->addItem(font + qt_(" (not installed)"), font);
3005         }
3006         fontModule->fontsRomanCO->setCurrentIndex(rpos);
3007
3008         font = toqstr(bp_.fonts_sans);
3009         int spos = fontModule->fontsSansCO->findData(font);
3010         if (spos == -1) {
3011                 spos = fontModule->fontsSansCO->count();
3012                 fontModule->fontsSansCO->addItem(font + qt_(" (not installed)"), font);
3013         }
3014         fontModule->fontsSansCO->setCurrentIndex(spos);
3015
3016         font = toqstr(bp_.fonts_typewriter);
3017         int tpos = fontModule->fontsTypewriterCO->findData(font);
3018         if (tpos == -1) {
3019                 tpos = fontModule->fontsTypewriterCO->count();
3020                 fontModule->fontsTypewriterCO->addItem(font + qt_(" (not installed)"), font);
3021         }
3022         fontModule->fontsTypewriterCO->setCurrentIndex(tpos);
3023
3024         if (bp_.useNonTeXFonts && os_fonts_available) {
3025                 fontModule->fontencLA->setEnabled(false);
3026                 fontModule->fontencCO->setEnabled(false);
3027                 fontModule->fontencLE->setEnabled(false);
3028         } else {
3029                 fontModule->fontencLA->setEnabled(true);
3030                 fontModule->fontencCO->setEnabled(true);
3031                 fontModule->fontencLE->setEnabled(true);
3032                 romanChanged(rpos);
3033                 sansChanged(spos);
3034                 ttChanged(tpos);
3035         }
3036
3037         if (!bp_.fonts_cjk.empty())
3038                 fontModule->cjkFontLE->setText(
3039                         toqstr(bp_.fonts_cjk));
3040         else
3041                 fontModule->cjkFontLE->setText(QString());
3042
3043         fontModule->fontScCB->setChecked(bp_.fonts_expert_sc);
3044         fontModule->fontOsfCB->setChecked(bp_.fonts_old_figures);
3045         fontModule->scaleSansSB->setValue(bp_.fonts_sans_scale);
3046         fontModule->scaleTypewriterSB->setValue(bp_.fonts_typewriter_scale);
3047
3048         int nn = findToken(GuiDocument::fontfamilies, bp_.fonts_default_family);
3049         if (nn >= 0)
3050                 fontModule->fontsDefaultCO->setCurrentIndex(nn);
3051
3052         if (bp_.fontenc == "global") {
3053                 fontModule->fontencCO->setCurrentIndex(0);
3054                 fontModule->fontencLE->setEnabled(false);
3055         } else if (bp_.fontenc == "default") {
3056                 fontModule->fontencCO->setCurrentIndex(2);
3057                 fontModule->fontencLE->setEnabled(false);
3058         } else {
3059                 fontModule->fontencCO->setCurrentIndex(1);
3060                 fontModule->fontencLE->setText(toqstr(bp_.fontenc));
3061         }
3062
3063         // paper
3064         bool const extern_geometry =
3065                 documentClass().provides("geometry");
3066         int const psize = bp_.papersize;
3067         pageLayoutModule->papersizeCO->setCurrentIndex(psize);
3068         setCustomPapersize(!extern_geometry && psize == 1);
3069         pageLayoutModule->papersizeCO->setEnabled(!extern_geometry);
3070
3071         bool const landscape =
3072                 bp_.orientation == ORIENTATION_LANDSCAPE;
3073         pageLayoutModule->landscapeRB->setChecked(landscape);
3074         pageLayoutModule->portraitRB->setChecked(!landscape);
3075         pageLayoutModule->landscapeRB->setEnabled(!extern_geometry);
3076         pageLayoutModule->portraitRB->setEnabled(!extern_geometry);
3077
3078         pageLayoutModule->facingPagesCB->setChecked(
3079                 bp_.sides == TwoSides);
3080
3081         lengthToWidgets(pageLayoutModule->paperwidthLE,
3082                 pageLayoutModule->paperwidthUnitCO, bp_.paperwidth, default_unit);
3083         lengthToWidgets(pageLayoutModule->paperheightLE,
3084                 pageLayoutModule->paperheightUnitCO, bp_.paperheight, default_unit);
3085
3086         // margins
3087         Ui::MarginsUi * m = marginsModule;
3088
3089         setMargins();
3090
3091         lengthToWidgets(m->topLE, m->topUnit,
3092                 bp_.topmargin, default_unit);
3093
3094         lengthToWidgets(m->bottomLE, m->bottomUnit,
3095                 bp_.bottommargin, default_unit);
3096
3097         lengthToWidgets(m->innerLE, m->innerUnit,
3098                 bp_.leftmargin, default_unit);
3099
3100         lengthToWidgets(m->outerLE, m->outerUnit,
3101                 bp_.rightmargin, default_unit);
3102
3103         lengthToWidgets(m->headheightLE, m->headheightUnit,
3104                 bp_.headheight, default_unit);
3105
3106         lengthToWidgets(m->headsepLE, m->headsepUnit,
3107                 bp_.headsep, default_unit);
3108
3109         lengthToWidgets(m->footskipLE, m->footskipUnit,
3110                 bp_.footskip, default_unit);
3111
3112         lengthToWidgets(m->columnsepLE, m->columnsepUnit,
3113                 bp_.columnsep, default_unit);
3114
3115         // branches
3116         updateUnknownBranches();
3117         branchesModule->update(bp_);
3118
3119         // PDF support
3120         PDFOptions const & pdf = bp_.pdfoptions();
3121         pdfSupportModule->use_hyperrefGB->setChecked(pdf.use_hyperref);
3122         if (bp_.documentClass().provides("hyperref"))
3123                 pdfSupportModule->use_hyperrefGB->setTitle(qt_("C&ustomize Hyperref Options"));
3124         else
3125                 pdfSupportModule->use_hyperrefGB->setTitle(qt_("&Use Hyperref Support"));
3126         pdfSupportModule->titleLE->setText(toqstr(pdf.title));
3127         pdfSupportModule->authorLE->setText(toqstr(pdf.author));
3128         pdfSupportModule->subjectLE->setText(toqstr(pdf.subject));
3129         pdfSupportModule->keywordsLE->setText(toqstr(pdf.keywords));
3130
3131         pdfSupportModule->bookmarksGB->setChecked(pdf.bookmarks);
3132         pdfSupportModule->bookmarksnumberedCB->setChecked(pdf.bookmarksnumbered);
3133         pdfSupportModule->bookmarksopenGB->setChecked(pdf.bookmarksopen);
3134
3135         pdfSupportModule->bookmarksopenlevelSB->setValue(pdf.bookmarksopenlevel);
3136
3137         pdfSupportModule->breaklinksCB->setChecked(pdf.breaklinks);
3138         pdfSupportModule->pdfborderCB->setChecked(pdf.pdfborder);
3139         pdfSupportModule->pdfusetitleCB->setChecked(pdf.pdfusetitle);
3140         pdfSupportModule->colorlinksCB->setChecked(pdf.colorlinks);
3141
3142         nn = findToken(backref_opts, pdf.backref);
3143         if (nn >= 0)
3144                 pdfSupportModule->backrefCO->setCurrentIndex(nn);
3145
3146         pdfSupportModule->fullscreenCB->setChecked
3147                 (pdf.pagemode == pdf.pagemode_fullscreen);
3148
3149         pdfSupportModule->optionsLE->setText(
3150                 toqstr(pdf.quoted_options));
3151
3152         // Make sure that the bc is in the INITIAL state
3153         if (bc().policy().buttonStatus(ButtonPolicy::RESTORE))
3154                 bc().restore();
3155
3156         // clear changed branches cache
3157         changedBranches_.clear();
3158 }
3159
3160
3161 void GuiDocument::saveDocDefault()
3162 {
3163         // we have to apply the params first
3164         applyView();
3165         saveAsDefault();
3166 }
3167
3168
3169 void GuiDocument::updateAvailableModules()
3170 {
3171         modules_av_model_.clear();
3172         list<modInfoStruct> const & modInfoList = getModuleInfo();
3173         list<modInfoStruct>::const_iterator mit = modInfoList.begin();
3174         list<modInfoStruct>::const_iterator men = modInfoList.end();
3175         for (int i = 0; mit != men; ++mit, ++i)
3176                 modules_av_model_.insertRow(i, mit->name, mit->id,
3177                                 mit->description);
3178 }
3179
3180
3181 void GuiDocument::updateSelectedModules()
3182 {
3183         modules_sel_model_.clear();
3184         list<modInfoStruct> const selModList = getSelectedModules();
3185         list<modInfoStruct>::const_iterator mit = selModList.begin();
3186         list<modInfoStruct>::const_iterator men = selModList.end();
3187         for (int i = 0; mit != men; ++mit, ++i)
3188                 modules_sel_model_.insertRow(i, mit->name, mit->id,
3189                                 mit->description);
3190 }
3191
3192
3193 void GuiDocument::updateIncludeonlys()
3194 {
3195         masterChildModule->childrenTW->clear();
3196         QString const no = qt_("No");
3197         QString const yes = qt_("Yes");
3198
3199         if (includeonlys_.empty()) {
3200                 masterChildModule->includeallRB->setChecked(true);
3201                 masterChildModule->childrenTW->setEnabled(false);
3202                 masterChildModule->maintainAuxCB->setEnabled(false);
3203         } else {
3204                 masterChildModule->includeonlyRB->setChecked(true);
3205                 masterChildModule->childrenTW->setEnabled(true);
3206                 masterChildModule->maintainAuxCB->setEnabled(true);
3207         }
3208         QTreeWidgetItem * item = 0;
3209         ListOfBuffers children = buffer().getChildren();
3210         ListOfBuffers::const_iterator it  = children.begin();
3211         ListOfBuffers::const_iterator end = children.end();
3212         bool has_unincluded = false;
3213         bool all_unincluded = true;
3214         for (; it != end; ++it) {
3215                 item = new QTreeWidgetItem(masterChildModule->childrenTW);
3216                 // FIXME Unicode
3217                 string const name =
3218                         to_utf8(makeRelPath(from_utf8((*it)->fileName().absFileName()),
3219                                                         from_utf8(buffer().filePath())));
3220                 item->setText(0, toqstr(name));
3221                 item->setText(1, isChildIncluded(name) ? yes : no);
3222                 if (!isChildIncluded(name))
3223                         has_unincluded = true;
3224                 else
3225                         all_unincluded = false;
3226         }
3227         // Both if all childs are included and if none is included
3228         // is equal to "include all" (i.e., ommit \includeonly).
3229         // Thus, reset the GUI.
3230         if (!has_unincluded || all_unincluded) {
3231                 masterChildModule->includeallRB->setChecked(true);
3232                 masterChildModule->childrenTW->setEnabled(false);
3233                 includeonlys_.clear();
3234         }
3235         // If all are included, we need to update again.
3236         if (!has_unincluded)
3237                 updateIncludeonlys();
3238 }
3239
3240
3241 void GuiDocument::updateContents()
3242 {
3243         // Nothing to do here as the document settings is not cursor dependant.
3244         return;
3245 }
3246
3247
3248 void GuiDocument::useClassDefaults()
3249 {
3250         if (applyPB->isEnabled()) {
3251                 int const ret = Alert::prompt(_("Unapplied changes"),
3252                                 _("Some changes in the dialog were not yet applied.\n"
3253                                   "If you do not apply now, they will be lost after this action."),
3254                                 1, 1, _("&Apply"), _("&Dismiss"));
3255                 if (ret == 0)
3256                         applyView();
3257         }
3258
3259         int idx = latexModule->classCO->currentIndex();
3260         string const classname = classes_model_.getIDString(idx);
3261         if (!bp_.setBaseClass(classname)) {
3262                 Alert::error(_("Error"), _("Unable to set document class."));
3263                 return;
3264         }
3265         bp_.useClassDefaults();
3266         paramsToDialog();
3267 }
3268
3269
3270 void GuiDocument::setLayoutComboByIDString(string const & idString)
3271 {
3272         int idx = classes_model_.findIDString(idString);
3273         if (idx < 0)
3274                 Alert::warning(_("Can't set layout!"),
3275                         bformat(_("Unable to set layout for ID: %1$s"), from_utf8(idString)));
3276         else
3277                 latexModule->classCO->setCurrentIndex(idx);
3278 }
3279
3280
3281 bool GuiDocument::isValid()
3282 {
3283         return
3284                 validateListingsParameters().isEmpty() &&
3285                 localLayout->isValid() &&
3286                 (
3287                         // if we're asking for skips between paragraphs
3288                         !textLayoutModule->skipRB->isChecked() ||
3289                         // then either we haven't chosen custom
3290                         textLayoutModule->skipCO->currentIndex() != 3 ||
3291                         // or else a length has been given
3292                         !textLayoutModule->skipLE->text().isEmpty()
3293                 ) &&
3294                 (
3295                         // if we're asking for indentation
3296                         !textLayoutModule->indentRB->isChecked() ||
3297                         // then either we haven't chosen custom
3298                         textLayoutModule->indentCO->currentIndex() != 1 ||
3299                         // or else a length has been given
3300                         !textLayoutModule->indentLE->text().isEmpty()
3301                 );
3302 }
3303
3304
3305 char const * const GuiDocument::fontfamilies[5] = {
3306         "default", "rmdefault", "sfdefault", "ttdefault", ""
3307 };
3308
3309
3310 char const * GuiDocument::fontfamilies_gui[5] = {
3311         N_("Default"), N_("Roman"), N_("Sans Serif"), N_("Typewriter"), ""
3312 };
3313
3314
3315 bool GuiDocument::initialiseParams(string const &)
3316 {
3317         BufferView const * view = bufferview();
3318         if (!view) {
3319                 bp_ = BufferParams();
3320                 paramsToDialog();
3321                 return true;
3322         }
3323         bp_ = view->buffer().params();
3324         loadModuleInfo();
3325         updateAvailableModules();
3326         //FIXME It'd be nice to make sure here that the selected
3327         //modules are consistent: That required modules are actually
3328         //selected, and that we don't have conflicts. If so, we could
3329         //at least pop up a warning.
3330         paramsToDialog();
3331         return true;
3332 }
3333
3334
3335 void GuiDocument::clearParams()
3336 {
3337         bp_ = BufferParams();
3338 }
3339
3340
3341 BufferId GuiDocument::id() const
3342 {
3343         BufferView const * const view = bufferview();
3344         return view? &view->buffer() : 0;
3345 }
3346
3347
3348 list<GuiDocument::modInfoStruct> const & GuiDocument::getModuleInfo()
3349 {
3350         return moduleNames_;
3351 }
3352
3353
3354 list<GuiDocument::modInfoStruct> const
3355                 GuiDocument::makeModuleInfo(LayoutModuleList const & mods)
3356 {
3357         LayoutModuleList::const_iterator it =  mods.begin();
3358         LayoutModuleList::const_iterator end = mods.end();
3359         list<modInfoStruct> mInfo;
3360         for (; it != end; ++it) {
3361                 modInfoStruct m;
3362                 m.id = *it;
3363                 LyXModule const * const mod = theModuleList[*it];
3364                 if (mod)
3365                         // FIXME Unicode
3366                         m.name = toqstr(translateIfPossible(from_utf8(mod->getName())));
3367                 else
3368                         m.name = toqstr(*it) + toqstr(" (") + qt_("Not Found") + toqstr(")");
3369                 mInfo.push_back(m);
3370         }
3371         return mInfo;
3372 }
3373
3374
3375 list<GuiDocument::modInfoStruct> const GuiDocument::getSelectedModules()
3376 {
3377         return makeModuleInfo(params().getModules());
3378 }
3379
3380
3381 list<GuiDocument::modInfoStruct> const GuiDocument::getProvidedModules()
3382 {
3383         return makeModuleInfo(params().baseClass()->providedModules());
3384 }
3385
3386
3387 DocumentClass const & GuiDocument::documentClass() const
3388 {
3389         return bp_.documentClass();
3390 }
3391
3392
3393 static void dispatch_bufferparams(Dialog const & dialog,
3394         BufferParams const & bp, FuncCode lfun)
3395 {
3396         ostringstream ss;
3397         ss << "\\begin_header\n";
3398         bp.writeFile(ss);
3399         ss << "\\end_header\n";
3400         dialog.dispatch(FuncRequest(lfun, ss.str()));
3401 }
3402
3403
3404 void GuiDocument::dispatchParams()
3405 {
3406         // This must come first so that a language change is correctly noticed
3407         setLanguage();
3408
3409         // Apply the BufferParams. Note that this will set the base class
3410         // and then update the buffer's layout.
3411         dispatch_bufferparams(*this, params(), LFUN_BUFFER_PARAMS_APPLY);
3412
3413         if (!params().master.empty()) {
3414                 FileName const master_file = support::makeAbsPath(params().master,
3415                            support::onlyPath(buffer().absFileName()));
3416                 if (isLyXFileName(master_file.absFileName())) {
3417                         Buffer * master = checkAndLoadLyXFile(master_file);
3418                         if (master) {
3419                                 if (master->isChild(const_cast<Buffer *>(&buffer())))
3420                                         const_cast<Buffer &>(buffer()).setParent(master);
3421                                 else
3422                                         Alert::warning(_("Assigned master does not include this file"),
3423                                                 bformat(_("You must include this file in the document\n"
3424                                                           "'%1$s' in order to use the master document\n"
3425                                                           "feature."), from_utf8(params().master)));
3426                         } else
3427                                 Alert::warning(_("Could not load master"),
3428                                                 bformat(_("The master document '%1$s'\n"
3429                                                            "could not be loaded."),
3430                                                            from_utf8(params().master)));
3431                 }
3432         }
3433
3434         // Generate the colours requested by each new branch.
3435         BranchList & branchlist = params().branchlist();
3436         if (!branchlist.empty()) {
3437                 BranchList::const_iterator it = branchlist.begin();
3438                 BranchList::const_iterator const end = branchlist.end();
3439                 for (; it != end; ++it) {
3440                         docstring const & current_branch = it->branch();
3441                         Branch const * branch = branchlist.find(current_branch);
3442                         string const x11hexname = X11hexname(branch->color());
3443                         // display the new color
3444                         docstring const str = current_branch + ' ' + from_ascii(x11hexname);
3445                         dispatch(FuncRequest(LFUN_SET_COLOR, str));
3446                 }
3447
3448                 // Open insets of selected branches, close deselected ones
3449                 dispatch(FuncRequest(LFUN_INSET_FORALL,
3450                         "Branch inset-toggle assign"));
3451         }
3452         // rename branches in the document
3453         executeBranchRenaming();
3454         // and clear changed branches cache
3455         changedBranches_.clear();
3456
3457         // Generate the colours requested by indices.
3458         IndicesList & indiceslist = params().indiceslist();
3459         if (!indiceslist.empty()) {
3460                 IndicesList::const_iterator it = indiceslist.begin();
3461                 IndicesList::const_iterator const end = indiceslist.end();
3462                 for (; it != end; ++it) {
3463                         docstring const & current_index = it->shortcut();
3464                         Index const * index = indiceslist.findShortcut(current_index);
3465                         string const x11hexname = X11hexname(index->color());
3466                         // display the new color
3467                         docstring const str = current_index + ' ' + from_ascii(x11hexname);
3468                         dispatch(FuncRequest(LFUN_SET_COLOR, str));
3469                 }
3470         }
3471         // FIXME LFUN
3472         // If we used an LFUN, we would not need these two lines:
3473         BufferView * bv = const_cast<BufferView *>(bufferview());
3474         bv->processUpdateFlags(Update::Force | Update::FitCursor);
3475 }
3476
3477
3478 void GuiDocument::setLanguage() const
3479 {
3480         Language const * const newL = bp_.language;
3481         if (buffer().params().language == newL)
3482                 return;
3483
3484         string const & lang_name = newL->lang();
3485         dispatch(FuncRequest(LFUN_BUFFER_LANGUAGE, lang_name));
3486 }
3487
3488
3489 void GuiDocument::saveAsDefault() const
3490 {
3491         dispatch_bufferparams(*this, params(), LFUN_BUFFER_SAVE_AS_DEFAULT);
3492 }
3493
3494
3495 bool GuiDocument::isFontAvailable(string const & font) const
3496 {
3497         if (font == "default" || font == "cmr"
3498             || font == "cmss" || font == "cmtt")
3499                 // these are standard
3500                 return true;
3501         if (font == "lmodern" || font == "lmss" || font == "lmtt")
3502                 return LaTeXFeatures::isAvailable("lmodern");
3503         if (font == "times" || font == "palatino"
3504                  || font == "helvet" || font == "courier")
3505                 return LaTeXFeatures::isAvailable("psnfss");
3506         if (font == "cmbr" || font == "cmtl")
3507                 return LaTeXFeatures::isAvailable("cmbright");
3508         if (font == "utopia")
3509                 return LaTeXFeatures::isAvailable("utopia")
3510                         || LaTeXFeatures::isAvailable("fourier");
3511         if (font == "beraserif" || font == "berasans"
3512                 || font == "beramono")
3513                 return LaTeXFeatures::isAvailable("bera");
3514         return LaTeXFeatures::isAvailable(font);
3515 }
3516
3517
3518 bool GuiDocument::providesOSF(string const & font) const
3519 {
3520         if (fontModule->osFontsCB->isChecked())
3521                 // FIXME: we should check if the fonts really
3522                 // have OSF support. But how?
3523                 return true;
3524         if (font == "cmr")
3525                 return isFontAvailable("eco");
3526         if (font == "palatino")
3527                 return isFontAvailable("mathpazo");
3528         return false;
3529 }
3530
3531
3532 bool GuiDocument::providesSC(string const & font) const
3533 {
3534         if (fontModule->osFontsCB->isChecked())
3535                 return false;
3536         if (font == "palatino")
3537                 return isFontAvailable("mathpazo");
3538         if (font == "utopia")
3539                 return isFontAvailable("fourier");
3540         return false;
3541 }
3542
3543
3544 bool GuiDocument::providesScale(string const & font) const
3545 {
3546         if (fontModule->osFontsCB->isChecked())
3547                 return true;
3548         return font == "helvet" || font == "luximono"
3549                 || font == "berasans"  || font == "beramono";
3550 }
3551
3552
3553 void GuiDocument::loadModuleInfo()
3554 {
3555         moduleNames_.clear();
3556         LyXModuleList::const_iterator it  = theModuleList.begin();
3557         LyXModuleList::const_iterator end = theModuleList.end();
3558         for (; it != end; ++it) {
3559                 modInfoStruct m;
3560                 m.id = it->getID();
3561                 // FIXME Unicode
3562                 m.name = toqstr(translateIfPossible(from_utf8(it->getName())));
3563                 // this is supposed to give us the first sentence of the description
3564                 // FIXME Unicode
3565                 QString desc =
3566                         toqstr(translateIfPossible(from_utf8(it->getDescription())));
3567                 int const pos = desc.indexOf(".");
3568                 if (pos > 0)
3569                         desc.truncate(pos + 1);
3570                 m.description = desc;
3571                 moduleNames_.push_back(m);
3572         }
3573 }
3574
3575
3576 void GuiDocument::updateUnknownBranches()
3577 {
3578         if (!bufferview())
3579                 return;
3580         list<docstring> used_branches;
3581         buffer().getUsedBranches(used_branches);
3582         list<docstring>::const_iterator it = used_branches.begin();
3583         QStringList unknown_branches;
3584         for (; it != used_branches.end() ; ++it) {
3585                 if (!buffer().params().branchlist().find(*it))
3586                         unknown_branches.append(toqstr(*it));
3587         }
3588         branchesModule->setUnknownBranches(unknown_branches);
3589 }
3590
3591
3592 void GuiDocument::branchesRename(docstring const & oldname, docstring const & newname)
3593 {
3594         map<docstring, docstring>::iterator it = changedBranches_.begin();
3595         for (; it != changedBranches_.end() ; ++it) {
3596                 if (it->second == oldname) {
3597                         // branch has already been renamed
3598                         it->second = newname;
3599                         return;
3600                 }
3601         }
3602         // store new name
3603         changedBranches_[oldname] = newname;
3604 }
3605
3606
3607 void GuiDocument::executeBranchRenaming() const
3608 {
3609         map<docstring, docstring>::const_iterator it = changedBranches_.begin();
3610         for (; it != changedBranches_.end() ; ++it) {
3611                 docstring const arg = '"' + it->first + '"' + " " + '"' + it->second + '"';
3612                 dispatch(FuncRequest(LFUN_BRANCHES_RENAME, arg));
3613         }
3614 }
3615
3616
3617 Dialog * createGuiDocument(GuiView & lv) { return new GuiDocument(lv); }
3618
3619
3620 } // namespace frontend
3621 } // namespace lyx
3622
3623 #include "moc_GuiDocument.cpp"