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