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