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