]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiView.C
* src/frontends/qt4/GuiSelection.C
[lyx.git] / src / frontends / qt4 / GuiView.C
1 /**
2  * \file GuiView.C
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 "QLyXKeySym.h"
21 #include "QLMenubar.h"
22 #include "QLToolbar.h"
23 #include "QCommandBuffer.h"
24 #include "qt_helpers.h"
25
26 #include "frontends/Application.h"
27 #include "frontends/Gui.h"
28 #include "frontends/WorkArea.h"
29
30 #include "support/filetools.h"
31 #include "support/convert.h"
32 #include "support/lstrings.h"
33
34 #include "BufferView.h"
35 #include "bufferlist.h"
36 #include "debug.h"
37 #include "funcrequest.h"
38 #include "lyx_cb.h"
39 #include "lyxrc.h"
40 #include "lyx_main.h"
41 #include "session.h"
42 #include "lyxfunc.h"
43 #include "MenuBackend.h"
44 #include "buffer.h"
45 #include "bufferlist.h"
46
47 #include <QAction>
48 #include <QApplication>
49 #include <QCloseEvent>
50 #include <QPixmap>
51 #include <QStatusBar>
52 #include <QToolBar>
53 #include <QTabBar>
54 #include <QDesktopWidget>
55 #include <QVBoxLayout>
56
57 #include <boost/bind.hpp>
58 #include <boost/shared_ptr.hpp>
59
60 using std::endl;
61 using std::string;
62 using std::vector;
63
64 namespace lyx {
65
66 using support::FileName;
67 using support::onlyFilename;
68 using support::subst;
69 using support::libFileSearch;
70
71 namespace frontend {
72
73 namespace {
74
75 int const statusbar_timer_value = 3000;
76
77 } // namespace anon
78
79
80 class WidgetWithTabBar : public QWidget
81 {
82 public:
83         QTabBar* tabbar;
84         WidgetWithTabBar(QWidget* w)
85         {
86                 tabbar = new QTabBar;
87                 QVBoxLayout* l = new QVBoxLayout;
88                 l->addWidget(tabbar);
89                 l->addWidget(w);
90                 l->setMargin(0);
91                 setLayout(l);
92         }
93 };
94
95
96 struct GuiView::GuiViewPrivate
97 {
98         typedef std::map<int, FuncRequest> FuncMap;
99         typedef std::pair<int, FuncRequest> FuncMapPair;
100         typedef std::map<string, QString> NameMap;
101         typedef std::pair<string, QString> NameMapPair;
102
103         FuncMap funcmap;
104         NameMap namemap;
105         WidgetWithTabBar* wt;
106
107         int posx_offset;
108         int posy_offset;
109
110         GuiViewPrivate() : wt(0), posx_offset(0), posy_offset(0)
111         {}
112
113         unsigned int smallIconSize;
114         unsigned int normalIconSize;
115         unsigned int bigIconSize;
116         // static needed by "New Window"
117         static unsigned int lastIconSize;
118
119         QMenu* toolBarPopup(GuiView *parent)
120         {
121                 // FIXME: translation 
122                 QMenu* menu = new QMenu(parent);
123                 QActionGroup *iconSizeGroup = new QActionGroup(parent);
124
125                 QAction *smallIcons = new QAction(iconSizeGroup);
126                 smallIcons->setText("Small sized icons");
127                 smallIcons->setCheckable(true);
128                 QObject::connect(smallIcons, SIGNAL(triggered()), parent, SLOT(smallSizedIcons()));
129                 menu->addAction(smallIcons);
130
131                 QAction *normalIcons = new QAction(iconSizeGroup);
132                 normalIcons->setText("Normal sized icons");
133                 normalIcons->setCheckable(true);
134                 QObject::connect(normalIcons, SIGNAL(triggered()), parent, SLOT(normalSizedIcons()));
135                 menu->addAction(normalIcons);
136
137
138                 QAction *bigIcons = new QAction(iconSizeGroup);
139                 bigIcons->setText("Big sized icons");
140                 bigIcons->setCheckable(true);
141                 QObject::connect(bigIcons, SIGNAL(triggered()), parent, SLOT(bigSizedIcons()));
142                 menu->addAction(bigIcons);
143
144                 unsigned int cur = parent->iconSize().width();
145                 if ( cur == parent->d.smallIconSize)
146                         smallIcons->setChecked(true);
147                 else if (cur == parent->d.normalIconSize)
148                         normalIcons->setChecked(true);
149                 else if (cur == parent->d.bigIconSize)
150                         bigIcons->setChecked(true);
151
152                 return menu;
153         }
154 };
155
156
157 unsigned int GuiView::GuiViewPrivate::lastIconSize = 0;
158
159
160 GuiView::GuiView(int id)
161         : QMainWindow(), LyXView(id), commandbuffer_(0), quitting_by_menu_(false),
162           d(*new GuiViewPrivate)
163 {
164         // Qt bug? signal lastWindowClosed does not work
165         setAttribute(Qt::WA_QuitOnClose, false);
166         setAttribute(Qt::WA_DeleteOnClose, true);
167
168         // hardcode here the platform specific icon size
169         d.smallIconSize = 14;   // scaling problems
170         d.normalIconSize = 20;  // ok, default
171         d.bigIconSize = 26;             // better for some math icons
172
173 #ifndef Q_WS_MACX
174         //  assign an icon to main form. We do not do it under Qt/Mac,
175         //  since the icon is provided in the application bundle.
176         FileName const iconname = libFileSearch("images", "lyx", "xpm");
177         if (!iconname.empty())
178                 setWindowIcon(QPixmap(toqstr(iconname.absFilename())));
179 #endif
180 }
181
182
183 GuiView::~GuiView()
184 {
185         menubar_.reset();
186         delete &d;
187 }
188
189
190 void GuiView::close()
191 {
192         quitting_by_menu_ = true;
193         QMainWindow::close();
194         quitting_by_menu_ = false;
195 }
196
197
198 void GuiView::setFocus()
199 {
200         BOOST_ASSERT(work_area_);
201         static_cast<GuiWorkArea *>(work_area_)->setFocus();
202 }
203
204
205 QMenu* GuiView::createPopupMenu()
206 {
207         return d.toolBarPopup(this);
208 }
209
210
211 void GuiView::init()
212 {
213         menubar_.reset(new QLMenubar(this, menubackend));
214         QObject::connect(menuBar(), SIGNAL(triggered(QAction *)),
215                 this, SLOT(updateMenu(QAction *)));
216
217         getToolbars().init();
218
219         statusBar()->setSizeGripEnabled(false);
220
221         QObject::connect(&statusbar_timer_, SIGNAL(timeout()),
222                 this, SLOT(update_view_state_qt()));
223
224         BOOST_ASSERT(work_area_);
225         if (!work_area_->bufferView().buffer() && !theBufferList().empty())
226                 setBuffer(theBufferList().first());
227
228         // make sure the buttons are disabled if needed
229         updateToolbars();
230         updateLayoutChoice();
231         updateMenubar();
232 }
233
234
235 void GuiView::closeEvent(QCloseEvent * close_event)
236 {
237         // we may have been called through the close window button
238         // which bypasses the LFUN machinery.
239         if (!quitting_by_menu_) {
240                 if (!theBufferList().quitWriteAll()) {
241                         close_event->ignore();
242                         return;
243                 }
244         }
245         if (view()->buffer()) {
246                 // save cursor position for opened files to .lyx/session
247                 LyX::ref().session().lastFilePos().save(
248                         FileName(buffer()->fileName()),
249                         boost::tie(view()->cursor().pit(),
250                         view()->cursor().pos()));
251         }
252         theApp()->gui().unregisterView(id());   
253         if (theApp()->gui().viewIds().empty())
254         {
255                 // this is the place where we leave the frontend.
256                 // it is the only point at which we start quitting.
257                 saveGeometry();
258                 close_event->accept();
259                 // quit the event loop
260                 qApp->quit();
261         }
262         close_event->accept();
263 }
264
265
266 void GuiView::saveGeometry()
267 {
268         static bool done = false;
269         if (done)
270                 return;
271         else
272                 done = true;
273
274         // FIXME:
275         // change the ifdef to 'geometry = normalGeometry();' only
276         // when Trolltech has fixed the broken normalGeometry on X11:
277         // http://www.trolltech.com/developer/task-tracker/index_html?id=119684+&method=entry
278         // Then also the moveEvent, resizeEvent, and the
279         // code for floatingGeometry_ can be removed;
280         // adjust GuiView::setGeometry()
281 #ifdef Q_WS_WIN
282         QRect geometry = normalGeometry();
283 #else
284         updateFloatingGeometry();
285         QRect geometry = floatingGeometry_;
286 #endif
287
288         // save windows size and position
289         Session & session = LyX::ref().session();
290         session.sessionInfo().save("WindowWidth", convert<string>(geometry.width()));
291         session.sessionInfo().save("WindowHeight", convert<string>(geometry.height()));
292         session.sessionInfo().save("WindowIsMaximized", (isMaximized() ? "yes" : "no"));
293         session.sessionInfo().save("IconSizeXY", convert<string>(iconSize().width()));
294         if (lyxrc.geometry_xysaved) {
295                 session.sessionInfo().save("WindowPosX", convert<string>(geometry.x() + d.posx_offset));
296                 session.sessionInfo().save("WindowPosY", convert<string>(geometry.y() + d.posy_offset));
297         }
298         getToolbars().saveToolbarInfo();
299 }
300                                                   
301
302 void GuiView::setGeometry(unsigned int width,
303                                                                   unsigned int height,
304                                                                   int posx, int posy,
305                                                                   bool maximize,
306                                                                   unsigned int iconSizeXY,
307                                                                   const std::string & geometryArg)
308 {
309         // use last value (not at startup)
310         if (d.lastIconSize != 0)
311                 setIconSize(d.lastIconSize);
312         else if (iconSizeXY != 0)
313                 setIconSize(iconSizeXY);
314         else
315                 setIconSize(d.normalIconSize);
316
317         // only true when the -geometry option was NOT used
318         if (width != 0 && height != 0) {
319                 if (posx != -1 && posy != -1) {
320                         // if there are ever startup positioning problems 
321                         // on a virtual desktop then check the 6 lines below
322                         // http://doc.trolltech.com/4.2/qdesktopwidget.html 
323                         QDesktopWidget& dw = *qApp->desktop();
324                         QRect desk = dw.availableGeometry(dw.primaryScreen());
325                         (posx >= desk.width() ? posx = 50 : true);
326                         (posy >= desk.height()? posy = 50 : true);
327 #ifdef Q_WS_WIN
328                         // FIXME: use setGeometry only when Trolltech has fixed the qt4/X11 bug
329                         QWidget::setGeometry(posx, posy, width, height);
330 #else
331                         resize(width, height);
332                         move(posx, posy);
333 #endif
334                 } else {
335                         resize(width, height);
336                 }
337
338                 if (maximize)
339                         setWindowState(Qt::WindowMaximized);
340         }
341         else
342         {
343                 // FIXME: move this code into parse_geometry() (lyx_main.C)
344 #ifdef Q_WS_WIN
345                 int x, y;
346                 int w, h;
347                 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
348                 re.indexIn( toqstr(geometryArg.c_str()));
349                 w = re.cap( 1 ).toInt();
350                 h = re.cap( 2 ).toInt();
351                 x = re.cap( 3 ).toInt();
352                 y = re.cap( 4 ).toInt();
353                 QWidget::setGeometry( x, y, w, h );
354 #endif
355         }
356
357         show();
358
359         // For an unknown reason, the Window title update is not effective for
360         // the second windows up until it is shown on screen (Qt bug?).
361         updateWindowTitle();
362
363         // after show geometry() has changed (Qt bug?)
364         // we compensate the drift when storing the position
365         d.posx_offset = 0;
366         d.posy_offset = 0;
367         if (width != 0 && height != 0) 
368                 if (posx != -1 && posy != -1) {
369 #ifdef Q_WS_WIN
370                         d.posx_offset = posx - normalGeometry().x();
371                         d.posy_offset = posy - normalGeometry().y();
372 #else
373                         if (!maximize) {
374                                 d.posx_offset = posx - geometry().x();
375                                 d.posy_offset = posy - geometry().y();
376                         }
377 #endif
378                 }
379 }
380
381
382 void GuiView::updateMenu(QAction * /*action*/)
383 {
384         menubar_->update();
385 }
386
387
388 void GuiView::setWindowTitle(docstring const & t, docstring const & it)
389 {
390         QString title = windowTitle();
391         QString new_title = toqstr(t);
392         if (title != new_title) {
393                 QMainWindow::setWindowTitle(new_title);
394                 QMainWindow::setWindowIconText(toqstr(it));
395         }
396 }
397
398
399 void GuiView::addCommandBuffer(QToolBar * toolbar)
400 {
401         commandbuffer_ = new QCommandBuffer(this, *controlcommand_);
402         focus_command_buffer.connect(boost::bind(&GuiView::focus_command_widget, this));
403         toolbar->addWidget(commandbuffer_);
404 }
405
406
407 void GuiView::message(docstring const & str)
408 {
409         statusBar()->showMessage(toqstr(str));
410         statusbar_timer_.stop();
411         statusbar_timer_.start(statusbar_timer_value);
412 }
413
414
415 void GuiView::clearMessage()
416 {
417         update_view_state_qt();
418 }
419
420
421 void GuiView::setIconSize(unsigned int size)
422 {
423         d.lastIconSize = size;
424         QMainWindow::setIconSize(QSize(size, size));
425 }
426
427
428 void GuiView::smallSizedIcons()
429 {
430         setIconSize(d.smallIconSize);
431 }
432
433
434 void GuiView::normalSizedIcons()
435 {
436         setIconSize(d.normalIconSize);
437 }
438
439
440 void GuiView::bigSizedIcons()
441 {
442         setIconSize(d.bigIconSize);
443 }
444
445
446 void GuiView::focus_command_widget()
447 {
448         if (commandbuffer_)
449                 commandbuffer_->focus_command();
450 }
451
452
453 void GuiView::update_view_state_qt()
454 {
455         statusBar()->showMessage(toqstr(theLyXFunc().viewStatusMessage()));
456         statusbar_timer_.stop();
457 }
458
459
460 void GuiView::initTab(QWidget* workarea)
461 {
462         d.wt = new WidgetWithTabBar(workarea);
463         setCentralWidget(d.wt);
464         QObject::connect(d.wt->tabbar, SIGNAL(currentChanged(int)),
465                         this, SLOT(currentTabChanged(int)));
466 }
467
468
469 void GuiView::updateTab()
470 {
471         QTabBar& tb = *d.wt->tabbar;
472
473         // update when all  is done
474         tb.blockSignals(true);
475
476         typedef std::vector<string> Strings;
477         Strings const names = theBufferList().getFileNames();
478         size_t n_size = names.size();
479
480         Strings addtab;
481         // show tabs only when there is more 
482         // than one file opened
483         if (n_size > 1)
484         {
485                 for (size_t i = 0; i != n_size; i++) 
486                         if (d.namemap.find(names[i]) == d.namemap.end())
487                                 addtab.push_back(names.at(i));
488         }
489
490         for(size_t i = 0; i<addtab.size(); i++)
491         {
492                 QString tab_name = lyx::toqstr(onlyFilename(addtab.at(i))); 
493                 d.namemap.insert(GuiViewPrivate::NameMapPair(addtab.at(i), tab_name));
494                 tb.addTab(tab_name);
495         }
496
497         // check if all names showed by the tabs
498         // are also in the current bufferlist
499         Strings removetab;
500         bool notall = true;
501         if (n_size < 2)
502                 notall = false;
503         std::map<string, QString>::iterator tabit = d.namemap.begin();
504         for (;tabit != d.namemap.end(); ++tabit)
505         {
506                 bool found = false;
507                 for (size_t i = 0; i != n_size; i++) 
508                         if (tabit->first == names.at(i) && notall)
509                                 found = true;
510                 if (!found)
511                         removetab.push_back(tabit->first);
512         }
513         
514
515         // remove tabs
516         for(size_t i = 0; i<removetab.size(); i++)
517         {
518                 if (d.namemap.find(removetab.at(i)) != d.namemap.end())
519                 {
520                         tabit = d.namemap.find(removetab.at(i));
521                         for (int i = 0; i < tb.count(); i++)
522                                 if (tb.tabText(i) == tabit->second)
523                                 {
524                                         tb.removeTab(i);
525                                         break;
526                                 }
527                         d.namemap.erase(tabit);
528                 }
529         }
530
531         // rebuild func map
532         if (removetab.size() > 0 || addtab.size() > 0)
533         {
534                 d.funcmap.clear();
535                 tabit = d.namemap.begin();
536                 for (;tabit != d.namemap.end(); ++tabit)
537                 {
538                         QTabBar& tb = *d.wt->tabbar;
539                         for (int i = 0; i < tb.count(); i++)
540                         {
541                                 if (tb.tabText(i) == tabit->second)
542                                 {
543                                         FuncRequest func(LFUN_BUFFER_SWITCH, tabit->first);
544                                         d.funcmap.insert(GuiViewPrivate::FuncMapPair(i, func));
545                                         break;
546                                 }
547                         }
548                 }
549         }
550
551         // set current tab
552         if (view()->buffer()) 
553         {
554                 string cur_title = view()->buffer()->fileName();
555                 if (d.namemap.find(cur_title) != d.namemap.end())
556                 {
557                         QString tabname = d.namemap.find(cur_title)->second;
558                         for (int i = 0; i < tb.count(); i++)
559                                 if (tb.tabText(i) == tabname)
560                                 {
561                                         tb.setCurrentIndex(i);
562                                         break;
563                                 }
564                 }
565         }
566
567         tb.blockSignals(false);
568         d.wt->update();
569 }
570
571
572 void GuiView::currentTabChanged (int index)
573 {
574         std::map<int, FuncRequest>::const_iterator it = d.funcmap.find(index);
575         if (it != d.funcmap.end())
576                 activated(it->second);
577 }
578
579
580 void GuiView::updateStatusBar()
581 {
582         // let the user see the explicit message
583         if (statusbar_timer_.isActive())
584                 return;
585
586         statusBar()->showMessage(toqstr(theLyXFunc().viewStatusMessage()));
587 }
588
589
590 void GuiView::activated(FuncRequest const & func)
591 {
592         dispatch(func);
593 }
594
595
596 bool GuiView::hasFocus() const
597 {
598         return qApp->activeWindow() == this;
599 }
600
601
602 void  GuiView::updateFloatingGeometry()
603 {
604         if (!isMaximized())
605                 floatingGeometry_ = QRect(x(), y(), width(), height());
606 }
607
608
609 void GuiView::resizeEvent(QResizeEvent *)
610 {
611         updateFloatingGeometry();
612 }
613
614
615 void GuiView::moveEvent(QMoveEvent *)
616 {
617         updateFloatingGeometry();
618 }
619
620
621 bool GuiView::event(QEvent * e)
622 {
623         // Useful debug code:
624         /*
625         switch (e->type())
626         {
627         case QEvent::WindowActivate:
628         case QEvent::ActivationChange:
629         case QEvent::WindowDeactivate:
630         case QEvent::Paint:
631         case QEvent::Enter:
632         case QEvent::Leave:
633         case QEvent::HoverEnter:
634         case QEvent::HoverLeave:
635         case QEvent::HoverMove:
636         case QEvent::StatusTip:
637                 break;
638         default:
639         */
640
641         if (e->type() == QEvent::ShortcutOverride) {
642                 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
643                 if (ke->key() == Qt::Key_Tab || ke->key() == Qt::Key_Backtab) {
644                         boost::shared_ptr<QLyXKeySym> sym(new QLyXKeySym);
645                         sym->set(ke);
646                         BOOST_ASSERT(work_area_);
647                         work_area_->processKeySym(sym, key_modifier::none);
648                         e->accept();
649                         return true;
650                 }
651         }
652         //} for the debug switch above.
653
654         return QMainWindow::event(e);
655 }
656
657
658 bool GuiView::focusNextPrevChild(bool /*next*/)
659 {
660         setFocus();
661         return true;
662 }
663
664
665 void GuiView::show()
666 {
667         QMainWindow::setWindowTitle(qt_("LyX"));
668         QMainWindow::show();
669         updateFloatingGeometry();
670 }
671
672
673 void GuiView::busy(bool yes)
674 {
675         BOOST_ASSERT(work_area_);
676         static_cast<GuiWorkArea *>(work_area_)->setUpdatesEnabled(!yes);
677
678         if (yes) {
679                 work_area_->stopBlinkingCursor();
680                 QApplication::setOverrideCursor(Qt::WaitCursor);
681         }
682         else {
683                 work_area_->startBlinkingCursor();
684                 QApplication::restoreOverrideCursor();
685         }
686 }
687
688
689 Toolbars::ToolbarPtr GuiView::makeToolbar(ToolbarBackend::Toolbar const & tbb)
690 {
691         QLToolbar * Tb = new QLToolbar(tbb, *this);
692         //static QLToolbar * lastTb = 0;
693
694         if (tbb.flags & ToolbarBackend::TOP) {
695                         addToolBar(Qt::TopToolBarArea, Tb);
696                         addToolBarBreak(Qt::TopToolBarArea);
697         }
698         if (tbb.flags & ToolbarBackend::BOTTOM) {
699                 addToolBar(Qt::BottomToolBarArea, Tb);
700                 /*
701                 // Qt bug:
702                 // http://www.trolltech.com/developer/task-tracker/index_html?id=137015&method=entry
703                 // Doesn't work because the toolbar will evtl. be hidden.
704                 if (lastTb)
705                         insertToolBarBreak(lastTb);
706                 lastTb = Tb;
707                 */
708         }
709         if (tbb.flags & ToolbarBackend::LEFT) {
710                 addToolBar(Qt::LeftToolBarArea, Tb);
711         }
712         if (tbb.flags & ToolbarBackend::RIGHT) {
713                 addToolBar(Qt::RightToolBarArea, Tb);
714         }
715
716         return Toolbars::ToolbarPtr(Tb);
717 }
718
719 } // namespace frontend
720 } // namespace lyx
721
722 #include "GuiView_moc.cpp"