]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiView.cpp
Push latest Andre's changes toward their true direction:
[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 "GuiImplementation.h"
19 #include "GuiWorkArea.h"
20 #include "GuiKeySymbol.h"
21 #include "GuiMenubar.h"
22 #include "GuiToolbar.h"
23 #include "GuiToolbars.h"
24 #include "Dialogs.h"
25 #include "Gui.h"
26
27 #include "qt_helpers.h"
28
29 #include "frontends/Application.h"
30 #include "frontends/Dialogs.h"
31 #include "frontends/Gui.h"
32
33 #include "support/filetools.h"
34 #include "support/convert.h"
35 #include "support/lstrings.h"
36 #include "support/os.h"
37
38 #include "buffer_funcs.h"
39 #include "Buffer.h"
40 #include "BufferList.h"
41 #include "BufferParams.h"
42 #include "BufferView.h"
43 #include "Cursor.h"
44 #include "debug.h"
45 #include "ErrorList.h"
46 #include "FuncRequest.h"
47 #include "gettext.h"
48 #include "Intl.h"
49 #include "Layout.h"
50 #include "LyXFunc.h"
51 #include "LyX.h"
52 #include "LyXRC.h"
53 #include "MenuBackend.h"
54 #include "Paragraph.h"
55 #include "Session.h"
56 #include "TextClass.h"
57 #include "Text.h"
58 #include "ToolbarBackend.h"
59 #include "version.h"
60
61 #include "support/lstrings.h"
62 #include "support/filetools.h" // OnlyFilename()
63 #include "support/Timeout.h"
64
65 #include <QAction>
66 #include <QApplication>
67 #include <QCloseEvent>
68 #include <QDesktopWidget>
69 #include <QDragEnterEvent>
70 #include <QDropEvent>
71 #include <QList>
72 #include <QMenu>
73 #include <QPainter>
74 #include <QPixmap>
75 #include <QPushButton>
76 #include <QSplitter>
77 #include <QStackedWidget>
78 #include <QStatusBar>
79 #include <QToolBar>
80 #include <QUrl>
81
82 #include <boost/bind.hpp>
83 #include <boost/current_function.hpp>
84
85 #ifdef HAVE_SYS_TIME_H
86 # include <sys/time.h>
87 #endif
88 #ifdef HAVE_UNISTD_H
89 # include <unistd.h>
90 #endif
91
92 using std::endl;
93 using std::string;
94 using std::vector;
95
96 namespace lyx {
97
98 extern bool quitting;
99
100 namespace frontend {
101
102 using support::bformat;
103 using support::FileName;
104 using support::makeDisplayPath;
105 using support::onlyFilename;
106
107 namespace {
108
109 int const statusbar_timer_value = 3000;
110
111 class BackgroundWidget : public QWidget
112 {
113 public:
114         BackgroundWidget(QString const & file, QString const & text)
115         {
116                 splash_ = new QPixmap(file);
117                 if (!splash_) {
118                         lyxerr << "could not load splash screen: '" << fromqstr(file) << "'" << endl;
119                         return;
120                 }
121
122                 QPainter pain(splash_);
123                 pain.setPen(QColor(255, 255, 0));
124                 QFont font;
125                 // The font used to display the version info
126                 font.setStyleHint(QFont::SansSerif);
127                 font.setWeight(QFont::Bold);
128                 font.setPointSize(convert<int>(lyxrc.font_sizes[FONT_SIZE_LARGE]));
129                 pain.setFont(font);
130                 pain.drawText(260, 270, text);
131         }
132
133         void paintEvent(QPaintEvent *)
134         {
135                 if (!splash_)
136                         return;
137
138                 int x = (width() - splash_->width()) / 2;
139                 int y = (height() - splash_->height()) / 2;
140                 QPainter pain(this);
141                 pain.drawPixmap(x, y, *splash_);
142         }
143
144 private:
145         QPixmap * splash_;
146 };
147
148 } // namespace anon
149
150
151 struct GuiView::GuiViewPrivate
152 {
153         GuiViewPrivate()
154                 : current_work_area_(0), posx_offset(0), posy_offset(0)
155         {}
156
157         ~GuiViewPrivate()
158         {
159                 delete splitter_;
160                 delete bg_widget_;
161                 delete stack_widget_;
162                 delete menubar_;
163                 delete toolbars_;
164         }
165
166         unsigned int smallIconSize;
167         unsigned int normalIconSize;
168         unsigned int bigIconSize;
169         // static needed by "New Window"
170         static unsigned int lastIconSize;
171
172         QMenu * toolBarPopup(GuiView * parent)
173         {
174                 // FIXME: translation
175                 QMenu * menu = new QMenu(parent);
176                 QActionGroup * iconSizeGroup = new QActionGroup(parent);
177
178                 QAction * smallIcons = new QAction(iconSizeGroup);
179                 smallIcons->setText(qt_("Small-sized icons"));
180                 smallIcons->setCheckable(true);
181                 QObject::connect(smallIcons, SIGNAL(triggered()),
182                         parent, SLOT(smallSizedIcons()));
183                 menu->addAction(smallIcons);
184
185                 QAction * normalIcons = new QAction(iconSizeGroup);
186                 normalIcons->setText(qt_("Normal-sized icons"));
187                 normalIcons->setCheckable(true);
188                 QObject::connect(normalIcons, SIGNAL(triggered()),
189                         parent, SLOT(normalSizedIcons()));
190                 menu->addAction(normalIcons);
191
192                 QAction * bigIcons = new QAction(iconSizeGroup);
193                 bigIcons->setText(qt_("Big-sized icons"));
194                 bigIcons->setCheckable(true);
195                 QObject::connect(bigIcons, SIGNAL(triggered()),
196                         parent, SLOT(bigSizedIcons()));
197                 menu->addAction(bigIcons);
198
199                 unsigned int cur = parent->iconSize().width();
200                 if ( cur == parent->d.smallIconSize)
201                         smallIcons->setChecked(true);
202                 else if (cur == parent->d.normalIconSize)
203                         normalIcons->setChecked(true);
204                 else if (cur == parent->d.bigIconSize)
205                         bigIcons->setChecked(true);
206
207                 return menu;
208         }
209
210         void initBackground()
211         {
212                 LYXERR(Debug::GUI) << "show banner: " << lyxrc.show_banner << endl;
213                 /// The text to be written on top of the pixmap
214                 QString const text = lyx_version ? QString(lyx_version) : qt_("unknown version");
215                 bg_widget_ = new BackgroundWidget(":/images/banner.png", text);
216         }
217
218         void setBackground()
219         {
220                 stack_widget_->setCurrentWidget(bg_widget_);
221                 bg_widget_->setUpdatesEnabled(true);
222         }
223
224         TabWorkArea * tabWorkArea(int i)
225         {
226                 return dynamic_cast<TabWorkArea *>(splitter_->widget(i));
227         }
228
229         TabWorkArea * currentTabWorkArea()
230         {
231                 if (splitter_->count() == 1)
232                         // The first TabWorkArea is always the first one, if any.
233                         return tabWorkArea(0);
234
235                 TabWorkArea * tab_widget = 0;
236                 for (int i = 0; i != splitter_->count(); ++i) {
237                         QWidget * w = splitter_->widget(i);
238                         if (!w->hasFocus())
239                                 continue;
240                         tab_widget = dynamic_cast<TabWorkArea *>(w);
241                         if (tab_widget)
242                                 break;
243                 }
244
245                 return tab_widget;
246         }
247
248 public:
249         ///
250         string cur_title;
251
252         GuiWorkArea * current_work_area_;
253         int posx_offset;
254         int posy_offset;
255
256         QSplitter * splitter_;
257         QStackedWidget * stack_widget_;
258         BackgroundWidget * bg_widget_;
259         /// view's menubar
260         GuiMenubar * menubar_;
261         /// view's toolbars
262         GuiToolbars * toolbars_;
263         ///
264         docstring current_layout;
265 };
266
267
268 unsigned int GuiView::GuiViewPrivate::lastIconSize = 0;
269
270
271 GuiView::GuiView(int id)
272         : QMainWindow(), LyXView(id),
273           d(*new GuiViewPrivate),
274                 quitting_by_menu_(false),
275                 autosave_timeout_(new Timeout(5000)),
276           dialogs_(new Dialogs(*this))
277 {
278         // Start autosave timer
279         if (lyxrc.autosave) {
280                 autosave_timeout_->timeout.connect(boost::bind(&GuiView::autoSave, this));
281                 autosave_timeout_->setTimeout(lyxrc.autosave * 1000);
282                 autosave_timeout_->start();
283         }
284
285         // Qt bug? signal lastWindowClosed does not work
286         setAttribute(Qt::WA_QuitOnClose, false);
287         setAttribute(Qt::WA_DeleteOnClose, true);
288
289         // hardcode here the platform specific icon size
290         d.smallIconSize = 14;   // scaling problems
291         d.normalIconSize = 20;  // ok, default
292         d.bigIconSize = 26;             // better for some math icons
293
294 #ifndef Q_WS_MACX
295         // assign an icon to main form. We do not do it under Qt/Mac,
296         // since the icon is provided in the application bundle.
297         setWindowIcon(QPixmap(":/images/lyx.png"));
298 #endif
299
300
301         d.splitter_ = new QSplitter;
302
303         d.initBackground();
304         LYXERR(Debug::GUI) << "stack widget!" << endl;
305         d.stack_widget_ = new QStackedWidget;
306         d.stack_widget_->addWidget(d.bg_widget_);
307         d.stack_widget_->addWidget(d.splitter_);
308         setCentralWidget(d.stack_widget_);
309
310         // For Drag&Drop.
311         setAcceptDrops(true);
312 }
313
314
315 GuiView::~GuiView()
316 {
317         delete dialogs_;
318         delete autosave_timeout_;
319         delete &d;
320 }
321
322
323 void GuiView::close()
324 {
325         quitting_by_menu_ = true;
326         d.current_work_area_ = 0;
327         for (int i = 0; i != d.splitter_->count(); ++i) {
328                 TabWorkArea * twa = d.tabWorkArea(i);
329                 if (twa)
330                         twa->closeAll();
331         }
332         QMainWindow::close();
333         quitting_by_menu_ = false;
334 }
335
336
337 void GuiView::setFocus()
338 {
339         if (d.current_work_area_)
340                 d.current_work_area_->setFocus();
341         else
342                 QWidget::setFocus();
343 }
344
345
346 QMenu* GuiView::createPopupMenu()
347 {
348         return d.toolBarPopup(this);
349 }
350
351
352 void GuiView::init()
353 {
354         // GuiToolbars *must* be initialised before GuiMenubar.
355         d.toolbars_ = new GuiToolbars(*this);
356         // FIXME: GuiToolbars::init() cannot be integrated in the ctor
357         // because LyXFunc::getStatus() needs a properly initialized
358         // GuiToolbars object (for LFUN_TOOLBAR_TOGGLE).
359         d.toolbars_->init();
360         d.menubar_ = new GuiMenubar(this, menubackend);
361
362         statusBar()->setSizeGripEnabled(true);
363
364         QObject::connect(&statusbar_timer_, SIGNAL(timeout()),
365                 this, SLOT(update_view_state_qt()));
366
367         d.setBackground();
368 }
369
370
371 void GuiView::closeEvent(QCloseEvent * close_event)
372 {
373         // we may have been called through the close window button
374         // which bypasses the LFUN machinery.
375         if (!quitting_by_menu_ && theApp()->gui().viewIds().size() == 1) {
376                 if (!theBufferList().quitWriteAll()) {
377                         close_event->ignore();
378                         return;
379                 }
380         }
381
382         // Make sure that no LFUN use this close to be closed View.
383         theLyXFunc().setLyXView(0);
384         // Make sure the timer time out will not trigger a statusbar update.
385         statusbar_timer_.stop();
386
387         theApp()->gui().unregisterView(id());
388         if (!theApp()->gui().viewIds().empty()) {
389                 // Just close the window and do nothing else if this is not the
390                 // last window.
391                 close_event->accept();
392                 return;
393         }
394
395         quitting = true;
396
397         // this is the place where we leave the frontend.
398         // it is the only point at which we start quitting.
399         saveGeometry();
400         close_event->accept();
401         // quit the event loop
402         qApp->quit();
403 }
404
405
406 void GuiView::dragEnterEvent(QDragEnterEvent * event)
407 {
408         if (event->mimeData()->hasUrls())
409                 event->accept();
410         /// \todo Ask lyx-devel is this is enough:
411         /// if (event->mimeData()->hasFormat("text/plain"))
412         ///     event->acceptProposedAction();
413 }
414
415
416 void GuiView::dropEvent(QDropEvent* event)
417 {
418         QList<QUrl> files = event->mimeData()->urls();
419         if (files.isEmpty())
420                 return;
421
422         LYXERR(Debug::GUI) << BOOST_CURRENT_FUNCTION
423                 << " got URLs!" << endl;
424         for (int i = 0; i != files.size(); ++i) {
425                 string const file = support::os::internal_path(fromqstr(
426                         files.at(i).toLocalFile()));
427                 if (!file.empty())
428                         dispatch(FuncRequest(LFUN_FILE_OPEN, file));
429         }
430 }
431
432
433 void GuiView::saveGeometry()
434 {
435         static bool done = false;
436         if (done)
437                 return;
438         else
439                 done = true;
440
441         // FIXME:
442         // change the ifdef to 'geometry = normalGeometry();' only
443         // when Trolltech has fixed the broken normalGeometry on X11:
444         // http://www.trolltech.com/developer/task-tracker/index_html?id=119684+&method=entry
445         // Then also the moveEvent, resizeEvent, and the
446         // code for floatingGeometry_ can be removed;
447         // adjust GuiView::setGeometry()
448
449         QRect normal_geometry;
450         int maximized;
451 #ifdef Q_WS_WIN
452         normal_geometry = normalGeometry();
453         if (isMaximized()) {
454                 maximized = CompletelyMaximized;
455         } else {
456                 maximized = NotMaximized;
457         }
458 #else
459         normal_geometry = updateFloatingGeometry();
460
461         QDesktopWidget& dw = *qApp->desktop();
462         QRect desk = dw.availableGeometry(dw.primaryScreen());
463         // Qt bug on Linux: load completely maximized, vert max. save-> frameGeometry().height() is wrong
464         if (isMaximized() && desk.width() <= frameGeometry().width() && desk.height() <= frameGeometry().height()) {
465                 maximized = CompletelyMaximized;
466                 // maximizing does not work when the window is allready hor. or vert. maximized
467                 // Tested only on KDE
468                 int dh = frameGeometry().height() - height();
469                 if (desk.height() <= normal_geometry.height() + dh)
470                         normal_geometry.setHeight(normal_geometry.height() - 1);
471                 int dw = frameGeometry().width() - width();
472                 if (desk.width() <= normal_geometry.width() + dw)
473                         normal_geometry.setWidth(normal_geometry.width() - 1);
474         } else if (desk.height() <= frameGeometry().height()) {
475                 maximized = VerticallyMaximized;
476         } else if (desk.width() <= frameGeometry().width()) {
477                 maximized = HorizontallyMaximized;
478         } else {
479                 maximized = NotMaximized;
480         }
481 #endif
482
483         // save windows size and position
484         SessionInfoSection & info = LyX::ref().session().sessionInfo();
485         info.save("WindowWidth", convert<string>(normal_geometry.width()));
486         info.save("WindowHeight", convert<string>(normal_geometry.height()));
487         info.save("WindowMaximized", convert<string>(maximized));
488         info.save("IconSizeXY", convert<string>(iconSize().width()));
489         if (lyxrc.geometry_xysaved) {
490                 info.save("WindowPosX", convert<string>(normal_geometry.x() + d.posx_offset));
491                 info.save("WindowPosY", convert<string>(normal_geometry.y() + d.posy_offset));
492         }
493         d.toolbars_->saveToolbarInfo();
494 }
495
496
497 void GuiView::setGeometry(unsigned int width,
498                           unsigned int height,
499                           int posx, int posy,
500                           int maximized,
501                           unsigned int iconSizeXY,
502                           const string & geometryArg)
503 {
504         // use last value (not at startup)
505         if (d.lastIconSize != 0)
506                 setIconSize(d.lastIconSize);
507         else if (iconSizeXY != 0)
508                 setIconSize(iconSizeXY);
509         else
510                 setIconSize(d.normalIconSize);
511
512         // only true when the -geometry option was NOT used
513         if (width != 0 && height != 0) {
514                 if (posx != -1 && posy != -1) {
515                         // if there are startup positioning problems:
516                         // http://doc.trolltech.com/4.2/qdesktopwidget.html
517                         QDesktopWidget& dw = *qApp->desktop();
518                         if (dw.isVirtualDesktop()) {
519                                 if(!dw.geometry().contains(posx, posy)) {
520                                         posx = 50;
521                                         posy = 50;
522                                 }
523                         } else {
524                                 // Which system doesn't use a virtual desktop?
525                                 // TODO save also last screen number and check if it is still availabe.
526                         }
527 #ifdef Q_WS_WIN
528                         // FIXME: use setGeometry only when Trolltech has fixed the qt4/X11 bug
529                         QWidget::setGeometry(posx, posy, width, height);
530 #else
531                         resize(width, height);
532                         move(posx, posy);
533 #endif
534                 } else {
535                         resize(width, height);
536                 }
537
538                 // remember original size
539                 floatingGeometry_ = QRect(posx, posy, width, height);
540
541                 if (maximized != NotMaximized) {
542                         if (maximized == CompletelyMaximized) {
543                                 setWindowState(Qt::WindowMaximized);
544                         } else {
545 #ifndef Q_WS_WIN
546                                 // TODO How to set by the window manager?
547                                 //      setWindowState(Qt::WindowVerticallyMaximized);
548                                 //      is not possible
549                                 QDesktopWidget& dw = *qApp->desktop();
550                                 QRect desk = dw.availableGeometry(dw.primaryScreen());
551                                 if (maximized == VerticallyMaximized)
552                                         resize(width, desk.height());
553                                 if (maximized == HorizontallyMaximized)
554                                         resize(desk.width(), height);
555 #endif
556                         }
557                 }
558         }
559         else
560         {
561                 // FIXME: move this code into parse_geometry() (LyX.cpp)
562 #ifdef Q_WS_WIN
563                 int x, y;
564                 int w, h;
565                 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
566                 re.indexIn(toqstr(geometryArg.c_str()));
567                 w = re.cap(1).toInt();
568                 h = re.cap(2).toInt();
569                 x = re.cap(3).toInt();
570                 y = re.cap(4).toInt();
571                 QWidget::setGeometry( x, y, w, h );
572 #else
573                 // silence warning
574                 (void)geometryArg;
575 #endif
576         }
577         
578         d.setBackground();
579         
580         show();
581
582         // after show geometry() has changed (Qt bug?)
583         // we compensate the drift when storing the position
584         d.posx_offset = 0;
585         d.posy_offset = 0;
586         if (width != 0 && height != 0)
587                 if (posx != -1 && posy != -1) {
588 #ifdef Q_WS_WIN
589                         d.posx_offset = posx - normalGeometry().x();
590                         d.posy_offset = posy - normalGeometry().y();
591 #else
592 #ifndef Q_WS_MACX
593                         if (maximized == NotMaximized) {
594                                 d.posx_offset = posx - geometry().x();
595                                 d.posy_offset = posy - geometry().y();
596                         }
597 #endif
598 #endif
599                 }
600 }
601
602
603 void GuiView::message(docstring const & str)
604 {
605         statusBar()->showMessage(toqstr(str));
606         statusbar_timer_.stop();
607         statusbar_timer_.start(statusbar_timer_value);
608 }
609
610
611 void GuiView::clearMessage()
612 {
613         update_view_state_qt();
614 }
615
616
617 void GuiView::setIconSize(unsigned int size)
618 {
619         d.lastIconSize = size;
620         QMainWindow::setIconSize(QSize(size, size));
621 }
622
623
624 void GuiView::smallSizedIcons()
625 {
626         setIconSize(d.smallIconSize);
627 }
628
629
630 void GuiView::normalSizedIcons()
631 {
632         setIconSize(d.normalIconSize);
633 }
634
635
636 void GuiView::bigSizedIcons()
637 {
638         setIconSize(d.bigIconSize);
639 }
640
641
642 void GuiView::update_view_state_qt()
643 {
644         if (!hasFocus())
645                 return;
646         theLyXFunc().setLyXView(this);
647         statusBar()->showMessage(toqstr(theLyXFunc().viewStatusMessage()));
648         statusbar_timer_.stop();
649 }
650
651
652 void GuiView::updateWindowTitle(GuiWorkArea * wa)
653 {
654         if (wa != d.current_work_area_)
655                 return;
656         setWindowTitle(qt_("LyX: ") + wa->windowTitle());
657         setWindowIconText(wa->windowIconText());
658 }
659
660
661 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
662 {
663         disconnectBuffer();
664         disconnectBufferView();
665         connectBufferView(wa->bufferView());
666         connectBuffer(wa->bufferView().buffer());
667         d.current_work_area_ = wa;
668         QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
669                 this, SLOT(updateWindowTitle(GuiWorkArea *)));
670         updateWindowTitle(wa);
671
672         updateToc();
673         // Buffer-dependent dialogs should be updated or
674         // hidden. This should go here because some dialogs (eg ToC)
675         // require bv_->text.
676         getDialogs().updateBufferDependent(true);
677         updateToolbars();
678         updateLayoutChoice(false);
679         updateStatusBar();
680 }
681
682
683 void GuiView::updateStatusBar()
684 {
685         // let the user see the explicit message
686         if (statusbar_timer_.isActive())
687                 return;
688
689         statusBar()->showMessage(toqstr(theLyXFunc().viewStatusMessage()));
690 }
691
692
693 void GuiView::activated(FuncRequest const & func)
694 {
695         dispatch(func);
696 }
697
698
699 bool GuiView::hasFocus() const
700 {
701         return qApp->activeWindow() == this;
702 }
703
704
705 QRect  GuiView::updateFloatingGeometry()
706 {
707         QDesktopWidget& dw = *qApp->desktop();
708         QRect desk = dw.availableGeometry(dw.primaryScreen());
709         // remember only non-maximized sizes
710         if (!isMaximized() && desk.width() > frameGeometry().width() && desk.height() > frameGeometry().height()) {
711                 floatingGeometry_ = QRect(x(), y(), width(), height());
712         }
713         return floatingGeometry_;
714 }
715
716
717 void GuiView::resizeEvent(QResizeEvent *)
718 {
719         updateFloatingGeometry();
720 }
721
722
723 void GuiView::moveEvent(QMoveEvent *)
724 {
725         updateFloatingGeometry();
726 }
727
728
729 bool GuiView::event(QEvent * e)
730 {
731         switch (e->type())
732         {
733         // Useful debug code:
734         //case QEvent::ActivationChange:
735         //case QEvent::WindowDeactivate:
736         //case QEvent::Paint:
737         //case QEvent::Enter:
738         //case QEvent::Leave:
739         //case QEvent::HoverEnter:
740         //case QEvent::HoverLeave:
741         //case QEvent::HoverMove:
742         //case QEvent::StatusTip:
743         //case QEvent::DragEnter:
744         //case QEvent::DragLeave:
745         //case QEvent::Drop:
746         //      break;
747
748         case QEvent::WindowActivate: {
749                 theApp()->setCurrentView(*this);
750                 if (d.current_work_area_) {
751                         BufferView & bv = d.current_work_area_->bufferView();
752                         connectBufferView(bv);
753                         connectBuffer(bv.buffer());
754                         // The document structure, name and dialogs might have
755                         // changed in another view.
756                         getDialogs().updateBufferDependent(true);
757                 } else {
758                         setWindowTitle(qt_("LyX"));
759                         setWindowIconText(qt_("LyX"));
760                 }
761                 return QMainWindow::event(e);
762         }
763         case QEvent::ShortcutOverride: {
764                 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
765                 if (!d.current_work_area_) {
766                         theLyXFunc().setLyXView(this);
767                         KeySymbol sym;
768                         setKeySymbol(&sym, ke);
769                         theLyXFunc().processKeySym(sym, q_key_state(ke->modifiers()));
770                         e->accept();
771                         return true;
772                 }
773                 if (ke->key() == Qt::Key_Tab || ke->key() == Qt::Key_Backtab) {
774                         KeySymbol sym;
775                         setKeySymbol(&sym, ke);
776                         d.current_work_area_->processKeySym(sym, NoModifier);
777                         e->accept();
778                         return true;
779                 }
780         }
781         default:
782                 return QMainWindow::event(e);
783         }
784 }
785
786
787 bool GuiView::focusNextPrevChild(bool /*next*/)
788 {
789         setFocus();
790         return true;
791 }
792
793
794 void GuiView::showView()
795 {
796         setWindowTitle(qt_("LyX"));
797         show();
798         updateFloatingGeometry();
799 }
800
801
802 void GuiView::setBusy(bool yes)
803 {
804         if (d.current_work_area_) {
805                 d.current_work_area_->setUpdatesEnabled(!yes);
806                 if (yes)
807                         d.current_work_area_->stopBlinkingCursor();
808                 else
809                         d.current_work_area_->startBlinkingCursor();
810         }
811
812         if (yes)
813                 QApplication::setOverrideCursor(Qt::WaitCursor);
814         else
815                 QApplication::restoreOverrideCursor();
816 }
817
818
819 GuiToolbar * GuiView::makeToolbar(ToolbarInfo const & tbinfo, bool newline)
820 {
821         GuiToolbar * toolBar = new GuiToolbar(tbinfo, *this);
822
823         if (tbinfo.flags & ToolbarInfo::TOP) {
824                 if (newline)
825                         addToolBarBreak(Qt::TopToolBarArea);
826                 addToolBar(Qt::TopToolBarArea, toolBar);
827         }
828
829         if (tbinfo.flags & ToolbarInfo::BOTTOM) {
830 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
831 #if (QT_VERSION >= 0x040202)
832                 if (newline)
833                         addToolBarBreak(Qt::BottomToolBarArea);
834 #endif
835                 addToolBar(Qt::BottomToolBarArea, toolBar);
836         }
837
838         if (tbinfo.flags & ToolbarInfo::LEFT) {
839 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
840 #if (QT_VERSION >= 0x040202)
841                 if (newline)
842                         addToolBarBreak(Qt::LeftToolBarArea);
843 #endif
844                 addToolBar(Qt::LeftToolBarArea, toolBar);
845         }
846
847         if (tbinfo.flags & ToolbarInfo::RIGHT) {
848 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
849 #if (QT_VERSION >= 0x040202)
850                 if (newline)
851                         addToolBarBreak(Qt::RightToolBarArea);
852 #endif
853                 addToolBar(Qt::RightToolBarArea, toolBar);
854         }
855
856         // The following does not work so I cannot restore to exact toolbar location
857         /*
858         ToolbarSection::ToolbarInfo & tbinfo = LyX::ref().session().toolbars().load(tbinfo.name);
859         toolBar->move(tbinfo.posx, tbinfo.posy);
860         */
861
862         return toolBar;
863 }
864
865
866 GuiWorkArea * GuiView::workArea(Buffer & buffer)
867 {
868         for (int i = 0; i != d.splitter_->count(); ++i) {
869                 GuiWorkArea * wa = d.tabWorkArea(i)->workArea(buffer);
870                 if (wa)
871                         return wa;
872         }
873         return 0;
874 }
875
876
877 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
878 {
879         GuiWorkArea * wa = new GuiWorkArea(buffer, *this);
880         wa->setUpdatesEnabled(false);
881
882         // Automatically create a TabWorkArea if there are none yet.
883         if (!d.splitter_->count())
884                 addTabWorkArea();
885
886         TabWorkArea * tab_widget = d.currentTabWorkArea();
887         tab_widget->addTab(wa, wa->windowTitle());
888         QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
889                 tab_widget, SLOT(updateTabText(GuiWorkArea *)));
890
891         wa->bufferView().updateMetrics();
892
893         // Hide tabbar if there's only one tab.
894         tab_widget->showBar(tab_widget->count() > 1);
895         return wa;
896 }
897
898
899 void GuiView::addTabWorkArea()
900 {
901         TabWorkArea * twa = new TabWorkArea;
902         QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
903                 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
904         d.splitter_->addWidget(twa);
905         d.stack_widget_->setCurrentWidget(d.splitter_);
906 }
907
908
909 GuiWorkArea * GuiView::currentWorkArea()
910 {
911         return d.current_work_area_;
912 }
913
914
915 GuiWorkArea const * GuiView::currentWorkArea() const
916 {
917         return d.current_work_area_;
918 }
919
920
921 void GuiView::setCurrentWorkArea(GuiWorkArea * work_area)
922 {
923         BOOST_ASSERT(work_area);
924
925         // Changing work area can result from opening a file so
926         // update the toc in any case.
927         updateToc();
928
929         GuiWorkArea * wa = static_cast<GuiWorkArea *>(work_area);
930         d.current_work_area_ = wa;
931         for (int i = 0; i != d.splitter_->count(); ++i) {
932                 if (d.tabWorkArea(i)->setCurrentWorkArea(wa))
933                         return;
934         }
935 }
936
937
938 void GuiView::removeWorkArea(GuiWorkArea * work_area)
939 {
940         BOOST_ASSERT(work_area);
941         GuiWorkArea * gwa = static_cast<GuiWorkArea *>(work_area);
942         if (gwa == d.current_work_area_) {
943                 disconnectBuffer();
944                 disconnectBufferView();
945                 getDialogs().hideBufferDependent();
946                 d.current_work_area_ = 0;
947         }
948
949         // removing a work area often results from closing a file so
950         // update the toc in any case.
951         updateToc();
952
953         for (int i = 0; i != d.splitter_->count(); ++i) {
954                 TabWorkArea * twa = d.tabWorkArea(i);
955                 if (!twa->removeWorkArea(gwa))
956                         // Not found in this tab group.
957                         continue;
958
959                 // We found and removed the GuiWorkArea.
960                 if (twa->count()) {
961                         // No more WorkAreas in this tab group, so delete it.
962                         delete twa;
963                         break;
964                 }
965
966                 if (d.current_work_area_)
967                         // This means that we are not closing the current GuiWorkArea;
968                         break;
969
970                 // Switch to the next GuiWorkArea in the found TabWorkArea.
971                 d.current_work_area_ = twa->currentWorkArea();
972                 break;
973         }
974
975         if (d.splitter_->count() == 0)
976                 // No more work area, switch to the background widget.
977                 d.setBackground();
978 }
979
980
981 void GuiView::showMiniBuffer(bool visible)
982 {
983         d.toolbars_->showCommandBuffer(visible);
984 }
985
986
987 void GuiView::openMenu(docstring const & name)
988 {
989         d.menubar_->openByName(toqstr(name));
990 }
991
992
993 void GuiView::openLayoutList()
994 {
995         d.toolbars_->openLayoutList();
996 }
997
998
999 void GuiView::updateLayoutChoice(bool force)
1000 {
1001         // Don't show any layouts without a buffer
1002         if (!buffer()) {
1003                 d.toolbars_->clearLayoutList();
1004                 return;
1005         }
1006
1007         // Update the layout display
1008         if (d.toolbars_->updateLayoutList(buffer()->params().getTextClassPtr(), force)) {
1009                 d.current_layout = buffer()->params().getTextClass().defaultLayoutName();
1010         }
1011
1012         docstring const & layout = d.current_work_area_->bufferView().cursor().
1013                 innerParagraph().layout()->name();
1014
1015         if (layout != d.current_layout) {
1016                 d.toolbars_->setLayout(layout);
1017                 d.current_layout = layout;
1018         }
1019 }
1020
1021
1022 bool GuiView::isToolbarVisible(std::string const & id)
1023 {
1024         return d.toolbars_->visible(id);
1025 }
1026
1027 void GuiView::updateToolbars()
1028 {
1029         if (d.current_work_area_) {
1030                 bool const math =
1031                         d.current_work_area_->bufferView().cursor().inMathed();
1032                 bool const table =
1033                         lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1034                 bool const review =
1035                         lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1036                         lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onoff(true);
1037
1038                 d.toolbars_->update(math, table, review);
1039         } else
1040                 d.toolbars_->update(false, false, false);
1041
1042         // update read-only status of open dialogs.
1043         getDialogs().checkStatus();
1044 }
1045
1046
1047 ToolbarInfo * GuiView::getToolbarInfo(string const & name)
1048 {
1049         return d.toolbars_->getToolbarInfo(name);
1050 }
1051
1052
1053 void GuiView::toggleToolbarState(string const & name, bool allowauto)
1054 {
1055         // it is possible to get current toolbar status like this,...
1056         // but I decide to obey the order of ToolbarBackend::flags
1057         // and disregard real toolbar status.
1058         // toolbars_->saveToolbarInfo();
1059         //
1060         // toggle state on/off/auto
1061         d.toolbars_->toggleToolbarState(name, allowauto);
1062         // update toolbar
1063         updateToolbars();
1064 }
1065
1066
1067 Buffer * GuiView::buffer()
1068 {
1069         if (d.current_work_area_)
1070                 return &d.current_work_area_->bufferView().buffer();
1071         return 0;
1072 }
1073
1074
1075 Buffer const * GuiView::buffer() const
1076 {
1077         if (d.current_work_area_)
1078                 return &d.current_work_area_->bufferView().buffer();
1079         return 0;
1080 }
1081
1082
1083 void GuiView::setBuffer(Buffer * newBuffer)
1084 {
1085         BOOST_ASSERT(newBuffer);
1086         setBusy(true);
1087
1088         GuiWorkArea * wa = workArea(*newBuffer);
1089         if (wa == 0) {
1090                 updateLabels(*newBuffer->masterBuffer());
1091                 wa = addWorkArea(*newBuffer);
1092         } else {
1093                 //Disconnect the old buffer...there's no new one.
1094                 disconnectBuffer();
1095         }
1096         connectBuffer(*newBuffer);
1097         connectBufferView(wa->bufferView());
1098         setCurrentWorkArea(wa);
1099
1100         setBusy(false);
1101 }
1102
1103
1104 Buffer * GuiView::loadLyXFile(FileName const & filename, bool tolastfiles)
1105 {
1106         setBusy(true);
1107
1108         Buffer * newBuffer = checkAndLoadLyXFile(filename);
1109
1110         if (!newBuffer) {
1111                 message(_("Document not loaded."));
1112                 updateStatusBar();
1113                 setBusy(false);
1114                 return 0;
1115         }
1116
1117         GuiWorkArea * wa = workArea(*newBuffer);
1118         if (wa == 0)
1119                 wa = addWorkArea(*newBuffer);
1120
1121         // scroll to the position when the file was last closed
1122         if (lyxrc.use_lastfilepos) {
1123                 LastFilePosSection::FilePos filepos =
1124                         LyX::ref().session().lastFilePos().load(filename);
1125                 // if successfully move to pit (returned par_id is not zero),
1126                 // update metrics and reset font
1127                 wa->bufferView().moveToPosition(filepos.pit, filepos.pos, 0, 0);
1128         }
1129
1130         if (tolastfiles)
1131                 LyX::ref().session().lastFiles().add(filename);
1132
1133         setBusy(false);
1134         return newBuffer;
1135 }
1136
1137
1138 void GuiView::connectBuffer(Buffer & buf)
1139 {
1140         buf.setGuiDelegate(this);
1141 }
1142
1143
1144 void GuiView::disconnectBuffer()
1145 {
1146         if (d.current_work_area_)
1147                 d.current_work_area_->bufferView().setGuiDelegate(0);
1148 }
1149
1150
1151 void GuiView::connectBufferView(BufferView & bv)
1152 {
1153         bv.setGuiDelegate(this);
1154 }
1155
1156
1157 void GuiView::disconnectBufferView()
1158 {
1159         if (d.current_work_area_)
1160                 d.current_work_area_->bufferView().setGuiDelegate(0);
1161 }
1162
1163
1164 void GuiView::errors(string const & error_type)
1165 {
1166         ErrorList & el = buffer()->errorList(error_type);
1167         if (!el.empty())
1168                 getDialogs().show("errorlist", error_type);
1169 }
1170
1171
1172 void GuiView::showDialog(string const & name)
1173 {
1174         getDialogs().show(name);
1175 }
1176
1177
1178 void GuiView::showDialogWithData(string const & name, string const & data)
1179 {
1180         getDialogs().show(name, data);
1181 }
1182
1183
1184 void GuiView::showInsetDialog(string const & name, string const & data,
1185                 Inset * inset)
1186 {
1187         getDialogs().show(name, data, inset);
1188 }
1189
1190
1191 void GuiView::updateDialog(string const & name, string const & data)
1192 {
1193         if (getDialogs().visible(name))
1194                 getDialogs().update(name, data);
1195 }
1196
1197
1198 BufferView * GuiView::view()
1199 {
1200         return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1201 }
1202
1203
1204 void GuiView::updateToc()
1205 {
1206         updateDialog("toc", "");
1207 }
1208
1209
1210 void GuiView::updateEmbeddedFiles()
1211 {
1212         updateDialog("embedding", "");
1213 }
1214
1215
1216 void GuiView::autoSave()
1217 {
1218         LYXERR(Debug::INFO) << "Running autoSave()" << endl;
1219
1220         if (buffer())
1221                 view()->buffer().autoSave();
1222 }
1223
1224
1225 void GuiView::resetAutosaveTimers()
1226 {
1227         if (lyxrc.autosave)
1228                 autosave_timeout_->restart();
1229 }
1230
1231
1232 void GuiView::dispatch(FuncRequest const & cmd)
1233 {
1234         string const argument = to_utf8(cmd.argument());
1235         switch(cmd.action) {
1236                 case LFUN_BUFFER_SWITCH:
1237                         setBuffer(theBufferList().getBuffer(to_utf8(cmd.argument())));
1238                         break;
1239                 default:
1240                         theLyXFunc().setLyXView(this);
1241                         lyx::dispatch(cmd);
1242         }
1243 }
1244
1245
1246 Buffer const * GuiView::updateInset(Inset const * inset)
1247 {
1248         if (!d.current_work_area_)
1249                 return 0;
1250
1251         if (inset)
1252                 d.current_work_area_->scheduleRedraw();
1253
1254         return &d.current_work_area_->bufferView().buffer();
1255 }
1256
1257
1258 void GuiView::restartCursor()
1259 {
1260         /* When we move around, or type, it's nice to be able to see
1261          * the cursor immediately after the keypress.
1262          */
1263         if (d.current_work_area_)
1264                 d.current_work_area_->startBlinkingCursor();
1265 }
1266
1267 } // namespace frontend
1268 } // namespace lyx
1269
1270 #include "GuiView_moc.cpp"