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