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 "CoordCache.h"
25 #include "CutAndPaste.h"
27 #include "DispatchResult.h"
28 #include "ErrorList.h"
30 #include "FloatList.h"
31 #include "FuncRequest.h"
32 #include "FuncStatus.h"
35 #include "InsetIterator.h"
37 #include "LaTeXFeatures.h"
38 #include "callback.h" // added for Dispatch functions
44 #include "TextClass.h"
47 #include "Paragraph.h"
48 #include "paragraph_funcs.h"
49 #include "ParagraphParameters.h"
50 #include "ParIterator.h"
55 #include "WordLangTuple.h"
56 #include "MetricsInfo.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/Selection.h"
68 #include "graphics/Previews.h"
70 #include "support/convert.h"
71 #include "support/FileFilterList.h"
72 #include "support/filetools.h"
73 #include "support/Package.h"
74 #include "support/types.h"
76 #include <boost/bind.hpp>
77 #include <boost/current_function.hpp>
84 using std::istringstream;
88 using std::mem_fun_ref;
95 using support::addPath;
96 using support::bformat;
97 using support::FileFilterList;
98 using support::FileName;
99 using support::fileSearch;
100 using support::isDirWriteable;
101 using support::isFileReadable;
102 using support::makeDisplayPath;
103 using support::package;
105 namespace Alert = frontend::Alert;
109 /// Return an inset of this class if it exists at the current cursor position
111 T * getInsetByCode(Cursor & cur, Inset::Code code)
114 DocIterator it = cur;
115 if (it.nextInset() &&
116 it.nextInset()->lyxCode() == code) {
117 inset = static_cast<T*>(it.nextInset());
125 BufferView::BufferView(Buffer & buf)
126 : width_(0), height_(0), buffer_(buf), wh_(0),
128 multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
129 intl_(new Intl), last_inset_(0)
131 xsel_cache_.set = false;
132 intl_->initKeyMapper(lyxrc.use_kbmap);
134 cursor_.push(buffer_.inset());
135 cursor_.resetAnchor();
136 buffer_.text().setCurrentFont(cursor_);
138 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
139 graphics::Previews::get().generateBufferPreviews(buffer_);
143 BufferView::~BufferView()
148 Buffer * BufferView::buffer()
154 Buffer const * BufferView::buffer() const
160 bool BufferView::fitCursor()
162 if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
163 frontend::FontMetrics const & fm =
164 theFontMetrics(cursor_.getFont());
165 int const asc = fm.maxAscent();
166 int const des = fm.maxDescent();
167 Point const p = bv_funcs::getPos(*this, cursor_, cursor_.boundary());
168 if (p.y_ - asc >= 0 && p.y_ + des < height_)
176 bool BufferView::multiParSel()
178 if (!cursor_.selection())
180 bool ret = multiparsel_cache_;
181 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
182 // Either this, or previous selection spans paragraphs
183 return ret || multiparsel_cache_;
187 bool BufferView::update(Update::flags flags)
189 // last_inset_ points to the last visited inset. This pointer may become
190 // invalid because of keyboard editing. Since all such operations
191 // causes screen update(), I reset last_inset_ to avoid such a problem.
193 // This is close to a hot-path.
195 << BOOST_CURRENT_FUNCTION
196 << "[fitcursor = " << (flags & Update::FitCursor)
197 << ", forceupdate = " << (flags & Update::Force)
198 << ", singlepar = " << (flags & Update::SinglePar)
199 << "] buffer: " << &buffer_ << endl;
201 // Update macro store
202 if (!(cursor().inMathed() && cursor().inMacroMode()))
203 buffer_.buildMacros();
205 // Now do the first drawing step if needed. This consists on updating
206 // the CoordCache in updateMetrics().
207 // The second drawing step is done in WorkArea::redraw() if needed.
209 // Case when no explicit update is requested.
211 // no need to redraw anything.
212 metrics_info_.update_strategy = NoScreenUpdate;
216 if (flags == Update::Decoration) {
217 metrics_info_.update_strategy = DecorationUpdate;
221 if (flags == Update::FitCursor
222 || flags == (Update::Decoration | Update::FitCursor)) {
223 bool const fit_cursor = fitCursor();
224 // tell the frontend to update the screen if needed.
226 updateMetrics(false);
229 if (flags & Update::Decoration) {
230 metrics_info_.update_strategy = DecorationUpdate;
233 // no screen update is needed.
234 metrics_info_.update_strategy = NoScreenUpdate;
238 bool full_metrics = flags & Update::Force;
239 if (flags & Update::MultiParSel)
240 full_metrics |= multiParSel();
242 bool const single_par = !full_metrics;
243 updateMetrics(single_par);
245 if (flags & Update::FitCursor && fitCursor())
246 updateMetrics(false);
248 // tell the frontend to update the screen.
253 void BufferView::updateScrollbar()
255 Text & t = buffer_.text();
256 TextMetrics & tm = text_metrics_[&t];
258 int const parsize = int(t.paragraphs().size() - 1);
259 if (anchor_ref_ > parsize) {
260 anchor_ref_ = parsize;
265 << BOOST_CURRENT_FUNCTION
266 << " Updating scrollbar: height: " << t.paragraphs().size()
267 << " curr par: " << cursor_.bottom().pit()
268 << " default height " << defaultRowHeight() << endl;
270 // It would be better to fix the scrollbar to understand
271 // values in [0..1] and divide everything by wh
273 // estimated average paragraph height:
277 int h = tm.parMetrics(anchor_ref_).height();
279 // Normalize anchor/offset (MV):
280 while (offset_ref_ > h && anchor_ref_ < parsize) {
283 h = tm.parMetrics(anchor_ref_).height();
285 // Look at paragraph heights on-screen
288 for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
291 int const h2 = tm.parMetrics(pit).height();
297 int const hav = sumh / nh;
298 // More realistic average paragraph height
303 scrollbarParameters_.height = (parsize + 1) * wh_;
304 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
305 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
309 ScrollbarParameters const & BufferView::scrollbarParameters() const
311 return scrollbarParameters_;
315 void BufferView::scrollDocView(int value)
317 LYXERR(Debug::GUI) << BOOST_CURRENT_FUNCTION
318 << "[ value = " << value << "]" << endl;
320 Text & t = buffer_.text();
321 TextMetrics & tm = text_metrics_[&t];
323 float const bar = value / float(wh_ * t.paragraphs().size());
325 anchor_ref_ = int(bar * t.paragraphs().size());
326 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
327 anchor_ref_ = int(t.paragraphs().size()) - 1;
329 tm.redoParagraph(anchor_ref_);
330 int const h = tm.parMetrics(anchor_ref_).height();
331 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
332 updateMetrics(false);
336 void BufferView::setCursorFromScrollbar()
338 Text & t = buffer_.text();
340 int const height = 2 * defaultRowHeight();
341 int const first = height;
342 int const last = height_ - height;
343 Cursor & cur = cursor_;
345 bv_funcs::CurStatus st = bv_funcs::status(this, cur);
348 case bv_funcs::CUR_ABOVE:
349 // We reset the cursor because bv_funcs::status() does not
350 // work when the cursor is within mathed.
351 cur.reset(buffer_.inset());
352 t.setCursorFromCoordinates(cur, 0, first);
353 cur.clearSelection();
355 case bv_funcs::CUR_BELOW:
356 // We reset the cursor because bv_funcs::status() does not
357 // work when the cursor is within mathed.
358 cur.reset(buffer_.inset());
359 t.setCursorFromCoordinates(cur, 0, last);
360 cur.clearSelection();
362 case bv_funcs::CUR_INSIDE:
363 int const y = bv_funcs::getPos(*this, cur, cur.boundary()).y_;
364 int const newy = min(last, max(y, first));
366 cur.reset(buffer_.inset());
367 t.setCursorFromCoordinates(cur, 0, newy);
373 Change const BufferView::getCurrentChange() const
375 if (!cursor_.selection())
376 return Change(Change::UNCHANGED);
378 DocIterator dit = cursor_.selectionBegin();
379 return dit.paragraph().lookupChange(dit.pos());
383 void BufferView::saveBookmark(unsigned int idx)
385 // tenatively save bookmark, id and pos will be used to
386 // acturately locate a bookmark in a 'live' lyx session.
387 // pit and pos will be updated with bottom level pit/pos
389 LyX::ref().session().bookmarks().save(
390 FileName(buffer_.fileName()),
391 cursor_.bottom().pit(),
392 cursor_.bottom().pos(),
393 cursor_.paragraph().id(),
398 // emit message signal.
399 message(_("Save bookmark"));
403 boost::tuple<pit_type, pos_type, int> BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
404 int top_id, pos_type top_pos)
406 cursor_.clearSelection();
408 // if a valid par_id is given, try it first
409 // This is the case for a 'live' bookmark when unique paragraph ID
410 // is used to track bookmarks.
412 ParIterator par = buffer_.getParFromID(top_id);
413 if (par != buffer_.par_iterator_end()) {
414 DocIterator dit = makeDocIterator(par, min(par->size(), top_pos));
415 // Some slices of the iterator may not be
416 // reachable (e.g. closed collapsable inset)
417 // so the dociterator may need to be
418 // shortened. Otherwise, setCursor may crash
419 // lyx when the cursor can not be set to these
421 size_t const n = dit.depth();
422 for (size_t i = 0; i < n; ++i)
423 if (dit[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
428 // Note: return bottom (document) level pit.
429 return boost::make_tuple(cursor_.bottom().pit(), cursor_.bottom().pos(), top_id);
432 // if top_id == 0, or searching through top_id failed
433 // This is the case for a 'restored' bookmark when only bottom
434 // (document level) pit was saved. Because of this, bookmark
435 // restoration is inaccurate. If a bookmark was within an inset,
436 // it will be restored to the left of the outmost inset that contains
438 if (static_cast<size_t>(bottom_pit) < buffer_.paragraphs().size()) {
439 DocIterator it = doc_iterator_begin(buffer_.inset());
440 it.pit() = bottom_pit;
441 it.pos() = min(bottom_pos, it.paragraph().size());
443 return boost::make_tuple(it.pit(), it.pos(),
444 it.paragraph().id());
447 return boost::make_tuple(pit_type(0), pos_type(0), 0);
451 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
453 if (lyxrc.rtl_support) {
454 if (cursor_.innerText()->real_current_font.isRightToLeft()) {
455 if (intl_->keymap == Intl::PRIMARY)
458 if (intl_->keymap == Intl::SECONDARY)
463 intl_->getTransManager().translateAndInsert(c, t, cur);
467 int BufferView::workWidth() const
473 void BufferView::center()
475 CursorSlice & bot = cursor_.bottom();
476 TextMetrics & tm = text_metrics_[bot.text()];
477 pit_type const pit = bot.pit();
478 tm.redoParagraph(pit);
479 ParagraphMetrics const & pm = tm.parMetrics(pit);
481 offset_ref_ = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary()).y_
482 + pm.ascent() - height_ / 2;
486 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
490 Cursor & cur = cursor_;
492 switch (cmd.action) {
495 flag.enabled(!buffer_.undostack().empty());
498 flag.enabled(!buffer_.redostack().empty());
500 case LFUN_FILE_INSERT:
501 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
502 case LFUN_FILE_INSERT_PLAINTEXT:
503 case LFUN_BOOKMARK_SAVE:
504 // FIXME: Actually, these LFUNS should be moved to Text
505 flag.enabled(cur.inTexted());
507 case LFUN_FONT_STATE:
508 case LFUN_LABEL_INSERT:
509 case LFUN_PARAGRAPH_GOTO:
510 // FIXME handle non-trivially
511 case LFUN_OUTLINE_UP:
512 case LFUN_OUTLINE_DOWN:
513 case LFUN_OUTLINE_IN:
514 case LFUN_OUTLINE_OUT:
516 case LFUN_REFERENCE_NEXT:
518 case LFUN_WORD_REPLACE:
521 case LFUN_MARK_TOGGLE:
522 case LFUN_SCREEN_RECENTER:
523 case LFUN_BIBTEX_DATABASE_ADD:
524 case LFUN_BIBTEX_DATABASE_DEL:
525 case LFUN_WORDS_COUNT:
526 case LFUN_NEXT_INSET_TOGGLE:
530 case LFUN_LABEL_GOTO: {
531 flag.enabled(!cmd.argument().empty()
532 || getInsetByCode<InsetRef>(cur, Inset::REF_CODE));
536 case LFUN_CHANGES_TRACK:
538 flag.setOnOff(buffer_.params().trackChanges);
541 case LFUN_CHANGES_OUTPUT:
543 flag.setOnOff(buffer_.params().outputChanges);
546 case LFUN_CHANGES_MERGE:
547 case LFUN_CHANGE_NEXT:
548 case LFUN_ALL_CHANGES_ACCEPT:
549 case LFUN_ALL_CHANGES_REJECT:
550 // TODO: context-sensitive enabling of LFUNs
551 // In principle, these command should only be enabled if there
552 // is a change in the document. However, without proper
553 // optimizations, this will inevitably result in poor performance.
557 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
558 flag.setOnOff(buffer_.params().compressed);
570 Update::flags BufferView::dispatch(FuncRequest const & cmd)
572 //lyxerr << BOOST_CURRENT_FUNCTION
573 // << [ cmd = " << cmd << "]" << endl;
575 // Make sure that the cached BufferView is correct.
576 LYXERR(Debug::ACTION) << BOOST_CURRENT_FUNCTION
577 << " action[" << cmd.action << ']'
578 << " arg[" << to_utf8(cmd.argument()) << ']'
579 << " x[" << cmd.x << ']'
580 << " y[" << cmd.y << ']'
581 << " button[" << cmd.button() << ']'
584 Cursor & cur = cursor_;
585 // Default Update flags.
586 Update::flags updateFlags = Update::Force | Update::FitCursor;
588 switch (cmd.action) {
591 cur.message(_("Undo"));
592 cur.clearSelection();
593 if (!textUndo(*this)) {
594 cur.message(_("No further undo information"));
595 updateFlags = Update::None;
600 cur.message(_("Redo"));
601 cur.clearSelection();
602 if (!textRedo(*this)) {
603 cur.message(_("No further redo information"));
604 updateFlags = Update::None;
608 case LFUN_FILE_INSERT:
610 menuInsertLyXFile(to_utf8(cmd.argument()));
613 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
615 insertPlaintextFile(this, to_utf8(cmd.argument()), true);
618 case LFUN_FILE_INSERT_PLAINTEXT:
620 insertPlaintextFile(this, to_utf8(cmd.argument()), false);
623 case LFUN_FONT_STATE:
624 cur.message(cur.currentState());
627 case LFUN_BOOKMARK_SAVE:
628 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
631 case LFUN_LABEL_GOTO: {
632 docstring label = cmd.argument();
635 getInsetByCode<InsetRef>(cursor_,
638 label = inset->getParam("reference");
639 // persistent=false: use temp_bookmark
649 case LFUN_PARAGRAPH_GOTO: {
650 int const id = convert<int>(to_utf8(cmd.argument()));
652 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
653 b = theBufferList().next(b)) {
655 ParIterator par = b->getParFromID(id);
656 if (par == b->par_iterator_end()) {
658 << "No matching paragraph found! ["
659 << id << "]." << endl;
662 << "Paragraph " << par->id()
663 << " found in buffer `"
664 << b->fileName() << "'." << endl;
668 setCursor(makeDocIterator(par, 0));
670 // Switch to other buffer view and resend cmd
671 theLyXFunc().dispatch(FuncRequest(
672 LFUN_BUFFER_SWITCH, b->fileName()));
673 theLyXFunc().dispatch(cmd);
674 updateFlags = Update::None;
683 case LFUN_OUTLINE_UP:
684 toc::outline(toc::Up, cursor_);
685 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
686 updateLabels(buffer_);
688 case LFUN_OUTLINE_DOWN:
689 toc::outline(toc::Down, cursor_);
690 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
691 updateLabels(buffer_);
693 case LFUN_OUTLINE_IN:
694 toc::outline(toc::In, cursor_);
695 updateLabels(buffer_);
697 case LFUN_OUTLINE_OUT:
698 toc::outline(toc::Out, cursor_);
699 updateLabels(buffer_);
703 bv_funcs::gotoInset(this, Inset::NOTE_CODE, false);
706 case LFUN_REFERENCE_NEXT: {
707 vector<Inset_code> tmp;
708 tmp.push_back(Inset::LABEL_CODE);
709 tmp.push_back(Inset::REF_CODE);
710 bv_funcs::gotoInset(this, tmp, true);
714 case LFUN_CHANGES_TRACK:
715 buffer_.params().trackChanges = !buffer_.params().trackChanges;
718 case LFUN_CHANGES_OUTPUT:
719 buffer_.params().outputChanges = !buffer_.params().outputChanges;
720 if (buffer_.params().outputChanges) {
721 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
722 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
723 LaTeXFeatures::isAvailable("xcolor");
725 if (!dvipost && !xcolorsoul) {
726 Alert::warning(_("Changes not shown in LaTeX output"),
727 _("Changes will not be highlighted in LaTeX output, "
728 "because neither dvipost nor xcolor/soul are installed.\n"
729 "Please install these packages or redefine "
730 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
731 } else if (!xcolorsoul) {
732 Alert::warning(_("Changes not shown in LaTeX output"),
733 _("Changes will not be highlighted in LaTeX output "
734 "when using pdflatex, because xcolor and soul are not installed.\n"
735 "Please install both packages or redefine "
736 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
741 case LFUN_CHANGE_NEXT:
742 findNextChange(this);
745 case LFUN_CHANGES_MERGE:
746 if (findNextChange(this))
747 showDialog("changes");
750 case LFUN_ALL_CHANGES_ACCEPT:
751 // select complete document
752 cursor_.reset(buffer_.inset());
753 cursor_.selHandle(true);
754 buffer_.text().cursorBottom(cursor_);
755 // accept everything in a single step to support atomic undo
756 buffer_.text().acceptOrRejectChanges(cursor_, Text::ACCEPT);
759 case LFUN_ALL_CHANGES_REJECT:
760 // select complete document
761 cursor_.reset(buffer_.inset());
762 cursor_.selHandle(true);
763 buffer_.text().cursorBottom(cursor_);
764 // reject everything in a single step to support atomic undo
765 // Note: reject does not work recursively; the user may have to repeat the operation
766 buffer_.text().acceptOrRejectChanges(cursor_, Text::REJECT);
773 case LFUN_WORD_REPLACE: {
774 bool has_deleted = false;
775 if (cur.selection()) {
776 DocIterator beg = cur.selectionBegin();
777 DocIterator end = cur.selectionEnd();
778 if (beg.pit() == end.pit()) {
779 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
780 if (cur.paragraph().isDeleted(p))
785 replace(this, cmd, has_deleted);
790 cur.clearSelection();
792 cur.message(from_utf8(N_("Mark off")));
796 cur.clearSelection();
799 cur.message(from_utf8(N_("Mark on")));
802 case LFUN_MARK_TOGGLE:
803 cur.clearSelection();
806 cur.message(from_utf8(N_("Mark removed")));
809 cur.message(from_utf8(N_("Mark set")));
814 case LFUN_SCREEN_RECENTER:
818 case LFUN_BIBTEX_DATABASE_ADD: {
819 Cursor tmpcur = cursor_;
820 bv_funcs::findInset(tmpcur, Inset::BIBTEX_CODE, false);
821 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
824 if (inset->addDatabase(to_utf8(cmd.argument())))
825 buffer_.updateBibfilesCache();
830 case LFUN_BIBTEX_DATABASE_DEL: {
831 Cursor tmpcur = cursor_;
832 bv_funcs::findInset(tmpcur, Inset::BIBTEX_CODE, false);
833 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
836 if (inset->delDatabase(to_utf8(cmd.argument())))
837 buffer_.updateBibfilesCache();
842 case LFUN_WORDS_COUNT: {
843 DocIterator from, to;
844 if (cur.selection()) {
845 from = cur.selectionBegin();
846 to = cur.selectionEnd();
848 from = doc_iterator_begin(buffer_.inset());
849 to = doc_iterator_end(buffer_.inset());
851 int const count = countWords(from, to);
855 message = bformat(_("%1$d words in selection."),
858 message = bformat(_("%1$d words in document."),
863 message = _("One word in selection.");
865 message = _("One word in document.");
868 Alert::information(_("Count words"), message);
872 case LFUN_BUFFER_TOGGLE_COMPRESSION:
873 // turn compression on/off
874 buffer_.params().compressed = !buffer_.params().compressed;
877 case LFUN_NEXT_INSET_TOGGLE: {
878 // this is the real function we want to invoke
879 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
880 // if there is an inset at cursor, see whether it
882 Inset * inset = cur.nextInset();
883 if (inset && inset->isActive()) {
885 tmpcur.pushLeft(*inset);
886 inset->dispatch(tmpcur, tmpcmd);
887 if (tmpcur.result().dispatched()) {
891 // if it did not work, try the underlying inset.
892 if (!cur.result().dispatched())
893 cur.dispatch(tmpcmd);
895 if (cur.result().dispatched())
896 cur.clearSelection();
902 updateFlags = Update::None;
909 docstring const BufferView::requestSelection()
911 Cursor & cur = cursor_;
913 if (!cur.selection()) {
914 xsel_cache_.set = false;
918 if (!xsel_cache_.set ||
919 cur.top() != xsel_cache_.cursor ||
920 cur.anchor_.top() != xsel_cache_.anchor)
922 xsel_cache_.cursor = cur.top();
923 xsel_cache_.anchor = cur.anchor_.top();
924 xsel_cache_.set = cur.selection();
925 return cur.selectionAsString(false);
931 void BufferView::clearSelection()
933 cursor_.clearSelection();
934 // Clear the selection buffer. Otherwise a subsequent
935 // middle-mouse-button paste would use the selection buffer,
936 // not the more current external selection.
937 cap::clearSelection();
938 xsel_cache_.set = false;
939 // The buffer did not really change, but this causes the
940 // redraw we need because we cleared the selection above.
945 void BufferView::workAreaResize(int width, int height)
947 // Update from work area
951 // The complete text metrics will be redone.
952 text_metrics_.clear();
953 updateMetrics(false);
957 Inset const * BufferView::getCoveringInset(Text const & text, int x, int y)
959 pit_type pit = text.getPitNearY(*this, y);
960 BOOST_ASSERT(pit != -1);
961 Paragraph const & par = text.getPar(pit);
964 << BOOST_CURRENT_FUNCTION
969 InsetList::const_iterator iit = par.insetlist.begin();
970 InsetList::const_iterator iend = par.insetlist.end();
971 for (; iit != iend; ++iit) {
972 Inset * const inset = iit->inset;
973 if (inset->covers(*this, x, y)) {
974 if (!inset->descendable())
975 // No need to go further down if the inset is not
979 size_t cell_number = inset->nargs();
980 // Check all the inner cell.
981 for (size_t i = 0; i != cell_number; ++i) {
982 Text const * inner_text = inset->getText(i);
985 Inset const * inset_deeper =
986 getCoveringInset(*inner_text, x, y);
993 << BOOST_CURRENT_FUNCTION
994 << ": Hit inset: " << inset << endl;
999 << BOOST_CURRENT_FUNCTION
1000 << ": No inset hit. " << endl;
1005 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1007 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1009 // This is only called for mouse related events including
1010 // LFUN_FILE_OPEN generated by drag-and-drop.
1011 FuncRequest cmd = cmd0;
1014 cur.push(buffer_.inset());
1015 cur.selection() = cursor_.selection();
1017 // Either the inset under the cursor or the
1018 // surrounding Text will handle this event.
1020 // make sure we stay within the screen...
1021 cmd.y = min(max(cmd.y, -1), height_);
1023 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1025 // Get inset under mouse, if there is one.
1026 Inset const * covering_inset =
1027 getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1028 if (covering_inset == last_inset_)
1029 // Same inset, no need to do anything...
1032 bool need_redraw = false;
1033 // const_cast because of setMouseHover().
1034 Inset * inset = const_cast<Inset *>(covering_inset);
1036 // Remove the hint on the last hovered inset (if any).
1037 need_redraw |= last_inset_->setMouseHover(false);
1039 // Highlighted the newly hovered inset (if any).
1040 need_redraw |= inset->setMouseHover(true);
1041 last_inset_ = inset;
1043 // if last metrics update was in singlepar mode, WorkArea::redraw() will
1044 // not expose the button for redraw. We adjust here the metrics dimension
1045 // to enable a full redraw.
1046 // FIXME: It is possible to redraw only the area around the button!
1048 && metrics_info_.update_strategy == SingleParUpdate) {
1049 // FIXME: It should be possible to redraw only the area around
1050 // the button by doing this:
1052 //metrics_info_.singlepar = false;
1053 //metrics_info_.y1 = ymin of button;
1054 //metrics_info_.y2 = ymax of button;
1056 // Unfortunately, rowpainter.cpp:paintText() does not distinguish
1057 // between background updates and text updates. So we use the hammer
1058 // solution for now. We could also avoid the updateMetrics() below
1059 // by using the first and last pit of the CoordCache. Have a look
1060 // at Text::getPitNearY() to see what I mean.
1062 //metrics_info_.pit1 = first pit of CoordCache;
1063 //metrics_info_.pit2 = last pit of CoordCache;
1064 //metrics_info_.singlepar = false;
1065 //metrics_info_.y1 = 0;
1066 //metrics_info_.y2 = height_;
1068 updateMetrics(false);
1071 // This event (moving without mouse click) is not passed further.
1072 // This should be changed if it is further utilized.
1076 // Build temporary cursor.
1077 Inset * inset = buffer_.text().editXY(cur, cmd.x, cmd.y);
1079 // Put anchor at the same position.
1082 // Try to dispatch to an non-editable inset near this position
1083 // via the temp cursor. If the inset wishes to change the real
1084 // cursor it has to do so explicitly by using
1085 // cur.bv().cursor() = cur; (or similar)
1087 inset->dispatch(cur, cmd);
1090 // Now dispatch to the temporary cursor. If the real cursor should
1091 // be modified, the inset's dispatch has to do so explicitly.
1092 if (!cur.result().dispatched())
1095 //Do we have a selection?
1096 theSelection().haveSelection(cursor().selection());
1098 // Redraw if requested and necessary.
1099 if (cur.result().dispatched() && cur.result().update())
1100 return update(cur.result().update());
1106 void BufferView::scroll(int /*lines*/)
1108 // Text const * t = buffer_.text();
1109 // int const line_height = defaultRowHeight();
1111 // // The new absolute coordinate
1112 // int new_top_y = top_y() + lines * line_height;
1114 // // Restrict to a valid value
1115 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1116 // new_top_y = std::max(0, new_top_y);
1118 // scrollDocView(new_top_y);
1123 void BufferView::setCursorFromRow(int row)
1128 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1130 cursor_.reset(buffer_.inset());
1132 buffer_.text().setCursor(cursor_, 0, 0);
1134 buffer_.text().setCursor(cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1138 void BufferView::gotoLabel(docstring const & label)
1140 for (InsetIterator it = inset_iterator_begin(buffer_.inset()); it; ++it) {
1141 vector<docstring> labels;
1142 it->getLabelList(buffer_, labels);
1143 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1152 TextMetrics const & BufferView::textMetrics(Text const * t) const
1154 return const_cast<BufferView *>(this)->textMetrics(t);
1158 TextMetrics & BufferView::textMetrics(Text const * t)
1160 TextMetricsCache::iterator tmc_it = text_metrics_.find(t);
1161 if (tmc_it == text_metrics_.end()) {
1162 tmc_it = text_metrics_.insert(
1163 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1165 return tmc_it->second;
1169 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1172 return textMetrics(t).parMetrics(pit);
1176 int BufferView::workHeight() const
1182 void BufferView::setCursor(DocIterator const & dit)
1184 size_t const n = dit.depth();
1185 for (size_t i = 0; i < n; ++i)
1186 dit[i].inset().edit(cursor_, true);
1188 cursor_.setCursor(dit);
1189 cursor_.selection() = false;
1193 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1195 // Would be wrong to delete anything if we have a selection.
1196 if (cur.selection())
1199 bool need_anchor_change = false;
1200 bool changed = cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1201 need_anchor_change);
1203 if (need_anchor_change)
1209 updateLabels(buffer_);
1211 updateMetrics(false);
1217 bool BufferView::mouseSetCursor(Cursor & cur)
1219 BOOST_ASSERT(&cur.bv() == this);
1221 // this event will clear selection so we save selection for
1222 // persistent selection
1223 cap::saveSelection(cursor());
1225 // Has the cursor just left the inset?
1226 bool badcursor = false;
1227 bool leftinset = (&cursor_.inset() != &cur.inset());
1229 badcursor = notifyCursorLeaves(cursor_, cur);
1231 // do the dEPM magic if needed
1232 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1233 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1234 // the leftinset bool would not be necessary (badcursor instead).
1235 bool update = leftinset;
1236 if (!badcursor && cursor_.inTexted())
1237 update |= checkDepm(cur, cursor_);
1239 // if the cursor was in an empty script inset and the new
1240 // position is in the nucleus of the inset, notifyCursorLeaves
1241 // will kill the script inset itself. So we check all the
1242 // elements of the cursor to make sure that they are correct.
1243 // For an example, see bug 2933:
1244 // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1245 // The code below could maybe be moved to a DocIterator method.
1246 //lyxerr << "cur before " << cur <<std::endl;
1247 DocIterator dit(cur.inset());
1248 dit.push_back(cur.bottom());
1250 while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1251 dit.push_back(cur[i]);
1254 //lyxerr << "5 cur after" << dit <<std::endl;
1256 cursor_.setCursor(dit);
1257 cursor_.boundary(cur.boundary());
1258 cursor_.clearSelection();
1264 void BufferView::putSelectionAt(DocIterator const & cur,
1265 int length, bool backwards)
1267 cursor_.clearSelection();
1273 cursor_.pos() += length;
1274 cursor_.setSelection(cursor_, -length);
1276 cursor_.setSelection(cursor_, length);
1281 Cursor & BufferView::cursor()
1287 Cursor const & BufferView::cursor() const
1293 pit_type BufferView::anchor_ref() const
1299 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1301 return metrics_info_;
1305 // FIXME: We should split-up updateMetrics() for the singlepar case.
1306 void BufferView::updateMetrics(bool singlepar)
1308 Text & buftext = buffer_.text();
1309 TextMetrics & tm = textMetrics(&buftext);
1310 pit_type size = int(buftext.paragraphs().size());
1312 if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1313 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1318 // Clear out the position cache in case of full screen redraw,
1319 coord_cache_.clear();
1321 // Clear out paragraph metrics to avoid having invalid metrics
1322 // in the cache from paragraphs not relayouted below
1326 // If the paragraph metrics has changed, we can not
1327 // use the singlepar optimisation.
1329 // In Single Paragraph mode, rebreak only
1330 // the (main text, not inset!) paragraph containing the cursor.
1331 // (if this paragraph contains insets etc., rebreaking will
1332 // recursively descend)
1333 && tm.redoParagraph(cursor_.bottom().pit()))
1336 pit_type const pit = anchor_ref_;
1339 size_t const npit = buftext.paragraphs().size();
1341 // Rebreak anchor paragraph.
1343 tm.redoParagraph(pit);
1345 int y0 = tm.parMetrics(pit).ascent() - offset_ref_;
1347 // Redo paragraphs above anchor if necessary.
1349 while (y1 > 0 && pit1 > 0) {
1350 y1 -= tm.parMetrics(pit1).ascent();
1353 tm.redoParagraph(pit1);
1354 y1 -= tm.parMetrics(pit1).descent();
1358 // Take care of ascent of first line
1359 y1 -= tm.parMetrics(pit1).ascent();
1361 // Normalize anchor for next time
1365 // Grey at the beginning is ugly
1366 if (pit1 == 0 && y1 > 0) {
1372 // Redo paragraphs below the anchor if necessary.
1374 while (y2 < height_ && pit2 < int(npit) - 1) {
1375 y2 += tm.parMetrics(pit2).descent();
1378 tm.redoParagraph(pit2);
1379 y2 += tm.parMetrics(pit2).ascent();
1382 // Take care of descent of last line
1383 y2 += tm.parMetrics(pit2).descent();
1385 // The coordinates of all these paragraphs are correct, cache them
1387 CoordCache::InnerParPosCache & parPos = coord_cache_.parPos()[&buftext];
1388 for (pit_type pit = pit1; pit <= pit2; ++pit) {
1389 ParagraphMetrics const & pm = tm.parMetrics(pit);
1391 parPos[pit] = Point(0, y);
1392 if (singlepar && pit == cursor_.bottom().pit()) {
1393 // In Single Paragraph mode, collect here the
1394 // y1 and y2 of the (one) paragraph the cursor is in
1395 y1 = y - pm.ascent();
1396 y2 = y + pm.descent();
1402 // collect cursor paragraph iter bounds
1403 pit1 = cursor_.bottom().pit();
1404 pit2 = cursor_.bottom().pit();
1407 LYXERR(Debug::DEBUG)
1408 << BOOST_CURRENT_FUNCTION
1411 << " pit1: " << pit1
1412 << " pit2: " << pit2
1413 << " npit: " << npit
1414 << " singlepar: " << singlepar
1418 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2,
1419 singlepar? SingleParUpdate: FullScreenUpdate, size);
1421 if (lyxerr.debugging(Debug::WORKAREA)) {
1422 LYXERR(Debug::WORKAREA) << "BufferView::updateMetrics" << endl;
1423 coord_cache_.dump();
1428 void BufferView::menuInsertLyXFile(string const & filenm)
1430 BOOST_ASSERT(cursor_.inTexted());
1431 string filename = filenm;
1433 if (filename.empty()) {
1434 // Launch a file browser
1436 string initpath = lyxrc.document_path;
1437 string const trypath = buffer_.filePath();
1438 // If directory is writeable, use this as default.
1439 if (isDirWriteable(FileName(trypath)))
1443 FileDialog fileDlg(_("Select LyX document to insert"),
1445 make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1446 make_pair(_("Examples|#E#e"),
1447 from_utf8(addPath(package().system_support().absFilename(),
1450 FileDialog::Result result =
1451 fileDlg.open(from_utf8(initpath),
1452 FileFilterList(_("LyX Documents (*.lyx)")),
1455 if (result.first == FileDialog::Later)
1459 filename = to_utf8(result.second);
1461 // check selected filename
1462 if (filename.empty()) {
1463 // emit message signal.
1464 message(_("Canceled."));
1469 // Get absolute path of file and add ".lyx"
1470 // to the filename if necessary
1471 filename = fileSearch(string(), filename, "lyx").absFilename();
1473 docstring const disp_fn = makeDisplayPath(filename);
1474 // emit message signal.
1475 message(bformat(_("Inserting document %1$s..."), disp_fn));
1478 Buffer buf("", false);
1479 if (lyx::loadLyXFile(&buf, FileName(filename))) {
1480 ErrorList & el = buffer_.errorList("Parse");
1481 // Copy the inserted document error list into the current buffer one.
1482 el = buf.errorList("Parse");
1483 recordUndo(cursor_);
1484 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1485 buf.params().textclass, el);
1486 res = _("Document %1$s inserted.");
1488 res = _("Could not insert document %1$s");
1490 // emit message signal.
1491 message(bformat(res, disp_fn));
1492 buffer_.errors("Parse");
1493 updateMetrics(false);