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"
27 #include "DispatchResult.h"
28 #include "EmbeddedFiles.h"
29 #include "ErrorList.h"
31 #include "FloatList.h"
32 #include "FuncRequest.h"
33 #include "FuncStatus.h"
36 #include "InsetIterator.h"
38 #include "LaTeXFeatures.h"
44 #include "MetricsInfo.h"
45 #include "Paragraph.h"
46 #include "paragraph_funcs.h"
47 #include "ParagraphParameters.h"
48 #include "ParIterator.h"
51 #include "TextClass.h"
52 #include "TextMetrics.h"
55 #include "WordLangTuple.h"
57 #include "insets/InsetBibtex.h"
58 #include "insets/InsetCommand.h" // ChangeRefs
59 #include "insets/InsetRef.h"
60 #include "insets/InsetText.h"
62 #include "frontends/alert.h"
63 #include "frontends/Delegates.h"
64 #include "frontends/FileDialog.h"
65 #include "frontends/FontMetrics.h"
66 #include "frontends/Painter.h"
67 #include "frontends/Selection.h"
69 #include "graphics/Previews.h"
71 #include "support/convert.h"
72 #include "support/lstrings.h"
73 #include "support/FileFilterList.h"
74 #include "support/filetools.h"
75 #include "support/Package.h"
76 #include "support/types.h"
78 #include <boost/current_function.hpp>
89 using std::istringstream;
90 using std::istream_iterator;
94 using std::mem_fun_ref;
100 using support::addPath;
101 using support::bformat;
102 using support::FileFilterList;
103 using support::FileName;
104 using support::fileSearch;
105 using support::makeDisplayPath;
106 using support::makeAbsPath;
107 using support::package;
109 namespace Alert = frontend::Alert;
113 /// Return an inset of this class if it exists at the current cursor position
115 T * getInsetByCode(Cursor const & cur, InsetCode code)
117 DocIterator it = cur;
118 Inset * inset = it.nextInset();
119 if (inset && inset->lyxCode() == code)
120 return static_cast<T*>(inset);
125 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
128 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
129 docstring const & contents)
131 DocIterator tmpdit = dit;
134 Inset const * inset = tmpdit.nextInset();
136 && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()
137 && (contents.empty() ||
138 static_cast<InsetCommand const *>(inset)->getFirstNonOptParam() == contents)) {
142 tmpdit.forwardInset();
149 /// Looks for next inset with one of the given codes.
150 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
154 DocIterator tmpdit = dit;
155 tmpdit.forwardInset();
160 Inset const * inset = tmpdit.nextInset();
162 && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()) {
163 contents = static_cast<InsetCommand const *>(inset)->getFirstNonOptParam();
167 if (!findNextInset(tmpdit, codes, contents)) {
168 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
169 tmpdit = doc_iterator_begin(tmpdit.bottom().inset());
170 if (!findNextInset(tmpdit, codes, contents))
181 /// Looks for next inset with the given code
182 void findInset(DocIterator & dit, InsetCode code, bool same_content)
184 findInset(dit, vector<InsetCode>(1, code), same_content);
188 /// Moves cursor to the next inset with one of the given codes.
189 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
192 Cursor tmpcur = bv->cursor();
193 if (!findInset(tmpcur, codes, same_content)) {
194 bv->cursor().message(_("No more insets"));
198 tmpcur.clearSelection();
199 bv->setCursor(tmpcur);
203 /// Moves cursor to the next inset with given code.
204 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
206 gotoInset(bv, vector<InsetCode>(1, code), same_content);
210 /// A map from a Text to the associated text metrics
211 typedef std::map<Text const *, TextMetrics> TextMetricsCache;
216 /////////////////////////////////////////////////////////////////////
220 /////////////////////////////////////////////////////////////////////
222 struct BufferView::Private
224 Private(BufferView & bv): wh_(0), cursor_(bv),
225 anchor_ref_(0), offset_ref_(0), need_centering_(false),
226 last_inset_(0), gui_(0)
230 ScrollbarParameters scrollbarParameters_;
232 ViewMetricsInfo metrics_info_;
234 CoordCache coord_cache_;
236 /// Estimated average par height for scrollbar.
238 /// this is used to handle XSelection events in the right manner.
247 pit_type anchor_ref_;
251 bool need_centering_;
253 /// keyboard mapping object.
256 /// last visited inset.
257 /** kept to send setMouseHover(false).
258 * Not owned, so don't delete.
262 mutable TextMetricsCache text_metrics_;
265 /** Not owned, so don't delete.
267 frontend::GuiBufferViewDelegate * gui_;
271 BufferView::BufferView(Buffer & buf)
272 : width_(0), height_(0), buffer_(buf), d(new Private(*this))
274 d->xsel_cache_.set = false;
275 d->intl_.initKeyMapper(lyxrc.use_kbmap);
277 d->cursor_.push(buffer_.inset());
278 d->cursor_.resetAnchor();
279 d->cursor_.setCurrentFont();
281 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
282 graphics::Previews::get().generateBufferPreviews(buffer_);
286 BufferView::~BufferView()
288 // current buffer is going to be switched-off, save cursor pos
289 // Ideally, the whole cursor stack should be saved, but session
290 // currently can only handle bottom (whole document) level pit and pos.
291 // That is to say, if a cursor is in a nested inset, it will be
292 // restore to the left of the top level inset.
293 LastFilePosSection::FilePos fp;
294 fp.pit = d->cursor_.bottom().pit();
295 fp.pos = d->cursor_.bottom().pos();
296 LyX::ref().session().lastFilePos().save(buffer_.fileName(), fp);
302 Intl & BufferView::getIntl()
308 Intl const & BufferView::getIntl() const
314 CoordCache & BufferView::coordCache()
316 return d->coord_cache_;
320 CoordCache const & BufferView::coordCache() const
322 return d->coord_cache_;
326 Buffer & BufferView::buffer()
332 Buffer const & BufferView::buffer() const
338 bool BufferView::fitCursor()
340 if (cursorStatus(d->cursor_) == CUR_INSIDE) {
341 frontend::FontMetrics const & fm =
342 theFontMetrics(d->cursor_.getFont().fontInfo());
343 int const asc = fm.maxAscent();
344 int const des = fm.maxDescent();
345 Point const p = getPos(d->cursor_, d->cursor_.boundary());
346 if (p.y_ - asc >= 0 && p.y_ + des < height_)
354 void BufferView::processUpdateFlags(Update::flags flags)
356 // last_inset_ points to the last visited inset. This pointer may become
357 // invalid because of keyboard editing. Since all such operations
358 // causes screen update(), I reset last_inset_ to avoid such a problem.
360 // This is close to a hot-path.
361 LYXERR(Debug::DEBUG, "BufferView::processUpdateFlags()"
362 << "[fitcursor = " << (flags & Update::FitCursor)
363 << ", forceupdate = " << (flags & Update::Force)
364 << ", singlepar = " << (flags & Update::SinglePar)
365 << "] buffer: " << &buffer_);
367 // Update macro store
368 if (!(cursor().inMathed() && cursor().inMacroMode()))
369 buffer_.updateMacros();
371 // Now do the first drawing step if needed. This consists on updating
372 // the CoordCache in updateMetrics().
373 // The second drawing step is done in WorkArea::redraw() if needed.
375 // Case when no explicit update is requested.
377 // no need to redraw anything.
378 d->metrics_info_.update_strategy = NoScreenUpdate;
382 if (flags == Update::Decoration) {
383 d->metrics_info_.update_strategy = DecorationUpdate;
388 if (flags == Update::FitCursor
389 || flags == (Update::Decoration | Update::FitCursor)) {
390 bool const fit_cursor = fitCursor();
391 // tell the frontend to update the screen if needed.
397 if (flags & Update::Decoration) {
398 d->metrics_info_.update_strategy = DecorationUpdate;
402 // no screen update is needed.
403 d->metrics_info_.update_strategy = NoScreenUpdate;
407 bool const full_metrics = flags & Update::Force;
409 if (full_metrics || !singleParUpdate())
410 // We have to update the full screen metrics.
413 if (!(flags & Update::FitCursor)) {
418 //FIXME: updateMetrics() does not update paragraph position
419 // This is done at draw() time. So we need a redraw!
422 // The screen has already been updated thanks to the
423 // 'buffer_.changed()' call three line above. So no need
427 // The screen has been recentered around the cursor position so
434 void BufferView::updateScrollbar()
436 Text & t = buffer_.text();
437 TextMetrics & tm = d->text_metrics_[&t];
439 int const parsize = int(t.paragraphs().size() - 1);
440 if (d->anchor_ref_ > parsize) {
441 d->anchor_ref_ = parsize;
445 LYXERR(Debug::GUI, BOOST_CURRENT_FUNCTION
446 << " Updating scrollbar: height: " << t.paragraphs().size()
447 << " curr par: " << d->cursor_.bottom().pit()
448 << " default height " << defaultRowHeight());
450 // It would be better to fix the scrollbar to understand
451 // values in [0..1] and divide everything by wh
453 // estimated average paragraph height:
455 d->wh_ = height_ / 4;
457 int h = tm.parMetrics(d->anchor_ref_).height();
459 // Normalize anchor/offset (MV):
460 while (d->offset_ref_ > h && d->anchor_ref_ < parsize) {
463 h = tm.parMetrics(d->anchor_ref_).height();
465 // Look at paragraph heights on-screen
468 for (pit_type pit = d->anchor_ref_; pit <= parsize; ++pit) {
471 int const h2 = tm.parMetrics(pit).height();
477 int const hav = sumh / nh;
478 // More realistic average paragraph height
483 d->scrollbarParameters_.height = (parsize + 1) * d->wh_;
484 d->scrollbarParameters_.position = d->anchor_ref_ * d->wh_ + int(d->offset_ref_ * d->wh_ / float(h));
485 d->scrollbarParameters_.lineScrollHeight = int(d->wh_ * defaultRowHeight() / float(h));
489 ScrollbarParameters const & BufferView::scrollbarParameters() const
491 return d->scrollbarParameters_;
495 void BufferView::scrollDocView(int value)
497 LYXERR(Debug::GUI, BOOST_CURRENT_FUNCTION << "[ value = " << value << "]");
499 Text & t = buffer_.text();
500 TextMetrics & tm = d->text_metrics_[&t];
502 float const bar = value / float(d->wh_ * t.paragraphs().size());
504 d->anchor_ref_ = int(bar * t.paragraphs().size());
505 if (d->anchor_ref_ > int(t.paragraphs().size()) - 1)
506 d->anchor_ref_ = int(t.paragraphs().size()) - 1;
508 tm.redoParagraph(d->anchor_ref_);
509 int const h = tm.parMetrics(d->anchor_ref_).height();
510 d->offset_ref_ = int((bar * t.paragraphs().size() - d->anchor_ref_) * h);
516 void BufferView::setCursorFromScrollbar()
518 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
520 int const height = 2 * defaultRowHeight();
521 int const first = height;
522 int const last = height_ - height;
523 Cursor & cur = d->cursor_;
525 switch (cursorStatus(cur)) {
527 // We reset the cursor because cursorStatus() does not
528 // work when the cursor is within mathed.
529 cur.reset(buffer_.inset());
530 tm.setCursorFromCoordinates(cur, 0, first);
531 cur.clearSelection();
534 // We reset the cursor because cursorStatus() does not
535 // work when the cursor is within mathed.
536 cur.reset(buffer_.inset());
537 tm.setCursorFromCoordinates(cur, 0, last);
538 cur.clearSelection();
541 int const y = getPos(cur, cur.boundary()).y_;
542 int const newy = min(last, max(y, first));
544 cur.reset(buffer_.inset());
545 tm.setCursorFromCoordinates(cur, 0, newy);
551 Change const BufferView::getCurrentChange() const
553 if (!d->cursor_.selection())
554 return Change(Change::UNCHANGED);
556 DocIterator dit = d->cursor_.selectionBegin();
557 return dit.paragraph().lookupChange(dit.pos());
561 // this could be used elsewhere as well?
562 // FIXME: This does not work within mathed!
563 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
565 Point const p = getPos(dit, dit.boundary());
568 if (p.y_ > workHeight())
574 void BufferView::saveBookmark(unsigned int idx)
576 // tenatively save bookmark, id and pos will be used to
577 // acturately locate a bookmark in a 'live' lyx session.
578 // pit and pos will be updated with bottom level pit/pos
580 LyX::ref().session().bookmarks().save(
582 d->cursor_.bottom().pit(),
583 d->cursor_.bottom().pos(),
584 d->cursor_.paragraph().id(),
589 // emit message signal.
590 message(_("Save bookmark"));
594 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
595 int top_id, pos_type top_pos)
597 bool success = false;
600 d->cursor_.clearSelection();
602 // if a valid par_id is given, try it first
603 // This is the case for a 'live' bookmark when unique paragraph ID
604 // is used to track bookmarks.
606 ParIterator par = buffer_.getParFromID(top_id);
607 if (par != buffer_.par_iterator_end()) {
608 doc_it = makeDocIterator(par, min(par->size(), top_pos));
609 // Some slices of the iterator may not be
610 // reachable (e.g. closed collapsable inset)
611 // so the dociterator may need to be
612 // shortened. Otherwise, setCursor may crash
613 // lyx when the cursor can not be set to these
615 size_t const n = doc_it.depth();
616 for (size_t i = 0; i < n; ++i)
617 if (doc_it[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
625 // if top_id == 0, or searching through top_id failed
626 // This is the case for a 'restored' bookmark when only bottom
627 // (document level) pit was saved. Because of this, bookmark
628 // restoration is inaccurate. If a bookmark was within an inset,
629 // it will be restored to the left of the outmost inset that contains
631 if (static_cast<size_t>(bottom_pit) < buffer_.paragraphs().size()) {
632 doc_it = doc_iterator_begin(buffer_.inset());
633 doc_it.pit() = bottom_pit;
634 doc_it.pos() = min(bottom_pos, doc_it.paragraph().size());
639 // Note: only bottom (document) level pit is set.
641 // set the current font.
642 d->cursor_.setCurrentFont();
643 // center the screen on this new position.
651 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
653 if (lyxrc.rtl_support) {
654 if (d->cursor_.real_current_font.isRightToLeft()) {
655 if (d->intl_.keymap == Intl::PRIMARY)
656 d->intl_.keyMapSec();
658 if (d->intl_.keymap == Intl::SECONDARY)
659 d->intl_.keyMapPrim();
663 d->intl_.getTransManager().translateAndInsert(c, t, cur);
667 int BufferView::workWidth() const
673 void BufferView::updateOffsetRef()
675 // No need to update d->offset_ref_ in this case.
676 if (!d->need_centering_)
679 // We are not properly started yet, delay until resizing is
684 CursorSlice & bot = d->cursor_.bottom();
685 TextMetrics & tm = d->text_metrics_[bot.text()];
686 ParagraphMetrics const & pm = tm.parMetrics(bot.pit());
687 int y = coordOffset(d->cursor_, d->cursor_.boundary()).y_;
688 d->offset_ref_ = y + pm.ascent() - height_ / 2;
690 d->need_centering_ = false;
694 void BufferView::center()
696 d->anchor_ref_ = d->cursor_.bottom().pit();
697 d->need_centering_ = true;
701 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
705 Cursor & cur = d->cursor_;
707 switch (cmd.action) {
710 flag.enabled(buffer_.undo().hasUndoStack());
713 flag.enabled(buffer_.undo().hasRedoStack());
715 case LFUN_FILE_INSERT:
716 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
717 case LFUN_FILE_INSERT_PLAINTEXT:
718 case LFUN_BOOKMARK_SAVE:
719 // FIXME: Actually, these LFUNS should be moved to Text
720 flag.enabled(cur.inTexted());
722 case LFUN_FONT_STATE:
723 case LFUN_LABEL_INSERT:
724 case LFUN_INFO_INSERT:
725 case LFUN_PARAGRAPH_GOTO:
727 case LFUN_REFERENCE_NEXT:
729 case LFUN_WORD_REPLACE:
732 case LFUN_MARK_TOGGLE:
733 case LFUN_SCREEN_RECENTER:
734 case LFUN_BIBTEX_DATABASE_ADD:
735 case LFUN_BIBTEX_DATABASE_DEL:
736 case LFUN_WORDS_COUNT:
737 case LFUN_NEXT_INSET_TOGGLE:
741 case LFUN_LABEL_GOTO: {
742 flag.enabled(!cmd.argument().empty()
743 || getInsetByCode<InsetRef>(cur, REF_CODE));
747 case LFUN_CHANGES_TRACK:
749 flag.setOnOff(buffer_.params().trackChanges);
752 case LFUN_CHANGES_OUTPUT:
754 flag.setOnOff(buffer_.params().outputChanges);
757 case LFUN_CHANGES_MERGE:
758 case LFUN_CHANGE_NEXT:
759 case LFUN_ALL_CHANGES_ACCEPT:
760 case LFUN_ALL_CHANGES_REJECT:
761 // TODO: context-sensitive enabling of LFUNs
762 // In principle, these command should only be enabled if there
763 // is a change in the document. However, without proper
764 // optimizations, this will inevitably result in poor performance.
768 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
769 flag.setOnOff(buffer_.params().compressed);
773 case LFUN_BUFFER_TOGGLE_EMBEDDING: {
774 flag.setOnOff(buffer_.params().embedded);
779 case LFUN_SCREEN_DOWN:
783 // FIXME: LFUN_SCREEN_DOWN_SELECT should be removed from
784 // everywhere else before this can enabled:
785 case LFUN_SCREEN_UP_SELECT:
786 case LFUN_SCREEN_DOWN_SELECT:
790 case LFUN_LAYOUT_TABULAR:
791 flag.enabled(cur.innerInsetOfType(TABULAR_CODE));
795 case LFUN_LAYOUT_PARAGRAPH:
796 flag.enabled(cur.inset().forceDefaultParagraphs(cur.idx()));
799 case LFUN_INSET_SETTINGS: {
800 InsetCode code = cur.inset().lyxCode();
804 enable = cmd.argument() == "tabular";
807 enable = cmd.argument() == "ert";
810 enable = cmd.argument() == "float";
813 enable = cmd.argument() == "wrap";
816 enable = cmd.argument() == "note";
819 enable = cmd.argument() == "branch";
822 enable = cmd.argument() == "box";
825 enable = cmd.argument() == "listings";
830 flag.enabled(enable);
834 case LFUN_DIALOG_SHOW_NEW_INSET:
835 flag.enabled(cur.inset().lyxCode() != ERT_CODE &&
836 cur.inset().lyxCode() != LISTINGS_CODE);
837 if (cur.inset().lyxCode() == CAPTION_CODE) {
839 if (cur.inset().getStatus(cur, cmd, flag))
852 Update::flags BufferView::dispatch(FuncRequest const & cmd)
854 //lyxerr << BOOST_CURRENT_FUNCTION
855 // << [ cmd = " << cmd << "]" << endl;
857 // Make sure that the cached BufferView is correct.
858 LYXERR(Debug::ACTION, BOOST_CURRENT_FUNCTION
859 << " action[" << cmd.action << ']'
860 << " arg[" << to_utf8(cmd.argument()) << ']'
861 << " x[" << cmd.x << ']'
862 << " y[" << cmd.y << ']'
863 << " button[" << cmd.button() << ']');
865 Cursor & cur = d->cursor_;
866 // Default Update flags.
867 Update::flags updateFlags = Update::Force | Update::FitCursor;
869 switch (cmd.action) {
872 cur.message(_("Undo"));
873 cur.clearSelection();
874 if (!cur.textUndo()) {
875 cur.message(_("No further undo information"));
876 updateFlags = Update::None;
881 cur.message(_("Redo"));
882 cur.clearSelection();
883 if (!cur.textRedo()) {
884 cur.message(_("No further redo information"));
885 updateFlags = Update::None;
889 case LFUN_FILE_INSERT:
891 menuInsertLyXFile(to_utf8(cmd.argument()));
894 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
896 insertPlaintextFile(to_utf8(cmd.argument()), true);
899 case LFUN_FILE_INSERT_PLAINTEXT:
901 insertPlaintextFile(to_utf8(cmd.argument()), false);
904 case LFUN_FONT_STATE:
905 cur.message(cur.currentState());
908 case LFUN_BOOKMARK_SAVE:
909 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
912 case LFUN_LABEL_GOTO: {
913 docstring label = cmd.argument();
916 getInsetByCode<InsetRef>(d->cursor_,
919 label = inset->getParam("reference");
920 // persistent=false: use temp_bookmark
930 case LFUN_PARAGRAPH_GOTO: {
931 int const id = convert<int>(to_utf8(cmd.argument()));
933 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
934 b = theBufferList().next(b)) {
936 ParIterator par = b->getParFromID(id);
937 if (par == b->par_iterator_end()) {
938 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
940 LYXERR(Debug::INFO, "Paragraph " << par->id()
941 << " found in buffer `"
942 << b->absFileName() << "'.");
946 setCursor(makeDocIterator(par, 0));
948 // Switch to other buffer view and resend cmd
949 theLyXFunc().dispatch(FuncRequest(
950 LFUN_BUFFER_SWITCH, b->absFileName()));
951 theLyXFunc().dispatch(cmd);
952 updateFlags = Update::None;
962 gotoInset(this, NOTE_CODE, false);
965 case LFUN_REFERENCE_NEXT: {
966 vector<InsetCode> tmp;
967 tmp.push_back(LABEL_CODE);
968 tmp.push_back(REF_CODE);
969 gotoInset(this, tmp, true);
973 case LFUN_CHANGES_TRACK:
974 buffer_.params().trackChanges = !buffer_.params().trackChanges;
977 case LFUN_CHANGES_OUTPUT:
978 buffer_.params().outputChanges = !buffer_.params().outputChanges;
979 if (buffer_.params().outputChanges) {
980 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
981 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
982 LaTeXFeatures::isAvailable("xcolor");
984 if (!dvipost && !xcolorsoul) {
985 Alert::warning(_("Changes not shown in LaTeX output"),
986 _("Changes will not be highlighted in LaTeX output, "
987 "because neither dvipost nor xcolor/soul are installed.\n"
988 "Please install these packages or redefine "
989 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
990 } else if (!xcolorsoul) {
991 Alert::warning(_("Changes not shown in LaTeX output"),
992 _("Changes will not be highlighted in LaTeX output "
993 "when using pdflatex, because xcolor and soul are not installed.\n"
994 "Please install both packages or redefine "
995 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1000 case LFUN_CHANGE_NEXT:
1001 findNextChange(this);
1004 case LFUN_CHANGES_MERGE:
1005 if (findNextChange(this))
1006 showDialog("changes");
1009 case LFUN_ALL_CHANGES_ACCEPT:
1010 // select complete document
1011 d->cursor_.reset(buffer_.inset());
1012 d->cursor_.selHandle(true);
1013 buffer_.text().cursorBottom(d->cursor_);
1014 // accept everything in a single step to support atomic undo
1015 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::ACCEPT);
1018 case LFUN_ALL_CHANGES_REJECT:
1019 // select complete document
1020 d->cursor_.reset(buffer_.inset());
1021 d->cursor_.selHandle(true);
1022 buffer_.text().cursorBottom(d->cursor_);
1023 // reject everything in a single step to support atomic undo
1024 // Note: reject does not work recursively; the user may have to repeat the operation
1025 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::REJECT);
1028 case LFUN_WORD_FIND:
1032 case LFUN_WORD_REPLACE: {
1033 bool has_deleted = false;
1034 if (cur.selection()) {
1035 DocIterator beg = cur.selectionBegin();
1036 DocIterator end = cur.selectionEnd();
1037 if (beg.pit() == end.pit()) {
1038 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1039 if (cur.paragraph().isDeleted(p))
1044 replace(this, cmd, has_deleted);
1049 cur.clearSelection();
1051 cur.message(from_utf8(N_("Mark off")));
1055 cur.clearSelection();
1058 cur.message(from_utf8(N_("Mark on")));
1061 case LFUN_MARK_TOGGLE:
1062 cur.clearSelection();
1065 cur.message(from_utf8(N_("Mark removed")));
1068 cur.message(from_utf8(N_("Mark set")));
1073 case LFUN_SCREEN_RECENTER:
1077 case LFUN_BIBTEX_DATABASE_ADD: {
1078 Cursor tmpcur = d->cursor_;
1079 findInset(tmpcur, BIBTEX_CODE, false);
1080 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1083 if (inset->addDatabase(to_utf8(cmd.argument())))
1084 buffer_.updateBibfilesCache();
1089 case LFUN_BIBTEX_DATABASE_DEL: {
1090 Cursor tmpcur = d->cursor_;
1091 findInset(tmpcur, BIBTEX_CODE, false);
1092 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1095 if (inset->delDatabase(to_utf8(cmd.argument())))
1096 buffer_.updateBibfilesCache();
1101 case LFUN_WORDS_COUNT: {
1102 DocIterator from, to;
1103 if (cur.selection()) {
1104 from = cur.selectionBegin();
1105 to = cur.selectionEnd();
1107 from = doc_iterator_begin(buffer_.inset());
1108 to = doc_iterator_end(buffer_.inset());
1110 int const count = countWords(from, to);
1113 if (cur.selection())
1114 message = bformat(_("%1$d words in selection."),
1117 message = bformat(_("%1$d words in document."),
1121 if (cur.selection())
1122 message = _("One word in selection.");
1124 message = _("One word in document.");
1127 Alert::information(_("Count words"), message);
1131 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1132 // turn compression on/off
1133 buffer_.params().compressed = !buffer_.params().compressed;
1136 case LFUN_BUFFER_TOGGLE_EMBEDDING:
1137 // turn embedding on/off
1138 buffer_.embeddedFiles().enable(!buffer_.params().embedded);
1141 case LFUN_NEXT_INSET_TOGGLE: {
1142 // this is the real function we want to invoke
1143 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1144 // if there is an inset at cursor, see whether it
1146 Inset * inset = cur.nextInset();
1148 if (inset->isActive()) {
1149 Cursor tmpcur = cur;
1150 tmpcur.pushBackward(*inset);
1151 inset->dispatch(tmpcur, tmpcmd);
1152 if (tmpcur.result().dispatched()) {
1155 } else if (inset->editable() == Inset::IS_EDITABLE) {
1156 inset->edit(cur, true);
1159 // if it did not work, try the underlying inset.
1160 if (!cur.result().dispatched())
1161 cur.dispatch(tmpcmd);
1163 if (cur.result().dispatched())
1164 cur.clearSelection();
1169 case LFUN_SCREEN_UP:
1170 case LFUN_SCREEN_DOWN: {
1171 Point p = getPos(cur, cur.boundary());
1172 if (p.y_ < 0 || p.y_ > height_) {
1173 // The cursor is off-screen so recenter before proceeding.
1176 //FIXME: updateMetrics() does not update paragraph position
1177 // This is done at draw() time. So we need a redraw!
1178 // But no screen update is needed.
1179 d->metrics_info_.update_strategy = NoScreenUpdate;
1181 p = getPos(cur, cur.boundary());
1183 scroll(cmd.action == LFUN_SCREEN_UP? - height_ : height_);
1184 cur.reset(buffer_.inset());
1185 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1186 //FIXME: what to do with cur.x_target()?
1188 // The metrics are already up to date. see scroll()
1189 updateFlags = Update::None;
1193 case LFUN_SCREEN_UP_SELECT:
1194 case LFUN_SCREEN_DOWN_SELECT: {
1195 cur.selHandle(true);
1196 size_t initial_depth = cur.depth();
1197 Point const p = getPos(cur, cur.boundary());
1198 scroll(cmd.action == LFUN_SCREEN_UP_SELECT? - height_ : height_);
1199 // FIXME: We need to verify if the cursor stayed within an inset...
1200 //cur.reset(buffer_.inset());
1201 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1203 while (cur.depth() > initial_depth) {
1206 // FIXME: we need to do a redraw again because of the selection
1207 // But no screen update is needed.
1208 d->metrics_info_.update_strategy = NoScreenUpdate;
1210 updateFlags = Update::Force | Update::FitCursor;
1215 updateFlags = Update::None;
1222 docstring const BufferView::requestSelection()
1224 Cursor & cur = d->cursor_;
1226 if (!cur.selection()) {
1227 d->xsel_cache_.set = false;
1231 if (!d->xsel_cache_.set ||
1232 cur.top() != d->xsel_cache_.cursor ||
1233 cur.anchor_.top() != d->xsel_cache_.anchor)
1235 d->xsel_cache_.cursor = cur.top();
1236 d->xsel_cache_.anchor = cur.anchor_.top();
1237 d->xsel_cache_.set = cur.selection();
1238 return cur.selectionAsString(false);
1244 void BufferView::clearSelection()
1246 d->cursor_.clearSelection();
1247 // Clear the selection buffer. Otherwise a subsequent
1248 // middle-mouse-button paste would use the selection buffer,
1249 // not the more current external selection.
1250 cap::clearSelection();
1251 d->xsel_cache_.set = false;
1252 // The buffer did not really change, but this causes the
1253 // redraw we need because we cleared the selection above.
1258 void BufferView::resize(int width, int height)
1260 // Update from work area
1268 Inset const * BufferView::getCoveringInset(Text const & text, int x, int y)
1270 TextMetrics & tm = d->text_metrics_[&text];
1271 Inset * inset = tm.checkInsetHit(x, y);
1275 if (!inset->descendable())
1276 // No need to go further down if the inset is not
1280 size_t cell_number = inset->nargs();
1281 // Check all the inner cell.
1282 for (size_t i = 0; i != cell_number; ++i) {
1283 Text const * inner_text = inset->getText(i);
1286 Inset const * inset_deeper =
1287 getCoveringInset(*inner_text, x, y);
1289 return inset_deeper;
1297 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1299 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1301 // This is only called for mouse related events including
1302 // LFUN_FILE_OPEN generated by drag-and-drop.
1303 FuncRequest cmd = cmd0;
1306 cur.push(buffer_.inset());
1307 cur.selection() = d->cursor_.selection();
1309 // Either the inset under the cursor or the
1310 // surrounding Text will handle this event.
1312 // make sure we stay within the screen...
1313 cmd.y = min(max(cmd.y, -1), height_);
1315 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1317 // Get inset under mouse, if there is one.
1318 Inset const * covering_inset =
1319 getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1320 if (covering_inset == d->last_inset_)
1321 // Same inset, no need to do anything...
1324 bool need_redraw = false;
1325 // const_cast because of setMouseHover().
1326 Inset * inset = const_cast<Inset *>(covering_inset);
1328 // Remove the hint on the last hovered inset (if any).
1329 need_redraw |= d->last_inset_->setMouseHover(false);
1331 // Highlighted the newly hovered inset (if any).
1332 need_redraw |= inset->setMouseHover(true);
1333 d->last_inset_ = inset;
1337 // if last metrics update was in singlepar mode, WorkArea::redraw() will
1338 // not expose the button for redraw. We adjust here the metrics dimension
1339 // to enable a full redraw in any case as this is not costly.
1340 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
1341 std::pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
1342 std::pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
1343 int y1 = firstpm.second->position() - firstpm.second->ascent();
1344 int y2 = lastpm.second->position() + lastpm.second->descent();
1345 d->metrics_info_ = ViewMetricsInfo(firstpm.first, lastpm.first, y1, y2,
1346 FullScreenUpdate, buffer_.text().paragraphs().size());
1347 // Reinitialize anchor to first pit.
1348 d->anchor_ref_ = firstpm.first;
1349 d->offset_ref_ = -y1;
1350 LYXERR(Debug::PAINTING,
1351 "Mouse hover detected at: (" << cmd.x << ", " << cmd.y << ")"
1352 << "\nTriggering redraw: y1: " << y1 << " y2: " << y2
1353 << " pit1: " << firstpm.first << " pit2: " << lastpm.first);
1355 // This event (moving without mouse click) is not passed further.
1356 // This should be changed if it is further utilized.
1361 // Build temporary cursor.
1362 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1364 // Put anchor at the same position.
1367 // Try to dispatch to an non-editable inset near this position
1368 // via the temp cursor. If the inset wishes to change the real
1369 // cursor it has to do so explicitly by using
1370 // cur.bv().cursor() = cur; (or similar)
1372 inset->dispatch(cur, cmd);
1374 // Now dispatch to the temporary cursor. If the real cursor should
1375 // be modified, the inset's dispatch has to do so explicitly.
1376 if (!cur.result().dispatched())
1379 //Do we have a selection?
1380 theSelection().haveSelection(cursor().selection());
1382 // If the command has been dispatched,
1383 if (cur.result().dispatched()
1384 // an update is asked,
1385 && cur.result().update())
1386 processUpdateFlags(cur.result().update());
1390 void BufferView::scroll(int y)
1399 void BufferView::scrollDown(int offset)
1401 Text * text = &buffer_.text();
1402 TextMetrics & tm = d->text_metrics_[text];
1403 int ymax = height_ + offset;
1405 std::pair<pit_type, ParagraphMetrics const *> last = tm.last();
1406 int bottom_pos = last.second->position() + last.second->descent();
1407 if (last.first + 1 == int(text->paragraphs().size())) {
1408 if (bottom_pos <= height_)
1410 offset = min(offset, bottom_pos - height_);
1413 if (bottom_pos > ymax)
1415 tm.newParMetricsDown();
1417 d->offset_ref_ += offset;
1423 void BufferView::scrollUp(int offset)
1425 Text * text = &buffer_.text();
1426 TextMetrics & tm = d->text_metrics_[text];
1427 int ymin = - offset;
1429 std::pair<pit_type, ParagraphMetrics const *> first = tm.first();
1430 int top_pos = first.second->position() - first.second->ascent();
1431 if (first.first == 0) {
1434 offset = min(offset, - top_pos);
1439 tm.newParMetricsUp();
1441 d->offset_ref_ -= offset;
1447 void BufferView::setCursorFromRow(int row)
1452 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1454 d->cursor_.reset(buffer_.inset());
1456 buffer_.text().setCursor(d->cursor_, 0, 0);
1458 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1462 void BufferView::gotoLabel(docstring const & label)
1464 for (InsetIterator it = inset_iterator_begin(buffer_.inset()); it; ++it) {
1465 vector<docstring> labels;
1466 it->getLabelList(buffer_, labels);
1467 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1469 processUpdateFlags(Update::FitCursor);
1476 TextMetrics const & BufferView::textMetrics(Text const * t) const
1478 return const_cast<BufferView *>(this)->textMetrics(t);
1482 TextMetrics & BufferView::textMetrics(Text const * t)
1484 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
1485 if (tmc_it == d->text_metrics_.end()) {
1486 tmc_it = d->text_metrics_.insert(
1487 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1489 return tmc_it->second;
1493 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1496 return textMetrics(t).parMetrics(pit);
1500 int BufferView::workHeight() const
1506 void BufferView::setCursor(DocIterator const & dit)
1508 size_t const n = dit.depth();
1509 for (size_t i = 0; i < n; ++i)
1510 dit[i].inset().edit(d->cursor_, true);
1512 d->cursor_.setCursor(dit);
1513 d->cursor_.selection() = false;
1517 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1519 // Would be wrong to delete anything if we have a selection.
1520 if (cur.selection())
1523 bool need_anchor_change = false;
1524 bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1525 need_anchor_change);
1527 if (need_anchor_change)
1533 updateLabels(buffer_);
1541 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
1543 BOOST_ASSERT(&cur.bv() == this);
1546 // this event will clear selection so we save selection for
1547 // persistent selection
1548 cap::saveSelection(cursor());
1550 // Has the cursor just left the inset?
1551 bool badcursor = false;
1552 bool leftinset = (&d->cursor_.inset() != &cur.inset());
1554 badcursor = notifyCursorLeaves(d->cursor_, cur);
1556 // FIXME: shift-mouse selection doesn't work well across insets.
1557 bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
1559 // do the dEPM magic if needed
1560 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1561 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1562 // the leftinset bool would not be necessary (badcursor instead).
1563 bool update = leftinset;
1564 if (!do_selection && !badcursor && d->cursor_.inTexted())
1565 update |= checkDepm(cur, d->cursor_);
1567 // if the cursor was in an empty script inset and the new
1568 // position is in the nucleus of the inset, notifyCursorLeaves
1569 // will kill the script inset itself. So we check all the
1570 // elements of the cursor to make sure that they are correct.
1571 // For an example, see bug 2933:
1572 // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1573 // The code below could maybe be moved to a DocIterator method.
1574 //lyxerr << "cur before " << cur <<std::endl;
1575 DocIterator dit(cur.inset());
1576 dit.push_back(cur.bottom());
1578 while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1579 dit.push_back(cur[i]);
1582 //lyxerr << "5 cur after" << dit <<std::endl;
1584 d->cursor_.setCursor(dit);
1585 d->cursor_.boundary(cur.boundary());
1587 d->cursor_.setSelection();
1589 d->cursor_.clearSelection();
1591 d->cursor_.finishUndo();
1592 d->cursor_.setCurrentFont();
1597 void BufferView::putSelectionAt(DocIterator const & cur,
1598 int length, bool backwards)
1600 d->cursor_.clearSelection();
1606 d->cursor_.pos() += length;
1607 d->cursor_.setSelection(d->cursor_, -length);
1609 d->cursor_.setSelection(d->cursor_, length);
1614 Cursor & BufferView::cursor()
1620 Cursor const & BufferView::cursor() const
1626 pit_type BufferView::anchor_ref() const
1628 return d->anchor_ref_;
1632 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1634 return d->metrics_info_;
1638 bool BufferView::singleParUpdate()
1640 Text & buftext = buffer_.text();
1641 pit_type const bottom_pit = d->cursor_.bottom().pit();
1642 TextMetrics & tm = textMetrics(&buftext);
1643 int old_height = tm.parMetrics(bottom_pit).height();
1645 // In Single Paragraph mode, rebreak only
1646 // the (main text, not inset!) paragraph containing the cursor.
1647 // (if this paragraph contains insets etc., rebreaking will
1648 // recursively descend)
1649 tm.redoParagraph(bottom_pit);
1650 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
1651 if (pm.height() != old_height)
1652 // Paragraph height has changed so we cannot proceed to
1653 // the singlePar optimisation.
1656 int y1 = pm.position() - pm.ascent();
1657 int y2 = pm.position() + pm.descent();
1658 d->metrics_info_ = ViewMetricsInfo(bottom_pit, bottom_pit, y1, y2,
1659 SingleParUpdate, buftext.paragraphs().size());
1660 LYXERR(Debug::PAINTING, BOOST_CURRENT_FUNCTION
1663 << " pit: " << bottom_pit
1664 << " singlepar: 1");
1669 void BufferView::updateMetrics()
1671 Text & buftext = buffer_.text();
1672 pit_type const npit = int(buftext.paragraphs().size());
1674 if (d->anchor_ref_ > int(npit - 1)) {
1675 d->anchor_ref_ = int(npit - 1);
1679 // Clear out the position cache in case of full screen redraw,
1680 d->coord_cache_.clear();
1682 // Clear out paragraph metrics to avoid having invalid metrics
1683 // in the cache from paragraphs not relayouted below
1684 // The complete text metrics will be redone.
1685 d->text_metrics_.clear();
1687 TextMetrics & tm = textMetrics(&buftext);
1689 pit_type const pit = d->anchor_ref_;
1693 // Rebreak anchor paragraph.
1694 tm.redoParagraph(pit);
1696 // Take care of anchor offset if case a recentering is needed.
1699 int y0 = tm.parMetrics(pit).ascent() - d->offset_ref_;
1701 // Redo paragraphs above anchor if necessary.
1703 while (y1 > 0 && pit1 > 0) {
1704 y1 -= tm.parMetrics(pit1).ascent();
1706 tm.redoParagraph(pit1);
1707 y1 -= tm.parMetrics(pit1).descent();
1710 // Take care of ascent of first line
1711 y1 -= tm.parMetrics(pit1).ascent();
1713 // Normalize anchor for next time
1714 d->anchor_ref_ = pit1;
1715 d->offset_ref_ = -y1;
1717 // Grey at the beginning is ugly
1718 if (pit1 == 0 && y1 > 0) {
1724 // Redo paragraphs below the anchor if necessary.
1726 while (y2 < height_ && pit2 < int(npit) - 1) {
1727 y2 += tm.parMetrics(pit2).descent();
1729 tm.redoParagraph(pit2);
1730 y2 += tm.parMetrics(pit2).ascent();
1733 // Take care of descent of last line
1734 y2 += tm.parMetrics(pit2).descent();
1736 LYXERR(Debug::PAINTING, BOOST_CURRENT_FUNCTION
1739 << " pit1: " << pit1
1740 << " pit2: " << pit2
1741 << " npit: " << npit
1742 << " singlepar: 0");
1744 d->metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2,
1745 FullScreenUpdate, npit);
1747 if (lyxerr.debugging(Debug::WORKAREA)) {
1748 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
1749 d->coord_cache_.dump();
1754 void BufferView::menuInsertLyXFile(string const & filenm)
1756 BOOST_ASSERT(d->cursor_.inTexted());
1757 string filename = filenm;
1759 if (filename.empty()) {
1760 // Launch a file browser
1762 string initpath = lyxrc.document_path;
1763 string const trypath = buffer_.filePath();
1764 // If directory is writeable, use this as default.
1765 if (FileName(trypath).isDirWritable())
1769 FileDialog dlg(_("Select LyX document to insert"), LFUN_FILE_INSERT);
1770 dlg.setButton1(_("Documents|#o#O"), from_utf8(lyxrc.document_path));
1771 dlg.setButton2(_("Examples|#E#e"),
1772 from_utf8(addPath(package().system_support().absFilename(),
1775 FileDialog::Result result =
1776 dlg.open(from_utf8(initpath),
1777 FileFilterList(_("LyX Documents (*.lyx)")),
1780 if (result.first == FileDialog::Later)
1784 filename = to_utf8(result.second);
1786 // check selected filename
1787 if (filename.empty()) {
1788 // emit message signal.
1789 message(_("Canceled."));
1794 // Get absolute path of file and add ".lyx"
1795 // to the filename if necessary
1796 filename = fileSearch(string(), filename, "lyx").absFilename();
1798 docstring const disp_fn = makeDisplayPath(filename);
1799 // emit message signal.
1800 message(bformat(_("Inserting document %1$s..."), disp_fn));
1803 Buffer buf("", false);
1804 if (buf.loadLyXFile(FileName(filename))) {
1805 ErrorList & el = buffer_.errorList("Parse");
1806 // Copy the inserted document error list into the current buffer one.
1807 el = buf.errorList("Parse");
1808 buffer_.undo().recordUndo(d->cursor_);
1809 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
1810 buf.params().getTextClassPtr(), el);
1811 res = _("Document %1$s inserted.");
1813 res = _("Could not insert document %1$s");
1816 // emit message signal.
1817 message(bformat(res, disp_fn));
1818 buffer_.errors("Parse");
1823 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
1829 // Addup contribution of nested insets, from inside to outside,
1830 // keeping the outer paragraph for a special handling below
1831 for (size_t i = dit.depth() - 1; i >= 1; --i) {
1832 CursorSlice const & sl = dit[i];
1836 // get relative position inside sl.inset()
1837 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
1839 // Make relative position inside of the edited inset relative to sl.inset()
1843 // In case of an RTL inset, the edited inset will be positioned to the left
1846 bool boundary_i = boundary && i + 1 == dit.depth();
1847 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
1852 // remember width for the case that sl.inset() is positioned in an RTL inset
1853 if (i && dit[i - 1].text()) {
1854 // If this Inset is inside a Text Inset, retrieve the Dimension
1855 // from the containing text instead of using Inset::dimension() which
1856 // might not be implemented.
1857 // FIXME (Abdel 23/09/2007): this is a bit messy because of the
1858 // elimination of Inset::dim_ cache. This coordOffset() method needs
1859 // to be rewritten in light of the new design.
1860 Dimension const & dim = parMetrics(dit[i - 1].text(),
1861 dit[i - 1].pit()).insetDimension(&sl.inset());
1864 Dimension const dim = sl.inset().dimension(*this);
1868 //lyxerr << "Cursor::getPos, i: "
1869 // << i << " x: " << xx << " y: " << y << endl;
1872 // Add contribution of initial rows of outermost paragraph
1873 CursorSlice const & sl = dit[0];
1874 TextMetrics const & tm = textMetrics(sl.text());
1875 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
1876 BOOST_ASSERT(!pm.rows().empty());
1877 y -= pm.rows()[0].ascent();
1879 // FIXME: document this mess
1881 if (sl.pos() > 0 && dit.depth() == 1) {
1883 if (pos && boundary)
1885 // lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << std::endl;
1886 rend = pm.pos2row(pos);
1888 rend = pm.pos2row(sl.pos());
1890 size_t rend = pm.pos2row(sl.pos());
1892 for (size_t rit = 0; rit != rend; ++rit)
1893 y += pm.rows()[rit].height();
1894 y += pm.rows()[rend].ascent();
1896 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
1898 // Make relative position from the nested inset now bufferview absolute.
1899 int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
1902 // In the RTL case place the nested inset at the left of the cursor in
1903 // the outer paragraph
1904 bool boundary_1 = boundary && 1 == dit.depth();
1905 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
1913 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
1915 CursorSlice const & bot = dit.bottom();
1916 TextMetrics const & tm = textMetrics(bot.text());
1917 if (!tm.has(bot.pit()))
1918 return Point(-1, -1);
1920 Point p = coordOffset(dit, boundary); // offset from outer paragraph
1921 p.y_ += tm.parMetrics(bot.pit()).position();
1926 void BufferView::draw(frontend::Painter & pain)
1928 LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
1929 Text & text = buffer_.text();
1930 TextMetrics const & tm = d->text_metrics_[&text];
1931 int const y = d->metrics_info_.y1
1932 + tm.parMetrics(d->metrics_info_.p1).ascent();
1933 PainterInfo pi(this, pain);
1935 switch (d->metrics_info_.update_strategy) {
1937 case NoScreenUpdate:
1938 // If no screen painting is actually needed, only some the different
1939 // coordinates of insets and paragraphs needs to be updated.
1940 pi.full_repaint = true;
1941 pi.pain.setDrawingEnabled(false);
1945 case SingleParUpdate:
1946 // Only the current outermost paragraph will be redrawn.
1947 pi.full_repaint = false;
1948 tm.drawParagraph(pi, d->metrics_info_.p1, 0, y);
1951 case DecorationUpdate:
1952 // FIXME: We should also distinguish DecorationUpdate to avoid text
1953 // drawing if possible. This is not possible to do easily right now
1954 // because of the single backing pixmap.
1956 case FullScreenUpdate:
1957 // The whole screen, including insets, will be refreshed.
1958 pi.full_repaint = true;
1960 // Clear background (if not delegated to rows)
1961 pain.fillRectangle(0, d->metrics_info_.y1, width_,
1962 d->metrics_info_.y2 - d->metrics_info_.y1,
1963 buffer_.inset().backgroundColor());
1966 // and grey out above (should not happen later)
1967 if (d->metrics_info_.y1 > 0)
1968 pain.fillRectangle(0, 0, width_,
1969 d->metrics_info_.y1, Color_bottomarea);
1971 // and possibly grey out below
1972 if (d->metrics_info_.y2 < height_)
1973 pain.fillRectangle(0, d->metrics_info_.y2, width_,
1974 height_ - d->metrics_info_.y2, Color_bottomarea);
1978 LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING ***");
1982 void BufferView::message(docstring const & msg)
1985 d->gui_->message(msg);
1989 void BufferView::showDialog(std::string const & name)
1992 d->gui_->showDialog(name);
1996 void BufferView::showDialogWithData(std::string const & name,
1997 std::string const & data)
2000 d->gui_->showDialogWithData(name, data);
2004 void BufferView::showInsetDialog(std::string const & name,
2005 std::string const & data, Inset * inset)
2008 d->gui_->showInsetDialog(name, data, inset);
2012 void BufferView::updateDialog(std::string const & name, std::string const & data)
2015 d->gui_->updateDialog(name, data);
2019 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2025 // FIXME: Move this out of BufferView again
2026 docstring BufferView::contentsOfPlaintextFile(string const & f,
2031 if (fname.empty()) {
2032 FileDialog dlg(_("Select file to insert"),
2034 ? LFUN_FILE_INSERT_PLAINTEXT_PARA
2035 : LFUN_FILE_INSERT_PLAINTEXT) );
2037 FileDialog::Result result =
2038 dlg.open(from_utf8(buffer().filePath()),
2039 FileFilterList(), docstring());
2041 if (result.first == FileDialog::Later)
2044 fname = makeAbsPath(to_utf8(result.second));
2050 if (!fname.isReadable()) {
2051 docstring const error = from_ascii(strerror(errno));
2052 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2053 docstring const text =
2054 bformat(_("Could not read the specified document\n"
2055 "%1$s\ndue to the error: %2$s"), file, error);
2056 Alert::error(_("Could not read file"), text);
2060 ifstream ifs(fname.toFilesystemEncoding().c_str());
2062 docstring const error = from_ascii(strerror(errno));
2063 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2064 docstring const text =
2065 bformat(_("Could not open the specified document\n"
2066 "%1$s\ndue to the error: %2$s"), file, error);
2067 Alert::error(_("Could not open file"), text);
2071 ifs.unsetf(std::ios::skipws);
2072 istream_iterator<char> ii(ifs);
2073 istream_iterator<char> end;
2074 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
2075 // We use this until the compilers get better...
2076 std::vector<char> tmp;
2077 copy(ii, end, back_inserter(tmp));
2078 string const tmpstr(tmp.begin(), tmp.end());
2080 // This is what we want to use and what we will use once the
2081 // compilers get good enough.
2082 //string tmpstr(ii, end); // yet a reason for using std::string
2083 // alternate approach to get the file into a string:
2085 copy(ii, end, back_inserter(tmpstr));
2088 // FIXME UNICODE: We don't know the encoding of the file
2089 docstring file_content = from_utf8(tmpstr);
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 = from_local8bit(tmpstr);
2100 return normalize_c(file_content);
2104 void BufferView::insertPlaintextFile(string const & f, bool asParagraph)
2106 docstring const tmpstr = contentsOfPlaintextFile(f, asParagraph);
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);