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