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/WorkArea.h"
69 #include "graphics/Previews.h"
71 #include "support/convert.h"
72 #include "support/filefilterlist.h"
73 #include "support/filetools.h"
74 #include "support/forkedcontr.h"
75 #include "support/package.h"
76 #include "support/types.h"
78 #include <boost/bind.hpp>
79 #include <boost/current_function.hpp>
84 using lyx::frontend::WorkArea;
85 using lyx::frontend::Clipboard;
86 using lyx::frontend::Gui;
90 using lyx::support::addPath;
91 using lyx::support::bformat;
92 using lyx::support::FileFilterList;
93 using lyx::support::fileSearch;
94 using lyx::support::ForkedcallsController;
95 using lyx::support::isDirWriteable;
96 using lyx::support::makeDisplayPath;
97 using lyx::support::makeAbsPath;
98 using lyx::support::package;
101 using std::istringstream;
102 using std::make_pair;
106 using std::mem_fun_ref;
109 extern BufferList bufferlist;
114 unsigned int const saved_positions_num = 20;
116 // All the below connection objects are needed because of a bug in some
117 // versions of GCC (<=2.96 are on the suspects list.) By having and assigning
118 // to these connections we avoid a segfault upon startup, and also at exit.
121 boost::signals::connection timecon;
123 /// Return an inset of this class if it exists at the current cursor position
125 T * getInsetByCode(LCursor & cur, InsetBase::Code code)
128 DocIterator it = cur;
129 if (it.nextInset() &&
130 it.nextInset()->lyxCode() == code) {
131 inset = static_cast<T*>(it.nextInset());
139 BufferView::Pimpl::Pimpl(BufferView & bv, LyXView * owner)
140 : bv_(&bv), owner_(owner), buffer_(0), wh_(0), cursor_timeout(400),
141 using_xterm_cursor(false), cursor_(bv),
142 multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0)
144 xsel_cache_.set = false;
147 timecon = cursor_timeout.timeout
148 .connect(boost::bind(&BufferView::Pimpl::cursorToggle, this));
150 cursor_timeout.start();
152 saved_positions.resize(saved_positions_num);
153 // load saved bookmarks
154 lyx::Session::BookmarkList & bmList = LyX::ref().session().loadBookmarks();
155 for (lyx::Session::BookmarkList::iterator bm = bmList.begin();
156 bm != bmList.end(); ++bm)
157 if (bm->get<0>() < saved_positions_num)
158 saved_positions[bm->get<0>()] = Position( bm->get<1>(), bm->get<2>(), bm->get<3>() );
159 // and then clear them
164 void BufferView::Pimpl::addError(ErrorItem const & ei)
166 errorlist_.push_back(ei);
170 void BufferView::Pimpl::showReadonly(bool)
172 owner_->updateWindowTitle();
173 owner_->getDialogs().updateBufferDependent(false);
177 void BufferView::Pimpl::connectBuffer(Buffer & buf)
179 if (errorConnection_.connected())
184 boost::bind(&BufferView::Pimpl::addError, this, _1));
188 boost::bind(&LyXView::message, owner_, _1));
192 boost::bind(&LyXView::busy, owner_, _1));
195 buf.updateTitles.connect(
196 boost::bind(&LyXView::updateWindowTitle, owner_));
199 buf.resetAutosaveTimers.connect(
200 boost::bind(&LyXView::resetAutosaveTimer, owner_));
202 readonlyConnection_ =
203 buf.readonly.connect(
204 boost::bind(&BufferView::Pimpl::showReadonly, this, _1));
208 boost::bind(&BufferView::Pimpl::setBuffer, this, (Buffer *)0));
212 void BufferView::Pimpl::disconnectBuffer()
214 errorConnection_.disconnect();
215 messageConnection_.disconnect();
216 busyConnection_.disconnect();
217 titleConnection_.disconnect();
218 timerConnection_.disconnect();
219 readonlyConnection_.disconnect();
220 closingConnection_.disconnect();
224 void BufferView::Pimpl::newFile(string const & filename, string const & tname,
227 setBuffer(::newFile(filename, tname, isNamed));
231 bool BufferView::Pimpl::loadLyXFile(string const & filename, bool tolastfiles)
233 // Get absolute path of file and add ".lyx"
234 // to the filename if necessary
235 string s = fileSearch(string(), filename, "lyx");
237 bool const found = !s.empty();
242 // File already open?
243 if (bufferlist.exists(s)) {
244 string const file = makeDisplayPath(s, 20);
245 string text = bformat(_("The document %1$s is already "
246 "loaded.\n\nDo you want to revert "
247 "to the saved version?"), file);
248 int const ret = Alert::prompt(_("Revert to saved document?"),
249 text, 0, 1, _("&Revert"), _("&Switch to document"));
252 setBuffer(bufferlist.getBuffer(s));
255 // FIXME: should be LFUN_REVERT
256 if (!bufferlist.close(bufferlist.getBuffer(s), false))
258 // Fall through to new load. (Asger)
264 b = bufferlist.newBuffer(s);
266 if (!::loadLyXFile(b, s)) {
267 bufferlist.release(b);
271 string text = bformat(_("The document %1$s does not yet "
272 "exist.\n\nDo you want to create "
273 "a new document?"), s);
274 int const ret = Alert::prompt(_("Create new document?"),
275 text, 0, 1, _("&Create"), _("Cancel"));
278 b = ::newFile(s, string(), true);
284 bv_->showErrorList(_("Parse"));
286 // scroll to the position when the file was last closed
287 if (lyxrc.use_lastfilepos) {
290 boost::tie(pit, pos) = LyX::ref().session().loadFilePosition(s);
291 // I am not sure how to separate the following part to a function
292 // so I will leave this to Lars.
294 // check pit since the document may be externally changed.
295 if ( static_cast<size_t>(pit) < b->paragraphs().size() ) {
296 ParIterator it = b->par_iterator_begin();
297 ParIterator const end = b->par_iterator_end();
298 for (; it != end; ++it)
299 if (it.pit() == pit) {
300 // restored pos may be bigger than it->size
301 bv_->setCursor(makeDocIterator(it, min(pos, it->size())));
302 bv_->update(Update::FitCursor);
309 LyX::ref().session().addLastFile(b->fileName());
315 lyx::frontend::Gui & BufferView::Pimpl::gui() const
317 return owner_->gui();
321 int BufferView::Pimpl::width() const
327 int BufferView::Pimpl::height() const
333 void BufferView::Pimpl::setBuffer(Buffer * b)
335 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
336 << "[ b = " << b << "]" << endl;
340 // Save the actual cursor position and anchor inside the
341 // buffer so that it can be restored in case we rechange
342 // to this buffer later on.
343 buffer_->saveCursor(cursor_.selectionBegin(),
344 cursor_.selectionEnd());
345 // current buffer is going to be switched-off, save cursor pos
346 LyX::ref().session().saveFilePosition(buffer_->fileName(),
347 boost::tie(cursor_.pit(), cursor_.pos()) );
350 // If we are closing current buffer, switch to the first in
353 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
354 << " No Buffer!" << endl;
355 // We are closing the buffer, use the first buffer as current
356 buffer_ = bufferlist.first();
357 owner_->getDialogs().hideBufferDependent();
359 // Set current buffer
364 cursor_ = LCursor(*bv_);
369 // If we're quitting lyx, don't bother updating stuff
374 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
375 << "Buffer addr: " << buffer_ << endl;
376 connectBuffer(*buffer_);
377 cursor_.push(buffer_->inset());
378 cursor_.resetAnchor();
379 buffer_->text().init(bv_);
380 buffer_->text().setCurrentFont(cursor_);
381 if (buffer_->getCursor().size() > 0 &&
382 buffer_->getAnchor().size() > 0)
384 cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
385 cursor_.resetAnchor();
386 cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
387 cursor_.setSelection();
390 // Buffer-dependent dialogs should be updated or
391 // hidden. This should go here because some dialogs (eg ToC)
392 // require bv_->text.
393 owner_->getDialogs().updateBufferDependent(true);
397 owner_->updateMenubar();
398 owner_->updateToolbars();
399 owner_->updateLayoutChoice();
400 owner_->updateWindowTitle();
402 // This is done after the layout combox has been populated
404 size_t i = cursor_.depth() - 1;
405 // we know we'll eventually find a paragraph
407 CursorSlice const & slice = cursor_[i];
408 if (!slice.inset().inMathed()) {
409 LyXLayout_ptr const layout = slice.paragraph().layout();
410 owner_->setLayout(layout->name());
418 if (buffer_ && lyx::graphics::Previews::status() != LyXRC::PREVIEW_OFF)
419 lyx::graphics::Previews::get().generateBufferPreviews(*buffer_);
423 void BufferView::Pimpl::resizeCurrentBuffer()
425 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
427 owner_->message(_("Formatting document..."));
429 LyXText * text = bv_->text();
439 // Reset the "Formatting..." message
440 owner_->clearMessage();
444 void BufferView::Pimpl::updateScrollbar()
447 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
448 << " no text in updateScrollbar" << endl;
449 scrollbarParameters_.reset();
453 LyXText & t = *bv_->text();
454 int const parsize = int(t.paragraphs().size() - 1);
455 if (anchor_ref_ > parsize) {
456 anchor_ref_ = parsize;
461 << BOOST_CURRENT_FUNCTION
462 << " Updating scrollbar: height: " << t.paragraphs().size()
463 << " curr par: " << cursor_.bottom().pit()
464 << " default height " << defaultRowHeight() << endl;
466 // It would be better to fix the scrollbar to understand
467 // values in [0..1] and divide everything by wh
469 // estimated average paragraph height:
472 int h = t.getPar(anchor_ref_).height();
474 // Normalize anchor/offset (MV):
475 while (offset_ref_ > h && anchor_ref_ < parsize) {
478 h = t.getPar(anchor_ref_).height();
480 // Look at paragraph heights on-screen
483 for (lyx::pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
486 int const h2 = t.getPar(pit).height();
490 int const hav = sumh / nh;
491 // More realistic average paragraph height
495 scrollbarParameters_.height = (parsize + 1) * wh_;
496 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
497 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
501 ScrollbarParameters const & BufferView::Pimpl::scrollbarParameters() const
503 return scrollbarParameters_;
507 void BufferView::Pimpl::scrollDocView(int value)
509 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
510 << "[ value = " << value << "]" << endl;
515 owner_->gui().guiCursor().hide();
517 LyXText & t = *bv_->text();
519 float const bar = value / float(wh_ * t.paragraphs().size());
521 anchor_ref_ = int(bar * t.paragraphs().size());
522 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
523 anchor_ref_ = int(t.paragraphs().size()) - 1;
524 t.redoParagraph(anchor_ref_);
525 int const h = t.getPar(anchor_ref_).height();
526 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
529 if (!lyxrc.cursor_follows_scrollbar)
532 int const height = 2 * defaultRowHeight();
533 int const first = height;
534 int const last = height_ - height;
535 LCursor & cur = cursor_;
537 bv_funcs::CurStatus st = bv_funcs::status(bv_, cur);
540 case bv_funcs::CUR_ABOVE:
541 t.setCursorFromCoordinates(cur, 0, first);
542 cur.clearSelection();
544 case bv_funcs::CUR_BELOW:
545 t.setCursorFromCoordinates(cur, 0, last);
546 cur.clearSelection();
548 case bv_funcs::CUR_INSIDE:
549 int const y = bv_funcs::getPos(cur, cur.boundary()).y_;
550 int const newy = min(last, max(y, first));
552 cur.reset(buffer_->inset());
553 t.setCursorFromCoordinates(cur, 0, newy);
556 owner_->updateLayoutChoice();
560 void BufferView::Pimpl::scroll(int /*lines*/)
565 // LyXText const * t = bv_->text();
566 // int const line_height = defaultRowHeight();
568 // // The new absolute coordinate
569 // int new_top_y = top_y() + lines * line_height;
571 // // Restrict to a valid value
572 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
573 // new_top_y = std::max(0, new_top_y);
575 // scrollDocView(new_top_y);
577 // // Update the scrollbar.
578 // workArea_->setScrollbarParams(t->height(), top_y(), defaultRowHeight());
582 void BufferView::Pimpl::workAreaKeyPress(LyXKeySymPtr key,
583 key_modifier::state state)
585 owner_->getLyXFunc().processKeySym(key, state);
587 /* This is perhaps a bit of a hack. When we move
588 * around, or type, it's nice to be able to see
589 * the cursor immediately after the keypress. So
590 * we reset the toggle timeout and force the visibility
591 * of the cursor. Note we cannot do this inside
592 * dispatch() itself, because that's called recursively.
595 owner_->gui().guiCursor().show(*bv_);
599 void BufferView::Pimpl::selectionRequested()
606 LCursor & cur = cursor_;
608 if (!cur.selection()) {
609 xsel_cache_.set = false;
613 if (!xsel_cache_.set ||
614 cur.top() != xsel_cache_.cursor ||
615 cur.anchor_.top() != xsel_cache_.anchor)
617 xsel_cache_.cursor = cur.top();
618 xsel_cache_.anchor = cur.anchor_.top();
619 xsel_cache_.set = cur.selection();
620 sel = cur.selectionAsString(false);
622 owner_->gui().clipboard().put(sel);
627 void BufferView::Pimpl::selectionLost()
630 owner_->gui().guiCursor().hide();
631 cursor_.clearSelection();
632 xsel_cache_.set = false;
637 void BufferView::Pimpl::workAreaResize(int width, int height)
639 bool const widthChange = width != width_;
640 bool const heightChange = height != height_;
642 // Update from work area
646 if (buffer_ && widthChange) {
647 // The visible LyXView need a resize
648 resizeCurrentBuffer();
651 if (widthChange || heightChange)
654 owner_->updateLayoutChoice();
658 bool BufferView::Pimpl::fitCursor()
660 if (bv_funcs::status(bv_, cursor_) == bv_funcs::CUR_INSIDE) {
661 LyXFont const font = cursor_.getFont();
662 int const asc = font_metrics::maxAscent(font);
663 int const des = font_metrics::maxDescent(font);
664 Point const p = bv_funcs::getPos(cursor_, cursor_.boundary());
665 if (p.y_ - asc >= 0 && p.y_ + des < height_)
673 bool BufferView::Pimpl::multiParSel()
675 if (!cursor_.selection())
677 bool ret = multiparsel_cache_;
678 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
679 // Either this, or previous selection spans paragraphs
680 return ret || multiparsel_cache_;
684 ViewMetricsInfo const & BufferView::Pimpl::viewMetricsInfo()
686 return metrics_info_;
690 void BufferView::Pimpl::update(Update::flags flags)
693 << BOOST_CURRENT_FUNCTION
694 << "[fitcursor = " << (flags & Update::FitCursor)
695 << ", forceupdate = " << (flags & Update::Force)
696 << ", singlepar = " << (flags & Update::SinglePar)
697 << "] buffer: " << buffer_ << endl;
699 // Check needed to survive LyX startup
701 // Update macro store
702 buffer_->buildMacros();
705 std::swap(theCoords, backup);
707 // This, together with doneUpdating(), verifies (using
708 // asserts) that screen redraw is not called from
710 theCoords.startUpdating();
712 // First drawing step
713 updateMetrics(flags & Update::SinglePar);
714 bool forceupdate(flags & (Update::Force | Update::SinglePar));
716 if ((flags & Update::FitCursor) && fitCursor()) {
720 if ((flags & Update::MultiParSel) && multiParSel()) {
725 // Second drawing step
726 owner_->workArea()->redraw(*bv_);
728 // Abort updating of the coord
729 // cache - just restore the old one
730 std::swap(theCoords, backup);
733 owner_->workArea()->greyOut();
735 owner_->view_state_changed();
739 // Callback for cursor timer
740 void BufferView::Pimpl::cursorToggle()
743 owner_->gui().guiCursor().toggle(*bv_);
745 // Use this opportunity to deal with any child processes that
746 // have finished but are waiting to communicate this fact
747 // to the rest of LyX.
748 ForkedcallsController & fcc = ForkedcallsController::get();
749 fcc.handleCompletedProcesses();
752 cursor_timeout.restart();
756 bool BufferView::Pimpl::available() const
758 return buffer_ && bv_->text();
762 Change const BufferView::Pimpl::getCurrentChange()
764 if (!buffer_->params().tracking_changes)
765 return Change(Change::UNCHANGED);
767 LyXText * text = bv_->getLyXText();
768 LCursor & cur = cursor_;
770 if (!cur.selection())
771 return Change(Change::UNCHANGED);
773 return text->getPar(cur.selBegin().pit()).
774 lookupChange(cur.selBegin().pos());
778 void BufferView::Pimpl::savePosition(unsigned int i)
780 if (i >= saved_positions_num)
782 BOOST_ASSERT(cursor_.inTexted());
783 saved_positions[i] = Position(buffer_->fileName(),
784 cursor_.paragraph().id(),
787 owner_->message(bformat(_("Saved bookmark %1$d"), i));
791 void BufferView::Pimpl::restorePosition(unsigned int i)
793 if (i >= saved_positions_num)
796 string const fname = saved_positions[i].filename;
798 cursor_.clearSelection();
800 if (fname != buffer_->fileName()) {
802 if (bufferlist.exists(fname))
803 b = bufferlist.getBuffer(fname);
805 b = bufferlist.newBuffer(fname);
806 // Don't ask, just load it
807 ::loadLyXFile(b, fname);
813 ParIterator par = buffer_->getParFromID(saved_positions[i].par_id);
814 if (par == buffer_->par_iterator_end())
817 bv_->setCursor(makeDocIterator(par, min(par->size(), saved_positions[i].par_pos)));
820 owner_->message(bformat(_("Moved to bookmark %1$d"), i));
824 bool BufferView::Pimpl::isSavedPosition(unsigned int i)
826 return i < saved_positions_num && !saved_positions[i].filename.empty();
830 void BufferView::Pimpl::saveSavedPositions()
832 // save bookmarks. It is better to use the pit interface
833 // but I do not know how to effectively convert between
835 for (unsigned int i=1; i < saved_positions_num; ++i) {
836 if ( isSavedPosition(i) )
837 LyX::ref().session().saveBookmark( boost::tie(
839 saved_positions[i].filename,
840 saved_positions[i].par_id,
841 saved_positions[i].par_pos) );
846 void BufferView::Pimpl::switchKeyMap()
848 if (!lyxrc.rtl_support)
851 Intl & intl = owner_->getIntl();
852 if (bv_->getLyXText()->real_current_font.isRightToLeft()) {
853 if (intl.keymap == Intl::PRIMARY)
856 if (intl.keymap == Intl::SECONDARY)
862 void BufferView::Pimpl::center()
864 CursorSlice & bot = cursor_.bottom();
865 lyx::pit_type const pit = bot.pit();
866 bot.text()->redoParagraph(pit);
867 Paragraph const & par = bot.text()->paragraphs()[pit];
869 offset_ref_ = bv_funcs::coordOffset(cursor_, cursor_.boundary()).y_
870 + par.ascent() - height_ / 2;
875 void BufferView::Pimpl::menuInsertLyXFile(string const & filenm)
877 BOOST_ASSERT(cursor_.inTexted());
878 string filename = filenm;
880 if (filename.empty()) {
881 // Launch a file browser
882 string initpath = lyxrc.document_path;
885 string const trypath = owner_->buffer()->filePath();
886 // If directory is writeable, use this as default.
887 if (isDirWriteable(trypath))
891 FileDialog fileDlg(_("Select LyX document to insert"),
893 make_pair(string(_("Documents|#o#O")),
894 string(lyxrc.document_path)),
895 make_pair(string(_("Examples|#E#e")),
896 string(addPath(package().system_support(), "examples"))));
898 FileDialog::Result result =
899 fileDlg.open(initpath,
900 FileFilterList(_("LyX Documents (*.lyx)")),
903 if (result.first == FileDialog::Later)
906 filename = result.second;
908 // check selected filename
909 if (filename.empty()) {
910 owner_->message(_("Canceled."));
915 // Get absolute path of file and add ".lyx"
916 // to the filename if necessary
917 filename = fileSearch(string(), filename, "lyx");
919 string const disp_fn = makeDisplayPath(filename);
920 owner_->message(bformat(_("Inserting document %1$s..."), disp_fn));
923 Buffer buf("", false);
924 buf.error.connect(boost::bind(&BufferView::Pimpl::addError, this, _1));
925 if (::loadLyXFile(&buf, makeAbsPath(filename))) {
926 lyx::cap::pasteParagraphList(cursor_, buf.paragraphs(),
927 buf.params().textclass);
928 res = _("Document %1$s inserted.");
930 res = _("Could not insert document %1$s");
932 owner_->message(bformat(res, disp_fn));
933 bv_->showErrorList(_("Document insertion"));
934 resizeCurrentBuffer();
938 void BufferView::Pimpl::trackChanges()
940 bool const tracking = buffer_->params().tracking_changes;
943 for_each(buffer_->par_iterator_begin(),
944 buffer_->par_iterator_end(),
945 bind(&Paragraph::trackChanges, _1, Change::UNCHANGED));
946 buffer_->params().tracking_changes = true;
948 // We cannot allow undos beyond the freeze point
949 buffer_->undostack().clear();
951 cursor_.setCursor(doc_iterator_begin(buffer_->inset()));
952 if (lyx::find::findNextChange(bv_)) {
953 owner_->getDialogs().show("changes");
957 for_each(buffer_->par_iterator_begin(),
958 buffer_->par_iterator_end(),
959 mem_fun_ref(&Paragraph::untrackChanges));
961 buffer_->params().tracking_changes = false;
964 buffer_->redostack().clear();
968 bool BufferView::Pimpl::workAreaDispatch(FuncRequest const & cmd0)
970 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
972 // This is only called for mouse related events including
973 // LFUN_FILE_OPEN generated by drag-and-drop.
974 FuncRequest cmd = cmd0;
977 if (cmd.action == LFUN_FILE_OPEN) {
978 owner_->dispatch(cmd);
986 cur.push(buffer_->inset());
987 cur.selection() = cursor_.selection();
989 // Doesn't go through lyxfunc, so we need to update
990 // the layout choice etc. ourselves
992 // E.g. Qt mouse press when no buffer
996 owner_->gui().guiCursor().hide();
998 // Either the inset under the cursor or the
999 // surrounding LyXText will handle this event.
1001 // Build temporary cursor.
1002 cmd.y = min(max(cmd.y, -1), height_);
1003 InsetBase * inset = bv_->text()->editXY(cur, cmd.x, cmd.y);
1004 //lyxerr << BOOST_CURRENT_FUNCTION
1005 // << " * hit inset at tip: " << inset << endl;
1006 //lyxerr << BOOST_CURRENT_FUNCTION
1007 // << " * created temp cursor:" << cur << endl;
1009 // Put anchor at the same position.
1012 // Try to dispatch to an non-editable inset near this position
1013 // via the temp cursor. If the inset wishes to change the real
1014 // cursor it has to do so explicitly by using
1015 // cur.bv().cursor() = cur; (or similar)
1017 inset->dispatch(cur, cmd);
1019 // Now dispatch to the temporary cursor. If the real cursor should
1020 // be modified, the inset's dispatch has to do so explicitly.
1021 if (!cur.result().dispatched())
1024 if (cur.result().dispatched()) {
1025 // Redraw if requested or necessary.
1026 if (cur.result().update())
1027 update(Update::FitCursor | Update::Force);
1029 update(Update::FitCursor | Update::MultiParSel);
1032 // See workAreaKeyPress
1033 cursor_timeout.restart();
1034 owner_->gui().guiCursor().show(*bv_);
1036 // Skip these when selecting
1037 if (cmd.action != LFUN_MOUSE_MOTION) {
1038 owner_->updateLayoutChoice();
1039 owner_->updateToolbars();
1042 // Slight hack: this is only called currently when we
1043 // clicked somewhere, so we force through the display
1044 // of the new status here.
1045 owner_->clearMessage();
1050 FuncStatus BufferView::Pimpl::getStatus(FuncRequest const & cmd)
1054 switch (cmd.action) {
1057 flag.enabled(!buffer_->undostack().empty());
1060 flag.enabled(!buffer_->redostack().empty());
1062 case LFUN_FILE_INSERT:
1063 case LFUN_FILE_INSERT_ASCII_PARA:
1064 case LFUN_FILE_INSERT_ASCII:
1065 case LFUN_BOOKMARK_SAVE:
1066 // FIXME: Actually, these LFUNS should be moved to LyXText
1067 flag.enabled(cursor_.inTexted());
1069 case LFUN_FONT_STATE:
1070 case LFUN_LABEL_INSERT:
1071 case LFUN_PARAGRAPH_GOTO:
1072 // FIXME handle non-trivially
1073 case LFUN_OUTLINE_UP:
1074 case LFUN_OUTLINE_DOWN:
1075 case LFUN_OUTLINE_IN:
1076 case LFUN_OUTLINE_OUT:
1077 case LFUN_ERROR_NEXT:
1078 case LFUN_NOTE_NEXT:
1079 case LFUN_REFERENCE_NEXT:
1080 case LFUN_WORD_FIND:
1081 case LFUN_WORD_REPLACE:
1084 case LFUN_MARK_TOGGLE:
1085 case LFUN_SCREEN_RECENTER:
1086 case LFUN_BIBTEX_DATABASE_ADD:
1087 case LFUN_BIBTEX_DATABASE_DEL:
1088 case LFUN_WORDS_COUNT:
1092 case LFUN_LABEL_GOTO: {
1093 flag.enabled(!cmd.argument.empty()
1094 || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
1098 case LFUN_BOOKMARK_GOTO:
1099 flag.enabled(isSavedPosition(convert<unsigned int>(cmd.argument)));
1101 case LFUN_CHANGES_TRACK:
1103 flag.setOnOff(buffer_->params().tracking_changes);
1106 case LFUN_CHANGES_OUTPUT: {
1107 OutputParams runparams;
1108 LaTeXFeatures features(*buffer_, buffer_->params(), runparams);
1109 flag.enabled(buffer_ && buffer_->params().tracking_changes
1110 && features.isAvailable("dvipost"));
1111 flag.setOnOff(buffer_->params().output_changes);
1115 case LFUN_CHANGES_MERGE:
1116 case LFUN_CHANGE_ACCEPT: // what about these two
1117 case LFUN_CHANGE_REJECT: // what about these two
1118 case LFUN_ALL_CHANGES_ACCEPT:
1119 case LFUN_ALL_CHANGES_REJECT:
1120 flag.enabled(buffer_ && buffer_->params().tracking_changes);
1123 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
1124 flag.setOnOff(buffer_->params().compressed);
1129 flag.enabled(false);
1137 bool BufferView::Pimpl::dispatch(FuncRequest const & cmd)
1139 //lyxerr << BOOST_CURRENT_FUNCTION
1140 // << [ cmd = " << cmd << "]" << endl;
1142 // Make sure that the cached BufferView is correct.
1143 lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
1144 << " action[" << cmd.action << ']'
1145 << " arg[" << cmd.argument << ']'
1146 << " x[" << cmd.x << ']'
1147 << " y[" << cmd.y << ']'
1148 << " button[" << cmd.button() << ']'
1151 LCursor & cur = cursor_;
1153 switch (cmd.action) {
1157 cur.message(_("Undo"));
1158 cur.clearSelection();
1159 if (!textUndo(*bv_))
1160 cur.message(_("No further undo information"));
1168 cur.message(_("Redo"));
1169 cur.clearSelection();
1170 if (!textRedo(*bv_))
1171 cur.message(_("No further redo information"));
1177 case LFUN_FILE_INSERT:
1178 menuInsertLyXFile(cmd.argument);
1181 case LFUN_FILE_INSERT_ASCII_PARA:
1182 insertAsciiFile(bv_, cmd.argument, true);
1185 case LFUN_FILE_INSERT_ASCII:
1186 insertAsciiFile(bv_, cmd.argument, false);
1189 case LFUN_FONT_STATE:
1190 cur.message(cur.currentState());
1193 case LFUN_BOOKMARK_SAVE:
1194 savePosition(convert<unsigned int>(cmd.argument));
1197 case LFUN_BOOKMARK_GOTO:
1198 restorePosition(convert<unsigned int>(cmd.argument));
1201 case LFUN_LABEL_GOTO: {
1202 string label = cmd.argument;
1203 if (label.empty()) {
1205 getInsetByCode<InsetRef>(cursor_,
1206 InsetBase::REF_CODE);
1208 label = inset->getContents();
1214 bv_->gotoLabel(label);
1218 case LFUN_PARAGRAPH_GOTO: {
1219 int const id = convert<int>(cmd.argument);
1220 ParIterator par = buffer_->getParFromID(id);
1221 if (par == buffer_->par_iterator_end()) {
1222 lyxerr[Debug::INFO] << "No matching paragraph found! ["
1223 << id << ']' << endl;
1226 lyxerr[Debug::INFO] << "Paragraph " << par->id()
1227 << " found." << endl;
1231 bv_->setCursor(makeDocIterator(par, 0));
1238 case LFUN_OUTLINE_UP:
1239 lyx::toc::outline(lyx::toc::Up, cursor_);
1240 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
1241 updateLabels(*buffer_);
1243 case LFUN_OUTLINE_DOWN:
1244 lyx::toc::outline(lyx::toc::Down, cursor_);
1245 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
1246 updateLabels(*buffer_);
1248 case LFUN_OUTLINE_IN:
1249 lyx::toc::outline(lyx::toc::In, cursor_);
1250 updateLabels(*buffer_);
1252 case LFUN_OUTLINE_OUT:
1253 lyx::toc::outline(lyx::toc::Out, cursor_);
1254 updateLabels(*buffer_);
1257 case LFUN_ERROR_NEXT:
1258 bv_funcs::gotoInset(bv_, InsetBase::ERROR_CODE, false);
1261 case LFUN_NOTE_NEXT:
1262 bv_funcs::gotoInset(bv_, InsetBase::NOTE_CODE, false);
1265 case LFUN_REFERENCE_NEXT: {
1266 vector<InsetBase_code> tmp;
1267 tmp.push_back(InsetBase::LABEL_CODE);
1268 tmp.push_back(InsetBase::REF_CODE);
1269 bv_funcs::gotoInset(bv_, tmp, true);
1273 case LFUN_CHANGES_TRACK:
1277 case LFUN_CHANGES_OUTPUT: {
1278 bool const state = buffer_->params().output_changes;
1279 buffer_->params().output_changes = !state;
1283 case LFUN_CHANGES_MERGE:
1284 if (lyx::find::findNextChange(bv_))
1285 owner_->getDialogs().show("changes");
1288 case LFUN_ALL_CHANGES_ACCEPT: {
1289 cursor_.reset(buffer_->inset());
1290 #ifdef WITH_WARNINGS
1291 #warning FIXME changes
1293 while (lyx::find::findNextChange(bv_))
1294 bv_->getLyXText()->acceptChange(cursor_);
1299 case LFUN_ALL_CHANGES_REJECT: {
1300 cursor_.reset(buffer_->inset());
1301 #ifdef WITH_WARNINGS
1302 #warning FIXME changes
1304 while (lyx::find::findNextChange(bv_))
1305 bv_->getLyXText()->rejectChange(cursor_);
1309 case LFUN_WORD_FIND:
1310 lyx::find::find(bv_, cmd);
1313 case LFUN_WORD_REPLACE:
1314 lyx::find::replace(bv_, cmd);
1318 cur.clearSelection();
1320 cur.message(N_("Mark off"));
1324 cur.clearSelection();
1327 cur.message(N_("Mark on"));
1330 case LFUN_MARK_TOGGLE:
1331 cur.clearSelection();
1334 cur.message(N_("Mark removed"));
1337 cur.message(N_("Mark set"));
1342 case LFUN_SCREEN_RECENTER:
1346 case LFUN_BIBTEX_DATABASE_ADD: {
1347 LCursor tmpcur = cursor_;
1348 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
1349 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1350 InsetBase::BIBTEX_CODE);
1352 if (inset->addDatabase(cmd.argument))
1353 buffer_->updateBibfilesCache();
1358 case LFUN_BIBTEX_DATABASE_DEL: {
1359 LCursor tmpcur = cursor_;
1360 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
1361 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1362 InsetBase::BIBTEX_CODE);
1364 if (inset->delDatabase(cmd.argument))
1365 buffer_->updateBibfilesCache();
1370 case LFUN_WORDS_COUNT: {
1371 DocIterator from, to;
1372 if (cur.selection()) {
1373 from = cur.selectionBegin();
1374 to = cur.selectionEnd();
1376 from = doc_iterator_begin(buffer_->inset());
1377 to = doc_iterator_end(buffer_->inset());
1379 int const count = countWords(from, to);
1382 if (cur.selection())
1383 message = bformat(_("%1$d words in selection."),
1386 message = bformat(_("%1$d words in document."),
1390 if (cur.selection())
1391 message = _("One word in selection.");
1393 message = _("One word in document.");
1396 Alert::information(_("Count words"), message);
1400 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1401 // turn compression on/off
1402 buffer_->params().compressed = !buffer_->params().compressed;
1413 void BufferView::Pimpl::updateMetrics(bool singlepar)
1415 // Remove old position cache
1417 BufferView & bv = *bv_;
1418 LyXText * const text = bv.text();
1419 lyx::pit_type size = int(text->paragraphs().size());
1421 if (anchor_ref_ > int(text->paragraphs().size() - 1)) {
1422 anchor_ref_ = int(text->paragraphs().size() - 1);
1426 lyx::pit_type const pit = anchor_ref_;
1429 size_t const npit = text->paragraphs().size();
1431 // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
1432 // the (main text, not inset!) paragraph containing the cursor.
1433 // (if this paragraph contains insets etc., rebreaking will
1434 // recursively descend)
1435 if (!singlepar || pit == cursor_.bottom().pit())
1436 text->redoParagraph(pit);
1437 int y0 = text->getPar(pit).ascent() - offset_ref_;
1439 // Redo paragraphs above anchor if necessary; again, in Single Par
1440 // mode, only if we encounter the (main text) one having the cursor.
1442 while (y1 > 0 && pit1 > 0) {
1443 y1 -= text->getPar(pit1).ascent();
1445 if (!singlepar || pit1 == cursor_.bottom().pit())
1446 text->redoParagraph(pit1);
1447 y1 -= text->getPar(pit1).descent();
1451 // Take care of ascent of first line
1452 y1 -= text->getPar(pit1).ascent();
1454 // Normalize anchor for next time
1458 // Grey at the beginning is ugly
1459 if (pit1 == 0 && y1 > 0) {
1465 // Redo paragraphs below the anchor if necessary. Single par mode:
1466 // only the one containing the cursor if encountered.
1468 while (y2 < bv.workHeight() && pit2 < int(npit) - 1) {
1469 y2 += text->getPar(pit2).descent();
1471 if (!singlepar || pit2 == cursor_.bottom().pit())
1472 text->redoParagraph(pit2);
1473 y2 += text->getPar(pit2).ascent();
1476 // Take care of descent of last line
1477 y2 += text->getPar(pit2).descent();
1479 // The coordinates of all these paragraphs are correct, cache them
1481 for (lyx::pit_type pit = pit1; pit <= pit2; ++pit) {
1482 y += text->getPar(pit).ascent();
1483 theCoords.parPos()[text][pit] = Point(0, y);
1484 if (singlepar && pit == cursor_.bottom().pit()) {
1485 // In Single Paragraph mode, collect here the
1486 // y1 and y2 of the (one) paragraph the cursor is in
1487 y1 = y - text->getPar(pit).ascent();
1488 y2 = y + text->getPar(pit).descent();
1490 y += text->getPar(pit).descent();
1494 // collect cursor paragraph iter bounds
1495 pit1 = cursor_.bottom().pit();
1496 pit2 = cursor_.bottom().pit();
1499 lyxerr[Debug::DEBUG]
1500 << BOOST_CURRENT_FUNCTION
1503 << " pit1: " << pit1
1504 << " pit2: " << pit2
1505 << " npit: " << npit
1506 << " singlepar: " << singlepar
1510 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2, singlepar, size);