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