]> git.lyx.org Git - lyx.git/blob - src/BufferView.cpp
Revert cs 28908: wrong fix.
[lyx.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 "BranchList.h"
20 #include "Buffer.h"
21 #include "buffer_funcs.h"
22 #include "BufferList.h"
23 #include "BufferParams.h"
24 #include "CoordCache.h"
25 #include "Cursor.h"
26 #include "CutAndPaste.h"
27 #include "DispatchResult.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 "MetricsInfo.h"
43 #include "Paragraph.h"
44 #include "paragraph_funcs.h"
45 #include "ParagraphParameters.h"
46 #include "ParIterator.h"
47 #include "Session.h"
48 #include "Text.h"
49 #include "TextClass.h"
50 #include "TextMetrics.h"
51 #include "TexRow.h"
52 #include "TocBackend.h"
53 #include "VSpace.h"
54 #include "WordLangTuple.h"
55
56 #include "insets/InsetBibtex.h"
57 #include "insets/InsetCommand.h" // ChangeRefs
58 #include "insets/InsetExternal.h"
59 #include "insets/InsetGraphics.h"
60 #include "insets/InsetRef.h"
61 #include "insets/InsetText.h"
62 #include "insets/InsetNote.h"
63
64 #include "frontends/alert.h"
65 #include "frontends/Application.h"
66 #include "frontends/Delegates.h"
67 #include "frontends/FontMetrics.h"
68 #include "frontends/Painter.h"
69 #include "frontends/Selection.h"
70
71 #include "graphics/Previews.h"
72
73 #include "support/convert.h"
74 #include "support/debug.h"
75 #include "support/ExceptionMessage.h"
76 #include "support/filetools.h"
77 #include "support/gettext.h"
78 #include "support/lstrings.h"
79 #include "support/Package.h"
80 #include "support/types.h"
81
82 #include <cerrno>
83 #include <fstream>
84 #include <functional>
85 #include <iterator>
86 #include <vector>
87
88 using namespace std;
89 using namespace lyx::support;
90
91 namespace lyx {
92
93 namespace Alert = frontend::Alert;
94
95 namespace {
96
97 /// Return an inset of this class if it exists at the current cursor position
98 template <class T>
99 T * getInsetByCode(Cursor const & cur, InsetCode code)
100 {
101         DocIterator it = cur;
102         Inset * inset = it.nextInset();
103         if (inset && inset->lyxCode() == code)
104                 return static_cast<T*>(inset);
105         return 0;
106 }
107
108
109 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
110         bool same_content);
111
112 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
113         docstring const & contents)
114 {
115         DocIterator tmpdit = dit;
116
117         while (tmpdit) {
118                 Inset const * inset = tmpdit.nextInset();
119                 if (inset
120                     && std::find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()
121                     && (contents.empty() ||
122                     static_cast<InsetCommand const *>(inset)->getFirstNonOptParam() == contents)) {
123                         dit = tmpdit;
124                         return true;
125                 }
126                 tmpdit.forwardInset();
127         }
128
129         return false;
130 }
131
132
133 /// Looks for next inset with one of the given codes.
134 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
135         bool same_content)
136 {
137         docstring contents;
138         DocIterator tmpdit = dit;
139         tmpdit.forwardInset();
140         if (!tmpdit)
141                 return false;
142
143         if (same_content) {
144                 Inset const * inset = tmpdit.nextInset();
145                 if (inset
146                     && std::find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()) {
147                         contents = static_cast<InsetCommand const *>(inset)->getFirstNonOptParam();
148                 }
149         }
150
151         if (!findNextInset(tmpdit, codes, contents)) {
152                 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
153                         Inset * inset = &tmpdit.bottom().inset();
154                         tmpdit = doc_iterator_begin(&inset->buffer(), inset);
155                         if (!findNextInset(tmpdit, codes, contents))
156                                 return false;
157                 } else {
158                         return false;
159                 }
160         }
161
162         dit = tmpdit;
163         return true;
164 }
165
166
167 /// Looks for next inset with the given code
168 void findInset(DocIterator & dit, InsetCode code, bool same_content)
169 {
170         findInset(dit, vector<InsetCode>(1, code), same_content);
171 }
172
173
174 /// Moves cursor to the next inset with one of the given codes.
175 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
176                bool same_content)
177 {
178         Cursor tmpcur = bv->cursor();
179         if (!findInset(tmpcur, codes, same_content)) {
180                 bv->cursor().message(_("No more insets"));
181                 return;
182         }
183
184         tmpcur.clearSelection();
185         bv->setCursor(tmpcur);
186         bv->showCursor();
187 }
188
189
190 /// Moves cursor to the next inset with given code.
191 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
192 {
193         gotoInset(bv, vector<InsetCode>(1, code), same_content);
194 }
195
196
197 /// A map from a Text to the associated text metrics
198 typedef map<Text const *, TextMetrics> TextMetricsCache;
199
200 enum ScreenUpdateStrategy {
201         NoScreenUpdate,
202         SingleParUpdate,
203         FullScreenUpdate,
204         DecorationUpdate
205 };
206
207 } // anon namespace
208
209
210 /////////////////////////////////////////////////////////////////////
211 //
212 // BufferView
213 //
214 /////////////////////////////////////////////////////////////////////
215
216 struct BufferView::Private
217 {
218         Private(BufferView & bv): wh_(0), cursor_(bv),
219                 anchor_pit_(0), anchor_ypos_(0),
220                 inlineCompletionUniqueChars_(0),
221                 last_inset_(0), bookmark_edit_position_(0), gui_(0)
222         {}
223
224         ///
225         ScrollbarParameters scrollbarParameters_;
226         ///
227         ScreenUpdateStrategy update_strategy_;
228         ///
229         CoordCache coord_cache_;
230
231         /// Estimated average par height for scrollbar.
232         int wh_;
233         /// this is used to handle XSelection events in the right manner.
234         struct {
235                 CursorSlice cursor;
236                 CursorSlice anchor;
237                 bool set;
238         } xsel_cache_;
239         ///
240         Cursor cursor_;
241         ///
242         pit_type anchor_pit_;
243         ///
244         int anchor_ypos_;
245         ///
246         vector<int> par_height_;
247
248         ///
249         DocIterator inlineCompletionPos_;
250         ///
251         docstring inlineCompletion_;
252         ///
253         size_t inlineCompletionUniqueChars_;
254
255         /// keyboard mapping object.
256         Intl intl_;
257
258         /// last visited inset.
259         /** kept to send setMouseHover(false).
260           * Not owned, so don't delete.
261           */
262         Inset * last_inset_;
263
264         // cache for id of the paragraph which was edited the last time
265         int bookmark_edit_position_;
266
267         mutable TextMetricsCache text_metrics_;
268
269         /// Whom to notify.
270         /** Not owned, so don't delete.
271           */
272         frontend::GuiBufferViewDelegate * gui_;
273
274         /// Cache for Find Next
275         FuncRequest search_request_cache_;
276 };
277
278
279 BufferView::BufferView(Buffer & buf)
280         : width_(0), height_(0), full_screen_(false), buffer_(buf),
281       d(new Private(*this))
282 {
283         d->xsel_cache_.set = false;
284         d->intl_.initKeyMapper(lyxrc.use_kbmap);
285
286         d->cursor_.setBuffer(&buf);
287         d->cursor_.push(buffer_.inset());
288         d->cursor_.resetAnchor();
289         d->cursor_.setCurrentFont();
290
291         if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
292                 thePreviews().generateBufferPreviews(buffer_);
293 }
294
295
296 BufferView::~BufferView()
297 {
298         // current buffer is going to be switched-off, save cursor pos
299         // Ideally, the whole cursor stack should be saved, but session
300         // currently can only handle bottom (whole document) level pit and pos.
301         // That is to say, if a cursor is in a nested inset, it will be
302         // restore to the left of the top level inset.
303         LastFilePosSection::FilePos fp;
304         fp.pit = d->cursor_.bottom().pit();
305         fp.pos = d->cursor_.bottom().pos();
306         theSession().lastFilePos().save(buffer_.fileName(), fp);
307
308         delete d;
309 }
310
311
312 int BufferView::rightMargin() const
313 {
314         // The additional test for the case the outliner is opened.
315         if (!full_screen_ ||
316                 !lyxrc.full_screen_limit ||
317                 width_ < lyxrc.full_screen_width + 20)
318                         return 10;
319
320         return (width_ - lyxrc.full_screen_width) / 2;
321 }
322
323
324 int BufferView::leftMargin() const
325 {
326         return rightMargin();
327 }
328
329
330 bool BufferView::isTopScreen() const
331 {
332         return d->scrollbarParameters_.position == d->scrollbarParameters_.min;
333 }
334
335
336 bool BufferView::isBottomScreen() const
337 {
338         return d->scrollbarParameters_.position == d->scrollbarParameters_.max;
339 }
340
341
342 Intl & BufferView::getIntl()
343 {
344         return d->intl_;
345 }
346
347
348 Intl const & BufferView::getIntl() const
349 {
350         return d->intl_;
351 }
352
353
354 CoordCache & BufferView::coordCache()
355 {
356         return d->coord_cache_;
357 }
358
359
360 CoordCache const & BufferView::coordCache() const
361 {
362         return d->coord_cache_;
363 }
364
365
366 Buffer & BufferView::buffer()
367 {
368         return buffer_;
369 }
370
371
372 Buffer const & BufferView::buffer() const
373 {
374         return buffer_;
375 }
376
377
378 bool BufferView::fitCursor()
379 {
380         if (cursorStatus(d->cursor_) == CUR_INSIDE) {
381                 frontend::FontMetrics const & fm =
382                         theFontMetrics(d->cursor_.getFont().fontInfo());
383                 int const asc = fm.maxAscent();
384                 int const des = fm.maxDescent();
385                 Point const p = getPos(d->cursor_, d->cursor_.boundary());
386                 if (p.y_ - asc >= 0 && p.y_ + des < height_)
387                         return false;
388         }
389         return true;
390 }
391
392
393 void BufferView::processUpdateFlags(Update::flags flags)
394 {
395         // last_inset_ points to the last visited inset. This pointer may become
396         // invalid because of keyboard editing. Since all such operations
397         // causes screen update(), I reset last_inset_ to avoid such a problem.
398         d->last_inset_ = 0;
399         // This is close to a hot-path.
400         LYXERR(Debug::DEBUG, "BufferView::processUpdateFlags()"
401                 << "[fitcursor = " << (flags & Update::FitCursor)
402                 << ", forceupdate = " << (flags & Update::Force)
403                 << ", singlepar = " << (flags & Update::SinglePar)
404                 << "]  buffer: " << &buffer_);
405
406         buffer_.updateMacros();
407
408         // Now do the first drawing step if needed. This consists on updating
409         // the CoordCache in updateMetrics().
410         // The second drawing step is done in WorkArea::redraw() if needed.
411
412         // Case when no explicit update is requested.
413         if (!flags) {
414                 // no need to redraw anything.
415                 d->update_strategy_ = NoScreenUpdate;
416                 return;
417         }
418
419         if (flags == Update::Decoration) {
420                 d->update_strategy_ = DecorationUpdate;
421                 buffer_.changed();
422                 return;
423         }
424
425         if (flags == Update::FitCursor
426                 || flags == (Update::Decoration | Update::FitCursor)) {
427                 // tell the frontend to update the screen if needed.
428                 if (fitCursor()) {
429                         showCursor();
430                         return;
431                 }
432                 if (flags & Update::Decoration) {
433                         d->update_strategy_ = DecorationUpdate;
434                         buffer_.changed();
435                         return;
436                 }
437                 // no screen update is needed.
438                 d->update_strategy_ = NoScreenUpdate;
439                 return;
440         }
441
442         bool const full_metrics = flags & Update::Force || !singleParUpdate();
443
444         if (full_metrics)
445                 // We have to update the full screen metrics.
446                 updateMetrics();
447
448         if (!(flags & Update::FitCursor)) {
449                 // Nothing to do anymore. Trigger a redraw and return
450                 buffer_.changed();
451                 return;
452         }
453
454         // updateMetrics() does not update paragraph position
455         // This is done at draw() time. So we need a redraw!
456         buffer_.changed();
457
458         if (fitCursor()) {
459                 // The cursor is off screen so ensure it is visible.
460                 // refresh it:
461                 showCursor();
462         }
463 }
464
465
466 void BufferView::updateScrollbar()
467 {
468         if (height_ == 0 && width_ == 0)
469                 return;
470
471         // We prefer fixed size line scrolling.
472         d->scrollbarParameters_.single_step = defaultRowHeight();
473         // We prefer full screen page scrolling.
474         d->scrollbarParameters_.page_step = height_;
475
476         Text & t = buffer_.text();
477         TextMetrics & tm = d->text_metrics_[&t];                
478
479         LYXERR(Debug::GUI, " Updating scrollbar: height: "
480                 << t.paragraphs().size()
481                 << " curr par: " << d->cursor_.bottom().pit()
482                 << " default height " << defaultRowHeight());
483
484         size_t const parsize = t.paragraphs().size();
485         if (d->par_height_.size() != parsize) {
486                 d->par_height_.clear();
487                 // FIXME: We assume a default paragraph height of 2 rows. This
488                 // should probably be pondered with the screen width.
489                 d->par_height_.resize(parsize, defaultRowHeight() * 2);
490         }
491
492         // Look at paragraph heights on-screen
493         pair<pit_type, ParagraphMetrics const *> first = tm.first();
494         pair<pit_type, ParagraphMetrics const *> last = tm.last();
495         for (pit_type pit = first.first; pit <= last.first; ++pit) {
496                 d->par_height_[pit] = tm.parMetrics(pit).height();
497                 LYXERR(Debug::SCROLLING, "storing height for pit " << pit << " : "
498                         << d->par_height_[pit]);
499         }
500
501         int top_pos = first.second->position() - first.second->ascent();
502         int bottom_pos = last.second->position() + last.second->descent();
503         bool first_visible = first.first == 0 && top_pos >= 0;
504         bool last_visible = last.first + 1 == int(parsize) && bottom_pos <= height_;
505         if (first_visible && last_visible) {
506                 d->scrollbarParameters_.min = 0;
507                 d->scrollbarParameters_.max = 0;
508                 return;
509         }
510
511         d->scrollbarParameters_.min = top_pos;
512         for (size_t i = 0; i != size_t(first.first); ++i)
513                 d->scrollbarParameters_.min -= d->par_height_[i];
514         d->scrollbarParameters_.max = bottom_pos;
515         for (size_t i = last.first + 1; i != parsize; ++i)
516                 d->scrollbarParameters_.max += d->par_height_[i];
517
518         d->scrollbarParameters_.position = 0;
519         // The reference is the top position so we remove one page.
520         d->scrollbarParameters_.max -= d->scrollbarParameters_.page_step;
521 }
522
523
524 ScrollbarParameters const & BufferView::scrollbarParameters() const
525 {
526         return d->scrollbarParameters_;
527 }
528
529
530 docstring BufferView::toolTip(int x, int y) const
531 {
532         // Get inset under mouse, if there is one.
533         Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
534         if (!covering_inset)
535                 // No inset, no tooltip...
536                 return docstring();
537         return covering_inset->toolTip(*this, x, y);
538 }
539
540
541 docstring BufferView::contextMenu(int x, int y) const
542 {
543         //If there is a selection, return the containing inset menu
544         if (d->cursor_.selection())
545                 return d->cursor_.inset().contextMenu(*this, x, y);
546
547         // Get inset under mouse, if there is one.
548         Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
549         if (covering_inset)
550                 return covering_inset->contextMenu(*this, x, y);
551
552         return buffer_.inset().contextMenu(*this, x, y);
553 }
554
555
556 void BufferView::scrollDocView(int value)
557 {
558         int const offset = value - d->scrollbarParameters_.position;
559
560         // No scrolling at all? No need to redraw anything
561         if (offset == 0)
562                 return;
563
564         // If the offset is less than 2 screen height, prefer to scroll instead.
565         if (abs(offset) <= 2 * height_) {
566                 d->anchor_ypos_ -= offset;
567                 updateMetrics();
568                 buffer_.changed();
569                 return;
570         }
571
572         // cut off at the top
573         if (value <= d->scrollbarParameters_.min) {
574                 DocIterator dit = doc_iterator_begin(&buffer_);
575                 showCursor(dit);
576                 LYXERR(Debug::SCROLLING, "scroll to top");
577                 return;
578         }
579
580         // cut off at the bottom
581         if (value >= d->scrollbarParameters_.max) {
582                 DocIterator dit = doc_iterator_end(&buffer_);
583                 dit.backwardPos();
584                 showCursor(dit);
585                 LYXERR(Debug::SCROLLING, "scroll to bottom");
586                 return;
587         }
588
589         // find paragraph at target position
590         int par_pos = d->scrollbarParameters_.min;
591         pit_type i = 0;
592         for (; i != int(d->par_height_.size()); ++i) {
593                 par_pos += d->par_height_[i];
594                 if (par_pos >= value)
595                         break;
596         }
597
598         if (par_pos < value) {
599                 // It seems we didn't find the correct pit so stay on the safe side and
600                 // scroll to bottom.
601                 LYXERR0("scrolling position not found!");
602                 scrollDocView(d->scrollbarParameters_.max);
603                 return;
604         }
605
606         DocIterator dit = doc_iterator_begin(&buffer_);
607         dit.pit() = i;
608         LYXERR(Debug::SCROLLING, "value = " << value << " -> scroll to pit " << i);
609         showCursor(dit);
610 }
611
612
613 // FIXME: this method is not working well.
614 void BufferView::setCursorFromScrollbar()
615 {
616         TextMetrics & tm = d->text_metrics_[&buffer_.text()];
617
618         int const height = 2 * defaultRowHeight();
619         int const first = height;
620         int const last = height_ - height;
621         int newy = 0;
622         Cursor const & oldcur = d->cursor_;
623
624         switch (cursorStatus(oldcur)) {
625         case CUR_ABOVE:
626                 newy = first;
627                 break;
628         case CUR_BELOW:
629                 newy = last;
630                 break;
631         case CUR_INSIDE:
632                 int const y = getPos(oldcur, oldcur.boundary()).y_;
633                 newy = min(last, max(y, first));
634                 if (y == newy) 
635                         return;
636         }
637         // We reset the cursor because cursorStatus() does not
638         // work when the cursor is within mathed.
639         Cursor cur(*this);
640         cur.reset(buffer_.inset());
641         tm.setCursorFromCoordinates(cur, 0, newy);
642
643         // update the bufferview cursor and notify insets
644         // FIXME: Care about the d->cursor_ flags to redraw if needed
645         Cursor old = d->cursor_;
646         mouseSetCursor(cur);
647         bool badcursor = notifyCursorLeavesOrEnters(old, d->cursor_);
648         if (badcursor)
649                 d->cursor_.fixIfBroken();
650 }
651
652
653 Change const BufferView::getCurrentChange() const
654 {
655         if (!d->cursor_.selection())
656                 return Change(Change::UNCHANGED);
657
658         DocIterator dit = d->cursor_.selectionBegin();
659         return dit.paragraph().lookupChange(dit.pos());
660 }
661
662
663 // this could be used elsewhere as well?
664 // FIXME: This does not work within mathed!
665 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
666 {
667         Point const p = getPos(dit, dit.boundary());
668         if (p.y_ < 0)
669                 return CUR_ABOVE;
670         if (p.y_ > workHeight())
671                 return CUR_BELOW;
672         return CUR_INSIDE;
673 }
674
675
676 void BufferView::bookmarkEditPosition()
677 {
678         // Don't eat cpu time for each keystroke
679         if (d->cursor_.paragraph().id() == d->bookmark_edit_position_)
680                 return;
681         saveBookmark(0);
682         d->bookmark_edit_position_ = d->cursor_.paragraph().id();
683 }
684
685
686 void BufferView::saveBookmark(unsigned int idx)
687 {
688         // tentatively save bookmark, id and pos will be used to
689         // acturately locate a bookmark in a 'live' lyx session.
690         // pit and pos will be updated with bottom level pit/pos
691         // when lyx exits.
692         theSession().bookmarks().save(
693                 buffer_.fileName(),
694                 d->cursor_.bottom().pit(),
695                 d->cursor_.bottom().pos(),
696                 d->cursor_.paragraph().id(),
697                 d->cursor_.pos(),
698                 idx
699         );
700         if (idx)
701                 // emit message signal.
702                 message(_("Save bookmark"));
703 }
704
705
706 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
707         int top_id, pos_type top_pos)
708 {
709         bool success = false;
710         DocIterator dit;
711
712         d->cursor_.clearSelection();
713
714         // if a valid par_id is given, try it first
715         // This is the case for a 'live' bookmark when unique paragraph ID
716         // is used to track bookmarks.
717         if (top_id > 0) {
718                 dit = buffer_.getParFromID(top_id);
719                 if (!dit.atEnd()) {
720                         dit.pos() = min(dit.paragraph().size(), top_pos);
721                         // Some slices of the iterator may not be
722                         // reachable (e.g. closed collapsable inset)
723                         // so the dociterator may need to be
724                         // shortened. Otherwise, setCursor may crash
725                         // lyx when the cursor can not be set to these
726                         // insets.
727                         size_t const n = dit.depth();
728                         for (size_t i = 0; i < n; ++i)
729                                 if (dit[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
730                                         dit.resize(i);
731                                         break;
732                                 }
733                         success = true;
734                 }
735         }
736
737         // if top_id == 0, or searching through top_id failed
738         // This is the case for a 'restored' bookmark when only bottom
739         // (document level) pit was saved. Because of this, bookmark
740         // restoration is inaccurate. If a bookmark was within an inset,
741         // it will be restored to the left of the outmost inset that contains
742         // the bookmark.
743         if (bottom_pit < int(buffer_.paragraphs().size())) {
744                 dit = doc_iterator_begin(&buffer_);
745                                 
746                 dit.pit() = bottom_pit;
747                 dit.pos() = min(bottom_pos, dit.paragraph().size());
748                 success = true;
749         }
750
751         if (success) {
752                 // Note: only bottom (document) level pit is set.
753                 setCursor(dit);
754                 // set the current font.
755                 d->cursor_.setCurrentFont();
756                 // To center the screen on this new position we need the
757                 // paragraph position which is computed at draw() time.
758                 // So we need a redraw!
759                 buffer_.changed();
760                 if (fitCursor())
761                         showCursor();
762         }
763
764         return success;
765 }
766
767
768 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
769 {
770         if (lyxrc.rtl_support) {
771                 if (d->cursor_.real_current_font.isRightToLeft()) {
772                         if (d->intl_.keymap == Intl::PRIMARY)
773                                 d->intl_.keyMapSec();
774                 } else {
775                         if (d->intl_.keymap == Intl::SECONDARY)
776                                 d->intl_.keyMapPrim();
777                 }
778         }
779
780         d->intl_.getTransManager().translateAndInsert(c, t, cur);
781 }
782
783
784 int BufferView::workWidth() const
785 {
786         return width_;
787 }
788
789
790 void BufferView::showCursor()
791 {
792         showCursor(d->cursor_);
793 }
794
795
796 void BufferView::showCursor(DocIterator const & dit)
797 {
798         // We are not properly started yet, delay until resizing is
799         // done.
800         if (height_ == 0)
801                 return;
802
803         LYXERR(Debug::SCROLLING, "recentering!");
804
805         CursorSlice const & bot = dit.bottom();
806         TextMetrics & tm = d->text_metrics_[bot.text()];
807
808         pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
809         int bot_pit = bot.pit();
810         if (bot_pit > max_pit) {
811                 // FIXME: Why does this happen?
812                 LYXERR0("bottom pit is greater that max pit: "
813                         << bot_pit << " > " << max_pit);
814                 bot_pit = max_pit;
815         }
816
817         if (bot_pit == tm.first().first - 1)
818                 tm.newParMetricsUp();
819         else if (bot_pit == tm.last().first + 1)
820                 tm.newParMetricsDown();
821
822         if (tm.contains(bot_pit)) {
823                 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
824                 LASSERT(!pm.rows().empty(), /**/);
825                 // FIXME: smooth scrolling doesn't work in mathed.
826                 CursorSlice const & cs = dit.innerTextSlice();
827                 int offset = coordOffset(dit, dit.boundary()).y_;
828                 int ypos = pm.position() + offset;
829                 Dimension const & row_dim =
830                         pm.getRow(cs.pos(), dit.boundary()).dimension();
831                 int scrolled = 0;
832                 if (ypos - row_dim.ascent() < 0)
833                         scrolled = scrollUp(- ypos + row_dim.ascent());
834                 else if (ypos + row_dim.descent() > height_)
835                         scrolled = scrollDown(ypos - height_ + defaultRowHeight() ); 
836
837                 // else, nothing to do, the cursor is already visible so we just return.
838                 if (scrolled != 0) {
839                         updateMetrics();
840                         buffer_.changed();
841                 }
842                 return;
843         }
844
845         // fix inline completion position
846         if (d->inlineCompletionPos_.fixIfBroken())
847                 d->inlineCompletionPos_ = DocIterator();
848
849         tm.redoParagraph(bot_pit);
850         ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
851         int offset = coordOffset(dit, dit.boundary()).y_;
852
853         d->anchor_pit_ = bot_pit;
854         CursorSlice const & cs = dit.innerTextSlice();
855         Dimension const & row_dim =
856                 pm.getRow(cs.pos(), dit.boundary()).dimension();
857
858         if (d->anchor_pit_ == 0)
859                 d->anchor_ypos_ = offset + pm.ascent();
860         else if (d->anchor_pit_ == max_pit)
861                 d->anchor_ypos_ = height_ - offset - row_dim.descent();
862         else if (offset > height_)
863                 d->anchor_ypos_ = height_ - offset - defaultRowHeight();
864         else
865                 d->anchor_ypos_ = defaultRowHeight() * 2;
866
867         updateMetrics();
868         buffer_.changed();
869 }
870
871
872 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
873 {
874         FuncStatus flag;
875
876         Cursor & cur = d->cursor_;
877
878         switch (cmd.action) {
879
880         case LFUN_UNDO:
881                 flag.setEnabled(buffer_.undo().hasUndoStack());
882                 break;
883         case LFUN_REDO:
884                 flag.setEnabled(buffer_.undo().hasRedoStack());
885                 break;
886         case LFUN_FILE_INSERT:
887         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
888         case LFUN_FILE_INSERT_PLAINTEXT:
889         case LFUN_BOOKMARK_SAVE:
890                 // FIXME: Actually, these LFUNS should be moved to Text
891                 flag.setEnabled(cur.inTexted());
892                 break;
893         case LFUN_FONT_STATE:
894         case LFUN_LABEL_INSERT:
895         case LFUN_INFO_INSERT:
896         case LFUN_INSET_EDIT:
897         case LFUN_PARAGRAPH_GOTO:
898         case LFUN_NOTE_NEXT:
899         case LFUN_REFERENCE_NEXT:
900         case LFUN_WORD_FIND:
901         case LFUN_WORD_FINDADV:
902         case LFUN_WORD_REPLACE:
903         case LFUN_MARK_OFF:
904         case LFUN_MARK_ON:
905         case LFUN_MARK_TOGGLE:
906         case LFUN_SCREEN_RECENTER:
907         case LFUN_BIBTEX_DATABASE_ADD:
908         case LFUN_BIBTEX_DATABASE_DEL:
909         case LFUN_NOTES_MUTATE:
910         case LFUN_ALL_INSETS_TOGGLE:
911         case LFUN_STATISTICS:
912                 flag.setEnabled(true);
913                 break;
914
915         // @todo Test if current WorkArea is the search WorkArea
916         case LFUN_REGEXP_MODE:
917                 flag.setEnabled(! this->cursor().inRegexped());
918                 break;
919
920         case LFUN_COPY_LABEL_AS_REF: {
921                 // if there is an inset at cursor, see whether it
922                 // handles the lfun
923                 Inset * inset = cur.nextInset();
924                 if (!inset || !inset->getStatus(cur, cmd, flag))
925                         flag.setEnabled(false);
926                 break;
927         }
928
929         case LFUN_NEXT_INSET_TOGGLE: 
930         case LFUN_NEXT_INSET_MODIFY: {
931                 // this is the real function we want to invoke
932                 FuncRequest tmpcmd = cmd;
933                 tmpcmd.action = (cmd.action == LFUN_NEXT_INSET_TOGGLE) 
934                         ? LFUN_INSET_TOGGLE : LFUN_INSET_MODIFY;
935                 // if there is an inset at cursor, see whether it
936                 // handles the lfun, other start from scratch
937                 Inset * inset = cur.nextInset();
938                 if (!inset || !inset->getStatus(cur, tmpcmd, flag))
939                         flag = lyx::getStatus(tmpcmd);
940                 break;
941         }
942
943         case LFUN_LABEL_GOTO: {
944                 flag.setEnabled(!cmd.argument().empty()
945                     || getInsetByCode<InsetRef>(cur, REF_CODE));
946                 break;
947         }
948
949         case LFUN_CHANGES_TRACK:
950                 flag.setEnabled(true);
951                 flag.setOnOff(buffer_.params().trackChanges);
952                 break;
953
954         case LFUN_CHANGES_OUTPUT:
955                 flag.setEnabled(true);
956                 flag.setOnOff(buffer_.params().outputChanges);
957                 break;
958
959         case LFUN_CHANGES_MERGE:
960         case LFUN_CHANGE_NEXT:
961         case LFUN_ALL_CHANGES_ACCEPT:
962         case LFUN_ALL_CHANGES_REJECT:
963                 // TODO: context-sensitive enabling of LFUNs
964                 // In principle, these command should only be enabled if there
965                 // is a change in the document. However, without proper
966                 // optimizations, this will inevitably result in poor performance.
967                 flag.setEnabled(true);
968                 break;
969
970         case LFUN_BUFFER_TOGGLE_COMPRESSION: {
971                 flag.setOnOff(buffer_.params().compressed);
972                 break;
973         }
974         
975         case LFUN_SCREEN_UP:
976         case LFUN_SCREEN_DOWN:
977         case LFUN_SCROLL:
978         case LFUN_SCREEN_UP_SELECT:
979         case LFUN_SCREEN_DOWN_SELECT:
980                 flag.setEnabled(true);
981                 break;
982
983         case LFUN_LAYOUT_TABULAR:
984                 flag.setEnabled(cur.innerInsetOfType(TABULAR_CODE));
985                 break;
986
987         case LFUN_LAYOUT:
988                 flag.setEnabled(!cur.inset().forcePlainLayout(cur.idx()));
989                 break;
990
991         case LFUN_LAYOUT_PARAGRAPH:
992                 flag.setEnabled(cur.inset().allowParagraphCustomization(cur.idx()));
993                 break;
994
995         case LFUN_INSET_SETTINGS: {
996                 InsetCode code = cur.inset().lyxCode();
997                 if (cmd.getArg(0) == insetName(code)) {
998                         flag.setEnabled(true);
999                         break;
1000                 }
1001                 bool enable = false;
1002                 InsetCode next_code = cur.nextInset()
1003                         ? cur.nextInset()->lyxCode() : NO_CODE;
1004                 //FIXME: remove these special cases:
1005                 switch (next_code) {
1006                         case TABULAR_CODE:
1007                         case ERT_CODE:
1008                         case FLOAT_CODE:
1009                         case WRAP_CODE:
1010                         case NOTE_CODE:
1011                         case BRANCH_CODE:
1012                         case PHANTOM_CODE:
1013                         case BOX_CODE:
1014                         case LISTINGS_CODE:
1015                                 enable = (cmd.argument().empty() ||
1016                                           cmd.getArg(0) == insetName(next_code));
1017                                 break;
1018                         default:
1019                                 break;
1020                 }
1021                 flag.setEnabled(enable);
1022                 break;
1023         }
1024
1025         case LFUN_DIALOG_SHOW_NEW_INSET:
1026                 flag.setEnabled(cur.inset().lyxCode() != ERT_CODE &&
1027                         cur.inset().lyxCode() != LISTINGS_CODE);
1028                 if (cur.inset().lyxCode() == CAPTION_CODE) {
1029                         FuncStatus flag;
1030                         if (cur.inset().getStatus(cur, cmd, flag))
1031                                 return flag;
1032                 }
1033                 break;
1034
1035         case LFUN_BRANCH_ACTIVATE: 
1036         case LFUN_BRANCH_DEACTIVATE: {
1037                 bool enable = false;
1038                 docstring const branchName = cmd.argument();
1039                 if (!branchName.empty())
1040                         enable = buffer_.params().branchlist().find(branchName);
1041                 flag.setEnabled(enable);
1042                 break;
1043         }
1044
1045         default:
1046                 flag.setEnabled(false);
1047         }
1048
1049         return flag;
1050 }
1051
1052
1053 bool BufferView::dispatch(FuncRequest const & cmd)
1054 {
1055         //lyxerr << [ cmd = " << cmd << "]" << endl;
1056
1057         // Make sure that the cached BufferView is correct.
1058         LYXERR(Debug::ACTION, " action[" << cmd.action << ']'
1059                 << " arg[" << to_utf8(cmd.argument()) << ']'
1060                 << " x[" << cmd.x << ']'
1061                 << " y[" << cmd.y << ']'
1062                 << " button[" << cmd.button() << ']');
1063
1064         Cursor & cur = d->cursor_;
1065
1066         switch (cmd.action) {
1067
1068         case LFUN_UNDO:
1069                 cur.message(_("Undo"));
1070                 cur.clearSelection();
1071                 if (!cur.textUndo())
1072                         cur.message(_("No further undo information"));
1073                 else
1074                         processUpdateFlags(Update::Force | Update::FitCursor);
1075                 break;
1076
1077         case LFUN_REDO:
1078                 cur.message(_("Redo"));
1079                 cur.clearSelection();
1080                 if (!cur.textRedo())
1081                         cur.message(_("No further redo information"));
1082                 else
1083                         processUpdateFlags(Update::Force | Update::FitCursor);
1084                 break;
1085
1086         case LFUN_FONT_STATE:
1087                 cur.message(cur.currentState());
1088                 break;
1089
1090         case LFUN_BOOKMARK_SAVE:
1091                 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1092                 break;
1093
1094         case LFUN_LABEL_GOTO: {
1095                 docstring label = cmd.argument();
1096                 if (label.empty()) {
1097                         InsetRef * inset =
1098                                 getInsetByCode<InsetRef>(d->cursor_, REF_CODE);
1099                         if (inset) {
1100                                 label = inset->getParam("reference");
1101                                 // persistent=false: use temp_bookmark
1102                                 saveBookmark(0);
1103                         }
1104                 }
1105                 if (!label.empty())
1106                         gotoLabel(label);
1107                 break;
1108         }
1109         
1110         case LFUN_INSET_EDIT: {
1111                 FuncRequest fr(cmd);
1112                 // if there is an inset at cursor, see whether it
1113                 // can be modified.
1114                 Inset * inset = cur.nextInset();
1115                 if (inset)
1116                         inset->dispatch(cur, fr);
1117                 // if it did not work, try the underlying inset.
1118                 if (!inset || !cur.result().dispatched())
1119                         cur.dispatch(cmd);
1120
1121                 // FIXME I'm adding the last break to solve a crash,
1122                 // but that is obviously not right.
1123                 if (!cur.result().dispatched())
1124                         // It did not work too; no action needed.
1125                         break;
1126                 break;
1127         }
1128
1129         case LFUN_PARAGRAPH_GOTO: {
1130                 int const id = convert<int>(cmd.getArg(0));
1131                 int const pos = convert<int>(cmd.getArg(1));
1132                 int i = 0;
1133                 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1134                         b = theBufferList().next(b)) {
1135
1136                         DocIterator dit = b->getParFromID(id);
1137                         if (dit.atEnd()) {
1138                                 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1139                                 ++i;
1140                                 continue;
1141                         }
1142                         LYXERR(Debug::INFO, "Paragraph " << dit.paragraph().id()
1143                                 << " found in buffer `"
1144                                 << b->absFileName() << "'.");
1145
1146                         if (b == &buffer_) {
1147                                 // Set the cursor
1148                                 dit.pos() = pos;
1149                                 setCursor(dit);
1150                                 processUpdateFlags(Update::Force | Update::FitCursor);
1151                         } else {
1152                                 // Switch to other buffer view and resend cmd
1153                                 theLyXFunc().dispatch(FuncRequest(
1154                                         LFUN_BUFFER_SWITCH, b->absFileName()));
1155                                 theLyXFunc().dispatch(cmd);
1156                         }
1157                         break;
1158                 }
1159                 break;
1160         }
1161
1162         case LFUN_NOTE_NEXT:
1163                 gotoInset(this, NOTE_CODE, false);
1164                 break;
1165
1166         case LFUN_REFERENCE_NEXT: {
1167                 vector<InsetCode> tmp;
1168                 tmp.push_back(LABEL_CODE);
1169                 tmp.push_back(REF_CODE);
1170                 gotoInset(this, tmp, true);
1171                 break;
1172         }
1173
1174         case LFUN_CHANGES_TRACK:
1175                 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1176                 break;
1177
1178         case LFUN_CHANGES_OUTPUT:
1179                 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1180                 if (buffer_.params().outputChanges) {
1181                         bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
1182                         bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
1183                                           LaTeXFeatures::isAvailable("xcolor");
1184
1185                         if (!dvipost && !xcolorulem) {
1186                                 Alert::warning(_("Changes not shown in LaTeX output"),
1187                                                _("Changes will not be highlighted in LaTeX output, "
1188                                                  "because neither dvipost nor xcolor/ulem are installed.\n"
1189                                                  "Please install these packages or redefine "
1190                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1191                         } else if (!xcolorulem) {
1192                                 Alert::warning(_("Changes not shown in LaTeX output"),
1193                                                _("Changes will not be highlighted in LaTeX output "
1194                                                  "when using pdflatex, because xcolor and ulem are not installed.\n"
1195                                                  "Please install both packages or redefine "
1196                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1197                         }
1198                 }
1199                 break;
1200
1201         case LFUN_CHANGE_NEXT:
1202                 findNextChange(this);
1203                 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1204                 processUpdateFlags(Update::Force | Update::FitCursor);
1205                 break;
1206
1207         case LFUN_CHANGES_MERGE:
1208                 if (findNextChange(this)) {
1209                         processUpdateFlags(Update::Force | Update::FitCursor);
1210                         showDialog("changes");
1211                 }
1212                 break;
1213
1214         case LFUN_ALL_CHANGES_ACCEPT:
1215                 // select complete document
1216                 d->cursor_.reset(buffer_.inset());
1217                 d->cursor_.selHandle(true);
1218                 buffer_.text().cursorBottom(d->cursor_);
1219                 // accept everything in a single step to support atomic undo
1220                 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::ACCEPT);
1221                 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1222                 processUpdateFlags(Update::Force | Update::FitCursor);
1223                 break;
1224
1225         case LFUN_ALL_CHANGES_REJECT:
1226                 // select complete document
1227                 d->cursor_.reset(buffer_.inset());
1228                 d->cursor_.selHandle(true);
1229                 buffer_.text().cursorBottom(d->cursor_);
1230                 // reject everything in a single step to support atomic undo
1231                 // Note: reject does not work recursively; the user may have to repeat the operation
1232                 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::REJECT);
1233                 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1234                 processUpdateFlags(Update::Force | Update::FitCursor);
1235                 break;
1236
1237         case LFUN_WORD_FIND: {
1238                 FuncRequest req = cmd;
1239                 if (cmd.argument().empty() && !d->search_request_cache_.argument().empty())
1240                         req = d->search_request_cache_;
1241                 if (req.argument().empty()) {
1242                         theLyXFunc().dispatch(FuncRequest(LFUN_DIALOG_SHOW, "findreplace"));
1243                         break;
1244                 }
1245                 if (find(this, req))
1246                         showCursor();
1247                 else
1248                         message(_("String not found!"));
1249                 d->search_request_cache_ = req;
1250                 break;
1251         }
1252
1253         case LFUN_WORD_REPLACE: {
1254                 bool has_deleted = false;
1255                 if (cur.selection()) {
1256                         DocIterator beg = cur.selectionBegin();
1257                         DocIterator end = cur.selectionEnd();
1258                         if (beg.pit() == end.pit()) {
1259                                 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1260                                         if (cur.paragraph().isDeleted(p))
1261                                                 has_deleted = true;
1262                                 }
1263                         }
1264                 }
1265                 replace(this, cmd, has_deleted);
1266                 break;
1267         }
1268
1269         case LFUN_WORD_FINDADV:
1270                 findAdv(this, cmd);
1271                 break;
1272
1273         case LFUN_MARK_OFF:
1274                 cur.clearSelection();
1275                 cur.resetAnchor();
1276                 cur.message(from_utf8(N_("Mark off")));
1277                 break;
1278
1279         case LFUN_MARK_ON:
1280                 cur.clearSelection();
1281                 cur.setMark(true);
1282                 cur.resetAnchor();
1283                 cur.message(from_utf8(N_("Mark on")));
1284                 break;
1285
1286         case LFUN_MARK_TOGGLE:
1287                 cur.clearSelection();
1288                 if (cur.mark()) {
1289                         cur.setMark(false);
1290                         cur.message(from_utf8(N_("Mark removed")));
1291                 } else {
1292                         cur.setMark(true);
1293                         cur.message(from_utf8(N_("Mark set")));
1294                 }
1295                 cur.resetAnchor();
1296                 break;
1297
1298         case LFUN_SCREEN_RECENTER:
1299                 showCursor();
1300                 break;
1301
1302         case LFUN_BIBTEX_DATABASE_ADD: {
1303                 Cursor tmpcur = d->cursor_;
1304                 findInset(tmpcur, BIBTEX_CODE, false);
1305                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1306                                                 BIBTEX_CODE);
1307                 if (inset) {
1308                         if (inset->addDatabase(cmd.argument()))
1309                                 buffer_.updateBibfilesCache();
1310                 }
1311                 break;
1312         }
1313
1314         case LFUN_BIBTEX_DATABASE_DEL: {
1315                 Cursor tmpcur = d->cursor_;
1316                 findInset(tmpcur, BIBTEX_CODE, false);
1317                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1318                                                 BIBTEX_CODE);
1319                 if (inset) {
1320                         if (inset->delDatabase(cmd.argument()))
1321                                 buffer_.updateBibfilesCache();
1322                 }
1323                 break;
1324         }
1325
1326         case LFUN_STATISTICS: {
1327                 DocIterator from, to;
1328                 if (cur.selection()) {
1329                         from = cur.selectionBegin();
1330                         to = cur.selectionEnd();
1331                 } else {
1332                         from = doc_iterator_begin(&buffer_);
1333                         to = doc_iterator_end(&buffer_);
1334                 }
1335                 int const words = countWords(from, to);
1336                 int const chars = countChars(from, to, false);
1337                 int const chars_blanks = countChars(from, to, true);
1338                 docstring message;
1339                 if (cur.selection())
1340                         message = _("Statistics for the selection:");
1341                 else
1342                         message = _("Statistics for the document:");
1343                 message += "\n\n";
1344                 if (words != 1)
1345                         message += bformat(_("%1$d words"), words);
1346                 else
1347                         message += _("One word");
1348                 message += "\n";
1349                 if (chars_blanks != 1)
1350                         message += bformat(_("%1$d characters (including blanks)"),
1351                                           chars_blanks);
1352                 else
1353                         message += _("One character (including blanks)");
1354                 message += "\n";
1355                 if (chars != 1)
1356                         message += bformat(_("%1$d characters (excluding blanks)"),
1357                                           chars);
1358                 else
1359                         message += _("One character (excluding blanks)");
1360
1361                 Alert::information(_("Statistics"), message);
1362         }
1363                 break;
1364
1365         case LFUN_BUFFER_TOGGLE_COMPRESSION:
1366                 // turn compression on/off
1367                 buffer_.params().compressed = !buffer_.params().compressed;
1368                 break;
1369         case LFUN_COPY_LABEL_AS_REF: {
1370                 // if there is an inset at cursor, try to copy it
1371                 Inset * inset = cur.nextInset();
1372                 if (inset) {
1373                         FuncRequest tmpcmd = cmd;
1374                         inset->dispatch(cur, tmpcmd);
1375                 }
1376                 if (!cur.result().dispatched())
1377                         // It did not work too; no action needed.
1378                         break;
1379                 cur.clearSelection();
1380                 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1381                 break;
1382         }
1383         case LFUN_NEXT_INSET_TOGGLE: {
1384                 // create the the real function we want to invoke
1385                 FuncRequest tmpcmd = cmd;
1386                 tmpcmd.action = LFUN_INSET_TOGGLE;
1387                 // if there is an inset at cursor, see whether it
1388                 // wants to toggle.
1389                 Inset * inset = cur.nextInset();
1390                 if (inset) {
1391                         if (inset->isActive()) {
1392                                 Cursor tmpcur = cur;
1393                                 tmpcur.pushBackward(*inset);
1394                                 inset->dispatch(tmpcur, tmpcmd);
1395                                 if (tmpcur.result().dispatched())
1396                                         cur.dispatched();
1397                         } else 
1398                                 inset->dispatch(cur, tmpcmd);
1399                 }
1400                 // if it did not work, try the underlying inset.
1401                 if (!inset || !cur.result().dispatched())
1402                         cur.dispatch(tmpcmd);
1403
1404                 if (!cur.result().dispatched())
1405                         // It did not work too; no action needed.
1406                         break;
1407                 cur.clearSelection();
1408                 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1409                 break;
1410         }
1411
1412         case LFUN_NEXT_INSET_MODIFY: {
1413                 // create the the real function we want to invoke
1414                 FuncRequest tmpcmd = cmd;
1415                 tmpcmd.action = LFUN_INSET_MODIFY;
1416                 // if there is an inset at cursor, see whether it
1417                 // can be modified.
1418                 Inset * inset = cur.nextInset();
1419                 if (inset) {
1420                         cur.recordUndo();
1421                         inset->dispatch(cur, tmpcmd);
1422                 }
1423                 // if it did not work, try the underlying inset.
1424                 if (!inset || !cur.result().dispatched()) {
1425                         cur.recordUndo();
1426                         cur.dispatch(tmpcmd);
1427                 }
1428
1429                 if (!cur.result().dispatched())
1430                         // It did not work too; no action needed.
1431                         break;
1432                 cur.clearSelection();
1433                 processUpdateFlags(Update::Force | Update::FitCursor);
1434                 break;
1435         }
1436
1437         case LFUN_SCREEN_UP:
1438         case LFUN_SCREEN_DOWN: {
1439                 Point p = getPos(cur, cur.boundary());
1440                 if (p.y_ < 0 || p.y_ > height_) {
1441                         // The cursor is off-screen so recenter before proceeding.
1442                         showCursor();
1443                         p = getPos(cur, cur.boundary());
1444                 }
1445                 int const scrolled = scroll(cmd.action == LFUN_SCREEN_UP
1446                         ? - height_ : height_);
1447                 if (cmd.action == LFUN_SCREEN_UP && scrolled > - height_)
1448                         p = Point(0, 0);
1449                 if (cmd.action == LFUN_SCREEN_DOWN && scrolled < height_)
1450                         p = Point(width_, height_);
1451                 Cursor old = cur;
1452                 cur.reset(buffer_.inset());
1453                 updateMetrics();
1454                 buffer_.changed();
1455                 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1456                 //FIXME: what to do with cur.x_target()?
1457                 bool const update = cur.bv().checkDepm(cur, old);
1458                 cur.finishUndo();
1459                 if (update)
1460                         processUpdateFlags(Update::Force | Update::FitCursor);
1461                 break;
1462         }
1463
1464         case LFUN_SCROLL:
1465                 lfunScroll(cmd);
1466                 break;
1467
1468         case LFUN_SCREEN_UP_SELECT: {
1469                 cur.selHandle(true);
1470                 if (isTopScreen()) {
1471                         lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
1472                         cur.finishUndo();
1473                         break;
1474                 }
1475                 int y = getPos(cur, cur.boundary()).y_;
1476                 int const ymin = y - height_ + defaultRowHeight();
1477                 while (y > ymin && cur.up())
1478                         y = getPos(cur, cur.boundary()).y_;
1479
1480                 cur.finishUndo();
1481                 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1482                 break;
1483         }
1484
1485         case LFUN_SCREEN_DOWN_SELECT: {
1486                 cur.selHandle(true);
1487                 if (isBottomScreen()) {
1488                         lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
1489                         cur.finishUndo();
1490                         break;
1491                 }
1492                 int y = getPos(cur, cur.boundary()).y_;
1493                 int const ymax = y + height_ - defaultRowHeight();
1494                 while (y < ymax && cur.down())
1495                         y = getPos(cur, cur.boundary()).y_;
1496
1497                 cur.finishUndo();
1498                 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1499                 break;
1500         }
1501
1502         case LFUN_BRANCH_ACTIVATE:
1503         case LFUN_BRANCH_DEACTIVATE:
1504                 buffer_.dispatch(cmd);
1505                 processUpdateFlags(Update::Force);
1506                 break;
1507
1508         // This could be rewriten using some command like forall <insetname> <command>
1509         // once the insets refactoring is done.
1510         case LFUN_NOTES_MUTATE: {
1511                 if (cmd.argument().empty())
1512                         break;
1513
1514                 if (mutateNotes(cur, cmd.getArg(0), cmd.getArg(1))) {
1515                         processUpdateFlags(Update::Force);
1516                 }
1517                 break;
1518         }
1519
1520         case LFUN_ALL_INSETS_TOGGLE: {
1521                 string action;
1522                 string const name = split(to_utf8(cmd.argument()), action, ' ');
1523                 InsetCode const inset_code = insetCode(name);
1524
1525                 FuncRequest fr(LFUN_INSET_TOGGLE, action);
1526
1527                 Inset & inset = cur.buffer()->inset();
1528                 InsetIterator it  = inset_iterator_begin(inset);
1529                 InsetIterator const end = inset_iterator_end(inset);
1530                 for (; it != end; ++it) {
1531                         if (it->asInsetCollapsable()
1532                             && (inset_code == NO_CODE
1533                             || inset_code == it->lyxCode())) {
1534                                 Cursor tmpcur = cur;
1535                                 tmpcur.pushBackward(*it);
1536                                 it->dispatch(tmpcur, fr);
1537                         }
1538                 }
1539                 processUpdateFlags(Update::Force | Update::FitCursor);
1540                 break;
1541         }
1542
1543         default:
1544                 return false;
1545         }
1546
1547         return true;
1548 }
1549
1550
1551 docstring const BufferView::requestSelection()
1552 {
1553         Cursor & cur = d->cursor_;
1554
1555         LYXERR(Debug::SELECTION, "requestSelection: cur.selection: " << cur.selection());
1556         if (!cur.selection()) {
1557                 d->xsel_cache_.set = false;
1558                 return docstring();
1559         }
1560
1561         LYXERR(Debug::SELECTION, "requestSelection: xsel_cache.set: " << d->xsel_cache_.set);
1562         if (!d->xsel_cache_.set ||
1563             cur.top() != d->xsel_cache_.cursor ||
1564             cur.anchor_.top() != d->xsel_cache_.anchor)
1565         {
1566                 d->xsel_cache_.cursor = cur.top();
1567                 d->xsel_cache_.anchor = cur.anchor_.top();
1568                 d->xsel_cache_.set = cur.selection();
1569                 return cur.selectionAsString(false);
1570         }
1571         return docstring();
1572 }
1573
1574
1575 void BufferView::clearSelection()
1576 {
1577         d->cursor_.clearSelection();
1578         // Clear the selection buffer. Otherwise a subsequent
1579         // middle-mouse-button paste would use the selection buffer,
1580         // not the more current external selection.
1581         cap::clearSelection();
1582         d->xsel_cache_.set = false;
1583         // The buffer did not really change, but this causes the
1584         // redraw we need because we cleared the selection above.
1585         buffer_.changed();
1586 }
1587
1588
1589 void BufferView::resize(int width, int height)
1590 {
1591         // Update from work area
1592         width_ = width;
1593         height_ = height;
1594
1595         // Clear the paragraph height cache.
1596         d->par_height_.clear();
1597         // Redo the metrics.
1598         updateMetrics();
1599 }
1600
1601
1602 Inset const * BufferView::getCoveringInset(Text const & text,
1603                 int x, int y) const
1604 {
1605         TextMetrics & tm = d->text_metrics_[&text];
1606         Inset * inset = tm.checkInsetHit(x, y);
1607         if (!inset)
1608                 return 0;
1609
1610         if (!inset->descendable())
1611                 // No need to go further down if the inset is not
1612                 // descendable.
1613                 return inset;
1614
1615         size_t cell_number = inset->nargs();
1616         // Check all the inner cell.
1617         for (size_t i = 0; i != cell_number; ++i) {
1618                 Text const * inner_text = inset->getText(i);
1619                 if (inner_text) {
1620                         // Try deeper.
1621                         Inset const * inset_deeper =
1622                                 getCoveringInset(*inner_text, x, y);
1623                         if (inset_deeper)
1624                                 return inset_deeper;
1625                 }
1626         }
1627
1628         return inset;
1629 }
1630
1631
1632 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1633 {
1634         //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
1635
1636         // This is only called for mouse related events including
1637         // LFUN_FILE_OPEN generated by drag-and-drop.
1638         FuncRequest cmd = cmd0;
1639
1640         Cursor old = cursor();
1641         Cursor cur(*this);
1642         cur.push(buffer_.inset());
1643         cur.setSelection(d->cursor_.selection());
1644
1645         // Either the inset under the cursor or the
1646         // surrounding Text will handle this event.
1647
1648         // make sure we stay within the screen...
1649         cmd.y = min(max(cmd.y, -1), height_);
1650
1651         if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1652
1653                 // Get inset under mouse, if there is one.
1654                 Inset const * covering_inset =
1655                         getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1656                 if (covering_inset == d->last_inset_)
1657                         // Same inset, no need to do anything...
1658                         return;
1659
1660                 bool need_redraw = false;
1661                 // const_cast because of setMouseHover().
1662                 Inset * inset = const_cast<Inset *>(covering_inset);
1663                 if (d->last_inset_)
1664                         // Remove the hint on the last hovered inset (if any).
1665                         need_redraw |= d->last_inset_->setMouseHover(false);
1666                 if (inset)
1667                         // Highlighted the newly hovered inset (if any).
1668                         need_redraw |= inset->setMouseHover(true);
1669                 d->last_inset_ = inset;
1670                 if (!need_redraw)
1671                         return;
1672
1673                 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
1674                         << cmd.x << ", " << cmd.y << ")");
1675
1676                 d->update_strategy_ = DecorationUpdate;
1677
1678                 // This event (moving without mouse click) is not passed further.
1679                 // This should be changed if it is further utilized.
1680                 buffer_.changed();
1681                 return;
1682         }
1683
1684         // Build temporary cursor.
1685         Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1686
1687         // Put anchor at the same position.
1688         cur.resetAnchor();
1689
1690         cur.beginUndoGroup();
1691
1692         // Try to dispatch to an non-editable inset near this position
1693         // via the temp cursor. If the inset wishes to change the real
1694         // cursor it has to do so explicitly by using
1695         //  cur.bv().cursor() = cur;  (or similar)
1696         if (inset)
1697                 inset->dispatch(cur, cmd);
1698
1699         // Now dispatch to the temporary cursor. If the real cursor should
1700         // be modified, the inset's dispatch has to do so explicitly.
1701         if (!inset || !cur.result().dispatched())
1702                 cur.dispatch(cmd);
1703
1704         cur.endUndoGroup();
1705
1706         // Notify left insets
1707         if (cur != old) {
1708                 old.fixIfBroken();
1709                 bool badcursor = notifyCursorLeavesOrEnters(old, cur);
1710                 if (badcursor)
1711                         cursor().fixIfBroken();
1712         }
1713         
1714         // Do we have a selection?
1715         theSelection().haveSelection(cursor().selection());
1716
1717         // If the command has been dispatched,
1718         if (cur.result().dispatched() || cur.result().update())
1719                 processUpdateFlags(cur.result().update());
1720 }
1721
1722
1723 void BufferView::lfunScroll(FuncRequest const & cmd)
1724 {
1725         string const scroll_type = cmd.getArg(0);
1726         int const scroll_step = 
1727                 (scroll_type == "line") ? d->scrollbarParameters_.single_step
1728                 : (scroll_type == "page") ? d->scrollbarParameters_.page_step : 0;
1729         if (scroll_step == 0)
1730                 return;
1731         string const scroll_quantity = cmd.getArg(1);
1732         if (scroll_quantity == "up")
1733                 scrollUp(scroll_step);
1734         else if (scroll_quantity == "down")
1735                 scrollDown(scroll_step);
1736         else {
1737                 int const scroll_value = convert<int>(scroll_quantity);
1738                 if (scroll_value)
1739                         scroll(scroll_step * scroll_value);
1740         }
1741         updateMetrics();
1742         buffer_.changed();
1743 }
1744
1745
1746 int BufferView::scroll(int y)
1747 {
1748         if (y > 0)
1749                 return scrollDown(y);
1750         if (y < 0)
1751                 return scrollUp(-y);
1752         return 0;
1753 }
1754
1755
1756 int BufferView::scrollDown(int offset)
1757 {
1758         Text * text = &buffer_.text();
1759         TextMetrics & tm = d->text_metrics_[text];
1760         int ymax = height_ + offset;
1761         while (true) {
1762                 pair<pit_type, ParagraphMetrics const *> last = tm.last();
1763                 int bottom_pos = last.second->position() + last.second->descent();
1764                 if (last.first + 1 == int(text->paragraphs().size())) {
1765                         if (bottom_pos <= height_)
1766                                 return 0;
1767                         offset = min(offset, bottom_pos - height_);
1768                         break;
1769                 }
1770                 if (bottom_pos > ymax)
1771                         break;
1772                 tm.newParMetricsDown();
1773         }
1774         d->anchor_ypos_ -= offset;
1775         return -offset;
1776 }
1777
1778
1779 int BufferView::scrollUp(int offset)
1780 {
1781         Text * text = &buffer_.text();
1782         TextMetrics & tm = d->text_metrics_[text];
1783         int ymin = - offset;
1784         while (true) {
1785                 pair<pit_type, ParagraphMetrics const *> first = tm.first();
1786                 int top_pos = first.second->position() - first.second->ascent();
1787                 if (first.first == 0) {
1788                         if (top_pos >= 0)
1789                                 return 0;
1790                         offset = min(offset, - top_pos);
1791                         break;
1792                 }
1793                 if (top_pos < ymin)
1794                         break;
1795                 tm.newParMetricsUp();
1796         }
1797         d->anchor_ypos_ += offset;
1798         return offset;
1799 }
1800
1801
1802 void BufferView::setCursorFromRow(int row)
1803 {
1804         int tmpid = -1;
1805         int tmppos = -1;
1806
1807         buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1808
1809         d->cursor_.reset(buffer_.inset());
1810         if (tmpid == -1)
1811                 buffer_.text().setCursor(d->cursor_, 0, 0);
1812         else
1813                 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1814 }
1815
1816
1817 bool BufferView::setCursorFromInset(Inset const * inset)
1818 {
1819         // are we already there?
1820         if (cursor().nextInset() == inset)
1821                 return true;
1822
1823         // Inset is not at cursor position. Find it in the document.
1824         Cursor cur(*this);
1825         cur.reset(buffer().inset());
1826         while (cur && cur.nextInset() != inset)
1827                 cur.forwardInset();
1828
1829         if (cur) {
1830                 setCursor(cur);
1831                 return true;
1832         }
1833         return false;
1834 }
1835
1836
1837 void BufferView::gotoLabel(docstring const & label)
1838 {
1839         std::vector<Buffer const *> bufs = buffer().allRelatives();
1840         std::vector<Buffer const *>::iterator it = bufs.begin();
1841         for (; it != bufs.end(); ++it) {
1842                 Buffer const * buf = *it;
1843
1844                 // find label
1845                 Toc & toc = buf->tocBackend().toc("label");
1846                 TocIterator toc_it = toc.begin();
1847                 TocIterator end = toc.end();
1848                 for (; toc_it != end; ++toc_it) {
1849                         if (label == toc_it->str()) {
1850                                 dispatch(toc_it->action());
1851                                 return;
1852                         }
1853                 }
1854         }
1855 }
1856
1857
1858 TextMetrics const & BufferView::textMetrics(Text const * t) const
1859 {
1860         return const_cast<BufferView *>(this)->textMetrics(t);
1861 }
1862
1863
1864 TextMetrics & BufferView::textMetrics(Text const * t)
1865 {
1866         TextMetricsCache::iterator tmc_it  = d->text_metrics_.find(t);
1867         if (tmc_it == d->text_metrics_.end()) {
1868                 tmc_it = d->text_metrics_.insert(
1869                         make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1870         }
1871         return tmc_it->second;
1872 }
1873
1874
1875 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1876                 pit_type pit) const
1877 {
1878         return textMetrics(t).parMetrics(pit);
1879 }
1880
1881
1882 int BufferView::workHeight() const
1883 {
1884         return height_;
1885 }
1886
1887
1888 void BufferView::setCursor(DocIterator const & dit)
1889 {
1890         size_t const n = dit.depth();
1891         for (size_t i = 0; i < n; ++i)
1892                 dit[i].inset().edit(d->cursor_, true);
1893
1894         d->cursor_.setCursor(dit);
1895         d->cursor_.setSelection(false);
1896 }
1897
1898
1899 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1900 {
1901         // Would be wrong to delete anything if we have a selection.
1902         if (cur.selection())
1903                 return false;
1904
1905         bool need_anchor_change = false;
1906         bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1907                 need_anchor_change);
1908
1909         if (need_anchor_change)
1910                 cur.resetAnchor();
1911
1912         if (!changed)
1913                 return false;
1914
1915         d->cursor_ = cur;
1916
1917         buffer_.updateLabels();
1918
1919         updateMetrics();
1920         buffer_.changed();
1921         return true;
1922 }
1923
1924
1925 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
1926 {
1927         LASSERT(&cur.bv() == this, /**/);
1928
1929         if (!select)
1930                 // this event will clear selection so we save selection for
1931                 // persistent selection
1932                 cap::saveSelection(cursor());
1933
1934         // Has the cursor just left the inset?
1935         bool leftinset = (&d->cursor_.inset() != &cur.inset());
1936         if (leftinset)
1937                 d->cursor_.fixIfBroken();
1938
1939         // FIXME: shift-mouse selection doesn't work well across insets.
1940         bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
1941
1942         // do the dEPM magic if needed
1943         // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1944         // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1945         // the leftinset bool would not be necessary (badcursor instead).
1946         bool update = leftinset;
1947         if (!do_selection && d->cursor_.inTexted())
1948                 update |= checkDepm(cur, d->cursor_);
1949
1950         d->cursor_.setCursor(cur);
1951         d->cursor_.boundary(cur.boundary());
1952         if (do_selection)
1953                 d->cursor_.setSelection();
1954         else
1955                 d->cursor_.clearSelection();
1956
1957         d->cursor_.finishUndo();
1958         d->cursor_.setCurrentFont();
1959         return update;
1960 }
1961
1962
1963 void BufferView::putSelectionAt(DocIterator const & cur,
1964                                 int length, bool backwards)
1965 {
1966         d->cursor_.clearSelection();
1967
1968         setCursor(cur);
1969
1970         if (length) {
1971                 if (backwards) {
1972                         d->cursor_.pos() += length;
1973                         d->cursor_.setSelection(d->cursor_, -length);
1974                 } else
1975                         d->cursor_.setSelection(d->cursor_, length);
1976         }
1977         // Ensure a redraw happens in any case because the new selection could 
1978         // possibly be on the same screen as the previous selection.
1979         processUpdateFlags(Update::Force | Update::FitCursor);
1980 }
1981
1982
1983 Cursor & BufferView::cursor()
1984 {
1985         return d->cursor_;
1986 }
1987
1988
1989 Cursor const & BufferView::cursor() const
1990 {
1991         return d->cursor_;
1992 }
1993
1994
1995 pit_type BufferView::anchor_ref() const
1996 {
1997         return d->anchor_pit_;
1998 }
1999
2000
2001 bool BufferView::singleParUpdate()
2002 {
2003         Text & buftext = buffer_.text();
2004         pit_type const bottom_pit = d->cursor_.bottom().pit();
2005         TextMetrics & tm = textMetrics(&buftext);
2006         int old_height = tm.parMetrics(bottom_pit).height();
2007
2008         // make sure inline completion pointer is ok
2009         if (d->inlineCompletionPos_.fixIfBroken())
2010                 d->inlineCompletionPos_ = DocIterator();
2011
2012         // In Single Paragraph mode, rebreak only
2013         // the (main text, not inset!) paragraph containing the cursor.
2014         // (if this paragraph contains insets etc., rebreaking will
2015         // recursively descend)
2016         tm.redoParagraph(bottom_pit);
2017         ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);                
2018         if (pm.height() != old_height)
2019                 // Paragraph height has changed so we cannot proceed to
2020                 // the singlePar optimisation.
2021                 return false;
2022
2023         d->update_strategy_ = SingleParUpdate;
2024
2025         LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
2026                 << " y2: " << pm.position() + pm.descent()
2027                 << " pit: " << bottom_pit
2028                 << " singlepar: 1");
2029         return true;
2030 }
2031
2032
2033 void BufferView::updateMetrics()
2034 {
2035         if (height_ == 0 || width_ == 0)
2036                 return;
2037
2038         Text & buftext = buffer_.text();
2039         pit_type const npit = int(buftext.paragraphs().size());
2040
2041         // Clear out the position cache in case of full screen redraw,
2042         d->coord_cache_.clear();
2043
2044         // Clear out paragraph metrics to avoid having invalid metrics
2045         // in the cache from paragraphs not relayouted below
2046         // The complete text metrics will be redone.
2047         d->text_metrics_.clear();
2048
2049         TextMetrics & tm = textMetrics(&buftext);
2050
2051         // make sure inline completion pointer is ok
2052         if (d->inlineCompletionPos_.fixIfBroken())
2053                 d->inlineCompletionPos_ = DocIterator();
2054         
2055         if (d->anchor_pit_ >= npit)
2056                 // The anchor pit must have been deleted...
2057                 d->anchor_pit_ = npit - 1;
2058
2059         // Rebreak anchor paragraph.
2060         tm.redoParagraph(d->anchor_pit_);
2061         ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
2062         
2063         // position anchor
2064         if (d->anchor_pit_ == 0) {
2065                 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
2066                 
2067                 // Complete buffer visible? Then it's easy.
2068                 if (scrollRange == 0)
2069                         d->anchor_ypos_ = anchor_pm.ascent();
2070         
2071                 // FIXME: Some clever handling needed to show
2072                 // the _first_ paragraph up to the top if the cursor is
2073                 // in the first line.
2074         }               
2075         anchor_pm.setPosition(d->anchor_ypos_);
2076
2077         LYXERR(Debug::PAINTING, "metrics: "
2078                 << " anchor pit = " << d->anchor_pit_
2079                 << " anchor ypos = " << d->anchor_ypos_);
2080
2081         // Redo paragraphs above anchor if necessary.
2082         int y1 = d->anchor_ypos_ - anchor_pm.ascent();
2083         // We are now just above the anchor paragraph.
2084         pit_type pit1 = d->anchor_pit_ - 1;
2085         for (; pit1 >= 0 && y1 >= 0; --pit1) {
2086                 tm.redoParagraph(pit1);
2087                 ParagraphMetrics & pm = tm.par_metrics_[pit1];
2088                 y1 -= pm.descent();
2089                 // Save the paragraph position in the cache.
2090                 pm.setPosition(y1);
2091                 y1 -= pm.ascent();
2092         }
2093
2094         // Redo paragraphs below the anchor if necessary.
2095         int y2 = d->anchor_ypos_ + anchor_pm.descent();
2096         // We are now just below the anchor paragraph.
2097         pit_type pit2 = d->anchor_pit_ + 1;
2098         for (; pit2 < npit && y2 <= height_; ++pit2) {
2099                 tm.redoParagraph(pit2);
2100                 ParagraphMetrics & pm = tm.par_metrics_[pit2];
2101                 y2 += pm.ascent();
2102                 // Save the paragraph position in the cache.
2103                 pm.setPosition(y2);
2104                 y2 += pm.descent();
2105         }
2106
2107         LYXERR(Debug::PAINTING, "Metrics: "
2108                 << " anchor pit = " << d->anchor_pit_
2109                 << " anchor ypos = " << d->anchor_ypos_
2110                 << " y1 = " << y1
2111                 << " y2 = " << y2
2112                 << " pit1 = " << pit1
2113                 << " pit2 = " << pit2);
2114
2115         d->update_strategy_ = FullScreenUpdate;
2116
2117         if (lyxerr.debugging(Debug::WORKAREA)) {
2118                 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
2119                 d->coord_cache_.dump();
2120         }
2121 }
2122
2123
2124 void BufferView::insertLyXFile(FileName const & fname)
2125 {
2126         LASSERT(d->cursor_.inTexted(), /**/);
2127
2128         // Get absolute path of file and add ".lyx"
2129         // to the filename if necessary
2130         FileName filename = fileSearch(string(), fname.absFilename(), "lyx");
2131
2132         docstring const disp_fn = makeDisplayPath(filename.absFilename());
2133         // emit message signal.
2134         message(bformat(_("Inserting document %1$s..."), disp_fn));
2135
2136         docstring res;
2137         Buffer buf("", false);
2138         if (buf.loadLyXFile(filename)) {
2139                 ErrorList & el = buffer_.errorList("Parse");
2140                 // Copy the inserted document error list into the current buffer one.
2141                 el = buf.errorList("Parse");
2142                 buffer_.undo().recordUndo(d->cursor_);
2143                 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
2144                                              buf.params().documentClassPtr(), el);
2145                 res = _("Document %1$s inserted.");
2146         } else {
2147                 res = _("Could not insert document %1$s");
2148         }
2149
2150         updateMetrics();
2151         buffer_.changed();
2152         // emit message signal.
2153         message(bformat(res, disp_fn));
2154         buffer_.errors("Parse");
2155 }
2156
2157
2158 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
2159 {
2160         int x = 0;
2161         int y = 0;
2162         int lastw = 0;
2163
2164         // Addup contribution of nested insets, from inside to outside,
2165         // keeping the outer paragraph for a special handling below
2166         for (size_t i = dit.depth() - 1; i >= 1; --i) {
2167                 CursorSlice const & sl = dit[i];
2168                 int xx = 0;
2169                 int yy = 0;
2170                 
2171                 // get relative position inside sl.inset()
2172                 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
2173                 
2174                 // Make relative position inside of the edited inset relative to sl.inset()
2175                 x += xx;
2176                 y += yy;
2177                 
2178                 // In case of an RTL inset, the edited inset will be positioned to the left
2179                 // of xx:yy
2180                 if (sl.text()) {
2181                         bool boundary_i = boundary && i + 1 == dit.depth();
2182                         bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
2183                         if (rtl)
2184                                 x -= lastw;
2185                 }
2186
2187                 // remember width for the case that sl.inset() is positioned in an RTL inset
2188                 if (i && dit[i - 1].text()) {
2189                         // If this Inset is inside a Text Inset, retrieve the Dimension
2190                         // from the containing text instead of using Inset::dimension() which
2191                         // might not be implemented.
2192                         // FIXME (Abdel 23/09/2007): this is a bit messy because of the
2193                         // elimination of Inset::dim_ cache. This coordOffset() method needs
2194                         // to be rewritten in light of the new design.
2195                         Dimension const & dim = parMetrics(dit[i - 1].text(),
2196                                 dit[i - 1].pit()).insetDimension(&sl.inset());
2197                         lastw = dim.wid;
2198                 } else {
2199                         Dimension const dim = sl.inset().dimension(*this);
2200                         lastw = dim.wid;
2201                 }
2202                 
2203                 //lyxerr << "Cursor::getPos, i: "
2204                 // << i << " x: " << xx << " y: " << y << endl;
2205         }
2206
2207         // Add contribution of initial rows of outermost paragraph
2208         CursorSlice const & sl = dit[0];
2209         TextMetrics const & tm = textMetrics(sl.text());
2210         ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
2211         LASSERT(!pm.rows().empty(), /**/);
2212         y -= pm.rows()[0].ascent();
2213 #if 1
2214         // FIXME: document this mess
2215         size_t rend;
2216         if (sl.pos() > 0 && dit.depth() == 1) {
2217                 int pos = sl.pos();
2218                 if (pos && boundary)
2219                         --pos;
2220 //              lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
2221                 rend = pm.pos2row(pos);
2222         } else
2223                 rend = pm.pos2row(sl.pos());
2224 #else
2225         size_t rend = pm.pos2row(sl.pos());
2226 #endif
2227         for (size_t rit = 0; rit != rend; ++rit)
2228                 y += pm.rows()[rit].height();
2229         y += pm.rows()[rend].ascent();
2230         
2231         TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
2232         
2233         // Make relative position from the nested inset now bufferview absolute.
2234         int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
2235         x += xx;
2236         
2237         // In the RTL case place the nested inset at the left of the cursor in 
2238         // the outer paragraph
2239         bool boundary_1 = boundary && 1 == dit.depth();
2240         bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
2241         if (rtl)
2242                 x -= lastw;
2243         
2244         return Point(x, y);
2245 }
2246
2247
2248 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
2249 {
2250         if (!paragraphVisible(dit))
2251                 return Point(-1, -1);
2252
2253         CursorSlice const & bot = dit.bottom();
2254         TextMetrics const & tm = textMetrics(bot.text());
2255
2256         Point p = coordOffset(dit, boundary); // offset from outer paragraph
2257         p.y_ += tm.parMetrics(bot.pit()).position();
2258         return p;
2259 }
2260
2261
2262 bool BufferView::paragraphVisible(DocIterator const & dit) const
2263 {
2264         CursorSlice const & bot = dit.bottom();
2265         TextMetrics const & tm = textMetrics(bot.text());
2266
2267         return tm.contains(bot.pit());
2268 }
2269
2270
2271 void BufferView::draw(frontend::Painter & pain)
2272 {
2273         if (height_ == 0 || width_ == 0)
2274                 return;
2275         LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
2276
2277         Text & text = buffer_.text();
2278         TextMetrics const & tm = d->text_metrics_[&text];
2279         int const y = tm.first().second->position();
2280         PainterInfo pi(this, pain);
2281
2282         switch (d->update_strategy_) {
2283
2284         case NoScreenUpdate:
2285                 // If no screen painting is actually needed, only some the different
2286                 // coordinates of insets and paragraphs needs to be updated.
2287                 pi.full_repaint = true;
2288                 pi.pain.setDrawingEnabled(false);
2289                 tm.draw(pi, 0, y);
2290                 break;
2291
2292         case SingleParUpdate:
2293                 pi.full_repaint = false;
2294                 // In general, only the current row of the outermost paragraph
2295                 // will be redrawn. Particular cases where selection spans
2296                 // multiple paragraph are correctly detected in TextMetrics.
2297                 tm.draw(pi, 0, y);
2298                 break;
2299
2300         case DecorationUpdate:
2301                 // FIXME: We should also distinguish DecorationUpdate to avoid text
2302                 // drawing if possible. This is not possible to do easily right now
2303                 // because of the single backing pixmap.
2304
2305         case FullScreenUpdate:
2306                 // The whole screen, including insets, will be refreshed.
2307                 pi.full_repaint = true;
2308
2309                 // Clear background.
2310                 pain.fillRectangle(0, 0, width_, height_,
2311                         pi.backgroundColor(&buffer_.inset()));
2312
2313                 // Draw everything.
2314                 tm.draw(pi, 0, y);
2315
2316                 // and possibly grey out below
2317                 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2318                 int const y2 = lastpm.second->position() + lastpm.second->descent();
2319                 if (y2 < height_)
2320                         pain.fillRectangle(0, y2, width_, height_ - y2, Color_bottomarea);
2321                 break;
2322         }
2323         LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING  ***");
2324
2325         // The scrollbar needs an update.
2326         updateScrollbar();
2327
2328         // Normalize anchor for next time
2329         pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
2330         pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2331         for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
2332                 ParagraphMetrics const & pm = tm.parMetrics(pit);
2333                 if (pm.position() + pm.descent() > 0) {
2334                         d->anchor_pit_ = pit;
2335                         d->anchor_ypos_ = pm.position();
2336                         break;
2337                 }
2338         }
2339         LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
2340                 << "  anchor ypos = " << d->anchor_ypos_);
2341 }
2342
2343
2344 void BufferView::message(docstring const & msg)
2345 {
2346         if (d->gui_)
2347                 d->gui_->message(msg);
2348 }
2349
2350
2351 void BufferView::showDialog(string const & name)
2352 {
2353         if (d->gui_)
2354                 d->gui_->showDialog(name, string());
2355 }
2356
2357
2358 void BufferView::showDialog(string const & name,
2359         string const & data, Inset * inset)
2360 {
2361         if (d->gui_)
2362                 d->gui_->showDialog(name, data, inset);
2363 }
2364
2365
2366 void BufferView::updateDialog(string const & name, string const & data)
2367 {
2368         if (d->gui_)
2369                 d->gui_->updateDialog(name, data);
2370 }
2371
2372
2373 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2374 {
2375         d->gui_ = gui;
2376 }
2377
2378
2379 // FIXME: Move this out of BufferView again
2380 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
2381 {
2382         if (!fname.isReadableFile()) {
2383                 docstring const error = from_ascii(strerror(errno));
2384                 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2385                 docstring const text =
2386                   bformat(_("Could not read the specified document\n"
2387                             "%1$s\ndue to the error: %2$s"), file, error);
2388                 Alert::error(_("Could not read file"), text);
2389                 return docstring();
2390         }
2391
2392         if (!fname.isReadableFile()) {
2393                 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2394                 docstring const text =
2395                   bformat(_("%1$s\n is not readable."), file);
2396                 Alert::error(_("Could not open file"), text);
2397                 return docstring();
2398         }
2399
2400         // FIXME UNICODE: We don't know the encoding of the file
2401         docstring file_content = fname.fileContents("UTF-8");
2402         if (file_content.empty()) {
2403                 Alert::error(_("Reading not UTF-8 encoded file"),
2404                              _("The file is not UTF-8 encoded.\n"
2405                                "It will be read as local 8Bit-encoded.\n"
2406                                "If this does not give the correct result\n"
2407                                "then please change the encoding of the file\n"
2408                                "to UTF-8 with a program other than LyX.\n"));
2409                 file_content = fname.fileContents("local8bit");
2410         }
2411
2412         return normalize_c(file_content);
2413 }
2414
2415
2416 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
2417 {
2418         docstring const tmpstr = contentsOfPlaintextFile(f);
2419
2420         if (tmpstr.empty())
2421                 return;
2422
2423         Cursor & cur = cursor();
2424         cap::replaceSelection(cur);
2425         buffer_.undo().recordUndo(cur);
2426         if (asParagraph)
2427                 cur.innerText()->insertStringAsParagraphs(cur, tmpstr);
2428         else
2429                 cur.innerText()->insertStringAsLines(cur, tmpstr);
2430
2431         updateMetrics();
2432         buffer_.changed();
2433 }
2434
2435
2436 docstring const & BufferView::inlineCompletion() const
2437 {
2438         return d->inlineCompletion_;
2439 }
2440
2441
2442 size_t const & BufferView::inlineCompletionUniqueChars() const
2443 {
2444         return d->inlineCompletionUniqueChars_;
2445 }
2446
2447
2448 DocIterator const & BufferView::inlineCompletionPos() const
2449 {
2450         return d->inlineCompletionPos_;
2451 }
2452
2453
2454 bool samePar(DocIterator const & a, DocIterator const & b)
2455 {
2456         if (a.empty() && b.empty())
2457                 return true;
2458         if (a.empty() || b.empty())
2459                 return false;
2460         if (a.depth() != b.depth())
2461                 return false;
2462         return &a.innerParagraph() == &b.innerParagraph();
2463 }
2464
2465
2466 void BufferView::setInlineCompletion(Cursor & cur, DocIterator const & pos, 
2467         docstring const & completion, size_t uniqueChars)
2468 {
2469         uniqueChars = min(completion.size(), uniqueChars);
2470         bool changed = d->inlineCompletion_ != completion
2471                 || d->inlineCompletionUniqueChars_ != uniqueChars;
2472         bool singlePar = true;
2473         d->inlineCompletion_ = completion;
2474         d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
2475         
2476         //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
2477         
2478         // at new position?
2479         DocIterator const & old = d->inlineCompletionPos_;
2480         if (old != pos) {
2481                 //lyxerr << "inlineCompletionPos changed" << std::endl;
2482                 // old or pos are in another paragraph?
2483                 if ((!samePar(cur, pos) && !pos.empty())
2484                     || (!samePar(cur, old) && !old.empty())) {
2485                         singlePar = false;
2486                         //lyxerr << "different paragraph" << std::endl;
2487                 }
2488                 d->inlineCompletionPos_ = pos;
2489         }
2490         
2491         // set update flags
2492         if (changed) {
2493                 if (singlePar && !(cur.disp_.update() & Update::Force))
2494                         cur.updateFlags(cur.disp_.update() | Update::SinglePar);
2495                 else
2496                         cur.updateFlags(cur.disp_.update() | Update::Force);
2497         }
2498 }
2499
2500 } // namespace lyx