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