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 dispatchcon;
120 boost::signals::connection timecon;
121 boost::signals::connection doccon;
122 boost::signals::connection resizecon;
123 boost::signals::connection kpresscon;
124 boost::signals::connection selectioncon;
125 boost::signals::connection lostcon;
128 /// Return an inset of this class if it exists at the current cursor position
130 T * getInsetByCode(LCursor & cur, InsetBase::Code code)
133 DocIterator it = cur;
134 if (it.nextInset() &&
135 it.nextInset()->lyxCode() == code) {
136 inset = static_cast<T*>(it.nextInset());
144 BufferView::Pimpl::Pimpl(BufferView & bv, LyXView * owner,
145 int width, int height)
146 : bv_(&bv), owner_(owner), buffer_(0), wh_(0), cursor_timeout(400),
147 using_xterm_cursor(false), cursor_(bv),
148 anchor_ref_(0), offset_ref_(0)
150 xsel_cache_.set = false;
152 workarea_.reset(WorkAreaFactory::create(*owner_, width, height));
153 screen_.reset(LyXScreenFactory::create(workarea()));
156 doccon = workarea().scrollDocView
157 .connect(boost::bind(&BufferView::Pimpl::scrollDocView, this, _1));
158 resizecon = workarea().workAreaResize
159 .connect(boost::bind(&BufferView::Pimpl::workAreaResize, this));
160 dispatchcon = workarea().dispatch
161 .connect(boost::bind(&BufferView::Pimpl::workAreaDispatch, this, _1));
162 kpresscon = workarea().workAreaKeyPress
163 .connect(boost::bind(&BufferView::Pimpl::workAreaKeyPress, this, _1, _2));
164 selectioncon = workarea().selectionRequested
165 .connect(boost::bind(&BufferView::Pimpl::selectionRequested, this));
166 lostcon = workarea().selectionLost
167 .connect(boost::bind(&BufferView::Pimpl::selectionLost, this));
169 timecon = cursor_timeout.timeout
170 .connect(boost::bind(&BufferView::Pimpl::cursorToggle, this));
171 cursor_timeout.start();
172 saved_positions.resize(saved_positions_num);
173 // load saved bookmarks
174 lyx::Session::BookmarkList & bmList = LyX::ref().session().loadBookmarks();
175 for (lyx::Session::BookmarkList::iterator bm = bmList.begin();
176 bm != bmList.end(); ++bm)
177 if (bm->get<0>() < saved_positions_num)
178 saved_positions[bm->get<0>()] = Position( bm->get<1>(), bm->get<2>(), bm->get<3>() );
179 // and then clear them
184 void BufferView::Pimpl::addError(ErrorItem const & ei)
186 errorlist_.push_back(ei);
190 void BufferView::Pimpl::showReadonly(bool)
192 owner_->updateWindowTitle();
193 owner_->getDialogs().updateBufferDependent(false);
197 void BufferView::Pimpl::connectBuffer(Buffer & buf)
199 if (errorConnection_.connected())
204 boost::bind(&BufferView::Pimpl::addError, this, _1));
208 boost::bind(&LyXView::message, owner_, _1));
212 boost::bind(&LyXView::busy, owner_, _1));
215 buf.updateTitles.connect(
216 boost::bind(&LyXView::updateWindowTitle, owner_));
219 buf.resetAutosaveTimers.connect(
220 boost::bind(&LyXView::resetAutosaveTimer, owner_));
222 readonlyConnection_ =
223 buf.readonly.connect(
224 boost::bind(&BufferView::Pimpl::showReadonly, this, _1));
228 boost::bind(&BufferView::Pimpl::setBuffer, this, (Buffer *)0));
232 void BufferView::Pimpl::disconnectBuffer()
234 errorConnection_.disconnect();
235 messageConnection_.disconnect();
236 busyConnection_.disconnect();
237 titleConnection_.disconnect();
238 timerConnection_.disconnect();
239 readonlyConnection_.disconnect();
240 closingConnection_.disconnect();
244 void BufferView::Pimpl::newFile(string const & filename, string const & tname,
247 setBuffer(::newFile(filename, tname, isNamed));
251 bool BufferView::Pimpl::loadLyXFile(string const & filename, bool tolastfiles)
253 // Get absolute path of file and add ".lyx"
254 // to the filename if necessary
255 string s = fileSearch(string(), filename, "lyx");
257 bool const found = !s.empty();
262 // File already open?
263 if (bufferlist.exists(s)) {
264 string const file = makeDisplayPath(s, 20);
265 string text = bformat(_("The document %1$s is already "
266 "loaded.\n\nDo you want to revert "
267 "to the saved version?"), file);
268 int const ret = Alert::prompt(_("Revert to saved document?"),
269 text, 0, 1, _("&Revert"), _("&Switch to document"));
272 setBuffer(bufferlist.getBuffer(s));
275 // FIXME: should be LFUN_REVERT
276 if (!bufferlist.close(bufferlist.getBuffer(s), false))
278 // Fall through to new load. (Asger)
284 b = bufferlist.newBuffer(s);
286 if (!::loadLyXFile(b, s)) {
287 bufferlist.release(b);
291 string text = bformat(_("The document %1$s does not yet "
292 "exist.\n\nDo you want to create "
293 "a new document?"), s);
294 int const ret = Alert::prompt(_("Create new document?"),
295 text, 0, 1, _("&Create"), _("Cancel"));
298 b = ::newFile(s, string(), true);
304 bv_->showErrorList(_("Parse"));
306 // scroll to the position when the file was last closed
307 if (lyxrc.use_lastfilepos) {
310 boost::tie(pit, pos) = LyX::ref().session().loadFilePosition(s);
311 // I am not sure how to separate the following part to a function
312 // so I will leave this to Lars.
314 // check pit since the document may be externally changed.
315 if ( static_cast<size_t>(pit) < b->paragraphs().size() ) {
316 ParIterator it = b->par_iterator_begin();
317 ParIterator const end = b->par_iterator_end();
318 for (; it != end; ++it)
319 if (it.pit() == pit) {
320 // restored pos may be bigger than it->size
321 bv_->setCursor(makeDocIterator(it, min(pos, it->size())));
322 bv_->update(Update::FitCursor);
329 LyX::ref().session().addLastFile(b->fileName());
335 WorkArea & BufferView::Pimpl::workarea() const
337 return *workarea_.get();
341 LyXScreen & BufferView::Pimpl::screen() const
343 return *screen_.get();
347 Painter & BufferView::Pimpl::painter() const
349 return workarea().getPainter();
353 void BufferView::Pimpl::setBuffer(Buffer * b)
355 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
356 << "[ b = " << b << "]" << endl;
360 // Save the actual cursor position and anchor inside the
361 // buffer so that it can be restored in case we rechange
362 // to this buffer later on.
363 buffer_->saveCursor(cursor_.selectionBegin(),
364 cursor_.selectionEnd());
365 // current buffer is going to be switched-off, save cursor pos
366 LyX::ref().session().saveFilePosition(buffer_->fileName(),
367 boost::tie(cursor_.pit(), cursor_.pos()) );
370 // If we are closing current buffer, switch to the first in
373 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
374 << " No Buffer!" << endl;
375 // We are closing the buffer, use the first buffer as current
376 buffer_ = bufferlist.first();
377 owner_->getDialogs().hideBufferDependent();
379 // Set current buffer
384 cursor_ = LCursor(*bv_);
389 // If we're quitting lyx, don't bother updating stuff
394 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
395 << "Buffer addr: " << buffer_ << endl;
396 connectBuffer(*buffer_);
397 cursor_.push(buffer_->inset());
398 cursor_.resetAnchor();
399 buffer_->text().init(bv_);
400 buffer_->text().setCurrentFont(cursor_);
401 if (buffer_->getCursor().size() > 0 &&
402 buffer_->getAnchor().size() > 0)
404 cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
405 cursor_.resetAnchor();
406 cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
407 cursor_.setSelection();
410 // Buffer-dependent dialogs should be updated or
411 // hidden. This should go here because some dialogs (eg ToC)
412 // require bv_->text.
413 owner_->getDialogs().updateBufferDependent(true);
418 owner_->updateMenubar();
419 owner_->updateToolbars();
420 owner_->updateLayoutChoice();
421 owner_->updateWindowTitle();
423 // This is done after the layout combox has been populated
425 size_t i = cursor_.depth() - 1;
426 // we know we'll eventually find a paragraph
428 CursorSlice const & slice = cursor_[i];
429 if (!slice.inset().inMathed()) {
430 LyXLayout_ptr const layout = slice.paragraph().layout();
431 owner_->setLayout(layout->name());
439 if (buffer_ && lyx::graphics::Previews::status() != LyXRC::PREVIEW_OFF)
440 lyx::graphics::Previews::get().generateBufferPreviews(*buffer_);
444 void BufferView::Pimpl::resizeCurrentBuffer()
446 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
448 owner_->message(_("Formatting document..."));
450 LyXText * text = bv_->text();
460 // Reset the "Formatting..." message
461 owner_->clearMessage();
467 void BufferView::Pimpl::updateScrollbar()
470 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
471 << " no text in updateScrollbar" << endl;
472 workarea().setScrollbarParams(0, 0, 0);
476 LyXText & t = *bv_->text();
477 int const parsize = int(t.paragraphs().size() - 1);
478 if (anchor_ref_ > parsize) {
479 anchor_ref_ = parsize;
484 << BOOST_CURRENT_FUNCTION
485 << " Updating scrollbar: height: " << t.paragraphs().size()
486 << " curr par: " << cursor_.bottom().pit()
487 << " default height " << defaultRowHeight() << endl;
489 // It would be better to fix the scrollbar to understand
490 // values in [0..1] and divide everything by wh
492 // estimated average paragraph height:
494 wh_ = workarea().workHeight() / 4;
495 int h = t.getPar(anchor_ref_).height();
497 // Normalize anchor/offset (MV):
498 while (offset_ref_ > h && anchor_ref_ < parsize) {
501 h = t.getPar(anchor_ref_).height();
503 // Look at paragraph heights on-screen
506 for (lyx::pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
507 if (sumh > workarea().workHeight())
509 int const h2 = t.getPar(pit).height();
513 int const hav = sumh / nh;
514 // More realistic average paragraph height
518 workarea().setScrollbarParams((parsize + 1) * wh_,
519 anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h)),
520 int(wh_ * defaultRowHeight() / float(h)));
524 void BufferView::Pimpl::scrollDocView(int value)
526 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
527 << "[ value = " << value << "]" << endl;
532 screen().hideCursor();
534 LyXText & t = *bv_->text();
536 float const bar = value / float(wh_ * t.paragraphs().size());
538 anchor_ref_ = int(bar * t.paragraphs().size());
539 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
540 anchor_ref_ = int(t.paragraphs().size()) - 1;
541 t.redoParagraph(anchor_ref_);
542 int const h = t.getPar(anchor_ref_).height();
543 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
546 if (!lyxrc.cursor_follows_scrollbar)
549 int const height = 2 * defaultRowHeight();
550 int const first = height;
551 int const last = workarea().workHeight() - height;
552 LCursor & cur = cursor_;
554 bv_funcs::CurStatus st = bv_funcs::status(bv_, cur);
557 case bv_funcs::CUR_ABOVE:
558 t.setCursorFromCoordinates(cur, 0, first);
559 cur.clearSelection();
561 case bv_funcs::CUR_BELOW:
562 t.setCursorFromCoordinates(cur, 0, last);
563 cur.clearSelection();
565 case bv_funcs::CUR_INSIDE:
566 int const y = bv_funcs::getPos(cur, cur.boundary()).y_;
567 int const newy = min(last, max(y, first));
569 cur.reset(buffer_->inset());
570 t.setCursorFromCoordinates(cur, 0, newy);
573 owner_->updateLayoutChoice();
577 void BufferView::Pimpl::scroll(int /*lines*/)
582 // LyXText const * t = bv_->text();
583 // int const line_height = defaultRowHeight();
585 // // The new absolute coordinate
586 // int new_top_y = top_y() + lines * line_height;
588 // // Restrict to a valid value
589 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
590 // new_top_y = std::max(0, new_top_y);
592 // scrollDocView(new_top_y);
594 // // Update the scrollbar.
595 // workarea().setScrollbarParams(t->height(), top_y(), defaultRowHeight());
599 void BufferView::Pimpl::workAreaKeyPress(LyXKeySymPtr key,
600 key_modifier::state state)
602 owner_->getLyXFunc().processKeySym(key, state);
604 /* This is perhaps a bit of a hack. When we move
605 * around, or type, it's nice to be able to see
606 * the cursor immediately after the keypress. So
607 * we reset the toggle timeout and force the visibility
608 * of the cursor. Note we cannot do this inside
609 * dispatch() itself, because that's called recursively.
612 screen().showCursor(*bv_);
616 void BufferView::Pimpl::selectionRequested()
623 LCursor & cur = cursor_;
625 if (!cur.selection()) {
626 xsel_cache_.set = false;
630 if (!xsel_cache_.set ||
631 cur.top() != xsel_cache_.cursor ||
632 cur.anchor_.top() != xsel_cache_.anchor)
634 xsel_cache_.cursor = cur.top();
635 xsel_cache_.anchor = cur.anchor_.top();
636 xsel_cache_.set = cur.selection();
637 sel = cur.selectionAsString(false);
639 workarea().putClipboard(sel);
644 void BufferView::Pimpl::selectionLost()
647 screen().hideCursor();
648 cursor_.clearSelection();
649 xsel_cache_.set = false;
654 void BufferView::Pimpl::workAreaResize()
656 static int work_area_width;
657 static int work_area_height;
659 bool const widthChange = workarea().workWidth() != work_area_width;
660 bool const heightChange = workarea().workHeight() != work_area_height;
662 // Update from work area
663 work_area_width = workarea().workWidth();
664 work_area_height = workarea().workHeight();
666 if (buffer_ && widthChange) {
667 // The visible LyXView need a resize
668 resizeCurrentBuffer();
671 if (widthChange || heightChange)
674 // Always make sure that the scrollbar is sane.
676 owner_->updateLayoutChoice();
680 bool BufferView::Pimpl::fitCursor()
682 if (bv_funcs::status(bv_, cursor_) == bv_funcs::CUR_INSIDE) {
683 LyXFont const font = cursor_.getFont();
684 int const asc = font_metrics::maxAscent(font);
685 int const des = font_metrics::maxDescent(font);
686 Point const p = bv_funcs::getPos(cursor_, cursor_.boundary());
687 if (p.y_ - asc >= 0 && p.y_ + des < workarea().workHeight())
695 bool BufferView::Pimpl::multiParSel()
697 if (!cursor_.selection())
699 bool ret = multiparsel_cache_;
700 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
701 // Either this, or previous selection spans paragraphs
702 return ret || multiparsel_cache_;
706 void BufferView::Pimpl::update(Update::flags flags)
709 << BOOST_CURRENT_FUNCTION
710 << "[fitcursor = " << (flags & Update::FitCursor)
711 << ", forceupdate = " << (flags & Update::Force)
712 << ", singlepar = " << (flags & Update::SinglePar)
713 << "] buffer: " << buffer_ << endl;
715 // Check needed to survive LyX startup
717 // Update macro store
718 buffer_->buildMacros();
721 std::swap(theCoords, backup);
723 // This, together with doneUpdating(), verifies (using
724 // asserts) that screen redraw is not called from
726 theCoords.startUpdating();
728 // First drawing step
729 ViewMetricsInfo vi = metrics(flags & Update::SinglePar);
730 bool forceupdate(flags & (Update::Force | Update::SinglePar));
732 if ((flags & Update::FitCursor) && fitCursor()) {
736 if ((flags & Update::MultiParSel) && multiParSel()) {
741 // Second drawing step
742 screen().redraw(*bv_, vi);
744 // Abort updating of the coord
745 // cache - just restore the old one
746 std::swap(theCoords, backup);
753 owner_->view_state_changed();
757 // Callback for cursor timer
758 void BufferView::Pimpl::cursorToggle()
761 screen().toggleCursor(*bv_);
763 // Use this opportunity to deal with any child processes that
764 // have finished but are waiting to communicate this fact
765 // to the rest of LyX.
766 ForkedcallsController & fcc = ForkedcallsController::get();
767 fcc.handleCompletedProcesses();
770 cursor_timeout.restart();
774 bool BufferView::Pimpl::available() const
776 return buffer_ && bv_->text();
780 Change const BufferView::Pimpl::getCurrentChange()
782 if (!buffer_->params().tracking_changes)
783 return Change(Change::UNCHANGED);
785 LyXText * text = bv_->getLyXText();
786 LCursor & cur = cursor_;
788 if (!cur.selection())
789 return Change(Change::UNCHANGED);
791 return text->getPar(cur.selBegin().pit()).
792 lookupChangeFull(cur.selBegin().pos());
796 void BufferView::Pimpl::savePosition(unsigned int i)
798 if (i >= saved_positions_num)
800 BOOST_ASSERT(cursor_.inTexted());
801 saved_positions[i] = Position(buffer_->fileName(),
802 cursor_.paragraph().id(),
805 owner_->message(bformat(_("Saved bookmark %1$d"), i));
809 void BufferView::Pimpl::restorePosition(unsigned int i)
811 if (i >= saved_positions_num)
814 string const fname = saved_positions[i].filename;
816 cursor_.clearSelection();
818 if (fname != buffer_->fileName()) {
820 if (bufferlist.exists(fname))
821 b = bufferlist.getBuffer(fname);
823 b = bufferlist.newBuffer(fname);
824 // Don't ask, just load it
825 ::loadLyXFile(b, fname);
831 ParIterator par = buffer_->getParFromID(saved_positions[i].par_id);
832 if (par == buffer_->par_iterator_end())
835 bv_->setCursor(makeDocIterator(par, min(par->size(), saved_positions[i].par_pos)));
838 owner_->message(bformat(_("Moved to bookmark %1$d"), i));
842 bool BufferView::Pimpl::isSavedPosition(unsigned int i)
844 return i < saved_positions_num && !saved_positions[i].filename.empty();
848 void BufferView::Pimpl::saveSavedPositions()
850 // save bookmarks. It is better to use the pit interface
851 // but I do not know how to effectively convert between
853 for (unsigned int i=1; i < saved_positions_num; ++i) {
854 if ( isSavedPosition(i) )
855 LyX::ref().session().saveBookmark( boost::tie(
857 saved_positions[i].filename,
858 saved_positions[i].par_id,
859 saved_positions[i].par_pos) );
864 void BufferView::Pimpl::switchKeyMap()
866 if (!lyxrc.rtl_support)
869 Intl & intl = owner_->getIntl();
870 if (bv_->getLyXText()->real_current_font.isRightToLeft()) {
871 if (intl.keymap == Intl::PRIMARY)
874 if (intl.keymap == Intl::SECONDARY)
880 void BufferView::Pimpl::center()
882 CursorSlice & bot = cursor_.bottom();
883 lyx::pit_type const pit = bot.pit();
884 bot.text()->redoParagraph(pit);
885 Paragraph const & par = bot.text()->paragraphs()[pit];
887 offset_ref_ = bv_funcs::coordOffset(cursor_, cursor_.boundary()).y_
888 + par.ascent() - workarea().workHeight() / 2;
892 void BufferView::Pimpl::stuffClipboard(string const & content) const
894 workarea().putClipboard(content);
898 void BufferView::Pimpl::menuInsertLyXFile(string const & filenm)
900 BOOST_ASSERT(cursor_.inTexted());
901 string filename = filenm;
903 if (filename.empty()) {
904 // Launch a file browser
905 string initpath = lyxrc.document_path;
908 string const trypath = owner_->buffer()->filePath();
909 // If directory is writeable, use this as default.
910 if (isDirWriteable(trypath))
914 FileDialog fileDlg(_("Select LyX document to insert"),
916 make_pair(string(_("Documents|#o#O")),
917 string(lyxrc.document_path)),
918 make_pair(string(_("Examples|#E#e")),
919 string(addPath(package().system_support(), "examples"))));
921 FileDialog::Result result =
922 fileDlg.open(initpath,
923 FileFilterList(_("LyX Documents (*.lyx)")),
926 if (result.first == FileDialog::Later)
929 filename = result.second;
931 // check selected filename
932 if (filename.empty()) {
933 owner_->message(_("Canceled."));
938 // Get absolute path of file and add ".lyx"
939 // to the filename if necessary
940 filename = fileSearch(string(), filename, "lyx");
942 string const disp_fn = makeDisplayPath(filename);
943 owner_->message(bformat(_("Inserting document %1$s..."), disp_fn));
946 Buffer buf("", false);
947 buf.error.connect(boost::bind(&BufferView::Pimpl::addError, this, _1));
948 if (::loadLyXFile(&buf, makeAbsPath(filename))) {
949 lyx::cap::pasteParagraphList(cursor_, buf.paragraphs(),
950 buf.params().textclass);
951 res = _("Document %1$s inserted.");
953 res = _("Could not insert document %1$s");
955 owner_->message(bformat(res, disp_fn));
956 bv_->showErrorList(_("Document insertion"));
957 resizeCurrentBuffer();
961 void BufferView::Pimpl::trackChanges()
963 bool const tracking = buffer_->params().tracking_changes;
966 for_each(buffer_->par_iterator_begin(),
967 buffer_->par_iterator_end(),
968 bind(&Paragraph::trackChanges, _1, Change::UNCHANGED));
969 buffer_->params().tracking_changes = true;
971 // We cannot allow undos beyond the freeze point
972 buffer_->undostack().clear();
974 cursor_.setCursor(doc_iterator_begin(buffer_->inset()));
975 if (lyx::find::findNextChange(bv_)) {
976 owner_->getDialogs().show("changes");
980 for_each(buffer_->par_iterator_begin(),
981 buffer_->par_iterator_end(),
982 mem_fun_ref(&Paragraph::untrackChanges));
984 buffer_->params().tracking_changes = false;
987 buffer_->redostack().clear();
991 bool BufferView::Pimpl::workAreaDispatch(FuncRequest const & cmd0)
993 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
995 // This is only called for mouse related events including
996 // LFUN_FILE_OPEN generated by drag-and-drop.
997 FuncRequest cmd = cmd0;
1000 if (cmd.action == LFUN_FILE_OPEN) {
1001 owner_->dispatch(cmd);
1009 cur.push(buffer_->inset());
1010 cur.selection() = cursor_.selection();
1012 // Doesn't go through lyxfunc, so we need to update
1013 // the layout choice etc. ourselves
1015 // E.g. Qt mouse press when no buffer
1019 screen().hideCursor();
1021 // Either the inset under the cursor or the
1022 // surrounding LyXText will handle this event.
1024 // Build temporary cursor.
1025 cmd.y = min(max(cmd.y,-1), workarea().workHeight());
1026 InsetBase * inset = bv_->text()->editXY(cur, cmd.x, cmd.y);
1027 //lyxerr << BOOST_CURRENT_FUNCTION
1028 // << " * hit inset at tip: " << inset << endl;
1029 //lyxerr << BOOST_CURRENT_FUNCTION
1030 // << " * created temp cursor:" << cur << endl;
1032 // Put anchor at the same position.
1035 // Try to dispatch to an non-editable inset near this position
1036 // via the temp cursor. If the inset wishes to change the real
1037 // cursor it has to do so explicitly by using
1038 // cur.bv().cursor() = cur; (or similar)
1040 inset->dispatch(cur, cmd);
1042 // Now dispatch to the temporary cursor. If the real cursor should
1043 // be modified, the inset's dispatch has to do so explicitly.
1044 if (!cur.result().dispatched())
1047 if (cur.result().dispatched()) {
1048 // Redraw if requested or necessary.
1049 if (cur.result().update())
1050 update(Update::FitCursor | Update::Force);
1052 update(Update::FitCursor | Update::MultiParSel);
1055 // See workAreaKeyPress
1056 cursor_timeout.restart();
1057 screen().showCursor(*bv_);
1059 // Skip these when selecting
1060 if (cmd.action != LFUN_MOUSE_MOTION) {
1061 owner_->updateLayoutChoice();
1062 owner_->updateToolbars();
1065 // Slight hack: this is only called currently when we
1066 // clicked somewhere, so we force through the display
1067 // of the new status here.
1068 owner_->clearMessage();
1073 FuncStatus BufferView::Pimpl::getStatus(FuncRequest const & cmd)
1077 switch (cmd.action) {
1080 flag.enabled(!buffer_->undostack().empty());
1083 flag.enabled(!buffer_->redostack().empty());
1085 case LFUN_FILE_INSERT:
1086 case LFUN_FILE_INSERT_ASCII_PARA:
1087 case LFUN_FILE_INSERT_ASCII:
1088 // FIXME: Actually, these LFUNS should be moved to LyXText
1089 flag.enabled(cursor_.inTexted());
1091 case LFUN_FONT_STATE:
1092 case LFUN_INSERT_LABEL:
1093 case LFUN_BOOKMARK_SAVE:
1094 case LFUN_GOTO_PARAGRAPH:
1096 case LFUN_GOTOERROR:
1098 case LFUN_REFERENCE_GOTO:
1099 case LFUN_WORD_FIND:
1100 case LFUN_WORD_REPLACE:
1105 case LFUN_BIBDB_ADD:
1106 case LFUN_BIBDB_DEL:
1107 case LFUN_WORDS_COUNT:
1111 case LFUN_LABEL_GOTO: {
1112 flag.enabled(!cmd.argument.empty()
1113 || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
1117 case LFUN_BOOKMARK_GOTO:
1118 flag.enabled(isSavedPosition(convert<unsigned int>(cmd.argument)));
1120 case LFUN_TRACK_CHANGES:
1122 flag.setOnOff(buffer_->params().tracking_changes);
1125 case LFUN_OUTPUT_CHANGES: {
1126 OutputParams runparams;
1127 LaTeXFeatures features(*buffer_, buffer_->params(), runparams);
1128 flag.enabled(buffer_ && buffer_->params().tracking_changes
1129 && features.isAvailable("dvipost"));
1130 flag.setOnOff(buffer_->params().output_changes);
1134 case LFUN_MERGE_CHANGES:
1135 case LFUN_ACCEPT_CHANGE: // what about these two
1136 case LFUN_REJECT_CHANGE: // what about these two
1137 case LFUN_ACCEPT_ALL_CHANGES:
1138 case LFUN_REJECT_ALL_CHANGES:
1139 flag.enabled(buffer_ && buffer_->params().tracking_changes);
1142 flag.enabled(false);
1150 bool BufferView::Pimpl::dispatch(FuncRequest const & cmd)
1152 //lyxerr << BOOST_CURRENT_FUNCTION
1153 // << [ cmd = " << cmd << "]" << endl;
1155 // Make sure that the cached BufferView is correct.
1156 lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
1157 << " action[" << cmd.action << ']'
1158 << " arg[" << cmd.argument << ']'
1159 << " x[" << cmd.x << ']'
1160 << " y[" << cmd.y << ']'
1161 << " button[" << cmd.button() << ']'
1164 LCursor & cur = cursor_;
1166 switch (cmd.action) {
1170 cur.message(_("Undo"));
1171 cur.clearSelection();
1172 if (!textUndo(*bv_))
1173 cur.message(_("No further undo information"));
1181 cur.message(_("Redo"));
1182 cur.clearSelection();
1183 if (!textRedo(*bv_))
1184 cur.message(_("No further redo information"));
1190 case LFUN_FILE_INSERT:
1191 menuInsertLyXFile(cmd.argument);
1194 case LFUN_FILE_INSERT_ASCII_PARA:
1195 insertAsciiFile(bv_, cmd.argument, true);
1198 case LFUN_FILE_INSERT_ASCII:
1199 insertAsciiFile(bv_, cmd.argument, false);
1202 case LFUN_FONT_STATE:
1203 cur.message(cur.currentState());
1206 case LFUN_BOOKMARK_SAVE:
1207 savePosition(convert<unsigned int>(cmd.argument));
1210 case LFUN_BOOKMARK_GOTO:
1211 restorePosition(convert<unsigned int>(cmd.argument));
1214 case LFUN_LABEL_GOTO: {
1215 string label = cmd.argument;
1216 if (label.empty()) {
1218 getInsetByCode<InsetRef>(cursor_,
1219 InsetBase::REF_CODE);
1221 label = inset->getContents();
1227 bv_->gotoLabel(label);
1231 case LFUN_GOTO_PARAGRAPH: {
1232 int const id = convert<int>(cmd.argument);
1233 ParIterator par = buffer_->getParFromID(id);
1234 if (par == buffer_->par_iterator_end()) {
1235 lyxerr[Debug::INFO] << "No matching paragraph found! ["
1236 << id << ']' << endl;
1239 lyxerr[Debug::INFO] << "Paragraph " << par->id()
1240 << " found." << endl;
1244 bv_->setCursor(makeDocIterator(par, 0));
1251 case LFUN_OUTLINE: {
1252 lyx::toc::OutlineOp const op =
1253 static_cast<lyx::toc::OutlineOp>(convert<int>(cmd.argument));
1254 lyx::toc::outline(op, buffer_, cursor_.pit());
1255 bv_->text()->setCursor(cursor_, cursor_.pit(), 0);
1256 buffer_->markDirty();
1257 updateCounters(*buffer_);
1261 case LFUN_GOTOERROR:
1262 bv_funcs::gotoInset(bv_, InsetBase::ERROR_CODE, false);
1266 bv_funcs::gotoInset(bv_, InsetBase::NOTE_CODE, false);
1269 case LFUN_REFERENCE_GOTO: {
1270 vector<InsetBase_code> tmp;
1271 tmp.push_back(InsetBase::LABEL_CODE);
1272 tmp.push_back(InsetBase::REF_CODE);
1273 bv_funcs::gotoInset(bv_, tmp, true);
1277 case LFUN_TRACK_CHANGES:
1281 case LFUN_OUTPUT_CHANGES: {
1282 bool const state = buffer_->params().output_changes;
1283 buffer_->params().output_changes = !state;
1287 case LFUN_MERGE_CHANGES:
1288 if (lyx::find::findNextChange(bv_))
1289 owner_->getDialogs().show("changes");
1292 case LFUN_ACCEPT_ALL_CHANGES: {
1293 cursor_.reset(buffer_->inset());
1294 #ifdef WITH_WARNINGS
1295 #warning FIXME changes
1297 while (lyx::find::findNextChange(bv_))
1298 bv_->getLyXText()->acceptChange(cursor_);
1303 case LFUN_REJECT_ALL_CHANGES: {
1304 cursor_.reset(buffer_->inset());
1305 #ifdef WITH_WARNINGS
1306 #warning FIXME changes
1308 while (lyx::find::findNextChange(bv_))
1309 bv_->getLyXText()->rejectChange(cursor_);
1313 case LFUN_WORD_FIND:
1314 lyx::find::find(bv_, cmd);
1317 case LFUN_WORD_REPLACE:
1318 lyx::find::replace(bv_, cmd);
1322 cur.clearSelection();
1324 cur.message(N_("Mark off"));
1328 cur.clearSelection();
1331 cur.message(N_("Mark on"));
1335 cur.clearSelection();
1338 cur.message(N_("Mark removed"));
1341 cur.message(N_("Mark set"));
1350 case LFUN_BIBDB_ADD: {
1351 LCursor tmpcur = cursor_;
1352 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
1353 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1354 InsetBase::BIBTEX_CODE);
1356 inset->addDatabase(cmd.argument);
1360 case LFUN_BIBDB_DEL: {
1361 LCursor tmpcur = cursor_;
1362 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
1363 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1364 InsetBase::BIBTEX_CODE);
1366 inset->delDatabase(cmd.argument);
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);
1407 ViewMetricsInfo BufferView::Pimpl::metrics(bool singlepar)
1409 // Remove old position cache
1411 BufferView & bv = *bv_;
1412 LyXText * const text = bv.text();
1413 lyx::pit_type size = int(text->paragraphs().size());
1415 if (anchor_ref_ > int(text->paragraphs().size() - 1)) {
1416 anchor_ref_ = int(text->paragraphs().size() - 1);
1420 lyx::pit_type const pit = anchor_ref_;
1423 size_t const npit = text->paragraphs().size();
1425 // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
1426 // the (main text, not inset!) paragraph containing the cursor.
1427 // (if this paragraph contains insets etc., rebreaking will
1428 // recursively descend)
1429 if (!singlepar || pit == cursor_.bottom().pit())
1430 text->redoParagraph(pit);
1431 int y0 = text->getPar(pit).ascent() - offset_ref_;
1433 // Redo paragraphs above anchor if necessary; again, in Single Par
1434 // mode, only if we encounter the (main text) one having the cursor.
1436 while (y1 > 0 && pit1 > 0) {
1437 y1 -= text->getPar(pit1).ascent();
1439 if (!singlepar || pit1 == cursor_.bottom().pit())
1440 text->redoParagraph(pit1);
1441 y1 -= text->getPar(pit1).descent();
1445 // Take care of ascent of first line
1446 y1 -= text->getPar(pit1).ascent();
1448 // Normalize anchor for next time
1452 // Grey at the beginning is ugly
1453 if (pit1 == 0 && y1 > 0) {
1459 // Redo paragraphs below the anchor if necessary. Single par mode:
1460 // only the one containing the cursor if encountered.
1462 while (y2 < bv.workHeight() && pit2 < int(npit) - 1) {
1463 y2 += text->getPar(pit2).descent();
1465 if (!singlepar || pit2 == cursor_.bottom().pit())
1466 text->redoParagraph(pit2);
1467 y2 += text->getPar(pit2).ascent();
1470 // Take care of descent of last line
1471 y2 += text->getPar(pit2).descent();
1473 // The coordinates of all these paragraphs are correct, cache them
1475 for (lyx::pit_type pit = pit1; pit <= pit2; ++pit) {
1476 y += text->getPar(pit).ascent();
1477 theCoords.parPos()[text][pit] = Point(0, y);
1478 if (singlepar && pit == cursor_.bottom().pit()) {
1479 // In Single Paragraph mode, collect here the
1480 // y1 and y2 of the (one) paragraph the cursor is in
1481 y1 = y - text->getPar(pit).ascent();
1482 y2 = y + text->getPar(pit).descent();
1484 y += text->getPar(pit).descent();
1488 // collect cursor paragraph iter bounds
1489 pit1 = cursor_.bottom().pit();
1490 pit2 = cursor_.bottom().pit();
1493 lyxerr[Debug::DEBUG]
1494 << BOOST_CURRENT_FUNCTION
1497 << " pit1: " << pit1
1498 << " pit2: " << pit2
1499 << " npit: " << npit
1500 << " singlepar: " << singlepar
1504 return ViewMetricsInfo(pit1, pit2, y1, y2, singlepar, size);