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"
29 #include "dispatchresult.h"
31 #include "FloatList.h"
32 #include "funcrequest.h"
33 #include "FuncStatus.h"
36 #include "insetiterator.h"
37 #include "LaTeXFeatures.h"
38 #include "lyx_cb.h" // added for Dispatch functions
44 #include "lastfiles.h"
45 #include "metricsinfo.h"
46 #include "paragraph.h"
47 #include "paragraph_funcs.h"
48 #include "ParagraphParameters.h"
49 #include "pariterator.h"
50 #include "rowpainter.h"
54 #include "insets/insetbibtex.h"
55 #include "insets/insetref.h"
56 #include "insets/insettext.h"
58 #include "frontends/Alert.h"
59 #include "frontends/Dialogs.h"
60 #include "frontends/FileDialog.h"
61 #include "frontends/font_metrics.h"
62 #include "frontends/LyXView.h"
63 #include "frontends/LyXScreenFactory.h"
64 #include "frontends/screen.h"
65 #include "frontends/WorkArea.h"
66 #include "frontends/WorkAreaFactory.h"
68 #include "graphics/Previews.h"
70 #include "support/convert.h"
71 #include "support/filefilterlist.h"
72 #include "support/filetools.h"
73 #include "support/forkedcontr.h"
74 #include "support/package.h"
75 #include "support/types.h"
77 #include <boost/bind.hpp>
78 #include <boost/current_function.hpp>
85 using lyx::support::AddPath;
86 using lyx::support::bformat;
87 using lyx::support::FileFilterList;
88 using lyx::support::FileSearch;
89 using lyx::support::ForkedcallsController;
90 using lyx::support::IsDirWriteable;
91 using lyx::support::MakeDisplayPath;
92 using lyx::support::MakeAbsPath;
93 using lyx::support::package;
96 using std::istringstream;
101 using std::mem_fun_ref;
105 extern BufferList bufferlist;
110 unsigned int const saved_positions_num = 20;
112 // All the below connection objects are needed because of a bug in some
113 // versions of GCC (<=2.96 are on the suspects list.) By having and assigning
114 // to these connections we avoid a segfault upon startup, and also at exit.
117 boost::signals::connection dispatchcon;
118 boost::signals::connection timecon;
119 boost::signals::connection doccon;
120 boost::signals::connection resizecon;
121 boost::signals::connection kpresscon;
122 boost::signals::connection selectioncon;
123 boost::signals::connection lostcon;
126 /// Return an inset of this class if it exists at the current cursor position
128 T * getInsetByCode(LCursor & cur, InsetBase::Code code)
131 DocIterator it = cur;
132 if (it.nextInset() &&
133 it.nextInset()->lyxCode() == code) {
134 inset = static_cast<T*>(it.nextInset());
142 BufferView::Pimpl::Pimpl(BufferView & bv, LyXView * owner,
143 int width, int height)
144 : bv_(&bv), owner_(owner), buffer_(0), wh_(0), cursor_timeout(400),
145 using_xterm_cursor(false), cursor_(bv),
146 anchor_ref_(0), offset_ref_(0)
148 xsel_cache_.set = false;
150 workarea_.reset(WorkAreaFactory::create(*owner_, width, height));
151 screen_.reset(LyXScreenFactory::create(workarea()));
154 doccon = workarea().scrollDocView
155 .connect(boost::bind(&BufferView::Pimpl::scrollDocView, this, _1));
156 resizecon = workarea().workAreaResize
157 .connect(boost::bind(&BufferView::Pimpl::workAreaResize, this));
158 dispatchcon = workarea().dispatch
159 .connect(boost::bind(&BufferView::Pimpl::workAreaDispatch, this, _1));
160 kpresscon = workarea().workAreaKeyPress
161 .connect(boost::bind(&BufferView::Pimpl::workAreaKeyPress, this, _1, _2));
162 selectioncon = workarea().selectionRequested
163 .connect(boost::bind(&BufferView::Pimpl::selectionRequested, this));
164 lostcon = workarea().selectionLost
165 .connect(boost::bind(&BufferView::Pimpl::selectionLost, this));
167 timecon = cursor_timeout.timeout
168 .connect(boost::bind(&BufferView::Pimpl::cursorToggle, this));
169 cursor_timeout.start();
170 saved_positions.resize(saved_positions_num);
174 void BufferView::Pimpl::addError(ErrorItem const & ei)
176 errorlist_.push_back(ei);
180 void BufferView::Pimpl::showReadonly(bool)
182 owner_->updateWindowTitle();
183 owner_->getDialogs().updateBufferDependent(false);
187 void BufferView::Pimpl::connectBuffer(Buffer & buf)
189 if (errorConnection_.connected())
194 boost::bind(&BufferView::Pimpl::addError, this, _1));
198 boost::bind(&LyXView::message, owner_, _1));
202 boost::bind(&LyXView::busy, owner_, _1));
205 buf.updateTitles.connect(
206 boost::bind(&LyXView::updateWindowTitle, owner_));
209 buf.resetAutosaveTimers.connect(
210 boost::bind(&LyXView::resetAutosaveTimer, owner_));
212 readonlyConnection_ =
213 buf.readonly.connect(
214 boost::bind(&BufferView::Pimpl::showReadonly, this, _1));
218 boost::bind(&BufferView::Pimpl::setBuffer, this, (Buffer *)0));
222 void BufferView::Pimpl::disconnectBuffer()
224 errorConnection_.disconnect();
225 messageConnection_.disconnect();
226 busyConnection_.disconnect();
227 titleConnection_.disconnect();
228 timerConnection_.disconnect();
229 readonlyConnection_.disconnect();
230 closingConnection_.disconnect();
234 void BufferView::Pimpl::newFile(string const & filename, string const & tname,
237 setBuffer(::newFile(filename, tname, isNamed));
241 bool BufferView::Pimpl::loadLyXFile(string const & filename, bool tolastfiles)
243 // Get absolute path of file and add ".lyx"
244 // to the filename if necessary
245 string s = FileSearch(string(), filename, "lyx");
247 bool const found = !s.empty();
252 // File already open?
253 if (bufferlist.exists(s)) {
254 string const file = MakeDisplayPath(s, 20);
255 string text = bformat(_("The document %1$s is already "
256 "loaded.\n\nDo you want to revert "
257 "to the saved version?"), file);
258 int const ret = Alert::prompt(_("Revert to saved document?"),
259 text, 0, 1, _("&Revert"), _("&Switch to document"));
262 setBuffer(bufferlist.getBuffer(s));
265 // FIXME: should be LFUN_REVERT
266 if (!bufferlist.close(bufferlist.getBuffer(s), false))
268 // Fall through to new load. (Asger)
274 b = bufferlist.newBuffer(s);
276 if (!::loadLyXFile(b, s)) {
277 bufferlist.release(b);
281 string text = bformat(_("The document %1$s does not yet "
282 "exist.\n\nDo you want to create "
283 "a new document?"), s);
284 int const ret = Alert::prompt(_("Create new document?"),
285 text, 0, 1, _("&Create"), _("Cancel"));
288 b = ::newFile(s, string(), true);
294 bv_->showErrorList(_("Parse"));
297 LyX::ref().lastfiles().newFile(b->fileName());
303 WorkArea & BufferView::Pimpl::workarea() const
305 return *workarea_.get();
309 LyXScreen & BufferView::Pimpl::screen() const
311 return *screen_.get();
315 Painter & BufferView::Pimpl::painter() const
317 return workarea().getPainter();
321 void BufferView::Pimpl::setBuffer(Buffer * b)
323 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
324 << "[ b = " << b << "]" << endl;
328 // Save the actual cursor position and anchor inside the
329 // buffer so that it can be restored in case we rechange
330 // to this buffer later on.
331 buffer_->saveCursor(cursor_.selectionBegin(),
332 cursor_.selectionEnd());
335 // If we are closing current buffer, switch to the first in
338 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
339 << " No Buffer!" << endl;
340 // We are closing the buffer, use the first buffer as current
341 buffer_ = bufferlist.first();
342 owner_->getDialogs().hideBufferDependent();
344 // Set current buffer
349 cursor_ = LCursor(*bv_);
354 // If we're quitting lyx, don't bother updating stuff
359 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
360 << "Buffer addr: " << buffer_ << endl;
361 connectBuffer(*buffer_);
362 cursor_.push(buffer_->inset());
363 cursor_.resetAnchor();
364 buffer_->text().init(bv_);
365 buffer_->text().setCurrentFont(cursor_);
366 if (buffer_->getCursor().size() > 0 &&
367 buffer_->getAnchor().size() > 0)
369 cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
370 cursor_.resetAnchor();
371 cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
372 cursor_.setSelection();
375 // Buffer-dependent dialogs should be updated or
376 // hidden. This should go here because some dialogs (eg ToC)
377 // require bv_->text.
378 owner_->getDialogs().updateBufferDependent(true);
383 owner_->updateMenubar();
384 owner_->updateToolbars();
385 owner_->updateLayoutChoice();
386 owner_->updateWindowTitle();
388 // This is done after the layout combox has been populated
390 size_t i = cursor_.depth() - 1;
391 // we know we'll eventually find a paragraph
393 CursorSlice const & slice = cursor_[i];
394 if (!slice.inset().inMathed()) {
395 LyXLayout_ptr const layout = slice.paragraph().layout();
396 owner_->setLayout(layout->name());
404 if (buffer_ && lyx::graphics::Previews::status() != LyXRC::PREVIEW_OFF)
405 lyx::graphics::Previews::get().generateBufferPreviews(*buffer_);
409 void BufferView::Pimpl::resizeCurrentBuffer()
411 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
413 owner_->message(_("Formatting document..."));
415 LyXText * text = bv_->text();
425 // Reset the "Formatting..." message
426 owner_->clearMessage();
432 void BufferView::Pimpl::updateScrollbar()
435 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
436 << " no text in updateScrollbar" << endl;
437 workarea().setScrollbarParams(0, 0, 0);
441 LyXText & t = *bv_->text();
442 int const parsize = int(t.paragraphs().size() - 1);
443 if (anchor_ref_ > parsize) {
444 anchor_ref_ = parsize;
449 << BOOST_CURRENT_FUNCTION
450 << " Updating scrollbar: height: " << t.paragraphs().size()
451 << " curr par: " << cursor_.bottom().pit()
452 << " default height " << defaultRowHeight() << endl;
454 // It would be better to fix the scrollbar to understand
455 // values in [0..1] and divide everything by wh
457 // estimated average paragraph height:
459 wh_ = workarea().workHeight() / 4;
460 int h = t.getPar(anchor_ref_).height();
462 // Normalize anchor/offset (MV):
463 while (offset_ref_ > h && anchor_ref_ < parsize) {
466 h = t.getPar(anchor_ref_).height();
468 // Look at paragraph heights on-screen
471 for (lyx::pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
472 if (sumh > workarea().workHeight())
474 int const h2 = t.getPar(pit).height();
478 int const hav = sumh / nh;
479 // More realistic average paragraph height
483 workarea().setScrollbarParams((parsize + 1) * wh_,
484 anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h)),
485 int(wh_ * defaultRowHeight() / float(h)));
489 void BufferView::Pimpl::scrollDocView(int value)
491 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
492 << "[ value = " << value << "]" << endl;
497 screen().hideCursor();
499 LyXText & t = *bv_->text();
501 float const bar = value / float(wh_ * t.paragraphs().size());
503 anchor_ref_ = int(bar * t.paragraphs().size());
504 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
505 anchor_ref_ = int(t.paragraphs().size()) - 1;
506 t.redoParagraph(anchor_ref_);
507 int const h = t.getPar(anchor_ref_).height();
508 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
511 if (!lyxrc.cursor_follows_scrollbar)
514 int const height = 2 * defaultRowHeight();
515 int const first = height;
516 int const last = workarea().workHeight() - height;
517 LCursor & cur = cursor_;
519 bv_funcs::CurStatus st = bv_funcs::status(bv_, cur);
522 case bv_funcs::CUR_ABOVE:
523 t.setCursorFromCoordinates(cur, 0, first);
524 cur.clearSelection();
526 case bv_funcs::CUR_BELOW:
527 t.setCursorFromCoordinates(cur, 0, last);
528 cur.clearSelection();
530 case bv_funcs::CUR_INSIDE:
531 int const y = bv_funcs::getPos(cur, cur.boundary()).y_;
532 int const newy = min(last, max(y, first));
534 cur.reset(buffer_->inset());
535 t.setCursorFromCoordinates(cur, 0, newy);
538 owner_->updateLayoutChoice();
542 void BufferView::Pimpl::scroll(int /*lines*/)
547 // LyXText const * t = bv_->text();
548 // int const line_height = defaultRowHeight();
550 // // The new absolute coordinate
551 // int new_top_y = top_y() + lines * line_height;
553 // // Restrict to a valid value
554 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
555 // new_top_y = std::max(0, new_top_y);
557 // scrollDocView(new_top_y);
559 // // Update the scrollbar.
560 // workarea().setScrollbarParams(t->height(), top_y(), defaultRowHeight());
564 void BufferView::Pimpl::workAreaKeyPress(LyXKeySymPtr key,
565 key_modifier::state state)
567 owner_->getLyXFunc().processKeySym(key, state);
569 /* This is perhaps a bit of a hack. When we move
570 * around, or type, it's nice to be able to see
571 * the cursor immediately after the keypress. So
572 * we reset the toggle timeout and force the visibility
573 * of the cursor. Note we cannot do this inside
574 * dispatch() itself, because that's called recursively.
577 screen().showCursor(*bv_);
581 void BufferView::Pimpl::selectionRequested()
588 LCursor & cur = cursor_;
590 if (!cur.selection()) {
591 xsel_cache_.set = false;
595 if (!xsel_cache_.set ||
596 cur.top() != xsel_cache_.cursor ||
597 cur.anchor_.top() != xsel_cache_.anchor)
599 xsel_cache_.cursor = cur.top();
600 xsel_cache_.anchor = cur.anchor_.top();
601 xsel_cache_.set = cur.selection();
602 sel = cur.selectionAsString(false);
604 workarea().putClipboard(sel);
609 void BufferView::Pimpl::selectionLost()
612 screen().hideCursor();
613 cursor_.clearSelection();
614 xsel_cache_.set = false;
619 void BufferView::Pimpl::workAreaResize()
621 static int work_area_width;
622 static int work_area_height;
624 bool const widthChange = workarea().workWidth() != work_area_width;
625 bool const heightChange = workarea().workHeight() != work_area_height;
627 // Update from work area
628 work_area_width = workarea().workWidth();
629 work_area_height = workarea().workHeight();
631 if (buffer_ && widthChange) {
632 // The visible LyXView need a resize
633 resizeCurrentBuffer();
636 if (widthChange || heightChange)
639 // Always make sure that the scrollbar is sane.
641 owner_->updateLayoutChoice();
645 bool BufferView::Pimpl::fitCursor()
647 if (bv_funcs::status(bv_, cursor_) == bv_funcs::CUR_INSIDE) {
648 LyXFont const font = cursor_.getFont();
649 int const asc = font_metrics::maxAscent(font);
650 int const des = font_metrics::maxDescent(font);
651 Point const p = bv_funcs::getPos(cursor_, cursor_.boundary());
652 if (p.y_ - asc >= 0 && p.y_ + des < workarea().workHeight())
660 void BufferView::Pimpl::update(Update::flags flags)
663 << BOOST_CURRENT_FUNCTION
664 << "[fitcursor = " << (flags & Update::FitCursor)
665 << ", forceupdate = " << (flags & Update::Force)
666 << ", singlepar = " << (flags & Update::SinglePar)
667 << "] buffer: " << buffer_ << endl;
669 // Check needed to survive LyX startup
671 // Update macro store
672 buffer_->buildMacros();
675 std::swap(theCoords, backup);
677 // This, together with doneUpdating(), verifies (using
678 // asserts) that screen redraw is not called from
680 theCoords.startUpdating();
682 // First drawing step
683 ViewMetricsInfo vi = metrics(flags & Update::SinglePar);
684 bool forceupdate(flags & Update::Force);
686 if ((flags & Update::FitCursor) && fitCursor()) {
691 // Second drawing step
692 screen().redraw(*bv_, vi);
694 // Abort updating of the coord
695 // cache - just restore the old one
696 std::swap(theCoords, backup);
703 owner_->view_state_changed();
707 // Callback for cursor timer
708 void BufferView::Pimpl::cursorToggle()
711 screen().toggleCursor(*bv_);
713 // Use this opportunity to deal with any child processes that
714 // have finished but are waiting to communicate this fact
715 // to the rest of LyX.
716 ForkedcallsController & fcc = ForkedcallsController::get();
717 fcc.handleCompletedProcesses();
720 cursor_timeout.restart();
724 bool BufferView::Pimpl::available() const
726 return buffer_ && bv_->text();
730 Change const BufferView::Pimpl::getCurrentChange()
732 if (!buffer_->params().tracking_changes)
733 return Change(Change::UNCHANGED);
735 LyXText * text = bv_->getLyXText();
736 LCursor & cur = cursor_;
738 if (!cur.selection())
739 return Change(Change::UNCHANGED);
741 return text->getPar(cur.selBegin().pit()).
742 lookupChangeFull(cur.selBegin().pos());
746 void BufferView::Pimpl::savePosition(unsigned int i)
748 if (i >= saved_positions_num)
750 BOOST_ASSERT(cursor_.inTexted());
751 saved_positions[i] = Position(buffer_->fileName(),
752 cursor_.paragraph().id(),
755 owner_->message(bformat(_("Saved bookmark %1$d"), i));
759 void BufferView::Pimpl::restorePosition(unsigned int i)
761 if (i >= saved_positions_num)
764 string const fname = saved_positions[i].filename;
766 cursor_.clearSelection();
768 if (fname != buffer_->fileName()) {
770 if (bufferlist.exists(fname))
771 b = bufferlist.getBuffer(fname);
773 b = bufferlist.newBuffer(fname);
774 // Don't ask, just load it
775 ::loadLyXFile(b, fname);
781 ParIterator par = buffer_->getParFromID(saved_positions[i].par_id);
782 if (par == buffer_->par_iterator_end())
785 bv_->setCursor(makeDocIterator(par, min(par->size(), saved_positions[i].par_pos)));
788 owner_->message(bformat(_("Moved to bookmark %1$d"), i));
792 bool BufferView::Pimpl::isSavedPosition(unsigned int i)
794 return i < saved_positions_num && !saved_positions[i].filename.empty();
798 void BufferView::Pimpl::switchKeyMap()
800 if (!lyxrc.rtl_support)
803 Intl & intl = owner_->getIntl();
804 if (bv_->getLyXText()->real_current_font.isRightToLeft()) {
805 if (intl.keymap == Intl::PRIMARY)
808 if (intl.keymap == Intl::SECONDARY)
814 void BufferView::Pimpl::center()
816 CursorSlice & bot = cursor_.bottom();
817 lyx::pit_type const pit = bot.pit();
818 bot.text()->redoParagraph(pit);
819 Paragraph const & par = bot.text()->paragraphs()[pit];
821 offset_ref_ = bv_funcs::coordOffset(cursor_, cursor_.boundary()).y_
822 + par.ascent() - workarea().workHeight() / 2;
826 void BufferView::Pimpl::stuffClipboard(string const & content) const
828 workarea().putClipboard(content);
832 void BufferView::Pimpl::MenuInsertLyXFile(string const & filenm)
834 string filename = filenm;
836 if (filename.empty()) {
837 // Launch a file browser
838 string initpath = lyxrc.document_path;
841 string const trypath = owner_->buffer()->filePath();
842 // If directory is writeable, use this as default.
843 if (IsDirWriteable(trypath))
847 FileDialog fileDlg(_("Select LyX document to insert"),
849 make_pair(string(_("Documents|#o#O")),
850 string(lyxrc.document_path)),
851 make_pair(string(_("Examples|#E#e")),
852 string(AddPath(package().system_support(), "examples"))));
854 FileDialog::Result result =
855 fileDlg.open(initpath,
856 FileFilterList(_("LyX Documents (*.lyx)")),
859 if (result.first == FileDialog::Later)
862 filename = result.second;
864 // check selected filename
865 if (filename.empty()) {
866 owner_->message(_("Canceled."));
871 // Get absolute path of file and add ".lyx"
872 // to the filename if necessary
873 filename = FileSearch(string(), filename, "lyx");
875 string const disp_fn = MakeDisplayPath(filename);
876 owner_->message(bformat(_("Inserting document %1$s..."), disp_fn));
878 cursor_.clearSelection();
879 bv_->getLyXText()->breakParagraph(cursor_);
881 BOOST_ASSERT(cursor_.inTexted());
883 string const fname = MakeAbsPath(filename);
884 bool const res = buffer_->readFile(fname, cursor_.pit());
885 resizeCurrentBuffer();
887 string s = res ? _("Document %1$s inserted.")
888 : _("Could not insert document %1$s");
889 owner_->message(bformat(s, disp_fn));
893 void BufferView::Pimpl::trackChanges()
895 bool const tracking = buffer_->params().tracking_changes;
898 for_each(buffer_->par_iterator_begin(),
899 buffer_->par_iterator_end(),
900 bind(&Paragraph::trackChanges, _1, Change::UNCHANGED));
901 buffer_->params().tracking_changes = true;
903 // We cannot allow undos beyond the freeze point
904 buffer_->undostack().clear();
906 cursor_.setCursor(doc_iterator_begin(buffer_->inset()));
907 bool const found = lyx::find::findNextChange(bv_);
909 // We reset the cursor to the start of the
910 // document, since the Changes Dialog is going
911 // to search for the next change anyway.
912 cursor_.setCursor(doc_iterator_begin(buffer_->inset()));
913 owner_->getDialogs().show("changes");
917 for_each(buffer_->par_iterator_begin(),
918 buffer_->par_iterator_end(),
919 mem_fun_ref(&Paragraph::untrackChanges));
921 buffer_->params().tracking_changes = false;
924 buffer_->redostack().clear();
928 bool BufferView::Pimpl::workAreaDispatch(FuncRequest const & cmd0)
930 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
932 // This is only called for mouse related events including
933 // LFUN_FILE_OPEN generated by drag-and-drop.
934 FuncRequest cmd = cmd0;
937 if (cmd.action == LFUN_FILE_OPEN) {
938 owner_->dispatch(cmd);
946 cur.push(buffer_->inset());
947 cur.selection() = cursor_.selection();
949 // Doesn't go through lyxfunc, so we need to update
950 // the layout choice etc. ourselves
952 // E.g. Qt mouse press when no buffer
956 screen().hideCursor();
958 // Either the inset under the cursor or the
959 // surrounding LyXText will handle this event.
961 // Build temporary cursor.
962 cmd.y = min(max(cmd.y,-1), workarea().workHeight());
963 InsetBase * inset = bv_->text()->editXY(cur, cmd.x, cmd.y);
964 //lyxerr << BOOST_CURRENT_FUNCTION
965 // << " * hit inset at tip: " << inset << endl;
966 //lyxerr << BOOST_CURRENT_FUNCTION
967 // << " * created temp cursor:" << cur << endl;
969 // Put anchor at the same position.
972 // Try to dispatch to an non-editable inset near this position
973 // via the temp cursor. If the inset wishes to change the real
974 // cursor it has to do so explicitly by using
975 // cur.bv().cursor() = cur; (or similar)
977 inset->dispatch(cur, cmd);
979 // Now dispatch to the temporary cursor. If the real cursor should
980 // be modified, the inset's dispatch has to do so explicitly.
981 if (!cur.result().dispatched())
984 if (cur.result().dispatched()) {
985 // Redraw if requested or necessary.
986 if (cur.result().update())
987 update(Update::FitCursor | Update::Force);
992 // See workAreaKeyPress
993 cursor_timeout.restart();
994 screen().showCursor(*bv_);
996 // Skip these when selecting
997 if (cmd.action != LFUN_MOUSE_MOTION) {
998 owner_->updateLayoutChoice();
999 owner_->updateToolbars();
1002 // Slight hack: this is only called currently when we
1003 // clicked somewhere, so we force through the display
1004 // of the new status here.
1005 owner_->clearMessage();
1010 FuncStatus BufferView::Pimpl::getStatus(FuncRequest const & cmd)
1014 switch (cmd.action) {
1017 flag.enabled(!buffer_->undostack().empty());
1020 flag.enabled(!buffer_->redostack().empty());
1022 case LFUN_FILE_INSERT:
1023 case LFUN_FILE_INSERT_ASCII_PARA:
1024 case LFUN_FILE_INSERT_ASCII:
1025 case LFUN_FONT_STATE:
1026 case LFUN_INSERT_LABEL:
1027 case LFUN_BOOKMARK_SAVE:
1028 case LFUN_GOTO_PARAGRAPH:
1029 case LFUN_GOTOERROR:
1031 case LFUN_REFERENCE_GOTO:
1032 case LFUN_WORD_FIND:
1033 case LFUN_WORD_REPLACE:
1038 case LFUN_BIBDB_ADD:
1039 case LFUN_BIBDB_DEL:
1040 case LFUN_WORDS_COUNT:
1044 case LFUN_LABEL_GOTO: {
1045 flag.enabled(!cmd.argument.empty()
1046 || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
1050 case LFUN_BOOKMARK_GOTO:
1051 flag.enabled(isSavedPosition(convert<unsigned int>(cmd.argument)));
1053 case LFUN_TRACK_CHANGES:
1055 flag.setOnOff(buffer_->params().tracking_changes);
1058 case LFUN_OUTPUT_CHANGES: {
1059 LaTeXFeatures features(*buffer_, buffer_->params(), false);
1060 flag.enabled(buffer_ && buffer_->params().tracking_changes
1061 && features.isAvailable("dvipost"));
1062 flag.setOnOff(buffer_->params().output_changes);
1066 case LFUN_MERGE_CHANGES:
1067 case LFUN_ACCEPT_CHANGE: // what about these two
1068 case LFUN_REJECT_CHANGE: // what about these two
1069 case LFUN_ACCEPT_ALL_CHANGES:
1070 case LFUN_REJECT_ALL_CHANGES:
1071 flag.enabled(buffer_ && buffer_->params().tracking_changes);
1074 flag.enabled(false);
1082 bool BufferView::Pimpl::dispatch(FuncRequest const & cmd)
1084 //lyxerr << BOOST_CURRENT_FUNCTION
1085 // << [ cmd = " << cmd << "]" << endl;
1087 // Make sure that the cached BufferView is correct.
1088 lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
1089 << " action[" << cmd.action << ']'
1090 << " arg[" << cmd.argument << ']'
1091 << " x[" << cmd.x << ']'
1092 << " y[" << cmd.y << ']'
1093 << " button[" << cmd.button() << ']'
1096 LCursor & cur = cursor_;
1098 switch (cmd.action) {
1102 cur.message(_("Undo"));
1103 cur.clearSelection();
1104 if (!textUndo(*bv_))
1105 cur.message(_("No further undo information"));
1113 cur.message(_("Redo"));
1114 cur.clearSelection();
1115 if (!textRedo(*bv_))
1116 cur.message(_("No further redo information"));
1122 case LFUN_FILE_INSERT:
1123 MenuInsertLyXFile(cmd.argument);
1126 case LFUN_FILE_INSERT_ASCII_PARA:
1127 InsertAsciiFile(bv_, cmd.argument, true);
1130 case LFUN_FILE_INSERT_ASCII:
1131 InsertAsciiFile(bv_, cmd.argument, false);
1134 case LFUN_FONT_STATE:
1135 cur.message(cur.currentState());
1138 case LFUN_BOOKMARK_SAVE:
1139 savePosition(convert<unsigned int>(cmd.argument));
1142 case LFUN_BOOKMARK_GOTO:
1143 restorePosition(convert<unsigned int>(cmd.argument));
1146 case LFUN_LABEL_GOTO: {
1147 string label = cmd.argument;
1148 if (label.empty()) {
1150 getInsetByCode<InsetRef>(cursor_,
1151 InsetBase::REF_CODE);
1153 label = inset->getContents();
1159 bv_->gotoLabel(label);
1163 case LFUN_GOTO_PARAGRAPH: {
1164 int const id = convert<int>(cmd.argument);
1165 ParIterator par = buffer_->getParFromID(id);
1166 if (par == buffer_->par_iterator_end()) {
1167 lyxerr[Debug::INFO] << "No matching paragraph found! ["
1168 << id << ']' << endl;
1171 lyxerr[Debug::INFO] << "Paragraph " << par->id()
1172 << " found." << endl;
1176 bv_->setCursor(makeDocIterator(par, 0));
1183 case LFUN_GOTOERROR:
1184 bv_funcs::gotoInset(bv_, InsetBase::ERROR_CODE, false);
1188 bv_funcs::gotoInset(bv_, InsetBase::NOTE_CODE, false);
1191 case LFUN_REFERENCE_GOTO: {
1192 vector<InsetBase_code> tmp;
1193 tmp.push_back(InsetBase::LABEL_CODE);
1194 tmp.push_back(InsetBase::REF_CODE);
1195 bv_funcs::gotoInset(bv_, tmp, true);
1199 case LFUN_TRACK_CHANGES:
1203 case LFUN_OUTPUT_CHANGES: {
1204 bool const state = buffer_->params().output_changes;
1205 buffer_->params().output_changes = !state;
1209 case LFUN_MERGE_CHANGES:
1210 owner_->getDialogs().show("changes");
1213 case LFUN_ACCEPT_ALL_CHANGES: {
1214 cursor_.reset(buffer_->inset());
1215 #ifdef WITH_WARNINGS
1216 #warning FIXME changes
1218 while (lyx::find::findNextChange(bv_))
1219 bv_->getLyXText()->acceptChange(cursor_);
1224 case LFUN_REJECT_ALL_CHANGES: {
1225 cursor_.reset(buffer_->inset());
1226 #ifdef WITH_WARNINGS
1227 #warning FIXME changes
1229 while (lyx::find::findNextChange(bv_))
1230 bv_->getLyXText()->rejectChange(cursor_);
1234 case LFUN_WORD_FIND:
1235 lyx::find::find(bv_, cmd);
1238 case LFUN_WORD_REPLACE:
1239 lyx::find::replace(bv_, cmd);
1243 cur.clearSelection();
1245 cur.message(N_("Mark off"));
1249 cur.clearSelection();
1252 cur.message(N_("Mark on"));
1256 cur.clearSelection();
1259 cur.message(N_("Mark removed"));
1262 cur.message(N_("Mark set"));
1271 case LFUN_BIBDB_ADD: {
1272 LCursor tmpcur = cursor_;
1273 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
1274 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1275 InsetBase::BIBTEX_CODE);
1277 inset->addDatabase(cmd.argument);
1281 case LFUN_BIBDB_DEL: {
1282 LCursor tmpcur = cursor_;
1283 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
1284 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1285 InsetBase::BIBTEX_CODE);
1287 inset->delDatabase(cmd.argument);
1291 case LFUN_WORDS_COUNT: {
1292 DocIterator from, to;
1293 if (cur.selection()) {
1294 from = cur.selectionBegin();
1295 to = cur.selectionEnd();
1297 from = doc_iterator_begin(buffer_->inset());
1298 to = doc_iterator_end(buffer_->inset());
1300 int const count = countWords(from, to);
1303 if (cur.selection())
1304 message = bformat(_("%1$d words in selection."),
1307 message = bformat(_("%1$d words in document."),
1311 if (cur.selection())
1312 message = _("One word in selection.");
1314 message = _("One word in document.");
1317 Alert::information(_("Count words"), message);
1328 ViewMetricsInfo BufferView::Pimpl::metrics(bool singlepar)
1330 // Remove old position cache
1332 BufferView & bv = *bv_;
1333 LyXText * const text = bv.text();
1334 if (anchor_ref_ > int(text->paragraphs().size() - 1)) {
1335 anchor_ref_ = int(text->paragraphs().size() - 1);
1339 lyx::pit_type const pit = anchor_ref_;
1342 size_t const npit = text->paragraphs().size();
1344 // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
1345 // the (main text, not inset!) paragraph containing the cursor.
1346 // (if this paragraph contains insets etc., rebreaking will
1347 // recursively descend)
1348 if (!singlepar || pit == cursor_.bottom().pit())
1349 text->redoParagraph(pit);
1350 int y0 = text->getPar(pit).ascent() - offset_ref_;
1352 // Redo paragraphs above anchor if necessary; again, in Single Par
1353 // mode, only if we encounter the (main text) one having the cursor.
1355 while (y1 > 0 && pit1 > 0) {
1356 y1 -= text->getPar(pit1).ascent();
1358 if (!singlepar || pit1 == cursor_.bottom().pit())
1359 text->redoParagraph(pit1);
1360 y1 -= text->getPar(pit1).descent();
1364 // Take care of ascent of first line
1365 y1 -= text->getPar(pit1).ascent();
1367 // Normalize anchor for next time
1371 // Grey at the beginning is ugly
1372 if (pit1 == 0 && y1 > 0) {
1378 // Redo paragraphs below the anchor if necessary. Single par mode:
1379 // only the one containing the cursor if encountered.
1381 while (y2 < bv.workHeight() && pit2 < int(npit) - 1) {
1382 y2 += text->getPar(pit2).descent();
1384 if (!singlepar || pit2 == cursor_.bottom().pit())
1385 text->redoParagraph(pit2);
1386 y2 += text->getPar(pit2).ascent();
1389 // Take care of descent of last line
1390 y2 += text->getPar(pit2).descent();
1392 // The coordinates of all these paragraphs are correct, cache them
1394 for (lyx::pit_type pit = pit1; pit <= pit2; ++pit) {
1395 y += text->getPar(pit).ascent();
1396 theCoords.parPos()[text][pit] = Point(0, y);
1397 if (singlepar && pit == cursor_.bottom().pit()) {
1398 // In Single Paragraph mode, collect here the
1399 // y1 and y2 of the (one) paragraph the cursor is in
1400 y1 = y - text->getPar(pit).ascent();
1401 y2 = y + text->getPar(pit).descent();
1403 y += text->getPar(pit).descent();
1407 // collect cursor paragraph iter bounds
1408 pit1 = cursor_.bottom().pit();
1409 pit2 = cursor_.bottom().pit();
1412 lyxerr[Debug::DEBUG]
1413 << BOOST_CURRENT_FUNCTION
1416 << " pit1: " << pit1
1417 << " pit2: " << pit2
1418 << " npit: " << npit
1419 << " singlepar: " << singlepar
1422 return ViewMetricsInfo(pit1, pit2, y1, y2, singlepar);