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/Dialogs.h"
62 #include "frontends/FileDialog.h"
63 #include "frontends/font_metrics.h"
64 #include "frontends/LyXView.h"
65 #include "frontends/LyXScreenFactory.h"
66 #include "frontends/screen.h"
67 #include "frontends/WorkArea.h"
68 #include "frontends/WorkAreaFactory.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>
87 using lyx::support::addPath;
88 using lyx::support::bformat;
89 using lyx::support::FileFilterList;
90 using lyx::support::fileSearch;
91 using lyx::support::ForkedcallsController;
92 using lyx::support::isDirWriteable;
93 using lyx::support::makeDisplayPath;
94 using lyx::support::makeAbsPath;
95 using lyx::support::package;
98 using std::istringstream;
103 using std::mem_fun_ref;
107 extern BufferList bufferlist;
112 unsigned int const saved_positions_num = 20;
114 // All the below connection objects are needed because of a bug in some
115 // versions of GCC (<=2.96 are on the suspects list.) By having and assigning
116 // to these connections we avoid a segfault upon startup, and also at exit.
119 boost::signals::connection timecon;
121 /// Return an inset of this class if it exists at the current cursor position
123 T * getInsetByCode(LCursor & cur, InsetBase::Code code)
126 DocIterator it = cur;
127 if (it.nextInset() &&
128 it.nextInset()->lyxCode() == code) {
129 inset = static_cast<T*>(it.nextInset());
137 BufferView::Pimpl::Pimpl(BufferView & bv, LyXView * owner,
138 int width, int height)
139 : bv_(&bv), owner_(owner), buffer_(0), wh_(0), cursor_timeout(400),
140 using_xterm_cursor(false), cursor_(bv),
141 anchor_ref_(0), offset_ref_(0)
143 xsel_cache_.set = false;
145 workarea_.reset(WorkAreaFactory::create(*owner_, width, height));
146 screen_.reset(LyXScreenFactory::create(workarea()));
149 timecon = cursor_timeout.timeout
150 .connect(boost::bind(&BufferView::Pimpl::cursorToggle, this));
152 cursor_timeout.start();
154 saved_positions.resize(saved_positions_num);
155 // load saved bookmarks
156 lyx::Session::BookmarkList & bmList = LyX::ref().session().loadBookmarks();
157 for (lyx::Session::BookmarkList::iterator bm = bmList.begin();
158 bm != bmList.end(); ++bm)
159 if (bm->get<0>() < saved_positions_num)
160 saved_positions[bm->get<0>()] = Position( bm->get<1>(), bm->get<2>(), bm->get<3>() );
161 // and then clear them
166 void BufferView::Pimpl::addError(ErrorItem const & ei)
168 errorlist_.push_back(ei);
172 void BufferView::Pimpl::showReadonly(bool)
174 owner_->updateWindowTitle();
175 owner_->getDialogs().updateBufferDependent(false);
179 void BufferView::Pimpl::connectBuffer(Buffer & buf)
181 if (errorConnection_.connected())
186 boost::bind(&BufferView::Pimpl::addError, this, _1));
190 boost::bind(&LyXView::message, owner_, _1));
194 boost::bind(&LyXView::busy, owner_, _1));
197 buf.updateTitles.connect(
198 boost::bind(&LyXView::updateWindowTitle, owner_));
201 buf.resetAutosaveTimers.connect(
202 boost::bind(&LyXView::resetAutosaveTimer, owner_));
204 readonlyConnection_ =
205 buf.readonly.connect(
206 boost::bind(&BufferView::Pimpl::showReadonly, this, _1));
210 boost::bind(&BufferView::Pimpl::setBuffer, this, (Buffer *)0));
214 void BufferView::Pimpl::disconnectBuffer()
216 errorConnection_.disconnect();
217 messageConnection_.disconnect();
218 busyConnection_.disconnect();
219 titleConnection_.disconnect();
220 timerConnection_.disconnect();
221 readonlyConnection_.disconnect();
222 closingConnection_.disconnect();
226 void BufferView::Pimpl::newFile(string const & filename, string const & tname,
229 setBuffer(::newFile(filename, tname, isNamed));
233 bool BufferView::Pimpl::loadLyXFile(string const & filename, bool tolastfiles)
235 // Get absolute path of file and add ".lyx"
236 // to the filename if necessary
237 string s = fileSearch(string(), filename, "lyx");
239 bool const found = !s.empty();
244 // File already open?
245 if (bufferlist.exists(s)) {
246 string const file = makeDisplayPath(s, 20);
247 string text = bformat(_("The document %1$s is already "
248 "loaded.\n\nDo you want to revert "
249 "to the saved version?"), file);
250 int const ret = Alert::prompt(_("Revert to saved document?"),
251 text, 0, 1, _("&Revert"), _("&Switch to document"));
254 setBuffer(bufferlist.getBuffer(s));
257 // FIXME: should be LFUN_REVERT
258 if (!bufferlist.close(bufferlist.getBuffer(s), false))
260 // Fall through to new load. (Asger)
266 b = bufferlist.newBuffer(s);
268 if (!::loadLyXFile(b, s)) {
269 bufferlist.release(b);
273 string text = bformat(_("The document %1$s does not yet "
274 "exist.\n\nDo you want to create "
275 "a new document?"), s);
276 int const ret = Alert::prompt(_("Create new document?"),
277 text, 0, 1, _("&Create"), _("Cancel"));
280 b = ::newFile(s, string(), true);
286 bv_->showErrorList(_("Parse"));
288 // scroll to the position when the file was last closed
289 if (lyxrc.use_lastfilepos) {
292 boost::tie(pit, pos) = LyX::ref().session().loadFilePosition(s);
293 // I am not sure how to separate the following part to a function
294 // so I will leave this to Lars.
296 // check pit since the document may be externally changed.
297 if ( static_cast<size_t>(pit) < b->paragraphs().size() ) {
298 ParIterator it = b->par_iterator_begin();
299 ParIterator const end = b->par_iterator_end();
300 for (; it != end; ++it)
301 if (it.pit() == pit) {
302 // restored pos may be bigger than it->size
303 bv_->setCursor(makeDocIterator(it, min(pos, it->size())));
304 bv_->update(Update::FitCursor);
311 LyX::ref().session().addLastFile(b->fileName());
317 WorkArea & BufferView::Pimpl::workarea() const
319 return *workarea_.get();
323 LyXScreen & BufferView::Pimpl::screen() const
325 return *screen_.get();
329 Painter & BufferView::Pimpl::painter() const
331 return workarea().getPainter();
335 void BufferView::Pimpl::setBuffer(Buffer * b)
337 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
338 << "[ b = " << b << "]" << endl;
342 // Save the actual cursor position and anchor inside the
343 // buffer so that it can be restored in case we rechange
344 // to this buffer later on.
345 buffer_->saveCursor(cursor_.selectionBegin(),
346 cursor_.selectionEnd());
347 // current buffer is going to be switched-off, save cursor pos
348 LyX::ref().session().saveFilePosition(buffer_->fileName(),
349 boost::tie(cursor_.pit(), cursor_.pos()) );
352 // If we are closing current buffer, switch to the first in
355 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
356 << " No Buffer!" << endl;
357 // We are closing the buffer, use the first buffer as current
358 buffer_ = bufferlist.first();
359 owner_->getDialogs().hideBufferDependent();
361 // Set current buffer
366 cursor_ = LCursor(*bv_);
371 // If we're quitting lyx, don't bother updating stuff
376 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
377 << "Buffer addr: " << buffer_ << endl;
378 connectBuffer(*buffer_);
379 cursor_.push(buffer_->inset());
380 cursor_.resetAnchor();
381 buffer_->text().init(bv_);
382 buffer_->text().setCurrentFont(cursor_);
383 if (buffer_->getCursor().size() > 0 &&
384 buffer_->getAnchor().size() > 0)
386 cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
387 cursor_.resetAnchor();
388 cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
389 cursor_.setSelection();
392 // Buffer-dependent dialogs should be updated or
393 // hidden. This should go here because some dialogs (eg ToC)
394 // require bv_->text.
395 owner_->getDialogs().updateBufferDependent(true);
400 owner_->updateMenubar();
401 owner_->updateToolbars();
402 owner_->updateLayoutChoice();
403 owner_->updateWindowTitle();
405 // This is done after the layout combox has been populated
407 size_t i = cursor_.depth() - 1;
408 // we know we'll eventually find a paragraph
410 CursorSlice const & slice = cursor_[i];
411 if (!slice.inset().inMathed()) {
412 LyXLayout_ptr const layout = slice.paragraph().layout();
413 owner_->setLayout(layout->name());
421 if (buffer_ && lyx::graphics::Previews::status() != LyXRC::PREVIEW_OFF)
422 lyx::graphics::Previews::get().generateBufferPreviews(*buffer_);
426 void BufferView::Pimpl::resizeCurrentBuffer()
428 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
430 owner_->message(_("Formatting document..."));
432 LyXText * text = bv_->text();
442 // Reset the "Formatting..." message
443 owner_->clearMessage();
449 void BufferView::Pimpl::updateScrollbar()
452 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
453 << " no text in updateScrollbar" << endl;
454 workarea().setScrollbarParams(0, 0, 0);
458 LyXText & t = *bv_->text();
459 int const parsize = int(t.paragraphs().size() - 1);
460 if (anchor_ref_ > parsize) {
461 anchor_ref_ = parsize;
466 << BOOST_CURRENT_FUNCTION
467 << " Updating scrollbar: height: " << t.paragraphs().size()
468 << " curr par: " << cursor_.bottom().pit()
469 << " default height " << defaultRowHeight() << endl;
471 // It would be better to fix the scrollbar to understand
472 // values in [0..1] and divide everything by wh
474 // estimated average paragraph height:
476 wh_ = workarea().workHeight() / 4;
477 int h = t.getPar(anchor_ref_).height();
479 // Normalize anchor/offset (MV):
480 while (offset_ref_ > h && anchor_ref_ < parsize) {
483 h = t.getPar(anchor_ref_).height();
485 // Look at paragraph heights on-screen
488 for (lyx::pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
489 if (sumh > workarea().workHeight())
491 int const h2 = t.getPar(pit).height();
495 int const hav = sumh / nh;
496 // More realistic average paragraph height
500 workarea().setScrollbarParams((parsize + 1) * wh_,
501 anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h)),
502 int(wh_ * defaultRowHeight() / float(h)));
506 void BufferView::Pimpl::scrollDocView(int value)
508 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
509 << "[ value = " << value << "]" << endl;
514 screen().hideCursor();
516 LyXText & t = *bv_->text();
518 float const bar = value / float(wh_ * t.paragraphs().size());
520 anchor_ref_ = int(bar * t.paragraphs().size());
521 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
522 anchor_ref_ = int(t.paragraphs().size()) - 1;
523 t.redoParagraph(anchor_ref_);
524 int const h = t.getPar(anchor_ref_).height();
525 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
528 if (!lyxrc.cursor_follows_scrollbar)
531 int const height = 2 * defaultRowHeight();
532 int const first = height;
533 int const last = workarea().workHeight() - height;
534 LCursor & cur = cursor_;
536 bv_funcs::CurStatus st = bv_funcs::status(bv_, cur);
539 case bv_funcs::CUR_ABOVE:
540 t.setCursorFromCoordinates(cur, 0, first);
541 cur.clearSelection();
543 case bv_funcs::CUR_BELOW:
544 t.setCursorFromCoordinates(cur, 0, last);
545 cur.clearSelection();
547 case bv_funcs::CUR_INSIDE:
548 int const y = bv_funcs::getPos(cur, cur.boundary()).y_;
549 int const newy = min(last, max(y, first));
551 cur.reset(buffer_->inset());
552 t.setCursorFromCoordinates(cur, 0, newy);
555 owner_->updateLayoutChoice();
559 void BufferView::Pimpl::scroll(int /*lines*/)
564 // LyXText const * t = bv_->text();
565 // int const line_height = defaultRowHeight();
567 // // The new absolute coordinate
568 // int new_top_y = top_y() + lines * line_height;
570 // // Restrict to a valid value
571 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
572 // new_top_y = std::max(0, new_top_y);
574 // scrollDocView(new_top_y);
576 // // Update the scrollbar.
577 // workarea().setScrollbarParams(t->height(), top_y(), defaultRowHeight());
581 void BufferView::Pimpl::workAreaKeyPress(LyXKeySymPtr key,
582 key_modifier::state state)
584 owner_->getLyXFunc().processKeySym(key, state);
586 /* This is perhaps a bit of a hack. When we move
587 * around, or type, it's nice to be able to see
588 * the cursor immediately after the keypress. So
589 * we reset the toggle timeout and force the visibility
590 * of the cursor. Note we cannot do this inside
591 * dispatch() itself, because that's called recursively.
594 screen().showCursor(*bv_);
598 void BufferView::Pimpl::selectionRequested()
605 LCursor & cur = cursor_;
607 if (!cur.selection()) {
608 xsel_cache_.set = false;
612 if (!xsel_cache_.set ||
613 cur.top() != xsel_cache_.cursor ||
614 cur.anchor_.top() != xsel_cache_.anchor)
616 xsel_cache_.cursor = cur.top();
617 xsel_cache_.anchor = cur.anchor_.top();
618 xsel_cache_.set = cur.selection();
619 sel = cur.selectionAsString(false);
621 workarea().putClipboard(sel);
626 void BufferView::Pimpl::selectionLost()
629 screen().hideCursor();
630 cursor_.clearSelection();
631 xsel_cache_.set = false;
636 void BufferView::Pimpl::workAreaResize()
638 static int work_area_width;
639 static int work_area_height;
641 bool const widthChange = workarea().workWidth() != work_area_width;
642 bool const heightChange = workarea().workHeight() != work_area_height;
644 // Update from work area
645 work_area_width = workarea().workWidth();
646 work_area_height = workarea().workHeight();
648 if (buffer_ && widthChange) {
649 // The visible LyXView need a resize
650 resizeCurrentBuffer();
653 if (widthChange || heightChange)
656 // Always make sure that the scrollbar is sane.
658 owner_->updateLayoutChoice();
662 bool BufferView::Pimpl::fitCursor()
664 if (bv_funcs::status(bv_, cursor_) == bv_funcs::CUR_INSIDE) {
665 LyXFont const font = cursor_.getFont();
666 int const asc = font_metrics::maxAscent(font);
667 int const des = font_metrics::maxDescent(font);
668 Point const p = bv_funcs::getPos(cursor_, cursor_.boundary());
669 if (p.y_ - asc >= 0 && p.y_ + des < workarea().workHeight())
677 bool BufferView::Pimpl::multiParSel()
679 if (!cursor_.selection())
681 bool ret = multiparsel_cache_;
682 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
683 // Either this, or previous selection spans paragraphs
684 return ret || multiparsel_cache_;
688 void BufferView::Pimpl::update(Update::flags flags)
691 << BOOST_CURRENT_FUNCTION
692 << "[fitcursor = " << (flags & Update::FitCursor)
693 << ", forceupdate = " << (flags & Update::Force)
694 << ", singlepar = " << (flags & Update::SinglePar)
695 << "] buffer: " << buffer_ << endl;
697 // Check needed to survive LyX startup
699 // Update macro store
700 buffer_->buildMacros();
703 std::swap(theCoords, backup);
705 // This, together with doneUpdating(), verifies (using
706 // asserts) that screen redraw is not called from
708 theCoords.startUpdating();
710 // First drawing step
711 ViewMetricsInfo vi = metrics(flags & Update::SinglePar);
712 bool forceupdate(flags & (Update::Force | Update::SinglePar));
714 if ((flags & Update::FitCursor) && fitCursor()) {
718 if ((flags & Update::MultiParSel) && multiParSel()) {
723 // Second drawing step
724 screen().redraw(*bv_, vi);
726 // Abort updating of the coord
727 // cache - just restore the old one
728 std::swap(theCoords, backup);
735 owner_->view_state_changed();
739 // Callback for cursor timer
740 void BufferView::Pimpl::cursorToggle()
743 screen().toggleCursor(*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 lookupChangeFull(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() - workarea().workHeight() / 2;
874 void BufferView::Pimpl::stuffClipboard(string const & content) const
876 workarea().putClipboard(content);
880 void BufferView::Pimpl::menuInsertLyXFile(string const & filenm)
882 BOOST_ASSERT(cursor_.inTexted());
883 string filename = filenm;
885 if (filename.empty()) {
886 // Launch a file browser
887 string initpath = lyxrc.document_path;
890 string const trypath = owner_->buffer()->filePath();
891 // If directory is writeable, use this as default.
892 if (isDirWriteable(trypath))
896 FileDialog fileDlg(_("Select LyX document to insert"),
898 make_pair(string(_("Documents|#o#O")),
899 string(lyxrc.document_path)),
900 make_pair(string(_("Examples|#E#e")),
901 string(addPath(package().system_support(), "examples"))));
903 FileDialog::Result result =
904 fileDlg.open(initpath,
905 FileFilterList(_("LyX Documents (*.lyx)")),
908 if (result.first == FileDialog::Later)
911 filename = result.second;
913 // check selected filename
914 if (filename.empty()) {
915 owner_->message(_("Canceled."));
920 // Get absolute path of file and add ".lyx"
921 // to the filename if necessary
922 filename = fileSearch(string(), filename, "lyx");
924 string const disp_fn = makeDisplayPath(filename);
925 owner_->message(bformat(_("Inserting document %1$s..."), disp_fn));
928 Buffer buf("", false);
929 buf.error.connect(boost::bind(&BufferView::Pimpl::addError, this, _1));
930 if (::loadLyXFile(&buf, makeAbsPath(filename))) {
931 lyx::cap::pasteParagraphList(cursor_, buf.paragraphs(),
932 buf.params().textclass);
933 res = _("Document %1$s inserted.");
935 res = _("Could not insert document %1$s");
937 owner_->message(bformat(res, disp_fn));
938 bv_->showErrorList(_("Document insertion"));
939 resizeCurrentBuffer();
943 void BufferView::Pimpl::trackChanges()
945 bool const tracking = buffer_->params().tracking_changes;
948 for_each(buffer_->par_iterator_begin(),
949 buffer_->par_iterator_end(),
950 bind(&Paragraph::trackChanges, _1, Change::UNCHANGED));
951 buffer_->params().tracking_changes = true;
953 // We cannot allow undos beyond the freeze point
954 buffer_->undostack().clear();
956 cursor_.setCursor(doc_iterator_begin(buffer_->inset()));
957 if (lyx::find::findNextChange(bv_)) {
958 owner_->getDialogs().show("changes");
962 for_each(buffer_->par_iterator_begin(),
963 buffer_->par_iterator_end(),
964 mem_fun_ref(&Paragraph::untrackChanges));
966 buffer_->params().tracking_changes = false;
969 buffer_->redostack().clear();
973 bool BufferView::Pimpl::workAreaDispatch(FuncRequest const & cmd0)
975 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
977 // This is only called for mouse related events including
978 // LFUN_FILE_OPEN generated by drag-and-drop.
979 FuncRequest cmd = cmd0;
982 if (cmd.action == LFUN_FILE_OPEN) {
983 owner_->dispatch(cmd);
991 cur.push(buffer_->inset());
992 cur.selection() = cursor_.selection();
994 // Doesn't go through lyxfunc, so we need to update
995 // the layout choice etc. ourselves
997 // E.g. Qt mouse press when no buffer
1001 screen().hideCursor();
1003 // Either the inset under the cursor or the
1004 // surrounding LyXText will handle this event.
1006 // Build temporary cursor.
1007 cmd.y = min(max(cmd.y,-1), workarea().workHeight());
1008 InsetBase * inset = bv_->text()->editXY(cur, cmd.x, cmd.y);
1009 //lyxerr << BOOST_CURRENT_FUNCTION
1010 // << " * hit inset at tip: " << inset << endl;
1011 //lyxerr << BOOST_CURRENT_FUNCTION
1012 // << " * created temp cursor:" << cur << endl;
1014 // Put anchor at the same position.
1017 // Try to dispatch to an non-editable inset near this position
1018 // via the temp cursor. If the inset wishes to change the real
1019 // cursor it has to do so explicitly by using
1020 // cur.bv().cursor() = cur; (or similar)
1022 inset->dispatch(cur, cmd);
1024 // Now dispatch to the temporary cursor. If the real cursor should
1025 // be modified, the inset's dispatch has to do so explicitly.
1026 if (!cur.result().dispatched())
1029 if (cur.result().dispatched()) {
1030 // Redraw if requested or necessary.
1031 if (cur.result().update())
1032 update(Update::FitCursor | Update::Force);
1034 update(Update::FitCursor | Update::MultiParSel);
1037 // See workAreaKeyPress
1038 cursor_timeout.restart();
1039 screen().showCursor(*bv_);
1041 // Skip these when selecting
1042 if (cmd.action != LFUN_MOUSE_MOTION) {
1043 owner_->updateLayoutChoice();
1044 owner_->updateToolbars();
1047 // Slight hack: this is only called currently when we
1048 // clicked somewhere, so we force through the display
1049 // of the new status here.
1050 owner_->clearMessage();
1055 FuncStatus BufferView::Pimpl::getStatus(FuncRequest const & cmd)
1059 switch (cmd.action) {
1062 flag.enabled(!buffer_->undostack().empty());
1065 flag.enabled(!buffer_->redostack().empty());
1067 case LFUN_FILE_INSERT:
1068 case LFUN_FILE_INSERT_ASCII_PARA:
1069 case LFUN_FILE_INSERT_ASCII:
1070 // FIXME: Actually, these LFUNS should be moved to LyXText
1071 flag.enabled(cursor_.inTexted());
1073 case LFUN_FONT_STATE:
1074 case LFUN_INSERT_LABEL:
1075 case LFUN_BOOKMARK_SAVE:
1076 case LFUN_GOTO_PARAGRAPH:
1077 // FIXME handle non-trivially
1078 case LFUN_OUTLINE_UP:
1079 case LFUN_OUTLINE_DOWN:
1080 case LFUN_OUTLINE_IN:
1081 case LFUN_OUTLINE_OUT:
1082 case LFUN_GOTOERROR:
1084 case LFUN_REFERENCE_GOTO:
1085 case LFUN_WORD_FIND:
1086 case LFUN_WORD_REPLACE:
1091 case LFUN_BIBDB_ADD:
1092 case LFUN_BIBDB_DEL:
1093 case LFUN_WORDS_COUNT:
1097 case LFUN_LABEL_GOTO: {
1098 flag.enabled(!cmd.argument.empty()
1099 || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
1103 case LFUN_BOOKMARK_GOTO:
1104 flag.enabled(isSavedPosition(convert<unsigned int>(cmd.argument)));
1106 case LFUN_TRACK_CHANGES:
1108 flag.setOnOff(buffer_->params().tracking_changes);
1111 case LFUN_OUTPUT_CHANGES: {
1112 OutputParams runparams;
1113 LaTeXFeatures features(*buffer_, buffer_->params(), runparams);
1114 flag.enabled(buffer_ && buffer_->params().tracking_changes
1115 && features.isAvailable("dvipost"));
1116 flag.setOnOff(buffer_->params().output_changes);
1120 case LFUN_MERGE_CHANGES:
1121 case LFUN_ACCEPT_CHANGE: // what about these two
1122 case LFUN_REJECT_CHANGE: // what about these two
1123 case LFUN_ACCEPT_ALL_CHANGES:
1124 case LFUN_REJECT_ALL_CHANGES:
1125 flag.enabled(buffer_ && buffer_->params().tracking_changes);
1128 flag.enabled(false);
1136 bool BufferView::Pimpl::dispatch(FuncRequest const & cmd)
1138 //lyxerr << BOOST_CURRENT_FUNCTION
1139 // << [ cmd = " << cmd << "]" << endl;
1141 // Make sure that the cached BufferView is correct.
1142 lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
1143 << " action[" << cmd.action << ']'
1144 << " arg[" << cmd.argument << ']'
1145 << " x[" << cmd.x << ']'
1146 << " y[" << cmd.y << ']'
1147 << " button[" << cmd.button() << ']'
1150 LCursor & cur = cursor_;
1152 switch (cmd.action) {
1156 cur.message(_("Undo"));
1157 cur.clearSelection();
1158 if (!textUndo(*bv_))
1159 cur.message(_("No further undo information"));
1167 cur.message(_("Redo"));
1168 cur.clearSelection();
1169 if (!textRedo(*bv_))
1170 cur.message(_("No further redo information"));
1176 case LFUN_FILE_INSERT:
1177 menuInsertLyXFile(cmd.argument);
1180 case LFUN_FILE_INSERT_ASCII_PARA:
1181 insertAsciiFile(bv_, cmd.argument, true);
1184 case LFUN_FILE_INSERT_ASCII:
1185 insertAsciiFile(bv_, cmd.argument, false);
1188 case LFUN_FONT_STATE:
1189 cur.message(cur.currentState());
1192 case LFUN_BOOKMARK_SAVE:
1193 savePosition(convert<unsigned int>(cmd.argument));
1196 case LFUN_BOOKMARK_GOTO:
1197 restorePosition(convert<unsigned int>(cmd.argument));
1200 case LFUN_LABEL_GOTO: {
1201 string label = cmd.argument;
1202 if (label.empty()) {
1204 getInsetByCode<InsetRef>(cursor_,
1205 InsetBase::REF_CODE);
1207 label = inset->getContents();
1213 bv_->gotoLabel(label);
1217 case LFUN_GOTO_PARAGRAPH: {
1218 int const id = convert<int>(cmd.argument);
1219 ParIterator par = buffer_->getParFromID(id);
1220 if (par == buffer_->par_iterator_end()) {
1221 lyxerr[Debug::INFO] << "No matching paragraph found! ["
1222 << id << ']' << endl;
1225 lyxerr[Debug::INFO] << "Paragraph " << par->id()
1226 << " found." << endl;
1230 bv_->setCursor(makeDocIterator(par, 0));
1237 case LFUN_OUTLINE_UP:
1238 lyx::toc::outline(lyx::toc::UP, cursor_);
1239 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
1240 updateLabels(*buffer_);
1242 case LFUN_OUTLINE_DOWN:
1243 lyx::toc::outline(lyx::toc::DOWN, cursor_);
1244 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
1245 updateLabels(*buffer_);
1247 case LFUN_OUTLINE_IN:
1248 lyx::toc::outline(lyx::toc::IN, cursor_);
1249 updateLabels(*buffer_);
1251 case LFUN_OUTLINE_OUT:
1252 lyx::toc::outline(lyx::toc::OUT, cursor_);
1253 updateLabels(*buffer_);
1256 case LFUN_GOTOERROR:
1257 bv_funcs::gotoInset(bv_, InsetBase::ERROR_CODE, false);
1261 bv_funcs::gotoInset(bv_, InsetBase::NOTE_CODE, false);
1264 case LFUN_REFERENCE_GOTO: {
1265 vector<InsetBase_code> tmp;
1266 tmp.push_back(InsetBase::LABEL_CODE);
1267 tmp.push_back(InsetBase::REF_CODE);
1268 bv_funcs::gotoInset(bv_, tmp, true);
1272 case LFUN_TRACK_CHANGES:
1276 case LFUN_OUTPUT_CHANGES: {
1277 bool const state = buffer_->params().output_changes;
1278 buffer_->params().output_changes = !state;
1282 case LFUN_MERGE_CHANGES:
1283 if (lyx::find::findNextChange(bv_))
1284 owner_->getDialogs().show("changes");
1287 case LFUN_ACCEPT_ALL_CHANGES: {
1288 cursor_.reset(buffer_->inset());
1289 #ifdef WITH_WARNINGS
1290 #warning FIXME changes
1292 while (lyx::find::findNextChange(bv_))
1293 bv_->getLyXText()->acceptChange(cursor_);
1298 case LFUN_REJECT_ALL_CHANGES: {
1299 cursor_.reset(buffer_->inset());
1300 #ifdef WITH_WARNINGS
1301 #warning FIXME changes
1303 while (lyx::find::findNextChange(bv_))
1304 bv_->getLyXText()->rejectChange(cursor_);
1308 case LFUN_WORD_FIND:
1309 lyx::find::find(bv_, cmd);
1312 case LFUN_WORD_REPLACE:
1313 lyx::find::replace(bv_, cmd);
1317 cur.clearSelection();
1319 cur.message(N_("Mark off"));
1323 cur.clearSelection();
1326 cur.message(N_("Mark on"));
1330 cur.clearSelection();
1333 cur.message(N_("Mark removed"));
1336 cur.message(N_("Mark set"));
1345 case LFUN_BIBDB_ADD: {
1346 LCursor tmpcur = cursor_;
1347 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
1348 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1349 InsetBase::BIBTEX_CODE);
1351 if (inset->addDatabase(cmd.argument))
1352 buffer_->updateBibfilesCache();
1357 case LFUN_BIBDB_DEL: {
1358 LCursor tmpcur = cursor_;
1359 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
1360 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1361 InsetBase::BIBTEX_CODE);
1363 if (inset->delDatabase(cmd.argument))
1364 buffer_->updateBibfilesCache();
1369 case LFUN_WORDS_COUNT: {
1370 DocIterator from, to;
1371 if (cur.selection()) {
1372 from = cur.selectionBegin();
1373 to = cur.selectionEnd();
1375 from = doc_iterator_begin(buffer_->inset());
1376 to = doc_iterator_end(buffer_->inset());
1378 int const count = countWords(from, to);
1381 if (cur.selection())
1382 message = bformat(_("%1$d words in selection."),
1385 message = bformat(_("%1$d words in document."),
1389 if (cur.selection())
1390 message = _("One word in selection.");
1392 message = _("One word in document.");
1395 Alert::information(_("Count words"), message);
1406 ViewMetricsInfo BufferView::Pimpl::metrics(bool singlepar)
1408 // Remove old position cache
1410 BufferView & bv = *bv_;
1411 LyXText * const text = bv.text();
1412 lyx::pit_type size = int(text->paragraphs().size());
1414 if (anchor_ref_ > int(text->paragraphs().size() - 1)) {
1415 anchor_ref_ = int(text->paragraphs().size() - 1);
1419 lyx::pit_type const pit = anchor_ref_;
1422 size_t const npit = text->paragraphs().size();
1424 // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
1425 // the (main text, not inset!) paragraph containing the cursor.
1426 // (if this paragraph contains insets etc., rebreaking will
1427 // recursively descend)
1428 if (!singlepar || pit == cursor_.bottom().pit())
1429 text->redoParagraph(pit);
1430 int y0 = text->getPar(pit).ascent() - offset_ref_;
1432 // Redo paragraphs above anchor if necessary; again, in Single Par
1433 // mode, only if we encounter the (main text) one having the cursor.
1435 while (y1 > 0 && pit1 > 0) {
1436 y1 -= text->getPar(pit1).ascent();
1438 if (!singlepar || pit1 == cursor_.bottom().pit())
1439 text->redoParagraph(pit1);
1440 y1 -= text->getPar(pit1).descent();
1444 // Take care of ascent of first line
1445 y1 -= text->getPar(pit1).ascent();
1447 // Normalize anchor for next time
1451 // Grey at the beginning is ugly
1452 if (pit1 == 0 && y1 > 0) {
1458 // Redo paragraphs below the anchor if necessary. Single par mode:
1459 // only the one containing the cursor if encountered.
1461 while (y2 < bv.workHeight() && pit2 < int(npit) - 1) {
1462 y2 += text->getPar(pit2).descent();
1464 if (!singlepar || pit2 == cursor_.bottom().pit())
1465 text->redoParagraph(pit2);
1466 y2 += text->getPar(pit2).ascent();
1469 // Take care of descent of last line
1470 y2 += text->getPar(pit2).descent();
1472 // The coordinates of all these paragraphs are correct, cache them
1474 for (lyx::pit_type pit = pit1; pit <= pit2; ++pit) {
1475 y += text->getPar(pit).ascent();
1476 theCoords.parPos()[text][pit] = Point(0, y);
1477 if (singlepar && pit == cursor_.bottom().pit()) {
1478 // In Single Paragraph mode, collect here the
1479 // y1 and y2 of the (one) paragraph the cursor is in
1480 y1 = y - text->getPar(pit).ascent();
1481 y2 = y + text->getPar(pit).descent();
1483 y += text->getPar(pit).descent();
1487 // collect cursor paragraph iter bounds
1488 pit1 = cursor_.bottom().pit();
1489 pit2 = cursor_.bottom().pit();
1492 lyxerr[Debug::DEBUG]
1493 << BOOST_CURRENT_FUNCTION
1496 << " pit1: " << pit1
1497 << " pit2: " << pit2
1498 << " npit: " << npit
1499 << " singlepar: " << singlepar
1503 return ViewMetricsInfo(pit1, pit2, y1, y2, singlepar, size);