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