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