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 "bufferview_funcs.h"
24 #include "coordcache.h"
25 #include "CutAndPaste.h"
27 #include "dispatchresult.h"
28 #include "errorlist.h"
30 #include "FloatList.h"
31 #include "funcrequest.h"
32 #include "FuncStatus.h"
35 #include "insetiterator.h"
37 #include "LaTeXFeatures.h"
38 #include "lyx_cb.h" // added for Dispatch functions
42 #include "lyxlayout.h"
44 #include "lyxtextclass.h"
47 #include "paragraph.h"
48 #include "paragraph_funcs.h"
49 #include "ParagraphParameters.h"
50 #include "pariterator.h"
55 #include "WordLangTuple.h"
56 #include "metricsinfo.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/FileDialog.h"
65 #include "frontends/FontMetrics.h"
67 #include "graphics/Previews.h"
69 #include "support/convert.h"
70 #include "support/filefilterlist.h"
71 #include "support/filetools.h"
72 #include "support/package.h"
73 #include "support/types.h"
75 #include <boost/bind.hpp>
76 #include <boost/current_function.hpp>
84 using support::addPath;
85 using support::bformat;
86 using support::FileFilterList;
87 using support::FileName;
88 using support::fileSearch;
89 using support::isDirWriteable;
90 using support::isFileReadable;
91 using support::makeDisplayPath;
92 using support::package;
96 using std::istringstream;
100 using std::mem_fun_ref;
104 namespace Alert = frontend::Alert;
108 /// Return an inset of this class if it exists at the current cursor position
110 T * getInsetByCode(LCursor & cur, InsetBase::Code code)
113 DocIterator it = cur;
114 if (it.nextInset() &&
115 it.nextInset()->lyxCode() == code) {
116 inset = static_cast<T*>(it.nextInset());
124 BufferView::BufferView()
125 : width_(0), height_(0), buffer_(0), wh_(0),
127 multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
128 intl_(new Intl), last_inset_(0)
130 xsel_cache_.set = false;
131 intl_->initKeyMapper(lyxrc.use_kbmap);
135 BufferView::~BufferView()
140 Buffer * BufferView::buffer() const
146 void BufferView::setBuffer(Buffer * b)
148 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
149 << "[ b = " << b << "]" << endl;
152 // Save the actual cursor position and anchor inside the
153 // buffer so that it can be restored in case we rechange
154 // to this buffer later on.
155 buffer_->saveCursor(cursor_.selectionBegin(),
156 cursor_.selectionEnd());
157 // current buffer is going to be switched-off, save cursor pos
158 LyX::ref().session().lastFilePos().save(FileName(buffer_->fileName()),
159 boost::tie(cursor_.pit(), cursor_.pos()) );
162 // If we're quitting lyx, don't bother updating stuff
168 // If we are closing current buffer, switch to the first in
171 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
172 << " No Buffer!" << endl;
173 // We are closing the buffer, use the first buffer as current
174 buffer_ = theBufferList().first();
176 // Set current buffer
181 cursor_ = LCursor(*this);
186 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
187 << "Buffer addr: " << buffer_ << endl;
188 cursor_.push(buffer_->inset());
189 cursor_.resetAnchor();
190 updateLabels(*buffer_);
191 buffer_->text().setCurrentFont(cursor_);
192 if (buffer_->getCursor().size() > 0 &&
193 buffer_->getAnchor().size() > 0)
195 cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
196 cursor_.resetAnchor();
197 cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
198 cursor_.setSelection();
203 updateMetrics(false);
205 if (buffer_ && graphics::Previews::status() != LyXRC::PREVIEW_OFF)
206 graphics::Previews::get().generateBufferPreviews(*buffer_);
210 bool BufferView::loadLyXFile(FileName const & filename, bool tolastfiles)
212 // File already open?
213 if (theBufferList().exists(filename.absFilename())) {
214 docstring const file = makeDisplayPath(filename.absFilename(), 20);
215 docstring text = bformat(_("The document %1$s is already "
216 "loaded.\n\nDo you want to revert "
217 "to the saved version?"), file);
218 int const ret = Alert::prompt(_("Revert to saved document?"),
219 text, 0, 1, _("&Revert"), _("&Switch to document"));
222 setBuffer(theBufferList().getBuffer(filename.absFilename()));
225 // FIXME: should be LFUN_REVERT
226 if (!theBufferList().close(theBufferList().getBuffer(filename.absFilename()), false))
228 // Fall through to new load. (Asger)
234 if (isFileReadable(filename)) {
235 b = theBufferList().newBuffer(filename.absFilename());
236 if (!lyx::loadLyXFile(b, filename)) {
237 theBufferList().release(b);
241 docstring text = bformat(_("The document %1$s does not yet "
242 "exist.\n\nDo you want to create "
243 "a new document?"), from_utf8(filename.absFilename()));
244 int const ret = Alert::prompt(_("Create new document?"),
245 text, 0, 1, _("&Create"), _("Cancel"));
248 b = newFile(filename.absFilename(), string(), true);
256 // Send the "errors" signal in case of parsing errors
259 // scroll to the position when the file was last closed
260 if (lyxrc.use_lastfilepos) {
263 boost::tie(pit, pos) = LyX::ref().session().lastFilePos().load(filename);
264 // I am not sure how to separate the following part to a function
265 // so I will leave this to Lars.
267 // check pit since the document may be externally changed.
268 if ( static_cast<size_t>(pit) < b->paragraphs().size() ) {
269 ParIterator it = b->par_iterator_begin();
270 ParIterator const end = b->par_iterator_end();
271 for (; it != end; ++it)
272 if (it.pit() == pit) {
273 // restored pos may be bigger than it->size
274 setCursor(makeDocIterator(it, min(pos, it->size())));
275 // No need to update the metrics if fitCursor returns false.
277 updateMetrics(false);
284 LyX::ref().session().lastFiles().add(FileName(b->fileName()));
290 void BufferView::reload()
292 if (theBufferList().close(buffer_, false))
293 loadLyXFile(FileName(buffer_->fileName()));
297 void BufferView::resize()
302 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
304 updateMetrics(false);
309 bool BufferView::fitCursor()
311 if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
312 frontend::FontMetrics const & fm =
313 theFontMetrics(cursor_.getFont());
314 int const asc = fm.maxAscent();
315 int const des = fm.maxDescent();
316 Point const p = bv_funcs::getPos(*this, cursor_, cursor_.boundary());
317 if (p.y_ - asc >= 0 && p.y_ + des < height_)
325 bool BufferView::multiParSel()
327 if (!cursor_.selection())
329 bool ret = multiparsel_cache_;
330 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
331 // Either this, or previous selection spans paragraphs
332 return ret || multiparsel_cache_;
336 bool BufferView::update(Update::flags flags)
338 // This is close to a hot-path.
339 if (lyxerr.debugging(Debug::DEBUG)) {
341 << BOOST_CURRENT_FUNCTION
342 << "[fitcursor = " << (flags & Update::FitCursor)
343 << ", forceupdate = " << (flags & Update::Force)
344 << ", singlepar = " << (flags & Update::SinglePar)
345 << "] buffer: " << buffer_ << endl;
348 // Check needed to survive LyX startup
352 if (lyxerr.debugging(Debug::WORKAREA)) {
353 lyxerr[Debug::WORKAREA] << "BufferView::update" << std::endl;
356 // Update macro store
357 buffer_->buildMacros();
359 // Now do the first drawing step if needed. This consists on updating
360 // the CoordCache in updateMetrics().
361 // The second drawing step is done in WorkArea::redraw() if needed.
363 // Case when no explicit update is requested.
365 // no need to redraw anything.
369 if (flags == Update::FitCursor) {
370 bool const fit_cursor = fitCursor();
372 updateMetrics(false);
373 // tell the frontend to update the screen if needed.
377 bool full_metrics = flags & Update::Force;
378 if (flags & Update::MultiParSel)
379 full_metrics |= multiParSel();
381 bool const single_par = !full_metrics;
382 updateMetrics(single_par);
384 if (flags & Update::FitCursor && fitCursor())
385 updateMetrics(false);
387 // tell the frontend to update the screen.
392 void BufferView::updateScrollbar()
395 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
396 << " no text in updateScrollbar" << endl;
397 scrollbarParameters_.reset();
401 LyXText & t = buffer_->text();
402 TextMetrics & tm = text_metrics_[&t];
404 int const parsize = int(t.paragraphs().size() - 1);
405 if (anchor_ref_ > parsize) {
406 anchor_ref_ = parsize;
410 if (lyxerr.debugging(Debug::GUI)) {
412 << BOOST_CURRENT_FUNCTION
413 << " Updating scrollbar: height: " << t.paragraphs().size()
414 << " curr par: " << cursor_.bottom().pit()
415 << " default height " << defaultRowHeight() << endl;
418 // It would be better to fix the scrollbar to understand
419 // values in [0..1] and divide everything by wh
421 // estimated average paragraph height:
425 int h = tm.parMetrics(anchor_ref_).height();
427 // Normalize anchor/offset (MV):
428 while (offset_ref_ > h && anchor_ref_ < parsize) {
431 h = tm.parMetrics(anchor_ref_).height();
433 // Look at paragraph heights on-screen
436 for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
439 int const h2 = tm.parMetrics(pit).height();
445 int const hav = sumh / nh;
446 // More realistic average paragraph height
451 scrollbarParameters_.height = (parsize + 1) * wh_;
452 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
453 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
457 ScrollbarParameters const & BufferView::scrollbarParameters() const
459 return scrollbarParameters_;
463 void BufferView::scrollDocView(int value)
465 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
466 << "[ value = " << value << "]" << endl;
471 LyXText & t = buffer_->text();
472 TextMetrics & tm = text_metrics_[&t];
474 float const bar = value / float(wh_ * t.paragraphs().size());
476 anchor_ref_ = int(bar * t.paragraphs().size());
477 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
478 anchor_ref_ = int(t.paragraphs().size()) - 1;
480 tm.redoParagraph(anchor_ref_);
481 int const h = tm.parMetrics(anchor_ref_).height();
482 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
483 updateMetrics(false);
487 void BufferView::setCursorFromScrollbar()
489 LyXText & t = buffer_->text();
491 int const height = 2 * defaultRowHeight();
492 int const first = height;
493 int const last = height_ - height;
494 LCursor & cur = cursor_;
496 bv_funcs::CurStatus st = bv_funcs::status(this, cur);
499 case bv_funcs::CUR_ABOVE:
500 t.setCursorFromCoordinates(cur, 0, first);
501 cur.clearSelection();
503 case bv_funcs::CUR_BELOW:
504 t.setCursorFromCoordinates(cur, 0, last);
505 cur.clearSelection();
507 case bv_funcs::CUR_INSIDE:
508 int const y = bv_funcs::getPos(*this, cur, cur.boundary()).y_;
509 int const newy = min(last, max(y, first));
511 cur.reset(buffer_->inset());
512 t.setCursorFromCoordinates(cur, 0, newy);
518 Change const BufferView::getCurrentChange() const
520 if (!cursor_.selection())
521 return Change(Change::UNCHANGED);
523 DocIterator dit = cursor_.selectionBegin();
524 return dit.paragraph().lookupChange(dit.pos());
528 void BufferView::saveBookmark(bool persistent)
530 LyX::ref().session().bookmarks().save(
531 FileName(buffer_->fileName()),
532 cursor_.paragraph().id(),
537 // emit message signal.
538 message(_("Save bookmark"));
542 void BufferView::moveToPosition(int par_id, pos_type par_pos)
544 cursor_.clearSelection();
546 ParIterator par = buffer_->getParFromID(par_id);
547 if (par == buffer_->par_iterator_end())
550 setCursor(makeDocIterator(par, min(par->size(), par_pos)));
554 void BufferView::switchKeyMap()
556 if (!lyxrc.rtl_support)
559 if (getLyXText()->real_current_font.isRightToLeft()) {
560 if (intl_->keymap == Intl::PRIMARY)
563 if (intl_->keymap == Intl::SECONDARY)
569 int BufferView::workWidth() const
575 void BufferView::center()
577 CursorSlice & bot = cursor_.bottom();
578 TextMetrics & tm = text_metrics_[bot.text()];
579 pit_type const pit = bot.pit();
580 tm.redoParagraph(pit);
581 ParagraphMetrics const & pm = tm.parMetrics(pit);
583 offset_ref_ = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary()).y_
584 + pm.ascent() - height_ / 2;
588 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
592 switch (cmd.action) {
595 flag.enabled(!buffer_->undostack().empty());
598 flag.enabled(!buffer_->redostack().empty());
600 case LFUN_FILE_INSERT:
601 case LFUN_FILE_INSERT_ASCII_PARA:
602 case LFUN_FILE_INSERT_ASCII:
603 case LFUN_BOOKMARK_SAVE:
604 // FIXME: Actually, these LFUNS should be moved to LyXText
605 flag.enabled(cursor_.inTexted());
607 case LFUN_FONT_STATE:
608 case LFUN_LABEL_INSERT:
609 case LFUN_PARAGRAPH_GOTO:
610 // FIXME handle non-trivially
611 case LFUN_OUTLINE_UP:
612 case LFUN_OUTLINE_DOWN:
613 case LFUN_OUTLINE_IN:
614 case LFUN_OUTLINE_OUT:
616 case LFUN_REFERENCE_NEXT:
618 case LFUN_WORD_REPLACE:
621 case LFUN_MARK_TOGGLE:
622 case LFUN_SCREEN_RECENTER:
623 case LFUN_BIBTEX_DATABASE_ADD:
624 case LFUN_BIBTEX_DATABASE_DEL:
625 case LFUN_WORDS_COUNT:
626 case LFUN_NEXT_INSET_TOGGLE:
630 case LFUN_LABEL_GOTO: {
631 flag.enabled(!cmd.argument().empty()
632 || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
636 case LFUN_CHANGES_TRACK:
638 flag.setOnOff(buffer_->params().trackChanges);
641 case LFUN_CHANGES_OUTPUT: {
642 OutputParams runparams;
643 LaTeXFeatures features(*buffer_, buffer_->params(), runparams);
644 flag.enabled(buffer_ && features.isAvailable("dvipost"));
645 flag.setOnOff(buffer_->params().outputChanges);
649 case LFUN_CHANGES_MERGE:
650 case LFUN_CHANGE_NEXT:
651 case LFUN_ALL_CHANGES_ACCEPT:
652 case LFUN_ALL_CHANGES_REJECT:
653 // TODO: context-sensitive enabling of LFUNs
654 // In principle, these command should only be enabled if there
655 // is a change in the document. However, without proper
656 // optimizations, this will inevitably result in poor performance.
657 flag.enabled(buffer_);
660 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
661 flag.setOnOff(buffer_->params().compressed);
673 bool BufferView::dispatch(FuncRequest const & cmd)
675 //lyxerr << BOOST_CURRENT_FUNCTION
676 // << [ cmd = " << cmd << "]" << endl;
678 // Make sure that the cached BufferView is correct.
679 lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
680 << " action[" << cmd.action << ']'
681 << " arg[" << to_utf8(cmd.argument()) << ']'
682 << " x[" << cmd.x << ']'
683 << " y[" << cmd.y << ']'
684 << " button[" << cmd.button() << ']'
687 LCursor & cur = cursor_;
689 switch (cmd.action) {
693 cur.message(_("Undo"));
694 cur.clearSelection();
695 if (!textUndo(*this))
696 cur.message(_("No further undo information"));
704 cur.message(_("Redo"));
705 cur.clearSelection();
706 if (!textRedo(*this))
707 cur.message(_("No further redo information"));
713 case LFUN_FILE_INSERT:
715 menuInsertLyXFile(to_utf8(cmd.argument()));
718 case LFUN_FILE_INSERT_ASCII_PARA:
720 insertAsciiFile(this, to_utf8(cmd.argument()), true);
723 case LFUN_FILE_INSERT_ASCII:
725 insertAsciiFile(this, to_utf8(cmd.argument()), false);
728 case LFUN_FONT_STATE:
729 cur.message(cur.currentState());
732 case LFUN_BOOKMARK_SAVE:
733 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
736 case LFUN_LABEL_GOTO: {
737 docstring label = cmd.argument();
740 getInsetByCode<InsetRef>(cursor_,
741 InsetBase::REF_CODE);
743 label = inset->getParam("reference");
744 // persistent=false: use temp_bookmark
754 case LFUN_PARAGRAPH_GOTO: {
755 int const id = convert<int>(to_utf8(cmd.argument()));
757 for (Buffer * b = buffer_; i == 0 || b != buffer_; b = theBufferList().next(b)) {
758 ParIterator par = b->getParFromID(id);
759 if (par == b->par_iterator_end()) {
761 << "No matching paragraph found! ["
762 << id << "]." << endl;
765 << "Paragraph " << par->id()
766 << " found in buffer `"
767 << b->fileName() << "'." << endl;
771 setCursor(makeDocIterator(par, 0));
775 // Switch to other buffer view and resend cmd
776 theLyXFunc().dispatch(FuncRequest(
777 LFUN_BUFFER_SWITCH, b->fileName()));
778 theLyXFunc().dispatch(cmd);
787 case LFUN_OUTLINE_UP:
788 toc::outline(toc::Up, cursor_);
789 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
790 updateLabels(*buffer_);
792 case LFUN_OUTLINE_DOWN:
793 toc::outline(toc::Down, cursor_);
794 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
795 updateLabels(*buffer_);
797 case LFUN_OUTLINE_IN:
798 toc::outline(toc::In, cursor_);
799 updateLabels(*buffer_);
801 case LFUN_OUTLINE_OUT:
802 toc::outline(toc::Out, cursor_);
803 updateLabels(*buffer_);
807 bv_funcs::gotoInset(this, InsetBase::NOTE_CODE, false);
810 case LFUN_REFERENCE_NEXT: {
811 vector<InsetBase_code> tmp;
812 tmp.push_back(InsetBase::LABEL_CODE);
813 tmp.push_back(InsetBase::REF_CODE);
814 bv_funcs::gotoInset(this, tmp, true);
818 case LFUN_CHANGES_TRACK:
819 buffer_->params().trackChanges = !buffer_->params().trackChanges;
822 case LFUN_CHANGES_OUTPUT: {
823 buffer_->params().outputChanges = !buffer_->params().outputChanges;
827 case LFUN_CHANGE_NEXT:
828 findNextChange(this);
831 case LFUN_CHANGES_MERGE:
832 if (findNextChange(this))
833 showDialog("changes");
836 case LFUN_ALL_CHANGES_ACCEPT: {
837 cursor_.reset(buffer_->inset());
839 #warning FIXME changes
841 while (findNextChange(this))
842 getLyXText()->acceptChange(cursor_);
847 case LFUN_ALL_CHANGES_REJECT: {
848 cursor_.reset(buffer_->inset());
850 #warning FIXME changes
852 while (findNextChange(this))
853 getLyXText()->rejectChange(cursor_);
861 case LFUN_WORD_REPLACE:
866 cur.clearSelection();
868 cur.message(from_utf8(N_("Mark off")));
872 cur.clearSelection();
875 cur.message(from_utf8(N_("Mark on")));
878 case LFUN_MARK_TOGGLE:
879 cur.clearSelection();
882 cur.message(from_utf8(N_("Mark removed")));
885 cur.message(from_utf8(N_("Mark set")));
890 case LFUN_SCREEN_RECENTER:
894 case LFUN_BIBTEX_DATABASE_ADD: {
895 LCursor tmpcur = cursor_;
896 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
897 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
898 InsetBase::BIBTEX_CODE);
900 if (inset->addDatabase(to_utf8(cmd.argument())))
901 buffer_->updateBibfilesCache();
906 case LFUN_BIBTEX_DATABASE_DEL: {
907 LCursor tmpcur = cursor_;
908 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
909 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
910 InsetBase::BIBTEX_CODE);
912 if (inset->delDatabase(to_utf8(cmd.argument())))
913 buffer_->updateBibfilesCache();
918 case LFUN_WORDS_COUNT: {
919 DocIterator from, to;
920 if (cur.selection()) {
921 from = cur.selectionBegin();
922 to = cur.selectionEnd();
924 from = doc_iterator_begin(buffer_->inset());
925 to = doc_iterator_end(buffer_->inset());
927 int const count = countWords(from, to);
931 message = bformat(_("%1$d words in selection."),
934 message = bformat(_("%1$d words in document."),
939 message = _("One word in selection.");
941 message = _("One word in document.");
944 Alert::information(_("Count words"), message);
948 case LFUN_BUFFER_TOGGLE_COMPRESSION:
949 // turn compression on/off
950 buffer_->params().compressed = !buffer_->params().compressed;
953 case LFUN_NEXT_INSET_TOGGLE: {
954 // this is the real function we want to invoke
955 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
956 // if there is an inset at cursor, see whether it
958 InsetBase * inset = cur.nextInset();
959 if (inset && inset->isActive()) {
960 LCursor tmpcur = cur;
961 tmpcur.pushLeft(*inset);
962 inset->dispatch(tmpcur, tmpcmd);
963 if (tmpcur.result().dispatched()) {
967 // if it did not work, try the underlying inset.
968 if (!cur.result().dispatched())
969 cur.dispatch(tmpcmd);
971 if (cur.result().dispatched())
972 cur.clearSelection();
985 docstring const BufferView::requestSelection()
990 LCursor & cur = cursor_;
992 if (!cur.selection()) {
993 xsel_cache_.set = false;
997 if (!xsel_cache_.set ||
998 cur.top() != xsel_cache_.cursor ||
999 cur.anchor_.top() != xsel_cache_.anchor)
1001 xsel_cache_.cursor = cur.top();
1002 xsel_cache_.anchor = cur.anchor_.top();
1003 xsel_cache_.set = cur.selection();
1004 return cur.selectionAsString(false);
1010 void BufferView::clearSelection()
1013 cursor_.clearSelection();
1014 xsel_cache_.set = false;
1019 void BufferView::workAreaResize(int width, int height)
1021 // A resize is triggered whenever a window gets focus,
1022 // because of the shared rows() of a buffer in multiple
1025 // Update from work area
1029 text_metrics_.clear();
1036 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1038 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1040 // This is only called for mouse related events including
1041 // LFUN_FILE_OPEN generated by drag-and-drop.
1042 FuncRequest cmd = cmd0;
1044 // E.g. Qt mouse press when no buffer
1049 cur.push(buffer_->inset());
1050 cur.selection() = cursor_.selection();
1052 // Either the inset under the cursor or the
1053 // surrounding LyXText will handle this event.
1055 // Build temporary cursor.
1056 cmd.y = min(max(cmd.y, -1), height_);
1057 InsetBase * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1059 //lyxerr << BOOST_CURRENT_FUNCTION
1060 // << " * hit inset at tip: " << inset << endl;
1061 //lyxerr << BOOST_CURRENT_FUNCTION
1062 // << " * created temp cursor:" << cur << endl;
1064 // NOTE: editXY returns the top level inset of nested insets. If you happen
1065 // to move from a text (inset=0) to a text inside an inset (e.g. an opened
1066 // footnote inset, again inset=0), that inset will not be redrawn.
1067 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1068 bool need_redraw = false;
1070 if (inset != last_inset_) {
1072 need_redraw |= last_inset_->setMouseHover(false);
1074 need_redraw |= inset->setMouseHover(true);
1075 last_inset_ = inset;
1078 // if last metrics update was in singlepar mode, WorkArea::redraw() will
1079 // not expose the button for redraw. We adjust here the metrics dimension
1080 // to enable a full redraw.
1081 // FIXME: It is possible to redraw only the area around the button!
1082 if (need_redraw && metrics_info_.singlepar) {
1083 // FIXME: It should be possible to redraw only the area around
1084 // the button by doing this:
1086 //metrics_info_.singlepar = false;
1087 //metrics_info_.y1 = ymin of button;
1088 //metrics_info_.y2 = ymax of button;
1090 // Unfortunately, rowpainter.C:paintText() does not distinguish
1091 // between background updates and text updates. So we use the hammer
1092 // solution for now. We could also avoid the updateMetrics() below
1093 // by using the first and last pit of the CoordCache. Have a look
1094 // at LyXText::getPitNearY() to see what I mean.
1096 //metrics_info_.pit1 = first pit of CoordCache;
1097 //metrics_info_.pit2 = last pit of CoordCache;
1098 //metrics_info_.singlepar = false;
1099 //metrics_info_.y1 = 0;
1100 //metrics_info_.y2 = height_;
1102 updateMetrics(false);
1105 // This event (moving without mouse click) is not passed further.
1106 // This should be changed if it is further utilized.
1110 // Put anchor at the same position.
1113 // Try to dispatch to an non-editable inset near this position
1114 // via the temp cursor. If the inset wishes to change the real
1115 // cursor it has to do so explicitly by using
1116 // cur.bv().cursor() = cur; (or similar)
1118 inset->dispatch(cur, cmd);
1121 // Now dispatch to the temporary cursor. If the real cursor should
1122 // be modified, the inset's dispatch has to do so explicitly.
1123 if (!cur.result().dispatched())
1126 // Redraw if requested and necessary.
1127 if (cur.result().dispatched() && cur.result().update())
1128 return update(cur.result().update());
1134 void BufferView::scroll(int /*lines*/)
1139 // LyXText const * t = &buffer_->text();
1140 // int const line_height = defaultRowHeight();
1142 // // The new absolute coordinate
1143 // int new_top_y = top_y() + lines * line_height;
1145 // // Restrict to a valid value
1146 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1147 // new_top_y = std::max(0, new_top_y);
1149 // scrollDocView(new_top_y);
1151 // // Update the scrollbar.
1152 // workArea_->setScrollbarParams(t->height(), top_y(), defaultRowHeight());}
1156 void BufferView::setCursorFromRow(int row)
1161 buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1164 buffer_->text().setCursor(cursor_, 0, 0);
1166 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1170 void BufferView::gotoLabel(docstring const & label)
1172 for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1173 vector<docstring> labels;
1174 it->getLabelList(*buffer_, labels);
1175 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1184 LyXText * BufferView::getLyXText()
1186 LyXText * text = cursor_.innerText();
1192 LyXText const * BufferView::getLyXText() const
1194 LyXText const * text = cursor_.innerText();
1200 TextMetrics const & BufferView::textMetrics(LyXText const * t) const
1202 return const_cast<BufferView *>(this)->textMetrics(t);
1206 TextMetrics & BufferView::textMetrics(LyXText const * t)
1208 TextMetricsCache::iterator tmc_it = text_metrics_.find(t);
1209 if (tmc_it == text_metrics_.end()) {
1210 tmc_it = text_metrics_.insert(
1211 make_pair(t, TextMetrics(this, const_cast<LyXText *>(t)))).first;
1213 return tmc_it->second;
1217 ParagraphMetrics const & BufferView::parMetrics(LyXText const * t,
1220 return textMetrics(t).parMetrics(pit);
1224 int BufferView::workHeight() const
1230 void BufferView::setCursor(DocIterator const & dit)
1232 size_t const n = dit.depth();
1233 for (size_t i = 0; i < n; ++i)
1234 dit[i].inset().edit(cursor_, true);
1236 cursor_.setCursor(dit);
1237 cursor_.selection() = false;
1241 bool BufferView::checkDepm(LCursor & cur, LCursor & old)
1243 // Would be wrong to delete anything if we have a selection.
1244 if (cur.selection())
1247 bool need_anchor_change = false;
1248 bool changed = cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1249 need_anchor_change);
1251 if (need_anchor_change)
1257 updateMetrics(false);
1263 bool BufferView::mouseSetCursor(LCursor & cur)
1265 BOOST_ASSERT(&cur.bv() == this);
1267 // Has the cursor just left the inset?
1268 bool badcursor = false;
1269 if (&cursor_.inset() != &cur.inset())
1270 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1272 // do the dEPM magic if needed
1273 // FIXME: move this to InsetText::notifyCursorLeaves?
1274 bool update = false;
1275 if (!badcursor && cursor_.inTexted())
1276 checkDepm(cur, cursor_);
1279 cursor_.clearSelection();
1280 cursor_.setTargetX();
1286 void BufferView::putSelectionAt(DocIterator const & cur,
1287 int length, bool backwards)
1289 cursor_.clearSelection();
1295 cursor_.pos() += length;
1296 cursor_.setSelection(cursor_, -length);
1298 cursor_.setSelection(cursor_, length);
1303 LCursor & BufferView::cursor()
1309 LCursor const & BufferView::cursor() const
1315 pit_type BufferView::anchor_ref() const
1321 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1323 return metrics_info_;
1327 void BufferView::updateMetrics(bool singlepar)
1329 LyXText & buftext = buffer_->text();
1330 TextMetrics & tm = textMetrics(&buftext);
1331 pit_type size = int(buftext.paragraphs().size());
1333 if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1334 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1338 pit_type const pit = anchor_ref_;
1341 size_t const npit = buftext.paragraphs().size();
1343 // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
1344 // the (main text, not inset!) paragraph containing the cursor.
1345 // (if this paragraph contains insets etc., rebreaking will
1346 // recursively descend)
1347 if (!singlepar || pit == cursor_.bottom().pit())
1348 if (tm.redoParagraph(pit))
1351 // Clear out the position cache in case of full screen redraw.
1353 coord_cache_.clear();
1355 int y0 = tm.parMetrics(pit).ascent() - offset_ref_;
1357 // Redo paragraphs above anchor if necessary; again, in Single Par
1358 // mode, only if we encounter the (main text) one having the cursor.
1360 while (y1 > 0 && pit1 > 0) {
1361 y1 -= tm.parMetrics(pit1).ascent();
1363 if (!singlepar || pit1 == cursor_.bottom().pit())
1364 tm.redoParagraph(pit1);
1365 y1 -= tm.parMetrics(pit1).descent();
1369 // Take care of ascent of first line
1370 y1 -= tm.parMetrics(pit1).ascent();
1372 // Normalize anchor for next time
1376 // Grey at the beginning is ugly
1377 if (pit1 == 0 && y1 > 0) {
1383 // Redo paragraphs below the anchor if necessary. Single par mode:
1384 // only the one containing the cursor if encountered.
1386 while (y2 < height_ && pit2 < int(npit) - 1) {
1387 y2 += tm.parMetrics(pit2).descent();
1389 if (!singlepar || pit2 == cursor_.bottom().pit())
1390 tm.redoParagraph(pit2);
1391 y2 += tm.parMetrics(pit2).ascent();
1394 // Take care of descent of last line
1395 y2 += tm.parMetrics(pit2).descent();
1397 // The coordinates of all these paragraphs are correct, cache them
1399 CoordCache::InnerParPosCache & parPos = coord_cache_.parPos()[&buftext];
1400 for (pit_type pit = pit1; pit <= pit2; ++pit) {
1401 ParagraphMetrics const & pm = tm.parMetrics(pit);
1403 parPos[pit] = Point(0, y);
1404 if (singlepar && pit == cursor_.bottom().pit()) {
1405 // In Single Paragraph mode, collect here the
1406 // y1 and y2 of the (one) paragraph the cursor is in
1407 y1 = y - pm.ascent();
1408 y2 = y + pm.descent();
1414 // collect cursor paragraph iter bounds
1415 pit1 = cursor_.bottom().pit();
1416 pit2 = cursor_.bottom().pit();
1419 lyxerr[Debug::DEBUG]
1420 << BOOST_CURRENT_FUNCTION
1423 << " pit1: " << pit1
1424 << " pit2: " << pit2
1425 << " npit: " << npit
1426 << " singlepar: " << singlepar
1430 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2, singlepar, size);
1432 if (lyxerr.debugging(Debug::WORKAREA)) {
1433 lyxerr[Debug::WORKAREA] << "BufferView::updateMetrics" << endl;
1434 coord_cache_.dump();
1439 void BufferView::menuInsertLyXFile(string const & filenm)
1441 BOOST_ASSERT(cursor_.inTexted());
1442 string filename = filenm;
1444 if (filename.empty()) {
1445 // Launch a file browser
1447 string initpath = lyxrc.document_path;
1450 string const trypath = buffer_->filePath();
1451 // If directory is writeable, use this as default.
1452 if (isDirWriteable(FileName(trypath)))
1457 FileDialog fileDlg(_("Select LyX document to insert"),
1459 make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1460 make_pair(_("Examples|#E#e"), from_utf8(addPath(package().system_support(), "examples"))));
1462 FileDialog::Result result =
1463 fileDlg.open(from_utf8(initpath),
1464 FileFilterList(_("LyX Documents (*.lyx)")),
1467 if (result.first == FileDialog::Later)
1471 filename = to_utf8(result.second);
1473 // check selected filename
1474 if (filename.empty()) {
1475 // emit message signal.
1476 message(_("Canceled."));
1481 // Get absolute path of file and add ".lyx"
1482 // to the filename if necessary
1483 filename = fileSearch(string(), filename, "lyx").absFilename();
1485 docstring const disp_fn = makeDisplayPath(filename);
1486 // emit message signal.
1487 message(bformat(_("Inserting document %1$s..."), disp_fn));
1490 Buffer buf("", false);
1491 if (lyx::loadLyXFile(&buf, FileName(filename))) {
1492 ErrorList & el = buffer_->errorList("Parse");
1493 // Copy the inserted document error list into the current buffer one.
1494 el = buf.errorList("Parse");
1495 recordUndo(cursor_);
1496 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1497 buf.params().textclass, el);
1498 res = _("Document %1$s inserted.");
1500 res = _("Could not insert document %1$s");
1502 // emit message signal.
1503 message(bformat(res, disp_fn));
1504 buffer_->errors("Parse");