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