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