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