]> git.lyx.org Git - lyx.git/blob - src/BufferView_pimpl.C
fix nullstream also in pch files
[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 void BufferView::Pimpl::update(Update::flags flags)
662 {
663         lyxerr[Debug::DEBUG]
664                 << BOOST_CURRENT_FUNCTION
665                 << "[fitcursor = " << (flags & Update::FitCursor)
666                 << ", forceupdate = " << (flags & Update::Force)
667                 << ", singlepar = " << (flags & Update::SinglePar)
668                 << "]  buffer: " << buffer_ << endl;
669
670         // Check needed to survive LyX startup
671         if (buffer_) {
672                 // Update macro store
673                 buffer_->buildMacros();
674
675                 CoordCache backup;
676                 std::swap(theCoords, backup);
677
678                 // This, together with doneUpdating(), verifies (using
679                 // asserts) that screen redraw is not called from
680                 // within itself.
681                 theCoords.startUpdating();
682
683                 // First drawing step
684                 ViewMetricsInfo vi = metrics(flags & Update::SinglePar);
685                 bool forceupdate(flags & Update::Force);
686
687                 if ((flags & Update::FitCursor) && fitCursor()) {
688                         forceupdate = true;
689                         vi = metrics();
690                 }
691                 if (forceupdate) {
692                         // Second drawing step
693                         screen().redraw(*bv_, vi);
694                 } else {
695                         // Abort updating of the coord
696                         // cache - just restore the old one
697                         std::swap(theCoords, backup);
698                 }
699         } else
700                 screen().greyOut();
701
702         // And the scrollbar
703         updateScrollbar();
704         owner_->view_state_changed();
705 }
706
707
708 // Callback for cursor timer
709 void BufferView::Pimpl::cursorToggle()
710 {
711         if (buffer_) {
712                 screen().toggleCursor(*bv_);
713
714                 // Use this opportunity to deal with any child processes that
715                 // have finished but are waiting to communicate this fact
716                 // to the rest of LyX.
717                 ForkedcallsController & fcc = ForkedcallsController::get();
718                 fcc.handleCompletedProcesses();
719         }
720
721         cursor_timeout.restart();
722 }
723
724
725 bool BufferView::Pimpl::available() const
726 {
727         return buffer_ && bv_->text();
728 }
729
730
731 Change const BufferView::Pimpl::getCurrentChange()
732 {
733         if (!buffer_->params().tracking_changes)
734                 return Change(Change::UNCHANGED);
735
736         LyXText * text = bv_->getLyXText();
737         LCursor & cur = cursor_;
738
739         if (!cur.selection())
740                 return Change(Change::UNCHANGED);
741
742         return text->getPar(cur.selBegin().pit()).
743                         lookupChangeFull(cur.selBegin().pos());
744 }
745
746
747 void BufferView::Pimpl::savePosition(unsigned int i)
748 {
749         if (i >= saved_positions_num)
750                 return;
751         BOOST_ASSERT(cursor_.inTexted());
752         saved_positions[i] = Position(buffer_->fileName(),
753                                       cursor_.paragraph().id(),
754                                       cursor_.pos());
755         if (i > 0)
756                 owner_->message(bformat(_("Saved bookmark %1$d"), i));
757 }
758
759
760 void BufferView::Pimpl::restorePosition(unsigned int i)
761 {
762         if (i >= saved_positions_num)
763                 return;
764
765         string const fname = saved_positions[i].filename;
766
767         cursor_.clearSelection();
768
769         if (fname != buffer_->fileName()) {
770                 Buffer * b = 0;
771                 if (bufferlist.exists(fname))
772                         b = bufferlist.getBuffer(fname);
773                 else {
774                         b = bufferlist.newBuffer(fname);
775                         // Don't ask, just load it
776                         ::loadLyXFile(b, fname);
777                 }
778                 if (b)
779                         setBuffer(b);
780         }
781
782         ParIterator par = buffer_->getParFromID(saved_positions[i].par_id);
783         if (par == buffer_->par_iterator_end())
784                 return;
785
786         bv_->setCursor(makeDocIterator(par, min(par->size(), saved_positions[i].par_pos)));
787
788         if (i > 0)
789                 owner_->message(bformat(_("Moved to bookmark %1$d"), i));
790 }
791
792
793 bool BufferView::Pimpl::isSavedPosition(unsigned int i)
794 {
795         return i < saved_positions_num && !saved_positions[i].filename.empty();
796 }
797
798
799 void BufferView::Pimpl::switchKeyMap()
800 {
801         if (!lyxrc.rtl_support)
802                 return;
803
804         Intl & intl = owner_->getIntl();
805         if (bv_->getLyXText()->real_current_font.isRightToLeft()) {
806                 if (intl.keymap == Intl::PRIMARY)
807                         intl.KeyMapSec();
808         } else {
809                 if (intl.keymap == Intl::SECONDARY)
810                         intl.KeyMapPrim();
811         }
812 }
813
814
815 void BufferView::Pimpl::center()
816 {
817         CursorSlice & bot = cursor_.bottom();
818         lyx::pit_type const pit = bot.pit();
819         bot.text()->redoParagraph(pit);
820         Paragraph const & par = bot.text()->paragraphs()[pit];
821         anchor_ref_ = pit;
822         offset_ref_ = bv_funcs::coordOffset(cursor_, cursor_.boundary()).y_
823                 + par.ascent() - workarea().workHeight() / 2;
824 }
825
826
827 void BufferView::Pimpl::stuffClipboard(string const & content) const
828 {
829         workarea().putClipboard(content);
830 }
831
832
833 void BufferView::Pimpl::MenuInsertLyXFile(string const & filenm)
834 {
835         BOOST_ASSERT(cursor_.inTexted());
836         string filename = filenm;
837
838         if (filename.empty()) {
839                 // Launch a file browser
840                 string initpath = lyxrc.document_path;
841
842                 if (available()) {
843                         string const trypath = owner_->buffer()->filePath();
844                         // If directory is writeable, use this as default.
845                         if (IsDirWriteable(trypath))
846                                 initpath = trypath;
847                 }
848
849                 FileDialog fileDlg(_("Select LyX document to insert"),
850                         LFUN_FILE_INSERT,
851                         make_pair(string(_("Documents|#o#O")),
852                                   string(lyxrc.document_path)),
853                         make_pair(string(_("Examples|#E#e")),
854                                   string(AddPath(package().system_support(), "examples"))));
855
856                 FileDialog::Result result =
857                         fileDlg.open(initpath,
858                                      FileFilterList(_("LyX Documents (*.lyx)")),
859                                      string());
860
861                 if (result.first == FileDialog::Later)
862                         return;
863
864                 filename = result.second;
865
866                 // check selected filename
867                 if (filename.empty()) {
868                         owner_->message(_("Canceled."));
869                         return;
870                 }
871         }
872
873         // Get absolute path of file and add ".lyx"
874         // to the filename if necessary
875         filename = FileSearch(string(), filename, "lyx");
876
877         string const disp_fn = MakeDisplayPath(filename);
878         owner_->message(bformat(_("Inserting document %1$s..."), disp_fn));
879
880         string res;
881         Buffer buf("", false);
882         buf.error.connect(boost::bind(&BufferView::Pimpl::addError, this, _1));
883         if (::loadLyXFile(&buf, MakeAbsPath(filename))) {
884                 lyx::cap::pasteParagraphList(cursor_, buf.paragraphs(), 
885                                              buf.params().textclass);
886                 res = _("Document %1$s inserted.");
887         } else
888                 res = _("Could not insert document %1$s");
889
890         owner_->message(bformat(res, disp_fn));
891         bv_->showErrorList(_("Document insertion"));
892         resizeCurrentBuffer();
893 }
894
895
896 void BufferView::Pimpl::trackChanges()
897 {
898         bool const tracking = buffer_->params().tracking_changes;
899
900         if (!tracking) {
901                 for_each(buffer_->par_iterator_begin(),
902                          buffer_->par_iterator_end(),
903                          bind(&Paragraph::trackChanges, _1, Change::UNCHANGED));
904                 buffer_->params().tracking_changes = true;
905
906                 // We cannot allow undos beyond the freeze point
907                 buffer_->undostack().clear();
908         } else {
909                 cursor_.setCursor(doc_iterator_begin(buffer_->inset()));
910                 bool const found = lyx::find::findNextChange(bv_);
911                 if (found) {
912                         // We reset the cursor to the start of the
913                         // document, since the Changes Dialog is going
914                         // to search for the next change anyway.
915                         cursor_.setCursor(doc_iterator_begin(buffer_->inset()));
916                         owner_->getDialogs().show("changes");
917                         return;
918                 }
919
920                 for_each(buffer_->par_iterator_begin(),
921                          buffer_->par_iterator_end(),
922                          mem_fun_ref(&Paragraph::untrackChanges));
923
924                 buffer_->params().tracking_changes = false;
925         }
926
927         buffer_->redostack().clear();
928 }
929
930
931 bool BufferView::Pimpl::workAreaDispatch(FuncRequest const & cmd0)
932 {
933         //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
934
935         // This is only called for mouse related events including
936         // LFUN_FILE_OPEN generated by drag-and-drop.
937         FuncRequest cmd = cmd0;
938
939         // Handle drag&drop
940         if (cmd.action == LFUN_FILE_OPEN) {
941                 owner_->dispatch(cmd);
942                 return true;
943         }
944
945         if (!buffer_)
946                 return false;
947
948         LCursor cur(*bv_);
949         cur.push(buffer_->inset());
950         cur.selection() = cursor_.selection();
951
952         // Doesn't go through lyxfunc, so we need to update
953         // the layout choice etc. ourselves
954
955         // E.g. Qt mouse press when no buffer
956         if (!available())
957                 return false;
958
959         screen().hideCursor();
960
961         // Either the inset under the cursor or the
962         // surrounding LyXText will handle this event.
963
964         // Build temporary cursor.
965         cmd.y = min(max(cmd.y,-1), workarea().workHeight());
966         InsetBase * inset = bv_->text()->editXY(cur, cmd.x, cmd.y);
967         //lyxerr << BOOST_CURRENT_FUNCTION
968         //       << " * hit inset at tip: " << inset << endl;
969         //lyxerr << BOOST_CURRENT_FUNCTION
970         //       << " * created temp cursor:" << cur << endl;
971
972         // Put anchor at the same position.
973         cur.resetAnchor();
974
975         // Try to dispatch to an non-editable inset near this position
976         // via the temp cursor. If the inset wishes to change the real
977         // cursor it has to do so explicitly by using
978         //  cur.bv().cursor() = cur;  (or similar)
979         if (inset)
980                 inset->dispatch(cur, cmd);
981
982         // Now dispatch to the temporary cursor. If the real cursor should
983         // be modified, the inset's dispatch has to do so explicitly.
984         if (!cur.result().dispatched())
985                 cur.dispatch(cmd);
986
987         if (cur.result().dispatched()) {
988                 // Redraw if requested or necessary.
989                 if (cur.result().update())
990                         update(Update::FitCursor | Update::Force);
991                 else
992                         update();
993         }
994
995         // See workAreaKeyPress
996         cursor_timeout.restart();
997         screen().showCursor(*bv_);
998
999         // Skip these when selecting
1000         if (cmd.action != LFUN_MOUSE_MOTION) {
1001                 owner_->updateLayoutChoice();
1002                 owner_->updateToolbars();
1003         }
1004
1005         // Slight hack: this is only called currently when we
1006         // clicked somewhere, so we force through the display
1007         // of the new status here.
1008         owner_->clearMessage();
1009         return true;
1010 }
1011
1012
1013 FuncStatus BufferView::Pimpl::getStatus(FuncRequest const & cmd)
1014 {
1015         FuncStatus flag;
1016
1017         switch (cmd.action) {
1018
1019         case LFUN_UNDO:
1020                 flag.enabled(!buffer_->undostack().empty());
1021                 break;
1022         case LFUN_REDO:
1023                 flag.enabled(!buffer_->redostack().empty());
1024                 break;
1025         case LFUN_FILE_INSERT:
1026         case LFUN_FILE_INSERT_ASCII_PARA:
1027         case LFUN_FILE_INSERT_ASCII:
1028                 // FIXME: Actually, these LFUNS should be moved to LyXText
1029                 flag.enabled(cursor_.inTexted());
1030                 break;
1031         case LFUN_FONT_STATE:
1032         case LFUN_INSERT_LABEL:
1033         case LFUN_BOOKMARK_SAVE:
1034         case LFUN_GOTO_PARAGRAPH:
1035         case LFUN_GOTOERROR:
1036         case LFUN_GOTONOTE:
1037         case LFUN_REFERENCE_GOTO:
1038         case LFUN_WORD_FIND:
1039         case LFUN_WORD_REPLACE:
1040         case LFUN_MARK_OFF:
1041         case LFUN_MARK_ON:
1042         case LFUN_SETMARK:
1043         case LFUN_CENTER:
1044         case LFUN_BIBDB_ADD:
1045         case LFUN_BIBDB_DEL:
1046         case LFUN_WORDS_COUNT:
1047                 flag.enabled(true);
1048                 break;
1049
1050         case LFUN_LABEL_GOTO: {
1051                 flag.enabled(!cmd.argument.empty()
1052                     || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
1053                 break;
1054         }
1055
1056         case LFUN_BOOKMARK_GOTO:
1057                 flag.enabled(isSavedPosition(convert<unsigned int>(cmd.argument)));
1058                 break;
1059         case LFUN_TRACK_CHANGES:
1060                 flag.enabled(true);
1061                 flag.setOnOff(buffer_->params().tracking_changes);
1062                 break;
1063
1064         case LFUN_OUTPUT_CHANGES: {
1065                 LaTeXFeatures features(*buffer_, buffer_->params(), false);
1066                 flag.enabled(buffer_ && buffer_->params().tracking_changes
1067                         && features.isAvailable("dvipost"));
1068                 flag.setOnOff(buffer_->params().output_changes);
1069                 break;
1070         }
1071
1072         case LFUN_MERGE_CHANGES:
1073         case LFUN_ACCEPT_CHANGE: // what about these two
1074         case LFUN_REJECT_CHANGE: // what about these two
1075         case LFUN_ACCEPT_ALL_CHANGES:
1076         case LFUN_REJECT_ALL_CHANGES:
1077                 flag.enabled(buffer_ && buffer_->params().tracking_changes);
1078                 break;
1079         default:
1080                 flag.enabled(false);
1081         }
1082
1083         return flag;
1084 }
1085
1086
1087
1088 bool BufferView::Pimpl::dispatch(FuncRequest const & cmd)
1089 {
1090         //lyxerr << BOOST_CURRENT_FUNCTION
1091         //       << [ cmd = " << cmd << "]" << endl;
1092
1093         // Make sure that the cached BufferView is correct.
1094         lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
1095                 << " action[" << cmd.action << ']'
1096                 << " arg[" << cmd.argument << ']'
1097                 << " x[" << cmd.x << ']'
1098                 << " y[" << cmd.y << ']'
1099                 << " button[" << cmd.button() << ']'
1100                 << endl;
1101
1102         LCursor & cur = cursor_;
1103
1104         switch (cmd.action) {
1105
1106         case LFUN_UNDO:
1107                 if (available()) {
1108                         cur.message(_("Undo"));
1109                         cur.clearSelection();
1110                         if (!textUndo(*bv_))
1111                                 cur.message(_("No further undo information"));
1112                         update();
1113                         switchKeyMap();
1114                 }
1115                 break;
1116
1117         case LFUN_REDO:
1118                 if (available()) {
1119                         cur.message(_("Redo"));
1120                         cur.clearSelection();
1121                         if (!textRedo(*bv_))
1122                                 cur.message(_("No further redo information"));
1123                         update();
1124                         switchKeyMap();
1125                 }
1126                 break;
1127
1128         case LFUN_FILE_INSERT:
1129                 MenuInsertLyXFile(cmd.argument);
1130                 break;
1131
1132         case LFUN_FILE_INSERT_ASCII_PARA:
1133                 InsertAsciiFile(bv_, cmd.argument, true);
1134                 break;
1135
1136         case LFUN_FILE_INSERT_ASCII:
1137                 InsertAsciiFile(bv_, cmd.argument, false);
1138                 break;
1139
1140         case LFUN_FONT_STATE:
1141                 cur.message(cur.currentState());
1142                 break;
1143
1144         case LFUN_BOOKMARK_SAVE:
1145                 savePosition(convert<unsigned int>(cmd.argument));
1146                 break;
1147
1148         case LFUN_BOOKMARK_GOTO:
1149                 restorePosition(convert<unsigned int>(cmd.argument));
1150                 break;
1151
1152         case LFUN_LABEL_GOTO: {
1153                 string label = cmd.argument;
1154                 if (label.empty()) {
1155                         InsetRef * inset =
1156                                 getInsetByCode<InsetRef>(cursor_,
1157                                                          InsetBase::REF_CODE);
1158                         if (inset) {
1159                                 label = inset->getContents();
1160                                 savePosition(0);
1161                         }
1162                 }
1163
1164                 if (!label.empty())
1165                         bv_->gotoLabel(label);
1166                 break;
1167         }
1168
1169         case LFUN_GOTO_PARAGRAPH: {
1170                 int const id = convert<int>(cmd.argument);
1171                 ParIterator par = buffer_->getParFromID(id);
1172                 if (par == buffer_->par_iterator_end()) {
1173                         lyxerr[Debug::INFO] << "No matching paragraph found! ["
1174                                             << id << ']' << endl;
1175                         break;
1176                 } else {
1177                         lyxerr[Debug::INFO] << "Paragraph " << par->id()
1178                                             << " found." << endl;
1179                 }
1180
1181                 // Set the cursor
1182                 bv_->setCursor(makeDocIterator(par, 0));
1183
1184                 update();
1185                 switchKeyMap();
1186                 break;
1187         }
1188
1189         case LFUN_GOTOERROR:
1190                 bv_funcs::gotoInset(bv_, InsetBase::ERROR_CODE, false);
1191                 break;
1192
1193         case LFUN_GOTONOTE:
1194                 bv_funcs::gotoInset(bv_, InsetBase::NOTE_CODE, false);
1195                 break;
1196
1197         case LFUN_REFERENCE_GOTO: {
1198                 vector<InsetBase_code> tmp;
1199                 tmp.push_back(InsetBase::LABEL_CODE);
1200                 tmp.push_back(InsetBase::REF_CODE);
1201                 bv_funcs::gotoInset(bv_, tmp, true);
1202                 break;
1203         }
1204
1205         case LFUN_TRACK_CHANGES:
1206                 trackChanges();
1207                 break;
1208
1209         case LFUN_OUTPUT_CHANGES: {
1210                 bool const state = buffer_->params().output_changes;
1211                 buffer_->params().output_changes = !state;
1212                 break;
1213         }
1214
1215         case LFUN_MERGE_CHANGES:
1216                 owner_->getDialogs().show("changes");
1217                 break;
1218
1219         case LFUN_ACCEPT_ALL_CHANGES: {
1220                 cursor_.reset(buffer_->inset());
1221 #ifdef WITH_WARNINGS
1222 #warning FIXME changes
1223 #endif
1224                 while (lyx::find::findNextChange(bv_))
1225                         bv_->getLyXText()->acceptChange(cursor_);
1226                 update();
1227                 break;
1228         }
1229
1230         case LFUN_REJECT_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()->rejectChange(cursor_);
1237                 break;
1238         }
1239
1240         case LFUN_WORD_FIND:
1241                 lyx::find::find(bv_, cmd);
1242                 break;
1243
1244         case LFUN_WORD_REPLACE:
1245                 lyx::find::replace(bv_, cmd);
1246                 break;
1247
1248         case LFUN_MARK_OFF:
1249                 cur.clearSelection();
1250                 cur.resetAnchor();
1251                 cur.message(N_("Mark off"));
1252                 break;
1253
1254         case LFUN_MARK_ON:
1255                 cur.clearSelection();
1256                 cur.mark() = true;
1257                 cur.resetAnchor();
1258                 cur.message(N_("Mark on"));
1259                 break;
1260
1261         case LFUN_SETMARK:
1262                 cur.clearSelection();
1263                 if (cur.mark()) {
1264                         cur.mark() = false;
1265                         cur.message(N_("Mark removed"));
1266                 } else {
1267                         cur.mark() = true;
1268                         cur.message(N_("Mark set"));
1269                 }
1270                 cur.resetAnchor();
1271                 break;
1272
1273         case LFUN_CENTER:
1274                 center();
1275                 break;
1276
1277         case LFUN_BIBDB_ADD: {
1278                 LCursor tmpcur = cursor_;
1279                 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
1280                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1281                                                 InsetBase::BIBTEX_CODE);
1282                 if (inset)
1283                         inset->addDatabase(cmd.argument);
1284                 break;
1285         }
1286
1287         case LFUN_BIBDB_DEL: {
1288                 LCursor tmpcur = cursor_;
1289                 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
1290                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1291                                                 InsetBase::BIBTEX_CODE);
1292                 if (inset)
1293                         inset->delDatabase(cmd.argument);
1294                 break;
1295         }
1296
1297         case LFUN_WORDS_COUNT: {
1298                 DocIterator from, to;
1299                 if (cur.selection()) {
1300                         from = cur.selectionBegin();
1301                         to = cur.selectionEnd();
1302                 } else {
1303                         from = doc_iterator_begin(buffer_->inset());
1304                         to = doc_iterator_end(buffer_->inset());
1305                 }
1306                 int const count = countWords(from, to);
1307                 string message;
1308                 if (count != 1) {
1309                         if (cur.selection())
1310                                 message = bformat(_("%1$d words in selection."),
1311                                           count);
1312                                 else
1313                                         message = bformat(_("%1$d words in document."),
1314                                                           count);
1315                 }
1316                 else {
1317                         if (cur.selection())
1318                                 message = _("One word in selection.");
1319                         else
1320                                 message = _("One word in document.");
1321                 }
1322
1323                 Alert::information(_("Count words"), message);
1324         }
1325                 break;
1326         default:
1327                 return false;
1328         }
1329
1330         return true;
1331 }
1332
1333
1334 ViewMetricsInfo BufferView::Pimpl::metrics(bool singlepar)
1335 {
1336         // Remove old position cache
1337         theCoords.clear();
1338         BufferView & bv = *bv_;
1339         LyXText * const text = bv.text();
1340         if (anchor_ref_ > int(text->paragraphs().size() - 1)) {
1341                 anchor_ref_ = int(text->paragraphs().size() - 1);
1342                 offset_ref_ = 0;
1343         }
1344
1345         lyx::pit_type const pit = anchor_ref_;
1346         int pit1 = pit;
1347         int pit2 = pit;
1348         size_t const npit = text->paragraphs().size();
1349
1350         // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
1351         // the (main text, not inset!) paragraph containing the cursor.
1352         // (if this paragraph contains insets etc., rebreaking will 
1353         // recursively descend)
1354         if (!singlepar || pit == cursor_.bottom().pit())
1355                 text->redoParagraph(pit);
1356         int y0 = text->getPar(pit).ascent() - offset_ref_;
1357
1358         // Redo paragraphs above anchor if necessary; again, in Single Par
1359         // mode, only if we encounter the (main text) one having the cursor.
1360         int y1 = y0;
1361         while (y1 > 0 && pit1 > 0) {
1362                 y1 -= text->getPar(pit1).ascent();
1363                 --pit1;
1364                 if (!singlepar || pit1 == cursor_.bottom().pit())
1365                         text->redoParagraph(pit1);
1366                 y1 -= text->getPar(pit1).descent();
1367         }
1368
1369
1370         // Take care of ascent of first line
1371         y1 -= text->getPar(pit1).ascent();
1372
1373         // Normalize anchor for next time
1374         anchor_ref_ = pit1;
1375         offset_ref_ = -y1;
1376
1377         // Grey at the beginning is ugly
1378         if (pit1 == 0 && y1 > 0) {
1379                 y0 -= y1;
1380                 y1 = 0;
1381                 anchor_ref_ = 0;
1382         }
1383
1384         // Redo paragraphs below the anchor if necessary. Single par mode:
1385         // only the one containing the cursor if encountered.
1386         int y2 = y0;
1387         while (y2 < bv.workHeight() && pit2 < int(npit) - 1) {
1388                 y2 += text->getPar(pit2).descent();
1389                 ++pit2;
1390                 if (!singlepar || pit2 == cursor_.bottom().pit())
1391                         text->redoParagraph(pit2);
1392                 y2 += text->getPar(pit2).ascent();
1393         }
1394
1395         // Take care of descent of last line
1396         y2 += text->getPar(pit2).descent();
1397
1398         // The coordinates of all these paragraphs are correct, cache them
1399         int y = y1;
1400         for (lyx::pit_type pit = pit1; pit <= pit2; ++pit) {
1401                 y += text->getPar(pit).ascent();
1402                 theCoords.parPos()[text][pit] = Point(0, y);
1403                 if (singlepar && pit == cursor_.bottom().pit()) {
1404                         // In Single Paragraph mode, collect here the 
1405                         // y1 and y2 of the (one) paragraph the cursor is in
1406                         y1 = y - text->getPar(pit).ascent();
1407                         y2 = y + text->getPar(pit).descent();
1408                 }
1409                 y += text->getPar(pit).descent();
1410         }
1411
1412         if (singlepar) {
1413                 // collect cursor paragraph iter bounds
1414                 pit1 = cursor_.bottom().pit();
1415                 pit2 = cursor_.bottom().pit();
1416         }
1417         
1418         lyxerr[Debug::DEBUG]
1419                 << BOOST_CURRENT_FUNCTION
1420                 << " y1: " << y1
1421                 << " y2: " << y2
1422                 << " pit1: " << pit1
1423                 << " pit2: " << pit2
1424                 << " npit: " << npit
1425                 << " singlepar: " << singlepar
1426                 << endl;
1427
1428         return ViewMetricsInfo(pit1, pit2, y1, y2, singlepar);
1429 }