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