]> git.lyx.org Git - lyx.git/blob - src/BufferView_pimpl.C
7 out
[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 "lyxtext.h"
24 #include "lyxrow.h"
25 #include "paragraph.h"
26 #include "frontends/LyXView.h"
27 #include "commandtags.h"
28 #include "lyxfunc.h"
29 #include "debug.h"
30 #include "bufferview_funcs.h"
31 #include "TextCache.h"
32 #include "bufferlist.h"
33 #include "lyxrc.h"
34 #include "intl.h"
35 // added for Dispatch functions
36 #include "lyx_cb.h"
37 #include "lyx_main.h"
38 #include "FloatList.h"
39 #include "gettext.h"
40 #include "ParagraphParameters.h"
41 #include "undo_funcs.h"
42 #include "funcrequest.h"
43 #include "box.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/insetref.h"
51 #include "insets/insetparent.h"
52 #include "insets/insetindex.h"
53 #include "insets/insetinclude.h"
54 #include "insets/insetcite.h"
55 #include "insets/insetgraphics.h"
56 #include "insets/insetmarginal.h"
57 #include "insets/insetcaption.h"
58 #include "insets/insetfloatlist.h"
59
60 #include "mathed/formulabase.h"
61
62 #include "graphics/Previews.h"
63
64 #include "support/LAssert.h"
65 #include "support/lstrings.h"
66 #include "support/filetools.h"
67
68 #include <boost/bind.hpp>
69 #include <boost/signals/connection.hpp>
70
71 #include <unistd.h>
72 #include <sys/wait.h>
73
74
75 using std::vector;
76 using std::find_if;
77 using std::find;
78 using std::pair;
79 using std::endl;
80 using std::make_pair;
81 using std::min;
82
83 using lyx::pos_type;
84
85 /* the selection possible is needed, that only motion events are
86  * used, where the bottom press event was on the drawing area too */
87 bool selection_possible = false;
88
89 extern BufferList bufferlist;
90 extern int bibitemMaxWidth(BufferView *, LyXFont const &);
91
92
93 namespace {
94
95 unsigned int const saved_positions_num = 20;
96
97 // All the below connection objects are needed because of a bug in some
98 // versions of GCC (<=2.96 are on the suspects list.) By having and assigning
99 // to these connections we avoid a segfault upon startup, and also at exit.
100 // (Lgb)
101
102 boost::signals::connection timecon;
103 boost::signals::connection doccon;
104 boost::signals::connection resizecon;
105 boost::signals::connection bpresscon;
106 boost::signals::connection breleasecon;
107 boost::signals::connection motioncon;
108 boost::signals::connection doublecon;
109 boost::signals::connection triplecon;
110 boost::signals::connection kpresscon;
111 boost::signals::connection selectioncon;
112 boost::signals::connection lostcon;
113
114
115         /**
116          * Return the on-screen dimensions of the inset at the cursor.
117          * Pre-condition: the cursor must be at an inset.
118          */
119 Box insetDimensions(BufferView * bv, LyXText const & text,
120                                        LyXCursor const & cursor)
121 {
122         Paragraph /*const*/ & par = *cursor.par();
123         pos_type const pos = cursor.pos();
124
125         lyx::Assert(par.getInset(pos));
126
127         Inset const & inset(*par.getInset(pos));
128
129         LyXFont const & font = text.getFont(bv->buffer(), &par, pos);
130
131         int const width = inset.width(bv, font);
132         int const inset_x = font.isVisibleRightToLeft()
133                 ? (cursor.ix() - width) : cursor.ix();
134
135         return Box(
136                 inset_x + inset.scroll(),
137                 inset_x + width,
138                 cursor.iy() - inset.ascent(bv, font),
139                 cursor.iy() + inset.descent(bv, font));
140 }
141
142
143 /**
144  * check if the given co-ordinates are inside an inset at the
145  * given cursor, if one exists. If so, the inset is returned,
146  * and the co-ordinates are made relative. Otherwise, 0 is returned.
147  */
148 Inset * checkInset(BufferView * bv, LyXText const & text,
149                                       LyXCursor const & cursor, int & x, int & y)
150 {
151         pos_type const pos = cursor.pos();
152         Paragraph /*const*/ & par(*cursor.par());
153
154         if (pos >= par.size() || !par.isInset(pos)) {
155                 return 0;
156         }
157
158         Inset /*const*/ * inset = par.getInset(pos);
159
160         if (!isEditableInset(inset)) 
161                 return 0;
162
163         Box b = insetDimensions(bv, text, cursor);
164
165         if (!b.contained(x, y)) {
166                 lyxerr[Debug::GUI] << "Missed inset at x,y " << x << "," << y
167                         << " box " << b << endl;
168                 return 0;
169         }
170
171         text.setCursor(bv, &par, pos, true);
172
173         x -= b.x1;
174         // The origin of an inset is on the baseline
175         y -= text.cursor.iy();
176
177         return inset;
178 }
179
180 } // anon namespace
181
182
183 BufferView::Pimpl::Pimpl(BufferView * bv, LyXView * owner,
184              int xpos, int ypos, int width, int height)
185         : bv_(bv), owner_(owner), buffer_(0), cursor_timeout(400),
186           using_xterm_cursor(false)
187 {
188         workarea_.reset(WorkAreaFactory::create(xpos, ypos, width, height));
189         screen_.reset(LyXScreenFactory::create(workarea()));
190
191         // Setup the signals
192         doccon = workarea().scrollDocView
193                 .connect(boost::bind(&BufferView::Pimpl::scrollDocView, this, _1));
194         resizecon = workarea().workAreaResize
195                 .connect(boost::bind(&BufferView::Pimpl::workAreaResize, this));
196         bpresscon = workarea().workAreaButtonPress
197                 .connect(boost::bind(&BufferView::Pimpl::workAreaButtonPress, this, _1, _2, _3));
198         breleasecon = workarea().workAreaButtonRelease
199                 .connect(boost::bind(&BufferView::Pimpl::workAreaButtonRelease, this, _1, _2, _3));
200         motioncon = workarea().workAreaMotionNotify
201                 .connect(boost::bind(&BufferView::Pimpl::workAreaMotionNotify, this, _1, _2, _3));
202         doublecon = workarea().workAreaDoubleClick
203                 .connect(boost::bind(&BufferView::Pimpl::doubleClick, this, _1, _2, _3));
204         triplecon = workarea().workAreaTripleClick
205                 .connect(boost::bind(&BufferView::Pimpl::tripleClick, this, _1, _2, _3));
206         kpresscon = workarea().workAreaKeyPress
207                 .connect(boost::bind(&BufferView::Pimpl::workAreaKeyPress, this, _1, _2));
208         selectioncon = workarea().selectionRequested
209                 .connect(boost::bind(&BufferView::Pimpl::selectionRequested, this));
210         lostcon = workarea().selectionLost
211                 .connect(boost::bind(&BufferView::Pimpl::selectionLost, this));
212
213         timecon = cursor_timeout.timeout
214                 .connect(boost::bind(&BufferView::Pimpl::cursorToggle, this));
215         cursor_timeout.start();
216         saved_positions.resize(saved_positions_num);
217 }
218
219
220 WorkArea & BufferView::Pimpl::workarea() const
221 {
222         return *workarea_.get();
223 }
224
225
226 LyXScreen & BufferView::Pimpl::screen() const
227 {
228         return *screen_.get();
229 }
230
231
232 Painter & BufferView::Pimpl::painter() const
233 {
234         return workarea().getPainter();
235 }
236
237
238 void BufferView::Pimpl::buffer(Buffer * b)
239 {
240         lyxerr[Debug::INFO] << "Setting buffer in BufferView ("
241                             << b << ")" << endl;
242         if (buffer_) {
243                 buffer_->delUser(bv_);
244
245                 // Put the old text into the TextCache, but
246                 // only if the buffer is still loaded.
247                 // Also set the owner of the test to 0
248                 //              bv_->text->owner(0);
249                 textcache.add(buffer_, workarea().workWidth(), bv_->text);
250                 if (lyxerr.debugging())
251                         textcache.show(lyxerr, "BufferView::buffer");
252
253                 bv_->text = 0;
254         }
255
256         // set current buffer
257         buffer_ = b;
258
259         if (bufferlist.getState() == BufferList::CLOSING) return;
260
261         // if we are closing the buffer, use the first buffer as current
262         if (!buffer_) {
263                 buffer_ = bufferlist.first();
264         }
265
266         if (buffer_) {
267                 lyxerr[Debug::INFO] << "Buffer addr: " << buffer_ << endl;
268                 buffer_->addUser(bv_);
269
270                 // If we don't have a text object for this, we make one
271                 if (bv_->text == 0) {
272                         resizeCurrentBuffer();
273                 }
274
275                 // FIXME: needed when ?
276                 bv_->text->first_y =
277                         screen().topCursorVisible(bv_->text->cursor, bv_->text->first_y);
278
279                 // Similarly, buffer-dependent dialogs should be updated or
280                 // hidden. This should go here because some dialogs (eg ToC)
281                 // require bv_->text.
282                 owner_->getDialogs().updateBufferDependent(true);
283         } else {
284                 lyxerr[Debug::INFO] << "  No Buffer!" << endl;
285                 owner_->getDialogs().hideBufferDependent();
286
287                 // Also remove all remaining text's from the testcache.
288                 // (there should not be any!) (if there is any it is a
289                 // bug!)
290                 if (lyxerr.debugging())
291                         textcache.show(lyxerr, "buffer delete all");
292                 textcache.clear();
293         }
294
295         repaint();
296         updateScrollbar();
297         owner_->updateMenubar();
298         owner_->updateToolbar();
299         owner_->updateLayoutChoice();
300         owner_->updateWindowTitle();
301
302         if (grfx::Previews::activated() && buffer_)
303                 grfx::Previews::get().generateBufferPreviews(*buffer_);
304 }
305
306
307 bool BufferView::Pimpl::fitCursor()
308 {
309         bool ret;
310
311         if (bv_->theLockingInset()) {
312                 bv_->theLockingInset()->fitInsetCursor(bv_);
313                 ret = true;
314         } else {
315                 ret = screen().fitCursor(bv_->text, bv_);
316         }
317
318         bv_->owner()->getDialogs().updateParagraph();
319         if (ret)
320                 updateScrollbar();
321         return ret;
322 }
323
324
325 void BufferView::Pimpl::redoCurrentBuffer()
326 {
327         lyxerr[Debug::INFO] << "BufferView::redoCurrentBuffer" << endl;
328         if (buffer_ && bv_->text) {
329                 resizeCurrentBuffer();
330                 updateScrollbar();
331                 owner_->updateLayoutChoice();
332                 repaint();
333         }
334 }
335
336
337 int BufferView::Pimpl::resizeCurrentBuffer()
338 {
339         lyxerr[Debug::INFO] << "resizeCurrentBuffer" << endl;
340
341         Paragraph * par = 0;
342         Paragraph * selstartpar = 0;
343         Paragraph * selendpar = 0;
344         UpdatableInset * the_locking_inset = 0;
345
346         pos_type pos = 0;
347         pos_type selstartpos = 0;
348         pos_type selendpos = 0;
349         bool selection = false;
350         bool mark_set  = false;
351
352         owner_->prohibitInput();
353
354         owner_->message(_("Formatting document..."));
355
356         if (bv_->text) {
357                 par = bv_->text->cursor.par();
358                 pos = bv_->text->cursor.pos();
359                 selstartpar = bv_->text->selection.start.par();
360                 selstartpos = bv_->text->selection.start.pos();
361                 selendpar = bv_->text->selection.end.par();
362                 selendpos = bv_->text->selection.end.pos();
363                 selection = bv_->text->selection.set();
364                 mark_set = bv_->text->selection.mark();
365                 the_locking_inset = bv_->theLockingInset();
366                 buffer_->resizeInsets(bv_);
367                 // I don't think the delete and new are necessary here we just could
368                 // call only init! (Jug 20020419)
369                 delete bv_->text;
370                 bv_->text = new LyXText(bv_);
371                 bv_->text->init(bv_);
372         } else {
373                 // See if we have a text in TextCache that fits
374                 // the new buffer_ with the correct width.
375                 bv_->text = textcache.findFit(buffer_, workarea().workWidth());
376                 if (bv_->text) {
377                         if (lyxerr.debugging()) {
378                                 lyxerr << "Found a LyXText that fits:\n";
379                                 textcache.show(lyxerr, make_pair(buffer_, make_pair(workarea().workWidth(), bv_->text)));
380                         }
381                         // Set the owner of the newly found text
382                         //      bv_->text->owner(bv_);
383                         if (lyxerr.debugging())
384                                 textcache.show(lyxerr, "resizeCurrentBuffer");
385                 } else {
386                         bv_->text = new LyXText(bv_);
387                         bv_->text->init(bv_);
388                         //buffer_->resizeInsets(bv_);
389                 }
390         }
391
392         if (par) {
393                 bv_->text->selection.set(true);
394                 // At this point just to avoid the Delete-Empty-Paragraph-
395                 // Mechanism when setting the cursor.
396                 bv_->text->selection.mark(mark_set);
397                 if (selection) {
398                         bv_->text->setCursor(bv_, selstartpar, selstartpos);
399                         bv_->text->selection.cursor = bv_->text->cursor;
400                         bv_->text->setCursor(bv_, selendpar, selendpos);
401                         bv_->text->setSelection(bv_);
402                         bv_->text->setCursor(bv_, par, pos);
403                 } else {
404                         bv_->text->setCursor(bv_, par, pos);
405                         bv_->text->selection.cursor = bv_->text->cursor;
406                         bv_->text->selection.set(false);
407                 }
408                 // remake the inset locking
409                 bv_->theLockingInset(the_locking_inset);
410         }
411
412         bv_->text->first_y = screen().topCursorVisible(bv_->text->cursor, bv_->text->first_y);
413
414         switchKeyMap();
415         owner_->allowInput();
416
417         updateScrollbar();
418
419         return 0;
420 }
421
422
423 void BufferView::Pimpl::repaint()
424 {
425         // Regenerate the screen.
426         screen().redraw(bv_->text, bv_);
427 }
428
429
430 void BufferView::Pimpl::updateScrollbar()
431 {
432         if (!bv_->text) {
433                 lyxerr[Debug::GUI] << "no text in updateScrollbar" << endl;
434                 workarea().setScrollbarParams(0, 0, 0);
435                 return;
436         }
437
438         LyXText const & t = *bv_->text;
439
440         lyxerr[Debug::GUI] << "Updating scrollbar: h " << t.height << ", first_y "
441                 << t.first_y << ", default height " << t.defaultHeight() << endl;
442
443         workarea().setScrollbarParams(t.height, t.first_y, t.defaultHeight());
444 }
445
446
447 void BufferView::Pimpl::scrollDocView(int value)
448 {
449         lyxerr[Debug::GUI] << "scrollDocView of " << value << endl;
450
451         if (!buffer_) return;
452
453         screen().draw(bv_->text, bv_, value);
454
455         if (!lyxrc.cursor_follows_scrollbar) {
456                 return;
457         }
458
459         LyXText * vbt = bv_->text;
460
461         int const height = vbt->defaultHeight();
462         int const first = static_cast<int>((bv_->text->first_y + height));
463         int const last = static_cast<int>((bv_->text->first_y + workarea().workHeight() - height));
464
465         if (vbt->cursor.y() < first)
466                 vbt->setCursorFromCoordinates(bv_, 0, first);
467         else if (vbt->cursor.y() > last)
468                 vbt->setCursorFromCoordinates(bv_, 0, last);
469 }
470
471
472 int BufferView::Pimpl::scroll(long time)
473 {
474         if (!buffer_)
475                 return 0;
476
477         LyXText const * t = bv_->text;
478
479         double const diff = t->defaultHeight()
480                 + double(time) * double(time) * 0.125;
481
482         scrollDocView(int(diff));
483         workarea().setScrollbarParams(t->height, t->first_y, t->defaultHeight());
484         return 0;
485 }
486
487
488 void BufferView::Pimpl::workAreaKeyPress(LyXKeySymPtr key,
489                                          key_modifier::state state)
490 {
491         bv_->owner()->getLyXFunc().processKeySym(key, state);
492 }
493
494
495 void BufferView::Pimpl::workAreaMotionNotify(int x, int y, mouse_button::state state)
496 {
497         // Only use motion with button 1
498         if (!(state & mouse_button::button1))
499                 return;
500
501         if (!buffer_)
502                 return;
503
504         // Check for inset locking
505         if (bv_->theLockingInset()) {
506                 LyXCursor cursor = bv_->text->cursor;
507                 LyXFont font = bv_->text->getFont(buffer_,
508                                                   cursor.par(), cursor.pos());
509                 int width = bv_->theLockingInset()->width(bv_, font);
510                 int inset_x = font.isVisibleRightToLeft()
511                         ? cursor.ix() - width : cursor.ix();
512                 int start_x = inset_x + bv_->theLockingInset()->scroll();
513
514                 FuncRequest cmd(bv_, LFUN_MOUSE_MOTION,
515                                   x - start_x, y - cursor.iy() + bv_->text->first_y, state);
516                 bv_->theLockingInset()->localDispatch(cmd);
517                 return;
518         }
519
520         // The test for not selection possible is needed, that only motion
521         // events are used, where the bottom press event was on
522         //  the drawing area too
523         if (!selection_possible)
524                 return;
525
526         screen().hideCursor();
527
528         Row * cursorrow = bv_->text->cursor.row();
529         bv_->text->setCursorFromCoordinates(bv_, x, y + bv_->text->first_y);
530 #if 0
531         // sorry for this but I have a strange error that the y value jumps at
532         // a certain point. This seems like an error in my xforms library or
533         // in some other local environment, but I would like to leave this here
534         // for the moment until I can remove this (Jug 20020418)
535         if (y_before < bv_->text->cursor.y())
536                 lyxerr << y_before << ":" << bv_->text->cursor.y() << endl;
537 #endif
538         // This is to allow jumping over large insets
539         if (cursorrow == bv_->text->cursor.row()) {
540                 if (y >= int(workarea().workHeight())) {
541                         bv_->text->cursorDown(bv_, false);
542                 } else if (y < 0) {
543                         bv_->text->cursorUp(bv_, false);
544                 }
545         }
546
547         if (!bv_->text->selection.set())
548                 update(bv_->text, BufferView::UPDATE); // Maybe an empty line was deleted
549
550         bv_->text->setSelection(bv_);
551         screen().toggleToggle(bv_->text, bv_);
552         fitCursor();
553         showCursor();
554 }
555
556
557 // Single-click on work area
558 void BufferView::Pimpl::workAreaButtonPress(int xpos, int ypos,
559                                             mouse_button::state button)
560 {
561         if (!buffer_)
562                 return;
563
564         // ok ok, this is a hack (for xforms)
565         if (button == mouse_button::button4) {
566                 scroll(-lyxrc.wheel_jump);
567                 // We shouldn't go further down as we really should only do the
568                 // scrolling and be done with this. Otherwise we may open some
569                 // dialogs (Jug 20020424).
570                 return;
571         } else if (button == mouse_button::button5) {
572                 scroll(lyxrc.wheel_jump);
573                 // We shouldn't go further down as we really should only do the
574                 // scrolling and be done with this. Otherwise we may open some
575                 // dialogs (Jug 20020424).
576                 return;
577         }
578
579         Inset * inset_hit = checkInsetHit(bv_->text, xpos, ypos);
580
581         // Middle button press pastes if we have a selection
582         // We do this here as if the selection was inside an inset
583         // it could get cleared on the unlocking of the inset so
584         // we have to check this first
585         bool paste_internally = false;
586         if (button == mouse_button::button2 && bv_->getLyXText()->selection.set()) {
587                 owner_->dispatch(FuncRequest(LFUN_COPY));
588                 paste_internally = true;
589         }
590
591         int const screen_first = bv_->text->first_y;
592
593         if (bv_->theLockingInset()) {
594                 // We are in inset locking mode
595
596                 // Check whether the inset was hit. If not reset mode,
597                 // otherwise give the event to the inset
598                 if (inset_hit == bv_->theLockingInset()) {
599                         FuncRequest cmd(bv_, LFUN_MOUSE_PRESS, xpos, ypos, button);
600                         bv_->theLockingInset()->localDispatch(cmd);
601                         return;
602                 }
603                 bv_->unlockInset(bv_->theLockingInset());
604         }
605
606         if (!inset_hit)
607                 selection_possible = true;
608         screen().hideCursor();
609
610         // Clear the selection
611         screen().toggleSelection(bv_->text, bv_);
612         bv_->text->clearSelection();
613         bv_->text->fullRebreak(bv_);
614         update();
615         updateScrollbar();
616
617         // Single left click in math inset?
618         if (isHighlyEditableInset(inset_hit)) {
619                 // Highly editable inset, like math
620                 UpdatableInset * inset = static_cast<UpdatableInset *>(inset_hit);
621                 selection_possible = false;
622                 owner_->updateLayoutChoice();
623                 owner_->message(inset->editMessage());
624                 //inset->edit(bv_, xpos, ypos, button);
625                 // We just have to lock the inset before calling a PressEvent on it!
626                 // we don't need the edit() call here! (Jug20020329)
627                 if (!bv_->lockInset(inset)) {
628                         lyxerr[Debug::INSETS] << "Cannot lock inset" << endl;
629                 }
630                 FuncRequest cmd(bv_, LFUN_MOUSE_PRESS, xpos, ypos, button);
631                 inset->localDispatch(cmd);
632                 return;
633         }
634         // I'm not sure we should continue here if we hit an inset (Jug20020403)
635
636         // Right click on a footnote flag opens float menu
637         if (button == mouse_button::button3) {
638                 selection_possible = false;
639                 return;
640         }
641
642         if (!inset_hit) // otherwise it was already set in checkInsetHit(...)
643                 bv_->text->setCursorFromCoordinates(bv_, xpos, ypos + screen_first);
644         finishUndo();
645         bv_->text->selection.cursor = bv_->text->cursor;
646         bv_->text->cursor.x_fix(bv_->text->cursor.x());
647
648         owner_->updateLayoutChoice();
649         if (fitCursor()) {
650                 selection_possible = false;
651         }
652
653         // Insert primary selection with middle mouse
654         // if there is a local selection in the current buffer,
655         // insert this
656         if (button == mouse_button::button2) {
657                 if (paste_internally)
658                         owner_->dispatch(FuncRequest(LFUN_PASTE));
659                 else
660                         owner_->dispatch(FuncRequest(LFUN_PASTESELECTION, "paragraph"));
661                 selection_possible = false;
662                 return;
663         }
664 }
665
666
667 void BufferView::Pimpl::doubleClick(int /*x*/, int /*y*/, mouse_button::state button)
668 {
669         if (!buffer_)
670                 return;
671
672         LyXText * text = bv_->getLyXText();
673
674         if (text->bv_owner && bv_->theLockingInset())
675                 return;
676
677         if (button == mouse_button::button1) {
678                 if (text->bv_owner) {
679                         screen().hideCursor();
680                         screen().toggleSelection(text, bv_);
681                         text->selectWord(bv_, LyXText::WHOLE_WORD_STRICT);
682                         screen().toggleSelection(text, bv_, false);
683                 } else {
684                         text->selectWord(bv_, LyXText::WHOLE_WORD_STRICT);
685                 }
686                 // This will fit the cursor on the screen if necessary
687                 update(text, BufferView::SELECT|BufferView::FITCUR);
688                 workarea().haveSelection(bv_->getLyXText()->selection.set());
689         }
690 }
691
692
693 void BufferView::Pimpl::tripleClick(int /*x*/, int /*y*/, mouse_button::state button)
694 {
695         if (!buffer_)
696                 return;
697
698         LyXText * text = bv_->getLyXText();
699
700         if (text->bv_owner && bv_->theLockingInset())
701             return;
702
703         if (button == mouse_button::button1) {
704                 if (text->bv_owner) {
705                         screen().hideCursor();
706                         screen().toggleSelection(text, bv_);
707                 }
708                 text->cursorHome(bv_);
709                 text->selection.cursor = text->cursor;
710                 text->cursorEnd(bv_);
711                 text->setSelection(bv_);
712                 if (text->bv_owner) {
713                         screen().toggleSelection(text, bv_, false);
714                 }
715                 // This will fit the cursor on the screen if necessary
716                 update(text, BufferView::SELECT|BufferView::FITCUR);
717                 workarea().haveSelection(bv_->getLyXText()->selection.set());
718         }
719 }
720
721
722 void BufferView::Pimpl::selectionRequested()
723 {
724         static string sel;
725
726         if (!available())
727                 return;
728
729         LyXText * text = bv_->getLyXText();
730
731         if (text->selection.set() &&
732                 (!bv_->text->xsel_cache.set() ||
733                  text->selection.start != bv_->text->xsel_cache.start ||
734                  text->selection.end != bv_->text->xsel_cache.end))
735         {
736                 bv_->text->xsel_cache = text->selection;
737                 sel = text->selectionAsString(bv_->buffer(), false);
738         } else if (!text->selection.set()) {
739                 sel = string();
740                 bv_->text->xsel_cache.set(false);
741         }
742         if (!sel.empty()) {
743                 workarea().putClipboard(sel);
744         }
745 }
746
747
748 void BufferView::Pimpl::selectionLost()
749 {
750         if (available()) {
751                 hideCursor();
752                 toggleSelection();
753                 bv_->getLyXText()->clearSelection();
754                 showCursor();
755                 bv_->text->xsel_cache.set(false);
756         }
757 }
758
759
760 void BufferView::Pimpl::workAreaButtonRelease(int x, int y,
761                                               mouse_button::state button)
762 {
763         // do nothing if we used the mouse wheel
764         if (!buffer_ || button == mouse_button::button4 || button == mouse_button::button5)
765                 return;
766
767         // If we hit an inset, we have the inset coordinates in these
768         // and inset_hit points to the inset.  If we do not hit an
769         // inset, inset_hit is 0, and inset_x == x, inset_y == y.
770         Inset * inset_hit = checkInsetHit(bv_->text, x, y);
771
772         if (bv_->theLockingInset()) {
773                 // We are in inset locking mode.
774
775                 // LyX does a kind of work-area grabbing for insets.
776                 // Only a ButtonPress FuncRequest outside the inset will
777                 // force a insetUnlock.
778                 FuncRequest cmd(bv_, LFUN_MOUSE_RELEASE, x, y, button);
779                 bv_->theLockingInset()->localDispatch(cmd);
780                 return;
781         }
782
783         selection_possible = false;
784
785         if (button == mouse_button::button2)
786                 return;
787
788         // finish selection
789         if (button == mouse_button::button1) {
790                 workarea().haveSelection(bv_->getLyXText()->selection.set());
791         }
792
793         switchKeyMap();
794         owner_->view_state_changed();
795         owner_->updateMenubar();
796         owner_->updateToolbar();
797
798         // Did we hit an editable inset?
799         if (inset_hit) {
800                 selection_possible = false;
801
802                 // if we reach this point with a selection, it
803                 // must mean we are currently selecting.
804                 // But we don't want to open the inset
805                 // because that is annoying for the user.
806                 // So just pretend we didn't hit it.
807                 // this is OK because a "kosher" ButtonRelease
808                 // will follow a ButtonPress that clears
809                 // the selection.
810                 // Note this also fixes selection drawing
811                 // problems if we end up opening an inset
812                 if (bv_->getLyXText()->selection.set())
813                         return;
814
815                 // CHECK fix this proper in 0.13
816                 // well, maybe 13.0 !!!!!!!!!
817
818                 // Following a ref shouldn't issue
819                 // a push on the undo-stack
820                 // anylonger, now that we have
821                 // keybindings for following
822                 // references and returning from
823                 // references.  IMHO though, it
824                 // should be the inset's own business
825                 // to push or not push on the undo
826                 // stack. They don't *have* to
827                 // alter the document...
828                 // (Joacim)
829                 // ...or maybe the SetCursorParUndo()
830                 // below isn't necessary at all anylonger?
831                 if (inset_hit->lyxCode() == Inset::REF_CODE) {
832                         setCursorParUndo(bv_);
833                 }
834
835                 owner_->message(inset_hit->editMessage());
836
837                 if (isHighlyEditableInset(inset_hit)) {
838                         // Highly editable inset, like math
839                         UpdatableInset *inset = (UpdatableInset *)inset_hit;
840                         FuncRequest cmd(bv_, LFUN_MOUSE_RELEASE, x, y, button);
841                         inset->localDispatch(cmd);
842                 } else {
843                         FuncRequest cmd(bv_, LFUN_MOUSE_RELEASE, x, y, button);
844                         inset_hit->localDispatch(cmd);
845                         // IMO this is a grosshack! Inset's should be changed so that
846                         // they call the actions they have to do with the insetButtonRel.
847                         // function and not in the edit(). This should be changed
848                         // (Jug 20020329)
849 #ifdef WITH_WARNINGS
850 #warning Please remove donot call inset->edit() here (Jug 20020812)
851 #endif
852                         inset_hit->edit(bv_, x, y, button);
853                 }
854                 return;
855         }
856
857         // Maybe we want to edit a bibitem ale970302
858         if (bv_->text->cursor.par()->bibkey) {
859                 bool const is_rtl = bv_->text->cursor.par()->isRightToLeftPar(buffer_->params);
860                 int const width = bibitemMaxWidth(bv_, buffer_->params.getLyXTextClass().defaultfont());
861                 if ((is_rtl && x > bv_->text->workWidth(bv_)-20-width) ||
862                     (!is_rtl && x < 20+width)) {
863                         bv_->text->cursor.par()->bibkey->edit(bv_, 0, 0, mouse_button::none);
864                 }
865         }
866
867         return;
868 }
869
870
871
872
873 Inset * BufferView::Pimpl::checkInsetHit(LyXText * text, int & x, int & y)
874 {
875         int y_tmp = y + text->first_y;
876
877         LyXCursor cursor;
878         text->setCursorFromCoordinates(bv_, cursor, x, y_tmp);
879
880         Inset * inset = checkInset(bv_, *text, cursor, x, y_tmp);
881
882         if (inset) {
883                 y = y_tmp;
884                 return inset;
885         }
886
887         // look at previous position
888         if (cursor.pos() == 0) {
889                 return 0;
890         }
891
892         // move back one
893         text->setCursor(bv_, cursor, cursor.par(), cursor.pos() - 1, true);
894
895         inset = checkInset(bv_, *text, cursor, x, y_tmp);
896         if (inset) {
897                 y = y_tmp;
898         }
899         return inset;
900 }
901
902
903 void BufferView::Pimpl::workAreaResize()
904 {
905         static int work_area_width;
906         static int work_area_height;
907
908         bool const widthChange = workarea().workWidth() != work_area_width;
909         bool const heightChange = workarea().workHeight() != work_area_height;
910
911         // update from work area
912         work_area_width = workarea().workWidth();
913         work_area_height = workarea().workHeight();
914
915         if (buffer_ != 0) {
916                 if (widthChange) {
917                         // The visible LyXView need a resize
918                         resizeCurrentBuffer();
919
920                         // Remove all texts from the textcache
921                         // This is not _really_ what we want to do. What
922                         // we really want to do is to delete in textcache
923                         // that does not have a BufferView with matching
924                         // width, but as long as we have only one BufferView
925                         // deleting all gives the same result.
926                         if (lyxerr.debugging())
927                                 textcache.show(lyxerr, "Expose delete all");
928                         textcache.clear();
929                         // FIXME: this is already done in resizeCurrentBuffer() ??
930                         buffer_->resizeInsets(bv_);
931                 } else if (heightChange) {
932                         // fitCursor() ensures we don't jump back
933                         // to the start of the document on vertical
934                         // resize
935                         fitCursor();
936                 }
937         }
938
939         if (widthChange || heightChange) {
940                 repaint();
941         }
942
943         // always make sure that the scrollbar is sane.
944         updateScrollbar();
945         owner_->updateLayoutChoice();
946         return;
947 }
948
949
950 void BufferView::Pimpl::update()
951 {
952         if (!bv_->theLockingInset() || !bv_->theLockingInset()->nodraw()) {
953                 LyXText::text_status st = bv_->text->status();
954                 screen().update(bv_->text, bv_);
955                 bool fitc = false;
956                 while (bv_->text->status() == LyXText::CHANGED_IN_DRAW) {
957                         bv_->text->fullRebreak(bv_);
958                         st = LyXText::NEED_MORE_REFRESH;
959                         bv_->text->setCursor(bv_, bv_->text->cursor.par(),
960                                              bv_->text->cursor.pos());
961                         if (bv_->text->selection.set()) {
962                                 bv_->text->setCursor(bv_, bv_->text->selection.start,
963                                                      bv_->text->selection.start.par(),
964                                                      bv_->text->selection.start.pos());
965                                 bv_->text->setCursor(bv_, bv_->text->selection.end,
966                                                      bv_->text->selection.end.par(),
967                                                      bv_->text->selection.end.pos());
968                         }
969                         fitc = true;
970                         bv_->text->status(bv_, st);
971                         screen().update(bv_->text, bv_);
972                 }
973                 // do this here instead of in the screen::update because of
974                 // the above loop!
975                 bv_->text->status(bv_, LyXText::UNCHANGED);
976                 if (fitc)
977                         fitCursor();
978         }
979 }
980
981 // Values used when calling update:
982 // -3 - update
983 // -2 - update, move sel_cursor if selection, fitcursor
984 // -1 - update, move sel_cursor if selection, fitcursor, mark dirty
985 //  0 - update, move sel_cursor if selection, fitcursor
986 //  1 - update, move sel_cursor if selection, fitcursor, mark dirty
987 //  3 - update, move sel_cursor if selection
988 //
989 // update -
990 // a simple redraw of the parts that need refresh
991 //
992 // move sel_cursor if selection -
993 // the text's sel_cursor is moved if there is selection is progress
994 //
995 // fitcursor -
996 // fitCursor() is called and the scrollbar updated
997 //
998 // mark dirty -
999 // the buffer is marked dirty.
1000 //
1001 // enum {
1002 //       UPDATE = 0,
1003 //       SELECT = 1,
1004 //       FITCUR = 2,
1005 //       CHANGE = 4
1006 // };
1007 //
1008 // UPDATE_ONLY = UPDATE;
1009 // UPDATE_SELECT = UPDATE | SELECT;
1010 // UPDATE_SELECT_MOVE = UPDATE | SELECT | FITCUR;
1011 // UPDATE_SELECT_MOVE_AFTER_CHANGE = UPDATE | SELECT | FITCUR | CHANGE;
1012 //
1013 // update(-3) -> update(0)         -> update(0) -> update(UPDATE)
1014 // update(-2) -> update(1 + 2)     -> update(3) -> update(SELECT|FITCUR)
1015 // update(-1) -> update(1 + 2 + 4) -> update(7) -> update(SELECT|FITCUR|CHANGE)
1016 // update(1)  -> update(1 + 2 + 4) -> update(7) -> update(SELECT|FITCUR|CHANGE)
1017 // update(3)  -> update(1)         -> update(1) -> update(SELECT)
1018
1019 void BufferView::Pimpl::update(LyXText * text, BufferView::UpdateCodes f)
1020 {
1021         owner_->updateLayoutChoice();
1022
1023         if (!text->selection.set() && (f & SELECT)) {
1024                 text->selection.cursor = text->cursor;
1025         }
1026
1027         text->fullRebreak(bv_);
1028
1029         if (text->inset_owner) {
1030                 text->inset_owner->setUpdateStatus(bv_, InsetText::NONE);
1031                 updateInset(text->inset_owner, false);
1032         } else {
1033                 update();
1034         }
1035
1036         if ((f & FITCUR)) {
1037                 fitCursor();
1038         }
1039
1040         if ((f & CHANGE)) {
1041                 buffer_->markDirty();
1042         }
1043 }
1044
1045
1046 // Callback for cursor timer
1047 void BufferView::Pimpl::cursorToggle()
1048 {
1049         if (!buffer_) {
1050                 cursor_timeout.restart();
1051                 return;
1052         }
1053
1054         /* FIXME */
1055         extern void reapSpellchecker(void);
1056         reapSpellchecker();
1057
1058         if (!bv_->theLockingInset()) {
1059                 screen().cursorToggle(bv_);
1060         } else {
1061                 bv_->theLockingInset()->toggleInsetCursor(bv_);
1062         }
1063
1064         cursor_timeout.restart();
1065 }
1066
1067
1068 bool BufferView::Pimpl::available() const
1069 {
1070         if (buffer_ && bv_->text)
1071                 return true;
1072         return false;
1073 }
1074
1075
1076 void BufferView::Pimpl::beforeChange(LyXText * text)
1077 {
1078         toggleSelection();
1079         text->clearSelection();
1080 }
1081
1082
1083 void BufferView::Pimpl::savePosition(unsigned int i)
1084 {
1085         if (i >= saved_positions_num)
1086                 return;
1087         saved_positions[i] = Position(buffer_->fileName(),
1088                                       bv_->text->cursor.par()->id(),
1089                                       bv_->text->cursor.pos());
1090         if (i > 0) {
1091                 ostringstream str;
1092                 str << _("Saved bookmark") << ' ' << i;
1093                 owner_->message(str.str().c_str());
1094         }
1095 }
1096
1097
1098 void BufferView::Pimpl::restorePosition(unsigned int i)
1099 {
1100         if (i >= saved_positions_num)
1101                 return;
1102
1103         string const fname = saved_positions[i].filename;
1104
1105         beforeChange(bv_->text);
1106
1107         if (fname != buffer_->fileName()) {
1108                 Buffer * b = bufferlist.exists(fname) ?
1109                         bufferlist.getBuffer(fname) :
1110                         bufferlist.loadLyXFile(fname); // don't ask, just load it
1111                 if (b != 0) buffer(b);
1112         }
1113
1114         Paragraph * par = buffer_->getParFromID(saved_positions[i].par_id);
1115         if (!par)
1116                 return;
1117
1118         bv_->text->setCursor(bv_, par,
1119                              min(par->size(), saved_positions[i].par_pos));
1120
1121         update(bv_->text, BufferView::SELECT | BufferView::FITCUR);
1122         if (i > 0) {
1123                 ostringstream str;
1124                 str << _("Moved to bookmark") << ' ' << i;
1125                 owner_->message(str.str().c_str());
1126         }
1127 }
1128
1129
1130 bool BufferView::Pimpl::isSavedPosition(unsigned int i)
1131 {
1132         if (i >= saved_positions_num)
1133                 return false;
1134
1135         return !saved_positions[i].filename.empty();
1136 }
1137
1138
1139 void BufferView::Pimpl::switchKeyMap()
1140 {
1141         if (!lyxrc.rtl_support)
1142                 return;
1143
1144         LyXText * text = bv_->getLyXText();
1145         if (text->real_current_font.isRightToLeft()
1146             && !(bv_->theLockingInset()
1147                  && bv_->theLockingInset()->lyxCode() == Inset::ERT_CODE))
1148         {
1149                 if (owner_->getIntl().keymap == Intl::PRIMARY)
1150                         owner_->getIntl().KeyMapSec();
1151         } else {
1152                 if (owner_->getIntl().keymap == Intl::SECONDARY)
1153                         owner_->getIntl().KeyMapPrim();
1154         }
1155 }
1156
1157
1158 void BufferView::Pimpl::insetUnlock()
1159 {
1160         if (bv_->theLockingInset()) {
1161                 bv_->theLockingInset()->insetUnlock(bv_);
1162                 bv_->theLockingInset(0);
1163                 finishUndo();
1164         }
1165 }
1166
1167
1168 void BufferView::Pimpl::showCursor()
1169 {
1170         if (bv_->theLockingInset())
1171                 bv_->theLockingInset()->showInsetCursor(bv_);
1172         else
1173                 screen().showCursor(bv_->text, bv_);
1174 }
1175
1176
1177 void BufferView::Pimpl::hideCursor()
1178 {
1179         if (!bv_->theLockingInset())
1180                 screen().hideCursor();
1181 }
1182
1183
1184 void BufferView::Pimpl::toggleSelection(bool b)
1185 {
1186         if (bv_->theLockingInset())
1187                 bv_->theLockingInset()->toggleSelection(bv_, b);
1188         screen().toggleSelection(bv_->text, bv_, b);
1189 }
1190
1191
1192 void BufferView::Pimpl::toggleToggle()
1193 {
1194         screen().toggleToggle(bv_->text, bv_);
1195 }
1196
1197
1198 void BufferView::Pimpl::center()
1199 {
1200         LyXText * t = bv_->text;
1201
1202         beforeChange(t);
1203         int const half_height = workarea().workHeight() / 2;
1204         int new_y = 0;
1205
1206         if (t->cursor.y() > half_height) {
1207                 new_y = t->cursor.y() - half_height;
1208         }
1209
1210         // FIXME: can we do this w/o calling screen directly ?
1211         // This updates first_y but means the fitCursor() call
1212         // from the update(FITCUR) doesn't realise that we might
1213         // have moved (e.g. from GOTOPARAGRAPH), so doesn't cause
1214         // the scrollbar to be updated as it should, so we have
1215         // to do it manually. Any operation that does a center()
1216         // and also might have moved first_y must make sure to call
1217         // updateScrollbar() currently. Never mind that this is a
1218         // pretty obfuscated way of updating t->first_y
1219         screen().draw(t, bv_, new_y);
1220
1221         update(t, BufferView::SELECT | BufferView::FITCUR);
1222 }
1223
1224
1225 void BufferView::Pimpl::stuffClipboard(string const & stuff) const
1226 {
1227         workarea().putClipboard(stuff);
1228 }
1229
1230
1231 /*
1232  * Dispatch functions for actions which can be valid for BufferView->text
1233  * and/or InsetText->text!!!
1234  */
1235
1236
1237 Inset * BufferView::Pimpl::getInsetByCode(Inset::Code code)
1238 {
1239 #if 0
1240         LyXCursor cursor = bv_->getLyXText()->cursor;
1241         Buffer::inset_iterator it =
1242                 find_if(Buffer::inset_iterator(
1243                         cursor.par(), cursor.pos()),
1244                         buffer_->inset_iterator_end(),
1245                         lyx::compare_memfun(&Inset::lyxCode, code));
1246         return it != buffer_->inset_iterator_end() ? (*it) : 0;
1247 #else
1248         // Ok, this is a little bit too brute force but it
1249         // should work for now. Better infrastructure is comming. (Lgb)
1250
1251         Buffer * b = bv_->buffer();
1252         LyXCursor cursor = bv_->getLyXText()->cursor;
1253
1254         Buffer::inset_iterator beg = b->inset_iterator_begin();
1255         Buffer::inset_iterator end = b->inset_iterator_end();
1256
1257         bool cursor_par_seen = false;
1258
1259         for (; beg != end; ++beg) {
1260                 if (beg.getPar() == cursor.par()) {
1261                         cursor_par_seen = true;
1262                 }
1263                 if (cursor_par_seen) {
1264                         if (beg.getPar() == cursor.par()
1265                             && beg.getPos() >= cursor.pos()) {
1266                                 break;
1267                         } else if (beg.getPar() != cursor.par()) {
1268                                 break;
1269                         }
1270                 }
1271
1272         }
1273         if (beg != end) {
1274                 // Now find the first inset that matches code.
1275                 for (; beg != end; ++beg) {
1276                         if (beg->lyxCode() == code) {
1277                                 return &(*beg);
1278                         }
1279                 }
1280         }
1281         return 0;
1282 #endif
1283 }
1284
1285
1286 void BufferView::Pimpl::MenuInsertLyXFile(string const & filen)
1287 {
1288         string filename = filen;
1289
1290         if (filename.empty()) {
1291                 // Launch a file browser
1292                 string initpath = lyxrc.document_path;
1293
1294                 if (available()) {
1295                         string const trypath = owner_->buffer()->filePath();
1296                         // If directory is writeable, use this as default.
1297                         if (IsDirWriteable(trypath))
1298                                 initpath = trypath;
1299                 }
1300
1301                 FileDialog fileDlg(bv_->owner(),
1302                                    _("Select LyX document to insert"),
1303                         LFUN_FILE_INSERT,
1304                         make_pair(string(_("Documents|#o#O")),
1305                                   string(lyxrc.document_path)),
1306                         make_pair(string(_("Examples|#E#e")),
1307                                   string(AddPath(system_lyxdir, "examples"))));
1308
1309                 FileDialog::Result result =
1310                         fileDlg.Select(initpath,
1311                                        _("*.lyx| LyX Documents (*.lyx)"));
1312
1313                 if (result.first == FileDialog::Later)
1314                         return;
1315
1316                 filename = result.second;
1317
1318                 // check selected filename
1319                 if (filename.empty()) {
1320                         owner_->message(_("Canceled."));
1321                         return;
1322                 }
1323         }
1324
1325         // get absolute path of file and add ".lyx" to the filename if
1326         // necessary
1327         filename = FileSearch(string(), filename, "lyx");
1328
1329         string const disp_fn(MakeDisplayPath(filename));
1330
1331         ostringstream s1;
1332         s1 << _("Inserting document") << ' '
1333            << disp_fn << " ...";
1334         owner_->message(s1.str().c_str());
1335         bool const res = bv_->insertLyXFile(filename);
1336         if (res) {
1337                 ostringstream str;
1338                 str << _("Document") << ' ' << disp_fn
1339                     << ' ' << _("inserted.");
1340                 owner_->message(str.str().c_str());
1341         } else {
1342                 ostringstream str;
1343                 str << _("Could not insert document") << ' '
1344                     << disp_fn;
1345                 owner_->message(str.str().c_str());
1346         }
1347 }
1348
1349
1350 bool BufferView::Pimpl::dispatch(FuncRequest const & ev)
1351 {
1352         lyxerr[Debug::ACTION] << "BufferView::Pimpl::Dispatch: action["
1353           << ev.action <<"] arg[" << ev.argument << "]" << endl;
1354
1355         LyXTextClass const & tclass = buffer_->params.getLyXTextClass();
1356
1357         switch (ev.action) {
1358
1359         case LFUN_TOC_INSERT:
1360         {
1361                 InsetCommandParams p;
1362                 p.setCmdName("tableofcontents");
1363                 Inset * inset = new InsetTOC(p);
1364                 if (!insertInset(inset, tclass.defaultLayoutName()))
1365                         delete inset;
1366                 break;
1367         }
1368
1369         case LFUN_SCROLL_INSET:
1370                 // this is not handled here as this function is only active
1371                 // if we have a locking_inset and that one is (or contains)
1372                 // a tabular-inset
1373                 break;
1374
1375         case LFUN_INSET_GRAPHICS:
1376         {
1377                 Inset * new_inset = new InsetGraphics;
1378                 if (!insertInset(new_inset)) {
1379                         delete new_inset;
1380                 } else {
1381                         // this is need because you don't use a inset->Edit()
1382                         updateInset(new_inset, true);
1383                         new_inset->edit(bv_);
1384                 }
1385                 break;
1386         }
1387
1388         case LFUN_LAYOUT_COPY:
1389                 bv_->copyEnvironment();
1390                 break;
1391
1392         case LFUN_LAYOUT_PASTE:
1393                 bv_->pasteEnvironment();
1394                 switchKeyMap();
1395                 break;
1396
1397         case LFUN_DEPTH_MIN:
1398                 changeDepth(bv_, bv_->getLyXText(), -1);
1399                 break;
1400
1401         case LFUN_DEPTH_PLUS:
1402                 changeDepth(bv_, bv_->getLyXText(), 1);
1403                 break;
1404
1405         case LFUN_FREE:
1406                 owner_->getDialogs().setUserFreeFont();
1407                 break;
1408
1409         case LFUN_FILE_INSERT:
1410                 MenuInsertLyXFile(ev.argument);
1411                 break;
1412
1413         case LFUN_FILE_INSERT_ASCII_PARA:
1414                 InsertAsciiFile(bv_, ev.argument, true);
1415                 break;
1416
1417         case LFUN_FILE_INSERT_ASCII:
1418                 InsertAsciiFile(bv_, ev.argument, false);
1419                 break;
1420
1421         case LFUN_LANGUAGE:
1422                 lang(bv_, ev.argument);
1423                 switchKeyMap();
1424                 owner_->view_state_changed();
1425                 break;
1426
1427         case LFUN_EMPH:
1428                 emph(bv_);
1429                 owner_->view_state_changed();
1430                 break;
1431
1432         case LFUN_BOLD:
1433                 bold(bv_);
1434                 owner_->view_state_changed();
1435                 break;
1436
1437         case LFUN_NOUN:
1438                 noun(bv_);
1439                 owner_->view_state_changed();
1440                 break;
1441
1442         case LFUN_CODE:
1443                 code(bv_);
1444                 owner_->view_state_changed();
1445                 break;
1446
1447         case LFUN_SANS:
1448                 sans(bv_);
1449                 owner_->view_state_changed();
1450                 break;
1451
1452         case LFUN_ROMAN:
1453                 roman(bv_);
1454                 owner_->view_state_changed();
1455                 break;
1456
1457         case LFUN_DEFAULT:
1458                 styleReset(bv_);
1459                 owner_->view_state_changed();
1460                 break;
1461
1462         case LFUN_UNDERLINE:
1463                 underline(bv_);
1464                 owner_->view_state_changed();
1465                 break;
1466
1467         case LFUN_FONT_SIZE:
1468                 fontSize(bv_, ev.argument);
1469                 owner_->view_state_changed();
1470                 break;
1471
1472         case LFUN_FONT_STATE:
1473                 owner_->getLyXFunc().setMessage(currentState(bv_));
1474                 break;
1475
1476         case LFUN_INSERT_LABEL:
1477                 MenuInsertLabel(bv_, ev.argument);
1478                 break;
1479
1480         case LFUN_REF_INSERT:
1481                 if (ev.argument.empty()) {
1482                         InsetCommandParams p("ref");
1483                         owner_->getDialogs().createRef(p.getAsString());
1484                 } else {
1485                         InsetCommandParams p;
1486                         p.setFromString(ev.argument);
1487
1488                         InsetRef * inset = new InsetRef(p, *buffer_);
1489                         if (!insertInset(inset))
1490                                 delete inset;
1491                         else
1492                                 updateInset(inset, true);
1493                 }
1494                 break;
1495
1496         case LFUN_BOOKMARK_SAVE:
1497                 savePosition(strToUnsignedInt(ev.argument));
1498                 break;
1499
1500         case LFUN_BOOKMARK_GOTO:
1501                 restorePosition(strToUnsignedInt(ev.argument));
1502                 break;
1503
1504         case LFUN_REF_GOTO:
1505         {
1506                 string label = ev.argument;
1507                 if (label.empty()) {
1508                         InsetRef * inset =
1509                                 static_cast<InsetRef*>(getInsetByCode(Inset::REF_CODE));
1510                         if (inset) {
1511                                 label = inset->getContents();
1512                                 savePosition(0);
1513                         }
1514                 }
1515
1516                 if (!label.empty()) {
1517                         //bv_->savePosition(0);
1518                         if (!bv_->gotoLabel(label))
1519                                 Alert::alert(_("Error"),
1520                                            _("Couldn't find this label"),
1521                                            _("in current document."));
1522                 }
1523         }
1524         break;
1525
1526         case LFUN_HTMLURL:
1527         case LFUN_URL:
1528         {
1529                 InsetCommandParams p;
1530                 if (ev.action == LFUN_HTMLURL)
1531                         p.setCmdName("htmlurl");
1532                 else
1533                         p.setCmdName("url");
1534                 owner_->getDialogs().createUrl(p.getAsString());
1535         }
1536         break;
1537
1538         case LFUN_INSERT_URL:
1539         {
1540                 InsetCommandParams p;
1541                 p.setFromString(ev.argument);
1542
1543                 InsetUrl * inset = new InsetUrl(p);
1544                 if (!insertInset(inset))
1545                         delete inset;
1546                 else
1547                         updateInset(inset, true);
1548         }
1549         break;
1550
1551         case LFUN_INSET_CAPTION:
1552         {
1553                 // Do we have a locking inset...
1554                 if (bv_->theLockingInset()) {
1555                         lyxerr << "Locking inset code: "
1556                                << static_cast<int>(bv_->theLockingInset()->lyxCode());
1557                         InsetCaption * new_inset =
1558                                 new InsetCaption(buffer_->params);
1559                         new_inset->setOwner(bv_->theLockingInset());
1560                         new_inset->setAutoBreakRows(true);
1561                         new_inset->setDrawFrame(0, InsetText::LOCKED);
1562                         new_inset->setFrameColor(0, LColor::captionframe);
1563                         if (insertInset(new_inset))
1564                                 new_inset->edit(bv_);
1565                         else
1566                                 delete new_inset;
1567                 }
1568         }
1569         break;
1570
1571
1572         // --- accented characters ---------------------------
1573
1574         case LFUN_UMLAUT:
1575         case LFUN_CIRCUMFLEX:
1576         case LFUN_GRAVE:
1577         case LFUN_ACUTE:
1578         case LFUN_TILDE:
1579         case LFUN_CEDILLA:
1580         case LFUN_MACRON:
1581         case LFUN_DOT:
1582         case LFUN_UNDERDOT:
1583         case LFUN_UNDERBAR:
1584         case LFUN_CARON:
1585         case LFUN_SPECIAL_CARON:
1586         case LFUN_BREVE:
1587         case LFUN_TIE:
1588         case LFUN_HUNG_UMLAUT:
1589         case LFUN_CIRCLE:
1590         case LFUN_OGONEK:
1591                 if (ev.argument.empty()) {
1592                         // As always...
1593                         owner_->getLyXFunc().handleKeyFunc(ev.action);
1594                 } else {
1595                         owner_->getLyXFunc().handleKeyFunc(ev.action);
1596                         owner_->getIntl().getTransManager()
1597                                 .TranslateAndInsert(ev.argument[0], bv_->getLyXText());
1598                         update(bv_->getLyXText(),
1599                                BufferView::SELECT
1600                                | BufferView::FITCUR
1601                                | BufferView::CHANGE);
1602                 }
1603                 break;
1604
1605         case LFUN_MATH_MACRO:
1606         case LFUN_MATH_DELIM:
1607         case LFUN_INSERT_MATRIX:
1608         case LFUN_INSERT_MATH:
1609         case LFUN_MATH_IMPORT_SELECTION: // Imports LaTeX from the X selection
1610         case LFUN_MATH_DISPLAY:          // Open or create a displayed math inset
1611         case LFUN_MATH_MODE:             // Open or create an inlined math inset
1612         case LFUN_GREEK:                 // Insert a single greek letter
1613                 mathDispatch(FuncRequest(bv_, ev.action, ev.argument));
1614                 break;
1615
1616         case LFUN_CITATION_INSERT:
1617         {
1618                 InsetCommandParams p;
1619                 p.setFromString(ev.argument);
1620
1621                 InsetCitation * inset = new InsetCitation(p);
1622                 if (!insertInset(inset))
1623                         delete inset;
1624                 else
1625                         updateInset(inset, true);
1626         }
1627         break;
1628
1629         case LFUN_INSERT_BIBTEX:
1630         {
1631                 // ale970405+lasgoutt970425
1632                 // The argument can be up to two tokens separated
1633                 // by a space. The first one is the bibstyle.
1634                 string const db = token(ev.argument, ' ', 0);
1635                 string bibstyle = token(ev.argument, ' ', 1);
1636                 if (bibstyle.empty())
1637                         bibstyle = "plain";
1638
1639                 InsetCommandParams p("BibTeX", db, bibstyle);
1640                 InsetBibtex * inset = new InsetBibtex(p);
1641
1642                 if (insertInset(inset)) {
1643                         if (ev.argument.empty())
1644                                 inset->edit(bv_);
1645                 } else
1646                         delete inset;
1647         }
1648         break;
1649
1650         // BibTeX data bases
1651         case LFUN_BIBDB_ADD:
1652         {
1653                 InsetBibtex * inset =
1654                         static_cast<InsetBibtex*>(getInsetByCode(Inset::BIBTEX_CODE));
1655                 if (inset) {
1656                         inset->addDatabase(ev.argument);
1657                 }
1658         }
1659         break;
1660
1661         case LFUN_BIBDB_DEL:
1662         {
1663                 InsetBibtex * inset =
1664                         static_cast<InsetBibtex*>(getInsetByCode(Inset::BIBTEX_CODE));
1665                 if (inset) {
1666                         inset->delDatabase(ev.argument);
1667                 }
1668         }
1669         break;
1670
1671         case LFUN_BIBTEX_STYLE:
1672         {
1673                 InsetBibtex * inset =
1674                         static_cast<InsetBibtex*>(getInsetByCode(Inset::BIBTEX_CODE));
1675                 if (inset) {
1676                         inset->setOptions(ev.argument);
1677                 }
1678         }
1679         break;
1680
1681         case LFUN_INDEX_INSERT:
1682         {
1683                 string entry = ev.argument;
1684                 if (entry.empty())
1685                         entry = bv_->getLyXText()->getStringToIndex(bv_);
1686
1687                 if (entry.empty()) {
1688                         owner_->getDialogs().createIndex();
1689                         break;
1690                 }
1691
1692                 InsetIndex * inset = new InsetIndex(InsetCommandParams("index", entry));
1693
1694                 if (!insertInset(inset)) {
1695                         delete inset;
1696                 } else {
1697                         updateInset(inset, true);
1698                 }
1699         }
1700         break;
1701
1702         case LFUN_INDEX_PRINT:
1703         {
1704                 InsetCommandParams p("printindex");
1705                 Inset * inset = new InsetPrintIndex(p);
1706                 if (!insertInset(inset, tclass.defaultLayoutName()))
1707                         delete inset;
1708         }
1709         break;
1710
1711         case LFUN_PARENTINSERT:
1712         {
1713                 InsetCommandParams p("lyxparent", ev.argument);
1714                 Inset * inset = new InsetParent(p, *buffer_);
1715                 if (!insertInset(inset, tclass.defaultLayoutName()))
1716                         delete inset;
1717         }
1718
1719         break;
1720
1721         case LFUN_CHILD_INSERT:
1722         {
1723                 InsetInclude::Params p;
1724                 p.cparams.setFromString(ev.argument);
1725                 p.masterFilename_ = buffer_->fileName();
1726
1727                 InsetInclude * inset = new InsetInclude(p);
1728                 if (!insertInset(inset))
1729                         delete inset;
1730                 else {
1731                         updateInset(inset, true);
1732                         bv_->owner()->getDialogs().showInclude(inset);
1733                 }
1734         }
1735         break;
1736
1737         case LFUN_FLOAT_LIST:
1738                 if (tclass.floats().typeExist(ev.argument)) {
1739                         Inset * inset = new InsetFloatList(ev.argument);
1740                         if (!insertInset(inset, tclass.defaultLayoutName()))
1741                                 delete inset;
1742                 } else {
1743                         lyxerr << "Non-existent float type: "
1744                                << ev.argument << endl;
1745                 }
1746                 break;
1747
1748         case LFUN_THESAURUS_ENTRY:
1749         {
1750                 string arg = ev.argument;
1751
1752                 if (arg.empty()) {
1753                         arg = bv_->getLyXText()->selectionAsString(buffer_,
1754                                                                    false);
1755
1756                         // FIXME
1757                         if (arg.size() > 100 || arg.empty()) {
1758                                 // Get word or selection
1759                                 bv_->getLyXText()->selectWordWhenUnderCursor(bv_, LyXText::WHOLE_WORD);
1760                                 arg = bv_->getLyXText()->selectionAsString(buffer_, false);
1761                                 // FIXME: where is getLyXText()->unselect(bv_) ?
1762                         }
1763                 }
1764
1765                 bv_->owner()->getDialogs().showThesaurus(arg);
1766         }
1767                 break;
1768
1769         case LFUN_UNKNOWN_ACTION:
1770                 ev.errorMessage(N_("Unknown function!"));
1771                 break;
1772
1773         default:
1774                 FuncRequest cmd = ev;
1775                 cmd.setView(bv_);
1776                 return bv_->getLyXText()->dispatch(cmd);
1777         } // end of switch
1778
1779         return true;
1780 }
1781
1782
1783 bool BufferView::Pimpl::insertInset(Inset * inset, string const & lout)
1784 {
1785         // if we are in a locking inset we should try to insert the
1786         // inset there otherwise this is a illegal function now
1787         if (bv_->theLockingInset()) {
1788                 if (bv_->theLockingInset()->insetAllowed(inset))
1789                     return bv_->theLockingInset()->insertInset(bv_, inset);
1790                 return false;
1791         }
1792
1793         // not quite sure if we want this...
1794         setCursorParUndo(bv_);
1795         freezeUndo();
1796
1797         beforeChange(bv_->text);
1798         if (!lout.empty()) {
1799                 update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
1800                 bv_->text->breakParagraph(bv_);
1801                 update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
1802
1803                 if (!bv_->text->cursor.par()->empty()) {
1804                         bv_->text->cursorLeft(bv_);
1805
1806                         bv_->text->breakParagraph(bv_);
1807                         update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
1808                 }
1809
1810                 string lres = lout;
1811                 LyXTextClass const & tclass =
1812                         buffer_->params.getLyXTextClass();
1813                 bool hasLayout = tclass.hasLayout(lres);
1814                 string lay = tclass.defaultLayoutName();
1815
1816                 if (hasLayout != false) {
1817                         // layout found
1818                         lay = lres;
1819                 } else {
1820                         // layout not fount using default
1821                         lay = tclass.defaultLayoutName();
1822                 }
1823
1824                 bv_->text->setLayout(bv_, lay);
1825
1826                 bv_->text->setParagraph(bv_, 0, 0,
1827                                    0, 0,
1828                                    VSpace(VSpace::NONE), VSpace(VSpace::NONE),
1829                                    Spacing(),
1830                                    LYX_ALIGN_LAYOUT,
1831                                    string(),
1832                                    0);
1833                 update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
1834         }
1835
1836         bv_->text->insertInset(bv_, inset);
1837         update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
1838
1839         unFreezeUndo();
1840         return true;
1841 }
1842
1843
1844 void BufferView::Pimpl::updateInset(Inset * inset, bool mark_dirty)
1845 {
1846         if (!inset || !available())
1847                 return;
1848
1849         // first check for locking insets
1850         if (bv_->theLockingInset()) {
1851                 if (bv_->theLockingInset() == inset) {
1852                         if (bv_->text->updateInset(bv_, inset)) {
1853                                 update();
1854                                 if (mark_dirty) {
1855                                         buffer_->markDirty();
1856                                 }
1857                                 updateScrollbar();
1858                                 return;
1859                         }
1860                 } else if (bv_->theLockingInset()->updateInsetInInset(bv_, inset)) {
1861                         if (bv_->text->updateInset(bv_,  bv_->theLockingInset())) {
1862                                 update();
1863                                 if (mark_dirty) {
1864                                         buffer_->markDirty();
1865                                 }
1866                                 updateScrollbar();
1867                                 return;
1868                         }
1869                 }
1870         }
1871
1872         // then check if the inset is a top_level inset (has no owner)
1873         // if yes do the update as always otherwise we have to update the
1874         // toplevel inset where this inset is inside
1875         Inset * tl_inset = inset;
1876         while (tl_inset->owner())
1877                 tl_inset = tl_inset->owner();
1878         hideCursor();
1879         if (tl_inset == inset) {
1880                 update(bv_->text, BufferView::UPDATE);
1881                 if (bv_->text->updateInset(bv_, inset)) {
1882                         if (mark_dirty) {
1883                                 update(bv_->text,
1884                                        BufferView::SELECT
1885                                        | BufferView::FITCUR
1886                                        | BufferView::CHANGE);
1887                         } else {
1888                                 update(bv_->text, SELECT);
1889                         }
1890                         return;
1891                 }
1892         } else if (static_cast<UpdatableInset *>(tl_inset)
1893                            ->updateInsetInInset(bv_, inset))
1894         {
1895                 if (bv_->text->updateInset(bv_, tl_inset)) {
1896                         update();
1897                         updateScrollbar();
1898                 }
1899         }
1900 }