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
45 #include "lastfiles.h"
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"
55 #include "insets/insetbibtex.h"
56 #include "insets/insetref.h"
57 #include "insets/insettext.h"
59 #include "frontends/Alert.h"
60 #include "frontends/Dialogs.h"
61 #include "frontends/FileDialog.h"
62 #include "frontends/font_metrics.h"
63 #include "frontends/LyXView.h"
64 #include "frontends/LyXScreenFactory.h"
65 #include "frontends/screen.h"
66 #include "frontends/WorkArea.h"
67 #include "frontends/WorkAreaFactory.h"
69 #include "graphics/Previews.h"
71 #include "support/convert.h"
72 #include "support/filefilterlist.h"
73 #include "support/filetools.h"
74 #include "support/forkedcontr.h"
75 #include "support/package.h"
76 #include "support/types.h"
78 #include <boost/bind.hpp>
79 #include <boost/current_function.hpp>
86 using lyx::support::AddPath;
87 using lyx::support::bformat;
88 using lyx::support::FileFilterList;
89 using lyx::support::FileSearch;
90 using lyx::support::ForkedcallsController;
91 using lyx::support::IsDirWriteable;
92 using lyx::support::MakeDisplayPath;
93 using lyx::support::MakeAbsPath;
94 using lyx::support::package;
97 using std::istringstream;
102 using std::mem_fun_ref;
106 extern BufferList bufferlist;
111 unsigned int const saved_positions_num = 20;
113 // All the below connection objects are needed because of a bug in some
114 // versions of GCC (<=2.96 are on the suspects list.) By having and assigning
115 // to these connections we avoid a segfault upon startup, and also at exit.
118 boost::signals::connection dispatchcon;
119 boost::signals::connection timecon;
120 boost::signals::connection doccon;
121 boost::signals::connection resizecon;
122 boost::signals::connection kpresscon;
123 boost::signals::connection selectioncon;
124 boost::signals::connection lostcon;
127 /// Return an inset of this class if it exists at the current cursor position
129 T * getInsetByCode(LCursor & cur, InsetBase::Code code)
132 DocIterator it = cur;
133 if (it.nextInset() &&
134 it.nextInset()->lyxCode() == code) {
135 inset = static_cast<T*>(it.nextInset());
143 BufferView::Pimpl::Pimpl(BufferView & bv, LyXView * owner,
144 int width, int height)
145 : bv_(&bv), owner_(owner), buffer_(0), wh_(0), cursor_timeout(400),
146 using_xterm_cursor(false), cursor_(bv),
147 anchor_ref_(0), offset_ref_(0)
149 xsel_cache_.set = false;
151 workarea_.reset(WorkAreaFactory::create(*owner_, width, height));
152 screen_.reset(LyXScreenFactory::create(workarea()));
155 doccon = workarea().scrollDocView
156 .connect(boost::bind(&BufferView::Pimpl::scrollDocView, this, _1));
157 resizecon = workarea().workAreaResize
158 .connect(boost::bind(&BufferView::Pimpl::workAreaResize, this));
159 dispatchcon = workarea().dispatch
160 .connect(boost::bind(&BufferView::Pimpl::workAreaDispatch, this, _1));
161 kpresscon = workarea().workAreaKeyPress
162 .connect(boost::bind(&BufferView::Pimpl::workAreaKeyPress, this, _1, _2));
163 selectioncon = workarea().selectionRequested
164 .connect(boost::bind(&BufferView::Pimpl::selectionRequested, this));
165 lostcon = workarea().selectionLost
166 .connect(boost::bind(&BufferView::Pimpl::selectionLost, this));
168 timecon = cursor_timeout.timeout
169 .connect(boost::bind(&BufferView::Pimpl::cursorToggle, this));
170 cursor_timeout.start();
171 saved_positions.resize(saved_positions_num);
175 void BufferView::Pimpl::addError(ErrorItem const & ei)
177 errorlist_.push_back(ei);
181 void BufferView::Pimpl::showReadonly(bool)
183 owner_->updateWindowTitle();
184 owner_->getDialogs().updateBufferDependent(false);
188 void BufferView::Pimpl::connectBuffer(Buffer & buf)
190 if (errorConnection_.connected())
195 boost::bind(&BufferView::Pimpl::addError, this, _1));
199 boost::bind(&LyXView::message, owner_, _1));
203 boost::bind(&LyXView::busy, owner_, _1));
206 buf.updateTitles.connect(
207 boost::bind(&LyXView::updateWindowTitle, owner_));
210 buf.resetAutosaveTimers.connect(
211 boost::bind(&LyXView::resetAutosaveTimer, owner_));
213 readonlyConnection_ =
214 buf.readonly.connect(
215 boost::bind(&BufferView::Pimpl::showReadonly, this, _1));
219 boost::bind(&BufferView::Pimpl::setBuffer, this, (Buffer *)0));
223 void BufferView::Pimpl::disconnectBuffer()
225 errorConnection_.disconnect();
226 messageConnection_.disconnect();
227 busyConnection_.disconnect();
228 titleConnection_.disconnect();
229 timerConnection_.disconnect();
230 readonlyConnection_.disconnect();
231 closingConnection_.disconnect();
235 void BufferView::Pimpl::newFile(string const & filename, string const & tname,
238 setBuffer(::newFile(filename, tname, isNamed));
242 bool BufferView::Pimpl::loadLyXFile(string const & filename, bool tolastfiles)
244 // Get absolute path of file and add ".lyx"
245 // to the filename if necessary
246 string s = FileSearch(string(), filename, "lyx");
248 bool const found = !s.empty();
253 // File already open?
254 if (bufferlist.exists(s)) {
255 string const file = MakeDisplayPath(s, 20);
256 string text = bformat(_("The document %1$s is already "
257 "loaded.\n\nDo you want to revert "
258 "to the saved version?"), file);
259 int const ret = Alert::prompt(_("Revert to saved document?"),
260 text, 0, 1, _("&Revert"), _("&Switch to document"));
263 setBuffer(bufferlist.getBuffer(s));
266 // FIXME: should be LFUN_REVERT
267 if (!bufferlist.close(bufferlist.getBuffer(s), false))
269 // Fall through to new load. (Asger)
275 b = bufferlist.newBuffer(s);
277 if (!::loadLyXFile(b, s)) {
278 bufferlist.release(b);
282 string text = bformat(_("The document %1$s does not yet "
283 "exist.\n\nDo you want to create "
284 "a new document?"), s);
285 int const ret = Alert::prompt(_("Create new document?"),
286 text, 0, 1, _("&Create"), _("Cancel"));
289 b = ::newFile(s, string(), true);
295 bv_->showErrorList(_("Parse"));
298 LyX::ref().lastfiles().newFile(b->fileName());
304 WorkArea & BufferView::Pimpl::workarea() const
306 return *workarea_.get();
310 LyXScreen & BufferView::Pimpl::screen() const
312 return *screen_.get();
316 Painter & BufferView::Pimpl::painter() const
318 return workarea().getPainter();
322 void BufferView::Pimpl::setBuffer(Buffer * b)
324 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
325 << "[ b = " << b << "]" << endl;
329 // Save the actual cursor position and anchor inside the
330 // buffer so that it can be restored in case we rechange
331 // to this buffer later on.
332 buffer_->saveCursor(cursor_.selectionBegin(),
333 cursor_.selectionEnd());
336 // If we are closing current buffer, switch to the first in
339 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
340 << " No Buffer!" << endl;
341 // We are closing the buffer, use the first buffer as current
342 buffer_ = bufferlist.first();
343 owner_->getDialogs().hideBufferDependent();
345 // Set current buffer
350 cursor_ = LCursor(*bv_);
355 // If we're quitting lyx, don't bother updating stuff
360 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
361 << "Buffer addr: " << buffer_ << endl;
362 connectBuffer(*buffer_);
363 cursor_.push(buffer_->inset());
364 cursor_.resetAnchor();
365 buffer_->text().init(bv_);
366 buffer_->text().setCurrentFont(cursor_);
367 if (buffer_->getCursor().size() > 0 &&
368 buffer_->getAnchor().size() > 0)
370 cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
371 cursor_.resetAnchor();
372 cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
373 cursor_.setSelection();
376 // Buffer-dependent dialogs should be updated or
377 // hidden. This should go here because some dialogs (eg ToC)
378 // require bv_->text.
379 owner_->getDialogs().updateBufferDependent(true);
384 owner_->updateMenubar();
385 owner_->updateToolbars();
386 owner_->updateLayoutChoice();
387 owner_->updateWindowTitle();
389 // This is done after the layout combox has been populated
391 size_t i = cursor_.depth() - 1;
392 // we know we'll eventually find a paragraph
394 CursorSlice const & slice = cursor_[i];
395 if (!slice.inset().inMathed()) {
396 LyXLayout_ptr const layout = slice.paragraph().layout();
397 owner_->setLayout(layout->name());
405 if (buffer_ && lyx::graphics::Previews::status() != LyXRC::PREVIEW_OFF)
406 lyx::graphics::Previews::get().generateBufferPreviews(*buffer_);
410 void BufferView::Pimpl::resizeCurrentBuffer()
412 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
414 owner_->message(_("Formatting document..."));
416 LyXText * text = bv_->text();
426 // Reset the "Formatting..." message
427 owner_->clearMessage();
433 void BufferView::Pimpl::updateScrollbar()
436 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
437 << " no text in updateScrollbar" << endl;
438 workarea().setScrollbarParams(0, 0, 0);
442 LyXText & t = *bv_->text();
443 int const parsize = int(t.paragraphs().size() - 1);
444 if (anchor_ref_ > parsize) {
445 anchor_ref_ = parsize;
450 << BOOST_CURRENT_FUNCTION
451 << " Updating scrollbar: height: " << t.paragraphs().size()
452 << " curr par: " << cursor_.bottom().pit()
453 << " default height " << defaultRowHeight() << endl;
455 // It would be better to fix the scrollbar to understand
456 // values in [0..1] and divide everything by wh
458 // estimated average paragraph height:
460 wh_ = workarea().workHeight() / 4;
461 int h = t.getPar(anchor_ref_).height();
463 // Normalize anchor/offset (MV):
464 while (offset_ref_ > h && anchor_ref_ < parsize) {
467 h = t.getPar(anchor_ref_).height();
469 // Look at paragraph heights on-screen
472 for (lyx::pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
473 if (sumh > workarea().workHeight())
475 int const h2 = t.getPar(pit).height();
479 int const hav = sumh / nh;
480 // More realistic average paragraph height
484 workarea().setScrollbarParams((parsize + 1) * wh_,
485 anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h)),
486 int(wh_ * defaultRowHeight() / float(h)));
490 void BufferView::Pimpl::scrollDocView(int value)
492 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
493 << "[ value = " << value << "]" << endl;
498 screen().hideCursor();
500 LyXText & t = *bv_->text();
502 float const bar = value / float(wh_ * t.paragraphs().size());
504 anchor_ref_ = int(bar * t.paragraphs().size());
505 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
506 anchor_ref_ = int(t.paragraphs().size()) - 1;
507 t.redoParagraph(anchor_ref_);
508 int const h = t.getPar(anchor_ref_).height();
509 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
512 if (!lyxrc.cursor_follows_scrollbar)
515 int const height = 2 * defaultRowHeight();
516 int const first = height;
517 int const last = workarea().workHeight() - height;
518 LCursor & cur = cursor_;
520 bv_funcs::CurStatus st = bv_funcs::status(bv_, cur);
523 case bv_funcs::CUR_ABOVE:
524 t.setCursorFromCoordinates(cur, 0, first);
525 cur.clearSelection();
527 case bv_funcs::CUR_BELOW:
528 t.setCursorFromCoordinates(cur, 0, last);
529 cur.clearSelection();
531 case bv_funcs::CUR_INSIDE:
532 int const y = bv_funcs::getPos(cur, cur.boundary()).y_;
533 int const newy = min(last, max(y, first));
535 cur.reset(buffer_->inset());
536 t.setCursorFromCoordinates(cur, 0, newy);
539 owner_->updateLayoutChoice();
543 void BufferView::Pimpl::scroll(int /*lines*/)
548 // LyXText const * t = bv_->text();
549 // int const line_height = defaultRowHeight();
551 // // The new absolute coordinate
552 // int new_top_y = top_y() + lines * line_height;
554 // // Restrict to a valid value
555 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
556 // new_top_y = std::max(0, new_top_y);
558 // scrollDocView(new_top_y);
560 // // Update the scrollbar.
561 // workarea().setScrollbarParams(t->height(), top_y(), defaultRowHeight());
565 void BufferView::Pimpl::workAreaKeyPress(LyXKeySymPtr key,
566 key_modifier::state state)
568 owner_->getLyXFunc().processKeySym(key, state);
570 /* This is perhaps a bit of a hack. When we move
571 * around, or type, it's nice to be able to see
572 * the cursor immediately after the keypress. So
573 * we reset the toggle timeout and force the visibility
574 * of the cursor. Note we cannot do this inside
575 * dispatch() itself, because that's called recursively.
578 screen().showCursor(*bv_);
582 void BufferView::Pimpl::selectionRequested()
589 LCursor & cur = cursor_;
591 if (!cur.selection()) {
592 xsel_cache_.set = false;
596 if (!xsel_cache_.set ||
597 cur.top() != xsel_cache_.cursor ||
598 cur.anchor_.top() != xsel_cache_.anchor)
600 xsel_cache_.cursor = cur.top();
601 xsel_cache_.anchor = cur.anchor_.top();
602 xsel_cache_.set = cur.selection();
603 sel = cur.selectionAsString(false);
605 workarea().putClipboard(sel);
610 void BufferView::Pimpl::selectionLost()
613 screen().hideCursor();
614 cursor_.clearSelection();
615 xsel_cache_.set = false;
620 void BufferView::Pimpl::workAreaResize()
622 static int work_area_width;
623 static int work_area_height;
625 bool const widthChange = workarea().workWidth() != work_area_width;
626 bool const heightChange = workarea().workHeight() != work_area_height;
628 // Update from work area
629 work_area_width = workarea().workWidth();
630 work_area_height = workarea().workHeight();
632 if (buffer_ && widthChange) {
633 // The visible LyXView need a resize
634 resizeCurrentBuffer();
637 if (widthChange || heightChange)
640 // Always make sure that the scrollbar is sane.
642 owner_->updateLayoutChoice();
646 bool BufferView::Pimpl::fitCursor()
648 if (bv_funcs::status(bv_, cursor_) == bv_funcs::CUR_INSIDE) {
649 LyXFont const font = cursor_.getFont();
650 int const asc = font_metrics::maxAscent(font);
651 int const des = font_metrics::maxDescent(font);
652 Point const p = bv_funcs::getPos(cursor_, cursor_.boundary());
653 if (p.y_ - asc >= 0 && p.y_ + des < workarea().workHeight())
661 bool BufferView::Pimpl::multiParSel()
663 if (!cursor_.selection())
665 bool ret = multiparsel_cache_;
666 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
667 // Either this, or previous selection spans paragraphs
668 return ret || multiparsel_cache_;
672 void BufferView::Pimpl::update(Update::flags flags)
675 << BOOST_CURRENT_FUNCTION
676 << "[fitcursor = " << (flags & Update::FitCursor)
677 << ", forceupdate = " << (flags & Update::Force)
678 << ", singlepar = " << (flags & Update::SinglePar)
679 << "] buffer: " << buffer_ << endl;
681 // Check needed to survive LyX startup
683 // Update macro store
684 buffer_->buildMacros();
687 std::swap(theCoords, backup);
689 // This, together with doneUpdating(), verifies (using
690 // asserts) that screen redraw is not called from
692 theCoords.startUpdating();
694 // First drawing step
695 ViewMetricsInfo vi = metrics(flags & Update::SinglePar);
696 bool forceupdate(flags & (Update::Force | Update::SinglePar));
698 if ((flags & Update::FitCursor) && fitCursor()) {
702 if ((flags & Update::MultiParSel) && multiParSel()) {
707 // Second drawing step
708 screen().redraw(*bv_, vi);
710 // Abort updating of the coord
711 // cache - just restore the old one
712 std::swap(theCoords, backup);
719 owner_->view_state_changed();
723 // Callback for cursor timer
724 void BufferView::Pimpl::cursorToggle()
727 screen().toggleCursor(*bv_);
729 // Use this opportunity to deal with any child processes that
730 // have finished but are waiting to communicate this fact
731 // to the rest of LyX.
732 ForkedcallsController & fcc = ForkedcallsController::get();
733 fcc.handleCompletedProcesses();
736 cursor_timeout.restart();
740 bool BufferView::Pimpl::available() const
742 return buffer_ && bv_->text();
746 Change const BufferView::Pimpl::getCurrentChange()
748 if (!buffer_->params().tracking_changes)
749 return Change(Change::UNCHANGED);
751 LyXText * text = bv_->getLyXText();
752 LCursor & cur = cursor_;
754 if (!cur.selection())
755 return Change(Change::UNCHANGED);
757 return text->getPar(cur.selBegin().pit()).
758 lookupChangeFull(cur.selBegin().pos());
762 void BufferView::Pimpl::savePosition(unsigned int i)
764 if (i >= saved_positions_num)
766 BOOST_ASSERT(cursor_.inTexted());
767 saved_positions[i] = Position(buffer_->fileName(),
768 cursor_.paragraph().id(),
771 owner_->message(bformat(_("Saved bookmark %1$d"), i));
775 void BufferView::Pimpl::restorePosition(unsigned int i)
777 if (i >= saved_positions_num)
780 string const fname = saved_positions[i].filename;
782 cursor_.clearSelection();
784 if (fname != buffer_->fileName()) {
786 if (bufferlist.exists(fname))
787 b = bufferlist.getBuffer(fname);
789 b = bufferlist.newBuffer(fname);
790 // Don't ask, just load it
791 ::loadLyXFile(b, fname);
797 ParIterator par = buffer_->getParFromID(saved_positions[i].par_id);
798 if (par == buffer_->par_iterator_end())
801 bv_->setCursor(makeDocIterator(par, min(par->size(), saved_positions[i].par_pos)));
804 owner_->message(bformat(_("Moved to bookmark %1$d"), i));
808 bool BufferView::Pimpl::isSavedPosition(unsigned int i)
810 return i < saved_positions_num && !saved_positions[i].filename.empty();
814 void BufferView::Pimpl::switchKeyMap()
816 if (!lyxrc.rtl_support)
819 Intl & intl = owner_->getIntl();
820 if (bv_->getLyXText()->real_current_font.isRightToLeft()) {
821 if (intl.keymap == Intl::PRIMARY)
824 if (intl.keymap == Intl::SECONDARY)
830 void BufferView::Pimpl::center()
832 CursorSlice & bot = cursor_.bottom();
833 lyx::pit_type const pit = bot.pit();
834 bot.text()->redoParagraph(pit);
835 Paragraph const & par = bot.text()->paragraphs()[pit];
837 offset_ref_ = bv_funcs::coordOffset(cursor_, cursor_.boundary()).y_
838 + par.ascent() - workarea().workHeight() / 2;
842 void BufferView::Pimpl::stuffClipboard(string const & content) const
844 workarea().putClipboard(content);
848 void BufferView::Pimpl::MenuInsertLyXFile(string const & filenm)
850 BOOST_ASSERT(cursor_.inTexted());
851 string filename = filenm;
853 if (filename.empty()) {
854 // Launch a file browser
855 string initpath = lyxrc.document_path;
858 string const trypath = owner_->buffer()->filePath();
859 // If directory is writeable, use this as default.
860 if (IsDirWriteable(trypath))
864 FileDialog fileDlg(_("Select LyX document to insert"),
866 make_pair(string(_("Documents|#o#O")),
867 string(lyxrc.document_path)),
868 make_pair(string(_("Examples|#E#e")),
869 string(AddPath(package().system_support(), "examples"))));
871 FileDialog::Result result =
872 fileDlg.open(initpath,
873 FileFilterList(_("LyX Documents (*.lyx)")),
876 if (result.first == FileDialog::Later)
879 filename = result.second;
881 // check selected filename
882 if (filename.empty()) {
883 owner_->message(_("Canceled."));
888 // Get absolute path of file and add ".lyx"
889 // to the filename if necessary
890 filename = FileSearch(string(), filename, "lyx");
892 string const disp_fn = MakeDisplayPath(filename);
893 owner_->message(bformat(_("Inserting document %1$s..."), disp_fn));
896 Buffer buf("", false);
897 buf.error.connect(boost::bind(&BufferView::Pimpl::addError, this, _1));
898 if (::loadLyXFile(&buf, MakeAbsPath(filename))) {
899 lyx::cap::pasteParagraphList(cursor_, buf.paragraphs(),
900 buf.params().textclass);
901 res = _("Document %1$s inserted.");
903 res = _("Could not insert document %1$s");
905 owner_->message(bformat(res, disp_fn));
906 bv_->showErrorList(_("Document insertion"));
907 resizeCurrentBuffer();
911 void BufferView::Pimpl::trackChanges()
913 bool const tracking = buffer_->params().tracking_changes;
916 for_each(buffer_->par_iterator_begin(),
917 buffer_->par_iterator_end(),
918 bind(&Paragraph::trackChanges, _1, Change::UNCHANGED));
919 buffer_->params().tracking_changes = true;
921 // We cannot allow undos beyond the freeze point
922 buffer_->undostack().clear();
924 cursor_.setCursor(doc_iterator_begin(buffer_->inset()));
925 if (lyx::find::findNextChange(bv_)) {
926 owner_->getDialogs().show("changes");
930 for_each(buffer_->par_iterator_begin(),
931 buffer_->par_iterator_end(),
932 mem_fun_ref(&Paragraph::untrackChanges));
934 buffer_->params().tracking_changes = false;
937 buffer_->redostack().clear();
941 bool BufferView::Pimpl::workAreaDispatch(FuncRequest const & cmd0)
943 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
945 // This is only called for mouse related events including
946 // LFUN_FILE_OPEN generated by drag-and-drop.
947 FuncRequest cmd = cmd0;
950 if (cmd.action == LFUN_FILE_OPEN) {
951 owner_->dispatch(cmd);
959 cur.push(buffer_->inset());
960 cur.selection() = cursor_.selection();
962 // Doesn't go through lyxfunc, so we need to update
963 // the layout choice etc. ourselves
965 // E.g. Qt mouse press when no buffer
969 screen().hideCursor();
971 // Either the inset under the cursor or the
972 // surrounding LyXText will handle this event.
974 // Build temporary cursor.
975 cmd.y = min(max(cmd.y,-1), workarea().workHeight());
976 InsetBase * inset = bv_->text()->editXY(cur, cmd.x, cmd.y);
977 //lyxerr << BOOST_CURRENT_FUNCTION
978 // << " * hit inset at tip: " << inset << endl;
979 //lyxerr << BOOST_CURRENT_FUNCTION
980 // << " * created temp cursor:" << cur << endl;
982 // Put anchor at the same position.
985 // Try to dispatch to an non-editable inset near this position
986 // via the temp cursor. If the inset wishes to change the real
987 // cursor it has to do so explicitly by using
988 // cur.bv().cursor() = cur; (or similar)
990 inset->dispatch(cur, cmd);
992 // Now dispatch to the temporary cursor. If the real cursor should
993 // be modified, the inset's dispatch has to do so explicitly.
994 if (!cur.result().dispatched())
997 if (cur.result().dispatched()) {
998 // Redraw if requested or necessary.
999 if (cur.result().update())
1000 update(Update::FitCursor | Update::Force);
1002 update(Update::FitCursor | Update::MultiParSel);
1005 // See workAreaKeyPress
1006 cursor_timeout.restart();
1007 screen().showCursor(*bv_);
1009 // Skip these when selecting
1010 if (cmd.action != LFUN_MOUSE_MOTION) {
1011 owner_->updateLayoutChoice();
1012 owner_->updateToolbars();
1015 // Slight hack: this is only called currently when we
1016 // clicked somewhere, so we force through the display
1017 // of the new status here.
1018 owner_->clearMessage();
1023 FuncStatus BufferView::Pimpl::getStatus(FuncRequest const & cmd)
1027 switch (cmd.action) {
1030 flag.enabled(!buffer_->undostack().empty());
1033 flag.enabled(!buffer_->redostack().empty());
1035 case LFUN_FILE_INSERT:
1036 case LFUN_FILE_INSERT_ASCII_PARA:
1037 case LFUN_FILE_INSERT_ASCII:
1038 // FIXME: Actually, these LFUNS should be moved to LyXText
1039 flag.enabled(cursor_.inTexted());
1041 case LFUN_FONT_STATE:
1042 case LFUN_INSERT_LABEL:
1043 case LFUN_BOOKMARK_SAVE:
1044 case LFUN_GOTO_PARAGRAPH:
1045 case LFUN_GOTOERROR:
1047 case LFUN_REFERENCE_GOTO:
1048 case LFUN_WORD_FIND:
1049 case LFUN_WORD_REPLACE:
1054 case LFUN_BIBDB_ADD:
1055 case LFUN_BIBDB_DEL:
1056 case LFUN_WORDS_COUNT:
1060 case LFUN_LABEL_GOTO: {
1061 flag.enabled(!cmd.argument.empty()
1062 || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
1066 case LFUN_BOOKMARK_GOTO:
1067 flag.enabled(isSavedPosition(convert<unsigned int>(cmd.argument)));
1069 case LFUN_TRACK_CHANGES:
1071 flag.setOnOff(buffer_->params().tracking_changes);
1074 case LFUN_OUTPUT_CHANGES: {
1075 LaTeXFeatures features(*buffer_, buffer_->params(), false);
1076 flag.enabled(buffer_ && buffer_->params().tracking_changes
1077 && features.isAvailable("dvipost"));
1078 flag.setOnOff(buffer_->params().output_changes);
1082 case LFUN_MERGE_CHANGES:
1083 case LFUN_ACCEPT_CHANGE: // what about these two
1084 case LFUN_REJECT_CHANGE: // what about these two
1085 case LFUN_ACCEPT_ALL_CHANGES:
1086 case LFUN_REJECT_ALL_CHANGES:
1087 flag.enabled(buffer_ && buffer_->params().tracking_changes);
1090 flag.enabled(false);
1098 bool BufferView::Pimpl::dispatch(FuncRequest const & cmd)
1100 //lyxerr << BOOST_CURRENT_FUNCTION
1101 // << [ cmd = " << cmd << "]" << endl;
1103 // Make sure that the cached BufferView is correct.
1104 lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
1105 << " action[" << cmd.action << ']'
1106 << " arg[" << cmd.argument << ']'
1107 << " x[" << cmd.x << ']'
1108 << " y[" << cmd.y << ']'
1109 << " button[" << cmd.button() << ']'
1112 LCursor & cur = cursor_;
1114 switch (cmd.action) {
1118 cur.message(_("Undo"));
1119 cur.clearSelection();
1120 if (!textUndo(*bv_))
1121 cur.message(_("No further undo information"));
1129 cur.message(_("Redo"));
1130 cur.clearSelection();
1131 if (!textRedo(*bv_))
1132 cur.message(_("No further redo information"));
1138 case LFUN_FILE_INSERT:
1139 MenuInsertLyXFile(cmd.argument);
1142 case LFUN_FILE_INSERT_ASCII_PARA:
1143 InsertAsciiFile(bv_, cmd.argument, true);
1146 case LFUN_FILE_INSERT_ASCII:
1147 InsertAsciiFile(bv_, cmd.argument, false);
1150 case LFUN_FONT_STATE:
1151 cur.message(cur.currentState());
1154 case LFUN_BOOKMARK_SAVE:
1155 savePosition(convert<unsigned int>(cmd.argument));
1158 case LFUN_BOOKMARK_GOTO:
1159 restorePosition(convert<unsigned int>(cmd.argument));
1162 case LFUN_LABEL_GOTO: {
1163 string label = cmd.argument;
1164 if (label.empty()) {
1166 getInsetByCode<InsetRef>(cursor_,
1167 InsetBase::REF_CODE);
1169 label = inset->getContents();
1175 bv_->gotoLabel(label);
1179 case LFUN_GOTO_PARAGRAPH: {
1180 int const id = convert<int>(cmd.argument);
1181 ParIterator par = buffer_->getParFromID(id);
1182 if (par == buffer_->par_iterator_end()) {
1183 lyxerr[Debug::INFO] << "No matching paragraph found! ["
1184 << id << ']' << endl;
1187 lyxerr[Debug::INFO] << "Paragraph " << par->id()
1188 << " found." << endl;
1192 bv_->setCursor(makeDocIterator(par, 0));
1199 case LFUN_GOTOERROR:
1200 bv_funcs::gotoInset(bv_, InsetBase::ERROR_CODE, false);
1204 bv_funcs::gotoInset(bv_, InsetBase::NOTE_CODE, false);
1207 case LFUN_REFERENCE_GOTO: {
1208 vector<InsetBase_code> tmp;
1209 tmp.push_back(InsetBase::LABEL_CODE);
1210 tmp.push_back(InsetBase::REF_CODE);
1211 bv_funcs::gotoInset(bv_, tmp, true);
1215 case LFUN_TRACK_CHANGES:
1219 case LFUN_OUTPUT_CHANGES: {
1220 bool const state = buffer_->params().output_changes;
1221 buffer_->params().output_changes = !state;
1225 case LFUN_MERGE_CHANGES:
1226 if (lyx::find::findNextChange(bv_))
1227 owner_->getDialogs().show("changes");
1230 case LFUN_ACCEPT_ALL_CHANGES: {
1231 cursor_.reset(buffer_->inset());
1232 #ifdef WITH_WARNINGS
1233 #warning FIXME changes
1235 while (lyx::find::findNextChange(bv_))
1236 bv_->getLyXText()->acceptChange(cursor_);
1241 case LFUN_REJECT_ALL_CHANGES: {
1242 cursor_.reset(buffer_->inset());
1243 #ifdef WITH_WARNINGS
1244 #warning FIXME changes
1246 while (lyx::find::findNextChange(bv_))
1247 bv_->getLyXText()->rejectChange(cursor_);
1251 case LFUN_WORD_FIND:
1252 lyx::find::find(bv_, cmd);
1255 case LFUN_WORD_REPLACE:
1256 lyx::find::replace(bv_, cmd);
1260 cur.clearSelection();
1262 cur.message(N_("Mark off"));
1266 cur.clearSelection();
1269 cur.message(N_("Mark on"));
1273 cur.clearSelection();
1276 cur.message(N_("Mark removed"));
1279 cur.message(N_("Mark set"));
1288 case LFUN_BIBDB_ADD: {
1289 LCursor tmpcur = cursor_;
1290 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
1291 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1292 InsetBase::BIBTEX_CODE);
1294 inset->addDatabase(cmd.argument);
1298 case LFUN_BIBDB_DEL: {
1299 LCursor tmpcur = cursor_;
1300 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
1301 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1302 InsetBase::BIBTEX_CODE);
1304 inset->delDatabase(cmd.argument);
1308 case LFUN_WORDS_COUNT: {
1309 DocIterator from, to;
1310 if (cur.selection()) {
1311 from = cur.selectionBegin();
1312 to = cur.selectionEnd();
1314 from = doc_iterator_begin(buffer_->inset());
1315 to = doc_iterator_end(buffer_->inset());
1317 int const count = countWords(from, to);
1320 if (cur.selection())
1321 message = bformat(_("%1$d words in selection."),
1324 message = bformat(_("%1$d words in document."),
1328 if (cur.selection())
1329 message = _("One word in selection.");
1331 message = _("One word in document.");
1334 Alert::information(_("Count words"), message);
1345 ViewMetricsInfo BufferView::Pimpl::metrics(bool singlepar)
1347 // Remove old position cache
1349 BufferView & bv = *bv_;
1350 LyXText * const text = bv.text();
1351 lyx::pit_type size = int(text->paragraphs().size());
1353 if (anchor_ref_ > int(text->paragraphs().size() - 1)) {
1354 anchor_ref_ = int(text->paragraphs().size() - 1);
1358 lyx::pit_type const pit = anchor_ref_;
1361 size_t const npit = text->paragraphs().size();
1363 // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
1364 // the (main text, not inset!) paragraph containing the cursor.
1365 // (if this paragraph contains insets etc., rebreaking will
1366 // recursively descend)
1367 if (!singlepar || pit == cursor_.bottom().pit())
1368 text->redoParagraph(pit);
1369 int y0 = text->getPar(pit).ascent() - offset_ref_;
1371 // Redo paragraphs above anchor if necessary; again, in Single Par
1372 // mode, only if we encounter the (main text) one having the cursor.
1374 while (y1 > 0 && pit1 > 0) {
1375 y1 -= text->getPar(pit1).ascent();
1377 if (!singlepar || pit1 == cursor_.bottom().pit())
1378 text->redoParagraph(pit1);
1379 y1 -= text->getPar(pit1).descent();
1383 // Take care of ascent of first line
1384 y1 -= text->getPar(pit1).ascent();
1386 // Normalize anchor for next time
1390 // Grey at the beginning is ugly
1391 if (pit1 == 0 && y1 > 0) {
1397 // Redo paragraphs below the anchor if necessary. Single par mode:
1398 // only the one containing the cursor if encountered.
1400 while (y2 < bv.workHeight() && pit2 < int(npit) - 1) {
1401 y2 += text->getPar(pit2).descent();
1403 if (!singlepar || pit2 == cursor_.bottom().pit())
1404 text->redoParagraph(pit2);
1405 y2 += text->getPar(pit2).ascent();
1408 // Take care of descent of last line
1409 y2 += text->getPar(pit2).descent();
1411 // The coordinates of all these paragraphs are correct, cache them
1413 for (lyx::pit_type pit = pit1; pit <= pit2; ++pit) {
1414 y += text->getPar(pit).ascent();
1415 theCoords.parPos()[text][pit] = Point(0, y);
1416 if (singlepar && pit == cursor_.bottom().pit()) {
1417 // In Single Paragraph mode, collect here the
1418 // y1 and y2 of the (one) paragraph the cursor is in
1419 y1 = y - text->getPar(pit).ascent();
1420 y2 = y + text->getPar(pit).descent();
1422 y += text->getPar(pit).descent();
1426 // collect cursor paragraph iter bounds
1427 pit1 = cursor_.bottom().pit();
1428 pit2 = cursor_.bottom().pit();
1431 lyxerr[Debug::DEBUG]
1432 << BOOST_CURRENT_FUNCTION
1435 << " pit1: " << pit1
1436 << " pit2: " << pit2
1437 << " npit: " << npit
1438 << " singlepar: " << singlepar
1442 return ViewMetricsInfo(pit1, pit2, y1, y2, singlepar, size);