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"
24 #include "CutAndPaste.h"
26 #include "dispatchresult.h"
27 #include "errorlist.h"
29 #include "FloatList.h"
30 #include "funcrequest.h"
31 #include "FuncStatus.h"
34 #include "insetiterator.h"
36 #include "LaTeXFeatures.h"
37 #include "lyx_cb.h" // added for Dispatch functions
41 #include "lyxlayout.h"
43 #include "lyxtextclass.h"
46 #include "paragraph.h"
47 #include "paragraph_funcs.h"
48 #include "ParagraphParameters.h"
49 #include "pariterator.h"
54 #include "WordLangTuple.h"
55 #include "metricsinfo.h"
57 #include "insets/insetbibtex.h"
58 #include "insets/insetcommand.h" // ChangeRefs
59 #include "insets/insetref.h"
60 #include "insets/insettext.h"
62 #include "frontends/Alert.h"
63 #include "frontends/FileDialog.h"
64 #include "frontends/FontMetrics.h"
66 #include "graphics/Previews.h"
68 #include "support/convert.h"
69 #include "support/filefilterlist.h"
70 #include "support/filetools.h"
71 #include "support/package.h"
72 #include "support/types.h"
74 #include <boost/bind.hpp>
75 #include <boost/current_function.hpp>
83 using support::addPath;
84 using support::bformat;
85 using support::FileFilterList;
86 using support::fileSearch;
87 using support::isDirWriteable;
88 using support::makeDisplayPath;
89 using support::makeAbsPath;
90 using support::package;
94 using std::istringstream;
98 using std::mem_fun_ref;
102 namespace Alert = frontend::Alert;
106 /// Return an inset of this class if it exists at the current cursor position
108 T * getInsetByCode(LCursor & cur, InsetBase::Code code)
111 DocIterator it = cur;
112 if (it.nextInset() &&
113 it.nextInset()->lyxCode() == code) {
114 inset = static_cast<T*>(it.nextInset());
122 BufferView::BufferView()
123 : width_(0), height_(0), buffer_(0), wh_(0),
125 multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
128 xsel_cache_.set = false;
129 intl_->initKeyMapper(lyxrc.use_kbmap);
133 BufferView::~BufferView()
138 Buffer * BufferView::buffer() const
144 void BufferView::setBuffer(Buffer * b)
146 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
147 << "[ b = " << b << "]" << endl;
150 // Save the actual cursor position and anchor inside the
151 // buffer so that it can be restored in case we rechange
152 // to this buffer later on.
153 buffer_->saveCursor(cursor_.selectionBegin(),
154 cursor_.selectionEnd());
155 // current buffer is going to be switched-off, save cursor pos
156 LyX::ref().session().lastFilePos().save(buffer_->fileName(),
157 boost::tie(cursor_.pit(), cursor_.pos()) );
160 // If we're quitting lyx, don't bother updating stuff
166 // If we are closing current buffer, switch to the first in
169 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
170 << " No Buffer!" << endl;
171 // We are closing the buffer, use the first buffer as current
172 buffer_ = theBufferList().first();
174 // Set current buffer
179 cursor_ = LCursor(*this);
184 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
185 << "Buffer addr: " << buffer_ << endl;
186 cursor_.push(buffer_->inset());
187 cursor_.resetAnchor();
188 buffer_->text().init(this);
189 buffer_->text().setCurrentFont(cursor_);
190 if (buffer_->getCursor().size() > 0 &&
191 buffer_->getAnchor().size() > 0)
193 cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
194 cursor_.resetAnchor();
195 cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
196 cursor_.setSelection();
201 updateMetrics(false);
203 if (buffer_ && graphics::Previews::status() != LyXRC::PREVIEW_OFF)
204 graphics::Previews::get().generateBufferPreviews(*buffer_);
208 bool BufferView::loadLyXFile(string const & filename, bool tolastfiles)
210 // Get absolute path of file and add ".lyx"
211 // to the filename if necessary
212 string s = fileSearch(string(), filename, "lyx");
214 bool const found = !s.empty();
219 // File already open?
220 if (theBufferList().exists(s)) {
221 docstring const file = makeDisplayPath(s, 20);
222 docstring text = bformat(_("The document %1$s is already "
223 "loaded.\n\nDo you want to revert "
224 "to the saved version?"), file);
225 int const ret = Alert::prompt(_("Revert to saved document?"),
226 text, 0, 1, _("&Revert"), _("&Switch to document"));
229 setBuffer(theBufferList().getBuffer(s));
232 // FIXME: should be LFUN_REVERT
233 if (!theBufferList().close(theBufferList().getBuffer(s), false))
235 // Fall through to new load. (Asger)
242 b = theBufferList().newBuffer(s);
243 if (!lyx::loadLyXFile(b, s)) {
244 theBufferList().release(b);
248 docstring text = bformat(_("The document %1$s does not yet "
249 "exist.\n\nDo you want to create "
250 "a new document?"), from_utf8(s));
251 int const ret = Alert::prompt(_("Create new document?"),
252 text, 0, 1, _("&Create"), _("Cancel"));
255 b = newFile(s, string(), true);
263 // Send the "errors" signal in case of parsing errors
266 // scroll to the position when the file was last closed
267 if (lyxrc.use_lastfilepos) {
270 boost::tie(pit, pos) = LyX::ref().session().lastFilePos().load(s);
271 // I am not sure how to separate the following part to a function
272 // so I will leave this to Lars.
274 // check pit since the document may be externally changed.
275 if ( static_cast<size_t>(pit) < b->paragraphs().size() ) {
276 ParIterator it = b->par_iterator_begin();
277 ParIterator const end = b->par_iterator_end();
278 for (; it != end; ++it)
279 if (it.pit() == pit) {
280 // restored pos may be bigger than it->size
281 setCursor(makeDocIterator(it, min(pos, it->size())));
282 // No need to update the metrics if fitCursor returns false.
284 updateMetrics(false);
291 LyX::ref().session().lastFiles().add(b->fileName());
297 void BufferView::reload()
299 string const fn = buffer_->fileName();
300 if (theBufferList().close(buffer_, false))
305 void BufferView::resize()
310 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
312 buffer_->text().init(this);
318 bool BufferView::fitCursor()
320 if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
321 frontend::FontMetrics const & fm =
322 theFontMetrics(cursor_.getFont());
323 int const asc = fm.maxAscent();
324 int const des = fm.maxDescent();
325 Point const p = bv_funcs::getPos(*this, cursor_, cursor_.boundary());
326 if (p.y_ - asc >= 0 && p.y_ + des < height_)
334 bool BufferView::multiParSel()
336 if (!cursor_.selection())
338 bool ret = multiparsel_cache_;
339 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
340 // Either this, or previous selection spans paragraphs
341 return ret || multiparsel_cache_;
345 std::pair<bool, bool> BufferView::update(Update::flags flags)
347 // This is close to a hot-path.
348 if (lyxerr.debugging(Debug::DEBUG)) {
350 << BOOST_CURRENT_FUNCTION
351 << "[fitcursor = " << (flags & Update::FitCursor)
352 << ", forceupdate = " << (flags & Update::Force)
353 << ", singlepar = " << (flags & Update::SinglePar)
354 << "] buffer: " << buffer_ << endl;
357 // Check needed to survive LyX startup
359 return make_pair(false, false);
361 if (lyxerr.debugging(Debug::WORKAREA)) {
362 lyxerr[Debug::WORKAREA] << "BufferView::update" << std::endl;
365 // Update macro store
366 buffer_->buildMacros();
368 // Now do the first drawing step if needed. This consists on updating
369 // the CoordCache in updateMetrics().
370 // The second drawing step is done in WorkArea::redraw() if needed.
372 // Case when no explicit update is requested.
374 // no need to do anything.
375 return make_pair(false, false);
378 if (flags == Update::FitCursor) {
379 bool const fit_cursor = fitCursor();
381 updateMetrics(false);
382 // tell the frontend to update the screen.
383 return make_pair(fit_cursor, false);
386 bool full_metrics = flags & Update::Force;
387 if (flags & Update::MultiParSel)
388 full_metrics |= multiParSel();
390 bool const single_par = !full_metrics;
391 updateMetrics(single_par);
393 if (flags & Update::FitCursor && fitCursor())
394 updateMetrics(false);
396 // tell the frontend to update the screen.
397 return make_pair(true, single_par);
401 void BufferView::updateScrollbar()
404 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
405 << " no text in updateScrollbar" << endl;
406 scrollbarParameters_.reset();
410 LyXText & t = buffer_->text();
411 int const parsize = int(t.paragraphs().size() - 1);
412 if (anchor_ref_ > parsize) {
413 anchor_ref_ = parsize;
417 if (lyxerr.debugging(Debug::GUI)) {
419 << BOOST_CURRENT_FUNCTION
420 << " Updating scrollbar: height: " << t.paragraphs().size()
421 << " curr par: " << cursor_.bottom().pit()
422 << " default height " << defaultRowHeight() << endl;
425 // It would be better to fix the scrollbar to understand
426 // values in [0..1] and divide everything by wh
428 // estimated average paragraph height:
431 int h = t.getPar(anchor_ref_).height();
433 // Normalize anchor/offset (MV):
434 while (offset_ref_ > h && anchor_ref_ < parsize) {
437 h = t.getPar(anchor_ref_).height();
439 // Look at paragraph heights on-screen
442 for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
445 int const h2 = t.getPar(pit).height();
451 int const hav = sumh / nh;
452 // More realistic average paragraph height
457 scrollbarParameters_.height = (parsize + 1) * wh_;
458 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
459 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
463 ScrollbarParameters const & BufferView::scrollbarParameters() const
465 return scrollbarParameters_;
469 void BufferView::scrollDocView(int value)
471 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
472 << "[ value = " << value << "]" << endl;
477 LyXText & t = buffer_->text();
479 float const bar = value / float(wh_ * t.paragraphs().size());
481 anchor_ref_ = int(bar * t.paragraphs().size());
482 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
483 anchor_ref_ = int(t.paragraphs().size()) - 1;
484 t.redoParagraph(*this, anchor_ref_);
485 int const h = t.getPar(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(
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 pit_type const pit = bot.pit();
583 bot.text()->redoParagraph(*this, pit);
584 Paragraph const & par = bot.text()->paragraphs()[pit];
586 offset_ref_ = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary()).y_
587 + par.ascent() - height_ / 2;
591 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
595 switch (cmd.action) {
598 flag.enabled(!buffer_->undostack().empty());
601 flag.enabled(!buffer_->redostack().empty());
603 case LFUN_FILE_INSERT:
604 case LFUN_FILE_INSERT_ASCII_PARA:
605 case LFUN_FILE_INSERT_ASCII:
606 case LFUN_BOOKMARK_SAVE:
607 // FIXME: Actually, these LFUNS should be moved to LyXText
608 flag.enabled(cursor_.inTexted());
610 case LFUN_FONT_STATE:
611 case LFUN_LABEL_INSERT:
612 case LFUN_PARAGRAPH_GOTO:
613 // FIXME handle non-trivially
614 case LFUN_OUTLINE_UP:
615 case LFUN_OUTLINE_DOWN:
616 case LFUN_OUTLINE_IN:
617 case LFUN_OUTLINE_OUT:
619 case LFUN_REFERENCE_NEXT:
621 case LFUN_WORD_REPLACE:
624 case LFUN_MARK_TOGGLE:
625 case LFUN_SCREEN_RECENTER:
626 case LFUN_BIBTEX_DATABASE_ADD:
627 case LFUN_BIBTEX_DATABASE_DEL:
628 case LFUN_WORDS_COUNT:
629 case LFUN_NEXT_INSET_TOGGLE:
633 case LFUN_LABEL_GOTO: {
634 flag.enabled(!cmd.argument().empty()
635 || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
639 case LFUN_CHANGES_TRACK:
641 flag.setOnOff(buffer_->params().trackChanges);
644 case LFUN_CHANGES_OUTPUT: {
645 OutputParams runparams;
646 LaTeXFeatures features(*buffer_, buffer_->params(), runparams);
647 flag.enabled(buffer_ && features.isAvailable("dvipost"));
648 flag.setOnOff(buffer_->params().outputChanges);
652 case LFUN_CHANGES_MERGE:
653 case LFUN_CHANGE_NEXT:
654 case LFUN_ALL_CHANGES_ACCEPT:
655 case LFUN_ALL_CHANGES_REJECT:
656 // TODO: context-sensitive enabling of LFUNs
657 // In principle, these command should only be enabled if there
658 // is a change in the document. However, without proper
659 // optimizations, this will inevitably result in poor performance.
660 flag.enabled(buffer_);
663 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
664 flag.setOnOff(buffer_->params().compressed);
676 bool BufferView::dispatch(FuncRequest const & cmd)
678 //lyxerr << BOOST_CURRENT_FUNCTION
679 // << [ cmd = " << cmd << "]" << endl;
681 // Make sure that the cached BufferView is correct.
682 lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
683 << " action[" << cmd.action << ']'
684 << " arg[" << to_utf8(cmd.argument()) << ']'
685 << " x[" << cmd.x << ']'
686 << " y[" << cmd.y << ']'
687 << " button[" << cmd.button() << ']'
690 LCursor & cur = cursor_;
692 switch (cmd.action) {
696 cur.message(_("Undo"));
697 cur.clearSelection();
698 if (!textUndo(*this))
699 cur.message(_("No further undo information"));
707 cur.message(_("Redo"));
708 cur.clearSelection();
709 if (!textRedo(*this))
710 cur.message(_("No further redo information"));
716 case LFUN_FILE_INSERT:
717 // FIXME: We don't know the encoding of filenames
718 menuInsertLyXFile(to_utf8(cmd.argument()));
721 case LFUN_FILE_INSERT_ASCII_PARA:
722 // FIXME: We don't know the encoding of filenames
723 insertAsciiFile(this, to_utf8(cmd.argument()), true);
726 case LFUN_FILE_INSERT_ASCII:
727 // FIXME: We don't know the encoding of filenames
728 insertAsciiFile(this, to_utf8(cmd.argument()), false);
731 case LFUN_FONT_STATE:
732 cur.message(from_utf8(cur.currentState()));
735 case LFUN_BOOKMARK_SAVE:
736 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
739 case LFUN_LABEL_GOTO: {
740 docstring label = cmd.argument();
743 getInsetByCode<InsetRef>(cursor_,
744 InsetBase::REF_CODE);
746 label = inset->getParam("reference");
747 // persistent=false: use temp_bookmark
757 case LFUN_PARAGRAPH_GOTO: {
758 int const id = convert<int>(to_utf8(cmd.argument()));
760 for (Buffer * b = buffer_; i == 0 || b != buffer_; b = theBufferList().next(b)) {
761 ParIterator par = b->getParFromID(id);
762 if (par == b->par_iterator_end()) {
764 << "No matching paragraph found! ["
765 << id << "]." << endl;
768 << "Paragraph " << par->id()
769 << " found in buffer `"
770 << b->fileName() << "'." << endl;
774 setCursor(makeDocIterator(par, 0));
778 // Switch to other buffer view and resend cmd
779 theLyXFunc().dispatch(FuncRequest(
780 LFUN_BUFFER_SWITCH, b->fileName()));
781 theLyXFunc().dispatch(cmd);
790 case LFUN_OUTLINE_UP:
791 toc::outline(toc::Up, cursor_);
792 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
793 updateLabels(*buffer_);
795 case LFUN_OUTLINE_DOWN:
796 toc::outline(toc::Down, cursor_);
797 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
798 updateLabels(*buffer_);
800 case LFUN_OUTLINE_IN:
801 toc::outline(toc::In, cursor_);
802 updateLabels(*buffer_);
804 case LFUN_OUTLINE_OUT:
805 toc::outline(toc::Out, cursor_);
806 updateLabels(*buffer_);
810 bv_funcs::gotoInset(this, InsetBase::NOTE_CODE, false);
813 case LFUN_REFERENCE_NEXT: {
814 vector<InsetBase_code> tmp;
815 tmp.push_back(InsetBase::LABEL_CODE);
816 tmp.push_back(InsetBase::REF_CODE);
817 bv_funcs::gotoInset(this, tmp, true);
821 case LFUN_CHANGES_TRACK:
822 buffer_->params().trackChanges = !buffer_->params().trackChanges;
825 case LFUN_CHANGES_OUTPUT: {
826 buffer_->params().outputChanges = !buffer_->params().outputChanges;
830 case LFUN_CHANGE_NEXT:
831 findNextChange(this);
834 case LFUN_CHANGES_MERGE:
835 if (findNextChange(this))
836 showDialog("changes");
839 case LFUN_ALL_CHANGES_ACCEPT: {
840 cursor_.reset(buffer_->inset());
842 #warning FIXME changes
844 while (findNextChange(this))
845 getLyXText()->acceptChange(cursor_);
850 case LFUN_ALL_CHANGES_REJECT: {
851 cursor_.reset(buffer_->inset());
853 #warning FIXME changes
855 while (findNextChange(this))
856 getLyXText()->rejectChange(cursor_);
864 case LFUN_WORD_REPLACE:
869 cur.clearSelection();
871 cur.message(from_utf8(N_("Mark off")));
875 cur.clearSelection();
878 cur.message(from_utf8(N_("Mark on")));
881 case LFUN_MARK_TOGGLE:
882 cur.clearSelection();
885 cur.message(from_utf8(N_("Mark removed")));
888 cur.message(from_utf8(N_("Mark set")));
893 case LFUN_SCREEN_RECENTER:
897 case LFUN_BIBTEX_DATABASE_ADD: {
898 LCursor tmpcur = cursor_;
899 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
900 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
901 InsetBase::BIBTEX_CODE);
903 if (inset->addDatabase(to_utf8(cmd.argument())))
904 buffer_->updateBibfilesCache();
909 case LFUN_BIBTEX_DATABASE_DEL: {
910 LCursor tmpcur = cursor_;
911 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
912 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
913 InsetBase::BIBTEX_CODE);
915 if (inset->delDatabase(to_utf8(cmd.argument())))
916 buffer_->updateBibfilesCache();
921 case LFUN_WORDS_COUNT: {
922 DocIterator from, to;
923 if (cur.selection()) {
924 from = cur.selectionBegin();
925 to = cur.selectionEnd();
927 from = doc_iterator_begin(buffer_->inset());
928 to = doc_iterator_end(buffer_->inset());
930 int const count = countWords(from, to);
934 message = bformat(_("%1$d words in selection."),
937 message = bformat(_("%1$d words in document."),
942 message = _("One word in selection.");
944 message = _("One word in document.");
947 Alert::information(_("Count words"), message);
951 case LFUN_BUFFER_TOGGLE_COMPRESSION:
952 // turn compression on/off
953 buffer_->params().compressed = !buffer_->params().compressed;
956 case LFUN_NEXT_INSET_TOGGLE: {
957 // this is the real function we want to invoke
958 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
959 // if there is an inset at cursor, see whether it
961 InsetBase * inset = cur.nextInset();
962 if (inset && inset->isActive()) {
963 LCursor tmpcur = cur;
964 tmpcur.pushLeft(*inset);
965 inset->dispatch(tmpcur, tmpcmd);
966 if (tmpcur.result().dispatched()) {
970 // if it did not work, try the underlying inset.
971 if (!cur.result().dispatched())
972 cur.dispatch(tmpcmd);
974 if (cur.result().dispatched())
975 cur.clearSelection();
988 docstring const BufferView::requestSelection()
993 LCursor & cur = cursor_;
995 if (!cur.selection()) {
996 xsel_cache_.set = false;
1000 if (!xsel_cache_.set ||
1001 cur.top() != xsel_cache_.cursor ||
1002 cur.anchor_.top() != xsel_cache_.anchor)
1004 xsel_cache_.cursor = cur.top();
1005 xsel_cache_.anchor = cur.anchor_.top();
1006 xsel_cache_.set = cur.selection();
1007 return cur.selectionAsString(false);
1013 void BufferView::clearSelection()
1016 cursor_.clearSelection();
1017 xsel_cache_.set = false;
1022 void BufferView::workAreaResize(int width, int height)
1024 bool const widthChange = width != width_;
1025 bool const heightChange = height != height_;
1027 // Update from work area
1038 std::pair<bool, bool> BufferView::workAreaDispatch(FuncRequest const & cmd0)
1040 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1042 // This is only called for mouse related events including
1043 // LFUN_FILE_OPEN generated by drag-and-drop.
1044 FuncRequest cmd = cmd0;
1046 // E.g. Qt mouse press when no buffer
1048 return make_pair(false, false);
1051 cur.push(buffer_->inset());
1052 cur.selection() = cursor_.selection();
1054 // Either the inset under the cursor or the
1055 // surrounding LyXText will handle this event.
1057 // Build temporary cursor.
1058 cmd.y = min(max(cmd.y, -1), height_);
1059 InsetBase * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1061 //lyxerr << BOOST_CURRENT_FUNCTION
1062 // << " * hit inset at tip: " << inset << endl;
1063 //lyxerr << BOOST_CURRENT_FUNCTION
1064 // << " * created temp cursor:" << cur << endl;
1066 // Put anchor at the same position.
1069 // Try to dispatch to an non-editable inset near this position
1070 // via the temp cursor. If the inset wishes to change the real
1071 // cursor it has to do so explicitly by using
1072 // cur.bv().cursor() = cur; (or similar)
1074 inset->dispatch(cur, cmd);
1077 // Now dispatch to the temporary cursor. If the real cursor should
1078 // be modified, the inset's dispatch has to do so explicitly.
1079 if (!cur.result().dispatched())
1082 // Redraw if requested and necessary.
1083 if (cur.result().dispatched() && cur.result().update())
1084 return update(cur.result().update());
1086 // When the above and the inner function are fixed, we can do this:
1087 return make_pair(false, false);
1091 void BufferView::scroll(int /*lines*/)
1096 // LyXText const * t = &buffer_->text();
1097 // int const line_height = defaultRowHeight();
1099 // // The new absolute coordinate
1100 // int new_top_y = top_y() + lines * line_height;
1102 // // Restrict to a valid value
1103 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1104 // new_top_y = std::max(0, new_top_y);
1106 // scrollDocView(new_top_y);
1108 // // Update the scrollbar.
1109 // workArea_->setScrollbarParams(t->height(), top_y(), defaultRowHeight());}
1113 void BufferView::setCursorFromRow(int row)
1118 buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1121 buffer_->text().setCursor(cursor_, 0, 0);
1123 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1127 void BufferView::gotoLabel(docstring const & label)
1129 for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1130 vector<docstring> labels;
1131 it->getLabelList(*buffer_, labels);
1132 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1141 LyXText * BufferView::getLyXText()
1143 LyXText * text = cursor_.innerText();
1149 LyXText const * BufferView::getLyXText() const
1151 LyXText const * text = cursor_.innerText();
1157 int BufferView::workHeight() const
1163 void BufferView::setCursor(DocIterator const & dit)
1165 size_t const n = dit.depth();
1166 for (size_t i = 0; i < n; ++i)
1167 dit[i].inset().edit(cursor_, true);
1169 cursor_.setCursor(dit);
1170 cursor_.selection() = false;
1174 void BufferView::mouseSetCursor(LCursor & cur)
1176 BOOST_ASSERT(&cur.bv() == this);
1178 // Has the cursor just left the inset?
1179 bool badcursor = false;
1180 if (&cursor_.inset() != &cur.inset())
1181 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1183 // do the dEPM magic if needed
1184 // FIXME: move this to InsetText::notifyCursorLeaves?
1185 if (!badcursor && cursor_.inTexted())
1186 cursor_.text()->deleteEmptyParagraphMechanism(cur, cursor_);
1189 cursor_.clearSelection();
1190 cursor_.setTargetX();
1196 void BufferView::putSelectionAt(DocIterator const & cur,
1197 int length, bool backwards)
1199 cursor_.clearSelection();
1205 cursor_.pos() += length;
1206 cursor_.setSelection(cursor_, -length);
1208 cursor_.setSelection(cursor_, length);
1213 LCursor & BufferView::cursor()
1219 LCursor const & BufferView::cursor() const
1225 pit_type BufferView::anchor_ref() const
1231 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1233 return metrics_info_;
1237 void BufferView::updateMetrics(bool singlepar)
1239 // Clear out the position cache in case of full screen redraw.
1241 coord_cache_.clear();
1243 LyXText & buftext = buffer_->text();
1244 pit_type size = int(buftext.paragraphs().size());
1246 if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1247 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1251 pit_type const pit = anchor_ref_;
1254 size_t const npit = buftext.paragraphs().size();
1256 // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
1257 // the (main text, not inset!) paragraph containing the cursor.
1258 // (if this paragraph contains insets etc., rebreaking will
1259 // recursively descend)
1260 if (!singlepar || pit == cursor_.bottom().pit())
1261 buftext.redoParagraph(*this, pit);
1262 int y0 = buftext.getPar(pit).ascent() - offset_ref_;
1264 // Redo paragraphs above anchor if necessary; again, in Single Par
1265 // mode, only if we encounter the (main text) one having the cursor.
1267 while (y1 > 0 && pit1 > 0) {
1268 y1 -= buftext.getPar(pit1).ascent();
1270 if (!singlepar || pit1 == cursor_.bottom().pit())
1271 buftext.redoParagraph(*this, pit1);
1272 y1 -= buftext.getPar(pit1).descent();
1276 // Take care of ascent of first line
1277 y1 -= buftext.getPar(pit1).ascent();
1279 // Normalize anchor for next time
1283 // Grey at the beginning is ugly
1284 if (pit1 == 0 && y1 > 0) {
1290 // Redo paragraphs below the anchor if necessary. Single par mode:
1291 // only the one containing the cursor if encountered.
1293 while (y2 < height_ && pit2 < int(npit) - 1) {
1294 y2 += buftext.getPar(pit2).descent();
1296 if (!singlepar || pit2 == cursor_.bottom().pit())
1297 buftext.redoParagraph(*this, pit2);
1298 y2 += buftext.getPar(pit2).ascent();
1301 // Take care of descent of last line
1302 y2 += buftext.getPar(pit2).descent();
1304 // The coordinates of all these paragraphs are correct, cache them
1306 CoordCache::InnerParPosCache & parPos = coord_cache_.parPos()[&buftext];
1307 for (pit_type pit = pit1; pit <= pit2; ++pit) {
1308 Paragraph const & par = buftext.getPar(pit);
1310 parPos[pit] = Point(0, y);
1311 if (singlepar && pit == cursor_.bottom().pit()) {
1312 // In Single Paragraph mode, collect here the
1313 // y1 and y2 of the (one) paragraph the cursor is in
1314 y1 = y - par.ascent();
1315 y2 = y + par.descent();
1321 // collect cursor paragraph iter bounds
1322 pit1 = cursor_.bottom().pit();
1323 pit2 = cursor_.bottom().pit();
1326 lyxerr[Debug::DEBUG]
1327 << BOOST_CURRENT_FUNCTION
1330 << " pit1: " << pit1
1331 << " pit2: " << pit2
1332 << " npit: " << npit
1333 << " singlepar: " << singlepar
1337 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2, singlepar, size);
1339 if (lyxerr.debugging(Debug::WORKAREA)) {
1340 lyxerr[Debug::WORKAREA] << "BufferView::updateMetrics" << endl;
1341 coord_cache_.dump();
1346 void BufferView::menuInsertLyXFile(string const & filenm)
1348 BOOST_ASSERT(cursor_.inTexted());
1349 string filename = filenm;
1351 if (filename.empty()) {
1352 // Launch a file browser
1354 string initpath = lyxrc.document_path;
1357 string const trypath = buffer_->filePath();
1358 // If directory is writeable, use this as default.
1359 if (isDirWriteable(trypath))
1364 FileDialog fileDlg(_("Select LyX document to insert"),
1366 make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1367 make_pair(_("Examples|#E#e"), from_utf8(addPath(package().system_support(), "examples"))));
1369 FileDialog::Result result =
1370 fileDlg.open(from_utf8(initpath),
1371 FileFilterList(_("LyX Documents (*.lyx)")),
1374 if (result.first == FileDialog::Later)
1378 filename = to_utf8(result.second);
1380 // check selected filename
1381 if (filename.empty()) {
1382 // emit message signal.
1383 message(_("Canceled."));
1388 // Get absolute path of file and add ".lyx"
1389 // to the filename if necessary
1390 filename = fileSearch(string(), filename, "lyx");
1392 docstring const disp_fn = makeDisplayPath(filename);
1393 // emit message signal.
1394 message(bformat(_("Inserting document %1$s..."), disp_fn));
1397 Buffer buf("", false);
1398 if (lyx::loadLyXFile(&buf, makeAbsPath(filename))) {
1399 ErrorList & el = buffer_->errorList("Parse");
1400 // Copy the inserted document error list into the current buffer one.
1401 el = buf.errorList("Parse");
1402 recordUndo(cursor_);
1403 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1404 buf.params().textclass, el);
1405 res = _("Document %1$s inserted.");
1407 res = _("Could not insert document %1$s");
1409 // emit message signal.
1410 message(bformat(res, disp_fn));
1411 buffer_->errors("Parse");