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