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