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