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