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