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