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