]> git.lyx.org Git - lyx.git/blob - src/BufferView_pimpl.C
fix crash when toggling change tracking off
[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), 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;
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                 owner_->setLayout(cursor_.paragraph().layout()->name());
391
392         if (buffer_ && lyx::graphics::Previews::status() != LyXRC::PREVIEW_OFF)
393                 lyx::graphics::Previews::get().generateBufferPreviews(*buffer_);
394 }
395
396
397 void BufferView::Pimpl::resizeCurrentBuffer()
398 {
399         lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
400         owner_->busy(true);
401         owner_->message(_("Formatting document..."));
402
403         LyXText * text = bv_->text();
404         if (!text)
405                 return;
406
407         text->init(bv_);
408         update();
409
410         switchKeyMap();
411         owner_->busy(false);
412
413         // Reset the "Formatting..." message
414         owner_->clearMessage();
415
416         updateScrollbar();
417 }
418
419
420 void BufferView::Pimpl::updateScrollbar()
421 {
422         if (!bv_->text()) {
423                 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
424                                      << " no text in updateScrollbar" << endl;
425                 workarea().setScrollbarParams(0, 0, 0);
426                 return;
427         }
428
429         LyXText & t = *bv_->text();
430         if (anchor_ref_ >  int(t.paragraphs().size()) - 1) {
431                 anchor_ref_ = int(t.paragraphs().size()) - 1;
432                 offset_ref_ = 0;
433         }
434
435         lyxerr[Debug::GUI]
436                 << BOOST_CURRENT_FUNCTION
437                 << " Updating scrollbar: height: " << t.paragraphs().size()
438                 << " curr par: " << cursor_.bottom().pit()
439                 << " default height " << defaultRowHeight() << endl;
440
441         // It would be better to fix the scrollbar to understand
442         // values in [0..1] and divide everything by wh
443
444         // estimated average paragraph height:
445         int const wh = workarea().workHeight() / 4; 
446         int h = t.getPar(anchor_ref_).height();
447         // Normalize anchor/offset (MV):
448         while (offset_ref_ > h) {
449                 anchor_ref_++;
450                 offset_ref_ -= h;
451                 h = t.getPar(anchor_ref_).height();
452         }
453         
454         // The "+ 2" makes inoculates doc bottom display against
455         // unrealistic wh values (docs with very large paragraphs) (MV)
456         workarea().setScrollbarParams((t.paragraphs().size() + 2) * wh, 
457                 anchor_ref_ * wh + int(offset_ref_ * wh / float(h)), 
458                 int(wh * defaultRowHeight() / float(h)));
459 //      workarea().setScrollbarParams(t.paragraphs().size(), anchor_ref_, 1);
460 }
461
462
463 void BufferView::Pimpl::scrollDocView(int value)
464 {
465         lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
466                            << "[ value = " << value << "]" << endl;
467
468         if (!buffer_)
469                 return;
470
471         screen().hideCursor();
472
473         int const wh = workarea().workHeight() / 4;
474
475         LyXText & t = *bv_->text();
476
477         float const bar = value / float(wh * t.paragraphs().size());
478
479         anchor_ref_ = int(bar * t.paragraphs().size());
480         t.redoParagraph(anchor_ref_);
481         int const h = t.getPar(anchor_ref_).height();
482         offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
483         update();
484
485         if (!lyxrc.cursor_follows_scrollbar)
486                 return;
487
488         int const height = 2 * defaultRowHeight();
489         int const first = height;
490         int const last = workarea().workHeight() - height;
491         LCursor & cur = cursor_;
492
493         bv_funcs::CurStatus st = bv_funcs::status(bv_, cur);
494
495         switch (st) {
496         case bv_funcs::CUR_ABOVE:
497                 t.setCursorFromCoordinates(cur, 0, first);
498                 cur.clearSelection();
499                 break;
500         case bv_funcs::CUR_BELOW:
501                 t.setCursorFromCoordinates(cur, 0, last);
502                 cur.clearSelection();
503                 break;
504         case bv_funcs::CUR_INSIDE:
505                 int const y = bv_funcs::getPos(cur, cur.boundary()).y_;
506                 int const newy = min(last, max(y, first));
507                 if (y != newy) {
508                         cur.reset(buffer_->inset());
509                         t.setCursorFromCoordinates(cur, 0, newy);
510                 }
511         }
512         owner_->updateLayoutChoice();
513 }
514
515
516 void BufferView::Pimpl::scroll(int /*lines*/)
517 {
518 //      if (!buffer_)
519 //              return;
520 //
521 //      LyXText const * t = bv_->text();
522 //      int const line_height = defaultRowHeight();
523 //
524 //      // The new absolute coordinate
525 //      int new_top_y = top_y() + lines * line_height;
526 //
527 //      // Restrict to a valid value
528 //      new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
529 //      new_top_y = std::max(0, new_top_y);
530 //
531 //      scrollDocView(new_top_y);
532 //
533 //      // Update the scrollbar.
534 //      workarea().setScrollbarParams(t->height(), top_y(), defaultRowHeight());
535 }
536
537
538 void BufferView::Pimpl::workAreaKeyPress(LyXKeySymPtr key,
539                                          key_modifier::state state)
540 {
541         owner_->getLyXFunc().processKeySym(key, state);
542
543         /* This is perhaps a bit of a hack. When we move
544          * around, or type, it's nice to be able to see
545          * the cursor immediately after the keypress. So
546          * we reset the toggle timeout and force the visibility
547          * of the cursor. Note we cannot do this inside
548          * dispatch() itself, because that's called recursively.
549          */
550         if (available())
551                 screen().showCursor(*bv_);
552 }
553
554
555 void BufferView::Pimpl::selectionRequested()
556 {
557         static string sel;
558
559         if (!available())
560                 return;
561
562         LCursor & cur = cursor_;
563
564         if (!cur.selection()) {
565                 xsel_cache_.set = false;
566                 return;
567         }
568
569         if (!xsel_cache_.set ||
570             cur.top() != xsel_cache_.cursor ||
571             cur.anchor_.top() != xsel_cache_.anchor)
572         {
573                 xsel_cache_.cursor = cur.top();
574                 xsel_cache_.anchor = cur.anchor_.top();
575                 xsel_cache_.set = cur.selection();
576                 sel = cur.selectionAsString(false);
577                 if (!sel.empty())
578                         workarea().putClipboard(sel);
579         }
580 }
581
582
583 void BufferView::Pimpl::selectionLost()
584 {
585         if (available()) {
586                 screen().hideCursor();
587                 cursor_.clearSelection();
588                 xsel_cache_.set = false;
589         }
590 }
591
592
593 void BufferView::Pimpl::workAreaResize()
594 {
595         static int work_area_width;
596         static int work_area_height;
597
598         bool const widthChange = workarea().workWidth() != work_area_width;
599         bool const heightChange = workarea().workHeight() != work_area_height;
600
601         // Update from work area
602         work_area_width = workarea().workWidth();
603         work_area_height = workarea().workHeight();
604
605         if (buffer_ && widthChange) {
606                 // The visible LyXView need a resize
607                 resizeCurrentBuffer();
608         }
609
610         if (widthChange || heightChange)
611                 update();
612
613         // Always make sure that the scrollbar is sane.
614         updateScrollbar();
615         owner_->updateLayoutChoice();
616 }
617
618
619 bool BufferView::Pimpl::fitCursor()
620 {
621         if (bv_funcs::status(bv_, cursor_) == bv_funcs::CUR_INSIDE) {
622                 LyXFont const font = cursor_.getFont();
623                 int const asc = font_metrics::maxAscent(font);
624                 int const des = font_metrics::maxDescent(font);
625                 Point const p = bv_funcs::getPos(cursor_, cursor_.boundary());
626                 if (p.y_ - asc >= 0 && p.y_ + des < workarea().workHeight())
627                         return false;
628         }
629         center();
630         return true;
631 }
632
633
634 void BufferView::Pimpl::update(Update::flags flags)
635 {
636         lyxerr[Debug::DEBUG]
637                 << BOOST_CURRENT_FUNCTION
638                 << "[fitcursor = " << (flags & Update::FitCursor)
639                 << ", forceupdate = " << (flags & Update::Force)
640                 << ", singlepar = " << (flags & Update::SinglePar)
641                 << "]  buffer: " << buffer_ << endl;
642
643         // Check needed to survive LyX startup
644         if (buffer_) {
645                 // Update macro store
646                 buffer_->buildMacros();
647
648                 CoordCache backup;
649                 std::swap(theCoords, backup);
650
651                 // This, together with doneUpdating(), verifies (using
652                 // asserts) that screen redraw is not called from
653                 // within itself.
654                 theCoords.startUpdating();
655
656                 // First drawing step
657                 ViewMetricsInfo vi = metrics();
658                 bool forceupdate(flags & Update::Force);
659
660                 if ((flags & Update::FitCursor) && fitCursor()) {
661                         forceupdate = true;
662                         vi = metrics(flags & Update::SinglePar);
663                 }
664                 if (forceupdate) {
665                         // Second drawing step
666                         screen().redraw(*bv_, vi);
667                 } else {
668                         // Abort updating of the coord
669                         // cache - just restore the old one
670                         std::swap(theCoords, backup);
671                 }
672         } else
673                 screen().greyOut();
674
675         // And the scrollbar
676         updateScrollbar();
677         owner_->view_state_changed();
678 }
679
680
681 // Callback for cursor timer
682 void BufferView::Pimpl::cursorToggle()
683 {
684         if (buffer_) {
685                 screen().toggleCursor(*bv_);
686
687                 // Use this opportunity to deal with any child processes that
688                 // have finished but are waiting to communicate this fact
689                 // to the rest of LyX.
690                 ForkedcallsController & fcc = ForkedcallsController::get();
691                 fcc.handleCompletedProcesses();
692         }
693
694         cursor_timeout.restart();
695 }
696
697
698 bool BufferView::Pimpl::available() const
699 {
700         return buffer_ && bv_->text();
701 }
702
703
704 Change const BufferView::Pimpl::getCurrentChange()
705 {
706         if (!buffer_->params().tracking_changes)
707                 return Change(Change::UNCHANGED);
708
709         LyXText * text = bv_->getLyXText();
710         LCursor & cur = cursor_;
711
712         if (!cur.selection())
713                 return Change(Change::UNCHANGED);
714
715         return text->getPar(cur.selBegin().pit()).
716                         lookupChangeFull(cur.selBegin().pos());
717 }
718
719
720 void BufferView::Pimpl::savePosition(unsigned int i)
721 {
722         if (i >= saved_positions_num)
723                 return;
724         BOOST_ASSERT(cursor_.inTexted());
725         saved_positions[i] = Position(buffer_->fileName(),
726                                       cursor_.paragraph().id(),
727                                       cursor_.pos());
728         if (i > 0)
729                 owner_->message(bformat(_("Saved bookmark %1$d"), i));
730 }
731
732
733 void BufferView::Pimpl::restorePosition(unsigned int i)
734 {
735         if (i >= saved_positions_num)
736                 return;
737
738         string const fname = saved_positions[i].filename;
739
740         cursor_.clearSelection();
741
742         if (fname != buffer_->fileName()) {
743                 Buffer * b = 0;
744                 if (bufferlist.exists(fname))
745                         b = bufferlist.getBuffer(fname);
746                 else {
747                         b = bufferlist.newBuffer(fname);
748                         // Don't ask, just load it
749                         ::loadLyXFile(b, fname);
750                 }
751                 if (b)
752                         setBuffer(b);
753         }
754
755         ParIterator par = buffer_->getParFromID(saved_positions[i].par_id);
756         if (par == buffer_->par_iterator_end())
757                 return;
758
759         bv_->setCursor(makeDocIterator(par, min(par->size(), saved_positions[i].par_pos)));
760
761         if (i > 0)
762                 owner_->message(bformat(_("Moved to bookmark %1$d"), i));
763 }
764
765
766 bool BufferView::Pimpl::isSavedPosition(unsigned int i)
767 {
768         return i < saved_positions_num && !saved_positions[i].filename.empty();
769 }
770
771
772 void BufferView::Pimpl::switchKeyMap()
773 {
774         if (!lyxrc.rtl_support)
775                 return;
776
777         Intl & intl = owner_->getIntl();
778         if (bv_->getLyXText()->real_current_font.isRightToLeft()) {
779                 if (intl.keymap == Intl::PRIMARY)
780                         intl.KeyMapSec();
781         } else {
782                 if (intl.keymap == Intl::SECONDARY)
783                         intl.KeyMapPrim();
784         }
785 }
786
787
788 void BufferView::Pimpl::center()
789 {
790         CursorSlice & bot = cursor_.bottom();
791         lyx::pit_type const pit = bot.pit();
792         bot.text()->redoParagraph(pit);
793         Paragraph const & par = bot.text()->paragraphs()[pit];
794         anchor_ref_ = pit;
795         offset_ref_ = bv_funcs::coordOffset(cursor_, cursor_.boundary()).y_
796                 + par.ascent() - workarea().workHeight() / 2;
797 }
798
799
800 void BufferView::Pimpl::stuffClipboard(string const & content) const
801 {
802         workarea().putClipboard(content);
803 }
804
805
806 void BufferView::Pimpl::MenuInsertLyXFile(string const & filenm)
807 {
808         string filename = filenm;
809
810         if (filename.empty()) {
811                 // Launch a file browser
812                 string initpath = lyxrc.document_path;
813
814                 if (available()) {
815                         string const trypath = owner_->buffer()->filePath();
816                         // If directory is writeable, use this as default.
817                         if (IsDirWriteable(trypath))
818                                 initpath = trypath;
819                 }
820
821                 FileDialog fileDlg(_("Select LyX document to insert"),
822                         LFUN_FILE_INSERT,
823                         make_pair(string(_("Documents|#o#O")),
824                                   string(lyxrc.document_path)),
825                         make_pair(string(_("Examples|#E#e")),
826                                   string(AddPath(package().system_support(), "examples"))));
827
828                 FileDialog::Result result =
829                         fileDlg.open(initpath,
830                                      FileFilterList(_("LyX Documents (*.lyx)")),
831                                      string());
832
833                 if (result.first == FileDialog::Later)
834                         return;
835
836                 filename = result.second;
837
838                 // check selected filename
839                 if (filename.empty()) {
840                         owner_->message(_("Canceled."));
841                         return;
842                 }
843         }
844
845         // Get absolute path of file and add ".lyx"
846         // to the filename if necessary
847         filename = FileSearch(string(), filename, "lyx");
848
849         string const disp_fn = MakeDisplayPath(filename);
850         owner_->message(bformat(_("Inserting document %1$s..."), disp_fn));
851
852         cursor_.clearSelection();
853         bv_->getLyXText()->breakParagraph(cursor_);
854
855         BOOST_ASSERT(cursor_.inTexted());
856
857         string const fname = MakeAbsPath(filename);
858         bool const res = buffer_->readFile(fname, cursor_.pit());
859         resizeCurrentBuffer();
860
861         string s = res ? _("Document %1$s inserted.")
862                        : _("Could not insert document %1$s");
863         owner_->message(bformat(s, disp_fn));
864 }
865
866
867 void BufferView::Pimpl::trackChanges()
868 {
869         bool const tracking = buffer_->params().tracking_changes;
870
871         if (!tracking) {
872                 for_each(buffer_->par_iterator_begin(),
873                          buffer_->par_iterator_end(),
874                          bind(&Paragraph::trackChanges, _1, Change::UNCHANGED));
875                 buffer_->params().tracking_changes = true;
876
877                 // We cannot allow undos beyond the freeze point
878                 buffer_->undostack().clear();
879         } else {
880                 cursor_.setCursor(doc_iterator_begin(buffer_->inset()));
881                 bool const found = lyx::find::findNextChange(bv_);
882                 if (found) {
883                         // We reset the cursor to the start of the
884                         // document, since the Changes Dialog is going
885                         // to search for the next change anyway.
886                         cursor_.setCursor(doc_iterator_begin(buffer_->inset()));
887                         owner_->getDialogs().show("changes");
888                         return;
889                 }
890
891                 for_each(buffer_->par_iterator_begin(),
892                          buffer_->par_iterator_end(),
893                          mem_fun_ref(&Paragraph::untrackChanges));
894
895                 buffer_->params().tracking_changes = false;
896         }
897
898         buffer_->redostack().clear();
899 }
900
901
902 bool BufferView::Pimpl::workAreaDispatch(FuncRequest const & cmd0)
903 {
904         //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
905
906         // This is only called for mouse related events including
907         // LFUN_FILE_OPEN generated by drag-and-drop.
908         FuncRequest cmd = cmd0;
909
910         // Handle drag&drop
911         if (cmd.action == LFUN_FILE_OPEN) {
912                 owner_->dispatch(cmd);
913                 return true;
914         }
915
916         if (!buffer_)
917                 return false;
918
919         LCursor cur(*bv_);
920         cur.push(buffer_->inset());
921         cur.selection() = cursor_.selection();
922
923         // Doesn't go through lyxfunc, so we need to update
924         // the layout choice etc. ourselves
925
926         // E.g. Qt mouse press when no buffer
927         if (!available())
928                 return false;
929
930         screen().hideCursor();
931
932         // Either the inset under the cursor or the
933         // surrounding LyXText will handle this event.
934
935         // Build temporary cursor.
936         cmd.y = min(max(cmd.y,-1), workarea().workHeight());
937         InsetBase * inset = bv_->text()->editXY(cur, cmd.x, cmd.y);
938         //lyxerr << BOOST_CURRENT_FUNCTION
939         //       << " * hit inset at tip: " << inset << endl;
940         //lyxerr << BOOST_CURRENT_FUNCTION
941         //       << " * created temp cursor:" << cur << endl;
942
943         // Put anchor at the same position.
944         cur.resetAnchor();
945
946         // Try to dispatch to an non-editable inset near this position
947         // via the temp cursor. If the inset wishes to change the real
948         // cursor it has to do so explicitly by using
949         //  cur.bv().cursor() = cur;  (or similar)
950         if (inset)
951                 inset->dispatch(cur, cmd);
952
953         // Now dispatch to the temporary cursor. If the real cursor should
954         // be modified, the inset's dispatch has to do so explicitly.
955         if (!cur.result().dispatched())
956                 cur.dispatch(cmd);
957
958         if (cur.result().dispatched()) {
959                 // Redraw if requested or necessary.
960                 if (cur.result().update())
961                         update(Update::FitCursor | Update::Force);
962                 else
963                         update();
964         }
965
966         // See workAreaKeyPress
967         cursor_timeout.restart();
968         screen().showCursor(*bv_);
969
970         // Skip these when selecting
971         if (cmd.action != LFUN_MOUSE_MOTION) {
972                 owner_->updateLayoutChoice();
973                 owner_->updateToolbars();
974         }
975
976         // Slight hack: this is only called currently when we
977         // clicked somewhere, so we force through the display
978         // of the new status here.
979         owner_->clearMessage();
980         return true;
981 }
982
983
984 FuncStatus BufferView::Pimpl::getStatus(FuncRequest const & cmd)
985 {
986         FuncStatus flag;
987
988         switch (cmd.action) {
989
990         case LFUN_UNDO:
991                 flag.enabled(!buffer_->undostack().empty());
992                 break;
993         case LFUN_REDO:
994                 flag.enabled(!buffer_->redostack().empty());
995                 break;
996         case LFUN_FILE_INSERT:
997         case LFUN_FILE_INSERT_ASCII_PARA:
998         case LFUN_FILE_INSERT_ASCII:
999         case LFUN_FONT_STATE:
1000         case LFUN_INSERT_LABEL:
1001         case LFUN_BOOKMARK_SAVE:
1002         case LFUN_GOTO_PARAGRAPH:
1003         case LFUN_GOTOERROR:
1004         case LFUN_GOTONOTE:
1005         case LFUN_REFERENCE_GOTO:
1006         case LFUN_WORD_FIND:
1007         case LFUN_WORD_REPLACE:
1008         case LFUN_MARK_OFF:
1009         case LFUN_MARK_ON:
1010         case LFUN_SETMARK:
1011         case LFUN_CENTER:
1012         case LFUN_BIBDB_ADD:
1013         case LFUN_BIBDB_DEL:
1014         case LFUN_WORDS_COUNT:
1015                 flag.enabled(true);
1016                 break;
1017
1018         case LFUN_LABEL_GOTO: {
1019                 flag.enabled(!cmd.argument.empty()
1020                     || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
1021                 break;
1022         }
1023
1024         case LFUN_BOOKMARK_GOTO:
1025                 flag.enabled(isSavedPosition(convert<unsigned int>(cmd.argument)));
1026                 break;
1027         case LFUN_TRACK_CHANGES:
1028                 flag.enabled(true);
1029                 flag.setOnOff(buffer_->params().tracking_changes);
1030                 break;
1031
1032         case LFUN_OUTPUT_CHANGES: {
1033                 LaTeXFeatures features(*buffer_, buffer_->params(), false);
1034                 flag.enabled(buffer_ && buffer_->params().tracking_changes
1035                         && features.isAvailable("dvipost"));
1036                 flag.setOnOff(buffer_->params().output_changes);
1037                 break;
1038         }
1039
1040         case LFUN_MERGE_CHANGES:
1041         case LFUN_ACCEPT_CHANGE: // what about these two
1042         case LFUN_REJECT_CHANGE: // what about these two
1043         case LFUN_ACCEPT_ALL_CHANGES:
1044         case LFUN_REJECT_ALL_CHANGES:
1045                 flag.enabled(buffer_ && buffer_->params().tracking_changes);
1046                 break;
1047         default:
1048                 flag.enabled(false);
1049         }
1050
1051         return flag;
1052 }
1053
1054
1055
1056 bool BufferView::Pimpl::dispatch(FuncRequest const & cmd)
1057 {
1058         //lyxerr << BOOST_CURRENT_FUNCTION
1059         //       << [ cmd = " << cmd << "]" << endl;
1060
1061         // Make sure that the cached BufferView is correct.
1062         lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
1063                 << " action[" << cmd.action << ']'
1064                 << " arg[" << cmd.argument << ']'
1065                 << " x[" << cmd.x << ']'
1066                 << " y[" << cmd.y << ']'
1067                 << " button[" << cmd.button() << ']'
1068                 << endl;
1069
1070         LCursor & cur = cursor_;
1071
1072         switch (cmd.action) {
1073
1074         case LFUN_UNDO:
1075                 if (available()) {
1076                         cur.message(_("Undo"));
1077                         cur.clearSelection();
1078                         if (!textUndo(*bv_))
1079                                 cur.message(_("No further undo information"));
1080                         update();
1081                         switchKeyMap();
1082                 }
1083                 break;
1084
1085         case LFUN_REDO:
1086                 if (available()) {
1087                         cur.message(_("Redo"));
1088                         cur.clearSelection();
1089                         if (!textRedo(*bv_))
1090                                 cur.message(_("No further redo information"));
1091                         update();
1092                         switchKeyMap();
1093                 }
1094                 break;
1095
1096         case LFUN_FILE_INSERT:
1097                 MenuInsertLyXFile(cmd.argument);
1098                 break;
1099
1100         case LFUN_FILE_INSERT_ASCII_PARA:
1101                 InsertAsciiFile(bv_, cmd.argument, true);
1102                 break;
1103
1104         case LFUN_FILE_INSERT_ASCII:
1105                 InsertAsciiFile(bv_, cmd.argument, false);
1106                 break;
1107
1108         case LFUN_FONT_STATE:
1109                 cur.message(cur.currentState());
1110                 break;
1111
1112         case LFUN_BOOKMARK_SAVE:
1113                 savePosition(convert<unsigned int>(cmd.argument));
1114                 break;
1115
1116         case LFUN_BOOKMARK_GOTO:
1117                 restorePosition(convert<unsigned int>(cmd.argument));
1118                 break;
1119
1120         case LFUN_LABEL_GOTO: {
1121                 string label = cmd.argument;
1122                 if (label.empty()) {
1123                         InsetRef * inset =
1124                                 getInsetByCode<InsetRef>(cursor_,
1125                                                          InsetBase::REF_CODE);
1126                         if (inset) {
1127                                 label = inset->getContents();
1128                                 savePosition(0);
1129                         }
1130                 }
1131
1132                 if (!label.empty())
1133                         bv_->gotoLabel(label);
1134                 break;
1135         }
1136
1137         case LFUN_GOTO_PARAGRAPH: {
1138                 int const id = convert<int>(cmd.argument);
1139                 ParIterator par = buffer_->getParFromID(id);
1140                 if (par == buffer_->par_iterator_end()) {
1141                         lyxerr[Debug::INFO] << "No matching paragraph found! ["
1142                                             << id << ']' << endl;
1143                         break;
1144                 } else {
1145                         lyxerr[Debug::INFO] << "Paragraph " << par->id()
1146                                             << " found." << endl;
1147                 }
1148
1149                 // Set the cursor
1150                 bv_->setCursor(makeDocIterator(par, 0));
1151
1152                 update();
1153                 switchKeyMap();
1154                 break;
1155         }
1156
1157         case LFUN_GOTOERROR:
1158                 bv_funcs::gotoInset(bv_, InsetBase::ERROR_CODE, false);
1159                 break;
1160
1161         case LFUN_GOTONOTE:
1162                 bv_funcs::gotoInset(bv_, InsetBase::NOTE_CODE, false);
1163                 break;
1164
1165         case LFUN_REFERENCE_GOTO: {
1166                 vector<InsetBase_code> tmp;
1167                 tmp.push_back(InsetBase::LABEL_CODE);
1168                 tmp.push_back(InsetBase::REF_CODE);
1169                 bv_funcs::gotoInset(bv_, tmp, true);
1170                 break;
1171         }
1172
1173         case LFUN_TRACK_CHANGES:
1174                 trackChanges();
1175                 break;
1176
1177         case LFUN_OUTPUT_CHANGES: {
1178                 bool const state = buffer_->params().output_changes;
1179                 buffer_->params().output_changes = !state;
1180                 break;
1181         }
1182
1183         case LFUN_MERGE_CHANGES:
1184                 owner_->getDialogs().show("changes");
1185                 break;
1186
1187         case LFUN_ACCEPT_ALL_CHANGES: {
1188                 cursor_.reset(buffer_->inset());
1189 #ifdef WITH_WARNINGS
1190 #warning FIXME changes
1191 #endif
1192                 while (lyx::find::findNextChange(bv_))
1193                         bv_->getLyXText()->acceptChange(cursor_);
1194                 update();
1195                 break;
1196         }
1197
1198         case LFUN_REJECT_ALL_CHANGES: {
1199                 cursor_.reset(buffer_->inset());
1200 #ifdef WITH_WARNINGS
1201 #warning FIXME changes
1202 #endif
1203                 while (lyx::find::findNextChange(bv_))
1204                         bv_->getLyXText()->rejectChange(cursor_);
1205                 break;
1206         }
1207
1208         case LFUN_WORD_FIND:
1209                 lyx::find::find(bv_, cmd);
1210                 break;
1211
1212         case LFUN_WORD_REPLACE:
1213                 lyx::find::replace(bv_, cmd);
1214                 break;
1215
1216         case LFUN_MARK_OFF:
1217                 cur.clearSelection();
1218                 cur.resetAnchor();
1219                 cur.message(N_("Mark off"));
1220                 break;
1221
1222         case LFUN_MARK_ON:
1223                 cur.clearSelection();
1224                 cur.mark() = true;
1225                 cur.resetAnchor();
1226                 cur.message(N_("Mark on"));
1227                 break;
1228
1229         case LFUN_SETMARK:
1230                 cur.clearSelection();
1231                 if (cur.mark()) {
1232                         cur.mark() = false;
1233                         cur.message(N_("Mark removed"));
1234                 } else {
1235                         cur.mark() = true;
1236                         cur.message(N_("Mark set"));
1237                 }
1238                 cur.resetAnchor();
1239                 break;
1240
1241         case LFUN_CENTER:
1242                 center();
1243                 break;
1244
1245         case LFUN_BIBDB_ADD: {
1246                 LCursor tmpcur = cursor_;
1247                 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
1248                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1249                                                 InsetBase::BIBTEX_CODE);
1250                 if (inset)
1251                         inset->addDatabase(cmd.argument);
1252                 break;
1253         }
1254
1255         case LFUN_BIBDB_DEL: {
1256                 LCursor tmpcur = cursor_;
1257                 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
1258                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1259                                                 InsetBase::BIBTEX_CODE);
1260                 if (inset)
1261                         inset->delDatabase(cmd.argument);
1262                 break;
1263         }
1264
1265         case LFUN_WORDS_COUNT: {
1266                 DocIterator from, to;
1267                 if (cur.selection()) {
1268                         from = cur.selectionBegin();
1269                         to = cur.selectionEnd();
1270                 } else {
1271                         from = doc_iterator_begin(buffer_->inset());
1272                         to = doc_iterator_end(buffer_->inset());
1273                 }
1274                 int const count = countWords(from, to);
1275                 string message;
1276                 if (count != 1) {
1277                         if (cur.selection())
1278                                 message = bformat(_("%1$d words in selection."),
1279                                           count);
1280                                 else
1281                                         message = bformat(_("%1$d words in document."),
1282                                                           count);
1283                 }
1284                 else {
1285                         if (cur.selection())
1286                                 message = _("One word in selection.");
1287                         else
1288                                 message = _("One word in document.");
1289                 }
1290
1291                 Alert::information(_("Count words"), message);
1292         }
1293                 break;
1294         default:
1295                 return false;
1296         }
1297
1298         return true;
1299 }
1300
1301
1302 ViewMetricsInfo BufferView::Pimpl::metrics(bool singlepar)
1303 {
1304         // Remove old position cache
1305         theCoords.clear();
1306         BufferView & bv = *bv_;
1307         LyXText * const text = bv.text();
1308         if (anchor_ref_ > int(text->paragraphs().size() - 1)) {
1309                 anchor_ref_ = int(text->paragraphs().size() - 1);
1310                 offset_ref_ = 0;
1311         }
1312
1313         lyx::pit_type const pit = anchor_ref_;
1314         int pit1 = pit;
1315         int pit2 = pit;
1316         size_t const npit = text->paragraphs().size();
1317
1318         lyxerr[Debug::DEBUG]
1319                 << BOOST_CURRENT_FUNCTION
1320                 << " npit: " << npit
1321                 << " pit1: " << pit1
1322                 << " pit2: " << pit2
1323                 << endl;
1324
1325         // Rebreak anchor par
1326         text->redoParagraph(pit);
1327         int y0 = text->getPar(pit1).ascent() - offset_ref_;
1328
1329         // Redo paragraphs above cursor if necessary
1330         int y1 = y0;
1331         while (!singlepar && y1 > 0 && pit1 > 0) {
1332                 y1 -= text->getPar(pit1).ascent();
1333                 --pit1;
1334                 text->redoParagraph(pit1);
1335                 y1 -= text->getPar(pit1).descent();
1336         }
1337
1338
1339         // Take care of ascent of first line
1340         y1 -= text->getPar(pit1).ascent();
1341
1342         // Normalize anchor for next time
1343         anchor_ref_ = pit1;
1344         offset_ref_ = -y1;
1345
1346         // Grey at the beginning is ugly
1347         if (pit1 == 0 && y1 > 0) {
1348                 y0 -= y1;
1349                 y1 = 0;
1350                 anchor_ref_ = 0;
1351         }
1352
1353         // Redo paragraphs below cursor if necessary
1354         int y2 = y0;
1355         while (!singlepar && y2 < bv.workHeight() && pit2 < int(npit) - 1) {
1356                 y2 += text->getPar(pit2).descent();
1357                 ++pit2;
1358                 text->redoParagraph(pit2);
1359                 y2 += text->getPar(pit2).ascent();
1360         }
1361
1362         // Take care of descent of last line
1363         y2 += text->getPar(pit2).descent();
1364
1365         // The coordinates of all these paragraphs are correct, cache them
1366         int y = y1;
1367         for (lyx::pit_type pit = pit1; pit <= pit2; ++pit) {
1368                 y += text->getPar(pit).ascent();
1369                 theCoords.parPos()[text][pit] = Point(0, y);
1370                 y += text->getPar(pit).descent();
1371         }
1372
1373         lyxerr[Debug::DEBUG]
1374                 << BOOST_CURRENT_FUNCTION
1375                 << " y1: " << y1
1376                 << " y2: " << y2
1377                 << endl;
1378
1379         return ViewMetricsInfo(pit1, pit2, y1, y2, singlepar);
1380 }