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);
346 void BufferView::setCursorFromScrollbar()
348 TextMetrics & tm = text_metrics_[&buffer_.text()];
350 int const height = 2 * defaultRowHeight();
351 int const first = height;
352 int const last = height_ - height;
353 Cursor & cur = cursor_;
355 bv_funcs::CurStatus st = bv_funcs::status(this, cur);
358 case bv_funcs::CUR_ABOVE:
359 // We reset the cursor because bv_funcs::status() does not
360 // work when the cursor is within mathed.
361 cur.reset(buffer_.inset());
362 tm.setCursorFromCoordinates(cur, 0, first);
363 cur.clearSelection();
365 case bv_funcs::CUR_BELOW:
366 // We reset the cursor because bv_funcs::status() does not
367 // work when the cursor is within mathed.
368 cur.reset(buffer_.inset());
369 tm.setCursorFromCoordinates(cur, 0, last);
370 cur.clearSelection();
372 case bv_funcs::CUR_INSIDE:
373 int const y = bv_funcs::getPos(*this, cur, cur.boundary()).y_;
374 int const newy = min(last, max(y, first));
376 cur.reset(buffer_.inset());
377 tm.setCursorFromCoordinates(cur, 0, newy);
383 Change const BufferView::getCurrentChange() const
385 if (!cursor_.selection())
386 return Change(Change::UNCHANGED);
388 DocIterator dit = cursor_.selectionBegin();
389 return dit.paragraph().lookupChange(dit.pos());
393 void BufferView::saveBookmark(unsigned int idx)
395 // tenatively save bookmark, id and pos will be used to
396 // acturately locate a bookmark in a 'live' lyx session.
397 // pit and pos will be updated with bottom level pit/pos
399 LyX::ref().session().bookmarks().save(
400 FileName(buffer_.fileName()),
401 cursor_.bottom().pit(),
402 cursor_.bottom().pos(),
403 cursor_.paragraph().id(),
408 // emit message signal.
409 message(_("Save bookmark"));
413 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
414 int top_id, pos_type top_pos)
416 bool success = false;
419 cursor_.clearSelection();
421 // if a valid par_id is given, try it first
422 // This is the case for a 'live' bookmark when unique paragraph ID
423 // is used to track bookmarks.
425 ParIterator par = buffer_.getParFromID(top_id);
426 if (par != buffer_.par_iterator_end()) {
427 doc_it = makeDocIterator(par, min(par->size(), top_pos));
428 // Some slices of the iterator may not be
429 // reachable (e.g. closed collapsable inset)
430 // so the dociterator may need to be
431 // shortened. Otherwise, setCursor may crash
432 // lyx when the cursor can not be set to these
434 size_t const n = doc_it.depth();
435 for (size_t i = 0; i < n; ++i)
436 if (doc_it[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
444 // if top_id == 0, or searching through top_id failed
445 // This is the case for a 'restored' bookmark when only bottom
446 // (document level) pit was saved. Because of this, bookmark
447 // restoration is inaccurate. If a bookmark was within an inset,
448 // it will be restored to the left of the outmost inset that contains
450 if (static_cast<size_t>(bottom_pit) < buffer_.paragraphs().size()) {
451 doc_it = doc_iterator_begin(buffer_.inset());
452 doc_it.pit() = bottom_pit;
453 doc_it.pos() = min(bottom_pos, doc_it.paragraph().size());
458 // Note: only bottom (document) level pit is set.
460 // set the current font.
461 cursor_.setCurrentFont();
462 // center the screen on this new position.
470 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
472 if (lyxrc.rtl_support) {
473 if (cursor_.real_current_font.isRightToLeft()) {
474 if (intl_->keymap == Intl::PRIMARY)
477 if (intl_->keymap == Intl::SECONDARY)
482 intl_->getTransManager().translateAndInsert(c, t, cur);
486 int BufferView::workWidth() const
492 void BufferView::updateOffsetRef()
494 // No need to update offset_ref_ in this case.
495 if (!need_centering_)
498 // We are not properly started yet, delay until resizing is
503 CursorSlice & bot = cursor_.bottom();
504 TextMetrics & tm = text_metrics_[bot.text()];
505 ParagraphMetrics const & pm = tm.parMetrics(bot.pit());
506 Point p = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary());
507 offset_ref_ = p.y_ + pm.ascent() - height_ / 2;
509 need_centering_ = false;
513 void BufferView::center()
515 anchor_ref_ = cursor_.bottom().pit();
516 need_centering_ = true;
520 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
524 Cursor & cur = cursor_;
526 switch (cmd.action) {
529 flag.enabled(!buffer_.undostack().empty());
532 flag.enabled(!buffer_.redostack().empty());
534 case LFUN_FILE_INSERT:
535 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
536 case LFUN_FILE_INSERT_PLAINTEXT:
537 case LFUN_BOOKMARK_SAVE:
538 // FIXME: Actually, these LFUNS should be moved to Text
539 flag.enabled(cur.inTexted());
541 case LFUN_FONT_STATE:
542 case LFUN_LABEL_INSERT:
543 case LFUN_PARAGRAPH_GOTO:
544 // FIXME handle non-trivially
545 case LFUN_OUTLINE_UP:
546 case LFUN_OUTLINE_DOWN:
547 case LFUN_OUTLINE_IN:
548 case LFUN_OUTLINE_OUT:
550 case LFUN_REFERENCE_NEXT:
552 case LFUN_WORD_REPLACE:
555 case LFUN_MARK_TOGGLE:
556 case LFUN_SCREEN_RECENTER:
557 case LFUN_BIBTEX_DATABASE_ADD:
558 case LFUN_BIBTEX_DATABASE_DEL:
559 case LFUN_WORDS_COUNT:
560 case LFUN_NEXT_INSET_TOGGLE:
564 case LFUN_LABEL_GOTO: {
565 flag.enabled(!cmd.argument().empty()
566 || getInsetByCode<InsetRef>(cur, Inset::REF_CODE));
570 case LFUN_CHANGES_TRACK:
572 flag.setOnOff(buffer_.params().trackChanges);
575 case LFUN_CHANGES_OUTPUT:
577 flag.setOnOff(buffer_.params().outputChanges);
580 case LFUN_CHANGES_MERGE:
581 case LFUN_CHANGE_NEXT:
582 case LFUN_ALL_CHANGES_ACCEPT:
583 case LFUN_ALL_CHANGES_REJECT:
584 // TODO: context-sensitive enabling of LFUNs
585 // In principle, these command should only be enabled if there
586 // is a change in the document. However, without proper
587 // optimizations, this will inevitably result in poor performance.
591 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
592 flag.setOnOff(buffer_.params().compressed);
597 case LFUN_SCREEN_DOWN:
601 // FIXME: LFUN_SCREEN_DOWN_SELECT should be removed from
602 // everywhere else before this can enabled:
603 case LFUN_SCREEN_UP_SELECT:
604 case LFUN_SCREEN_DOWN_SELECT:
616 Update::flags BufferView::dispatch(FuncRequest const & cmd)
618 //lyxerr << BOOST_CURRENT_FUNCTION
619 // << [ cmd = " << cmd << "]" << endl;
621 // Make sure that the cached BufferView is correct.
622 LYXERR(Debug::ACTION) << BOOST_CURRENT_FUNCTION
623 << " action[" << cmd.action << ']'
624 << " arg[" << to_utf8(cmd.argument()) << ']'
625 << " x[" << cmd.x << ']'
626 << " y[" << cmd.y << ']'
627 << " button[" << cmd.button() << ']'
630 Cursor & cur = cursor_;
631 // Default Update flags.
632 Update::flags updateFlags = Update::Force | Update::FitCursor;
634 switch (cmd.action) {
637 cur.message(_("Undo"));
638 cur.clearSelection();
639 if (!textUndo(*this)) {
640 cur.message(_("No further undo information"));
641 updateFlags = Update::None;
646 cur.message(_("Redo"));
647 cur.clearSelection();
648 if (!textRedo(*this)) {
649 cur.message(_("No further redo information"));
650 updateFlags = Update::None;
654 case LFUN_FILE_INSERT:
656 menuInsertLyXFile(to_utf8(cmd.argument()));
659 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
661 insertPlaintextFile(this, to_utf8(cmd.argument()), true);
664 case LFUN_FILE_INSERT_PLAINTEXT:
666 insertPlaintextFile(this, to_utf8(cmd.argument()), false);
669 case LFUN_FONT_STATE:
670 cur.message(cur.currentState());
673 case LFUN_BOOKMARK_SAVE:
674 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
677 case LFUN_LABEL_GOTO: {
678 docstring label = cmd.argument();
681 getInsetByCode<InsetRef>(cursor_,
684 label = inset->getParam("reference");
685 // persistent=false: use temp_bookmark
695 case LFUN_PARAGRAPH_GOTO: {
696 int const id = convert<int>(to_utf8(cmd.argument()));
698 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
699 b = theBufferList().next(b)) {
701 ParIterator par = b->getParFromID(id);
702 if (par == b->par_iterator_end()) {
704 << "No matching paragraph found! ["
705 << id << "]." << endl;
708 << "Paragraph " << par->id()
709 << " found in buffer `"
710 << b->fileName() << "'." << endl;
714 setCursor(makeDocIterator(par, 0));
716 // Switch to other buffer view and resend cmd
717 theLyXFunc().dispatch(FuncRequest(
718 LFUN_BUFFER_SWITCH, b->fileName()));
719 theLyXFunc().dispatch(cmd);
720 updateFlags = Update::None;
729 case LFUN_OUTLINE_UP:
730 toc::outline(toc::Up, cursor_);
731 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
732 updateLabels(buffer_);
734 case LFUN_OUTLINE_DOWN:
735 toc::outline(toc::Down, cursor_);
736 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
737 updateLabels(buffer_);
739 case LFUN_OUTLINE_IN:
740 toc::outline(toc::In, cursor_);
741 updateLabels(buffer_);
743 case LFUN_OUTLINE_OUT:
744 toc::outline(toc::Out, cursor_);
745 updateLabels(buffer_);
749 bv_funcs::gotoInset(this, Inset::NOTE_CODE, false);
752 case LFUN_REFERENCE_NEXT: {
753 vector<Inset_code> tmp;
754 tmp.push_back(Inset::LABEL_CODE);
755 tmp.push_back(Inset::REF_CODE);
756 bv_funcs::gotoInset(this, tmp, true);
760 case LFUN_CHANGES_TRACK:
761 buffer_.params().trackChanges = !buffer_.params().trackChanges;
764 case LFUN_CHANGES_OUTPUT:
765 buffer_.params().outputChanges = !buffer_.params().outputChanges;
766 if (buffer_.params().outputChanges) {
767 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
768 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
769 LaTeXFeatures::isAvailable("xcolor");
771 if (!dvipost && !xcolorsoul) {
772 Alert::warning(_("Changes not shown in LaTeX output"),
773 _("Changes will not be highlighted in LaTeX output, "
774 "because neither dvipost nor xcolor/soul are installed.\n"
775 "Please install these packages or redefine "
776 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
777 } else if (!xcolorsoul) {
778 Alert::warning(_("Changes not shown in LaTeX output"),
779 _("Changes will not be highlighted in LaTeX output "
780 "when using pdflatex, because xcolor and soul are not installed.\n"
781 "Please install both packages or redefine "
782 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
787 case LFUN_CHANGE_NEXT:
788 findNextChange(this);
791 case LFUN_CHANGES_MERGE:
792 if (findNextChange(this))
793 showDialog("changes");
796 case LFUN_ALL_CHANGES_ACCEPT:
797 // select complete document
798 cursor_.reset(buffer_.inset());
799 cursor_.selHandle(true);
800 buffer_.text().cursorBottom(cursor_);
801 // accept everything in a single step to support atomic undo
802 buffer_.text().acceptOrRejectChanges(cursor_, Text::ACCEPT);
805 case LFUN_ALL_CHANGES_REJECT:
806 // select complete document
807 cursor_.reset(buffer_.inset());
808 cursor_.selHandle(true);
809 buffer_.text().cursorBottom(cursor_);
810 // reject everything in a single step to support atomic undo
811 // Note: reject does not work recursively; the user may have to repeat the operation
812 buffer_.text().acceptOrRejectChanges(cursor_, Text::REJECT);
819 case LFUN_WORD_REPLACE: {
820 bool has_deleted = false;
821 if (cur.selection()) {
822 DocIterator beg = cur.selectionBegin();
823 DocIterator end = cur.selectionEnd();
824 if (beg.pit() == end.pit()) {
825 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
826 if (cur.paragraph().isDeleted(p))
831 replace(this, cmd, has_deleted);
836 cur.clearSelection();
838 cur.message(from_utf8(N_("Mark off")));
842 cur.clearSelection();
845 cur.message(from_utf8(N_("Mark on")));
848 case LFUN_MARK_TOGGLE:
849 cur.clearSelection();
852 cur.message(from_utf8(N_("Mark removed")));
855 cur.message(from_utf8(N_("Mark set")));
860 case LFUN_SCREEN_RECENTER:
864 case LFUN_BIBTEX_DATABASE_ADD: {
865 Cursor tmpcur = cursor_;
866 bv_funcs::findInset(tmpcur, Inset::BIBTEX_CODE, false);
867 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
870 if (inset->addDatabase(to_utf8(cmd.argument())))
871 buffer_.updateBibfilesCache();
876 case LFUN_BIBTEX_DATABASE_DEL: {
877 Cursor tmpcur = cursor_;
878 bv_funcs::findInset(tmpcur, Inset::BIBTEX_CODE, false);
879 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
882 if (inset->delDatabase(to_utf8(cmd.argument())))
883 buffer_.updateBibfilesCache();
888 case LFUN_WORDS_COUNT: {
889 DocIterator from, to;
890 if (cur.selection()) {
891 from = cur.selectionBegin();
892 to = cur.selectionEnd();
894 from = doc_iterator_begin(buffer_.inset());
895 to = doc_iterator_end(buffer_.inset());
897 int const count = countWords(from, to);
901 message = bformat(_("%1$d words in selection."),
904 message = bformat(_("%1$d words in document."),
909 message = _("One word in selection.");
911 message = _("One word in document.");
914 Alert::information(_("Count words"), message);
918 case LFUN_BUFFER_TOGGLE_COMPRESSION:
919 // turn compression on/off
920 buffer_.params().compressed = !buffer_.params().compressed;
923 case LFUN_NEXT_INSET_TOGGLE: {
924 // this is the real function we want to invoke
925 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
926 // if there is an inset at cursor, see whether it
928 Inset * inset = cur.nextInset();
930 if (inset->isActive()) {
932 tmpcur.pushLeft(*inset);
933 inset->dispatch(tmpcur, tmpcmd);
934 if (tmpcur.result().dispatched()) {
937 } else if (inset->editable() == Inset::IS_EDITABLE) {
938 inset->edit(cur, true);
941 // if it did not work, try the underlying inset.
942 if (!cur.result().dispatched())
943 cur.dispatch(tmpcmd);
945 if (cur.result().dispatched())
946 cur.clearSelection();
952 case LFUN_SCREEN_DOWN: {
953 Point const p = bv_funcs::getPos(*this, cur, cur.boundary());
954 scroll(cmd.action == LFUN_SCREEN_UP? - height_ : height_);
955 cur.reset(buffer_.inset());
956 text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
957 //FIXME: what to do with cur.x_target()?
959 // The metrics are already up to date. see scroll()
960 updateFlags = Update::None;
964 case LFUN_SCREEN_UP_SELECT:
965 case LFUN_SCREEN_DOWN_SELECT: {
967 size_t initial_depth = cur.depth();
968 Point const p = bv_funcs::getPos(*this, cur, cur.boundary());
969 scroll(cmd.action == LFUN_SCREEN_UP_SELECT? - height_ : height_);
970 // FIXME: We need to verify if the cursor stayed within an inset...
971 //cur.reset(buffer_.inset());
972 text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
974 while (cur.depth() > initial_depth) {
977 // FIXME: we need to do a redraw again because of the selection
979 updateFlags = Update::Force | Update::FitCursor;
984 updateFlags = Update::None;
991 docstring const BufferView::requestSelection()
993 Cursor & cur = cursor_;
995 if (!cur.selection()) {
996 xsel_cache_.set = false;
1000 if (!xsel_cache_.set ||
1001 cur.top() != xsel_cache_.cursor ||
1002 cur.anchor_.top() != xsel_cache_.anchor)
1004 xsel_cache_.cursor = cur.top();
1005 xsel_cache_.anchor = cur.anchor_.top();
1006 xsel_cache_.set = cur.selection();
1007 return cur.selectionAsString(false);
1013 void BufferView::clearSelection()
1015 cursor_.clearSelection();
1016 // Clear the selection buffer. Otherwise a subsequent
1017 // middle-mouse-button paste would use the selection buffer,
1018 // not the more current external selection.
1019 cap::clearSelection();
1020 xsel_cache_.set = false;
1021 // The buffer did not really change, but this causes the
1022 // redraw we need because we cleared the selection above.
1027 void BufferView::resize(int width, int height)
1029 // Update from work area
1033 updateMetrics(false);
1037 Inset const * BufferView::getCoveringInset(Text const & text, int x, int y)
1039 pit_type pit = text_metrics_[&text].getPitNearY(y);
1040 BOOST_ASSERT(pit != -1);
1041 Paragraph const & par = text.getPar(pit);
1043 LYXERR(Debug::DEBUG)
1044 << BOOST_CURRENT_FUNCTION
1049 InsetList::const_iterator iit = par.insetlist.begin();
1050 InsetList::const_iterator iend = par.insetlist.end();
1051 for (; iit != iend; ++iit) {
1052 Inset * const inset = iit->inset;
1053 if (inset->covers(*this, x, y)) {
1054 if (!inset->descendable())
1055 // No need to go further down if the inset is not
1059 size_t cell_number = inset->nargs();
1060 // Check all the inner cell.
1061 for (size_t i = 0; i != cell_number; ++i) {
1062 Text const * inner_text = inset->getText(i);
1065 Inset const * inset_deeper =
1066 getCoveringInset(*inner_text, x, y);
1068 return inset_deeper;
1072 LYXERR(Debug::DEBUG)
1073 << BOOST_CURRENT_FUNCTION
1074 << ": Hit inset: " << inset << endl;
1078 LYXERR(Debug::DEBUG)
1079 << BOOST_CURRENT_FUNCTION
1080 << ": No inset hit. " << endl;
1085 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1087 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1089 // This is only called for mouse related events including
1090 // LFUN_FILE_OPEN generated by drag-and-drop.
1091 FuncRequest cmd = cmd0;
1094 cur.push(buffer_.inset());
1095 cur.selection() = cursor_.selection();
1097 // Either the inset under the cursor or the
1098 // surrounding Text will handle this event.
1100 // make sure we stay within the screen...
1101 cmd.y = min(max(cmd.y, -1), height_);
1103 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1105 // Get inset under mouse, if there is one.
1106 Inset const * covering_inset =
1107 getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1108 if (covering_inset == last_inset_)
1109 // Same inset, no need to do anything...
1112 bool need_redraw = false;
1113 // const_cast because of setMouseHover().
1114 Inset * inset = const_cast<Inset *>(covering_inset);
1116 // Remove the hint on the last hovered inset (if any).
1117 need_redraw |= last_inset_->setMouseHover(false);
1119 // Highlighted the newly hovered inset (if any).
1120 need_redraw |= inset->setMouseHover(true);
1121 last_inset_ = inset;
1123 // if last metrics update was in singlepar mode, WorkArea::redraw() will
1124 // not expose the button for redraw. We adjust here the metrics dimension
1125 // to enable a full redraw.
1126 // FIXME: It is possible to redraw only the area around the button!
1128 && metrics_info_.update_strategy == SingleParUpdate) {
1129 // FIXME: It should be possible to redraw only the area around
1130 // the button by doing this:
1132 //metrics_info_.singlepar = false;
1133 //metrics_info_.y1 = ymin of button;
1134 //metrics_info_.y2 = ymax of button;
1136 // Unfortunately, BufferView::draw() does not distinguish
1137 // between background updates and text updates. So we use the hammer
1138 // solution for now. We could also avoid the updateMetrics() below
1139 // by using the first and last pit of the CoordCache. Have a look
1140 // at Text::getPitNearY() to see what I mean.
1142 //metrics_info_.pit1 = first pit of CoordCache;
1143 //metrics_info_.pit2 = last pit of CoordCache;
1144 //metrics_info_.singlepar = false;
1145 //metrics_info_.y1 = 0;
1146 //metrics_info_.y2 = height_;
1148 updateMetrics(false);
1151 // This event (moving without mouse click) is not passed further.
1152 // This should be changed if it is further utilized.
1156 // Build temporary cursor.
1157 Inset * inset = text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1159 // Put anchor at the same position.
1162 // Try to dispatch to an non-editable inset near this position
1163 // via the temp cursor. If the inset wishes to change the real
1164 // cursor it has to do so explicitly by using
1165 // cur.bv().cursor() = cur; (or similar)
1167 inset->dispatch(cur, cmd);
1170 // Now dispatch to the temporary cursor. If the real cursor should
1171 // be modified, the inset's dispatch has to do so explicitly.
1172 if (!cur.result().dispatched())
1175 //Do we have a selection?
1176 theSelection().haveSelection(cursor().selection());
1178 // Redraw if requested and necessary.
1179 if (cur.result().dispatched() && cur.result().update())
1180 return update(cur.result().update());
1186 void BufferView::scroll(int y)
1195 void BufferView::scrollDown(int offset)
1197 Text * text = &buffer_.text();
1198 TextMetrics & tm = text_metrics_[text];
1199 int ymax = height_ + offset;
1201 std::pair<pit_type, ParagraphMetrics> const & last = tm.last();
1202 int bottom_pos = last.second.position() + last.second.descent();
1203 if (last.first == text->paragraphs().size() - 1) {
1204 if (bottom_pos <= height_)
1206 offset = min(offset, bottom_pos - height_);
1209 if (bottom_pos > ymax)
1211 tm.newParMetricsDown();
1213 offset_ref_ += offset;
1214 updateMetrics(false);
1219 void BufferView::scrollUp(int offset)
1221 Text * text = &buffer_.text();
1222 TextMetrics & tm = text_metrics_[text];
1223 int ymin = - offset;
1225 std::pair<pit_type, ParagraphMetrics> const & first = tm.first();
1226 int top_pos = first.second.position() - first.second.ascent();
1227 if (first.first == 0) {
1230 offset = min(offset, - top_pos);
1235 tm.newParMetricsUp();
1237 offset_ref_ -= offset;
1238 updateMetrics(false);
1243 void BufferView::setCursorFromRow(int row)
1248 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1250 cursor_.reset(buffer_.inset());
1252 buffer_.text().setCursor(cursor_, 0, 0);
1254 buffer_.text().setCursor(cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1258 void BufferView::gotoLabel(docstring const & label)
1260 for (InsetIterator it = inset_iterator_begin(buffer_.inset()); it; ++it) {
1261 vector<docstring> labels;
1262 it->getLabelList(buffer_, labels);
1263 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1272 TextMetrics const & BufferView::textMetrics(Text const * t) const
1274 return const_cast<BufferView *>(this)->textMetrics(t);
1278 TextMetrics & BufferView::textMetrics(Text const * t)
1280 TextMetricsCache::iterator tmc_it = text_metrics_.find(t);
1281 if (tmc_it == text_metrics_.end()) {
1282 tmc_it = text_metrics_.insert(
1283 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1285 return tmc_it->second;
1289 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1292 return textMetrics(t).parMetrics(pit);
1296 int BufferView::workHeight() const
1302 void BufferView::setCursor(DocIterator const & dit)
1304 size_t const n = dit.depth();
1305 for (size_t i = 0; i < n; ++i)
1306 dit[i].inset().edit(cursor_, true);
1308 cursor_.setCursor(dit);
1309 cursor_.selection() = false;
1313 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1315 // Would be wrong to delete anything if we have a selection.
1316 if (cur.selection())
1319 bool need_anchor_change = false;
1320 bool changed = cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1321 need_anchor_change);
1323 if (need_anchor_change)
1329 updateLabels(buffer_);
1331 updateMetrics(false);
1337 bool BufferView::mouseSetCursor(Cursor & cur)
1339 BOOST_ASSERT(&cur.bv() == this);
1341 // this event will clear selection so we save selection for
1342 // persistent selection
1343 cap::saveSelection(cursor());
1345 // Has the cursor just left the inset?
1346 bool badcursor = false;
1347 bool leftinset = (&cursor_.inset() != &cur.inset());
1349 badcursor = notifyCursorLeaves(cursor_, cur);
1351 // do the dEPM magic if needed
1352 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1353 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1354 // the leftinset bool would not be necessary (badcursor instead).
1355 bool update = leftinset;
1356 if (!badcursor && cursor_.inTexted())
1357 update |= checkDepm(cur, cursor_);
1359 // if the cursor was in an empty script inset and the new
1360 // position is in the nucleus of the inset, notifyCursorLeaves
1361 // will kill the script inset itself. So we check all the
1362 // elements of the cursor to make sure that they are correct.
1363 // For an example, see bug 2933:
1364 // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1365 // The code below could maybe be moved to a DocIterator method.
1366 //lyxerr << "cur before " << cur <<std::endl;
1367 DocIterator dit(cur.inset());
1368 dit.push_back(cur.bottom());
1370 while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1371 dit.push_back(cur[i]);
1374 //lyxerr << "5 cur after" << dit <<std::endl;
1376 cursor_.setCursor(dit);
1377 cursor_.boundary(cur.boundary());
1378 cursor_.clearSelection();
1384 void BufferView::putSelectionAt(DocIterator const & cur,
1385 int length, bool backwards)
1387 cursor_.clearSelection();
1393 cursor_.pos() += length;
1394 cursor_.setSelection(cursor_, -length);
1396 cursor_.setSelection(cursor_, length);
1401 Cursor & BufferView::cursor()
1407 Cursor const & BufferView::cursor() const
1413 pit_type BufferView::anchor_ref() const
1419 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1421 return metrics_info_;
1425 // FIXME: We should split-up updateMetrics() for the singlepar case.
1426 void BufferView::updateMetrics(bool singlepar)
1428 Text & buftext = buffer_.text();
1429 pit_type const npit = int(buftext.paragraphs().size());
1431 if (anchor_ref_ > int(npit - 1)) {
1432 anchor_ref_ = int(npit - 1);
1437 // Clear out the position cache in case of full screen redraw,
1438 coord_cache_.clear();
1440 // Clear out paragraph metrics to avoid having invalid metrics
1441 // in the cache from paragraphs not relayouted below
1442 // The complete text metrics will be redone.
1443 text_metrics_.clear();
1446 TextMetrics & tm = textMetrics(&buftext);
1448 pit_type const bottom_pit = cursor_.bottom().pit();
1449 // If the paragraph metrics has changed, we can not
1450 // use the singlepar optimisation.
1452 // In Single Paragraph mode, rebreak only
1453 // the (main text, not inset!) paragraph containing the cursor.
1454 // (if this paragraph contains insets etc., rebreaking will
1455 // recursively descend)
1456 && !tm.redoParagraph(bottom_pit)) {
1459 // collect cursor paragraph iter bounds
1460 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
1461 int y1 = pm.position() - pm.ascent();
1462 int y2 = pm.position() + pm.descent();
1463 metrics_info_ = ViewMetricsInfo(bottom_pit, bottom_pit, y1, y2,
1464 SingleParUpdate, npit);
1465 LYXERR(Debug::PAINTING)
1466 << BOOST_CURRENT_FUNCTION
1469 << " pit: " << bottom_pit
1470 << " singlepar: " << singlepar
1475 pit_type const pit = anchor_ref_;
1479 // Rebreak anchor paragraph.
1480 tm.redoParagraph(pit);
1484 int y0 = tm.parMetrics(pit).ascent() - offset_ref_;
1486 // Redo paragraphs above anchor if necessary.
1488 while (y1 > 0 && pit1 > 0) {
1489 y1 -= tm.parMetrics(pit1).ascent();
1491 tm.redoParagraph(pit1);
1492 y1 -= tm.parMetrics(pit1).descent();
1495 // Take care of ascent of first line
1496 y1 -= tm.parMetrics(pit1).ascent();
1498 // Normalize anchor for next time
1502 // Grey at the beginning is ugly
1503 if (pit1 == 0 && y1 > 0) {
1509 // Redo paragraphs below the anchor if necessary.
1511 while (y2 < height_ && pit2 < int(npit) - 1) {
1512 y2 += tm.parMetrics(pit2).descent();
1514 tm.redoParagraph(pit2);
1515 y2 += tm.parMetrics(pit2).ascent();
1518 // Take care of descent of last line
1519 y2 += tm.parMetrics(pit2).descent();
1521 LYXERR(Debug::PAINTING)
1522 << BOOST_CURRENT_FUNCTION
1525 << " pit1: " << pit1
1526 << " pit2: " << pit2
1527 << " npit: " << npit
1528 << " singlepar: " << singlepar
1531 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2,
1532 FullScreenUpdate, npit);
1534 if (lyxerr.debugging(Debug::WORKAREA)) {
1535 LYXERR(Debug::WORKAREA) << "BufferView::updateMetrics" << endl;
1536 coord_cache_.dump();
1541 void BufferView::menuInsertLyXFile(string const & filenm)
1543 BOOST_ASSERT(cursor_.inTexted());
1544 string filename = filenm;
1546 if (filename.empty()) {
1547 // Launch a file browser
1549 string initpath = lyxrc.document_path;
1550 string const trypath = buffer_.filePath();
1551 // If directory is writeable, use this as default.
1552 if (isDirWriteable(FileName(trypath)))
1556 FileDialog fileDlg(_("Select LyX document to insert"),
1558 make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1559 make_pair(_("Examples|#E#e"),
1560 from_utf8(addPath(package().system_support().absFilename(),
1563 FileDialog::Result result =
1564 fileDlg.open(from_utf8(initpath),
1565 FileFilterList(_("LyX Documents (*.lyx)")),
1568 if (result.first == FileDialog::Later)
1572 filename = to_utf8(result.second);
1574 // check selected filename
1575 if (filename.empty()) {
1576 // emit message signal.
1577 message(_("Canceled."));
1582 // Get absolute path of file and add ".lyx"
1583 // to the filename if necessary
1584 filename = fileSearch(string(), filename, "lyx").absFilename();
1586 docstring const disp_fn = makeDisplayPath(filename);
1587 // emit message signal.
1588 message(bformat(_("Inserting document %1$s..."), disp_fn));
1591 Buffer buf("", false);
1592 if (lyx::loadLyXFile(&buf, FileName(filename))) {
1593 ErrorList & el = buffer_.errorList("Parse");
1594 // Copy the inserted document error list into the current buffer one.
1595 el = buf.errorList("Parse");
1596 recordUndo(cursor_);
1597 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1598 buf.params().getTextClass_ptr(), el);
1599 res = _("Document %1$s inserted.");
1601 res = _("Could not insert document %1$s");
1603 // emit message signal.
1604 message(bformat(res, disp_fn));
1605 buffer_.errors("Parse");
1606 updateMetrics(false);
1610 void BufferView::draw(frontend::Painter & pain)
1612 PainterInfo pi(this, pain);
1613 // Should the whole screen, including insets, be refreshed?
1614 // FIXME: We should also distinguish DecorationUpdate to avoid text
1615 // drawing if possible. This is not possible to do easily right now
1616 // because of the single backing pixmap.
1617 pi.full_repaint = metrics_info_.update_strategy != SingleParUpdate;
1619 if (pi.full_repaint)
1620 // Clear background (if not delegated to rows)
1621 pain.fillRectangle(0, metrics_info_.y1, width_,
1622 metrics_info_.y2 - metrics_info_.y1,
1623 buffer_.inset().backgroundColor());
1625 LYXERR(Debug::PAINTING) << "\t\t*** START DRAWING ***" << endl;
1626 Text & text = buffer_.text();
1627 TextMetrics const & tm = text_metrics_[&text];
1628 int y = metrics_info_.y1 + tm.parMetrics(metrics_info_.p1).ascent();
1629 if (!pi.full_repaint)
1630 tm.drawParagraph(pi, metrics_info_.p1, 0, y);
1633 LYXERR(Debug::PAINTING) << "\n\t\t*** END DRAWING ***" << endl;
1635 // and grey out above (should not happen later)
1636 // lyxerr << "par ascent: " << text.getPar(metrics_info_.p1).ascent() << endl;
1637 if (metrics_info_.y1 > 0
1638 && metrics_info_.update_strategy == FullScreenUpdate)
1639 pain.fillRectangle(0, 0, width_, metrics_info_.y1, Color::bottomarea);
1641 // and possibly grey out below
1642 // lyxerr << "par descent: " << text.getPar(metrics_info_.p1).ascent() << endl;
1643 if (metrics_info_.y2 < height_
1644 && metrics_info_.update_strategy == FullScreenUpdate)
1645 pain.fillRectangle(0, metrics_info_.y2, width_,
1646 height_ - metrics_info_.y2, Color::bottomarea);