]> git.lyx.org Git - features.git/blob - src/BufferView.cpp
Prepare the code for context menu support.
[features.git] / src / BufferView.cpp
1 /**
2  * \file BufferView.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Alfredo Braunstein
7  * \author Lars Gullik Bjønnes
8  * \author John Levon
9  * \author André Pönitz
10  * \author Jürgen Vigna
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16
17 #include "BufferView.h"
18
19 #include "Buffer.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
23 #include "CoordCache.h"
24 #include "Cursor.h"
25 #include "CutAndPaste.h"
26 #include "DispatchResult.h"
27 #include "EmbeddedFiles.h"
28 #include "ErrorList.h"
29 #include "factory.h"
30 #include "FloatList.h"
31 #include "FuncRequest.h"
32 #include "FuncStatus.h"
33 #include "Intl.h"
34 #include "InsetIterator.h"
35 #include "Language.h"
36 #include "LaTeXFeatures.h"
37 #include "LyX.h"
38 #include "lyxfind.h"
39 #include "LyXFunc.h"
40 #include "Layout.h"
41 #include "LyXRC.h"
42 #include "MenuBackend.h"
43 #include "MetricsInfo.h"
44 #include "Paragraph.h"
45 #include "paragraph_funcs.h"
46 #include "ParagraphParameters.h"
47 #include "ParIterator.h"
48 #include "Session.h"
49 #include "Text.h"
50 #include "TextClass.h"
51 #include "TextMetrics.h"
52 #include "TexRow.h"
53 #include "VSpace.h"
54 #include "WordLangTuple.h"
55
56 #include "insets/InsetBibtex.h"
57 #include "insets/InsetCommand.h" // ChangeRefs
58 #include "insets/InsetRef.h"
59 #include "insets/InsetText.h"
60
61 #include "frontends/alert.h"
62 #include "frontends/Delegates.h"
63 #include "frontends/FontMetrics.h"
64 #include "frontends/Painter.h"
65 #include "frontends/Selection.h"
66
67 #include "graphics/Previews.h"
68
69 #include "support/convert.h"
70 #include "support/debug.h"
71 #include "support/FileFilterList.h"
72 #include "support/filetools.h"
73 #include "support/gettext.h"
74 #include "support/lstrings.h"
75 #include "support/Package.h"
76 #include "support/types.h"
77
78 #include <cerrno>
79 #include <fstream>
80 #include <functional>
81 #include <iterator>
82 #include <vector>
83
84 using namespace std;
85 using namespace lyx::support;
86
87 namespace lyx {
88
89 namespace Alert = frontend::Alert;
90
91 namespace {
92
93 /// Return an inset of this class if it exists at the current cursor position
94 template <class T>
95 T * getInsetByCode(Cursor const & cur, InsetCode code)
96 {
97         DocIterator it = cur;
98         Inset * inset = it.nextInset();
99         if (inset && inset->lyxCode() == code)
100                 return static_cast<T*>(inset);
101         return 0;
102 }
103
104
105 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
106         bool same_content);
107
108 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
109         docstring const & contents)
110 {
111         DocIterator tmpdit = dit;
112
113         while (tmpdit) {
114                 Inset const * inset = tmpdit.nextInset();
115                 if (inset
116                     && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()
117                     && (contents.empty() ||
118                     static_cast<InsetCommand const *>(inset)->getFirstNonOptParam() == contents)) {
119                         dit = tmpdit;
120                         return true;
121                 }
122                 tmpdit.forwardInset();
123         }
124
125         return false;
126 }
127
128
129 /// Looks for next inset with one of the given codes.
130 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
131         bool same_content)
132 {
133         docstring contents;
134         DocIterator tmpdit = dit;
135         tmpdit.forwardInset();
136         if (!tmpdit)
137                 return false;
138
139         if (same_content) {
140                 Inset const * inset = tmpdit.nextInset();
141                 if (inset
142                     && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()) {
143                         contents = static_cast<InsetCommand const *>(inset)->getFirstNonOptParam();
144                 }
145         }
146
147         if (!findNextInset(tmpdit, codes, contents)) {
148                 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
149                         tmpdit  = doc_iterator_begin(tmpdit.bottom().inset());
150                         if (!findNextInset(tmpdit, codes, contents))
151                                 return false;
152                 } else
153                         return false;
154         }
155
156         dit = tmpdit;
157         return true;
158 }
159
160
161 /// Looks for next inset with the given code
162 void findInset(DocIterator & dit, InsetCode code, bool same_content)
163 {
164         findInset(dit, vector<InsetCode>(1, code), same_content);
165 }
166
167
168 /// Moves cursor to the next inset with one of the given codes.
169 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
170                bool same_content)
171 {
172         Cursor tmpcur = bv->cursor();
173         if (!findInset(tmpcur, codes, same_content)) {
174                 bv->cursor().message(_("No more insets"));
175                 return;
176         }
177
178         tmpcur.clearSelection();
179         bv->setCursor(tmpcur);
180         bv->showCursor();
181 }
182
183
184 /// Moves cursor to the next inset with given code.
185 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
186 {
187         gotoInset(bv, vector<InsetCode>(1, code), same_content);
188 }
189
190
191 /// A map from a Text to the associated text metrics
192 typedef map<Text const *, TextMetrics> TextMetricsCache;
193
194 enum ScreenUpdateStrategy {
195         NoScreenUpdate,
196         SingleParUpdate,
197         FullScreenUpdate,
198         DecorationUpdate
199 };
200
201 } // anon namespace
202
203
204 /////////////////////////////////////////////////////////////////////
205 //
206 // BufferView
207 //
208 /////////////////////////////////////////////////////////////////////
209
210 struct BufferView::Private
211 {
212         Private(BufferView & bv): wh_(0), cursor_(bv),
213                 anchor_pit_(0), anchor_ypos_(0),
214                 last_inset_(0), gui_(0)
215         {}
216
217         ///
218         ScrollbarParameters scrollbarParameters_;
219         ///
220         ScreenUpdateStrategy update_strategy_;
221         ///
222         CoordCache coord_cache_;
223
224         /// Estimated average par height for scrollbar.
225         int wh_;
226         /// this is used to handle XSelection events in the right manner.
227         struct {
228                 CursorSlice cursor;
229                 CursorSlice anchor;
230                 bool set;
231         } xsel_cache_;
232         ///
233         Cursor cursor_;
234         ///
235         pit_type anchor_pit_;
236         ///
237         int anchor_ypos_;
238         ///
239         vector<int> par_height_;
240
241         /// keyboard mapping object.
242         Intl intl_;
243
244         /// last visited inset.
245         /** kept to send setMouseHover(false).
246           * Not owned, so don't delete.
247           */
248         Inset * last_inset_;
249
250         mutable TextMetricsCache text_metrics_;
251
252         /// Whom to notify.
253         /** Not owned, so don't delete.
254           */
255         frontend::GuiBufferViewDelegate * gui_;
256 };
257
258
259 BufferView::BufferView(Buffer & buf)
260         : width_(0), height_(0), buffer_(buf), d(new Private(*this))
261 {
262         d->xsel_cache_.set = false;
263         d->intl_.initKeyMapper(lyxrc.use_kbmap);
264
265         d->cursor_.push(buffer_.inset());
266         d->cursor_.resetAnchor();
267         d->cursor_.setCurrentFont();
268
269         if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
270                 graphics::Previews::get().generateBufferPreviews(buffer_);
271 }
272
273
274 BufferView::~BufferView()
275 {
276         // current buffer is going to be switched-off, save cursor pos
277         // Ideally, the whole cursor stack should be saved, but session
278         // currently can only handle bottom (whole document) level pit and pos.
279         // That is to say, if a cursor is in a nested inset, it will be
280         // restore to the left of the top level inset.
281         LastFilePosSection::FilePos fp;
282         fp.pit = d->cursor_.bottom().pit();
283         fp.pos = d->cursor_.bottom().pos();
284         LyX::ref().session().lastFilePos().save(buffer_.fileName(), fp);
285
286         delete d;
287 }
288
289
290 Intl & BufferView::getIntl()
291 {
292         return d->intl_;
293 }
294
295
296 Intl const & BufferView::getIntl() const
297 {
298         return d->intl_;
299 }
300
301
302 CoordCache & BufferView::coordCache()
303 {
304         return d->coord_cache_;
305 }
306
307
308 CoordCache const & BufferView::coordCache() const
309 {
310         return d->coord_cache_;
311 }
312
313
314 Buffer & BufferView::buffer()
315 {
316         return buffer_;
317 }
318
319
320 Buffer const & BufferView::buffer() const
321 {
322         return buffer_;
323 }
324
325
326 bool BufferView::fitCursor()
327 {
328         if (cursorStatus(d->cursor_) == CUR_INSIDE) {
329                 frontend::FontMetrics const & fm =
330                         theFontMetrics(d->cursor_.getFont().fontInfo());
331                 int const asc = fm.maxAscent();
332                 int const des = fm.maxDescent();
333                 Point const p = getPos(d->cursor_, d->cursor_.boundary());
334                 if (p.y_ - asc >= 0 && p.y_ + des < height_)
335                         return false;
336         }
337         return true;
338 }
339
340
341 void BufferView::processUpdateFlags(Update::flags flags)
342 {
343         // last_inset_ points to the last visited inset. This pointer may become
344         // invalid because of keyboard editing. Since all such operations
345         // causes screen update(), I reset last_inset_ to avoid such a problem.
346         d->last_inset_ = 0;
347         // This is close to a hot-path.
348         LYXERR(Debug::DEBUG, "BufferView::processUpdateFlags()"
349                 << "[fitcursor = " << (flags & Update::FitCursor)
350                 << ", forceupdate = " << (flags & Update::Force)
351                 << ", singlepar = " << (flags & Update::SinglePar)
352                 << "]  buffer: " << &buffer_);
353
354         buffer_.updateMacros();
355
356         // Now do the first drawing step if needed. This consists on updating
357         // the CoordCache in updateMetrics().
358         // The second drawing step is done in WorkArea::redraw() if needed.
359
360         // Case when no explicit update is requested.
361         if (!flags) {
362                 // no need to redraw anything.
363                 d->update_strategy_ = NoScreenUpdate;
364                 return;
365         }
366
367         if (flags == Update::Decoration) {
368                 d->update_strategy_ = DecorationUpdate;
369                 buffer_.changed();
370                 return;
371         }
372
373         if (flags == Update::FitCursor
374                 || flags == (Update::Decoration | Update::FitCursor)) {
375                 // tell the frontend to update the screen if needed.
376                 if (fitCursor()) {
377                         showCursor();
378                         return;
379                 }
380                 if (flags & Update::Decoration) {
381                         d->update_strategy_ = DecorationUpdate;
382                         buffer_.changed();
383                         return;
384                 }
385                 // no screen update is needed.
386                 d->update_strategy_ = NoScreenUpdate;
387                 return;
388         }
389
390         bool const full_metrics = flags & Update::Force || !singleParUpdate();
391
392         if (full_metrics)
393                 // We have to update the full screen metrics.
394                 updateMetrics();
395
396         if (!(flags & Update::FitCursor)) {
397                 // Nothing to do anymore. Trigger a redraw and return
398                 buffer_.changed();
399                 return;
400         }
401
402         // updateMetrics() does not update paragraph position
403         // This is done at draw() time. So we need a redraw!
404         buffer_.changed();
405
406         if (fitCursor()) {
407                 // The cursor is off screen so ensure it is visible.
408                 // refresh it:
409                 showCursor();
410         }
411 }
412
413
414 void BufferView::updateScrollbar()
415 {
416         if (height_ == 0)
417                 return;
418
419         Text & t = buffer_.text();
420         TextMetrics & tm = d->text_metrics_[&t];                
421
422         LYXERR(Debug::GUI, " Updating scrollbar: height: "
423                 << t.paragraphs().size()
424                 << " curr par: " << d->cursor_.bottom().pit()
425                 << " default height " << defaultRowHeight());
426
427         int const parsize = int(t.paragraphs().size());
428         if (d->par_height_.size() != parsize) {
429                 d->par_height_.clear();
430                 // FIXME: We assume a default paragraph height of 2 rows. This
431                 // should probably be pondered with the screen width.
432                 d->par_height_.resize(parsize, defaultRowHeight() * 2);
433         }
434
435         // It would be better to fix the scrollbar to understand
436         // values in [0..1] and divide everything by wh
437
438         // Look at paragraph heights on-screen
439         pit_type first_visible_pit = -1;
440         pair<pit_type, ParagraphMetrics const *> first = tm.first();
441         pair<pit_type, ParagraphMetrics const *> last = tm.last();
442         for (pit_type pit = first.first; pit <= last.first; ++pit) {
443                 ParagraphMetrics const & pm = tm.parMetrics(pit);
444                 d->par_height_[pit] = pm.height();
445                 if (first_visible_pit >= 0 || pm.position() + pm.descent() <= 0)
446                         continue;
447                 first_visible_pit = pit;
448                 LYXERR(Debug::SCROLLING, "first visible pit " << first_visible_pit);
449                 // FIXME: we should look for the first visible row within
450                 // the deepest inset!
451                 int row_pos = pm.position();
452                 size_t const nrows = pm.rows().size();
453                 for (size_t i = 0; i != nrows; ++i) {
454                         Row const & row = pm.rows()[i];
455                         if (row_pos >= 0) {
456                                 LYXERR(Debug::SCROLLING, "first visible row " << i
457                                         << "(row pos = " << row_pos << ");");
458                                 break;
459                         }
460                         row_pos += row.height();
461                 }
462                 d->scrollbarParameters_.position = row_pos;
463         }
464
465         d->scrollbarParameters_.height = 0;
466         for (size_t i = 0; i != d->par_height_.size(); ++i) {
467                 if (i == first_visible_pit)
468                         d->scrollbarParameters_.position += d->scrollbarParameters_.height;
469                 d->scrollbarParameters_.height += d->par_height_[i];
470         }
471
472         // We prefer fixed size line scrolling.
473         d->scrollbarParameters_.lineScrollHeight = defaultRowHeight();
474 }
475
476
477 ScrollbarParameters const & BufferView::scrollbarParameters() const
478 {
479         return d->scrollbarParameters_;
480 }
481
482
483 docstring BufferView::toolTip(int x, int y) const
484 {
485         // Get inset under mouse, if there is one.
486         Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
487         if (!covering_inset)
488                 // No inset, no tooltip...
489                 return docstring();
490         return covering_inset->toolTip(*this, x, y);
491 }
492
493
494 Menu const & BufferView::contextMenu(int x, int y) const
495 {
496         // FIXME: Do something more elaborate here.
497         return menubackend.getMenu(from_ascii("edit"));
498 }
499
500
501 void BufferView::scrollDocView(int value)
502 {
503         int const offset = value - d->scrollbarParameters_.position;
504         // If the offset is less than 2 screen height, prefer to scroll instead.
505         if (abs(offset) <= 2 * height_) {
506                 scroll(offset);
507                 return;
508         }
509
510         int par_pos = 0;
511         for (size_t i = 0; i != d->par_height_.size(); ++i) {
512                 par_pos += d->par_height_[i];
513                 if (par_pos >= value) {
514                         d->anchor_pit_ = pit_type(i);
515                         break;
516                 }
517         }
518
519         LYXERR(Debug::SCROLLING, "value = " << value
520                 << "\tanchor_ref_ = " << d->anchor_pit_
521                 << "\tpar_pos = " << par_pos);
522
523         d->anchor_ypos_ = par_pos - value;
524         updateMetrics();
525         buffer_.changed();
526 }
527
528
529 // FIXME: this method is not working well.
530 void BufferView::setCursorFromScrollbar()
531 {
532         TextMetrics & tm = d->text_metrics_[&buffer_.text()];
533
534         int const height = 2 * defaultRowHeight();
535         int const first = height;
536         int const last = height_ - height;
537         Cursor & cur = d->cursor_;
538
539         switch (cursorStatus(cur)) {
540         case CUR_ABOVE:
541                 // We reset the cursor because cursorStatus() does not
542                 // work when the cursor is within mathed.
543                 cur.reset(buffer_.inset());
544                 tm.setCursorFromCoordinates(cur, 0, first);
545                 cur.clearSelection();
546                 break;
547         case CUR_BELOW:
548                 // We reset the cursor because cursorStatus() does not
549                 // work when the cursor is within mathed.
550                 cur.reset(buffer_.inset());
551                 tm.setCursorFromCoordinates(cur, 0, last);
552                 cur.clearSelection();
553                 break;
554         case CUR_INSIDE:
555                 int const y = getPos(cur, cur.boundary()).y_;
556                 int const newy = min(last, max(y, first));
557                 if (y != newy) {
558                         cur.reset(buffer_.inset());
559                         tm.setCursorFromCoordinates(cur, 0, newy);
560                 }
561         }
562 }
563
564
565 Change const BufferView::getCurrentChange() const
566 {
567         if (!d->cursor_.selection())
568                 return Change(Change::UNCHANGED);
569
570         DocIterator dit = d->cursor_.selectionBegin();
571         return dit.paragraph().lookupChange(dit.pos());
572 }
573
574
575 // this could be used elsewhere as well?
576 // FIXME: This does not work within mathed!
577 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
578 {
579         Point const p = getPos(dit, dit.boundary());
580         if (p.y_ < 0)
581                 return CUR_ABOVE;
582         if (p.y_ > workHeight())
583                 return CUR_BELOW;
584         return CUR_INSIDE;
585 }
586
587
588 void BufferView::saveBookmark(unsigned int idx)
589 {
590         // tenatively save bookmark, id and pos will be used to
591         // acturately locate a bookmark in a 'live' lyx session.
592         // pit and pos will be updated with bottom level pit/pos
593         // when lyx exits.
594         LyX::ref().session().bookmarks().save(
595                 buffer_.fileName(),
596                 d->cursor_.bottom().pit(),
597                 d->cursor_.bottom().pos(),
598                 d->cursor_.paragraph().id(),
599                 d->cursor_.pos(),
600                 idx
601         );
602         if (idx)
603                 // emit message signal.
604                 message(_("Save bookmark"));
605 }
606
607
608 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
609         int top_id, pos_type top_pos)
610 {
611         bool success = false;
612         DocIterator doc_it;
613
614         d->cursor_.clearSelection();
615
616         // if a valid par_id is given, try it first
617         // This is the case for a 'live' bookmark when unique paragraph ID
618         // is used to track bookmarks.
619         if (top_id > 0) {
620                 ParIterator par = buffer_.getParFromID(top_id);
621                 if (par != buffer_.par_iterator_end()) {
622                         doc_it = makeDocIterator(par, min(par->size(), top_pos));
623                         // Some slices of the iterator may not be
624                         // reachable (e.g. closed collapsable inset)
625                         // so the dociterator may need to be
626                         // shortened. Otherwise, setCursor may crash
627                         // lyx when the cursor can not be set to these
628                         // insets.
629                         size_t const n = doc_it.depth();
630                         for (size_t i = 0; i < n; ++i)
631                                 if (doc_it[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
632                                         doc_it.resize(i);
633                                         break;
634                                 }
635                         success = true;
636                 }
637         }
638
639         // if top_id == 0, or searching through top_id failed
640         // This is the case for a 'restored' bookmark when only bottom
641         // (document level) pit was saved. Because of this, bookmark
642         // restoration is inaccurate. If a bookmark was within an inset,
643         // it will be restored to the left of the outmost inset that contains
644         // the bookmark.
645         if (static_cast<size_t>(bottom_pit) < buffer_.paragraphs().size()) {
646                 doc_it = doc_iterator_begin(buffer_.inset());
647                 doc_it.pit() = bottom_pit;
648                 doc_it.pos() = min(bottom_pos, doc_it.paragraph().size());
649                 success = true;
650         }
651
652         if (success) {
653                 // Note: only bottom (document) level pit is set.
654                 setCursor(doc_it);
655                 // set the current font.
656                 d->cursor_.setCurrentFont();
657                 // To center the screen on this new position we need the
658                 // paragraph position which is computed at draw() time.
659                 // So we need a redraw!
660                 buffer_.changed();
661                 if (fitCursor())
662                         showCursor();
663         }
664
665         return success;
666 }
667
668
669 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
670 {
671         if (lyxrc.rtl_support) {
672                 if (d->cursor_.real_current_font.isRightToLeft()) {
673                         if (d->intl_.keymap == Intl::PRIMARY)
674                                 d->intl_.keyMapSec();
675                 } else {
676                         if (d->intl_.keymap == Intl::SECONDARY)
677                                 d->intl_.keyMapPrim();
678                 }
679         }
680
681         d->intl_.getTransManager().translateAndInsert(c, t, cur);
682 }
683
684
685 int BufferView::workWidth() const
686 {
687         return width_;
688 }
689
690
691 void BufferView::showCursor()
692 {
693         // We are not properly started yet, delay until resizing is
694         // done.
695         if (height_ == 0)
696                 return;
697
698         LYXERR(Debug::SCROLLING, "recentering!");
699
700         CursorSlice & bot = d->cursor_.bottom();
701         TextMetrics & tm = d->text_metrics_[bot.text()];
702
703         pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
704         int bot_pit = d->cursor_.bottom().pit();
705         if (bot_pit > max_pit) {
706                 // FIXME: Why does this happen?
707                 LYXERR0("bottom pit is greater that max pit: "
708                         << bot_pit << " > " << max_pit);
709                 bot_pit = max_pit;
710         }
711
712         if (bot_pit == tm.first().first - 1)
713                 tm.newParMetricsUp();
714         else if (bot_pit == tm.last().first + 1)
715                 tm.newParMetricsDown();
716
717         if (tm.has(bot_pit)) {
718                 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
719                 int offset = coordOffset(d->cursor_, d->cursor_.boundary()).y_;
720                 int ypos = pm.position() + offset;
721                 Dimension const & row_dim = d->cursor_.textRow().dimension();
722                 if (ypos - row_dim.ascent() < 0)
723                         scrollUp(- ypos + row_dim.ascent());
724                 else if (ypos + row_dim.descent() > height_)
725                         scrollDown(ypos - height_ + row_dim.descent());
726                 // else, nothing to do, the cursor is already visible so we just return.
727                 return;
728         }
729
730         tm.redoParagraph(bot_pit);
731         ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
732         int offset = coordOffset(d->cursor_, d->cursor_.boundary()).y_;
733
734         d->anchor_pit_ = bot_pit;
735         Dimension const & row_dim = d->cursor_.textRow().dimension();
736
737         if (d->anchor_pit_ == 0)
738                 d->anchor_ypos_ = offset + pm.ascent();
739         else if (d->anchor_pit_ == max_pit)
740                 d->anchor_ypos_ = height_ - offset - row_dim.descent();
741         else
742                 d->anchor_ypos_ = offset + pm.ascent() - height_ / 2;
743
744         updateMetrics();
745         buffer_.changed();
746 }
747
748
749 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
750 {
751         FuncStatus flag;
752
753         Cursor & cur = d->cursor_;
754
755         switch (cmd.action) {
756
757         case LFUN_UNDO:
758                 flag.enabled(buffer_.undo().hasUndoStack());
759                 break;
760         case LFUN_REDO:
761                 flag.enabled(buffer_.undo().hasRedoStack());
762                 break;
763         case LFUN_FILE_INSERT:
764         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
765         case LFUN_FILE_INSERT_PLAINTEXT:
766         case LFUN_BOOKMARK_SAVE:
767                 // FIXME: Actually, these LFUNS should be moved to Text
768                 flag.enabled(cur.inTexted());
769                 break;
770         case LFUN_FONT_STATE:
771         case LFUN_LABEL_INSERT:
772         case LFUN_INFO_INSERT:
773         case LFUN_PARAGRAPH_GOTO:
774         case LFUN_NOTE_NEXT:
775         case LFUN_REFERENCE_NEXT:
776         case LFUN_WORD_FIND:
777         case LFUN_WORD_REPLACE:
778         case LFUN_MARK_OFF:
779         case LFUN_MARK_ON:
780         case LFUN_MARK_TOGGLE:
781         case LFUN_SCREEN_RECENTER:
782         case LFUN_BIBTEX_DATABASE_ADD:
783         case LFUN_BIBTEX_DATABASE_DEL:
784         case LFUN_WORDS_COUNT:
785         case LFUN_NEXT_INSET_TOGGLE:
786                 flag.enabled(true);
787                 break;
788
789         case LFUN_LABEL_GOTO: {
790                 flag.enabled(!cmd.argument().empty()
791                     || getInsetByCode<InsetRef>(cur, REF_CODE));
792                 break;
793         }
794
795         case LFUN_CHANGES_TRACK:
796                 flag.enabled(true);
797                 flag.setOnOff(buffer_.params().trackChanges);
798                 break;
799
800         case LFUN_CHANGES_OUTPUT:
801                 flag.enabled(true);
802                 flag.setOnOff(buffer_.params().outputChanges);
803                 break;
804
805         case LFUN_CHANGES_MERGE:
806         case LFUN_CHANGE_NEXT:
807         case LFUN_ALL_CHANGES_ACCEPT:
808         case LFUN_ALL_CHANGES_REJECT:
809                 // TODO: context-sensitive enabling of LFUNs
810                 // In principle, these command should only be enabled if there
811                 // is a change in the document. However, without proper
812                 // optimizations, this will inevitably result in poor performance.
813                 flag.enabled(true);
814                 break;
815
816         case LFUN_BUFFER_TOGGLE_COMPRESSION: {
817                 flag.setOnOff(buffer_.params().compressed);
818                 break;
819         }
820         
821         case LFUN_BUFFER_TOGGLE_EMBEDDING: {
822                 flag.setOnOff(buffer_.params().embedded);
823                 break;
824         }
825
826         case LFUN_SCREEN_UP:
827         case LFUN_SCREEN_DOWN:
828                 flag.enabled(true);
829                 break;
830
831         // FIXME: LFUN_SCREEN_DOWN_SELECT should be removed from
832         // everywhere else before this can enabled:
833         case LFUN_SCREEN_UP_SELECT:
834         case LFUN_SCREEN_DOWN_SELECT:
835                 flag.enabled(false);
836                 break;
837
838         case LFUN_LAYOUT_TABULAR:
839                 flag.enabled(cur.innerInsetOfType(TABULAR_CODE));
840                 break;
841
842         case LFUN_LAYOUT:
843         case LFUN_LAYOUT_PARAGRAPH:
844                 flag.enabled(cur.inset().forceDefaultParagraphs(cur.idx()));
845                 break;
846
847         case LFUN_INSET_SETTINGS: {
848                 InsetCode code = cur.inset().lyxCode();
849                 bool enable = false;
850                 switch (code) {
851                         case TABULAR_CODE:
852                                 enable = cmd.argument() == "tabular";
853                                 break;
854                         case ERT_CODE:
855                                 enable = cmd.argument() == "ert";
856                                 break;
857                         case FLOAT_CODE:
858                                 enable = cmd.argument() == "float";
859                                 break;
860                         case WRAP_CODE:
861                                 enable = cmd.argument() == "wrap";
862                                 break;
863                         case NOTE_CODE:
864                                 enable = cmd.argument() == "note";
865                                 break;
866                         case BRANCH_CODE:
867                                 enable = cmd.argument() == "branch";
868                                 break;
869                         case BOX_CODE:
870                                 enable = cmd.argument() == "box";
871                                 break;
872                         case LISTINGS_CODE:
873                                 enable = cmd.argument() == "listings";
874                                 break;
875                         default:
876                                 break;
877                 }
878                 flag.enabled(enable);
879                 break;
880         }
881
882         case LFUN_DIALOG_SHOW_NEW_INSET:
883                 flag.enabled(cur.inset().lyxCode() != ERT_CODE &&
884                         cur.inset().lyxCode() != LISTINGS_CODE);
885                 if (cur.inset().lyxCode() == CAPTION_CODE) {
886                         FuncStatus flag;
887                         if (cur.inset().getStatus(cur, cmd, flag))
888                                 return flag;
889                 }
890                 break;
891
892         default:
893                 flag.enabled(false);
894         }
895
896         return flag;
897 }
898
899
900 bool BufferView::dispatch(FuncRequest const & cmd)
901 {
902         //lyxerr << [ cmd = " << cmd << "]" << endl;
903
904         // Make sure that the cached BufferView is correct.
905         LYXERR(Debug::ACTION, " action[" << cmd.action << ']'
906                 << " arg[" << to_utf8(cmd.argument()) << ']'
907                 << " x[" << cmd.x << ']'
908                 << " y[" << cmd.y << ']'
909                 << " button[" << cmd.button() << ']');
910
911         Cursor & cur = d->cursor_;
912
913         switch (cmd.action) {
914
915         case LFUN_UNDO:
916                 cur.message(_("Undo"));
917                 cur.clearSelection();
918                 if (!cur.textUndo())
919                         cur.message(_("No further undo information"));
920                 break;
921
922         case LFUN_REDO:
923                 cur.message(_("Redo"));
924                 cur.clearSelection();
925                 if (!cur.textRedo())
926                         cur.message(_("No further redo information"));
927                 break;
928
929         case LFUN_FONT_STATE:
930                 cur.message(cur.currentState());
931                 break;
932
933         case LFUN_BOOKMARK_SAVE:
934                 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
935                 break;
936
937         case LFUN_LABEL_GOTO: {
938                 docstring label = cmd.argument();
939                 if (label.empty()) {
940                         InsetRef * inset =
941                                 getInsetByCode<InsetRef>(d->cursor_,
942                                                          REF_CODE);
943                         if (inset) {
944                                 label = inset->getParam("reference");
945                                 // persistent=false: use temp_bookmark
946                                 saveBookmark(0);
947                         }
948                 }
949
950                 if (!label.empty())
951                         gotoLabel(label);
952                 break;
953         }
954
955         case LFUN_PARAGRAPH_GOTO: {
956                 int const id = convert<int>(to_utf8(cmd.argument()));
957                 int i = 0;
958                 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
959                         b = theBufferList().next(b)) {
960
961                         ParIterator par = b->getParFromID(id);
962                         if (par == b->par_iterator_end()) {
963                                 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
964                         } else {
965                                 LYXERR(Debug::INFO, "Paragraph " << par->id()
966                                         << " found in buffer `"
967                                         << b->absFileName() << "'.");
968
969                                 if (b == &buffer_) {
970                                         // Set the cursor
971                                         setCursor(makeDocIterator(par, 0));
972                                         showCursor();
973                                 } else {
974                                         // Switch to other buffer view and resend cmd
975                                         theLyXFunc().dispatch(FuncRequest(
976                                                 LFUN_BUFFER_SWITCH, b->absFileName()));
977                                         theLyXFunc().dispatch(cmd);
978                                 }
979                                 break;
980                         }
981                         ++i;
982                 }
983                 break;
984         }
985
986         case LFUN_NOTE_NEXT:
987                 gotoInset(this, NOTE_CODE, false);
988                 break;
989
990         case LFUN_REFERENCE_NEXT: {
991                 vector<InsetCode> tmp;
992                 tmp.push_back(LABEL_CODE);
993                 tmp.push_back(REF_CODE);
994                 gotoInset(this, tmp, true);
995                 break;
996         }
997
998         case LFUN_CHANGES_TRACK:
999                 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1000                 break;
1001
1002         case LFUN_CHANGES_OUTPUT:
1003                 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1004                 if (buffer_.params().outputChanges) {
1005                         bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
1006                         bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1007                                           LaTeXFeatures::isAvailable("xcolor");
1008
1009                         if (!dvipost && !xcolorsoul) {
1010                                 Alert::warning(_("Changes not shown in LaTeX output"),
1011                                                _("Changes will not be highlighted in LaTeX output, "
1012                                                  "because neither dvipost nor xcolor/soul are installed.\n"
1013                                                  "Please install these packages or redefine "
1014                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1015                         } else if (!xcolorsoul) {
1016                                 Alert::warning(_("Changes not shown in LaTeX output"),
1017                                                _("Changes will not be highlighted in LaTeX output "
1018                                                  "when using pdflatex, because xcolor and soul are not installed.\n"
1019                                                  "Please install both packages or redefine "
1020                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1021                         }
1022                 }
1023                 break;
1024
1025         case LFUN_CHANGE_NEXT:
1026                 findNextChange(this);
1027                 break;
1028
1029         case LFUN_CHANGES_MERGE:
1030                 if (findNextChange(this))
1031                         showDialog("changes");
1032                 break;
1033
1034         case LFUN_ALL_CHANGES_ACCEPT:
1035                 // select complete document
1036                 d->cursor_.reset(buffer_.inset());
1037                 d->cursor_.selHandle(true);
1038                 buffer_.text().cursorBottom(d->cursor_);
1039                 // accept everything in a single step to support atomic undo
1040                 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::ACCEPT);
1041                 break;
1042
1043         case LFUN_ALL_CHANGES_REJECT:
1044                 // select complete document
1045                 d->cursor_.reset(buffer_.inset());
1046                 d->cursor_.selHandle(true);
1047                 buffer_.text().cursorBottom(d->cursor_);
1048                 // reject everything in a single step to support atomic undo
1049                 // Note: reject does not work recursively; the user may have to repeat the operation
1050                 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::REJECT);
1051                 break;
1052
1053         case LFUN_WORD_FIND:
1054                 find(this, cmd);
1055                 break;
1056
1057         case LFUN_WORD_REPLACE: {
1058                 bool has_deleted = false;
1059                 if (cur.selection()) {
1060                         DocIterator beg = cur.selectionBegin();
1061                         DocIterator end = cur.selectionEnd();
1062                         if (beg.pit() == end.pit()) {
1063                                 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1064                                         if (cur.paragraph().isDeleted(p))
1065                                                 has_deleted = true;
1066                                 }
1067                         }
1068                 }
1069                 replace(this, cmd, has_deleted);
1070                 break;
1071         }
1072
1073         case LFUN_MARK_OFF:
1074                 cur.clearSelection();
1075                 cur.resetAnchor();
1076                 cur.message(from_utf8(N_("Mark off")));
1077                 break;
1078
1079         case LFUN_MARK_ON:
1080                 cur.clearSelection();
1081                 cur.mark() = true;
1082                 cur.resetAnchor();
1083                 cur.message(from_utf8(N_("Mark on")));
1084                 break;
1085
1086         case LFUN_MARK_TOGGLE:
1087                 cur.clearSelection();
1088                 if (cur.mark()) {
1089                         cur.mark() = false;
1090                         cur.message(from_utf8(N_("Mark removed")));
1091                 } else {
1092                         cur.mark() = true;
1093                         cur.message(from_utf8(N_("Mark set")));
1094                 }
1095                 cur.resetAnchor();
1096                 break;
1097
1098         case LFUN_SCREEN_RECENTER:
1099                 showCursor();
1100                 break;
1101
1102         case LFUN_BIBTEX_DATABASE_ADD: {
1103                 Cursor tmpcur = d->cursor_;
1104                 findInset(tmpcur, BIBTEX_CODE, false);
1105                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1106                                                 BIBTEX_CODE);
1107                 if (inset) {
1108                         if (inset->addDatabase(to_utf8(cmd.argument())))
1109                                 buffer_.updateBibfilesCache();
1110                 }
1111                 break;
1112         }
1113
1114         case LFUN_BIBTEX_DATABASE_DEL: {
1115                 Cursor tmpcur = d->cursor_;
1116                 findInset(tmpcur, BIBTEX_CODE, false);
1117                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1118                                                 BIBTEX_CODE);
1119                 if (inset) {
1120                         if (inset->delDatabase(to_utf8(cmd.argument())))
1121                                 buffer_.updateBibfilesCache();
1122                 }
1123                 break;
1124         }
1125
1126         case LFUN_WORDS_COUNT: {
1127                 DocIterator from, to;
1128                 if (cur.selection()) {
1129                         from = cur.selectionBegin();
1130                         to = cur.selectionEnd();
1131                 } else {
1132                         from = doc_iterator_begin(buffer_.inset());
1133                         to = doc_iterator_end(buffer_.inset());
1134                 }
1135                 int const count = countWords(from, to);
1136                 docstring message;
1137                 if (count != 1) {
1138                         if (cur.selection())
1139                                 message = bformat(_("%1$d words in selection."),
1140                                           count);
1141                                 else
1142                                         message = bformat(_("%1$d words in document."),
1143                                                           count);
1144                 }
1145                 else {
1146                         if (cur.selection())
1147                                 message = _("One word in selection.");
1148                         else
1149                                 message = _("One word in document.");
1150                 }
1151
1152                 Alert::information(_("Count words"), message);
1153         }
1154                 break;
1155
1156         case LFUN_BUFFER_TOGGLE_COMPRESSION:
1157                 // turn compression on/off
1158                 buffer_.params().compressed = !buffer_.params().compressed;
1159                 break;
1160         
1161         case LFUN_BUFFER_TOGGLE_EMBEDDING:
1162                 // turn embedding on/off
1163                 buffer_.embeddedFiles().enable(!buffer_.params().embedded);
1164                 break;
1165
1166         case LFUN_NEXT_INSET_TOGGLE: {
1167                 // this is the real function we want to invoke
1168                 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1169                 // if there is an inset at cursor, see whether it
1170                 // wants to toggle.
1171                 Inset * inset = cur.nextInset();
1172                 if (inset) {
1173                         if (inset->isActive()) {
1174                                 Cursor tmpcur = cur;
1175                                 tmpcur.pushBackward(*inset);
1176                                 inset->dispatch(tmpcur, tmpcmd);
1177                                 if (tmpcur.result().dispatched()) {
1178                                         cur.dispatched();
1179                                 }
1180                         } else if (inset->editable() == Inset::IS_EDITABLE) {
1181                                 inset->edit(cur, true);
1182                         }
1183                 }
1184                 // if it did not work, try the underlying inset.
1185                 if (!cur.result().dispatched())
1186                         cur.dispatch(tmpcmd);
1187
1188                 if (cur.result().dispatched())
1189                         cur.clearSelection();
1190
1191                 break;
1192         }
1193
1194         case LFUN_SCREEN_UP:
1195         case LFUN_SCREEN_DOWN: {
1196                 Point p = getPos(cur, cur.boundary());
1197                 if (p.y_ < 0 || p.y_ > height_) {
1198                         // The cursor is off-screen so recenter before proceeding.
1199                         showCursor();
1200                         p = getPos(cur, cur.boundary());
1201                 }
1202                 scroll(cmd.action == LFUN_SCREEN_UP? - height_ : height_);
1203                 cur.reset(buffer_.inset());
1204                 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1205                 //FIXME: what to do with cur.x_target()?
1206                 cur.finishUndo();
1207                 break;
1208         }
1209
1210         case LFUN_SCREEN_UP_SELECT:
1211         case LFUN_SCREEN_DOWN_SELECT: {
1212                 // Those two are not ready yet for consumption.
1213                 return false;
1214
1215                 cur.selHandle(true);
1216                 size_t initial_depth = cur.depth();
1217                 Point const p = getPos(cur, cur.boundary());
1218                 scroll(cmd.action == LFUN_SCREEN_UP_SELECT? - height_ : height_);
1219                 // FIXME: We need to verify if the cursor stayed within an inset...
1220                 //cur.reset(buffer_.inset());
1221                 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1222                 cur.finishUndo();
1223                 while (cur.depth() > initial_depth) {
1224                         cur.forwardInset();
1225                 }
1226                 // FIXME: we need to do a redraw again because of the selection
1227                 // But no screen update is needed.
1228                 d->update_strategy_ = NoScreenUpdate;
1229                 buffer_.changed();
1230                 break;
1231         }
1232
1233         default:
1234                 return false;
1235         }
1236
1237         return true;
1238 }
1239
1240
1241 docstring const BufferView::requestSelection()
1242 {
1243         Cursor & cur = d->cursor_;
1244
1245         if (!cur.selection()) {
1246                 d->xsel_cache_.set = false;
1247                 return docstring();
1248         }
1249
1250         if (!d->xsel_cache_.set ||
1251             cur.top() != d->xsel_cache_.cursor ||
1252             cur.anchor_.top() != d->xsel_cache_.anchor)
1253         {
1254                 d->xsel_cache_.cursor = cur.top();
1255                 d->xsel_cache_.anchor = cur.anchor_.top();
1256                 d->xsel_cache_.set = cur.selection();
1257                 return cur.selectionAsString(false);
1258         }
1259         return docstring();
1260 }
1261
1262
1263 void BufferView::clearSelection()
1264 {
1265         d->cursor_.clearSelection();
1266         // Clear the selection buffer. Otherwise a subsequent
1267         // middle-mouse-button paste would use the selection buffer,
1268         // not the more current external selection.
1269         cap::clearSelection();
1270         d->xsel_cache_.set = false;
1271         // The buffer did not really change, but this causes the
1272         // redraw we need because we cleared the selection above.
1273         buffer_.changed();
1274 }
1275
1276
1277 void BufferView::resize(int width, int height)
1278 {
1279         // Update from work area
1280         width_ = width;
1281         height_ = height;
1282
1283         // Clear the paragraph height cache.
1284         d->par_height_.clear();
1285
1286         updateMetrics();
1287 }
1288
1289
1290 Inset const * BufferView::getCoveringInset(Text const & text,
1291                 int x, int y) const
1292 {
1293         TextMetrics & tm = d->text_metrics_[&text];
1294         Inset * inset = tm.checkInsetHit(x, y);
1295         if (!inset)
1296                 return 0;
1297
1298         if (!inset->descendable())
1299                 // No need to go further down if the inset is not
1300                 // descendable.
1301                 return inset;
1302
1303         size_t cell_number = inset->nargs();
1304         // Check all the inner cell.
1305         for (size_t i = 0; i != cell_number; ++i) {
1306                 Text const * inner_text = inset->getText(i);
1307                 if (inner_text) {
1308                         // Try deeper.
1309                         Inset const * inset_deeper =
1310                                 getCoveringInset(*inner_text, x, y);
1311                         if (inset_deeper)
1312                                 return inset_deeper;
1313                 }
1314         }
1315
1316         return inset;
1317 }
1318
1319
1320 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1321 {
1322         //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
1323
1324         // This is only called for mouse related events including
1325         // LFUN_FILE_OPEN generated by drag-and-drop.
1326         FuncRequest cmd = cmd0;
1327
1328         Cursor cur(*this);
1329         cur.push(buffer_.inset());
1330         cur.selection() = d->cursor_.selection();
1331
1332         // Either the inset under the cursor or the
1333         // surrounding Text will handle this event.
1334
1335         // make sure we stay within the screen...
1336         cmd.y = min(max(cmd.y, -1), height_);
1337
1338         if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1339
1340                 // Get inset under mouse, if there is one.
1341                 Inset const * covering_inset =
1342                         getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1343                 if (covering_inset == d->last_inset_)
1344                         // Same inset, no need to do anything...
1345                         return;
1346
1347                 bool need_redraw = false;
1348                 // const_cast because of setMouseHover().
1349                 Inset * inset = const_cast<Inset *>(covering_inset);
1350                 if (d->last_inset_)
1351                         // Remove the hint on the last hovered inset (if any).
1352                         need_redraw |= d->last_inset_->setMouseHover(false);
1353                 if (inset)
1354                         // Highlighted the newly hovered inset (if any).
1355                         need_redraw |= inset->setMouseHover(true);
1356                 d->last_inset_ = inset;
1357                 if (!need_redraw)
1358                         return;
1359
1360                 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
1361                         << cmd.x << ", " << cmd.y << ")");
1362
1363                 d->update_strategy_ = DecorationUpdate;
1364
1365                 // This event (moving without mouse click) is not passed further.
1366                 // This should be changed if it is further utilized.
1367                 buffer_.changed();
1368                 return;
1369         }
1370
1371         // Build temporary cursor.
1372         Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1373
1374         // Put anchor at the same position.
1375         cur.resetAnchor();
1376
1377         // Try to dispatch to an non-editable inset near this position
1378         // via the temp cursor. If the inset wishes to change the real
1379         // cursor it has to do so explicitly by using
1380         //  cur.bv().cursor() = cur;  (or similar)
1381         if (inset)
1382                 inset->dispatch(cur, cmd);
1383
1384         // Now dispatch to the temporary cursor. If the real cursor should
1385         // be modified, the inset's dispatch has to do so explicitly.
1386         if (!cur.result().dispatched())
1387                 cur.dispatch(cmd);
1388
1389         //Do we have a selection?
1390         theSelection().haveSelection(cursor().selection());
1391
1392         // If the command has been dispatched,
1393         if (cur.result().dispatched()
1394                 // an update is asked,
1395                 && cur.result().update())
1396                 processUpdateFlags(cur.result().update());
1397 }
1398
1399
1400 void BufferView::scroll(int y)
1401 {
1402         if (y > 0)
1403                 scrollDown(y);
1404         else if (y < 0)
1405                 scrollUp(-y);
1406 }
1407
1408
1409 void BufferView::scrollDown(int offset)
1410 {
1411         Text * text = &buffer_.text();
1412         TextMetrics & tm = d->text_metrics_[text];
1413         int ymax = height_ + offset;
1414         while (true) {
1415                 pair<pit_type, ParagraphMetrics const *> last = tm.last();
1416                 int bottom_pos = last.second->position() + last.second->descent();
1417                 if (last.first + 1 == int(text->paragraphs().size())) {
1418                         if (bottom_pos <= height_)
1419                                 return;
1420                         offset = min(offset, bottom_pos - height_);
1421                         break;
1422                 }
1423                 if (bottom_pos > ymax)
1424                         break;
1425                 tm.newParMetricsDown();
1426         }
1427         d->anchor_ypos_ -= offset;
1428         updateMetrics();
1429         buffer_.changed();
1430 }
1431
1432
1433 void BufferView::scrollUp(int offset)
1434 {
1435         Text * text = &buffer_.text();
1436         TextMetrics & tm = d->text_metrics_[text];
1437         int ymin = - offset;
1438         while (true) {
1439                 pair<pit_type, ParagraphMetrics const *> first = tm.first();
1440                 int top_pos = first.second->position() - first.second->ascent();
1441                 if (first.first == 0) {
1442                         if (top_pos >= 0)
1443                                 return;
1444                         offset = min(offset, - top_pos);
1445                         break;
1446                 }
1447                 if (top_pos < ymin)
1448                         break;
1449                 tm.newParMetricsUp();
1450         }
1451         d->anchor_ypos_ += offset;
1452         updateMetrics();
1453         buffer_.changed();
1454 }
1455
1456
1457 void BufferView::setCursorFromRow(int row)
1458 {
1459         int tmpid = -1;
1460         int tmppos = -1;
1461
1462         buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1463
1464         d->cursor_.reset(buffer_.inset());
1465         if (tmpid == -1)
1466                 buffer_.text().setCursor(d->cursor_, 0, 0);
1467         else
1468                 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1469 }
1470
1471
1472 void BufferView::gotoLabel(docstring const & label)
1473 {
1474         for (InsetIterator it = inset_iterator_begin(buffer_.inset()); it; ++it) {
1475                 vector<docstring> labels;
1476                 it->getLabelList(buffer_, labels);
1477                 if (find(labels.begin(), labels.end(), label) != labels.end()) {
1478                         setCursor(it);
1479                         showCursor();
1480                         return;
1481                 }
1482         }
1483 }
1484
1485
1486 TextMetrics const & BufferView::textMetrics(Text const * t) const
1487 {
1488         return const_cast<BufferView *>(this)->textMetrics(t);
1489 }
1490
1491
1492 TextMetrics & BufferView::textMetrics(Text const * t)
1493 {
1494         TextMetricsCache::iterator tmc_it  = d->text_metrics_.find(t);
1495         if (tmc_it == d->text_metrics_.end()) {
1496                 tmc_it = d->text_metrics_.insert(
1497                         make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1498         }
1499         return tmc_it->second;
1500 }
1501
1502
1503 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1504                 pit_type pit) const
1505 {
1506         return textMetrics(t).parMetrics(pit);
1507 }
1508
1509
1510 int BufferView::workHeight() const
1511 {
1512         return height_;
1513 }
1514
1515
1516 void BufferView::setCursor(DocIterator const & dit)
1517 {
1518         size_t const n = dit.depth();
1519         for (size_t i = 0; i < n; ++i)
1520                 dit[i].inset().edit(d->cursor_, true);
1521
1522         d->cursor_.setCursor(dit);
1523         d->cursor_.selection() = false;
1524 }
1525
1526
1527 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1528 {
1529         // Would be wrong to delete anything if we have a selection.
1530         if (cur.selection())
1531                 return false;
1532
1533         bool need_anchor_change = false;
1534         bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1535                 need_anchor_change);
1536
1537         if (need_anchor_change)
1538                 cur.resetAnchor();
1539
1540         if (!changed)
1541                 return false;
1542
1543         updateLabels(buffer_);
1544
1545         updateMetrics();
1546         buffer_.changed();
1547         return true;
1548 }
1549
1550
1551 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
1552 {
1553         BOOST_ASSERT(&cur.bv() == this);
1554
1555         if (!select)
1556                 // this event will clear selection so we save selection for
1557                 // persistent selection
1558                 cap::saveSelection(cursor());
1559
1560         // Has the cursor just left the inset?
1561         bool badcursor = false;
1562         bool leftinset = (&d->cursor_.inset() != &cur.inset());
1563         if (leftinset)
1564                 badcursor = notifyCursorLeaves(d->cursor_, cur);
1565
1566         // FIXME: shift-mouse selection doesn't work well across insets.
1567         bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
1568
1569         // do the dEPM magic if needed
1570         // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1571         // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1572         // the leftinset bool would not be necessary (badcursor instead).
1573         bool update = leftinset;
1574         if (!do_selection && !badcursor && d->cursor_.inTexted())
1575                 update |= checkDepm(cur, d->cursor_);
1576
1577         // if the cursor was in an empty script inset and the new
1578         // position is in the nucleus of the inset, notifyCursorLeaves
1579         // will kill the script inset itself. So we check all the
1580         // elements of the cursor to make sure that they are correct.
1581         // For an example, see bug 2933:
1582         // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1583         // The code below could maybe be moved to a DocIterator method.
1584         //lyxerr << "cur before " << cur <<endl;
1585         DocIterator dit(cur.inset());
1586         dit.push_back(cur.bottom());
1587         size_t i = 1;
1588         while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1589                 dit.push_back(cur[i]);
1590                 ++i;
1591         }
1592         //lyxerr << "5 cur after" << dit <<endl;
1593
1594         d->cursor_.setCursor(dit);
1595         d->cursor_.boundary(cur.boundary());
1596         if (do_selection)
1597                 d->cursor_.setSelection();
1598         else
1599                 d->cursor_.clearSelection();
1600
1601         d->cursor_.finishUndo();
1602         d->cursor_.setCurrentFont();
1603         return update;
1604 }
1605
1606
1607 void BufferView::putSelectionAt(DocIterator const & cur,
1608                                 int length, bool backwards)
1609 {
1610         d->cursor_.clearSelection();
1611
1612         setCursor(cur);
1613
1614         if (length) {
1615                 if (backwards) {
1616                         d->cursor_.pos() += length;
1617                         d->cursor_.setSelection(d->cursor_, -length);
1618                 } else
1619                         d->cursor_.setSelection(d->cursor_, length);
1620         }
1621 }
1622
1623
1624 Cursor & BufferView::cursor()
1625 {
1626         return d->cursor_;
1627 }
1628
1629
1630 Cursor const & BufferView::cursor() const
1631 {
1632         return d->cursor_;
1633 }
1634
1635
1636 pit_type BufferView::anchor_ref() const
1637 {
1638         return d->anchor_pit_;
1639 }
1640
1641
1642 bool BufferView::singleParUpdate()
1643 {
1644         Text & buftext = buffer_.text();
1645         pit_type const bottom_pit = d->cursor_.bottom().pit();
1646         TextMetrics & tm = textMetrics(&buftext);
1647         int old_height = tm.parMetrics(bottom_pit).height();
1648
1649         // In Single Paragraph mode, rebreak only
1650         // the (main text, not inset!) paragraph containing the cursor.
1651         // (if this paragraph contains insets etc., rebreaking will
1652         // recursively descend)
1653         tm.redoParagraph(bottom_pit);
1654         ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);                
1655         if (pm.height() != old_height)
1656                 // Paragraph height has changed so we cannot proceed to
1657                 // the singlePar optimisation.
1658                 return false;
1659
1660         d->update_strategy_ = SingleParUpdate;
1661
1662         LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
1663                 << " y2: " << pm.position() + pm.descent()
1664                 << " pit: " << bottom_pit
1665                 << " singlepar: 1");
1666         return true;
1667 }
1668
1669
1670 void BufferView::updateMetrics()
1671 {
1672         Text & buftext = buffer_.text();
1673         pit_type const npit = int(buftext.paragraphs().size());
1674
1675         // Clear out the position cache in case of full screen redraw,
1676         d->coord_cache_.clear();
1677
1678         // Clear out paragraph metrics to avoid having invalid metrics
1679         // in the cache from paragraphs not relayouted below
1680         // The complete text metrics will be redone.
1681         d->text_metrics_.clear();
1682
1683         TextMetrics & tm = textMetrics(&buftext);
1684
1685         // Rebreak anchor paragraph.
1686         tm.redoParagraph(d->anchor_pit_);
1687         ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
1688         anchor_pm.setPosition(d->anchor_ypos_);
1689
1690         LYXERR(Debug::PAINTING, "metrics: "
1691                 << " anchor pit = " << d->anchor_pit_
1692                 << " anchor ypos = " << d->anchor_ypos_);
1693
1694         // Redo paragraphs above anchor if necessary.
1695         int y1 = d->anchor_ypos_ - anchor_pm.ascent();
1696         // We are now just above the anchor paragraph.
1697         pit_type pit1 = d->anchor_pit_ - 1;
1698         for (; pit1 >= 0 && y1 >= 0; --pit1) {
1699                 tm.redoParagraph(pit1);
1700                 ParagraphMetrics & pm = tm.par_metrics_[pit1];
1701                 y1 -= pm.descent();
1702                 // Save the paragraph position in the cache.
1703                 pm.setPosition(y1);
1704                 y1 -= pm.ascent();
1705         }
1706
1707         // Redo paragraphs below the anchor if necessary.
1708         int y2 = d->anchor_ypos_ + anchor_pm.descent();
1709         // We are now just below the anchor paragraph.
1710         pit_type pit2 = d->anchor_pit_ + 1;
1711         for (; pit2 < npit && y2 <= height_; ++pit2) {
1712                 tm.redoParagraph(pit2);
1713                 ParagraphMetrics & pm = tm.par_metrics_[pit2];
1714                 y2 += pm.ascent();
1715                 // Save the paragraph position in the cache.
1716                 pm.setPosition(y2);
1717                 y2 += pm.descent();
1718         }
1719
1720         LYXERR(Debug::PAINTING, "Metrics: "
1721                 << " anchor pit = " << d->anchor_pit_
1722                 << " anchor ypos = " << d->anchor_ypos_
1723                 << " y1 = " << y1
1724                 << " y2 = " << y2
1725                 << " pit1 = " << pit1
1726                 << " pit2 = " << pit2);
1727
1728         d->update_strategy_ = FullScreenUpdate;
1729
1730         if (lyxerr.debugging(Debug::WORKAREA)) {
1731                 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
1732                 d->coord_cache_.dump();
1733         }
1734 }
1735
1736
1737 void BufferView::insertLyXFile(FileName const & fname)
1738 {
1739         BOOST_ASSERT(d->cursor_.inTexted());
1740
1741         // Get absolute path of file and add ".lyx"
1742         // to the filename if necessary
1743         FileName filename = fileSearch(string(), fname.absFilename(), "lyx");
1744
1745         docstring const disp_fn = makeDisplayPath(filename.absFilename());
1746         // emit message signal.
1747         message(bformat(_("Inserting document %1$s..."), disp_fn));
1748
1749         docstring res;
1750         Buffer buf("", false);
1751         if (buf.loadLyXFile(filename)) {
1752                 ErrorList & el = buffer_.errorList("Parse");
1753                 // Copy the inserted document error list into the current buffer one.
1754                 el = buf.errorList("Parse");
1755                 buffer_.undo().recordUndo(d->cursor_);
1756                 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
1757                                              buf.params().getTextClassPtr(), el);
1758                 res = _("Document %1$s inserted.");
1759         } else {
1760                 res = _("Could not insert document %1$s");
1761         }
1762
1763         updateMetrics();
1764         buffer_.changed();
1765         // emit message signal.
1766         message(bformat(res, disp_fn));
1767         buffer_.errors("Parse");
1768 }
1769
1770
1771 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
1772 {
1773         int x = 0;
1774         int y = 0;
1775         int lastw = 0;
1776
1777         // Addup contribution of nested insets, from inside to outside,
1778         // keeping the outer paragraph for a special handling below
1779         for (size_t i = dit.depth() - 1; i >= 1; --i) {
1780                 CursorSlice const & sl = dit[i];
1781                 int xx = 0;
1782                 int yy = 0;
1783                 
1784                 // get relative position inside sl.inset()
1785                 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
1786                 
1787                 // Make relative position inside of the edited inset relative to sl.inset()
1788                 x += xx;
1789                 y += yy;
1790                 
1791                 // In case of an RTL inset, the edited inset will be positioned to the left
1792                 // of xx:yy
1793                 if (sl.text()) {
1794                         bool boundary_i = boundary && i + 1 == dit.depth();
1795                         bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
1796                         if (rtl)
1797                                 x -= lastw;
1798                 }
1799
1800                 // remember width for the case that sl.inset() is positioned in an RTL inset
1801                 if (i && dit[i - 1].text()) {
1802                         // If this Inset is inside a Text Inset, retrieve the Dimension
1803                         // from the containing text instead of using Inset::dimension() which
1804                         // might not be implemented.
1805                         // FIXME (Abdel 23/09/2007): this is a bit messy because of the
1806                         // elimination of Inset::dim_ cache. This coordOffset() method needs
1807                         // to be rewritten in light of the new design.
1808                         Dimension const & dim = parMetrics(dit[i - 1].text(),
1809                                 dit[i - 1].pit()).insetDimension(&sl.inset());
1810                         lastw = dim.wid;
1811                 } else {
1812                         Dimension const dim = sl.inset().dimension(*this);
1813                         lastw = dim.wid;
1814                 }
1815                 
1816                 //lyxerr << "Cursor::getPos, i: "
1817                 // << i << " x: " << xx << " y: " << y << endl;
1818         }
1819
1820         // Add contribution of initial rows of outermost paragraph
1821         CursorSlice const & sl = dit[0];
1822         TextMetrics const & tm = textMetrics(sl.text());
1823         ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
1824         BOOST_ASSERT(!pm.rows().empty());
1825         y -= pm.rows()[0].ascent();
1826 #if 1
1827         // FIXME: document this mess
1828         size_t rend;
1829         if (sl.pos() > 0 && dit.depth() == 1) {
1830                 int pos = sl.pos();
1831                 if (pos && boundary)
1832                         --pos;
1833 //              lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
1834                 rend = pm.pos2row(pos);
1835         } else
1836                 rend = pm.pos2row(sl.pos());
1837 #else
1838         size_t rend = pm.pos2row(sl.pos());
1839 #endif
1840         for (size_t rit = 0; rit != rend; ++rit)
1841                 y += pm.rows()[rit].height();
1842         y += pm.rows()[rend].ascent();
1843         
1844         TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
1845         
1846         // Make relative position from the nested inset now bufferview absolute.
1847         int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
1848         x += xx;
1849         
1850         // In the RTL case place the nested inset at the left of the cursor in 
1851         // the outer paragraph
1852         bool boundary_1 = boundary && 1 == dit.depth();
1853         bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
1854         if (rtl)
1855                 x -= lastw;
1856         
1857         return Point(x, y);
1858 }
1859
1860
1861 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
1862 {
1863         CursorSlice const & bot = dit.bottom();
1864         TextMetrics const & tm = textMetrics(bot.text());
1865         if (!tm.has(bot.pit()))
1866                 return Point(-1, -1);
1867
1868         Point p = coordOffset(dit, boundary); // offset from outer paragraph
1869         p.y_ += tm.parMetrics(bot.pit()).position();
1870         return p;
1871 }
1872
1873
1874 void BufferView::draw(frontend::Painter & pain)
1875 {
1876         LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
1877         Text & text = buffer_.text();
1878         TextMetrics const & tm = d->text_metrics_[&text];
1879         int const y = tm.first().second->position();
1880         PainterInfo pi(this, pain);
1881
1882         switch (d->update_strategy_) {
1883
1884         case NoScreenUpdate:
1885                 // If no screen painting is actually needed, only some the different
1886                 // coordinates of insets and paragraphs needs to be updated.
1887                 pi.full_repaint = true;
1888                 pi.pain.setDrawingEnabled(false);
1889                 tm.draw(pi, 0, y);
1890                 break;
1891
1892         case SingleParUpdate:
1893                 pi.full_repaint = false;
1894                 // In general, only the current row of the outermost paragraph
1895                 // will be redrawn. Particular cases where selection spans
1896                 // multiple paragraph are correctly detected in TextMetrics.
1897                 tm.draw(pi, 0, y);
1898                 break;
1899
1900         case DecorationUpdate:
1901                 // FIXME: We should also distinguish DecorationUpdate to avoid text
1902                 // drawing if possible. This is not possible to do easily right now
1903                 // because of the single backing pixmap.
1904
1905         case FullScreenUpdate:
1906                 // The whole screen, including insets, will be refreshed.
1907                 pi.full_repaint = true;
1908
1909                 // Clear background.
1910                 pain.fillRectangle(0, 0, width_, height_,
1911                         buffer_.inset().backgroundColor());
1912
1913                 // Draw everything.
1914                 tm.draw(pi, 0, y);
1915
1916                 // and possibly grey out below
1917                 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
1918                 int const y2 = lastpm.second->position() + lastpm.second->descent();
1919                 if (y2 < height_)
1920                         pain.fillRectangle(0, y2, width_, height_ - y2, Color_bottomarea);
1921                 break;
1922         }
1923         LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING  ***");
1924
1925         // The scrollbar needs an update.
1926         updateScrollbar();
1927
1928         // Normalize anchor for next time
1929         pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
1930         pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
1931         for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
1932                 ParagraphMetrics const & pm = tm.parMetrics(pit);
1933                 if (pm.position() + pm.descent() > 0) {
1934                         d->anchor_pit_ = pit;
1935                         d->anchor_ypos_ = pm.position();
1936                         break;
1937                 }
1938         }
1939         LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
1940                 << "  anchor ypos = " << d->anchor_ypos_);
1941 }
1942
1943
1944 void BufferView::message(docstring const & msg)
1945 {
1946         if (d->gui_)
1947                 d->gui_->message(msg);
1948 }
1949
1950
1951 void BufferView::showDialog(string const & name)
1952 {
1953         if (d->gui_)
1954                 d->gui_->showDialog(name, string());
1955 }
1956
1957
1958 void BufferView::showDialog(string const & name,
1959         string const & data, Inset * inset)
1960 {
1961         if (d->gui_)
1962                 d->gui_->showDialog(name, data, inset);
1963 }
1964
1965
1966 void BufferView::updateDialog(string const & name, string const & data)
1967 {
1968         if (d->gui_)
1969                 d->gui_->updateDialog(name, data);
1970 }
1971
1972
1973 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
1974 {
1975         d->gui_ = gui;
1976 }
1977
1978
1979 // FIXME: Move this out of BufferView again
1980 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
1981 {
1982         if (!fname.isReadableFile()) {
1983                 docstring const error = from_ascii(strerror(errno));
1984                 docstring const file = makeDisplayPath(fname.absFilename(), 50);
1985                 docstring const text =
1986                   bformat(_("Could not read the specified document\n"
1987                             "%1$s\ndue to the error: %2$s"), file, error);
1988                 Alert::error(_("Could not read file"), text);
1989                 return docstring();
1990         }
1991
1992         if (!fname.isReadableFile()) {
1993                 docstring const file = makeDisplayPath(fname.absFilename(), 50);
1994                 docstring const text =
1995                   bformat(_("%1$s\n is not readable."), file);
1996                 Alert::error(_("Could not open file"), text);
1997                 return docstring();
1998         }
1999
2000         // FIXME UNICODE: We don't know the encoding of the file
2001         docstring file_content = fname.fileContents("UTF-8");
2002         if (file_content.empty()) {
2003                 Alert::error(_("Reading not UTF-8 encoded file"),
2004                              _("The file is not UTF-8 encoded.\n"
2005                                "It will be read as local 8Bit-encoded.\n"
2006                                "If this does not give the correct result\n"
2007                                "then please change the encoding of the file\n"
2008                                "to UTF-8 with a program other than LyX.\n"));
2009                 file_content = fname.fileContents("local8bit");
2010         }
2011
2012         return normalize_c(file_content);
2013 }
2014
2015
2016 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
2017 {
2018         docstring const tmpstr = contentsOfPlaintextFile(f);
2019
2020         if (tmpstr.empty())
2021                 return;
2022
2023         Cursor & cur = cursor();
2024         cap::replaceSelection(cur);
2025         buffer_.undo().recordUndo(cur);
2026         if (asParagraph)
2027                 cur.innerText()->insertStringAsParagraphs(cur, tmpstr);
2028         else
2029                 cur.innerText()->insertStringAsLines(cur, tmpstr);
2030
2031         updateMetrics();
2032         buffer_.changed();
2033 }
2034
2035 } // namespace lyx