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