2 * \file BufferView_pimpl.C
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Asger Alstrup
7 * \author Alfredo Braunstein
8 * \author Lars Gullik Bjønnes
9 * \author Jean-Marc Lasgouttes
10 * \author Angus Leeming
12 * \author André Pönitz
14 * \author Jürgen Vigna
16 * Full author contact details are available in file CREDITS.
21 #include "BufferView_pimpl.h"
23 #include "buffer_funcs.h"
24 #include "bufferlist.h"
25 #include "bufferparams.h"
26 #include "coordcache.h"
29 #include "dispatchresult.h"
31 #include "FloatList.h"
32 #include "funcrequest.h"
33 #include "FuncStatus.h"
36 #include "insetiterator.h"
37 #include "LaTeXFeatures.h"
38 #include "lyx_cb.h" // added for Dispatch functions
44 #include "lastfiles.h"
45 #include "metricsinfo.h"
46 #include "paragraph.h"
47 #include "paragraph_funcs.h"
48 #include "ParagraphParameters.h"
49 #include "pariterator.h"
50 #include "rowpainter.h"
54 #include "insets/insetbibtex.h"
55 #include "insets/insetref.h"
56 #include "insets/insettext.h"
58 #include "frontends/Alert.h"
59 #include "frontends/Dialogs.h"
60 #include "frontends/FileDialog.h"
61 #include "frontends/font_metrics.h"
62 #include "frontends/LyXView.h"
63 #include "frontends/LyXScreenFactory.h"
64 #include "frontends/screen.h"
65 #include "frontends/WorkArea.h"
66 #include "frontends/WorkAreaFactory.h"
68 #include "graphics/Previews.h"
70 #include "support/convert.h"
71 #include "support/filefilterlist.h"
72 #include "support/filetools.h"
73 #include "support/forkedcontr.h"
74 #include "support/package.h"
75 #include "support/types.h"
77 #include <boost/bind.hpp>
78 #include <boost/current_function.hpp>
85 using lyx::support::AddPath;
86 using lyx::support::bformat;
87 using lyx::support::FileFilterList;
88 using lyx::support::FileSearch;
89 using lyx::support::ForkedcallsController;
90 using lyx::support::IsDirWriteable;
91 using lyx::support::MakeDisplayPath;
92 using lyx::support::MakeAbsPath;
93 using lyx::support::package;
96 using std::istringstream;
101 using std::mem_fun_ref;
105 extern BufferList bufferlist;
110 unsigned int const saved_positions_num = 20;
112 // All the below connection objects are needed because of a bug in some
113 // versions of GCC (<=2.96 are on the suspects list.) By having and assigning
114 // to these connections we avoid a segfault upon startup, and also at exit.
117 boost::signals::connection dispatchcon;
118 boost::signals::connection timecon;
119 boost::signals::connection doccon;
120 boost::signals::connection resizecon;
121 boost::signals::connection kpresscon;
122 boost::signals::connection selectioncon;
123 boost::signals::connection lostcon;
126 /// Return an inset of this class if it exists at the current cursor position
128 T * getInsetByCode(LCursor & cur, InsetBase::Code code)
131 DocIterator it = cur;
132 if (it.nextInset() &&
133 it.nextInset()->lyxCode() == code) {
134 inset = static_cast<T*>(it.nextInset());
142 BufferView::Pimpl::Pimpl(BufferView & bv, LyXView * owner,
143 int width, int height)
144 : bv_(&bv), owner_(owner), buffer_(0), cursor_timeout(400),
145 using_xterm_cursor(false), cursor_(bv) ,
146 anchor_ref_(0), offset_ref_(0)
148 xsel_cache_.set = false;
150 workarea_.reset(WorkAreaFactory::create(*owner_, width, height));
151 screen_.reset(LyXScreenFactory::create(workarea()));
154 doccon = workarea().scrollDocView
155 .connect(boost::bind(&BufferView::Pimpl::scrollDocView, this, _1));
156 resizecon = workarea().workAreaResize
157 .connect(boost::bind(&BufferView::Pimpl::workAreaResize, this));
158 dispatchcon = workarea().dispatch
159 .connect(boost::bind(&BufferView::Pimpl::workAreaDispatch, this, _1));
160 kpresscon = workarea().workAreaKeyPress
161 .connect(boost::bind(&BufferView::Pimpl::workAreaKeyPress, this, _1, _2));
162 selectioncon = workarea().selectionRequested
163 .connect(boost::bind(&BufferView::Pimpl::selectionRequested, this));
164 lostcon = workarea().selectionLost
165 .connect(boost::bind(&BufferView::Pimpl::selectionLost, this));
167 timecon = cursor_timeout.timeout
168 .connect(boost::bind(&BufferView::Pimpl::cursorToggle, this));
169 cursor_timeout.start();
170 saved_positions.resize(saved_positions_num);
174 void BufferView::Pimpl::addError(ErrorItem const & ei)
176 errorlist_.push_back(ei);
180 void BufferView::Pimpl::showReadonly(bool)
182 owner_->updateWindowTitle();
183 owner_->getDialogs().updateBufferDependent(false);
187 void BufferView::Pimpl::connectBuffer(Buffer & buf)
189 if (errorConnection_.connected())
194 boost::bind(&BufferView::Pimpl::addError, this, _1));
198 boost::bind(&LyXView::message, owner_, _1));
202 boost::bind(&LyXView::busy, owner_, _1));
205 buf.updateTitles.connect(
206 boost::bind(&LyXView::updateWindowTitle, owner_));
209 buf.resetAutosaveTimers.connect(
210 boost::bind(&LyXView::resetAutosaveTimer, owner_));
212 readonlyConnection_ =
213 buf.readonly.connect(
214 boost::bind(&BufferView::Pimpl::showReadonly, this, _1));
218 boost::bind(&BufferView::Pimpl::setBuffer, this, (Buffer *)0));
222 void BufferView::Pimpl::disconnectBuffer()
224 errorConnection_.disconnect();
225 messageConnection_.disconnect();
226 busyConnection_.disconnect();
227 titleConnection_.disconnect();
228 timerConnection_.disconnect();
229 readonlyConnection_.disconnect();
230 closingConnection_.disconnect();
234 void BufferView::Pimpl::newFile(string const & filename, string const & tname,
237 setBuffer(::newFile(filename, tname, isNamed));
241 bool BufferView::Pimpl::loadLyXFile(string const & filename, bool tolastfiles)
243 // Get absolute path of file and add ".lyx"
244 // to the filename if necessary
245 string s = FileSearch(string(), filename, "lyx");
247 bool const found = !s.empty();
252 // File already open?
253 if (bufferlist.exists(s)) {
254 string const file = MakeDisplayPath(s, 20);
255 string text = bformat(_("The document %1$s is already "
256 "loaded.\n\nDo you want to revert "
257 "to the saved version?"), file);
258 int const ret = Alert::prompt(_("Revert to saved document?"),
259 text, 0, 1, _("&Revert"), _("&Switch to document"));
262 setBuffer(bufferlist.getBuffer(s));
265 // FIXME: should be LFUN_REVERT
266 if (!bufferlist.close(bufferlist.getBuffer(s), false))
268 // Fall through to new load. (Asger)
274 b = bufferlist.newBuffer(s);
276 if (!::loadLyXFile(b, s)) {
277 bufferlist.release(b);
281 string text = bformat(_("The document %1$s does not yet "
282 "exist.\n\nDo you want to create "
283 "a new document?"), s);
284 int const ret = Alert::prompt(_("Create new document?"),
285 text, 0, 1, _("&Create"), _("Cancel"));
288 b = ::newFile(s, string(), true);
294 bv_->showErrorList(_("Parse"));
297 LyX::ref().lastfiles().newFile(b->fileName());
303 WorkArea & BufferView::Pimpl::workarea() const
305 return *workarea_.get();
309 LyXScreen & BufferView::Pimpl::screen() const
311 return *screen_.get();
315 Painter & BufferView::Pimpl::painter() const
317 return workarea().getPainter();
321 void BufferView::Pimpl::setBuffer(Buffer * b)
323 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
324 << "[ b = " << b << "]" << endl;
328 // Save the actual cursor position and anchor inside the
329 // buffer so that it can be restored in case we rechange
330 // to this buffer later on.
331 buffer_->saveCursor(cursor_.selectionBegin(),
332 cursor_.selectionEnd());
335 // If we are closing current buffer, switch to the first in
338 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
339 << " No Buffer!" << endl;
340 // We are closing the buffer, use the first buffer as current
341 buffer_ = bufferlist.first();
342 owner_->getDialogs().hideBufferDependent();
344 // Set current buffer
349 cursor_ = LCursor(*bv_);
354 // If we're quitting lyx, don't bother updating stuff
359 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
360 << "Buffer addr: " << buffer_ << endl;
361 connectBuffer(*buffer_);
362 cursor_.push(buffer_->inset());
363 cursor_.resetAnchor();
364 buffer_->text().init(bv_);
365 buffer_->text().setCurrentFont(cursor_);
366 if (buffer_->getCursor().size() > 0 &&
367 buffer_->getAnchor().size() > 0)
369 cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
370 cursor_.resetAnchor();
371 cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
372 cursor_.setSelection();
375 // Buffer-dependent dialogs should be updated or
376 // hidden. This should go here because some dialogs (eg ToC)
377 // require bv_->text.
378 owner_->getDialogs().updateBufferDependent(true);
383 owner_->updateMenubar();
384 owner_->updateToolbars();
385 owner_->updateLayoutChoice();
386 owner_->updateWindowTitle();
388 // This is done after the layout combox has been populated
390 owner_->setLayout(cursor_.paragraph().layout()->name());
392 if (buffer_ && lyx::graphics::Previews::status() != LyXRC::PREVIEW_OFF)
393 lyx::graphics::Previews::get().generateBufferPreviews(*buffer_);
397 void BufferView::Pimpl::resizeCurrentBuffer()
399 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
401 owner_->message(_("Formatting document..."));
403 LyXText * text = bv_->text();
413 // Reset the "Formatting..." message
414 owner_->clearMessage();
420 void BufferView::Pimpl::updateScrollbar()
423 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
424 << " no text in updateScrollbar" << endl;
425 workarea().setScrollbarParams(0, 0, 0);
429 LyXText & t = *bv_->text();
430 if (anchor_ref_ > int(t.paragraphs().size()) - 1) {
431 anchor_ref_ = int(t.paragraphs().size()) - 1;
436 << BOOST_CURRENT_FUNCTION
437 << " Updating scrollbar: height: " << t.paragraphs().size()
438 << " curr par: " << cursor_.bottom().pit()
439 << " default height " << defaultRowHeight() << endl;
441 // It would be better to fix the scrollbar to understand
442 // values in [0..1] and divide everything by wh
443 int const wh = workarea().workHeight() / 4;
444 int const h = t.getPar(anchor_ref_).height();
445 workarea().setScrollbarParams(t.paragraphs().size() * wh, anchor_ref_ * wh + int(offset_ref_ * wh / float(h)), int (wh * defaultRowHeight() / float(h)));
446 // workarea().setScrollbarParams(t.paragraphs().size(), anchor_ref_, 1);
450 void BufferView::Pimpl::scrollDocView(int value)
452 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
453 << "[ value = " << value << "]" << endl;
458 screen().hideCursor();
460 int const wh = workarea().workHeight() / 4;
462 LyXText & t = *bv_->text();
464 float const bar = value / float(wh * t.paragraphs().size());
466 anchor_ref_ = int(bar * t.paragraphs().size());
467 t.redoParagraph(anchor_ref_);
468 int const h = t.getPar(anchor_ref_).height();
469 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
472 if (!lyxrc.cursor_follows_scrollbar)
475 int const height = 2 * defaultRowHeight();
476 int const first = height;
477 int const last = workarea().workHeight() - height;
478 LCursor & cur = cursor_;
480 bv_funcs::CurStatus st = bv_funcs::status(bv_, cur);
483 case bv_funcs::CUR_ABOVE:
484 t.setCursorFromCoordinates(cur, 0, first);
485 cur.clearSelection();
487 case bv_funcs::CUR_BELOW:
488 t.setCursorFromCoordinates(cur, 0, last);
489 cur.clearSelection();
491 case bv_funcs::CUR_INSIDE:
492 int const y = bv_funcs::getPos(cur, cur.boundary()).y_;
493 int const newy = min(last, max(y, first));
495 cur.reset(buffer_->inset());
496 t.setCursorFromCoordinates(cur, 0, newy);
499 owner_->updateLayoutChoice();
503 void BufferView::Pimpl::scroll(int /*lines*/)
508 // LyXText const * t = bv_->text();
509 // int const line_height = defaultRowHeight();
511 // // The new absolute coordinate
512 // int new_top_y = top_y() + lines * line_height;
514 // // Restrict to a valid value
515 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
516 // new_top_y = std::max(0, new_top_y);
518 // scrollDocView(new_top_y);
520 // // Update the scrollbar.
521 // workarea().setScrollbarParams(t->height(), top_y(), defaultRowHeight());
525 void BufferView::Pimpl::workAreaKeyPress(LyXKeySymPtr key,
526 key_modifier::state state)
528 owner_->getLyXFunc().processKeySym(key, state);
530 /* This is perhaps a bit of a hack. When we move
531 * around, or type, it's nice to be able to see
532 * the cursor immediately after the keypress. So
533 * we reset the toggle timeout and force the visibility
534 * of the cursor. Note we cannot do this inside
535 * dispatch() itself, because that's called recursively.
538 screen().showCursor(*bv_);
542 void BufferView::Pimpl::selectionRequested()
549 LCursor & cur = cursor_;
551 if (!cur.selection()) {
552 xsel_cache_.set = false;
556 if (!xsel_cache_.set ||
557 cur.top() != xsel_cache_.cursor ||
558 cur.anchor_.top() != xsel_cache_.anchor)
560 xsel_cache_.cursor = cur.top();
561 xsel_cache_.anchor = cur.anchor_.top();
562 xsel_cache_.set = cur.selection();
563 sel = cur.selectionAsString(false);
565 workarea().putClipboard(sel);
570 void BufferView::Pimpl::selectionLost()
573 screen().hideCursor();
574 cursor_.clearSelection();
575 xsel_cache_.set = false;
580 void BufferView::Pimpl::workAreaResize()
582 static int work_area_width;
583 static int work_area_height;
585 bool const widthChange = workarea().workWidth() != work_area_width;
586 bool const heightChange = workarea().workHeight() != work_area_height;
588 // Update from work area
589 work_area_width = workarea().workWidth();
590 work_area_height = workarea().workHeight();
592 if (buffer_ && widthChange) {
593 // The visible LyXView need a resize
594 resizeCurrentBuffer();
597 if (widthChange || heightChange)
600 // Always make sure that the scrollbar is sane.
602 owner_->updateLayoutChoice();
606 bool BufferView::Pimpl::fitCursor()
608 if (bv_funcs::status(bv_, cursor_) == bv_funcs::CUR_INSIDE) {
609 LyXFont const font = cursor_.getFont();
610 int const asc = font_metrics::maxAscent(font);
611 int const des = font_metrics::maxDescent(font);
612 Point const p = bv_funcs::getPos(cursor_, cursor_.boundary());
613 if (p.y_ - asc >= 0 && p.y_ + des < workarea().workHeight())
621 void BufferView::Pimpl::update(Update::flags flags)
624 << BOOST_CURRENT_FUNCTION
625 << "[fitcursor = " << (flags & Update::FitCursor)
626 << ", forceupdate = " << (flags & Update::Force)
627 << ", singlepar = " << (flags & Update::SinglePar)
628 << "] buffer: " << buffer_ << endl;
630 // Check needed to survive LyX startup
632 // Update macro store
633 buffer_->buildMacros();
636 std::swap(theCoords, backup);
638 // This, together with doneUpdating(), verifies (using
639 // asserts) that screen redraw is not called from
641 theCoords.startUpdating();
643 // First drawing step
644 ViewMetricsInfo vi = metrics();
645 bool forceupdate(flags & Update::Force);
647 if ((flags & Update::FitCursor) && fitCursor()) {
649 vi = metrics(flags & Update::SinglePar);
652 // Second drawing step
653 screen().redraw(*bv_, vi);
655 // Abort updating of the coord
656 // cache - just restore the old one
657 std::swap(theCoords, backup);
664 owner_->view_state_changed();
668 // Callback for cursor timer
669 void BufferView::Pimpl::cursorToggle()
672 screen().toggleCursor(*bv_);
674 // Use this opportunity to deal with any child processes that
675 // have finished but are waiting to communicate this fact
676 // to the rest of LyX.
677 ForkedcallsController & fcc = ForkedcallsController::get();
678 fcc.handleCompletedProcesses();
681 cursor_timeout.restart();
685 bool BufferView::Pimpl::available() const
687 return buffer_ && bv_->text();
691 Change const BufferView::Pimpl::getCurrentChange()
693 if (!buffer_->params().tracking_changes)
694 return Change(Change::UNCHANGED);
696 LyXText * text = bv_->getLyXText();
697 LCursor & cur = cursor_;
699 if (!cur.selection())
700 return Change(Change::UNCHANGED);
702 return text->getPar(cur.selBegin().pit()).
703 lookupChangeFull(cur.selBegin().pos());
707 void BufferView::Pimpl::savePosition(unsigned int i)
709 if (i >= saved_positions_num)
711 BOOST_ASSERT(cursor_.inTexted());
712 saved_positions[i] = Position(buffer_->fileName(),
713 cursor_.paragraph().id(),
716 owner_->message(bformat(_("Saved bookmark %1$d"), i));
720 void BufferView::Pimpl::restorePosition(unsigned int i)
722 if (i >= saved_positions_num)
725 string const fname = saved_positions[i].filename;
727 cursor_.clearSelection();
729 if (fname != buffer_->fileName()) {
731 if (bufferlist.exists(fname))
732 b = bufferlist.getBuffer(fname);
734 b = bufferlist.newBuffer(fname);
735 // Don't ask, just load it
736 ::loadLyXFile(b, fname);
742 ParIterator par = buffer_->getParFromID(saved_positions[i].par_id);
743 if (par == buffer_->par_iterator_end())
746 bv_->setCursor(makeDocIterator(par, min(par->size(), saved_positions[i].par_pos)));
749 owner_->message(bformat(_("Moved to bookmark %1$d"), i));
753 bool BufferView::Pimpl::isSavedPosition(unsigned int i)
755 return i < saved_positions_num && !saved_positions[i].filename.empty();
759 void BufferView::Pimpl::switchKeyMap()
761 if (!lyxrc.rtl_support)
764 Intl & intl = owner_->getIntl();
765 if (bv_->getLyXText()->real_current_font.isRightToLeft()) {
766 if (intl.keymap == Intl::PRIMARY)
769 if (intl.keymap == Intl::SECONDARY)
775 void BufferView::Pimpl::center()
777 CursorSlice & bot = cursor_.bottom();
778 lyx::pit_type const pit = bot.pit();
779 bot.text()->redoParagraph(pit);
780 Paragraph const & par = bot.text()->paragraphs()[pit];
782 offset_ref_ = bv_funcs::coordOffset(cursor_, cursor_.boundary()).y_
783 + par.ascent() - workarea().workHeight() / 2;
787 void BufferView::Pimpl::stuffClipboard(string const & content) const
789 workarea().putClipboard(content);
793 void BufferView::Pimpl::MenuInsertLyXFile(string const & filenm)
795 string filename = filenm;
797 if (filename.empty()) {
798 // Launch a file browser
799 string initpath = lyxrc.document_path;
802 string const trypath = owner_->buffer()->filePath();
803 // If directory is writeable, use this as default.
804 if (IsDirWriteable(trypath))
808 FileDialog fileDlg(_("Select LyX document to insert"),
810 make_pair(string(_("Documents|#o#O")),
811 string(lyxrc.document_path)),
812 make_pair(string(_("Examples|#E#e")),
813 string(AddPath(package().system_support(), "examples"))));
815 FileDialog::Result result =
816 fileDlg.open(initpath,
817 FileFilterList(_("LyX Documents (*.lyx)")),
820 if (result.first == FileDialog::Later)
823 filename = result.second;
825 // check selected filename
826 if (filename.empty()) {
827 owner_->message(_("Canceled."));
832 // Get absolute path of file and add ".lyx"
833 // to the filename if necessary
834 filename = FileSearch(string(), filename, "lyx");
836 string const disp_fn = MakeDisplayPath(filename);
837 owner_->message(bformat(_("Inserting document %1$s..."), disp_fn));
839 cursor_.clearSelection();
840 bv_->getLyXText()->breakParagraph(cursor_);
842 BOOST_ASSERT(cursor_.inTexted());
844 string const fname = MakeAbsPath(filename);
845 bool const res = buffer_->readFile(fname, cursor_.pit());
846 resizeCurrentBuffer();
848 string s = res ? _("Document %1$s inserted.")
849 : _("Could not insert document %1$s");
850 owner_->message(bformat(s, disp_fn));
854 void BufferView::Pimpl::trackChanges()
856 bool const tracking = buffer_->params().tracking_changes;
859 for_each(buffer_->par_iterator_begin(),
860 buffer_->par_iterator_end(),
861 bind(&Paragraph::trackChanges, _1, Change::UNCHANGED));
862 buffer_->params().tracking_changes = true;
864 // We cannot allow undos beyond the freeze point
865 buffer_->undostack().clear();
868 bv_->text()->setCursor(cursor_, 0, 0);
870 #warning changes FIXME
872 bool const found = lyx::find::findNextChange(bv_);
874 owner_->getDialogs().show("changes");
878 for_each(buffer_->par_iterator_begin(),
879 buffer_->par_iterator_end(),
880 mem_fun_ref(&Paragraph::untrackChanges));
882 buffer_->params().tracking_changes = false;
885 buffer_->redostack().clear();
889 bool BufferView::Pimpl::workAreaDispatch(FuncRequest const & cmd0)
891 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
893 // This is only called for mouse related events including
894 // LFUN_FILE_OPEN generated by drag-and-drop.
895 FuncRequest cmd = cmd0;
898 if (cmd.action == LFUN_FILE_OPEN) {
899 owner_->dispatch(cmd);
907 cur.push(buffer_->inset());
908 cur.selection() = cursor_.selection();
910 // Doesn't go through lyxfunc, so we need to update
911 // the layout choice etc. ourselves
913 // E.g. Qt mouse press when no buffer
917 screen().hideCursor();
919 // Either the inset under the cursor or the
920 // surrounding LyXText will handle this event.
922 // Build temporary cursor.
923 cmd.y = min(max(cmd.y,-1), workarea().workHeight());
924 InsetBase * inset = bv_->text()->editXY(cur, cmd.x, cmd.y);
925 //lyxerr << BOOST_CURRENT_FUNCTION
926 // << " * hit inset at tip: " << inset << endl;
927 //lyxerr << BOOST_CURRENT_FUNCTION
928 // << " * created temp cursor:" << cur << endl;
930 // Put anchor at the same position.
933 // Try to dispatch to an non-editable inset near this position
934 // via the temp cursor. If the inset wishes to change the real
935 // cursor it has to do so explicitly by using
936 // cur.bv().cursor() = cur; (or similar)
938 inset->dispatch(cur, cmd);
940 // Now dispatch to the temporary cursor. If the real cursor should
941 // be modified, the inset's dispatch has to do so explicitly.
942 if (!cur.result().dispatched())
945 if (cur.result().dispatched()) {
946 // Redraw if requested or necessary.
947 if (cur.result().update())
948 update(Update::FitCursor | Update::Force);
953 // See workAreaKeyPress
954 cursor_timeout.restart();
955 screen().showCursor(*bv_);
957 // Skip these when selecting
958 if (cmd.action != LFUN_MOUSE_MOTION) {
959 owner_->updateLayoutChoice();
960 owner_->updateToolbars();
963 // Slight hack: this is only called currently when we
964 // clicked somewhere, so we force through the display
965 // of the new status here.
966 owner_->clearMessage();
971 FuncStatus BufferView::Pimpl::getStatus(FuncRequest const & cmd)
975 switch (cmd.action) {
978 flag.enabled(!buffer_->undostack().empty());
981 flag.enabled(!buffer_->redostack().empty());
983 case LFUN_FILE_INSERT:
984 case LFUN_FILE_INSERT_ASCII_PARA:
985 case LFUN_FILE_INSERT_ASCII:
986 case LFUN_FONT_STATE:
987 case LFUN_INSERT_LABEL:
988 case LFUN_BOOKMARK_SAVE:
989 case LFUN_GOTO_PARAGRAPH:
992 case LFUN_REFERENCE_GOTO:
994 case LFUN_WORD_REPLACE:
1000 case LFUN_BIBDB_DEL:
1001 case LFUN_WORDS_COUNT:
1005 case LFUN_LABEL_GOTO: {
1006 flag.enabled(!cmd.argument.empty()
1007 || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
1011 case LFUN_BOOKMARK_GOTO:
1012 flag.enabled(isSavedPosition(convert<unsigned int>(cmd.argument)));
1014 case LFUN_TRACK_CHANGES:
1016 flag.setOnOff(buffer_->params().tracking_changes);
1019 case LFUN_OUTPUT_CHANGES: {
1020 LaTeXFeatures features(*buffer_, buffer_->params(), false);
1021 flag.enabled(buffer_ && buffer_->params().tracking_changes
1022 && features.isAvailable("dvipost"));
1023 flag.setOnOff(buffer_->params().output_changes);
1027 case LFUN_MERGE_CHANGES:
1028 case LFUN_ACCEPT_CHANGE: // what about these two
1029 case LFUN_REJECT_CHANGE: // what about these two
1030 case LFUN_ACCEPT_ALL_CHANGES:
1031 case LFUN_REJECT_ALL_CHANGES:
1032 flag.enabled(buffer_ && buffer_->params().tracking_changes);
1035 flag.enabled(false);
1043 bool BufferView::Pimpl::dispatch(FuncRequest const & cmd)
1045 //lyxerr << BOOST_CURRENT_FUNCTION
1046 // << [ cmd = " << cmd << "]" << endl;
1048 // Make sure that the cached BufferView is correct.
1049 lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
1050 << " action[" << cmd.action << ']'
1051 << " arg[" << cmd.argument << ']'
1052 << " x[" << cmd.x << ']'
1053 << " y[" << cmd.y << ']'
1054 << " button[" << cmd.button() << ']'
1057 LCursor & cur = cursor_;
1059 switch (cmd.action) {
1063 cur.message(_("Undo"));
1064 cur.clearSelection();
1065 if (!textUndo(*bv_))
1066 cur.message(_("No further undo information"));
1074 cur.message(_("Redo"));
1075 cur.clearSelection();
1076 if (!textRedo(*bv_))
1077 cur.message(_("No further redo information"));
1083 case LFUN_FILE_INSERT:
1084 MenuInsertLyXFile(cmd.argument);
1087 case LFUN_FILE_INSERT_ASCII_PARA:
1088 InsertAsciiFile(bv_, cmd.argument, true);
1091 case LFUN_FILE_INSERT_ASCII:
1092 InsertAsciiFile(bv_, cmd.argument, false);
1095 case LFUN_FONT_STATE:
1096 cur.message(cur.currentState());
1099 case LFUN_BOOKMARK_SAVE:
1100 savePosition(convert<unsigned int>(cmd.argument));
1103 case LFUN_BOOKMARK_GOTO:
1104 restorePosition(convert<unsigned int>(cmd.argument));
1107 case LFUN_LABEL_GOTO: {
1108 string label = cmd.argument;
1109 if (label.empty()) {
1111 getInsetByCode<InsetRef>(cursor_,
1112 InsetBase::REF_CODE);
1114 label = inset->getContents();
1120 bv_->gotoLabel(label);
1124 case LFUN_GOTO_PARAGRAPH: {
1125 int const id = convert<int>(cmd.argument);
1126 ParIterator par = buffer_->getParFromID(id);
1127 if (par == buffer_->par_iterator_end()) {
1128 lyxerr[Debug::INFO] << "No matching paragraph found! ["
1129 << id << ']' << endl;
1132 lyxerr[Debug::INFO] << "Paragraph " << par->id()
1133 << " found." << endl;
1137 bv_->setCursor(makeDocIterator(par, 0));
1144 case LFUN_GOTOERROR:
1145 bv_funcs::gotoInset(bv_, InsetBase::ERROR_CODE, false);
1149 bv_funcs::gotoInset(bv_, InsetBase::NOTE_CODE, false);
1152 case LFUN_REFERENCE_GOTO: {
1153 vector<InsetBase_code> tmp;
1154 tmp.push_back(InsetBase::LABEL_CODE);
1155 tmp.push_back(InsetBase::REF_CODE);
1156 bv_funcs::gotoInset(bv_, tmp, true);
1160 case LFUN_TRACK_CHANGES:
1164 case LFUN_OUTPUT_CHANGES: {
1165 bool const state = buffer_->params().output_changes;
1166 buffer_->params().output_changes = !state;
1170 case LFUN_MERGE_CHANGES:
1171 owner_->getDialogs().show("changes");
1174 case LFUN_ACCEPT_ALL_CHANGES: {
1175 cursor_.reset(buffer_->inset());
1176 #ifdef WITH_WARNINGS
1177 #warning FIXME changes
1179 while (lyx::find::findNextChange(bv_))
1180 bv_->getLyXText()->acceptChange(cursor_);
1185 case LFUN_REJECT_ALL_CHANGES: {
1186 cursor_.reset(buffer_->inset());
1187 #ifdef WITH_WARNINGS
1188 #warning FIXME changes
1190 while (lyx::find::findNextChange(bv_))
1191 bv_->getLyXText()->rejectChange(cursor_);
1195 case LFUN_WORD_FIND:
1196 lyx::find::find(bv_, cmd);
1199 case LFUN_WORD_REPLACE:
1200 lyx::find::replace(bv_, cmd);
1204 cur.clearSelection();
1206 cur.message(N_("Mark off"));
1210 cur.clearSelection();
1213 cur.message(N_("Mark on"));
1217 cur.clearSelection();
1220 cur.message(N_("Mark removed"));
1223 cur.message(N_("Mark set"));
1232 case LFUN_BIBDB_ADD: {
1233 LCursor tmpcur = cursor_;
1234 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
1235 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1236 InsetBase::BIBTEX_CODE);
1238 inset->addDatabase(cmd.argument);
1242 case LFUN_BIBDB_DEL: {
1243 LCursor tmpcur = cursor_;
1244 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
1245 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1246 InsetBase::BIBTEX_CODE);
1248 inset->delDatabase(cmd.argument);
1252 case LFUN_WORDS_COUNT: {
1253 DocIterator from, to;
1254 if (cur.selection()) {
1255 from = cur.selectionBegin();
1256 to = cur.selectionEnd();
1258 from = doc_iterator_begin(buffer_->inset());
1259 to = doc_iterator_end(buffer_->inset());
1261 int const count = countWords(from, to);
1264 if (cur.selection())
1265 message = bformat(_("%1$d words in selection."),
1268 message = bformat(_("%1$d words in document."),
1272 if (cur.selection())
1273 message = _("One word in selection.");
1275 message = _("One word in document.");
1278 Alert::information(_("Count words"), message);
1289 ViewMetricsInfo BufferView::Pimpl::metrics(bool singlepar)
1291 // Remove old position cache
1293 BufferView & bv = *bv_;
1294 LyXText * const text = bv.text();
1295 if (anchor_ref_ > int(text->paragraphs().size() - 1)) {
1296 anchor_ref_ = int(text->paragraphs().size() - 1);
1300 lyx::pit_type const pit = anchor_ref_;
1303 size_t const npit = text->paragraphs().size();
1305 lyxerr[Debug::DEBUG]
1306 << BOOST_CURRENT_FUNCTION
1307 << " npit: " << npit
1308 << " pit1: " << pit1
1309 << " pit2: " << pit2
1312 // Rebreak anchor par
1313 text->redoParagraph(pit);
1314 int y0 = text->getPar(pit1).ascent() - offset_ref_;
1316 // Redo paragraphs above cursor if necessary
1318 while (!singlepar && y1 > 0 && pit1 > 0) {
1319 y1 -= text->getPar(pit1).ascent();
1321 text->redoParagraph(pit1);
1322 y1 -= text->getPar(pit1).descent();
1326 // Take care of ascent of first line
1327 y1 -= text->getPar(pit1).ascent();
1329 // Normalize anchor for next time
1333 // Grey at the beginning is ugly
1334 if (pit1 == 0 && y1 > 0) {
1340 // Redo paragraphs below cursor if necessary
1342 while (!singlepar && y2 < bv.workHeight() && pit2 < int(npit) - 1) {
1343 y2 += text->getPar(pit2).descent();
1345 text->redoParagraph(pit2);
1346 y2 += text->getPar(pit2).ascent();
1349 // Take care of descent of last line
1350 y2 += text->getPar(pit2).descent();
1352 // The coordinates of all these paragraphs are correct, cache them
1354 for (lyx::pit_type pit = pit1; pit <= pit2; ++pit) {
1355 y += text->getPar(pit).ascent();
1356 theCoords.parPos()[text][pit] = Point(0, y);
1357 y += text->getPar(pit).descent();
1360 lyxerr[Debug::DEBUG]
1361 << BOOST_CURRENT_FUNCTION
1366 return ViewMetricsInfo(pit1, pit2, y1, y2, singlepar);