3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Alfredo Braunstein
7 * \author Lars Gullik Bjønnes
10 * \author Jürgen Vigna
12 * Full author contact details are available in file CREDITS.
17 #include "BufferView.h"
20 #include "buffer_funcs.h"
21 #include "bufferlist.h"
22 #include "bufferparams.h"
23 #include "coordcache.h"
24 #include "CutAndPaste.h"
26 #include "dispatchresult.h"
27 #include "errorlist.h"
29 #include "FloatList.h"
30 #include "funcrequest.h"
31 #include "FuncStatus.h"
34 #include "insetiterator.h"
36 #include "LaTeXFeatures.h"
37 #include "lyx_cb.h" // added for Dispatch functions
41 #include "lyxlayout.h"
43 #include "lyxtextclass.h"
46 #include "paragraph.h"
47 #include "paragraph_funcs.h"
48 #include "ParagraphParameters.h"
49 #include "pariterator.h"
54 #include "WordLangTuple.h"
55 #include "metricsinfo.h"
57 #include "insets/insetbibtex.h"
58 #include "insets/insetcommand.h" // ChangeRefs
59 #include "insets/insetref.h"
60 #include "insets/insettext.h"
62 #include "frontends/Alert.h"
63 #include "frontends/FileDialog.h"
64 #include "frontends/FontMetrics.h"
66 #include "graphics/Previews.h"
68 #include "support/convert.h"
69 #include "support/filefilterlist.h"
70 #include "support/filetools.h"
71 #include "support/package.h"
72 #include "support/types.h"
74 #include <boost/bind.hpp>
75 #include <boost/current_function.hpp>
83 using support::addPath;
84 using support::bformat;
85 using support::FileFilterList;
86 using support::FileName;
87 using support::fileSearch;
88 using support::isDirWriteable;
89 using support::isFileReadable;
90 using support::makeDisplayPath;
91 using support::makeAbsPath;
92 using support::package;
96 using std::istringstream;
100 using std::mem_fun_ref;
104 namespace Alert = frontend::Alert;
108 /// Return an inset of this class if it exists at the current cursor position
110 T * getInsetByCode(LCursor & cur, InsetBase::Code code)
113 DocIterator it = cur;
114 if (it.nextInset() &&
115 it.nextInset()->lyxCode() == code) {
116 inset = static_cast<T*>(it.nextInset());
124 BufferView::BufferView()
125 : width_(0), height_(0), buffer_(0), wh_(0),
127 multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
128 intl_(new Intl), last_inset_(0)
130 xsel_cache_.set = false;
131 intl_->initKeyMapper(lyxrc.use_kbmap);
135 BufferView::~BufferView()
140 Buffer * BufferView::buffer() const
146 void BufferView::setBuffer(Buffer * b)
148 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
149 << "[ b = " << b << "]" << endl;
152 // Save the actual cursor position and anchor inside the
153 // buffer so that it can be restored in case we rechange
154 // to this buffer later on.
155 buffer_->saveCursor(cursor_.selectionBegin(),
156 cursor_.selectionEnd());
157 // current buffer is going to be switched-off, save cursor pos
158 LyX::ref().session().lastFilePos().save(FileName(buffer_->fileName()),
159 boost::tie(cursor_.pit(), cursor_.pos()) );
162 // If we're quitting lyx, don't bother updating stuff
168 // If we are closing current buffer, switch to the first in
171 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
172 << " No Buffer!" << endl;
173 // We are closing the buffer, use the first buffer as current
174 buffer_ = theBufferList().first();
176 // Set current buffer
181 cursor_ = LCursor(*this);
186 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
187 << "Buffer addr: " << buffer_ << endl;
188 cursor_.push(buffer_->inset());
189 cursor_.resetAnchor();
190 buffer_->text().init(this);
191 buffer_->text().setCurrentFont(cursor_);
192 if (buffer_->getCursor().size() > 0 &&
193 buffer_->getAnchor().size() > 0)
195 cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
196 cursor_.resetAnchor();
197 cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
198 cursor_.setSelection();
203 updateMetrics(false);
205 if (buffer_ && graphics::Previews::status() != LyXRC::PREVIEW_OFF)
206 graphics::Previews::get().generateBufferPreviews(*buffer_);
210 bool BufferView::loadLyXFile(FileName const & filename, bool tolastfiles)
212 // File already open?
213 if (theBufferList().exists(filename.absFilename())) {
214 docstring const file = makeDisplayPath(filename.absFilename(), 20);
215 docstring text = bformat(_("The document %1$s is already "
216 "loaded.\n\nDo you want to revert "
217 "to the saved version?"), file);
218 int const ret = Alert::prompt(_("Revert to saved document?"),
219 text, 0, 1, _("&Revert"), _("&Switch to document"));
222 setBuffer(theBufferList().getBuffer(filename.absFilename()));
225 // FIXME: should be LFUN_REVERT
226 if (!theBufferList().close(theBufferList().getBuffer(filename.absFilename()), false))
228 // Fall through to new load. (Asger)
234 if (isFileReadable(filename)) {
235 b = theBufferList().newBuffer(filename.absFilename());
236 if (!lyx::loadLyXFile(b, filename)) {
237 theBufferList().release(b);
241 docstring text = bformat(_("The document %1$s does not yet "
242 "exist.\n\nDo you want to create "
243 "a new document?"), from_utf8(filename.absFilename()));
244 int const ret = Alert::prompt(_("Create new document?"),
245 text, 0, 1, _("&Create"), _("Cancel"));
248 b = newFile(filename.absFilename(), string(), true);
256 // Send the "errors" signal in case of parsing errors
259 // scroll to the position when the file was last closed
260 if (lyxrc.use_lastfilepos) {
263 boost::tie(pit, pos) = LyX::ref().session().lastFilePos().load(filename);
264 // I am not sure how to separate the following part to a function
265 // so I will leave this to Lars.
267 // check pit since the document may be externally changed.
268 if ( static_cast<size_t>(pit) < b->paragraphs().size() ) {
269 ParIterator it = b->par_iterator_begin();
270 ParIterator const end = b->par_iterator_end();
271 for (; it != end; ++it)
272 if (it.pit() == pit) {
273 // restored pos may be bigger than it->size
274 setCursor(makeDocIterator(it, min(pos, it->size())));
275 // No need to update the metrics if fitCursor returns false.
277 updateMetrics(false);
284 LyX::ref().session().lastFiles().add(FileName(b->fileName()));
290 void BufferView::reload()
292 if (theBufferList().close(buffer_, false))
293 loadLyXFile(FileName(buffer_->fileName()));
297 void BufferView::resize()
302 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
304 buffer_->text().init(this);
305 updateMetrics(false);
310 bool BufferView::fitCursor()
312 if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
313 frontend::FontMetrics const & fm =
314 theFontMetrics(cursor_.getFont());
315 int const asc = fm.maxAscent();
316 int const des = fm.maxDescent();
317 Point const p = bv_funcs::getPos(*this, cursor_, cursor_.boundary());
318 if (p.y_ - asc >= 0 && p.y_ + des < height_)
326 bool BufferView::multiParSel()
328 if (!cursor_.selection())
330 bool ret = multiparsel_cache_;
331 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
332 // Either this, or previous selection spans paragraphs
333 return ret || multiparsel_cache_;
337 bool BufferView::update(Update::flags flags)
339 // This is close to a hot-path.
340 if (lyxerr.debugging(Debug::DEBUG)) {
342 << BOOST_CURRENT_FUNCTION
343 << "[fitcursor = " << (flags & Update::FitCursor)
344 << ", forceupdate = " << (flags & Update::Force)
345 << ", singlepar = " << (flags & Update::SinglePar)
346 << "] buffer: " << buffer_ << endl;
349 // Check needed to survive LyX startup
353 if (lyxerr.debugging(Debug::WORKAREA)) {
354 lyxerr[Debug::WORKAREA] << "BufferView::update" << std::endl;
357 // Update macro store
358 buffer_->buildMacros();
360 // Now do the first drawing step if needed. This consists on updating
361 // the CoordCache in updateMetrics().
362 // The second drawing step is done in WorkArea::redraw() if needed.
364 // Case when no explicit update is requested.
366 // no need to redraw anything.
370 if (flags == Update::FitCursor) {
371 bool const fit_cursor = fitCursor();
373 updateMetrics(false);
374 // tell the frontend to update the screen if needed.
378 bool full_metrics = flags & Update::Force;
379 if (flags & Update::MultiParSel)
380 full_metrics |= multiParSel();
382 bool const single_par = !full_metrics;
383 updateMetrics(single_par);
385 if (flags & Update::FitCursor && fitCursor())
386 updateMetrics(false);
388 // tell the frontend to update the screen.
393 void BufferView::updateScrollbar()
396 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
397 << " no text in updateScrollbar" << endl;
398 scrollbarParameters_.reset();
402 LyXText & t = buffer_->text();
403 int const parsize = int(t.paragraphs().size() - 1);
404 if (anchor_ref_ > parsize) {
405 anchor_ref_ = parsize;
409 if (lyxerr.debugging(Debug::GUI)) {
411 << BOOST_CURRENT_FUNCTION
412 << " Updating scrollbar: height: " << t.paragraphs().size()
413 << " curr par: " << cursor_.bottom().pit()
414 << " default height " << defaultRowHeight() << endl;
417 // It would be better to fix the scrollbar to understand
418 // values in [0..1] and divide everything by wh
420 // estimated average paragraph height:
423 int h = t.getPar(anchor_ref_).height();
425 // Normalize anchor/offset (MV):
426 while (offset_ref_ > h && anchor_ref_ < parsize) {
429 h = t.getPar(anchor_ref_).height();
431 // Look at paragraph heights on-screen
434 for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
437 int const h2 = t.getPar(pit).height();
443 int const hav = sumh / nh;
444 // More realistic average paragraph height
449 scrollbarParameters_.height = (parsize + 1) * wh_;
450 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
451 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
455 ScrollbarParameters const & BufferView::scrollbarParameters() const
457 return scrollbarParameters_;
461 void BufferView::scrollDocView(int value)
463 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
464 << "[ value = " << value << "]" << endl;
469 LyXText & t = buffer_->text();
471 float const bar = value / float(wh_ * t.paragraphs().size());
473 anchor_ref_ = int(bar * t.paragraphs().size());
474 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
475 anchor_ref_ = int(t.paragraphs().size()) - 1;
476 t.redoParagraph(*this, anchor_ref_);
477 int const h = t.getPar(anchor_ref_).height();
478 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
479 updateMetrics(false);
483 void BufferView::setCursorFromScrollbar()
485 LyXText & t = buffer_->text();
487 int const height = 2 * defaultRowHeight();
488 int const first = height;
489 int const last = height_ - height;
490 LCursor & cur = cursor_;
492 bv_funcs::CurStatus st = bv_funcs::status(this, cur);
495 case bv_funcs::CUR_ABOVE:
496 t.setCursorFromCoordinates(cur, 0, first);
497 cur.clearSelection();
499 case bv_funcs::CUR_BELOW:
500 t.setCursorFromCoordinates(cur, 0, last);
501 cur.clearSelection();
503 case bv_funcs::CUR_INSIDE:
504 int const y = bv_funcs::getPos(*this, cur, cur.boundary()).y_;
505 int const newy = min(last, max(y, first));
507 cur.reset(buffer_->inset());
508 t.setCursorFromCoordinates(cur, 0, newy);
514 Change const BufferView::getCurrentChange() const
516 if (!cursor_.selection())
517 return Change(Change::UNCHANGED);
519 DocIterator dit = cursor_.selectionBegin();
520 return dit.paragraph().lookupChange(dit.pos());
524 void BufferView::saveBookmark(bool persistent)
526 LyX::ref().session().bookmarks().save(
527 FileName(buffer_->fileName()),
528 cursor_.paragraph().id(),
533 // emit message signal.
534 message(_("Save bookmark"));
538 void BufferView::moveToPosition(int par_id, pos_type par_pos)
540 cursor_.clearSelection();
542 ParIterator par = buffer_->getParFromID(par_id);
543 if (par == buffer_->par_iterator_end())
546 setCursor(makeDocIterator(par, min(par->size(), par_pos)));
550 void BufferView::switchKeyMap()
552 if (!lyxrc.rtl_support)
555 if (getLyXText()->real_current_font.isRightToLeft()) {
556 if (intl_->keymap == Intl::PRIMARY)
559 if (intl_->keymap == Intl::SECONDARY)
565 int BufferView::workWidth() const
571 void BufferView::center()
573 CursorSlice & bot = cursor_.bottom();
574 pit_type const pit = bot.pit();
575 bot.text()->redoParagraph(*this, pit);
576 Paragraph const & par = bot.text()->paragraphs()[pit];
578 offset_ref_ = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary()).y_
579 + par.ascent() - height_ / 2;
583 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
587 switch (cmd.action) {
590 flag.enabled(!buffer_->undostack().empty());
593 flag.enabled(!buffer_->redostack().empty());
595 case LFUN_FILE_INSERT:
596 case LFUN_FILE_INSERT_ASCII_PARA:
597 case LFUN_FILE_INSERT_ASCII:
598 case LFUN_BOOKMARK_SAVE:
599 // FIXME: Actually, these LFUNS should be moved to LyXText
600 flag.enabled(cursor_.inTexted());
602 case LFUN_FONT_STATE:
603 case LFUN_LABEL_INSERT:
604 case LFUN_PARAGRAPH_GOTO:
605 // FIXME handle non-trivially
606 case LFUN_OUTLINE_UP:
607 case LFUN_OUTLINE_DOWN:
608 case LFUN_OUTLINE_IN:
609 case LFUN_OUTLINE_OUT:
611 case LFUN_REFERENCE_NEXT:
613 case LFUN_WORD_REPLACE:
616 case LFUN_MARK_TOGGLE:
617 case LFUN_SCREEN_RECENTER:
618 case LFUN_BIBTEX_DATABASE_ADD:
619 case LFUN_BIBTEX_DATABASE_DEL:
620 case LFUN_WORDS_COUNT:
621 case LFUN_NEXT_INSET_TOGGLE:
625 case LFUN_LABEL_GOTO: {
626 flag.enabled(!cmd.argument().empty()
627 || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
631 case LFUN_CHANGES_TRACK:
633 flag.setOnOff(buffer_->params().trackChanges);
636 case LFUN_CHANGES_OUTPUT: {
637 OutputParams runparams;
638 LaTeXFeatures features(*buffer_, buffer_->params(), runparams);
639 flag.enabled(buffer_ && features.isAvailable("dvipost"));
640 flag.setOnOff(buffer_->params().outputChanges);
644 case LFUN_CHANGES_MERGE:
645 case LFUN_CHANGE_NEXT:
646 case LFUN_ALL_CHANGES_ACCEPT:
647 case LFUN_ALL_CHANGES_REJECT:
648 // TODO: context-sensitive enabling of LFUNs
649 // In principle, these command should only be enabled if there
650 // is a change in the document. However, without proper
651 // optimizations, this will inevitably result in poor performance.
652 flag.enabled(buffer_);
655 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
656 flag.setOnOff(buffer_->params().compressed);
668 bool BufferView::dispatch(FuncRequest const & cmd)
670 //lyxerr << BOOST_CURRENT_FUNCTION
671 // << [ cmd = " << cmd << "]" << endl;
673 // Make sure that the cached BufferView is correct.
674 lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
675 << " action[" << cmd.action << ']'
676 << " arg[" << to_utf8(cmd.argument()) << ']'
677 << " x[" << cmd.x << ']'
678 << " y[" << cmd.y << ']'
679 << " button[" << cmd.button() << ']'
682 LCursor & cur = cursor_;
684 switch (cmd.action) {
688 cur.message(_("Undo"));
689 cur.clearSelection();
690 if (!textUndo(*this))
691 cur.message(_("No further undo information"));
699 cur.message(_("Redo"));
700 cur.clearSelection();
701 if (!textRedo(*this))
702 cur.message(_("No further redo information"));
708 case LFUN_FILE_INSERT:
710 menuInsertLyXFile(to_utf8(cmd.argument()));
713 case LFUN_FILE_INSERT_ASCII_PARA:
715 insertAsciiFile(this, to_utf8(cmd.argument()), true);
718 case LFUN_FILE_INSERT_ASCII:
720 insertAsciiFile(this, to_utf8(cmd.argument()), false);
723 case LFUN_FONT_STATE:
724 cur.message(from_utf8(cur.currentState()));
727 case LFUN_BOOKMARK_SAVE:
728 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
731 case LFUN_LABEL_GOTO: {
732 docstring label = cmd.argument();
735 getInsetByCode<InsetRef>(cursor_,
736 InsetBase::REF_CODE);
738 label = inset->getParam("reference");
739 // persistent=false: use temp_bookmark
749 case LFUN_PARAGRAPH_GOTO: {
750 int const id = convert<int>(to_utf8(cmd.argument()));
752 for (Buffer * b = buffer_; i == 0 || b != buffer_; b = theBufferList().next(b)) {
753 ParIterator par = b->getParFromID(id);
754 if (par == b->par_iterator_end()) {
756 << "No matching paragraph found! ["
757 << id << "]." << endl;
760 << "Paragraph " << par->id()
761 << " found in buffer `"
762 << b->fileName() << "'." << endl;
766 setCursor(makeDocIterator(par, 0));
770 // Switch to other buffer view and resend cmd
771 theLyXFunc().dispatch(FuncRequest(
772 LFUN_BUFFER_SWITCH, b->fileName()));
773 theLyXFunc().dispatch(cmd);
782 case LFUN_OUTLINE_UP:
783 toc::outline(toc::Up, cursor_);
784 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
785 updateLabels(*buffer_);
787 case LFUN_OUTLINE_DOWN:
788 toc::outline(toc::Down, cursor_);
789 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
790 updateLabels(*buffer_);
792 case LFUN_OUTLINE_IN:
793 toc::outline(toc::In, cursor_);
794 updateLabels(*buffer_);
796 case LFUN_OUTLINE_OUT:
797 toc::outline(toc::Out, cursor_);
798 updateLabels(*buffer_);
802 bv_funcs::gotoInset(this, InsetBase::NOTE_CODE, false);
805 case LFUN_REFERENCE_NEXT: {
806 vector<InsetBase_code> tmp;
807 tmp.push_back(InsetBase::LABEL_CODE);
808 tmp.push_back(InsetBase::REF_CODE);
809 bv_funcs::gotoInset(this, tmp, true);
813 case LFUN_CHANGES_TRACK:
814 buffer_->params().trackChanges = !buffer_->params().trackChanges;
817 case LFUN_CHANGES_OUTPUT: {
818 buffer_->params().outputChanges = !buffer_->params().outputChanges;
822 case LFUN_CHANGE_NEXT:
823 findNextChange(this);
826 case LFUN_CHANGES_MERGE:
827 if (findNextChange(this))
828 showDialog("changes");
831 case LFUN_ALL_CHANGES_ACCEPT: {
832 cursor_.reset(buffer_->inset());
834 #warning FIXME changes
836 while (findNextChange(this))
837 getLyXText()->acceptChange(cursor_);
842 case LFUN_ALL_CHANGES_REJECT: {
843 cursor_.reset(buffer_->inset());
845 #warning FIXME changes
847 while (findNextChange(this))
848 getLyXText()->rejectChange(cursor_);
856 case LFUN_WORD_REPLACE:
861 cur.clearSelection();
863 cur.message(from_utf8(N_("Mark off")));
867 cur.clearSelection();
870 cur.message(from_utf8(N_("Mark on")));
873 case LFUN_MARK_TOGGLE:
874 cur.clearSelection();
877 cur.message(from_utf8(N_("Mark removed")));
880 cur.message(from_utf8(N_("Mark set")));
885 case LFUN_SCREEN_RECENTER:
889 case LFUN_BIBTEX_DATABASE_ADD: {
890 LCursor tmpcur = cursor_;
891 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
892 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
893 InsetBase::BIBTEX_CODE);
895 if (inset->addDatabase(to_utf8(cmd.argument())))
896 buffer_->updateBibfilesCache();
901 case LFUN_BIBTEX_DATABASE_DEL: {
902 LCursor tmpcur = cursor_;
903 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
904 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
905 InsetBase::BIBTEX_CODE);
907 if (inset->delDatabase(to_utf8(cmd.argument())))
908 buffer_->updateBibfilesCache();
913 case LFUN_WORDS_COUNT: {
914 DocIterator from, to;
915 if (cur.selection()) {
916 from = cur.selectionBegin();
917 to = cur.selectionEnd();
919 from = doc_iterator_begin(buffer_->inset());
920 to = doc_iterator_end(buffer_->inset());
922 int const count = countWords(from, to);
926 message = bformat(_("%1$d words in selection."),
929 message = bformat(_("%1$d words in document."),
934 message = _("One word in selection.");
936 message = _("One word in document.");
939 Alert::information(_("Count words"), message);
943 case LFUN_BUFFER_TOGGLE_COMPRESSION:
944 // turn compression on/off
945 buffer_->params().compressed = !buffer_->params().compressed;
948 case LFUN_NEXT_INSET_TOGGLE: {
949 // this is the real function we want to invoke
950 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
951 // if there is an inset at cursor, see whether it
953 InsetBase * inset = cur.nextInset();
954 if (inset && inset->isActive()) {
955 LCursor tmpcur = cur;
956 tmpcur.pushLeft(*inset);
957 inset->dispatch(tmpcur, tmpcmd);
958 if (tmpcur.result().dispatched()) {
962 // if it did not work, try the underlying inset.
963 if (!cur.result().dispatched())
964 cur.dispatch(tmpcmd);
966 if (cur.result().dispatched())
967 cur.clearSelection();
980 docstring const BufferView::requestSelection()
985 LCursor & cur = cursor_;
987 if (!cur.selection()) {
988 xsel_cache_.set = false;
992 if (!xsel_cache_.set ||
993 cur.top() != xsel_cache_.cursor ||
994 cur.anchor_.top() != xsel_cache_.anchor)
996 xsel_cache_.cursor = cur.top();
997 xsel_cache_.anchor = cur.anchor_.top();
998 xsel_cache_.set = cur.selection();
999 return cur.selectionAsString(false);
1005 void BufferView::clearSelection()
1008 cursor_.clearSelection();
1009 xsel_cache_.set = false;
1014 void BufferView::workAreaResize(int width, int height)
1016 // A resize is triggered whenever a window gets focus,
1017 // because of the shared rows() of a buffer in multiple
1020 // Update from work area
1029 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1031 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1033 // This is only called for mouse related events including
1034 // LFUN_FILE_OPEN generated by drag-and-drop.
1035 FuncRequest cmd = cmd0;
1037 // E.g. Qt mouse press when no buffer
1042 cur.push(buffer_->inset());
1043 cur.selection() = cursor_.selection();
1045 // Either the inset under the cursor or the
1046 // surrounding LyXText will handle this event.
1048 // Build temporary cursor.
1049 cmd.y = min(max(cmd.y, -1), height_);
1050 InsetBase * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1052 //lyxerr << BOOST_CURRENT_FUNCTION
1053 // << " * hit inset at tip: " << inset << endl;
1054 //lyxerr << BOOST_CURRENT_FUNCTION
1055 // << " * created temp cursor:" << cur << endl;
1057 // NOTE: editXY returns the top level inset of nested insets. If you happen
1058 // to move from a text (inset=0) to a text inside an inset (e.g. an opened
1059 // footnote inset, again inset=0), that inset will not be redrawn.
1060 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1061 bool need_redraw = false;
1063 if (inset != last_inset_) {
1065 need_redraw |= last_inset_->setMouseHover(false);
1067 need_redraw |= inset->setMouseHover(true);
1068 last_inset_ = inset;
1071 // if last metrics update was in singlepar mode, WorkArea::redraw() will
1072 // not expose the button for redraw. We adjust here the metrics dimension
1073 // to enable a full redraw.
1074 // FIXME: It is possible to redraw only the area around the button!
1075 if (need_redraw && metrics_info_.singlepar) {
1076 // FIXME: It should be possible to redraw only the area around
1077 // the button by doing this:
1079 //metrics_info_.singlepar = false;
1080 //metrics_info_.y1 = ymin of button;
1081 //metrics_info_.y2 = ymax of button;
1083 // Unfortunately, rowpainter.C:paintText() does not distinguish
1084 // between background updates and text updates. So we use the hammer
1085 // solution for now. We could also avoid the updateMetrics() below
1086 // by using the first and last pit of the CoordCache. Have a look
1087 // at LyXText::getPitNearY() to see what I mean.
1089 //metrics_info_.pit1 = first pit of CoordCache;
1090 //metrics_info_.pit2 = last pit of CoordCache;
1091 //metrics_info_.singlepar = false;
1092 //metrics_info_.y1 = 0;
1093 //metrics_info_.y2 = height_;
1095 updateMetrics(false);
1098 // This event (moving without mouse click) is not passed further.
1099 // This should be changed if it is further utilized.
1103 // Put anchor at the same position.
1106 // Try to dispatch to an non-editable inset near this position
1107 // via the temp cursor. If the inset wishes to change the real
1108 // cursor it has to do so explicitly by using
1109 // cur.bv().cursor() = cur; (or similar)
1111 inset->dispatch(cur, cmd);
1114 // Now dispatch to the temporary cursor. If the real cursor should
1115 // be modified, the inset's dispatch has to do so explicitly.
1116 if (!cur.result().dispatched())
1119 // Redraw if requested and necessary.
1120 if (cur.result().dispatched() && cur.result().update())
1121 return update(cur.result().update());
1127 void BufferView::scroll(int /*lines*/)
1132 // LyXText const * t = &buffer_->text();
1133 // int const line_height = defaultRowHeight();
1135 // // The new absolute coordinate
1136 // int new_top_y = top_y() + lines * line_height;
1138 // // Restrict to a valid value
1139 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1140 // new_top_y = std::max(0, new_top_y);
1142 // scrollDocView(new_top_y);
1144 // // Update the scrollbar.
1145 // workArea_->setScrollbarParams(t->height(), top_y(), defaultRowHeight());}
1149 void BufferView::setCursorFromRow(int row)
1154 buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1157 buffer_->text().setCursor(cursor_, 0, 0);
1159 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1163 void BufferView::gotoLabel(docstring const & label)
1165 for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1166 vector<docstring> labels;
1167 it->getLabelList(*buffer_, labels);
1168 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1177 LyXText * BufferView::getLyXText()
1179 LyXText * text = cursor_.innerText();
1185 LyXText const * BufferView::getLyXText() const
1187 LyXText const * text = cursor_.innerText();
1193 int BufferView::workHeight() const
1199 void BufferView::setCursor(DocIterator const & dit)
1201 size_t const n = dit.depth();
1202 for (size_t i = 0; i < n; ++i)
1203 dit[i].inset().edit(cursor_, true);
1205 cursor_.setCursor(dit);
1206 cursor_.selection() = false;
1210 bool BufferView::mouseSetCursor(LCursor & cur)
1212 BOOST_ASSERT(&cur.bv() == this);
1214 // Has the cursor just left the inset?
1215 bool badcursor = false;
1216 if (&cursor_.inset() != &cur.inset())
1217 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1219 // do the dEPM magic if needed
1220 // FIXME: move this to InsetText::notifyCursorLeaves?
1221 bool update = false;
1222 if (!badcursor && cursor_.inTexted())
1223 update = cursor_.text()->deleteEmptyParagraphMechanism(cur, cursor_);
1226 cursor_.clearSelection();
1227 cursor_.setTargetX();
1233 void BufferView::putSelectionAt(DocIterator const & cur,
1234 int length, bool backwards)
1236 cursor_.clearSelection();
1242 cursor_.pos() += length;
1243 cursor_.setSelection(cursor_, -length);
1245 cursor_.setSelection(cursor_, length);
1250 LCursor & BufferView::cursor()
1256 LCursor const & BufferView::cursor() const
1262 pit_type BufferView::anchor_ref() const
1268 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1270 return metrics_info_;
1274 void BufferView::updateMetrics(bool singlepar)
1276 // Clear out the position cache in case of full screen redraw.
1278 coord_cache_.clear();
1280 LyXText & buftext = buffer_->text();
1281 pit_type size = int(buftext.paragraphs().size());
1283 if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1284 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1288 pit_type const pit = anchor_ref_;
1291 size_t const npit = buftext.paragraphs().size();
1293 // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
1294 // the (main text, not inset!) paragraph containing the cursor.
1295 // (if this paragraph contains insets etc., rebreaking will
1296 // recursively descend)
1297 if (!singlepar || pit == cursor_.bottom().pit())
1298 buftext.redoParagraph(*this, pit);
1299 int y0 = buftext.getPar(pit).ascent() - offset_ref_;
1301 // Redo paragraphs above anchor if necessary; again, in Single Par
1302 // mode, only if we encounter the (main text) one having the cursor.
1304 while (y1 > 0 && pit1 > 0) {
1305 y1 -= buftext.getPar(pit1).ascent();
1307 if (!singlepar || pit1 == cursor_.bottom().pit())
1308 buftext.redoParagraph(*this, pit1);
1309 y1 -= buftext.getPar(pit1).descent();
1313 // Take care of ascent of first line
1314 y1 -= buftext.getPar(pit1).ascent();
1316 // Normalize anchor for next time
1320 // Grey at the beginning is ugly
1321 if (pit1 == 0 && y1 > 0) {
1327 // Redo paragraphs below the anchor if necessary. Single par mode:
1328 // only the one containing the cursor if encountered.
1330 while (y2 < height_ && pit2 < int(npit) - 1) {
1331 y2 += buftext.getPar(pit2).descent();
1333 if (!singlepar || pit2 == cursor_.bottom().pit())
1334 buftext.redoParagraph(*this, pit2);
1335 y2 += buftext.getPar(pit2).ascent();
1338 // Take care of descent of last line
1339 y2 += buftext.getPar(pit2).descent();
1341 // The coordinates of all these paragraphs are correct, cache them
1343 CoordCache::InnerParPosCache & parPos = coord_cache_.parPos()[&buftext];
1344 for (pit_type pit = pit1; pit <= pit2; ++pit) {
1345 Paragraph const & par = buftext.getPar(pit);
1347 parPos[pit] = Point(0, y);
1348 if (singlepar && pit == cursor_.bottom().pit()) {
1349 // In Single Paragraph mode, collect here the
1350 // y1 and y2 of the (one) paragraph the cursor is in
1351 y1 = y - par.ascent();
1352 y2 = y + par.descent();
1358 // collect cursor paragraph iter bounds
1359 pit1 = cursor_.bottom().pit();
1360 pit2 = cursor_.bottom().pit();
1363 lyxerr[Debug::DEBUG]
1364 << BOOST_CURRENT_FUNCTION
1367 << " pit1: " << pit1
1368 << " pit2: " << pit2
1369 << " npit: " << npit
1370 << " singlepar: " << singlepar
1374 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2, singlepar, size);
1376 if (lyxerr.debugging(Debug::WORKAREA)) {
1377 lyxerr[Debug::WORKAREA] << "BufferView::updateMetrics" << endl;
1378 coord_cache_.dump();
1383 void BufferView::menuInsertLyXFile(string const & filenm)
1385 BOOST_ASSERT(cursor_.inTexted());
1386 string filename = filenm;
1388 if (filename.empty()) {
1389 // Launch a file browser
1391 string initpath = lyxrc.document_path;
1394 string const trypath = buffer_->filePath();
1395 // If directory is writeable, use this as default.
1396 if (isDirWriteable(trypath))
1401 FileDialog fileDlg(_("Select LyX document to insert"),
1403 make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1404 make_pair(_("Examples|#E#e"), from_utf8(addPath(package().system_support(), "examples"))));
1406 FileDialog::Result result =
1407 fileDlg.open(from_utf8(initpath),
1408 FileFilterList(_("LyX Documents (*.lyx)")),
1411 if (result.first == FileDialog::Later)
1415 filename = to_utf8(result.second);
1417 // check selected filename
1418 if (filename.empty()) {
1419 // emit message signal.
1420 message(_("Canceled."));
1425 // Get absolute path of file and add ".lyx"
1426 // to the filename if necessary
1427 filename = fileSearch(string(), filename, "lyx").absFilename();
1429 docstring const disp_fn = makeDisplayPath(filename);
1430 // emit message signal.
1431 message(bformat(_("Inserting document %1$s..."), disp_fn));
1434 Buffer buf("", false);
1435 if (lyx::loadLyXFile(&buf, FileName(filename))) {
1436 ErrorList & el = buffer_->errorList("Parse");
1437 // Copy the inserted document error list into the current buffer one.
1438 el = buf.errorList("Parse");
1439 recordUndo(cursor_);
1440 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1441 buf.params().textclass, el);
1442 res = _("Document %1$s inserted.");
1444 res = _("Could not insert document %1$s");
1446 // emit message signal.
1447 message(bformat(res, disp_fn));
1448 buffer_->errors("Parse");