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