]> git.lyx.org Git - lyx.git/blob - src/BufferView_pimpl.C
76206336463998a3850529294b69810a25c9225d
[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 Braustein
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 "mathed/formulabase.h"
63
64 #include "support/filetools.h"
65 #include "support/path_defines.h"
66 #include "support/tostr.h"
67
68 #include <boost/bind.hpp>
69
70 using bv_funcs::currentState;
71
72 using lyx::pos_type;
73
74 using lyx::support::AddPath;
75 using lyx::support::bformat;
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         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_ = buf.error.connect(boost::bind(&BufferView::Pimpl::addError, this, _1));
160         messageConnection_ = buf.message.connect(boost::bind(&LyXView::message, owner_, _1));
161         busyConnection_ = buf.busy.connect(boost::bind(&LyXView::busy, owner_, _1));
162         titleConnection_ = buf.updateTitles.connect(boost::bind(&LyXView::updateWindowTitle, owner_));
163         timerConnection_ = buf.resetAutosaveTimers.connect(boost::bind(&LyXView::resetAutosaveTimer, owner_));
164         readonlyConnection_ = buf.readonly.connect(boost::bind(&BufferView::Pimpl::showReadonly, this, _1));
165         closingConnection_ = buf.closing.connect(boost::bind(&BufferView::Pimpl::buffer, this, (Buffer *)0));
166 }
167
168
169 void BufferView::Pimpl::disconnectBuffer()
170 {
171         errorConnection_.disconnect();
172         messageConnection_.disconnect();
173         busyConnection_.disconnect();
174         titleConnection_.disconnect();
175         timerConnection_.disconnect();
176         readonlyConnection_.disconnect();
177         closingConnection_.disconnect();
178 }
179
180
181 bool BufferView::Pimpl::newFile(string const & filename,
182                                 string const & tname,
183                                 bool isNamed)
184 {
185         Buffer * b = ::newFile(filename, tname, isNamed);
186         buffer(b);
187         return true;
188 }
189
190
191 bool BufferView::Pimpl::loadLyXFile(string const & filename, bool tolastfiles)
192 {
193         // get absolute path of file and add ".lyx" to the filename if
194         // necessary
195         string s = FileSearch(string(), filename, "lyx");
196
197         bool const found = !s.empty();
198
199         if (!found)
200                 s = filename;
201
202         // file already open?
203         if (bufferlist.exists(s)) {
204                 string const file = MakeDisplayPath(s, 20);
205                 string text = bformat(_("The document %1$s is already "
206                                         "loaded.\n\nDo you want to revert "
207                                         "to the saved version?"), file);
208                 int const ret = Alert::prompt(_("Revert to saved document?"),
209                         text, 0, 1,  _("&Revert"), _("&Switch to document"));
210
211                 if (ret != 0) {
212                         buffer(bufferlist.getBuffer(s));
213                         return true;
214                 } else {
215                         // FIXME: should be LFUN_REVERT
216                         if (!bufferlist.close(bufferlist.getBuffer(s), false))
217                                 return false;
218                         // Fall through to new load. (Asger)
219                 }
220         }
221
222         Buffer * b;
223
224         if (found) {
225                 b = bufferlist.newBuffer(s);
226                 connectBuffer(*b);
227                 if (!::loadLyXFile(b, s)) {
228                         bufferlist.release(b);
229                         return false;
230                 }
231         } else {
232                 string text = bformat(_("The document %1$s does not yet "
233                                         "exist.\n\nDo you want to create "
234                                         "a new document?"), s);
235                 int const ret = Alert::prompt(_("Create new document?"),
236                          text, 0, 1, _("&Create"), _("Cancel"));
237
238                 if (ret == 0)
239                         b = ::newFile(s, string(), true);
240                 else
241                         return false;
242         }
243
244         buffer(b);
245         bv_->showErrorList(_("Parse"));
246
247         if (tolastfiles)
248                 LyX::ref().lastfiles().newFile(b->fileName());
249
250         return true;
251 }
252
253
254 WorkArea & BufferView::Pimpl::workarea() const
255 {
256         return *workarea_.get();
257 }
258
259
260 LyXScreen & BufferView::Pimpl::screen() const
261 {
262         return *screen_.get();
263 }
264
265
266 Painter & BufferView::Pimpl::painter() const
267 {
268         return workarea().getPainter();
269 }
270
271
272 void BufferView::Pimpl::top_y(int y)
273 {
274         top_y_ = y;
275 }
276
277
278 int BufferView::Pimpl::top_y() const
279 {
280         return top_y_;
281 }
282
283
284 void BufferView::Pimpl::buffer(Buffer * b)
285 {
286         lyxerr[Debug::INFO] << "Setting buffer in BufferView ("
287                             << b << ')' << endl;
288         if (buffer_) {
289                 disconnectBuffer();
290                 delete bv_->text;
291                 bv_->text = 0;
292         }
293
294         // set current buffer
295         buffer_ = b;
296
297         top_y_ = 0;
298
299         // if we're quitting lyx, don't bother updating stuff
300         if (quitting)
301                 return;
302
303         // if we are closing the buffer, use the first buffer as current
304         if (!buffer_)
305                 buffer_ = bufferlist.first();
306
307         if (buffer_) {
308                 lyxerr[Debug::INFO] << "Buffer addr: " << buffer_ << endl;
309                 connectBuffer(*buffer_);
310
311                 // If we don't have a text object for this, we make one
312                 if (bv_->text == 0)
313                         resizeCurrentBuffer();
314
315                 // FIXME: needed when ?
316                 fitCursor();
317
318                 // Buffer-dependent dialogs should be updated or
319                 // hidden. This should go here because some dialogs (eg ToC)
320                 // require bv_->text.
321                 owner_->getDialogs().updateBufferDependent(true);
322         } else {
323                 lyxerr[Debug::INFO] << "  No Buffer!" << endl;
324                 owner_->getDialogs().hideBufferDependent();
325         }
326
327         update();
328         updateScrollbar();
329         owner_->updateMenubar();
330         owner_->updateToolbar();
331         owner_->updateLayoutChoice();
332         owner_->updateWindowTitle();
333
334         // Don't forget to update the Layout
335         if (buffer_)
336                 owner_->setLayout(bv_->text->cursorPar()->layout()->name());
337
338         if (lyx::graphics::Previews::activated() && buffer_)
339                 lyx::graphics::Previews::get().generateBufferPreviews(*buffer_);
340 }
341
342
343 bool BufferView::Pimpl::fitCursor()
344 {
345         lyxerr << "BufferView::Pimpl::fitCursor." << endl;
346         if (screen().fitCursor(bv_)) {
347                 updateScrollbar();
348                 return true;
349         }
350         return false;
351 }
352
353
354 void BufferView::Pimpl::redoCurrentBuffer()
355 {
356         lyxerr[Debug::INFO] << "BufferView::redoCurrentBuffer" << endl;
357         if (buffer_ && bv_->text) {
358                 resizeCurrentBuffer();
359                 updateScrollbar();
360                 owner_->updateLayoutChoice();
361                 update();
362         }
363 }
364
365
366 void BufferView::Pimpl::resizeCurrentBuffer()
367 {
368         lyxerr[Debug::INFO] << "resizeCurrentBuffer" << endl;
369
370         int par = -1;
371         int selstartpar = -1;
372         int selendpar = -1;
373
374         pos_type pos = 0;
375         pos_type selstartpos = 0;
376         pos_type selendpos = 0;
377         bool selection = false;
378         bool mark_set  = false;
379
380         owner_->busy(true);
381
382         owner_->message(_("Formatting document..."));
383
384         if (bv_->text) {
385                 par = bv_->text->cursor.par();
386                 pos = bv_->text->cursor.pos();
387                 selstartpar = bv_->text->selection.start.par();
388                 selstartpos = bv_->text->selection.start.pos();
389                 selendpar = bv_->text->selection.end.par();
390                 selendpos = bv_->text->selection.end.pos();
391                 selection = bv_->text->selection.set();
392                 mark_set = bv_->text->selection.mark();
393                 bv_->text->fullRebreak();
394                 update();
395         } else {
396                 bv_->text = new LyXText(bv_, 0, false, bv_->buffer()->paragraphs());
397                 bv_->text->init(bv_);
398         }
399
400         if (par != -1) {
401                 bv_->text->selection.set(true);
402                 // At this point just to avoid the Delete-Empty-Paragraph-
403                 // Mechanism when setting the cursor.
404                 bv_->text->selection.mark(mark_set);
405                 if (selection) {
406                         bv_->text->setCursor(selstartpar, selstartpos);
407                         bv_->text->selection.cursor = bv_->text->cursor;
408                         bv_->text->setCursor(selendpar, selendpos);
409                         bv_->text->setSelection();
410                         bv_->text->setCursor(par, pos);
411                 } else {
412                         bv_->text->setCursor(par, pos);
413                         bv_->text->selection.cursor = bv_->text->cursor;
414                         bv_->text->selection.set(false);
415                 }
416         }
417
418         fitCursor();
419
420         switchKeyMap();
421         owner_->busy(false);
422
423         // reset the "Formatting..." message
424         owner_->clearMessage();
425
426         updateScrollbar();
427 }
428
429
430 void BufferView::Pimpl::updateScrollbar()
431 {
432         if (!bv_->text) {
433                 lyxerr[Debug::GUI] << "no text in updateScrollbar" << endl;
434                 workarea().setScrollbarParams(0, 0, 0);
435                 return;
436         }
437
438         LyXText const & t = *bv_->text;
439
440         lyxerr[Debug::GUI] << "Updating scrollbar: h " << t.height << ", top_y() "
441                 << top_y() << ", default height " << defaultRowHeight() << endl;
442
443         workarea().setScrollbarParams(t.height, top_y(), defaultRowHeight());
444 }
445
446
447 void BufferView::Pimpl::scrollDocView(int value)
448 {
449         lyxerr[Debug::GUI] << "scrollDocView of " << value << endl;
450
451         if (!buffer_)
452                 return;
453
454         screen().hideCursor();
455
456         top_y(value);
457         screen().redraw(*bv_);
458
459         if (!lyxrc.cursor_follows_scrollbar)
460                 return;
461
462         int const height = defaultRowHeight();
463         int const first = top_y() + height;
464         int const last = top_y() + workarea().workHeight() - height;
465
466         LyXText * text = bv_->text;
467         if (text->cursor.y() < first)
468                 text->setCursorFromCoordinates(0, first);
469         else if (text->cursor.y() > last)
470                 text->setCursorFromCoordinates(0, last);
471
472         owner_->updateLayoutChoice();
473 }
474
475
476 void BufferView::Pimpl::scroll(int lines)
477 {
478         if (!buffer_)
479                 return;
480
481         LyXText const * t = bv_->text;
482         int const line_height = defaultRowHeight();
483
484         // The new absolute coordinate
485         int new_top_y = top_y() + lines * line_height;
486
487         // Restrict to a valid value
488         new_top_y = std::min(t->height - 4 * line_height, new_top_y);
489         new_top_y = std::max(0, new_top_y);
490
491         scrollDocView(new_top_y);
492
493         // Update the scrollbar.
494         workarea().setScrollbarParams(t->height, top_y(), defaultRowHeight());
495 }
496
497
498 void BufferView::Pimpl::workAreaKeyPress(LyXKeySymPtr key,
499                                          key_modifier::state state)
500 {
501         bv_->owner()->getLyXFunc().processKeySym(key, state);
502
503         /* This is perhaps a bit of a hack. When we move
504          * around, or type, it's nice to be able to see
505          * the cursor immediately after the keypress. So
506          * we reset the toggle timeout and force the visibility
507          * of the cursor. Note we cannot do this inside
508          * dispatch() itself, because that's called recursively.
509          */
510         if (available()) {
511                 cursor_timeout.restart();
512                 screen().showCursor(*bv_);
513         }
514 }
515
516
517 void BufferView::Pimpl::selectionRequested()
518 {
519         static string sel;
520
521         if (!available())
522                 return;
523
524         LyXText * text = bv_->getLyXText();
525
526         if (text->selection.set() &&
527                 (!bv_->text->xsel_cache.set() ||
528                  text->selection.start != bv_->text->xsel_cache.start ||
529                  text->selection.end != bv_->text->xsel_cache.end))
530         {
531                 bv_->text->xsel_cache = text->selection;
532                 sel = text->selectionAsString(*bv_->buffer(), false);
533         } else if (!text->selection.set()) {
534                 sel = string();
535                 bv_->text->xsel_cache.set(false);
536         }
537         if (!sel.empty()) {
538                 workarea().putClipboard(sel);
539         }
540 }
541
542
543 void BufferView::Pimpl::selectionLost()
544 {
545         if (available()) {
546                 screen().hideCursor();
547                 bv_->getLyXText()->clearSelection();
548                 bv_->text->xsel_cache.set(false);
549         }
550 }
551
552
553 void BufferView::Pimpl::workAreaResize()
554 {
555         static int work_area_width;
556         static int work_area_height;
557
558         bool const widthChange = workarea().workWidth() != work_area_width;
559         bool const heightChange = workarea().workHeight() != work_area_height;
560
561         // update from work area
562         work_area_width = workarea().workWidth();
563         work_area_height = workarea().workHeight();
564
565         if (buffer_ != 0) {
566                 if (widthChange) {
567                         // The visible LyXView need a resize
568                         resizeCurrentBuffer();
569                 }
570         }
571
572         if (widthChange || heightChange)
573                 update();
574
575         // always make sure that the scrollbar is sane.
576         updateScrollbar();
577         owner_->updateLayoutChoice();
578 }
579
580
581 void BufferView::Pimpl::update()
582 {
583         //lyxerr << "BufferView::update()" << endl;
584         // fix cursor coordinate cache in case something went wrong
585
586         // check needed to survive LyX startup
587         if (bv_->getLyXText()) {
588                 // update all 'visible' paragraphs
589                 ParagraphList::iterator beg;
590                 ParagraphList::iterator end;
591                 getParsInRange(buffer_->paragraphs(),
592                                top_y(), top_y() + workarea().workHeight(),
593                                beg, end);
594                 bv_->text->redoParagraphs(beg, end);
595                 bv_->getLyXText()->redoCursor();
596                 updateScrollbar();
597         }
598         screen().redraw(*bv_);
599 }
600
601
602 // Callback for cursor timer
603 void BufferView::Pimpl::cursorToggle()
604 {
605         if (!buffer_) {
606                 cursor_timeout.restart();
607                 return;
608         }
609
610         screen().toggleCursor(*bv_);
611         cursor_timeout.restart();
612 }
613
614
615 bool BufferView::Pimpl::available() const
616 {
617         return buffer_ && bv_->text;
618 }
619
620
621 Change const BufferView::Pimpl::getCurrentChange()
622 {
623         if (!bv_->buffer()->params().tracking_changes)
624                 return Change(Change::UNCHANGED);
625
626         LyXText * text = bv_->getLyXText();
627
628         if (!text->selection.set())
629                 return Change(Change::UNCHANGED);
630
631         return text->getPar(text->selection.start)
632                 ->lookupChangeFull(text->selection.start.pos());
633 }
634
635
636 void BufferView::Pimpl::savePosition(unsigned int i)
637 {
638         if (i >= saved_positions_num)
639                 return;
640         saved_positions[i] = Position(buffer_->fileName(),
641                                       bv_->text->cursorPar()->id(),
642                                       bv_->text->cursor.pos());
643         if (i > 0)
644                 owner_->message(bformat(_("Saved bookmark %1$s"), tostr(i)));
645 }
646
647
648 void BufferView::Pimpl::restorePosition(unsigned int i)
649 {
650         if (i >= saved_positions_num)
651                 return;
652
653         string const fname = saved_positions[i].filename;
654
655         bv_->text->clearSelection();
656
657         if (fname != buffer_->fileName()) {
658                 Buffer * b = 0;
659                 if (bufferlist.exists(fname))
660                         b = bufferlist.getBuffer(fname);
661                 else {
662                         b = bufferlist.newBuffer(fname);
663                         ::loadLyXFile(b, fname); // don't ask, just load it
664                 }
665                 if (b)
666                         buffer(b);
667         }
668
669         ParIterator par = buffer_->getParFromID(saved_positions[i].par_id);
670         if (par == buffer_->par_iterator_end())
671                 return;
672
673         bv_->text->setCursor(par.pit(),
674                              min(par->size(), saved_positions[i].par_pos));
675
676         update();
677         if (i > 0)
678                 owner_->message(bformat(_("Moved to bookmark %1$s"), tostr(i)));
679 }
680
681
682 bool BufferView::Pimpl::isSavedPosition(unsigned int i)
683 {
684         return i < saved_positions_num && !saved_positions[i].filename.empty();
685 }
686
687
688 void BufferView::Pimpl::switchKeyMap()
689 {
690         if (!lyxrc.rtl_support)
691                 return;
692
693         Intl & intl = owner_->getIntl();
694         if (bv_->getLyXText()->real_current_font.isRightToLeft()) {
695                 if (intl.keymap == Intl::PRIMARY)
696                         intl.KeyMapSec();
697         } else {
698                 if (intl.keymap == Intl::SECONDARY)
699                         intl.KeyMapPrim();
700         }
701 }
702
703
704 void BufferView::Pimpl::center()
705 {
706         LyXText * text = bv_->text;
707
708         text->clearSelection();
709         int const half_height = workarea().workHeight() / 2;
710         int new_y = std::max(0, text->cursor.y() - half_height);
711
712         // FIXME: look at this comment again ...
713         // This updates top_y() but means the fitCursor() call
714         // from the update(FITCUR) doesn't realise that we might
715         // have moved (e.g. from GOTOPARAGRAPH), so doesn't cause
716         // the scrollbar to be updated as it should, so we have
717         // to do it manually. Any operation that does a center()
718         // and also might have moved top_y() must make sure to call
719         // updateScrollbar() currently. Never mind that this is a
720         // pretty obfuscated way of updating t->top_y()
721         top_y(new_y);
722         update();
723 }
724
725
726 void BufferView::Pimpl::stuffClipboard(string const & stuff) const
727 {
728         workarea().putClipboard(stuff);
729 }
730
731
732 InsetOld * BufferView::Pimpl::getInsetByCode(InsetOld::Code code)
733 {
734 #if 0
735         LyXCursor cursor = bv_->getLyXText()->cursor;
736         Buffer::inset_iterator it =
737                 find_if(Buffer::inset_iterator(
738                         cursorPar(), cursor.pos()),
739                         buffer_->inset_iterator_end(),
740                         lyx::compare_memfun(&Inset::lyxCode, code));
741         return it != buffer_->inset_iterator_end() ? (*it) : 0;
742 #else
743         // Ok, this is a little bit too brute force but it
744         // should work for now. Better infrastructure is coming. (Lgb)
745
746         Buffer * b = bv_->buffer();
747         LyXText * text =  bv_->getLyXText();
748
749         Buffer::inset_iterator beg = b->inset_iterator_begin();
750         Buffer::inset_iterator end = b->inset_iterator_end();
751
752         bool cursorPar_seen = false;
753
754         for (; beg != end; ++beg) {
755                 if (beg.getPar() == text->cursorPar()) {
756                         cursorPar_seen = true;
757                 }
758                 if (cursorPar_seen) {
759                         if (beg.getPar() == text->cursorPar()
760                             && beg.getPos() >= text->cursor.pos()) {
761                                 break;
762                         } else if (beg.getPar() != text->cursorPar()) {
763                                 break;
764                         }
765                 }
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         }
776         return 0;
777 #endif
778 }
779
780
781 void BufferView::Pimpl::MenuInsertLyXFile(string const & filen)
782 {
783         string filename = filen;
784
785         if (filename.empty()) {
786                 // Launch a file browser
787                 string initpath = lyxrc.document_path;
788
789                 if (available()) {
790                         string const trypath = owner_->buffer()->filePath();
791                         // If directory is writeable, use this as default.
792                         if (IsDirWriteable(trypath))
793                                 initpath = trypath;
794                 }
795
796                 FileDialog fileDlg(_("Select LyX document to insert"),
797                         LFUN_FILE_INSERT,
798                         make_pair(string(_("Documents|#o#O")),
799                                   string(lyxrc.document_path)),
800                         make_pair(string(_("Examples|#E#e")),
801                                   string(AddPath(system_lyxdir(), "examples"))));
802
803                 FileDialog::Result result =
804                         fileDlg.open(initpath,
805                                        _("*.lyx| LyX Documents (*.lyx)"));
806
807                 if (result.first == FileDialog::Later)
808                         return;
809
810                 filename = result.second;
811
812                 // check selected filename
813                 if (filename.empty()) {
814                         owner_->message(_("Canceled."));
815                         return;
816                 }
817         }
818
819         // get absolute path of file and add ".lyx" to the filename if
820         // necessary
821         filename = FileSearch(string(), filename, "lyx");
822
823         string const disp_fn = MakeDisplayPath(filename);
824         owner_->message(bformat(_("Inserting document %1$s..."), disp_fn));
825         if (bv_->insertLyXFile(filename))
826                 owner_->message(bformat(_("Document %1$s inserted."),
827                                         disp_fn));
828         else
829                 owner_->message(bformat(_("Could not insert document %1$s"),
830                                         disp_fn));
831 }
832
833
834 void BufferView::Pimpl::trackChanges()
835 {
836         Buffer * buf(bv_->buffer());
837         bool const tracking(buf->params().tracking_changes);
838
839         if (!tracking) {
840                 ParIterator const end = buf->par_iterator_end();
841                 for (ParIterator it = buf->par_iterator_begin(); it != end; ++it)
842                         it->trackChanges();
843                 buf->params().tracking_changes = true;
844
845                 // we cannot allow undos beyond the freeze point
846                 buf->undostack().clear();
847         } else {
848                 update();
849                 bv_->text->setCursor(0, 0);
850 #warning changes FIXME
851                 //moveCursorUpdate(false);
852
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 #warning remove me
869 LCursor theTempCursor(0);
870
871 namespace {
872
873         InsetOld * insetFromCoords(BufferView * bv, int x, int y)
874         {
875                 LyXText * text = bv->text;
876                 InsetOld * inset = 0;
877                 theTempCursor = LCursor(bv);
878                 while (true) {
879                         InsetOld * inset_hit = text->checkInsetHit(x, y);
880                         if (!inset_hit)
881                                 break;
882                         inset = inset_hit;
883                         if (!inset_hit->descendable())
884                                 break;
885                         text = inset_hit->getText(0);
886                         lyxerr << "Hit inset: " << inset << " at x: " << x
887                                 << " text: " << text << " y: " << y << endl;
888                         theTempCursor.push(static_cast<UpdatableInset*>(inset));
889                 }
890                 return inset;
891         }
892
893 }
894
895
896 bool BufferView::Pimpl::workAreaDispatch(FuncRequest const & cmd)
897 {
898         switch (cmd.action) {
899         case LFUN_MOUSE_PRESS:
900         case LFUN_MOUSE_MOTION:
901         case LFUN_MOUSE_RELEASE:
902         case LFUN_MOUSE_DOUBLE:
903         case LFUN_MOUSE_TRIPLE: {
904                 // We pass those directly to the Bufferview, since
905                 // otherwise selection handling breaks down
906
907                 // Doesn't go through lyxfunc, so we need to update
908                 // the layout choice etc. ourselves
909
910                 // e.g. Qt mouse press when no buffer
911                 if (!available())
912                         return false;
913
914                 screen().hideCursor();
915
916                 // either the inset under the cursor or the surrounding LyXText will
917                 // handle this event.
918
919                 // built temporary path to inset
920                 InsetOld * inset = insetFromCoords(bv_, cmd.x, cmd.y); 
921                 FuncRequest cmd1(cmd, bv_);
922                 DispatchResult res;
923
924                 // try to dispatch to that inset
925                 if (inset) {
926                         FuncRequest cmd2 = cmd1;
927                         lyxerr << "dispatching action " << cmd2.action 
928                                 << " to inset " << inset << endl;
929                         cmd2.x -= inset->x();
930                         cmd2.y -= inset->y();
931                         res = inset->dispatch(cmd2);
932                         if (res.update()) {
933                                 bv_->update();
934                                 bv_->cursor().updatePos();
935                         }
936                         res.update(false);
937                         switch (res.val()) {
938                                 case FINISHED:
939                                 case FINISHED_RIGHT:
940                                 case FINISHED_UP: 
941                                 case FINISHED_DOWN:
942                                         theTempCursor.pop();
943                                         bv_->cursor() = theTempCursor;
944                                         bv_->cursor().innerText()->setCursorFromCoordinates(cmd.x, top_y() + cmd.y);
945                                         if (bv_->fitCursor())
946                                                 bv_->update();
947                                         return true;
948                                 default:
949                                         lyxerr << "not dispatched by inner inset val: " << res.val() << endl;
950                                         break;
951                         }
952                 }
953
954                 // otherwise set cursor to surrounding LyXText
955                 if (!res.dispatched()) {
956                         lyxerr << "temp cursor is: " << theTempCursor << endl;
957                         lyxerr << "dispatching " << cmd1
958                                << " to surrounding LyXText "
959                                << theTempCursor.innerText() << endl;
960                         bv_->cursor() = theTempCursor;
961                         res = bv_->cursor().innerText()->dispatch(cmd1);
962                         if (bv_->fitCursor() || res.update())
963                                 bv_->update();
964                         
965                         //return DispatchResult(true, true);
966                 }
967                 // see workAreaKeyPress
968                 cursor_timeout.restart();
969                 screen().showCursor(*bv_);
970
971                 // skip these when selecting
972                 if (cmd.action != LFUN_MOUSE_MOTION) {
973                         owner_->updateLayoutChoice();
974                         owner_->updateToolbar();
975                 }
976
977                 // slight hack: this is only called currently when we
978                 // clicked somewhere, so we force through the display
979                 // of the new status here.
980                 owner_->clearMessage();
981                 return true;
982         }
983
984         default:
985                 owner_->dispatch(cmd);
986                 return true;
987         }
988 }
989
990
991 bool BufferView::Pimpl::dispatch(FuncRequest const & ev_in)
992 {
993         // Make sure that the cached BufferView is correct.
994         FuncRequest ev = ev_in;
995         ev.setView(bv_);
996
997         lyxerr[Debug::ACTION] << "BufferView::Pimpl::Dispatch:"
998                 << " action[" << ev.action << ']'
999                 << " arg[" << ev.argument << ']'
1000                 << " x[" << ev.x << ']'
1001                 << " y[" << ev.y << ']'
1002                 << " button[" << ev.button() << ']'
1003                 << endl;
1004
1005         LyXTextClass const & tclass = buffer_->params().getLyXTextClass();
1006
1007         switch (ev.action) {
1008
1009         case LFUN_SCROLL_INSET:
1010                 // this is not handled here as this function is only active
1011                 // if we have a locking_inset and that one is (or contains)
1012                 // a tabular-inset
1013                 break;
1014
1015         case LFUN_FILE_INSERT:
1016                 MenuInsertLyXFile(ev.argument);
1017                 break;
1018
1019         case LFUN_FILE_INSERT_ASCII_PARA:
1020                 InsertAsciiFile(bv_, ev.argument, true);
1021                 break;
1022
1023         case LFUN_FILE_INSERT_ASCII:
1024                 InsertAsciiFile(bv_, ev.argument, false);
1025                 break;
1026
1027         case LFUN_FONT_STATE:
1028                 owner_->getLyXFunc().setMessage(currentState(bv_));
1029                 break;
1030
1031         case LFUN_INSERT_LABEL: {
1032                 // Try and generate a valid label
1033                 string const contents = ev.argument.empty() ?
1034                         getPossibleLabel(*bv_) : ev.argument;
1035                 InsetCommandParams icp("label", contents);
1036                 string data = InsetCommandMailer::params2string("label", icp);
1037                 owner_->getDialogs().show("label", data, 0);
1038                 break;
1039         }
1040
1041         case LFUN_BOOKMARK_SAVE:
1042                 savePosition(strToUnsignedInt(ev.argument));
1043                 break;
1044
1045         case LFUN_BOOKMARK_GOTO:
1046                 restorePosition(strToUnsignedInt(ev.argument));
1047                 break;
1048
1049         case LFUN_REF_GOTO: {
1050                 string label = ev.argument;
1051                 if (label.empty()) {
1052                         InsetRef * inset =
1053                                 static_cast<InsetRef*>(getInsetByCode(InsetOld::REF_CODE));
1054                         if (inset) {
1055                                 label = inset->getContents();
1056                                 savePosition(0);
1057                         }
1058                 }
1059
1060                 if (!label.empty())
1061                         bv_->gotoLabel(label);
1062         }
1063         break;
1064
1065         // --- accented characters ---------------------------
1066
1067         case LFUN_UMLAUT:
1068         case LFUN_CIRCUMFLEX:
1069         case LFUN_GRAVE:
1070         case LFUN_ACUTE:
1071         case LFUN_TILDE:
1072         case LFUN_CEDILLA:
1073         case LFUN_MACRON:
1074         case LFUN_DOT:
1075         case LFUN_UNDERDOT:
1076         case LFUN_UNDERBAR:
1077         case LFUN_CARON:
1078         case LFUN_SPECIAL_CARON:
1079         case LFUN_BREVE:
1080         case LFUN_TIE:
1081         case LFUN_HUNG_UMLAUT:
1082         case LFUN_CIRCLE:
1083         case LFUN_OGONEK:
1084                 if (ev.argument.empty()) {
1085                         // As always...
1086                         owner_->getLyXFunc().handleKeyFunc(ev.action);
1087                 } else {
1088                         owner_->getLyXFunc().handleKeyFunc(ev.action);
1089                         owner_->getIntl().getTransManager()
1090                                 .TranslateAndInsert(ev.argument[0], bv_->getLyXText());
1091                         update();
1092                 }
1093                 break;
1094
1095         case LFUN_MATH_MACRO:
1096         case LFUN_MATH_DELIM:
1097         case LFUN_INSERT_MATRIX:
1098         case LFUN_INSERT_MATH:
1099         case LFUN_MATH_IMPORT_SELECTION: // Imports LaTeX from the X selection
1100         case LFUN_MATH_DISPLAY:          // Open or create a displayed math inset
1101         case LFUN_MATH_MODE:             // Open or create an inlined math inset
1102                 mathDispatch(ev);
1103                 break;
1104
1105         case LFUN_INSET_APPLY: {
1106                 string const name = ev.getArg(0);
1107
1108                 InsetBase * inset = owner_->getDialogs().getOpenInset(name);
1109                 if (inset) {
1110                         // This works both for 'original' and 'mathed' insets.
1111                         // Note that the localDispatch performs update also.
1112                         FuncRequest fr(bv_, LFUN_INSET_MODIFY, ev.argument);
1113                         inset->dispatch(fr);
1114                 } else {
1115                         FuncRequest fr(bv_, LFUN_INSET_INSERT, ev.argument);
1116                         dispatch(fr);
1117                 }
1118         }
1119         break;
1120
1121         case LFUN_INSET_INSERT: {
1122                 InsetOld * inset = createInset(ev);
1123                 if (!inset || !insertInset(inset))
1124                         delete inset;
1125                 break;
1126         }
1127
1128         case LFUN_FLOAT_LIST:
1129                 if (tclass.floats().typeExist(ev.argument)) {
1130                         InsetOld * inset = new InsetFloatList(ev.argument);
1131                         if (!insertInset(inset, tclass.defaultLayoutName()))
1132                                 delete inset;
1133                 } else {
1134                         lyxerr << "Non-existent float type: "
1135                                << ev.argument << endl;
1136                 }
1137                 break;
1138
1139         case LFUN_LAYOUT_PARAGRAPH: {
1140                 string data;
1141                 params2string(*bv_->getLyXText()->cursorPar(), data);
1142                 data = "show\n" + data;
1143                 bv_->owner()->getDialogs().show("paragraph", data);
1144                 break;
1145         }
1146
1147         case LFUN_PARAGRAPH_UPDATE:
1148                 updateParagraphDialog();
1149                 break;
1150
1151         case LFUN_PARAGRAPH_APPLY:
1152                 setParagraphParams(*bv_, ev.argument);
1153                 break;
1154
1155         case LFUN_THESAURUS_ENTRY: {
1156                 string arg = ev.argument;
1157
1158                 if (arg.empty()) {
1159                         arg = bv_->getLyXText()->selectionAsString(*buffer_,
1160                                                                    false);
1161
1162                         // FIXME
1163                         if (arg.size() > 100 || arg.empty()) {
1164                                 // Get word or selection
1165                                 bv_->getLyXText()->selectWordWhenUnderCursor(lyx::WHOLE_WORD);
1166                                 arg = bv_->getLyXText()->selectionAsString(*buffer_, false);
1167                                 // FIXME: where is getLyXText()->unselect(bv_) ?
1168                         }
1169                 }
1170
1171                 bv_->owner()->getDialogs().show("thesaurus", arg);
1172                 break;
1173         }
1174
1175         case LFUN_TRACK_CHANGES:
1176                 trackChanges();
1177                 break;
1178
1179         case LFUN_MERGE_CHANGES:
1180                 owner_->getDialogs().show("changes");
1181                 break;
1182
1183         case LFUN_ACCEPT_ALL_CHANGES: {
1184                 bv_->text->setCursor(0, 0);
1185 #warning FIXME changes
1186                 //moveCursorUpdate(false);
1187
1188                 while (lyx::find::findNextChange(bv_))
1189                         bv_->getLyXText()->acceptChange();
1190
1191                 update();
1192                 break;
1193         }
1194
1195         case LFUN_REJECT_ALL_CHANGES: {
1196                 bv_->text->setCursor(0, 0);
1197 #warning FIXME changes
1198                 //moveCursorUpdate(false);
1199
1200                 while (lyx::find::findNextChange(bv_))
1201                         bv_->getLyXText()->rejectChange();
1202
1203                 update();
1204                 break;
1205         }
1206
1207         case LFUN_ACCEPT_CHANGE: {
1208                 bv_->getLyXText()->acceptChange();
1209                 update();
1210                 break;
1211         }
1212
1213         case LFUN_REJECT_CHANGE: {
1214                 bv_->getLyXText()->rejectChange();
1215                 update();
1216                 break;
1217         }
1218
1219         case LFUN_UNKNOWN_ACTION:
1220                 ev.errorMessage(N_("Unknown function!"));
1221                 break;
1222
1223         default:
1224                 return bv_->getLyXText()->dispatch(FuncRequest(ev, bv_)).dispatched();
1225         } // end of switch
1226
1227         return true;
1228 }
1229
1230
1231 bool BufferView::Pimpl::insertInset(InsetOld * inset, string const & lout)
1232 {
1233 #ifdef LOCK
1234         // if we are in a locking inset we should try to insert the
1235         // inset there otherwise this is a illegal function now
1236         if (bv_->theLockingInset()) {
1237                 if (bv_->theLockingInset()->insetAllowed(inset))
1238                         return bv_->theLockingInset()->insertInset(bv_, inset);
1239                 return false;
1240         }
1241 #endif
1242
1243         // not quite sure if we want this...
1244         bv_->text->recUndo(bv_->text->cursor.par());
1245         freezeUndo();
1246
1247         bv_->text->clearSelection();
1248         if (!lout.empty()) {
1249                 bv_->text->breakParagraph(bv_->buffer()->paragraphs());
1250
1251                 if (!bv_->text->cursorPar()->empty()) {
1252                         bv_->text->cursorLeft(bv_);
1253                         bv_->text->breakParagraph(bv_->buffer()->paragraphs());
1254                 }
1255
1256                 string lres = lout;
1257                 LyXTextClass const & tclass = buffer_->params().getLyXTextClass();
1258                 bool hasLayout = tclass.hasLayout(lres);
1259
1260                 bv_->text->setLayout(hasLayout ? lres : tclass.defaultLayoutName());
1261
1262                 bv_->text->setParagraph(
1263                                    VSpace(VSpace::NONE), VSpace(VSpace::NONE),
1264                                    Spacing(),
1265                                    LYX_ALIGN_LAYOUT,
1266                                    string(),
1267                                    0);
1268         }
1269         bv_->cursor().innerText()->insertInset(inset);
1270         update();
1271
1272         unFreezeUndo();
1273         return true;
1274 }
1275
1276
1277 bool BufferView::Pimpl::ChangeInsets(InsetOld::Code code,
1278                                      string const & from, string const & to)
1279 {
1280         bool need_update = false;
1281         LyXCursor cursor = bv_->text->cursor;
1282         LyXCursor tmpcursor = cursor;
1283         cursor.par(tmpcursor.par());
1284         cursor.pos(tmpcursor.pos());
1285
1286         ParIterator end = bv_->buffer()->par_iterator_end();
1287         for (ParIterator it = bv_->buffer()->par_iterator_begin();
1288              it != end; ++it) {
1289                 bool changed_inset = false;
1290                 for (InsetList::iterator it2 = it->insetlist.begin();
1291                      it2 != it->insetlist.end(); ++it2) {
1292                         if (it2->inset->lyxCode() == code) {
1293                                 InsetCommand * inset = static_cast<InsetCommand *>(it2->inset);
1294                                 if (inset->getContents() == from) {
1295                                         inset->setContents(to);
1296                                         changed_inset = true;
1297                                 }
1298                         }
1299                 }
1300                 if (changed_inset) {
1301                         need_update = true;
1302
1303                         // FIXME
1304
1305                         // The test it.size()==1 was needed to prevent crashes.
1306                         // How to set the cursor correctly when it.size()>1 ??
1307                         if (it.size() == 1) {
1308                                 bv_->text->setCursorIntern(bv_->text->parOffset(it.pit()), 0);
1309                                 bv_->text->redoParagraph(bv_->text->cursorPar());
1310                         }
1311                 }
1312         }
1313         bv_->text->setCursorIntern(cursor.par(), cursor.pos());
1314         return need_update;
1315 }
1316
1317
1318 void BufferView::Pimpl::updateParagraphDialog()
1319 {
1320         if (!bv_->owner()->getDialogs().visible("paragraph"))
1321                 return;
1322         Paragraph const & par = *bv_->getLyXText()->cursorPar();
1323         string data;
1324         params2string(par, data);
1325
1326         // Will the paragraph accept changes from the dialog?
1327         InsetOld * const inset = par.inInset();
1328         bool const accept =
1329                 !(inset && inset->forceDefaultParagraphs(inset));
1330
1331         data = "update " + tostr(accept) + '\n' + data;
1332         bv_->owner()->getDialogs().update("paragraph", data);
1333 }
1334
1335