3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Alfredo Braunstein
7 * \author Lars Gullik Bjønnes
10 * \author Jürgen Vigna
12 * Full author contact details are available in file CREDITS.
17 #include "BufferView.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
23 #include "CoordCache.h"
25 #include "CutAndPaste.h"
26 #include "DispatchResult.h"
27 #include "EmbeddedFiles.h"
28 #include "ErrorList.h"
30 #include "FloatList.h"
31 #include "FuncRequest.h"
32 #include "FuncStatus.h"
34 #include "InsetIterator.h"
36 #include "LaTeXFeatures.h"
42 #include "MenuBackend.h"
43 #include "MetricsInfo.h"
44 #include "Paragraph.h"
45 #include "paragraph_funcs.h"
46 #include "ParagraphParameters.h"
47 #include "ParIterator.h"
50 #include "TextClass.h"
51 #include "TextMetrics.h"
54 #include "WordLangTuple.h"
56 #include "insets/InsetBibtex.h"
57 #include "insets/InsetCommand.h" // ChangeRefs
58 #include "insets/InsetRef.h"
59 #include "insets/InsetText.h"
61 #include "frontends/alert.h"
62 #include "frontends/Application.h"
63 #include "frontends/Delegates.h"
64 #include "frontends/FontMetrics.h"
65 #include "frontends/Painter.h"
66 #include "frontends/Selection.h"
68 #include "graphics/Previews.h"
70 #include "support/convert.h"
71 #include "support/debug.h"
72 #include "support/FileFilterList.h"
73 #include "support/filetools.h"
74 #include "support/gettext.h"
75 #include "support/lstrings.h"
76 #include "support/Package.h"
77 #include "support/types.h"
86 using namespace lyx::support;
90 namespace Alert = frontend::Alert;
94 /// Return an inset of this class if it exists at the current cursor position
96 T * getInsetByCode(Cursor const & cur, InsetCode code)
99 Inset * inset = it.nextInset();
100 if (inset && inset->lyxCode() == code)
101 return static_cast<T*>(inset);
106 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
109 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
110 docstring const & contents)
112 DocIterator tmpdit = dit;
115 Inset const * inset = tmpdit.nextInset();
117 && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()
118 && (contents.empty() ||
119 static_cast<InsetCommand const *>(inset)->getFirstNonOptParam() == contents)) {
123 tmpdit.forwardInset();
130 /// Looks for next inset with one of the given codes.
131 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
135 DocIterator tmpdit = dit;
136 tmpdit.forwardInset();
141 Inset const * inset = tmpdit.nextInset();
143 && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()) {
144 contents = static_cast<InsetCommand const *>(inset)->getFirstNonOptParam();
148 if (!findNextInset(tmpdit, codes, contents)) {
149 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
150 tmpdit = doc_iterator_begin(tmpdit.bottom().inset());
151 if (!findNextInset(tmpdit, codes, contents))
162 /// Looks for next inset with the given code
163 void findInset(DocIterator & dit, InsetCode code, bool same_content)
165 findInset(dit, vector<InsetCode>(1, code), same_content);
169 /// Moves cursor to the next inset with one of the given codes.
170 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
173 Cursor tmpcur = bv->cursor();
174 if (!findInset(tmpcur, codes, same_content)) {
175 bv->cursor().message(_("No more insets"));
179 tmpcur.clearSelection();
180 bv->setCursor(tmpcur);
185 /// Moves cursor to the next inset with given code.
186 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
188 gotoInset(bv, vector<InsetCode>(1, code), same_content);
192 /// A map from a Text to the associated text metrics
193 typedef map<Text const *, TextMetrics> TextMetricsCache;
195 enum ScreenUpdateStrategy {
205 /////////////////////////////////////////////////////////////////////
209 /////////////////////////////////////////////////////////////////////
211 struct BufferView::Private
213 Private(BufferView & bv): wh_(0), cursor_(bv),
214 anchor_pit_(0), anchor_ypos_(0),
215 last_inset_(0), gui_(0)
219 ScrollbarParameters scrollbarParameters_;
221 ScreenUpdateStrategy update_strategy_;
223 CoordCache coord_cache_;
225 /// Estimated average par height for scrollbar.
227 /// this is used to handle XSelection events in the right manner.
236 pit_type anchor_pit_;
240 vector<int> par_height_;
242 /// keyboard mapping object.
245 /// last visited inset.
246 /** kept to send setMouseHover(false).
247 * Not owned, so don't delete.
251 mutable TextMetricsCache text_metrics_;
254 /** Not owned, so don't delete.
256 frontend::GuiBufferViewDelegate * gui_;
260 BufferView::BufferView(Buffer & buf)
261 : width_(0), height_(0), buffer_(buf), d(new Private(*this))
263 d->xsel_cache_.set = false;
264 d->intl_.initKeyMapper(lyxrc.use_kbmap);
266 d->cursor_.push(buffer_.inset());
267 d->cursor_.resetAnchor();
268 d->cursor_.setCurrentFont();
270 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
271 graphics::Previews::get().generateBufferPreviews(buffer_);
275 BufferView::~BufferView()
277 // current buffer is going to be switched-off, save cursor pos
278 // Ideally, the whole cursor stack should be saved, but session
279 // currently can only handle bottom (whole document) level pit and pos.
280 // That is to say, if a cursor is in a nested inset, it will be
281 // restore to the left of the top level inset.
282 LastFilePosSection::FilePos fp;
283 fp.pit = d->cursor_.bottom().pit();
284 fp.pos = d->cursor_.bottom().pos();
285 LyX::ref().session().lastFilePos().save(buffer_.fileName(), fp);
291 Intl & BufferView::getIntl()
297 Intl const & BufferView::getIntl() const
303 CoordCache & BufferView::coordCache()
305 return d->coord_cache_;
309 CoordCache const & BufferView::coordCache() const
311 return d->coord_cache_;
315 Buffer & BufferView::buffer()
321 Buffer const & BufferView::buffer() const
327 bool BufferView::fitCursor()
329 if (cursorStatus(d->cursor_) == CUR_INSIDE) {
330 frontend::FontMetrics const & fm =
331 theFontMetrics(d->cursor_.getFont().fontInfo());
332 int const asc = fm.maxAscent();
333 int const des = fm.maxDescent();
334 Point const p = getPos(d->cursor_, d->cursor_.boundary());
335 if (p.y_ - asc >= 0 && p.y_ + des < height_)
342 void BufferView::processUpdateFlags(Update::flags flags)
344 // last_inset_ points to the last visited inset. This pointer may become
345 // invalid because of keyboard editing. Since all such operations
346 // causes screen update(), I reset last_inset_ to avoid such a problem.
348 // This is close to a hot-path.
349 LYXERR(Debug::DEBUG, "BufferView::processUpdateFlags()"
350 << "[fitcursor = " << (flags & Update::FitCursor)
351 << ", forceupdate = " << (flags & Update::Force)
352 << ", singlepar = " << (flags & Update::SinglePar)
353 << "] buffer: " << &buffer_);
355 buffer_.updateMacros();
357 // Now do the first drawing step if needed. This consists on updating
358 // the CoordCache in updateMetrics().
359 // The second drawing step is done in WorkArea::redraw() if needed.
361 // Case when no explicit update is requested.
363 // no need to redraw anything.
364 d->update_strategy_ = NoScreenUpdate;
368 if (flags == Update::Decoration) {
369 d->update_strategy_ = DecorationUpdate;
374 if (flags == Update::FitCursor
375 || flags == (Update::Decoration | Update::FitCursor)) {
376 // tell the frontend to update the screen if needed.
381 if (flags & Update::Decoration) {
382 d->update_strategy_ = DecorationUpdate;
386 // no screen update is needed.
387 d->update_strategy_ = NoScreenUpdate;
391 bool const full_metrics = flags & Update::Force || !singleParUpdate();
394 // We have to update the full screen metrics.
397 if (!(flags & Update::FitCursor)) {
398 // Nothing to do anymore. Trigger a redraw and return
403 // updateMetrics() does not update paragraph position
404 // This is done at draw() time. So we need a redraw!
408 // The cursor is off screen so ensure it is visible.
415 void BufferView::updateScrollbar()
420 Text & t = buffer_.text();
421 TextMetrics & tm = d->text_metrics_[&t];
423 LYXERR(Debug::GUI, " Updating scrollbar: height: "
424 << t.paragraphs().size()
425 << " curr par: " << d->cursor_.bottom().pit()
426 << " default height " << defaultRowHeight());
428 int const parsize = int(t.paragraphs().size());
429 if (d->par_height_.size() != parsize) {
430 d->par_height_.clear();
431 // FIXME: We assume a default paragraph height of 2 rows. This
432 // should probably be pondered with the screen width.
433 d->par_height_.resize(parsize, defaultRowHeight() * 2);
436 // It would be better to fix the scrollbar to understand
437 // values in [0..1] and divide everything by wh
439 // Look at paragraph heights on-screen
440 pit_type first_visible_pit = -1;
441 pair<pit_type, ParagraphMetrics const *> first = tm.first();
442 pair<pit_type, ParagraphMetrics const *> last = tm.last();
443 for (pit_type pit = first.first; pit <= last.first; ++pit) {
444 ParagraphMetrics const & pm = tm.parMetrics(pit);
445 d->par_height_[pit] = pm.height();
446 if (first_visible_pit >= 0 || pm.position() + pm.descent() <= 0)
448 first_visible_pit = pit;
449 LYXERR(Debug::SCROLLING, "first visible pit " << first_visible_pit);
450 // FIXME: we should look for the first visible row within
451 // the deepest inset!
452 int row_pos = pm.position();
453 size_t const nrows = pm.rows().size();
454 for (size_t i = 0; i != nrows; ++i) {
455 Row const & row = pm.rows()[i];
457 LYXERR(Debug::SCROLLING, "first visible row " << i
458 << "(row pos = " << row_pos << ");");
461 row_pos += row.height();
463 d->scrollbarParameters_.position = row_pos;
466 d->scrollbarParameters_.height = 0;
467 for (size_t i = 0; i != d->par_height_.size(); ++i) {
468 if (i == first_visible_pit)
469 d->scrollbarParameters_.position += d->scrollbarParameters_.height;
470 d->scrollbarParameters_.height += d->par_height_[i];
473 // We prefer fixed size line scrolling.
474 d->scrollbarParameters_.lineScrollHeight = defaultRowHeight();
478 ScrollbarParameters const & BufferView::scrollbarParameters() const
480 return d->scrollbarParameters_;
484 docstring BufferView::toolTip(int x, int y) const
486 // Get inset under mouse, if there is one.
487 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
489 // No inset, no tooltip...
491 return covering_inset->toolTip(*this, x, y);
495 docstring BufferView::contextMenu(int x, int y) const
497 // Get inset under mouse, if there is one.
498 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
500 return covering_inset->contextMenu(*this, x, y);
502 // FIXME: Do something more elaborate here.
503 return from_ascii("edit");
507 void BufferView::scrollDocView(int value)
509 int const offset = value - d->scrollbarParameters_.position;
510 // If the offset is less than 2 screen height, prefer to scroll instead.
511 if (abs(offset) <= 2 * height_) {
517 for (size_t i = 0; i != d->par_height_.size(); ++i) {
518 par_pos += d->par_height_[i];
519 if (par_pos >= value) {
520 d->anchor_pit_ = pit_type(i);
525 LYXERR(Debug::SCROLLING, "value = " << value
526 << "\tanchor_ref_ = " << d->anchor_pit_
527 << "\tpar_pos = " << par_pos);
529 d->anchor_ypos_ = par_pos - value;
535 // FIXME: this method is not working well.
536 void BufferView::setCursorFromScrollbar()
538 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
540 int const height = 2 * defaultRowHeight();
541 int const first = height;
542 int const last = height_ - height;
543 Cursor & cur = d->cursor_;
545 switch (cursorStatus(cur)) {
547 // We reset the cursor because cursorStatus() does not
548 // work when the cursor is within mathed.
549 cur.reset(buffer_.inset());
550 tm.setCursorFromCoordinates(cur, 0, first);
551 cur.clearSelection();
554 // We reset the cursor because cursorStatus() does not
555 // work when the cursor is within mathed.
556 cur.reset(buffer_.inset());
557 tm.setCursorFromCoordinates(cur, 0, last);
558 cur.clearSelection();
561 int const y = getPos(cur, cur.boundary()).y_;
562 int const newy = min(last, max(y, first));
564 cur.reset(buffer_.inset());
565 tm.setCursorFromCoordinates(cur, 0, newy);
571 Change const BufferView::getCurrentChange() const
573 if (!d->cursor_.selection())
574 return Change(Change::UNCHANGED);
576 DocIterator dit = d->cursor_.selectionBegin();
577 return dit.paragraph().lookupChange(dit.pos());
581 // this could be used elsewhere as well?
582 // FIXME: This does not work within mathed!
583 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
585 Point const p = getPos(dit, dit.boundary());
588 if (p.y_ > workHeight())
594 void BufferView::saveBookmark(unsigned int idx)
596 // tenatively save bookmark, id and pos will be used to
597 // acturately locate a bookmark in a 'live' lyx session.
598 // pit and pos will be updated with bottom level pit/pos
600 LyX::ref().session().bookmarks().save(
602 d->cursor_.bottom().pit(),
603 d->cursor_.bottom().pos(),
604 d->cursor_.paragraph().id(),
609 // emit message signal.
610 message(_("Save bookmark"));
614 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
615 int top_id, pos_type top_pos)
617 bool success = false;
620 d->cursor_.clearSelection();
622 // if a valid par_id is given, try it first
623 // This is the case for a 'live' bookmark when unique paragraph ID
624 // is used to track bookmarks.
626 ParIterator par = buffer_.getParFromID(top_id);
627 if (par != buffer_.par_iterator_end()) {
628 doc_it = makeDocIterator(par, min(par->size(), top_pos));
629 // Some slices of the iterator may not be
630 // reachable (e.g. closed collapsable inset)
631 // so the dociterator may need to be
632 // shortened. Otherwise, setCursor may crash
633 // lyx when the cursor can not be set to these
635 size_t const n = doc_it.depth();
636 for (size_t i = 0; i < n; ++i)
637 if (doc_it[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
645 // if top_id == 0, or searching through top_id failed
646 // This is the case for a 'restored' bookmark when only bottom
647 // (document level) pit was saved. Because of this, bookmark
648 // restoration is inaccurate. If a bookmark was within an inset,
649 // it will be restored to the left of the outmost inset that contains
651 if (static_cast<size_t>(bottom_pit) < buffer_.paragraphs().size()) {
652 doc_it = doc_iterator_begin(buffer_.inset());
653 doc_it.pit() = bottom_pit;
654 doc_it.pos() = min(bottom_pos, doc_it.paragraph().size());
659 // Note: only bottom (document) level pit is set.
661 // set the current font.
662 d->cursor_.setCurrentFont();
663 // To center the screen on this new position we need the
664 // paragraph position which is computed at draw() time.
665 // So we need a redraw!
675 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
677 if (lyxrc.rtl_support) {
678 if (d->cursor_.real_current_font.isRightToLeft()) {
679 if (d->intl_.keymap == Intl::PRIMARY)
680 d->intl_.keyMapSec();
682 if (d->intl_.keymap == Intl::SECONDARY)
683 d->intl_.keyMapPrim();
687 d->intl_.getTransManager().translateAndInsert(c, t, cur);
691 int BufferView::workWidth() const
697 void BufferView::showCursor()
699 // We are not properly started yet, delay until resizing is
704 LYXERR(Debug::SCROLLING, "recentering!");
706 CursorSlice & bot = d->cursor_.bottom();
707 TextMetrics & tm = d->text_metrics_[bot.text()];
709 pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
710 int bot_pit = d->cursor_.bottom().pit();
711 if (bot_pit > max_pit) {
712 // FIXME: Why does this happen?
713 LYXERR0("bottom pit is greater that max pit: "
714 << bot_pit << " > " << max_pit);
718 if (bot_pit == tm.first().first - 1)
719 tm.newParMetricsUp();
720 else if (bot_pit == tm.last().first + 1)
721 tm.newParMetricsDown();
723 if (tm.has(bot_pit)) {
724 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
725 int offset = coordOffset(d->cursor_, d->cursor_.boundary()).y_;
726 int ypos = pm.position() + offset;
727 Dimension const & row_dim = d->cursor_.textRow().dimension();
728 if (ypos - row_dim.ascent() < 0)
729 scrollUp(- ypos + row_dim.ascent());
730 else if (ypos + row_dim.descent() > height_)
731 scrollDown(ypos - height_ + row_dim.descent());
732 // else, nothing to do, the cursor is already visible so we just return.
736 tm.redoParagraph(bot_pit);
737 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
738 int offset = coordOffset(d->cursor_, d->cursor_.boundary()).y_;
740 d->anchor_pit_ = bot_pit;
741 Dimension const & row_dim = d->cursor_.textRow().dimension();
743 if (d->anchor_pit_ == 0)
744 d->anchor_ypos_ = offset + pm.ascent();
745 else if (d->anchor_pit_ == max_pit)
746 d->anchor_ypos_ = height_ - offset - row_dim.descent();
748 d->anchor_ypos_ = offset + pm.ascent() - height_ / 2;
755 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
759 Cursor & cur = d->cursor_;
761 switch (cmd.action) {
764 flag.enabled(buffer_.undo().hasUndoStack());
767 flag.enabled(buffer_.undo().hasRedoStack());
769 case LFUN_FILE_INSERT:
770 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
771 case LFUN_FILE_INSERT_PLAINTEXT:
772 case LFUN_BOOKMARK_SAVE:
773 // FIXME: Actually, these LFUNS should be moved to Text
774 flag.enabled(cur.inTexted());
776 case LFUN_FONT_STATE:
777 case LFUN_LABEL_INSERT:
778 case LFUN_INFO_INSERT:
779 case LFUN_PARAGRAPH_GOTO:
781 case LFUN_REFERENCE_NEXT:
783 case LFUN_WORD_REPLACE:
786 case LFUN_MARK_TOGGLE:
787 case LFUN_SCREEN_RECENTER:
788 case LFUN_BIBTEX_DATABASE_ADD:
789 case LFUN_BIBTEX_DATABASE_DEL:
790 case LFUN_WORDS_COUNT:
791 case LFUN_NEXT_INSET_TOGGLE:
795 case LFUN_LABEL_GOTO: {
796 flag.enabled(!cmd.argument().empty()
797 || getInsetByCode<InsetRef>(cur, REF_CODE));
801 case LFUN_CHANGES_TRACK:
803 flag.setOnOff(buffer_.params().trackChanges);
806 case LFUN_CHANGES_OUTPUT:
808 flag.setOnOff(buffer_.params().outputChanges);
811 case LFUN_CHANGES_MERGE:
812 case LFUN_CHANGE_NEXT:
813 case LFUN_ALL_CHANGES_ACCEPT:
814 case LFUN_ALL_CHANGES_REJECT:
815 // TODO: context-sensitive enabling of LFUNs
816 // In principle, these command should only be enabled if there
817 // is a change in the document. However, without proper
818 // optimizations, this will inevitably result in poor performance.
822 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
823 flag.setOnOff(buffer_.params().compressed);
827 case LFUN_BUFFER_TOGGLE_EMBEDDING: {
828 flag.setOnOff(buffer_.params().embedded);
833 case LFUN_SCREEN_DOWN:
837 // FIXME: LFUN_SCREEN_DOWN_SELECT should be removed from
838 // everywhere else before this can enabled:
839 case LFUN_SCREEN_UP_SELECT:
840 case LFUN_SCREEN_DOWN_SELECT:
844 case LFUN_LAYOUT_TABULAR:
845 flag.enabled(cur.innerInsetOfType(TABULAR_CODE));
849 case LFUN_LAYOUT_PARAGRAPH:
850 flag.enabled(cur.inset().forceDefaultParagraphs(cur.idx()));
853 case LFUN_INSET_SETTINGS: {
854 InsetCode code = cur.inset().lyxCode();
858 enable = cmd.argument() == "tabular";
861 enable = cmd.argument() == "ert";
864 enable = cmd.argument() == "float";
867 enable = cmd.argument() == "wrap";
870 enable = cmd.argument() == "note";
873 enable = cmd.argument() == "branch";
876 enable = cmd.argument() == "box";
879 enable = cmd.argument() == "listings";
884 flag.enabled(enable);
888 case LFUN_DIALOG_SHOW_NEW_INSET:
889 flag.enabled(cur.inset().lyxCode() != ERT_CODE &&
890 cur.inset().lyxCode() != LISTINGS_CODE);
891 if (cur.inset().lyxCode() == CAPTION_CODE) {
893 if (cur.inset().getStatus(cur, cmd, flag))
906 bool BufferView::dispatch(FuncRequest const & cmd)
908 //lyxerr << [ cmd = " << cmd << "]" << endl;
910 // Make sure that the cached BufferView is correct.
911 LYXERR(Debug::ACTION, " action[" << cmd.action << ']'
912 << " arg[" << to_utf8(cmd.argument()) << ']'
913 << " x[" << cmd.x << ']'
914 << " y[" << cmd.y << ']'
915 << " button[" << cmd.button() << ']');
917 Cursor & cur = d->cursor_;
919 switch (cmd.action) {
922 cur.message(_("Undo"));
923 cur.clearSelection();
925 cur.message(_("No further undo information"));
929 cur.message(_("Redo"));
930 cur.clearSelection();
932 cur.message(_("No further redo information"));
935 case LFUN_FONT_STATE:
936 cur.message(cur.currentState());
939 case LFUN_BOOKMARK_SAVE:
940 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
943 case LFUN_LABEL_GOTO: {
944 docstring label = cmd.argument();
947 getInsetByCode<InsetRef>(d->cursor_,
950 label = inset->getParam("reference");
951 // persistent=false: use temp_bookmark
961 case LFUN_PARAGRAPH_GOTO: {
962 int const id = convert<int>(to_utf8(cmd.argument()));
964 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
965 b = theBufferList().next(b)) {
967 ParIterator par = b->getParFromID(id);
968 if (par == b->par_iterator_end()) {
969 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
971 LYXERR(Debug::INFO, "Paragraph " << par->id()
972 << " found in buffer `"
973 << b->absFileName() << "'.");
977 setCursor(makeDocIterator(par, 0));
980 // Switch to other buffer view and resend cmd
981 theLyXFunc().dispatch(FuncRequest(
982 LFUN_BUFFER_SWITCH, b->absFileName()));
983 theLyXFunc().dispatch(cmd);
993 gotoInset(this, NOTE_CODE, false);
996 case LFUN_REFERENCE_NEXT: {
997 vector<InsetCode> tmp;
998 tmp.push_back(LABEL_CODE);
999 tmp.push_back(REF_CODE);
1000 gotoInset(this, tmp, true);
1004 case LFUN_CHANGES_TRACK:
1005 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1008 case LFUN_CHANGES_OUTPUT:
1009 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1010 if (buffer_.params().outputChanges) {
1011 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1012 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1013 LaTeXFeatures::isAvailable("xcolor");
1015 if (!dvipost && !xcolorsoul) {
1016 Alert::warning(_("Changes not shown in LaTeX output"),
1017 _("Changes will not be highlighted in LaTeX output, "
1018 "because neither dvipost nor xcolor/soul are installed.\n"
1019 "Please install these packages or redefine "
1020 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1021 } else if (!xcolorsoul) {
1022 Alert::warning(_("Changes not shown in LaTeX output"),
1023 _("Changes will not be highlighted in LaTeX output "
1024 "when using pdflatex, because xcolor and soul are not installed.\n"
1025 "Please install both packages or redefine "
1026 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1031 case LFUN_CHANGE_NEXT:
1032 findNextChange(this);
1035 case LFUN_CHANGES_MERGE:
1036 if (findNextChange(this))
1037 showDialog("changes");
1040 case LFUN_ALL_CHANGES_ACCEPT:
1041 // select complete document
1042 d->cursor_.reset(buffer_.inset());
1043 d->cursor_.selHandle(true);
1044 buffer_.text().cursorBottom(d->cursor_);
1045 // accept everything in a single step to support atomic undo
1046 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::ACCEPT);
1049 case LFUN_ALL_CHANGES_REJECT:
1050 // select complete document
1051 d->cursor_.reset(buffer_.inset());
1052 d->cursor_.selHandle(true);
1053 buffer_.text().cursorBottom(d->cursor_);
1054 // reject everything in a single step to support atomic undo
1055 // Note: reject does not work recursively; the user may have to repeat the operation
1056 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::REJECT);
1059 case LFUN_WORD_FIND:
1063 case LFUN_WORD_REPLACE: {
1064 bool has_deleted = false;
1065 if (cur.selection()) {
1066 DocIterator beg = cur.selectionBegin();
1067 DocIterator end = cur.selectionEnd();
1068 if (beg.pit() == end.pit()) {
1069 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1070 if (cur.paragraph().isDeleted(p))
1075 replace(this, cmd, has_deleted);
1080 cur.clearSelection();
1082 cur.message(from_utf8(N_("Mark off")));
1086 cur.clearSelection();
1089 cur.message(from_utf8(N_("Mark on")));
1092 case LFUN_MARK_TOGGLE:
1093 cur.clearSelection();
1096 cur.message(from_utf8(N_("Mark removed")));
1099 cur.message(from_utf8(N_("Mark set")));
1104 case LFUN_SCREEN_RECENTER:
1108 case LFUN_BIBTEX_DATABASE_ADD: {
1109 Cursor tmpcur = d->cursor_;
1110 findInset(tmpcur, BIBTEX_CODE, false);
1111 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1114 if (inset->addDatabase(to_utf8(cmd.argument())))
1115 buffer_.updateBibfilesCache();
1120 case LFUN_BIBTEX_DATABASE_DEL: {
1121 Cursor tmpcur = d->cursor_;
1122 findInset(tmpcur, BIBTEX_CODE, false);
1123 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1126 if (inset->delDatabase(to_utf8(cmd.argument())))
1127 buffer_.updateBibfilesCache();
1132 case LFUN_WORDS_COUNT: {
1133 DocIterator from, to;
1134 if (cur.selection()) {
1135 from = cur.selectionBegin();
1136 to = cur.selectionEnd();
1138 from = doc_iterator_begin(buffer_.inset());
1139 to = doc_iterator_end(buffer_.inset());
1141 int const count = countWords(from, to);
1144 if (cur.selection())
1145 message = bformat(_("%1$d words in selection."),
1148 message = bformat(_("%1$d words in document."),
1152 if (cur.selection())
1153 message = _("One word in selection.");
1155 message = _("One word in document.");
1158 Alert::information(_("Count words"), message);
1162 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1163 // turn compression on/off
1164 buffer_.params().compressed = !buffer_.params().compressed;
1167 case LFUN_BUFFER_TOGGLE_EMBEDDING:
1168 // turn embedding on/off
1169 buffer_.embeddedFiles().enable(!buffer_.params().embedded);
1172 case LFUN_NEXT_INSET_TOGGLE: {
1173 // this is the real function we want to invoke
1174 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1175 // if there is an inset at cursor, see whether it
1177 Inset * inset = cur.nextInset();
1179 if (inset->isActive()) {
1180 Cursor tmpcur = cur;
1181 tmpcur.pushBackward(*inset);
1182 inset->dispatch(tmpcur, tmpcmd);
1183 if (tmpcur.result().dispatched()) {
1186 } else if (inset->editable() == Inset::IS_EDITABLE) {
1187 inset->edit(cur, true);
1190 // if it did not work, try the underlying inset.
1191 if (!cur.result().dispatched())
1192 cur.dispatch(tmpcmd);
1194 if (cur.result().dispatched())
1195 cur.clearSelection();
1200 case LFUN_SCREEN_UP:
1201 case LFUN_SCREEN_DOWN: {
1202 Point p = getPos(cur, cur.boundary());
1203 if (p.y_ < 0 || p.y_ > height_) {
1204 // The cursor is off-screen so recenter before proceeding.
1206 p = getPos(cur, cur.boundary());
1208 scroll(cmd.action == LFUN_SCREEN_UP? - height_ : height_);
1209 cur.reset(buffer_.inset());
1210 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1211 //FIXME: what to do with cur.x_target()?
1216 case LFUN_SCREEN_UP_SELECT:
1217 case LFUN_SCREEN_DOWN_SELECT: {
1218 // Those two are not ready yet for consumption.
1221 cur.selHandle(true);
1222 size_t initial_depth = cur.depth();
1223 Point const p = getPos(cur, cur.boundary());
1224 scroll(cmd.action == LFUN_SCREEN_UP_SELECT? - height_ : height_);
1225 // FIXME: We need to verify if the cursor stayed within an inset...
1226 //cur.reset(buffer_.inset());
1227 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1229 while (cur.depth() > initial_depth) {
1232 // FIXME: we need to do a redraw again because of the selection
1233 // But no screen update is needed.
1234 d->update_strategy_ = NoScreenUpdate;
1247 docstring const BufferView::requestSelection()
1249 Cursor & cur = d->cursor_;
1251 if (!cur.selection()) {
1252 d->xsel_cache_.set = false;
1256 if (!d->xsel_cache_.set ||
1257 cur.top() != d->xsel_cache_.cursor ||
1258 cur.anchor_.top() != d->xsel_cache_.anchor)
1260 d->xsel_cache_.cursor = cur.top();
1261 d->xsel_cache_.anchor = cur.anchor_.top();
1262 d->xsel_cache_.set = cur.selection();
1263 return cur.selectionAsString(false);
1269 void BufferView::clearSelection()
1271 d->cursor_.clearSelection();
1272 // Clear the selection buffer. Otherwise a subsequent
1273 // middle-mouse-button paste would use the selection buffer,
1274 // not the more current external selection.
1275 cap::clearSelection();
1276 d->xsel_cache_.set = false;
1277 // The buffer did not really change, but this causes the
1278 // redraw we need because we cleared the selection above.
1283 void BufferView::resize(int width, int height)
1285 // Update from work area
1289 // Clear the paragraph height cache.
1290 d->par_height_.clear();
1296 Inset const * BufferView::getCoveringInset(Text const & text,
1299 TextMetrics & tm = d->text_metrics_[&text];
1300 Inset * inset = tm.checkInsetHit(x, y);
1304 if (!inset->descendable())
1305 // No need to go further down if the inset is not
1309 size_t cell_number = inset->nargs();
1310 // Check all the inner cell.
1311 for (size_t i = 0; i != cell_number; ++i) {
1312 Text const * inner_text = inset->getText(i);
1315 Inset const * inset_deeper =
1316 getCoveringInset(*inner_text, x, y);
1318 return inset_deeper;
1326 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1328 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
1330 // This is only called for mouse related events including
1331 // LFUN_FILE_OPEN generated by drag-and-drop.
1332 FuncRequest cmd = cmd0;
1335 cur.push(buffer_.inset());
1336 cur.selection() = d->cursor_.selection();
1338 // Either the inset under the cursor or the
1339 // surrounding Text will handle this event.
1341 // make sure we stay within the screen...
1342 cmd.y = min(max(cmd.y, -1), height_);
1344 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1346 // Get inset under mouse, if there is one.
1347 Inset const * covering_inset =
1348 getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1349 if (covering_inset == d->last_inset_)
1350 // Same inset, no need to do anything...
1353 bool need_redraw = false;
1354 // const_cast because of setMouseHover().
1355 Inset * inset = const_cast<Inset *>(covering_inset);
1357 // Remove the hint on the last hovered inset (if any).
1358 need_redraw |= d->last_inset_->setMouseHover(false);
1360 // Highlighted the newly hovered inset (if any).
1361 need_redraw |= inset->setMouseHover(true);
1362 d->last_inset_ = inset;
1366 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
1367 << cmd.x << ", " << cmd.y << ")");
1369 d->update_strategy_ = DecorationUpdate;
1371 // This event (moving without mouse click) is not passed further.
1372 // This should be changed if it is further utilized.
1377 // Build temporary cursor.
1378 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1380 // Put anchor at the same position.
1383 // Try to dispatch to an non-editable inset near this position
1384 // via the temp cursor. If the inset wishes to change the real
1385 // cursor it has to do so explicitly by using
1386 // cur.bv().cursor() = cur; (or similar)
1388 inset->dispatch(cur, cmd);
1390 // Now dispatch to the temporary cursor. If the real cursor should
1391 // be modified, the inset's dispatch has to do so explicitly.
1392 if (!cur.result().dispatched())
1395 //Do we have a selection?
1396 theSelection().haveSelection(cursor().selection());
1398 // If the command has been dispatched,
1399 if (cur.result().dispatched()
1400 // an update is asked,
1401 && cur.result().update())
1402 processUpdateFlags(cur.result().update());
1406 void BufferView::scroll(int y)
1415 void BufferView::scrollDown(int offset)
1417 Text * text = &buffer_.text();
1418 TextMetrics & tm = d->text_metrics_[text];
1419 int ymax = height_ + offset;
1421 pair<pit_type, ParagraphMetrics const *> last = tm.last();
1422 int bottom_pos = last.second->position() + last.second->descent();
1423 if (last.first + 1 == int(text->paragraphs().size())) {
1424 if (bottom_pos <= height_)
1426 offset = min(offset, bottom_pos - height_);
1429 if (bottom_pos > ymax)
1431 tm.newParMetricsDown();
1433 d->anchor_ypos_ -= offset;
1439 void BufferView::scrollUp(int offset)
1441 Text * text = &buffer_.text();
1442 TextMetrics & tm = d->text_metrics_[text];
1443 int ymin = - offset;
1445 pair<pit_type, ParagraphMetrics const *> first = tm.first();
1446 int top_pos = first.second->position() - first.second->ascent();
1447 if (first.first == 0) {
1450 offset = min(offset, - top_pos);
1455 tm.newParMetricsUp();
1457 d->anchor_ypos_ += offset;
1463 void BufferView::setCursorFromRow(int row)
1468 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1470 d->cursor_.reset(buffer_.inset());
1472 buffer_.text().setCursor(d->cursor_, 0, 0);
1474 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1478 void BufferView::gotoLabel(docstring const & label)
1480 for (InsetIterator it = inset_iterator_begin(buffer_.inset()); it; ++it) {
1481 vector<docstring> labels;
1482 it->getLabelList(buffer_, labels);
1483 if (find(labels.begin(), labels.end(), label) != labels.end()) {
1492 TextMetrics const & BufferView::textMetrics(Text const * t) const
1494 return const_cast<BufferView *>(this)->textMetrics(t);
1498 TextMetrics & BufferView::textMetrics(Text const * t)
1500 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
1501 if (tmc_it == d->text_metrics_.end()) {
1502 tmc_it = d->text_metrics_.insert(
1503 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1505 return tmc_it->second;
1509 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1512 return textMetrics(t).parMetrics(pit);
1516 int BufferView::workHeight() const
1522 void BufferView::setCursor(DocIterator const & dit)
1524 size_t const n = dit.depth();
1525 for (size_t i = 0; i < n; ++i)
1526 dit[i].inset().edit(d->cursor_, true);
1528 d->cursor_.setCursor(dit);
1529 d->cursor_.selection() = false;
1533 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1535 // Would be wrong to delete anything if we have a selection.
1536 if (cur.selection())
1539 bool need_anchor_change = false;
1540 bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1541 need_anchor_change);
1543 if (need_anchor_change)
1549 updateLabels(buffer_);
1557 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
1559 BOOST_ASSERT(&cur.bv() == this);
1562 // this event will clear selection so we save selection for
1563 // persistent selection
1564 cap::saveSelection(cursor());
1566 // Has the cursor just left the inset?
1567 bool badcursor = false;
1568 bool leftinset = (&d->cursor_.inset() != &cur.inset());
1570 badcursor = notifyCursorLeaves(d->cursor_, cur);
1572 // FIXME: shift-mouse selection doesn't work well across insets.
1573 bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
1575 // do the dEPM magic if needed
1576 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1577 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1578 // the leftinset bool would not be necessary (badcursor instead).
1579 bool update = leftinset;
1580 if (!do_selection && !badcursor && d->cursor_.inTexted())
1581 update |= checkDepm(cur, d->cursor_);
1583 // if the cursor was in an empty script inset and the new
1584 // position is in the nucleus of the inset, notifyCursorLeaves
1585 // will kill the script inset itself. So we check all the
1586 // elements of the cursor to make sure that they are correct.
1587 // For an example, see bug 2933:
1588 // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1589 // The code below could maybe be moved to a DocIterator method.
1590 //lyxerr << "cur before " << cur <<endl;
1591 DocIterator dit(cur.inset());
1592 dit.push_back(cur.bottom());
1594 while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1595 dit.push_back(cur[i]);
1598 //lyxerr << "5 cur after" << dit <<endl;
1600 d->cursor_.setCursor(dit);
1601 d->cursor_.boundary(cur.boundary());
1603 d->cursor_.setSelection();
1605 d->cursor_.clearSelection();
1607 d->cursor_.finishUndo();
1608 d->cursor_.setCurrentFont();
1613 void BufferView::putSelectionAt(DocIterator const & cur,
1614 int length, bool backwards)
1616 d->cursor_.clearSelection();
1622 d->cursor_.pos() += length;
1623 d->cursor_.setSelection(d->cursor_, -length);
1625 d->cursor_.setSelection(d->cursor_, length);
1630 Cursor & BufferView::cursor()
1636 Cursor const & BufferView::cursor() const
1642 pit_type BufferView::anchor_ref() const
1644 return d->anchor_pit_;
1648 bool BufferView::singleParUpdate()
1650 Text & buftext = buffer_.text();
1651 pit_type const bottom_pit = d->cursor_.bottom().pit();
1652 TextMetrics & tm = textMetrics(&buftext);
1653 int old_height = tm.parMetrics(bottom_pit).height();
1655 // In Single Paragraph mode, rebreak only
1656 // the (main text, not inset!) paragraph containing the cursor.
1657 // (if this paragraph contains insets etc., rebreaking will
1658 // recursively descend)
1659 tm.redoParagraph(bottom_pit);
1660 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
1661 if (pm.height() != old_height)
1662 // Paragraph height has changed so we cannot proceed to
1663 // the singlePar optimisation.
1666 d->update_strategy_ = SingleParUpdate;
1668 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
1669 << " y2: " << pm.position() + pm.descent()
1670 << " pit: " << bottom_pit
1671 << " singlepar: 1");
1676 void BufferView::updateMetrics()
1678 Text & buftext = buffer_.text();
1679 pit_type const npit = int(buftext.paragraphs().size());
1681 // Clear out the position cache in case of full screen redraw,
1682 d->coord_cache_.clear();
1684 // Clear out paragraph metrics to avoid having invalid metrics
1685 // in the cache from paragraphs not relayouted below
1686 // The complete text metrics will be redone.
1687 d->text_metrics_.clear();
1689 TextMetrics & tm = textMetrics(&buftext);
1691 // Rebreak anchor paragraph.
1692 tm.redoParagraph(d->anchor_pit_);
1693 ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
1694 anchor_pm.setPosition(d->anchor_ypos_);
1696 LYXERR(Debug::PAINTING, "metrics: "
1697 << " anchor pit = " << d->anchor_pit_
1698 << " anchor ypos = " << d->anchor_ypos_);
1700 // Redo paragraphs above anchor if necessary.
1701 int y1 = d->anchor_ypos_ - anchor_pm.ascent();
1702 // We are now just above the anchor paragraph.
1703 pit_type pit1 = d->anchor_pit_ - 1;
1704 for (; pit1 >= 0 && y1 >= 0; --pit1) {
1705 tm.redoParagraph(pit1);
1706 ParagraphMetrics & pm = tm.par_metrics_[pit1];
1708 // Save the paragraph position in the cache.
1713 // Redo paragraphs below the anchor if necessary.
1714 int y2 = d->anchor_ypos_ + anchor_pm.descent();
1715 // We are now just below the anchor paragraph.
1716 pit_type pit2 = d->anchor_pit_ + 1;
1717 for (; pit2 < npit && y2 <= height_; ++pit2) {
1718 tm.redoParagraph(pit2);
1719 ParagraphMetrics & pm = tm.par_metrics_[pit2];
1721 // Save the paragraph position in the cache.
1726 LYXERR(Debug::PAINTING, "Metrics: "
1727 << " anchor pit = " << d->anchor_pit_
1728 << " anchor ypos = " << d->anchor_ypos_
1731 << " pit1 = " << pit1
1732 << " pit2 = " << pit2);
1734 d->update_strategy_ = FullScreenUpdate;
1736 if (lyxerr.debugging(Debug::WORKAREA)) {
1737 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
1738 d->coord_cache_.dump();
1743 void BufferView::insertLyXFile(FileName const & fname)
1745 BOOST_ASSERT(d->cursor_.inTexted());
1747 // Get absolute path of file and add ".lyx"
1748 // to the filename if necessary
1749 FileName filename = fileSearch(string(), fname.absFilename(), "lyx");
1751 docstring const disp_fn = makeDisplayPath(filename.absFilename());
1752 // emit message signal.
1753 message(bformat(_("Inserting document %1$s..."), disp_fn));
1756 Buffer buf("", false);
1757 if (buf.loadLyXFile(filename)) {
1758 ErrorList & el = buffer_.errorList("Parse");
1759 // Copy the inserted document error list into the current buffer one.
1760 el = buf.errorList("Parse");
1761 buffer_.undo().recordUndo(d->cursor_);
1762 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
1763 buf.params().getTextClassPtr(), el);
1764 res = _("Document %1$s inserted.");
1766 res = _("Could not insert document %1$s");
1771 // emit message signal.
1772 message(bformat(res, disp_fn));
1773 buffer_.errors("Parse");
1777 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
1783 // Addup contribution of nested insets, from inside to outside,
1784 // keeping the outer paragraph for a special handling below
1785 for (size_t i = dit.depth() - 1; i >= 1; --i) {
1786 CursorSlice const & sl = dit[i];
1790 // get relative position inside sl.inset()
1791 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
1793 // Make relative position inside of the edited inset relative to sl.inset()
1797 // In case of an RTL inset, the edited inset will be positioned to the left
1800 bool boundary_i = boundary && i + 1 == dit.depth();
1801 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
1806 // remember width for the case that sl.inset() is positioned in an RTL inset
1807 if (i && dit[i - 1].text()) {
1808 // If this Inset is inside a Text Inset, retrieve the Dimension
1809 // from the containing text instead of using Inset::dimension() which
1810 // might not be implemented.
1811 // FIXME (Abdel 23/09/2007): this is a bit messy because of the
1812 // elimination of Inset::dim_ cache. This coordOffset() method needs
1813 // to be rewritten in light of the new design.
1814 Dimension const & dim = parMetrics(dit[i - 1].text(),
1815 dit[i - 1].pit()).insetDimension(&sl.inset());
1818 Dimension const dim = sl.inset().dimension(*this);
1822 //lyxerr << "Cursor::getPos, i: "
1823 // << i << " x: " << xx << " y: " << y << endl;
1826 // Add contribution of initial rows of outermost paragraph
1827 CursorSlice const & sl = dit[0];
1828 TextMetrics const & tm = textMetrics(sl.text());
1829 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
1830 BOOST_ASSERT(!pm.rows().empty());
1831 y -= pm.rows()[0].ascent();
1833 // FIXME: document this mess
1835 if (sl.pos() > 0 && dit.depth() == 1) {
1837 if (pos && boundary)
1839 // lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
1840 rend = pm.pos2row(pos);
1842 rend = pm.pos2row(sl.pos());
1844 size_t rend = pm.pos2row(sl.pos());
1846 for (size_t rit = 0; rit != rend; ++rit)
1847 y += pm.rows()[rit].height();
1848 y += pm.rows()[rend].ascent();
1850 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
1852 // Make relative position from the nested inset now bufferview absolute.
1853 int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
1856 // In the RTL case place the nested inset at the left of the cursor in
1857 // the outer paragraph
1858 bool boundary_1 = boundary && 1 == dit.depth();
1859 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
1867 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
1869 CursorSlice const & bot = dit.bottom();
1870 TextMetrics const & tm = textMetrics(bot.text());
1871 if (!tm.has(bot.pit()))
1872 return Point(-1, -1);
1874 Point p = coordOffset(dit, boundary); // offset from outer paragraph
1875 p.y_ += tm.parMetrics(bot.pit()).position();
1880 void BufferView::draw(frontend::Painter & pain)
1882 LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
1883 Text & text = buffer_.text();
1884 TextMetrics const & tm = d->text_metrics_[&text];
1885 int const y = tm.first().second->position();
1886 PainterInfo pi(this, pain);
1888 switch (d->update_strategy_) {
1890 case NoScreenUpdate:
1891 // If no screen painting is actually needed, only some the different
1892 // coordinates of insets and paragraphs needs to be updated.
1893 pi.full_repaint = true;
1894 pi.pain.setDrawingEnabled(false);
1898 case SingleParUpdate:
1899 pi.full_repaint = false;
1900 // In general, only the current row of the outermost paragraph
1901 // will be redrawn. Particular cases where selection spans
1902 // multiple paragraph are correctly detected in TextMetrics.
1906 case DecorationUpdate:
1907 // FIXME: We should also distinguish DecorationUpdate to avoid text
1908 // drawing if possible. This is not possible to do easily right now
1909 // because of the single backing pixmap.
1911 case FullScreenUpdate:
1912 // The whole screen, including insets, will be refreshed.
1913 pi.full_repaint = true;
1915 // Clear background.
1916 pain.fillRectangle(0, 0, width_, height_,
1917 buffer_.inset().backgroundColor());
1922 // and possibly grey out below
1923 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
1924 int const y2 = lastpm.second->position() + lastpm.second->descent();
1926 pain.fillRectangle(0, y2, width_, height_ - y2, Color_bottomarea);
1929 LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING ***");
1931 // The scrollbar needs an update.
1934 // Normalize anchor for next time
1935 pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
1936 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
1937 for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
1938 ParagraphMetrics const & pm = tm.parMetrics(pit);
1939 if (pm.position() + pm.descent() > 0) {
1940 d->anchor_pit_ = pit;
1941 d->anchor_ypos_ = pm.position();
1945 LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
1946 << " anchor ypos = " << d->anchor_ypos_);
1950 void BufferView::message(docstring const & msg)
1953 d->gui_->message(msg);
1957 void BufferView::showDialog(string const & name)
1960 d->gui_->showDialog(name, string());
1964 void BufferView::showDialog(string const & name,
1965 string const & data, Inset * inset)
1968 d->gui_->showDialog(name, data, inset);
1972 void BufferView::updateDialog(string const & name, string const & data)
1975 d->gui_->updateDialog(name, data);
1979 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
1985 // FIXME: Move this out of BufferView again
1986 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
1988 if (!fname.isReadableFile()) {
1989 docstring const error = from_ascii(strerror(errno));
1990 docstring const file = makeDisplayPath(fname.absFilename(), 50);
1991 docstring const text =
1992 bformat(_("Could not read the specified document\n"
1993 "%1$s\ndue to the error: %2$s"), file, error);
1994 Alert::error(_("Could not read file"), text);
1998 if (!fname.isReadableFile()) {
1999 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2000 docstring const text =
2001 bformat(_("%1$s\n is not readable."), file);
2002 Alert::error(_("Could not open file"), text);
2006 // FIXME UNICODE: We don't know the encoding of the file
2007 docstring file_content = fname.fileContents("UTF-8");
2008 if (file_content.empty()) {
2009 Alert::error(_("Reading not UTF-8 encoded file"),
2010 _("The file is not UTF-8 encoded.\n"
2011 "It will be read as local 8Bit-encoded.\n"
2012 "If this does not give the correct result\n"
2013 "then please change the encoding of the file\n"
2014 "to UTF-8 with a program other than LyX.\n"));
2015 file_content = fname.fileContents("local8bit");
2018 return normalize_c(file_content);
2022 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
2024 docstring const tmpstr = contentsOfPlaintextFile(f);
2029 Cursor & cur = cursor();
2030 cap::replaceSelection(cur);
2031 buffer_.undo().recordUndo(cur);
2033 cur.innerText()->insertStringAsParagraphs(cur, tmpstr);
2035 cur.innerText()->insertStringAsLines(cur, tmpstr);