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