]> git.lyx.org Git - lyx.git/blob - src/BufferView_pimpl.C
The markDirty() and fitCursor() changes
[lyx.git] / src / BufferView_pimpl.C
1 /**
2  * \file BufferView_pimpl.C
3  * Copyright 2002 the LyX Team
4  * Read the file COPYING
5  *
6  * \author various
7  */
8
9 #include <config.h>
10
11 #include "BufferView_pimpl.h"
12 #include "bufferlist.h"
13 #include "bufferview_funcs.h"
14 #include "commandtags.h"
15 #include "debug.h"
16 #include "factory.h"
17 #include "FloatList.h"
18 #include "funcrequest.h"
19 #include "gettext.h"
20 #include "intl.h"
21 #include "iterators.h"
22 #include "lyx_cb.h" // added for Dispatch functions
23 #include "lyx_main.h"
24 #include "lyxfind.h"
25 #include "lyxfunc.h"
26 #include "lyxtext.h"
27 #include "lyxrc.h"
28 #include "lyxrow.h"
29 #include "paragraph.h"
30 #include "ParagraphParameters.h"
31 #include "TextCache.h"
32 #include "undo_funcs.h"
33
34 #include "insets/insetfloatlist.h"
35 #include "insets/insetgraphics.h"
36 #include "insets/insetinclude.h"
37 #include "insets/insetref.h"
38 #include "insets/insettext.h"
39
40 #include "frontends/Alert.h"
41 #include "frontends/Dialogs.h"
42 #include "frontends/FileDialog.h"
43 #include "frontends/LyXView.h"
44 #include "frontends/LyXScreenFactory.h"
45 #include "frontends/mouse_state.h"
46 #include "frontends/screen.h"
47 #include "frontends/WorkArea.h"
48 #include "frontends/WorkAreaFactory.h"
49
50 #include "mathed/formulabase.h"
51
52 #include "graphics/Previews.h"
53
54 #include "support/LAssert.h"
55 #include "support/lstrings.h"
56 #include "support/filetools.h"
57
58 #include <boost/bind.hpp>
59 #include <boost/signals/connection.hpp>
60 #include "BoostFormat.h"
61
62 #include <unistd.h>
63 #include <sys/wait.h>
64
65
66 using std::vector;
67 using std::find_if;
68 using std::find;
69 using std::pair;
70 using std::endl;
71 using std::make_pair;
72 using std::min;
73
74 using lyx::pos_type;
75
76 extern BufferList bufferlist;
77
78
79 namespace {
80
81 unsigned int const saved_positions_num = 20;
82
83 // All the below connection objects are needed because of a bug in some
84 // versions of GCC (<=2.96 are on the suspects list.) By having and assigning
85 // to these connections we avoid a segfault upon startup, and also at exit.
86 // (Lgb)
87
88 boost::signals::connection dispatchcon;
89 boost::signals::connection timecon;
90 boost::signals::connection doccon;
91 boost::signals::connection resizecon;
92 boost::signals::connection kpresscon;
93 boost::signals::connection selectioncon;
94 boost::signals::connection lostcon;
95
96
97 } // anon namespace
98
99
100 BufferView::Pimpl::Pimpl(BufferView * bv, LyXView * owner,
101              int xpos, int ypos, int width, int height)
102         : bv_(bv), owner_(owner), buffer_(0), cursor_timeout(400),
103           using_xterm_cursor(false)
104 {
105         workarea_.reset(WorkAreaFactory::create(xpos, ypos, width, height));
106         screen_.reset(LyXScreenFactory::create(workarea()));
107
108         // Setup the signals
109         doccon = workarea().scrollDocView
110                 .connect(boost::bind(&BufferView::Pimpl::scrollDocView, this, _1));
111         resizecon = workarea().workAreaResize
112                 .connect(boost::bind(&BufferView::Pimpl::workAreaResize, this));
113         dispatchcon = workarea().dispatch
114                 .connect(boost::bind(&BufferView::Pimpl::dispatch, this, _1));
115         kpresscon = workarea().workAreaKeyPress
116                 .connect(boost::bind(&BufferView::Pimpl::workAreaKeyPress, this, _1, _2));
117         selectioncon = workarea().selectionRequested
118                 .connect(boost::bind(&BufferView::Pimpl::selectionRequested, this));
119         lostcon = workarea().selectionLost
120                 .connect(boost::bind(&BufferView::Pimpl::selectionLost, this));
121
122         timecon = cursor_timeout.timeout
123                 .connect(boost::bind(&BufferView::Pimpl::cursorToggle, this));
124         cursor_timeout.start();
125         saved_positions.resize(saved_positions_num);
126 }
127
128
129 WorkArea & BufferView::Pimpl::workarea() const
130 {
131         return *workarea_.get();
132 }
133
134
135 LyXScreen & BufferView::Pimpl::screen() const
136 {
137         return *screen_.get();
138 }
139
140
141 Painter & BufferView::Pimpl::painter() const
142 {
143         return workarea().getPainter();
144 }
145
146
147 void BufferView::Pimpl::buffer(Buffer * b)
148 {
149         lyxerr[Debug::INFO] << "Setting buffer in BufferView ("
150                             << b << ')' << endl;
151         if (buffer_) {
152                 buffer_->delUser(bv_);
153
154                 // Put the old text into the TextCache, but
155                 // only if the buffer is still loaded.
156                 // Also set the owner of the test to 0
157                 //              bv_->text->owner(0);
158                 textcache.add(buffer_, workarea().workWidth(), bv_->text);
159                 if (lyxerr.debugging())
160                         textcache.show(lyxerr, "BufferView::buffer");
161
162                 bv_->text = 0;
163         }
164
165         // set current buffer
166         buffer_ = b;
167
168         // if we're quitting lyx, don't bother updating stuff
169         if (quitting)
170                 return;
171
172         // if we are closing the buffer, use the first buffer as current
173         if (!buffer_) {
174                 buffer_ = bufferlist.first();
175         }
176
177         if (buffer_) {
178                 lyxerr[Debug::INFO] << "Buffer addr: " << buffer_ << endl;
179                 buffer_->addUser(bv_);
180
181                 // If we don't have a text object for this, we make one
182                 if (bv_->text == 0) {
183                         resizeCurrentBuffer();
184                 }
185
186                 // FIXME: needed when ?
187                 bv_->text->top_y(screen().topCursorVisible(bv_->text->cursor, bv_->text->top_y()));
188
189                 // Similarly, buffer-dependent dialogs should be updated or
190                 // hidden. This should go here because some dialogs (eg ToC)
191                 // require bv_->text.
192                 owner_->getDialogs().updateBufferDependent(true);
193         } else {
194                 lyxerr[Debug::INFO] << "  No Buffer!" << endl;
195                 owner_->getDialogs().hideBufferDependent();
196
197                 // Also remove all remaining text's from the testcache.
198                 // (there should not be any!) (if there is any it is a
199                 // bug!)
200                 if (lyxerr.debugging())
201                         textcache.show(lyxerr, "buffer delete all");
202                 textcache.clear();
203         }
204
205         repaint();
206         updateScrollbar();
207         owner_->updateMenubar();
208         owner_->updateToolbar();
209         owner_->updateLayoutChoice();
210         owner_->updateWindowTitle();
211
212         if (grfx::Previews::activated() && buffer_)
213                 grfx::Previews::get().generateBufferPreviews(*buffer_);
214 }
215
216
217 bool BufferView::Pimpl::fitCursor()
218 {
219         bool ret;
220
221         if (bv_->theLockingInset()) {
222                 bv_->theLockingInset()->fitInsetCursor(bv_);
223                 ret = true;
224         } else {
225                 ret = screen().fitCursor(bv_->text, bv_);
226         }
227
228         dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
229
230         if (ret)
231                 updateScrollbar();
232         return ret;
233 }
234
235
236 void BufferView::Pimpl::redoCurrentBuffer()
237 {
238         lyxerr[Debug::INFO] << "BufferView::redoCurrentBuffer" << endl;
239         if (buffer_ && bv_->text) {
240                 resizeCurrentBuffer();
241                 updateScrollbar();
242                 owner_->updateLayoutChoice();
243                 repaint();
244         }
245 }
246
247
248 int BufferView::Pimpl::resizeCurrentBuffer()
249 {
250         lyxerr[Debug::INFO] << "resizeCurrentBuffer" << endl;
251
252         Paragraph * par = 0;
253         Paragraph * selstartpar = 0;
254         Paragraph * selendpar = 0;
255         UpdatableInset * the_locking_inset = 0;
256
257         pos_type pos = 0;
258         pos_type selstartpos = 0;
259         pos_type selendpos = 0;
260         bool selection = false;
261         bool mark_set  = false;
262
263         owner_->busy(true);
264
265         owner_->message(_("Formatting document..."));
266
267         if (bv_->text) {
268                 par = bv_->text->cursor.par();
269                 pos = bv_->text->cursor.pos();
270                 selstartpar = bv_->text->selection.start.par();
271                 selstartpos = bv_->text->selection.start.pos();
272                 selendpar = bv_->text->selection.end.par();
273                 selendpos = bv_->text->selection.end.pos();
274                 selection = bv_->text->selection.set();
275                 mark_set = bv_->text->selection.mark();
276                 the_locking_inset = bv_->theLockingInset();
277                 buffer_->resizeInsets(bv_);
278                 // I don't think the delete and new are necessary here we just could
279                 // call only init! (Jug 20020419)
280                 delete bv_->text;
281                 bv_->text = new LyXText(bv_);
282                 bv_->text->init(bv_);
283         } else {
284                 // See if we have a text in TextCache that fits
285                 // the new buffer_ with the correct width.
286                 bv_->text = textcache.findFit(buffer_, workarea().workWidth());
287                 if (bv_->text) {
288                         if (lyxerr.debugging()) {
289                                 lyxerr << "Found a LyXText that fits:\n";
290                                 textcache.show(lyxerr, make_pair(buffer_, make_pair(workarea().workWidth(), bv_->text)));
291                         }
292                         // Set the owner of the newly found text
293                         //      bv_->text->owner(bv_);
294                         if (lyxerr.debugging())
295                                 textcache.show(lyxerr, "resizeCurrentBuffer");
296
297                         buffer_->resizeInsets(bv_);
298                 } else {
299                         bv_->text = new LyXText(bv_);
300                         bv_->text->init(bv_);
301                         //buffer_->resizeInsets(bv_);
302                 }
303         }
304
305         if (par) {
306                 bv_->text->selection.set(true);
307                 // At this point just to avoid the Delete-Empty-Paragraph-
308                 // Mechanism when setting the cursor.
309                 bv_->text->selection.mark(mark_set);
310                 if (selection) {
311                         bv_->text->setCursor(selstartpar, selstartpos);
312                         bv_->text->selection.cursor = bv_->text->cursor;
313                         bv_->text->setCursor(selendpar, selendpos);
314                         bv_->text->setSelection();
315                         bv_->text->setCursor(par, pos);
316                 } else {
317                         bv_->text->setCursor(par, pos);
318                         bv_->text->selection.cursor = bv_->text->cursor;
319                         bv_->text->selection.set(false);
320                 }
321                 // remake the inset locking
322                 bv_->theLockingInset(the_locking_inset);
323         }
324
325         bv_->text->top_y(screen().topCursorVisible(bv_->text->cursor, bv_->text->top_y()));
326
327         switchKeyMap();
328         owner_->busy(false);
329
330         updateScrollbar();
331
332         return 0;
333 }
334
335
336 void BufferView::Pimpl::repaint()
337 {
338         // Regenerate the screen.
339         screen().redraw(bv_->text, bv_);
340 }
341
342
343 void BufferView::Pimpl::updateScrollbar()
344 {
345         if (!bv_->text) {
346                 lyxerr[Debug::GUI] << "no text in updateScrollbar" << endl;
347                 workarea().setScrollbarParams(0, 0, 0);
348                 return;
349         }
350
351         LyXText const & t = *bv_->text;
352
353         lyxerr[Debug::GUI] << "Updating scrollbar: h " << t.height << ", top_y() "
354                 << t.top_y() << ", default height " << defaultRowHeight() << endl;
355
356         workarea().setScrollbarParams(t.height, t.top_y(), defaultRowHeight());
357 }
358
359
360 void BufferView::Pimpl::scrollDocView(int value)
361 {
362         lyxerr[Debug::GUI] << "scrollDocView of " << value << endl;
363
364         if (!buffer_)
365                 return;
366
367         screen().draw(bv_->text, bv_, value);
368
369         if (!lyxrc.cursor_follows_scrollbar)
370                 return;
371
372         LyXText * vbt = bv_->text;
373
374         int const height = defaultRowHeight();
375         int const first = static_cast<int>((bv_->text->top_y() + height));
376         int const last = static_cast<int>((bv_->text->top_y() + workarea().workHeight() - height));
377
378         if (vbt->cursor.y() < first)
379                 vbt->setCursorFromCoordinates(0, first);
380         else if (vbt->cursor.y() > last)
381                 vbt->setCursorFromCoordinates(0, last);
382
383         owner_->updateLayoutChoice();
384 }
385
386
387 void BufferView::Pimpl::scroll(int lines)
388 {
389         if (!buffer_) {
390                 return;
391         }
392
393         LyXText const * t = bv_->text;
394         int const line_height = defaultRowHeight();
395
396         // The new absolute coordinate
397         int new_top_y = t->top_y() + lines * line_height;
398
399         // Restrict to a valid value
400         new_top_y = std::min(t->height - 4 * line_height, new_top_y);
401         new_top_y = std::max(0, new_top_y);
402
403         scrollDocView(new_top_y);
404
405         // Update the scrollbar.
406         workarea().setScrollbarParams(t->height, t->top_y(), defaultRowHeight());
407 }
408
409
410 void BufferView::Pimpl::workAreaKeyPress(LyXKeySymPtr key,
411                                          key_modifier::state state)
412 {
413         bv_->owner()->getLyXFunc().processKeySym(key, state);
414 }
415
416
417 void BufferView::Pimpl::selectionRequested()
418 {
419         static string sel;
420
421         if (!available())
422                 return;
423
424         LyXText * text = bv_->getLyXText();
425
426         if (text->selection.set() &&
427                 (!bv_->text->xsel_cache.set() ||
428                  text->selection.start != bv_->text->xsel_cache.start ||
429                  text->selection.end != bv_->text->xsel_cache.end))
430         {
431                 bv_->text->xsel_cache = text->selection;
432                 sel = text->selectionAsString(bv_->buffer(), false);
433         } else if (!text->selection.set()) {
434                 sel = string();
435                 bv_->text->xsel_cache.set(false);
436         }
437         if (!sel.empty()) {
438                 workarea().putClipboard(sel);
439         }
440 }
441
442
443 void BufferView::Pimpl::selectionLost()
444 {
445         if (available()) {
446                 hideCursor();
447                 toggleSelection();
448                 bv_->getLyXText()->clearSelection();
449                 showCursor();
450                 bv_->text->xsel_cache.set(false);
451         }
452 }
453
454
455 void BufferView::Pimpl::workAreaResize()
456 {
457         static int work_area_width;
458         static int work_area_height;
459
460         bool const widthChange = workarea().workWidth() != work_area_width;
461         bool const heightChange = workarea().workHeight() != work_area_height;
462
463         // update from work area
464         work_area_width = workarea().workWidth();
465         work_area_height = workarea().workHeight();
466
467         if (buffer_ != 0) {
468                 if (widthChange) {
469                         // The visible LyXView need a resize
470                         resizeCurrentBuffer();
471
472                         // Remove all texts from the textcache
473                         // This is not _really_ what we want to do. What
474                         // we really want to do is to delete in textcache
475                         // that does not have a BufferView with matching
476                         // width, but as long as we have only one BufferView
477                         // deleting all gives the same result.
478                         if (lyxerr.debugging())
479                                 textcache.show(lyxerr, "Expose delete all");
480                         textcache.clear();
481                         // FIXME: this is already done in resizeCurrentBuffer() ??
482                         buffer_->resizeInsets(bv_);
483                 } else if (heightChange) {
484                         // fitCursor() ensures we don't jump back
485                         // to the start of the document on vertical
486                         // resize
487                         fitCursor();
488                 }
489         }
490
491         if (widthChange || heightChange) {
492                 repaint();
493         }
494
495         // always make sure that the scrollbar is sane.
496         updateScrollbar();
497         owner_->updateLayoutChoice();
498         return;
499 }
500
501
502 void BufferView::Pimpl::update()
503 {
504         if (!bv_->theLockingInset() || !bv_->theLockingInset()->nodraw()) {
505                 screen().update(*bv_);
506                 bool fitc = false;
507                 while (bv_->text->status() == LyXText::CHANGED_IN_DRAW) {
508                         bv_->text->fullRebreak();
509                         bv_->text->setCursor(bv_->text->cursor.par(),
510                                              bv_->text->cursor.pos());
511                         if (bv_->text->selection.set()) {
512                                 bv_->text->setCursor(bv_->text->selection.start,
513                                                      bv_->text->selection.start.par(),
514                                                      bv_->text->selection.start.pos());
515                                 bv_->text->setCursor(bv_->text->selection.end,
516                                                      bv_->text->selection.end.par(),
517                                                      bv_->text->selection.end.pos());
518                         }
519                         fitc = true;
520                         bv_->text->postPaint(0);
521                         screen().update(*bv_);
522                 }
523
524                 // do this here instead of in the screen::update because of
525                 // the above loop!
526                 bv_->text->clearPaint();
527
528                 if (fitc)
529                         fitCursor();
530         }
531 }
532
533
534 void BufferView::Pimpl::update(LyXText * text, BufferView::UpdateCodes f)
535 {
536         if (!text->selection.set() && (f & SELECT)) {
537                 text->selection.cursor = text->cursor;
538         }
539
540         text->fullRebreak();
541
542         if (text->inset_owner) {
543                 text->inset_owner->setUpdateStatus(bv_, InsetText::NONE);
544                 updateInset(text->inset_owner);
545         } else {
546                 update();
547         }
548 }
549
550
551 void BufferView::Pimpl::update(BufferView::UpdateCodes f)
552 {
553         LyXText * text = bv_->text;
554
555         if (!text->selection.set() && (f & SELECT)) {
556                 text->selection.cursor = text->cursor;
557         }
558
559         text->fullRebreak();
560
561         if (text->inset_owner) {
562                 text->inset_owner->setUpdateStatus(bv_, InsetText::NONE);
563                 updateInset(text->inset_owner);
564         } else {
565                 update();
566         }
567 }
568
569
570 // Callback for cursor timer
571 void BufferView::Pimpl::cursorToggle()
572 {
573         if (!buffer_) {
574                 cursor_timeout.restart();
575                 return;
576         }
577
578         if (!bv_->theLockingInset()) {
579                 screen().cursorToggle(bv_);
580         } else {
581                 bv_->theLockingInset()->toggleInsetCursor(bv_);
582         }
583
584         cursor_timeout.restart();
585 }
586
587
588 bool BufferView::Pimpl::available() const
589 {
590         if (buffer_ && bv_->text)
591                 return true;
592         return false;
593 }
594
595
596 Change const BufferView::Pimpl::getCurrentChange()
597 {
598         if (!bv_->buffer()->params.tracking_changes)
599                 return Change(Change::UNCHANGED);
600
601         LyXText * t(bv_->getLyXText());
602
603         if (!t->selection.set())
604                 return Change(Change::UNCHANGED);
605
606         LyXCursor const & cur(t->selection.start);
607         return cur.par()->lookupChangeFull(cur.pos());
608 }
609
610
611 void BufferView::Pimpl::beforeChange(LyXText * text)
612 {
613         toggleSelection();
614         text->clearSelection();
615 }
616
617
618 void BufferView::Pimpl::savePosition(unsigned int i)
619 {
620         if (i >= saved_positions_num)
621                 return;
622         saved_positions[i] = Position(buffer_->fileName(),
623                                       bv_->text->cursor.par()->id(),
624                                       bv_->text->cursor.pos());
625         if (i > 0) {
626                 ostringstream str;
627 #if USE_BOOST_FORMAT
628                 str << boost::format(_("Saved bookmark %1$d")) % i;
629 #else
630                 str << _("Saved bookmark ") << i;
631 #endif
632                 owner_->message(STRCONV(str.str()));
633         }
634 }
635
636
637 void BufferView::Pimpl::restorePosition(unsigned int i)
638 {
639         if (i >= saved_positions_num)
640                 return;
641
642         string const fname = saved_positions[i].filename;
643
644         beforeChange(bv_->text);
645
646         if (fname != buffer_->fileName()) {
647                 Buffer * b = bufferlist.exists(fname) ?
648                         bufferlist.getBuffer(fname) :
649                         bufferlist.loadLyXFile(fname); // don't ask, just load it
650                 if (b != 0) buffer(b);
651         }
652
653         Paragraph * par = buffer_->getParFromID(saved_positions[i].par_id);
654         if (!par)
655                 return;
656
657         bv_->text->setCursor(par,
658                              min(par->size(), saved_positions[i].par_pos));
659
660         update(BufferView::SELECT);
661         if (i > 0) {
662                 ostringstream str;
663 #if USE_BOOST_FORMAT
664                 str << boost::format(_("Moved to bookmark %1$d")) % i;
665 #else
666                 str << _("Moved to bookmark ") << i;
667 #endif
668                 owner_->message(STRCONV(str.str()));
669         }
670 }
671
672
673 bool BufferView::Pimpl::isSavedPosition(unsigned int i)
674 {
675         if (i >= saved_positions_num)
676                 return false;
677
678         return !saved_positions[i].filename.empty();
679 }
680
681
682 void BufferView::Pimpl::switchKeyMap()
683 {
684         if (!lyxrc.rtl_support)
685                 return;
686
687         LyXText * text = bv_->getLyXText();
688         if (text->real_current_font.isRightToLeft()
689             && !(bv_->theLockingInset()
690                  && bv_->theLockingInset()->lyxCode() == Inset::ERT_CODE))
691         {
692                 if (owner_->getIntl().keymap == Intl::PRIMARY)
693                         owner_->getIntl().KeyMapSec();
694         } else {
695                 if (owner_->getIntl().keymap == Intl::SECONDARY)
696                         owner_->getIntl().KeyMapPrim();
697         }
698 }
699
700
701 void BufferView::Pimpl::insetUnlock()
702 {
703         if (bv_->theLockingInset()) {
704                 bv_->theLockingInset()->insetUnlock(bv_);
705                 bv_->theLockingInset(0);
706                 finishUndo();
707         }
708 }
709
710
711 void BufferView::Pimpl::showCursor()
712 {
713         if (bv_->theLockingInset())
714                 bv_->theLockingInset()->showInsetCursor(bv_);
715         else
716                 screen().showCursor(bv_->text, bv_);
717 }
718
719
720 void BufferView::Pimpl::hideCursor()
721 {
722         if (!bv_->theLockingInset())
723                 screen().hideCursor();
724 }
725
726
727 void BufferView::Pimpl::toggleSelection(bool b)
728 {
729         if (bv_->theLockingInset())
730                 bv_->theLockingInset()->toggleSelection(bv_, b);
731         screen().toggleSelection(bv_->text, bv_, b);
732 }
733
734
735 void BufferView::Pimpl::toggleToggle()
736 {
737         screen().toggleToggle(bv_->text, bv_);
738 }
739
740
741 void BufferView::Pimpl::center()
742 {
743         LyXText * t = bv_->text;
744
745         beforeChange(t);
746         int const half_height = workarea().workHeight() / 2;
747         int new_y = 0;
748
749         if (t->cursor.y() > half_height) {
750                 new_y = t->cursor.y() - half_height;
751         }
752
753         // FIXME: look at this comment again ...
754
755         // FIXME: can we do this w/o calling screen directly ?
756         // This updates top_y() but means the fitCursor() call
757         // from the update(FITCUR) doesn't realise that we might
758         // have moved (e.g. from GOTOPARAGRAPH), so doesn't cause
759         // the scrollbar to be updated as it should, so we have
760         // to do it manually. Any operation that does a center()
761         // and also might have moved top_y() must make sure to call
762         // updateScrollbar() currently. Never mind that this is a
763         // pretty obfuscated way of updating t->top_y()
764         screen().draw(t, bv_, new_y);
765
766         update(BufferView::SELECT);
767 }
768
769
770 void BufferView::Pimpl::stuffClipboard(string const & stuff) const
771 {
772         workarea().putClipboard(stuff);
773 }
774
775
776 /*
777  * Dispatch functions for actions which can be valid for BufferView->text
778  * and/or InsetText->text!!!
779  */
780
781
782 Inset * BufferView::Pimpl::getInsetByCode(Inset::Code code)
783 {
784 #if 0
785         LyXCursor cursor = bv_->getLyXText()->cursor;
786         Buffer::inset_iterator it =
787                 find_if(Buffer::inset_iterator(
788                         cursor.par(), cursor.pos()),
789                         buffer_->inset_iterator_end(),
790                         lyx::compare_memfun(&Inset::lyxCode, code));
791         return it != buffer_->inset_iterator_end() ? (*it) : 0;
792 #else
793         // Ok, this is a little bit too brute force but it
794         // should work for now. Better infrastructure is comming. (Lgb)
795
796         Buffer * b = bv_->buffer();
797         LyXCursor cursor = bv_->getLyXText()->cursor;
798
799         Buffer::inset_iterator beg = b->inset_iterator_begin();
800         Buffer::inset_iterator end = b->inset_iterator_end();
801
802         bool cursor_par_seen = false;
803
804         for (; beg != end; ++beg) {
805                 if (beg.getPar() == cursor.par()) {
806                         cursor_par_seen = true;
807                 }
808                 if (cursor_par_seen) {
809                         if (beg.getPar() == cursor.par()
810                             && beg.getPos() >= cursor.pos()) {
811                                 break;
812                         } else if (beg.getPar() != cursor.par()) {
813                                 break;
814                         }
815                 }
816
817         }
818         if (beg != end) {
819                 // Now find the first inset that matches code.
820                 for (; beg != end; ++beg) {
821                         if (beg->lyxCode() == code) {
822                                 return &(*beg);
823                         }
824                 }
825         }
826         return 0;
827 #endif
828 }
829
830
831 void BufferView::Pimpl::MenuInsertLyXFile(string const & filen)
832 {
833         string filename = filen;
834
835         if (filename.empty()) {
836                 // Launch a file browser
837                 string initpath = lyxrc.document_path;
838
839                 if (available()) {
840                         string const trypath = owner_->buffer()->filePath();
841                         // If directory is writeable, use this as default.
842                         if (IsDirWriteable(trypath))
843                                 initpath = trypath;
844                 }
845
846                 FileDialog fileDlg(_("Select LyX document to insert"),
847                         LFUN_FILE_INSERT,
848                         make_pair(string(_("Documents|#o#O")),
849                                   string(lyxrc.document_path)),
850                         make_pair(string(_("Examples|#E#e")),
851                                   string(AddPath(system_lyxdir, "examples"))));
852
853                 FileDialog::Result result =
854                         fileDlg.open(initpath,
855                                        _("*.lyx| LyX Documents (*.lyx)"));
856
857                 if (result.first == FileDialog::Later)
858                         return;
859
860                 filename = result.second;
861
862                 // check selected filename
863                 if (filename.empty()) {
864                         owner_->message(_("Canceled."));
865                         return;
866                 }
867         }
868
869         // get absolute path of file and add ".lyx" to the filename if
870         // necessary
871         filename = FileSearch(string(), filename, "lyx");
872
873         string const disp_fn(MakeDisplayPath(filename));
874
875         ostringstream s1;
876 #if USE_BOOST_FORMAT
877         s1 << boost::format(_("Inserting document %1$s...")) % disp_fn;
878 #else
879         s1 << _("Inserting document ") << disp_fn << _("...");
880 #endif
881         owner_->message(STRCONV(s1.str()));
882         bool const res = bv_->insertLyXFile(filename);
883         if (res) {
884                 ostringstream str;
885 #if USE_BOOST_FORMAT
886                 str << boost::format(_("Document %1$s inserted.")) % disp_fn;
887 #else
888                 str << _("Document ") << disp_fn << _(" inserted.");
889 #endif
890                 owner_->message(STRCONV(str.str()));
891         } else {
892                 ostringstream str;
893 #if USE_BOOST_FORMAT
894                 str << boost::format(_("Could not insert document %1$s")) % disp_fn;
895 #else
896                 str << _("Could not insert document ") << disp_fn;
897 #endif
898                 owner_->message(STRCONV(str.str()));
899         }
900 }
901
902
903 void BufferView::Pimpl::trackChanges()
904 {
905         Buffer * buf(bv_->buffer());
906         bool const tracking(buf->params.tracking_changes);
907
908         if (!tracking) {
909                 ParIterator const end = buf->par_iterator_end();
910                 for (ParIterator it = buf->par_iterator_begin(); it != end; ++it) {
911                         (*it)->trackChanges();
912                 }
913                 buf->params.tracking_changes = true;
914
915                 // we cannot allow undos beyond the freeze point
916                 buf->undostack.clear();
917         } else {
918                 update(BufferView::SELECT);
919                 bv_->text->setCursor(&(*buf->paragraphs.begin()), 0);
920 #warning changes FIXME
921                 //moveCursorUpdate(false);
922
923                 bool found = lyxfind::findNextChange(bv_);
924                 if (found) {
925                         owner_->getDialogs().show("changes");
926                         return;
927                 }
928
929                 ParIterator const end = buf->par_iterator_end();
930                 for (ParIterator it = buf->par_iterator_begin(); it != end; ++it) {
931                         (*it)->untrackChanges();
932                 }
933                 buf->params.tracking_changes = false;
934         }
935
936         buf->redostack.clear();
937 }
938
939
940 bool BufferView::Pimpl::dispatch(FuncRequest const & ev_in)
941 {
942         // Make sure that the cached BufferView is correct.
943         FuncRequest ev = ev_in;
944         ev.setView(bv_);
945
946         lyxerr[Debug::ACTION] << "BufferView::Pimpl::Dispatch:"
947                 << " action[" << ev.action << ']'
948                 << " arg[" << ev.argument << ']'
949                 << " x[" << ev.x << ']'
950                 << " y[" << ev.y << ']'
951                 << " button[" << ev.button() << ']'
952                 << endl;
953
954         // e.g. Qt mouse press when no buffer
955         if (!buffer_)
956                 return false;
957
958         LyXTextClass const & tclass = buffer_->params.getLyXTextClass();
959
960         switch (ev.action) {
961
962         case LFUN_SCROLL_INSET:
963                 // this is not handled here as this function is only active
964                 // if we have a locking_inset and that one is (or contains)
965                 // a tabular-inset
966                 break;
967
968         case LFUN_LAYOUT_COPY:
969                 bv_->copyEnvironment();
970                 break;
971
972         case LFUN_LAYOUT_PASTE:
973                 bv_->pasteEnvironment();
974                 switchKeyMap();
975                 break;
976
977         case LFUN_FILE_INSERT:
978                 MenuInsertLyXFile(ev.argument);
979                 break;
980
981         case LFUN_FILE_INSERT_ASCII_PARA:
982                 InsertAsciiFile(bv_, ev.argument, true);
983                 break;
984
985         case LFUN_FILE_INSERT_ASCII:
986                 InsertAsciiFile(bv_, ev.argument, false);
987                 break;
988
989         case LFUN_LANGUAGE:
990                 lang(bv_, ev.argument);
991                 switchKeyMap();
992                 owner_->view_state_changed();
993                 break;
994
995         case LFUN_EMPH:
996                 emph(bv_);
997                 owner_->view_state_changed();
998                 break;
999
1000         case LFUN_BOLD:
1001                 bold(bv_);
1002                 owner_->view_state_changed();
1003                 break;
1004
1005         case LFUN_NOUN:
1006                 noun(bv_);
1007                 owner_->view_state_changed();
1008                 break;
1009
1010         case LFUN_CODE:
1011                 code(bv_);
1012                 owner_->view_state_changed();
1013                 break;
1014
1015         case LFUN_SANS:
1016                 sans(bv_);
1017                 owner_->view_state_changed();
1018                 break;
1019
1020         case LFUN_ROMAN:
1021                 roman(bv_);
1022                 owner_->view_state_changed();
1023                 break;
1024
1025         case LFUN_DEFAULT:
1026                 styleReset(bv_);
1027                 owner_->view_state_changed();
1028                 break;
1029
1030         case LFUN_UNDERLINE:
1031                 underline(bv_);
1032                 owner_->view_state_changed();
1033                 break;
1034
1035         case LFUN_FONT_SIZE:
1036                 fontSize(bv_, ev.argument);
1037                 owner_->view_state_changed();
1038                 break;
1039
1040         case LFUN_FONT_STATE:
1041                 owner_->getLyXFunc().setMessage(currentState(bv_));
1042                 break;
1043
1044         case LFUN_INSERT_LABEL: {
1045                 // Try and generate a valid label
1046                 string const contents = ev.argument.empty() ?
1047                         getPossibleLabel(*bv_) : ev.argument;
1048                 InsetCommandParams icp("label", contents);
1049                 string data = InsetCommandMailer::params2string("label", icp);
1050                 owner_->getDialogs().show("label", data, 0);
1051         }
1052         break;
1053
1054         case LFUN_BOOKMARK_SAVE:
1055                 savePosition(strToUnsignedInt(ev.argument));
1056                 break;
1057
1058         case LFUN_BOOKMARK_GOTO:
1059                 restorePosition(strToUnsignedInt(ev.argument));
1060                 break;
1061
1062         case LFUN_REF_GOTO:
1063         {
1064                 string label = ev.argument;
1065                 if (label.empty()) {
1066                         InsetRef * inset =
1067                                 static_cast<InsetRef*>(getInsetByCode(Inset::REF_CODE));
1068                         if (inset) {
1069                                 label = inset->getContents();
1070                                 savePosition(0);
1071                         }
1072                 }
1073
1074                 if (!label.empty()) {
1075                         //bv_->savePosition(0);
1076                         if (!bv_->gotoLabel(label))
1077                                 Alert::alert(_("Error"),
1078                                            _("Couldn't find this label"),
1079                                            _("in current document."));
1080                 }
1081         }
1082         break;
1083
1084         // --- accented characters ---------------------------
1085
1086         case LFUN_UMLAUT:
1087         case LFUN_CIRCUMFLEX:
1088         case LFUN_GRAVE:
1089         case LFUN_ACUTE:
1090         case LFUN_TILDE:
1091         case LFUN_CEDILLA:
1092         case LFUN_MACRON:
1093         case LFUN_DOT:
1094         case LFUN_UNDERDOT:
1095         case LFUN_UNDERBAR:
1096         case LFUN_CARON:
1097         case LFUN_SPECIAL_CARON:
1098         case LFUN_BREVE:
1099         case LFUN_TIE:
1100         case LFUN_HUNG_UMLAUT:
1101         case LFUN_CIRCLE:
1102         case LFUN_OGONEK:
1103                 if (ev.argument.empty()) {
1104                         // As always...
1105                         owner_->getLyXFunc().handleKeyFunc(ev.action);
1106                 } else {
1107                         owner_->getLyXFunc().handleKeyFunc(ev.action);
1108                         owner_->getIntl().getTransManager()
1109                                 .TranslateAndInsert(ev.argument[0], bv_->getLyXText());
1110                         update(bv_->getLyXText(), BufferView::SELECT);
1111                 }
1112                 break;
1113
1114         case LFUN_MATH_MACRO:
1115         case LFUN_MATH_DELIM:
1116         case LFUN_INSERT_MATRIX:
1117         case LFUN_INSERT_MATH:
1118         case LFUN_MATH_IMPORT_SELECTION: // Imports LaTeX from the X selection
1119         case LFUN_MATH_DISPLAY:          // Open or create a displayed math inset
1120         case LFUN_MATH_MODE:             // Open or create an inlined math inset
1121         case LFUN_GREEK:                 // Insert a single greek letter
1122                 mathDispatch(ev);
1123                 break;
1124
1125         case LFUN_INSET_APPLY: {
1126                 string const name = ev.getArg(0);
1127
1128                 InsetBase * base = owner_->getDialogs().getOpenInset(name);
1129                 if (base) {
1130                         // This works both for 'original' and 'mathed' insets.
1131                         // Note that the localDispatch performs updateInset
1132                         // also.
1133                         FuncRequest fr(bv_, LFUN_INSET_MODIFY, ev.argument);
1134                         base->localDispatch(fr);
1135                 } else {
1136                         Inset * inset = createInset(ev);
1137                         if (inset && insertInset(inset)) {
1138                                 updateInset(inset);
1139                         } else {
1140                                 delete inset;
1141                         }
1142                 }
1143
1144                 if (name == "bibitem") {
1145                         // We need to do a redraw because the maximum
1146                         // InsetBibitem width could have changed
1147 #warning please check you mean repaint() not update(),
1148 #warning and whether the repaint() is needed at all
1149                         bv_->repaint();
1150                         bv_->fitCursor();
1151                 }
1152         }
1153         break;
1154
1155         case LFUN_FLOAT_LIST:
1156                 if (tclass.floats().typeExist(ev.argument)) {
1157                         Inset * inset = new InsetFloatList(ev.argument);
1158                         if (!insertInset(inset, tclass.defaultLayoutName()))
1159                                 delete inset;
1160                 } else {
1161                         lyxerr << "Non-existent float type: "
1162                                << ev.argument << endl;
1163                 }
1164                 break;
1165
1166         case LFUN_LAYOUT_PARAGRAPH: {
1167                 Paragraph const * par = bv_->getLyXText()->cursor.par();
1168                 if (!par)
1169                         break;
1170
1171                 string data;
1172                 params2string(*par, data);
1173
1174                 data = "show\n" + data;
1175                 bv_->owner()->getDialogs().show("paragraph", data);
1176                 break;
1177         }
1178
1179         case LFUN_PARAGRAPH_UPDATE: {
1180                 Paragraph const * par = bv_->getLyXText()->cursor.par();
1181                 if (!par)
1182                         break;
1183
1184                 string data;
1185                 params2string(*par, data);
1186
1187                 // Will the paragraph accept changes from the dialog?
1188                 Inset * const inset = par->inInset();
1189                 bool const accept =
1190                         !(inset && inset->forceDefaultParagraphs(inset));
1191
1192                 data = "update " + tostr(accept) + '\n' + data;
1193                 bv_->owner()->getDialogs().update("paragraph", data);
1194                 break;
1195         }
1196
1197         case LFUN_PARAGRAPH_APPLY:
1198                 setParagraphParams(*bv_, ev.argument);
1199                 break;
1200
1201         case LFUN_THESAURUS_ENTRY:
1202         {
1203                 string arg = ev.argument;
1204
1205                 if (arg.empty()) {
1206                         arg = bv_->getLyXText()->selectionAsString(buffer_,
1207                                                                    false);
1208
1209                         // FIXME
1210                         if (arg.size() > 100 || arg.empty()) {
1211                                 // Get word or selection
1212                                 bv_->getLyXText()->selectWordWhenUnderCursor(LyXText::WHOLE_WORD);
1213                                 arg = bv_->getLyXText()->selectionAsString(buffer_, false);
1214                                 // FIXME: where is getLyXText()->unselect(bv_) ?
1215                         }
1216                 }
1217
1218                 bv_->owner()->getDialogs().showThesaurus(arg);
1219         }
1220                 break;
1221
1222         case LFUN_TRACK_CHANGES:
1223                 trackChanges();
1224                 break;
1225
1226         case LFUN_MERGE_CHANGES:
1227                 owner_->getDialogs().show("changes");
1228                 break;
1229
1230         case LFUN_ACCEPT_ALL_CHANGES: {
1231                 update(BufferView::SELECT);
1232                 bv_->text->setCursor(&(*bv_->buffer()->paragraphs.begin()), 0);
1233 #warning FIXME changes
1234                 //moveCursorUpdate(false);
1235
1236                 while (lyxfind::findNextChange(bv_)) {
1237                         bv_->getLyXText()->acceptChange();
1238                 }
1239                 update(BufferView::SELECT);
1240                 break;
1241         }
1242
1243         case LFUN_REJECT_ALL_CHANGES: {
1244                 update(BufferView::SELECT);
1245                 bv_->text->setCursor(&(*bv_->buffer()->paragraphs.begin()), 0);
1246 #warning FIXME changes
1247                 //moveCursorUpdate(false);
1248
1249                 while (lyxfind::findNextChange(bv_)) {
1250                         bv_->getLyXText()->rejectChange();
1251                 }
1252                 update(BufferView::SELECT);
1253                 break;
1254         }
1255
1256         case LFUN_ACCEPT_CHANGE: {
1257                 bv_->getLyXText()->acceptChange();
1258                 update(BufferView::SELECT);
1259                 break;
1260         }
1261
1262         case LFUN_REJECT_CHANGE: {
1263                 bv_->getLyXText()->rejectChange();
1264                 update(BufferView::SELECT);
1265                 break;
1266         }
1267
1268         case LFUN_UNKNOWN_ACTION:
1269                 ev.errorMessage(N_("Unknown function!"));
1270                 break;
1271
1272         default:
1273                 return bv_->getLyXText()->dispatch(FuncRequest(ev, bv_));
1274         } // end of switch
1275
1276         return true;
1277 }
1278
1279
1280 bool BufferView::Pimpl::insertInset(Inset * inset, string const & lout)
1281 {
1282         // if we are in a locking inset we should try to insert the
1283         // inset there otherwise this is a illegal function now
1284         if (bv_->theLockingInset()) {
1285                 if (bv_->theLockingInset()->insetAllowed(inset))
1286                         return bv_->theLockingInset()->insertInset(bv_, inset);
1287                 return false;
1288         }
1289
1290         // not quite sure if we want this...
1291         setCursorParUndo(bv_);
1292         freezeUndo();
1293
1294         beforeChange(bv_->text);
1295         if (!lout.empty()) {
1296                 update(BufferView::SELECT);
1297                 bv_->text->breakParagraph(bv_->buffer()->paragraphs);
1298                 update(BufferView::SELECT);
1299
1300                 if (!bv_->text->cursor.par()->empty()) {
1301                         bv_->text->cursorLeft(bv_);
1302
1303                         bv_->text->breakParagraph(bv_->buffer()->paragraphs);
1304                         update(BufferView::SELECT);
1305                 }
1306
1307                 string lres = lout;
1308                 LyXTextClass const & tclass =
1309                         buffer_->params.getLyXTextClass();
1310                 bool hasLayout = tclass.hasLayout(lres);
1311                 string lay = tclass.defaultLayoutName();
1312
1313                 if (hasLayout != false) {
1314                         // layout found
1315                         lay = lres;
1316                 } else {
1317                         // layout not fount using default
1318                         lay = tclass.defaultLayoutName();
1319                 }
1320
1321                 bv_->text->setLayout(lay);
1322
1323                 bv_->text->setParagraph(0, 0,
1324                                    0, 0,
1325                                    VSpace(VSpace::NONE), VSpace(VSpace::NONE),
1326                                    Spacing(),
1327                                    LYX_ALIGN_LAYOUT,
1328                                    string(),
1329                                    0);
1330                 update(BufferView::SELECT);
1331         }
1332
1333         bv_->text->insertInset(inset);
1334         update(BufferView::SELECT);
1335
1336         unFreezeUndo();
1337         return true;
1338 }
1339
1340
1341 void BufferView::Pimpl::updateInset(Inset * inset)
1342 {
1343         if (!inset || !available())
1344                 return;
1345
1346         // first check for locking insets
1347         if (bv_->theLockingInset()) {
1348                 if (bv_->theLockingInset() == inset) {
1349                         if (bv_->text->updateInset(inset)) {
1350                                 update();
1351                                 updateScrollbar();
1352                                 return;
1353                         }
1354                 } else if (bv_->theLockingInset()->updateInsetInInset(bv_, inset)) {
1355                         if (bv_->text->updateInset(bv_->theLockingInset())) {
1356                                 update();
1357                                 updateScrollbar();
1358                                 return;
1359                         }
1360                 }
1361         }
1362
1363         // then check if the inset is a top_level inset (has no owner)
1364         // if yes do the update as always otherwise we have to update the
1365         // toplevel inset where this inset is inside
1366         Inset * tl_inset = inset;
1367         while (tl_inset->owner())
1368                 tl_inset = tl_inset->owner();
1369         hideCursor();
1370         if (tl_inset == inset) {
1371                 update(BufferView::UPDATE);
1372                 if (bv_->text->updateInset(inset)) {
1373                         update(BufferView::SELECT);
1374                         return;
1375                 }
1376         } else if (static_cast<UpdatableInset *>(tl_inset)
1377                            ->updateInsetInInset(bv_, inset))
1378         {
1379                 if (bv_->text->updateInset(tl_inset)) {
1380                         update();
1381                         updateScrollbar();
1382                 }
1383         }
1384 }