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::package;
95 using std::istringstream;
99 using std::mem_fun_ref;
103 namespace Alert = frontend::Alert;
107 /// Return an inset of this class if it exists at the current cursor position
109 T * getInsetByCode(LCursor & cur, InsetBase::Code code)
112 DocIterator it = cur;
113 if (it.nextInset() &&
114 it.nextInset()->lyxCode() == code) {
115 inset = static_cast<T*>(it.nextInset());
123 BufferView::BufferView()
124 : width_(0), height_(0), buffer_(0), wh_(0),
126 multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
127 intl_(new Intl), last_inset_(0)
129 xsel_cache_.set = false;
130 intl_->initKeyMapper(lyxrc.use_kbmap);
134 BufferView::~BufferView()
139 Buffer * BufferView::buffer() const
145 void BufferView::setBuffer(Buffer * b)
147 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
148 << "[ b = " << b << "]" << endl;
151 // Save the actual cursor position and anchor inside the
152 // buffer so that it can be restored in case we rechange
153 // to this buffer later on.
154 buffer_->saveCursor(cursor_.selectionBegin(),
155 cursor_.selectionEnd());
156 // current buffer is going to be switched-off, save cursor pos
157 LyX::ref().session().lastFilePos().save(FileName(buffer_->fileName()),
158 boost::tie(cursor_.pit(), cursor_.pos()) );
161 // If we're quitting lyx, don't bother updating stuff
167 // If we are closing current buffer, switch to the first in
170 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
171 << " No Buffer!" << endl;
172 // We are closing the buffer, use the first buffer as current
173 buffer_ = theBufferList().first();
175 // Set current buffer
180 cursor_ = LCursor(*this);
185 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
186 << "Buffer addr: " << buffer_ << endl;
187 cursor_.push(buffer_->inset());
188 cursor_.resetAnchor();
189 buffer_->text().init(this);
190 buffer_->text().setCurrentFont(cursor_);
191 if (buffer_->getCursor().size() > 0 &&
192 buffer_->getAnchor().size() > 0)
194 cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
195 cursor_.resetAnchor();
196 cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
197 cursor_.setSelection();
202 updateMetrics(false);
204 if (buffer_ && graphics::Previews::status() != LyXRC::PREVIEW_OFF)
205 graphics::Previews::get().generateBufferPreviews(*buffer_);
209 bool BufferView::loadLyXFile(FileName const & filename, bool tolastfiles)
211 // File already open?
212 if (theBufferList().exists(filename.absFilename())) {
213 docstring const file = makeDisplayPath(filename.absFilename(), 20);
214 docstring text = bformat(_("The document %1$s is already "
215 "loaded.\n\nDo you want to revert "
216 "to the saved version?"), file);
217 int const ret = Alert::prompt(_("Revert to saved document?"),
218 text, 0, 1, _("&Revert"), _("&Switch to document"));
221 setBuffer(theBufferList().getBuffer(filename.absFilename()));
224 // FIXME: should be LFUN_REVERT
225 if (!theBufferList().close(theBufferList().getBuffer(filename.absFilename()), false))
227 // Fall through to new load. (Asger)
233 if (isFileReadable(filename)) {
234 b = theBufferList().newBuffer(filename.absFilename());
235 if (!lyx::loadLyXFile(b, filename)) {
236 theBufferList().release(b);
240 docstring text = bformat(_("The document %1$s does not yet "
241 "exist.\n\nDo you want to create "
242 "a new document?"), from_utf8(filename.absFilename()));
243 int const ret = Alert::prompt(_("Create new document?"),
244 text, 0, 1, _("&Create"), _("Cancel"));
247 b = newFile(filename.absFilename(), string(), true);
255 // Send the "errors" signal in case of parsing errors
258 // scroll to the position when the file was last closed
259 if (lyxrc.use_lastfilepos) {
262 boost::tie(pit, pos) = LyX::ref().session().lastFilePos().load(filename);
263 // I am not sure how to separate the following part to a function
264 // so I will leave this to Lars.
266 // check pit since the document may be externally changed.
267 if ( static_cast<size_t>(pit) < b->paragraphs().size() ) {
268 ParIterator it = b->par_iterator_begin();
269 ParIterator const end = b->par_iterator_end();
270 for (; it != end; ++it)
271 if (it.pit() == pit) {
272 // restored pos may be bigger than it->size
273 setCursor(makeDocIterator(it, min(pos, it->size())));
274 // No need to update the metrics if fitCursor returns false.
276 updateMetrics(false);
283 LyX::ref().session().lastFiles().add(FileName(b->fileName()));
289 void BufferView::reload()
291 if (theBufferList().close(buffer_, false))
292 loadLyXFile(FileName(buffer_->fileName()));
296 void BufferView::resize()
301 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
303 buffer_->text().init(this);
304 updateMetrics(false);
309 bool BufferView::fitCursor()
311 if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
312 frontend::FontMetrics const & fm =
313 theFontMetrics(cursor_.getFont());
314 int const asc = fm.maxAscent();
315 int const des = fm.maxDescent();
316 Point const p = bv_funcs::getPos(*this, cursor_, cursor_.boundary());
317 if (p.y_ - asc >= 0 && p.y_ + des < height_)
325 bool BufferView::multiParSel()
327 if (!cursor_.selection())
329 bool ret = multiparsel_cache_;
330 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
331 // Either this, or previous selection spans paragraphs
332 return ret || multiparsel_cache_;
336 bool BufferView::update(Update::flags flags)
338 // This is close to a hot-path.
339 if (lyxerr.debugging(Debug::DEBUG)) {
341 << BOOST_CURRENT_FUNCTION
342 << "[fitcursor = " << (flags & Update::FitCursor)
343 << ", forceupdate = " << (flags & Update::Force)
344 << ", singlepar = " << (flags & Update::SinglePar)
345 << "] buffer: " << buffer_ << endl;
348 // Check needed to survive LyX startup
352 if (lyxerr.debugging(Debug::WORKAREA)) {
353 lyxerr[Debug::WORKAREA] << "BufferView::update" << std::endl;
356 // Update macro store
357 buffer_->buildMacros();
359 // Now do the first drawing step if needed. This consists on updating
360 // the CoordCache in updateMetrics().
361 // The second drawing step is done in WorkArea::redraw() if needed.
363 // Case when no explicit update is requested.
365 // no need to redraw anything.
369 if (flags == Update::FitCursor) {
370 bool const fit_cursor = fitCursor();
372 updateMetrics(false);
373 // tell the frontend to update the screen if needed.
377 bool full_metrics = flags & Update::Force;
378 if (flags & Update::MultiParSel)
379 full_metrics |= multiParSel();
381 bool const single_par = !full_metrics;
382 updateMetrics(single_par);
384 if (flags & Update::FitCursor && fitCursor())
385 updateMetrics(false);
387 // tell the frontend to update the screen.
392 void BufferView::updateScrollbar()
395 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
396 << " no text in updateScrollbar" << endl;
397 scrollbarParameters_.reset();
401 LyXText & t = buffer_->text();
402 int const parsize = int(t.paragraphs().size() - 1);
403 if (anchor_ref_ > parsize) {
404 anchor_ref_ = parsize;
408 if (lyxerr.debugging(Debug::GUI)) {
410 << BOOST_CURRENT_FUNCTION
411 << " Updating scrollbar: height: " << t.paragraphs().size()
412 << " curr par: " << cursor_.bottom().pit()
413 << " default height " << defaultRowHeight() << endl;
416 // It would be better to fix the scrollbar to understand
417 // values in [0..1] and divide everything by wh
419 // estimated average paragraph height:
422 int h = t.getPar(anchor_ref_).height();
424 // Normalize anchor/offset (MV):
425 while (offset_ref_ > h && anchor_ref_ < parsize) {
428 h = t.getPar(anchor_ref_).height();
430 // Look at paragraph heights on-screen
433 for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
436 int const h2 = t.getPar(pit).height();
442 int const hav = sumh / nh;
443 // More realistic average paragraph height
448 scrollbarParameters_.height = (parsize + 1) * wh_;
449 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
450 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
454 ScrollbarParameters const & BufferView::scrollbarParameters() const
456 return scrollbarParameters_;
460 void BufferView::scrollDocView(int value)
462 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
463 << "[ value = " << value << "]" << endl;
468 LyXText & t = buffer_->text();
470 float const bar = value / float(wh_ * t.paragraphs().size());
472 anchor_ref_ = int(bar * t.paragraphs().size());
473 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
474 anchor_ref_ = int(t.paragraphs().size()) - 1;
475 t.redoParagraph(*this, anchor_ref_);
476 int const h = t.getPar(anchor_ref_).height();
477 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
478 updateMetrics(false);
482 void BufferView::setCursorFromScrollbar()
484 LyXText & t = buffer_->text();
486 int const height = 2 * defaultRowHeight();
487 int const first = height;
488 int const last = height_ - height;
489 LCursor & cur = cursor_;
491 bv_funcs::CurStatus st = bv_funcs::status(this, cur);
494 case bv_funcs::CUR_ABOVE:
495 t.setCursorFromCoordinates(cur, 0, first);
496 cur.clearSelection();
498 case bv_funcs::CUR_BELOW:
499 t.setCursorFromCoordinates(cur, 0, last);
500 cur.clearSelection();
502 case bv_funcs::CUR_INSIDE:
503 int const y = bv_funcs::getPos(*this, cur, cur.boundary()).y_;
504 int const newy = min(last, max(y, first));
506 cur.reset(buffer_->inset());
507 t.setCursorFromCoordinates(cur, 0, newy);
513 Change const BufferView::getCurrentChange() const
515 if (!cursor_.selection())
516 return Change(Change::UNCHANGED);
518 DocIterator dit = cursor_.selectionBegin();
519 return dit.paragraph().lookupChange(dit.pos());
523 void BufferView::saveBookmark(bool persistent)
525 LyX::ref().session().bookmarks().save(
526 FileName(buffer_->fileName()),
527 cursor_.paragraph().id(),
532 // emit message signal.
533 message(_("Save bookmark"));
537 void BufferView::moveToPosition(int par_id, pos_type par_pos)
539 cursor_.clearSelection();
541 ParIterator par = buffer_->getParFromID(par_id);
542 if (par == buffer_->par_iterator_end())
545 setCursor(makeDocIterator(par, min(par->size(), par_pos)));
549 void BufferView::switchKeyMap()
551 if (!lyxrc.rtl_support)
554 if (getLyXText()->real_current_font.isRightToLeft()) {
555 if (intl_->keymap == Intl::PRIMARY)
558 if (intl_->keymap == Intl::SECONDARY)
564 int BufferView::workWidth() const
570 void BufferView::center()
572 CursorSlice & bot = cursor_.bottom();
573 pit_type const pit = bot.pit();
574 bot.text()->redoParagraph(*this, pit);
575 Paragraph const & par = bot.text()->paragraphs()[pit];
577 offset_ref_ = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary()).y_
578 + par.ascent() - height_ / 2;
582 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
586 switch (cmd.action) {
589 flag.enabled(!buffer_->undostack().empty());
592 flag.enabled(!buffer_->redostack().empty());
594 case LFUN_FILE_INSERT:
595 case LFUN_FILE_INSERT_ASCII_PARA:
596 case LFUN_FILE_INSERT_ASCII:
597 case LFUN_BOOKMARK_SAVE:
598 // FIXME: Actually, these LFUNS should be moved to LyXText
599 flag.enabled(cursor_.inTexted());
601 case LFUN_FONT_STATE:
602 case LFUN_LABEL_INSERT:
603 case LFUN_PARAGRAPH_GOTO:
604 // FIXME handle non-trivially
605 case LFUN_OUTLINE_UP:
606 case LFUN_OUTLINE_DOWN:
607 case LFUN_OUTLINE_IN:
608 case LFUN_OUTLINE_OUT:
610 case LFUN_REFERENCE_NEXT:
612 case LFUN_WORD_REPLACE:
615 case LFUN_MARK_TOGGLE:
616 case LFUN_SCREEN_RECENTER:
617 case LFUN_BIBTEX_DATABASE_ADD:
618 case LFUN_BIBTEX_DATABASE_DEL:
619 case LFUN_WORDS_COUNT:
620 case LFUN_NEXT_INSET_TOGGLE:
624 case LFUN_LABEL_GOTO: {
625 flag.enabled(!cmd.argument().empty()
626 || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
630 case LFUN_CHANGES_TRACK:
632 flag.setOnOff(buffer_->params().trackChanges);
635 case LFUN_CHANGES_OUTPUT: {
636 OutputParams runparams;
637 LaTeXFeatures features(*buffer_, buffer_->params(), runparams);
638 flag.enabled(buffer_ && features.isAvailable("dvipost"));
639 flag.setOnOff(buffer_->params().outputChanges);
643 case LFUN_CHANGES_MERGE:
644 case LFUN_CHANGE_NEXT:
645 case LFUN_ALL_CHANGES_ACCEPT:
646 case LFUN_ALL_CHANGES_REJECT:
647 // TODO: context-sensitive enabling of LFUNs
648 // In principle, these command should only be enabled if there
649 // is a change in the document. However, without proper
650 // optimizations, this will inevitably result in poor performance.
651 flag.enabled(buffer_);
654 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
655 flag.setOnOff(buffer_->params().compressed);
667 bool BufferView::dispatch(FuncRequest const & cmd)
669 //lyxerr << BOOST_CURRENT_FUNCTION
670 // << [ cmd = " << cmd << "]" << endl;
672 // Make sure that the cached BufferView is correct.
673 lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
674 << " action[" << cmd.action << ']'
675 << " arg[" << to_utf8(cmd.argument()) << ']'
676 << " x[" << cmd.x << ']'
677 << " y[" << cmd.y << ']'
678 << " button[" << cmd.button() << ']'
681 LCursor & cur = cursor_;
683 switch (cmd.action) {
687 cur.message(_("Undo"));
688 cur.clearSelection();
689 if (!textUndo(*this))
690 cur.message(_("No further undo information"));
698 cur.message(_("Redo"));
699 cur.clearSelection();
700 if (!textRedo(*this))
701 cur.message(_("No further redo information"));
707 case LFUN_FILE_INSERT:
709 menuInsertLyXFile(to_utf8(cmd.argument()));
712 case LFUN_FILE_INSERT_ASCII_PARA:
714 insertAsciiFile(this, to_utf8(cmd.argument()), true);
717 case LFUN_FILE_INSERT_ASCII:
719 insertAsciiFile(this, to_utf8(cmd.argument()), false);
722 case LFUN_FONT_STATE:
723 cur.message(cur.currentState());
726 case LFUN_BOOKMARK_SAVE:
727 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
730 case LFUN_LABEL_GOTO: {
731 docstring label = cmd.argument();
734 getInsetByCode<InsetRef>(cursor_,
735 InsetBase::REF_CODE);
737 label = inset->getParam("reference");
738 // persistent=false: use temp_bookmark
748 case LFUN_PARAGRAPH_GOTO: {
749 int const id = convert<int>(to_utf8(cmd.argument()));
751 for (Buffer * b = buffer_; i == 0 || b != buffer_; b = theBufferList().next(b)) {
752 ParIterator par = b->getParFromID(id);
753 if (par == b->par_iterator_end()) {
755 << "No matching paragraph found! ["
756 << id << "]." << endl;
759 << "Paragraph " << par->id()
760 << " found in buffer `"
761 << b->fileName() << "'." << endl;
765 setCursor(makeDocIterator(par, 0));
769 // Switch to other buffer view and resend cmd
770 theLyXFunc().dispatch(FuncRequest(
771 LFUN_BUFFER_SWITCH, b->fileName()));
772 theLyXFunc().dispatch(cmd);
781 case LFUN_OUTLINE_UP:
782 toc::outline(toc::Up, cursor_);
783 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
784 updateLabels(*buffer_);
786 case LFUN_OUTLINE_DOWN:
787 toc::outline(toc::Down, cursor_);
788 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
789 updateLabels(*buffer_);
791 case LFUN_OUTLINE_IN:
792 toc::outline(toc::In, cursor_);
793 updateLabels(*buffer_);
795 case LFUN_OUTLINE_OUT:
796 toc::outline(toc::Out, cursor_);
797 updateLabels(*buffer_);
801 bv_funcs::gotoInset(this, InsetBase::NOTE_CODE, false);
804 case LFUN_REFERENCE_NEXT: {
805 vector<InsetBase_code> tmp;
806 tmp.push_back(InsetBase::LABEL_CODE);
807 tmp.push_back(InsetBase::REF_CODE);
808 bv_funcs::gotoInset(this, tmp, true);
812 case LFUN_CHANGES_TRACK:
813 buffer_->params().trackChanges = !buffer_->params().trackChanges;
816 case LFUN_CHANGES_OUTPUT: {
817 buffer_->params().outputChanges = !buffer_->params().outputChanges;
821 case LFUN_CHANGE_NEXT:
822 findNextChange(this);
825 case LFUN_CHANGES_MERGE:
826 if (findNextChange(this))
827 showDialog("changes");
830 case LFUN_ALL_CHANGES_ACCEPT: {
831 cursor_.reset(buffer_->inset());
833 #warning FIXME changes
835 while (findNextChange(this))
836 getLyXText()->acceptChange(cursor_);
841 case LFUN_ALL_CHANGES_REJECT: {
842 cursor_.reset(buffer_->inset());
844 #warning FIXME changes
846 while (findNextChange(this))
847 getLyXText()->rejectChange(cursor_);
855 case LFUN_WORD_REPLACE:
860 cur.clearSelection();
862 cur.message(from_utf8(N_("Mark off")));
866 cur.clearSelection();
869 cur.message(from_utf8(N_("Mark on")));
872 case LFUN_MARK_TOGGLE:
873 cur.clearSelection();
876 cur.message(from_utf8(N_("Mark removed")));
879 cur.message(from_utf8(N_("Mark set")));
884 case LFUN_SCREEN_RECENTER:
888 case LFUN_BIBTEX_DATABASE_ADD: {
889 LCursor tmpcur = cursor_;
890 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
891 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
892 InsetBase::BIBTEX_CODE);
894 if (inset->addDatabase(to_utf8(cmd.argument())))
895 buffer_->updateBibfilesCache();
900 case LFUN_BIBTEX_DATABASE_DEL: {
901 LCursor tmpcur = cursor_;
902 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
903 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
904 InsetBase::BIBTEX_CODE);
906 if (inset->delDatabase(to_utf8(cmd.argument())))
907 buffer_->updateBibfilesCache();
912 case LFUN_WORDS_COUNT: {
913 DocIterator from, to;
914 if (cur.selection()) {
915 from = cur.selectionBegin();
916 to = cur.selectionEnd();
918 from = doc_iterator_begin(buffer_->inset());
919 to = doc_iterator_end(buffer_->inset());
921 int const count = countWords(from, to);
925 message = bformat(_("%1$d words in selection."),
928 message = bformat(_("%1$d words in document."),
933 message = _("One word in selection.");
935 message = _("One word in document.");
938 Alert::information(_("Count words"), message);
942 case LFUN_BUFFER_TOGGLE_COMPRESSION:
943 // turn compression on/off
944 buffer_->params().compressed = !buffer_->params().compressed;
947 case LFUN_NEXT_INSET_TOGGLE: {
948 // this is the real function we want to invoke
949 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
950 // if there is an inset at cursor, see whether it
952 InsetBase * inset = cur.nextInset();
953 if (inset && inset->isActive()) {
954 LCursor tmpcur = cur;
955 tmpcur.pushLeft(*inset);
956 inset->dispatch(tmpcur, tmpcmd);
957 if (tmpcur.result().dispatched()) {
961 // if it did not work, try the underlying inset.
962 if (!cur.result().dispatched())
963 cur.dispatch(tmpcmd);
965 if (cur.result().dispatched())
966 cur.clearSelection();
979 docstring const BufferView::requestSelection()
984 LCursor & cur = cursor_;
986 if (!cur.selection()) {
987 xsel_cache_.set = false;
991 if (!xsel_cache_.set ||
992 cur.top() != xsel_cache_.cursor ||
993 cur.anchor_.top() != xsel_cache_.anchor)
995 xsel_cache_.cursor = cur.top();
996 xsel_cache_.anchor = cur.anchor_.top();
997 xsel_cache_.set = cur.selection();
998 return cur.selectionAsString(false);
1004 void BufferView::clearSelection()
1007 cursor_.clearSelection();
1008 xsel_cache_.set = false;
1013 void BufferView::workAreaResize(int width, int height)
1015 // A resize is triggered whenever a window gets focus,
1016 // because of the shared rows() of a buffer in multiple
1019 // Update from work area
1028 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1030 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1032 // This is only called for mouse related events including
1033 // LFUN_FILE_OPEN generated by drag-and-drop.
1034 FuncRequest cmd = cmd0;
1036 // E.g. Qt mouse press when no buffer
1041 cur.push(buffer_->inset());
1042 cur.selection() = cursor_.selection();
1044 // Either the inset under the cursor or the
1045 // surrounding LyXText will handle this event.
1047 // Build temporary cursor.
1048 cmd.y = min(max(cmd.y, -1), height_);
1049 InsetBase * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1051 //lyxerr << BOOST_CURRENT_FUNCTION
1052 // << " * hit inset at tip: " << inset << endl;
1053 //lyxerr << BOOST_CURRENT_FUNCTION
1054 // << " * created temp cursor:" << cur << endl;
1056 // NOTE: editXY returns the top level inset of nested insets. If you happen
1057 // to move from a text (inset=0) to a text inside an inset (e.g. an opened
1058 // footnote inset, again inset=0), that inset will not be redrawn.
1059 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1060 bool need_redraw = false;
1062 if (inset != last_inset_) {
1064 need_redraw |= last_inset_->setMouseHover(false);
1066 need_redraw |= inset->setMouseHover(true);
1067 last_inset_ = inset;
1070 // if last metrics update was in singlepar mode, WorkArea::redraw() will
1071 // not expose the button for redraw. We adjust here the metrics dimension
1072 // to enable a full redraw.
1073 // FIXME: It is possible to redraw only the area around the button!
1074 if (need_redraw && metrics_info_.singlepar) {
1075 // FIXME: It should be possible to redraw only the area around
1076 // the button by doing this:
1078 //metrics_info_.singlepar = false;
1079 //metrics_info_.y1 = ymin of button;
1080 //metrics_info_.y2 = ymax of button;
1082 // Unfortunately, rowpainter.C:paintText() does not distinguish
1083 // between background updates and text updates. So we use the hammer
1084 // solution for now. We could also avoid the updateMetrics() below
1085 // by using the first and last pit of the CoordCache. Have a look
1086 // at LyXText::getPitNearY() to see what I mean.
1088 //metrics_info_.pit1 = first pit of CoordCache;
1089 //metrics_info_.pit2 = last pit of CoordCache;
1090 //metrics_info_.singlepar = false;
1091 //metrics_info_.y1 = 0;
1092 //metrics_info_.y2 = height_;
1094 updateMetrics(false);
1097 // This event (moving without mouse click) is not passed further.
1098 // This should be changed if it is further utilized.
1102 // Put anchor at the same position.
1105 // Try to dispatch to an non-editable inset near this position
1106 // via the temp cursor. If the inset wishes to change the real
1107 // cursor it has to do so explicitly by using
1108 // cur.bv().cursor() = cur; (or similar)
1110 inset->dispatch(cur, cmd);
1113 // Now dispatch to the temporary cursor. If the real cursor should
1114 // be modified, the inset's dispatch has to do so explicitly.
1115 if (!cur.result().dispatched())
1118 // Redraw if requested and necessary.
1119 if (cur.result().dispatched() && cur.result().update())
1120 return update(cur.result().update());
1126 void BufferView::scroll(int /*lines*/)
1131 // LyXText const * t = &buffer_->text();
1132 // int const line_height = defaultRowHeight();
1134 // // The new absolute coordinate
1135 // int new_top_y = top_y() + lines * line_height;
1137 // // Restrict to a valid value
1138 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1139 // new_top_y = std::max(0, new_top_y);
1141 // scrollDocView(new_top_y);
1143 // // Update the scrollbar.
1144 // workArea_->setScrollbarParams(t->height(), top_y(), defaultRowHeight());}
1148 void BufferView::setCursorFromRow(int row)
1153 buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1156 buffer_->text().setCursor(cursor_, 0, 0);
1158 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1162 void BufferView::gotoLabel(docstring const & label)
1164 for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1165 vector<docstring> labels;
1166 it->getLabelList(*buffer_, labels);
1167 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1176 LyXText * BufferView::getLyXText()
1178 LyXText * text = cursor_.innerText();
1184 LyXText const * BufferView::getLyXText() const
1186 LyXText const * text = cursor_.innerText();
1192 int BufferView::workHeight() const
1198 void BufferView::setCursor(DocIterator const & dit)
1200 size_t const n = dit.depth();
1201 for (size_t i = 0; i < n; ++i)
1202 dit[i].inset().edit(cursor_, true);
1204 cursor_.setCursor(dit);
1205 cursor_.selection() = false;
1209 bool BufferView::mouseSetCursor(LCursor & cur)
1211 BOOST_ASSERT(&cur.bv() == this);
1213 // Has the cursor just left the inset?
1214 bool badcursor = false;
1215 if (&cursor_.inset() != &cur.inset())
1216 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1218 // do the dEPM magic if needed
1219 // FIXME: move this to InsetText::notifyCursorLeaves?
1220 bool update = false;
1221 if (!badcursor && cursor_.inTexted())
1222 update = cursor_.text()->deleteEmptyParagraphMechanism(cur, cursor_);
1225 cursor_.clearSelection();
1226 cursor_.setTargetX();
1232 void BufferView::putSelectionAt(DocIterator const & cur,
1233 int length, bool backwards)
1235 cursor_.clearSelection();
1241 cursor_.pos() += length;
1242 cursor_.setSelection(cursor_, -length);
1244 cursor_.setSelection(cursor_, length);
1249 LCursor & BufferView::cursor()
1255 LCursor const & BufferView::cursor() const
1261 pit_type BufferView::anchor_ref() const
1267 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1269 return metrics_info_;
1273 void BufferView::updateMetrics(bool singlepar)
1275 // Clear out the position cache in case of full screen redraw.
1277 coord_cache_.clear();
1279 LyXText & buftext = buffer_->text();
1280 pit_type size = int(buftext.paragraphs().size());
1282 if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1283 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1287 pit_type const pit = anchor_ref_;
1290 size_t const npit = buftext.paragraphs().size();
1292 // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
1293 // the (main text, not inset!) paragraph containing the cursor.
1294 // (if this paragraph contains insets etc., rebreaking will
1295 // recursively descend)
1296 if (!singlepar || pit == cursor_.bottom().pit())
1297 buftext.redoParagraph(*this, pit);
1298 int y0 = buftext.getPar(pit).ascent() - offset_ref_;
1300 // Redo paragraphs above anchor if necessary; again, in Single Par
1301 // mode, only if we encounter the (main text) one having the cursor.
1303 while (y1 > 0 && pit1 > 0) {
1304 y1 -= buftext.getPar(pit1).ascent();
1306 if (!singlepar || pit1 == cursor_.bottom().pit())
1307 buftext.redoParagraph(*this, pit1);
1308 y1 -= buftext.getPar(pit1).descent();
1312 // Take care of ascent of first line
1313 y1 -= buftext.getPar(pit1).ascent();
1315 // Normalize anchor for next time
1319 // Grey at the beginning is ugly
1320 if (pit1 == 0 && y1 > 0) {
1326 // Redo paragraphs below the anchor if necessary. Single par mode:
1327 // only the one containing the cursor if encountered.
1329 while (y2 < height_ && pit2 < int(npit) - 1) {
1330 y2 += buftext.getPar(pit2).descent();
1332 if (!singlepar || pit2 == cursor_.bottom().pit())
1333 buftext.redoParagraph(*this, pit2);
1334 y2 += buftext.getPar(pit2).ascent();
1337 // Take care of descent of last line
1338 y2 += buftext.getPar(pit2).descent();
1340 // The coordinates of all these paragraphs are correct, cache them
1342 CoordCache::InnerParPosCache & parPos = coord_cache_.parPos()[&buftext];
1343 for (pit_type pit = pit1; pit <= pit2; ++pit) {
1344 Paragraph const & par = buftext.getPar(pit);
1346 parPos[pit] = Point(0, y);
1347 if (singlepar && pit == cursor_.bottom().pit()) {
1348 // In Single Paragraph mode, collect here the
1349 // y1 and y2 of the (one) paragraph the cursor is in
1350 y1 = y - par.ascent();
1351 y2 = y + par.descent();
1357 // collect cursor paragraph iter bounds
1358 pit1 = cursor_.bottom().pit();
1359 pit2 = cursor_.bottom().pit();
1362 lyxerr[Debug::DEBUG]
1363 << BOOST_CURRENT_FUNCTION
1366 << " pit1: " << pit1
1367 << " pit2: " << pit2
1368 << " npit: " << npit
1369 << " singlepar: " << singlepar
1373 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2, singlepar, size);
1375 if (lyxerr.debugging(Debug::WORKAREA)) {
1376 lyxerr[Debug::WORKAREA] << "BufferView::updateMetrics" << endl;
1377 coord_cache_.dump();
1382 void BufferView::menuInsertLyXFile(string const & filenm)
1384 BOOST_ASSERT(cursor_.inTexted());
1385 string filename = filenm;
1387 if (filename.empty()) {
1388 // Launch a file browser
1390 string initpath = lyxrc.document_path;
1393 string const trypath = buffer_->filePath();
1394 // If directory is writeable, use this as default.
1395 if (isDirWriteable(FileName(trypath)))
1400 FileDialog fileDlg(_("Select LyX document to insert"),
1402 make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1403 make_pair(_("Examples|#E#e"), from_utf8(addPath(package().system_support(), "examples"))));
1405 FileDialog::Result result =
1406 fileDlg.open(from_utf8(initpath),
1407 FileFilterList(_("LyX Documents (*.lyx)")),
1410 if (result.first == FileDialog::Later)
1414 filename = to_utf8(result.second);
1416 // check selected filename
1417 if (filename.empty()) {
1418 // emit message signal.
1419 message(_("Canceled."));
1424 // Get absolute path of file and add ".lyx"
1425 // to the filename if necessary
1426 filename = fileSearch(string(), filename, "lyx").absFilename();
1428 docstring const disp_fn = makeDisplayPath(filename);
1429 // emit message signal.
1430 message(bformat(_("Inserting document %1$s..."), disp_fn));
1433 Buffer buf("", false);
1434 if (lyx::loadLyXFile(&buf, FileName(filename))) {
1435 ErrorList & el = buffer_->errorList("Parse");
1436 // Copy the inserted document error list into the current buffer one.
1437 el = buf.errorList("Parse");
1438 recordUndo(cursor_);
1439 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1440 buf.params().textclass, el);
1441 res = _("Document %1$s inserted.");
1443 res = _("Could not insert document %1$s");
1445 // emit message signal.
1446 message(bformat(res, disp_fn));
1447 buffer_->errors("Parse");