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