]> git.lyx.org Git - features.git/blob - src/frontends/qt4/GuiView.cpp
Fix bug #6550: "Any Changes will be lost" even when there are no changes.
[features.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)
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_;
1115 }
1116
1117
1118 void GuiView::setBusy(bool busy)
1119 {
1120         busy_ = busy;
1121         if (d.current_work_area_) {
1122                 d.current_work_area_->setUpdatesEnabled(!busy);
1123                 if (busy)
1124                         d.current_work_area_->stopBlinkingCursor();
1125                 else
1126                         d.current_work_area_->startBlinkingCursor();
1127         }
1128
1129         if (busy)
1130                 QApplication::setOverrideCursor(Qt::WaitCursor);
1131         else
1132                 QApplication::restoreOverrideCursor();
1133 }
1134
1135
1136 GuiWorkArea * GuiView::workArea(Buffer & buffer)
1137 {
1138         if (currentWorkArea()
1139                 && &currentWorkArea()->bufferView().buffer() == &buffer)
1140                 return (GuiWorkArea *) currentWorkArea();
1141         if (TabWorkArea * twa = d.currentTabWorkArea())
1142                 return twa->workArea(buffer);
1143         return 0;
1144 }
1145
1146
1147 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
1148 {
1149         // Automatically create a TabWorkArea if there are none yet.
1150         TabWorkArea * tab_widget = d.splitter_->count()
1151                 ? d.currentTabWorkArea() : addTabWorkArea();
1152         return tab_widget->addWorkArea(buffer, *this);
1153 }
1154
1155
1156 TabWorkArea * GuiView::addTabWorkArea()
1157 {
1158         TabWorkArea * twa = new TabWorkArea;
1159         QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
1160                 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
1161         QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
1162                          this, SLOT(on_lastWorkAreaRemoved()));
1163
1164         d.splitter_->addWidget(twa);
1165         d.stack_widget_->setCurrentWidget(d.splitter_);
1166         return twa;
1167 }
1168
1169
1170 GuiWorkArea const * GuiView::currentWorkArea() const
1171 {
1172         return d.current_work_area_;
1173 }
1174
1175
1176 GuiWorkArea * GuiView::currentWorkArea()
1177 {
1178         return d.current_work_area_;
1179 }
1180
1181
1182 GuiWorkArea const * GuiView::currentMainWorkArea() const
1183 {
1184         if (!d.currentTabWorkArea())
1185                 return 0;
1186         return d.currentTabWorkArea()->currentWorkArea();
1187 }
1188
1189
1190 GuiWorkArea * GuiView::currentMainWorkArea()
1191 {
1192         if (!d.currentTabWorkArea())
1193                 return 0;
1194         return d.currentTabWorkArea()->currentWorkArea();
1195 }
1196
1197
1198 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
1199 {
1200         LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
1201         if (!wa) {
1202                 d.current_work_area_ = 0;
1203                 d.setBackground();
1204                 return;
1205         }
1206
1207         // FIXME: I've no clue why this is here and why it accesses
1208         //  theGuiApp()->currentView, which might be 0 (bug 6464).
1209         //  See also 27525 (vfr).
1210         if (theGuiApp()->currentView() == this
1211                   && theGuiApp()->currentView()->currentWorkArea() == wa)
1212                 return;
1213
1214         if (currentBufferView())
1215                 cap::saveSelection(currentBufferView()->cursor());
1216
1217         theGuiApp()->setCurrentView(this);
1218         d.current_work_area_ = wa;
1219         for (int i = 0; i != d.splitter_->count(); ++i) {
1220                 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1221                         //if (d.current_main_work_area_)
1222                         //      d.current_main_work_area_->setFrameStyle(QFrame::NoFrame);
1223                         d.current_main_work_area_ = wa;
1224                         //d.current_main_work_area_->setFrameStyle(QFrame::Box | QFrame::Plain);
1225                         //d.current_main_work_area_->setLineWidth(2);
1226                         LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1227                         return;
1228                 }
1229         }
1230         LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1231         on_currentWorkAreaChanged(wa);
1232         BufferView & bv = wa->bufferView();
1233         bv.cursor().fixIfBroken();
1234         bv.updateMetrics();
1235         wa->setUpdatesEnabled(true);
1236         LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1237 }
1238
1239
1240 void GuiView::removeWorkArea(GuiWorkArea * wa)
1241 {
1242         LASSERT(wa, return);
1243         if (wa == d.current_work_area_) {
1244                 disconnectBuffer();
1245                 disconnectBufferView();
1246                 d.current_work_area_ = 0;
1247                 d.current_main_work_area_ = 0;
1248         }
1249
1250         bool found_twa = false;
1251         for (int i = 0; i != d.splitter_->count(); ++i) {
1252                 TabWorkArea * twa = d.tabWorkArea(i);
1253                 if (twa->removeWorkArea(wa)) {
1254                         // Found in this tab group, and deleted the GuiWorkArea.
1255                         found_twa = true;
1256                         if (twa->count() != 0) {
1257                                 if (d.current_work_area_ == 0)
1258                                         // This means that we are closing the current GuiWorkArea, so
1259                                         // switch to the next GuiWorkArea in the found TabWorkArea.
1260                                         setCurrentWorkArea(twa->currentWorkArea());
1261                         } else {
1262                                 // No more WorkAreas in this tab group, so delete it.
1263                                 delete twa;
1264                         }
1265                         break;
1266                 }
1267         }
1268
1269         // It is not a tabbed work area (i.e., the search work area), so it
1270         // should be deleted by other means.
1271         LASSERT(found_twa, /* */);
1272
1273         if (d.current_work_area_ == 0) {
1274                 if (d.splitter_->count() != 0) {
1275                         TabWorkArea * twa = d.currentTabWorkArea();
1276                         setCurrentWorkArea(twa->currentWorkArea());
1277                 } else {
1278                         // No more work areas, switch to the background widget.
1279                         setCurrentWorkArea(0);
1280                 }
1281         }
1282 }
1283
1284
1285 LayoutBox * GuiView::getLayoutDialog() const
1286 {
1287         return d.layout_;
1288 }
1289
1290
1291 void GuiView::updateLayoutList()
1292 {
1293         if (d.layout_)
1294                 d.layout_->updateContents(false);
1295 }
1296
1297
1298 void GuiView::updateToolbars()
1299 {
1300         ToolbarMap::iterator end = d.toolbars_.end();
1301         if (d.current_work_area_) {
1302                 bool const math =
1303                         d.current_work_area_->bufferView().cursor().inMathed()
1304                         && !d.current_work_area_->bufferView().cursor().inRegexped();
1305                 bool const table =
1306                         lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1307                 bool const review =
1308                         lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1309                         lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onOff(true);
1310                 bool const mathmacrotemplate =
1311                         lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1312
1313                 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1314                         it->second->update(math, table, review, mathmacrotemplate);
1315         } else
1316                 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1317                         it->second->update(false, false, false, false);
1318 }
1319
1320
1321 void GuiView::setBuffer(Buffer * newBuffer)
1322 {
1323         LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << endl);
1324         LASSERT(newBuffer, return);
1325         setBusy(true);
1326
1327         GuiWorkArea * wa = workArea(*newBuffer);
1328         if (wa == 0) {
1329                 newBuffer->masterBuffer()->updateBuffer();
1330                 wa = addWorkArea(*newBuffer);
1331                 // scroll to the position when the file was last closed
1332                 if (lyxrc.use_lastfilepos) {
1333                         LastFilePosSection::FilePos filepos =
1334                                 theSession().lastFilePos().load(newBuffer->fileName());
1335                         wa->bufferView().moveToPosition(filepos.pit, filepos.pos, 0, 0);
1336                 }
1337         } else {
1338                 //Disconnect the old buffer...there's no new one.
1339                 disconnectBuffer();
1340         }
1341         connectBuffer(*newBuffer);
1342         connectBufferView(wa->bufferView());
1343         setCurrentWorkArea(wa);
1344
1345         setBusy(false);
1346 }
1347
1348
1349 void GuiView::connectBuffer(Buffer & buf)
1350 {
1351         buf.setGuiDelegate(this);
1352 }
1353
1354
1355 void GuiView::disconnectBuffer()
1356 {
1357         if (d.current_work_area_)
1358                 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1359 }
1360
1361
1362 void GuiView::connectBufferView(BufferView & bv)
1363 {
1364         bv.setGuiDelegate(this);
1365 }
1366
1367
1368 void GuiView::disconnectBufferView()
1369 {
1370         if (d.current_work_area_)
1371                 d.current_work_area_->bufferView().setGuiDelegate(0);
1372 }
1373
1374
1375 void GuiView::errors(string const & error_type, bool from_master)
1376 {
1377         ErrorList & el = from_master ?
1378                 currentBufferView()->buffer().masterBuffer()->errorList(error_type)
1379                 : currentBufferView()->buffer().errorList(error_type);
1380         string data = error_type;
1381         if (from_master)
1382                 data = "from_master|" + error_type;
1383         if (!el.empty())
1384                 showDialog("errorlist", data);
1385 }
1386
1387
1388 void GuiView::updateTocItem(string const & type, DocIterator const & dit)
1389 {
1390         d.toc_models_.updateItem(toqstr(type), dit);
1391 }
1392
1393
1394 void GuiView::structureChanged()
1395 {
1396         d.toc_models_.reset(documentBufferView());
1397         // Navigator needs more than a simple update in this case. It needs to be
1398         // rebuilt.
1399         updateDialog("toc", "");
1400 }
1401
1402
1403 void GuiView::updateDialog(string const & name, string const & data)
1404 {
1405         if (!isDialogVisible(name))
1406                 return;
1407
1408         map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1409         if (it == d.dialogs_.end())
1410                 return;
1411
1412         Dialog * const dialog = it->second.get();
1413         if (dialog->isVisibleView())
1414                 dialog->initialiseParams(data);
1415 }
1416
1417
1418 BufferView * GuiView::documentBufferView()
1419 {
1420         return currentMainWorkArea()
1421                 ? &currentMainWorkArea()->bufferView()
1422                 : 0;
1423 }
1424
1425
1426 BufferView const * GuiView::documentBufferView() const
1427 {
1428         return currentMainWorkArea()
1429                 ? &currentMainWorkArea()->bufferView()
1430                 : 0;
1431 }
1432
1433
1434 BufferView * GuiView::currentBufferView()
1435 {
1436         return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1437 }
1438
1439
1440 BufferView const * GuiView::currentBufferView() const
1441 {
1442         return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1443 }
1444
1445
1446 #if (QT_VERSION >= 0x040400)
1447 docstring GuiView::GuiViewPrivate::saveAndDestroy(Buffer const * orig, Buffer * buffer, FileName const & fname)
1448 {
1449         bool failed = true;
1450         FileName const tmp_ret = FileName::tempName("lyxauto");
1451         if (!tmp_ret.empty()) {
1452                 if (buffer->writeFile(tmp_ret))
1453                         failed = !tmp_ret.moveTo(fname);
1454         }
1455         if (failed) {
1456                 // failed to write/rename tmp_ret so try writing direct
1457                 failed = buffer->writeFile(fname);
1458         }
1459         delete buffer;
1460         busyBuffers.remove(orig);
1461         return failed
1462                 ? _("Automatic save failed!")
1463                 : _("Automatic save done.");
1464 }
1465 #endif
1466
1467
1468 void GuiView::autoSave()
1469 {
1470         LYXERR(Debug::INFO, "Running autoSave()");
1471
1472         Buffer * buffer = documentBufferView()
1473                 ? &documentBufferView()->buffer() : 0;
1474         if (!buffer)
1475                 return;
1476
1477 #if (QT_VERSION >= 0x040400)
1478         GuiViewPrivate::busyBuffers.insert(buffer);
1479         QFuture<docstring> f = QtConcurrent::run(GuiViewPrivate::saveAndDestroy, buffer, buffer->clone(),
1480                 buffer->getAutosaveFileName());
1481         d.autosave_watcher_.setFuture(f);
1482 #else
1483         buffer->autoSave();
1484 #endif
1485 }
1486
1487
1488 void GuiView::resetAutosaveTimers()
1489 {
1490         if (lyxrc.autosave)
1491                 d.autosave_timeout_.restart();
1492 }
1493
1494
1495 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1496 {
1497         bool enable = true;
1498         Buffer * buf = currentBufferView()
1499                 ? &currentBufferView()->buffer() : 0;
1500         Buffer * doc_buffer = documentBufferView()
1501                 ? &(documentBufferView()->buffer()) : 0;
1502
1503         // Check whether we need a buffer
1504         if (!lyxaction.funcHasFlag(cmd.action(), LyXAction::NoBuffer) && !buf) {
1505                 // no, exit directly
1506                 flag.message(from_utf8(N_("Command not allowed with"
1507                                         "out any document open")));
1508                 flag.setEnabled(false);
1509                 return true;
1510         }
1511
1512         if (cmd.origin() == FuncRequest::TOC) {
1513                 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1514                 if (!toc || !toc->getStatus(documentBufferView()->cursor(), cmd, flag))
1515                         flag.setEnabled(false);
1516                 return true;
1517         }
1518
1519         switch(cmd.action()) {
1520         case LFUN_BUFFER_IMPORT:
1521                 break;
1522
1523         case LFUN_MASTER_BUFFER_UPDATE:
1524         case LFUN_MASTER_BUFFER_VIEW:
1525                 enable = doc_buffer && doc_buffer->parent() != 0
1526                         && !d.processing_thread_watcher_.isRunning();
1527                 break;
1528
1529         case LFUN_BUFFER_UPDATE:
1530         case LFUN_BUFFER_VIEW: {
1531                 if (!doc_buffer || d.processing_thread_watcher_.isRunning()) {
1532                         enable = false;
1533                         break;
1534                 }
1535                 string format = to_utf8(cmd.argument());
1536                 if (cmd.argument().empty())
1537                         format = doc_buffer->getDefaultOutputFormat();
1538                 enable = doc_buffer->isExportableFormat(format);
1539                 break;
1540         }
1541
1542         case LFUN_BUFFER_RELOAD:
1543                 enable = doc_buffer && !doc_buffer->isUnnamed()
1544                         && doc_buffer->fileName().exists()
1545                         && (!doc_buffer->isClean()
1546                            || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1547                 break;
1548
1549         case LFUN_BUFFER_CHILD_OPEN:
1550                 enable = doc_buffer;
1551                 break;
1552
1553         case LFUN_BUFFER_WRITE:
1554                 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1555                 break;
1556
1557         //FIXME: This LFUN should be moved to GuiApplication.
1558         case LFUN_BUFFER_WRITE_ALL: {
1559                 // We enable the command only if there are some modified buffers
1560                 Buffer * first = theBufferList().first();
1561                 enable = false;
1562                 if (!first)
1563                         break;
1564                 Buffer * b = first;
1565                 // We cannot use a for loop as the buffer list is a cycle.
1566                 do {
1567                         if (!b->isClean()) {
1568                                 enable = true;
1569                                 break;
1570                         }
1571                         b = theBufferList().next(b);
1572                 } while (b != first);
1573                 break;
1574         }
1575
1576         case LFUN_BUFFER_WRITE_AS:
1577                 enable = doc_buffer;
1578                 break;
1579
1580         case LFUN_BUFFER_CLOSE:
1581                 enable = doc_buffer;
1582                 break;
1583
1584         case LFUN_BUFFER_CLOSE_ALL:
1585                 enable = theBufferList().last() != theBufferList().first();
1586                 break;
1587
1588         case LFUN_SPLIT_VIEW:
1589                 if (cmd.getArg(0) == "vertical")
1590                         enable = doc_buffer && (d.splitter_->count() == 1 ||
1591                                          d.splitter_->orientation() == Qt::Vertical);
1592                 else
1593                         enable = doc_buffer && (d.splitter_->count() == 1 ||
1594                                          d.splitter_->orientation() == Qt::Horizontal);
1595                 break;
1596
1597         case LFUN_CLOSE_TAB_GROUP:
1598                 enable = d.currentTabWorkArea();
1599                 break;
1600
1601         case LFUN_TOOLBAR_TOGGLE: {
1602                 string const name = cmd.getArg(0);
1603                 if (GuiToolbar * t = toolbar(name))
1604                         flag.setOnOff(t->isVisible());
1605                 else {
1606                         enable = false;
1607                         docstring const msg =
1608                                 bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name));
1609                         flag.message(msg);
1610                 }
1611                 break;
1612         }
1613
1614         case LFUN_DROP_LAYOUTS_CHOICE:
1615                 enable = buf;
1616                 break;
1617
1618         case LFUN_UI_TOGGLE:
1619                 flag.setOnOff(isFullScreen());
1620                 break;
1621
1622         case LFUN_DIALOG_DISCONNECT_INSET:
1623                 break;
1624
1625         case LFUN_DIALOG_HIDE:
1626                 // FIXME: should we check if the dialog is shown?
1627                 break;
1628
1629         case LFUN_DIALOG_TOGGLE:
1630                 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1631                 // fall through to set "enable"
1632         case LFUN_DIALOG_SHOW: {
1633                 string const name = cmd.getArg(0);
1634                 if (!doc_buffer)
1635                         enable = name == "aboutlyx"
1636                                 || name == "file" //FIXME: should be removed.
1637                                 || name == "prefs"
1638                                 || name == "texinfo"
1639                                 || name == "progress"
1640                                 || name == "compare";
1641                 else if (name == "print")
1642                         enable = doc_buffer->isExportable("dvi")
1643                                 && lyxrc.print_command != "none";
1644                 else if (name == "character" || name == "symbols") {
1645                         if (!buf || buf->isReadonly())
1646                                 enable = false;
1647                         else {
1648                                 // FIXME we should consider passthru
1649                                 // paragraphs too.
1650                                 Inset const & in = currentBufferView()->cursor().inset();
1651                                 enable = !in.getLayout().isPassThru();
1652                         }
1653                 }
1654                 else if (name == "latexlog")
1655                         enable = FileName(doc_buffer->logName()).isReadableFile();
1656                 else if (name == "spellchecker")
1657                         enable = theSpellChecker() && !doc_buffer->isReadonly();
1658                 else if (name == "vclog")
1659                         enable = doc_buffer->lyxvc().inUse();
1660                 break;
1661         }
1662
1663         case LFUN_DIALOG_UPDATE: {
1664                 string const name = cmd.getArg(0);
1665                 if (!buf)
1666                         enable = name == "prefs";
1667                 break;
1668         }
1669
1670         case LFUN_COMMAND_EXECUTE:
1671         case LFUN_MESSAGE:
1672         case LFUN_MENU_OPEN:
1673                 // Nothing to check.
1674                 break;
1675
1676         case LFUN_COMPLETION_INLINE:
1677                 if (!d.current_work_area_
1678                         || !d.current_work_area_->completer().inlinePossible(
1679                         currentBufferView()->cursor()))
1680                         enable = false;
1681                 break;
1682
1683         case LFUN_COMPLETION_POPUP:
1684                 if (!d.current_work_area_
1685                         || !d.current_work_area_->completer().popupPossible(
1686                         currentBufferView()->cursor()))
1687                         enable = false;
1688                 break;
1689
1690         case LFUN_COMPLETION_COMPLETE:
1691                 if (!d.current_work_area_
1692                         || !d.current_work_area_->completer().inlinePossible(
1693                         currentBufferView()->cursor()))
1694                         enable = false;
1695                 break;
1696
1697         case LFUN_COMPLETION_ACCEPT:
1698                 if (!d.current_work_area_
1699                         || (!d.current_work_area_->completer().popupVisible()
1700                         && !d.current_work_area_->completer().inlineVisible()
1701                         && !d.current_work_area_->completer().completionAvailable()))
1702                         enable = false;
1703                 break;
1704
1705         case LFUN_COMPLETION_CANCEL:
1706                 if (!d.current_work_area_
1707                         || (!d.current_work_area_->completer().popupVisible()
1708                         && !d.current_work_area_->completer().inlineVisible()))
1709                         enable = false;
1710                 break;
1711
1712         case LFUN_BUFFER_ZOOM_OUT:
1713                 enable = doc_buffer && lyxrc.zoom > 10;
1714                 break;
1715
1716         case LFUN_BUFFER_ZOOM_IN:
1717                 enable = doc_buffer;
1718                 break;
1719
1720         case LFUN_BUFFER_NEXT:
1721         case LFUN_BUFFER_PREVIOUS:
1722                 // FIXME: should we check is there is an previous or next buffer?
1723                 break;
1724         case LFUN_BUFFER_SWITCH:
1725                 // toggle on the current buffer, but do not toggle off
1726                 // the other ones (is that a good idea?)
1727                 if (doc_buffer
1728                         && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1729                         flag.setOnOff(true);
1730                 break;
1731
1732         case LFUN_VC_REGISTER:
1733                 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1734                 break;
1735         case LFUN_VC_CHECK_IN:
1736                 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1737                 break;
1738         case LFUN_VC_CHECK_OUT:
1739                 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1740                 break;
1741         case LFUN_VC_LOCKING_TOGGLE:
1742                 enable = doc_buffer && !doc_buffer->isReadonly()
1743                         && doc_buffer->lyxvc().lockingToggleEnabled();
1744                 flag.setOnOff(enable && doc_buffer->lyxvc().locking());
1745                 break;
1746         case LFUN_VC_REVERT:
1747                 enable = doc_buffer && doc_buffer->lyxvc().inUse() && !doc_buffer->isReadonly();
1748                 break;
1749         case LFUN_VC_UNDO_LAST:
1750                 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1751                 break;
1752         case LFUN_VC_REPO_UPDATE:
1753                 enable = doc_buffer && doc_buffer->lyxvc().repoUpdateEnabled();
1754                 break;
1755         case LFUN_VC_COMMAND: {
1756                 if (cmd.argument().empty())
1757                         enable = false;
1758                 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1759                         enable = false;
1760                 break;
1761         }
1762         case LFUN_VC_COMPARE:
1763                 enable = doc_buffer && doc_buffer->lyxvc().prepareFileRevisionEnabled();
1764                 break;
1765
1766         case LFUN_SERVER_GOTO_FILE_ROW:
1767                 break;
1768         case LFUN_FORWARD_SEARCH:
1769                 enable = !(lyxrc.forward_search_dvi.empty() && lyxrc.forward_search_pdf.empty());
1770                 break;
1771
1772         default:
1773                 return false;
1774         }
1775
1776         if (!enable)
1777                 flag.setEnabled(false);
1778
1779         return true;
1780 }
1781
1782
1783 static FileName selectTemplateFile()
1784 {
1785         FileDialog dlg(qt_("Select template file"));
1786         dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1787         dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1788
1789         FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1790                                  QStringList(qt_("LyX Documents (*.lyx)")));
1791
1792         if (result.first == FileDialog::Later)
1793                 return FileName();
1794         if (result.second.isEmpty())
1795                 return FileName();
1796         return FileName(fromqstr(result.second));
1797 }
1798
1799
1800 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1801 {
1802         setBusy(true);
1803
1804         Buffer * newBuffer = 0;
1805         try {
1806                 newBuffer = checkAndLoadLyXFile(filename);
1807         } catch (ExceptionMessage const & e) {
1808                 setBusy(false);
1809                 throw(e);
1810         }
1811
1812         if (!newBuffer) {
1813                 message(_("Document not loaded."));
1814                 setBusy(false);
1815                 return 0;
1816         }
1817
1818         setBuffer(newBuffer);
1819
1820         if (tolastfiles)
1821                 theSession().lastFiles().add(filename);
1822
1823         setBusy(false);
1824         return newBuffer;
1825 }
1826
1827
1828 void GuiView::openDocument(string const & fname)
1829 {
1830         string initpath = lyxrc.document_path;
1831
1832         if (documentBufferView()) {
1833                 string const trypath = documentBufferView()->buffer().filePath();
1834                 // If directory is writeable, use this as default.
1835                 if (FileName(trypath).isDirWritable())
1836                         initpath = trypath;
1837         }
1838
1839         string filename;
1840
1841         if (fname.empty()) {
1842                 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1843                 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1844                 dlg.setButton2(qt_("Examples|#E#e"),
1845                                 toqstr(addPath(package().system_support().absFileName(), "examples")));
1846
1847                 QStringList filter(qt_("LyX Documents (*.lyx)"));
1848                 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1849                         << qt_("LyX-1.4.x Documents (*.lyx14)")
1850                         << qt_("LyX-1.5.x Documents (*.lyx15)")
1851                         << qt_("LyX-1.6.x Documents (*.lyx16)");
1852                 FileDialog::Result result =
1853                         dlg.open(toqstr(initpath), filter);
1854
1855                 if (result.first == FileDialog::Later)
1856                         return;
1857
1858                 filename = fromqstr(result.second);
1859
1860                 // check selected filename
1861                 if (filename.empty()) {
1862                         message(_("Canceled."));
1863                         return;
1864                 }
1865         } else
1866                 filename = fname;
1867
1868         // get absolute path of file and add ".lyx" to the filename if
1869         // necessary.
1870         FileName const fullname =
1871                         fileSearch(string(), filename, "lyx", support::may_not_exist);
1872         if (!fullname.empty())
1873                 filename = fullname.absFileName();
1874
1875         if (!fullname.onlyPath().isDirectory()) {
1876                 Alert::warning(_("Invalid filename"),
1877                                 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1878                                 from_utf8(fullname.absFileName())));
1879                 return;
1880         }
1881
1882         // if the file doesn't exist and isn't already open (bug 6645),
1883         // let the user create one
1884         if (!fullname.exists() && !theBufferList().exists(fullname)) {
1885                 // the user specifically chose this name. Believe him.
1886                 Buffer * const b = newFile(filename, string(), true);
1887                 if (b)
1888                         setBuffer(b);
1889                 return;
1890         }
1891
1892         docstring const disp_fn = makeDisplayPath(filename);
1893         message(bformat(_("Opening document %1$s..."), disp_fn));
1894
1895         docstring str2;
1896         Buffer * buf = loadDocument(fullname);
1897         if (buf) {
1898                 // I don't think this is needed, since it will be done in setBuffer().
1899                 // buf->updateBuffer();
1900                 setBuffer(buf);
1901                 buf->errors("Parse");
1902                 str2 = bformat(_("Document %1$s opened."), disp_fn);
1903                 if (buf->lyxvc().inUse())
1904                         str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1905                                 " " + _("Version control detected.");
1906         } else {
1907                 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1908         }
1909         message(str2);
1910 }
1911
1912 // FIXME: clean that
1913 static bool import(GuiView * lv, FileName const & filename,
1914         string const & format, ErrorList & errorList)
1915 {
1916         FileName const lyxfile(support::changeExtension(filename.absFileName(), ".lyx"));
1917
1918         string loader_format;
1919         vector<string> loaders = theConverters().loaders();
1920         if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1921                 for (vector<string>::const_iterator it = loaders.begin();
1922                          it != loaders.end(); ++it) {
1923                         if (!theConverters().isReachable(format, *it))
1924                                 continue;
1925
1926                         string const tofile =
1927                                 support::changeExtension(filename.absFileName(),
1928                                 formats.extension(*it));
1929                         if (!theConverters().convert(0, filename, FileName(tofile),
1930                                 filename, format, *it, errorList))
1931                                 return false;
1932                         loader_format = *it;
1933                         break;
1934                 }
1935                 if (loader_format.empty()) {
1936                         frontend::Alert::error(_("Couldn't import file"),
1937                                          bformat(_("No information for importing the format %1$s."),
1938                                          formats.prettyName(format)));
1939                         return false;
1940                 }
1941         } else
1942                 loader_format = format;
1943
1944         if (loader_format == "lyx") {
1945                 Buffer * buf = lv->loadDocument(lyxfile);
1946                 if (!buf)
1947                         return false;
1948                 // I don't think this is needed, since it will be done in setBuffer().
1949                 // buf->updateBuffer();
1950                 lv->setBuffer(buf);
1951                 buf->errors("Parse");
1952         } else {
1953                 Buffer * const b = newFile(lyxfile.absFileName(), string(), true);
1954                 if (!b)
1955                         return false;
1956                 lv->setBuffer(b);
1957                 bool as_paragraphs = loader_format == "textparagraph";
1958                 string filename2 = (loader_format == format) ? filename.absFileName()
1959                         : support::changeExtension(filename.absFileName(),
1960                                           formats.extension(loader_format));
1961                 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
1962                         as_paragraphs);
1963                 guiApp->setCurrentView(lv);
1964                 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
1965         }
1966
1967         return true;
1968 }
1969
1970
1971 void GuiView::importDocument(string const & argument)
1972 {
1973         string format;
1974         string filename = split(argument, format, ' ');
1975
1976         LYXERR(Debug::INFO, format << " file: " << filename);
1977
1978         // need user interaction
1979         if (filename.empty()) {
1980                 string initpath = lyxrc.document_path;
1981                 if (documentBufferView()) {
1982                         string const trypath = documentBufferView()->buffer().filePath();
1983                         // If directory is writeable, use this as default.
1984                         if (FileName(trypath).isDirWritable())
1985                                 initpath = trypath;
1986                 }
1987
1988                 docstring const text = bformat(_("Select %1$s file to import"),
1989                         formats.prettyName(format));
1990
1991                 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
1992                 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1993                 dlg.setButton2(qt_("Examples|#E#e"),
1994                         toqstr(addPath(package().system_support().absFileName(), "examples")));
1995
1996                 docstring filter = formats.prettyName(format);
1997                 filter += " (*.";
1998                 // FIXME UNICODE
1999                 filter += from_utf8(formats.extension(format));
2000                 filter += ')';
2001
2002                 FileDialog::Result result =
2003                         dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
2004
2005                 if (result.first == FileDialog::Later)
2006                         return;
2007
2008                 filename = fromqstr(result.second);
2009
2010                 // check selected filename
2011                 if (filename.empty())
2012                         message(_("Canceled."));
2013         }
2014
2015         if (filename.empty())
2016                 return;
2017
2018         // get absolute path of file
2019         FileName const fullname(support::makeAbsPath(filename));
2020
2021         FileName const lyxfile(support::changeExtension(fullname.absFileName(), ".lyx"));
2022
2023         // Check if the document already is open
2024         Buffer * buf = theBufferList().getBuffer(lyxfile);
2025         if (buf) {
2026                 setBuffer(buf);
2027                 if (!closeBuffer()) {
2028                         message(_("Canceled."));
2029                         return;
2030                 }
2031         }
2032
2033         docstring const displaypath = makeDisplayPath(lyxfile.absFileName(), 30);
2034
2035         // if the file exists already, and we didn't do
2036         // -i lyx thefile.lyx, warn
2037         if (lyxfile.exists() && fullname != lyxfile) {
2038
2039                 docstring text = bformat(_("The document %1$s already exists.\n\n"
2040                         "Do you want to overwrite that document?"), displaypath);
2041                 int const ret = Alert::prompt(_("Overwrite document?"),
2042                         text, 0, 1, _("&Overwrite"), _("&Cancel"));
2043
2044                 if (ret == 1) {
2045                         message(_("Canceled."));
2046                         return;
2047                 }
2048         }
2049
2050         message(bformat(_("Importing %1$s..."), displaypath));
2051         ErrorList errorList;
2052         if (import(this, fullname, format, errorList))
2053                 message(_("imported."));
2054         else
2055                 message(_("file not imported!"));
2056
2057         // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
2058 }
2059
2060
2061 void GuiView::newDocument(string const & filename, bool from_template)
2062 {
2063         FileName initpath(lyxrc.document_path);
2064         if (documentBufferView()) {
2065                 FileName const trypath(documentBufferView()->buffer().filePath());
2066                 // If directory is writeable, use this as default.
2067                 if (trypath.isDirWritable())
2068                         initpath = trypath;
2069         }
2070
2071         string templatefile;
2072         if (from_template) {
2073                 templatefile = selectTemplateFile().absFileName();
2074                 if (templatefile.empty())
2075                         return;
2076         }
2077
2078         Buffer * b;
2079         if (filename.empty())
2080                 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
2081         else
2082                 b = newFile(filename, templatefile, true);
2083
2084         if (b)
2085                 setBuffer(b);
2086
2087         // If no new document could be created, it is unsure
2088         // whether there is a valid BufferView.
2089         if (currentBufferView())
2090                 // Ensure the cursor is correctly positioned on screen.
2091                 currentBufferView()->showCursor();
2092 }
2093
2094
2095 void GuiView::insertLyXFile(docstring const & fname)
2096 {
2097         BufferView * bv = documentBufferView();
2098         if (!bv)
2099                 return;
2100
2101         // FIXME UNICODE
2102         FileName filename(to_utf8(fname));
2103
2104         if (!filename.empty()) {
2105                 bv->insertLyXFile(filename);
2106                 return;
2107         }
2108
2109         // Launch a file browser
2110         // FIXME UNICODE
2111         string initpath = lyxrc.document_path;
2112         string const trypath = bv->buffer().filePath();
2113         // If directory is writeable, use this as default.
2114         if (FileName(trypath).isDirWritable())
2115                 initpath = trypath;
2116
2117         // FIXME UNICODE
2118         FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
2119         dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2120         dlg.setButton2(qt_("Examples|#E#e"),
2121                 toqstr(addPath(package().system_support().absFileName(),
2122                 "examples")));
2123
2124         FileDialog::Result result = dlg.open(toqstr(initpath),
2125                                  QStringList(qt_("LyX Documents (*.lyx)")));
2126
2127         if (result.first == FileDialog::Later)
2128                 return;
2129
2130         // FIXME UNICODE
2131         filename.set(fromqstr(result.second));
2132
2133         // check selected filename
2134         if (filename.empty()) {
2135                 // emit message signal.
2136                 message(_("Canceled."));
2137                 return;
2138         }
2139
2140         bv->insertLyXFile(filename);
2141 }
2142
2143
2144 void GuiView::insertPlaintextFile(docstring const & fname,
2145         bool asParagraph)
2146 {
2147         BufferView * bv = documentBufferView();
2148         if (!bv)
2149                 return;
2150
2151         if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
2152                 message(_("Absolute filename expected."));
2153                 return;
2154         }
2155
2156         // FIXME UNICODE
2157         FileName filename(to_utf8(fname));
2158
2159         if (!filename.empty()) {
2160                 bv->insertPlaintextFile(filename, asParagraph);
2161                 return;
2162         }
2163
2164         FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
2165                 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
2166
2167         FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
2168                 QStringList(qt_("All Files (*)")));
2169
2170         if (result.first == FileDialog::Later)
2171                 return;
2172
2173         // FIXME UNICODE
2174         filename.set(fromqstr(result.second));
2175
2176         // check selected filename
2177         if (filename.empty()) {
2178                 // emit message signal.
2179                 message(_("Canceled."));
2180                 return;
2181         }
2182
2183         bv->insertPlaintextFile(filename, asParagraph);
2184 }
2185
2186
2187 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
2188 {
2189         FileName fname = b.fileName();
2190         FileName const oldname = fname;
2191
2192         if (!newname.empty()) {
2193                 // FIXME UNICODE
2194                 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFileName());
2195         } else {
2196                 // Switch to this Buffer.
2197                 setBuffer(&b);
2198
2199                 // No argument? Ask user through dialog.
2200                 // FIXME UNICODE
2201                 FileDialog dlg(qt_("Choose a filename to save document as"),
2202                                    LFUN_BUFFER_WRITE_AS);
2203                 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2204                 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
2205
2206                 if (!isLyXFileName(fname.absFileName()))
2207                         fname.changeExtension(".lyx");
2208
2209                 FileDialog::Result result =
2210                         dlg.save(toqstr(fname.onlyPath().absFileName()),
2211                                    QStringList(qt_("LyX Documents (*.lyx)")),
2212                                          toqstr(fname.onlyFileName()));
2213
2214                 if (result.first == FileDialog::Later)
2215                         return false;
2216
2217                 fname.set(fromqstr(result.second));
2218
2219                 if (fname.empty())
2220                         return false;
2221
2222                 if (!isLyXFileName(fname.absFileName()))
2223                         fname.changeExtension(".lyx");
2224         }
2225
2226         // fname is now the new Buffer location.
2227         if (FileName(fname).exists()) {
2228                 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2229                 docstring text = bformat(_("The document %1$s already "
2230                                            "exists.\n\nDo you want to "
2231                                            "overwrite that document?"),
2232                                          file);
2233                 int const ret = Alert::prompt(_("Overwrite document?"),
2234                         text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2235                 switch (ret) {
2236                 case 0: break;
2237                 case 1: return renameBuffer(b, docstring());
2238                 case 2: return false;
2239                 }
2240         }
2241
2242         FileName oldauto = b.getAutosaveFileName();
2243
2244         // Ok, change the name of the buffer
2245         b.setFileName(fname.absFileName());
2246         b.markDirty();
2247         bool unnamed = b.isUnnamed();
2248         b.setUnnamed(false);
2249         b.saveCheckSum(fname);
2250
2251         // bring the autosave file with us, just in case.
2252         b.moveAutosaveFile(oldauto);
2253
2254         if (!saveBuffer(b)) {
2255                 oldauto = b.getAutosaveFileName();
2256                 b.setFileName(oldname.absFileName());
2257                 b.setUnnamed(unnamed);
2258                 b.saveCheckSum(oldname);
2259                 b.moveAutosaveFile(oldauto);
2260                 return false;
2261         }
2262
2263         // validate version control data and
2264         // correct buffer title
2265         b.lyxvc().file_found_hook(b.fileName());
2266         b.updateTitles();
2267
2268         // the file has now been saved to the new location.
2269         // we need to check that the locations of child buffers
2270         // are still valid.
2271         b.checkChildBuffers();
2272
2273         return true;
2274 }
2275
2276
2277 bool GuiView::saveBuffer(Buffer & b)
2278 {
2279         if (workArea(b) && workArea(b)->inDialogMode())
2280                 return true;
2281
2282         if (b.isUnnamed())
2283                 return renameBuffer(b, docstring());
2284
2285         if (b.save()) {
2286                 theSession().lastFiles().add(b.fileName());
2287                 return true;
2288         }
2289
2290         // Switch to this Buffer.
2291         setBuffer(&b);
2292
2293         // FIXME: we don't tell the user *WHY* the save failed !!
2294         docstring const file = makeDisplayPath(b.absFileName(), 30);
2295         docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2296                                    "Do you want to rename the document and "
2297                                    "try again?"), file);
2298         int const ret = Alert::prompt(_("Rename and save?"),
2299                 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2300         switch (ret) {
2301         case 0:
2302                 if (!renameBuffer(b, docstring()))
2303                         return false;
2304                 break;
2305         case 1:
2306                 break;
2307         case 2:
2308                 return false;
2309         }
2310
2311         return saveBuffer(b);
2312 }
2313
2314
2315 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2316 {
2317         return closeWorkArea(wa, false);
2318 }
2319
2320
2321 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2322 {
2323         Buffer & buf = wa->bufferView().buffer();
2324         return closeWorkArea(wa, !buf.parent());
2325 }
2326
2327
2328 bool GuiView::closeBuffer()
2329 {
2330         GuiWorkArea * wa = currentMainWorkArea();
2331         setCurrentWorkArea(wa);
2332         Buffer & buf = wa->bufferView().buffer();
2333         return wa && closeWorkArea(wa, !buf.parent());
2334 }
2335
2336
2337 void GuiView::writeSession() const {
2338         GuiWorkArea const * active_wa = currentMainWorkArea();
2339         for (int i = 0; i < d.splitter_->count(); ++i) {
2340                 TabWorkArea * twa = d.tabWorkArea(i);
2341                 for (int j = 0; j < twa->count(); ++j) {
2342                         GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2343                         Buffer & buf = wa->bufferView().buffer();
2344                         theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2345                 }
2346         }
2347 }
2348
2349
2350 bool GuiView::closeBufferAll()
2351 {
2352         // Close the workareas in all other views
2353         QList<int> const ids = guiApp->viewIds();
2354         for (int i = 0; i != ids.size(); ++i) {
2355                 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2356                         return false;
2357         }
2358
2359         // Close our own workareas
2360         if (!closeWorkAreaAll())
2361                 return false;
2362
2363         // Now close the hidden buffers. We prevent hidden buffers from being
2364         // dirty, so we can just close them.
2365         theBufferList().closeAll();
2366         return true;
2367 }
2368
2369
2370 bool GuiView::closeWorkAreaAll()
2371 {
2372         setCurrentWorkArea(currentMainWorkArea());
2373
2374         // We might be in a situation that there is still a tabWorkArea, but
2375         // there are no tabs anymore. This can happen when we get here after a
2376         // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2377         // many TabWorkArea's have no documents anymore.
2378         int empty_twa = 0;
2379
2380         // We have to call count() each time, because it can happen that
2381         // more than one splitter will disappear in one iteration (bug 5998).
2382         for (; d.splitter_->count() > empty_twa; ) {
2383                 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2384
2385                 if (twa->count() == 0)
2386                         ++empty_twa;
2387                 else {
2388                         setCurrentWorkArea(twa->currentWorkArea());
2389                         if (!closeTabWorkArea(twa))
2390                                 return false;
2391                 }
2392         }
2393         return true;
2394 }
2395
2396
2397 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2398 {
2399         if (!wa)
2400                 return false;
2401
2402         Buffer & buf = wa->bufferView().buffer();
2403
2404         if (close_buffer && GuiViewPrivate::busyBuffers.contains(&buf)) {
2405                 Alert::warning(_("Close document "), _("Document could not be closed because it is processed by LyX."));
2406                 return false;
2407         }
2408
2409         if (close_buffer)
2410                 return closeBuffer(buf);
2411         else {
2412                 if (!inMultiTabs(wa))
2413                         if (!saveBufferIfNeeded(buf, true))
2414                                 return false;
2415                 removeWorkArea(wa);
2416                 return true;
2417         }
2418 }
2419
2420
2421 bool GuiView::closeBuffer(Buffer & buf)
2422 {
2423         // If we are in a close_event all children will be closed in some time,
2424         // so no need to do it here. This will ensure that the children end up
2425         // in the session file in the correct order. If we close the master
2426         // buffer, we can close or release the child buffers here too.
2427         if (!closing_) {
2428                 ListOfBuffers clist = buf.getChildren();
2429                 ListOfBuffers::const_iterator it = clist.begin();
2430                 ListOfBuffers::const_iterator const bend = clist.end();
2431                 for (; it != bend; ++it) {
2432                         // If a child is dirty, do not close
2433                         // without user intervention
2434                         //FIXME: should we look in other tabworkareas?
2435                         Buffer * child_buf = *it;
2436                         GuiWorkArea * child_wa = workArea(*child_buf);
2437                         if (child_wa) {
2438                                 if (!closeWorkArea(child_wa, true))
2439                                         return false;
2440                         } else
2441                                 theBufferList().releaseChild(&buf, child_buf);
2442                 }
2443         }
2444         // goto bookmark to update bookmark pit.
2445         //FIXME: we should update only the bookmarks related to this buffer!
2446         LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2447         for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2448                 guiApp->gotoBookmark(i+1, false, false);
2449
2450         if (saveBufferIfNeeded(buf, false)) {
2451                 buf.removeAutosaveFile();
2452                 theBufferList().release(&buf);
2453                 return true;
2454         }
2455         return false;
2456 }
2457
2458
2459 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2460 {
2461         while (twa == d.currentTabWorkArea()) {
2462                 twa->setCurrentIndex(twa->count()-1);
2463
2464                 GuiWorkArea * wa = twa->currentWorkArea();
2465                 Buffer & b = wa->bufferView().buffer();
2466
2467                 // We only want to close the buffer if the same buffer is not visible
2468                 // in another view, and if this is not a child and if we are closing
2469                 // a view (not a tabgroup).
2470                 bool const close_buffer =
2471                         !inMultiViews(wa) && !b.parent() && closing_;
2472
2473                 if (!closeWorkArea(wa, close_buffer))
2474                         return false;
2475         }
2476         return true;
2477 }
2478
2479
2480 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2481 {
2482         if (buf.isClean() || buf.paragraphs().empty())
2483                 return true;
2484
2485         // Switch to this Buffer.
2486         setBuffer(&buf);
2487
2488         docstring file;
2489         // FIXME: Unicode?
2490         if (buf.isUnnamed())
2491                 file = from_utf8(buf.fileName().onlyFileName());
2492         else
2493                 file = buf.fileName().displayName(30);
2494
2495         // Bring this window to top before asking questions.
2496         raise();
2497         activateWindow();
2498
2499         int ret;
2500         if (hiding && buf.isUnnamed()) {
2501                 docstring const text = bformat(_("The document %1$s has not been "
2502                                                  "saved yet.\n\nDo you want to save "
2503                                                  "the document?"), file);
2504                 ret = Alert::prompt(_("Save new document?"),
2505                         text, 0, 1, _("&Save"), _("&Cancel"));
2506                 if (ret == 1)
2507                         ++ret;
2508         } else {
2509                 docstring const text = bformat(_("The document %1$s has unsaved changes."
2510                         "\n\nDo you want to save the document or discard the changes?"), file);
2511                 ret = Alert::prompt(_("Save changed document?"),
2512                         text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2513         }
2514
2515         switch (ret) {
2516         case 0:
2517                 if (!saveBuffer(buf))
2518                         return false;
2519                 break;
2520         case 1:
2521                 // if we crash after this we could
2522                 // have no autosave file but I guess
2523                 // this is really improbable (Jug)
2524                 // Sometime improbable things happen, bug 6857 (ps)
2525                 // buf.removeAutosaveFile();
2526                 if (hiding)
2527                         // revert all changes
2528                         buf.reload();
2529                 buf.markClean();
2530                 break;
2531         case 2:
2532                 return false;
2533         }
2534         return true;
2535 }
2536
2537
2538 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2539 {
2540         Buffer & buf = wa->bufferView().buffer();
2541
2542         for (int i = 0; i != d.splitter_->count(); ++i) {
2543                 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2544                 if (wa_ && wa_ != wa)
2545                         return true;
2546         }
2547         return inMultiViews(wa);
2548 }
2549
2550
2551 bool GuiView::inMultiViews(GuiWorkArea * wa)
2552 {
2553         QList<int> const ids = guiApp->viewIds();
2554         Buffer & buf = wa->bufferView().buffer();
2555
2556         int found_twa = 0;
2557         for (int i = 0; i != ids.size() && found_twa <= 1; ++i) {
2558                 if (id_ == ids[i])
2559                         continue;
2560
2561                 if (guiApp->view(ids[i]).workArea(buf))
2562                         return true;
2563         }
2564         return false;
2565 }
2566
2567
2568 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2569 {
2570         Buffer * const curbuf = documentBufferView()
2571                 ? &documentBufferView()->buffer() : 0;
2572         Buffer * nextbuf = curbuf;
2573         while (true) {
2574                 if (np == NEXTBUFFER)
2575                         nextbuf = theBufferList().next(nextbuf);
2576                 else
2577                         nextbuf = theBufferList().previous(nextbuf);
2578                 if (nextbuf == curbuf)
2579                         break;
2580                 if (nextbuf == 0) {
2581                         nextbuf = curbuf;
2582                         break;
2583                 }
2584                 if (workArea(*nextbuf))
2585                         break;
2586         }
2587         setBuffer(nextbuf);
2588 }
2589
2590
2591 /// make sure the document is saved
2592 static bool ensureBufferClean(Buffer * buffer)
2593 {
2594         LASSERT(buffer, return false);
2595         if (buffer->isClean() && !buffer->isUnnamed())
2596                 return true;
2597
2598         docstring const file = buffer->fileName().displayName(30);
2599         docstring title;
2600         docstring text;
2601         if (!buffer->isUnnamed()) {
2602                 text = bformat(_("The document %1$s has unsaved "
2603                                                  "changes.\n\nDo you want to save "
2604                                                  "the document?"), file);
2605                 title = _("Save changed document?");
2606
2607         } else {
2608                 text = bformat(_("The document %1$s has not been "
2609                                                  "saved yet.\n\nDo you want to save "
2610                                                  "the document?"), file);
2611                 title = _("Save new document?");
2612         }
2613         int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2614
2615         if (ret == 0)
2616                 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2617
2618         return buffer->isClean() && !buffer->isUnnamed();
2619 }
2620
2621
2622 bool GuiView::reloadBuffer()
2623 {
2624         Buffer * buffer = documentBufferView()
2625                 ? &(documentBufferView()->buffer()) : 0;
2626         if (buffer)
2627                 return buffer->reload();
2628         return false;
2629 }
2630
2631
2632 void GuiView::checkExternallyModifiedBuffers()
2633 {
2634         BufferList::iterator bit = theBufferList().begin();
2635         BufferList::iterator const bend = theBufferList().end();
2636         for (; bit != bend; ++bit) {
2637                 if ((*bit)->fileName().exists()
2638                         && (*bit)->isExternallyModified(Buffer::checksum_method)) {
2639                         docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2640                                         " Reload now? Any local changes will be lost."),
2641                                         from_utf8((*bit)->absFileName()));
2642                         int const ret = Alert::prompt(_("Reload externally changed document?"),
2643                                                 text, 0, 1, _("&Reload"), _("&Cancel"));
2644                         if (!ret)
2645                                 (*bit)->reload();
2646                 }
2647         }
2648 }
2649
2650
2651 void GuiView::dispatchVC(FuncRequest const & cmd, DispatchResult & dr)
2652 {
2653         Buffer * buffer = documentBufferView()
2654                 ? &(documentBufferView()->buffer()) : 0;
2655
2656         switch (cmd.action()) {
2657         case LFUN_VC_REGISTER:
2658                 if (!buffer || !ensureBufferClean(buffer))
2659                         break;
2660                 if (!buffer->lyxvc().inUse()) {
2661                         if (buffer->lyxvc().registrer()) {
2662                                 reloadBuffer();
2663                                 dr.suppressMessageUpdate();
2664                         }
2665                 }
2666                 break;
2667
2668         case LFUN_VC_CHECK_IN:
2669                 if (!buffer || !ensureBufferClean(buffer))
2670                         break;
2671                 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2672                         dr.setMessage(buffer->lyxvc().checkIn());
2673                         if (!dr.message().empty())
2674                                 reloadBuffer();
2675                 }
2676                 break;
2677
2678         case LFUN_VC_CHECK_OUT:
2679                 if (!buffer || !ensureBufferClean(buffer))
2680                         break;
2681                 if (buffer->lyxvc().inUse()) {
2682                         dr.setMessage(buffer->lyxvc().checkOut());
2683                         reloadBuffer();
2684                 }
2685                 break;
2686
2687         case LFUN_VC_LOCKING_TOGGLE:
2688                 LASSERT(buffer, return);
2689                 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2690                         break;
2691                 if (buffer->lyxvc().inUse()) {
2692                         string res = buffer->lyxvc().lockingToggle();
2693                         if (res.empty()) {
2694                                 frontend::Alert::error(_("Revision control error."),
2695                                 _("Error when setting the locking property."));
2696                         } else {
2697                                 dr.setMessage(res);
2698                                 reloadBuffer();
2699                         }
2700                 }
2701                 break;
2702
2703         case LFUN_VC_REVERT:
2704                 LASSERT(buffer, return);
2705                 buffer->lyxvc().revert();
2706                 reloadBuffer();
2707                 dr.suppressMessageUpdate();
2708                 break;
2709
2710         case LFUN_VC_UNDO_LAST:
2711                 LASSERT(buffer, return);
2712                 buffer->lyxvc().undoLast();
2713                 reloadBuffer();
2714                 dr.suppressMessageUpdate();
2715                 break;
2716
2717         case LFUN_VC_REPO_UPDATE:
2718                 LASSERT(buffer, return);
2719                 if (ensureBufferClean(buffer)) {
2720                         dr.setMessage(buffer->lyxvc().repoUpdate());
2721                         checkExternallyModifiedBuffers();
2722                 }
2723                 break;
2724
2725         case LFUN_VC_COMMAND: {
2726                 string flag = cmd.getArg(0);
2727                 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2728                         break;
2729                 docstring message;
2730                 if (contains(flag, 'M')) {
2731                         if (!Alert::askForText(message, _("LyX VC: Log Message")))
2732                                 break;
2733                 }
2734                 string path = cmd.getArg(1);
2735                 if (contains(path, "$$p") && buffer)
2736                         path = subst(path, "$$p", buffer->filePath());
2737                 LYXERR(Debug::LYXVC, "Directory: " << path);
2738                 FileName pp(path);
2739                 if (!pp.isReadableDirectory()) {
2740                         lyxerr << _("Directory is not accessible.") << endl;
2741                         break;
2742                 }
2743                 support::PathChanger p(pp);
2744
2745                 string command = cmd.getArg(2);
2746                 if (command.empty())
2747                         break;
2748                 if (buffer) {
2749                         command = subst(command, "$$i", buffer->absFileName());
2750                         command = subst(command, "$$p", buffer->filePath());
2751                 }
2752                 command = subst(command, "$$m", to_utf8(message));
2753                 LYXERR(Debug::LYXVC, "Command: " << command);
2754                 Systemcall one;
2755                 one.startscript(Systemcall::Wait, command);
2756
2757                 if (!buffer)
2758                         break;
2759                 if (contains(flag, 'I'))
2760                         buffer->markDirty();
2761                 if (contains(flag, 'R'))
2762                         reloadBuffer();
2763
2764                 break;
2765                 }
2766
2767         case LFUN_VC_COMPARE: {
2768
2769                 if (cmd.argument().empty()) {
2770                         lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "comparehistory"));
2771                         break;
2772                 }
2773
2774                 string rev1 = cmd.getArg(0);
2775                 string f1, f2;
2776
2777                 // f1
2778                 if (!buffer->lyxvc().prepareFileRevision(rev1, f1))
2779                         break;
2780
2781                 if (isStrInt(rev1) && convert<int>(rev1) <= 0) {
2782                         f2 = buffer->absFileName();
2783                 } else {
2784                         string rev2 = cmd.getArg(1);
2785                         if (rev2.empty())
2786                                 break;
2787                         // f2
2788                         if (!buffer->lyxvc().prepareFileRevision(rev2, f2))
2789                                 break;
2790                 }
2791
2792                 LYXERR(Debug::LYXVC, "Launching comparison for fetched revisions:\n" <<
2793                                         f1 << "\n"  << f2 << "\n" );
2794                 string par = "compare run " + quoteName(f1) + " " + quoteName(f2);
2795                 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, par));
2796                 break;
2797         }
2798
2799         default:
2800                 break;
2801         }
2802 }
2803
2804
2805 void GuiView::openChildDocument(string const & fname)
2806 {
2807         LASSERT(documentBufferView(), return);
2808         Buffer & buffer = documentBufferView()->buffer();
2809         FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2810         documentBufferView()->saveBookmark(false);
2811         Buffer * child = 0;
2812         bool parsed = false;
2813         if (theBufferList().exists(filename)) {
2814                 child = theBufferList().getBuffer(filename);
2815         } else {
2816                 message(bformat(_("Opening child document %1$s..."),
2817                 makeDisplayPath(filename.absFileName())));
2818                 child = loadDocument(filename, false);
2819                 parsed = true;
2820         }
2821         if (!child)
2822                 return;
2823
2824         // Set the parent name of the child document.
2825         // This makes insertion of citations and references in the child work,
2826         // when the target is in the parent or another child document.
2827         child->setParent(&buffer);
2828
2829         // I don't think this is needed, since it will be called in
2830         // setBuffer().
2831         //      child->masterBuffer()->updateBuffer();
2832         setBuffer(child);
2833         if (parsed)
2834                 child->errors("Parse");
2835 }
2836
2837
2838 bool GuiView::goToFileRow(string const & argument)
2839 {
2840         string file_name;
2841         int row;
2842         size_t i = argument.find_last_of(' ');
2843         if (i != string::npos) {
2844                 file_name = os::internal_path(trim(argument.substr(0, i)));
2845                 istringstream is(argument.substr(i + 1));
2846                 is >> row;
2847                 if (is.fail())
2848                         i = string::npos;
2849         }
2850         if (i == string::npos) {
2851                 LYXERR0("Wrong argument: " << argument);
2852                 return false;
2853         }
2854         Buffer * buf = 0;
2855         string const abstmp = package().temp_dir().absFileName();
2856         string const realtmp = package().temp_dir().realPath();
2857         // We have to use os::path_prefix_is() here, instead of
2858         // simply prefixIs(), because the file name comes from
2859         // an external application and may need case adjustment.
2860         if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2861                 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2862                 // Needed by inverse dvi search. If it is a file
2863                 // in tmpdir, call the apropriated function.
2864                 // If tmpdir is a symlink, we may have the real
2865                 // path passed back, so we correct for that.
2866                 if (!prefixIs(file_name, abstmp))
2867                         file_name = subst(file_name, realtmp, abstmp);
2868                 buf = theBufferList().getBufferFromTmp(file_name);
2869         } else {
2870                 // Must replace extension of the file to be .lyx
2871                 // and get full path
2872                 FileName const s = fileSearch(string(),
2873                                                   support::changeExtension(file_name, ".lyx"), "lyx");
2874                 // Either change buffer or load the file
2875                 if (theBufferList().exists(s))
2876                         buf = theBufferList().getBuffer(s);
2877                 else if (s.exists()) {
2878                         buf = loadDocument(s);
2879                         if (!buf)
2880                                 return false;
2881                         // I don't think this is needed. loadDocument() calls
2882                         // setBuffer(), which calls updateBuffer().
2883                         // buf->updateBuffer();
2884                         buf->errors("Parse");
2885                 } else {
2886                         message(bformat(
2887                                         _("File does not exist: %1$s"),
2888                                         makeDisplayPath(file_name)));
2889                         return false;
2890                 }
2891         }
2892         setBuffer(buf);
2893         documentBufferView()->setCursorFromRow(row);
2894         return true;
2895 }
2896
2897
2898 #if (QT_VERSION >= 0x040400)
2899 template<class T>
2900 docstring GuiView::GuiViewPrivate::runAndDestroy(const T& func, Buffer const * orig, Buffer * buffer, string const & format, string const & msg)
2901 {
2902         bool const update_unincluded =
2903                                 buffer->params().maintain_unincluded_children
2904                                 && !buffer->params().getIncludedChildren().empty();
2905         bool const success = func(format, update_unincluded);
2906         delete buffer;
2907         busyBuffers.remove(orig);
2908         return success
2909                 ? bformat(_("Successful " + msg + " to format: %1$s"), from_utf8(format))
2910                 : bformat(_("Error " + msg + " format: %1$s"), from_utf8(format));
2911 }
2912
2913 docstring GuiView::GuiViewPrivate::compileAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2914 {
2915         bool (Buffer::* mem_func)(std::string const &, bool, bool) const = &Buffer::doExport;
2916         return runAndDestroy(bind(mem_func, buffer, _1, true, _2), orig, buffer, format, "export");
2917 }
2918
2919 docstring GuiView::GuiViewPrivate::exportAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2920 {
2921         bool (Buffer::* mem_func)(std::string const &, bool, bool) const = &Buffer::doExport;
2922         return runAndDestroy(bind(mem_func, buffer, _1, false, _2), orig, buffer, format, "export");
2923
2924 }
2925
2926 docstring GuiView::GuiViewPrivate::previewAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2927 {
2928         bool(Buffer::* mem_func)(std::string const &, bool) const = &Buffer::preview;
2929         return runAndDestroy(bind(mem_func, buffer, _1, _2), orig, buffer, format, "preview");
2930 }
2931 #endif
2932
2933
2934 bool GuiView::GuiViewPrivate::asyncBufferProcessing(
2935                            string const & argument,
2936                            Buffer const * used_buffer,
2937                            docstring const & msg,
2938                            docstring (*asyncFunc)(Buffer const *, Buffer *, string const &),
2939                            bool (Buffer::*syncFunc)(string const &, bool, bool) const,
2940                            bool (Buffer::*previewFunc)(string const &, bool) const)
2941 {
2942         if (!used_buffer) {
2943                 return false;
2944         }
2945         gv_->processingThreadStarted();
2946         string format = argument;
2947         if (format.empty()) {
2948                 format = used_buffer->getDefaultOutputFormat();
2949         }
2950 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2951         if (!msg.empty()) {
2952                 progress_->clearMessages();
2953                 gv_->message(msg);
2954         }
2955         GuiViewPrivate::busyBuffers.insert(used_buffer);
2956         QFuture<docstring> f = QtConcurrent::run(
2957                                 asyncFunc,
2958                                 used_buffer,
2959                                 used_buffer->clone(),
2960                                 format);
2961         setPreviewFuture(f);
2962         last_export_format = used_buffer->bufferFormat();
2963         (void) syncFunc;
2964         (void) previewFunc;
2965         // We are asynchronous, so we don't know here anything about the success
2966         return true;
2967 #else
2968         bool const update_unincluded =
2969                 used_buffer->params().maintain_unincluded_children &&
2970                 !used_buffer->params().getIncludedChildren().empty();
2971         if (syncFunc) {
2972                 return (used_buffer->*syncFunc)(format, true, update_unincluded);
2973         } else if (previewFunc) {
2974                 return (used_buffer->*previewFunc)(format, update_unincluded);
2975         }
2976         (void) asyncFunc;
2977         return false;
2978 #endif
2979 }
2980
2981 void GuiView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
2982 {
2983         BufferView * bv = currentBufferView();
2984         // By default we won't need any update.
2985         dr.screenUpdate(Update::None);
2986         // assume cmd will be dispatched
2987         dr.dispatched(true);
2988
2989         Buffer * doc_buffer = documentBufferView()
2990                 ? &(documentBufferView()->buffer()) : 0;
2991
2992         if (cmd.origin() == FuncRequest::TOC) {
2993                 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
2994                 // FIXME: do we need to pass a DispatchResult object here?
2995                 toc->doDispatch(bv->cursor(), cmd);
2996                 return;
2997         }
2998
2999         string const argument = to_utf8(cmd.argument());
3000
3001         switch(cmd.action()) {
3002                 case LFUN_BUFFER_CHILD_OPEN:
3003                         openChildDocument(to_utf8(cmd.argument()));
3004                         break;
3005
3006                 case LFUN_BUFFER_IMPORT:
3007                         importDocument(to_utf8(cmd.argument()));
3008                         break;
3009
3010                 case LFUN_BUFFER_EXPORT: {
3011                         if (!doc_buffer)
3012                                 break;
3013                         // GCC only sees strfwd.h when building merged
3014                         if (::lyx::operator==(cmd.argument(), "custom")) {
3015                                 dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"), dr);
3016                                 break;
3017                         }
3018 #if 0
3019                         // TODO Remove if we could export asynchronous
3020                         if (!doc_buffer->doExport(argument, false)) {
3021                                 dr.setError(true);
3022                                 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
3023                                         cmd.argument()));
3024                         }
3025 #else
3026                         /* TODO/Review: Is it a problem to also export the children?
3027                                         See the update_unincluded flag */
3028                         d.asyncBufferProcessing(argument,
3029                                                 doc_buffer,
3030                                                 _("Exporting ..."),
3031                                                 &GuiViewPrivate::exportAndDestroy,
3032                                                 &Buffer::doExport,
3033                                                 0);
3034                         // TODO Inform user about success
3035 #endif
3036                         break;
3037                 }
3038
3039                 case LFUN_BUFFER_UPDATE: {
3040                         d.asyncBufferProcessing(argument,
3041                                                 doc_buffer,
3042                                                 _("Exporting ..."),
3043                                                 &GuiViewPrivate::compileAndDestroy,
3044                                                 &Buffer::doExport,
3045                                                 0);
3046                         break;
3047                 }
3048                 case LFUN_BUFFER_VIEW: {
3049                         d.asyncBufferProcessing(argument,
3050                                                 doc_buffer,
3051                                                 _("Previewing ..."),
3052                                                 &GuiViewPrivate::previewAndDestroy,
3053                                                 0,
3054                                                 &Buffer::preview);
3055                         break;
3056                 }
3057                 case LFUN_MASTER_BUFFER_UPDATE: {
3058                         d.asyncBufferProcessing(argument,
3059                                                 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3060                                                 docstring(),
3061                                                 &GuiViewPrivate::compileAndDestroy,
3062                                                 &Buffer::doExport,
3063                                                 0);
3064                         break;
3065                 }
3066                 case LFUN_MASTER_BUFFER_VIEW: {
3067                         d.asyncBufferProcessing(argument,
3068                                                 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3069                                                 docstring(),
3070                                                 &GuiViewPrivate::previewAndDestroy,
3071                                                 0, &Buffer::preview);
3072                         break;
3073                 }
3074                 case LFUN_BUFFER_SWITCH: {
3075                         string const file_name = to_utf8(cmd.argument());
3076                         if (!FileName::isAbsolute(file_name)) {
3077                                 dr.setError(true);
3078                                 dr.setMessage(_("Absolute filename expected."));
3079                                 break;
3080                         }
3081
3082                         Buffer * buffer = theBufferList().getBuffer(FileName(file_name));
3083                         if (!buffer) {
3084                                 dr.setError(true);
3085                                 dr.setMessage(_("Document not loaded"));
3086                                 break;
3087                         }
3088
3089                         // Do we open or switch to the buffer in this view ?
3090                         if (workArea(*buffer)
3091                                   || lyxrc.open_buffers_in_tabs || !documentBufferView()) {
3092                                 setBuffer(buffer);
3093                                 break;
3094                         }
3095
3096                         // Look for the buffer in other views
3097                         QList<int> const ids = guiApp->viewIds();
3098                         int i = 0;
3099                         for (; i != ids.size(); ++i) {
3100                                 GuiView & gv = guiApp->view(ids[i]);
3101                                 if (gv.workArea(*buffer)) {
3102                                         gv.activateWindow();
3103                                         gv.setBuffer(buffer);
3104                                         break;
3105                                 }
3106                         }
3107
3108                         // If necessary, open a new window as a last resort
3109                         if (i == ids.size()) {
3110                                 lyx::dispatch(FuncRequest(LFUN_WINDOW_NEW));
3111                                 lyx::dispatch(cmd);
3112                         }
3113                         break;
3114                 }
3115
3116                 case LFUN_BUFFER_NEXT:
3117                         gotoNextOrPreviousBuffer(NEXTBUFFER);
3118                         break;
3119
3120                 case LFUN_BUFFER_PREVIOUS:
3121                         gotoNextOrPreviousBuffer(PREVBUFFER);
3122                         break;
3123
3124                 case LFUN_COMMAND_EXECUTE: {
3125                         bool const show_it = cmd.argument() != "off";
3126                         // FIXME: this is a hack, "minibuffer" should not be
3127                         // hardcoded.
3128                         if (GuiToolbar * t = toolbar("minibuffer")) {
3129                                 t->setVisible(show_it);
3130                                 if (show_it && t->commandBuffer())
3131                                         t->commandBuffer()->setFocus();
3132                         }
3133                         break;
3134                 }
3135                 case LFUN_DROP_LAYOUTS_CHOICE:
3136                         d.layout_->showPopup();
3137                         break;
3138
3139                 case LFUN_MENU_OPEN:
3140                         if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
3141                                 menu->exec(QCursor::pos());
3142                         break;
3143
3144                 case LFUN_FILE_INSERT:
3145                         insertLyXFile(cmd.argument());
3146                         break;
3147
3148                 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
3149                         insertPlaintextFile(cmd.argument(), true);
3150                         break;
3151
3152                 case LFUN_FILE_INSERT_PLAINTEXT:
3153                         insertPlaintextFile(cmd.argument(), false);
3154                         break;
3155
3156                 case LFUN_BUFFER_RELOAD: {
3157                         LASSERT(doc_buffer, break);
3158
3159                         int ret = 0;
3160                         if (!doc_buffer->isClean()) {
3161                                 docstring const file = 
3162                                         makeDisplayPath(doc_buffer->absFileName(), 20);
3163                                 docstring text = bformat(_("Any changes will be lost. "
3164                                         "Are you sure you want to revert to the saved version "
3165                                         "of the document %1$s?"), file);
3166                                 ret = Alert::prompt(_("Revert to saved document?"),
3167                                         text, 1, 1, _("&Revert"), _("&Cancel"));
3168                         }
3169
3170                         if (ret == 0) {
3171                                 doc_buffer->markClean();
3172                                 reloadBuffer();
3173                                 dr.forceBufferUpdate();
3174                         }
3175                         break;
3176                 }
3177
3178                 case LFUN_BUFFER_WRITE:
3179                         LASSERT(doc_buffer, break);
3180                         saveBuffer(*doc_buffer);
3181                         break;
3182
3183                 case LFUN_BUFFER_WRITE_AS:
3184                         LASSERT(doc_buffer, break);
3185                         renameBuffer(*doc_buffer, cmd.argument());
3186                         break;
3187
3188                 case LFUN_BUFFER_WRITE_ALL: {
3189                         Buffer * first = theBufferList().first();
3190                         if (!first)
3191                                 break;
3192                         message(_("Saving all documents..."));
3193                         // We cannot use a for loop as the buffer list cycles.
3194                         Buffer * b = first;
3195                         do {
3196                                 if (!b->isClean()) {
3197                                         saveBuffer(*b);
3198                                         LYXERR(Debug::ACTION, "Saved " << b->absFileName());
3199                                 }
3200                                 b = theBufferList().next(b);
3201                         } while (b != first);
3202                         dr.setMessage(_("All documents saved."));
3203                         break;
3204                 }
3205
3206                 case LFUN_BUFFER_CLOSE:
3207                         closeBuffer();
3208                         break;
3209
3210                 case LFUN_BUFFER_CLOSE_ALL:
3211                         closeBufferAll();
3212                         break;
3213
3214                 case LFUN_TOOLBAR_TOGGLE: {
3215                         string const name = cmd.getArg(0);
3216                         if (GuiToolbar * t = toolbar(name))
3217                                 t->toggle();
3218                         break;
3219                 }
3220
3221                 case LFUN_DIALOG_UPDATE: {
3222                         string const name = to_utf8(cmd.argument());
3223                         if (name == "prefs" || name == "document")
3224                                 updateDialog(name, string());
3225                         else if (name == "paragraph")
3226                                 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
3227                         else if (currentBufferView()) {
3228                                 Inset * inset = currentBufferView()->editedInset(name);
3229                                 // Can only update a dialog connected to an existing inset
3230                                 if (inset) {
3231                                         // FIXME: get rid of this indirection; GuiView ask the inset
3232                                         // if he is kind enough to update itself...
3233                                         FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
3234                                         //FIXME: pass DispatchResult here?
3235                                         inset->dispatch(currentBufferView()->cursor(), fr);
3236                                 }
3237                         } 
3238                         break;
3239                 }
3240
3241                 case LFUN_DIALOG_TOGGLE: {
3242                         if (isDialogVisible(cmd.getArg(0)))
3243                                 dispatch(FuncRequest(LFUN_DIALOG_HIDE, cmd.argument()), dr);
3244                         else
3245                                 dispatch(FuncRequest(LFUN_DIALOG_SHOW, cmd.argument()), dr);
3246                         break;
3247                 }
3248
3249                 case LFUN_DIALOG_DISCONNECT_INSET:
3250                         disconnectDialog(to_utf8(cmd.argument()));
3251                         break;
3252
3253                 case LFUN_DIALOG_HIDE: {
3254                         guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
3255                         break;
3256                 }
3257
3258                 case LFUN_DIALOG_SHOW: {
3259                         string const name = cmd.getArg(0);
3260                         string data = trim(to_utf8(cmd.argument()).substr(name.size()));
3261
3262                         if (name == "character") {
3263                                 data = freefont2string();
3264                                 if (!data.empty())
3265                                         showDialog("character", data);
3266                         } else if (name == "latexlog") {
3267                                 Buffer::LogType type;
3268                                 string const logfile = doc_buffer->logName(&type);
3269                                 switch (type) {
3270                                 case Buffer::latexlog:
3271                                         data = "latex ";
3272                                         break;
3273                                 case Buffer::buildlog:
3274                                         data = "literate ";
3275                                         break;
3276                                 }
3277                                 data += Lexer::quoteString(logfile);
3278                                 showDialog("log", data);
3279                         } else if (name == "vclog") {
3280                                 string const data = "vc " +
3281                                         Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
3282                                 showDialog("log", data);
3283                         } else if (name == "symbols") {
3284                                 data = bv->cursor().getEncoding()->name();
3285                                 if (!data.empty())
3286                                         showDialog("symbols", data);
3287                         // bug 5274
3288                         } else if (name == "prefs" && isFullScreen()) {
3289                                 lfunUiToggle("fullscreen");
3290                                 showDialog("prefs", data);
3291                         } else
3292                                 showDialog(name, data);
3293                         break;
3294                 }
3295
3296                 case LFUN_MESSAGE:
3297                         dr.setMessage(cmd.argument());
3298                         break;
3299
3300                 case LFUN_UI_TOGGLE: {
3301                         string arg = cmd.getArg(0);
3302                         if (!lfunUiToggle(arg)) {
3303                                 docstring const msg = "ui-toggle " + _("%1$s unknown command!");
3304                                 dr.setMessage(bformat(msg, from_utf8(arg)));
3305                         }
3306                         // Make sure the keyboard focus stays in the work area.
3307                         setFocus();
3308                         break;
3309                 }
3310
3311                 case LFUN_SPLIT_VIEW: {
3312                         LASSERT(doc_buffer, break);
3313                         string const orientation = cmd.getArg(0);
3314                         d.splitter_->setOrientation(orientation == "vertical"
3315                                 ? Qt::Vertical : Qt::Horizontal);
3316                         TabWorkArea * twa = addTabWorkArea();
3317                         GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
3318                         setCurrentWorkArea(wa);
3319                         break;
3320                 }
3321                 case LFUN_CLOSE_TAB_GROUP:
3322                         if (TabWorkArea * twa = d.currentTabWorkArea()) {
3323                                 closeTabWorkArea(twa);
3324                                 d.current_work_area_ = 0;
3325                                 twa = d.currentTabWorkArea();
3326                                 // Switch to the next GuiWorkArea in the found TabWorkArea.
3327                                 if (twa) {
3328                                         // Make sure the work area is up to date.
3329                                         setCurrentWorkArea(twa->currentWorkArea());
3330                                 } else {
3331                                         setCurrentWorkArea(0);
3332                                 }
3333                         }
3334                         break;
3335
3336                 case LFUN_COMPLETION_INLINE:
3337                         if (d.current_work_area_)
3338                                 d.current_work_area_->completer().showInline();
3339                         break;
3340
3341                 case LFUN_COMPLETION_POPUP:
3342                         if (d.current_work_area_)
3343                                 d.current_work_area_->completer().showPopup();
3344                         break;
3345
3346
3347                 case LFUN_COMPLETION_COMPLETE:
3348                         if (d.current_work_area_)
3349                                 d.current_work_area_->completer().tab();
3350                         break;
3351
3352                 case LFUN_COMPLETION_CANCEL:
3353                         if (d.current_work_area_) {
3354                                 if (d.current_work_area_->completer().popupVisible())
3355                                         d.current_work_area_->completer().hidePopup();
3356                                 else
3357                                         d.current_work_area_->completer().hideInline();
3358                         }
3359                         break;
3360
3361                 case LFUN_COMPLETION_ACCEPT:
3362                         if (d.current_work_area_)
3363                                 d.current_work_area_->completer().activate();
3364                         break;
3365
3366                 case LFUN_BUFFER_ZOOM_IN:
3367                 case LFUN_BUFFER_ZOOM_OUT:
3368                         if (cmd.argument().empty()) {
3369                                 if (cmd.action() == LFUN_BUFFER_ZOOM_IN)
3370                                         lyxrc.zoom += 20;
3371                                 else
3372                                         lyxrc.zoom -= 20;
3373                         } else
3374                                 lyxrc.zoom += convert<int>(cmd.argument());
3375
3376                         if (lyxrc.zoom < 10)
3377                                 lyxrc.zoom = 10;
3378
3379                         // The global QPixmapCache is used in GuiPainter to cache text
3380                         // painting so we must reset it.
3381                         QPixmapCache::clear();
3382                         guiApp->fontLoader().update();
3383                         lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3384                         break;
3385
3386                 case LFUN_VC_REGISTER:
3387                 case LFUN_VC_CHECK_IN:
3388                 case LFUN_VC_CHECK_OUT:
3389                 case LFUN_VC_REPO_UPDATE:
3390                 case LFUN_VC_LOCKING_TOGGLE:
3391                 case LFUN_VC_REVERT:
3392                 case LFUN_VC_UNDO_LAST:
3393                 case LFUN_VC_COMMAND:
3394                 case LFUN_VC_COMPARE:
3395                         dispatchVC(cmd, dr);
3396                         break;
3397
3398                 case LFUN_SERVER_GOTO_FILE_ROW:
3399                         goToFileRow(to_utf8(cmd.argument()));
3400                         break;
3401
3402                 case LFUN_FORWARD_SEARCH: {
3403                         FileName const path(doc_buffer->temppath());
3404                         string const texname = doc_buffer->latexName();
3405                         FileName const dviname(addName(path.absFileName(),
3406                                     support::changeExtension(texname, "dvi")));
3407                         FileName const pdfname(addName(path.absFileName(),
3408                                     support::changeExtension(texname, "pdf")));
3409                         if (!dviname.exists() && !pdfname.exists()) {
3410                                 dr.setMessage(_("Please, preview the document first."));
3411                                 break;
3412                         }
3413                         string outname = dviname.onlyFileName();
3414                         string command = lyxrc.forward_search_dvi;
3415                         if (!dviname.exists() ||
3416                             pdfname.lastModified() > dviname.lastModified()) {
3417                                 outname = pdfname.onlyFileName();
3418                                 command = lyxrc.forward_search_pdf;
3419                         }
3420
3421                         int row = doc_buffer->texrow().getRowFromIdPos(bv->cursor().paragraph().id(), bv->cursor().pos());
3422                         LYXERR(Debug::ACTION, "Forward search: row:" << row
3423                                 << " id:" << bv->cursor().paragraph().id());
3424                         if (!row || command.empty()) {
3425                                 dr.setMessage(_("Couldn't proceed."));
3426                                 break;
3427                         }
3428                         string texrow = convert<string>(row);
3429
3430                         command = subst(command, "$$n", texrow);
3431                         command = subst(command, "$$t", texname);
3432                         command = subst(command, "$$o", outname);
3433
3434                         PathChanger p(path);
3435                         Systemcall one;
3436                         one.startscript(Systemcall::DontWait, command);
3437                         break;
3438                 }
3439                 default:
3440                         dr.dispatched(false);
3441                         break;
3442         }
3443
3444         // Part of automatic menu appearance feature.
3445         if (isFullScreen()) {
3446                 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3447                         menuBar()->hide();
3448                 if (statusBar()->isVisible())
3449                         statusBar()->hide();
3450         }
3451
3452         return;
3453 }
3454
3455
3456 bool GuiView::lfunUiToggle(string const & ui_component)
3457 {
3458         if (ui_component == "scrollbar") {
3459                 // hide() is of no help
3460                 if (d.current_work_area_->verticalScrollBarPolicy() ==
3461                         Qt::ScrollBarAlwaysOff)
3462
3463                         d.current_work_area_->setVerticalScrollBarPolicy(
3464                                 Qt::ScrollBarAsNeeded);
3465                 else
3466                         d.current_work_area_->setVerticalScrollBarPolicy(
3467                                 Qt::ScrollBarAlwaysOff);
3468         } else if (ui_component == "statusbar") {
3469                 statusBar()->setVisible(!statusBar()->isVisible());
3470         } else if (ui_component == "menubar") {
3471                 menuBar()->setVisible(!menuBar()->isVisible());
3472         } else
3473 #if QT_VERSION >= 0x040300
3474         if (ui_component == "frame") {
3475                 int l, t, r, b;
3476                 getContentsMargins(&l, &t, &r, &b);
3477                 //are the frames in default state?
3478                 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3479                 if (l == 0) {
3480                         setContentsMargins(-2, -2, -2, -2);
3481                 } else {
3482                         setContentsMargins(0, 0, 0, 0);
3483                 }
3484         } else
3485 #endif
3486         if (ui_component == "fullscreen") {
3487                 toggleFullScreen();
3488         } else
3489                 return false;
3490         return true;
3491 }
3492
3493
3494 void GuiView::toggleFullScreen()
3495 {
3496         if (isFullScreen()) {
3497                 for (int i = 0; i != d.splitter_->count(); ++i)
3498                         d.tabWorkArea(i)->setFullScreen(false);
3499 #if QT_VERSION >= 0x040300
3500                 setContentsMargins(0, 0, 0, 0);
3501 #endif
3502                 setWindowState(windowState() ^ Qt::WindowFullScreen);
3503                 restoreLayout();
3504                 menuBar()->show();
3505                 statusBar()->show();
3506         } else {
3507                 // bug 5274
3508                 hideDialogs("prefs", 0);
3509                 for (int i = 0; i != d.splitter_->count(); ++i)
3510                         d.tabWorkArea(i)->setFullScreen(true);
3511 #if QT_VERSION >= 0x040300
3512                 setContentsMargins(-2, -2, -2, -2);
3513 #endif
3514                 saveLayout();
3515                 setWindowState(windowState() ^ Qt::WindowFullScreen);
3516                 statusBar()->hide();
3517                 if (lyxrc.full_screen_menubar)
3518                         menuBar()->hide();
3519                 if (lyxrc.full_screen_toolbars) {
3520                         ToolbarMap::iterator end = d.toolbars_.end();
3521                         for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3522                                 it->second->hide();
3523                 }
3524         }
3525
3526         // give dialogs like the TOC a chance to adapt
3527         updateDialogs();
3528 }
3529
3530
3531 Buffer const * GuiView::updateInset(Inset const * inset)
3532 {
3533         if (!inset)
3534                 return 0;
3535
3536         Buffer const * inset_buffer = &(inset->buffer());
3537
3538         for (int i = 0; i != d.splitter_->count(); ++i) {
3539                 GuiWorkArea * wa = d.tabWorkArea(i)->currentWorkArea();
3540                 if (!wa)
3541                         continue;
3542                 Buffer const * buffer = &(wa->bufferView().buffer());
3543                 if (inset_buffer == buffer)
3544                         wa->scheduleRedraw();
3545         }
3546         return inset_buffer;
3547 }
3548
3549
3550 void GuiView::restartCursor()
3551 {
3552         /* When we move around, or type, it's nice to be able to see
3553          * the cursor immediately after the keypress.
3554          */
3555         if (d.current_work_area_)
3556                 d.current_work_area_->startBlinkingCursor();
3557
3558         // Take this occasion to update the other GUI elements.
3559         updateDialogs();
3560         updateStatusBar();
3561 }
3562
3563
3564 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3565 {
3566         if (d.current_work_area_)
3567                 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3568 }
3569
3570 namespace {
3571
3572 // This list should be kept in sync with the list of insets in
3573 // src/insets/Inset.cpp.  I.e., if a dialog goes with an inset, the
3574 // dialog should have the same name as the inset.
3575 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3576 // docs in LyXAction.cpp.
3577
3578 char const * const dialognames[] = {
3579
3580 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3581 "citation", "compare", "comparehistory", "document", "errorlist", "ert",
3582 "external", "file", "findreplace", "findreplaceadv", "float", "graphics",
3583 "href", "include", "index", "index_print", "info", "listings", "label", "line",
3584 "log", "mathdelimiter", "mathmatrix", "mathspace", "nomenclature",
3585 "nomencl_print", "note", "paragraph", "phantom", "prefs", "print", "ref",
3586 "sendto", "space", "spellchecker", "symbols", "tabular", "tabularcreate",
3587 "thesaurus", "texinfo", "toc", "view-source", "vspace", "wrap", "progress"};
3588
3589 char const * const * const end_dialognames =
3590         dialognames + (sizeof(dialognames) / sizeof(char *));
3591
3592 class cmpCStr {
3593 public:
3594         cmpCStr(char const * name) : name_(name) {}
3595         bool operator()(char const * other) {
3596                 return strcmp(other, name_) == 0;
3597         }
3598 private:
3599         char const * name_;
3600 };
3601
3602
3603 bool isValidName(string const & name)
3604 {
3605         return find_if(dialognames, end_dialognames,
3606                                 cmpCStr(name.c_str())) != end_dialognames;
3607 }
3608
3609 } // namespace anon
3610
3611
3612 void GuiView::resetDialogs()
3613 {
3614         // Make sure that no LFUN uses any GuiView.
3615         guiApp->setCurrentView(0);
3616         saveLayout();
3617         menuBar()->clear();
3618         constructToolbars();
3619         guiApp->menus().fillMenuBar(menuBar(), this, false);
3620         d.layout_->updateContents(true);
3621         // Now update controls with current buffer.
3622         guiApp->setCurrentView(this);
3623         restoreLayout();
3624         restartCursor();
3625 }
3626
3627
3628 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3629 {
3630         if (!isValidName(name))
3631                 return 0;
3632
3633         map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3634
3635         if (it != d.dialogs_.end()) {
3636                 if (hide_it)
3637                         it->second->hideView();
3638                 return it->second.get();
3639         }
3640
3641         Dialog * dialog = build(name);
3642         d.dialogs_[name].reset(dialog);
3643         if (lyxrc.allow_geometry_session)
3644                 dialog->restoreSession();
3645         if (hide_it)
3646                 dialog->hideView();
3647         return dialog;
3648 }
3649
3650
3651 void GuiView::showDialog(string const & name, string const & data,
3652         Inset * inset)
3653 {
3654         triggerShowDialog(toqstr(name), toqstr(data), inset);
3655 }
3656
3657
3658 void GuiView::doShowDialog(QString const & qname, QString const & qdata,
3659         Inset * inset)
3660 {
3661         if (d.in_show_)
3662                 return;
3663
3664         const string name = fromqstr(qname);
3665         const string data = fromqstr(qdata);
3666
3667         d.in_show_ = true;
3668         try {
3669                 Dialog * dialog = findOrBuild(name, false);
3670                 if (dialog) {
3671                         bool const visible = dialog->isVisibleView();
3672                         dialog->showData(data);
3673                         if (inset && currentBufferView())
3674                                 currentBufferView()->editInset(name, inset);
3675                         // We only set the focus to the new dialog if it was not yet
3676                         // visible in order not to change the existing previous behaviour
3677                         if (visible) {
3678                                 // activateWindow is needed for floating dockviews
3679                                 dialog->asQWidget()->raise();
3680                                 dialog->asQWidget()->activateWindow();
3681                                 dialog->asQWidget()->setFocus();
3682                         }
3683                 }
3684         }
3685         catch (ExceptionMessage const & ex) {
3686                 d.in_show_ = false;
3687                 throw ex;
3688         }
3689         d.in_show_ = false;
3690 }
3691
3692
3693 bool GuiView::isDialogVisible(string const & name) const
3694 {
3695         map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3696         if (it == d.dialogs_.end())
3697                 return false;
3698         return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3699 }
3700
3701
3702 void GuiView::hideDialog(string const & name, Inset * inset)
3703 {
3704         map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3705         if (it == d.dialogs_.end())
3706                 return;
3707
3708         if (inset && currentBufferView()
3709                 && inset != currentBufferView()->editedInset(name))
3710                 return;
3711
3712         Dialog * const dialog = it->second.get();
3713         if (dialog->isVisibleView())
3714                 dialog->hideView();
3715         if (currentBufferView())
3716                 currentBufferView()->editInset(name, 0);
3717 }
3718
3719
3720 void GuiView::disconnectDialog(string const & name)
3721 {
3722         if (!isValidName(name))
3723                 return;
3724         if (currentBufferView())
3725                 currentBufferView()->editInset(name, 0);
3726 }
3727
3728
3729 void GuiView::hideAll() const
3730 {
3731         map<string, DialogPtr>::const_iterator it  = d.dialogs_.begin();
3732         map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3733
3734         for(; it != end; ++it)
3735                 it->second->hideView();
3736 }
3737
3738
3739 void GuiView::updateDialogs()
3740 {
3741         map<string, DialogPtr>::const_iterator it  = d.dialogs_.begin();
3742         map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3743
3744         for(; it != end; ++it) {
3745                 Dialog * dialog = it->second.get();
3746                 if (dialog) {
3747                         if (dialog->needBufferOpen() && !documentBufferView())
3748                                 hideDialog(fromqstr(dialog->name()), 0);
3749                         else if (dialog->isVisibleView())
3750                                 dialog->checkStatus();
3751                 }
3752         }
3753         updateToolbars();
3754         updateLayoutList();
3755 }
3756
3757 Dialog * createDialog(GuiView & lv, string const & name);
3758
3759 // will be replaced by a proper factory...
3760 Dialog * createGuiAbout(GuiView & lv);
3761 Dialog * createGuiBibtex(GuiView & lv);
3762 Dialog * createGuiChanges(GuiView & lv);
3763 Dialog * createGuiCharacter(GuiView & lv);
3764 Dialog * createGuiCitation(GuiView & lv);
3765 Dialog * createGuiCompare(GuiView & lv);
3766 Dialog * createGuiCompareHistory(GuiView & lv);
3767 Dialog * createGuiDelimiter(GuiView & lv);
3768 Dialog * createGuiDocument(GuiView & lv);
3769 Dialog * createGuiErrorList(GuiView & lv);
3770 Dialog * createGuiExternal(GuiView & lv);
3771 Dialog * createGuiGraphics(GuiView & lv);
3772 Dialog * createGuiInclude(GuiView & lv);
3773 Dialog * createGuiIndex(GuiView & lv);
3774 Dialog * createGuiLabel(GuiView & lv);
3775 Dialog * createGuiListings(GuiView & lv);
3776 Dialog * createGuiLog(GuiView & lv);
3777 Dialog * createGuiMathMatrix(GuiView & lv);
3778 Dialog * createGuiNomenclature(GuiView & lv);
3779 Dialog * createGuiNote(GuiView & lv);
3780 Dialog * createGuiParagraph(GuiView & lv);
3781 Dialog * createGuiPhantom(GuiView & lv);
3782 Dialog * createGuiPreferences(GuiView & lv);
3783 Dialog * createGuiPrint(GuiView & lv);
3784 Dialog * createGuiPrintindex(GuiView & lv);
3785 Dialog * createGuiPrintNomencl(GuiView & lv);
3786 Dialog * createGuiRef(GuiView & lv);
3787 Dialog * createGuiSearch(GuiView & lv);
3788 Dialog * createGuiSearchAdv(GuiView & lv);
3789 Dialog * createGuiSendTo(GuiView & lv);
3790 Dialog * createGuiShowFile(GuiView & lv);
3791 Dialog * createGuiSpellchecker(GuiView & lv);
3792 Dialog * createGuiSymbols(GuiView & lv);
3793 Dialog * createGuiTabularCreate(GuiView & lv);
3794 Dialog * createGuiTexInfo(GuiView & lv);
3795 Dialog * createGuiToc(GuiView & lv);
3796 Dialog * createGuiThesaurus(GuiView & lv);
3797 Dialog * createGuiHyperlink(GuiView & lv);
3798 Dialog * createGuiViewSource(GuiView & lv);
3799 Dialog * createGuiWrap(GuiView & lv);
3800 Dialog * createGuiProgressView(GuiView & lv);
3801
3802
3803
3804 Dialog * GuiView::build(string const & name)
3805 {
3806         LASSERT(isValidName(name), return 0);
3807
3808         Dialog * dialog = createDialog(*this, name);
3809         if (dialog)
3810                 return dialog;
3811
3812         if (name == "aboutlyx")
3813                 return createGuiAbout(*this);
3814         if (name == "bibtex")
3815                 return createGuiBibtex(*this);
3816         if (name == "changes")
3817                 return createGuiChanges(*this);
3818         if (name == "character")
3819                 return createGuiCharacter(*this);
3820         if (name == "citation")
3821                 return createGuiCitation(*this);
3822         if (name == "compare")
3823                 return createGuiCompare(*this);
3824         if (name == "comparehistory")
3825                 return createGuiCompareHistory(*this);
3826         if (name == "document")
3827                 return createGuiDocument(*this);
3828         if (name == "errorlist")
3829                 return createGuiErrorList(*this);
3830         if (name == "external")
3831                 return createGuiExternal(*this);
3832         if (name == "file")
3833                 return createGuiShowFile(*this);
3834         if (name == "findreplace")
3835                 return createGuiSearch(*this);
3836         if (name == "findreplaceadv")
3837                 return createGuiSearchAdv(*this);
3838         if (name == "graphics")
3839                 return createGuiGraphics(*this);
3840         if (name == "href")
3841                 return createGuiHyperlink(*this);
3842         if (name == "include")
3843                 return createGuiInclude(*this);
3844         if (name == "index")
3845                 return createGuiIndex(*this);
3846         if (name == "index_print")
3847                 return createGuiPrintindex(*this);
3848         if (name == "label")
3849                 return createGuiLabel(*this);
3850         if (name == "listings")
3851                 return createGuiListings(*this);
3852         if (name == "log")
3853                 return createGuiLog(*this);
3854         if (name == "mathdelimiter")
3855                 return createGuiDelimiter(*this);
3856         if (name == "mathmatrix")
3857                 return createGuiMathMatrix(*this);
3858         if (name == "nomenclature")
3859                 return createGuiNomenclature(*this);
3860         if (name == "nomencl_print")
3861                 return createGuiPrintNomencl(*this);
3862         if (name == "note")
3863                 return createGuiNote(*this);
3864         if (name == "paragraph")
3865                 return createGuiParagraph(*this);
3866         if (name == "phantom")
3867                 return createGuiPhantom(*this);
3868         if (name == "prefs")
3869                 return createGuiPreferences(*this);
3870         if (name == "print")
3871                 return createGuiPrint(*this);
3872         if (name == "ref")
3873                 return createGuiRef(*this);
3874         if (name == "sendto")
3875                 return createGuiSendTo(*this);
3876         if (name == "spellchecker")
3877                 return createGuiSpellchecker(*this);
3878         if (name == "symbols")
3879                 return createGuiSymbols(*this);
3880         if (name == "tabularcreate")
3881                 return createGuiTabularCreate(*this);
3882         if (name == "texinfo")
3883                 return createGuiTexInfo(*this);
3884         if (name == "thesaurus")
3885                 return createGuiThesaurus(*this);
3886         if (name == "toc")
3887                 return createGuiToc(*this);
3888         if (name == "view-source")
3889                 return createGuiViewSource(*this);
3890         if (name == "wrap")
3891                 return createGuiWrap(*this);
3892         if (name == "progress")
3893                 return createGuiProgressView(*this);
3894
3895         return 0;
3896 }
3897
3898
3899 } // namespace frontend
3900 } // namespace lyx
3901
3902 #include "moc_GuiView.cpp"