]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiView.cpp
89e439e029a8e83691ed60cf5bfc85ff122e186b
[lyx.git] / src / frontends / qt4 / GuiView.cpp
1 /**
2  * \file GuiView.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author John Levon
8  * \author Abdelrazak Younes
9  * \author Peter Kümmel
10  *
11  * Full author contact details are available in file CREDITS.
12  */
13
14 #include <config.h>
15
16 #include "GuiView.h"
17
18 #include "Dialog.h"
19 #include "DispatchResult.h"
20 #include "FileDialog.h"
21 #include "FontLoader.h"
22 #include "GuiApplication.h"
23 #include "GuiCommandBuffer.h"
24 #include "GuiCompleter.h"
25 #include "GuiKeySymbol.h"
26 #include "GuiToc.h"
27 #include "GuiToolbar.h"
28 #include "GuiWorkArea.h"
29 #include "LayoutBox.h"
30 #include "Menus.h"
31 #include "TocModel.h"
32
33 #include "qt_helpers.h"
34
35 #include "frontends/alert.h"
36
37 #include "buffer_funcs.h"
38 #include "Buffer.h"
39 #include "BufferList.h"
40 #include "BufferParams.h"
41 #include "BufferView.h"
42 #include "Compare.h"
43 #include "Converter.h"
44 #include "Cursor.h"
45 #include "CutAndPaste.h"
46 #include "Encoding.h"
47 #include "ErrorList.h"
48 #include "Format.h"
49 #include "FuncStatus.h"
50 #include "FuncRequest.h"
51 #include "Intl.h"
52 #include "Layout.h"
53 #include "Lexer.h"
54 #include "LyXAction.h"
55 #include "LyX.h"
56 #include "LyXRC.h"
57 #include "LyXVC.h"
58 #include "Paragraph.h"
59 #include "SpellChecker.h"
60 #include "TextClass.h"
61 #include "Text.h"
62 #include "Toolbars.h"
63 #include "version.h"
64
65 #include "support/convert.h"
66 #include "support/debug.h"
67 #include "support/ExceptionMessage.h"
68 #include "support/FileName.h"
69 #include "support/filetools.h"
70 #include "support/gettext.h"
71 #include "support/filetools.h"
72 #include "support/ForkedCalls.h"
73 #include "support/lassert.h"
74 #include "support/lstrings.h"
75 #include "support/os.h"
76 #include "support/Package.h"
77 #include "support/Path.h"
78 #include "support/Systemcall.h"
79 #include "support/Timeout.h"
80 #include "support/ProgressInterface.h"
81 #include "GuiProgress.h"
82
83 #include <QAction>
84 #include <QApplication>
85 #include <QCloseEvent>
86 #include <QDebug>
87 #include <QDesktopWidget>
88 #include <QDragEnterEvent>
89 #include <QDropEvent>
90 #include <QList>
91 #include <QMenu>
92 #include <QMenuBar>
93 #include <QPainter>
94 #include <QPixmap>
95 #include <QPixmapCache>
96 #include <QPoint>
97 #include <QPushButton>
98 #include <QSettings>
99 #include <QShowEvent>
100 #include <QSplitter>
101 #include <QStackedWidget>
102 #include <QStatusBar>
103 #include <QTime>
104 #include <QTimer>
105 #include <QToolBar>
106 #include <QUrl>
107 #include <QScrollBar>
108
109 #define EXPORT_in_THREAD 1
110
111 // QtConcurrent was introduced in Qt 4.4
112 #if (QT_VERSION >= 0x040400)
113 #include <QFuture>
114 #include <QFutureWatcher>
115 #include <QtConcurrentRun>
116 #endif
117
118 #include <boost/bind.hpp>
119
120 #include <sstream>
121
122 #ifdef HAVE_SYS_TIME_H
123 # include <sys/time.h>
124 #endif
125 #ifdef HAVE_UNISTD_H
126 # include <unistd.h>
127 #endif
128
129 using namespace std;
130 using namespace lyx::support;
131
132 namespace lyx {
133 namespace frontend {
134
135 namespace {
136
137 class BackgroundWidget : public QWidget
138 {
139 public:
140         BackgroundWidget()
141         {
142                 LYXERR(Debug::GUI, "show banner: " << lyxrc.show_banner);
143                 /// The text to be written on top of the pixmap
144                 QString const text = lyx_version ?
145                         qt_("version ") + lyx_version : qt_("unknown version");
146                 splash_ = getPixmap("images/", "banner", "png");
147
148                 QPainter pain(&splash_);
149                 pain.setPen(QColor(0, 0, 0));
150                 QFont font;
151                 // The font used to display the version info
152                 font.setStyleHint(QFont::SansSerif);
153                 font.setWeight(QFont::Bold);
154                 font.setPointSize(int(toqstr(lyxrc.font_sizes[FONT_SIZE_LARGE]).toDouble()));
155                 pain.setFont(font);
156                 pain.drawText(260, 15, text);
157                 setFocusPolicy(Qt::StrongFocus);
158         }
159
160         void paintEvent(QPaintEvent *)
161         {
162                 int x = (width() - splash_.width()) / 2;
163                 int y = (height() - splash_.height()) / 2;
164                 QPainter pain(this);
165                 pain.drawPixmap(x, y, splash_);
166         }
167
168         void keyPressEvent(QKeyEvent * ev)
169         {
170                 KeySymbol sym;
171                 setKeySymbol(&sym, ev);
172                 if (sym.isOK()) {
173                         guiApp->processKeySym(sym, q_key_state(ev->modifiers()));
174                         ev->accept();
175                 } else {
176                         ev->ignore();
177                 }
178         }
179
180 private:
181         QPixmap splash_;
182 };
183
184
185 /// Toolbar store providing access to individual toolbars by name.
186 typedef map<string, GuiToolbar *> ToolbarMap;
187
188 typedef boost::shared_ptr<Dialog> DialogPtr;
189
190 } // namespace anon
191
192
193 struct GuiView::GuiViewPrivate
194 {
195         GuiViewPrivate(GuiView * gv)
196                 : gv_(gv), current_work_area_(0), current_main_work_area_(0),
197                 layout_(0), autosave_timeout_(5000),
198                 in_show_(false)
199         {
200                 // hardcode here the platform specific icon size
201                 smallIconSize = 14;  // scaling problems
202                 normalIconSize = 20; // ok, default
203                 bigIconSize = 26;       // better for some math icons
204
205                 splitter_ = new QSplitter;
206                 bg_widget_ = new BackgroundWidget;
207                 stack_widget_ = new QStackedWidget;
208                 stack_widget_->addWidget(bg_widget_);
209                 stack_widget_->addWidget(splitter_);
210                 setBackground();
211
212                 // TODO cleanup, remove the singleton, handle multiple Windows?
213                 progress_ = ProgressInterface::instance();
214                 if (!dynamic_cast<GuiProgress*>(progress_)) {           
215                         progress_ = new GuiProgress();  // TODO who deletes it
216                         ProgressInterface::setInstance(progress_);                      
217                 }
218                 QObject::connect(
219                                 dynamic_cast<GuiProgress*>(progress_), 
220                                 SIGNAL(updateStatusBarMessage(QString const&)), 
221                                 gv, SLOT(updateStatusBarMessage(QString const&)));
222                 QObject::connect(
223                                 dynamic_cast<GuiProgress*>(progress_), 
224                                 SIGNAL(clearMessageText()), 
225                                 gv, SLOT(clearMessageText()));
226         }
227
228         ~GuiViewPrivate()
229         {
230                 delete splitter_;
231                 delete bg_widget_;
232                 delete stack_widget_;
233         }
234
235         QMenu * toolBarPopup(GuiView * parent)
236         {
237                 // FIXME: translation
238                 QMenu * menu = new QMenu(parent);
239                 QActionGroup * iconSizeGroup = new QActionGroup(parent);
240
241                 QAction * smallIcons = new QAction(iconSizeGroup);
242                 smallIcons->setText(qt_("Small-sized icons"));
243                 smallIcons->setCheckable(true);
244                 QObject::connect(smallIcons, SIGNAL(triggered()),
245                         parent, SLOT(smallSizedIcons()));
246                 menu->addAction(smallIcons);
247
248                 QAction * normalIcons = new QAction(iconSizeGroup);
249                 normalIcons->setText(qt_("Normal-sized icons"));
250                 normalIcons->setCheckable(true);
251                 QObject::connect(normalIcons, SIGNAL(triggered()),
252                         parent, SLOT(normalSizedIcons()));
253                 menu->addAction(normalIcons);
254
255                 QAction * bigIcons = new QAction(iconSizeGroup);
256                 bigIcons->setText(qt_("Big-sized icons"));
257                 bigIcons->setCheckable(true);
258                 QObject::connect(bigIcons, SIGNAL(triggered()),
259                         parent, SLOT(bigSizedIcons()));
260                 menu->addAction(bigIcons);
261
262                 unsigned int cur = parent->iconSize().width();
263                 if ( cur == parent->d.smallIconSize)
264                         smallIcons->setChecked(true);
265                 else if (cur == parent->d.normalIconSize)
266                         normalIcons->setChecked(true);
267                 else if (cur == parent->d.bigIconSize)
268                         bigIcons->setChecked(true);
269
270                 return menu;
271         }
272
273         void setBackground()
274         {
275                 stack_widget_->setCurrentWidget(bg_widget_);
276                 bg_widget_->setUpdatesEnabled(true);
277                 bg_widget_->setFocus();
278         }
279
280         TabWorkArea * tabWorkArea(int i)
281         {
282                 return dynamic_cast<TabWorkArea *>(splitter_->widget(i));
283         }
284
285         TabWorkArea * currentTabWorkArea()
286         {
287                 if (splitter_->count() == 1)
288                         // The first TabWorkArea is always the first one, if any.
289                         return tabWorkArea(0);
290
291                 for (int i = 0; i != splitter_->count(); ++i) {
292                         TabWorkArea * twa = tabWorkArea(i);
293                         if (current_main_work_area_ == twa->currentWorkArea())
294                                 return twa;
295                 }
296
297                 // None has the focus so we just take the first one.
298                 return tabWorkArea(0);
299         }
300
301 #if (QT_VERSION >= 0x040400)
302         void setPreviewFuture(QFuture<docstring> const & f)
303         {
304                 if (preview_watcher_.isRunning()) {
305                         // we prefer to cancel this preview in order to keep a snappy
306                         // interface.
307                         return;
308                 }
309                 preview_watcher_.setFuture(f);
310         }
311 #endif
312
313 public:
314         GuiView * gv_;
315         GuiWorkArea * current_work_area_;
316         GuiWorkArea * current_main_work_area_;
317         QSplitter * splitter_;
318         QStackedWidget * stack_widget_;
319         BackgroundWidget * bg_widget_;
320         /// view's toolbars
321         ToolbarMap toolbars_;
322         ProgressInterface* progress_;
323         /// The main layout box.
324         /** 
325          * \warning Don't Delete! The layout box is actually owned by
326          * whichever toolbar contains it. All the GuiView class needs is a
327          * means of accessing it.
328          *
329          * FIXME: replace that with a proper model so that we are not limited
330          * to only one dialog.
331          */
332         LayoutBox * layout_;
333
334         ///
335         map<string, DialogPtr> dialogs_;
336
337         unsigned int smallIconSize;
338         unsigned int normalIconSize;
339         unsigned int bigIconSize;
340         ///
341         QTimer statusbar_timer_;
342         /// auto-saving of buffers
343         Timeout autosave_timeout_;
344         /// flag against a race condition due to multiclicks, see bug #1119
345         bool in_show_;
346
347         ///
348         TocModels toc_models_;
349
350 #if (QT_VERSION >= 0x040400)
351         ///
352         QFutureWatcher<docstring> autosave_watcher_;
353         QFutureWatcher<docstring> preview_watcher_;
354 #else
355         struct DummyWatcher { bool isRunning(){return false;} }; 
356         DummyWatcher preview_watcher_;
357 #endif
358 };
359
360
361 GuiView::GuiView(int id)
362         : d(*new GuiViewPrivate(this)), id_(id), closing_(false)
363 {
364         // GuiToolbars *must* be initialised before the menu bar.
365         normalSizedIcons(); // at least on Mac the default is 32 otherwise, which is huge
366         constructToolbars();
367
368         // set ourself as the current view. This is needed for the menu bar
369         // filling, at least for the static special menu item on Mac. Otherwise
370         // they are greyed out.
371         guiApp->setCurrentView(this);
372         
373         // Fill up the menu bar.
374         guiApp->menus().fillMenuBar(menuBar(), this, true);
375
376         setCentralWidget(d.stack_widget_);
377
378         // Start autosave timer
379         if (lyxrc.autosave) {
380                 d.autosave_timeout_.timeout.connect(boost::bind(&GuiView::autoSave, this));
381                 d.autosave_timeout_.setTimeout(lyxrc.autosave * 1000);
382                 d.autosave_timeout_.start();
383         }
384         connect(&d.statusbar_timer_, SIGNAL(timeout()),
385                 this, SLOT(clearMessage()));
386
387         // We don't want to keep the window in memory if it is closed.
388         setAttribute(Qt::WA_DeleteOnClose, true);
389
390 #if (!defined(Q_WS_WIN) && !defined(Q_WS_MACX))
391         // assign an icon to main form. We do not do it under Qt/Win or Qt/Mac,
392         // since the icon is provided in the application bundle.
393         setWindowIcon(getPixmap("images/", "lyx", "png"));
394 #endif
395
396 #if (QT_VERSION >= 0x040300)
397         // use tabbed dock area for multiple docks
398         // (such as "source" and "messages")
399         setDockOptions(QMainWindow::ForceTabbedDocks);
400 #endif
401
402         // For Drag&Drop.
403         setAcceptDrops(true);
404
405         statusBar()->setSizeGripEnabled(true);
406         updateStatusBar();
407
408 #if (QT_VERSION >= 0x040400)
409         connect(&d.autosave_watcher_, SIGNAL(finished()), this,
410                 SLOT(threadFinished()));
411         connect(&d.preview_watcher_, SIGNAL(finished()), this,
412                 SLOT(threadFinished()));
413 #endif
414
415         connect(this, SIGNAL(triggerShowDialog(QString const &, QString const &, Inset *)),
416                 SLOT(doShowDialog(QString const &, QString const &, Inset *)));
417
418         // Forbid too small unresizable window because it can happen
419         // with some window manager under X11.
420         setMinimumSize(300, 200);
421
422         if (lyxrc.allow_geometry_session) {
423                 // Now take care of session management.
424                 if (restoreLayout())
425                         return;
426         }
427
428         // no session handling, default to a sane size.
429         setGeometry(50, 50, 690, 510);
430         initToolbars();
431
432         // clear session data if any.
433         QSettings settings;
434         settings.remove("views");
435 }
436
437
438 GuiView::~GuiView()
439 {
440         delete &d;
441 }
442
443
444 void GuiView::threadFinished()
445 {
446 #if (QT_VERSION >= 0x040400)
447         QFutureWatcher<docstring> const * watcher =
448                 static_cast<QFutureWatcher<docstring> const *>(sender());
449         message(watcher->result());
450 #endif
451 }
452
453
454 void GuiView::saveLayout() const
455 {
456         QSettings settings;
457         settings.beginGroup("views");
458         settings.beginGroup(QString::number(id_));
459 #ifdef Q_WS_X11
460         settings.setValue("pos", pos());
461         settings.setValue("size", size());
462 #else
463         settings.setValue("geometry", saveGeometry());
464 #endif
465         settings.setValue("layout", saveState(0));
466         settings.setValue("icon_size", iconSize());
467 }
468
469
470 bool GuiView::restoreLayout()
471 {
472         QSettings settings;
473         settings.beginGroup("views");
474         settings.beginGroup(QString::number(id_));
475         QString const icon_key = "icon_size";
476         if (!settings.contains(icon_key))
477                 return false;
478
479         //code below is skipped when when ~/.config/LyX is (re)created
480         setIconSize(settings.value(icon_key).toSize());
481 #ifdef Q_WS_X11
482         QPoint pos = settings.value("pos", QPoint(50, 50)).toPoint();
483         QSize size = settings.value("size", QSize(690, 510)).toSize();
484         resize(size);
485         move(pos);
486 #else
487         // Work-around for bug #6034: the window ends up in an undetermined
488         // state when trying to restore a maximized window when it is
489         // already maximized.
490         if (!(windowState() & Qt::WindowMaximized))
491                 if (!restoreGeometry(settings.value("geometry").toByteArray()))
492                         setGeometry(50, 50, 690, 510);
493 #endif
494         // Make sure layout is correctly oriented.
495         setLayoutDirection(qApp->layoutDirection());
496
497         // Allow the toc and view-source dock widget to be restored if needed.
498         Dialog * dialog;
499         if ((dialog = findOrBuild("toc", true)))
500                 // see bug 5082. At least setup title and enabled state.
501                 // Visibility will be adjusted by restoreState below.
502                 dialog->prepareView();
503         if ((dialog = findOrBuild("view-source", true)))
504                 dialog->prepareView();
505         if ((dialog = findOrBuild("progress", true)))
506                 dialog->prepareView();
507
508         if (!restoreState(settings.value("layout").toByteArray(), 0))
509                 initToolbars();
510         updateDialogs();
511         return true;
512 }
513
514
515 GuiToolbar * GuiView::toolbar(string const & name)
516 {
517         ToolbarMap::iterator it = d.toolbars_.find(name);
518         if (it != d.toolbars_.end())
519                 return it->second;
520
521         LYXERR(Debug::GUI, "Toolbar::display: no toolbar named " << name);
522         return 0;
523 }
524
525
526 void GuiView::constructToolbars()
527 {
528         ToolbarMap::iterator it = d.toolbars_.begin();
529         for (; it != d.toolbars_.end(); ++it)
530                 delete it->second;
531         d.toolbars_.clear();
532
533         // I don't like doing this here, but the standard toolbar
534         // destroys this object when it's destroyed itself (vfr)
535         d.layout_ = new LayoutBox(*this);
536         d.stack_widget_->addWidget(d.layout_);
537         d.layout_->move(0,0);
538
539         // extracts the toolbars from the backend
540         Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
541         Toolbars::Infos::iterator end = guiApp->toolbars().end();
542         for (; cit != end; ++cit)
543                 d.toolbars_[cit->name] =  new GuiToolbar(*cit, *this);
544 }
545
546
547 void GuiView::initToolbars()
548 {
549         // extracts the toolbars from the backend
550         Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
551         Toolbars::Infos::iterator end = guiApp->toolbars().end();
552         for (; cit != end; ++cit) {
553                 GuiToolbar * tb = toolbar(cit->name);
554                 if (!tb)
555                         continue;
556                 int const visibility = guiApp->toolbars().defaultVisibility(cit->name);
557                 bool newline = !(visibility & Toolbars::SAMEROW);
558                 tb->setVisible(false);
559                 tb->setVisibility(visibility);
560
561                 if (visibility & Toolbars::TOP) {
562                         if (newline)
563                                 addToolBarBreak(Qt::TopToolBarArea);
564                         addToolBar(Qt::TopToolBarArea, tb);
565                 }
566
567                 if (visibility & Toolbars::BOTTOM) {
568                         // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
569 #if (QT_VERSION >= 0x040202)
570                         if (newline)
571                                 addToolBarBreak(Qt::BottomToolBarArea);
572 #endif
573                         addToolBar(Qt::BottomToolBarArea, tb);
574                 }
575
576                 if (visibility & Toolbars::LEFT) {
577                         // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
578 #if (QT_VERSION >= 0x040202)
579                         if (newline)
580                                 addToolBarBreak(Qt::LeftToolBarArea);
581 #endif
582                         addToolBar(Qt::LeftToolBarArea, tb);
583                 }
584
585                 if (visibility & Toolbars::RIGHT) {
586                         // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
587 #if (QT_VERSION >= 0x040202)
588                         if (newline)
589                                 addToolBarBreak(Qt::RightToolBarArea);
590 #endif
591                         addToolBar(Qt::RightToolBarArea, tb);
592                 }
593
594                 if (visibility & Toolbars::ON)
595                         tb->setVisible(true);
596         }
597 }
598
599
600 TocModels & GuiView::tocModels()
601 {
602         return d.toc_models_;
603 }
604
605
606 void GuiView::setFocus()
607 {
608         LYXERR(Debug::DEBUG, "GuiView::setFocus()" << this);
609         QMainWindow::setFocus();
610 }
611
612
613 void GuiView::focusInEvent(QFocusEvent * e)
614 {
615         LYXERR(Debug::DEBUG, "GuiView::focusInEvent()" << this);
616         QMainWindow::focusInEvent(e);
617         // Make sure guiApp points to the correct view.
618         guiApp->setCurrentView(this);
619         if (currentMainWorkArea())
620                 currentMainWorkArea()->setFocus();
621         else if (currentWorkArea())
622                 currentWorkArea()->setFocus();
623         else
624                 d.bg_widget_->setFocus();
625 }
626
627
628 QMenu * GuiView::createPopupMenu()
629 {
630         return d.toolBarPopup(this);
631 }
632
633
634 void GuiView::showEvent(QShowEvent * e)
635 {
636         LYXERR(Debug::GUI, "Passed Geometry "
637                 << size().height() << "x" << size().width()
638                 << "+" << pos().x() << "+" << pos().y());
639
640         if (d.splitter_->count() == 0)
641                 // No work area, switch to the background widget.
642                 d.setBackground();
643
644         QMainWindow::showEvent(e);
645 }
646
647
648 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
649  ** is responsibility of the container (e.g., dialog)
650  **/
651 void GuiView::closeEvent(QCloseEvent * close_event)
652 {
653         LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
654         closing_ = true;
655
656         writeSession();
657
658         // it can happen that this event arrives without selecting the view,
659         // e.g. when clicking the close button on a background window.
660         setFocus();
661         if (!closeWorkAreaAll()) {
662                 closing_ = false;
663                 close_event->ignore();
664                 return;
665         }
666
667         // Make sure that nothing will use this to be closed View.
668         guiApp->unregisterView(this);
669
670         if (isFullScreen()) {
671                 // Switch off fullscreen before closing.
672                 toggleFullScreen();
673                 updateDialogs();
674         }
675
676         // Make sure the timer time out will not trigger a statusbar update.
677         d.statusbar_timer_.stop();
678
679         // Saving fullscreen requires additional tweaks in the toolbar code.
680         // It wouldn't also work under linux natively.
681         if (lyxrc.allow_geometry_session) {
682                 // Save this window geometry and layout.
683                 saveLayout();
684                 // Then the toolbar private states.
685                 ToolbarMap::iterator end = d.toolbars_.end();
686                 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
687                         it->second->saveSession();
688                 // Now take care of all other dialogs:
689                 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
690                 for (; it!= d.dialogs_.end(); ++it)
691                         it->second->saveSession();
692         }
693
694         close_event->accept();
695 }
696
697
698 void GuiView::dragEnterEvent(QDragEnterEvent * event)
699 {
700         if (event->mimeData()->hasUrls())
701                 event->accept();
702         /// \todo Ask lyx-devel is this is enough:
703         /// if (event->mimeData()->hasFormat("text/plain"))
704         ///     event->acceptProposedAction();
705 }
706
707
708 void GuiView::dropEvent(QDropEvent * event)
709 {
710         QList<QUrl> files = event->mimeData()->urls();
711         if (files.isEmpty())
712                 return;
713
714         LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
715         for (int i = 0; i != files.size(); ++i) {
716                 string const file = os::internal_path(fromqstr(
717                         files.at(i).toLocalFile()));
718                 if (file.empty())
719                         continue;
720
721                 string const ext = support::getExtension(file);
722                 vector<const Format *> found_formats;
723
724                 // Find all formats that have the correct extension.
725                 vector<const Format *> const & import_formats 
726                         = theConverters().importableFormats();
727                 vector<const Format *>::const_iterator it = import_formats.begin();
728                 for (; it != import_formats.end(); ++it)
729                         if ((*it)->extension() == ext)
730                                 found_formats.push_back(*it);
731
732                 FuncRequest cmd;
733                 if (found_formats.size() >= 1) {
734                         if (found_formats.size() > 1) {
735                                 //FIXME: show a dialog to choose the correct importable format
736                                 LYXERR(Debug::FILES,
737                                         "Multiple importable formats found, selecting first");
738                         }
739                         string const arg = found_formats[0]->name() + " " + file;
740                         cmd = FuncRequest(LFUN_BUFFER_IMPORT, arg);
741                 } 
742                 else {
743                         //FIXME: do we have to explicitly check whether it's a lyx file?
744                         LYXERR(Debug::FILES,
745                                 "No formats found, trying to open it as a lyx file");
746                         cmd = FuncRequest(LFUN_FILE_OPEN, file);
747                 }
748
749                 // Asynchronously post the event. DropEvent usually comes
750                 // from the BufferView. But reloading a file might close
751                 // the BufferView from within its own event handler.
752                 guiApp->dispatchDelayed(cmd);
753                 event->accept();
754         }
755 }
756
757
758 void GuiView::message(docstring const & str)
759 {
760         if (ForkedProcess::iAmAChild())
761                 return;
762         
763         // call is moved to GUI-thread by GuiProgress
764         d.progress_->appendMessage(toqstr(str));
765 }
766
767
768 void GuiView::clearMessageText()
769 {
770         message(docstring());
771 }
772
773
774 void GuiView::updateStatusBarMessage(QString const & str)
775 {
776         statusBar()->showMessage(str);
777         d.statusbar_timer_.stop();
778         d.statusbar_timer_.start(3000);
779 }
780
781
782 void GuiView::smallSizedIcons()
783 {
784         setIconSize(QSize(d.smallIconSize, d.smallIconSize));
785 }
786
787
788 void GuiView::normalSizedIcons()
789 {
790         setIconSize(QSize(d.normalIconSize, d.normalIconSize));
791 }
792
793
794 void GuiView::bigSizedIcons()
795 {
796         setIconSize(QSize(d.bigIconSize, d.bigIconSize));
797 }
798
799
800 void GuiView::clearMessage()
801 {
802         // FIXME: This code was introduced in r19643 to fix bug #4123. However,
803         // the hasFocus function mostly returns false, even if the focus is on
804         // a workarea in this view.
805         //if (!hasFocus())
806         //      return;
807         showMessage();
808         d.statusbar_timer_.stop();
809 }
810
811
812 void GuiView::updateWindowTitle(GuiWorkArea * wa)
813 {
814         if (wa != d.current_work_area_
815                 || wa->bufferView().buffer().isInternal())
816                 return;
817         setWindowTitle(qt_("LyX: ") + wa->windowTitle());
818         setWindowIconText(wa->windowIconText());
819 }
820
821
822 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
823 {
824         disconnectBuffer();
825         disconnectBufferView();
826         connectBufferView(wa->bufferView());
827         connectBuffer(wa->bufferView().buffer());
828         d.current_work_area_ = wa;
829         QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
830                 this, SLOT(updateWindowTitle(GuiWorkArea *)));
831         updateWindowTitle(wa);
832
833         structureChanged();
834
835         // The document settings needs to be reinitialised.
836         updateDialog("document", "");
837
838         // Buffer-dependent dialogs must be updated. This is done here because
839         // some dialogs require buffer()->text.
840         updateDialogs();
841 }
842
843
844 void GuiView::on_lastWorkAreaRemoved()
845 {
846         if (closing_)
847                 // We already are in a close event. Nothing more to do.
848                 return;
849
850         if (d.splitter_->count() > 1)
851                 // We have a splitter so don't close anything.
852                 return;
853
854         // Reset and updates the dialogs.
855         d.toc_models_.reset(0);
856         updateDialog("document", "");
857         updateDialogs();
858
859         resetWindowTitleAndIconText();
860         updateStatusBar();
861
862         if (lyxrc.open_buffers_in_tabs)
863                 // Nothing more to do, the window should stay open.
864                 return;
865
866         if (guiApp->viewIds().size() > 1) {
867                 close();
868                 return;
869         }
870
871 #ifdef Q_WS_MACX
872         // On Mac we also close the last window because the application stay
873         // resident in memory. On other platforms we don't close the last
874         // window because this would quit the application.
875         close();
876 #endif
877 }
878
879
880 void GuiView::updateStatusBar()
881 {
882         // let the user see the explicit message
883         if (d.statusbar_timer_.isActive())
884                 return;
885
886         showMessage();
887 }
888
889
890 void GuiView::showMessage()
891 {
892         QString msg = toqstr(theGuiApp()->viewStatusMessage());
893         if (msg.isEmpty()) {
894                 BufferView const * bv = currentBufferView();
895                 if (bv)
896                         msg = toqstr(bv->cursor().currentState());
897                 else
898                         msg = qt_("Welcome to LyX!");
899         }
900         statusBar()->showMessage(msg);
901 }
902
903
904 bool GuiView::event(QEvent * e)
905 {
906         switch (e->type())
907         {
908         // Useful debug code:
909         //case QEvent::ActivationChange:
910         //case QEvent::WindowDeactivate:
911         //case QEvent::Paint:
912         //case QEvent::Enter:
913         //case QEvent::Leave:
914         //case QEvent::HoverEnter:
915         //case QEvent::HoverLeave:
916         //case QEvent::HoverMove:
917         //case QEvent::StatusTip:
918         //case QEvent::DragEnter:
919         //case QEvent::DragLeave:
920         //case QEvent::Drop:
921         //      break;
922
923         case QEvent::WindowActivate: {
924                 GuiView * old_view = guiApp->currentView();
925                 if (this == old_view) {
926                         setFocus();
927                         return QMainWindow::event(e);
928                 }
929                 if (old_view && old_view->currentBufferView()) {
930                         // save current selection to the selection buffer to allow
931                         // middle-button paste in this window.
932                         cap::saveSelection(old_view->currentBufferView()->cursor());
933                 }
934                 guiApp->setCurrentView(this);
935                 if (d.current_work_area_) {
936                         BufferView & bv = d.current_work_area_->bufferView();
937                         connectBufferView(bv);
938                         connectBuffer(bv.buffer());
939                         // The document structure, name and dialogs might have
940                         // changed in another view.
941                         structureChanged();
942                         // The document settings needs to be reinitialised.
943                         updateDialog("document", "");
944                         updateDialogs();
945                 } else {
946                         resetWindowTitleAndIconText();
947                 }
948                 setFocus();
949                 return QMainWindow::event(e);
950         }
951
952         case QEvent::ShortcutOverride: {
953
954 // See bug 4888
955 #if (!defined Q_WS_X11) || (QT_VERSION >= 0x040500)
956                 if (isFullScreen() && menuBar()->isHidden()) {
957                         QKeyEvent * ke = static_cast<QKeyEvent*>(e);
958                         // FIXME: we should also try to detect special LyX shortcut such as
959                         // Alt-P and Alt-M. Right now there is a hack in
960                         // GuiWorkArea::processKeySym() that hides again the menubar for
961                         // those cases.
962                         if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
963                                 menuBar()->show();
964                                 return QMainWindow::event(e);
965                         }
966                 }
967 #endif
968                 return QMainWindow::event(e);
969         }
970
971         default:
972                 return QMainWindow::event(e);
973         }
974 }
975
976 void GuiView::resetWindowTitleAndIconText()
977 {
978         setWindowTitle(qt_("LyX"));
979         setWindowIconText(qt_("LyX"));
980 }
981
982 bool GuiView::focusNextPrevChild(bool /*next*/)
983 {
984         setFocus();
985         return true;
986 }
987
988
989 void GuiView::setBusy(bool busy)
990 {
991         if (d.current_work_area_) {
992                 d.current_work_area_->setUpdatesEnabled(!busy);
993                 if (busy)
994                         d.current_work_area_->stopBlinkingCursor();
995                 else
996                         d.current_work_area_->startBlinkingCursor();
997         }
998
999         if (busy)
1000                 QApplication::setOverrideCursor(Qt::WaitCursor);
1001         else
1002                 QApplication::restoreOverrideCursor();
1003 }
1004
1005
1006 GuiWorkArea * GuiView::workArea(Buffer & buffer)
1007 {
1008         if (currentWorkArea()
1009                 && &currentWorkArea()->bufferView().buffer() == &buffer)
1010                 return (GuiWorkArea *) currentWorkArea();
1011         if (TabWorkArea * twa = d.currentTabWorkArea())
1012                 return twa->workArea(buffer);
1013         return 0;
1014 }
1015
1016
1017 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
1018 {
1019         // Automatically create a TabWorkArea if there are none yet.
1020         TabWorkArea * tab_widget = d.splitter_->count() 
1021                 ? d.currentTabWorkArea() : addTabWorkArea();
1022         return tab_widget->addWorkArea(buffer, *this);
1023 }
1024
1025
1026 TabWorkArea * GuiView::addTabWorkArea()
1027 {
1028         TabWorkArea * twa = new TabWorkArea;
1029         QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
1030                 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
1031         QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
1032                          this, SLOT(on_lastWorkAreaRemoved()));
1033
1034         d.splitter_->addWidget(twa);
1035         d.stack_widget_->setCurrentWidget(d.splitter_);
1036         return twa;
1037 }
1038
1039
1040 GuiWorkArea const * GuiView::currentWorkArea() const
1041 {
1042         return d.current_work_area_;
1043 }
1044
1045
1046 GuiWorkArea * GuiView::currentWorkArea()
1047 {
1048         return d.current_work_area_;
1049 }
1050
1051
1052 GuiWorkArea const * GuiView::currentMainWorkArea() const
1053 {
1054         if (!d.currentTabWorkArea())
1055                 return 0;
1056         return d.currentTabWorkArea()->currentWorkArea();
1057 }
1058
1059
1060 GuiWorkArea * GuiView::currentMainWorkArea()
1061 {
1062         if (!d.currentTabWorkArea())
1063                 return 0;
1064         return d.currentTabWorkArea()->currentWorkArea();
1065 }
1066
1067
1068 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
1069 {
1070         LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
1071         if (!wa) {
1072                 d.current_work_area_ = 0;
1073                 d.setBackground();
1074                 return;
1075         }
1076
1077         // FIXME: I've no clue why this is here and why it accesses
1078         //  theGuiApp()->currentView, which might be 0 (bug 6464).
1079         //  See also 27525 (vfr).
1080         if (theGuiApp()->currentView() == this 
1081                   && theGuiApp()->currentView()->currentWorkArea() == wa) 
1082                 return;
1083
1084         if (currentBufferView())
1085                 cap::saveSelection(currentBufferView()->cursor());
1086
1087         theGuiApp()->setCurrentView(this);
1088         d.current_work_area_ = wa;
1089         for (int i = 0; i != d.splitter_->count(); ++i) {
1090                 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1091                         //if (d.current_main_work_area_)
1092                         //      d.current_main_work_area_->setFrameStyle(QFrame::NoFrame);
1093                         d.current_main_work_area_ = wa;
1094                         //d.current_main_work_area_->setFrameStyle(QFrame::Box | QFrame::Plain);
1095                         //d.current_main_work_area_->setLineWidth(2);
1096                         LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1097                         return;
1098                 }
1099         }
1100         LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1101         on_currentWorkAreaChanged(wa);
1102         BufferView & bv = wa->bufferView();
1103         bv.cursor().fixIfBroken();
1104         bv.updateMetrics();
1105         wa->setUpdatesEnabled(true);
1106         LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1107 }
1108
1109
1110 void GuiView::removeWorkArea(GuiWorkArea * wa)
1111 {
1112         LASSERT(wa, return);
1113         if (wa == d.current_work_area_) {
1114                 disconnectBuffer();
1115                 disconnectBufferView();
1116                 d.current_work_area_ = 0;
1117                 d.current_main_work_area_ = 0;
1118         }
1119
1120         bool found_twa = false;
1121         for (int i = 0; i != d.splitter_->count(); ++i) {
1122                 TabWorkArea * twa = d.tabWorkArea(i);
1123                 if (twa->removeWorkArea(wa)) {
1124                         // Found in this tab group, and deleted the GuiWorkArea.
1125                         found_twa = true;
1126                         if (twa->count() != 0) {
1127                                 if (d.current_work_area_ == 0)
1128                                         // This means that we are closing the current GuiWorkArea, so
1129                                         // switch to the next GuiWorkArea in the found TabWorkArea.
1130                                         setCurrentWorkArea(twa->currentWorkArea());
1131                         } else {
1132                                 // No more WorkAreas in this tab group, so delete it.
1133                                 delete twa;
1134                         }
1135                         break;
1136                 }
1137         }
1138
1139         // It is not a tabbed work area (i.e., the search work area), so it
1140         // should be deleted by other means.
1141         LASSERT(found_twa, /* */);
1142
1143         if (d.current_work_area_ == 0) {
1144                 if (d.splitter_->count() != 0) {
1145                         TabWorkArea * twa = d.currentTabWorkArea();
1146                         setCurrentWorkArea(twa->currentWorkArea());
1147                 } else {
1148                         // No more work areas, switch to the background widget.
1149                         setCurrentWorkArea(0);
1150                 }
1151         }
1152 }
1153
1154
1155 LayoutBox * GuiView::getLayoutDialog() const
1156 {
1157         return d.layout_;
1158 }
1159
1160
1161 void GuiView::updateLayoutList()
1162 {
1163         if (d.layout_)
1164                 d.layout_->updateContents(false);
1165 }
1166
1167
1168 void GuiView::updateToolbars()
1169 {
1170         ToolbarMap::iterator end = d.toolbars_.end();
1171         if (d.current_work_area_) {
1172                 bool const math =
1173                         d.current_work_area_->bufferView().cursor().inMathed();
1174                 bool const table =
1175                         lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1176                 bool const review =
1177                         lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1178                         lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onoff(true);
1179                 bool const mathmacrotemplate =
1180                         lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1181
1182                 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1183                         it->second->update(math, table, review, mathmacrotemplate);
1184         } else
1185                 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1186                         it->second->update(false, false, false, false);
1187 }
1188
1189
1190 void GuiView::setBuffer(Buffer * newBuffer)
1191 {
1192         LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << endl);
1193         LASSERT(newBuffer, return);
1194         setBusy(true);
1195
1196         GuiWorkArea * wa = workArea(*newBuffer);
1197         if (wa == 0) {
1198                 newBuffer->masterBuffer()->updateBuffer();
1199                 wa = addWorkArea(*newBuffer);
1200         } else {
1201                 //Disconnect the old buffer...there's no new one.
1202                 disconnectBuffer();
1203         }
1204         connectBuffer(*newBuffer);
1205         connectBufferView(wa->bufferView());
1206         setCurrentWorkArea(wa);
1207
1208         setBusy(false);
1209 }
1210
1211
1212 void GuiView::connectBuffer(Buffer & buf)
1213 {
1214         buf.setGuiDelegate(this);
1215 }
1216
1217
1218 void GuiView::disconnectBuffer()
1219 {
1220         if (d.current_work_area_)
1221                 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1222 }
1223
1224
1225 void GuiView::connectBufferView(BufferView & bv)
1226 {
1227         bv.setGuiDelegate(this);
1228 }
1229
1230
1231 void GuiView::disconnectBufferView()
1232 {
1233         if (d.current_work_area_)
1234                 d.current_work_area_->bufferView().setGuiDelegate(0);
1235 }
1236
1237
1238 void GuiView::errors(string const & error_type, bool from_master)
1239 {
1240         ErrorList & el = from_master ?
1241                 currentBufferView()->buffer().masterBuffer()->errorList(error_type)
1242                 : currentBufferView()->buffer().errorList(error_type);
1243         string data = error_type;
1244         if (from_master)
1245                 data = "from_master|" + error_type;
1246         if (!el.empty())
1247                 showDialog("errorlist", data);
1248 }
1249
1250
1251 void GuiView::updateTocItem(string const & type, DocIterator const & dit)
1252 {
1253         d.toc_models_.updateItem(toqstr(type), dit);
1254 }
1255
1256
1257 void GuiView::structureChanged()
1258 {
1259         d.toc_models_.reset(documentBufferView());
1260         // Navigator needs more than a simple update in this case. It needs to be
1261         // rebuilt.
1262         updateDialog("toc", "");
1263 }
1264
1265
1266 void GuiView::updateDialog(string const & name, string const & data)
1267 {
1268         if (!isDialogVisible(name))
1269                 return;
1270
1271         map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1272         if (it == d.dialogs_.end())
1273                 return;
1274
1275         Dialog * const dialog = it->second.get();
1276         if (dialog->isVisibleView())
1277                 dialog->initialiseParams(data);
1278 }
1279
1280
1281 BufferView * GuiView::documentBufferView()
1282 {
1283         return currentMainWorkArea()
1284                 ? &currentMainWorkArea()->bufferView()
1285                 : 0;
1286 }
1287
1288
1289 BufferView const * GuiView::documentBufferView() const 
1290 {
1291         return currentMainWorkArea()
1292                 ? &currentMainWorkArea()->bufferView()
1293                 : 0;
1294 }
1295
1296
1297 BufferView * GuiView::currentBufferView()
1298 {
1299         return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1300 }
1301
1302
1303 BufferView const * GuiView::currentBufferView() const
1304 {
1305         return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1306 }
1307
1308
1309 #if (QT_VERSION >= 0x040400)
1310 static docstring saveAndDestroyBuffer(Buffer * buffer, FileName const & fname)
1311 {
1312         bool failed = true;
1313         FileName const tmp_ret = FileName::tempName("lyxauto");
1314         if (!tmp_ret.empty()) {
1315                 if (buffer->writeFile(tmp_ret))
1316                         failed = !tmp_ret.moveTo(fname);
1317         }
1318         if (failed) {
1319                 // failed to write/rename tmp_ret so try writing direct
1320                 failed = buffer->writeFile(fname);
1321         }
1322         delete buffer;
1323         return failed
1324                 ? _("Automatic save failed!")
1325                 : _("Automatic save done.");
1326 }
1327 #endif
1328
1329
1330 void GuiView::autoSave()
1331 {
1332         LYXERR(Debug::INFO, "Running autoSave()");
1333
1334         Buffer * buffer = documentBufferView()
1335                 ? &documentBufferView()->buffer() : 0;
1336         if (!buffer)
1337                 return;
1338
1339 #if (QT_VERSION >= 0x040400)
1340         QFuture<docstring> f = QtConcurrent::run(saveAndDestroyBuffer, buffer->clone(),
1341                 buffer->getAutosaveFilename());
1342         d.autosave_watcher_.setFuture(f);
1343 #else
1344         buffer->autoSave();
1345 #endif
1346 }
1347
1348
1349 void GuiView::resetAutosaveTimers()
1350 {
1351         if (lyxrc.autosave)
1352                 d.autosave_timeout_.restart();
1353 }
1354
1355
1356 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1357 {
1358         bool enable = true;
1359         Buffer * buf = currentBufferView()
1360                 ? &currentBufferView()->buffer() : 0;
1361         Buffer * doc_buffer = documentBufferView()
1362                 ? &(documentBufferView()->buffer()) : 0;
1363
1364         // Check whether we need a buffer
1365         if (!lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer) && !buf) {
1366                 // no, exit directly
1367                 flag.message(from_utf8(N_("Command not allowed with"
1368                                         "out any document open")));
1369                 flag.setEnabled(false);
1370                 return true;
1371         }
1372
1373         if (cmd.origin == FuncRequest::TOC) {
1374                 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1375                 FuncStatus fs;
1376                 if (toc->getStatus(documentBufferView()->cursor(), cmd, fs))
1377                         flag |= fs;
1378                 else
1379                         flag.setEnabled(false);
1380                 return true;
1381         }
1382
1383         switch(cmd.action) {
1384         case LFUN_BUFFER_IMPORT:
1385                 break;
1386
1387         case LFUN_MASTER_BUFFER_UPDATE:
1388         case LFUN_MASTER_BUFFER_VIEW: 
1389                 enable = doc_buffer && doc_buffer->parent() != 0
1390                         && !d.preview_watcher_.isRunning();
1391                 break;
1392
1393         case LFUN_BUFFER_UPDATE:
1394         case LFUN_BUFFER_VIEW: {
1395                 if (!doc_buffer || d.preview_watcher_.isRunning()) {
1396                         enable = false;
1397                         break;
1398                 }
1399                 string format = to_utf8(cmd.argument());
1400                 if (cmd.argument().empty())
1401                         format = doc_buffer->getDefaultOutputFormat();
1402                 enable = doc_buffer->isExportableFormat(format);
1403                 break;
1404         }
1405
1406         case LFUN_BUFFER_RELOAD:
1407                 enable = doc_buffer && !doc_buffer->isUnnamed()
1408                         && doc_buffer->fileName().exists()
1409                         && (!doc_buffer->isClean()
1410                            || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1411                 break;
1412
1413         case LFUN_BUFFER_CHILD_OPEN:
1414                 enable = doc_buffer;
1415                 break;
1416
1417         case LFUN_BUFFER_WRITE:
1418                 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1419                 break;
1420
1421         //FIXME: This LFUN should be moved to GuiApplication.
1422         case LFUN_BUFFER_WRITE_ALL: {
1423                 // We enable the command only if there are some modified buffers
1424                 Buffer * first = theBufferList().first();
1425                 enable = false;
1426                 if (!first)
1427                         break;
1428                 Buffer * b = first;
1429                 // We cannot use a for loop as the buffer list is a cycle.
1430                 do {
1431                         if (!b->isClean()) {
1432                                 enable = true;
1433                                 break;
1434                         }
1435                         b = theBufferList().next(b);
1436                 } while (b != first); 
1437                 break;
1438         }
1439
1440         case LFUN_BUFFER_WRITE_AS:
1441                 enable = doc_buffer;
1442                 break;
1443
1444         case LFUN_BUFFER_CLOSE:
1445                 enable = doc_buffer;
1446                 break;
1447
1448         case LFUN_BUFFER_CLOSE_ALL:
1449                 enable = theBufferList().last() != theBufferList().first();
1450                 break;
1451
1452         case LFUN_SPLIT_VIEW:
1453                 if (cmd.getArg(0) == "vertical")
1454                         enable = doc_buffer && (d.splitter_->count() == 1 ||
1455                                          d.splitter_->orientation() == Qt::Vertical);
1456                 else
1457                         enable = doc_buffer && (d.splitter_->count() == 1 ||
1458                                          d.splitter_->orientation() == Qt::Horizontal);
1459                 break;
1460
1461         case LFUN_CLOSE_TAB_GROUP:
1462                 enable = d.currentTabWorkArea();
1463                 break;
1464
1465         case LFUN_TOOLBAR_TOGGLE: {
1466                 string const name = cmd.getArg(0);
1467                 if (GuiToolbar * t = toolbar(name))
1468                         flag.setOnOff(t->isVisible());
1469                 else {
1470                         enable = false;
1471                         docstring const msg = 
1472                                 bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name));
1473                         flag.message(msg);
1474                 }
1475                 break;
1476         }
1477
1478         case LFUN_DROP_LAYOUTS_CHOICE:
1479                 enable = buf; 
1480                 break;
1481
1482         case LFUN_UI_TOGGLE:
1483                 flag.setOnOff(isFullScreen());
1484                 break;
1485
1486         case LFUN_DIALOG_DISCONNECT_INSET:
1487                 break;
1488
1489         case LFUN_DIALOG_HIDE:
1490                 // FIXME: should we check if the dialog is shown?
1491                 break;
1492
1493         case LFUN_DIALOG_TOGGLE:
1494                 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1495                 // fall through to set "enable"
1496         case LFUN_DIALOG_SHOW: {
1497                 string const name = cmd.getArg(0);
1498                 if (!doc_buffer)
1499                         enable = name == "aboutlyx"
1500                                 || name == "file" //FIXME: should be removed.
1501                                 || name == "prefs"
1502                                 || name == "texinfo"
1503                                 || name == "progress"
1504                                 || name == "compare";
1505                 else if (name == "print")
1506                         enable = doc_buffer->isExportable("dvi")
1507                                 && lyxrc.print_command != "none";
1508                 else if (name == "character" || name == "symbols") {
1509                         if (!buf || buf->isReadonly()
1510                                 || !currentBufferView()->cursor().inTexted())
1511                                 enable = false;
1512                         else {
1513                                 // FIXME we should consider passthru
1514                                 // paragraphs too.
1515                                 Inset const & in = currentBufferView()->cursor().inset();
1516                                 enable = !in.getLayout().isPassThru();
1517                         }
1518                 }
1519                 else if (name == "latexlog")
1520                         enable = FileName(doc_buffer->logName()).isReadableFile();
1521                 else if (name == "spellchecker")
1522                         enable = theSpellChecker() && !doc_buffer->isReadonly();
1523                 else if (name == "vclog")
1524                         enable = doc_buffer->lyxvc().inUse();
1525                 break;
1526         }
1527
1528         case LFUN_DIALOG_UPDATE: {
1529                 string const name = cmd.getArg(0);
1530                 if (!buf)
1531                         enable = name == "prefs";
1532                 break;
1533         }
1534
1535         case LFUN_COMMAND_EXECUTE:
1536         case LFUN_MESSAGE:
1537         case LFUN_MENU_OPEN:
1538                 // Nothing to check.
1539                 break;
1540
1541         case LFUN_COMPLETION_INLINE:
1542                 if (!d.current_work_area_
1543                         || !d.current_work_area_->completer().inlinePossible(
1544                         currentBufferView()->cursor()))
1545                         enable = false;
1546                 break;
1547
1548         case LFUN_COMPLETION_POPUP:
1549                 if (!d.current_work_area_
1550                         || !d.current_work_area_->completer().popupPossible(
1551                         currentBufferView()->cursor()))
1552                         enable = false;
1553                 break;
1554
1555         case LFUN_COMPLETION_COMPLETE:
1556                 if (!d.current_work_area_
1557                         || !d.current_work_area_->completer().inlinePossible(
1558                         currentBufferView()->cursor()))
1559                         enable = false;
1560                 break;
1561
1562         case LFUN_COMPLETION_ACCEPT:
1563                 if (!d.current_work_area_
1564                         || (!d.current_work_area_->completer().popupVisible()
1565                         && !d.current_work_area_->completer().inlineVisible()
1566                         && !d.current_work_area_->completer().completionAvailable()))
1567                         enable = false;
1568                 break;
1569
1570         case LFUN_COMPLETION_CANCEL:
1571                 if (!d.current_work_area_
1572                         || (!d.current_work_area_->completer().popupVisible()
1573                         && !d.current_work_area_->completer().inlineVisible()))
1574                         enable = false;
1575                 break;
1576
1577         case LFUN_BUFFER_ZOOM_OUT:
1578                 enable = doc_buffer && lyxrc.zoom > 10;
1579                 break;
1580
1581         case LFUN_BUFFER_ZOOM_IN:
1582                 enable = doc_buffer;
1583                 break;
1584         
1585         case LFUN_BUFFER_NEXT:
1586         case LFUN_BUFFER_PREVIOUS:
1587                 // FIXME: should we check is there is an previous or next buffer?
1588                 break;
1589         case LFUN_BUFFER_SWITCH:
1590                 // toggle on the current buffer, but do not toggle off
1591                 // the other ones (is that a good idea?)
1592                 if (doc_buffer
1593                         && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1594                         flag.setOnOff(true);
1595                 break;
1596
1597         case LFUN_VC_REGISTER:
1598                 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1599                 break;
1600         case LFUN_VC_CHECK_IN:
1601                 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1602                 break;
1603         case LFUN_VC_CHECK_OUT:
1604                 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1605                 break;
1606         case LFUN_VC_LOCKING_TOGGLE:
1607                 enable = doc_buffer && !doc_buffer->isReadonly()
1608                         && doc_buffer->lyxvc().lockingToggleEnabled();
1609                 flag.setOnOff(enable && doc_buffer->lyxvc().locking());
1610                 break;
1611         case LFUN_VC_REVERT:
1612                 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1613                 break;
1614         case LFUN_VC_UNDO_LAST:
1615                 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1616                 break;
1617         case LFUN_VC_REPO_UPDATE:
1618                 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1619                 break;
1620         case LFUN_VC_COMMAND: {
1621                 if (cmd.argument().empty())
1622                         enable = false;
1623                 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1624                         enable = false;
1625                 break;
1626         }
1627         case LFUN_VC_COMPARE:
1628                 enable = doc_buffer && !cmd.argument().empty()
1629                          && doc_buffer->lyxvc().prepareFileRevisionEnabled();
1630                 break;
1631
1632         case LFUN_SERVER_GOTO_FILE_ROW:
1633                 break;
1634
1635         default:
1636                 return false;
1637         }
1638
1639         if (!enable)
1640                 flag.setEnabled(false);
1641
1642         return true;
1643 }
1644
1645
1646 static FileName selectTemplateFile()
1647 {
1648         FileDialog dlg(qt_("Select template file"));
1649         dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1650         dlg.setButton1(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1651
1652         FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1653                                  QStringList(qt_("LyX Documents (*.lyx)")));
1654
1655         if (result.first == FileDialog::Later)
1656                 return FileName();
1657         if (result.second.isEmpty())
1658                 return FileName();
1659         return FileName(fromqstr(result.second));
1660 }
1661
1662
1663 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1664 {
1665         setBusy(true);
1666
1667         Buffer * newBuffer = checkAndLoadLyXFile(filename);
1668
1669         if (!newBuffer) {
1670                 message(_("Document not loaded."));
1671                 setBusy(false);
1672                 return 0;
1673         }
1674         
1675         setBuffer(newBuffer);
1676
1677         // scroll to the position when the file was last closed
1678         if (lyxrc.use_lastfilepos) {
1679                 LastFilePosSection::FilePos filepos =
1680                         theSession().lastFilePos().load(filename);
1681                 documentBufferView()->moveToPosition(filepos.pit, filepos.pos, 0, 0);
1682         }
1683
1684         if (tolastfiles)
1685                 theSession().lastFiles().add(filename);
1686
1687         setBusy(false);
1688         return newBuffer;
1689 }
1690
1691
1692 void GuiView::openDocument(string const & fname)
1693 {
1694         string initpath = lyxrc.document_path;
1695
1696         if (documentBufferView()) {
1697                 string const trypath = documentBufferView()->buffer().filePath();
1698                 // If directory is writeable, use this as default.
1699                 if (FileName(trypath).isDirWritable())
1700                         initpath = trypath;
1701         }
1702
1703         string filename;
1704
1705         if (fname.empty()) {
1706                 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1707                 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1708                 dlg.setButton2(qt_("Examples|#E#e"),
1709                                 toqstr(addPath(package().system_support().absFilename(), "examples")));
1710
1711                 QStringList filter(qt_("LyX Documents (*.lyx)"));
1712                 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1713                         << qt_("LyX-1.4.x Documents (*.lyx14)")
1714                         << qt_("LyX-1.5.x Documents (*.lyx15)")
1715                         << qt_("LyX-1.6.x Documents (*.lyx16)");
1716                 FileDialog::Result result =
1717                         dlg.open(toqstr(initpath), filter);
1718
1719                 if (result.first == FileDialog::Later)
1720                         return;
1721
1722                 filename = fromqstr(result.second);
1723
1724                 // check selected filename
1725                 if (filename.empty()) {
1726                         message(_("Canceled."));
1727                         return;
1728                 }
1729         } else
1730                 filename = fname;
1731
1732         // get absolute path of file and add ".lyx" to the filename if
1733         // necessary. 
1734         FileName const fullname = 
1735                         fileSearch(string(), filename, "lyx", support::may_not_exist);
1736         if (!fullname.empty())
1737                 filename = fullname.absFilename();
1738
1739         if (!fullname.onlyPath().isDirectory()) {
1740                 Alert::warning(_("Invalid filename"),
1741                                 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1742                                 from_utf8(fullname.absFilename())));
1743                 return;
1744         }
1745         // if the file doesn't exist, let the user create one
1746         if (!fullname.exists()) {
1747                 // the user specifically chose this name. Believe him.
1748                 Buffer * const b = newFile(filename, string(), true);
1749                 if (b)
1750                         setBuffer(b);
1751                 return;
1752         }
1753
1754         docstring const disp_fn = makeDisplayPath(filename);
1755         message(bformat(_("Opening document %1$s..."), disp_fn));
1756
1757         docstring str2;
1758         Buffer * buf = loadDocument(fullname);
1759         if (buf) {
1760                 buf->updateBuffer();
1761                 setBuffer(buf);
1762                 buf->errors("Parse");
1763                 str2 = bformat(_("Document %1$s opened."), disp_fn);
1764                 if (buf->lyxvc().inUse())
1765                         str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1766                                 " " + _("Version control detected.");
1767         } else {
1768                 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1769         }
1770         message(str2);
1771 }
1772
1773 // FIXME: clean that
1774 static bool import(GuiView * lv, FileName const & filename,
1775         string const & format, ErrorList & errorList)
1776 {
1777         FileName const lyxfile(support::changeExtension(filename.absFilename(), ".lyx"));
1778
1779         string loader_format;
1780         vector<string> loaders = theConverters().loaders();
1781         if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1782                 for (vector<string>::const_iterator it = loaders.begin();
1783                          it != loaders.end(); ++it) {
1784                         if (!theConverters().isReachable(format, *it))
1785                                 continue;
1786
1787                         string const tofile =
1788                                 support::changeExtension(filename.absFilename(),
1789                                 formats.extension(*it));
1790                         if (!theConverters().convert(0, filename, FileName(tofile),
1791                                 filename, format, *it, errorList))
1792                                 return false;
1793                         loader_format = *it;
1794                         break;
1795                 }
1796                 if (loader_format.empty()) {
1797                         frontend::Alert::error(_("Couldn't import file"),
1798                                          bformat(_("No information for importing the format %1$s."),
1799                                          formats.prettyName(format)));
1800                         return false;
1801                 }
1802         } else
1803                 loader_format = format;
1804
1805         if (loader_format == "lyx") {
1806                 Buffer * buf = lv->loadDocument(lyxfile);
1807                 if (!buf)
1808                         return false;
1809                 buf->updateBuffer();
1810                 lv->setBuffer(buf);
1811                 buf->errors("Parse");
1812         } else {
1813                 Buffer * const b = newFile(lyxfile.absFilename(), string(), true);
1814                 if (!b)
1815                         return false;
1816                 lv->setBuffer(b);
1817                 bool as_paragraphs = loader_format == "textparagraph";
1818                 string filename2 = (loader_format == format) ? filename.absFilename()
1819                         : support::changeExtension(filename.absFilename(),
1820                                           formats.extension(loader_format));
1821                 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
1822                         as_paragraphs);
1823                 guiApp->setCurrentView(lv);
1824                 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
1825         }
1826
1827         return true;
1828 }
1829
1830
1831 void GuiView::importDocument(string const & argument)
1832 {
1833         string format;
1834         string filename = split(argument, format, ' ');
1835
1836         LYXERR(Debug::INFO, format << " file: " << filename);
1837
1838         // need user interaction
1839         if (filename.empty()) {
1840                 string initpath = lyxrc.document_path;
1841                 if (documentBufferView()) {
1842                         string const trypath = documentBufferView()->buffer().filePath();
1843                         // If directory is writeable, use this as default.
1844                         if (FileName(trypath).isDirWritable())
1845                                 initpath = trypath;
1846                 }
1847
1848                 docstring const text = bformat(_("Select %1$s file to import"),
1849                         formats.prettyName(format));
1850
1851                 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
1852                 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1853                 dlg.setButton2(qt_("Examples|#E#e"),
1854                         toqstr(addPath(package().system_support().absFilename(), "examples")));
1855
1856                 docstring filter = formats.prettyName(format);
1857                 filter += " (*.";
1858                 // FIXME UNICODE
1859                 filter += from_utf8(formats.extension(format));
1860                 filter += ')';
1861
1862                 FileDialog::Result result =
1863                         dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
1864
1865                 if (result.first == FileDialog::Later)
1866                         return;
1867
1868                 filename = fromqstr(result.second);
1869
1870                 // check selected filename
1871                 if (filename.empty())
1872                         message(_("Canceled."));
1873         }
1874
1875         if (filename.empty())
1876                 return;
1877
1878         // get absolute path of file
1879         FileName const fullname(support::makeAbsPath(filename));
1880
1881         FileName const lyxfile(support::changeExtension(fullname.absFilename(), ".lyx"));
1882
1883         // Check if the document already is open
1884         Buffer * buf = theBufferList().getBuffer(lyxfile);
1885         if (buf) {
1886                 setBuffer(buf);
1887                 if (!closeBuffer()) {
1888                         message(_("Canceled."));
1889                         return;
1890                 }
1891         }
1892
1893         docstring const displaypath = makeDisplayPath(lyxfile.absFilename(), 30);
1894
1895         // if the file exists already, and we didn't do
1896         // -i lyx thefile.lyx, warn
1897         if (lyxfile.exists() && fullname != lyxfile) {
1898
1899                 docstring text = bformat(_("The document %1$s already exists.\n\n"
1900                         "Do you want to overwrite that document?"), displaypath);
1901                 int const ret = Alert::prompt(_("Overwrite document?"),
1902                         text, 0, 1, _("&Overwrite"), _("&Cancel"));
1903
1904                 if (ret == 1) {
1905                         message(_("Canceled."));
1906                         return;
1907                 }
1908         }
1909
1910         message(bformat(_("Importing %1$s..."), displaypath));
1911         ErrorList errorList;
1912         if (import(this, fullname, format, errorList))
1913                 message(_("imported."));
1914         else
1915                 message(_("file not imported!"));
1916
1917         // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
1918 }
1919
1920
1921 void GuiView::newDocument(string const & filename, bool from_template)
1922 {
1923         FileName initpath(lyxrc.document_path);
1924         if (documentBufferView()) {
1925                 FileName const trypath(documentBufferView()->buffer().filePath());
1926                 // If directory is writeable, use this as default.
1927                 if (trypath.isDirWritable())
1928                         initpath = trypath;
1929         }
1930
1931         string templatefile;
1932         if (from_template) {
1933                 templatefile = selectTemplateFile().absFilename();
1934                 if (templatefile.empty())
1935                         return;
1936         }
1937         
1938         Buffer * b;
1939         if (filename.empty())
1940                 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
1941         else
1942                 b = newFile(filename, templatefile, true);
1943
1944         if (b)
1945                 setBuffer(b);
1946
1947         // If no new document could be created, it is unsure 
1948         // whether there is a valid BufferView.
1949         if (currentBufferView())
1950                 // Ensure the cursor is correctly positioned on screen.
1951                 currentBufferView()->showCursor();
1952 }
1953
1954
1955 void GuiView::insertLyXFile(docstring const & fname)
1956 {
1957         BufferView * bv = documentBufferView();
1958         if (!bv)
1959                 return;
1960
1961         // FIXME UNICODE
1962         FileName filename(to_utf8(fname));
1963         
1964         if (!filename.empty()) {
1965                 bv->insertLyXFile(filename);
1966                 return;
1967         }
1968
1969         // Launch a file browser
1970         // FIXME UNICODE
1971         string initpath = lyxrc.document_path;
1972         string const trypath = bv->buffer().filePath();
1973         // If directory is writeable, use this as default.
1974         if (FileName(trypath).isDirWritable())
1975                 initpath = trypath;
1976
1977         // FIXME UNICODE
1978         FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
1979         dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1980         dlg.setButton2(qt_("Examples|#E#e"),
1981                 toqstr(addPath(package().system_support().absFilename(),
1982                 "examples")));
1983
1984         FileDialog::Result result = dlg.open(toqstr(initpath),
1985                                  QStringList(qt_("LyX Documents (*.lyx)")));
1986
1987         if (result.first == FileDialog::Later)
1988                 return;
1989
1990         // FIXME UNICODE
1991         filename.set(fromqstr(result.second));
1992
1993         // check selected filename
1994         if (filename.empty()) {
1995                 // emit message signal.
1996                 message(_("Canceled."));
1997                 return;
1998         }
1999
2000         bv->insertLyXFile(filename);
2001 }
2002
2003
2004 void GuiView::insertPlaintextFile(docstring const & fname,
2005         bool asParagraph)
2006 {
2007         BufferView * bv = documentBufferView();
2008         if (!bv)
2009                 return;
2010
2011         if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
2012                 message(_("Absolute filename expected."));
2013                 return;
2014         }
2015
2016         // FIXME UNICODE
2017         FileName filename(to_utf8(fname));
2018         
2019         if (!filename.empty()) {
2020                 bv->insertPlaintextFile(filename, asParagraph);
2021                 return;
2022         }
2023
2024         FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
2025                 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
2026
2027         FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
2028                 QStringList(qt_("All Files (*)")));
2029
2030         if (result.first == FileDialog::Later)
2031                 return;
2032
2033         // FIXME UNICODE
2034         filename.set(fromqstr(result.second));
2035
2036         // check selected filename
2037         if (filename.empty()) {
2038                 // emit message signal.
2039                 message(_("Canceled."));
2040                 return;
2041         }
2042
2043         bv->insertPlaintextFile(filename, asParagraph);
2044 }
2045
2046
2047 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
2048 {
2049         FileName fname = b.fileName();
2050         FileName const oldname = fname;
2051
2052         if (!newname.empty()) {
2053                 // FIXME UNICODE
2054                 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFilename());
2055         } else {
2056                 // Switch to this Buffer.
2057                 setBuffer(&b);
2058
2059                 // No argument? Ask user through dialog.
2060                 // FIXME UNICODE
2061                 FileDialog dlg(qt_("Choose a filename to save document as"),
2062                                    LFUN_BUFFER_WRITE_AS);
2063                 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2064                 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
2065
2066                 if (!isLyXFilename(fname.absFilename()))
2067                         fname.changeExtension(".lyx");
2068
2069                 FileDialog::Result result =
2070                         dlg.save(toqstr(fname.onlyPath().absFilename()),
2071                                    QStringList(qt_("LyX Documents (*.lyx)")),
2072                                          toqstr(fname.onlyFileName()));
2073
2074                 if (result.first == FileDialog::Later)
2075                         return false;
2076
2077                 fname.set(fromqstr(result.second));
2078
2079                 if (fname.empty())
2080                         return false;
2081
2082                 if (!isLyXFilename(fname.absFilename()))
2083                         fname.changeExtension(".lyx");
2084         }
2085
2086         // fname is now the new Buffer location.
2087         if (FileName(fname).exists()) {
2088                 docstring const file = makeDisplayPath(fname.absFilename(), 30);
2089                 docstring text = bformat(_("The document %1$s already "
2090                                            "exists.\n\nDo you want to "
2091                                            "overwrite that document?"), 
2092                                          file);
2093                 int const ret = Alert::prompt(_("Overwrite document?"),
2094                         text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2095                 switch (ret) {
2096                 case 0: break;
2097                 case 1: return renameBuffer(b, docstring());
2098                 case 2: return false;
2099                 }
2100         }
2101
2102         FileName oldauto = b.getAutosaveFilename();
2103
2104         // Ok, change the name of the buffer
2105         b.setFileName(fname.absFilename());
2106         b.markDirty();
2107         bool unnamed = b.isUnnamed();
2108         b.setUnnamed(false);
2109         b.saveCheckSum(fname);
2110
2111         // bring the autosave file with us, just in case.
2112         b.moveAutosaveFile(oldauto);
2113         
2114         if (!saveBuffer(b)) {
2115                 oldauto = b.getAutosaveFilename();
2116                 b.setFileName(oldname.absFilename());
2117                 b.setUnnamed(unnamed);
2118                 b.saveCheckSum(oldname);
2119                 b.moveAutosaveFile(oldauto);
2120                 return false;
2121         }
2122
2123         // the file has now been saved to the new location.
2124         // we need to check that the locations of child buffers
2125         // are still valid.
2126         b.checkChildBuffers();
2127
2128         return true;
2129 }
2130
2131
2132 bool GuiView::saveBuffer(Buffer & b)
2133 {
2134         if (workArea(b) && workArea(b)->inDialogMode())
2135                 return true;
2136
2137         if (b.isUnnamed())
2138                 return renameBuffer(b, docstring());
2139
2140         if (b.save()) {
2141                 theSession().lastFiles().add(b.fileName());
2142                 return true;
2143         }
2144
2145         // Switch to this Buffer.
2146         setBuffer(&b);
2147
2148         // FIXME: we don't tell the user *WHY* the save failed !!
2149         docstring const file = makeDisplayPath(b.absFileName(), 30);
2150         docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2151                                    "Do you want to rename the document and "
2152                                    "try again?"), file);
2153         int const ret = Alert::prompt(_("Rename and save?"),
2154                 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2155         switch (ret) {
2156         case 0:
2157                 if (!renameBuffer(b, docstring()))
2158                         return false;
2159                 break;
2160         case 1:
2161                 break;
2162         case 2:
2163                 return false;
2164         }
2165
2166         return saveBuffer(b);
2167 }
2168
2169
2170 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2171 {
2172         return closeWorkArea(wa, false);
2173 }
2174
2175
2176 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2177 {
2178         Buffer & buf = wa->bufferView().buffer();
2179         return closeWorkArea(wa, !buf.parent());
2180 }
2181
2182
2183 bool GuiView::closeBuffer()
2184 {
2185         GuiWorkArea * wa = currentMainWorkArea();
2186         setCurrentWorkArea(wa);
2187         Buffer & buf = wa->bufferView().buffer();
2188         return wa && closeWorkArea(wa, !buf.parent());
2189 }
2190
2191
2192 void GuiView::writeSession() const {
2193         GuiWorkArea const * active_wa = currentMainWorkArea();
2194         for (int i = 0; i < d.splitter_->count(); ++i) {
2195                 TabWorkArea * twa = d.tabWorkArea(i);
2196                 for (int j = 0; j < twa->count(); ++j) {
2197                         GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2198                         Buffer & buf = wa->bufferView().buffer();
2199                         theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2200                 }
2201         }
2202 }
2203
2204
2205 bool GuiView::closeBufferAll()
2206 {
2207         // Close the workareas in all other views
2208         QList<int> const ids = guiApp->viewIds();
2209         for (int i = 0; i != ids.size(); ++i) {
2210                 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2211                         return false;
2212         }
2213
2214         // Close our own workareas
2215         if (!closeWorkAreaAll())
2216                 return false;
2217
2218         // Now close the hidden buffers. We prevent hidden buffers from being
2219         // dirty, so we can just close them.
2220         theBufferList().closeAll();
2221         return true;
2222 }
2223
2224
2225 bool GuiView::closeWorkAreaAll()
2226 {
2227         setCurrentWorkArea(currentMainWorkArea());
2228
2229         // We might be in a situation that there is still a tabWorkArea, but
2230         // there are no tabs anymore. This can happen when we get here after a 
2231         // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2232         // many TabWorkArea's have no documents anymore.
2233         int empty_twa = 0;
2234
2235         // We have to call count() each time, because it can happen that
2236         // more than one splitter will disappear in one iteration (bug 5998).
2237         for (; d.splitter_->count() > empty_twa; ) {
2238                 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2239
2240                 if (twa->count() == 0)
2241                         ++empty_twa;
2242                 else {
2243                         setCurrentWorkArea(twa->currentWorkArea());
2244                         if (!closeTabWorkArea(twa))
2245                                 return false;
2246                 }
2247         }
2248         return true;
2249 }
2250
2251
2252 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2253 {
2254         if (!wa)
2255                 return false;
2256
2257         Buffer & buf = wa->bufferView().buffer();
2258
2259         if (close_buffer)
2260                 return closeBuffer(buf);
2261         else {
2262                 if (!inMultiTabs(wa))
2263                         if (!saveBufferIfNeeded(buf, true))
2264                                 return false;
2265                 removeWorkArea(wa);
2266                 return true;
2267         }
2268 }
2269
2270
2271 bool GuiView::closeBuffer(Buffer & buf)
2272 {
2273         // If we are in a close_event all children will be closed in some time,
2274         // so no need to do it here. This will ensure that the children end up
2275         // in the session file in the correct order. If we close the master
2276         // buffer, we can close or release the child buffers here too.
2277         if (!closing_) {
2278                 vector<Buffer *> clist = buf.getChildren(false);
2279                 for (vector<Buffer *>::const_iterator it = clist.begin();
2280                          it != clist.end(); ++it) {
2281                         // If a child is dirty, do not close
2282                         // without user intervention
2283                         //FIXME: should we look in other tabworkareas?
2284                         Buffer * child_buf = *it;
2285                         GuiWorkArea * child_wa = workArea(*child_buf);
2286                         if (child_wa) {
2287                                 if (!closeWorkArea(child_wa, true))
2288                                         return false;
2289                         } else
2290                                 theBufferList().releaseChild(&buf, child_buf);
2291                 }
2292         }
2293         // goto bookmark to update bookmark pit.
2294         //FIXME: we should update only the bookmarks related to this buffer!
2295         LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2296         for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2297                 guiApp->gotoBookmark(i+1, false, false);
2298
2299         if (saveBufferIfNeeded(buf, false)) {
2300                 theBufferList().release(&buf);
2301                 return true;
2302         }
2303         return false;
2304 }
2305
2306
2307 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2308 {
2309         while (twa == d.currentTabWorkArea()) {
2310                 twa->setCurrentIndex(twa->count()-1);
2311
2312                 GuiWorkArea * wa = twa->currentWorkArea();
2313                 Buffer & b = wa->bufferView().buffer();
2314
2315                 // We only want to close the buffer if the same buffer is not visible
2316                 // in another view, and if this is not a child and if we are closing
2317                 // a view (not a tabgroup).
2318                 bool const close_buffer = 
2319                         !inMultiViews(wa) && !b.parent() && closing_;
2320
2321                 if (!closeWorkArea(wa, close_buffer))
2322                         return false;
2323         }
2324         return true;
2325 }
2326
2327
2328 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2329 {
2330         if (buf.isClean() || buf.paragraphs().empty())
2331                 return true;
2332
2333         // Switch to this Buffer.
2334         setBuffer(&buf);
2335
2336         docstring file;
2337         // FIXME: Unicode?
2338         if (buf.isUnnamed())
2339                 file = from_utf8(buf.fileName().onlyFileName());
2340         else
2341                 file = buf.fileName().displayName(30);
2342
2343         // Bring this window to top before asking questions.
2344         raise();
2345         activateWindow();
2346
2347         int ret;
2348         if (hiding && buf.isUnnamed()) {
2349                 docstring const text = bformat(_("The document %1$s has not been "
2350                                                  "saved yet.\n\nDo you want to save "
2351                                                  "the document?"), file);
2352                 ret = Alert::prompt(_("Save new document?"), 
2353                         text, 0, 1, _("&Save"), _("&Cancel"));
2354                 if (ret == 1)
2355                         ++ret;
2356         } else {
2357                 docstring const text = bformat(_("The document %1$s has unsaved changes."
2358                         "\n\nDo you want to save the document or discard the changes?"), file);
2359                 ret = Alert::prompt(_("Save changed document?"),
2360                         text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2361         }
2362
2363         switch (ret) {
2364         case 0:
2365                 if (!saveBuffer(buf))
2366                         return false;
2367                 break;
2368         case 1:
2369                 // if we crash after this we could
2370                 // have no autosave file but I guess
2371                 // this is really improbable (Jug)
2372                 buf.removeAutosaveFile();
2373                 if (hiding)
2374                         // revert all changes
2375                         buf.reload();
2376                 buf.markClean();
2377                 break;
2378         case 2:
2379                 return false;
2380         }
2381         return true;
2382 }
2383
2384
2385 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2386 {
2387         Buffer & buf = wa->bufferView().buffer();
2388
2389         for (int i = 0; i != d.splitter_->count(); ++i) {
2390                 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2391                 if (wa_ && wa_ != wa)
2392                         return true;
2393         }
2394         return inMultiViews(wa);
2395 }
2396
2397
2398 bool GuiView::inMultiViews(GuiWorkArea * wa)
2399 {
2400         QList<int> const ids = guiApp->viewIds();
2401         Buffer & buf = wa->bufferView().buffer();
2402
2403         int found_twa = 0;
2404         for (int i = 0; i != ids.size() && found_twa <= 1; ++i) {
2405                 if (id_ == ids[i])
2406                         continue;
2407                 
2408                 if (guiApp->view(ids[i]).workArea(buf))
2409                         return true;
2410         }
2411         return false;
2412 }
2413
2414
2415 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2416 {
2417         Buffer * const curbuf = documentBufferView()
2418                 ? &documentBufferView()->buffer() : 0;
2419         Buffer * nextbuf = curbuf;
2420         while (true) {
2421                 if (np == NEXTBUFFER)
2422                         nextbuf = theBufferList().next(nextbuf);
2423                 else
2424                         nextbuf = theBufferList().previous(nextbuf);
2425                 if (nextbuf == curbuf)
2426                         break;
2427                 if (nextbuf == 0) {
2428                         nextbuf = curbuf;
2429                         break;
2430                 }
2431                 if (workArea(*nextbuf))
2432                         break;
2433         }
2434         setBuffer(nextbuf);
2435 }
2436
2437
2438 /// make sure the document is saved
2439 static bool ensureBufferClean(Buffer * buffer)
2440 {
2441         LASSERT(buffer, return false);
2442         if (buffer->isClean() && !buffer->isUnnamed())
2443                 return true;
2444
2445         docstring const file = buffer->fileName().displayName(30);
2446         docstring title;
2447         docstring text;
2448         if (!buffer->isUnnamed()) {
2449                 text = bformat(_("The document %1$s has unsaved "
2450                                                  "changes.\n\nDo you want to save "
2451                                                  "the document?"), file);
2452                 title = _("Save changed document?");
2453                 
2454         } else {
2455                 text = bformat(_("The document %1$s has not been "
2456                                                  "saved yet.\n\nDo you want to save "
2457                                                  "the document?"), file);
2458                 title = _("Save new document?");
2459         }
2460         int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2461
2462         if (ret == 0)
2463                 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2464
2465         return buffer->isClean() && !buffer->isUnnamed();
2466 }
2467
2468
2469 void GuiView::reloadBuffer()
2470 {
2471         Buffer * buf = &documentBufferView()->buffer();
2472         buf->reload();
2473 }
2474
2475
2476 void GuiView::checkExternallyModifiedBuffers()
2477 {
2478         BufferList::iterator bit = theBufferList().begin();
2479         BufferList::iterator const bend = theBufferList().end();
2480         for (; bit != bend; ++bit) {
2481                 if ((*bit)->fileName().exists()
2482                         && (*bit)->isExternallyModified(Buffer::checksum_method)) {
2483                         docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2484                                         " Reload now? Any local changes will be lost."),
2485                                         from_utf8((*bit)->absFileName()));
2486                         int const ret = Alert::prompt(_("Reload externally changed document?"),
2487                                                 text, 0, 1, _("&Reload"), _("&Cancel"));
2488                         if (!ret)
2489                                 (*bit)->reload();
2490                 }
2491         }
2492 }
2493
2494
2495 //FIXME use a DispatchResult object to transmit messages
2496 void GuiView::dispatchVC(FuncRequest const & cmd)
2497 {
2498         // message for statusbar
2499         string msg;
2500         Buffer * buffer = documentBufferView()
2501                 ? &(documentBufferView()->buffer()) : 0;
2502
2503         switch (cmd.action) {
2504         case LFUN_VC_REGISTER:
2505                 if (!buffer || !ensureBufferClean(buffer))
2506                         break;
2507                 if (!buffer->lyxvc().inUse()) {
2508                         if (buffer->lyxvc().registrer())
2509                                 reloadBuffer();
2510                 }
2511                 break;
2512
2513         case LFUN_VC_CHECK_IN:
2514                 if (!buffer || !ensureBufferClean(buffer))
2515                         break;
2516                 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2517                         msg = buffer->lyxvc().checkIn();
2518                         if (!msg.empty())
2519                                 reloadBuffer();
2520                 }
2521                 break;
2522
2523         case LFUN_VC_CHECK_OUT:
2524                 if (!buffer || !ensureBufferClean(buffer))
2525                         break;
2526                 if (buffer->lyxvc().inUse()) {
2527                         msg = buffer->lyxvc().checkOut();
2528                         reloadBuffer();
2529                 }
2530                 break;
2531
2532         case LFUN_VC_LOCKING_TOGGLE:
2533                 LASSERT(buffer, return);
2534                 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2535                         break;
2536                 if (buffer->lyxvc().inUse()) {
2537                         string res = buffer->lyxvc().lockingToggle();
2538                         if (res.empty()) {
2539                                 frontend::Alert::error(_("Revision control error."),
2540                                 _("Error when setting the locking property."));
2541                         } else {
2542                                 msg = res;
2543                                 reloadBuffer();
2544                         }
2545                 }
2546                 break;
2547
2548         case LFUN_VC_REVERT:
2549                 LASSERT(buffer, return);
2550                 buffer->lyxvc().revert();
2551                 reloadBuffer();
2552                 break;
2553
2554         case LFUN_VC_UNDO_LAST:
2555                 LASSERT(buffer, return);
2556                 buffer->lyxvc().undoLast();
2557                 reloadBuffer();
2558                 break;
2559
2560         case LFUN_VC_REPO_UPDATE:
2561                 LASSERT(buffer, return);
2562                 if (ensureBufferClean(buffer)) {
2563                         msg = buffer->lyxvc().repoUpdate();
2564                         checkExternallyModifiedBuffers();
2565                 }
2566                 break;
2567
2568         case LFUN_VC_COMMAND: {
2569                 string flag = cmd.getArg(0);
2570                 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2571                         break;
2572                 docstring message;
2573                 if (contains(flag, 'M')) {
2574                         if (!Alert::askForText(message, _("LyX VC: Log Message")))
2575                                 break;
2576                 }
2577                 string path = cmd.getArg(1);
2578                 if (contains(path, "$$p") && buffer)
2579                         path = subst(path, "$$p", buffer->filePath());
2580                 LYXERR(Debug::LYXVC, "Directory: " << path);
2581                 FileName pp(path);
2582                 if (!pp.isReadableDirectory()) {
2583                         lyxerr << _("Directory is not accessible.") << endl;
2584                         break;
2585                 }
2586                 support::PathChanger p(pp);
2587
2588                 string command = cmd.getArg(2);
2589                 if (command.empty())
2590                         break;
2591                 if (buffer) {
2592                         command = subst(command, "$$i", buffer->absFileName());
2593                         command = subst(command, "$$p", buffer->filePath());
2594                 }
2595                 command = subst(command, "$$m", to_utf8(message));
2596                 LYXERR(Debug::LYXVC, "Command: " << command);
2597                 Systemcall one;
2598                 one.startscript(Systemcall::Wait, command);
2599
2600                 if (!buffer)
2601                         break;
2602                 if (contains(flag, 'I'))
2603                         buffer->markDirty();
2604                 if (contains(flag, 'R'))
2605                         reloadBuffer();
2606
2607                 break;
2608                 }
2609
2610         case LFUN_VC_COMPARE: {
2611
2612                 string rev1 = cmd.getArg(0);
2613                 string f1, f2;
2614
2615                 // f1
2616                 if (!buffer->lyxvc().prepareFileRevision(rev1, f1))
2617                         break;
2618
2619                 if (isStrInt(rev1) && convert<int>(rev1) <= 0) {
2620                         f2 = buffer->absFileName();
2621                 } else {
2622                         string rev2 = cmd.getArg(1);
2623                         if (rev2.empty())
2624                                 break;
2625                         // f2
2626                         if (!buffer->lyxvc().prepareFileRevision(rev2, f2))
2627                                 break;
2628                 }
2629                 // FIXME We need to call comparison feature here.
2630                 // This is quick and dirty code for testing VC.
2631                 // We need that comparison feature has some LFUN_COMPARE <FLAG> file1 file1
2632                 // where <FLAG> specifies whether we want GUI dialog or just launch
2633                 // running with defaults.
2634                 /*
2635                 FileName initpath(lyxrc.document_path);
2636                 Buffer * dest = newUnnamedFile(initpath, to_utf8(_("differences")));
2637                 CompareOptions options;
2638                 Compare * compare = new Compare(loadIfNeeded(FileName(f1)), loadIfNeeded(FileName(f2)), dest, options);
2639                 compare->start(QThread::LowPriority);
2640                 Sleep::millisec(200);
2641                 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH, dest->absFileName()));
2642                 */
2643                 break;
2644         }
2645
2646         default:
2647                 break;
2648         }
2649
2650         if (!msg.empty())
2651                 message(from_utf8(msg));
2652 }
2653
2654
2655 void GuiView::openChildDocument(string const & fname)
2656 {
2657         LASSERT(documentBufferView(), return);
2658         Buffer & buffer = documentBufferView()->buffer();
2659         FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2660         documentBufferView()->saveBookmark(false);
2661         Buffer * child = 0;
2662         bool parsed = false;
2663         if (theBufferList().exists(filename)) {
2664                 child = theBufferList().getBuffer(filename);
2665         } else {
2666                 message(bformat(_("Opening child document %1$s..."),
2667                 makeDisplayPath(filename.absFilename())));
2668                 child = loadDocument(filename, false);
2669                 parsed = true;
2670         }
2671         if (!child)
2672                 return;
2673
2674         // Set the parent name of the child document.
2675         // This makes insertion of citations and references in the child work,
2676         // when the target is in the parent or another child document.
2677         child->setParent(&buffer);
2678         child->masterBuffer()->updateBuffer();
2679         setBuffer(child);
2680         if (parsed)
2681                 child->errors("Parse");
2682 }
2683
2684
2685 bool GuiView::goToFileRow(string const & argument)
2686 {
2687         string file_name;
2688         int row;
2689         size_t i = argument.find_last_of(' ');
2690         if (i != string::npos) {
2691                 file_name = os::internal_path(trim(argument.substr(0, i)));
2692                 istringstream is(argument.substr(i + 1));
2693                 is >> row;
2694                 if (is.fail())
2695                         i = string::npos;
2696         }
2697         if (i == string::npos) {
2698                 LYXERR0("Wrong argument: " << argument);
2699                 return false;
2700         }
2701         Buffer * buf = 0;
2702         string const abstmp = package().temp_dir().absFilename();
2703         string const realtmp = package().temp_dir().realPath();
2704         // We have to use os::path_prefix_is() here, instead of
2705         // simply prefixIs(), because the file name comes from
2706         // an external application and may need case adjustment.
2707         if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2708                 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2709                 // Needed by inverse dvi search. If it is a file
2710                 // in tmpdir, call the apropriated function.
2711                 // If tmpdir is a symlink, we may have the real
2712                 // path passed back, so we correct for that.
2713                 if (!prefixIs(file_name, abstmp))
2714                         file_name = subst(file_name, realtmp, abstmp);
2715                 buf = theBufferList().getBufferFromTmp(file_name);
2716         } else {
2717                 // Must replace extension of the file to be .lyx
2718                 // and get full path
2719                 FileName const s = fileSearch(string(),
2720                                                   support::changeExtension(file_name, ".lyx"), "lyx");
2721                 // Either change buffer or load the file
2722                 if (theBufferList().exists(s))
2723                         buf = theBufferList().getBuffer(s);
2724                 else if (s.exists()) {
2725                         buf = loadDocument(s);
2726                         buf->updateBuffer();
2727                         buf->errors("Parse");
2728                 } else {
2729                         message(bformat(
2730                                         _("File does not exist: %1$s"),
2731                                         makeDisplayPath(file_name)));
2732                         return false;
2733                 }
2734         }
2735         setBuffer(buf);
2736         documentBufferView()->setCursorFromRow(row);
2737         return true;
2738 }
2739
2740
2741 #if (QT_VERSION >= 0x040400)
2742 static docstring exportAndDestroy(Buffer * buffer, string const & format)
2743 {
2744         bool const update_unincluded =
2745                                 buffer->params().maintain_unincluded_children
2746                                 && !buffer->params().getIncludedChildren().empty();
2747         bool const success = buffer->doExport(format, true, update_unincluded);
2748         delete buffer;
2749         return success
2750                 ? bformat(_("Successful export to format: %1$s"), from_utf8(format))
2751                 : bformat(_("Error exporting to format: %1$s"), from_utf8(format));
2752 }
2753
2754
2755 static docstring previewAndDestroy(Buffer * buffer, string const & format)
2756 {
2757         bool const update_unincluded =
2758                                 buffer->params().maintain_unincluded_children
2759                                 && !buffer->params().getIncludedChildren().empty();
2760         bool const success = buffer->preview(format, update_unincluded);
2761         delete buffer;
2762         return success
2763                 ? bformat(_("Successful preview of format: %1$s"), from_utf8(format))
2764                 : bformat(_("Error previewing format: %1$s"), from_utf8(format));
2765 }
2766 #endif
2767
2768
2769 void GuiView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
2770 {
2771         BufferView * bv = currentBufferView();
2772         // By default we won't need any update.
2773         dr.update(Update::None);
2774         // assume cmd will be dispatched
2775         dr.dispatched(true);
2776
2777         Buffer * doc_buffer = documentBufferView()
2778                 ? &(documentBufferView()->buffer()) : 0;
2779
2780         if (cmd.origin == FuncRequest::TOC) {
2781                 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
2782                 // FIXME: do we need to pass a DispatchResult object here?
2783                 toc->doDispatch(bv->cursor(), cmd);
2784                 return;
2785         }
2786
2787         string const argument = to_utf8(cmd.argument());
2788
2789         switch(cmd.action) {
2790                 case LFUN_BUFFER_CHILD_OPEN:
2791                         openChildDocument(to_utf8(cmd.argument()));
2792                         break;
2793
2794                 case LFUN_BUFFER_IMPORT:
2795                         importDocument(to_utf8(cmd.argument()));
2796                         break;
2797
2798                 case LFUN_BUFFER_EXPORT: {
2799                         if (!doc_buffer)
2800                                 break;
2801                         // GCC only sees strfwd.h when building merged
2802                         if (::lyx::operator==(cmd.argument(), "custom")) {
2803                                 dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"), 
2804                                          dr);
2805                                 break;
2806                         }
2807                         if (!doc_buffer->doExport(argument, false)) {
2808                                 dr.setError(true);
2809                                 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2810                                         cmd.argument()));
2811                         }
2812                         break;
2813                 }
2814
2815                 case LFUN_BUFFER_UPDATE: {
2816                         if (!doc_buffer)
2817                                 break;
2818                         string format = argument;
2819                         if (argument.empty())
2820                                 format = doc_buffer->getDefaultOutputFormat();
2821 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2822                         d.progress_->clearMessages();
2823                         message(_("Exporting ..."));
2824                         QFuture<docstring> f = QtConcurrent::run(exportAndDestroy,
2825                                 doc_buffer->clone(), format);
2826                         d.setPreviewFuture(f);
2827 #else
2828                         bool const update_unincluded =
2829                                 doc_buffer->params().maintain_unincluded_children
2830                                 && !doc_buffer->params().getIncludedChildren().empty();
2831                         doc_buffer->doExport(format, true, update_unincluded);
2832 #endif
2833                         break;
2834                 }
2835                 case LFUN_BUFFER_VIEW: {
2836                         if (!doc_buffer)
2837                                 break;
2838                         string format = argument;
2839                         if (argument.empty())
2840                                 format = doc_buffer->getDefaultOutputFormat();
2841 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2842                         d.progress_->clearMessages();
2843                         message(_("Previewing ..."));
2844                         QFuture<docstring> f = QtConcurrent::run(previewAndDestroy,
2845                                 doc_buffer->clone(), format);
2846                         d.setPreviewFuture(f);
2847 #else
2848                         bool const update_unincluded =
2849                                 doc_buffer->params().maintain_unincluded_children
2850                                 && !doc_buffer->params().getIncludedChildren().empty();
2851                         doc_buffer->preview(format, update_unincluded);
2852 #endif
2853                         break;
2854                 }
2855                 case LFUN_MASTER_BUFFER_UPDATE: {
2856                         if (!doc_buffer)
2857                                 break;
2858                         string format = argument;
2859                         Buffer const * master = doc_buffer->masterBuffer();
2860                         if (argument.empty())
2861                                 format = master->getDefaultOutputFormat();
2862 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2863                         QFuture<docstring> f = QtConcurrent::run(exportAndDestroy,
2864                                 master->clone(), format);
2865                         d.setPreviewFuture(f);
2866 #else
2867                         bool const update_unincluded =
2868                                 master->params().maintain_unincluded_children
2869                                 && !master->params().getIncludedChildren().empty();
2870                         master->doExport(format, true);
2871 #endif
2872                         break;
2873                 }
2874                 case LFUN_MASTER_BUFFER_VIEW: {
2875                         string format = argument;
2876                         Buffer const * master = doc_buffer->masterBuffer();
2877                         if (argument.empty())
2878                                 format = master->getDefaultOutputFormat();
2879 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2880                         QFuture<docstring> f = QtConcurrent::run(previewAndDestroy,
2881                                 master->clone(), format);
2882                         d.setPreviewFuture(f);
2883 #else
2884                         master->preview(format);
2885 #endif
2886                         break;
2887                 }
2888                 case LFUN_BUFFER_SWITCH:
2889                         if (FileName::isAbsolute(to_utf8(cmd.argument()))) {
2890                                 Buffer * buffer = 
2891                                         theBufferList().getBuffer(FileName(to_utf8(cmd.argument())));
2892                                 if (buffer)
2893                                         setBuffer(buffer);
2894                                 else {
2895                                         dr.setError(true);
2896                                         dr.setMessage(_("Document not loaded"));
2897                                 }
2898                         }
2899                         break;
2900
2901                 case LFUN_BUFFER_NEXT:
2902                         gotoNextOrPreviousBuffer(NEXTBUFFER);
2903                         break;
2904
2905                 case LFUN_BUFFER_PREVIOUS:
2906                         gotoNextOrPreviousBuffer(PREVBUFFER);
2907                         break;
2908
2909                 case LFUN_COMMAND_EXECUTE: {
2910                         bool const show_it = cmd.argument() != "off";
2911                         // FIXME: this is a hack, "minibuffer" should not be
2912                         // hardcoded.
2913                         if (GuiToolbar * t = toolbar("minibuffer")) {
2914                                 t->setVisible(show_it);
2915                                 if (show_it && t->commandBuffer())
2916                                         t->commandBuffer()->setFocus();
2917                         }
2918                         break;
2919                 }
2920                 case LFUN_DROP_LAYOUTS_CHOICE:
2921                         d.layout_->showPopup();
2922                         break;
2923
2924                 case LFUN_MENU_OPEN:
2925                         if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
2926                                 menu->exec(QCursor::pos());
2927                         break;
2928
2929                 case LFUN_FILE_INSERT:
2930                         insertLyXFile(cmd.argument());
2931                         break;
2932                 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
2933                         insertPlaintextFile(cmd.argument(), true);
2934                         break;
2935
2936                 case LFUN_FILE_INSERT_PLAINTEXT:
2937                         insertPlaintextFile(cmd.argument(), false);
2938                         break;
2939
2940                 case LFUN_BUFFER_RELOAD: {
2941                         LASSERT(doc_buffer, break);
2942                         docstring const file = makeDisplayPath(doc_buffer->absFileName(), 20);
2943                         docstring text = bformat(_("Any changes will be lost. Are you sure "
2944                                                                  "you want to revert to the saved version of the document %1$s?"), file);
2945                         int const ret = Alert::prompt(_("Revert to saved document?"),
2946                                 text, 1, 1, _("&Revert"), _("&Cancel"));
2947
2948                         if (ret == 0) {
2949                                 doc_buffer->markClean();
2950                                 reloadBuffer();
2951                         }
2952                         break;
2953                 }
2954
2955                 case LFUN_BUFFER_WRITE:
2956                         LASSERT(doc_buffer, break);
2957                         saveBuffer(*doc_buffer);
2958                         break;
2959
2960                 case LFUN_BUFFER_WRITE_AS:
2961                         LASSERT(doc_buffer, break);
2962                         renameBuffer(*doc_buffer, cmd.argument());
2963                         break;
2964
2965                 case LFUN_BUFFER_WRITE_ALL: {
2966                         Buffer * first = theBufferList().first();
2967                         if (!first)
2968                                 break;
2969                         message(_("Saving all documents..."));
2970                         // We cannot use a for loop as the buffer list cycles.
2971                         Buffer * b = first;
2972                         do {
2973                                 if (!b->isClean()) {
2974                                         saveBuffer(*b);
2975                                         LYXERR(Debug::ACTION, "Saved " << b->absFileName());
2976                                 }
2977                                 b = theBufferList().next(b);
2978                         } while (b != first); 
2979                         dr.setMessage(_("All documents saved."));
2980                         break;
2981                 }
2982
2983                 case LFUN_BUFFER_CLOSE:
2984                         closeBuffer();
2985                         break;
2986
2987                 case LFUN_BUFFER_CLOSE_ALL:
2988                         closeBufferAll();
2989                         break;
2990
2991                 case LFUN_TOOLBAR_TOGGLE: {
2992                         string const name = cmd.getArg(0);
2993                         if (GuiToolbar * t = toolbar(name))
2994                                 t->toggle();
2995                         break;
2996                 }
2997
2998                 case LFUN_DIALOG_UPDATE: {
2999                         string const name = to_utf8(cmd.argument());
3000                         if (currentBufferView()) {
3001                                 Inset * inset = currentBufferView()->editedInset(name);
3002                                 // Can only update a dialog connected to an existing inset
3003                                 if (!inset)
3004                                         break;
3005                                 // FIXME: get rid of this indirection; GuiView ask the inset
3006                                 // if he is kind enough to update itself...
3007                                 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
3008                                 //FIXME: pass DispatchResult here?
3009                                 inset->dispatch(currentBufferView()->cursor(), fr);
3010                         } else if (name == "paragraph") {
3011                                 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
3012                         } else if (name == "prefs" || name == "document") {
3013                                 updateDialog(name, string());
3014                         }
3015                         break;
3016                 }
3017
3018                 case LFUN_DIALOG_TOGGLE: {
3019                         if (isDialogVisible(cmd.getArg(0)))
3020                                 dispatch(FuncRequest(LFUN_DIALOG_HIDE, cmd.argument()), dr);
3021                         else
3022                                 dispatch(FuncRequest(LFUN_DIALOG_SHOW, cmd.argument()), dr);
3023                         break;
3024                 }
3025
3026                 case LFUN_DIALOG_DISCONNECT_INSET:
3027                         disconnectDialog(to_utf8(cmd.argument()));
3028                         break;
3029
3030                 case LFUN_DIALOG_HIDE: {
3031                         guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
3032                         break;
3033                 }
3034
3035                 case LFUN_DIALOG_SHOW: {
3036                         string const name = cmd.getArg(0);
3037                         string data = trim(to_utf8(cmd.argument()).substr(name.size()));
3038
3039                         if (name == "character") {
3040                                 data = freefont2string();
3041                                 if (!data.empty())
3042                                         showDialog("character", data);
3043                         } else if (name == "latexlog") {
3044                                 Buffer::LogType type; 
3045                                 string const logfile = doc_buffer->logName(&type);
3046                                 switch (type) {
3047                                 case Buffer::latexlog:
3048                                         data = "latex ";
3049                                         break;
3050                                 case Buffer::buildlog:
3051                                         data = "literate ";
3052                                         break;
3053                                 }
3054                                 data += Lexer::quoteString(logfile);
3055                                 showDialog("log", data);
3056                         } else if (name == "vclog") {
3057                                 string const data = "vc " +
3058                                         Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
3059                                 showDialog("log", data);
3060                         } else if (name == "symbols") {
3061                                 data = bv->cursor().getEncoding()->name();
3062                                 if (!data.empty())
3063                                         showDialog("symbols", data);
3064                         // bug 5274
3065                         } else if (name == "prefs" && isFullScreen()) {
3066                                 lfunUiToggle("fullscreen");
3067                                 showDialog("prefs", data);
3068                         } else
3069                                 showDialog(name, data);
3070                         break;
3071                 }
3072
3073                 case LFUN_MESSAGE:
3074                         dr.setMessage(cmd.argument());
3075                         break;
3076
3077                 case LFUN_UI_TOGGLE: {
3078                         string arg = cmd.getArg(0);
3079                         if (!lfunUiToggle(arg)) {
3080                                 docstring const msg = "ui-toggle " + _("%1$s unknown command!");
3081                                 dr.setMessage(bformat(msg, from_utf8(arg)));
3082                         }
3083                         // Make sure the keyboard focus stays in the work area.
3084                         setFocus();
3085                         break;
3086                 }
3087
3088                 case LFUN_SPLIT_VIEW: {
3089                         LASSERT(doc_buffer, break);
3090                         string const orientation = cmd.getArg(0);
3091                         d.splitter_->setOrientation(orientation == "vertical"
3092                                 ? Qt::Vertical : Qt::Horizontal);
3093                         TabWorkArea * twa = addTabWorkArea();
3094                         GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
3095                         setCurrentWorkArea(wa);
3096                         break;
3097                 }
3098                 case LFUN_CLOSE_TAB_GROUP:
3099                         if (TabWorkArea * twa = d.currentTabWorkArea()) {
3100                                 closeTabWorkArea(twa);
3101                                 d.current_work_area_ = 0;
3102                                 twa = d.currentTabWorkArea();
3103                                 // Switch to the next GuiWorkArea in the found TabWorkArea.
3104                                 if (twa) {
3105                                         // Make sure the work area is up to date.
3106                                         setCurrentWorkArea(twa->currentWorkArea());
3107                                 } else {
3108                                         setCurrentWorkArea(0);
3109                                 }
3110                         }
3111                         break;
3112                         
3113                 case LFUN_COMPLETION_INLINE:
3114                         if (d.current_work_area_)
3115                                 d.current_work_area_->completer().showInline();
3116                         break;
3117
3118                 case LFUN_COMPLETION_POPUP:
3119                         if (d.current_work_area_)
3120                                 d.current_work_area_->completer().showPopup();
3121                         break;
3122
3123
3124                 case LFUN_COMPLETION_COMPLETE:
3125                         if (d.current_work_area_)
3126                                 d.current_work_area_->completer().tab();
3127                         break;
3128
3129                 case LFUN_COMPLETION_CANCEL:
3130                         if (d.current_work_area_) {
3131                                 if (d.current_work_area_->completer().popupVisible())
3132                                         d.current_work_area_->completer().hidePopup();
3133                                 else
3134                                         d.current_work_area_->completer().hideInline();
3135                         }
3136                         break;
3137
3138                 case LFUN_COMPLETION_ACCEPT:
3139                         if (d.current_work_area_)
3140                                 d.current_work_area_->completer().activate();
3141                         break;
3142
3143                 case LFUN_BUFFER_ZOOM_IN:
3144                 case LFUN_BUFFER_ZOOM_OUT:
3145                         if (cmd.argument().empty()) {
3146                                 if (cmd.action == LFUN_BUFFER_ZOOM_IN)
3147                                         lyxrc.zoom += 20;
3148                                 else
3149                                         lyxrc.zoom -= 20;
3150                         } else
3151                                 lyxrc.zoom += convert<int>(cmd.argument());
3152
3153                         if (lyxrc.zoom < 10)
3154                                 lyxrc.zoom = 10;
3155                                 
3156                         // The global QPixmapCache is used in GuiPainter to cache text
3157                         // painting so we must reset it.
3158                         QPixmapCache::clear();
3159                         guiApp->fontLoader().update();
3160                         lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3161                         break;
3162
3163                 case LFUN_VC_REGISTER:
3164                 case LFUN_VC_CHECK_IN:
3165                 case LFUN_VC_CHECK_OUT:
3166                 case LFUN_VC_REPO_UPDATE:
3167                 case LFUN_VC_LOCKING_TOGGLE:
3168                 case LFUN_VC_REVERT:
3169                 case LFUN_VC_UNDO_LAST:
3170                 case LFUN_VC_COMMAND:
3171                 case LFUN_VC_COMPARE:
3172                         dispatchVC(cmd);
3173                         break;
3174
3175                 case LFUN_SERVER_GOTO_FILE_ROW:
3176                         goToFileRow(to_utf8(cmd.argument()));
3177                         break;
3178
3179                 default:
3180                         dr.dispatched(false);
3181                         break;
3182         }
3183
3184         // Part of automatic menu appearance feature.
3185         if (isFullScreen()) {
3186                 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3187                         menuBar()->hide();
3188                 if (statusBar()->isVisible())
3189                         statusBar()->hide();
3190         }
3191
3192         return;
3193 }
3194
3195
3196 bool GuiView::lfunUiToggle(string const & ui_component)
3197 {
3198         if (ui_component == "scrollbar") {
3199                 // hide() is of no help
3200                 if (d.current_work_area_->verticalScrollBarPolicy() ==
3201                         Qt::ScrollBarAlwaysOff)
3202
3203                         d.current_work_area_->setVerticalScrollBarPolicy(
3204                                 Qt::ScrollBarAsNeeded);
3205                 else
3206                         d.current_work_area_->setVerticalScrollBarPolicy(
3207                                 Qt::ScrollBarAlwaysOff);
3208         } else if (ui_component == "statusbar") {
3209                 statusBar()->setVisible(!statusBar()->isVisible());
3210         } else if (ui_component == "menubar") {
3211                 menuBar()->setVisible(!menuBar()->isVisible());
3212         } else
3213 #if QT_VERSION >= 0x040300
3214         if (ui_component == "frame") {
3215                 int l, t, r, b;
3216                 getContentsMargins(&l, &t, &r, &b);
3217                 //are the frames in default state?
3218                 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3219                 if (l == 0) {
3220                         setContentsMargins(-2, -2, -2, -2);
3221                 } else {
3222                         setContentsMargins(0, 0, 0, 0);
3223                 }
3224         } else
3225 #endif
3226         if (ui_component == "fullscreen") {
3227                 toggleFullScreen();
3228         } else
3229                 return false;
3230         return true;
3231 }
3232
3233
3234 void GuiView::toggleFullScreen()
3235 {
3236         if (isFullScreen()) {
3237                 for (int i = 0; i != d.splitter_->count(); ++i)
3238                         d.tabWorkArea(i)->setFullScreen(false);
3239 #if QT_VERSION >= 0x040300
3240                 setContentsMargins(0, 0, 0, 0);
3241 #endif
3242                 setWindowState(windowState() ^ Qt::WindowFullScreen);
3243                 restoreLayout();
3244                 menuBar()->show();
3245                 statusBar()->show();
3246         } else {
3247                 // bug 5274
3248                 hideDialogs("prefs", 0);
3249                 for (int i = 0; i != d.splitter_->count(); ++i)
3250                         d.tabWorkArea(i)->setFullScreen(true);
3251 #if QT_VERSION >= 0x040300
3252                 setContentsMargins(-2, -2, -2, -2);
3253 #endif
3254                 saveLayout();
3255                 setWindowState(windowState() ^ Qt::WindowFullScreen);
3256                 statusBar()->hide();
3257                 if (lyxrc.full_screen_menubar)
3258                         menuBar()->hide();
3259                 if (lyxrc.full_screen_toolbars) {
3260                         ToolbarMap::iterator end = d.toolbars_.end();
3261                         for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3262                                 it->second->hide();
3263                 }
3264         }
3265
3266         // give dialogs like the TOC a chance to adapt
3267         updateDialogs();
3268 }
3269
3270
3271 Buffer const * GuiView::updateInset(Inset const * inset)
3272 {
3273         if (!d.current_work_area_)
3274                 return 0;
3275
3276         if (inset)
3277                 d.current_work_area_->scheduleRedraw();
3278
3279         return &d.current_work_area_->bufferView().buffer();
3280 }
3281
3282
3283 void GuiView::restartCursor()
3284 {
3285         /* When we move around, or type, it's nice to be able to see
3286          * the cursor immediately after the keypress.
3287          */
3288         if (d.current_work_area_)
3289                 d.current_work_area_->startBlinkingCursor();
3290
3291         // Take this occasion to update the other GUI elements.
3292         updateDialogs();
3293         updateStatusBar();
3294 }
3295
3296
3297 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3298 {
3299         if (d.current_work_area_)
3300                 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3301 }
3302
3303 namespace {
3304
3305 // This list should be kept in sync with the list of insets in
3306 // src/insets/Inset.cpp.  I.e., if a dialog goes with an inset, the
3307 // dialog should have the same name as the inset.
3308 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3309 // docs in LyXAction.cpp.
3310
3311 char const * const dialognames[] = {
3312 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3313 "citation", "compare", "document", "errorlist", "ert", "external", "file",
3314 "findreplace", "findreplaceadv", "float", "graphics", "href", "include",
3315 "index", "index_print", "info", "listings", "label", "log", "mathdelimiter",
3316 "mathmatrix", "mathspace", "nomenclature", "nomencl_print", "note",
3317 "paragraph", "phantom", "prefs", "print", "ref", "sendto", "space",
3318 "spellchecker", "symbols", "tabular", "tabularcreate", "thesaurus", "texinfo",
3319 "toc", "view-source", "vspace", "wrap", "progress"};
3320
3321 char const * const * const end_dialognames =
3322         dialognames + (sizeof(dialognames) / sizeof(char *));
3323
3324 class cmpCStr {
3325 public:
3326         cmpCStr(char const * name) : name_(name) {}
3327         bool operator()(char const * other) {
3328                 return strcmp(other, name_) == 0;
3329         }
3330 private:
3331         char const * name_;
3332 };
3333
3334
3335 bool isValidName(string const & name)
3336 {
3337         return find_if(dialognames, end_dialognames,
3338                                 cmpCStr(name.c_str())) != end_dialognames;
3339 }
3340
3341 } // namespace anon
3342
3343
3344 void GuiView::resetDialogs()
3345 {
3346         // Make sure that no LFUN uses any GuiView.
3347         guiApp->setCurrentView(0);
3348         saveLayout();
3349         menuBar()->clear();
3350         constructToolbars();
3351         guiApp->menus().fillMenuBar(menuBar(), this, false);
3352         d.layout_->updateContents(true);
3353         // Now update controls with current buffer.
3354         guiApp->setCurrentView(this);
3355         restoreLayout();
3356         restartCursor();
3357 }
3358
3359
3360 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3361 {
3362         if (!isValidName(name))
3363                 return 0;
3364
3365         map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3366
3367         if (it != d.dialogs_.end()) {
3368                 if (hide_it)
3369                         it->second->hideView();
3370                 return it->second.get();
3371         }
3372
3373         Dialog * dialog = build(name);
3374         d.dialogs_[name].reset(dialog);
3375         if (lyxrc.allow_geometry_session)
3376                 dialog->restoreSession();
3377         if (hide_it)
3378                 dialog->hideView();
3379         return dialog;
3380 }
3381
3382
3383 void GuiView::showDialog(string const & name, string const & data,
3384         Inset * inset)
3385 {
3386         triggerShowDialog(toqstr(name), toqstr(data), inset);
3387 }
3388
3389
3390 void GuiView::doShowDialog(QString const & qname, QString const & qdata,
3391         Inset * inset)
3392 {
3393         if (d.in_show_)
3394                 return;
3395
3396         const string name = fromqstr(qname);
3397         const string data = fromqstr(qdata);
3398
3399         d.in_show_ = true;
3400         try {
3401                 Dialog * dialog = findOrBuild(name, false);
3402                 if (dialog) {
3403                         dialog->showData(data);
3404                         if (inset && currentBufferView())
3405                                 currentBufferView()->editInset(name, inset);
3406                 }
3407         }
3408         catch (ExceptionMessage const & ex) {
3409                 d.in_show_ = false;
3410                 throw ex;
3411         }
3412         d.in_show_ = false;
3413 }
3414
3415
3416 bool GuiView::isDialogVisible(string const & name) const
3417 {
3418         map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3419         if (it == d.dialogs_.end())
3420                 return false;
3421         return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3422 }
3423
3424
3425 void GuiView::hideDialog(string const & name, Inset * inset)
3426 {
3427         map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3428         if (it == d.dialogs_.end())
3429                 return;
3430
3431         if (inset && currentBufferView()
3432                 && inset != currentBufferView()->editedInset(name))
3433                 return;
3434
3435         Dialog * const dialog = it->second.get();
3436         if (dialog->isVisibleView())
3437                 dialog->hideView();
3438         if (currentBufferView())
3439                 currentBufferView()->editInset(name, 0);
3440 }
3441
3442
3443 void GuiView::disconnectDialog(string const & name)
3444 {
3445         if (!isValidName(name))
3446                 return;
3447         if (currentBufferView())
3448                 currentBufferView()->editInset(name, 0);
3449 }
3450
3451
3452 void GuiView::hideAll() const
3453 {
3454         map<string, DialogPtr>::const_iterator it  = d.dialogs_.begin();
3455         map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3456
3457         for(; it != end; ++it)
3458                 it->second->hideView();
3459 }
3460
3461
3462 void GuiView::updateDialogs()
3463 {
3464         map<string, DialogPtr>::const_iterator it  = d.dialogs_.begin();
3465         map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3466
3467         for(; it != end; ++it) {
3468                 Dialog * dialog = it->second.get();
3469                 if (dialog) {
3470                         if (dialog->isBufferDependent() && !documentBufferView())
3471                                 hideDialog(fromqstr(dialog->name()), 0);
3472                         else if (dialog->isVisibleView())
3473                                 dialog->checkStatus();
3474                 }
3475         }
3476         updateToolbars();
3477         updateLayoutList();
3478 }
3479
3480 Dialog * createDialog(GuiView & lv, string const & name);
3481
3482 // will be replaced by a proper factory...
3483 Dialog * createGuiAbout(GuiView & lv);
3484 Dialog * createGuiBibtex(GuiView & lv);
3485 Dialog * createGuiChanges(GuiView & lv);
3486 Dialog * createGuiCharacter(GuiView & lv);
3487 Dialog * createGuiCitation(GuiView & lv);
3488 Dialog * createGuiCompare(GuiView & lv);
3489 Dialog * createGuiDelimiter(GuiView & lv);
3490 Dialog * createGuiDocument(GuiView & lv);
3491 Dialog * createGuiErrorList(GuiView & lv);
3492 Dialog * createGuiExternal(GuiView & lv);
3493 Dialog * createGuiGraphics(GuiView & lv);
3494 Dialog * createGuiInclude(GuiView & lv);
3495 Dialog * createGuiIndex(GuiView & lv);
3496 Dialog * createGuiLabel(GuiView & lv);
3497 Dialog * createGuiListings(GuiView & lv);
3498 Dialog * createGuiLog(GuiView & lv);
3499 Dialog * createGuiMathMatrix(GuiView & lv);
3500 Dialog * createGuiNomenclature(GuiView & lv);
3501 Dialog * createGuiNote(GuiView & lv);
3502 Dialog * createGuiParagraph(GuiView & lv);
3503 Dialog * createGuiPhantom(GuiView & lv);
3504 Dialog * createGuiPreferences(GuiView & lv);
3505 Dialog * createGuiPrint(GuiView & lv);
3506 Dialog * createGuiPrintindex(GuiView & lv);
3507 Dialog * createGuiPrintNomencl(GuiView & lv);
3508 Dialog * createGuiRef(GuiView & lv);
3509 Dialog * createGuiSearch(GuiView & lv);
3510 Dialog * createGuiSearchAdv(GuiView & lv);
3511 Dialog * createGuiSendTo(GuiView & lv);
3512 Dialog * createGuiShowFile(GuiView & lv);
3513 Dialog * createGuiSpellchecker(GuiView & lv);
3514 Dialog * createGuiSymbols(GuiView & lv);
3515 Dialog * createGuiTabularCreate(GuiView & lv);
3516 Dialog * createGuiTexInfo(GuiView & lv);
3517 Dialog * createGuiToc(GuiView & lv);
3518 Dialog * createGuiThesaurus(GuiView & lv);
3519 Dialog * createGuiHyperlink(GuiView & lv);
3520 Dialog * createGuiViewSource(GuiView & lv);
3521 Dialog * createGuiWrap(GuiView & lv);
3522 Dialog * createGuiProgressView(GuiView & lv);
3523
3524
3525
3526 Dialog * GuiView::build(string const & name)
3527 {
3528         LASSERT(isValidName(name), return 0);
3529
3530         Dialog * dialog = createDialog(*this, name);
3531         if (dialog)
3532                 return dialog;
3533
3534         if (name == "aboutlyx")
3535                 return createGuiAbout(*this);
3536         if (name == "bibtex")
3537                 return createGuiBibtex(*this);
3538         if (name == "changes")
3539                 return createGuiChanges(*this);
3540         if (name == "character")
3541                 return createGuiCharacter(*this);
3542         if (name == "citation")
3543                 return createGuiCitation(*this);
3544         if (name == "compare")
3545                 return createGuiCompare(*this);
3546         if (name == "document")
3547                 return createGuiDocument(*this);
3548         if (name == "errorlist")
3549                 return createGuiErrorList(*this);
3550         if (name == "external")
3551                 return createGuiExternal(*this);
3552         if (name == "file")
3553                 return createGuiShowFile(*this);
3554         if (name == "findreplace")
3555                 return createGuiSearch(*this);
3556         if (name == "findreplaceadv")
3557                 return createGuiSearchAdv(*this);
3558         if (name == "graphics")
3559                 return createGuiGraphics(*this);
3560         if (name == "href")
3561                 return createGuiHyperlink(*this);
3562         if (name == "include")
3563                 return createGuiInclude(*this);
3564         if (name == "index")
3565                 return createGuiIndex(*this);
3566         if (name == "index_print")
3567                 return createGuiPrintindex(*this);
3568         if (name == "label")
3569                 return createGuiLabel(*this);
3570         if (name == "listings")
3571                 return createGuiListings(*this);
3572         if (name == "log")
3573                 return createGuiLog(*this);
3574         if (name == "mathdelimiter")
3575                 return createGuiDelimiter(*this);
3576         if (name == "mathmatrix")
3577                 return createGuiMathMatrix(*this);
3578         if (name == "nomenclature")
3579                 return createGuiNomenclature(*this);
3580         if (name == "nomencl_print")
3581                 return createGuiPrintNomencl(*this);
3582         if (name == "note")
3583                 return createGuiNote(*this);
3584         if (name == "paragraph")
3585                 return createGuiParagraph(*this);
3586         if (name == "phantom")
3587                 return createGuiPhantom(*this);
3588         if (name == "prefs")
3589                 return createGuiPreferences(*this);
3590         if (name == "print")
3591                 return createGuiPrint(*this);
3592         if (name == "ref")
3593                 return createGuiRef(*this);
3594         if (name == "sendto")
3595                 return createGuiSendTo(*this);
3596         if (name == "spellchecker")
3597                 return createGuiSpellchecker(*this);
3598         if (name == "symbols")
3599                 return createGuiSymbols(*this);
3600         if (name == "tabularcreate")
3601                 return createGuiTabularCreate(*this);
3602         if (name == "texinfo")
3603                 return createGuiTexInfo(*this);
3604         if (name == "thesaurus")
3605                 return createGuiThesaurus(*this);
3606         if (name == "toc")
3607                 return createGuiToc(*this);
3608         if (name == "view-source")
3609                 return createGuiViewSource(*this);
3610         if (name == "wrap")
3611                 return createGuiWrap(*this);
3612         if (name == "progress")
3613                 return createGuiProgressView(*this);
3614
3615         return 0;
3616 }
3617
3618
3619 } // namespace frontend
3620 } // namespace lyx
3621
3622 #include "moc_GuiView.cpp"