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"
58 #include "insets/InsetBibtex.h"
59 #include "insets/InsetCommand.h" // ChangeRefs
60 #include "insets/InsetRef.h"
61 #include "insets/InsetText.h"
63 #include "frontends/alert.h"
64 #include "frontends/Delegates.h"
65 #include "frontends/FileDialog.h"
66 #include "frontends/FontMetrics.h"
67 #include "frontends/Painter.h"
68 #include "frontends/Selection.h"
70 #include "graphics/Previews.h"
72 #include "support/convert.h"
73 #include "support/FileFilterList.h"
74 #include "support/filetools.h"
75 #include "support/Package.h"
76 #include "support/types.h"
77 #include "support/fs_extras.h"
79 #include <boost/bind.hpp>
80 #include <boost/current_function.hpp>
81 #include <boost/filesystem/operations.hpp>
91 using std::istringstream;
92 using std::istream_iterator;
96 using std::mem_fun_ref;
100 namespace fs = boost::filesystem;
104 using support::addPath;
105 using support::bformat;
106 using support::FileFilterList;
107 using support::FileName;
108 using support::fileSearch;
109 using support::makeDisplayPath;
110 using support::makeAbsPath;
111 using support::package;
113 namespace Alert = frontend::Alert;
117 /// Return an inset of this class if it exists at the current cursor position
119 T * getInsetByCode(Cursor const & cur, InsetCode code)
121 DocIterator it = cur;
122 Inset * inset = it.nextInset();
123 if (inset && inset->lyxCode() == code)
124 return static_cast<T*>(inset);
129 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
132 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
133 docstring const & contents)
135 DocIterator tmpdit = dit;
138 Inset const * inset = tmpdit.nextInset();
140 && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()
141 && (contents.empty() ||
142 static_cast<InsetCommand const *>(inset)->getFirstNonOptParam() == contents)) {
146 tmpdit.forwardInset();
153 /// Looks for next inset with one of the given codes.
154 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
158 DocIterator tmpdit = dit;
159 tmpdit.forwardInset();
164 Inset const * inset = tmpdit.nextInset();
166 && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()) {
167 contents = static_cast<InsetCommand const *>(inset)->getFirstNonOptParam();
171 if (!findNextInset(tmpdit, codes, contents)) {
172 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
173 tmpdit = doc_iterator_begin(tmpdit.bottom().inset());
174 if (!findNextInset(tmpdit, codes, contents))
185 /// Looks for next inset with the given code
186 void findInset(DocIterator & dit, InsetCode code, bool same_content)
188 findInset(dit, vector<InsetCode>(1, code), same_content);
192 /// Moves cursor to the next inset with one of the given codes.
193 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
196 Cursor tmpcur = bv->cursor();
197 if (!findInset(tmpcur, codes, same_content)) {
198 bv->cursor().message(_("No more insets"));
202 tmpcur.clearSelection();
203 bv->setCursor(tmpcur);
207 /// Moves cursor to the next inset with given code.
208 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
210 gotoInset(bv, vector<InsetCode>(1, code), same_content);
214 /// A map from a Text to the associated text metrics
215 typedef std::map<Text const *, TextMetrics> TextMetricsCache;
220 /////////////////////////////////////////////////////////////////////
224 /////////////////////////////////////////////////////////////////////
226 struct BufferView::Private
228 Private(BufferView & bv): wh_(0), cursor_(bv),
229 anchor_ref_(0), offset_ref_(0), need_centering_(false),
230 last_inset_(0), gui_(0)
234 ScrollbarParameters scrollbarParameters_;
236 ViewMetricsInfo metrics_info_;
238 CoordCache coord_cache_;
240 /// Estimated average par height for scrollbar.
242 /// this is used to handle XSelection events in the right manner.
251 pit_type anchor_ref_;
255 bool need_centering_;
257 /// keyboard mapping object.
260 /// last visited inset.
261 /** kept to send setMouseHover(false).
262 * Not owned, so don't delete.
266 mutable TextMetricsCache text_metrics_;
269 /** Not owned, so don't delete.
271 frontend::GuiBufferViewDelegate * gui_;
275 BufferView::BufferView(Buffer & buf)
276 : width_(0), height_(0), buffer_(buf), d(new Private(*this))
278 d->xsel_cache_.set = false;
279 d->intl_.initKeyMapper(lyxrc.use_kbmap);
281 d->cursor_.push(buffer_.inset());
282 d->cursor_.resetAnchor();
283 d->cursor_.setCurrentFont();
285 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
286 graphics::Previews::get().generateBufferPreviews(buffer_);
290 BufferView::~BufferView()
292 // current buffer is going to be switched-off, save cursor pos
293 // Ideally, the whole cursor stack should be saved, but session
294 // currently can only handle bottom (whole document) level pit and pos.
295 // That is to say, if a cursor is in a nested inset, it will be
296 // restore to the left of the top level inset.
297 LastFilePosSection::FilePos fp;
298 fp.pit = d->cursor_.bottom().pit();
299 fp.pos = d->cursor_.bottom().pos();
300 LyX::ref().session().lastFilePos().save(buffer_.fileName(), fp);
306 Intl & BufferView::getIntl()
312 Intl const & BufferView::getIntl() const
318 CoordCache & BufferView::coordCache()
320 return d->coord_cache_;
324 CoordCache const & BufferView::coordCache() const
326 return d->coord_cache_;
330 Buffer & BufferView::buffer()
336 Buffer const & BufferView::buffer() const
342 bool BufferView::fitCursor()
344 if (cursorStatus(d->cursor_) == CUR_INSIDE) {
345 frontend::FontMetrics const & fm =
346 theFontMetrics(d->cursor_.getFont().fontInfo());
347 int const asc = fm.maxAscent();
348 int const des = fm.maxDescent();
349 Point const p = getPos(d->cursor_, d->cursor_.boundary());
350 if (p.y_ - asc >= 0 && p.y_ + des < height_)
358 void BufferView::processUpdateFlags(Update::flags flags)
360 // last_inset_ points to the last visited inset. This pointer may become
361 // invalid because of keyboard editing. Since all such operations
362 // causes screen update(), I reset last_inset_ to avoid such a problem.
364 // This is close to a hot-path.
366 << BOOST_CURRENT_FUNCTION
367 << "[fitcursor = " << (flags & Update::FitCursor)
368 << ", forceupdate = " << (flags & Update::Force)
369 << ", singlepar = " << (flags & Update::SinglePar)
370 << "] buffer: " << &buffer_ << endl;
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->metrics_info_.update_strategy = NoScreenUpdate;
387 if (flags == Update::Decoration) {
388 d->metrics_info_.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->metrics_info_.update_strategy = DecorationUpdate;
407 // no screen update is needed.
408 d->metrics_info_.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;
451 << BOOST_CURRENT_FUNCTION
452 << " Updating scrollbar: height: " << t.paragraphs().size()
453 << " curr par: " << d->cursor_.bottom().pit()
454 << " default height " << defaultRowHeight() << endl;
456 // It would be better to fix the scrollbar to understand
457 // values in [0..1] and divide everything by wh
459 // estimated average paragraph height:
461 d->wh_ = height_ / 4;
463 int h = tm.parMetrics(d->anchor_ref_).height();
465 // Normalize anchor/offset (MV):
466 while (d->offset_ref_ > h && d->anchor_ref_ < parsize) {
469 h = tm.parMetrics(d->anchor_ref_).height();
471 // Look at paragraph heights on-screen
474 for (pit_type pit = d->anchor_ref_; pit <= parsize; ++pit) {
477 int const h2 = tm.parMetrics(pit).height();
483 int const hav = sumh / nh;
484 // More realistic average paragraph height
489 d->scrollbarParameters_.height = (parsize + 1) * d->wh_;
490 d->scrollbarParameters_.position = d->anchor_ref_ * d->wh_ + int(d->offset_ref_ * d->wh_ / float(h));
491 d->scrollbarParameters_.lineScrollHeight = int(d->wh_ * defaultRowHeight() / float(h));
495 ScrollbarParameters const & BufferView::scrollbarParameters() const
497 return d->scrollbarParameters_;
501 void BufferView::scrollDocView(int value)
503 LYXERR(Debug::GUI) << BOOST_CURRENT_FUNCTION
504 << "[ value = " << value << "]" << endl;
506 Text & t = buffer_.text();
507 TextMetrics & tm = d->text_metrics_[&t];
509 float const bar = value / float(d->wh_ * t.paragraphs().size());
511 d->anchor_ref_ = int(bar * t.paragraphs().size());
512 if (d->anchor_ref_ > int(t.paragraphs().size()) - 1)
513 d->anchor_ref_ = int(t.paragraphs().size()) - 1;
515 tm.redoParagraph(d->anchor_ref_);
516 int const h = tm.parMetrics(d->anchor_ref_).height();
517 d->offset_ref_ = int((bar * t.paragraphs().size() - d->anchor_ref_) * h);
523 void BufferView::setCursorFromScrollbar()
525 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
527 int const height = 2 * defaultRowHeight();
528 int const first = height;
529 int const last = height_ - height;
530 Cursor & cur = d->cursor_;
532 switch (cursorStatus(cur)) {
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, first);
538 cur.clearSelection();
541 // We reset the cursor because cursorStatus() does not
542 // work when the cursor is within mathed.
543 cur.reset(buffer_.inset());
544 tm.setCursorFromCoordinates(cur, 0, last);
545 cur.clearSelection();
548 int const y = getPos(cur, cur.boundary()).y_;
549 int const newy = min(last, max(y, first));
551 cur.reset(buffer_.inset());
552 tm.setCursorFromCoordinates(cur, 0, newy);
558 Change const BufferView::getCurrentChange() const
560 if (!d->cursor_.selection())
561 return Change(Change::UNCHANGED);
563 DocIterator dit = d->cursor_.selectionBegin();
564 return dit.paragraph().lookupChange(dit.pos());
568 // this could be used elsewhere as well?
569 // FIXME: This does not work within mathed!
570 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
572 Point const p = getPos(dit, dit.boundary());
575 if (p.y_ > workHeight())
581 void BufferView::saveBookmark(unsigned int idx)
583 // tenatively save bookmark, id and pos will be used to
584 // acturately locate a bookmark in a 'live' lyx session.
585 // pit and pos will be updated with bottom level pit/pos
587 LyX::ref().session().bookmarks().save(
589 d->cursor_.bottom().pit(),
590 d->cursor_.bottom().pos(),
591 d->cursor_.paragraph().id(),
596 // emit message signal.
597 message(_("Save bookmark"));
601 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
602 int top_id, pos_type top_pos)
604 bool success = false;
607 d->cursor_.clearSelection();
609 // if a valid par_id is given, try it first
610 // This is the case for a 'live' bookmark when unique paragraph ID
611 // is used to track bookmarks.
613 ParIterator par = buffer_.getParFromID(top_id);
614 if (par != buffer_.par_iterator_end()) {
615 doc_it = makeDocIterator(par, min(par->size(), top_pos));
616 // Some slices of the iterator may not be
617 // reachable (e.g. closed collapsable inset)
618 // so the dociterator may need to be
619 // shortened. Otherwise, setCursor may crash
620 // lyx when the cursor can not be set to these
622 size_t const n = doc_it.depth();
623 for (size_t i = 0; i < n; ++i)
624 if (doc_it[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
632 // if top_id == 0, or searching through top_id failed
633 // This is the case for a 'restored' bookmark when only bottom
634 // (document level) pit was saved. Because of this, bookmark
635 // restoration is inaccurate. If a bookmark was within an inset,
636 // it will be restored to the left of the outmost inset that contains
638 if (static_cast<size_t>(bottom_pit) < buffer_.paragraphs().size()) {
639 doc_it = doc_iterator_begin(buffer_.inset());
640 doc_it.pit() = bottom_pit;
641 doc_it.pos() = min(bottom_pos, doc_it.paragraph().size());
646 // Note: only bottom (document) level pit is set.
648 // set the current font.
649 d->cursor_.setCurrentFont();
650 // center the screen on this new position.
658 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
660 if (lyxrc.rtl_support) {
661 if (d->cursor_.real_current_font.isRightToLeft()) {
662 if (d->intl_.keymap == Intl::PRIMARY)
663 d->intl_.keyMapSec();
665 if (d->intl_.keymap == Intl::SECONDARY)
666 d->intl_.keyMapPrim();
670 d->intl_.getTransManager().translateAndInsert(c, t, cur);
674 int BufferView::workWidth() const
680 void BufferView::updateOffsetRef()
682 // No need to update d->offset_ref_ in this case.
683 if (!d->need_centering_)
686 // We are not properly started yet, delay until resizing is
691 CursorSlice & bot = d->cursor_.bottom();
692 TextMetrics & tm = d->text_metrics_[bot.text()];
693 ParagraphMetrics const & pm = tm.parMetrics(bot.pit());
694 int y = coordOffset(d->cursor_, d->cursor_.boundary()).y_;
695 d->offset_ref_ = y + pm.ascent() - height_ / 2;
697 d->need_centering_ = false;
701 void BufferView::center()
703 d->anchor_ref_ = d->cursor_.bottom().pit();
704 d->need_centering_ = true;
708 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
712 Cursor & cur = d->cursor_;
714 switch (cmd.action) {
717 flag.enabled(buffer_.undo().hasUndoStack());
720 flag.enabled(buffer_.undo().hasRedoStack());
722 case LFUN_FILE_INSERT:
723 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
724 case LFUN_FILE_INSERT_PLAINTEXT:
725 case LFUN_BOOKMARK_SAVE:
726 // FIXME: Actually, these LFUNS should be moved to Text
727 flag.enabled(cur.inTexted());
729 case LFUN_FONT_STATE:
730 case LFUN_LABEL_INSERT:
731 case LFUN_INFO_INSERT:
732 case LFUN_PARAGRAPH_GOTO:
734 case LFUN_REFERENCE_NEXT:
736 case LFUN_WORD_REPLACE:
739 case LFUN_MARK_TOGGLE:
740 case LFUN_SCREEN_RECENTER:
741 case LFUN_BIBTEX_DATABASE_ADD:
742 case LFUN_BIBTEX_DATABASE_DEL:
743 case LFUN_WORDS_COUNT:
744 case LFUN_NEXT_INSET_TOGGLE:
748 case LFUN_LABEL_GOTO: {
749 flag.enabled(!cmd.argument().empty()
750 || getInsetByCode<InsetRef>(cur, REF_CODE));
754 case LFUN_CHANGES_TRACK:
756 flag.setOnOff(buffer_.params().trackChanges);
759 case LFUN_CHANGES_OUTPUT:
761 flag.setOnOff(buffer_.params().outputChanges);
764 case LFUN_CHANGES_MERGE:
765 case LFUN_CHANGE_NEXT:
766 case LFUN_ALL_CHANGES_ACCEPT:
767 case LFUN_ALL_CHANGES_REJECT:
768 // TODO: context-sensitive enabling of LFUNs
769 // In principle, these command should only be enabled if there
770 // is a change in the document. However, without proper
771 // optimizations, this will inevitably result in poor performance.
775 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
776 flag.setOnOff(buffer_.params().compressed);
780 case LFUN_BUFFER_TOGGLE_EMBEDDING: {
781 flag.setOnOff(buffer_.params().embedded);
786 case LFUN_SCREEN_DOWN:
790 // FIXME: LFUN_SCREEN_DOWN_SELECT should be removed from
791 // everywhere else before this can enabled:
792 case LFUN_SCREEN_UP_SELECT:
793 case LFUN_SCREEN_DOWN_SELECT:
797 case LFUN_LAYOUT_TABULAR:
798 flag.enabled(cur.innerInsetOfType(TABULAR_CODE));
802 case LFUN_LAYOUT_PARAGRAPH:
803 flag.enabled(cur.inset().forceDefaultParagraphs(cur.idx()));
806 case LFUN_INSET_SETTINGS: {
807 InsetCode code = cur.inset().lyxCode();
811 enable = cmd.argument() == "tabular";
814 enable = cmd.argument() == "ert";
817 enable = cmd.argument() == "float";
820 enable = cmd.argument() == "wrap";
823 enable = cmd.argument() == "note";
826 enable = cmd.argument() == "branch";
829 enable = cmd.argument() == "box";
832 enable = cmd.argument() == "listings";
837 flag.enabled(enable);
841 case LFUN_DIALOG_SHOW_NEW_INSET:
842 flag.enabled(cur.inset().lyxCode() != ERT_CODE &&
843 cur.inset().lyxCode() != LISTINGS_CODE);
844 if (cur.inset().lyxCode() == CAPTION_CODE) {
846 if (cur.inset().getStatus(cur, cmd, flag))
859 Update::flags BufferView::dispatch(FuncRequest const & cmd)
861 //lyxerr << BOOST_CURRENT_FUNCTION
862 // << [ cmd = " << cmd << "]" << endl;
864 // Make sure that the cached BufferView is correct.
865 LYXERR(Debug::ACTION) << BOOST_CURRENT_FUNCTION
866 << " action[" << cmd.action << ']'
867 << " arg[" << to_utf8(cmd.argument()) << ']'
868 << " x[" << cmd.x << ']'
869 << " y[" << cmd.y << ']'
870 << " 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()) {
947 << "No matching paragraph found! ["
948 << id << "]." << endl;
951 << "Paragraph " << par->id()
952 << " found in buffer `"
953 << b->absFileName() << "'." << endl;
957 setCursor(makeDocIterator(par, 0));
959 // Switch to other buffer view and resend cmd
960 theLyXFunc().dispatch(FuncRequest(
961 LFUN_BUFFER_SWITCH, b->absFileName()));
962 theLyXFunc().dispatch(cmd);
963 updateFlags = Update::None;
973 gotoInset(this, NOTE_CODE, false);
976 case LFUN_REFERENCE_NEXT: {
977 vector<InsetCode> tmp;
978 tmp.push_back(LABEL_CODE);
979 tmp.push_back(REF_CODE);
980 gotoInset(this, tmp, true);
984 case LFUN_CHANGES_TRACK:
985 buffer_.params().trackChanges = !buffer_.params().trackChanges;
988 case LFUN_CHANGES_OUTPUT:
989 buffer_.params().outputChanges = !buffer_.params().outputChanges;
990 if (buffer_.params().outputChanges) {
991 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
992 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
993 LaTeXFeatures::isAvailable("xcolor");
995 if (!dvipost && !xcolorsoul) {
996 Alert::warning(_("Changes not shown in LaTeX output"),
997 _("Changes will not be highlighted in LaTeX output, "
998 "because neither dvipost nor xcolor/soul are installed.\n"
999 "Please install these packages or redefine "
1000 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1001 } else if (!xcolorsoul) {
1002 Alert::warning(_("Changes not shown in LaTeX output"),
1003 _("Changes will not be highlighted in LaTeX output "
1004 "when using pdflatex, because xcolor and soul are not installed.\n"
1005 "Please install both packages or redefine "
1006 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1011 case LFUN_CHANGE_NEXT:
1012 findNextChange(this);
1015 case LFUN_CHANGES_MERGE:
1016 if (findNextChange(this))
1017 showDialog("changes");
1020 case LFUN_ALL_CHANGES_ACCEPT:
1021 // select complete document
1022 d->cursor_.reset(buffer_.inset());
1023 d->cursor_.selHandle(true);
1024 buffer_.text().cursorBottom(d->cursor_);
1025 // accept everything in a single step to support atomic undo
1026 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::ACCEPT);
1029 case LFUN_ALL_CHANGES_REJECT:
1030 // select complete document
1031 d->cursor_.reset(buffer_.inset());
1032 d->cursor_.selHandle(true);
1033 buffer_.text().cursorBottom(d->cursor_);
1034 // reject everything in a single step to support atomic undo
1035 // Note: reject does not work recursively; the user may have to repeat the operation
1036 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::REJECT);
1039 case LFUN_WORD_FIND:
1043 case LFUN_WORD_REPLACE: {
1044 bool has_deleted = false;
1045 if (cur.selection()) {
1046 DocIterator beg = cur.selectionBegin();
1047 DocIterator end = cur.selectionEnd();
1048 if (beg.pit() == end.pit()) {
1049 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1050 if (cur.paragraph().isDeleted(p))
1055 replace(this, cmd, has_deleted);
1060 cur.clearSelection();
1062 cur.message(from_utf8(N_("Mark off")));
1066 cur.clearSelection();
1069 cur.message(from_utf8(N_("Mark on")));
1072 case LFUN_MARK_TOGGLE:
1073 cur.clearSelection();
1076 cur.message(from_utf8(N_("Mark removed")));
1079 cur.message(from_utf8(N_("Mark set")));
1084 case LFUN_SCREEN_RECENTER:
1088 case LFUN_BIBTEX_DATABASE_ADD: {
1089 Cursor tmpcur = d->cursor_;
1090 findInset(tmpcur, BIBTEX_CODE, false);
1091 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1094 if (inset->addDatabase(to_utf8(cmd.argument())))
1095 buffer_.updateBibfilesCache();
1100 case LFUN_BIBTEX_DATABASE_DEL: {
1101 Cursor tmpcur = d->cursor_;
1102 findInset(tmpcur, BIBTEX_CODE, false);
1103 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1106 if (inset->delDatabase(to_utf8(cmd.argument())))
1107 buffer_.updateBibfilesCache();
1112 case LFUN_WORDS_COUNT: {
1113 DocIterator from, to;
1114 if (cur.selection()) {
1115 from = cur.selectionBegin();
1116 to = cur.selectionEnd();
1118 from = doc_iterator_begin(buffer_.inset());
1119 to = doc_iterator_end(buffer_.inset());
1121 int const count = countWords(from, to);
1124 if (cur.selection())
1125 message = bformat(_("%1$d words in selection."),
1128 message = bformat(_("%1$d words in document."),
1132 if (cur.selection())
1133 message = _("One word in selection.");
1135 message = _("One word in document.");
1138 Alert::information(_("Count words"), message);
1142 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1143 // turn compression on/off
1144 buffer_.params().compressed = !buffer_.params().compressed;
1147 case LFUN_BUFFER_TOGGLE_EMBEDDING:
1148 // turn embedding on/off
1149 buffer_.embeddedFiles().enable(!buffer_.params().embedded);
1152 case LFUN_NEXT_INSET_TOGGLE: {
1153 // this is the real function we want to invoke
1154 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1155 // if there is an inset at cursor, see whether it
1157 Inset * inset = cur.nextInset();
1159 if (inset->isActive()) {
1160 Cursor tmpcur = cur;
1161 tmpcur.pushBackward(*inset);
1162 inset->dispatch(tmpcur, tmpcmd);
1163 if (tmpcur.result().dispatched()) {
1166 } else if (inset->editable() == Inset::IS_EDITABLE) {
1167 inset->edit(cur, true);
1170 // if it did not work, try the underlying inset.
1171 if (!cur.result().dispatched())
1172 cur.dispatch(tmpcmd);
1174 if (cur.result().dispatched())
1175 cur.clearSelection();
1180 case LFUN_SCREEN_UP:
1181 case LFUN_SCREEN_DOWN: {
1182 Point p = getPos(cur, cur.boundary());
1183 if (p.y_ < 0 || p.y_ > height_) {
1184 // The cursor is off-screen so recenter before proceeding.
1187 //FIXME: updateMetrics() does not update paragraph position
1188 // This is done at draw() time. So we need a redraw!
1189 // But no screen update is needed.
1190 d->metrics_info_.update_strategy = NoScreenUpdate;
1192 p = getPos(cur, cur.boundary());
1194 scroll(cmd.action == LFUN_SCREEN_UP? - height_ : height_);
1195 cur.reset(buffer_.inset());
1196 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1197 //FIXME: what to do with cur.x_target()?
1199 // The metrics are already up to date. see scroll()
1200 updateFlags = Update::None;
1204 case LFUN_SCREEN_UP_SELECT:
1205 case LFUN_SCREEN_DOWN_SELECT: {
1206 cur.selHandle(true);
1207 size_t initial_depth = cur.depth();
1208 Point const p = getPos(cur, cur.boundary());
1209 scroll(cmd.action == LFUN_SCREEN_UP_SELECT? - height_ : height_);
1210 // FIXME: We need to verify if the cursor stayed within an inset...
1211 //cur.reset(buffer_.inset());
1212 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1214 while (cur.depth() > initial_depth) {
1217 // FIXME: we need to do a redraw again because of the selection
1218 // But no screen update is needed.
1219 d->metrics_info_.update_strategy = NoScreenUpdate;
1221 updateFlags = Update::Force | Update::FitCursor;
1226 updateFlags = Update::None;
1233 docstring const BufferView::requestSelection()
1235 Cursor & cur = d->cursor_;
1237 if (!cur.selection()) {
1238 d->xsel_cache_.set = false;
1242 if (!d->xsel_cache_.set ||
1243 cur.top() != d->xsel_cache_.cursor ||
1244 cur.anchor_.top() != d->xsel_cache_.anchor)
1246 d->xsel_cache_.cursor = cur.top();
1247 d->xsel_cache_.anchor = cur.anchor_.top();
1248 d->xsel_cache_.set = cur.selection();
1249 return cur.selectionAsString(false);
1255 void BufferView::clearSelection()
1257 d->cursor_.clearSelection();
1258 // Clear the selection buffer. Otherwise a subsequent
1259 // middle-mouse-button paste would use the selection buffer,
1260 // not the more current external selection.
1261 cap::clearSelection();
1262 d->xsel_cache_.set = false;
1263 // The buffer did not really change, but this causes the
1264 // redraw we need because we cleared the selection above.
1269 void BufferView::resize(int width, int height)
1271 // Update from work area
1279 Inset const * BufferView::getCoveringInset(Text const & text, int x, int y)
1281 TextMetrics & tm = d->text_metrics_[&text];
1282 Inset * inset = tm.checkInsetHit(x, y);
1286 if (!inset->descendable())
1287 // No need to go further down if the inset is not
1291 size_t cell_number = inset->nargs();
1292 // Check all the inner cell.
1293 for (size_t i = 0; i != cell_number; ++i) {
1294 Text const * inner_text = inset->getText(i);
1297 Inset const * inset_deeper =
1298 getCoveringInset(*inner_text, x, y);
1300 return inset_deeper;
1308 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1310 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1312 // This is only called for mouse related events including
1313 // LFUN_FILE_OPEN generated by drag-and-drop.
1314 FuncRequest cmd = cmd0;
1317 cur.push(buffer_.inset());
1318 cur.selection() = d->cursor_.selection();
1320 // Either the inset under the cursor or the
1321 // surrounding Text will handle this event.
1323 // make sure we stay within the screen...
1324 cmd.y = min(max(cmd.y, -1), height_);
1326 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1328 // Get inset under mouse, if there is one.
1329 Inset const * covering_inset =
1330 getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1331 if (covering_inset == d->last_inset_)
1332 // Same inset, no need to do anything...
1335 bool need_redraw = false;
1336 // const_cast because of setMouseHover().
1337 Inset * inset = const_cast<Inset *>(covering_inset);
1339 // Remove the hint on the last hovered inset (if any).
1340 need_redraw |= d->last_inset_->setMouseHover(false);
1342 // Highlighted the newly hovered inset (if any).
1343 need_redraw |= inset->setMouseHover(true);
1344 d->last_inset_ = inset;
1348 // if last metrics update was in singlepar mode, WorkArea::redraw() will
1349 // not expose the button for redraw. We adjust here the metrics dimension
1350 // to enable a full redraw in any case as this is not costly.
1351 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
1352 std::pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
1353 std::pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
1354 int y1 = firstpm.second->position() - firstpm.second->ascent();
1355 int y2 = lastpm.second->position() + lastpm.second->descent();
1356 d->metrics_info_ = ViewMetricsInfo(firstpm.first, lastpm.first, y1, y2,
1357 FullScreenUpdate, buffer_.text().paragraphs().size());
1358 // Reinitialize anchor to first pit.
1359 d->anchor_ref_ = firstpm.first;
1360 d->offset_ref_ = -y1;
1361 LYXERR(Debug::PAINTING)
1362 << "Mouse hover detected at: (" << cmd.x << ", " << cmd.y << ")"
1363 << "\nTriggering redraw: y1: " << y1 << " y2: " << y2
1364 << " pit1: " << firstpm.first << " pit2: " << lastpm.first << endl;
1366 // This event (moving without mouse click) is not passed further.
1367 // This should be changed if it is further utilized.
1372 // Build temporary cursor.
1373 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1375 // Put anchor at the same position.
1378 // Try to dispatch to an non-editable inset near this position
1379 // via the temp cursor. If the inset wishes to change the real
1380 // cursor it has to do so explicitly by using
1381 // cur.bv().cursor() = cur; (or similar)
1383 inset->dispatch(cur, cmd);
1385 // Now dispatch to the temporary cursor. If the real cursor should
1386 // be modified, the inset's dispatch has to do so explicitly.
1387 if (!cur.result().dispatched())
1390 //Do we have a selection?
1391 theSelection().haveSelection(cursor().selection());
1393 // If the command has been dispatched,
1394 if (cur.result().dispatched()
1395 // an update is asked,
1396 && cur.result().update())
1397 processUpdateFlags(cur.result().update());
1401 void BufferView::scroll(int y)
1410 void BufferView::scrollDown(int offset)
1412 Text * text = &buffer_.text();
1413 TextMetrics & tm = d->text_metrics_[text];
1414 int ymax = height_ + offset;
1416 std::pair<pit_type, ParagraphMetrics const *> last = tm.last();
1417 int bottom_pos = last.second->position() + last.second->descent();
1418 if (last.first + 1 == int(text->paragraphs().size())) {
1419 if (bottom_pos <= height_)
1421 offset = min(offset, bottom_pos - height_);
1424 if (bottom_pos > ymax)
1426 tm.newParMetricsDown();
1428 d->offset_ref_ += offset;
1434 void BufferView::scrollUp(int offset)
1436 Text * text = &buffer_.text();
1437 TextMetrics & tm = d->text_metrics_[text];
1438 int ymin = - offset;
1440 std::pair<pit_type, ParagraphMetrics const *> first = tm.first();
1441 int top_pos = first.second->position() - first.second->ascent();
1442 if (first.first == 0) {
1445 offset = min(offset, - top_pos);
1450 tm.newParMetricsUp();
1452 d->offset_ref_ -= offset;
1458 void BufferView::setCursorFromRow(int row)
1463 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1465 d->cursor_.reset(buffer_.inset());
1467 buffer_.text().setCursor(d->cursor_, 0, 0);
1469 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1473 void BufferView::gotoLabel(docstring const & label)
1475 for (InsetIterator it = inset_iterator_begin(buffer_.inset()); it; ++it) {
1476 vector<docstring> labels;
1477 it->getLabelList(buffer_, labels);
1478 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1480 processUpdateFlags(Update::FitCursor);
1487 TextMetrics const & BufferView::textMetrics(Text const * t) const
1489 return const_cast<BufferView *>(this)->textMetrics(t);
1493 TextMetrics & BufferView::textMetrics(Text const * t)
1495 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
1496 if (tmc_it == d->text_metrics_.end()) {
1497 tmc_it = d->text_metrics_.insert(
1498 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1500 return tmc_it->second;
1504 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1507 return textMetrics(t).parMetrics(pit);
1511 int BufferView::workHeight() const
1517 void BufferView::setCursor(DocIterator const & dit)
1519 size_t const n = dit.depth();
1520 for (size_t i = 0; i < n; ++i)
1521 dit[i].inset().edit(d->cursor_, true);
1523 d->cursor_.setCursor(dit);
1524 d->cursor_.selection() = false;
1528 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1530 // Would be wrong to delete anything if we have a selection.
1531 if (cur.selection())
1534 bool need_anchor_change = false;
1535 bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1536 need_anchor_change);
1538 if (need_anchor_change)
1544 updateLabels(buffer_);
1552 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
1554 BOOST_ASSERT(&cur.bv() == this);
1557 // this event will clear selection so we save selection for
1558 // persistent selection
1559 cap::saveSelection(cursor());
1561 // Has the cursor just left the inset?
1562 bool badcursor = false;
1563 bool leftinset = (&d->cursor_.inset() != &cur.inset());
1565 badcursor = notifyCursorLeaves(d->cursor_, cur);
1567 // FIXME: shift-mouse selection doesn't work well across insets.
1568 bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
1570 // do the dEPM magic if needed
1571 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1572 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1573 // the leftinset bool would not be necessary (badcursor instead).
1574 bool update = leftinset;
1575 if (!do_selection && !badcursor && d->cursor_.inTexted())
1576 update |= checkDepm(cur, d->cursor_);
1578 // if the cursor was in an empty script inset and the new
1579 // position is in the nucleus of the inset, notifyCursorLeaves
1580 // will kill the script inset itself. So we check all the
1581 // elements of the cursor to make sure that they are correct.
1582 // For an example, see bug 2933:
1583 // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1584 // The code below could maybe be moved to a DocIterator method.
1585 //lyxerr << "cur before " << cur <<std::endl;
1586 DocIterator dit(cur.inset());
1587 dit.push_back(cur.bottom());
1589 while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1590 dit.push_back(cur[i]);
1593 //lyxerr << "5 cur after" << dit <<std::endl;
1595 d->cursor_.setCursor(dit);
1596 d->cursor_.boundary(cur.boundary());
1598 d->cursor_.setSelection();
1600 d->cursor_.clearSelection();
1602 d->cursor_.finishUndo();
1603 d->cursor_.setCurrentFont();
1608 void BufferView::putSelectionAt(DocIterator const & cur,
1609 int length, bool backwards)
1611 d->cursor_.clearSelection();
1617 d->cursor_.pos() += length;
1618 d->cursor_.setSelection(d->cursor_, -length);
1620 d->cursor_.setSelection(d->cursor_, length);
1625 Cursor & BufferView::cursor()
1631 Cursor const & BufferView::cursor() const
1637 pit_type BufferView::anchor_ref() const
1639 return d->anchor_ref_;
1643 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1645 return d->metrics_info_;
1649 bool BufferView::singleParUpdate()
1651 Text & buftext = buffer_.text();
1652 pit_type const bottom_pit = d->cursor_.bottom().pit();
1653 TextMetrics & tm = textMetrics(&buftext);
1654 int old_height = tm.parMetrics(bottom_pit).height();
1656 // In Single Paragraph mode, rebreak only
1657 // the (main text, not inset!) paragraph containing the cursor.
1658 // (if this paragraph contains insets etc., rebreaking will
1659 // recursively descend)
1660 tm.redoParagraph(bottom_pit);
1661 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
1662 if (pm.height() != old_height)
1663 // Paragraph height has changed so we cannot proceed to
1664 // the singlePar optimisation.
1667 int y1 = pm.position() - pm.ascent();
1668 int y2 = pm.position() + pm.descent();
1669 d->metrics_info_ = ViewMetricsInfo(bottom_pit, bottom_pit, y1, y2,
1670 SingleParUpdate, buftext.paragraphs().size());
1671 LYXERR(Debug::PAINTING)
1672 << BOOST_CURRENT_FUNCTION
1675 << " pit: " << bottom_pit
1682 void BufferView::updateMetrics()
1684 Text & buftext = buffer_.text();
1685 pit_type const npit = int(buftext.paragraphs().size());
1687 if (d->anchor_ref_ > int(npit - 1)) {
1688 d->anchor_ref_ = int(npit - 1);
1692 // Clear out the position cache in case of full screen redraw,
1693 d->coord_cache_.clear();
1695 // Clear out paragraph metrics to avoid having invalid metrics
1696 // in the cache from paragraphs not relayouted below
1697 // The complete text metrics will be redone.
1698 d->text_metrics_.clear();
1700 TextMetrics & tm = textMetrics(&buftext);
1702 pit_type const pit = d->anchor_ref_;
1706 // Rebreak anchor paragraph.
1707 tm.redoParagraph(pit);
1709 // Take care of anchor offset if case a recentering is needed.
1712 int y0 = tm.parMetrics(pit).ascent() - d->offset_ref_;
1714 // Redo paragraphs above anchor if necessary.
1716 while (y1 > 0 && pit1 > 0) {
1717 y1 -= tm.parMetrics(pit1).ascent();
1719 tm.redoParagraph(pit1);
1720 y1 -= tm.parMetrics(pit1).descent();
1723 // Take care of ascent of first line
1724 y1 -= tm.parMetrics(pit1).ascent();
1726 // Normalize anchor for next time
1727 d->anchor_ref_ = pit1;
1728 d->offset_ref_ = -y1;
1730 // Grey at the beginning is ugly
1731 if (pit1 == 0 && y1 > 0) {
1737 // Redo paragraphs below the anchor if necessary.
1739 while (y2 < height_ && pit2 < int(npit) - 1) {
1740 y2 += tm.parMetrics(pit2).descent();
1742 tm.redoParagraph(pit2);
1743 y2 += tm.parMetrics(pit2).ascent();
1746 // Take care of descent of last line
1747 y2 += tm.parMetrics(pit2).descent();
1749 LYXERR(Debug::PAINTING)
1750 << BOOST_CURRENT_FUNCTION
1753 << " pit1: " << pit1
1754 << " pit2: " << pit2
1755 << " npit: " << npit
1759 d->metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2,
1760 FullScreenUpdate, npit);
1762 if (lyxerr.debugging(Debug::WORKAREA)) {
1763 LYXERR(Debug::WORKAREA) << "BufferView::updateMetrics" << endl;
1764 d->coord_cache_.dump();
1769 void BufferView::menuInsertLyXFile(string const & filenm)
1771 BOOST_ASSERT(d->cursor_.inTexted());
1772 string filename = filenm;
1774 if (filename.empty()) {
1775 // Launch a file browser
1777 string initpath = lyxrc.document_path;
1778 string const trypath = buffer_.filePath();
1779 // If directory is writeable, use this as default.
1780 if (FileName(trypath).isDirWritable())
1784 FileDialog dlg(_("Select LyX document to insert"), LFUN_FILE_INSERT);
1785 dlg.setButton1(_("Documents|#o#O"), from_utf8(lyxrc.document_path));
1786 dlg.setButton2(_("Examples|#E#e"),
1787 from_utf8(addPath(package().system_support().absFilename(),
1790 FileDialog::Result result =
1791 dlg.open(from_utf8(initpath),
1792 FileFilterList(_("LyX Documents (*.lyx)")),
1795 if (result.first == FileDialog::Later)
1799 filename = to_utf8(result.second);
1801 // check selected filename
1802 if (filename.empty()) {
1803 // emit message signal.
1804 message(_("Canceled."));
1809 // Get absolute path of file and add ".lyx"
1810 // to the filename if necessary
1811 filename = fileSearch(string(), filename, "lyx").absFilename();
1813 docstring const disp_fn = makeDisplayPath(filename);
1814 // emit message signal.
1815 message(bformat(_("Inserting document %1$s..."), disp_fn));
1818 Buffer buf("", false);
1819 if (buf.loadLyXFile(FileName(filename))) {
1820 ErrorList & el = buffer_.errorList("Parse");
1821 // Copy the inserted document error list into the current buffer one.
1822 el = buf.errorList("Parse");
1823 buffer_.undo().recordUndo(d->cursor_);
1824 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
1825 buf.params().getTextClassPtr(), el);
1826 res = _("Document %1$s inserted.");
1828 res = _("Could not insert document %1$s");
1831 // emit message signal.
1832 message(bformat(res, disp_fn));
1833 buffer_.errors("Parse");
1838 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
1844 // Addup contribution of nested insets, from inside to outside,
1845 // keeping the outer paragraph for a special handling below
1846 for (size_t i = dit.depth() - 1; i >= 1; --i) {
1847 CursorSlice const & sl = dit[i];
1851 // get relative position inside sl.inset()
1852 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
1854 // Make relative position inside of the edited inset relative to sl.inset()
1858 // In case of an RTL inset, the edited inset will be positioned to the left
1861 bool boundary_i = boundary && i + 1 == dit.depth();
1862 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
1867 // remember width for the case that sl.inset() is positioned in an RTL inset
1868 if (i && dit[i - 1].text()) {
1869 // If this Inset is inside a Text Inset, retrieve the Dimension
1870 // from the containing text instead of using Inset::dimension() which
1871 // might not be implemented.
1872 // FIXME (Abdel 23/09/2007): this is a bit messy because of the
1873 // elimination of Inset::dim_ cache. This coordOffset() method needs
1874 // to be rewritten in light of the new design.
1875 Dimension const & dim = parMetrics(dit[i - 1].text(),
1876 dit[i - 1].pit()).insetDimension(&sl.inset());
1879 Dimension const dim = sl.inset().dimension(*this);
1883 //lyxerr << "Cursor::getPos, i: "
1884 // << i << " x: " << xx << " y: " << y << endl;
1887 // Add contribution of initial rows of outermost paragraph
1888 CursorSlice const & sl = dit[0];
1889 TextMetrics const & tm = textMetrics(sl.text());
1890 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
1891 BOOST_ASSERT(!pm.rows().empty());
1892 y -= pm.rows()[0].ascent();
1894 // FIXME: document this mess
1896 if (sl.pos() > 0 && dit.depth() == 1) {
1898 if (pos && boundary)
1900 // lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << std::endl;
1901 rend = pm.pos2row(pos);
1903 rend = pm.pos2row(sl.pos());
1905 size_t rend = pm.pos2row(sl.pos());
1907 for (size_t rit = 0; rit != rend; ++rit)
1908 y += pm.rows()[rit].height();
1909 y += pm.rows()[rend].ascent();
1911 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
1913 // Make relative position from the nested inset now bufferview absolute.
1914 int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
1917 // In the RTL case place the nested inset at the left of the cursor in
1918 // the outer paragraph
1919 bool boundary_1 = boundary && 1 == dit.depth();
1920 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
1928 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
1930 CursorSlice const & bot = dit.bottom();
1931 TextMetrics const & tm = textMetrics(bot.text());
1932 if (!tm.has(bot.pit()))
1933 return Point(-1, -1);
1935 Point p = coordOffset(dit, boundary); // offset from outer paragraph
1936 p.y_ += tm.parMetrics(bot.pit()).position();
1941 void BufferView::draw(frontend::Painter & pain)
1943 LYXERR(Debug::PAINTING) << "\t\t*** START DRAWING ***" << endl;
1944 Text & text = buffer_.text();
1945 TextMetrics const & tm = d->text_metrics_[&text];
1946 int const y = d->metrics_info_.y1
1947 + tm.parMetrics(d->metrics_info_.p1).ascent();
1948 PainterInfo pi(this, pain);
1950 switch (d->metrics_info_.update_strategy) {
1952 case NoScreenUpdate:
1953 // If no screen painting is actually needed, only some the different
1954 // coordinates of insets and paragraphs needs to be updated.
1955 pi.full_repaint = true;
1956 pi.pain.setDrawingEnabled(false);
1960 case SingleParUpdate:
1961 // Only the current outermost paragraph will be redrawn.
1962 pi.full_repaint = false;
1963 tm.drawParagraph(pi, d->metrics_info_.p1, 0, y);
1966 case DecorationUpdate:
1967 // FIXME: We should also distinguish DecorationUpdate to avoid text
1968 // drawing if possible. This is not possible to do easily right now
1969 // because of the single backing pixmap.
1971 case FullScreenUpdate:
1972 // The whole screen, including insets, will be refreshed.
1973 pi.full_repaint = true;
1975 // Clear background (if not delegated to rows)
1976 pain.fillRectangle(0, d->metrics_info_.y1, width_,
1977 d->metrics_info_.y2 - d->metrics_info_.y1,
1978 buffer_.inset().backgroundColor());
1981 // and grey out above (should not happen later)
1982 if (d->metrics_info_.y1 > 0)
1983 pain.fillRectangle(0, 0, width_,
1984 d->metrics_info_.y1, Color_bottomarea);
1986 // and possibly grey out below
1987 if (d->metrics_info_.y2 < height_)
1988 pain.fillRectangle(0, d->metrics_info_.y2, width_,
1989 height_ - d->metrics_info_.y2, Color_bottomarea);
1993 LYXERR(Debug::PAINTING) << "\n\t\t*** END DRAWING ***" << endl;
1997 void BufferView::message(docstring const & msg)
2000 d->gui_->message(msg);
2004 void BufferView::showDialog(std::string const & name)
2007 d->gui_->showDialog(name);
2011 void BufferView::showDialogWithData(std::string const & name,
2012 std::string const & data)
2015 d->gui_->showDialogWithData(name, data);
2019 void BufferView::showInsetDialog(std::string const & name,
2020 std::string const & data, Inset * inset)
2023 d->gui_->showInsetDialog(name, data, inset);
2027 void BufferView::updateDialog(std::string const & name, std::string const & data)
2030 d->gui_->updateDialog(name, data);
2034 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2040 // FIXME: Move this out of BufferView again
2041 docstring BufferView::contentsOfPlaintextFile(string const & f,
2046 if (fname.empty()) {
2047 FileDialog dlg(_("Select file to insert"),
2049 ? LFUN_FILE_INSERT_PLAINTEXT_PARA
2050 : LFUN_FILE_INSERT_PLAINTEXT) );
2052 FileDialog::Result result =
2053 dlg.open(from_utf8(buffer().filePath()),
2054 FileFilterList(), docstring());
2056 if (result.first == FileDialog::Later)
2059 fname = makeAbsPath(to_utf8(result.second));
2065 if (!fs::is_readable(fname.toFilesystemEncoding())) {
2066 docstring const error = from_ascii(strerror(errno));
2067 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2068 docstring const text =
2069 bformat(_("Could not read the specified document\n"
2070 "%1$s\ndue to the error: %2$s"), file, error);
2071 Alert::error(_("Could not read file"), text);
2075 ifstream ifs(fname.toFilesystemEncoding().c_str());
2077 docstring const error = from_ascii(strerror(errno));
2078 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2079 docstring const text =
2080 bformat(_("Could not open the specified document\n"
2081 "%1$s\ndue to the error: %2$s"), file, error);
2082 Alert::error(_("Could not open file"), text);
2086 ifs.unsetf(std::ios::skipws);
2087 istream_iterator<char> ii(ifs);
2088 istream_iterator<char> end;
2089 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
2090 // We use this until the compilers get better...
2091 std::vector<char> tmp;
2092 copy(ii, end, back_inserter(tmp));
2093 string const tmpstr(tmp.begin(), tmp.end());
2095 // This is what we want to use and what we will use once the
2096 // compilers get good enough.
2097 //string tmpstr(ii, end); // yet a reason for using std::string
2098 // alternate approach to get the file into a string:
2100 copy(ii, end, back_inserter(tmpstr));
2103 // FIXME UNICODE: We don't know the encoding of the file
2104 docstring file_content = from_utf8(tmpstr);
2105 if (file_content.empty()) {
2106 Alert::error(_("Reading not UTF-8 encoded file"),
2107 _("The file is not UTF-8 encoded.\n"
2108 "It will be read as local 8Bit-encoded.\n"
2109 "If this does not give the correct result\n"
2110 "then please change the encoding of the file\n"
2111 "to UTF-8 with a program other than LyX.\n"));
2112 file_content = from_local8bit(tmpstr);
2115 return normalize_c(file_content);
2119 void BufferView::insertPlaintextFile(string const & f, bool asParagraph)
2121 docstring const tmpstr = contentsOfPlaintextFile(f, asParagraph);
2126 Cursor & cur = cursor();
2127 cap::replaceSelection(cur);
2128 buffer_.undo().recordUndo(cur);
2130 cur.innerText()->insertStringAsParagraphs(cur, tmpstr);
2132 cur.innerText()->insertStringAsLines(cur, tmpstr);