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