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