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