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 "bufferview_funcs.h"
24 #include "callback.h" // added for Dispatch functions
25 #include "CoordCache.h"
26 #include "CutAndPaste.h"
28 #include "DispatchResult.h"
29 #include "ErrorList.h"
31 #include "FloatList.h"
32 #include "FuncRequest.h"
33 #include "FuncStatus.h"
36 #include "InsetIterator.h"
38 #include "LaTeXFeatures.h"
44 #include "MetricsInfo.h"
45 #include "Paragraph.h"
46 #include "paragraph_funcs.h"
47 #include "ParagraphParameters.h"
48 #include "ParIterator.h"
52 #include "TextClass.h"
56 #include "WordLangTuple.h"
58 #include "insets/InsetBibtex.h"
59 #include "insets/InsetCommand.h" // ChangeRefs
60 #include "insets/InsetRef.h"
61 #include "insets/InsetText.h"
63 #include "frontends/alert.h"
64 #include "frontends/FileDialog.h"
65 #include "frontends/FontMetrics.h"
66 #include "frontends/Painter.h"
67 #include "frontends/Selection.h"
69 #include "graphics/Previews.h"
71 #include "support/convert.h"
72 #include "support/FileFilterList.h"
73 #include "support/filetools.h"
74 #include "support/Package.h"
75 #include "support/types.h"
77 #include <boost/bind.hpp>
78 #include <boost/current_function.hpp>
85 using std::istringstream;
89 using std::mem_fun_ref;
96 using support::addPath;
97 using support::bformat;
98 using support::FileFilterList;
99 using support::FileName;
100 using support::fileSearch;
101 using support::isDirWriteable;
102 using support::isFileReadable;
103 using support::makeDisplayPath;
104 using support::package;
106 namespace Alert = frontend::Alert;
110 /// Return an inset of this class if it exists at the current cursor position
112 T * getInsetByCode(Cursor & cur, Inset::Code code)
115 DocIterator it = cur;
116 if (it.nextInset() &&
117 it.nextInset()->lyxCode() == code) {
118 inset = static_cast<T*>(it.nextInset());
126 BufferView::BufferView(Buffer & buf)
127 : width_(0), height_(0), buffer_(buf), wh_(0),
129 multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
130 need_centering_(false), intl_(new Intl), last_inset_(0)
132 xsel_cache_.set = false;
133 intl_->initKeyMapper(lyxrc.use_kbmap);
135 cursor_.push(buffer_.inset());
136 cursor_.resetAnchor();
137 cursor_.setCurrentFont();
139 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
140 graphics::Previews::get().generateBufferPreviews(buffer_);
144 BufferView::~BufferView()
146 // current buffer is going to be switched-off, save cursor pos
147 // Ideally, the whole cursor stack should be saved, but session
148 // currently can only handle bottom (whole document) level pit and pos.
149 // That is to say, if a cursor is in a nested inset, it will be
150 // restore to the left of the top level inset.
151 LyX::ref().session().lastFilePos().save(
152 support::FileName(buffer_.fileName()),
153 boost::tie(cursor_.bottom().pit(), cursor_.bottom().pos()) );
157 Buffer & BufferView::buffer()
163 Buffer const & BufferView::buffer() const
169 bool BufferView::fitCursor()
171 if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
172 frontend::FontMetrics const & fm =
173 theFontMetrics(cursor_.getFont());
174 int const asc = fm.maxAscent();
175 int const des = fm.maxDescent();
176 Point const p = bv_funcs::getPos(*this, cursor_, cursor_.boundary());
177 if (p.y_ - asc >= 0 && p.y_ + des < height_)
185 bool BufferView::multiParSel()
187 if (!cursor_.selection())
189 bool ret = multiparsel_cache_;
190 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
191 // Either this, or previous selection spans paragraphs
192 return ret || multiparsel_cache_;
196 bool BufferView::update(Update::flags flags)
198 // last_inset_ points to the last visited inset. This pointer may become
199 // invalid because of keyboard editing. Since all such operations
200 // causes screen update(), I reset last_inset_ to avoid such a problem.
202 // This is close to a hot-path.
204 << BOOST_CURRENT_FUNCTION
205 << "[fitcursor = " << (flags & Update::FitCursor)
206 << ", forceupdate = " << (flags & Update::Force)
207 << ", singlepar = " << (flags & Update::SinglePar)
208 << "] buffer: " << &buffer_ << endl;
210 // Update macro store
211 if (!(cursor().inMathed() && cursor().inMacroMode()))
212 buffer_.buildMacros();
214 // Now do the first drawing step if needed. This consists on updating
215 // the CoordCache in updateMetrics().
216 // The second drawing step is done in WorkArea::redraw() if needed.
218 // Case when no explicit update is requested.
220 // no need to redraw anything.
221 metrics_info_.update_strategy = NoScreenUpdate;
225 if (flags == Update::Decoration) {
226 metrics_info_.update_strategy = DecorationUpdate;
230 if (flags == Update::FitCursor
231 || flags == (Update::Decoration | Update::FitCursor)) {
232 bool const fit_cursor = fitCursor();
233 // tell the frontend to update the screen if needed.
235 updateMetrics(false);
238 if (flags & Update::Decoration) {
239 metrics_info_.update_strategy = DecorationUpdate;
242 // no screen update is needed.
243 metrics_info_.update_strategy = NoScreenUpdate;
247 bool full_metrics = flags & Update::Force;
248 if (flags & Update::MultiParSel)
249 full_metrics |= multiParSel();
251 bool const single_par = !full_metrics;
252 updateMetrics(single_par);
254 if (flags & Update::FitCursor && fitCursor())
255 updateMetrics(false);
257 // tell the frontend to update the screen.
262 void BufferView::updateScrollbar()
264 Text & t = buffer_.text();
265 TextMetrics & tm = text_metrics_[&t];
267 int const parsize = int(t.paragraphs().size() - 1);
268 if (anchor_ref_ > parsize) {
269 anchor_ref_ = parsize;
274 << BOOST_CURRENT_FUNCTION
275 << " Updating scrollbar: height: " << t.paragraphs().size()
276 << " curr par: " << cursor_.bottom().pit()
277 << " default height " << defaultRowHeight() << endl;
279 // It would be better to fix the scrollbar to understand
280 // values in [0..1] and divide everything by wh
282 // estimated average paragraph height:
286 int h = tm.parMetrics(anchor_ref_).height();
288 // Normalize anchor/offset (MV):
289 while (offset_ref_ > h && anchor_ref_ < parsize) {
292 h = tm.parMetrics(anchor_ref_).height();
294 // Look at paragraph heights on-screen
297 for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
300 int const h2 = tm.parMetrics(pit).height();
306 int const hav = sumh / nh;
307 // More realistic average paragraph height
312 scrollbarParameters_.height = (parsize + 1) * wh_;
313 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
314 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
318 ScrollbarParameters const & BufferView::scrollbarParameters() const
320 return scrollbarParameters_;
324 void BufferView::scrollDocView(int value)
326 LYXERR(Debug::GUI) << BOOST_CURRENT_FUNCTION
327 << "[ value = " << value << "]" << endl;
329 Text & t = buffer_.text();
330 TextMetrics & tm = text_metrics_[&t];
332 float const bar = value / float(wh_ * t.paragraphs().size());
334 anchor_ref_ = int(bar * t.paragraphs().size());
335 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
336 anchor_ref_ = int(t.paragraphs().size()) - 1;
338 tm.redoParagraph(anchor_ref_);
339 int const h = tm.parMetrics(anchor_ref_).height();
340 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
341 updateMetrics(false);
345 void BufferView::setCursorFromScrollbar()
347 TextMetrics & tm = text_metrics_[&buffer_.text()];
349 int const height = 2 * defaultRowHeight();
350 int const first = height;
351 int const last = height_ - height;
352 Cursor & cur = cursor_;
354 bv_funcs::CurStatus st = bv_funcs::status(this, cur);
357 case bv_funcs::CUR_ABOVE:
358 // We reset the cursor because bv_funcs::status() does not
359 // work when the cursor is within mathed.
360 cur.reset(buffer_.inset());
361 tm.setCursorFromCoordinates(cur, 0, first);
362 cur.clearSelection();
364 case bv_funcs::CUR_BELOW:
365 // We reset the cursor because bv_funcs::status() does not
366 // work when the cursor is within mathed.
367 cur.reset(buffer_.inset());
368 tm.setCursorFromCoordinates(cur, 0, last);
369 cur.clearSelection();
371 case bv_funcs::CUR_INSIDE:
372 int const y = bv_funcs::getPos(*this, cur, cur.boundary()).y_;
373 int const newy = min(last, max(y, first));
375 cur.reset(buffer_.inset());
376 tm.setCursorFromCoordinates(cur, 0, newy);
382 Change const BufferView::getCurrentChange() const
384 if (!cursor_.selection())
385 return Change(Change::UNCHANGED);
387 DocIterator dit = cursor_.selectionBegin();
388 return dit.paragraph().lookupChange(dit.pos());
392 void BufferView::saveBookmark(unsigned int idx)
394 // tenatively save bookmark, id and pos will be used to
395 // acturately locate a bookmark in a 'live' lyx session.
396 // pit and pos will be updated with bottom level pit/pos
398 LyX::ref().session().bookmarks().save(
399 FileName(buffer_.fileName()),
400 cursor_.bottom().pit(),
401 cursor_.bottom().pos(),
402 cursor_.paragraph().id(),
407 // emit message signal.
408 message(_("Save bookmark"));
412 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
413 int top_id, pos_type top_pos)
415 bool success = false;
418 cursor_.clearSelection();
420 // if a valid par_id is given, try it first
421 // This is the case for a 'live' bookmark when unique paragraph ID
422 // is used to track bookmarks.
424 ParIterator par = buffer_.getParFromID(top_id);
425 if (par != buffer_.par_iterator_end()) {
426 doc_it = makeDocIterator(par, min(par->size(), top_pos));
427 // Some slices of the iterator may not be
428 // reachable (e.g. closed collapsable inset)
429 // so the dociterator may need to be
430 // shortened. Otherwise, setCursor may crash
431 // lyx when the cursor can not be set to these
433 size_t const n = doc_it.depth();
434 for (size_t i = 0; i < n; ++i)
435 if (doc_it[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
443 // if top_id == 0, or searching through top_id failed
444 // This is the case for a 'restored' bookmark when only bottom
445 // (document level) pit was saved. Because of this, bookmark
446 // restoration is inaccurate. If a bookmark was within an inset,
447 // it will be restored to the left of the outmost inset that contains
449 if (static_cast<size_t>(bottom_pit) < buffer_.paragraphs().size()) {
450 doc_it = doc_iterator_begin(buffer_.inset());
451 doc_it.pit() = bottom_pit;
452 doc_it.pos() = min(bottom_pos, doc_it.paragraph().size());
457 // Note: only bottom (document) level pit is set.
459 // set the current font.
460 cursor_.setCurrentFont();
461 // center the screen on this new position.
469 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
471 if (lyxrc.rtl_support) {
472 if (cursor_.real_current_font.isRightToLeft()) {
473 if (intl_->keymap == Intl::PRIMARY)
476 if (intl_->keymap == Intl::SECONDARY)
481 intl_->getTransManager().translateAndInsert(c, t, cur);
485 int BufferView::workWidth() const
491 void BufferView::updateOffsetRef()
493 // No need to update offset_ref_ in this case.
494 if (!need_centering_)
497 // We are not properly started yet, delay until resizing is
502 CursorSlice & bot = cursor_.bottom();
503 TextMetrics & tm = text_metrics_[bot.text()];
504 ParagraphMetrics const & pm = tm.parMetrics(bot.pit());
505 Point p = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary());
506 offset_ref_ = p.y_ + pm.ascent() - height_ / 2;
508 need_centering_ = false;
512 void BufferView::center()
514 anchor_ref_ = cursor_.bottom().pit();
515 need_centering_ = true;
519 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
523 Cursor & cur = cursor_;
525 switch (cmd.action) {
528 flag.enabled(!buffer_.undostack().empty());
531 flag.enabled(!buffer_.redostack().empty());
533 case LFUN_FILE_INSERT:
534 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
535 case LFUN_FILE_INSERT_PLAINTEXT:
536 case LFUN_BOOKMARK_SAVE:
537 // FIXME: Actually, these LFUNS should be moved to Text
538 flag.enabled(cur.inTexted());
540 case LFUN_FONT_STATE:
541 case LFUN_LABEL_INSERT:
542 case LFUN_PARAGRAPH_GOTO:
543 // FIXME handle non-trivially
544 case LFUN_OUTLINE_UP:
545 case LFUN_OUTLINE_DOWN:
546 case LFUN_OUTLINE_IN:
547 case LFUN_OUTLINE_OUT:
549 case LFUN_REFERENCE_NEXT:
551 case LFUN_WORD_REPLACE:
554 case LFUN_MARK_TOGGLE:
555 case LFUN_SCREEN_RECENTER:
556 case LFUN_BIBTEX_DATABASE_ADD:
557 case LFUN_BIBTEX_DATABASE_DEL:
558 case LFUN_WORDS_COUNT:
559 case LFUN_NEXT_INSET_TOGGLE:
563 case LFUN_LABEL_GOTO: {
564 flag.enabled(!cmd.argument().empty()
565 || getInsetByCode<InsetRef>(cur, Inset::REF_CODE));
569 case LFUN_CHANGES_TRACK:
571 flag.setOnOff(buffer_.params().trackChanges);
574 case LFUN_CHANGES_OUTPUT:
576 flag.setOnOff(buffer_.params().outputChanges);
579 case LFUN_CHANGES_MERGE:
580 case LFUN_CHANGE_NEXT:
581 case LFUN_ALL_CHANGES_ACCEPT:
582 case LFUN_ALL_CHANGES_REJECT:
583 // TODO: context-sensitive enabling of LFUNs
584 // In principle, these command should only be enabled if there
585 // is a change in the document. However, without proper
586 // optimizations, this will inevitably result in poor performance.
590 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
591 flag.setOnOff(buffer_.params().compressed);
603 Update::flags BufferView::dispatch(FuncRequest const & cmd)
605 //lyxerr << BOOST_CURRENT_FUNCTION
606 // << [ cmd = " << cmd << "]" << endl;
608 // Make sure that the cached BufferView is correct.
609 LYXERR(Debug::ACTION) << BOOST_CURRENT_FUNCTION
610 << " action[" << cmd.action << ']'
611 << " arg[" << to_utf8(cmd.argument()) << ']'
612 << " x[" << cmd.x << ']'
613 << " y[" << cmd.y << ']'
614 << " button[" << cmd.button() << ']'
617 Cursor & cur = cursor_;
618 // Default Update flags.
619 Update::flags updateFlags = Update::Force | Update::FitCursor;
621 switch (cmd.action) {
624 cur.message(_("Undo"));
625 cur.clearSelection();
626 if (!textUndo(*this)) {
627 cur.message(_("No further undo information"));
628 updateFlags = Update::None;
633 cur.message(_("Redo"));
634 cur.clearSelection();
635 if (!textRedo(*this)) {
636 cur.message(_("No further redo information"));
637 updateFlags = Update::None;
641 case LFUN_FILE_INSERT:
643 menuInsertLyXFile(to_utf8(cmd.argument()));
646 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
648 insertPlaintextFile(this, to_utf8(cmd.argument()), true);
651 case LFUN_FILE_INSERT_PLAINTEXT:
653 insertPlaintextFile(this, to_utf8(cmd.argument()), false);
656 case LFUN_FONT_STATE:
657 cur.message(cur.currentState());
660 case LFUN_BOOKMARK_SAVE:
661 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
664 case LFUN_LABEL_GOTO: {
665 docstring label = cmd.argument();
668 getInsetByCode<InsetRef>(cursor_,
671 label = inset->getParam("reference");
672 // persistent=false: use temp_bookmark
682 case LFUN_PARAGRAPH_GOTO: {
683 int const id = convert<int>(to_utf8(cmd.argument()));
685 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
686 b = theBufferList().next(b)) {
688 ParIterator par = b->getParFromID(id);
689 if (par == b->par_iterator_end()) {
691 << "No matching paragraph found! ["
692 << id << "]." << endl;
695 << "Paragraph " << par->id()
696 << " found in buffer `"
697 << b->fileName() << "'." << endl;
701 setCursor(makeDocIterator(par, 0));
703 // Switch to other buffer view and resend cmd
704 theLyXFunc().dispatch(FuncRequest(
705 LFUN_BUFFER_SWITCH, b->fileName()));
706 theLyXFunc().dispatch(cmd);
707 updateFlags = Update::None;
716 case LFUN_OUTLINE_UP:
717 toc::outline(toc::Up, cursor_);
718 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
719 updateLabels(buffer_);
721 case LFUN_OUTLINE_DOWN:
722 toc::outline(toc::Down, cursor_);
723 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
724 updateLabels(buffer_);
726 case LFUN_OUTLINE_IN:
727 toc::outline(toc::In, cursor_);
728 updateLabels(buffer_);
730 case LFUN_OUTLINE_OUT:
731 toc::outline(toc::Out, cursor_);
732 updateLabels(buffer_);
736 bv_funcs::gotoInset(this, Inset::NOTE_CODE, false);
739 case LFUN_REFERENCE_NEXT: {
740 vector<Inset_code> tmp;
741 tmp.push_back(Inset::LABEL_CODE);
742 tmp.push_back(Inset::REF_CODE);
743 bv_funcs::gotoInset(this, tmp, true);
747 case LFUN_CHANGES_TRACK:
748 buffer_.params().trackChanges = !buffer_.params().trackChanges;
751 case LFUN_CHANGES_OUTPUT:
752 buffer_.params().outputChanges = !buffer_.params().outputChanges;
753 if (buffer_.params().outputChanges) {
754 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
755 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
756 LaTeXFeatures::isAvailable("xcolor");
758 if (!dvipost && !xcolorsoul) {
759 Alert::warning(_("Changes not shown in LaTeX output"),
760 _("Changes will not be highlighted in LaTeX output, "
761 "because neither dvipost nor xcolor/soul are installed.\n"
762 "Please install these packages or redefine "
763 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
764 } else if (!xcolorsoul) {
765 Alert::warning(_("Changes not shown in LaTeX output"),
766 _("Changes will not be highlighted in LaTeX output "
767 "when using pdflatex, because xcolor and soul are not installed.\n"
768 "Please install both packages or redefine "
769 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
774 case LFUN_CHANGE_NEXT:
775 findNextChange(this);
778 case LFUN_CHANGES_MERGE:
779 if (findNextChange(this))
780 showDialog("changes");
783 case LFUN_ALL_CHANGES_ACCEPT:
784 // select complete document
785 cursor_.reset(buffer_.inset());
786 cursor_.selHandle(true);
787 buffer_.text().cursorBottom(cursor_);
788 // accept everything in a single step to support atomic undo
789 buffer_.text().acceptOrRejectChanges(cursor_, Text::ACCEPT);
792 case LFUN_ALL_CHANGES_REJECT:
793 // select complete document
794 cursor_.reset(buffer_.inset());
795 cursor_.selHandle(true);
796 buffer_.text().cursorBottom(cursor_);
797 // reject everything in a single step to support atomic undo
798 // Note: reject does not work recursively; the user may have to repeat the operation
799 buffer_.text().acceptOrRejectChanges(cursor_, Text::REJECT);
806 case LFUN_WORD_REPLACE: {
807 bool has_deleted = false;
808 if (cur.selection()) {
809 DocIterator beg = cur.selectionBegin();
810 DocIterator end = cur.selectionEnd();
811 if (beg.pit() == end.pit()) {
812 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
813 if (cur.paragraph().isDeleted(p))
818 replace(this, cmd, has_deleted);
823 cur.clearSelection();
825 cur.message(from_utf8(N_("Mark off")));
829 cur.clearSelection();
832 cur.message(from_utf8(N_("Mark on")));
835 case LFUN_MARK_TOGGLE:
836 cur.clearSelection();
839 cur.message(from_utf8(N_("Mark removed")));
842 cur.message(from_utf8(N_("Mark set")));
847 case LFUN_SCREEN_RECENTER:
851 case LFUN_BIBTEX_DATABASE_ADD: {
852 Cursor tmpcur = cursor_;
853 bv_funcs::findInset(tmpcur, Inset::BIBTEX_CODE, false);
854 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
857 if (inset->addDatabase(to_utf8(cmd.argument())))
858 buffer_.updateBibfilesCache();
863 case LFUN_BIBTEX_DATABASE_DEL: {
864 Cursor tmpcur = cursor_;
865 bv_funcs::findInset(tmpcur, Inset::BIBTEX_CODE, false);
866 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
869 if (inset->delDatabase(to_utf8(cmd.argument())))
870 buffer_.updateBibfilesCache();
875 case LFUN_WORDS_COUNT: {
876 DocIterator from, to;
877 if (cur.selection()) {
878 from = cur.selectionBegin();
879 to = cur.selectionEnd();
881 from = doc_iterator_begin(buffer_.inset());
882 to = doc_iterator_end(buffer_.inset());
884 int const count = countWords(from, to);
888 message = bformat(_("%1$d words in selection."),
891 message = bformat(_("%1$d words in document."),
896 message = _("One word in selection.");
898 message = _("One word in document.");
901 Alert::information(_("Count words"), message);
905 case LFUN_BUFFER_TOGGLE_COMPRESSION:
906 // turn compression on/off
907 buffer_.params().compressed = !buffer_.params().compressed;
910 case LFUN_NEXT_INSET_TOGGLE: {
911 // this is the real function we want to invoke
912 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
913 // if there is an inset at cursor, see whether it
915 Inset * inset = cur.nextInset();
917 if (inset->isActive()) {
919 tmpcur.pushLeft(*inset);
920 inset->dispatch(tmpcur, tmpcmd);
921 if (tmpcur.result().dispatched()) {
924 } else if (inset->editable() == Inset::IS_EDITABLE) {
925 inset->edit(cur, true);
928 // if it did not work, try the underlying inset.
929 if (!cur.result().dispatched())
930 cur.dispatch(tmpcmd);
932 if (cur.result().dispatched())
933 cur.clearSelection();
939 updateFlags = Update::None;
946 docstring const BufferView::requestSelection()
948 Cursor & cur = cursor_;
950 if (!cur.selection()) {
951 xsel_cache_.set = false;
955 if (!xsel_cache_.set ||
956 cur.top() != xsel_cache_.cursor ||
957 cur.anchor_.top() != xsel_cache_.anchor)
959 xsel_cache_.cursor = cur.top();
960 xsel_cache_.anchor = cur.anchor_.top();
961 xsel_cache_.set = cur.selection();
962 return cur.selectionAsString(false);
968 void BufferView::clearSelection()
970 cursor_.clearSelection();
971 // Clear the selection buffer. Otherwise a subsequent
972 // middle-mouse-button paste would use the selection buffer,
973 // not the more current external selection.
974 cap::clearSelection();
975 xsel_cache_.set = false;
976 // The buffer did not really change, but this causes the
977 // redraw we need because we cleared the selection above.
982 void BufferView::resize(int width, int height)
984 // Update from work area
988 updateMetrics(false);
992 Inset const * BufferView::getCoveringInset(Text const & text, int x, int y)
994 pit_type pit = text_metrics_[&text].getPitNearY(y);
995 BOOST_ASSERT(pit != -1);
996 Paragraph const & par = text.getPar(pit);
999 << BOOST_CURRENT_FUNCTION
1004 InsetList::const_iterator iit = par.insetlist.begin();
1005 InsetList::const_iterator iend = par.insetlist.end();
1006 for (; iit != iend; ++iit) {
1007 Inset * const inset = iit->inset;
1008 if (inset->covers(*this, x, y)) {
1009 if (!inset->descendable())
1010 // No need to go further down if the inset is not
1014 size_t cell_number = inset->nargs();
1015 // Check all the inner cell.
1016 for (size_t i = 0; i != cell_number; ++i) {
1017 Text const * inner_text = inset->getText(i);
1020 Inset const * inset_deeper =
1021 getCoveringInset(*inner_text, x, y);
1023 return inset_deeper;
1027 LYXERR(Debug::DEBUG)
1028 << BOOST_CURRENT_FUNCTION
1029 << ": Hit inset: " << inset << endl;
1033 LYXERR(Debug::DEBUG)
1034 << BOOST_CURRENT_FUNCTION
1035 << ": No inset hit. " << endl;
1040 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1042 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1044 // This is only called for mouse related events including
1045 // LFUN_FILE_OPEN generated by drag-and-drop.
1046 FuncRequest cmd = cmd0;
1049 cur.push(buffer_.inset());
1050 cur.selection() = cursor_.selection();
1052 // Either the inset under the cursor or the
1053 // surrounding Text will handle this event.
1055 // make sure we stay within the screen...
1056 cmd.y = min(max(cmd.y, -1), height_);
1058 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1060 // Get inset under mouse, if there is one.
1061 Inset const * covering_inset =
1062 getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1063 if (covering_inset == last_inset_)
1064 // Same inset, no need to do anything...
1067 bool need_redraw = false;
1068 // const_cast because of setMouseHover().
1069 Inset * inset = const_cast<Inset *>(covering_inset);
1071 // Remove the hint on the last hovered inset (if any).
1072 need_redraw |= last_inset_->setMouseHover(false);
1074 // Highlighted the newly hovered inset (if any).
1075 need_redraw |= inset->setMouseHover(true);
1076 last_inset_ = inset;
1078 // if last metrics update was in singlepar mode, WorkArea::redraw() will
1079 // not expose the button for redraw. We adjust here the metrics dimension
1080 // to enable a full redraw.
1081 // FIXME: It is possible to redraw only the area around the button!
1083 && metrics_info_.update_strategy == SingleParUpdate) {
1084 // FIXME: It should be possible to redraw only the area around
1085 // the button by doing this:
1087 //metrics_info_.singlepar = false;
1088 //metrics_info_.y1 = ymin of button;
1089 //metrics_info_.y2 = ymax of button;
1091 // Unfortunately, BufferView::draw() does not distinguish
1092 // between background updates and text updates. So we use the hammer
1093 // solution for now. We could also avoid the updateMetrics() below
1094 // by using the first and last pit of the CoordCache. Have a look
1095 // at Text::getPitNearY() to see what I mean.
1097 //metrics_info_.pit1 = first pit of CoordCache;
1098 //metrics_info_.pit2 = last pit of CoordCache;
1099 //metrics_info_.singlepar = false;
1100 //metrics_info_.y1 = 0;
1101 //metrics_info_.y2 = height_;
1103 updateMetrics(false);
1106 // This event (moving without mouse click) is not passed further.
1107 // This should be changed if it is further utilized.
1111 // Build temporary cursor.
1112 Inset * inset = text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1114 // Put anchor at the same position.
1117 // Try to dispatch to an non-editable inset near this position
1118 // via the temp cursor. If the inset wishes to change the real
1119 // cursor it has to do so explicitly by using
1120 // cur.bv().cursor() = cur; (or similar)
1122 inset->dispatch(cur, cmd);
1125 // Now dispatch to the temporary cursor. If the real cursor should
1126 // be modified, the inset's dispatch has to do so explicitly.
1127 if (!cur.result().dispatched())
1130 //Do we have a selection?
1131 theSelection().haveSelection(cursor().selection());
1133 // Redraw if requested and necessary.
1134 if (cur.result().dispatched() && cur.result().update())
1135 return update(cur.result().update());
1141 void BufferView::scroll(int /*lines*/)
1143 // Text const * t = buffer_.text();
1144 // int const line_height = defaultRowHeight();
1146 // // The new absolute coordinate
1147 // int new_top_y = top_y() + lines * line_height;
1149 // // Restrict to a valid value
1150 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1151 // new_top_y = std::max(0, new_top_y);
1153 // scrollDocView(new_top_y);
1158 void BufferView::setCursorFromRow(int row)
1163 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1165 cursor_.reset(buffer_.inset());
1167 buffer_.text().setCursor(cursor_, 0, 0);
1169 buffer_.text().setCursor(cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1173 void BufferView::gotoLabel(docstring const & label)
1175 for (InsetIterator it = inset_iterator_begin(buffer_.inset()); it; ++it) {
1176 vector<docstring> labels;
1177 it->getLabelList(buffer_, labels);
1178 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1187 TextMetrics const & BufferView::textMetrics(Text const * t) const
1189 return const_cast<BufferView *>(this)->textMetrics(t);
1193 TextMetrics & BufferView::textMetrics(Text const * t)
1195 TextMetricsCache::iterator tmc_it = text_metrics_.find(t);
1196 if (tmc_it == text_metrics_.end()) {
1197 tmc_it = text_metrics_.insert(
1198 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1200 return tmc_it->second;
1204 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1207 return textMetrics(t).parMetrics(pit);
1211 int BufferView::workHeight() const
1217 void BufferView::setCursor(DocIterator const & dit)
1219 size_t const n = dit.depth();
1220 for (size_t i = 0; i < n; ++i)
1221 dit[i].inset().edit(cursor_, true);
1223 cursor_.setCursor(dit);
1224 cursor_.selection() = false;
1228 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1230 // Would be wrong to delete anything if we have a selection.
1231 if (cur.selection())
1234 bool need_anchor_change = false;
1235 bool changed = cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1236 need_anchor_change);
1238 if (need_anchor_change)
1244 updateLabels(buffer_);
1246 updateMetrics(false);
1252 bool BufferView::mouseSetCursor(Cursor & cur)
1254 BOOST_ASSERT(&cur.bv() == this);
1256 // this event will clear selection so we save selection for
1257 // persistent selection
1258 cap::saveSelection(cursor());
1260 // Has the cursor just left the inset?
1261 bool badcursor = false;
1262 bool leftinset = (&cursor_.inset() != &cur.inset());
1264 badcursor = notifyCursorLeaves(cursor_, cur);
1266 // do the dEPM magic if needed
1267 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1268 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1269 // the leftinset bool would not be necessary (badcursor instead).
1270 bool update = leftinset;
1271 if (!badcursor && cursor_.inTexted())
1272 update |= checkDepm(cur, cursor_);
1274 // if the cursor was in an empty script inset and the new
1275 // position is in the nucleus of the inset, notifyCursorLeaves
1276 // will kill the script inset itself. So we check all the
1277 // elements of the cursor to make sure that they are correct.
1278 // For an example, see bug 2933:
1279 // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1280 // The code below could maybe be moved to a DocIterator method.
1281 //lyxerr << "cur before " << cur <<std::endl;
1282 DocIterator dit(cur.inset());
1283 dit.push_back(cur.bottom());
1285 while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1286 dit.push_back(cur[i]);
1289 //lyxerr << "5 cur after" << dit <<std::endl;
1291 cursor_.setCursor(dit);
1292 cursor_.boundary(cur.boundary());
1293 cursor_.clearSelection();
1299 void BufferView::putSelectionAt(DocIterator const & cur,
1300 int length, bool backwards)
1302 cursor_.clearSelection();
1308 cursor_.pos() += length;
1309 cursor_.setSelection(cursor_, -length);
1311 cursor_.setSelection(cursor_, length);
1316 Cursor & BufferView::cursor()
1322 Cursor const & BufferView::cursor() const
1328 pit_type BufferView::anchor_ref() const
1334 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1336 return metrics_info_;
1340 // FIXME: We should split-up updateMetrics() for the singlepar case.
1341 void BufferView::updateMetrics(bool singlepar)
1343 Text & buftext = buffer_.text();
1344 pit_type const npit = int(buftext.paragraphs().size());
1346 if (anchor_ref_ > int(npit - 1)) {
1347 anchor_ref_ = int(npit - 1);
1352 // Clear out the position cache in case of full screen redraw,
1353 coord_cache_.clear();
1355 // Clear out paragraph metrics to avoid having invalid metrics
1356 // in the cache from paragraphs not relayouted below
1357 // The complete text metrics will be redone.
1358 text_metrics_.clear();
1361 TextMetrics & tm = textMetrics(&buftext);
1363 pit_type const bottom_pit = cursor_.bottom().pit();
1364 // If the paragraph metrics has changed, we can not
1365 // use the singlepar optimisation.
1367 // In Single Paragraph mode, rebreak only
1368 // the (main text, not inset!) paragraph containing the cursor.
1369 // (if this paragraph contains insets etc., rebreaking will
1370 // recursively descend)
1371 && !tm.redoParagraph(bottom_pit)) {
1374 // collect cursor paragraph iter bounds
1375 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
1376 int y1 = pm.position() - pm.ascent();
1377 int y2 = pm.position() + pm.descent();
1378 metrics_info_ = ViewMetricsInfo(bottom_pit, bottom_pit, y1, y2,
1379 SingleParUpdate, npit);
1380 LYXERR(Debug::PAINTING)
1381 << BOOST_CURRENT_FUNCTION
1384 << " pit: " << bottom_pit
1385 << " singlepar: " << singlepar
1390 pit_type const pit = anchor_ref_;
1394 // Rebreak anchor paragraph.
1395 tm.redoParagraph(pit);
1399 int y0 = tm.parMetrics(pit).ascent() - offset_ref_;
1401 // Redo paragraphs above anchor if necessary.
1403 while (y1 > 0 && pit1 > 0) {
1404 y1 -= tm.parMetrics(pit1).ascent();
1406 tm.redoParagraph(pit1);
1407 y1 -= tm.parMetrics(pit1).descent();
1410 // Take care of ascent of first line
1411 y1 -= tm.parMetrics(pit1).ascent();
1413 // Normalize anchor for next time
1417 // Grey at the beginning is ugly
1418 if (pit1 == 0 && y1 > 0) {
1424 // Redo paragraphs below the anchor if necessary.
1426 while (y2 < height_ && pit2 < int(npit) - 1) {
1427 y2 += tm.parMetrics(pit2).descent();
1429 tm.redoParagraph(pit2);
1430 y2 += tm.parMetrics(pit2).ascent();
1433 // Take care of descent of last line
1434 y2 += tm.parMetrics(pit2).descent();
1436 LYXERR(Debug::PAINTING)
1437 << BOOST_CURRENT_FUNCTION
1440 << " pit1: " << pit1
1441 << " pit2: " << pit2
1442 << " npit: " << npit
1443 << " singlepar: " << singlepar
1446 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2,
1447 FullScreenUpdate, npit);
1449 if (lyxerr.debugging(Debug::WORKAREA)) {
1450 LYXERR(Debug::WORKAREA) << "BufferView::updateMetrics" << endl;
1451 coord_cache_.dump();
1456 void BufferView::menuInsertLyXFile(string const & filenm)
1458 BOOST_ASSERT(cursor_.inTexted());
1459 string filename = filenm;
1461 if (filename.empty()) {
1462 // Launch a file browser
1464 string initpath = lyxrc.document_path;
1465 string const trypath = buffer_.filePath();
1466 // If directory is writeable, use this as default.
1467 if (isDirWriteable(FileName(trypath)))
1471 FileDialog fileDlg(_("Select LyX document to insert"),
1473 make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1474 make_pair(_("Examples|#E#e"),
1475 from_utf8(addPath(package().system_support().absFilename(),
1478 FileDialog::Result result =
1479 fileDlg.open(from_utf8(initpath),
1480 FileFilterList(_("LyX Documents (*.lyx)")),
1483 if (result.first == FileDialog::Later)
1487 filename = to_utf8(result.second);
1489 // check selected filename
1490 if (filename.empty()) {
1491 // emit message signal.
1492 message(_("Canceled."));
1497 // Get absolute path of file and add ".lyx"
1498 // to the filename if necessary
1499 filename = fileSearch(string(), filename, "lyx").absFilename();
1501 docstring const disp_fn = makeDisplayPath(filename);
1502 // emit message signal.
1503 message(bformat(_("Inserting document %1$s..."), disp_fn));
1506 Buffer buf("", false);
1507 if (lyx::loadLyXFile(&buf, FileName(filename))) {
1508 ErrorList & el = buffer_.errorList("Parse");
1509 // Copy the inserted document error list into the current buffer one.
1510 el = buf.errorList("Parse");
1511 recordUndo(cursor_);
1512 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1513 buf.params().getTextClass_ptr(), el);
1514 res = _("Document %1$s inserted.");
1516 res = _("Could not insert document %1$s");
1518 // emit message signal.
1519 message(bformat(res, disp_fn));
1520 buffer_.errors("Parse");
1521 updateMetrics(false);
1525 void BufferView::draw(frontend::Painter & pain)
1527 PainterInfo pi(this, pain);
1528 // Should the whole screen, including insets, be refreshed?
1529 // FIXME: We should also distinguish DecorationUpdate to avoid text
1530 // drawing if possible. This is not possible to do easily right now
1531 // because of the single backing pixmap.
1532 pi.full_repaint = metrics_info_.update_strategy != SingleParUpdate;
1534 if (pi.full_repaint)
1535 // Clear background (if not delegated to rows)
1536 pain.fillRectangle(0, metrics_info_.y1, width_,
1537 metrics_info_.y2 - metrics_info_.y1,
1538 buffer_.inset().backgroundColor());
1540 LYXERR(Debug::PAINTING) << "\t\t*** START DRAWING ***" << endl;
1541 Text & text = buffer_.text();
1542 TextMetrics const & tm = text_metrics_[&text];
1543 int y = metrics_info_.y1 + tm.parMetrics(metrics_info_.p1).ascent();
1544 if (!pi.full_repaint)
1545 tm.drawParagraph(pi, metrics_info_.p1, 0, y);
1548 LYXERR(Debug::PAINTING) << "\n\t\t*** END DRAWING ***" << endl;
1550 // and grey out above (should not happen later)
1551 // lyxerr << "par ascent: " << text.getPar(metrics_info_.p1).ascent() << endl;
1552 if (metrics_info_.y1 > 0
1553 && metrics_info_.update_strategy == FullScreenUpdate)
1554 pain.fillRectangle(0, 0, width_, metrics_info_.y1, Color::bottomarea);
1556 // and possibly grey out below
1557 // lyxerr << "par descent: " << text.getPar(metrics_info_.p1).ascent() << endl;
1558 if (metrics_info_.y2 < height_
1559 && metrics_info_.update_strategy == FullScreenUpdate)
1560 pain.fillRectangle(0, metrics_info_.y2, width_,
1561 height_ - metrics_info_.y2, Color::bottomarea);