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