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