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