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::fileSearch;
87 using support::isDirWriteable;
88 using support::makeDisplayPath;
89 using support::makeAbsPath;
90 using support::package;
94 using std::istringstream;
98 using std::mem_fun_ref;
102 namespace Alert = frontend::Alert;
106 /// Return an inset of this class if it exists at the current cursor position
108 T * getInsetByCode(LCursor & cur, InsetBase::Code code)
111 DocIterator it = cur;
112 if (it.nextInset() &&
113 it.nextInset()->lyxCode() == code) {
114 inset = static_cast<T*>(it.nextInset());
122 BufferView::BufferView()
123 : width_(0), height_(0), buffer_(0), wh_(0),
125 multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
128 xsel_cache_.set = false;
129 intl_->initKeyMapper(lyxrc.use_kbmap);
133 BufferView::~BufferView()
138 Buffer * BufferView::buffer() const
144 void BufferView::setBuffer(Buffer * b)
146 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
147 << "[ b = " << b << "]" << endl;
150 // Save the actual cursor position and anchor inside the
151 // buffer so that it can be restored in case we rechange
152 // to this buffer later on.
153 buffer_->saveCursor(cursor_.selectionBegin(),
154 cursor_.selectionEnd());
155 // current buffer is going to be switched-off, save cursor pos
156 LyX::ref().session().lastFilePos().save(buffer_->fileName(),
157 boost::tie(cursor_.pit(), cursor_.pos()) );
160 // If we're quitting lyx, don't bother updating stuff
166 // If we are closing current buffer, switch to the first in
169 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
170 << " No Buffer!" << endl;
171 // We are closing the buffer, use the first buffer as current
172 buffer_ = theBufferList().first();
174 // Set current buffer
179 cursor_ = LCursor(*this);
184 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
185 << "Buffer addr: " << buffer_ << endl;
186 cursor_.push(buffer_->inset());
187 cursor_.resetAnchor();
188 buffer_->text().init(this);
189 buffer_->text().setCurrentFont(cursor_);
190 if (buffer_->getCursor().size() > 0 &&
191 buffer_->getAnchor().size() > 0)
193 cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
194 cursor_.resetAnchor();
195 cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
196 cursor_.setSelection();
200 // FIXME: in principle, a simple call to updateMetrics(false) should
201 // be enough here. But, for unknown reason, it seems that only the line
202 // of the cursor is updated in the CoordCache.
204 updateMetrics(false);
206 if (buffer_ && graphics::Previews::status() != LyXRC::PREVIEW_OFF)
207 graphics::Previews::get().generateBufferPreviews(*buffer_);
211 bool BufferView::loadLyXFile(string const & filename, bool tolastfiles)
213 // Get absolute path of file and add ".lyx"
214 // to the filename if necessary
215 string s = fileSearch(string(), filename, "lyx");
217 bool const found = !s.empty();
222 // File already open?
223 if (theBufferList().exists(s)) {
224 docstring const file = makeDisplayPath(s, 20);
225 docstring text = bformat(_("The document %1$s is already "
226 "loaded.\n\nDo you want to revert "
227 "to the saved version?"), file);
228 int const ret = Alert::prompt(_("Revert to saved document?"),
229 text, 0, 1, _("&Revert"), _("&Switch to document"));
232 setBuffer(theBufferList().getBuffer(s));
235 // FIXME: should be LFUN_REVERT
236 if (!theBufferList().close(theBufferList().getBuffer(s), false))
238 // Fall through to new load. (Asger)
245 b = theBufferList().newBuffer(s);
246 if (!lyx::loadLyXFile(b, s)) {
247 theBufferList().release(b);
251 docstring text = bformat(_("The document %1$s does not yet "
252 "exist.\n\nDo you want to create "
253 "a new document?"), from_utf8(s));
254 int const ret = Alert::prompt(_("Create new document?"),
255 text, 0, 1, _("&Create"), _("Cancel"));
258 b = newFile(s, string(), true);
266 // Send the "errors" signal in case of parsing errors
269 // scroll to the position when the file was last closed
270 if (lyxrc.use_lastfilepos) {
273 boost::tie(pit, pos) = LyX::ref().session().lastFilePos().load(s);
274 // I am not sure how to separate the following part to a function
275 // so I will leave this to Lars.
277 // check pit since the document may be externally changed.
278 if ( static_cast<size_t>(pit) < b->paragraphs().size() ) {
279 ParIterator it = b->par_iterator_begin();
280 ParIterator const end = b->par_iterator_end();
281 for (; it != end; ++it)
282 if (it.pit() == pit) {
283 // restored pos may be bigger than it->size
284 setCursor(makeDocIterator(it, min(pos, it->size())));
285 update(Update::FitCursor);
292 LyX::ref().session().lastFiles().add(b->fileName());
298 void BufferView::reload()
300 string const fn = buffer_->fileName();
301 if (theBufferList().close(buffer_, false))
306 void BufferView::resize()
311 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
313 buffer_->text().init(this);
319 bool BufferView::fitCursor()
321 if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
322 frontend::FontMetrics const & fm =
323 theFontMetrics(cursor_.getFont());
324 int const asc = fm.maxAscent();
325 int const des = fm.maxDescent();
326 Point const p = bv_funcs::getPos(*this, cursor_, cursor_.boundary());
327 if (p.y_ - asc >= 0 && p.y_ + des < height_)
335 bool BufferView::multiParSel()
337 if (!cursor_.selection())
339 bool ret = multiparsel_cache_;
340 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
341 // Either this, or previous selection spans paragraphs
342 return ret || multiparsel_cache_;
346 std::pair<bool, bool> BufferView::update(Update::flags flags)
348 // This is close to a hot-path.
349 if (lyxerr.debugging(Debug::DEBUG)) {
351 << BOOST_CURRENT_FUNCTION
352 << "[fitcursor = " << (flags & Update::FitCursor)
353 << ", forceupdate = " << (flags & Update::Force)
354 << ", singlepar = " << (flags & Update::SinglePar)
355 << "] buffer: " << buffer_ << endl;
358 // Check needed to survive LyX startup
360 return make_pair(false, false);
362 if (lyxerr.debugging(Debug::WORKAREA)) {
363 lyxerr[Debug::WORKAREA] << "BufferView::update" << std::endl;
366 // Update macro store
367 buffer_->buildMacros();
369 // Now do the first drawing step if needed. This consists on updating
370 // the CoordCache in updateMetrics().
371 // The second drawing step is done in WorkArea::redraw() if needed.
373 // Case when no explicit update is requested.
375 // no need to do anything.
376 return make_pair(false, false);
379 bool full_metrics = flags & Update::Force;
380 if (flags & Update::MultiParSel)
381 full_metrics |= multiParSel();
383 bool const single_par = !full_metrics;
384 updateMetrics(single_par);
386 if (flags & Update::FitCursor && fitCursor())
387 updateMetrics(false);
389 // tell the frontend to update the screen.
390 return make_pair(true, single_par);
394 void BufferView::updateScrollbar()
397 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
398 << " no text in updateScrollbar" << endl;
399 scrollbarParameters_.reset();
403 LyXText & t = buffer_->text();
404 int const parsize = int(t.paragraphs().size() - 1);
405 if (anchor_ref_ > parsize) {
406 anchor_ref_ = parsize;
410 if (lyxerr.debugging(Debug::GUI)) {
412 << BOOST_CURRENT_FUNCTION
413 << " Updating scrollbar: height: " << t.paragraphs().size()
414 << " curr par: " << cursor_.bottom().pit()
415 << " default height " << defaultRowHeight() << endl;
418 // It would be better to fix the scrollbar to understand
419 // values in [0..1] and divide everything by wh
421 // estimated average paragraph height:
424 int h = t.getPar(anchor_ref_).height();
426 // Normalize anchor/offset (MV):
427 while (offset_ref_ > h && anchor_ref_ < parsize) {
430 h = t.getPar(anchor_ref_).height();
432 // Look at paragraph heights on-screen
435 for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
438 int const h2 = t.getPar(pit).height();
444 int const hav = sumh / nh;
445 // More realistic average paragraph height
450 scrollbarParameters_.height = (parsize + 1) * wh_;
451 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
452 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
456 ScrollbarParameters const & BufferView::scrollbarParameters() const
458 return scrollbarParameters_;
462 void BufferView::scrollDocView(int value)
464 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
465 << "[ value = " << value << "]" << endl;
470 LyXText & t = buffer_->text();
472 float const bar = value / float(wh_ * t.paragraphs().size());
474 anchor_ref_ = int(bar * t.paragraphs().size());
475 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
476 anchor_ref_ = int(t.paragraphs().size()) - 1;
477 t.redoParagraph(*this, anchor_ref_);
478 int const h = t.getPar(anchor_ref_).height();
479 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
480 updateMetrics(false);
484 void BufferView::setCursorFromScrollbar()
486 LyXText & t = buffer_->text();
488 int const height = 2 * defaultRowHeight();
489 int const first = height;
490 int const last = height_ - height;
491 LCursor & cur = cursor_;
493 bv_funcs::CurStatus st = bv_funcs::status(this, cur);
496 case bv_funcs::CUR_ABOVE:
497 t.setCursorFromCoordinates(cur, 0, first);
498 cur.clearSelection();
500 case bv_funcs::CUR_BELOW:
501 t.setCursorFromCoordinates(cur, 0, last);
502 cur.clearSelection();
504 case bv_funcs::CUR_INSIDE:
505 int const y = bv_funcs::getPos(*this, cur, cur.boundary()).y_;
506 int const newy = min(last, max(y, first));
508 cur.reset(buffer_->inset());
509 t.setCursorFromCoordinates(cur, 0, newy);
515 Change const BufferView::getCurrentChange() const
517 if (!cursor_.selection())
518 return Change(Change::UNCHANGED);
520 DocIterator dit = cursor_.selectionBegin();
521 return dit.paragraph().lookupChange(dit.pos());
525 void BufferView::saveBookmark(bool persistent)
527 LyX::ref().session().bookmarks().save(
529 cursor_.paragraph().id(),
534 // emit message signal.
535 message(_("Save bookmark"));
539 void BufferView::moveToPosition(int par_id, pos_type par_pos)
541 cursor_.clearSelection();
543 ParIterator par = buffer_->getParFromID(par_id);
544 if (par == buffer_->par_iterator_end())
547 setCursor(makeDocIterator(par, min(par->size(), par_pos)));
551 void BufferView::switchKeyMap()
553 if (!lyxrc.rtl_support)
556 if (getLyXText()->real_current_font.isRightToLeft()) {
557 if (intl_->keymap == Intl::PRIMARY)
560 if (intl_->keymap == Intl::SECONDARY)
566 int BufferView::workWidth() const
572 void BufferView::center()
574 CursorSlice & bot = cursor_.bottom();
575 pit_type const pit = bot.pit();
576 bot.text()->redoParagraph(*this, pit);
577 Paragraph const & par = bot.text()->paragraphs()[pit];
579 offset_ref_ = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary()).y_
580 + par.ascent() - height_ / 2;
584 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
588 switch (cmd.action) {
591 flag.enabled(!buffer_->undostack().empty());
594 flag.enabled(!buffer_->redostack().empty());
596 case LFUN_FILE_INSERT:
597 case LFUN_FILE_INSERT_ASCII_PARA:
598 case LFUN_FILE_INSERT_ASCII:
599 case LFUN_BOOKMARK_SAVE:
600 // FIXME: Actually, these LFUNS should be moved to LyXText
601 flag.enabled(cursor_.inTexted());
603 case LFUN_FONT_STATE:
604 case LFUN_LABEL_INSERT:
605 case LFUN_PARAGRAPH_GOTO:
606 // FIXME handle non-trivially
607 case LFUN_OUTLINE_UP:
608 case LFUN_OUTLINE_DOWN:
609 case LFUN_OUTLINE_IN:
610 case LFUN_OUTLINE_OUT:
612 case LFUN_REFERENCE_NEXT:
614 case LFUN_WORD_REPLACE:
617 case LFUN_MARK_TOGGLE:
618 case LFUN_SCREEN_RECENTER:
619 case LFUN_BIBTEX_DATABASE_ADD:
620 case LFUN_BIBTEX_DATABASE_DEL:
621 case LFUN_WORDS_COUNT:
622 case LFUN_NEXT_INSET_TOGGLE:
626 case LFUN_LABEL_GOTO: {
627 flag.enabled(!cmd.argument().empty()
628 || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
632 case LFUN_CHANGES_TRACK:
634 flag.setOnOff(buffer_->params().trackChanges);
637 case LFUN_CHANGES_OUTPUT: {
638 OutputParams runparams;
639 LaTeXFeatures features(*buffer_, buffer_->params(), runparams);
640 flag.enabled(buffer_ && features.isAvailable("dvipost"));
641 flag.setOnOff(buffer_->params().outputChanges);
645 case LFUN_CHANGES_MERGE:
646 case LFUN_CHANGE_NEXT:
647 case LFUN_ALL_CHANGES_ACCEPT:
648 case LFUN_ALL_CHANGES_REJECT:
649 flag.enabled(buffer_); // FIXME: Change tracking (MG)
652 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
653 flag.setOnOff(buffer_->params().compressed);
665 bool BufferView::dispatch(FuncRequest const & cmd)
667 //lyxerr << BOOST_CURRENT_FUNCTION
668 // << [ cmd = " << cmd << "]" << endl;
670 // Make sure that the cached BufferView is correct.
671 lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
672 << " action[" << cmd.action << ']'
673 << " arg[" << to_utf8(cmd.argument()) << ']'
674 << " x[" << cmd.x << ']'
675 << " y[" << cmd.y << ']'
676 << " button[" << cmd.button() << ']'
679 LCursor & cur = cursor_;
681 switch (cmd.action) {
685 cur.message(_("Undo"));
686 cur.clearSelection();
687 if (!textUndo(*this))
688 cur.message(_("No further undo information"));
696 cur.message(_("Redo"));
697 cur.clearSelection();
698 if (!textRedo(*this))
699 cur.message(_("No further redo information"));
705 case LFUN_FILE_INSERT:
706 // FIXME: We don't know the encoding of filenames
707 menuInsertLyXFile(to_utf8(cmd.argument()));
710 case LFUN_FILE_INSERT_ASCII_PARA:
711 // FIXME: We don't know the encoding of filenames
712 insertAsciiFile(this, to_utf8(cmd.argument()), true);
715 case LFUN_FILE_INSERT_ASCII:
716 // FIXME: We don't know the encoding of filenames
717 insertAsciiFile(this, to_utf8(cmd.argument()), false);
720 case LFUN_FONT_STATE:
721 cur.message(from_utf8(cur.currentState()));
724 case LFUN_BOOKMARK_SAVE:
725 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
728 case LFUN_LABEL_GOTO: {
729 docstring label = cmd.argument();
732 getInsetByCode<InsetRef>(cursor_,
733 InsetBase::REF_CODE);
735 label = inset->getParam("reference");
736 // persistent=false: use temp_bookmark
746 case LFUN_PARAGRAPH_GOTO: {
747 int const id = convert<int>(to_utf8(cmd.argument()));
749 for (Buffer * b = buffer_; i == 0 || b != buffer_; b = theBufferList().next(b)) {
750 ParIterator par = b->getParFromID(id);
751 if (par == b->par_iterator_end()) {
753 << "No matching paragraph found! ["
754 << id << "]." << endl;
757 << "Paragraph " << par->id()
758 << " found in buffer `"
759 << b->fileName() << "'." << endl;
763 setCursor(makeDocIterator(par, 0));
767 // Switch to other buffer view and resend cmd
768 theLyXFunc().dispatch(FuncRequest(
769 LFUN_BUFFER_SWITCH, b->fileName()));
770 theLyXFunc().dispatch(cmd);
779 case LFUN_OUTLINE_UP:
780 toc::outline(toc::Up, cursor_);
781 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
782 updateLabels(*buffer_);
784 case LFUN_OUTLINE_DOWN:
785 toc::outline(toc::Down, cursor_);
786 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
787 updateLabels(*buffer_);
789 case LFUN_OUTLINE_IN:
790 toc::outline(toc::In, cursor_);
791 updateLabels(*buffer_);
793 case LFUN_OUTLINE_OUT:
794 toc::outline(toc::Out, cursor_);
795 updateLabels(*buffer_);
799 bv_funcs::gotoInset(this, InsetBase::NOTE_CODE, false);
802 case LFUN_REFERENCE_NEXT: {
803 vector<InsetBase_code> tmp;
804 tmp.push_back(InsetBase::LABEL_CODE);
805 tmp.push_back(InsetBase::REF_CODE);
806 bv_funcs::gotoInset(this, tmp, true);
810 case LFUN_CHANGES_TRACK:
811 buffer_->params().trackChanges = !buffer_->params().trackChanges;
814 case LFUN_CHANGES_OUTPUT: {
815 buffer_->params().outputChanges = !buffer_->params().outputChanges;
819 case LFUN_CHANGE_NEXT:
820 findNextChange(this);
823 case LFUN_CHANGES_MERGE:
824 if (findNextChange(this))
825 showDialog("changes");
828 case LFUN_ALL_CHANGES_ACCEPT: {
829 cursor_.reset(buffer_->inset());
831 #warning FIXME changes
833 while (findNextChange(this))
834 getLyXText()->acceptChange(cursor_);
839 case LFUN_ALL_CHANGES_REJECT: {
840 cursor_.reset(buffer_->inset());
842 #warning FIXME changes
844 while (findNextChange(this))
845 getLyXText()->rejectChange(cursor_);
853 case LFUN_WORD_REPLACE:
858 cur.clearSelection();
860 cur.message(from_utf8(N_("Mark off")));
864 cur.clearSelection();
867 cur.message(from_utf8(N_("Mark on")));
870 case LFUN_MARK_TOGGLE:
871 cur.clearSelection();
874 cur.message(from_utf8(N_("Mark removed")));
877 cur.message(from_utf8(N_("Mark set")));
882 case LFUN_SCREEN_RECENTER:
886 case LFUN_BIBTEX_DATABASE_ADD: {
887 LCursor tmpcur = cursor_;
888 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
889 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
890 InsetBase::BIBTEX_CODE);
892 if (inset->addDatabase(to_utf8(cmd.argument())))
893 buffer_->updateBibfilesCache();
898 case LFUN_BIBTEX_DATABASE_DEL: {
899 LCursor tmpcur = cursor_;
900 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
901 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
902 InsetBase::BIBTEX_CODE);
904 if (inset->delDatabase(to_utf8(cmd.argument())))
905 buffer_->updateBibfilesCache();
910 case LFUN_WORDS_COUNT: {
911 DocIterator from, to;
912 if (cur.selection()) {
913 from = cur.selectionBegin();
914 to = cur.selectionEnd();
916 from = doc_iterator_begin(buffer_->inset());
917 to = doc_iterator_end(buffer_->inset());
919 int const count = countWords(from, to);
923 message = bformat(_("%1$d words in selection."),
926 message = bformat(_("%1$d words in document."),
931 message = _("One word in selection.");
933 message = _("One word in document.");
936 Alert::information(_("Count words"), message);
940 case LFUN_BUFFER_TOGGLE_COMPRESSION:
941 // turn compression on/off
942 buffer_->params().compressed = !buffer_->params().compressed;
945 case LFUN_NEXT_INSET_TOGGLE: {
946 // this is the real function we want to invoke
947 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
948 // if there is an inset at cursor, see whether it
950 InsetBase * inset = cur.nextInset();
951 if (inset && inset->isActive()) {
952 LCursor tmpcur = cur;
953 tmpcur.pushLeft(*inset);
954 inset->dispatch(tmpcur, tmpcmd);
955 if (tmpcur.result().dispatched()) {
959 // if it did not work, try the underlying inset.
960 if (!cur.result().dispatched())
961 cur.dispatch(tmpcmd);
963 if (cur.result().dispatched())
964 cur.clearSelection();
977 docstring const BufferView::requestSelection()
982 LCursor & cur = cursor_;
984 if (!cur.selection()) {
985 xsel_cache_.set = false;
989 if (!xsel_cache_.set ||
990 cur.top() != xsel_cache_.cursor ||
991 cur.anchor_.top() != xsel_cache_.anchor)
993 xsel_cache_.cursor = cur.top();
994 xsel_cache_.anchor = cur.anchor_.top();
995 xsel_cache_.set = cur.selection();
996 return cur.selectionAsString(false);
1002 void BufferView::clearSelection()
1005 cursor_.clearSelection();
1006 xsel_cache_.set = false;
1011 void BufferView::workAreaResize(int width, int height)
1013 bool const widthChange = width != width_;
1014 bool const heightChange = height != height_;
1016 // Update from work area
1027 std::pair<bool, bool> BufferView::workAreaDispatch(FuncRequest const & cmd0)
1029 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1031 // This is only called for mouse related events including
1032 // LFUN_FILE_OPEN generated by drag-and-drop.
1033 FuncRequest cmd = cmd0;
1035 // E.g. Qt mouse press when no buffer
1037 return make_pair(false, false);
1040 cur.push(buffer_->inset());
1041 cur.selection() = cursor_.selection();
1043 // Either the inset under the cursor or the
1044 // surrounding LyXText will handle this event.
1046 // Build temporary cursor.
1047 cmd.y = min(max(cmd.y, -1), height_);
1048 InsetBase * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1050 //lyxerr << BOOST_CURRENT_FUNCTION
1051 // << " * hit inset at tip: " << inset << endl;
1052 //lyxerr << BOOST_CURRENT_FUNCTION
1053 // << " * created temp cursor:" << cur << endl;
1055 // Put anchor at the same position.
1058 // Try to dispatch to an non-editable inset near this position
1059 // via the temp cursor. If the inset wishes to change the real
1060 // cursor it has to do so explicitly by using
1061 // cur.bv().cursor() = cur; (or similar)
1063 inset->dispatch(cur, cmd);
1066 // Now dispatch to the temporary cursor. If the real cursor should
1067 // be modified, the inset's dispatch has to do so explicitly.
1068 if (!cur.result().dispatched())
1071 // Redraw if requested and necessary.
1072 if (cur.result().dispatched() && cur.result().update())
1073 return update(cur.result().update());
1075 // When the above and the inner function are fixed, we can do this:
1076 return make_pair(false, false);
1080 void BufferView::scroll(int /*lines*/)
1085 // LyXText const * t = &buffer_->text();
1086 // int const line_height = defaultRowHeight();
1088 // // The new absolute coordinate
1089 // int new_top_y = top_y() + lines * line_height;
1091 // // Restrict to a valid value
1092 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1093 // new_top_y = std::max(0, new_top_y);
1095 // scrollDocView(new_top_y);
1097 // // Update the scrollbar.
1098 // workArea_->setScrollbarParams(t->height(), top_y(), defaultRowHeight());}
1102 void BufferView::setCursorFromRow(int row)
1107 buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1110 buffer_->text().setCursor(cursor_, 0, 0);
1112 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1116 void BufferView::gotoLabel(docstring const & label)
1118 for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1119 vector<docstring> labels;
1120 it->getLabelList(*buffer_, labels);
1121 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1130 LyXText * BufferView::getLyXText()
1132 LyXText * text = cursor_.innerText();
1138 LyXText const * BufferView::getLyXText() const
1140 LyXText const * text = cursor_.innerText();
1146 int BufferView::workHeight() const
1152 void BufferView::setCursor(DocIterator const & dit)
1154 size_t const n = dit.depth();
1155 for (size_t i = 0; i < n; ++i)
1156 dit[i].inset().edit(cursor_, true);
1158 cursor_.setCursor(dit);
1159 cursor_.selection() = false;
1163 void BufferView::mouseSetCursor(LCursor & cur)
1165 BOOST_ASSERT(&cur.bv() == this);
1167 // Has the cursor just left the inset?
1168 bool badcursor = false;
1169 if (&cursor_.inset() != &cur.inset())
1170 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1172 // do the dEPM magic if needed
1173 // FIXME: move this to InsetText::notifyCursorLeaves?
1174 if (!badcursor && cursor_.inTexted())
1175 cursor_.text()->deleteEmptyParagraphMechanism(cur, cursor_);
1178 cursor_.clearSelection();
1179 cursor_.setTargetX();
1185 void BufferView::putSelectionAt(DocIterator const & cur,
1186 int length, bool backwards)
1188 cursor_.clearSelection();
1194 cursor_.pos() += length;
1195 cursor_.setSelection(cursor_, -length);
1197 cursor_.setSelection(cursor_, length);
1202 LCursor & BufferView::cursor()
1208 LCursor const & BufferView::cursor() const
1214 pit_type BufferView::anchor_ref() const
1220 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1222 return metrics_info_;
1226 void BufferView::updateMetrics(bool singlepar)
1228 // Clear out the position cache in case of full screen redraw.
1230 coord_cache_.clear();
1232 LyXText & buftext = buffer_->text();
1233 pit_type size = int(buftext.paragraphs().size());
1235 if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1236 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1240 pit_type const pit = anchor_ref_;
1243 size_t const npit = buftext.paragraphs().size();
1245 // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
1246 // the (main text, not inset!) paragraph containing the cursor.
1247 // (if this paragraph contains insets etc., rebreaking will
1248 // recursively descend)
1249 if (!singlepar || pit == cursor_.bottom().pit())
1250 buftext.redoParagraph(*this, pit);
1251 int y0 = buftext.getPar(pit).ascent() - offset_ref_;
1253 // Redo paragraphs above anchor if necessary; again, in Single Par
1254 // mode, only if we encounter the (main text) one having the cursor.
1256 while (y1 > 0 && pit1 > 0) {
1257 y1 -= buftext.getPar(pit1).ascent();
1259 if (!singlepar || pit1 == cursor_.bottom().pit())
1260 buftext.redoParagraph(*this, pit1);
1261 y1 -= buftext.getPar(pit1).descent();
1265 // Take care of ascent of first line
1266 y1 -= buftext.getPar(pit1).ascent();
1268 // Normalize anchor for next time
1272 // Grey at the beginning is ugly
1273 if (pit1 == 0 && y1 > 0) {
1279 // Redo paragraphs below the anchor if necessary. Single par mode:
1280 // only the one containing the cursor if encountered.
1282 while (y2 < height_ && pit2 < int(npit) - 1) {
1283 y2 += buftext.getPar(pit2).descent();
1285 if (!singlepar || pit2 == cursor_.bottom().pit())
1286 buftext.redoParagraph(*this, pit2);
1287 y2 += buftext.getPar(pit2).ascent();
1290 // Take care of descent of last line
1291 y2 += buftext.getPar(pit2).descent();
1293 // The coordinates of all these paragraphs are correct, cache them
1295 CoordCache::InnerParPosCache & parPos = coord_cache_.parPos()[&buftext];
1296 for (pit_type pit = pit1; pit <= pit2; ++pit) {
1297 Paragraph const & par = buftext.getPar(pit);
1299 parPos[pit] = Point(0, y);
1300 if (singlepar && pit == cursor_.bottom().pit()) {
1301 // In Single Paragraph mode, collect here the
1302 // y1 and y2 of the (one) paragraph the cursor is in
1303 y1 = y - par.ascent();
1304 y2 = y + par.descent();
1310 // collect cursor paragraph iter bounds
1311 pit1 = cursor_.bottom().pit();
1312 pit2 = cursor_.bottom().pit();
1315 lyxerr[Debug::DEBUG]
1316 << BOOST_CURRENT_FUNCTION
1319 << " pit1: " << pit1
1320 << " pit2: " << pit2
1321 << " npit: " << npit
1322 << " singlepar: " << singlepar
1326 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2, singlepar, size);
1328 if (lyxerr.debugging(Debug::WORKAREA)) {
1329 lyxerr[Debug::WORKAREA] << "BufferView::updateMetrics" << endl;
1330 coord_cache_.dump();
1335 void BufferView::menuInsertLyXFile(string const & filenm)
1337 BOOST_ASSERT(cursor_.inTexted());
1338 string filename = filenm;
1340 if (filename.empty()) {
1341 // Launch a file browser
1343 string initpath = lyxrc.document_path;
1346 string const trypath = buffer_->filePath();
1347 // If directory is writeable, use this as default.
1348 if (isDirWriteable(trypath))
1353 FileDialog fileDlg(_("Select LyX document to insert"),
1355 make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1356 make_pair(_("Examples|#E#e"), from_utf8(addPath(package().system_support(), "examples"))));
1358 FileDialog::Result result =
1359 fileDlg.open(from_utf8(initpath),
1360 FileFilterList(_("LyX Documents (*.lyx)")),
1363 if (result.first == FileDialog::Later)
1367 filename = to_utf8(result.second);
1369 // check selected filename
1370 if (filename.empty()) {
1371 // emit message signal.
1372 message(_("Canceled."));
1377 // Get absolute path of file and add ".lyx"
1378 // to the filename if necessary
1379 filename = fileSearch(string(), filename, "lyx");
1381 docstring const disp_fn = makeDisplayPath(filename);
1382 // emit message signal.
1383 message(bformat(_("Inserting document %1$s..."), disp_fn));
1386 Buffer buf("", false);
1387 if (lyx::loadLyXFile(&buf, makeAbsPath(filename))) {
1388 ErrorList & el = buffer_->errorList("Parse");
1389 // Copy the inserted document error list into the current buffer one.
1390 el = buf.errorList("Parse");
1391 recordUndo(cursor_);
1392 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1393 buf.params().textclass, el);
1394 res = _("Document %1$s inserted.");
1396 res = _("Could not insert document %1$s");
1398 // emit message signal.
1399 message(bformat(res, disp_fn));
1400 buffer_->errors("Parse");