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