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