2 * \file BufferView_pimpl.C
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Asger Alstrup
7 * \author Alfredo Braunstein
8 * \author Lars Gullik Bjønnes
9 * \author Jean-Marc Lasgouttes
10 * \author Angus Leeming
12 * \author André Pönitz
14 * \author Jürgen Vigna
16 * Full author contact details are available in file CREDITS.
21 #include "BufferView_pimpl.h"
23 #include "buffer_funcs.h"
24 #include "bufferlist.h"
25 #include "bufferparams.h"
26 #include "coordcache.h"
28 #include "CutAndPaste.h"
30 #include "dispatchresult.h"
32 #include "FloatList.h"
33 #include "funcrequest.h"
34 #include "FuncStatus.h"
37 #include "insetiterator.h"
38 #include "LaTeXFeatures.h"
39 #include "lyx_cb.h" // added for Dispatch functions
46 #include "metricsinfo.h"
47 #include "paragraph.h"
48 #include "paragraph_funcs.h"
49 #include "ParagraphParameters.h"
50 #include "pariterator.h"
51 #include "rowpainter.h"
56 #include "insets/insetbibtex.h"
57 #include "insets/insetref.h"
58 #include "insets/insettext.h"
60 #include "frontends/Alert.h"
61 #include "frontends/Clipboard.h"
62 #include "frontends/Dialogs.h"
63 #include "frontends/FileDialog.h"
64 #include "frontends/font_metrics.h"
65 #include "frontends/Gui.h"
66 #include "frontends/LyXView.h"
67 #include "frontends/Painter.h"
68 #include "frontends/WorkArea.h"
70 #include "graphics/Previews.h"
72 #include "support/convert.h"
73 #include "support/filefilterlist.h"
74 #include "support/filetools.h"
75 #include "support/forkedcontr.h"
76 #include "support/package.h"
77 #include "support/types.h"
79 #include <boost/bind.hpp>
80 #include <boost/current_function.hpp>
85 using lyx::frontend::WorkArea;
86 using lyx::frontend::Clipboard;
87 using lyx::frontend::Gui;
91 using lyx::support::addPath;
92 using lyx::support::bformat;
93 using lyx::support::FileFilterList;
94 using lyx::support::fileSearch;
95 using lyx::support::ForkedcallsController;
96 using lyx::support::isDirWriteable;
97 using lyx::support::makeDisplayPath;
98 using lyx::support::makeAbsPath;
99 using lyx::support::package;
102 using std::istringstream;
103 using std::make_pair;
107 using std::mem_fun_ref;
110 extern BufferList bufferlist;
115 unsigned int const saved_positions_num = 20;
117 // All the below connection objects are needed because of a bug in some
118 // versions of GCC (<=2.96 are on the suspects list.) By having and assigning
119 // to these connections we avoid a segfault upon startup, and also at exit.
122 boost::signals::connection timecon;
124 /// Return an inset of this class if it exists at the current cursor position
126 T * getInsetByCode(LCursor & cur, InsetBase::Code code)
129 DocIterator it = cur;
130 if (it.nextInset() &&
131 it.nextInset()->lyxCode() == code) {
132 inset = static_cast<T*>(it.nextInset());
140 BufferView::Pimpl::Pimpl(BufferView & bv, LyXView * owner,
141 int width, int height)
142 : bv_(&bv), owner_(owner), buffer_(0), wh_(0), cursor_timeout(400),
143 using_xterm_cursor(false), cursor_(bv),
144 anchor_ref_(0), offset_ref_(0)
146 xsel_cache_.set = false;
148 workAreaId_ = owner_->gui().newWorkArea(width, height);
149 workArea_ = & owner_->gui().workArea(workAreaId_);
152 timecon = cursor_timeout.timeout
153 .connect(boost::bind(&BufferView::Pimpl::cursorToggle, this));
155 cursor_timeout.start();
157 saved_positions.resize(saved_positions_num);
158 // load saved bookmarks
159 lyx::Session::BookmarkList & bmList = LyX::ref().session().loadBookmarks();
160 for (lyx::Session::BookmarkList::iterator bm = bmList.begin();
161 bm != bmList.end(); ++bm)
162 if (bm->get<0>() < saved_positions_num)
163 saved_positions[bm->get<0>()] = Position( bm->get<1>(), bm->get<2>(), bm->get<3>() );
164 // and then clear them
169 void BufferView::Pimpl::addError(ErrorItem const & ei)
171 errorlist_.push_back(ei);
175 void BufferView::Pimpl::showReadonly(bool)
177 owner_->updateWindowTitle();
178 owner_->getDialogs().updateBufferDependent(false);
182 void BufferView::Pimpl::connectBuffer(Buffer & buf)
184 if (errorConnection_.connected())
189 boost::bind(&BufferView::Pimpl::addError, this, _1));
193 boost::bind(&LyXView::message, owner_, _1));
197 boost::bind(&LyXView::busy, owner_, _1));
200 buf.updateTitles.connect(
201 boost::bind(&LyXView::updateWindowTitle, owner_));
204 buf.resetAutosaveTimers.connect(
205 boost::bind(&LyXView::resetAutosaveTimer, owner_));
207 readonlyConnection_ =
208 buf.readonly.connect(
209 boost::bind(&BufferView::Pimpl::showReadonly, this, _1));
213 boost::bind(&BufferView::Pimpl::setBuffer, this, (Buffer *)0));
217 void BufferView::Pimpl::disconnectBuffer()
219 errorConnection_.disconnect();
220 messageConnection_.disconnect();
221 busyConnection_.disconnect();
222 titleConnection_.disconnect();
223 timerConnection_.disconnect();
224 readonlyConnection_.disconnect();
225 closingConnection_.disconnect();
229 void BufferView::Pimpl::newFile(string const & filename, string const & tname,
232 setBuffer(::newFile(filename, tname, isNamed));
236 bool BufferView::Pimpl::loadLyXFile(string const & filename, bool tolastfiles)
238 // Get absolute path of file and add ".lyx"
239 // to the filename if necessary
240 string s = fileSearch(string(), filename, "lyx");
242 bool const found = !s.empty();
247 // File already open?
248 if (bufferlist.exists(s)) {
249 string const file = makeDisplayPath(s, 20);
250 string text = bformat(_("The document %1$s is already "
251 "loaded.\n\nDo you want to revert "
252 "to the saved version?"), file);
253 int const ret = Alert::prompt(_("Revert to saved document?"),
254 text, 0, 1, _("&Revert"), _("&Switch to document"));
257 setBuffer(bufferlist.getBuffer(s));
260 // FIXME: should be LFUN_REVERT
261 if (!bufferlist.close(bufferlist.getBuffer(s), false))
263 // Fall through to new load. (Asger)
269 b = bufferlist.newBuffer(s);
271 if (!::loadLyXFile(b, s)) {
272 bufferlist.release(b);
276 string text = bformat(_("The document %1$s does not yet "
277 "exist.\n\nDo you want to create "
278 "a new document?"), s);
279 int const ret = Alert::prompt(_("Create new document?"),
280 text, 0, 1, _("&Create"), _("Cancel"));
283 b = ::newFile(s, string(), true);
289 bv_->showErrorList(_("Parse"));
291 // scroll to the position when the file was last closed
292 if (lyxrc.use_lastfilepos) {
295 boost::tie(pit, pos) = LyX::ref().session().loadFilePosition(s);
296 // I am not sure how to separate the following part to a function
297 // so I will leave this to Lars.
299 // check pit since the document may be externally changed.
300 if ( static_cast<size_t>(pit) < b->paragraphs().size() ) {
301 ParIterator it = b->par_iterator_begin();
302 ParIterator const end = b->par_iterator_end();
303 for (; it != end; ++it)
304 if (it.pit() == pit) {
305 // restored pos may be bigger than it->size
306 bv_->setCursor(makeDocIterator(it, min(pos, it->size())));
307 bv_->update(Update::FitCursor);
314 LyX::ref().session().addLastFile(b->fileName());
320 lyx::frontend::Gui & BufferView::Pimpl::gui() const
322 return owner_->gui();
326 lyx::frontend::WorkArea & BufferView::Pimpl::workarea() const
332 lyx::frontend::Clipboard & BufferView::Pimpl::clipboard() const
334 return owner_->gui().clipboard();
338 lyx::frontend::Painter & BufferView::Pimpl::painter() const
340 return workArea_->getPainter();
344 void BufferView::Pimpl::setBuffer(Buffer * b)
346 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
347 << "[ b = " << b << "]" << endl;
351 // Save the actual cursor position and anchor inside the
352 // buffer so that it can be restored in case we rechange
353 // to this buffer later on.
354 buffer_->saveCursor(cursor_.selectionBegin(),
355 cursor_.selectionEnd());
356 // current buffer is going to be switched-off, save cursor pos
357 LyX::ref().session().saveFilePosition(buffer_->fileName(),
358 boost::tie(cursor_.pit(), cursor_.pos()) );
361 // If we are closing current buffer, switch to the first in
364 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
365 << " No Buffer!" << endl;
366 // We are closing the buffer, use the first buffer as current
367 buffer_ = bufferlist.first();
368 owner_->getDialogs().hideBufferDependent();
370 // Set current buffer
375 cursor_ = LCursor(*bv_);
380 // If we're quitting lyx, don't bother updating stuff
385 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
386 << "Buffer addr: " << buffer_ << endl;
387 connectBuffer(*buffer_);
388 cursor_.push(buffer_->inset());
389 cursor_.resetAnchor();
390 buffer_->text().init(bv_);
391 buffer_->text().setCurrentFont(cursor_);
392 if (buffer_->getCursor().size() > 0 &&
393 buffer_->getAnchor().size() > 0)
395 cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
396 cursor_.resetAnchor();
397 cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
398 cursor_.setSelection();
401 // Buffer-dependent dialogs should be updated or
402 // hidden. This should go here because some dialogs (eg ToC)
403 // require bv_->text.
404 owner_->getDialogs().updateBufferDependent(true);
409 owner_->updateMenubar();
410 owner_->updateToolbars();
411 owner_->updateLayoutChoice();
412 owner_->updateWindowTitle();
414 // This is done after the layout combox has been populated
416 size_t i = cursor_.depth() - 1;
417 // we know we'll eventually find a paragraph
419 CursorSlice const & slice = cursor_[i];
420 if (!slice.inset().inMathed()) {
421 LyXLayout_ptr const layout = slice.paragraph().layout();
422 owner_->setLayout(layout->name());
430 if (buffer_ && lyx::graphics::Previews::status() != LyXRC::PREVIEW_OFF)
431 lyx::graphics::Previews::get().generateBufferPreviews(*buffer_);
435 void BufferView::Pimpl::resizeCurrentBuffer()
437 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
439 owner_->message(_("Formatting document..."));
441 LyXText * text = bv_->text();
451 // Reset the "Formatting..." message
452 owner_->clearMessage();
458 void BufferView::Pimpl::updateScrollbar()
461 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
462 << " no text in updateScrollbar" << endl;
463 workArea_->setScrollbarParams(0, 0, 0);
467 LyXText & t = *bv_->text();
468 int const parsize = int(t.paragraphs().size() - 1);
469 if (anchor_ref_ > parsize) {
470 anchor_ref_ = parsize;
475 << BOOST_CURRENT_FUNCTION
476 << " Updating scrollbar: height: " << t.paragraphs().size()
477 << " curr par: " << cursor_.bottom().pit()
478 << " default height " << defaultRowHeight() << endl;
480 // It would be better to fix the scrollbar to understand
481 // values in [0..1] and divide everything by wh
483 // estimated average paragraph height:
485 wh_ = workArea_->height() / 4;
486 int h = t.getPar(anchor_ref_).height();
488 // Normalize anchor/offset (MV):
489 while (offset_ref_ > h && anchor_ref_ < parsize) {
492 h = t.getPar(anchor_ref_).height();
494 // Look at paragraph heights on-screen
497 for (lyx::pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
498 if (sumh > workArea_->height())
500 int const h2 = t.getPar(pit).height();
504 int const hav = sumh / nh;
505 // More realistic average paragraph height
509 workArea_->setScrollbarParams((parsize + 1) * wh_,
510 anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h)),
511 int(wh_ * defaultRowHeight() / float(h)));
515 void BufferView::Pimpl::scrollDocView(int value)
517 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
518 << "[ value = " << value << "]" << endl;
523 owner_->gui().guiCursor().hide();
525 LyXText & t = *bv_->text();
527 float const bar = value / float(wh_ * t.paragraphs().size());
529 anchor_ref_ = int(bar * t.paragraphs().size());
530 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
531 anchor_ref_ = int(t.paragraphs().size()) - 1;
532 t.redoParagraph(anchor_ref_);
533 int const h = t.getPar(anchor_ref_).height();
534 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
537 if (!lyxrc.cursor_follows_scrollbar)
540 int const height = 2 * defaultRowHeight();
541 int const first = height;
542 int const last = workArea_->height() - height;
543 LCursor & cur = cursor_;
545 bv_funcs::CurStatus st = bv_funcs::status(bv_, cur);
548 case bv_funcs::CUR_ABOVE:
549 t.setCursorFromCoordinates(cur, 0, first);
550 cur.clearSelection();
552 case bv_funcs::CUR_BELOW:
553 t.setCursorFromCoordinates(cur, 0, last);
554 cur.clearSelection();
556 case bv_funcs::CUR_INSIDE:
557 int const y = bv_funcs::getPos(cur, cur.boundary()).y_;
558 int const newy = min(last, max(y, first));
560 cur.reset(buffer_->inset());
561 t.setCursorFromCoordinates(cur, 0, newy);
564 owner_->updateLayoutChoice();
568 void BufferView::Pimpl::scroll(int /*lines*/)
573 // LyXText const * t = bv_->text();
574 // int const line_height = defaultRowHeight();
576 // // The new absolute coordinate
577 // int new_top_y = top_y() + lines * line_height;
579 // // Restrict to a valid value
580 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
581 // new_top_y = std::max(0, new_top_y);
583 // scrollDocView(new_top_y);
585 // // Update the scrollbar.
586 // workArea_->.setScrollbarParams(t->height(), top_y(), defaultRowHeight());
590 void BufferView::Pimpl::workAreaKeyPress(LyXKeySymPtr key,
591 key_modifier::state state)
593 owner_->getLyXFunc().processKeySym(key, state);
595 /* This is perhaps a bit of a hack. When we move
596 * around, or type, it's nice to be able to see
597 * the cursor immediately after the keypress. So
598 * we reset the toggle timeout and force the visibility
599 * of the cursor. Note we cannot do this inside
600 * dispatch() itself, because that's called recursively.
603 owner_->gui().guiCursor().show(*bv_);
607 void BufferView::Pimpl::selectionRequested()
614 LCursor & cur = cursor_;
616 if (!cur.selection()) {
617 xsel_cache_.set = false;
621 if (!xsel_cache_.set ||
622 cur.top() != xsel_cache_.cursor ||
623 cur.anchor_.top() != xsel_cache_.anchor)
625 xsel_cache_.cursor = cur.top();
626 xsel_cache_.anchor = cur.anchor_.top();
627 xsel_cache_.set = cur.selection();
628 sel = cur.selectionAsString(false);
630 clipboard().put(sel);
635 void BufferView::Pimpl::selectionLost()
638 owner_->gui().guiCursor().hide();
639 cursor_.clearSelection();
640 xsel_cache_.set = false;
645 void BufferView::Pimpl::workAreaResize()
647 static int workArea_width;
648 static int workArea_height;
650 bool const widthChange = workArea_->width() != workArea_width;
651 bool const heightChange = workArea_->height() != workArea_height;
653 // Update from work area
654 workArea_width = workArea_->width();
655 workArea_height = workArea_->height();
657 if (buffer_ && widthChange) {
658 // The visible LyXView need a resize
659 resizeCurrentBuffer();
662 if (widthChange || heightChange)
665 // Always make sure that the scrollbar is sane.
667 owner_->updateLayoutChoice();
671 bool BufferView::Pimpl::fitCursor()
673 if (bv_funcs::status(bv_, cursor_) == bv_funcs::CUR_INSIDE) {
674 LyXFont const font = cursor_.getFont();
675 int const asc = font_metrics::maxAscent(font);
676 int const des = font_metrics::maxDescent(font);
677 Point const p = bv_funcs::getPos(cursor_, cursor_.boundary());
678 if (p.y_ - asc >= 0 && p.y_ + des < workArea_->height())
686 bool BufferView::Pimpl::multiParSel()
688 if (!cursor_.selection())
690 bool ret = multiparsel_cache_;
691 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
692 // Either this, or previous selection spans paragraphs
693 return ret || multiparsel_cache_;
697 void BufferView::Pimpl::update(Update::flags flags)
700 << BOOST_CURRENT_FUNCTION
701 << "[fitcursor = " << (flags & Update::FitCursor)
702 << ", forceupdate = " << (flags & Update::Force)
703 << ", singlepar = " << (flags & Update::SinglePar)
704 << "] buffer: " << buffer_ << endl;
706 // Check needed to survive LyX startup
708 // Update macro store
709 buffer_->buildMacros();
712 std::swap(theCoords, backup);
714 // This, together with doneUpdating(), verifies (using
715 // asserts) that screen redraw is not called from
717 theCoords.startUpdating();
719 // First drawing step
720 ViewMetricsInfo vi = metrics(flags & Update::SinglePar);
721 bool forceupdate(flags & (Update::Force | Update::SinglePar));
723 if ((flags & Update::FitCursor) && fitCursor()) {
727 if ((flags & Update::MultiParSel) && multiParSel()) {
732 // Second drawing step
733 workArea_->redraw(*bv_, vi);
735 // Abort updating of the coord
736 // cache - just restore the old one
737 std::swap(theCoords, backup);
740 workArea_->greyOut();
744 owner_->view_state_changed();
748 // Callback for cursor timer
749 void BufferView::Pimpl::cursorToggle()
752 owner_->gui().guiCursor().toggle(*bv_);
754 // Use this opportunity to deal with any child processes that
755 // have finished but are waiting to communicate this fact
756 // to the rest of LyX.
757 ForkedcallsController & fcc = ForkedcallsController::get();
758 fcc.handleCompletedProcesses();
761 cursor_timeout.restart();
765 bool BufferView::Pimpl::available() const
767 return buffer_ && bv_->text();
771 Change const BufferView::Pimpl::getCurrentChange()
773 if (!buffer_->params().tracking_changes)
774 return Change(Change::UNCHANGED);
776 LyXText * text = bv_->getLyXText();
777 LCursor & cur = cursor_;
779 if (!cur.selection())
780 return Change(Change::UNCHANGED);
782 return text->getPar(cur.selBegin().pit()).
783 lookupChange(cur.selBegin().pos());
787 void BufferView::Pimpl::savePosition(unsigned int i)
789 if (i >= saved_positions_num)
791 BOOST_ASSERT(cursor_.inTexted());
792 saved_positions[i] = Position(buffer_->fileName(),
793 cursor_.paragraph().id(),
796 owner_->message(bformat(_("Saved bookmark %1$d"), i));
800 void BufferView::Pimpl::restorePosition(unsigned int i)
802 if (i >= saved_positions_num)
805 string const fname = saved_positions[i].filename;
807 cursor_.clearSelection();
809 if (fname != buffer_->fileName()) {
811 if (bufferlist.exists(fname))
812 b = bufferlist.getBuffer(fname);
814 b = bufferlist.newBuffer(fname);
815 // Don't ask, just load it
816 ::loadLyXFile(b, fname);
822 ParIterator par = buffer_->getParFromID(saved_positions[i].par_id);
823 if (par == buffer_->par_iterator_end())
826 bv_->setCursor(makeDocIterator(par, min(par->size(), saved_positions[i].par_pos)));
829 owner_->message(bformat(_("Moved to bookmark %1$d"), i));
833 bool BufferView::Pimpl::isSavedPosition(unsigned int i)
835 return i < saved_positions_num && !saved_positions[i].filename.empty();
839 void BufferView::Pimpl::saveSavedPositions()
841 // save bookmarks. It is better to use the pit interface
842 // but I do not know how to effectively convert between
844 for (unsigned int i=1; i < saved_positions_num; ++i) {
845 if ( isSavedPosition(i) )
846 LyX::ref().session().saveBookmark( boost::tie(
848 saved_positions[i].filename,
849 saved_positions[i].par_id,
850 saved_positions[i].par_pos) );
855 void BufferView::Pimpl::switchKeyMap()
857 if (!lyxrc.rtl_support)
860 Intl & intl = owner_->getIntl();
861 if (bv_->getLyXText()->real_current_font.isRightToLeft()) {
862 if (intl.keymap == Intl::PRIMARY)
865 if (intl.keymap == Intl::SECONDARY)
871 void BufferView::Pimpl::center()
873 CursorSlice & bot = cursor_.bottom();
874 lyx::pit_type const pit = bot.pit();
875 bot.text()->redoParagraph(pit);
876 Paragraph const & par = bot.text()->paragraphs()[pit];
878 offset_ref_ = bv_funcs::coordOffset(cursor_, cursor_.boundary()).y_
879 + par.ascent() - workArea_->height() / 2;
883 void BufferView::Pimpl::stuffClipboard(string const & content) const
885 clipboard().put(content);
889 void BufferView::Pimpl::menuInsertLyXFile(string const & filenm)
891 BOOST_ASSERT(cursor_.inTexted());
892 string filename = filenm;
894 if (filename.empty()) {
895 // Launch a file browser
896 string initpath = lyxrc.document_path;
899 string const trypath = owner_->buffer()->filePath();
900 // If directory is writeable, use this as default.
901 if (isDirWriteable(trypath))
905 FileDialog fileDlg(_("Select LyX document to insert"),
907 make_pair(string(_("Documents|#o#O")),
908 string(lyxrc.document_path)),
909 make_pair(string(_("Examples|#E#e")),
910 string(addPath(package().system_support(), "examples"))));
912 FileDialog::Result result =
913 fileDlg.open(initpath,
914 FileFilterList(_("LyX Documents (*.lyx)")),
917 if (result.first == FileDialog::Later)
920 filename = result.second;
922 // check selected filename
923 if (filename.empty()) {
924 owner_->message(_("Canceled."));
929 // Get absolute path of file and add ".lyx"
930 // to the filename if necessary
931 filename = fileSearch(string(), filename, "lyx");
933 string const disp_fn = makeDisplayPath(filename);
934 owner_->message(bformat(_("Inserting document %1$s..."), disp_fn));
937 Buffer buf("", false);
938 buf.error.connect(boost::bind(&BufferView::Pimpl::addError, this, _1));
939 if (::loadLyXFile(&buf, makeAbsPath(filename))) {
940 lyx::cap::pasteParagraphList(cursor_, buf.paragraphs(),
941 buf.params().textclass);
942 res = _("Document %1$s inserted.");
944 res = _("Could not insert document %1$s");
946 owner_->message(bformat(res, disp_fn));
947 bv_->showErrorList(_("Document insertion"));
948 resizeCurrentBuffer();
952 void BufferView::Pimpl::trackChanges()
954 bool const tracking = buffer_->params().tracking_changes;
957 for_each(buffer_->par_iterator_begin(),
958 buffer_->par_iterator_end(),
959 bind(&Paragraph::trackChanges, _1, Change::UNCHANGED));
960 buffer_->params().tracking_changes = true;
962 // We cannot allow undos beyond the freeze point
963 buffer_->undostack().clear();
965 cursor_.setCursor(doc_iterator_begin(buffer_->inset()));
966 if (lyx::find::findNextChange(bv_)) {
967 owner_->getDialogs().show("changes");
971 for_each(buffer_->par_iterator_begin(),
972 buffer_->par_iterator_end(),
973 mem_fun_ref(&Paragraph::untrackChanges));
975 buffer_->params().tracking_changes = false;
978 buffer_->redostack().clear();
982 bool BufferView::Pimpl::workAreaDispatch(FuncRequest const & cmd0)
984 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
986 // This is only called for mouse related events including
987 // LFUN_FILE_OPEN generated by drag-and-drop.
988 FuncRequest cmd = cmd0;
991 if (cmd.action == LFUN_FILE_OPEN) {
992 owner_->dispatch(cmd);
1000 cur.push(buffer_->inset());
1001 cur.selection() = cursor_.selection();
1003 // Doesn't go through lyxfunc, so we need to update
1004 // the layout choice etc. ourselves
1006 // E.g. Qt mouse press when no buffer
1010 owner_->gui().guiCursor().hide();
1012 // Either the inset under the cursor or the
1013 // surrounding LyXText will handle this event.
1015 // Build temporary cursor.
1016 cmd.y = min(max(cmd.y, -1), workArea_->height());
1017 InsetBase * inset = bv_->text()->editXY(cur, cmd.x, cmd.y);
1018 //lyxerr << BOOST_CURRENT_FUNCTION
1019 // << " * hit inset at tip: " << inset << endl;
1020 //lyxerr << BOOST_CURRENT_FUNCTION
1021 // << " * created temp cursor:" << cur << endl;
1023 // Put anchor at the same position.
1026 // Try to dispatch to an non-editable inset near this position
1027 // via the temp cursor. If the inset wishes to change the real
1028 // cursor it has to do so explicitly by using
1029 // cur.bv().cursor() = cur; (or similar)
1031 inset->dispatch(cur, cmd);
1033 // Now dispatch to the temporary cursor. If the real cursor should
1034 // be modified, the inset's dispatch has to do so explicitly.
1035 if (!cur.result().dispatched())
1038 if (cur.result().dispatched()) {
1039 // Redraw if requested or necessary.
1040 if (cur.result().update())
1041 update(Update::FitCursor | Update::Force);
1043 update(Update::FitCursor | Update::MultiParSel);
1046 // See workAreaKeyPress
1047 cursor_timeout.restart();
1048 owner_->gui().guiCursor().show(*bv_);
1050 // Skip these when selecting
1051 if (cmd.action != LFUN_MOUSE_MOTION) {
1052 owner_->updateLayoutChoice();
1053 owner_->updateToolbars();
1056 // Slight hack: this is only called currently when we
1057 // clicked somewhere, so we force through the display
1058 // of the new status here.
1059 owner_->clearMessage();
1064 FuncStatus BufferView::Pimpl::getStatus(FuncRequest const & cmd)
1068 switch (cmd.action) {
1071 flag.enabled(!buffer_->undostack().empty());
1074 flag.enabled(!buffer_->redostack().empty());
1076 case LFUN_FILE_INSERT:
1077 case LFUN_FILE_INSERT_ASCII_PARA:
1078 case LFUN_FILE_INSERT_ASCII:
1079 case LFUN_BOOKMARK_SAVE:
1080 // FIXME: Actually, these LFUNS should be moved to LyXText
1081 flag.enabled(cursor_.inTexted());
1083 case LFUN_FONT_STATE:
1084 case LFUN_LABEL_INSERT:
1085 case LFUN_PARAGRAPH_GOTO:
1086 // FIXME handle non-trivially
1087 case LFUN_OUTLINE_UP:
1088 case LFUN_OUTLINE_DOWN:
1089 case LFUN_OUTLINE_IN:
1090 case LFUN_OUTLINE_OUT:
1091 case LFUN_ERROR_NEXT:
1092 case LFUN_NOTE_NEXT:
1093 case LFUN_REFERENCE_NEXT:
1094 case LFUN_WORD_FIND:
1095 case LFUN_WORD_REPLACE:
1098 case LFUN_MARK_TOGGLE:
1099 case LFUN_SCREEN_RECENTER:
1100 case LFUN_BIBTEX_DATABASE_ADD:
1101 case LFUN_BIBTEX_DATABASE_DEL:
1102 case LFUN_WORDS_COUNT:
1106 case LFUN_LABEL_GOTO: {
1107 flag.enabled(!cmd.argument.empty()
1108 || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
1112 case LFUN_BOOKMARK_GOTO:
1113 flag.enabled(isSavedPosition(convert<unsigned int>(cmd.argument)));
1115 case LFUN_CHANGES_TRACK:
1117 flag.setOnOff(buffer_->params().tracking_changes);
1120 case LFUN_CHANGES_OUTPUT: {
1121 OutputParams runparams;
1122 LaTeXFeatures features(*buffer_, buffer_->params(), runparams);
1123 flag.enabled(buffer_ && buffer_->params().tracking_changes
1124 && features.isAvailable("dvipost"));
1125 flag.setOnOff(buffer_->params().output_changes);
1129 case LFUN_CHANGES_MERGE:
1130 case LFUN_CHANGE_ACCEPT: // what about these two
1131 case LFUN_CHANGE_REJECT: // what about these two
1132 case LFUN_ALL_CHANGES_ACCEPT:
1133 case LFUN_ALL_CHANGES_REJECT:
1134 flag.enabled(buffer_ && buffer_->params().tracking_changes);
1137 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
1138 flag.setOnOff(buffer_->params().compressed);
1143 flag.enabled(false);
1151 bool BufferView::Pimpl::dispatch(FuncRequest const & cmd)
1153 //lyxerr << BOOST_CURRENT_FUNCTION
1154 // << [ cmd = " << cmd << "]" << endl;
1156 // Make sure that the cached BufferView is correct.
1157 lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
1158 << " action[" << cmd.action << ']'
1159 << " arg[" << cmd.argument << ']'
1160 << " x[" << cmd.x << ']'
1161 << " y[" << cmd.y << ']'
1162 << " button[" << cmd.button() << ']'
1165 LCursor & cur = cursor_;
1167 switch (cmd.action) {
1171 cur.message(_("Undo"));
1172 cur.clearSelection();
1173 if (!textUndo(*bv_))
1174 cur.message(_("No further undo information"));
1182 cur.message(_("Redo"));
1183 cur.clearSelection();
1184 if (!textRedo(*bv_))
1185 cur.message(_("No further redo information"));
1191 case LFUN_FILE_INSERT:
1192 menuInsertLyXFile(cmd.argument);
1195 case LFUN_FILE_INSERT_ASCII_PARA:
1196 insertAsciiFile(bv_, cmd.argument, true);
1199 case LFUN_FILE_INSERT_ASCII:
1200 insertAsciiFile(bv_, cmd.argument, false);
1203 case LFUN_FONT_STATE:
1204 cur.message(cur.currentState());
1207 case LFUN_BOOKMARK_SAVE:
1208 savePosition(convert<unsigned int>(cmd.argument));
1211 case LFUN_BOOKMARK_GOTO:
1212 restorePosition(convert<unsigned int>(cmd.argument));
1215 case LFUN_LABEL_GOTO: {
1216 string label = cmd.argument;
1217 if (label.empty()) {
1219 getInsetByCode<InsetRef>(cursor_,
1220 InsetBase::REF_CODE);
1222 label = inset->getContents();
1228 bv_->gotoLabel(label);
1232 case LFUN_PARAGRAPH_GOTO: {
1233 int const id = convert<int>(cmd.argument);
1234 ParIterator par = buffer_->getParFromID(id);
1235 if (par == buffer_->par_iterator_end()) {
1236 lyxerr[Debug::INFO] << "No matching paragraph found! ["
1237 << id << ']' << endl;
1240 lyxerr[Debug::INFO] << "Paragraph " << par->id()
1241 << " found." << endl;
1245 bv_->setCursor(makeDocIterator(par, 0));
1252 case LFUN_OUTLINE_UP:
1253 lyx::toc::outline(lyx::toc::Up, cursor_);
1254 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
1255 updateLabels(*buffer_);
1257 case LFUN_OUTLINE_DOWN:
1258 lyx::toc::outline(lyx::toc::Down, cursor_);
1259 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
1260 updateLabels(*buffer_);
1262 case LFUN_OUTLINE_IN:
1263 lyx::toc::outline(lyx::toc::In, cursor_);
1264 updateLabels(*buffer_);
1266 case LFUN_OUTLINE_OUT:
1267 lyx::toc::outline(lyx::toc::Out, cursor_);
1268 updateLabels(*buffer_);
1271 case LFUN_ERROR_NEXT:
1272 bv_funcs::gotoInset(bv_, InsetBase::ERROR_CODE, false);
1275 case LFUN_NOTE_NEXT:
1276 bv_funcs::gotoInset(bv_, InsetBase::NOTE_CODE, false);
1279 case LFUN_REFERENCE_NEXT: {
1280 vector<InsetBase_code> tmp;
1281 tmp.push_back(InsetBase::LABEL_CODE);
1282 tmp.push_back(InsetBase::REF_CODE);
1283 bv_funcs::gotoInset(bv_, tmp, true);
1287 case LFUN_CHANGES_TRACK:
1291 case LFUN_CHANGES_OUTPUT: {
1292 bool const state = buffer_->params().output_changes;
1293 buffer_->params().output_changes = !state;
1297 case LFUN_CHANGES_MERGE:
1298 if (lyx::find::findNextChange(bv_))
1299 owner_->getDialogs().show("changes");
1302 case LFUN_ALL_CHANGES_ACCEPT: {
1303 cursor_.reset(buffer_->inset());
1304 #ifdef WITH_WARNINGS
1305 #warning FIXME changes
1307 while (lyx::find::findNextChange(bv_))
1308 bv_->getLyXText()->acceptChange(cursor_);
1313 case LFUN_ALL_CHANGES_REJECT: {
1314 cursor_.reset(buffer_->inset());
1315 #ifdef WITH_WARNINGS
1316 #warning FIXME changes
1318 while (lyx::find::findNextChange(bv_))
1319 bv_->getLyXText()->rejectChange(cursor_);
1323 case LFUN_WORD_FIND:
1324 lyx::find::find(bv_, cmd);
1327 case LFUN_WORD_REPLACE:
1328 lyx::find::replace(bv_, cmd);
1332 cur.clearSelection();
1334 cur.message(N_("Mark off"));
1338 cur.clearSelection();
1341 cur.message(N_("Mark on"));
1344 case LFUN_MARK_TOGGLE:
1345 cur.clearSelection();
1348 cur.message(N_("Mark removed"));
1351 cur.message(N_("Mark set"));
1356 case LFUN_SCREEN_RECENTER:
1360 case LFUN_BIBTEX_DATABASE_ADD: {
1361 LCursor tmpcur = cursor_;
1362 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
1363 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1364 InsetBase::BIBTEX_CODE);
1366 if (inset->addDatabase(cmd.argument))
1367 buffer_->updateBibfilesCache();
1372 case LFUN_BIBTEX_DATABASE_DEL: {
1373 LCursor tmpcur = cursor_;
1374 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
1375 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1376 InsetBase::BIBTEX_CODE);
1378 if (inset->delDatabase(cmd.argument))
1379 buffer_->updateBibfilesCache();
1384 case LFUN_WORDS_COUNT: {
1385 DocIterator from, to;
1386 if (cur.selection()) {
1387 from = cur.selectionBegin();
1388 to = cur.selectionEnd();
1390 from = doc_iterator_begin(buffer_->inset());
1391 to = doc_iterator_end(buffer_->inset());
1393 int const count = countWords(from, to);
1396 if (cur.selection())
1397 message = bformat(_("%1$d words in selection."),
1400 message = bformat(_("%1$d words in document."),
1404 if (cur.selection())
1405 message = _("One word in selection.");
1407 message = _("One word in document.");
1410 Alert::information(_("Count words"), message);
1414 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1415 // turn compression on/off
1416 buffer_->params().compressed = !buffer_->params().compressed;
1427 ViewMetricsInfo BufferView::Pimpl::metrics(bool singlepar)
1429 // Remove old position cache
1431 BufferView & bv = *bv_;
1432 LyXText * const text = bv.text();
1433 lyx::pit_type size = int(text->paragraphs().size());
1435 if (anchor_ref_ > int(text->paragraphs().size() - 1)) {
1436 anchor_ref_ = int(text->paragraphs().size() - 1);
1440 lyx::pit_type const pit = anchor_ref_;
1443 size_t const npit = text->paragraphs().size();
1445 // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
1446 // the (main text, not inset!) paragraph containing the cursor.
1447 // (if this paragraph contains insets etc., rebreaking will
1448 // recursively descend)
1449 if (!singlepar || pit == cursor_.bottom().pit())
1450 text->redoParagraph(pit);
1451 int y0 = text->getPar(pit).ascent() - offset_ref_;
1453 // Redo paragraphs above anchor if necessary; again, in Single Par
1454 // mode, only if we encounter the (main text) one having the cursor.
1456 while (y1 > 0 && pit1 > 0) {
1457 y1 -= text->getPar(pit1).ascent();
1459 if (!singlepar || pit1 == cursor_.bottom().pit())
1460 text->redoParagraph(pit1);
1461 y1 -= text->getPar(pit1).descent();
1465 // Take care of ascent of first line
1466 y1 -= text->getPar(pit1).ascent();
1468 // Normalize anchor for next time
1472 // Grey at the beginning is ugly
1473 if (pit1 == 0 && y1 > 0) {
1479 // Redo paragraphs below the anchor if necessary. Single par mode:
1480 // only the one containing the cursor if encountered.
1482 while (y2 < bv.workHeight() && pit2 < int(npit) - 1) {
1483 y2 += text->getPar(pit2).descent();
1485 if (!singlepar || pit2 == cursor_.bottom().pit())
1486 text->redoParagraph(pit2);
1487 y2 += text->getPar(pit2).ascent();
1490 // Take care of descent of last line
1491 y2 += text->getPar(pit2).descent();
1493 // The coordinates of all these paragraphs are correct, cache them
1495 for (lyx::pit_type pit = pit1; pit <= pit2; ++pit) {
1496 y += text->getPar(pit).ascent();
1497 theCoords.parPos()[text][pit] = Point(0, y);
1498 if (singlepar && pit == cursor_.bottom().pit()) {
1499 // In Single Paragraph mode, collect here the
1500 // y1 and y2 of the (one) paragraph the cursor is in
1501 y1 = y - text->getPar(pit).ascent();
1502 y2 = y + text->getPar(pit).descent();
1504 y += text->getPar(pit).descent();
1508 // collect cursor paragraph iter bounds
1509 pit1 = cursor_.bottom().pit();
1510 pit2 = cursor_.bottom().pit();
1513 lyxerr[Debug::DEBUG]
1514 << BOOST_CURRENT_FUNCTION
1517 << " pit1: " << pit1
1518 << " pit2: " << pit2
1519 << " npit: " << npit
1520 << " singlepar: " << singlepar
1524 return ViewMetricsInfo(pit1, pit2, y1, y2, singlepar, size);