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