]> git.lyx.org Git - lyx.git/blob - src/BufferView_pimpl.C
fix crash after removing a table row (again due to uncorrected cursor
[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 "paragraph.h"
45 #include "paragraph_funcs.h"
46 #include "ParagraphParameters.h"
47 #include "pariterator.h"
48 #include "rowpainter.h"
49 #include "undo.h"
50 #include "vspace.h"
51
52 #include "insets/insetref.h"
53 #include "insets/insettext.h"
54
55 #include "frontends/Alert.h"
56 #include "frontends/Dialogs.h"
57 #include "frontends/FileDialog.h"
58 #include "frontends/LyXView.h"
59 #include "frontends/LyXScreenFactory.h"
60 #include "frontends/screen.h"
61 #include "frontends/WorkArea.h"
62 #include "frontends/WorkAreaFactory.h"
63
64 #include "graphics/Previews.h"
65
66 #include "support/filetools.h"
67 #include "support/forkedcontr.h"
68 #include "support/globbing.h"
69 #include "support/path_defines.h"
70 #include "support/tostr.h"
71 #include "support/types.h"
72
73 #include <boost/bind.hpp>
74
75 using lyx::pos_type;
76
77 using lyx::support::AddPath;
78 using lyx::support::bformat;
79 using lyx::support::FileFilterList;
80 using lyx::support::FileSearch;
81 using lyx::support::ForkedcallsController;
82 using lyx::support::IsDirWriteable;
83 using lyx::support::MakeDisplayPath;
84 using lyx::support::MakeAbsPath;
85 using lyx::support::strToUnsignedInt;
86 using lyx::support::system_lyxdir;
87
88 using std::endl;
89 using std::istringstream;
90 using std::make_pair;
91 using std::min;
92 using std::string;
93
94
95 extern BufferList bufferlist;
96
97
98 namespace {
99
100 unsigned int const saved_positions_num = 20;
101
102 // All the below connection objects are needed because of a bug in some
103 // versions of GCC (<=2.96 are on the suspects list.) By having and assigning
104 // to these connections we avoid a segfault upon startup, and also at exit.
105 // (Lgb)
106
107 boost::signals::connection dispatchcon;
108 boost::signals::connection timecon;
109 boost::signals::connection doccon;
110 boost::signals::connection resizecon;
111 boost::signals::connection kpresscon;
112 boost::signals::connection selectioncon;
113 boost::signals::connection lostcon;
114
115
116 /// Get next inset of this class from current cursor position
117 template <class T>
118 T * getInsetByCode(LCursor & cur, InsetBase::Code code)
119 {
120         T * inset = 0;
121         DocIterator it = cur;
122         if (it.nextInset() &&
123             it.nextInset()->lyxCode() == code) {
124                 inset = static_cast<T*>(it.nextInset());
125         }
126         return inset;
127 }
128
129
130 } // anon namespace
131
132
133 BufferView::Pimpl::Pimpl(BufferView & bv, LyXView * owner,
134                          int width, int height)
135         : bv_(&bv), owner_(owner), buffer_(0), cursor_timeout(400),
136           using_xterm_cursor(false), cursor_(bv)
137 {
138         xsel_cache_.set = false;
139
140         workarea_.reset(WorkAreaFactory::create(*owner_, width, height));
141         screen_.reset(LyXScreenFactory::create(workarea()));
142
143         // Setup the signals
144         doccon = workarea().scrollDocView
145                 .connect(boost::bind(&BufferView::Pimpl::scrollDocView, this, _1));
146         resizecon = workarea().workAreaResize
147                 .connect(boost::bind(&BufferView::Pimpl::workAreaResize, this));
148         dispatchcon = workarea().dispatch
149                 .connect(boost::bind(&BufferView::Pimpl::workAreaDispatch, this, _1));
150         kpresscon = workarea().workAreaKeyPress
151                 .connect(boost::bind(&BufferView::Pimpl::workAreaKeyPress, this, _1, _2));
152         selectioncon = workarea().selectionRequested
153                 .connect(boost::bind(&BufferView::Pimpl::selectionRequested, this));
154         lostcon = workarea().selectionLost
155                 .connect(boost::bind(&BufferView::Pimpl::selectionLost, this));
156
157         timecon = cursor_timeout.timeout
158                 .connect(boost::bind(&BufferView::Pimpl::cursorToggle, this));
159         cursor_timeout.start();
160         saved_positions.resize(saved_positions_num);
161 }
162
163
164 void BufferView::Pimpl::addError(ErrorItem const & ei)
165 {
166         errorlist_.push_back(ei);
167 }
168
169
170 void BufferView::Pimpl::showReadonly(bool)
171 {
172         owner_->updateWindowTitle();
173         owner_->getDialogs().updateBufferDependent(false);
174 }
175
176
177 void BufferView::Pimpl::connectBuffer(Buffer & buf)
178 {
179         if (errorConnection_.connected())
180                 disconnectBuffer();
181
182         errorConnection_ =
183                 buf.error.connect(
184                         boost::bind(&BufferView::Pimpl::addError, this, _1));
185
186         messageConnection_ =
187                 buf.message.connect(
188                         boost::bind(&LyXView::message, owner_, _1));
189
190         busyConnection_ =
191                 buf.busy.connect(
192                         boost::bind(&LyXView::busy, owner_, _1));
193
194         titleConnection_ =
195                 buf.updateTitles.connect(
196                         boost::bind(&LyXView::updateWindowTitle, owner_));
197
198         timerConnection_ =
199                 buf.resetAutosaveTimers.connect(
200                         boost::bind(&LyXView::resetAutosaveTimer, owner_));
201
202         readonlyConnection_ =
203                 buf.readonly.connect(
204                         boost::bind(&BufferView::Pimpl::showReadonly, this, _1));
205
206         closingConnection_ =
207                 buf.closing.connect(
208                         boost::bind(&BufferView::Pimpl::setBuffer, this, (Buffer *)0));
209 }
210
211
212 void BufferView::Pimpl::disconnectBuffer()
213 {
214         errorConnection_.disconnect();
215         messageConnection_.disconnect();
216         busyConnection_.disconnect();
217         titleConnection_.disconnect();
218         timerConnection_.disconnect();
219         readonlyConnection_.disconnect();
220         closingConnection_.disconnect();
221 }
222
223
224 void BufferView::Pimpl::newFile(string const & filename, string const & tname,
225         bool isNamed)
226 {
227         setBuffer(::newFile(filename, tname, isNamed));
228 }
229
230
231 bool BufferView::Pimpl::loadLyXFile(string const & filename, bool tolastfiles)
232 {
233         // get absolute path of file and add ".lyx" to the filename if
234         // necessary
235         string s = FileSearch(string(), filename, "lyx");
236
237         bool const found = !s.empty();
238
239         if (!found)
240                 s = filename;
241
242         // file already open?
243         if (bufferlist.exists(s)) {
244                 string const file = MakeDisplayPath(s, 20);
245                 string text = bformat(_("The document %1$s is already "
246                                         "loaded.\n\nDo you want to revert "
247                                         "to the saved version?"), file);
248                 int const ret = Alert::prompt(_("Revert to saved document?"),
249                         text, 0, 1,  _("&Revert"), _("&Switch to document"));
250
251                 if (ret != 0) {
252                         setBuffer(bufferlist.getBuffer(s));
253                         return true;
254                 }
255                 // FIXME: should be LFUN_REVERT
256                 if (!bufferlist.close(bufferlist.getBuffer(s), false))
257                         return false;
258                 // Fall through to new load. (Asger)
259         }
260
261         Buffer * b;
262
263         if (found) {
264                 b = bufferlist.newBuffer(s);
265                 connectBuffer(*b);
266                 if (!::loadLyXFile(b, s)) {
267                         bufferlist.release(b);
268                         return false;
269                 }
270         } else {
271                 string text = bformat(_("The document %1$s does not yet "
272                                         "exist.\n\nDo you want to create "
273                                         "a new document?"), s);
274                 int const ret = Alert::prompt(_("Create new document?"),
275                          text, 0, 1, _("&Create"), _("Cancel"));
276
277                 if (ret == 0)
278                         b = ::newFile(s, string(), true);
279                 else
280                         return false;
281         }
282
283         setBuffer(b);
284         bv_->showErrorList(_("Parse"));
285
286         if (tolastfiles)
287                 LyX::ref().lastfiles().newFile(b->fileName());
288
289         return true;
290 }
291
292
293 WorkArea & BufferView::Pimpl::workarea() const
294 {
295         return *workarea_.get();
296 }
297
298
299 LyXScreen & BufferView::Pimpl::screen() const
300 {
301         return *screen_.get();
302 }
303
304
305 Painter & BufferView::Pimpl::painter() const
306 {
307         return workarea().getPainter();
308 }
309
310
311 void BufferView::Pimpl::top_y(int y)
312 {
313         top_y_ = y;
314 }
315
316
317 int BufferView::Pimpl::top_y() const
318 {
319         return top_y_;
320 }
321
322
323 void BufferView::Pimpl::setBuffer(Buffer * b)
324 {
325         lyxerr[Debug::INFO] << "Setting buffer in BufferView ("
326                             << b << ')' << endl;
327         if (buffer_)
328                 disconnectBuffer();
329
330         // if we are closing current buffer, switch to the first in
331         // buffer list.
332         if (!b) {
333                 lyxerr[Debug::INFO] << "  No Buffer!" << endl;
334                 // we are closing the buffer, use the first buffer as current
335                 buffer_ = bufferlist.first();
336                 owner_->getDialogs().hideBufferDependent();
337         } else {
338                 // set current buffer
339                 buffer_ = b;
340         }
341
342         // reset old cursor
343         top_y_ = 0;
344         cursor_ = LCursor(*bv_);
345
346         // if we're quitting lyx, don't bother updating stuff
347         if (quitting)
348                 return;
349
350         if (buffer_) {
351                 lyxerr[Debug::INFO] << "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                 // If we don't have a text object for this, we make one
360                 //if (bv_->text() == 0)
361                 //      resizeCurrentBuffer();
362
363                 // Buffer-dependent dialogs should be updated or
364                 // hidden. This should go here because some dialogs (eg ToC)
365                 // require bv_->text.
366                 owner_->getDialogs().updateBufferDependent(true);
367         } 
368
369         update();
370         updateScrollbar();
371         owner_->updateMenubar();
372         owner_->updateToolbars();
373         owner_->updateLayoutChoice();
374         owner_->updateWindowTitle();
375
376         // This is done after the layout combox has been populated
377         if (buffer_)
378                 owner_->setLayout(cursor_.paragraph().layout()->name());
379
380         if (buffer_ && lyx::graphics::Previews::status() != LyXRC::PREVIEW_OFF)
381                 lyx::graphics::Previews::get().generateBufferPreviews(*buffer_);
382 }
383
384
385 bool BufferView::Pimpl::fitCursor()
386 {
387         // to get the correct y cursor info
388         lyxerr[Debug::DEBUG] << "BufferView::fitCursor" << std::endl;
389         lyx::par_type const pit = bv_->cursor().bottom().par();
390         bv_->text()->redoParagraph(pit);
391         refreshPar(*bv_, *bv_->text(), pit);
392
393         if (!screen().fitCursor(bv_))
394                 return false;
395         updateScrollbar();
396         return true;
397 }
398
399
400 void BufferView::Pimpl::redoCurrentBuffer()
401 {
402         lyxerr[Debug::DEBUG] << "BufferView::redoCurrentBuffer" << endl;
403         if (buffer_ && bv_->text()) {
404                 resizeCurrentBuffer();
405                 updateScrollbar();
406                 owner_->updateLayoutChoice();
407         }
408 }
409
410
411 void BufferView::Pimpl::resizeCurrentBuffer()
412 {
413         lyxerr[Debug::DEBUG] << "resizeCurrentBuffer" << endl;
414         owner_->busy(true);
415         owner_->message(_("Formatting document..."));
416
417         LyXText * text = bv_->text();
418         if (!text)
419                 return;
420
421         text->init(bv_);
422         update();
423         fitCursor();
424
425         switchKeyMap();
426         owner_->busy(false);
427
428         // reset the "Formatting..." message
429         owner_->clearMessage();
430
431         updateScrollbar();
432 }
433
434
435 void BufferView::Pimpl::updateScrollbar()
436 {
437         if (!bv_->text()) {
438                 lyxerr[Debug::DEBUG] << "no text in updateScrollbar" << endl;
439                 workarea().setScrollbarParams(0, 0, 0);
440                 return;
441         }
442
443         LyXText const & t = *bv_->text();
444
445         lyxerr[Debug::GUI]
446                 << "Updating scrollbar: height: " << t.height()
447                 << " top_y: " << top_y()
448                 << " default height " << defaultRowHeight() << endl;
449
450         workarea().setScrollbarParams(t.height(), top_y(), defaultRowHeight());
451 }
452
453
454 void BufferView::Pimpl::scrollDocView(int value)
455 {
456         lyxerr[Debug::GUI] << "scrollDocView of " << value << endl;
457
458         if (!buffer_)
459                 return;
460
461         screen().hideCursor();
462
463         top_y(value);
464         screen().redraw(*bv_);
465
466         if (!lyxrc.cursor_follows_scrollbar)
467                 return;
468
469         int const height = defaultRowHeight();
470         int const first = top_y() + height;
471         int const last = top_y() + workarea().workHeight() - height;
472
473         bv_->cursor().reset(bv_->buffer()->inset());
474         LyXText * text = bv_->text();
475         int y = text->cursorY(bv_->cursor().front());
476         if (y < first)
477                 y = first;
478         if (y > last)
479                 y = last;
480         text->setCursorFromCoordinates(bv_->cursor(), 0, y);
481
482         owner_->updateLayoutChoice();
483 }
484
485
486 void BufferView::Pimpl::scroll(int lines)
487 {
488         if (!buffer_)
489                 return;
490
491         LyXText const * t = bv_->text();
492         int const line_height = defaultRowHeight();
493
494         // The new absolute coordinate
495         int new_top_y = top_y() + lines * line_height;
496
497         // Restrict to a valid value
498         new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
499         new_top_y = std::max(0, new_top_y);
500
501         scrollDocView(new_top_y);
502
503         // Update the scrollbar.
504         workarea().setScrollbarParams(t->height(), top_y(), defaultRowHeight());
505 }
506
507
508 void BufferView::Pimpl::workAreaKeyPress(LyXKeySymPtr key,
509                                          key_modifier::state state)
510 {
511         bv_->owner()->getLyXFunc().processKeySym(key, state);
512
513         /* This is perhaps a bit of a hack. When we move
514          * around, or type, it's nice to be able to see
515          * the cursor immediately after the keypress. So
516          * we reset the toggle timeout and force the visibility
517          * of the cursor. Note we cannot do this inside
518          * dispatch() itself, because that's called recursively.
519          */
520         if (available()) {
521                 cursor_timeout.restart();
522                 screen().showCursor(*bv_);
523         }
524 }
525
526
527 void BufferView::Pimpl::selectionRequested()
528 {
529         static string sel;
530
531         if (!available())
532                 return;
533
534         LCursor & cur = bv_->cursor();
535
536         if (!cur.selection()) {
537                 xsel_cache_.set = false;
538                 return;
539         }
540
541         if (!xsel_cache_.set ||
542             cur.back() != xsel_cache_.cursor ||
543             cur.anchor_.back() != xsel_cache_.anchor)
544         {
545                 xsel_cache_.cursor = cur.back();
546                 xsel_cache_.anchor = cur.anchor_.back();
547                 xsel_cache_.set = cur.selection();
548                 sel = cur.selectionAsString(false);
549                 if (!sel.empty())
550                         workarea().putClipboard(sel);
551         }
552 }
553
554
555 void BufferView::Pimpl::selectionLost()
556 {
557         if (available()) {
558                 screen().hideCursor();
559                 bv_->cursor().clearSelection();
560                 xsel_cache_.set = false;
561         }
562 }
563
564
565 void BufferView::Pimpl::workAreaResize()
566 {
567         static int work_area_width;
568         static int work_area_height;
569
570         bool const widthChange = workarea().workWidth() != work_area_width;
571         bool const heightChange = workarea().workHeight() != work_area_height;
572
573         // update from work area
574         work_area_width = workarea().workWidth();
575         work_area_height = workarea().workHeight();
576
577         if (buffer_ && widthChange) {
578                 // The visible LyXView need a resize
579                 resizeCurrentBuffer();
580         }
581
582         if (widthChange || heightChange)
583                 update();
584
585         // always make sure that the scrollbar is sane.
586         updateScrollbar();
587         owner_->updateLayoutChoice();
588 }
589
590
591 void BufferView::Pimpl::update()
592 {
593         //lyxerr << "BufferView::Pimpl::update(), buffer: " << buffer_ << endl;
594         // fix cursor coordinate cache in case something went wrong
595
596         // check needed to survive LyX startup
597         if (buffer_) {
598                 // update macro store
599                 buffer_->buildMacros();
600
601                 // update all 'visible' paragraphs
602                 lyx::par_type beg, end;
603                 getParsInRange(buffer_->paragraphs(),
604                                top_y(), top_y() + workarea().workHeight(),
605                                beg, end);
606                 bv_->text()->redoParagraphs(beg, end);
607
608                 // and the scrollbar
609                 updateScrollbar();
610         }
611
612         // remove old position cache
613         theCoords.clear();
614
615         // The real, big redraw.
616         screen().redraw(*bv_);
617
618         bv_->owner()->view_state_changed();
619 }
620
621
622 // Callback for cursor timer
623 void BufferView::Pimpl::cursorToggle()
624 {
625         if (buffer_) {
626                 screen().toggleCursor(*bv_);
627
628                 // Use this opportunity to deal with any child processes that
629                 // have finished but are waiting to communicate this fact
630                 // to the rest of LyX.
631                 ForkedcallsController & fcc = ForkedcallsController::get();
632                 if (fcc.processesCompleted())
633                         fcc.handleCompletedProcesses();
634         }
635
636         cursor_timeout.restart();
637 }
638
639
640 bool BufferView::Pimpl::available() const
641 {
642         return buffer_ && bv_->text();
643 }
644
645
646 Change const BufferView::Pimpl::getCurrentChange()
647 {
648         if (!bv_->buffer()->params().tracking_changes)
649                 return Change(Change::UNCHANGED);
650
651         LyXText * text = bv_->getLyXText();
652         LCursor & cur = bv_->cursor();
653
654         if (!cur.selection())
655                 return Change(Change::UNCHANGED);
656
657         return text->getPar(cur.selBegin().par()).
658                         lookupChangeFull(cur.selBegin().pos());
659 }
660
661
662 void BufferView::Pimpl::savePosition(unsigned int i)
663 {
664         if (i >= saved_positions_num)
665                 return;
666         BOOST_ASSERT(bv_->cursor().inTexted());
667         saved_positions[i] = Position(buffer_->fileName(),
668                                       bv_->cursor().paragraph().id(),
669                                       bv_->cursor().pos());
670         if (i > 0)
671                 owner_->message(bformat(_("Saved bookmark %1$s"), tostr(i)));
672 }
673
674
675 void BufferView::Pimpl::restorePosition(unsigned int i)
676 {
677         if (i >= saved_positions_num)
678                 return;
679
680         string const fname = saved_positions[i].filename;
681
682         bv_->cursor().clearSelection();
683
684         if (fname != buffer_->fileName()) {
685                 Buffer * b = 0;
686                 if (bufferlist.exists(fname))
687                         b = bufferlist.getBuffer(fname);
688                 else {
689                         b = bufferlist.newBuffer(fname);
690                         ::loadLyXFile(b, fname); // don't ask, just load it
691                 }
692                 if (b)
693                         setBuffer(b);
694         }
695
696         ParIterator par = buffer_->getParFromID(saved_positions[i].par_id);
697         if (par == buffer_->par_iterator_end())
698                 return;
699
700         bv_->text()->setCursor(bv_->cursor(), par.pit(),
701                 min(par->size(), saved_positions[i].par_pos));
702
703         if (i > 0)
704                 owner_->message(bformat(_("Moved to bookmark %1$s"), tostr(i)));
705 }
706
707
708 bool BufferView::Pimpl::isSavedPosition(unsigned int i)
709 {
710         return i < saved_positions_num && !saved_positions[i].filename.empty();
711 }
712
713
714 void BufferView::Pimpl::switchKeyMap()
715 {
716         if (!lyxrc.rtl_support)
717                 return;
718
719         Intl & intl = owner_->getIntl();
720         if (bv_->getLyXText()->real_current_font.isRightToLeft()) {
721                 if (intl.keymap == Intl::PRIMARY)
722                         intl.KeyMapSec();
723         } else {
724                 if (intl.keymap == Intl::SECONDARY)
725                         intl.KeyMapPrim();
726         }
727 }
728
729
730 void BufferView::Pimpl::center()
731 {
732         LyXText * text = bv_->text();
733
734         bv_->cursor().clearSelection();
735         int const half_height = workarea().workHeight() / 2;
736         int new_y = text->cursorY(bv_->cursor().front()) - half_height;
737         if (new_y < 0)
738                 new_y = 0;
739
740         // FIXME: look at this comment again ...
741         // This updates top_y() but means the fitCursor() call
742         // from the update(FITCUR) doesn't realise that we might
743         // have moved (e.g. from GOTOPARAGRAPH), so doesn't cause
744         // the scrollbar to be updated as it should, so we have
745         // to do it manually. Any operation that does a center()
746         // and also might have moved top_y() must make sure to call
747         // updateScrollbar() currently. Never mind that this is a
748         // pretty obfuscated way of updating text->top_y()
749         top_y(new_y);
750 }
751
752
753 void BufferView::Pimpl::stuffClipboard(string const & stuff) const
754 {
755         workarea().putClipboard(stuff);
756 }
757
758
759 void BufferView::Pimpl::MenuInsertLyXFile(string const & filenm)
760 {
761         string filename = filenm;
762
763         if (filename.empty()) {
764                 // Launch a file browser
765                 string initpath = lyxrc.document_path;
766
767                 if (available()) {
768                         string const trypath = owner_->buffer()->filePath();
769                         // If directory is writeable, use this as default.
770                         if (IsDirWriteable(trypath))
771                                 initpath = trypath;
772                 }
773
774                 FileDialog fileDlg(_("Select LyX document to insert"),
775                         LFUN_FILE_INSERT,
776                         make_pair(string(_("Documents|#o#O")),
777                                   string(lyxrc.document_path)),
778                         make_pair(string(_("Examples|#E#e")),
779                                   string(AddPath(system_lyxdir(), "examples"))));
780
781                 FileDialog::Result result =
782                         fileDlg.open(initpath,
783                                      FileFilterList(_("LyX Documents (*.lyx)")),
784                                      string());
785
786                 if (result.first == FileDialog::Later)
787                         return;
788
789                 filename = result.second;
790
791                 // check selected filename
792                 if (filename.empty()) {
793                         owner_->message(_("Canceled."));
794                         return;
795                 }
796         }
797
798         // get absolute path of file and add ".lyx" to the filename if
799         // necessary
800         filename = FileSearch(string(), filename, "lyx");
801
802         string const disp_fn = MakeDisplayPath(filename);
803         owner_->message(bformat(_("Inserting document %1$s..."), disp_fn));
804
805         bv_->cursor().clearSelection();
806         bv_->text()->breakParagraph(bv_->cursor());
807
808         BOOST_ASSERT(bv_->cursor().inTexted());
809
810         string const fname = MakeAbsPath(filename);
811         bool const res = bv_->buffer()->readFile(fname, bv_->cursor().par());
812         bv_->resize();
813
814         string s = res ? _("Document %1$s inserted.")
815                        : _("Could not insert document %1$s");
816         owner_->message(bformat(s, disp_fn));
817 }
818
819
820 void BufferView::Pimpl::trackChanges()
821 {
822         Buffer * buf = bv_->buffer();
823         bool const tracking = buf->params().tracking_changes;
824
825         if (!tracking) {
826                 ParIterator const end = buf->par_iterator_end();
827                 for (ParIterator it = buf->par_iterator_begin(); it != end; ++it)
828                         it->trackChanges();
829                 buf->params().tracking_changes = true;
830
831                 // we cannot allow undos beyond the freeze point
832                 buf->undostack().clear();
833         } else {
834                 update();
835                 bv_->text()->setCursor(bv_->cursor(), 0, 0);
836 #ifdef WITH_WARNINGS
837 #warning changes FIXME
838 #endif
839                 bool found = lyx::find::findNextChange(bv_);
840                 if (found) {
841                         owner_->getDialogs().show("changes");
842                         return;
843                 }
844
845                 ParIterator const end = buf->par_iterator_end();
846                 for (ParIterator it = buf->par_iterator_begin(); it != end; ++it)
847                         it->untrackChanges();
848                 buf->params().tracking_changes = false;
849         }
850
851         buf->redostack().clear();
852 }
853
854
855 bool BufferView::Pimpl::workAreaDispatch(FuncRequest const & cmd0)
856 {
857         lyxerr << "BufferView::Pimpl::workAreaDispatch: request: "
858           << cmd0 << std::endl;
859         // this is only called for mouse related events including
860         // LFUN_FILE_OPEN generated by drag-and-drop.
861         FuncRequest cmd = cmd0;
862
863         // handle drag&drop
864         if (cmd.action == LFUN_FILE_OPEN) {
865                 owner_->dispatch(cmd);
866                 return true;
867         }
868
869         cmd.y += bv_->top_y();
870         if (!bv_->buffer())
871                 return false;
872
873         LCursor cur(*bv_);
874         cur.push(bv_->buffer()->inset());
875         cur.selection() = bv_->cursor().selection();
876
877         // Doesn't go through lyxfunc, so we need to update
878         // the layout choice etc. ourselves
879
880         // e.g. Qt mouse press when no buffer
881         if (!available())
882                 return false;
883
884         screen().hideCursor();
885
886         // Either the inset under the cursor or the
887         // surrounding LyXText will handle this event.
888
889         // Build temporary cursor.
890         InsetBase * inset = bv_->text()->editXY(cur, cmd.x, cmd.y);
891         lyxerr << " * created temp cursor: " << inset << endl;
892         lyxerr << " * hit inset at tip: " << inset << endl;
893         lyxerr << " * created temp cursor:" << cur << endl;
894
895         // Put anchor at the same position.
896         cur.resetAnchor();
897
898         // Try to dispatch to an non-editable inset near this position
899         // via the temp cursor. If the inset wishes to change the real
900         // cursor it has to do so explicitly by using
901         //  cur.bv().cursor() = cur;  (or similar)
902         if (inset)
903                 inset->dispatch(cur, cmd);
904
905         // Now dispatch to the temporary cursor. If the real cursor should
906         // be modified, the inset's dispatch has to do so explicitly.
907         if (!cur.result().dispatched())
908                 cur.dispatch(cmd);
909
910         if (cur.result().dispatched()) {
911                 // Redraw if requested or necessary.
912                 if (fitCursor() || cur.result().update())
913                         update();
914         }
915
916         // see workAreaKeyPress
917         cursor_timeout.restart();
918         screen().showCursor(*bv_);
919
920         // skip these when selecting
921         if (cmd.action != LFUN_MOUSE_MOTION) {
922                 owner_->updateLayoutChoice();
923                 owner_->updateToolbars();
924         }
925
926         // slight hack: this is only called currently when we
927         // clicked somewhere, so we force through the display
928         // of the new status here.
929         owner_->clearMessage();
930         return true;
931 }
932
933
934 FuncStatus BufferView::Pimpl::getStatus(FuncRequest const & cmd)
935 {
936         Buffer * buf = bv_->buffer();
937
938         FuncStatus flag;
939
940         switch (cmd.action) {
941
942         case LFUN_UNDO:
943                 flag.enabled(!buf->undostack().empty());
944                 break;
945         case LFUN_REDO:
946                 flag.enabled(!buf->redostack().empty());
947                 break;
948         case LFUN_FILE_INSERT:
949         case LFUN_FILE_INSERT_ASCII_PARA:
950         case LFUN_FILE_INSERT_ASCII:
951         case LFUN_FONT_STATE:
952         case LFUN_INSERT_LABEL:
953         case LFUN_BOOKMARK_SAVE:
954         case LFUN_REF_GOTO:
955         case LFUN_WORD_FIND:
956         case LFUN_WORD_REPLACE:
957         case LFUN_MARK_OFF:
958         case LFUN_MARK_ON:
959         case LFUN_SETMARK:
960         case LFUN_CENTER:
961         case LFUN_BEGINNINGBUF:
962         case LFUN_ENDBUF:
963         case LFUN_BEGINNINGBUFSEL:
964         case LFUN_ENDBUFSEL:
965                 flag.enabled(true);
966                 break;
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_BEGINNINGBUFSEL:
1137                 bv_->cursor().reset(bv_->buffer()->inset());
1138                 if (!cur.selection())
1139                         cur.resetAnchor();
1140                 bv_->text()->cursorTop(cur);
1141                 finishUndo();
1142                 break;
1143
1144         case LFUN_ENDBUFSEL:
1145                 bv_->cursor().reset(bv_->buffer()->inset());
1146                 if (!cur.selection())
1147                         cur.resetAnchor();
1148                 bv_->text()->cursorBottom(cur);
1149                 finishUndo();
1150                 break;
1151
1152         default:
1153                 return false;
1154         }
1155
1156         return true;
1157 }