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