]> git.lyx.org Git - lyx.git/blob - src/BufferView_pimpl.C
GUI API Cleanup step 2: merge of the "younes" branch.
[lyx.git] / src / BufferView_pimpl.C
1 /**
2  * \file BufferView_pimpl.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Asger Alstrup
7  * \author Alfredo Braunstein
8  * \author Lars Gullik Bjønnes
9  * \author Jean-Marc Lasgouttes
10  * \author Angus Leeming
11  * \author John Levon
12  * \author André Pönitz
13  * \author Dekel Tsur
14  * \author Jürgen Vigna
15  *
16  * Full author contact details are available in file CREDITS.
17  */
18
19 #include <config.h>
20
21 #include "BufferView_pimpl.h"
22 #include "buffer.h"
23 #include "buffer_funcs.h"
24 #include "bufferlist.h"
25 #include "bufferparams.h"
26 #include "coordcache.h"
27 #include "cursor.h"
28 #include "CutAndPaste.h"
29 #include "debug.h"
30 #include "dispatchresult.h"
31 #include "factory.h"
32 #include "FloatList.h"
33 #include "funcrequest.h"
34 #include "FuncStatus.h"
35 #include "gettext.h"
36 #include "intl.h"
37 #include "insetiterator.h"
38 #include "LaTeXFeatures.h"
39 #include "lyx_cb.h" // added for Dispatch functions
40 #include "lyx_main.h"
41 #include "lyxfind.h"
42 #include "lyxfunc.h"
43 #include "lyxtext.h"
44 #include "lyxrc.h"
45 #include "session.h"
46 #include "metricsinfo.h"
47 #include "paragraph.h"
48 #include "paragraph_funcs.h"
49 #include "ParagraphParameters.h"
50 #include "pariterator.h"
51 #include "rowpainter.h"
52 #include "toc.h"
53 #include "undo.h"
54 #include "vspace.h"
55
56 #include "insets/insetbibtex.h"
57 #include "insets/insetref.h"
58 #include "insets/insettext.h"
59
60 #include "frontends/Alert.h"
61 #include "frontends/Clipboard.h"
62 #include "frontends/Dialogs.h"
63 #include "frontends/FileDialog.h"
64 #include "frontends/font_metrics.h"
65 #include "frontends/Gui.h"
66 #include "frontends/LyXView.h"
67 #include "frontends/Painter.h"
68 #include "frontends/WorkArea.h"
69
70 #include "graphics/Previews.h"
71
72 #include "support/convert.h"
73 #include "support/filefilterlist.h"
74 #include "support/filetools.h"
75 #include "support/forkedcontr.h"
76 #include "support/package.h"
77 #include "support/types.h"
78
79 #include <boost/bind.hpp>
80 #include <boost/current_function.hpp>
81
82 #include <functional>
83 #include <vector>
84
85 using lyx::frontend::WorkArea;
86 using lyx::frontend::Clipboard;
87 using lyx::frontend::Gui;
88
89 using lyx::pos_type;
90
91 using lyx::support::addPath;
92 using lyx::support::bformat;
93 using lyx::support::FileFilterList;
94 using lyx::support::fileSearch;
95 using lyx::support::ForkedcallsController;
96 using lyx::support::isDirWriteable;
97 using lyx::support::makeDisplayPath;
98 using lyx::support::makeAbsPath;
99 using lyx::support::package;
100
101 using std::endl;
102 using std::istringstream;
103 using std::make_pair;
104 using std::min;
105 using std::max;
106 using std::string;
107 using std::mem_fun_ref;
108 using std::vector;
109
110 extern BufferList bufferlist;
111
112
113 namespace {
114
115 unsigned int const saved_positions_num = 20;
116
117 // All the below connection objects are needed because of a bug in some
118 // versions of GCC (<=2.96 are on the suspects list.) By having and assigning
119 // to these connections we avoid a segfault upon startup, and also at exit.
120 // (Lgb)
121
122 boost::signals::connection timecon;
123
124 /// Return an inset of this class if it exists at the current cursor position
125 template <class T>
126 T * getInsetByCode(LCursor & cur, InsetBase::Code code)
127 {
128         T * inset = 0;
129         DocIterator it = cur;
130         if (it.nextInset() &&
131             it.nextInset()->lyxCode() == code) {
132                 inset = static_cast<T*>(it.nextInset());
133         }
134         return inset;
135 }
136
137 } // anon namespace
138
139
140 BufferView::Pimpl::Pimpl(BufferView & bv, LyXView * owner, WorkArea * workArea)
141         : bv_(&bv), owner_(owner), workArea_(workArea), buffer_(0), wh_(0), cursor_timeout(400),
142           using_xterm_cursor(false), cursor_(bv),
143           anchor_ref_(0), offset_ref_(0)
144 {
145         xsel_cache_.set = false;
146
147         // Setup the signals
148         timecon = cursor_timeout.timeout
149                 .connect(boost::bind(&BufferView::Pimpl::cursorToggle, this));
150
151         cursor_timeout.start();
152         
153         saved_positions.resize(saved_positions_num);
154         // load saved bookmarks
155         lyx::Session::BookmarkList & bmList = LyX::ref().session().loadBookmarks();
156         for (lyx::Session::BookmarkList::iterator bm = bmList.begin();
157                 bm != bmList.end(); ++bm)
158                 if (bm->get<0>() < saved_positions_num)
159                         saved_positions[bm->get<0>()] = Position( bm->get<1>(), bm->get<2>(), bm->get<3>() );
160         // and then clear them
161         bmList.clear();
162 }
163
164
165 void BufferView::Pimpl::addError(ErrorItem const & ei)
166 {
167         errorlist_.push_back(ei);
168 }
169
170
171 void BufferView::Pimpl::showReadonly(bool)
172 {
173         owner_->updateWindowTitle();
174         owner_->getDialogs().updateBufferDependent(false);
175 }
176
177
178 void BufferView::Pimpl::connectBuffer(Buffer & buf)
179 {
180         if (errorConnection_.connected())
181                 disconnectBuffer();
182
183         errorConnection_ =
184                 buf.error.connect(
185                         boost::bind(&BufferView::Pimpl::addError, this, _1));
186
187         messageConnection_ =
188                 buf.message.connect(
189                         boost::bind(&LyXView::message, owner_, _1));
190
191         busyConnection_ =
192                 buf.busy.connect(
193                         boost::bind(&LyXView::busy, owner_, _1));
194
195         titleConnection_ =
196                 buf.updateTitles.connect(
197                         boost::bind(&LyXView::updateWindowTitle, owner_));
198
199         timerConnection_ =
200                 buf.resetAutosaveTimers.connect(
201                         boost::bind(&LyXView::resetAutosaveTimer, owner_));
202
203         readonlyConnection_ =
204                 buf.readonly.connect(
205                         boost::bind(&BufferView::Pimpl::showReadonly, this, _1));
206
207         closingConnection_ =
208                 buf.closing.connect(
209                         boost::bind(&BufferView::Pimpl::setBuffer, this, (Buffer *)0));
210 }
211
212
213 void BufferView::Pimpl::disconnectBuffer()
214 {
215         errorConnection_.disconnect();
216         messageConnection_.disconnect();
217         busyConnection_.disconnect();
218         titleConnection_.disconnect();
219         timerConnection_.disconnect();
220         readonlyConnection_.disconnect();
221         closingConnection_.disconnect();
222 }
223
224
225 void BufferView::Pimpl::newFile(string const & filename, string const & tname,
226         bool isNamed)
227 {
228         setBuffer(::newFile(filename, tname, isNamed));
229 }
230
231
232 bool BufferView::Pimpl::loadLyXFile(string const & filename, bool tolastfiles)
233 {
234         // Get absolute path of file and add ".lyx"
235         // to the filename if necessary
236         string s = fileSearch(string(), filename, "lyx");
237
238         bool const found = !s.empty();
239
240         if (!found)
241                 s = filename;
242
243         // File already open?
244         if (bufferlist.exists(s)) {
245                 string const file = makeDisplayPath(s, 20);
246                 string text = bformat(_("The document %1$s is already "
247                                         "loaded.\n\nDo you want to revert "
248                                         "to the saved version?"), file);
249                 int const ret = Alert::prompt(_("Revert to saved document?"),
250                         text, 0, 1,  _("&Revert"), _("&Switch to document"));
251
252                 if (ret != 0) {
253                         setBuffer(bufferlist.getBuffer(s));
254                         return true;
255                 }
256                 // FIXME: should be LFUN_REVERT
257                 if (!bufferlist.close(bufferlist.getBuffer(s), false))
258                         return false;
259                 // Fall through to new load. (Asger)
260         }
261
262         Buffer * b = 0;
263
264         if (found) {
265                 b = bufferlist.newBuffer(s);
266                 connectBuffer(*b);
267                 if (!::loadLyXFile(b, s)) {
268                         bufferlist.release(b);
269                         return false;
270                 }
271         } else {
272                 string text = bformat(_("The document %1$s does not yet "
273                                         "exist.\n\nDo you want to create "
274                                         "a new document?"), s);
275                 int const ret = Alert::prompt(_("Create new document?"),
276                          text, 0, 1, _("&Create"), _("Cancel"));
277
278                 if (ret == 0)
279                         b = ::newFile(s, string(), true);
280                 else
281                         return false;
282         }
283
284         setBuffer(b);
285         bv_->showErrorList(_("Parse"));
286
287         // scroll to the position when the file was last closed
288         if (lyxrc.use_lastfilepos) {
289                 lyx::pit_type pit;
290                 lyx::pos_type pos;
291                 boost::tie(pit, pos) = LyX::ref().session().loadFilePosition(s);
292                 // I am not sure how to separate the following part to a function
293                 // so I will leave this to Lars.
294                 //
295                 // check pit since the document may be externally changed.
296                 if ( static_cast<size_t>(pit) < b->paragraphs().size() ) {
297                         ParIterator it = b->par_iterator_begin();
298                         ParIterator const end = b->par_iterator_end();
299                         for (; it != end; ++it)
300                                 if (it.pit() == pit) {
301                                         // restored pos may be bigger than it->size
302                                         bv_->setCursor(makeDocIterator(it, min(pos, it->size())));
303                                         bv_->update(Update::FitCursor);
304                                         break;
305                                 }
306                 }
307         }
308
309         if (tolastfiles)
310                 LyX::ref().session().addLastFile(b->fileName());
311
312         return true;
313 }
314
315
316 lyx::frontend::Gui & BufferView::Pimpl::gui() const
317 {
318         return owner_->gui();
319 }
320
321
322 lyx::frontend::WorkArea & BufferView::Pimpl::workarea() const
323 {
324         return *workArea_;
325 }
326
327
328 lyx::frontend::Clipboard & BufferView::Pimpl::clipboard() const
329 {
330         return owner_->gui().clipboard();
331 }
332
333
334 lyx::frontend::Painter & BufferView::Pimpl::painter() const
335 {
336         return workArea_->getPainter();
337 }
338
339
340 int BufferView::Pimpl::width() const
341 {
342         return width_;
343 }
344
345
346 int BufferView::Pimpl::height() const
347 {
348         return height_;
349 }
350
351
352 void BufferView::Pimpl::setBuffer(Buffer * b)
353 {
354         lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
355                             << "[ b = " << b << "]" << endl;
356
357         if (buffer_) {
358                 disconnectBuffer();
359                 // Save the actual cursor position and anchor inside the
360                 // buffer so that it can be restored in case we rechange
361                 // to this buffer later on.
362                 buffer_->saveCursor(cursor_.selectionBegin(),
363                                     cursor_.selectionEnd());
364                 // current buffer is going to be switched-off, save cursor pos
365                 LyX::ref().session().saveFilePosition(buffer_->fileName(),
366                         boost::tie(cursor_.pit(), cursor_.pos()) );
367         }
368
369         // If we are closing current buffer, switch to the first in
370         // buffer list.
371         if (!b) {
372                 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
373                                     << " No Buffer!" << endl;
374                 // We are closing the buffer, use the first buffer as current
375                 buffer_ = bufferlist.first();
376                 owner_->getDialogs().hideBufferDependent();
377         } else {
378                 // Set current buffer
379                 buffer_ = b;
380         }
381
382         // Reset old cursor
383         cursor_ = LCursor(*bv_);
384         anchor_ref_ = 0;
385         offset_ref_ = 0;
386
387
388         // If we're quitting lyx, don't bother updating stuff
389         if (quitting)
390                 return;
391
392         if (buffer_) {
393                 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
394                                     << "Buffer addr: " << buffer_ << endl;
395                 connectBuffer(*buffer_);
396                 cursor_.push(buffer_->inset());
397                 cursor_.resetAnchor();
398                 buffer_->text().init(bv_);
399                 buffer_->text().setCurrentFont(cursor_);
400                 if (buffer_->getCursor().size() > 0 &&
401                     buffer_->getAnchor().size() > 0)
402                 {
403                         cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
404                         cursor_.resetAnchor();
405                         cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
406                         cursor_.setSelection();
407                 }
408
409                 // Buffer-dependent dialogs should be updated or
410                 // hidden. This should go here because some dialogs (eg ToC)
411                 // require bv_->text.
412                 owner_->getDialogs().updateBufferDependent(true);
413         }
414
415         update();
416         owner_->updateMenubar();
417         owner_->updateToolbars();
418         owner_->updateLayoutChoice();
419         owner_->updateWindowTitle();
420
421         // This is done after the layout combox has been populated
422         if (buffer_) {
423                 size_t i = cursor_.depth() - 1;
424                 // we know we'll eventually find a paragraph
425                 while (true) {
426                         CursorSlice const & slice = cursor_[i];
427                         if (!slice.inset().inMathed()) {
428                                 LyXLayout_ptr const layout = slice.paragraph().layout();
429                                 owner_->setLayout(layout->name());
430                                 break;
431                         }
432                         BOOST_ASSERT(i>0);
433                         --i;
434                 }
435         }
436
437         if (buffer_ && lyx::graphics::Previews::status() != LyXRC::PREVIEW_OFF)
438                 lyx::graphics::Previews::get().generateBufferPreviews(*buffer_);
439 }
440
441
442 void BufferView::Pimpl::resizeCurrentBuffer()
443 {
444         lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
445         owner_->busy(true);
446         owner_->message(_("Formatting document..."));
447
448         LyXText * text = bv_->text();
449         if (!text)
450                 return;
451
452         text->init(bv_);
453         update();
454
455         switchKeyMap();
456         owner_->busy(false);
457
458         // Reset the "Formatting..." message
459         owner_->clearMessage();
460 }
461
462
463 void BufferView::Pimpl::updateScrollbar()
464 {
465         if (!bv_->text()) {
466                 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
467                                      << " no text in updateScrollbar" << endl;
468                 scrollbarParameters_.reset();
469                 return;
470         }
471
472         LyXText & t = *bv_->text();
473         int const parsize = int(t.paragraphs().size() - 1);
474         if (anchor_ref_ >  parsize)  {
475                 anchor_ref_ = parsize;
476                 offset_ref_ = 0;
477         }
478
479         lyxerr[Debug::GUI]
480                 << BOOST_CURRENT_FUNCTION
481                 << " Updating scrollbar: height: " << t.paragraphs().size()
482                 << " curr par: " << cursor_.bottom().pit()
483                 << " default height " << defaultRowHeight() << endl;
484
485         // It would be better to fix the scrollbar to understand
486         // values in [0..1] and divide everything by wh
487
488         // estimated average paragraph height:
489         if (wh_ == 0)
490                 wh_ = height_ / 4;
491         int h = t.getPar(anchor_ref_).height();
492
493         // Normalize anchor/offset (MV):
494         while (offset_ref_ > h && anchor_ref_ < parsize) {
495                 anchor_ref_++;
496                 offset_ref_ -= h;
497                 h = t.getPar(anchor_ref_).height();
498         }
499         // Look at paragraph heights on-screen
500         int sumh = 0;
501         int nh = 0;
502         for (lyx::pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
503                 if (sumh > height_)
504                         break;
505                 int const h2 = t.getPar(pit).height();
506                 sumh += h2;
507                 nh++;
508         }
509         int const hav = sumh / nh;
510         // More realistic average paragraph height
511         if (hav > wh_)
512                 wh_ = hav;
513
514         scrollbarParameters_.height = (parsize + 1) * wh_;
515         scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
516         scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
517 }
518
519
520 ScrollbarParameters const & BufferView::Pimpl::scrollbarParameters() const
521 {
522         return scrollbarParameters_;
523 }
524
525
526 void BufferView::Pimpl::scrollDocView(int value)
527 {
528         lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
529                            << "[ value = " << value << "]" << endl;
530
531         if (!buffer_)
532                 return;
533
534         owner_->gui().guiCursor().hide();
535
536         LyXText & t = *bv_->text();
537
538         float const bar = value / float(wh_ * t.paragraphs().size());
539
540         anchor_ref_ = int(bar * t.paragraphs().size());
541         if (anchor_ref_ >  int(t.paragraphs().size()) - 1)
542                 anchor_ref_ = int(t.paragraphs().size()) - 1;
543         t.redoParagraph(anchor_ref_);
544         int const h = t.getPar(anchor_ref_).height();
545         offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
546         update();
547
548         if (!lyxrc.cursor_follows_scrollbar)
549                 return;
550
551         int const height = 2 * defaultRowHeight();
552         int const first = height;
553         int const last = height_ - height;
554         LCursor & cur = cursor_;
555
556         bv_funcs::CurStatus st = bv_funcs::status(bv_, cur);
557
558         switch (st) {
559         case bv_funcs::CUR_ABOVE:
560                 t.setCursorFromCoordinates(cur, 0, first);
561                 cur.clearSelection();
562                 break;
563         case bv_funcs::CUR_BELOW:
564                 t.setCursorFromCoordinates(cur, 0, last);
565                 cur.clearSelection();
566                 break;
567         case bv_funcs::CUR_INSIDE:
568                 int const y = bv_funcs::getPos(cur, cur.boundary()).y_;
569                 int const newy = min(last, max(y, first));
570                 if (y != newy) {
571                         cur.reset(buffer_->inset());
572                         t.setCursorFromCoordinates(cur, 0, newy);
573                 }
574         }
575         owner_->updateLayoutChoice();
576 }
577
578
579 void BufferView::Pimpl::scroll(int /*lines*/)
580 {
581 //      if (!buffer_)
582 //              return;
583 //
584 //      LyXText const * t = bv_->text();
585 //      int const line_height = defaultRowHeight();
586 //
587 //      // The new absolute coordinate
588 //      int new_top_y = top_y() + lines * line_height;
589 //
590 //      // Restrict to a valid value
591 //      new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
592 //      new_top_y = std::max(0, new_top_y);
593 //
594 //      scrollDocView(new_top_y);
595 //
596 //      // Update the scrollbar.
597 //      workArea_->setScrollbarParams(t->height(), top_y(), defaultRowHeight());
598 }
599
600
601 void BufferView::Pimpl::workAreaKeyPress(LyXKeySymPtr key,
602                                          key_modifier::state state)
603 {
604         owner_->getLyXFunc().processKeySym(key, state);
605
606         /* This is perhaps a bit of a hack. When we move
607          * around, or type, it's nice to be able to see
608          * the cursor immediately after the keypress. So
609          * we reset the toggle timeout and force the visibility
610          * of the cursor. Note we cannot do this inside
611          * dispatch() itself, because that's called recursively.
612          */
613         if (available())
614                 owner_->gui().guiCursor().show(*bv_);
615 }
616
617
618 void BufferView::Pimpl::selectionRequested()
619 {
620         static string sel;
621
622         if (!available())
623                 return;
624
625         LCursor & cur = cursor_;
626
627         if (!cur.selection()) {
628                 xsel_cache_.set = false;
629                 return;
630         }
631
632         if (!xsel_cache_.set ||
633             cur.top() != xsel_cache_.cursor ||
634             cur.anchor_.top() != xsel_cache_.anchor)
635         {
636                 xsel_cache_.cursor = cur.top();
637                 xsel_cache_.anchor = cur.anchor_.top();
638                 xsel_cache_.set = cur.selection();
639                 sel = cur.selectionAsString(false);
640                 if (!sel.empty())
641                         clipboard().put(sel);
642         }
643 }
644
645
646 void BufferView::Pimpl::selectionLost()
647 {
648         if (available()) {
649                 owner_->gui().guiCursor().hide();
650                 cursor_.clearSelection();
651                 xsel_cache_.set = false;
652         }
653 }
654
655
656 void BufferView::Pimpl::workAreaResize(int width, int height)
657 {
658         bool const widthChange = width != width_;
659         bool const heightChange = height != height_;
660
661         // Update from work area
662         width_ = width;
663         height_ = height;
664
665         if (buffer_ && widthChange) {
666                 // The visible LyXView need a resize
667                 resizeCurrentBuffer();
668         }
669
670         if (widthChange || heightChange)
671                 update();
672
673         owner_->updateLayoutChoice();
674 }
675
676
677 bool BufferView::Pimpl::fitCursor()
678 {
679         if (bv_funcs::status(bv_, cursor_) == bv_funcs::CUR_INSIDE) {
680                 LyXFont const font = cursor_.getFont();
681                 int const asc = font_metrics::maxAscent(font);
682                 int const des = font_metrics::maxDescent(font);
683                 Point const p = bv_funcs::getPos(cursor_, cursor_.boundary());
684                 if (p.y_ - asc >= 0 && p.y_ + des < height_)
685                         return false;
686         }
687         center();
688         return true;
689 }
690
691
692 bool BufferView::Pimpl::multiParSel()
693 {
694         if (!cursor_.selection())
695                 return false;
696         bool ret = multiparsel_cache_;
697         multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
698         // Either this, or previous selection spans paragraphs
699         return ret || multiparsel_cache_;
700 }
701
702
703 void BufferView::Pimpl::update(Update::flags flags)
704 {
705         lyxerr[Debug::DEBUG]
706                 << BOOST_CURRENT_FUNCTION
707                 << "[fitcursor = " << (flags & Update::FitCursor)
708                 << ", forceupdate = " << (flags & Update::Force)
709                 << ", singlepar = " << (flags & Update::SinglePar)
710                 << "]  buffer: " << buffer_ << endl;
711
712         // Check needed to survive LyX startup
713         if (buffer_) {
714                 // Update macro store
715                 buffer_->buildMacros();
716
717                 CoordCache backup;
718                 std::swap(theCoords, backup);
719
720                 // This, together with doneUpdating(), verifies (using
721                 // asserts) that screen redraw is not called from
722                 // within itself.
723                 theCoords.startUpdating();
724
725                 // First drawing step
726                 ViewMetricsInfo vi = metrics(flags & Update::SinglePar);
727                 bool forceupdate(flags & (Update::Force | Update::SinglePar));
728
729                 if ((flags & Update::FitCursor) && fitCursor()) {
730                         forceupdate = true;
731                         vi = metrics();
732                 }
733                 if ((flags & Update::MultiParSel) && multiParSel()) {
734                         forceupdate = true;
735                         vi = metrics();
736                 }
737                 if (forceupdate) {
738                         // Second drawing step
739                         workArea_->redraw(*bv_, vi);
740                 } else {
741                         // Abort updating of the coord
742                         // cache - just restore the old one
743                         std::swap(theCoords, backup);
744                 }
745         } else
746                 workArea_->greyOut();
747
748         owner_->view_state_changed();
749 }
750
751
752 // Callback for cursor timer
753 void BufferView::Pimpl::cursorToggle()
754 {
755         if (buffer_) {
756                 owner_->gui().guiCursor().toggle(*bv_);
757
758                 // Use this opportunity to deal with any child processes that
759                 // have finished but are waiting to communicate this fact
760                 // to the rest of LyX.
761                 ForkedcallsController & fcc = ForkedcallsController::get();
762                 fcc.handleCompletedProcesses();
763         }
764
765         cursor_timeout.restart();
766 }
767
768
769 bool BufferView::Pimpl::available() const
770 {
771         return buffer_ && bv_->text();
772 }
773
774
775 Change const BufferView::Pimpl::getCurrentChange()
776 {
777         if (!buffer_->params().tracking_changes)
778                 return Change(Change::UNCHANGED);
779
780         LyXText * text = bv_->getLyXText();
781         LCursor & cur = cursor_;
782
783         if (!cur.selection())
784                 return Change(Change::UNCHANGED);
785
786         return text->getPar(cur.selBegin().pit()).
787                         lookupChange(cur.selBegin().pos());
788 }
789
790
791 void BufferView::Pimpl::savePosition(unsigned int i)
792 {
793         if (i >= saved_positions_num)
794                 return;
795         BOOST_ASSERT(cursor_.inTexted());
796         saved_positions[i] = Position(buffer_->fileName(),
797                                       cursor_.paragraph().id(),
798                                       cursor_.pos());
799         if (i > 0)
800                 owner_->message(bformat(_("Saved bookmark %1$d"), i));
801 }
802
803
804 void BufferView::Pimpl::restorePosition(unsigned int i)
805 {
806         if (i >= saved_positions_num)
807                 return;
808
809         string const fname = saved_positions[i].filename;
810
811         cursor_.clearSelection();
812
813         if (fname != buffer_->fileName()) {
814                 Buffer * b = 0;
815                 if (bufferlist.exists(fname))
816                         b = bufferlist.getBuffer(fname);
817                 else {
818                         b = bufferlist.newBuffer(fname);
819                         // Don't ask, just load it
820                         ::loadLyXFile(b, fname);
821                 }
822                 if (b)
823                         setBuffer(b);
824         }
825
826         ParIterator par = buffer_->getParFromID(saved_positions[i].par_id);
827         if (par == buffer_->par_iterator_end())
828                 return;
829
830         bv_->setCursor(makeDocIterator(par, min(par->size(), saved_positions[i].par_pos)));
831
832         if (i > 0)
833                 owner_->message(bformat(_("Moved to bookmark %1$d"), i));
834 }
835
836
837 bool BufferView::Pimpl::isSavedPosition(unsigned int i)
838 {
839         return i < saved_positions_num && !saved_positions[i].filename.empty();
840 }
841
842
843 void BufferView::Pimpl::saveSavedPositions()
844 {
845         // save bookmarks. It is better to use the pit interface
846         // but I do not know how to effectively convert between
847         // par_id and pit.
848         for (unsigned int i=1; i < saved_positions_num; ++i) {
849                 if ( isSavedPosition(i) )
850                         LyX::ref().session().saveBookmark( boost::tie(
851                                 i,
852                                 saved_positions[i].filename,
853                                 saved_positions[i].par_id,
854                                 saved_positions[i].par_pos) );
855         }
856 }
857
858
859 void BufferView::Pimpl::switchKeyMap()
860 {
861         if (!lyxrc.rtl_support)
862                 return;
863
864         Intl & intl = owner_->getIntl();
865         if (bv_->getLyXText()->real_current_font.isRightToLeft()) {
866                 if (intl.keymap == Intl::PRIMARY)
867                         intl.keyMapSec();
868         } else {
869                 if (intl.keymap == Intl::SECONDARY)
870                         intl.keyMapPrim();
871         }
872 }
873
874
875 void BufferView::Pimpl::center()
876 {
877         CursorSlice & bot = cursor_.bottom();
878         lyx::pit_type const pit = bot.pit();
879         bot.text()->redoParagraph(pit);
880         Paragraph const & par = bot.text()->paragraphs()[pit];
881         anchor_ref_ = pit;
882         offset_ref_ = bv_funcs::coordOffset(cursor_, cursor_.boundary()).y_
883                 + par.ascent() - height_ / 2;
884 }
885
886
887 void BufferView::Pimpl::stuffClipboard(string const & content) const
888 {
889         clipboard().put(content);
890 }
891
892
893 void BufferView::Pimpl::menuInsertLyXFile(string const & filenm)
894 {
895         BOOST_ASSERT(cursor_.inTexted());
896         string filename = filenm;
897
898         if (filename.empty()) {
899                 // Launch a file browser
900                 string initpath = lyxrc.document_path;
901
902                 if (available()) {
903                         string const trypath = owner_->buffer()->filePath();
904                         // If directory is writeable, use this as default.
905                         if (isDirWriteable(trypath))
906                                 initpath = trypath;
907                 }
908
909                 FileDialog fileDlg(_("Select LyX document to insert"),
910                         LFUN_FILE_INSERT,
911                         make_pair(string(_("Documents|#o#O")),
912                                   string(lyxrc.document_path)),
913                         make_pair(string(_("Examples|#E#e")),
914                                   string(addPath(package().system_support(), "examples"))));
915
916                 FileDialog::Result result =
917                         fileDlg.open(initpath,
918                                      FileFilterList(_("LyX Documents (*.lyx)")),
919                                      string());
920
921                 if (result.first == FileDialog::Later)
922                         return;
923
924                 filename = result.second;
925
926                 // check selected filename
927                 if (filename.empty()) {
928                         owner_->message(_("Canceled."));
929                         return;
930                 }
931         }
932
933         // Get absolute path of file and add ".lyx"
934         // to the filename if necessary
935         filename = fileSearch(string(), filename, "lyx");
936
937         string const disp_fn = makeDisplayPath(filename);
938         owner_->message(bformat(_("Inserting document %1$s..."), disp_fn));
939
940         string res;
941         Buffer buf("", false);
942         buf.error.connect(boost::bind(&BufferView::Pimpl::addError, this, _1));
943         if (::loadLyXFile(&buf, makeAbsPath(filename))) {
944                 lyx::cap::pasteParagraphList(cursor_, buf.paragraphs(),
945                                              buf.params().textclass);
946                 res = _("Document %1$s inserted.");
947         } else
948                 res = _("Could not insert document %1$s");
949
950         owner_->message(bformat(res, disp_fn));
951         bv_->showErrorList(_("Document insertion"));
952         resizeCurrentBuffer();
953 }
954
955
956 void BufferView::Pimpl::trackChanges()
957 {
958         bool const tracking = buffer_->params().tracking_changes;
959
960         if (!tracking) {
961                 for_each(buffer_->par_iterator_begin(),
962                          buffer_->par_iterator_end(),
963                          bind(&Paragraph::trackChanges, _1, Change::UNCHANGED));
964                 buffer_->params().tracking_changes = true;
965
966                 // We cannot allow undos beyond the freeze point
967                 buffer_->undostack().clear();
968         } else {
969                 cursor_.setCursor(doc_iterator_begin(buffer_->inset()));
970                 if (lyx::find::findNextChange(bv_)) {
971                         owner_->getDialogs().show("changes");
972                         return;
973                 }
974
975                 for_each(buffer_->par_iterator_begin(),
976                          buffer_->par_iterator_end(),
977                          mem_fun_ref(&Paragraph::untrackChanges));
978
979                 buffer_->params().tracking_changes = false;
980         }
981
982         buffer_->redostack().clear();
983 }
984
985
986 bool BufferView::Pimpl::workAreaDispatch(FuncRequest const & cmd0)
987 {
988         //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
989
990         // This is only called for mouse related events including
991         // LFUN_FILE_OPEN generated by drag-and-drop.
992         FuncRequest cmd = cmd0;
993
994         // Handle drag&drop
995         if (cmd.action == LFUN_FILE_OPEN) {
996                 owner_->dispatch(cmd);
997                 return true;
998         }
999
1000         if (!buffer_)
1001                 return false;
1002
1003         LCursor cur(*bv_);
1004         cur.push(buffer_->inset());
1005         cur.selection() = cursor_.selection();
1006
1007         // Doesn't go through lyxfunc, so we need to update
1008         // the layout choice etc. ourselves
1009
1010         // E.g. Qt mouse press when no buffer
1011         if (!available())
1012                 return false;
1013
1014         owner_->gui().guiCursor().hide();
1015
1016         // Either the inset under the cursor or the
1017         // surrounding LyXText will handle this event.
1018
1019         // Build temporary cursor.
1020         cmd.y = min(max(cmd.y, -1), height_);
1021         InsetBase * inset = bv_->text()->editXY(cur, cmd.x, cmd.y);
1022         //lyxerr << BOOST_CURRENT_FUNCTION
1023         //       << " * hit inset at tip: " << inset << endl;
1024         //lyxerr << BOOST_CURRENT_FUNCTION
1025         //       << " * created temp cursor:" << cur << endl;
1026
1027         // Put anchor at the same position.
1028         cur.resetAnchor();
1029
1030         // Try to dispatch to an non-editable inset near this position
1031         // via the temp cursor. If the inset wishes to change the real
1032         // cursor it has to do so explicitly by using
1033         //  cur.bv().cursor() = cur;  (or similar)
1034         if (inset)
1035                 inset->dispatch(cur, cmd);
1036
1037         // Now dispatch to the temporary cursor. If the real cursor should
1038         // be modified, the inset's dispatch has to do so explicitly.
1039         if (!cur.result().dispatched())
1040                 cur.dispatch(cmd);
1041
1042         if (cur.result().dispatched()) {
1043                 // Redraw if requested or necessary.
1044                 if (cur.result().update())
1045                         update(Update::FitCursor | Update::Force);
1046                 else
1047                         update(Update::FitCursor | Update::MultiParSel);
1048         }
1049
1050         // See workAreaKeyPress
1051         cursor_timeout.restart();
1052         owner_->gui().guiCursor().show(*bv_);
1053
1054         // Skip these when selecting
1055         if (cmd.action != LFUN_MOUSE_MOTION) {
1056                 owner_->updateLayoutChoice();
1057                 owner_->updateToolbars();
1058         }
1059
1060         // Slight hack: this is only called currently when we
1061         // clicked somewhere, so we force through the display
1062         // of the new status here.
1063         owner_->clearMessage();
1064         return true;
1065 }
1066
1067
1068 FuncStatus BufferView::Pimpl::getStatus(FuncRequest const & cmd)
1069 {
1070         FuncStatus flag;
1071
1072         switch (cmd.action) {
1073
1074         case LFUN_UNDO:
1075                 flag.enabled(!buffer_->undostack().empty());
1076                 break;
1077         case LFUN_REDO:
1078                 flag.enabled(!buffer_->redostack().empty());
1079                 break;
1080         case LFUN_FILE_INSERT:
1081         case LFUN_FILE_INSERT_ASCII_PARA:
1082         case LFUN_FILE_INSERT_ASCII:
1083         case LFUN_BOOKMARK_SAVE:
1084                 // FIXME: Actually, these LFUNS should be moved to LyXText
1085                 flag.enabled(cursor_.inTexted());
1086                 break;
1087         case LFUN_FONT_STATE:
1088         case LFUN_LABEL_INSERT:
1089         case LFUN_PARAGRAPH_GOTO:
1090         // FIXME handle non-trivially
1091         case LFUN_OUTLINE_UP:
1092         case LFUN_OUTLINE_DOWN:
1093         case LFUN_OUTLINE_IN:
1094         case LFUN_OUTLINE_OUT:
1095         case LFUN_ERROR_NEXT:
1096         case LFUN_NOTE_NEXT:
1097         case LFUN_REFERENCE_NEXT:
1098         case LFUN_WORD_FIND:
1099         case LFUN_WORD_REPLACE:
1100         case LFUN_MARK_OFF:
1101         case LFUN_MARK_ON:
1102         case LFUN_MARK_TOGGLE:
1103         case LFUN_SCREEN_RECENTER:
1104         case LFUN_BIBTEX_DATABASE_ADD:
1105         case LFUN_BIBTEX_DATABASE_DEL:
1106         case LFUN_WORDS_COUNT:
1107                 flag.enabled(true);
1108                 break;
1109
1110         case LFUN_LABEL_GOTO: {
1111                 flag.enabled(!cmd.argument.empty()
1112                     || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
1113                 break;
1114         }
1115
1116         case LFUN_BOOKMARK_GOTO:
1117                 flag.enabled(isSavedPosition(convert<unsigned int>(cmd.argument)));
1118                 break;
1119         case LFUN_CHANGES_TRACK:
1120                 flag.enabled(true);
1121                 flag.setOnOff(buffer_->params().tracking_changes);
1122                 break;
1123
1124         case LFUN_CHANGES_OUTPUT: {
1125                 OutputParams runparams;
1126                 LaTeXFeatures features(*buffer_, buffer_->params(), runparams);
1127                 flag.enabled(buffer_ && buffer_->params().tracking_changes
1128                         && features.isAvailable("dvipost"));
1129                 flag.setOnOff(buffer_->params().output_changes);
1130                 break;
1131         }
1132
1133         case LFUN_CHANGES_MERGE:
1134         case LFUN_CHANGE_ACCEPT: // what about these two
1135         case LFUN_CHANGE_REJECT: // what about these two
1136         case LFUN_ALL_CHANGES_ACCEPT:
1137         case LFUN_ALL_CHANGES_REJECT:
1138                 flag.enabled(buffer_ && buffer_->params().tracking_changes);
1139                 break;
1140
1141         case LFUN_BUFFER_TOGGLE_COMPRESSION: {
1142                 flag.setOnOff(buffer_->params().compressed);
1143                 break;
1144         }
1145
1146         default:
1147                 flag.enabled(false);
1148         }
1149
1150         return flag;
1151 }
1152
1153
1154
1155 bool BufferView::Pimpl::dispatch(FuncRequest const & cmd)
1156 {
1157         //lyxerr << BOOST_CURRENT_FUNCTION
1158         //       << [ cmd = " << cmd << "]" << endl;
1159
1160         // Make sure that the cached BufferView is correct.
1161         lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
1162                 << " action[" << cmd.action << ']'
1163                 << " arg[" << cmd.argument << ']'
1164                 << " x[" << cmd.x << ']'
1165                 << " y[" << cmd.y << ']'
1166                 << " button[" << cmd.button() << ']'
1167                 << endl;
1168
1169         LCursor & cur = cursor_;
1170
1171         switch (cmd.action) {
1172
1173         case LFUN_UNDO:
1174                 if (available()) {
1175                         cur.message(_("Undo"));
1176                         cur.clearSelection();
1177                         if (!textUndo(*bv_))
1178                                 cur.message(_("No further undo information"));
1179                         update();
1180                         switchKeyMap();
1181                 }
1182                 break;
1183
1184         case LFUN_REDO:
1185                 if (available()) {
1186                         cur.message(_("Redo"));
1187                         cur.clearSelection();
1188                         if (!textRedo(*bv_))
1189                                 cur.message(_("No further redo information"));
1190                         update();
1191                         switchKeyMap();
1192                 }
1193                 break;
1194
1195         case LFUN_FILE_INSERT:
1196                 menuInsertLyXFile(cmd.argument);
1197                 break;
1198
1199         case LFUN_FILE_INSERT_ASCII_PARA:
1200                 insertAsciiFile(bv_, cmd.argument, true);
1201                 break;
1202
1203         case LFUN_FILE_INSERT_ASCII:
1204                 insertAsciiFile(bv_, cmd.argument, false);
1205                 break;
1206
1207         case LFUN_FONT_STATE:
1208                 cur.message(cur.currentState());
1209                 break;
1210
1211         case LFUN_BOOKMARK_SAVE:
1212                 savePosition(convert<unsigned int>(cmd.argument));
1213                 break;
1214
1215         case LFUN_BOOKMARK_GOTO:
1216                 restorePosition(convert<unsigned int>(cmd.argument));
1217                 break;
1218
1219         case LFUN_LABEL_GOTO: {
1220                 string label = cmd.argument;
1221                 if (label.empty()) {
1222                         InsetRef * inset =
1223                                 getInsetByCode<InsetRef>(cursor_,
1224                                                          InsetBase::REF_CODE);
1225                         if (inset) {
1226                                 label = inset->getContents();
1227                                 savePosition(0);
1228                         }
1229                 }
1230
1231                 if (!label.empty())
1232                         bv_->gotoLabel(label);
1233                 break;
1234         }
1235
1236         case LFUN_PARAGRAPH_GOTO: {
1237                 int const id = convert<int>(cmd.argument);
1238                 ParIterator par = buffer_->getParFromID(id);
1239                 if (par == buffer_->par_iterator_end()) {
1240                         lyxerr[Debug::INFO] << "No matching paragraph found! ["
1241                                             << id << ']' << endl;
1242                         break;
1243                 } else {
1244                         lyxerr[Debug::INFO] << "Paragraph " << par->id()
1245                                             << " found." << endl;
1246                 }
1247
1248                 // Set the cursor
1249                 bv_->setCursor(makeDocIterator(par, 0));
1250
1251                 update();
1252                 switchKeyMap();
1253                 break;
1254         }
1255
1256         case LFUN_OUTLINE_UP:
1257                 lyx::toc::outline(lyx::toc::Up, cursor_);
1258                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
1259                 updateLabels(*buffer_);
1260                 break;
1261         case LFUN_OUTLINE_DOWN:
1262                 lyx::toc::outline(lyx::toc::Down, cursor_);
1263                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
1264                 updateLabels(*buffer_);
1265                 break;
1266         case LFUN_OUTLINE_IN:
1267                 lyx::toc::outline(lyx::toc::In, cursor_);
1268                 updateLabels(*buffer_);
1269                 break;  
1270         case LFUN_OUTLINE_OUT:
1271                 lyx::toc::outline(lyx::toc::Out, cursor_);
1272                 updateLabels(*buffer_);
1273                 break;
1274
1275         case LFUN_ERROR_NEXT:
1276                 bv_funcs::gotoInset(bv_, InsetBase::ERROR_CODE, false);
1277                 break;
1278
1279         case LFUN_NOTE_NEXT:
1280                 bv_funcs::gotoInset(bv_, InsetBase::NOTE_CODE, false);
1281                 break;
1282
1283         case LFUN_REFERENCE_NEXT: {
1284                 vector<InsetBase_code> tmp;
1285                 tmp.push_back(InsetBase::LABEL_CODE);
1286                 tmp.push_back(InsetBase::REF_CODE);
1287                 bv_funcs::gotoInset(bv_, tmp, true);
1288                 break;
1289         }
1290
1291         case LFUN_CHANGES_TRACK:
1292                 trackChanges();
1293                 break;
1294
1295         case LFUN_CHANGES_OUTPUT: {
1296                 bool const state = buffer_->params().output_changes;
1297                 buffer_->params().output_changes = !state;
1298                 break;
1299         }
1300
1301         case LFUN_CHANGES_MERGE:
1302                 if (lyx::find::findNextChange(bv_))
1303                         owner_->getDialogs().show("changes");
1304                 break;
1305
1306         case LFUN_ALL_CHANGES_ACCEPT: {
1307                 cursor_.reset(buffer_->inset());
1308 #ifdef WITH_WARNINGS
1309 #warning FIXME changes
1310 #endif
1311                 while (lyx::find::findNextChange(bv_))
1312                         bv_->getLyXText()->acceptChange(cursor_);
1313                 update();
1314                 break;
1315         }
1316
1317         case LFUN_ALL_CHANGES_REJECT: {
1318                 cursor_.reset(buffer_->inset());
1319 #ifdef WITH_WARNINGS
1320 #warning FIXME changes
1321 #endif
1322                 while (lyx::find::findNextChange(bv_))
1323                         bv_->getLyXText()->rejectChange(cursor_);
1324                 break;
1325         }
1326
1327         case LFUN_WORD_FIND:
1328                 lyx::find::find(bv_, cmd);
1329                 break;
1330
1331         case LFUN_WORD_REPLACE:
1332                 lyx::find::replace(bv_, cmd);
1333                 break;
1334
1335         case LFUN_MARK_OFF:
1336                 cur.clearSelection();
1337                 cur.resetAnchor();
1338                 cur.message(N_("Mark off"));
1339                 break;
1340
1341         case LFUN_MARK_ON:
1342                 cur.clearSelection();
1343                 cur.mark() = true;
1344                 cur.resetAnchor();
1345                 cur.message(N_("Mark on"));
1346                 break;
1347
1348         case LFUN_MARK_TOGGLE:
1349                 cur.clearSelection();
1350                 if (cur.mark()) {
1351                         cur.mark() = false;
1352                         cur.message(N_("Mark removed"));
1353                 } else {
1354                         cur.mark() = true;
1355                         cur.message(N_("Mark set"));
1356                 }
1357                 cur.resetAnchor();
1358                 break;
1359
1360         case LFUN_SCREEN_RECENTER:
1361                 center();
1362                 break;
1363
1364         case LFUN_BIBTEX_DATABASE_ADD: {
1365                 LCursor tmpcur = cursor_;
1366                 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
1367                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1368                                                 InsetBase::BIBTEX_CODE);
1369                 if (inset) {
1370                         if (inset->addDatabase(cmd.argument))
1371                                 buffer_->updateBibfilesCache();
1372                 }
1373                 break;
1374         }
1375
1376         case LFUN_BIBTEX_DATABASE_DEL: {
1377                 LCursor tmpcur = cursor_;
1378                 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
1379                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1380                                                 InsetBase::BIBTEX_CODE);
1381                 if (inset) {
1382                         if (inset->delDatabase(cmd.argument))
1383                                 buffer_->updateBibfilesCache();
1384                 }
1385                 break;
1386         }
1387
1388         case LFUN_WORDS_COUNT: {
1389                 DocIterator from, to;
1390                 if (cur.selection()) {
1391                         from = cur.selectionBegin();
1392                         to = cur.selectionEnd();
1393                 } else {
1394                         from = doc_iterator_begin(buffer_->inset());
1395                         to = doc_iterator_end(buffer_->inset());
1396                 }
1397                 int const count = countWords(from, to);
1398                 string message;
1399                 if (count != 1) {
1400                         if (cur.selection())
1401                                 message = bformat(_("%1$d words in selection."),
1402                                           count);
1403                                 else
1404                                         message = bformat(_("%1$d words in document."),
1405                                                           count);
1406                 }
1407                 else {
1408                         if (cur.selection())
1409                                 message = _("One word in selection.");
1410                         else
1411                                 message = _("One word in document.");
1412                 }
1413
1414                 Alert::information(_("Count words"), message);
1415         }
1416                 break;
1417
1418         case LFUN_BUFFER_TOGGLE_COMPRESSION:
1419                 // turn compression on/off
1420                 buffer_->params().compressed = !buffer_->params().compressed;
1421                 break;
1422
1423         default:
1424                 return false;
1425         }
1426
1427         return true;
1428 }
1429
1430
1431 ViewMetricsInfo BufferView::Pimpl::metrics(bool singlepar)
1432 {
1433         // Remove old position cache
1434         theCoords.clear();
1435         BufferView & bv = *bv_;
1436         LyXText * const text = bv.text();
1437         lyx::pit_type size = int(text->paragraphs().size());
1438
1439         if (anchor_ref_ > int(text->paragraphs().size() - 1)) {
1440                 anchor_ref_ = int(text->paragraphs().size() - 1);
1441                 offset_ref_ = 0;
1442         }
1443
1444         lyx::pit_type const pit = anchor_ref_;
1445         int pit1 = pit;
1446         int pit2 = pit;
1447         size_t const npit = text->paragraphs().size();
1448
1449         // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
1450         // the (main text, not inset!) paragraph containing the cursor.
1451         // (if this paragraph contains insets etc., rebreaking will
1452         // recursively descend)
1453         if (!singlepar || pit == cursor_.bottom().pit())
1454                 text->redoParagraph(pit);
1455         int y0 = text->getPar(pit).ascent() - offset_ref_;
1456
1457         // Redo paragraphs above anchor if necessary; again, in Single Par
1458         // mode, only if we encounter the (main text) one having the cursor.
1459         int y1 = y0;
1460         while (y1 > 0 && pit1 > 0) {
1461                 y1 -= text->getPar(pit1).ascent();
1462                 --pit1;
1463                 if (!singlepar || pit1 == cursor_.bottom().pit())
1464                         text->redoParagraph(pit1);
1465                 y1 -= text->getPar(pit1).descent();
1466         }
1467
1468
1469         // Take care of ascent of first line
1470         y1 -= text->getPar(pit1).ascent();
1471
1472         // Normalize anchor for next time
1473         anchor_ref_ = pit1;
1474         offset_ref_ = -y1;
1475
1476         // Grey at the beginning is ugly
1477         if (pit1 == 0 && y1 > 0) {
1478                 y0 -= y1;
1479                 y1 = 0;
1480                 anchor_ref_ = 0;
1481         }
1482
1483         // Redo paragraphs below the anchor if necessary. Single par mode:
1484         // only the one containing the cursor if encountered.
1485         int y2 = y0;
1486         while (y2 < bv.workHeight() && pit2 < int(npit) - 1) {
1487                 y2 += text->getPar(pit2).descent();
1488                 ++pit2;
1489                 if (!singlepar || pit2 == cursor_.bottom().pit())
1490                         text->redoParagraph(pit2);
1491                 y2 += text->getPar(pit2).ascent();
1492         }
1493
1494         // Take care of descent of last line
1495         y2 += text->getPar(pit2).descent();
1496
1497         // The coordinates of all these paragraphs are correct, cache them
1498         int y = y1;
1499         for (lyx::pit_type pit = pit1; pit <= pit2; ++pit) {
1500                 y += text->getPar(pit).ascent();
1501                 theCoords.parPos()[text][pit] = Point(0, y);
1502                 if (singlepar && pit == cursor_.bottom().pit()) {
1503                         // In Single Paragraph mode, collect here the
1504                         // y1 and y2 of the (one) paragraph the cursor is in
1505                         y1 = y - text->getPar(pit).ascent();
1506                         y2 = y + text->getPar(pit).descent();
1507                 }
1508                 y += text->getPar(pit).descent();
1509         }
1510
1511         if (singlepar) {
1512                 // collect cursor paragraph iter bounds
1513                 pit1 = cursor_.bottom().pit();
1514                 pit2 = cursor_.bottom().pit();
1515         }
1516
1517         lyxerr[Debug::DEBUG]
1518                 << BOOST_CURRENT_FUNCTION
1519                 << " y1: " << y1
1520                 << " y2: " << y2
1521                 << " pit1: " << pit1
1522                 << " pit2: " << pit2
1523                 << " npit: " << npit
1524                 << " singlepar: " << singlepar
1525                 << "size: " << size
1526                 << endl;
1527
1528         return ViewMetricsInfo(pit1, pit2, y1, y2, singlepar, size);
1529 }