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 void BufferView::Pimpl::update(Update::flags flags)
664 << BOOST_CURRENT_FUNCTION
665 << "[fitcursor = " << (flags & Update::FitCursor)
666 << ", forceupdate = " << (flags & Update::Force)
667 << ", singlepar = " << (flags & Update::SinglePar)
668 << "] buffer: " << buffer_ << endl;
670 // Check needed to survive LyX startup
672 // Update macro store
673 buffer_->buildMacros();
676 std::swap(theCoords, backup);
678 // This, together with doneUpdating(), verifies (using
679 // asserts) that screen redraw is not called from
681 theCoords.startUpdating();
683 // First drawing step
684 ViewMetricsInfo vi = metrics(flags & Update::SinglePar);
685 bool forceupdate(flags & Update::Force);
687 if ((flags & Update::FitCursor) && fitCursor()) {
692 // Second drawing step
693 screen().redraw(*bv_, vi);
695 // Abort updating of the coord
696 // cache - just restore the old one
697 std::swap(theCoords, backup);
704 owner_->view_state_changed();
708 // Callback for cursor timer
709 void BufferView::Pimpl::cursorToggle()
712 screen().toggleCursor(*bv_);
714 // Use this opportunity to deal with any child processes that
715 // have finished but are waiting to communicate this fact
716 // to the rest of LyX.
717 ForkedcallsController & fcc = ForkedcallsController::get();
718 fcc.handleCompletedProcesses();
721 cursor_timeout.restart();
725 bool BufferView::Pimpl::available() const
727 return buffer_ && bv_->text();
731 Change const BufferView::Pimpl::getCurrentChange()
733 if (!buffer_->params().tracking_changes)
734 return Change(Change::UNCHANGED);
736 LyXText * text = bv_->getLyXText();
737 LCursor & cur = cursor_;
739 if (!cur.selection())
740 return Change(Change::UNCHANGED);
742 return text->getPar(cur.selBegin().pit()).
743 lookupChangeFull(cur.selBegin().pos());
747 void BufferView::Pimpl::savePosition(unsigned int i)
749 if (i >= saved_positions_num)
751 BOOST_ASSERT(cursor_.inTexted());
752 saved_positions[i] = Position(buffer_->fileName(),
753 cursor_.paragraph().id(),
756 owner_->message(bformat(_("Saved bookmark %1$d"), i));
760 void BufferView::Pimpl::restorePosition(unsigned int i)
762 if (i >= saved_positions_num)
765 string const fname = saved_positions[i].filename;
767 cursor_.clearSelection();
769 if (fname != buffer_->fileName()) {
771 if (bufferlist.exists(fname))
772 b = bufferlist.getBuffer(fname);
774 b = bufferlist.newBuffer(fname);
775 // Don't ask, just load it
776 ::loadLyXFile(b, fname);
782 ParIterator par = buffer_->getParFromID(saved_positions[i].par_id);
783 if (par == buffer_->par_iterator_end())
786 bv_->setCursor(makeDocIterator(par, min(par->size(), saved_positions[i].par_pos)));
789 owner_->message(bformat(_("Moved to bookmark %1$d"), i));
793 bool BufferView::Pimpl::isSavedPosition(unsigned int i)
795 return i < saved_positions_num && !saved_positions[i].filename.empty();
799 void BufferView::Pimpl::switchKeyMap()
801 if (!lyxrc.rtl_support)
804 Intl & intl = owner_->getIntl();
805 if (bv_->getLyXText()->real_current_font.isRightToLeft()) {
806 if (intl.keymap == Intl::PRIMARY)
809 if (intl.keymap == Intl::SECONDARY)
815 void BufferView::Pimpl::center()
817 CursorSlice & bot = cursor_.bottom();
818 lyx::pit_type const pit = bot.pit();
819 bot.text()->redoParagraph(pit);
820 Paragraph const & par = bot.text()->paragraphs()[pit];
822 offset_ref_ = bv_funcs::coordOffset(cursor_, cursor_.boundary()).y_
823 + par.ascent() - workarea().workHeight() / 2;
827 void BufferView::Pimpl::stuffClipboard(string const & content) const
829 workarea().putClipboard(content);
833 void BufferView::Pimpl::MenuInsertLyXFile(string const & filenm)
835 BOOST_ASSERT(cursor_.inTexted());
836 string filename = filenm;
838 if (filename.empty()) {
839 // Launch a file browser
840 string initpath = lyxrc.document_path;
843 string const trypath = owner_->buffer()->filePath();
844 // If directory is writeable, use this as default.
845 if (IsDirWriteable(trypath))
849 FileDialog fileDlg(_("Select LyX document to insert"),
851 make_pair(string(_("Documents|#o#O")),
852 string(lyxrc.document_path)),
853 make_pair(string(_("Examples|#E#e")),
854 string(AddPath(package().system_support(), "examples"))));
856 FileDialog::Result result =
857 fileDlg.open(initpath,
858 FileFilterList(_("LyX Documents (*.lyx)")),
861 if (result.first == FileDialog::Later)
864 filename = result.second;
866 // check selected filename
867 if (filename.empty()) {
868 owner_->message(_("Canceled."));
873 // Get absolute path of file and add ".lyx"
874 // to the filename if necessary
875 filename = FileSearch(string(), filename, "lyx");
877 string const disp_fn = MakeDisplayPath(filename);
878 owner_->message(bformat(_("Inserting document %1$s..."), disp_fn));
881 Buffer buf("", false);
882 buf.error.connect(boost::bind(&BufferView::Pimpl::addError, this, _1));
883 if (::loadLyXFile(&buf, MakeAbsPath(filename))) {
884 lyx::cap::pasteParagraphList(cursor_, buf.paragraphs(),
885 buf.params().textclass);
886 res = _("Document %1$s inserted.");
888 res = _("Could not insert document %1$s");
890 owner_->message(bformat(res, disp_fn));
891 bv_->showErrorList(_("Document insertion"));
892 resizeCurrentBuffer();
896 void BufferView::Pimpl::trackChanges()
898 bool const tracking = buffer_->params().tracking_changes;
901 for_each(buffer_->par_iterator_begin(),
902 buffer_->par_iterator_end(),
903 bind(&Paragraph::trackChanges, _1, Change::UNCHANGED));
904 buffer_->params().tracking_changes = true;
906 // We cannot allow undos beyond the freeze point
907 buffer_->undostack().clear();
909 cursor_.setCursor(doc_iterator_begin(buffer_->inset()));
910 bool const found = lyx::find::findNextChange(bv_);
912 // We reset the cursor to the start of the
913 // document, since the Changes Dialog is going
914 // to search for the next change anyway.
915 cursor_.setCursor(doc_iterator_begin(buffer_->inset()));
916 owner_->getDialogs().show("changes");
920 for_each(buffer_->par_iterator_begin(),
921 buffer_->par_iterator_end(),
922 mem_fun_ref(&Paragraph::untrackChanges));
924 buffer_->params().tracking_changes = false;
927 buffer_->redostack().clear();
931 bool BufferView::Pimpl::workAreaDispatch(FuncRequest const & cmd0)
933 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
935 // This is only called for mouse related events including
936 // LFUN_FILE_OPEN generated by drag-and-drop.
937 FuncRequest cmd = cmd0;
940 if (cmd.action == LFUN_FILE_OPEN) {
941 owner_->dispatch(cmd);
949 cur.push(buffer_->inset());
950 cur.selection() = cursor_.selection();
952 // Doesn't go through lyxfunc, so we need to update
953 // the layout choice etc. ourselves
955 // E.g. Qt mouse press when no buffer
959 screen().hideCursor();
961 // Either the inset under the cursor or the
962 // surrounding LyXText will handle this event.
964 // Build temporary cursor.
965 cmd.y = min(max(cmd.y,-1), workarea().workHeight());
966 InsetBase * inset = bv_->text()->editXY(cur, cmd.x, cmd.y);
967 //lyxerr << BOOST_CURRENT_FUNCTION
968 // << " * hit inset at tip: " << inset << endl;
969 //lyxerr << BOOST_CURRENT_FUNCTION
970 // << " * created temp cursor:" << cur << endl;
972 // Put anchor at the same position.
975 // Try to dispatch to an non-editable inset near this position
976 // via the temp cursor. If the inset wishes to change the real
977 // cursor it has to do so explicitly by using
978 // cur.bv().cursor() = cur; (or similar)
980 inset->dispatch(cur, cmd);
982 // Now dispatch to the temporary cursor. If the real cursor should
983 // be modified, the inset's dispatch has to do so explicitly.
984 if (!cur.result().dispatched())
987 if (cur.result().dispatched()) {
988 // Redraw if requested or necessary.
989 if (cur.result().update())
990 update(Update::FitCursor | Update::Force);
995 // See workAreaKeyPress
996 cursor_timeout.restart();
997 screen().showCursor(*bv_);
999 // Skip these when selecting
1000 if (cmd.action != LFUN_MOUSE_MOTION) {
1001 owner_->updateLayoutChoice();
1002 owner_->updateToolbars();
1005 // Slight hack: this is only called currently when we
1006 // clicked somewhere, so we force through the display
1007 // of the new status here.
1008 owner_->clearMessage();
1013 FuncStatus BufferView::Pimpl::getStatus(FuncRequest const & cmd)
1017 switch (cmd.action) {
1020 flag.enabled(!buffer_->undostack().empty());
1023 flag.enabled(!buffer_->redostack().empty());
1025 case LFUN_FILE_INSERT:
1026 case LFUN_FILE_INSERT_ASCII_PARA:
1027 case LFUN_FILE_INSERT_ASCII:
1028 // FIXME: Actually, these LFUNS should be moved to LyXText
1029 flag.enabled(cursor_.inTexted());
1031 case LFUN_FONT_STATE:
1032 case LFUN_INSERT_LABEL:
1033 case LFUN_BOOKMARK_SAVE:
1034 case LFUN_GOTO_PARAGRAPH:
1035 case LFUN_GOTOERROR:
1037 case LFUN_REFERENCE_GOTO:
1038 case LFUN_WORD_FIND:
1039 case LFUN_WORD_REPLACE:
1044 case LFUN_BIBDB_ADD:
1045 case LFUN_BIBDB_DEL:
1046 case LFUN_WORDS_COUNT:
1050 case LFUN_LABEL_GOTO: {
1051 flag.enabled(!cmd.argument.empty()
1052 || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
1056 case LFUN_BOOKMARK_GOTO:
1057 flag.enabled(isSavedPosition(convert<unsigned int>(cmd.argument)));
1059 case LFUN_TRACK_CHANGES:
1061 flag.setOnOff(buffer_->params().tracking_changes);
1064 case LFUN_OUTPUT_CHANGES: {
1065 LaTeXFeatures features(*buffer_, buffer_->params(), false);
1066 flag.enabled(buffer_ && buffer_->params().tracking_changes
1067 && features.isAvailable("dvipost"));
1068 flag.setOnOff(buffer_->params().output_changes);
1072 case LFUN_MERGE_CHANGES:
1073 case LFUN_ACCEPT_CHANGE: // what about these two
1074 case LFUN_REJECT_CHANGE: // what about these two
1075 case LFUN_ACCEPT_ALL_CHANGES:
1076 case LFUN_REJECT_ALL_CHANGES:
1077 flag.enabled(buffer_ && buffer_->params().tracking_changes);
1080 flag.enabled(false);
1088 bool BufferView::Pimpl::dispatch(FuncRequest const & cmd)
1090 //lyxerr << BOOST_CURRENT_FUNCTION
1091 // << [ cmd = " << cmd << "]" << endl;
1093 // Make sure that the cached BufferView is correct.
1094 lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
1095 << " action[" << cmd.action << ']'
1096 << " arg[" << cmd.argument << ']'
1097 << " x[" << cmd.x << ']'
1098 << " y[" << cmd.y << ']'
1099 << " button[" << cmd.button() << ']'
1102 LCursor & cur = cursor_;
1104 switch (cmd.action) {
1108 cur.message(_("Undo"));
1109 cur.clearSelection();
1110 if (!textUndo(*bv_))
1111 cur.message(_("No further undo information"));
1119 cur.message(_("Redo"));
1120 cur.clearSelection();
1121 if (!textRedo(*bv_))
1122 cur.message(_("No further redo information"));
1128 case LFUN_FILE_INSERT:
1129 MenuInsertLyXFile(cmd.argument);
1132 case LFUN_FILE_INSERT_ASCII_PARA:
1133 InsertAsciiFile(bv_, cmd.argument, true);
1136 case LFUN_FILE_INSERT_ASCII:
1137 InsertAsciiFile(bv_, cmd.argument, false);
1140 case LFUN_FONT_STATE:
1141 cur.message(cur.currentState());
1144 case LFUN_BOOKMARK_SAVE:
1145 savePosition(convert<unsigned int>(cmd.argument));
1148 case LFUN_BOOKMARK_GOTO:
1149 restorePosition(convert<unsigned int>(cmd.argument));
1152 case LFUN_LABEL_GOTO: {
1153 string label = cmd.argument;
1154 if (label.empty()) {
1156 getInsetByCode<InsetRef>(cursor_,
1157 InsetBase::REF_CODE);
1159 label = inset->getContents();
1165 bv_->gotoLabel(label);
1169 case LFUN_GOTO_PARAGRAPH: {
1170 int const id = convert<int>(cmd.argument);
1171 ParIterator par = buffer_->getParFromID(id);
1172 if (par == buffer_->par_iterator_end()) {
1173 lyxerr[Debug::INFO] << "No matching paragraph found! ["
1174 << id << ']' << endl;
1177 lyxerr[Debug::INFO] << "Paragraph " << par->id()
1178 << " found." << endl;
1182 bv_->setCursor(makeDocIterator(par, 0));
1189 case LFUN_GOTOERROR:
1190 bv_funcs::gotoInset(bv_, InsetBase::ERROR_CODE, false);
1194 bv_funcs::gotoInset(bv_, InsetBase::NOTE_CODE, false);
1197 case LFUN_REFERENCE_GOTO: {
1198 vector<InsetBase_code> tmp;
1199 tmp.push_back(InsetBase::LABEL_CODE);
1200 tmp.push_back(InsetBase::REF_CODE);
1201 bv_funcs::gotoInset(bv_, tmp, true);
1205 case LFUN_TRACK_CHANGES:
1209 case LFUN_OUTPUT_CHANGES: {
1210 bool const state = buffer_->params().output_changes;
1211 buffer_->params().output_changes = !state;
1215 case LFUN_MERGE_CHANGES:
1216 owner_->getDialogs().show("changes");
1219 case LFUN_ACCEPT_ALL_CHANGES: {
1220 cursor_.reset(buffer_->inset());
1221 #ifdef WITH_WARNINGS
1222 #warning FIXME changes
1224 while (lyx::find::findNextChange(bv_))
1225 bv_->getLyXText()->acceptChange(cursor_);
1230 case LFUN_REJECT_ALL_CHANGES: {
1231 cursor_.reset(buffer_->inset());
1232 #ifdef WITH_WARNINGS
1233 #warning FIXME changes
1235 while (lyx::find::findNextChange(bv_))
1236 bv_->getLyXText()->rejectChange(cursor_);
1240 case LFUN_WORD_FIND:
1241 lyx::find::find(bv_, cmd);
1244 case LFUN_WORD_REPLACE:
1245 lyx::find::replace(bv_, cmd);
1249 cur.clearSelection();
1251 cur.message(N_("Mark off"));
1255 cur.clearSelection();
1258 cur.message(N_("Mark on"));
1262 cur.clearSelection();
1265 cur.message(N_("Mark removed"));
1268 cur.message(N_("Mark set"));
1277 case LFUN_BIBDB_ADD: {
1278 LCursor tmpcur = cursor_;
1279 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
1280 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1281 InsetBase::BIBTEX_CODE);
1283 inset->addDatabase(cmd.argument);
1287 case LFUN_BIBDB_DEL: {
1288 LCursor tmpcur = cursor_;
1289 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
1290 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1291 InsetBase::BIBTEX_CODE);
1293 inset->delDatabase(cmd.argument);
1297 case LFUN_WORDS_COUNT: {
1298 DocIterator from, to;
1299 if (cur.selection()) {
1300 from = cur.selectionBegin();
1301 to = cur.selectionEnd();
1303 from = doc_iterator_begin(buffer_->inset());
1304 to = doc_iterator_end(buffer_->inset());
1306 int const count = countWords(from, to);
1309 if (cur.selection())
1310 message = bformat(_("%1$d words in selection."),
1313 message = bformat(_("%1$d words in document."),
1317 if (cur.selection())
1318 message = _("One word in selection.");
1320 message = _("One word in document.");
1323 Alert::information(_("Count words"), message);
1334 ViewMetricsInfo BufferView::Pimpl::metrics(bool singlepar)
1336 // Remove old position cache
1338 BufferView & bv = *bv_;
1339 LyXText * const text = bv.text();
1340 if (anchor_ref_ > int(text->paragraphs().size() - 1)) {
1341 anchor_ref_ = int(text->paragraphs().size() - 1);
1345 lyx::pit_type const pit = anchor_ref_;
1348 size_t const npit = text->paragraphs().size();
1350 // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
1351 // the (main text, not inset!) paragraph containing the cursor.
1352 // (if this paragraph contains insets etc., rebreaking will
1353 // recursively descend)
1354 if (!singlepar || pit == cursor_.bottom().pit())
1355 text->redoParagraph(pit);
1356 int y0 = text->getPar(pit).ascent() - offset_ref_;
1358 // Redo paragraphs above anchor if necessary; again, in Single Par
1359 // mode, only if we encounter the (main text) one having the cursor.
1361 while (y1 > 0 && pit1 > 0) {
1362 y1 -= text->getPar(pit1).ascent();
1364 if (!singlepar || pit1 == cursor_.bottom().pit())
1365 text->redoParagraph(pit1);
1366 y1 -= text->getPar(pit1).descent();
1370 // Take care of ascent of first line
1371 y1 -= text->getPar(pit1).ascent();
1373 // Normalize anchor for next time
1377 // Grey at the beginning is ugly
1378 if (pit1 == 0 && y1 > 0) {
1384 // Redo paragraphs below the anchor if necessary. Single par mode:
1385 // only the one containing the cursor if encountered.
1387 while (y2 < bv.workHeight() && pit2 < int(npit) - 1) {
1388 y2 += text->getPar(pit2).descent();
1390 if (!singlepar || pit2 == cursor_.bottom().pit())
1391 text->redoParagraph(pit2);
1392 y2 += text->getPar(pit2).ascent();
1395 // Take care of descent of last line
1396 y2 += text->getPar(pit2).descent();
1398 // The coordinates of all these paragraphs are correct, cache them
1400 for (lyx::pit_type pit = pit1; pit <= pit2; ++pit) {
1401 y += text->getPar(pit).ascent();
1402 theCoords.parPos()[text][pit] = Point(0, y);
1403 if (singlepar && pit == cursor_.bottom().pit()) {
1404 // In Single Paragraph mode, collect here the
1405 // y1 and y2 of the (one) paragraph the cursor is in
1406 y1 = y - text->getPar(pit).ascent();
1407 y2 = y + text->getPar(pit).descent();
1409 y += text->getPar(pit).descent();
1413 // collect cursor paragraph iter bounds
1414 pit1 = cursor_.bottom().pit();
1415 pit2 = cursor_.bottom().pit();
1418 lyxerr[Debug::DEBUG]
1419 << BOOST_CURRENT_FUNCTION
1422 << " pit1: " << pit1
1423 << " pit2: " << pit2
1424 << " npit: " << npit
1425 << " singlepar: " << singlepar
1428 return ViewMetricsInfo(pit1, pit2, y1, y2, singlepar);