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 // last_inset_ points to the last visited inset. This pointer may become
339 // invalid because of keyboard editing. Since all such operations
340 // causes screen update(), I reset last_inset_ to avoid such a problem.
342 // This is close to a hot-path.
343 if (lyxerr.debugging(Debug::DEBUG)) {
345 << BOOST_CURRENT_FUNCTION
346 << "[fitcursor = " << (flags & Update::FitCursor)
347 << ", forceupdate = " << (flags & Update::Force)
348 << ", singlepar = " << (flags & Update::SinglePar)
349 << "] buffer: " << buffer_ << endl;
352 // Check needed to survive LyX startup
356 if (lyxerr.debugging(Debug::WORKAREA)) {
357 lyxerr[Debug::WORKAREA] << "BufferView::update" << std::endl;
360 // Update macro store
361 buffer_->buildMacros();
363 // Now do the first drawing step if needed. This consists on updating
364 // the CoordCache in updateMetrics().
365 // The second drawing step is done in WorkArea::redraw() if needed.
367 // Case when no explicit update is requested.
369 // no need to redraw anything.
373 if (flags == Update::FitCursor) {
374 bool const fit_cursor = fitCursor();
376 updateMetrics(false);
377 // tell the frontend to update the screen if needed.
381 bool full_metrics = flags & Update::Force;
382 if (flags & Update::MultiParSel)
383 full_metrics |= multiParSel();
385 bool const single_par = !full_metrics;
386 updateMetrics(single_par);
388 if (flags & Update::FitCursor && fitCursor())
389 updateMetrics(false);
391 // tell the frontend to update the screen.
396 void BufferView::updateScrollbar()
399 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
400 << " no text in updateScrollbar" << endl;
401 scrollbarParameters_.reset();
405 LyXText & t = buffer_->text();
406 TextMetrics & tm = text_metrics_[&t];
408 int const parsize = int(t.paragraphs().size() - 1);
409 if (anchor_ref_ > parsize) {
410 anchor_ref_ = parsize;
414 if (lyxerr.debugging(Debug::GUI)) {
416 << BOOST_CURRENT_FUNCTION
417 << " Updating scrollbar: height: " << t.paragraphs().size()
418 << " curr par: " << cursor_.bottom().pit()
419 << " default height " << defaultRowHeight() << endl;
422 // It would be better to fix the scrollbar to understand
423 // values in [0..1] and divide everything by wh
425 // estimated average paragraph height:
429 int h = tm.parMetrics(anchor_ref_).height();
431 // Normalize anchor/offset (MV):
432 while (offset_ref_ > h && anchor_ref_ < parsize) {
435 h = tm.parMetrics(anchor_ref_).height();
437 // Look at paragraph heights on-screen
440 for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
443 int const h2 = tm.parMetrics(pit).height();
449 int const hav = sumh / nh;
450 // More realistic average paragraph height
455 scrollbarParameters_.height = (parsize + 1) * wh_;
456 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
457 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
461 ScrollbarParameters const & BufferView::scrollbarParameters() const
463 return scrollbarParameters_;
467 void BufferView::scrollDocView(int value)
469 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
470 << "[ value = " << value << "]" << endl;
475 LyXText & t = buffer_->text();
476 TextMetrics & tm = text_metrics_[&t];
478 float const bar = value / float(wh_ * t.paragraphs().size());
480 anchor_ref_ = int(bar * t.paragraphs().size());
481 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
482 anchor_ref_ = int(t.paragraphs().size()) - 1;
484 tm.redoParagraph(anchor_ref_);
485 int const h = tm.parMetrics(anchor_ref_).height();
486 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
487 updateMetrics(false);
491 void BufferView::setCursorFromScrollbar()
493 LyXText & t = buffer_->text();
495 int const height = 2 * defaultRowHeight();
496 int const first = height;
497 int const last = height_ - height;
498 LCursor & cur = cursor_;
500 bv_funcs::CurStatus st = bv_funcs::status(this, cur);
503 case bv_funcs::CUR_ABOVE:
504 t.setCursorFromCoordinates(cur, 0, first);
505 cur.clearSelection();
507 case bv_funcs::CUR_BELOW:
508 t.setCursorFromCoordinates(cur, 0, last);
509 cur.clearSelection();
511 case bv_funcs::CUR_INSIDE:
512 int const y = bv_funcs::getPos(*this, cur, cur.boundary()).y_;
513 int const newy = min(last, max(y, first));
515 cur.reset(buffer_->inset());
516 t.setCursorFromCoordinates(cur, 0, newy);
522 Change const BufferView::getCurrentChange() const
524 if (!cursor_.selection())
525 return Change(Change::UNCHANGED);
527 DocIterator dit = cursor_.selectionBegin();
528 return dit.paragraph().lookupChange(dit.pos());
532 void BufferView::saveBookmark(bool persistent)
534 LyX::ref().session().bookmarks().save(
535 FileName(buffer_->fileName()),
536 cursor_.paragraph().id(),
541 // emit message signal.
542 message(_("Save bookmark"));
546 void BufferView::moveToPosition(int par_id, pos_type par_pos)
548 cursor_.clearSelection();
550 ParIterator par = buffer_->getParFromID(par_id);
551 if (par == buffer_->par_iterator_end())
554 setCursor(makeDocIterator(par, min(par->size(), par_pos)));
558 void BufferView::switchKeyMap()
560 if (!lyxrc.rtl_support)
563 if (getLyXText()->real_current_font.isRightToLeft()) {
564 if (intl_->keymap == Intl::PRIMARY)
567 if (intl_->keymap == Intl::SECONDARY)
573 int BufferView::workWidth() const
579 void BufferView::center()
581 CursorSlice & bot = cursor_.bottom();
582 TextMetrics & tm = text_metrics_[bot.text()];
583 pit_type const pit = bot.pit();
584 tm.redoParagraph(pit);
585 ParagraphMetrics const & pm = tm.parMetrics(pit);
587 offset_ref_ = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary()).y_
588 + pm.ascent() - height_ / 2;
592 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
596 switch (cmd.action) {
599 flag.enabled(!buffer_->undostack().empty());
602 flag.enabled(!buffer_->redostack().empty());
604 case LFUN_FILE_INSERT:
605 case LFUN_FILE_INSERT_ASCII_PARA:
606 case LFUN_FILE_INSERT_ASCII:
607 case LFUN_BOOKMARK_SAVE:
608 // FIXME: Actually, these LFUNS should be moved to LyXText
609 flag.enabled(cursor_.inTexted());
611 case LFUN_FONT_STATE:
612 case LFUN_LABEL_INSERT:
613 case LFUN_PARAGRAPH_GOTO:
614 // FIXME handle non-trivially
615 case LFUN_OUTLINE_UP:
616 case LFUN_OUTLINE_DOWN:
617 case LFUN_OUTLINE_IN:
618 case LFUN_OUTLINE_OUT:
620 case LFUN_REFERENCE_NEXT:
622 case LFUN_WORD_REPLACE:
625 case LFUN_MARK_TOGGLE:
626 case LFUN_SCREEN_RECENTER:
627 case LFUN_BIBTEX_DATABASE_ADD:
628 case LFUN_BIBTEX_DATABASE_DEL:
629 case LFUN_WORDS_COUNT:
630 case LFUN_NEXT_INSET_TOGGLE:
634 case LFUN_LABEL_GOTO: {
635 flag.enabled(!cmd.argument().empty()
636 || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
640 case LFUN_CHANGES_TRACK:
642 flag.setOnOff(buffer_->params().trackChanges);
645 case LFUN_CHANGES_OUTPUT: {
646 OutputParams runparams;
647 LaTeXFeatures features(*buffer_, buffer_->params(), runparams);
648 flag.enabled(buffer_ && features.isAvailable("dvipost"));
649 flag.setOnOff(buffer_->params().outputChanges);
653 case LFUN_CHANGES_MERGE:
654 case LFUN_CHANGE_NEXT:
655 case LFUN_ALL_CHANGES_ACCEPT:
656 case LFUN_ALL_CHANGES_REJECT:
657 // TODO: context-sensitive enabling of LFUNs
658 // In principle, these command should only be enabled if there
659 // is a change in the document. However, without proper
660 // optimizations, this will inevitably result in poor performance.
661 flag.enabled(buffer_);
664 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
665 flag.setOnOff(buffer_->params().compressed);
677 bool BufferView::dispatch(FuncRequest const & cmd)
679 //lyxerr << BOOST_CURRENT_FUNCTION
680 // << [ cmd = " << cmd << "]" << endl;
682 // Make sure that the cached BufferView is correct.
683 lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
684 << " action[" << cmd.action << ']'
685 << " arg[" << to_utf8(cmd.argument()) << ']'
686 << " x[" << cmd.x << ']'
687 << " y[" << cmd.y << ']'
688 << " button[" << cmd.button() << ']'
691 LCursor & cur = cursor_;
693 switch (cmd.action) {
697 cur.message(_("Undo"));
698 cur.clearSelection();
699 if (!textUndo(*this))
700 cur.message(_("No further undo information"));
708 cur.message(_("Redo"));
709 cur.clearSelection();
710 if (!textRedo(*this))
711 cur.message(_("No further redo information"));
717 case LFUN_FILE_INSERT:
719 menuInsertLyXFile(to_utf8(cmd.argument()));
722 case LFUN_FILE_INSERT_ASCII_PARA:
724 insertAsciiFile(this, to_utf8(cmd.argument()), true);
727 case LFUN_FILE_INSERT_ASCII:
729 insertAsciiFile(this, to_utf8(cmd.argument()), false);
732 case LFUN_FONT_STATE:
733 cur.message(cur.currentState());
736 case LFUN_BOOKMARK_SAVE:
737 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
740 case LFUN_LABEL_GOTO: {
741 docstring label = cmd.argument();
744 getInsetByCode<InsetRef>(cursor_,
745 InsetBase::REF_CODE);
747 label = inset->getParam("reference");
748 // persistent=false: use temp_bookmark
758 case LFUN_PARAGRAPH_GOTO: {
759 int const id = convert<int>(to_utf8(cmd.argument()));
761 for (Buffer * b = buffer_; i == 0 || b != buffer_; b = theBufferList().next(b)) {
762 ParIterator par = b->getParFromID(id);
763 if (par == b->par_iterator_end()) {
765 << "No matching paragraph found! ["
766 << id << "]." << endl;
769 << "Paragraph " << par->id()
770 << " found in buffer `"
771 << b->fileName() << "'." << endl;
775 setCursor(makeDocIterator(par, 0));
779 // Switch to other buffer view and resend cmd
780 theLyXFunc().dispatch(FuncRequest(
781 LFUN_BUFFER_SWITCH, b->fileName()));
782 theLyXFunc().dispatch(cmd);
791 case LFUN_OUTLINE_UP:
792 toc::outline(toc::Up, cursor_);
793 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
794 updateLabels(*buffer_);
796 case LFUN_OUTLINE_DOWN:
797 toc::outline(toc::Down, cursor_);
798 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
799 updateLabels(*buffer_);
801 case LFUN_OUTLINE_IN:
802 toc::outline(toc::In, cursor_);
803 updateLabels(*buffer_);
805 case LFUN_OUTLINE_OUT:
806 toc::outline(toc::Out, cursor_);
807 updateLabels(*buffer_);
811 bv_funcs::gotoInset(this, InsetBase::NOTE_CODE, false);
814 case LFUN_REFERENCE_NEXT: {
815 vector<InsetBase_code> tmp;
816 tmp.push_back(InsetBase::LABEL_CODE);
817 tmp.push_back(InsetBase::REF_CODE);
818 bv_funcs::gotoInset(this, tmp, true);
822 case LFUN_CHANGES_TRACK:
823 buffer_->params().trackChanges = !buffer_->params().trackChanges;
826 case LFUN_CHANGES_OUTPUT: {
827 buffer_->params().outputChanges = !buffer_->params().outputChanges;
831 case LFUN_CHANGE_NEXT:
832 findNextChange(this);
835 case LFUN_CHANGES_MERGE:
836 if (findNextChange(this))
837 showDialog("changes");
840 case LFUN_ALL_CHANGES_ACCEPT: {
841 cursor_.reset(buffer_->inset());
843 #warning FIXME changes
845 while (findNextChange(this))
846 getLyXText()->acceptChange(cursor_);
851 case LFUN_ALL_CHANGES_REJECT: {
852 cursor_.reset(buffer_->inset());
854 #warning FIXME changes
856 while (findNextChange(this))
857 getLyXText()->rejectChange(cursor_);
865 case LFUN_WORD_REPLACE:
870 cur.clearSelection();
872 cur.message(from_utf8(N_("Mark off")));
876 cur.clearSelection();
879 cur.message(from_utf8(N_("Mark on")));
882 case LFUN_MARK_TOGGLE:
883 cur.clearSelection();
886 cur.message(from_utf8(N_("Mark removed")));
889 cur.message(from_utf8(N_("Mark set")));
894 case LFUN_SCREEN_RECENTER:
898 case LFUN_BIBTEX_DATABASE_ADD: {
899 LCursor tmpcur = cursor_;
900 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
901 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
902 InsetBase::BIBTEX_CODE);
904 if (inset->addDatabase(to_utf8(cmd.argument())))
905 buffer_->updateBibfilesCache();
910 case LFUN_BIBTEX_DATABASE_DEL: {
911 LCursor tmpcur = cursor_;
912 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
913 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
914 InsetBase::BIBTEX_CODE);
916 if (inset->delDatabase(to_utf8(cmd.argument())))
917 buffer_->updateBibfilesCache();
922 case LFUN_WORDS_COUNT: {
923 DocIterator from, to;
924 if (cur.selection()) {
925 from = cur.selectionBegin();
926 to = cur.selectionEnd();
928 from = doc_iterator_begin(buffer_->inset());
929 to = doc_iterator_end(buffer_->inset());
931 int const count = countWords(from, to);
935 message = bformat(_("%1$d words in selection."),
938 message = bformat(_("%1$d words in document."),
943 message = _("One word in selection.");
945 message = _("One word in document.");
948 Alert::information(_("Count words"), message);
952 case LFUN_BUFFER_TOGGLE_COMPRESSION:
953 // turn compression on/off
954 buffer_->params().compressed = !buffer_->params().compressed;
957 case LFUN_NEXT_INSET_TOGGLE: {
958 // this is the real function we want to invoke
959 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
960 // if there is an inset at cursor, see whether it
962 InsetBase * inset = cur.nextInset();
963 if (inset && inset->isActive()) {
964 LCursor tmpcur = cur;
965 tmpcur.pushLeft(*inset);
966 inset->dispatch(tmpcur, tmpcmd);
967 if (tmpcur.result().dispatched()) {
971 // if it did not work, try the underlying inset.
972 if (!cur.result().dispatched())
973 cur.dispatch(tmpcmd);
975 if (cur.result().dispatched())
976 cur.clearSelection();
989 docstring const BufferView::requestSelection()
994 LCursor & cur = cursor_;
996 if (!cur.selection()) {
997 xsel_cache_.set = false;
1001 if (!xsel_cache_.set ||
1002 cur.top() != xsel_cache_.cursor ||
1003 cur.anchor_.top() != xsel_cache_.anchor)
1005 xsel_cache_.cursor = cur.top();
1006 xsel_cache_.anchor = cur.anchor_.top();
1007 xsel_cache_.set = cur.selection();
1008 return cur.selectionAsString(false);
1014 void BufferView::clearSelection()
1017 cursor_.clearSelection();
1018 xsel_cache_.set = false;
1019 // The buffer did not really change, but this causes the
1020 // redraw we need because we cleared the selection above.
1026 void BufferView::workAreaResize(int width, int height)
1028 // A resize is triggered whenever a window gets focus,
1029 // because of the shared rows() of a buffer in multiple
1032 // Update from work area
1036 text_metrics_.clear();
1043 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1045 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1047 // This is only called for mouse related events including
1048 // LFUN_FILE_OPEN generated by drag-and-drop.
1049 FuncRequest cmd = cmd0;
1051 // E.g. Qt mouse press when no buffer
1056 cur.push(buffer_->inset());
1057 cur.selection() = cursor_.selection();
1059 // Either the inset under the cursor or the
1060 // surrounding LyXText will handle this event.
1062 // Build temporary cursor.
1063 cmd.y = min(max(cmd.y, -1), height_);
1064 InsetBase * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1066 //lyxerr << BOOST_CURRENT_FUNCTION
1067 // << " * hit inset at tip: " << inset << endl;
1068 //lyxerr << BOOST_CURRENT_FUNCTION
1069 // << " * created temp cursor:" << cur << endl;
1071 // NOTE: editXY returns the top level inset of nested insets. If you happen
1072 // to move from a text (inset=0) to a text inside an inset (e.g. an opened
1073 // footnote inset, again inset=0), that inset will not be redrawn.
1074 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1075 bool need_redraw = false;
1077 if (inset != last_inset_) {
1079 need_redraw |= last_inset_->setMouseHover(false);
1081 need_redraw |= inset->setMouseHover(true);
1082 last_inset_ = inset;
1085 // if last metrics update was in singlepar mode, WorkArea::redraw() will
1086 // not expose the button for redraw. We adjust here the metrics dimension
1087 // to enable a full redraw.
1088 // FIXME: It is possible to redraw only the area around the button!
1089 if (need_redraw && metrics_info_.singlepar) {
1090 // FIXME: It should be possible to redraw only the area around
1091 // the button by doing this:
1093 //metrics_info_.singlepar = false;
1094 //metrics_info_.y1 = ymin of button;
1095 //metrics_info_.y2 = ymax of button;
1097 // Unfortunately, rowpainter.C:paintText() does not distinguish
1098 // between background updates and text updates. So we use the hammer
1099 // solution for now. We could also avoid the updateMetrics() below
1100 // by using the first and last pit of the CoordCache. Have a look
1101 // at LyXText::getPitNearY() to see what I mean.
1103 //metrics_info_.pit1 = first pit of CoordCache;
1104 //metrics_info_.pit2 = last pit of CoordCache;
1105 //metrics_info_.singlepar = false;
1106 //metrics_info_.y1 = 0;
1107 //metrics_info_.y2 = height_;
1109 updateMetrics(false);
1112 // This event (moving without mouse click) is not passed further.
1113 // This should be changed if it is further utilized.
1117 // Put anchor at the same position.
1120 // Try to dispatch to an non-editable inset near this position
1121 // via the temp cursor. If the inset wishes to change the real
1122 // cursor it has to do so explicitly by using
1123 // cur.bv().cursor() = cur; (or similar)
1125 inset->dispatch(cur, cmd);
1128 // Now dispatch to the temporary cursor. If the real cursor should
1129 // be modified, the inset's dispatch has to do so explicitly.
1130 if (!cur.result().dispatched())
1133 // Redraw if requested and necessary.
1134 if (cur.result().dispatched() && cur.result().update())
1135 return update(cur.result().update());
1141 void BufferView::scroll(int /*lines*/)
1146 // LyXText const * t = &buffer_->text();
1147 // int const line_height = defaultRowHeight();
1149 // // The new absolute coordinate
1150 // int new_top_y = top_y() + lines * line_height;
1152 // // Restrict to a valid value
1153 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1154 // new_top_y = std::max(0, new_top_y);
1156 // scrollDocView(new_top_y);
1158 // // Update the scrollbar.
1159 // workArea_->setScrollbarParams(t->height(), top_y(), defaultRowHeight());}
1163 void BufferView::setCursorFromRow(int row)
1168 buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1171 buffer_->text().setCursor(cursor_, 0, 0);
1173 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1177 void BufferView::gotoLabel(docstring const & label)
1179 for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1180 vector<docstring> labels;
1181 it->getLabelList(*buffer_, labels);
1182 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1191 LyXText * BufferView::getLyXText()
1193 LyXText * text = cursor_.innerText();
1199 LyXText const * BufferView::getLyXText() const
1201 LyXText const * text = cursor_.innerText();
1207 TextMetrics const & BufferView::textMetrics(LyXText const * t) const
1209 return const_cast<BufferView *>(this)->textMetrics(t);
1213 TextMetrics & BufferView::textMetrics(LyXText const * t)
1215 TextMetricsCache::iterator tmc_it = text_metrics_.find(t);
1216 if (tmc_it == text_metrics_.end()) {
1217 tmc_it = text_metrics_.insert(
1218 make_pair(t, TextMetrics(this, const_cast<LyXText *>(t)))).first;
1220 return tmc_it->second;
1224 ParagraphMetrics const & BufferView::parMetrics(LyXText const * t,
1227 return textMetrics(t).parMetrics(pit);
1231 int BufferView::workHeight() const
1237 void BufferView::setCursor(DocIterator const & dit)
1239 size_t const n = dit.depth();
1240 for (size_t i = 0; i < n; ++i)
1241 dit[i].inset().edit(cursor_, true);
1243 cursor_.setCursor(dit);
1244 cursor_.selection() = false;
1248 bool BufferView::checkDepm(LCursor & cur, LCursor & old)
1250 // Would be wrong to delete anything if we have a selection.
1251 if (cur.selection())
1254 bool need_anchor_change = false;
1255 bool changed = cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1256 need_anchor_change);
1258 if (need_anchor_change)
1264 updateMetrics(false);
1270 bool BufferView::mouseSetCursor(LCursor & cur)
1272 BOOST_ASSERT(&cur.bv() == this);
1274 // Has the cursor just left the inset?
1275 bool badcursor = false;
1276 if (&cursor_.inset() != &cur.inset())
1277 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1279 // do the dEPM magic if needed
1280 // FIXME: move this to InsetText::notifyCursorLeaves?
1281 bool update = false;
1282 if (!badcursor && cursor_.inTexted())
1283 checkDepm(cur, cursor_);
1286 cursor_.clearSelection();
1287 cursor_.setTargetX();
1293 void BufferView::putSelectionAt(DocIterator const & cur,
1294 int length, bool backwards)
1296 cursor_.clearSelection();
1302 cursor_.pos() += length;
1303 cursor_.setSelection(cursor_, -length);
1305 cursor_.setSelection(cursor_, length);
1310 LCursor & BufferView::cursor()
1316 LCursor const & BufferView::cursor() const
1322 pit_type BufferView::anchor_ref() const
1328 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1330 return metrics_info_;
1334 // FIXME: We should split-up updateMetrics() for the singlepar case.
1335 void BufferView::updateMetrics(bool singlepar)
1337 LyXText & buftext = buffer_->text();
1338 TextMetrics & tm = textMetrics(&buftext);
1339 pit_type size = int(buftext.paragraphs().size());
1341 if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1342 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1346 // If the paragraph metrics has changed, we can not
1347 // use the singlepar optimisation.
1348 if (singlepar && tm.redoParagraph(cursor_.bottom().pit()))
1351 pit_type const pit = anchor_ref_;
1354 size_t const npit = buftext.paragraphs().size();
1356 // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
1357 // the (main text, not inset!) paragraph containing the cursor.
1358 // (if this paragraph contains insets etc., rebreaking will
1359 // recursively descend)
1360 if (!singlepar || pit == cursor_.bottom().pit())
1361 // If the paragraph metrics has changed, we can not
1362 // use the singlepar optimisation.
1363 if (tm.redoParagraph(pit))
1366 // Clear out the position cache in case of full screen redraw.
1368 coord_cache_.clear();
1370 int y0 = tm.parMetrics(pit).ascent() - offset_ref_;
1372 // Redo paragraphs above anchor if necessary; again, in Single Par
1373 // mode, only if we encounter the (main text) one having the cursor.
1375 while (y1 > 0 && pit1 > 0) {
1376 y1 -= tm.parMetrics(pit1).ascent();
1378 if (!singlepar || pit1 == cursor_.bottom().pit())
1379 tm.redoParagraph(pit1);
1380 y1 -= tm.parMetrics(pit1).descent();
1384 // Take care of ascent of first line
1385 y1 -= tm.parMetrics(pit1).ascent();
1387 // Normalize anchor for next time
1391 // Grey at the beginning is ugly
1392 if (pit1 == 0 && y1 > 0) {
1398 // Redo paragraphs below the anchor if necessary. Single par mode:
1399 // only the one containing the cursor if encountered.
1401 while (y2 < height_ && pit2 < int(npit) - 1) {
1402 y2 += tm.parMetrics(pit2).descent();
1404 if (!singlepar || pit2 == cursor_.bottom().pit())
1405 tm.redoParagraph(pit2);
1406 y2 += tm.parMetrics(pit2).ascent();
1409 // Take care of descent of last line
1410 y2 += tm.parMetrics(pit2).descent();
1412 // The coordinates of all these paragraphs are correct, cache them
1414 CoordCache::InnerParPosCache & parPos = coord_cache_.parPos()[&buftext];
1415 for (pit_type pit = pit1; pit <= pit2; ++pit) {
1416 ParagraphMetrics const & pm = tm.parMetrics(pit);
1418 parPos[pit] = Point(0, y);
1419 if (singlepar && pit == cursor_.bottom().pit()) {
1420 // In Single Paragraph mode, collect here the
1421 // y1 and y2 of the (one) paragraph the cursor is in
1422 y1 = y - pm.ascent();
1423 y2 = y + pm.descent();
1429 // collect cursor paragraph iter bounds
1430 pit1 = cursor_.bottom().pit();
1431 pit2 = cursor_.bottom().pit();
1434 lyxerr[Debug::DEBUG]
1435 << BOOST_CURRENT_FUNCTION
1438 << " pit1: " << pit1
1439 << " pit2: " << pit2
1440 << " npit: " << npit
1441 << " singlepar: " << singlepar
1445 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2, singlepar, size);
1447 if (lyxerr.debugging(Debug::WORKAREA)) {
1448 lyxerr[Debug::WORKAREA] << "BufferView::updateMetrics" << endl;
1449 coord_cache_.dump();
1454 void BufferView::menuInsertLyXFile(string const & filenm)
1456 BOOST_ASSERT(cursor_.inTexted());
1457 string filename = filenm;
1459 if (filename.empty()) {
1460 // Launch a file browser
1462 string initpath = lyxrc.document_path;
1465 string const trypath = buffer_->filePath();
1466 // If directory is writeable, use this as default.
1467 if (isDirWriteable(FileName(trypath)))
1472 FileDialog fileDlg(_("Select LyX document to insert"),
1474 make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1475 make_pair(_("Examples|#E#e"), from_utf8(addPath(package().system_support(), "examples"))));
1477 FileDialog::Result result =
1478 fileDlg.open(from_utf8(initpath),
1479 FileFilterList(_("LyX Documents (*.lyx)")),
1482 if (result.first == FileDialog::Later)
1486 filename = to_utf8(result.second);
1488 // check selected filename
1489 if (filename.empty()) {
1490 // emit message signal.
1491 message(_("Canceled."));
1496 // Get absolute path of file and add ".lyx"
1497 // to the filename if necessary
1498 filename = fileSearch(string(), filename, "lyx").absFilename();
1500 docstring const disp_fn = makeDisplayPath(filename);
1501 // emit message signal.
1502 message(bformat(_("Inserting document %1$s..."), disp_fn));
1505 Buffer buf("", false);
1506 if (lyx::loadLyXFile(&buf, FileName(filename))) {
1507 ErrorList & el = buffer_->errorList("Parse");
1508 // Copy the inserted document error list into the current buffer one.
1509 el = buf.errorList("Parse");
1510 recordUndo(cursor_);
1511 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1512 buf.params().textclass, el);
1513 res = _("Document %1$s inserted.");
1515 res = _("Could not insert document %1$s");
1517 // emit message signal.
1518 message(bformat(res, disp_fn));
1519 buffer_->errors("Parse");