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/Delegates.h"
62 #include "frontends/FileDialog.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/FileFilterList.h"
72 #include "support/filetools.h"
73 #include "support/gettext.h"
74 #include "support/lstrings.h"
75 #include "support/Package.h"
76 #include "support/types.h"
87 using std::istringstream;
88 using std::istream_iterator;
92 using std::mem_fun_ref;
98 using support::addPath;
99 using support::bformat;
100 using support::FileFilterList;
101 using support::FileName;
102 using support::fileSearch;
103 using support::makeDisplayPath;
104 using support::makeAbsPath;
105 using support::package;
107 namespace Alert = frontend::Alert;
111 /// Return an inset of this class if it exists at the current cursor position
113 T * getInsetByCode(Cursor const & cur, InsetCode code)
115 DocIterator it = cur;
116 Inset * inset = it.nextInset();
117 if (inset && inset->lyxCode() == code)
118 return static_cast<T*>(inset);
123 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
126 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
127 docstring const & contents)
129 DocIterator tmpdit = dit;
132 Inset const * inset = tmpdit.nextInset();
134 && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()
135 && (contents.empty() ||
136 static_cast<InsetCommand const *>(inset)->getFirstNonOptParam() == contents)) {
140 tmpdit.forwardInset();
147 /// Looks for next inset with one of the given codes.
148 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
152 DocIterator tmpdit = dit;
153 tmpdit.forwardInset();
158 Inset const * inset = tmpdit.nextInset();
160 && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()) {
161 contents = static_cast<InsetCommand const *>(inset)->getFirstNonOptParam();
165 if (!findNextInset(tmpdit, codes, contents)) {
166 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
167 tmpdit = doc_iterator_begin(tmpdit.bottom().inset());
168 if (!findNextInset(tmpdit, codes, contents))
179 /// Looks for next inset with the given code
180 void findInset(DocIterator & dit, InsetCode code, bool same_content)
182 findInset(dit, vector<InsetCode>(1, code), same_content);
186 /// Moves cursor to the next inset with one of the given codes.
187 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
190 Cursor tmpcur = bv->cursor();
191 if (!findInset(tmpcur, codes, same_content)) {
192 bv->cursor().message(_("No more insets"));
196 tmpcur.clearSelection();
197 bv->setCursor(tmpcur);
201 /// Moves cursor to the next inset with given code.
202 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
204 gotoInset(bv, vector<InsetCode>(1, code), same_content);
208 /// A map from a Text to the associated text metrics
209 typedef std::map<Text const *, TextMetrics> TextMetricsCache;
211 enum ScreenUpdateStrategy {
221 /////////////////////////////////////////////////////////////////////
225 /////////////////////////////////////////////////////////////////////
227 struct BufferView::Private
229 Private(BufferView & bv): wh_(0), cursor_(bv),
230 anchor_ref_(0), offset_ref_(0), need_centering_(false),
231 last_inset_(0), gui_(0)
235 ScrollbarParameters scrollbarParameters_;
237 ScreenUpdateStrategy update_strategy_;
239 CoordCache coord_cache_;
241 /// Estimated average par height for scrollbar.
243 /// this is used to handle XSelection events in the right manner.
252 pit_type anchor_ref_;
256 bool need_centering_;
258 /// keyboard mapping object.
261 /// last visited inset.
262 /** kept to send setMouseHover(false).
263 * Not owned, so don't delete.
267 mutable TextMetricsCache text_metrics_;
270 /** Not owned, so don't delete.
272 frontend::GuiBufferViewDelegate * gui_;
276 BufferView::BufferView(Buffer & buf)
277 : width_(0), height_(0), buffer_(buf), d(new Private(*this))
279 d->xsel_cache_.set = false;
280 d->intl_.initKeyMapper(lyxrc.use_kbmap);
282 d->cursor_.push(buffer_.inset());
283 d->cursor_.resetAnchor();
284 d->cursor_.setCurrentFont();
286 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
287 graphics::Previews::get().generateBufferPreviews(buffer_);
291 BufferView::~BufferView()
293 // current buffer is going to be switched-off, save cursor pos
294 // Ideally, the whole cursor stack should be saved, but session
295 // currently can only handle bottom (whole document) level pit and pos.
296 // That is to say, if a cursor is in a nested inset, it will be
297 // restore to the left of the top level inset.
298 LastFilePosSection::FilePos fp;
299 fp.pit = d->cursor_.bottom().pit();
300 fp.pos = d->cursor_.bottom().pos();
301 LyX::ref().session().lastFilePos().save(buffer_.fileName(), fp);
307 Intl & BufferView::getIntl()
313 Intl const & BufferView::getIntl() const
319 CoordCache & BufferView::coordCache()
321 return d->coord_cache_;
325 CoordCache const & BufferView::coordCache() const
327 return d->coord_cache_;
331 Buffer & BufferView::buffer()
337 Buffer const & BufferView::buffer() const
343 bool BufferView::fitCursor()
345 if (cursorStatus(d->cursor_) == CUR_INSIDE) {
346 frontend::FontMetrics const & fm =
347 theFontMetrics(d->cursor_.getFont().fontInfo());
348 int const asc = fm.maxAscent();
349 int const des = fm.maxDescent();
350 Point const p = getPos(d->cursor_, d->cursor_.boundary());
351 if (p.y_ - asc >= 0 && p.y_ + des < height_)
359 void BufferView::processUpdateFlags(Update::flags flags)
361 // last_inset_ points to the last visited inset. This pointer may become
362 // invalid because of keyboard editing. Since all such operations
363 // causes screen update(), I reset last_inset_ to avoid such a problem.
365 // This is close to a hot-path.
366 LYXERR(Debug::DEBUG, "BufferView::processUpdateFlags()"
367 << "[fitcursor = " << (flags & Update::FitCursor)
368 << ", forceupdate = " << (flags & Update::Force)
369 << ", singlepar = " << (flags & Update::SinglePar)
370 << "] buffer: " << &buffer_);
372 // Update macro store
373 if (!(cursor().inMathed() && cursor().inMacroMode()))
374 buffer_.updateMacros();
376 // Now do the first drawing step if needed. This consists on updating
377 // the CoordCache in updateMetrics().
378 // The second drawing step is done in WorkArea::redraw() if needed.
380 // Case when no explicit update is requested.
382 // no need to redraw anything.
383 d->update_strategy_ = NoScreenUpdate;
387 if (flags == Update::Decoration) {
388 d->update_strategy_ = DecorationUpdate;
393 if (flags == Update::FitCursor
394 || flags == (Update::Decoration | Update::FitCursor)) {
395 bool const fit_cursor = fitCursor();
396 // tell the frontend to update the screen if needed.
402 if (flags & Update::Decoration) {
403 d->update_strategy_ = DecorationUpdate;
407 // no screen update is needed.
408 d->update_strategy_ = NoScreenUpdate;
412 bool const full_metrics = flags & Update::Force;
414 if (full_metrics || !singleParUpdate())
415 // We have to update the full screen metrics.
418 if (!(flags & Update::FitCursor)) {
423 //FIXME: updateMetrics() does not update paragraph position
424 // This is done at draw() time. So we need a redraw!
427 // The screen has already been updated thanks to the
428 // 'buffer_.changed()' call three line above. So no need
432 // The screen has been recentered around the cursor position so
439 void BufferView::updateScrollbar()
441 Text & t = buffer_.text();
442 TextMetrics & tm = d->text_metrics_[&t];
444 int const parsize = int(t.paragraphs().size() - 1);
445 if (d->anchor_ref_ > parsize) {
446 d->anchor_ref_ = parsize;
450 LYXERR(Debug::GUI, " Updating scrollbar: height: "
451 << t.paragraphs().size()
452 << " curr par: " << d->cursor_.bottom().pit()
453 << " default height " << defaultRowHeight());
455 // It would be better to fix the scrollbar to understand
456 // values in [0..1] and divide everything by wh
458 // estimated average paragraph height:
460 d->wh_ = height_ / 4;
462 int h = tm.parMetrics(d->anchor_ref_).height();
464 // Normalize anchor/offset (MV):
465 while (d->offset_ref_ > h && d->anchor_ref_ < parsize) {
468 h = tm.parMetrics(d->anchor_ref_).height();
470 // Look at paragraph heights on-screen
473 for (pit_type pit = d->anchor_ref_; pit <= parsize; ++pit) {
476 int const h2 = tm.parMetrics(pit).height();
482 int const hav = sumh / nh;
483 // More realistic average paragraph height
488 d->scrollbarParameters_.height = (parsize + 1) * d->wh_;
489 d->scrollbarParameters_.position = d->anchor_ref_ * d->wh_ + int(d->offset_ref_ * d->wh_ / float(h));
490 d->scrollbarParameters_.lineScrollHeight = int(d->wh_ * defaultRowHeight() / float(h));
494 ScrollbarParameters const & BufferView::scrollbarParameters() const
496 return d->scrollbarParameters_;
500 void BufferView::scrollDocView(int value)
502 LYXERR(Debug::GUI, "[ value = " << value << "]");
504 Text & t = buffer_.text();
505 TextMetrics & tm = d->text_metrics_[&t];
507 float const bar = value / float(d->wh_ * t.paragraphs().size());
509 d->anchor_ref_ = int(bar * t.paragraphs().size());
510 if (d->anchor_ref_ > int(t.paragraphs().size()) - 1)
511 d->anchor_ref_ = int(t.paragraphs().size()) - 1;
513 tm.redoParagraph(d->anchor_ref_);
514 int const h = tm.parMetrics(d->anchor_ref_).height();
515 d->offset_ref_ = int((bar * t.paragraphs().size() - d->anchor_ref_) * h);
521 void BufferView::setCursorFromScrollbar()
523 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
525 int const height = 2 * defaultRowHeight();
526 int const first = height;
527 int const last = height_ - height;
528 Cursor & cur = d->cursor_;
530 switch (cursorStatus(cur)) {
532 // We reset the cursor because cursorStatus() does not
533 // work when the cursor is within mathed.
534 cur.reset(buffer_.inset());
535 tm.setCursorFromCoordinates(cur, 0, first);
536 cur.clearSelection();
539 // We reset the cursor because cursorStatus() does not
540 // work when the cursor is within mathed.
541 cur.reset(buffer_.inset());
542 tm.setCursorFromCoordinates(cur, 0, last);
543 cur.clearSelection();
546 int const y = getPos(cur, cur.boundary()).y_;
547 int const newy = min(last, max(y, first));
549 cur.reset(buffer_.inset());
550 tm.setCursorFromCoordinates(cur, 0, newy);
556 Change const BufferView::getCurrentChange() const
558 if (!d->cursor_.selection())
559 return Change(Change::UNCHANGED);
561 DocIterator dit = d->cursor_.selectionBegin();
562 return dit.paragraph().lookupChange(dit.pos());
566 // this could be used elsewhere as well?
567 // FIXME: This does not work within mathed!
568 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
570 Point const p = getPos(dit, dit.boundary());
573 if (p.y_ > workHeight())
579 void BufferView::saveBookmark(unsigned int idx)
581 // tenatively save bookmark, id and pos will be used to
582 // acturately locate a bookmark in a 'live' lyx session.
583 // pit and pos will be updated with bottom level pit/pos
585 LyX::ref().session().bookmarks().save(
587 d->cursor_.bottom().pit(),
588 d->cursor_.bottom().pos(),
589 d->cursor_.paragraph().id(),
594 // emit message signal.
595 message(_("Save bookmark"));
599 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
600 int top_id, pos_type top_pos)
602 bool success = false;
605 d->cursor_.clearSelection();
607 // if a valid par_id is given, try it first
608 // This is the case for a 'live' bookmark when unique paragraph ID
609 // is used to track bookmarks.
611 ParIterator par = buffer_.getParFromID(top_id);
612 if (par != buffer_.par_iterator_end()) {
613 doc_it = makeDocIterator(par, min(par->size(), top_pos));
614 // Some slices of the iterator may not be
615 // reachable (e.g. closed collapsable inset)
616 // so the dociterator may need to be
617 // shortened. Otherwise, setCursor may crash
618 // lyx when the cursor can not be set to these
620 size_t const n = doc_it.depth();
621 for (size_t i = 0; i < n; ++i)
622 if (doc_it[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
630 // if top_id == 0, or searching through top_id failed
631 // This is the case for a 'restored' bookmark when only bottom
632 // (document level) pit was saved. Because of this, bookmark
633 // restoration is inaccurate. If a bookmark was within an inset,
634 // it will be restored to the left of the outmost inset that contains
636 if (static_cast<size_t>(bottom_pit) < buffer_.paragraphs().size()) {
637 doc_it = doc_iterator_begin(buffer_.inset());
638 doc_it.pit() = bottom_pit;
639 doc_it.pos() = min(bottom_pos, doc_it.paragraph().size());
644 // Note: only bottom (document) level pit is set.
646 // set the current font.
647 d->cursor_.setCurrentFont();
648 // To center the screen on this new position we need the
649 // paragraph position which is computed at draw() time.
650 // So we need a redraw!
653 // We need another redraw because of the screen recentering.
661 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
663 if (lyxrc.rtl_support) {
664 if (d->cursor_.real_current_font.isRightToLeft()) {
665 if (d->intl_.keymap == Intl::PRIMARY)
666 d->intl_.keyMapSec();
668 if (d->intl_.keymap == Intl::SECONDARY)
669 d->intl_.keyMapPrim();
673 d->intl_.getTransManager().translateAndInsert(c, t, cur);
677 int BufferView::workWidth() const
683 void BufferView::updateOffsetRef()
685 // No need to update d->offset_ref_ in this case.
686 if (!d->need_centering_)
689 // We are not properly started yet, delay until resizing is
694 CursorSlice & bot = d->cursor_.bottom();
695 TextMetrics & tm = d->text_metrics_[bot.text()];
696 ParagraphMetrics const & pm = tm.parMetrics(bot.pit());
697 int y = coordOffset(d->cursor_, d->cursor_.boundary()).y_;
698 d->offset_ref_ = y + pm.ascent() - height_ / 2;
700 d->need_centering_ = false;
704 void BufferView::center()
706 d->anchor_ref_ = d->cursor_.bottom().pit();
707 d->need_centering_ = true;
711 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
715 Cursor & cur = d->cursor_;
717 switch (cmd.action) {
720 flag.enabled(buffer_.undo().hasUndoStack());
723 flag.enabled(buffer_.undo().hasRedoStack());
725 case LFUN_FILE_INSERT:
726 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
727 case LFUN_FILE_INSERT_PLAINTEXT:
728 case LFUN_BOOKMARK_SAVE:
729 // FIXME: Actually, these LFUNS should be moved to Text
730 flag.enabled(cur.inTexted());
732 case LFUN_FONT_STATE:
733 case LFUN_LABEL_INSERT:
734 case LFUN_INFO_INSERT:
735 case LFUN_PARAGRAPH_GOTO:
737 case LFUN_REFERENCE_NEXT:
739 case LFUN_WORD_REPLACE:
742 case LFUN_MARK_TOGGLE:
743 case LFUN_SCREEN_RECENTER:
744 case LFUN_BIBTEX_DATABASE_ADD:
745 case LFUN_BIBTEX_DATABASE_DEL:
746 case LFUN_WORDS_COUNT:
747 case LFUN_NEXT_INSET_TOGGLE:
751 case LFUN_LABEL_GOTO: {
752 flag.enabled(!cmd.argument().empty()
753 || getInsetByCode<InsetRef>(cur, REF_CODE));
757 case LFUN_CHANGES_TRACK:
759 flag.setOnOff(buffer_.params().trackChanges);
762 case LFUN_CHANGES_OUTPUT:
764 flag.setOnOff(buffer_.params().outputChanges);
767 case LFUN_CHANGES_MERGE:
768 case LFUN_CHANGE_NEXT:
769 case LFUN_ALL_CHANGES_ACCEPT:
770 case LFUN_ALL_CHANGES_REJECT:
771 // TODO: context-sensitive enabling of LFUNs
772 // In principle, these command should only be enabled if there
773 // is a change in the document. However, without proper
774 // optimizations, this will inevitably result in poor performance.
778 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
779 flag.setOnOff(buffer_.params().compressed);
783 case LFUN_BUFFER_TOGGLE_EMBEDDING: {
784 flag.setOnOff(buffer_.params().embedded);
789 case LFUN_SCREEN_DOWN:
793 // FIXME: LFUN_SCREEN_DOWN_SELECT should be removed from
794 // everywhere else before this can enabled:
795 case LFUN_SCREEN_UP_SELECT:
796 case LFUN_SCREEN_DOWN_SELECT:
800 case LFUN_LAYOUT_TABULAR:
801 flag.enabled(cur.innerInsetOfType(TABULAR_CODE));
805 case LFUN_LAYOUT_PARAGRAPH:
806 flag.enabled(cur.inset().forceDefaultParagraphs(cur.idx()));
809 case LFUN_INSET_SETTINGS: {
810 InsetCode code = cur.inset().lyxCode();
814 enable = cmd.argument() == "tabular";
817 enable = cmd.argument() == "ert";
820 enable = cmd.argument() == "float";
823 enable = cmd.argument() == "wrap";
826 enable = cmd.argument() == "note";
829 enable = cmd.argument() == "branch";
832 enable = cmd.argument() == "box";
835 enable = cmd.argument() == "listings";
840 flag.enabled(enable);
844 case LFUN_DIALOG_SHOW_NEW_INSET:
845 flag.enabled(cur.inset().lyxCode() != ERT_CODE &&
846 cur.inset().lyxCode() != LISTINGS_CODE);
847 if (cur.inset().lyxCode() == CAPTION_CODE) {
849 if (cur.inset().getStatus(cur, cmd, flag))
862 Update::flags BufferView::dispatch(FuncRequest const & cmd)
864 //lyxerr << [ cmd = " << cmd << "]" << endl;
866 // Make sure that the cached BufferView is correct.
867 LYXERR(Debug::ACTION, " action[" << cmd.action << ']'
868 << " arg[" << to_utf8(cmd.argument()) << ']'
869 << " x[" << cmd.x << ']'
870 << " y[" << cmd.y << ']'
871 << " button[" << cmd.button() << ']');
873 Cursor & cur = d->cursor_;
874 // Default Update flags.
875 Update::flags updateFlags = Update::Force | Update::FitCursor;
877 switch (cmd.action) {
880 cur.message(_("Undo"));
881 cur.clearSelection();
882 if (!cur.textUndo()) {
883 cur.message(_("No further undo information"));
884 updateFlags = Update::None;
889 cur.message(_("Redo"));
890 cur.clearSelection();
891 if (!cur.textRedo()) {
892 cur.message(_("No further redo information"));
893 updateFlags = Update::None;
897 case LFUN_FILE_INSERT:
899 menuInsertLyXFile(to_utf8(cmd.argument()));
902 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
904 insertPlaintextFile(to_utf8(cmd.argument()), true);
907 case LFUN_FILE_INSERT_PLAINTEXT:
909 insertPlaintextFile(to_utf8(cmd.argument()), false);
912 case LFUN_FONT_STATE:
913 cur.message(cur.currentState());
916 case LFUN_BOOKMARK_SAVE:
917 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
920 case LFUN_LABEL_GOTO: {
921 docstring label = cmd.argument();
924 getInsetByCode<InsetRef>(d->cursor_,
927 label = inset->getParam("reference");
928 // persistent=false: use temp_bookmark
938 case LFUN_PARAGRAPH_GOTO: {
939 int const id = convert<int>(to_utf8(cmd.argument()));
941 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
942 b = theBufferList().next(b)) {
944 ParIterator par = b->getParFromID(id);
945 if (par == b->par_iterator_end()) {
946 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
948 LYXERR(Debug::INFO, "Paragraph " << par->id()
949 << " found in buffer `"
950 << b->absFileName() << "'.");
954 setCursor(makeDocIterator(par, 0));
956 // Switch to other buffer view and resend cmd
957 theLyXFunc().dispatch(FuncRequest(
958 LFUN_BUFFER_SWITCH, b->absFileName()));
959 theLyXFunc().dispatch(cmd);
960 updateFlags = Update::None;
970 gotoInset(this, NOTE_CODE, false);
973 case LFUN_REFERENCE_NEXT: {
974 vector<InsetCode> tmp;
975 tmp.push_back(LABEL_CODE);
976 tmp.push_back(REF_CODE);
977 gotoInset(this, tmp, true);
981 case LFUN_CHANGES_TRACK:
982 buffer_.params().trackChanges = !buffer_.params().trackChanges;
985 case LFUN_CHANGES_OUTPUT:
986 buffer_.params().outputChanges = !buffer_.params().outputChanges;
987 if (buffer_.params().outputChanges) {
988 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
989 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
990 LaTeXFeatures::isAvailable("xcolor");
992 if (!dvipost && !xcolorsoul) {
993 Alert::warning(_("Changes not shown in LaTeX output"),
994 _("Changes will not be highlighted in LaTeX output, "
995 "because neither dvipost nor xcolor/soul are installed.\n"
996 "Please install these packages or redefine "
997 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
998 } else if (!xcolorsoul) {
999 Alert::warning(_("Changes not shown in LaTeX output"),
1000 _("Changes will not be highlighted in LaTeX output "
1001 "when using pdflatex, because xcolor and soul are not installed.\n"
1002 "Please install both packages or redefine "
1003 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1008 case LFUN_CHANGE_NEXT:
1009 findNextChange(this);
1012 case LFUN_CHANGES_MERGE:
1013 if (findNextChange(this))
1014 showDialog("changes");
1017 case LFUN_ALL_CHANGES_ACCEPT:
1018 // select complete document
1019 d->cursor_.reset(buffer_.inset());
1020 d->cursor_.selHandle(true);
1021 buffer_.text().cursorBottom(d->cursor_);
1022 // accept everything in a single step to support atomic undo
1023 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::ACCEPT);
1026 case LFUN_ALL_CHANGES_REJECT:
1027 // select complete document
1028 d->cursor_.reset(buffer_.inset());
1029 d->cursor_.selHandle(true);
1030 buffer_.text().cursorBottom(d->cursor_);
1031 // reject everything in a single step to support atomic undo
1032 // Note: reject does not work recursively; the user may have to repeat the operation
1033 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::REJECT);
1036 case LFUN_WORD_FIND:
1040 case LFUN_WORD_REPLACE: {
1041 bool has_deleted = false;
1042 if (cur.selection()) {
1043 DocIterator beg = cur.selectionBegin();
1044 DocIterator end = cur.selectionEnd();
1045 if (beg.pit() == end.pit()) {
1046 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1047 if (cur.paragraph().isDeleted(p))
1052 replace(this, cmd, has_deleted);
1057 cur.clearSelection();
1059 cur.message(from_utf8(N_("Mark off")));
1063 cur.clearSelection();
1066 cur.message(from_utf8(N_("Mark on")));
1069 case LFUN_MARK_TOGGLE:
1070 cur.clearSelection();
1073 cur.message(from_utf8(N_("Mark removed")));
1076 cur.message(from_utf8(N_("Mark set")));
1081 case LFUN_SCREEN_RECENTER:
1085 case LFUN_BIBTEX_DATABASE_ADD: {
1086 Cursor tmpcur = d->cursor_;
1087 findInset(tmpcur, BIBTEX_CODE, false);
1088 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1091 if (inset->addDatabase(to_utf8(cmd.argument())))
1092 buffer_.updateBibfilesCache();
1097 case LFUN_BIBTEX_DATABASE_DEL: {
1098 Cursor tmpcur = d->cursor_;
1099 findInset(tmpcur, BIBTEX_CODE, false);
1100 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1103 if (inset->delDatabase(to_utf8(cmd.argument())))
1104 buffer_.updateBibfilesCache();
1109 case LFUN_WORDS_COUNT: {
1110 DocIterator from, to;
1111 if (cur.selection()) {
1112 from = cur.selectionBegin();
1113 to = cur.selectionEnd();
1115 from = doc_iterator_begin(buffer_.inset());
1116 to = doc_iterator_end(buffer_.inset());
1118 int const count = countWords(from, to);
1121 if (cur.selection())
1122 message = bformat(_("%1$d words in selection."),
1125 message = bformat(_("%1$d words in document."),
1129 if (cur.selection())
1130 message = _("One word in selection.");
1132 message = _("One word in document.");
1135 Alert::information(_("Count words"), message);
1139 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1140 // turn compression on/off
1141 buffer_.params().compressed = !buffer_.params().compressed;
1144 case LFUN_BUFFER_TOGGLE_EMBEDDING:
1145 // turn embedding on/off
1146 buffer_.embeddedFiles().enable(!buffer_.params().embedded);
1149 case LFUN_NEXT_INSET_TOGGLE: {
1150 // this is the real function we want to invoke
1151 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1152 // if there is an inset at cursor, see whether it
1154 Inset * inset = cur.nextInset();
1156 if (inset->isActive()) {
1157 Cursor tmpcur = cur;
1158 tmpcur.pushBackward(*inset);
1159 inset->dispatch(tmpcur, tmpcmd);
1160 if (tmpcur.result().dispatched()) {
1163 } else if (inset->editable() == Inset::IS_EDITABLE) {
1164 inset->edit(cur, true);
1167 // if it did not work, try the underlying inset.
1168 if (!cur.result().dispatched())
1169 cur.dispatch(tmpcmd);
1171 if (cur.result().dispatched())
1172 cur.clearSelection();
1177 case LFUN_SCREEN_UP:
1178 case LFUN_SCREEN_DOWN: {
1179 Point p = getPos(cur, cur.boundary());
1180 if (p.y_ < 0 || p.y_ > height_) {
1181 // The cursor is off-screen so recenter before proceeding.
1184 //FIXME: updateMetrics() does not update paragraph position
1185 // This is done at draw() time. So we need a redraw!
1186 // But no screen update is needed.
1187 d->update_strategy_ = NoScreenUpdate;
1189 p = getPos(cur, cur.boundary());
1191 scroll(cmd.action == LFUN_SCREEN_UP? - height_ : height_);
1192 cur.reset(buffer_.inset());
1193 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1194 //FIXME: what to do with cur.x_target()?
1196 // The metrics are already up to date. see scroll()
1197 updateFlags = Update::None;
1201 case LFUN_SCREEN_UP_SELECT:
1202 case LFUN_SCREEN_DOWN_SELECT: {
1203 cur.selHandle(true);
1204 size_t initial_depth = cur.depth();
1205 Point const p = getPos(cur, cur.boundary());
1206 scroll(cmd.action == LFUN_SCREEN_UP_SELECT? - height_ : height_);
1207 // FIXME: We need to verify if the cursor stayed within an inset...
1208 //cur.reset(buffer_.inset());
1209 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1211 while (cur.depth() > initial_depth) {
1214 // FIXME: we need to do a redraw again because of the selection
1215 // But no screen update is needed.
1216 d->update_strategy_ = NoScreenUpdate;
1218 updateFlags = Update::Force | Update::FitCursor;
1223 updateFlags = Update::None;
1230 docstring const BufferView::requestSelection()
1232 Cursor & cur = d->cursor_;
1234 if (!cur.selection()) {
1235 d->xsel_cache_.set = false;
1239 if (!d->xsel_cache_.set ||
1240 cur.top() != d->xsel_cache_.cursor ||
1241 cur.anchor_.top() != d->xsel_cache_.anchor)
1243 d->xsel_cache_.cursor = cur.top();
1244 d->xsel_cache_.anchor = cur.anchor_.top();
1245 d->xsel_cache_.set = cur.selection();
1246 return cur.selectionAsString(false);
1252 void BufferView::clearSelection()
1254 d->cursor_.clearSelection();
1255 // Clear the selection buffer. Otherwise a subsequent
1256 // middle-mouse-button paste would use the selection buffer,
1257 // not the more current external selection.
1258 cap::clearSelection();
1259 d->xsel_cache_.set = false;
1260 // The buffer did not really change, but this causes the
1261 // redraw we need because we cleared the selection above.
1266 void BufferView::resize(int width, int height)
1268 // Update from work area
1276 Inset const * BufferView::getCoveringInset(Text const & text, int x, int y)
1278 TextMetrics & tm = d->text_metrics_[&text];
1279 Inset * inset = tm.checkInsetHit(x, y);
1283 if (!inset->descendable())
1284 // No need to go further down if the inset is not
1288 size_t cell_number = inset->nargs();
1289 // Check all the inner cell.
1290 for (size_t i = 0; i != cell_number; ++i) {
1291 Text const * inner_text = inset->getText(i);
1294 Inset const * inset_deeper =
1295 getCoveringInset(*inner_text, x, y);
1297 return inset_deeper;
1305 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1307 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
1309 // This is only called for mouse related events including
1310 // LFUN_FILE_OPEN generated by drag-and-drop.
1311 FuncRequest cmd = cmd0;
1314 cur.push(buffer_.inset());
1315 cur.selection() = d->cursor_.selection();
1317 // Either the inset under the cursor or the
1318 // surrounding Text will handle this event.
1320 // make sure we stay within the screen...
1321 cmd.y = min(max(cmd.y, -1), height_);
1323 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1325 // Get inset under mouse, if there is one.
1326 Inset const * covering_inset =
1327 getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1328 if (covering_inset == d->last_inset_)
1329 // Same inset, no need to do anything...
1332 bool need_redraw = false;
1333 // const_cast because of setMouseHover().
1334 Inset * inset = const_cast<Inset *>(covering_inset);
1336 // Remove the hint on the last hovered inset (if any).
1337 need_redraw |= d->last_inset_->setMouseHover(false);
1339 // Highlighted the newly hovered inset (if any).
1340 need_redraw |= inset->setMouseHover(true);
1341 d->last_inset_ = inset;
1345 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
1346 << cmd.x << ", " << cmd.y << ")");
1348 d->update_strategy_ = DecorationUpdate;
1350 // This event (moving without mouse click) is not passed further.
1351 // This should be changed if it is further utilized.
1356 // Build temporary cursor.
1357 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1359 // Put anchor at the same position.
1362 // Try to dispatch to an non-editable inset near this position
1363 // via the temp cursor. If the inset wishes to change the real
1364 // cursor it has to do so explicitly by using
1365 // cur.bv().cursor() = cur; (or similar)
1367 inset->dispatch(cur, cmd);
1369 // Now dispatch to the temporary cursor. If the real cursor should
1370 // be modified, the inset's dispatch has to do so explicitly.
1371 if (!cur.result().dispatched())
1374 //Do we have a selection?
1375 theSelection().haveSelection(cursor().selection());
1377 // If the command has been dispatched,
1378 if (cur.result().dispatched()
1379 // an update is asked,
1380 && cur.result().update())
1381 processUpdateFlags(cur.result().update());
1385 void BufferView::scroll(int y)
1394 void BufferView::scrollDown(int offset)
1396 Text * text = &buffer_.text();
1397 TextMetrics & tm = d->text_metrics_[text];
1398 int ymax = height_ + offset;
1400 std::pair<pit_type, ParagraphMetrics const *> last = tm.last();
1401 int bottom_pos = last.second->position() + last.second->descent();
1402 if (last.first + 1 == int(text->paragraphs().size())) {
1403 if (bottom_pos <= height_)
1405 offset = min(offset, bottom_pos - height_);
1408 if (bottom_pos > ymax)
1410 tm.newParMetricsDown();
1412 d->offset_ref_ += offset;
1418 void BufferView::scrollUp(int offset)
1420 Text * text = &buffer_.text();
1421 TextMetrics & tm = d->text_metrics_[text];
1422 int ymin = - offset;
1424 std::pair<pit_type, ParagraphMetrics const *> first = tm.first();
1425 int top_pos = first.second->position() - first.second->ascent();
1426 if (first.first == 0) {
1429 offset = min(offset, - top_pos);
1434 tm.newParMetricsUp();
1436 d->offset_ref_ -= offset;
1442 void BufferView::setCursorFromRow(int row)
1447 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1449 d->cursor_.reset(buffer_.inset());
1451 buffer_.text().setCursor(d->cursor_, 0, 0);
1453 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1457 void BufferView::gotoLabel(docstring const & label)
1459 for (InsetIterator it = inset_iterator_begin(buffer_.inset()); it; ++it) {
1460 vector<docstring> labels;
1461 it->getLabelList(buffer_, labels);
1462 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1464 processUpdateFlags(Update::FitCursor);
1471 TextMetrics const & BufferView::textMetrics(Text const * t) const
1473 return const_cast<BufferView *>(this)->textMetrics(t);
1477 TextMetrics & BufferView::textMetrics(Text const * t)
1479 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
1480 if (tmc_it == d->text_metrics_.end()) {
1481 tmc_it = d->text_metrics_.insert(
1482 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1484 return tmc_it->second;
1488 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1491 return textMetrics(t).parMetrics(pit);
1495 int BufferView::workHeight() const
1501 void BufferView::setCursor(DocIterator const & dit)
1503 size_t const n = dit.depth();
1504 for (size_t i = 0; i < n; ++i)
1505 dit[i].inset().edit(d->cursor_, true);
1507 d->cursor_.setCursor(dit);
1508 d->cursor_.selection() = false;
1512 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1514 // Would be wrong to delete anything if we have a selection.
1515 if (cur.selection())
1518 bool need_anchor_change = false;
1519 bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1520 need_anchor_change);
1522 if (need_anchor_change)
1528 updateLabels(buffer_);
1536 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
1538 BOOST_ASSERT(&cur.bv() == this);
1541 // this event will clear selection so we save selection for
1542 // persistent selection
1543 cap::saveSelection(cursor());
1545 // Has the cursor just left the inset?
1546 bool badcursor = false;
1547 bool leftinset = (&d->cursor_.inset() != &cur.inset());
1549 badcursor = notifyCursorLeaves(d->cursor_, cur);
1551 // FIXME: shift-mouse selection doesn't work well across insets.
1552 bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
1554 // do the dEPM magic if needed
1555 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1556 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1557 // the leftinset bool would not be necessary (badcursor instead).
1558 bool update = leftinset;
1559 if (!do_selection && !badcursor && d->cursor_.inTexted())
1560 update |= checkDepm(cur, d->cursor_);
1562 // if the cursor was in an empty script inset and the new
1563 // position is in the nucleus of the inset, notifyCursorLeaves
1564 // will kill the script inset itself. So we check all the
1565 // elements of the cursor to make sure that they are correct.
1566 // For an example, see bug 2933:
1567 // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1568 // The code below could maybe be moved to a DocIterator method.
1569 //lyxerr << "cur before " << cur <<std::endl;
1570 DocIterator dit(cur.inset());
1571 dit.push_back(cur.bottom());
1573 while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1574 dit.push_back(cur[i]);
1577 //lyxerr << "5 cur after" << dit <<std::endl;
1579 d->cursor_.setCursor(dit);
1580 d->cursor_.boundary(cur.boundary());
1582 d->cursor_.setSelection();
1584 d->cursor_.clearSelection();
1586 d->cursor_.finishUndo();
1587 d->cursor_.setCurrentFont();
1592 void BufferView::putSelectionAt(DocIterator const & cur,
1593 int length, bool backwards)
1595 d->cursor_.clearSelection();
1601 d->cursor_.pos() += length;
1602 d->cursor_.setSelection(d->cursor_, -length);
1604 d->cursor_.setSelection(d->cursor_, length);
1609 Cursor & BufferView::cursor()
1615 Cursor const & BufferView::cursor() const
1621 pit_type BufferView::anchor_ref() const
1623 return d->anchor_ref_;
1627 bool BufferView::singleParUpdate()
1629 Text & buftext = buffer_.text();
1630 pit_type const bottom_pit = d->cursor_.bottom().pit();
1631 TextMetrics & tm = textMetrics(&buftext);
1632 int old_height = tm.parMetrics(bottom_pit).height();
1634 // In Single Paragraph mode, rebreak only
1635 // the (main text, not inset!) paragraph containing the cursor.
1636 // (if this paragraph contains insets etc., rebreaking will
1637 // recursively descend)
1638 tm.redoParagraph(bottom_pit);
1639 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
1640 if (pm.height() != old_height)
1641 // Paragraph height has changed so we cannot proceed to
1642 // the singlePar optimisation.
1645 d->update_strategy_ = SingleParUpdate;
1647 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
1648 << " y2: " << pm.position() + pm.descent()
1649 << " pit: " << bottom_pit
1650 << " singlepar: 1");
1655 void BufferView::updateMetrics()
1657 Text & buftext = buffer_.text();
1658 pit_type const npit = int(buftext.paragraphs().size());
1660 if (d->anchor_ref_ > int(npit - 1)) {
1661 d->anchor_ref_ = int(npit - 1);
1665 // Clear out the position cache in case of full screen redraw,
1666 d->coord_cache_.clear();
1668 // Clear out paragraph metrics to avoid having invalid metrics
1669 // in the cache from paragraphs not relayouted below
1670 // The complete text metrics will be redone.
1671 d->text_metrics_.clear();
1673 TextMetrics & tm = textMetrics(&buftext);
1675 pit_type const pit = d->anchor_ref_;
1679 // Rebreak anchor paragraph.
1680 tm.redoParagraph(pit);
1682 // Take care of anchor offset if case a recentering is needed.
1685 int y0 = tm.parMetrics(pit).ascent() - d->offset_ref_;
1687 // Redo paragraphs above anchor if necessary.
1689 while (y1 > 0 && pit1 > 0) {
1690 y1 -= tm.parMetrics(pit1).ascent();
1692 tm.redoParagraph(pit1);
1693 y1 -= tm.parMetrics(pit1).descent();
1696 // Take care of ascent of first line
1697 y1 -= tm.parMetrics(pit1).ascent();
1699 // Normalize anchor for next time
1700 d->anchor_ref_ = pit1;
1701 d->offset_ref_ = -y1;
1703 // Grey at the beginning is ugly
1704 if (pit1 == 0 && y1 > 0) {
1710 // Redo paragraphs below the anchor if necessary.
1712 while (y2 < height_ && pit2 < int(npit) - 1) {
1713 y2 += tm.parMetrics(pit2).descent();
1715 tm.redoParagraph(pit2);
1716 y2 += tm.parMetrics(pit2).ascent();
1719 // Take care of descent of last line
1720 y2 += tm.parMetrics(pit2).descent();
1722 LYXERR(Debug::PAINTING, "\n y1: " << y1
1724 << " pit1: " << pit1
1725 << " pit2: " << pit2
1726 << " npit: " << npit
1727 << " singlepar: 0");
1729 d->update_strategy_ = FullScreenUpdate;
1731 if (lyxerr.debugging(Debug::WORKAREA)) {
1732 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
1733 d->coord_cache_.dump();
1738 void BufferView::menuInsertLyXFile(string const & filenm)
1740 BOOST_ASSERT(d->cursor_.inTexted());
1741 string filename = filenm;
1743 if (filename.empty()) {
1744 // Launch a file browser
1746 string initpath = lyxrc.document_path;
1747 string const trypath = buffer_.filePath();
1748 // If directory is writeable, use this as default.
1749 if (FileName(trypath).isDirWritable())
1753 FileDialog dlg(_("Select LyX document to insert"), LFUN_FILE_INSERT);
1754 dlg.setButton1(_("Documents|#o#O"), from_utf8(lyxrc.document_path));
1755 dlg.setButton2(_("Examples|#E#e"),
1756 from_utf8(addPath(package().system_support().absFilename(),
1759 FileDialog::Result result =
1760 dlg.open(from_utf8(initpath),
1761 FileFilterList(_("LyX Documents (*.lyx)")),
1764 if (result.first == FileDialog::Later)
1768 filename = to_utf8(result.second);
1770 // check selected filename
1771 if (filename.empty()) {
1772 // emit message signal.
1773 message(_("Canceled."));
1778 // Get absolute path of file and add ".lyx"
1779 // to the filename if necessary
1780 filename = fileSearch(string(), filename, "lyx").absFilename();
1782 docstring const disp_fn = makeDisplayPath(filename);
1783 // emit message signal.
1784 message(bformat(_("Inserting document %1$s..."), disp_fn));
1787 Buffer buf("", false);
1788 if (buf.loadLyXFile(FileName(filename))) {
1789 ErrorList & el = buffer_.errorList("Parse");
1790 // Copy the inserted document error list into the current buffer one.
1791 el = buf.errorList("Parse");
1792 buffer_.undo().recordUndo(d->cursor_);
1793 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
1794 buf.params().getTextClassPtr(), el);
1795 res = _("Document %1$s inserted.");
1797 res = _("Could not insert document %1$s");
1800 // emit message signal.
1801 message(bformat(res, disp_fn));
1802 buffer_.errors("Parse");
1807 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
1813 // Addup contribution of nested insets, from inside to outside,
1814 // keeping the outer paragraph for a special handling below
1815 for (size_t i = dit.depth() - 1; i >= 1; --i) {
1816 CursorSlice const & sl = dit[i];
1820 // get relative position inside sl.inset()
1821 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
1823 // Make relative position inside of the edited inset relative to sl.inset()
1827 // In case of an RTL inset, the edited inset will be positioned to the left
1830 bool boundary_i = boundary && i + 1 == dit.depth();
1831 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
1836 // remember width for the case that sl.inset() is positioned in an RTL inset
1837 if (i && dit[i - 1].text()) {
1838 // If this Inset is inside a Text Inset, retrieve the Dimension
1839 // from the containing text instead of using Inset::dimension() which
1840 // might not be implemented.
1841 // FIXME (Abdel 23/09/2007): this is a bit messy because of the
1842 // elimination of Inset::dim_ cache. This coordOffset() method needs
1843 // to be rewritten in light of the new design.
1844 Dimension const & dim = parMetrics(dit[i - 1].text(),
1845 dit[i - 1].pit()).insetDimension(&sl.inset());
1848 Dimension const dim = sl.inset().dimension(*this);
1852 //lyxerr << "Cursor::getPos, i: "
1853 // << i << " x: " << xx << " y: " << y << endl;
1856 // Add contribution of initial rows of outermost paragraph
1857 CursorSlice const & sl = dit[0];
1858 TextMetrics const & tm = textMetrics(sl.text());
1859 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
1860 BOOST_ASSERT(!pm.rows().empty());
1861 y -= pm.rows()[0].ascent();
1863 // FIXME: document this mess
1865 if (sl.pos() > 0 && dit.depth() == 1) {
1867 if (pos && boundary)
1869 // lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << std::endl;
1870 rend = pm.pos2row(pos);
1872 rend = pm.pos2row(sl.pos());
1874 size_t rend = pm.pos2row(sl.pos());
1876 for (size_t rit = 0; rit != rend; ++rit)
1877 y += pm.rows()[rit].height();
1878 y += pm.rows()[rend].ascent();
1880 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
1882 // Make relative position from the nested inset now bufferview absolute.
1883 int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
1886 // In the RTL case place the nested inset at the left of the cursor in
1887 // the outer paragraph
1888 bool boundary_1 = boundary && 1 == dit.depth();
1889 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
1897 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
1899 CursorSlice const & bot = dit.bottom();
1900 TextMetrics const & tm = textMetrics(bot.text());
1901 if (!tm.has(bot.pit()))
1902 return Point(-1, -1);
1904 Point p = coordOffset(dit, boundary); // offset from outer paragraph
1905 p.y_ += tm.parMetrics(bot.pit()).position();
1910 void BufferView::draw(frontend::Painter & pain)
1912 LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
1913 Text & text = buffer_.text();
1914 TextMetrics const & tm = d->text_metrics_[&text];
1915 int const y = - d->offset_ref_ + tm.parMetrics(d->anchor_ref_).ascent();
1916 PainterInfo pi(this, pain);
1918 switch (d->update_strategy_) {
1920 case NoScreenUpdate:
1921 // If no screen painting is actually needed, only some the different
1922 // coordinates of insets and paragraphs needs to be updated.
1923 pi.full_repaint = true;
1924 pi.pain.setDrawingEnabled(false);
1928 case SingleParUpdate:
1929 pi.full_repaint = false;
1930 // In general, only the current row of the outermost paragraph
1931 // will be redrawn. Particular cases where selection spans
1932 // multiple paragraph are correctly detected in TextMetrics.
1936 case DecorationUpdate:
1937 // FIXME: We should also distinguish DecorationUpdate to avoid text
1938 // drawing if possible. This is not possible to do easily right now
1939 // because of the single backing pixmap.
1941 case FullScreenUpdate:
1942 // The whole screen, including insets, will be refreshed.
1943 pi.full_repaint = true;
1945 // Clear background.
1946 pain.fillRectangle(0, 0, width_, height_,
1947 buffer_.inset().backgroundColor());
1950 // and possibly grey out below
1951 std::pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
1952 int const y2 = lastpm.second->position() + lastpm.second->descent();
1954 pain.fillRectangle(0, y2, width_, height_ - y2, Color_bottomarea);
1958 LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING ***");
1962 void BufferView::message(docstring const & msg)
1965 d->gui_->message(msg);
1969 void BufferView::showDialog(std::string const & name)
1972 d->gui_->showDialog(name, string());
1976 void BufferView::showDialog(std::string const & name,
1977 std::string const & data, Inset * inset)
1980 d->gui_->showDialog(name, data, inset);
1984 void BufferView::updateDialog(std::string const & name, std::string const & data)
1987 d->gui_->updateDialog(name, data);
1991 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
1997 // FIXME: Move this out of BufferView again
1998 docstring BufferView::contentsOfPlaintextFile(string const & f,
2003 if (fname.empty()) {
2004 FileDialog dlg(_("Select file to insert"),
2006 ? LFUN_FILE_INSERT_PLAINTEXT_PARA
2007 : LFUN_FILE_INSERT_PLAINTEXT) );
2009 FileDialog::Result result =
2010 dlg.open(from_utf8(buffer().filePath()),
2011 FileFilterList(), docstring());
2013 if (result.first == FileDialog::Later)
2016 if (result.second.empty())
2019 fname = makeAbsPath(to_utf8(result.second));
2022 if (!fname.isReadableFile()) {
2023 docstring const error = from_ascii(strerror(errno));
2024 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2025 docstring const text =
2026 bformat(_("Could not read the specified document\n"
2027 "%1$s\ndue to the error: %2$s"), file, error);
2028 Alert::error(_("Could not read file"), text);
2032 ifstream ifs(fname.toFilesystemEncoding().c_str());
2034 docstring const error = from_ascii(strerror(errno));
2035 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2036 docstring const text =
2037 bformat(_("Could not open the specified document\n"
2038 "%1$s\ndue to the error: %2$s"), file, error);
2039 Alert::error(_("Could not open file"), text);
2043 ifs.unsetf(std::ios::skipws);
2044 istream_iterator<char> ii(ifs);
2045 istream_iterator<char> end;
2046 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
2047 // We use this until the compilers get better...
2048 std::vector<char> tmp;
2049 copy(ii, end, back_inserter(tmp));
2050 string const tmpstr(tmp.begin(), tmp.end());
2052 // This is what we want to use and what we will use once the
2053 // compilers get good enough.
2054 //string tmpstr(ii, end); // yet a reason for using std::string
2055 // alternate approach to get the file into a string:
2057 copy(ii, end, back_inserter(tmpstr));
2060 // FIXME UNICODE: We don't know the encoding of the file
2061 docstring file_content = from_utf8(tmpstr);
2062 if (file_content.empty()) {
2063 Alert::error(_("Reading not UTF-8 encoded file"),
2064 _("The file is not UTF-8 encoded.\n"
2065 "It will be read as local 8Bit-encoded.\n"
2066 "If this does not give the correct result\n"
2067 "then please change the encoding of the file\n"
2068 "to UTF-8 with a program other than LyX.\n"));
2069 file_content = from_local8bit(tmpstr);
2072 return normalize_c(file_content);
2076 void BufferView::insertPlaintextFile(string const & f, bool asParagraph)
2078 docstring const tmpstr = contentsOfPlaintextFile(f, asParagraph);
2083 Cursor & cur = cursor();
2084 cap::replaceSelection(cur);
2085 buffer_.undo().recordUndo(cur);
2087 cur.innerText()->insertStringAsParagraphs(cur, tmpstr);
2089 cur.innerText()->insertStringAsLines(cur, tmpstr);