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