3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
8 * \author Abdelrazak Younes
11 * Full author contact details are available in file CREDITS.
18 #include "GuiImplementation.h"
19 #include "GuiWorkArea.h"
20 #include "QKeySymbol.h"
21 #include "QLMenubar.h"
22 #include "QLToolbar.h"
23 #include "QCommandBuffer.h"
24 #include "qt_helpers.h"
26 #include "frontends/Application.h"
27 #include "frontends/Dialogs.h"
28 #include "frontends/Gui.h"
29 #include "frontends/WorkArea.h"
31 #include "support/filetools.h"
32 #include "support/convert.h"
33 #include "support/lstrings.h"
34 #include "support/os.h"
37 #include "BufferView.h"
38 #include "BufferList.h"
41 #include "FuncRequest.h"
45 #include "MenuBackend.h"
50 #include <QApplication>
51 #include <QCloseEvent>
52 #include <QDesktopWidget>
53 #include <QDragEnterEvent>
59 #include <QPushButton>
60 #include <QStackedWidget>
66 #include <boost/bind.hpp>
67 #include <boost/shared_ptr.hpp>
68 #include <boost/current_function.hpp>
76 using support::FileName;
77 using support::libFileSearch;
78 using support::makeDisplayPath;
84 int const statusbar_timer_value = 3000;
86 class BackgroundWidget: public QWidget
89 BackgroundWidget(QString const & file, QString const & text)
91 splash_ = new QPixmap(file);
93 lyxerr << "could not load splash screen: '" << fromqstr(file) << "'" << endl;
97 QPainter pain(splash_);
98 pain.setPen(QColor(255, 255, 0));
100 // The font used to display the version info
101 font.setStyleHint(QFont::SansSerif);
102 font.setWeight(QFont::Bold);
103 font.setPointSize(convert<int>(lyxrc.font_sizes[Font::SIZE_LARGE]));
105 pain.drawText(260, 270, text);
108 void paintEvent(QPaintEvent * ev)
113 int x = (width() - splash_->width()) / 2;
114 int y = (height() - splash_->height()) / 2;
116 pain.drawPixmap(x, y, *splash_);
127 struct GuiView::GuiViewPrivate
134 QTabWidget * tab_widget_;
135 QStackedWidget * stack_widget_;
136 BackgroundWidget * bg_widget_;
138 GuiViewPrivate() : posx_offset(0), posy_offset(0)
141 unsigned int smallIconSize;
142 unsigned int normalIconSize;
143 unsigned int bigIconSize;
144 // static needed by "New Window"
145 static unsigned int lastIconSize;
147 QMenu* toolBarPopup(GuiView *parent)
149 // FIXME: translation
150 QMenu* menu = new QMenu(parent);
151 QActionGroup *iconSizeGroup = new QActionGroup(parent);
153 QAction *smallIcons = new QAction(iconSizeGroup);
154 smallIcons->setText(qt_("Small-sized icons"));
155 smallIcons->setCheckable(true);
156 QObject::connect(smallIcons, SIGNAL(triggered()), parent, SLOT(smallSizedIcons()));
157 menu->addAction(smallIcons);
159 QAction *normalIcons = new QAction(iconSizeGroup);
160 normalIcons->setText(qt_("Normal-sized icons"));
161 normalIcons->setCheckable(true);
162 QObject::connect(normalIcons, SIGNAL(triggered()), parent, SLOT(normalSizedIcons()));
163 menu->addAction(normalIcons);
165 QAction *bigIcons = new QAction(iconSizeGroup);
166 bigIcons->setText(qt_("Big-sized icons"));
167 bigIcons->setCheckable(true);
168 QObject::connect(bigIcons, SIGNAL(triggered()), parent, SLOT(bigSizedIcons()));
169 menu->addAction(bigIcons);
171 unsigned int cur = parent->iconSize().width();
172 if ( cur == parent->d.smallIconSize)
173 smallIcons->setChecked(true);
174 else if (cur == parent->d.normalIconSize)
175 normalIcons->setChecked(true);
176 else if (cur == parent->d.bigIconSize)
177 bigIcons->setChecked(true);
182 void initBackground()
185 LYXERR(Debug::GUI) << "show banner: " << lyxrc.show_banner << endl;
186 /// The text to be written on top of the pixmap
187 QString const text = lyx_version ? QString(lyx_version) : qt_("unknown version");
188 FileName const file = support::libFileSearch("images", "banner", "png");
192 bg_widget_ = new BackgroundWidget(toqstr(file.absFilename()), text);
200 stack_widget_->setCurrentWidget(bg_widget_);
201 bg_widget_->setUpdatesEnabled(true);
206 unsigned int GuiView::GuiViewPrivate::lastIconSize = 0;
209 GuiView::GuiView(int id)
210 : QMainWindow(), LyXView(id), commandbuffer_(0), quitting_by_menu_(false),
211 d(*new GuiViewPrivate)
213 // Qt bug? signal lastWindowClosed does not work
214 setAttribute(Qt::WA_QuitOnClose, false);
215 setAttribute(Qt::WA_DeleteOnClose, true);
217 // hardcode here the platform specific icon size
218 d.smallIconSize = 14; // scaling problems
219 d.normalIconSize = 20; // ok, default
220 d.bigIconSize = 26; // better for some math icons
223 // assign an icon to main form. We do not do it under Qt/Mac,
224 // since the icon is provided in the application bundle.
225 FileName const iconname = libFileSearch("images", "lyx", "xpm");
226 if (!iconname.empty())
227 setWindowIcon(QPixmap(toqstr(iconname.absFilename())));
230 d.tab_widget_ = new QTabWidget;
232 QPushButton * closeTabButton = new QPushButton(this);
233 FileName const file = support::libFileSearch("images", "closetab", "xpm");
235 QPixmap pm(toqstr(file.absFilename()));
236 closeTabButton->setIcon(QIcon(pm));
237 closeTabButton->setMaximumSize(pm.size());
238 closeTabButton->setFlat(true);
240 closeTabButton->setText("Close");
242 closeTabButton->setCursor(Qt::ArrowCursor);
243 closeTabButton->setToolTip(tr("Close tab"));
244 closeTabButton->setEnabled(true);
246 QObject::connect(d.tab_widget_, SIGNAL(currentChanged(int)),
247 this, SLOT(currentTabChanged(int)));
248 QObject::connect(closeTabButton, SIGNAL(clicked()),
249 this, SLOT(closeCurrentTab()));
251 d.tab_widget_->setCornerWidget(closeTabButton);
252 #if QT_VERSION >= 0x040200
253 d.tab_widget_->setUsesScrollButtons(true);
258 lyxerr << "stack widget!" << endl;
259 d.stack_widget_ = new QStackedWidget;
260 d.stack_widget_->addWidget(d.bg_widget_);
261 d.stack_widget_->addWidget(d.tab_widget_);
262 setCentralWidget(d.stack_widget_);
265 setCentralWidget(d.tab_widget_);
269 setAcceptDrops(true);
280 void GuiView::close()
282 quitting_by_menu_ = true;
283 QMainWindow::close();
284 quitting_by_menu_ = false;
288 void GuiView::setFocus()
290 if (d.tab_widget_->count())
291 d.tab_widget_->currentWidget()->setFocus();
295 QMenu* GuiView::createPopupMenu()
297 return d.toolBarPopup(this);
303 menubar_.reset(new QLMenubar(this, menubackend));
304 QObject::connect(menuBar(), SIGNAL(triggered(QAction *)),
305 this, SLOT(updateMenu(QAction *)));
307 getToolbars().init();
309 statusBar()->setSizeGripEnabled(true);
311 QObject::connect(&statusbar_timer_, SIGNAL(timeout()),
312 this, SLOT(update_view_state_qt()));
315 d.stack_widget_->setCurrentWidget(d.bg_widget_);
319 void GuiView::closeEvent(QCloseEvent * close_event)
321 // we may have been called through the close window button
322 // which bypasses the LFUN machinery.
323 if (!quitting_by_menu_ && theApp()->gui().viewIds().size() == 1) {
324 if (!theBufferList().quitWriteAll()) {
325 close_event->ignore();
330 // Make sure that no LFUN use this close to be closed View.
331 theLyXFunc().setLyXView(0);
332 // Make sure the timer time out will not trigger a statusbar update.
333 statusbar_timer_.stop();
335 theApp()->gui().unregisterView(id());
336 if (!theApp()->gui().viewIds().empty()) {
337 // Just close the window and do nothing else if this is not the
339 close_event->accept();
345 // this is the place where we leave the frontend.
346 // it is the only point at which we start quitting.
348 close_event->accept();
349 // quit the event loop
354 void GuiView::dragEnterEvent(QDragEnterEvent * event)
356 if (event->mimeData()->hasUrls())
358 /// \todo Ask lyx-devel is this is enough:
359 /// if (event->mimeData()->hasFormat("text/plain"))
360 /// event->acceptProposedAction();
364 void GuiView::dropEvent(QDropEvent* event)
366 QList<QUrl> files = event->mimeData()->urls();
370 LYXERR(Debug::GUI) << BOOST_CURRENT_FUNCTION
371 << " got URLs!" << endl;
372 for (int i = 0; i!=files.size(); ++i) {
373 string const file = support::os::internal_path(fromqstr(
374 files.at(i).toLocalFile()));
376 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
381 void GuiView::saveGeometry()
383 static bool done = false;
390 // change the ifdef to 'geometry = normalGeometry();' only
391 // when Trolltech has fixed the broken normalGeometry on X11:
392 // http://www.trolltech.com/developer/task-tracker/index_html?id=119684+&method=entry
393 // Then also the moveEvent, resizeEvent, and the
394 // code for floatingGeometry_ can be removed;
395 // adjust GuiView::setGeometry()
397 QRect normal_geometry;
400 normal_geometry = normalGeometry();
402 maximized = CompletelyMaximized;
404 maximized = NotMaximized;
407 normal_geometry = updateFloatingGeometry();
409 QDesktopWidget& dw = *qApp->desktop();
410 QRect desk = dw.availableGeometry(dw.primaryScreen());
411 // Qt bug on Linux: load completely maximized, vert max. save-> frameGeometry().height() is wrong
412 if (isMaximized() && desk.width() <= frameGeometry().width() && desk.height() <= frameGeometry().height()) {
413 maximized = CompletelyMaximized;
414 // maximizing does not work when the window is allready hor. or vert. maximized
415 // Tested only on KDE
416 int dh = frameGeometry().height() - height();
417 if (desk.height() <= normal_geometry.height() + dh)
418 normal_geometry.setHeight(normal_geometry.height() - 1);
419 int dw = frameGeometry().width() - width();
420 if (desk.width() <= normal_geometry.width() + dw)
421 normal_geometry.setWidth(normal_geometry.width() - 1);
422 } else if (desk.height() <= frameGeometry().height()) {
423 maximized = VerticallyMaximized;
424 } else if (desk.width() <= frameGeometry().width()) {
425 maximized = HorizontallyMaximized;
427 maximized = NotMaximized;
432 // save windows size and position
433 Session & session = LyX::ref().session();
434 session.sessionInfo().save("WindowWidth", convert<string>(normal_geometry.width()));
435 session.sessionInfo().save("WindowHeight", convert<string>(normal_geometry.height()));
436 session.sessionInfo().save("WindowMaximized", convert<string>(maximized));
437 session.sessionInfo().save("IconSizeXY", convert<string>(iconSize().width()));
438 if (lyxrc.geometry_xysaved) {
439 session.sessionInfo().save("WindowPosX", convert<string>(normal_geometry.x() + d.posx_offset));
440 session.sessionInfo().save("WindowPosY", convert<string>(normal_geometry.y() + d.posy_offset));
442 getToolbars().saveToolbarInfo();
446 void GuiView::setGeometry(unsigned int width,
450 unsigned int iconSizeXY,
451 const string & geometryArg)
453 // use last value (not at startup)
454 if (d.lastIconSize != 0)
455 setIconSize(d.lastIconSize);
456 else if (iconSizeXY != 0)
457 setIconSize(iconSizeXY);
459 setIconSize(d.normalIconSize);
461 // only true when the -geometry option was NOT used
462 if (width != 0 && height != 0) {
463 if (posx != -1 && posy != -1) {
464 // if there are startup positioning problems:
465 // http://doc.trolltech.com/4.2/qdesktopwidget.html
466 QDesktopWidget& dw = *qApp->desktop();
467 if (dw.isVirtualDesktop()) {
468 if(!dw.geometry().contains(posx, posy)) {
473 // Which system doesn't use a virtual desktop?
474 // TODO save also last screen number and check if it is still availabe.
477 // FIXME: use setGeometry only when Trolltech has fixed the qt4/X11 bug
478 QWidget::setGeometry(posx, posy, width, height);
480 resize(width, height);
484 resize(width, height);
487 // remember original size
488 floatingGeometry_ = QRect(posx, posy, width, height);
490 if (maximized != NotMaximized) {
491 if (maximized == CompletelyMaximized) {
492 setWindowState(Qt::WindowMaximized);
495 // TODO How to set by the window manager?
496 // setWindowState(Qt::WindowVerticallyMaximized);
498 QDesktopWidget& dw = *qApp->desktop();
499 QRect desk = dw.availableGeometry(dw.primaryScreen());
500 if (maximized == VerticallyMaximized)
501 resize(width, desk.height());
502 if (maximized == HorizontallyMaximized)
503 resize(desk.width(), height);
510 // FIXME: move this code into parse_geometry() (LyX.cpp)
514 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
515 re.indexIn(toqstr(geometryArg.c_str()));
516 w = re.cap(1).toInt();
517 h = re.cap(2).toInt();
518 x = re.cap(3).toInt();
519 y = re.cap(4).toInt();
520 QWidget::setGeometry( x, y, w, h );
531 // For an unknown reason, the Window title update is not effective for
532 // the second windows up until it is shown on screen (Qt bug?).
535 // after show geometry() has changed (Qt bug?)
536 // we compensate the drift when storing the position
539 if (width != 0 && height != 0)
540 if (posx != -1 && posy != -1) {
542 d.posx_offset = posx - normalGeometry().x();
543 d.posy_offset = posy - normalGeometry().y();
546 if (maximized == NotMaximized) {
547 d.posx_offset = posx - geometry().x();
548 d.posy_offset = posy - geometry().y();
556 void GuiView::updateMenu(QAction * /*action*/)
562 void GuiView::setWindowTitle(docstring const & t, docstring const & it)
564 QString title = windowTitle();
565 QString new_title = toqstr(t);
566 if (title != new_title) {
567 QMainWindow::setWindowTitle(new_title);
568 QMainWindow::setWindowIconText(toqstr(it));
573 void GuiView::addCommandBuffer(QToolBar * toolbar)
575 commandbuffer_ = new QCommandBuffer(this, *controlcommand_);
576 focus_command_buffer.connect(boost::bind(&GuiView::focus_command_widget, this));
577 toolbar->addWidget(commandbuffer_);
581 void GuiView::message(docstring const & str)
583 statusBar()->showMessage(toqstr(str));
584 statusbar_timer_.stop();
585 statusbar_timer_.start(statusbar_timer_value);
589 void GuiView::clearMessage()
591 update_view_state_qt();
595 void GuiView::setIconSize(unsigned int size)
597 d.lastIconSize = size;
598 QMainWindow::setIconSize(QSize(size, size));
602 void GuiView::smallSizedIcons()
604 setIconSize(d.smallIconSize);
608 void GuiView::normalSizedIcons()
610 setIconSize(d.normalIconSize);
614 void GuiView::bigSizedIcons()
616 setIconSize(d.bigIconSize);
620 void GuiView::focus_command_widget()
623 commandbuffer_->focus_command();
627 void GuiView::update_view_state_qt()
631 theLyXFunc().setLyXView(this);
632 statusBar()->showMessage(toqstr(theLyXFunc().viewStatusMessage()));
633 statusbar_timer_.stop();
637 void GuiView::closeCurrentTab()
639 dispatch(FuncRequest(LFUN_BUFFER_CLOSE));
643 void GuiView::currentTabChanged(int i)
646 disconnectBufferView();
647 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(d.tab_widget_->widget(i));
649 BufferView & bv = wa->bufferView();
650 connectBufferView(bv);
651 connectBuffer(bv.buffer());
652 bv.updateMetrics(false);
653 bv.cursor().fixIfBroken();
654 wa->setUpdatesEnabled(true);
659 // Buffer-dependent dialogs should be updated or
660 // hidden. This should go here because some dialogs (eg ToC)
661 // require bv_->text.
662 getDialogs().updateBufferDependent(true);
665 updateLayoutChoice();
669 lyxerr << "currentTabChanged " << i
670 << "File" << bv.buffer().fileName() << endl;
674 void GuiView::updateStatusBar()
676 // let the user see the explicit message
677 if (statusbar_timer_.isActive())
680 statusBar()->showMessage(toqstr(theLyXFunc().viewStatusMessage()));
684 void GuiView::activated(FuncRequest const & func)
690 bool GuiView::hasFocus() const
692 return qApp->activeWindow() == this;
696 QRect GuiView::updateFloatingGeometry()
698 QDesktopWidget& dw = *qApp->desktop();
699 QRect desk = dw.availableGeometry(dw.primaryScreen());
700 // remember only non-maximized sizes
701 if (!isMaximized() && desk.width() > frameGeometry().width() && desk.height() > frameGeometry().height()) {
702 floatingGeometry_ = QRect(x(), y(), width(), height());
704 return floatingGeometry_;
708 void GuiView::resizeEvent(QResizeEvent *)
710 updateFloatingGeometry();
714 void GuiView::moveEvent(QMoveEvent *)
716 updateFloatingGeometry();
720 bool GuiView::event(QEvent * e)
724 // Useful debug code:
725 //case QEvent::WindowActivate:
726 //case QEvent::ActivationChange:
727 //case QEvent::WindowDeactivate:
728 //case QEvent::Paint:
729 //case QEvent::Enter:
730 //case QEvent::Leave:
731 //case QEvent::HoverEnter:
732 //case QEvent::HoverLeave:
733 //case QEvent::HoverMove:
734 //case QEvent::StatusTip:
735 //case QEvent::DragEnter:
736 //case QEvent::DragLeave:
740 case QEvent::ShortcutOverride: {
741 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
742 if (d.tab_widget_->count() == 0) {
743 theLyXFunc().setLyXView(this);
744 boost::shared_ptr<QKeySymbol> sym(new QKeySymbol);
746 theLyXFunc().processKeySym(sym, q_key_state(ke->modifiers()));
750 if (ke->key() == Qt::Key_Tab || ke->key() == Qt::Key_Backtab) {
751 boost::shared_ptr<QKeySymbol> sym(new QKeySymbol);
753 currentWorkArea()->processKeySym(sym, key_modifier::none);
759 return QMainWindow::event(e);
764 bool GuiView::focusNextPrevChild(bool /*next*/)
773 QMainWindow::setWindowTitle(qt_("LyX"));
775 updateFloatingGeometry();
779 void GuiView::busy(bool yes)
781 if (d.tab_widget_->count()) {
782 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(d.tab_widget_->currentWidget());
784 wa->setUpdatesEnabled(!yes);
786 wa->stopBlinkingCursor();
788 wa->startBlinkingCursor();
792 QApplication::setOverrideCursor(Qt::WaitCursor);
794 QApplication::restoreOverrideCursor();
798 Toolbars::ToolbarPtr GuiView::makeToolbar(ToolbarInfo const & tbinfo, bool newline)
800 QLToolbar * Tb = new QLToolbar(tbinfo, *this);
802 if (tbinfo.flags & ToolbarInfo::TOP) {
804 addToolBarBreak(Qt::TopToolBarArea);
805 addToolBar(Qt::TopToolBarArea, Tb);
808 if (tbinfo.flags & ToolbarInfo::BOTTOM) {
809 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
810 #if (QT_VERSION >= 0x040202)
812 addToolBarBreak(Qt::BottomToolBarArea);
814 addToolBar(Qt::BottomToolBarArea, Tb);
817 if (tbinfo.flags & ToolbarInfo::LEFT) {
818 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
819 #if (QT_VERSION >= 0x040202)
821 addToolBarBreak(Qt::LeftToolBarArea);
823 addToolBar(Qt::LeftToolBarArea, Tb);
826 if (tbinfo.flags & ToolbarInfo::RIGHT) {
827 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
828 #if (QT_VERSION >= 0x040202)
830 addToolBarBreak(Qt::RightToolBarArea);
832 addToolBar(Qt::RightToolBarArea, Tb);
835 // The following does not work so I cannot restore to exact toolbar location
837 ToolbarSection::ToolbarInfo & tbinfo = LyX::ref().session().toolbars().load(tbinfo.name);
838 Tb->move(tbinfo.posx, tbinfo.posy);
841 return Toolbars::ToolbarPtr(Tb);
845 WorkArea * GuiView::workArea(Buffer & buffer)
847 for (int i = 0; i != d.tab_widget_->count(); ++i) {
848 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(d.tab_widget_->widget(i));
850 if (&wa->bufferView().buffer() == &buffer)
857 WorkArea * GuiView::addWorkArea(Buffer & buffer)
859 GuiWorkArea * wa = new GuiWorkArea(buffer, *this);
860 d.tab_widget_->addTab(wa, toqstr(makeDisplayPath(buffer.fileName(), 30)));
861 wa->bufferView().updateMetrics(false);
863 d.stack_widget_->setCurrentWidget(d.tab_widget_);
868 WorkArea * GuiView::currentWorkArea()
870 if (d.tab_widget_->count() == 0)
872 BOOST_ASSERT(dynamic_cast<GuiWorkArea *>(d.tab_widget_->currentWidget()));
873 return dynamic_cast<GuiWorkArea *>(d.tab_widget_->currentWidget());
877 WorkArea const * GuiView::currentWorkArea() const
879 if (d.tab_widget_->count() == 0)
881 BOOST_ASSERT(dynamic_cast<GuiWorkArea const *>(d.tab_widget_->currentWidget()));
882 return dynamic_cast<GuiWorkArea const *>(d.tab_widget_->currentWidget());
886 void GuiView::setCurrentWorkArea(WorkArea * work_area)
888 BOOST_ASSERT(work_area);
890 // Changing work area can result from opening a file so
891 // update the toc in any case.
894 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(work_area);
896 if (wa != d.tab_widget_->currentWidget())
897 // Switch to the work area.
898 d.tab_widget_->setCurrentWidget(wa);
900 // Make sure the work area is up to date.
901 currentTabChanged(d.tab_widget_->currentIndex());
906 void GuiView::removeWorkArea(WorkArea * work_area)
908 BOOST_ASSERT(work_area);
909 if (work_area == currentWorkArea()) {
911 disconnectBufferView();
914 // removing a work area often results from closing a file so
915 // update the toc in any case.
918 GuiWorkArea * gwa = dynamic_cast<GuiWorkArea *>(work_area);
920 int index = d.tab_widget_->indexOf(gwa);
921 d.tab_widget_->removeTab(index);
925 if (d.tab_widget_->count()) {
926 // make sure the next work area is enabled.
927 d.tab_widget_->currentWidget()->setUpdatesEnabled(true);
931 getDialogs().hideBufferDependent();
932 if (d.stack_widget_) {
933 // No more work area, switch to the background widget.
939 } // namespace frontend
942 #include "GuiView_moc.cpp"