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 "MetricsInfo.h"
43 #include "Paragraph.h"
44 #include "paragraph_funcs.h"
45 #include "ParagraphParameters.h"
46 #include "ParIterator.h"
49 #include "TextClass.h"
50 #include "TextMetrics.h"
53 #include "WordLangTuple.h"
55 #include "insets/InsetBibtex.h"
56 #include "insets/InsetCommand.h" // ChangeRefs
57 #include "insets/InsetRef.h"
58 #include "insets/InsetText.h"
60 #include "frontends/alert.h"
61 #include "frontends/Application.h"
62 #include "frontends/Delegates.h"
63 #include "frontends/FontMetrics.h"
64 #include "frontends/Painter.h"
65 #include "frontends/Selection.h"
67 #include "graphics/Previews.h"
69 #include "support/convert.h"
70 #include "support/debug.h"
71 #include "support/ExceptionMessage.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 // We prefer fixed size line scrolling.
421 d->scrollbarParameters_.single_step = defaultRowHeight();
422 // We prefer full screen page scrolling.
423 d->scrollbarParameters_.page_step = height_;
425 Text & t = buffer_.text();
426 TextMetrics & tm = d->text_metrics_[&t];
428 LYXERR(Debug::GUI, " Updating scrollbar: height: "
429 << t.paragraphs().size()
430 << " curr par: " << d->cursor_.bottom().pit()
431 << " default height " << defaultRowHeight());
433 int const parsize = int(t.paragraphs().size());
434 if (d->par_height_.size() != parsize) {
435 d->par_height_.clear();
436 // FIXME: We assume a default paragraph height of 2 rows. This
437 // should probably be pondered with the screen width.
438 d->par_height_.resize(parsize, defaultRowHeight() * 2);
441 // Look at paragraph heights on-screen
442 pair<pit_type, ParagraphMetrics const *> first = tm.first();
443 pair<pit_type, ParagraphMetrics const *> last = tm.last();
444 for (pit_type pit = first.first; pit <= last.first; ++pit) {
445 d->par_height_[pit] = tm.parMetrics(pit).height();
446 LYXERR(Debug::SCROLLING, "storing height for pit " << pit << " : "
447 << d->par_height_[pit]);
450 int top_pos = first.second->position() - first.second->ascent();
451 int bottom_pos = last.second->position() + last.second->descent();
452 bool first_visible = first.first == 0 && top_pos >= 0;
453 bool last_visible = last.first == parsize - 1 && bottom_pos <= height_;
454 if (first_visible && last_visible) {
455 d->scrollbarParameters_.min = 0;
456 d->scrollbarParameters_.max = 0;
460 d->scrollbarParameters_.min = top_pos;
461 for (size_t i = 0; i != first.first; ++i)
462 d->scrollbarParameters_.min -= d->par_height_[i];
463 d->scrollbarParameters_.max = bottom_pos;
464 for (size_t i = last.first + 1; i != parsize; ++i)
465 d->scrollbarParameters_.max += d->par_height_[i];
467 d->scrollbarParameters_.position = 0;
468 // The reference is the top position so we remove one page.
469 d->scrollbarParameters_.max -= d->scrollbarParameters_.page_step;
473 ScrollbarParameters const & BufferView::scrollbarParameters() const
475 return d->scrollbarParameters_;
479 docstring BufferView::toolTip(int x, int y) const
481 // Get inset under mouse, if there is one.
482 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
484 // No inset, no tooltip...
486 return covering_inset->toolTip(*this, x, y);
490 docstring BufferView::contextMenu(int x, int y) const
492 // Get inset under mouse, if there is one.
493 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
495 return covering_inset->contextMenu(*this, x, y);
497 // FIXME: Do something more elaborate here.
498 return from_ascii("edit");
502 void BufferView::scrollDocView(int value)
504 // cut off at the top
505 if (value <= d->scrollbarParameters_.min) {
506 DocIterator dit = doc_iterator_begin(buffer_.inset());
508 LYXERR(Debug::SCROLLING, "scroll to top");
512 // cut off at the top
513 if (value >= d->scrollbarParameters_.max) {
514 DocIterator dit = doc_iterator_end(buffer_.inset());
517 LYXERR(Debug::SCROLLING, "scroll to bottom");
522 int const offset = value - d->scrollbarParameters_.position;
523 // If the offset is less than 2 screen height, prefer to scroll instead.
524 if (abs(offset) <= 2 * height_) {
529 // find paragraph at target positin
530 int par_pos = d->scrollbarParameters_.min;
531 for (size_t i = 0; i != d->par_height_.size(); ++i) {
532 par_pos += d->par_height_[i];
533 if (par_pos >= value) {
534 d->anchor_pit_ = pit_type(i);
539 LYXERR(Debug::SCROLLING, "value = " << value
540 << "\tanchor_ref_ = " << d->anchor_pit_
541 << "\tpar_pos = " << par_pos);
543 // cut off at the end of the buffer
544 if (value > par_pos) {
545 value = d->scrollbarParameters_.max;
546 d->anchor_pit_ = d->par_height_.size() - 1;
549 // set pixel offset of screen to anchor pit
550 d->anchor_ypos_ = par_pos - value;
557 // FIXME: this method is not working well.
558 void BufferView::setCursorFromScrollbar()
560 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
562 int const height = 2 * defaultRowHeight();
563 int const first = height;
564 int const last = height_ - height;
565 Cursor & cur = d->cursor_;
567 switch (cursorStatus(cur)) {
569 // We reset the cursor because cursorStatus() does not
570 // work when the cursor is within mathed.
571 cur.reset(buffer_.inset());
572 tm.setCursorFromCoordinates(cur, 0, first);
573 cur.clearSelection();
576 // We reset the cursor because cursorStatus() does not
577 // work when the cursor is within mathed.
578 cur.reset(buffer_.inset());
579 tm.setCursorFromCoordinates(cur, 0, last);
580 cur.clearSelection();
583 int const y = getPos(cur, cur.boundary()).y_;
584 int const newy = min(last, max(y, first));
586 cur.reset(buffer_.inset());
587 tm.setCursorFromCoordinates(cur, 0, newy);
593 Change const BufferView::getCurrentChange() const
595 if (!d->cursor_.selection())
596 return Change(Change::UNCHANGED);
598 DocIterator dit = d->cursor_.selectionBegin();
599 return dit.paragraph().lookupChange(dit.pos());
603 // this could be used elsewhere as well?
604 // FIXME: This does not work within mathed!
605 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
607 Point const p = getPos(dit, dit.boundary());
610 if (p.y_ > workHeight())
616 void BufferView::saveBookmark(unsigned int idx)
618 // tenatively save bookmark, id and pos will be used to
619 // acturately locate a bookmark in a 'live' lyx session.
620 // pit and pos will be updated with bottom level pit/pos
622 LyX::ref().session().bookmarks().save(
624 d->cursor_.bottom().pit(),
625 d->cursor_.bottom().pos(),
626 d->cursor_.paragraph().id(),
631 // emit message signal.
632 message(_("Save bookmark"));
636 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
637 int top_id, pos_type top_pos)
639 bool success = false;
642 d->cursor_.clearSelection();
644 // if a valid par_id is given, try it first
645 // This is the case for a 'live' bookmark when unique paragraph ID
646 // is used to track bookmarks.
648 ParIterator par = buffer_.getParFromID(top_id);
649 if (par != buffer_.par_iterator_end()) {
650 doc_it = makeDocIterator(par, min(par->size(), top_pos));
651 // Some slices of the iterator may not be
652 // reachable (e.g. closed collapsable inset)
653 // so the dociterator may need to be
654 // shortened. Otherwise, setCursor may crash
655 // lyx when the cursor can not be set to these
657 size_t const n = doc_it.depth();
658 for (size_t i = 0; i < n; ++i)
659 if (doc_it[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
667 // if top_id == 0, or searching through top_id failed
668 // This is the case for a 'restored' bookmark when only bottom
669 // (document level) pit was saved. Because of this, bookmark
670 // restoration is inaccurate. If a bookmark was within an inset,
671 // it will be restored to the left of the outmost inset that contains
673 if (static_cast<size_t>(bottom_pit) < buffer_.paragraphs().size()) {
674 doc_it = doc_iterator_begin(buffer_.inset());
675 doc_it.pit() = bottom_pit;
676 doc_it.pos() = min(bottom_pos, doc_it.paragraph().size());
681 // Note: only bottom (document) level pit is set.
683 // set the current font.
684 d->cursor_.setCurrentFont();
685 // To center the screen on this new position we need the
686 // paragraph position which is computed at draw() time.
687 // So we need a redraw!
697 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
699 if (lyxrc.rtl_support) {
700 if (d->cursor_.real_current_font.isRightToLeft()) {
701 if (d->intl_.keymap == Intl::PRIMARY)
702 d->intl_.keyMapSec();
704 if (d->intl_.keymap == Intl::SECONDARY)
705 d->intl_.keyMapPrim();
709 d->intl_.getTransManager().translateAndInsert(c, t, cur);
713 int BufferView::workWidth() const
719 void BufferView::showCursor()
721 showCursor(d->cursor_);
725 void BufferView::showCursor(DocIterator const & dit)
727 // We are not properly started yet, delay until resizing is
732 LYXERR(Debug::SCROLLING, "recentering!");
734 CursorSlice const & bot = dit.bottom();
735 TextMetrics & tm = d->text_metrics_[bot.text()];
737 pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
738 int bot_pit = bot.pit();
739 if (bot_pit > max_pit) {
740 // FIXME: Why does this happen?
741 LYXERR0("bottom pit is greater that max pit: "
742 << bot_pit << " > " << max_pit);
746 if (bot_pit == tm.first().first - 1)
747 tm.newParMetricsUp();
748 else if (bot_pit == tm.last().first + 1)
749 tm.newParMetricsDown();
751 if (tm.has(bot_pit)) {
752 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
753 BOOST_ASSERT(!pm.rows().empty());
754 // FIXME: smooth scrolling doesn't work in mathed.
755 CursorSlice const & cs = dit.innerTextSlice();
756 int offset = coordOffset(dit, dit.boundary()).y_;
757 int ypos = pm.position() + offset;
758 Dimension const & row_dim =
759 pm.getRow(cs.pos(), dit.boundary()).dimension();
760 if (ypos - row_dim.ascent() < 0)
761 scrollUp(- ypos + row_dim.ascent());
762 else if (ypos + row_dim.descent() > height_)
763 scrollDown(ypos - height_ + row_dim.descent());
764 // else, nothing to do, the cursor is already visible so we just return.
768 tm.redoParagraph(bot_pit);
769 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
770 int offset = coordOffset(dit, dit.boundary()).y_;
772 d->anchor_pit_ = bot_pit;
773 CursorSlice const & cs = dit.innerTextSlice();
774 Dimension const & row_dim =
775 pm.getRow(cs.pos(), dit.boundary()).dimension();
777 if (d->anchor_pit_ == 0)
778 d->anchor_ypos_ = offset + pm.ascent();
779 else if (d->anchor_pit_ == max_pit)
780 d->anchor_ypos_ = height_ - offset - row_dim.descent();
782 d->anchor_ypos_ = defaultRowHeight() * 2 - offset - row_dim.descent();
789 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
793 Cursor & cur = d->cursor_;
795 switch (cmd.action) {
798 flag.enabled(buffer_.undo().hasUndoStack());
801 flag.enabled(buffer_.undo().hasRedoStack());
803 case LFUN_FILE_INSERT:
804 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
805 case LFUN_FILE_INSERT_PLAINTEXT:
806 case LFUN_BOOKMARK_SAVE:
807 // FIXME: Actually, these LFUNS should be moved to Text
808 flag.enabled(cur.inTexted());
810 case LFUN_FONT_STATE:
811 case LFUN_LABEL_INSERT:
812 case LFUN_INFO_INSERT:
813 case LFUN_PARAGRAPH_GOTO:
815 case LFUN_REFERENCE_NEXT:
817 case LFUN_WORD_REPLACE:
820 case LFUN_MARK_TOGGLE:
821 case LFUN_SCREEN_RECENTER:
822 case LFUN_BIBTEX_DATABASE_ADD:
823 case LFUN_BIBTEX_DATABASE_DEL:
824 case LFUN_STATISTICS:
825 case LFUN_NEXT_INSET_TOGGLE:
829 case LFUN_LABEL_GOTO: {
830 flag.enabled(!cmd.argument().empty()
831 || getInsetByCode<InsetRef>(cur, REF_CODE));
835 case LFUN_CHANGES_TRACK:
837 flag.setOnOff(buffer_.params().trackChanges);
840 case LFUN_CHANGES_OUTPUT:
842 flag.setOnOff(buffer_.params().outputChanges);
845 case LFUN_CHANGES_MERGE:
846 case LFUN_CHANGE_NEXT:
847 case LFUN_ALL_CHANGES_ACCEPT:
848 case LFUN_ALL_CHANGES_REJECT:
849 // TODO: context-sensitive enabling of LFUNs
850 // In principle, these command should only be enabled if there
851 // is a change in the document. However, without proper
852 // optimizations, this will inevitably result in poor performance.
856 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
857 flag.setOnOff(buffer_.params().compressed);
861 case LFUN_BUFFER_TOGGLE_EMBEDDING: {
862 flag.setOnOff(buffer_.params().embedded);
867 case LFUN_SCREEN_DOWN:
872 // FIXME: LFUN_SCREEN_DOWN_SELECT should be removed from
873 // everywhere else before this can enabled:
874 case LFUN_SCREEN_UP_SELECT:
875 case LFUN_SCREEN_DOWN_SELECT:
879 case LFUN_LAYOUT_TABULAR:
880 flag.enabled(cur.innerInsetOfType(TABULAR_CODE));
884 case LFUN_LAYOUT_PARAGRAPH:
885 flag.enabled(cur.inset().forceDefaultParagraphs(cur.idx()));
888 case LFUN_INSET_SETTINGS: {
889 InsetCode code = cur.inset().lyxCode();
893 enable = cmd.argument() == "tabular";
896 enable = cmd.argument() == "ert";
899 enable = cmd.argument() == "float";
902 enable = cmd.argument() == "wrap";
905 enable = cmd.argument() == "note";
908 enable = cmd.argument() == "branch";
911 enable = cmd.argument() == "box";
914 enable = cmd.argument() == "listings";
919 flag.enabled(enable);
923 case LFUN_DIALOG_SHOW_NEW_INSET:
924 flag.enabled(cur.inset().lyxCode() != ERT_CODE &&
925 cur.inset().lyxCode() != LISTINGS_CODE);
926 if (cur.inset().lyxCode() == CAPTION_CODE) {
928 if (cur.inset().getStatus(cur, cmd, flag))
941 bool BufferView::dispatch(FuncRequest const & cmd)
943 //lyxerr << [ cmd = " << cmd << "]" << endl;
945 // Make sure that the cached BufferView is correct.
946 LYXERR(Debug::ACTION, " action[" << cmd.action << ']'
947 << " arg[" << to_utf8(cmd.argument()) << ']'
948 << " x[" << cmd.x << ']'
949 << " y[" << cmd.y << ']'
950 << " button[" << cmd.button() << ']');
952 Cursor & cur = d->cursor_;
954 switch (cmd.action) {
957 cur.message(_("Undo"));
958 cur.clearSelection();
960 cur.message(_("No further undo information"));
962 processUpdateFlags(Update::Force | Update::FitCursor);
966 cur.message(_("Redo"));
967 cur.clearSelection();
969 cur.message(_("No further redo information"));
971 processUpdateFlags(Update::Force | Update::FitCursor);
974 case LFUN_FONT_STATE:
975 cur.message(cur.currentState());
978 case LFUN_BOOKMARK_SAVE:
979 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
982 case LFUN_LABEL_GOTO: {
983 docstring label = cmd.argument();
986 getInsetByCode<InsetRef>(d->cursor_,
989 label = inset->getParam("reference");
990 // persistent=false: use temp_bookmark
1000 case LFUN_PARAGRAPH_GOTO: {
1001 int const id = convert<int>(to_utf8(cmd.argument()));
1003 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1004 b = theBufferList().next(b)) {
1006 ParIterator par = b->getParFromID(id);
1007 if (par == b->par_iterator_end()) {
1008 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1010 LYXERR(Debug::INFO, "Paragraph " << par->id()
1011 << " found in buffer `"
1012 << b->absFileName() << "'.");
1014 if (b == &buffer_) {
1016 setCursor(makeDocIterator(par, 0));
1019 // Switch to other buffer view and resend cmd
1020 theLyXFunc().dispatch(FuncRequest(
1021 LFUN_BUFFER_SWITCH, b->absFileName()));
1022 theLyXFunc().dispatch(cmd);
1031 case LFUN_NOTE_NEXT:
1032 gotoInset(this, NOTE_CODE, false);
1035 case LFUN_REFERENCE_NEXT: {
1036 vector<InsetCode> tmp;
1037 tmp.push_back(LABEL_CODE);
1038 tmp.push_back(REF_CODE);
1039 gotoInset(this, tmp, true);
1043 case LFUN_CHANGES_TRACK:
1044 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1047 case LFUN_CHANGES_OUTPUT:
1048 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1049 if (buffer_.params().outputChanges) {
1050 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1051 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1052 LaTeXFeatures::isAvailable("xcolor");
1054 if (!dvipost && !xcolorsoul) {
1055 Alert::warning(_("Changes not shown in LaTeX output"),
1056 _("Changes will not be highlighted in LaTeX output, "
1057 "because neither dvipost nor xcolor/soul are installed.\n"
1058 "Please install these packages or redefine "
1059 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1060 } else if (!xcolorsoul) {
1061 Alert::warning(_("Changes not shown in LaTeX output"),
1062 _("Changes will not be highlighted in LaTeX output "
1063 "when using pdflatex, because xcolor and soul are not installed.\n"
1064 "Please install both packages or redefine "
1065 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1070 case LFUN_CHANGE_NEXT:
1071 findNextChange(this);
1074 case LFUN_CHANGES_MERGE:
1075 if (findNextChange(this))
1076 showDialog("changes");
1079 case LFUN_ALL_CHANGES_ACCEPT:
1080 // select complete document
1081 d->cursor_.reset(buffer_.inset());
1082 d->cursor_.selHandle(true);
1083 buffer_.text().cursorBottom(d->cursor_);
1084 // accept everything in a single step to support atomic undo
1085 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::ACCEPT);
1088 case LFUN_ALL_CHANGES_REJECT:
1089 // select complete document
1090 d->cursor_.reset(buffer_.inset());
1091 d->cursor_.selHandle(true);
1092 buffer_.text().cursorBottom(d->cursor_);
1093 // reject everything in a single step to support atomic undo
1094 // Note: reject does not work recursively; the user may have to repeat the operation
1095 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::REJECT);
1098 case LFUN_WORD_FIND:
1102 case LFUN_WORD_REPLACE: {
1103 bool has_deleted = false;
1104 if (cur.selection()) {
1105 DocIterator beg = cur.selectionBegin();
1106 DocIterator end = cur.selectionEnd();
1107 if (beg.pit() == end.pit()) {
1108 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1109 if (cur.paragraph().isDeleted(p))
1114 replace(this, cmd, has_deleted);
1119 cur.clearSelection();
1121 cur.message(from_utf8(N_("Mark off")));
1125 cur.clearSelection();
1128 cur.message(from_utf8(N_("Mark on")));
1131 case LFUN_MARK_TOGGLE:
1132 cur.clearSelection();
1135 cur.message(from_utf8(N_("Mark removed")));
1138 cur.message(from_utf8(N_("Mark set")));
1143 case LFUN_SCREEN_RECENTER:
1147 case LFUN_BIBTEX_DATABASE_ADD: {
1148 Cursor tmpcur = d->cursor_;
1149 findInset(tmpcur, BIBTEX_CODE, false);
1150 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1153 if (inset->addDatabase(to_utf8(cmd.argument())))
1154 buffer_.updateBibfilesCache();
1159 case LFUN_BIBTEX_DATABASE_DEL: {
1160 Cursor tmpcur = d->cursor_;
1161 findInset(tmpcur, BIBTEX_CODE, false);
1162 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1165 if (inset->delDatabase(to_utf8(cmd.argument())))
1166 buffer_.updateBibfilesCache();
1171 case LFUN_STATISTICS: {
1172 DocIterator from, to;
1173 if (cur.selection()) {
1174 from = cur.selectionBegin();
1175 to = cur.selectionEnd();
1177 from = doc_iterator_begin(buffer_.inset());
1178 to = doc_iterator_end(buffer_.inset());
1180 int const words = countWords(from, to);
1181 int const chars = countChars(from, to, false);
1182 int const chars_blanks = countChars(from, to, true);
1184 if (cur.selection())
1185 message = _("Statistics for the selection:");
1187 message = _("Statistics for the document:");
1190 message += bformat(_("%1$d words"), words);
1192 message += _("One word");
1194 if (chars_blanks != 1)
1195 message += bformat(_("%1$d characters (including blanks)"),
1198 message += _("One character (including blanks)");
1201 message += bformat(_("%1$d characters (excluding blanks)"),
1204 message += _("One character (excluding blanks)");
1206 Alert::information(_("Statistics"), message);
1210 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1211 // turn compression on/off
1212 buffer_.params().compressed = !buffer_.params().compressed;
1215 case LFUN_BUFFER_TOGGLE_EMBEDDING: {
1216 // turn embedding on/off
1218 buffer_.embeddedFiles().enable(!buffer_.params().embedded, buffer_);
1219 } catch (ExceptionMessage const & message) {
1220 Alert::error(message.title_, message.details_);
1225 case LFUN_NEXT_INSET_TOGGLE: {
1226 // this is the real function we want to invoke
1227 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1228 // if there is an inset at cursor, see whether it
1230 Inset * inset = cur.nextInset();
1232 if (inset->isActive()) {
1233 Cursor tmpcur = cur;
1234 tmpcur.pushBackward(*inset);
1235 inset->dispatch(tmpcur, tmpcmd);
1236 if (tmpcur.result().dispatched()) {
1239 } else if (inset->editable() == Inset::IS_EDITABLE) {
1240 inset->edit(cur, true);
1243 // if it did not work, try the underlying inset.
1244 if (!cur.result().dispatched())
1245 cur.dispatch(tmpcmd);
1247 if (!cur.result().dispatched())
1248 // It did not work too; no action needed.
1250 cur.clearSelection();
1251 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1255 case LFUN_SCREEN_UP:
1256 case LFUN_SCREEN_DOWN: {
1257 Point p = getPos(cur, cur.boundary());
1258 if (p.y_ < 0 || p.y_ > height_) {
1259 // The cursor is off-screen so recenter before proceeding.
1261 p = getPos(cur, cur.boundary());
1263 scroll(cmd.action == LFUN_SCREEN_UP? - height_ : height_);
1264 cur.reset(buffer_.inset());
1265 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1266 //FIXME: what to do with cur.x_target()?
1275 case LFUN_SCREEN_UP_SELECT:
1276 case LFUN_SCREEN_DOWN_SELECT: {
1277 // Those two are not ready yet for consumption.
1280 cur.selHandle(true);
1281 size_t initial_depth = cur.depth();
1282 Point const p = getPos(cur, cur.boundary());
1283 scroll(cmd.action == LFUN_SCREEN_UP_SELECT? - height_ : height_);
1284 // FIXME: We need to verify if the cursor stayed within an inset...
1285 //cur.reset(buffer_.inset());
1286 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1288 while (cur.depth() > initial_depth) {
1291 // FIXME: we need to do a redraw again because of the selection
1292 // But no screen update is needed.
1293 d->update_strategy_ = NoScreenUpdate;
1306 docstring const BufferView::requestSelection()
1308 Cursor & cur = d->cursor_;
1310 if (!cur.selection()) {
1311 d->xsel_cache_.set = false;
1315 if (!d->xsel_cache_.set ||
1316 cur.top() != d->xsel_cache_.cursor ||
1317 cur.anchor_.top() != d->xsel_cache_.anchor)
1319 d->xsel_cache_.cursor = cur.top();
1320 d->xsel_cache_.anchor = cur.anchor_.top();
1321 d->xsel_cache_.set = cur.selection();
1322 return cur.selectionAsString(false);
1328 void BufferView::clearSelection()
1330 d->cursor_.clearSelection();
1331 // Clear the selection buffer. Otherwise a subsequent
1332 // middle-mouse-button paste would use the selection buffer,
1333 // not the more current external selection.
1334 cap::clearSelection();
1335 d->xsel_cache_.set = false;
1336 // The buffer did not really change, but this causes the
1337 // redraw we need because we cleared the selection above.
1342 void BufferView::resize(int width, int height)
1344 // Update from work area
1348 // Clear the paragraph height cache.
1349 d->par_height_.clear();
1355 Inset const * BufferView::getCoveringInset(Text const & text,
1358 TextMetrics & tm = d->text_metrics_[&text];
1359 Inset * inset = tm.checkInsetHit(x, y);
1363 if (!inset->descendable())
1364 // No need to go further down if the inset is not
1368 size_t cell_number = inset->nargs();
1369 // Check all the inner cell.
1370 for (size_t i = 0; i != cell_number; ++i) {
1371 Text const * inner_text = inset->getText(i);
1374 Inset const * inset_deeper =
1375 getCoveringInset(*inner_text, x, y);
1377 return inset_deeper;
1385 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1387 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
1389 // This is only called for mouse related events including
1390 // LFUN_FILE_OPEN generated by drag-and-drop.
1391 FuncRequest cmd = cmd0;
1394 cur.push(buffer_.inset());
1395 cur.selection() = d->cursor_.selection();
1397 // Either the inset under the cursor or the
1398 // surrounding Text will handle this event.
1400 // make sure we stay within the screen...
1401 cmd.y = min(max(cmd.y, -1), height_);
1403 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1405 // Get inset under mouse, if there is one.
1406 Inset const * covering_inset =
1407 getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1408 if (covering_inset == d->last_inset_)
1409 // Same inset, no need to do anything...
1412 bool need_redraw = false;
1413 // const_cast because of setMouseHover().
1414 Inset * inset = const_cast<Inset *>(covering_inset);
1416 // Remove the hint on the last hovered inset (if any).
1417 need_redraw |= d->last_inset_->setMouseHover(false);
1419 // Highlighted the newly hovered inset (if any).
1420 need_redraw |= inset->setMouseHover(true);
1421 d->last_inset_ = inset;
1425 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
1426 << cmd.x << ", " << cmd.y << ")");
1428 d->update_strategy_ = DecorationUpdate;
1430 // This event (moving without mouse click) is not passed further.
1431 // This should be changed if it is further utilized.
1436 // Build temporary cursor.
1437 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1439 // Put anchor at the same position.
1442 // Try to dispatch to an non-editable inset near this position
1443 // via the temp cursor. If the inset wishes to change the real
1444 // cursor it has to do so explicitly by using
1445 // cur.bv().cursor() = cur; (or similar)
1447 inset->dispatch(cur, cmd);
1449 // Now dispatch to the temporary cursor. If the real cursor should
1450 // be modified, the inset's dispatch has to do so explicitly.
1451 if (!cur.result().dispatched())
1454 //Do we have a selection?
1455 theSelection().haveSelection(cursor().selection());
1457 // If the command has been dispatched,
1458 if (cur.result().dispatched()
1459 // an update is asked,
1460 && cur.result().update())
1461 processUpdateFlags(cur.result().update());
1465 void BufferView::lfunScroll(FuncRequest const & cmd)
1467 string const scroll_type = cmd.getArg(0);
1468 int const scroll_step =
1469 (scroll_type == "line")? d->scrollbarParameters_.single_step
1470 : (scroll_type == "page")? d->scrollbarParameters_.page_step : 0;
1471 if (scroll_step == 0)
1473 string const scroll_quantity = cmd.getArg(1);
1474 if (scroll_quantity == "up")
1475 scrollUp(scroll_step);
1476 else if (scroll_quantity == "down")
1477 scrollDown(scroll_step);
1479 int const scroll_value = convert<int>(scroll_quantity);
1481 scroll(scroll_step * scroll_value);
1486 void BufferView::scroll(int y)
1495 void BufferView::scrollDown(int offset)
1497 Text * text = &buffer_.text();
1498 TextMetrics & tm = d->text_metrics_[text];
1499 int ymax = height_ + offset;
1501 pair<pit_type, ParagraphMetrics const *> last = tm.last();
1502 int bottom_pos = last.second->position() + last.second->descent();
1503 if (last.first + 1 == int(text->paragraphs().size())) {
1504 if (bottom_pos <= height_)
1506 offset = min(offset, bottom_pos - height_);
1509 if (bottom_pos > ymax)
1511 tm.newParMetricsDown();
1513 d->anchor_ypos_ -= offset;
1519 void BufferView::scrollUp(int offset)
1521 Text * text = &buffer_.text();
1522 TextMetrics & tm = d->text_metrics_[text];
1523 int ymin = - offset;
1525 pair<pit_type, ParagraphMetrics const *> first = tm.first();
1526 int top_pos = first.second->position() - first.second->ascent();
1527 if (first.first == 0) {
1530 offset = min(offset, - top_pos);
1535 tm.newParMetricsUp();
1537 d->anchor_ypos_ += offset;
1543 void BufferView::setCursorFromRow(int row)
1548 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1550 d->cursor_.reset(buffer_.inset());
1552 buffer_.text().setCursor(d->cursor_, 0, 0);
1554 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1558 void BufferView::gotoLabel(docstring const & label)
1560 for (InsetIterator it = inset_iterator_begin(buffer_.inset()); it; ++it) {
1561 vector<docstring> labels;
1562 it->getLabelList(buffer_, labels);
1563 if (find(labels.begin(), labels.end(), label) != labels.end()) {
1572 TextMetrics const & BufferView::textMetrics(Text const * t) const
1574 return const_cast<BufferView *>(this)->textMetrics(t);
1578 TextMetrics & BufferView::textMetrics(Text const * t)
1580 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
1581 if (tmc_it == d->text_metrics_.end()) {
1582 tmc_it = d->text_metrics_.insert(
1583 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1585 return tmc_it->second;
1589 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1592 return textMetrics(t).parMetrics(pit);
1596 int BufferView::workHeight() const
1602 void BufferView::setCursor(DocIterator const & dit)
1604 size_t const n = dit.depth();
1605 for (size_t i = 0; i < n; ++i)
1606 dit[i].inset().edit(d->cursor_, true);
1608 d->cursor_.setCursor(dit);
1609 d->cursor_.selection() = false;
1613 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1615 // Would be wrong to delete anything if we have a selection.
1616 if (cur.selection())
1619 bool need_anchor_change = false;
1620 bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1621 need_anchor_change);
1623 if (need_anchor_change)
1631 updateLabels(buffer_);
1639 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
1641 BOOST_ASSERT(&cur.bv() == this);
1644 // this event will clear selection so we save selection for
1645 // persistent selection
1646 cap::saveSelection(cursor());
1648 // Has the cursor just left the inset?
1649 bool badcursor = false;
1650 bool leftinset = (&d->cursor_.inset() != &cur.inset());
1652 badcursor = notifyCursorLeaves(d->cursor_, cur);
1654 // FIXME: shift-mouse selection doesn't work well across insets.
1655 bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
1657 // do the dEPM magic if needed
1658 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1659 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1660 // the leftinset bool would not be necessary (badcursor instead).
1661 bool update = leftinset;
1662 if (!do_selection && !badcursor && d->cursor_.inTexted())
1663 update |= checkDepm(cur, d->cursor_);
1665 // if the cursor was in an empty script inset and the new
1666 // position is in the nucleus of the inset, notifyCursorLeaves
1667 // will kill the script inset itself. So we check all the
1668 // elements of the cursor to make sure that they are correct.
1669 // For an example, see bug 2933:
1670 // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1671 // The code below could maybe be moved to a DocIterator method.
1672 //lyxerr << "cur before " << cur <<endl;
1673 DocIterator dit(cur.inset());
1674 dit.push_back(cur.bottom());
1676 while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1677 dit.push_back(cur[i]);
1680 //lyxerr << "5 cur after" << dit <<endl;
1682 d->cursor_.setCursor(dit);
1683 d->cursor_.boundary(cur.boundary());
1685 d->cursor_.setSelection();
1687 d->cursor_.clearSelection();
1689 d->cursor_.finishUndo();
1690 d->cursor_.setCurrentFont();
1695 void BufferView::putSelectionAt(DocIterator const & cur,
1696 int length, bool backwards)
1698 d->cursor_.clearSelection();
1704 d->cursor_.pos() += length;
1705 d->cursor_.setSelection(d->cursor_, -length);
1707 d->cursor_.setSelection(d->cursor_, length);
1712 Cursor & BufferView::cursor()
1718 Cursor const & BufferView::cursor() const
1724 pit_type BufferView::anchor_ref() const
1726 return d->anchor_pit_;
1730 bool BufferView::singleParUpdate()
1732 Text & buftext = buffer_.text();
1733 pit_type const bottom_pit = d->cursor_.bottom().pit();
1734 TextMetrics & tm = textMetrics(&buftext);
1735 int old_height = tm.parMetrics(bottom_pit).height();
1737 // In Single Paragraph mode, rebreak only
1738 // the (main text, not inset!) paragraph containing the cursor.
1739 // (if this paragraph contains insets etc., rebreaking will
1740 // recursively descend)
1741 tm.redoParagraph(bottom_pit);
1742 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
1743 if (pm.height() != old_height)
1744 // Paragraph height has changed so we cannot proceed to
1745 // the singlePar optimisation.
1748 d->update_strategy_ = SingleParUpdate;
1750 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
1751 << " y2: " << pm.position() + pm.descent()
1752 << " pit: " << bottom_pit
1753 << " singlepar: 1");
1758 void BufferView::updateMetrics()
1760 Text & buftext = buffer_.text();
1761 pit_type const npit = int(buftext.paragraphs().size());
1763 // Clear out the position cache in case of full screen redraw,
1764 d->coord_cache_.clear();
1766 // Clear out paragraph metrics to avoid having invalid metrics
1767 // in the cache from paragraphs not relayouted below
1768 // The complete text metrics will be redone.
1769 d->text_metrics_.clear();
1771 TextMetrics & tm = textMetrics(&buftext);
1773 // Rebreak anchor paragraph.
1774 tm.redoParagraph(d->anchor_pit_);
1775 ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
1776 anchor_pm.setPosition(d->anchor_ypos_);
1778 LYXERR(Debug::PAINTING, "metrics: "
1779 << " anchor pit = " << d->anchor_pit_
1780 << " anchor ypos = " << d->anchor_ypos_);
1782 // Redo paragraphs above anchor if necessary.
1783 int y1 = d->anchor_ypos_ - anchor_pm.ascent();
1784 // We are now just above the anchor paragraph.
1785 pit_type pit1 = d->anchor_pit_ - 1;
1786 for (; pit1 >= 0 && y1 >= 0; --pit1) {
1787 tm.redoParagraph(pit1);
1788 ParagraphMetrics & pm = tm.par_metrics_[pit1];
1790 // Save the paragraph position in the cache.
1795 // Redo paragraphs below the anchor if necessary.
1796 int y2 = d->anchor_ypos_ + anchor_pm.descent();
1797 // We are now just below the anchor paragraph.
1798 pit_type pit2 = d->anchor_pit_ + 1;
1799 for (; pit2 < npit && y2 <= height_; ++pit2) {
1800 tm.redoParagraph(pit2);
1801 ParagraphMetrics & pm = tm.par_metrics_[pit2];
1803 // Save the paragraph position in the cache.
1808 LYXERR(Debug::PAINTING, "Metrics: "
1809 << " anchor pit = " << d->anchor_pit_
1810 << " anchor ypos = " << d->anchor_ypos_
1813 << " pit1 = " << pit1
1814 << " pit2 = " << pit2);
1816 d->update_strategy_ = FullScreenUpdate;
1818 if (lyxerr.debugging(Debug::WORKAREA)) {
1819 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
1820 d->coord_cache_.dump();
1825 void BufferView::insertLyXFile(FileName const & fname)
1827 BOOST_ASSERT(d->cursor_.inTexted());
1829 // Get absolute path of file and add ".lyx"
1830 // to the filename if necessary
1831 FileName filename = fileSearch(string(), fname.absFilename(), "lyx");
1833 docstring const disp_fn = makeDisplayPath(filename.absFilename());
1834 // emit message signal.
1835 message(bformat(_("Inserting document %1$s..."), disp_fn));
1838 Buffer buf("", false);
1839 if (buf.loadLyXFile(filename)) {
1840 ErrorList & el = buffer_.errorList("Parse");
1841 // Copy the inserted document error list into the current buffer one.
1842 el = buf.errorList("Parse");
1843 buffer_.undo().recordUndo(d->cursor_);
1844 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
1845 buf.params().getTextClassPtr(), el);
1846 res = _("Document %1$s inserted.");
1848 res = _("Could not insert document %1$s");
1853 // emit message signal.
1854 message(bformat(res, disp_fn));
1855 buffer_.errors("Parse");
1859 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
1865 // Addup contribution of nested insets, from inside to outside,
1866 // keeping the outer paragraph for a special handling below
1867 for (size_t i = dit.depth() - 1; i >= 1; --i) {
1868 CursorSlice const & sl = dit[i];
1872 // get relative position inside sl.inset()
1873 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
1875 // Make relative position inside of the edited inset relative to sl.inset()
1879 // In case of an RTL inset, the edited inset will be positioned to the left
1882 bool boundary_i = boundary && i + 1 == dit.depth();
1883 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
1888 // remember width for the case that sl.inset() is positioned in an RTL inset
1889 if (i && dit[i - 1].text()) {
1890 // If this Inset is inside a Text Inset, retrieve the Dimension
1891 // from the containing text instead of using Inset::dimension() which
1892 // might not be implemented.
1893 // FIXME (Abdel 23/09/2007): this is a bit messy because of the
1894 // elimination of Inset::dim_ cache. This coordOffset() method needs
1895 // to be rewritten in light of the new design.
1896 Dimension const & dim = parMetrics(dit[i - 1].text(),
1897 dit[i - 1].pit()).insetDimension(&sl.inset());
1900 Dimension const dim = sl.inset().dimension(*this);
1904 //lyxerr << "Cursor::getPos, i: "
1905 // << i << " x: " << xx << " y: " << y << endl;
1908 // Add contribution of initial rows of outermost paragraph
1909 CursorSlice const & sl = dit[0];
1910 TextMetrics const & tm = textMetrics(sl.text());
1911 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
1912 BOOST_ASSERT(!pm.rows().empty());
1913 y -= pm.rows()[0].ascent();
1915 // FIXME: document this mess
1917 if (sl.pos() > 0 && dit.depth() == 1) {
1919 if (pos && boundary)
1921 // lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
1922 rend = pm.pos2row(pos);
1924 rend = pm.pos2row(sl.pos());
1926 size_t rend = pm.pos2row(sl.pos());
1928 for (size_t rit = 0; rit != rend; ++rit)
1929 y += pm.rows()[rit].height();
1930 y += pm.rows()[rend].ascent();
1932 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
1934 // Make relative position from the nested inset now bufferview absolute.
1935 int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
1938 // In the RTL case place the nested inset at the left of the cursor in
1939 // the outer paragraph
1940 bool boundary_1 = boundary && 1 == dit.depth();
1941 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
1949 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
1951 CursorSlice const & bot = dit.bottom();
1952 TextMetrics const & tm = textMetrics(bot.text());
1953 if (!tm.has(bot.pit()))
1954 return Point(-1, -1);
1956 Point p = coordOffset(dit, boundary); // offset from outer paragraph
1957 p.y_ += tm.parMetrics(bot.pit()).position();
1962 void BufferView::draw(frontend::Painter & pain)
1964 LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
1965 Text & text = buffer_.text();
1966 TextMetrics const & tm = d->text_metrics_[&text];
1967 int const y = tm.first().second->position();
1968 PainterInfo pi(this, pain);
1970 switch (d->update_strategy_) {
1972 case NoScreenUpdate:
1973 // If no screen painting is actually needed, only some the different
1974 // coordinates of insets and paragraphs needs to be updated.
1975 pi.full_repaint = true;
1976 pi.pain.setDrawingEnabled(false);
1980 case SingleParUpdate:
1981 pi.full_repaint = false;
1982 // In general, only the current row of the outermost paragraph
1983 // will be redrawn. Particular cases where selection spans
1984 // multiple paragraph are correctly detected in TextMetrics.
1988 case DecorationUpdate:
1989 // FIXME: We should also distinguish DecorationUpdate to avoid text
1990 // drawing if possible. This is not possible to do easily right now
1991 // because of the single backing pixmap.
1993 case FullScreenUpdate:
1994 // The whole screen, including insets, will be refreshed.
1995 pi.full_repaint = true;
1997 // Clear background.
1998 pain.fillRectangle(0, 0, width_, height_,
1999 buffer_.inset().backgroundColor());
2004 // and possibly grey out below
2005 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2006 int const y2 = lastpm.second->position() + lastpm.second->descent();
2008 pain.fillRectangle(0, y2, width_, height_ - y2, Color_bottomarea);
2011 LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING ***");
2013 // The scrollbar needs an update.
2016 // Normalize anchor for next time
2017 pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
2018 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2019 for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
2020 ParagraphMetrics const & pm = tm.parMetrics(pit);
2021 if (pm.position() + pm.descent() > 0) {
2022 d->anchor_pit_ = pit;
2023 d->anchor_ypos_ = pm.position();
2027 LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
2028 << " anchor ypos = " << d->anchor_ypos_);
2032 void BufferView::message(docstring const & msg)
2035 d->gui_->message(msg);
2039 void BufferView::showDialog(string const & name)
2042 d->gui_->showDialog(name, string());
2046 void BufferView::showDialog(string const & name,
2047 string const & data, Inset * inset)
2050 d->gui_->showDialog(name, data, inset);
2054 void BufferView::updateDialog(string const & name, string const & data)
2057 d->gui_->updateDialog(name, data);
2061 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2067 // FIXME: Move this out of BufferView again
2068 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
2070 if (!fname.isReadableFile()) {
2071 docstring const error = from_ascii(strerror(errno));
2072 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2073 docstring const text =
2074 bformat(_("Could not read the specified document\n"
2075 "%1$s\ndue to the error: %2$s"), file, error);
2076 Alert::error(_("Could not read file"), text);
2080 if (!fname.isReadableFile()) {
2081 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2082 docstring const text =
2083 bformat(_("%1$s\n is not readable."), file);
2084 Alert::error(_("Could not open file"), text);
2088 // FIXME UNICODE: We don't know the encoding of the file
2089 docstring file_content = fname.fileContents("UTF-8");
2090 if (file_content.empty()) {
2091 Alert::error(_("Reading not UTF-8 encoded file"),
2092 _("The file is not UTF-8 encoded.\n"
2093 "It will be read as local 8Bit-encoded.\n"
2094 "If this does not give the correct result\n"
2095 "then please change the encoding of the file\n"
2096 "to UTF-8 with a program other than LyX.\n"));
2097 file_content = fname.fileContents("local8bit");
2100 return normalize_c(file_content);
2104 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
2106 docstring const tmpstr = contentsOfPlaintextFile(f);
2111 Cursor & cur = cursor();
2112 cap::replaceSelection(cur);
2113 buffer_.undo().recordUndo(cur);
2115 cur.innerText()->insertStringAsParagraphs(cur, tmpstr);
2117 cur.innerText()->insertStringAsLines(cur, tmpstr);