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 : bv_(&bv), owner_(owner), buffer_(0), wh_(0), cursor_timeout(400),
142 using_xterm_cursor(false), cursor_(bv),
143 multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0)
145 xsel_cache_.set = false;
148 timecon = cursor_timeout.timeout
149 .connect(boost::bind(&BufferView::Pimpl::cursorToggle, this));
151 cursor_timeout.start();
153 saved_positions.resize(saved_positions_num);
154 // load saved bookmarks
155 lyx::Session::BookmarkList & bmList = LyX::ref().session().loadBookmarks();
156 for (lyx::Session::BookmarkList::iterator bm = bmList.begin();
157 bm != bmList.end(); ++bm)
158 if (bm->get<0>() < saved_positions_num)
159 saved_positions[bm->get<0>()] = Position( bm->get<1>(), bm->get<2>(), bm->get<3>() );
160 // and then clear them
165 void BufferView::Pimpl::addError(ErrorItem const & ei)
167 errorlist_.push_back(ei);
171 void BufferView::Pimpl::showReadonly(bool)
173 owner_->updateWindowTitle();
174 owner_->getDialogs().updateBufferDependent(false);
178 void BufferView::Pimpl::connectBuffer(Buffer & buf)
180 if (errorConnection_.connected())
185 boost::bind(&BufferView::Pimpl::addError, this, _1));
189 boost::bind(&LyXView::message, owner_, _1));
193 boost::bind(&LyXView::busy, owner_, _1));
196 buf.updateTitles.connect(
197 boost::bind(&LyXView::updateWindowTitle, owner_));
200 buf.resetAutosaveTimers.connect(
201 boost::bind(&LyXView::resetAutosaveTimer, owner_));
203 readonlyConnection_ =
204 buf.readonly.connect(
205 boost::bind(&BufferView::Pimpl::showReadonly, this, _1));
209 boost::bind(&BufferView::Pimpl::setBuffer, this, (Buffer *)0));
213 void BufferView::Pimpl::disconnectBuffer()
215 errorConnection_.disconnect();
216 messageConnection_.disconnect();
217 busyConnection_.disconnect();
218 titleConnection_.disconnect();
219 timerConnection_.disconnect();
220 readonlyConnection_.disconnect();
221 closingConnection_.disconnect();
225 void BufferView::Pimpl::newFile(string const & filename, string const & tname,
228 setBuffer(::newFile(filename, tname, isNamed));
232 bool BufferView::Pimpl::loadLyXFile(string const & filename, bool tolastfiles)
234 // Get absolute path of file and add ".lyx"
235 // to the filename if necessary
236 string s = fileSearch(string(), filename, "lyx");
238 bool const found = !s.empty();
243 // File already open?
244 if (bufferlist.exists(s)) {
245 string const file = makeDisplayPath(s, 20);
246 string text = bformat(_("The document %1$s is already "
247 "loaded.\n\nDo you want to revert "
248 "to the saved version?"), file);
249 int const ret = Alert::prompt(_("Revert to saved document?"),
250 text, 0, 1, _("&Revert"), _("&Switch to document"));
253 setBuffer(bufferlist.getBuffer(s));
256 // FIXME: should be LFUN_REVERT
257 if (!bufferlist.close(bufferlist.getBuffer(s), false))
259 // Fall through to new load. (Asger)
265 b = bufferlist.newBuffer(s);
267 if (!::loadLyXFile(b, s)) {
268 bufferlist.release(b);
272 string text = bformat(_("The document %1$s does not yet "
273 "exist.\n\nDo you want to create "
274 "a new document?"), s);
275 int const ret = Alert::prompt(_("Create new document?"),
276 text, 0, 1, _("&Create"), _("Cancel"));
279 b = ::newFile(s, string(), true);
285 bv_->showErrorList(_("Parse"));
287 // scroll to the position when the file was last closed
288 if (lyxrc.use_lastfilepos) {
291 boost::tie(pit, pos) = LyX::ref().session().loadFilePosition(s);
292 // I am not sure how to separate the following part to a function
293 // so I will leave this to Lars.
295 // check pit since the document may be externally changed.
296 if ( static_cast<size_t>(pit) < b->paragraphs().size() ) {
297 ParIterator it = b->par_iterator_begin();
298 ParIterator const end = b->par_iterator_end();
299 for (; it != end; ++it)
300 if (it.pit() == pit) {
301 // restored pos may be bigger than it->size
302 bv_->setCursor(makeDocIterator(it, min(pos, it->size())));
303 bv_->update(Update::FitCursor);
310 LyX::ref().session().addLastFile(b->fileName());
316 lyx::frontend::Gui & BufferView::Pimpl::gui() const
318 return owner_->gui();
322 lyx::frontend::Painter & BufferView::Pimpl::painter() const
324 return owner_->workArea()->getPainter();
328 int BufferView::Pimpl::width() const
334 int BufferView::Pimpl::height() const
340 void BufferView::Pimpl::setBuffer(Buffer * b)
342 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
343 << "[ b = " << b << "]" << endl;
347 // Save the actual cursor position and anchor inside the
348 // buffer so that it can be restored in case we rechange
349 // to this buffer later on.
350 buffer_->saveCursor(cursor_.selectionBegin(),
351 cursor_.selectionEnd());
352 // current buffer is going to be switched-off, save cursor pos
353 LyX::ref().session().saveFilePosition(buffer_->fileName(),
354 boost::tie(cursor_.pit(), cursor_.pos()) );
357 // If we are closing current buffer, switch to the first in
360 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
361 << " No Buffer!" << endl;
362 // We are closing the buffer, use the first buffer as current
363 buffer_ = bufferlist.first();
364 owner_->getDialogs().hideBufferDependent();
366 // Set current buffer
371 cursor_ = LCursor(*bv_);
376 // If we're quitting lyx, don't bother updating stuff
381 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
382 << "Buffer addr: " << buffer_ << endl;
383 connectBuffer(*buffer_);
384 cursor_.push(buffer_->inset());
385 cursor_.resetAnchor();
386 buffer_->text().init(bv_);
387 buffer_->text().setCurrentFont(cursor_);
388 if (buffer_->getCursor().size() > 0 &&
389 buffer_->getAnchor().size() > 0)
391 cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
392 cursor_.resetAnchor();
393 cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
394 cursor_.setSelection();
397 // Buffer-dependent dialogs should be updated or
398 // hidden. This should go here because some dialogs (eg ToC)
399 // require bv_->text.
400 owner_->getDialogs().updateBufferDependent(true);
404 owner_->updateMenubar();
405 owner_->updateToolbars();
406 owner_->updateLayoutChoice();
407 owner_->updateWindowTitle();
409 // This is done after the layout combox has been populated
411 size_t i = cursor_.depth() - 1;
412 // we know we'll eventually find a paragraph
414 CursorSlice const & slice = cursor_[i];
415 if (!slice.inset().inMathed()) {
416 LyXLayout_ptr const layout = slice.paragraph().layout();
417 owner_->setLayout(layout->name());
425 if (buffer_ && lyx::graphics::Previews::status() != LyXRC::PREVIEW_OFF)
426 lyx::graphics::Previews::get().generateBufferPreviews(*buffer_);
430 void BufferView::Pimpl::resizeCurrentBuffer()
432 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
434 owner_->message(_("Formatting document..."));
436 LyXText * text = bv_->text();
446 // Reset the "Formatting..." message
447 owner_->clearMessage();
451 void BufferView::Pimpl::updateScrollbar()
454 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
455 << " no text in updateScrollbar" << endl;
456 scrollbarParameters_.reset();
460 LyXText & t = *bv_->text();
461 int const parsize = int(t.paragraphs().size() - 1);
462 if (anchor_ref_ > parsize) {
463 anchor_ref_ = parsize;
468 << BOOST_CURRENT_FUNCTION
469 << " Updating scrollbar: height: " << t.paragraphs().size()
470 << " curr par: " << cursor_.bottom().pit()
471 << " default height " << defaultRowHeight() << endl;
473 // It would be better to fix the scrollbar to understand
474 // values in [0..1] and divide everything by wh
476 // estimated average paragraph height:
479 int h = t.getPar(anchor_ref_).height();
481 // Normalize anchor/offset (MV):
482 while (offset_ref_ > h && anchor_ref_ < parsize) {
485 h = t.getPar(anchor_ref_).height();
487 // Look at paragraph heights on-screen
490 for (lyx::pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
493 int const h2 = t.getPar(pit).height();
497 int const hav = sumh / nh;
498 // More realistic average paragraph height
502 scrollbarParameters_.height = (parsize + 1) * wh_;
503 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
504 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
508 ScrollbarParameters const & BufferView::Pimpl::scrollbarParameters() const
510 return scrollbarParameters_;
514 void BufferView::Pimpl::scrollDocView(int value)
516 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
517 << "[ value = " << value << "]" << endl;
522 owner_->gui().guiCursor().hide();
524 LyXText & t = *bv_->text();
526 float const bar = value / float(wh_ * t.paragraphs().size());
528 anchor_ref_ = int(bar * t.paragraphs().size());
529 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
530 anchor_ref_ = int(t.paragraphs().size()) - 1;
531 t.redoParagraph(anchor_ref_);
532 int const h = t.getPar(anchor_ref_).height();
533 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
536 if (!lyxrc.cursor_follows_scrollbar)
539 int const height = 2 * defaultRowHeight();
540 int const first = height;
541 int const last = height_ - height;
542 LCursor & cur = cursor_;
544 bv_funcs::CurStatus st = bv_funcs::status(bv_, cur);
547 case bv_funcs::CUR_ABOVE:
548 t.setCursorFromCoordinates(cur, 0, first);
549 cur.clearSelection();
551 case bv_funcs::CUR_BELOW:
552 t.setCursorFromCoordinates(cur, 0, last);
553 cur.clearSelection();
555 case bv_funcs::CUR_INSIDE:
556 int const y = bv_funcs::getPos(cur, cur.boundary()).y_;
557 int const newy = min(last, max(y, first));
559 cur.reset(buffer_->inset());
560 t.setCursorFromCoordinates(cur, 0, newy);
563 owner_->updateLayoutChoice();
567 void BufferView::Pimpl::scroll(int /*lines*/)
572 // LyXText const * t = bv_->text();
573 // int const line_height = defaultRowHeight();
575 // // The new absolute coordinate
576 // int new_top_y = top_y() + lines * line_height;
578 // // Restrict to a valid value
579 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
580 // new_top_y = std::max(0, new_top_y);
582 // scrollDocView(new_top_y);
584 // // Update the scrollbar.
585 // workArea_->setScrollbarParams(t->height(), top_y(), defaultRowHeight());
589 void BufferView::Pimpl::workAreaKeyPress(LyXKeySymPtr key,
590 key_modifier::state state)
592 owner_->getLyXFunc().processKeySym(key, state);
594 /* This is perhaps a bit of a hack. When we move
595 * around, or type, it's nice to be able to see
596 * the cursor immediately after the keypress. So
597 * we reset the toggle timeout and force the visibility
598 * of the cursor. Note we cannot do this inside
599 * dispatch() itself, because that's called recursively.
602 owner_->gui().guiCursor().show(*bv_);
606 void BufferView::Pimpl::selectionRequested()
613 LCursor & cur = cursor_;
615 if (!cur.selection()) {
616 xsel_cache_.set = false;
620 if (!xsel_cache_.set ||
621 cur.top() != xsel_cache_.cursor ||
622 cur.anchor_.top() != xsel_cache_.anchor)
624 xsel_cache_.cursor = cur.top();
625 xsel_cache_.anchor = cur.anchor_.top();
626 xsel_cache_.set = cur.selection();
627 sel = cur.selectionAsString(false);
629 owner_->gui().clipboard().put(sel);
634 void BufferView::Pimpl::selectionLost()
637 owner_->gui().guiCursor().hide();
638 cursor_.clearSelection();
639 xsel_cache_.set = false;
644 void BufferView::Pimpl::workAreaResize(int width, int height)
646 bool const widthChange = width != width_;
647 bool const heightChange = height != height_;
649 // Update from work area
653 if (buffer_ && widthChange) {
654 // The visible LyXView need a resize
655 resizeCurrentBuffer();
658 if (widthChange || heightChange)
661 owner_->updateLayoutChoice();
665 bool BufferView::Pimpl::fitCursor()
667 if (bv_funcs::status(bv_, cursor_) == bv_funcs::CUR_INSIDE) {
668 LyXFont const font = cursor_.getFont();
669 int const asc = font_metrics::maxAscent(font);
670 int const des = font_metrics::maxDescent(font);
671 Point const p = bv_funcs::getPos(cursor_, cursor_.boundary());
672 if (p.y_ - asc >= 0 && p.y_ + des < height_)
680 bool BufferView::Pimpl::multiParSel()
682 if (!cursor_.selection())
684 bool ret = multiparsel_cache_;
685 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
686 // Either this, or previous selection spans paragraphs
687 return ret || multiparsel_cache_;
691 void BufferView::Pimpl::update(Update::flags flags)
694 << BOOST_CURRENT_FUNCTION
695 << "[fitcursor = " << (flags & Update::FitCursor)
696 << ", forceupdate = " << (flags & Update::Force)
697 << ", singlepar = " << (flags & Update::SinglePar)
698 << "] buffer: " << buffer_ << endl;
700 // Check needed to survive LyX startup
702 // Update macro store
703 buffer_->buildMacros();
706 std::swap(theCoords, backup);
708 // This, together with doneUpdating(), verifies (using
709 // asserts) that screen redraw is not called from
711 theCoords.startUpdating();
713 // First drawing step
714 ViewMetricsInfo vi = metrics(flags & Update::SinglePar);
715 bool forceupdate(flags & (Update::Force | Update::SinglePar));
717 if ((flags & Update::FitCursor) && fitCursor()) {
721 if ((flags & Update::MultiParSel) && multiParSel()) {
726 // Second drawing step
727 owner_->workArea()->redraw(*bv_, vi);
729 // Abort updating of the coord
730 // cache - just restore the old one
731 std::swap(theCoords, backup);
734 owner_->workArea()->greyOut();
736 owner_->view_state_changed();
740 // Callback for cursor timer
741 void BufferView::Pimpl::cursorToggle()
744 owner_->gui().guiCursor().toggle(*bv_);
746 // Use this opportunity to deal with any child processes that
747 // have finished but are waiting to communicate this fact
748 // to the rest of LyX.
749 ForkedcallsController & fcc = ForkedcallsController::get();
750 fcc.handleCompletedProcesses();
753 cursor_timeout.restart();
757 bool BufferView::Pimpl::available() const
759 return buffer_ && bv_->text();
763 Change const BufferView::Pimpl::getCurrentChange()
765 if (!buffer_->params().tracking_changes)
766 return Change(Change::UNCHANGED);
768 LyXText * text = bv_->getLyXText();
769 LCursor & cur = cursor_;
771 if (!cur.selection())
772 return Change(Change::UNCHANGED);
774 return text->getPar(cur.selBegin().pit()).
775 lookupChange(cur.selBegin().pos());
779 void BufferView::Pimpl::savePosition(unsigned int i)
781 if (i >= saved_positions_num)
783 BOOST_ASSERT(cursor_.inTexted());
784 saved_positions[i] = Position(buffer_->fileName(),
785 cursor_.paragraph().id(),
788 owner_->message(bformat(_("Saved bookmark %1$d"), i));
792 void BufferView::Pimpl::restorePosition(unsigned int i)
794 if (i >= saved_positions_num)
797 string const fname = saved_positions[i].filename;
799 cursor_.clearSelection();
801 if (fname != buffer_->fileName()) {
803 if (bufferlist.exists(fname))
804 b = bufferlist.getBuffer(fname);
806 b = bufferlist.newBuffer(fname);
807 // Don't ask, just load it
808 ::loadLyXFile(b, fname);
814 ParIterator par = buffer_->getParFromID(saved_positions[i].par_id);
815 if (par == buffer_->par_iterator_end())
818 bv_->setCursor(makeDocIterator(par, min(par->size(), saved_positions[i].par_pos)));
821 owner_->message(bformat(_("Moved to bookmark %1$d"), i));
825 bool BufferView::Pimpl::isSavedPosition(unsigned int i)
827 return i < saved_positions_num && !saved_positions[i].filename.empty();
831 void BufferView::Pimpl::saveSavedPositions()
833 // save bookmarks. It is better to use the pit interface
834 // but I do not know how to effectively convert between
836 for (unsigned int i=1; i < saved_positions_num; ++i) {
837 if ( isSavedPosition(i) )
838 LyX::ref().session().saveBookmark( boost::tie(
840 saved_positions[i].filename,
841 saved_positions[i].par_id,
842 saved_positions[i].par_pos) );
847 void BufferView::Pimpl::switchKeyMap()
849 if (!lyxrc.rtl_support)
852 Intl & intl = owner_->getIntl();
853 if (bv_->getLyXText()->real_current_font.isRightToLeft()) {
854 if (intl.keymap == Intl::PRIMARY)
857 if (intl.keymap == Intl::SECONDARY)
863 void BufferView::Pimpl::center()
865 CursorSlice & bot = cursor_.bottom();
866 lyx::pit_type const pit = bot.pit();
867 bot.text()->redoParagraph(pit);
868 Paragraph const & par = bot.text()->paragraphs()[pit];
870 offset_ref_ = bv_funcs::coordOffset(cursor_, cursor_.boundary()).y_
871 + par.ascent() - height_ / 2;
876 void BufferView::Pimpl::menuInsertLyXFile(string const & filenm)
878 BOOST_ASSERT(cursor_.inTexted());
879 string filename = filenm;
881 if (filename.empty()) {
882 // Launch a file browser
883 string initpath = lyxrc.document_path;
886 string const trypath = owner_->buffer()->filePath();
887 // If directory is writeable, use this as default.
888 if (isDirWriteable(trypath))
892 FileDialog fileDlg(_("Select LyX document to insert"),
894 make_pair(string(_("Documents|#o#O")),
895 string(lyxrc.document_path)),
896 make_pair(string(_("Examples|#E#e")),
897 string(addPath(package().system_support(), "examples"))));
899 FileDialog::Result result =
900 fileDlg.open(initpath,
901 FileFilterList(_("LyX Documents (*.lyx)")),
904 if (result.first == FileDialog::Later)
907 filename = result.second;
909 // check selected filename
910 if (filename.empty()) {
911 owner_->message(_("Canceled."));
916 // Get absolute path of file and add ".lyx"
917 // to the filename if necessary
918 filename = fileSearch(string(), filename, "lyx");
920 string const disp_fn = makeDisplayPath(filename);
921 owner_->message(bformat(_("Inserting document %1$s..."), disp_fn));
924 Buffer buf("", false);
925 buf.error.connect(boost::bind(&BufferView::Pimpl::addError, this, _1));
926 if (::loadLyXFile(&buf, makeAbsPath(filename))) {
927 lyx::cap::pasteParagraphList(cursor_, buf.paragraphs(),
928 buf.params().textclass);
929 res = _("Document %1$s inserted.");
931 res = _("Could not insert document %1$s");
933 owner_->message(bformat(res, disp_fn));
934 bv_->showErrorList(_("Document insertion"));
935 resizeCurrentBuffer();
939 void BufferView::Pimpl::trackChanges()
941 bool const tracking = buffer_->params().tracking_changes;
944 for_each(buffer_->par_iterator_begin(),
945 buffer_->par_iterator_end(),
946 bind(&Paragraph::trackChanges, _1, Change::UNCHANGED));
947 buffer_->params().tracking_changes = true;
949 // We cannot allow undos beyond the freeze point
950 buffer_->undostack().clear();
952 cursor_.setCursor(doc_iterator_begin(buffer_->inset()));
953 if (lyx::find::findNextChange(bv_)) {
954 owner_->getDialogs().show("changes");
958 for_each(buffer_->par_iterator_begin(),
959 buffer_->par_iterator_end(),
960 mem_fun_ref(&Paragraph::untrackChanges));
962 buffer_->params().tracking_changes = false;
965 buffer_->redostack().clear();
969 bool BufferView::Pimpl::workAreaDispatch(FuncRequest const & cmd0)
971 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
973 // This is only called for mouse related events including
974 // LFUN_FILE_OPEN generated by drag-and-drop.
975 FuncRequest cmd = cmd0;
978 if (cmd.action == LFUN_FILE_OPEN) {
979 owner_->dispatch(cmd);
987 cur.push(buffer_->inset());
988 cur.selection() = cursor_.selection();
990 // Doesn't go through lyxfunc, so we need to update
991 // the layout choice etc. ourselves
993 // E.g. Qt mouse press when no buffer
997 owner_->gui().guiCursor().hide();
999 // Either the inset under the cursor or the
1000 // surrounding LyXText will handle this event.
1002 // Build temporary cursor.
1003 cmd.y = min(max(cmd.y, -1), height_);
1004 InsetBase * inset = bv_->text()->editXY(cur, cmd.x, cmd.y);
1005 //lyxerr << BOOST_CURRENT_FUNCTION
1006 // << " * hit inset at tip: " << inset << endl;
1007 //lyxerr << BOOST_CURRENT_FUNCTION
1008 // << " * created temp cursor:" << cur << endl;
1010 // Put anchor at the same position.
1013 // Try to dispatch to an non-editable inset near this position
1014 // via the temp cursor. If the inset wishes to change the real
1015 // cursor it has to do so explicitly by using
1016 // cur.bv().cursor() = cur; (or similar)
1018 inset->dispatch(cur, cmd);
1020 // Now dispatch to the temporary cursor. If the real cursor should
1021 // be modified, the inset's dispatch has to do so explicitly.
1022 if (!cur.result().dispatched())
1025 if (cur.result().dispatched()) {
1026 // Redraw if requested or necessary.
1027 if (cur.result().update())
1028 update(Update::FitCursor | Update::Force);
1030 update(Update::FitCursor | Update::MultiParSel);
1033 // See workAreaKeyPress
1034 cursor_timeout.restart();
1035 owner_->gui().guiCursor().show(*bv_);
1037 // Skip these when selecting
1038 if (cmd.action != LFUN_MOUSE_MOTION) {
1039 owner_->updateLayoutChoice();
1040 owner_->updateToolbars();
1043 // Slight hack: this is only called currently when we
1044 // clicked somewhere, so we force through the display
1045 // of the new status here.
1046 owner_->clearMessage();
1051 FuncStatus BufferView::Pimpl::getStatus(FuncRequest const & cmd)
1055 switch (cmd.action) {
1058 flag.enabled(!buffer_->undostack().empty());
1061 flag.enabled(!buffer_->redostack().empty());
1063 case LFUN_FILE_INSERT:
1064 case LFUN_FILE_INSERT_ASCII_PARA:
1065 case LFUN_FILE_INSERT_ASCII:
1066 case LFUN_BOOKMARK_SAVE:
1067 // FIXME: Actually, these LFUNS should be moved to LyXText
1068 flag.enabled(cursor_.inTexted());
1070 case LFUN_FONT_STATE:
1071 case LFUN_LABEL_INSERT:
1072 case LFUN_PARAGRAPH_GOTO:
1073 // FIXME handle non-trivially
1074 case LFUN_OUTLINE_UP:
1075 case LFUN_OUTLINE_DOWN:
1076 case LFUN_OUTLINE_IN:
1077 case LFUN_OUTLINE_OUT:
1078 case LFUN_ERROR_NEXT:
1079 case LFUN_NOTE_NEXT:
1080 case LFUN_REFERENCE_NEXT:
1081 case LFUN_WORD_FIND:
1082 case LFUN_WORD_REPLACE:
1085 case LFUN_MARK_TOGGLE:
1086 case LFUN_SCREEN_RECENTER:
1087 case LFUN_BIBTEX_DATABASE_ADD:
1088 case LFUN_BIBTEX_DATABASE_DEL:
1089 case LFUN_WORDS_COUNT:
1093 case LFUN_LABEL_GOTO: {
1094 flag.enabled(!cmd.argument.empty()
1095 || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
1099 case LFUN_BOOKMARK_GOTO:
1100 flag.enabled(isSavedPosition(convert<unsigned int>(cmd.argument)));
1102 case LFUN_CHANGES_TRACK:
1104 flag.setOnOff(buffer_->params().tracking_changes);
1107 case LFUN_CHANGES_OUTPUT: {
1108 OutputParams runparams;
1109 LaTeXFeatures features(*buffer_, buffer_->params(), runparams);
1110 flag.enabled(buffer_ && buffer_->params().tracking_changes
1111 && features.isAvailable("dvipost"));
1112 flag.setOnOff(buffer_->params().output_changes);
1116 case LFUN_CHANGES_MERGE:
1117 case LFUN_CHANGE_ACCEPT: // what about these two
1118 case LFUN_CHANGE_REJECT: // what about these two
1119 case LFUN_ALL_CHANGES_ACCEPT:
1120 case LFUN_ALL_CHANGES_REJECT:
1121 flag.enabled(buffer_ && buffer_->params().tracking_changes);
1124 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
1125 flag.setOnOff(buffer_->params().compressed);
1130 flag.enabled(false);
1138 bool BufferView::Pimpl::dispatch(FuncRequest const & cmd)
1140 //lyxerr << BOOST_CURRENT_FUNCTION
1141 // << [ cmd = " << cmd << "]" << endl;
1143 // Make sure that the cached BufferView is correct.
1144 lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
1145 << " action[" << cmd.action << ']'
1146 << " arg[" << cmd.argument << ']'
1147 << " x[" << cmd.x << ']'
1148 << " y[" << cmd.y << ']'
1149 << " button[" << cmd.button() << ']'
1152 LCursor & cur = cursor_;
1154 switch (cmd.action) {
1158 cur.message(_("Undo"));
1159 cur.clearSelection();
1160 if (!textUndo(*bv_))
1161 cur.message(_("No further undo information"));
1169 cur.message(_("Redo"));
1170 cur.clearSelection();
1171 if (!textRedo(*bv_))
1172 cur.message(_("No further redo information"));
1178 case LFUN_FILE_INSERT:
1179 menuInsertLyXFile(cmd.argument);
1182 case LFUN_FILE_INSERT_ASCII_PARA:
1183 insertAsciiFile(bv_, cmd.argument, true);
1186 case LFUN_FILE_INSERT_ASCII:
1187 insertAsciiFile(bv_, cmd.argument, false);
1190 case LFUN_FONT_STATE:
1191 cur.message(cur.currentState());
1194 case LFUN_BOOKMARK_SAVE:
1195 savePosition(convert<unsigned int>(cmd.argument));
1198 case LFUN_BOOKMARK_GOTO:
1199 restorePosition(convert<unsigned int>(cmd.argument));
1202 case LFUN_LABEL_GOTO: {
1203 string label = cmd.argument;
1204 if (label.empty()) {
1206 getInsetByCode<InsetRef>(cursor_,
1207 InsetBase::REF_CODE);
1209 label = inset->getContents();
1215 bv_->gotoLabel(label);
1219 case LFUN_PARAGRAPH_GOTO: {
1220 int const id = convert<int>(cmd.argument);
1221 ParIterator par = buffer_->getParFromID(id);
1222 if (par == buffer_->par_iterator_end()) {
1223 lyxerr[Debug::INFO] << "No matching paragraph found! ["
1224 << id << ']' << endl;
1227 lyxerr[Debug::INFO] << "Paragraph " << par->id()
1228 << " found." << endl;
1232 bv_->setCursor(makeDocIterator(par, 0));
1239 case LFUN_OUTLINE_UP:
1240 lyx::toc::outline(lyx::toc::Up, cursor_);
1241 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
1242 updateLabels(*buffer_);
1244 case LFUN_OUTLINE_DOWN:
1245 lyx::toc::outline(lyx::toc::Down, cursor_);
1246 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
1247 updateLabels(*buffer_);
1249 case LFUN_OUTLINE_IN:
1250 lyx::toc::outline(lyx::toc::In, cursor_);
1251 updateLabels(*buffer_);
1253 case LFUN_OUTLINE_OUT:
1254 lyx::toc::outline(lyx::toc::Out, cursor_);
1255 updateLabels(*buffer_);
1258 case LFUN_ERROR_NEXT:
1259 bv_funcs::gotoInset(bv_, InsetBase::ERROR_CODE, false);
1262 case LFUN_NOTE_NEXT:
1263 bv_funcs::gotoInset(bv_, InsetBase::NOTE_CODE, false);
1266 case LFUN_REFERENCE_NEXT: {
1267 vector<InsetBase_code> tmp;
1268 tmp.push_back(InsetBase::LABEL_CODE);
1269 tmp.push_back(InsetBase::REF_CODE);
1270 bv_funcs::gotoInset(bv_, tmp, true);
1274 case LFUN_CHANGES_TRACK:
1278 case LFUN_CHANGES_OUTPUT: {
1279 bool const state = buffer_->params().output_changes;
1280 buffer_->params().output_changes = !state;
1284 case LFUN_CHANGES_MERGE:
1285 if (lyx::find::findNextChange(bv_))
1286 owner_->getDialogs().show("changes");
1289 case LFUN_ALL_CHANGES_ACCEPT: {
1290 cursor_.reset(buffer_->inset());
1291 #ifdef WITH_WARNINGS
1292 #warning FIXME changes
1294 while (lyx::find::findNextChange(bv_))
1295 bv_->getLyXText()->acceptChange(cursor_);
1300 case LFUN_ALL_CHANGES_REJECT: {
1301 cursor_.reset(buffer_->inset());
1302 #ifdef WITH_WARNINGS
1303 #warning FIXME changes
1305 while (lyx::find::findNextChange(bv_))
1306 bv_->getLyXText()->rejectChange(cursor_);
1310 case LFUN_WORD_FIND:
1311 lyx::find::find(bv_, cmd);
1314 case LFUN_WORD_REPLACE:
1315 lyx::find::replace(bv_, cmd);
1319 cur.clearSelection();
1321 cur.message(N_("Mark off"));
1325 cur.clearSelection();
1328 cur.message(N_("Mark on"));
1331 case LFUN_MARK_TOGGLE:
1332 cur.clearSelection();
1335 cur.message(N_("Mark removed"));
1338 cur.message(N_("Mark set"));
1343 case LFUN_SCREEN_RECENTER:
1347 case LFUN_BIBTEX_DATABASE_ADD: {
1348 LCursor tmpcur = cursor_;
1349 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
1350 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1351 InsetBase::BIBTEX_CODE);
1353 if (inset->addDatabase(cmd.argument))
1354 buffer_->updateBibfilesCache();
1359 case LFUN_BIBTEX_DATABASE_DEL: {
1360 LCursor tmpcur = cursor_;
1361 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
1362 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1363 InsetBase::BIBTEX_CODE);
1365 if (inset->delDatabase(cmd.argument))
1366 buffer_->updateBibfilesCache();
1371 case LFUN_WORDS_COUNT: {
1372 DocIterator from, to;
1373 if (cur.selection()) {
1374 from = cur.selectionBegin();
1375 to = cur.selectionEnd();
1377 from = doc_iterator_begin(buffer_->inset());
1378 to = doc_iterator_end(buffer_->inset());
1380 int const count = countWords(from, to);
1383 if (cur.selection())
1384 message = bformat(_("%1$d words in selection."),
1387 message = bformat(_("%1$d words in document."),
1391 if (cur.selection())
1392 message = _("One word in selection.");
1394 message = _("One word in document.");
1397 Alert::information(_("Count words"), message);
1401 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1402 // turn compression on/off
1403 buffer_->params().compressed = !buffer_->params().compressed;
1414 ViewMetricsInfo BufferView::Pimpl::metrics(bool singlepar)
1416 // Remove old position cache
1418 BufferView & bv = *bv_;
1419 LyXText * const text = bv.text();
1420 lyx::pit_type size = int(text->paragraphs().size());
1422 if (anchor_ref_ > int(text->paragraphs().size() - 1)) {
1423 anchor_ref_ = int(text->paragraphs().size() - 1);
1427 lyx::pit_type const pit = anchor_ref_;
1430 size_t const npit = text->paragraphs().size();
1432 // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
1433 // the (main text, not inset!) paragraph containing the cursor.
1434 // (if this paragraph contains insets etc., rebreaking will
1435 // recursively descend)
1436 if (!singlepar || pit == cursor_.bottom().pit())
1437 text->redoParagraph(pit);
1438 int y0 = text->getPar(pit).ascent() - offset_ref_;
1440 // Redo paragraphs above anchor if necessary; again, in Single Par
1441 // mode, only if we encounter the (main text) one having the cursor.
1443 while (y1 > 0 && pit1 > 0) {
1444 y1 -= text->getPar(pit1).ascent();
1446 if (!singlepar || pit1 == cursor_.bottom().pit())
1447 text->redoParagraph(pit1);
1448 y1 -= text->getPar(pit1).descent();
1452 // Take care of ascent of first line
1453 y1 -= text->getPar(pit1).ascent();
1455 // Normalize anchor for next time
1459 // Grey at the beginning is ugly
1460 if (pit1 == 0 && y1 > 0) {
1466 // Redo paragraphs below the anchor if necessary. Single par mode:
1467 // only the one containing the cursor if encountered.
1469 while (y2 < bv.workHeight() && pit2 < int(npit) - 1) {
1470 y2 += text->getPar(pit2).descent();
1472 if (!singlepar || pit2 == cursor_.bottom().pit())
1473 text->redoParagraph(pit2);
1474 y2 += text->getPar(pit2).ascent();
1477 // Take care of descent of last line
1478 y2 += text->getPar(pit2).descent();
1480 // The coordinates of all these paragraphs are correct, cache them
1482 for (lyx::pit_type pit = pit1; pit <= pit2; ++pit) {
1483 y += text->getPar(pit).ascent();
1484 theCoords.parPos()[text][pit] = Point(0, y);
1485 if (singlepar && pit == cursor_.bottom().pit()) {
1486 // In Single Paragraph mode, collect here the
1487 // y1 and y2 of the (one) paragraph the cursor is in
1488 y1 = y - text->getPar(pit).ascent();
1489 y2 = y + text->getPar(pit).descent();
1491 y += text->getPar(pit).descent();
1495 // collect cursor paragraph iter bounds
1496 pit1 = cursor_.bottom().pit();
1497 pit2 = cursor_.bottom().pit();
1500 lyxerr[Debug::DEBUG]
1501 << BOOST_CURRENT_FUNCTION
1504 << " pit1: " << pit1
1505 << " pit2: " << pit2
1506 << " npit: " << npit
1507 << " singlepar: " << singlepar
1511 return ViewMetricsInfo(pit1, pit2, y1, y2, singlepar, size);