]> git.lyx.org Git - lyx.git/blob - src/BufferView_pimpl.C
mathed31.diff
[lyx.git] / src / BufferView_pimpl.C
1 #include <config.h>
2
3 #include <unistd.h>
4 #include <sys/wait.h>
5
6 #ifdef __GNUG__
7 #pragma implementation
8 #endif
9
10 #include "BufferView_pimpl.h"
11 #include "WorkArea.h"
12 #include "lyxscreen.h"
13 #include "lyxtext.h"
14 #include "lyxrow.h"
15 #include "LyXView.h"
16 #include "commandtags.h"
17 #include "lyxfunc.h"
18 #include "minibuffer.h"
19 #include "font.h"
20 #include "bufferview_funcs.h"
21 #include "TextCache.h"
22 #include "bufferlist.h"
23 #include "insets/insetbib.h"
24 #include "insets/insettext.h"
25 #include "lyx_gui_misc.h"
26 #include "lyxrc.h"
27 #include "intl.h"
28 #include "support/LAssert.h"
29 #include "frontends/Dialogs.h"
30
31 #ifdef SIGC_CXX_NAMESPACES
32 using SigC::slot;
33 #endif
34
35 using std::pair;
36 using std::endl;
37 using std::make_pair;
38 using std::min;
39
40 /* the selection possible is needed, that only motion events are 
41  * used, where the bottom press event was on the drawing area too */
42 bool selection_possible = false;
43
44 extern BufferList bufferlist;
45 extern char ascii_type;
46
47 extern void sigchldhandler(pid_t pid, int * status);
48 extern int bibitemMaxWidth(BufferView *, LyXFont const &);
49
50 const unsigned int saved_positions_num = 20;
51
52 static inline
53 void waitForX()
54 {
55         XSync(fl_get_display(), 0);
56 }
57
58
59 static
60 void SetXtermCursor(Window win)
61 {
62         static Cursor cursor;
63         static bool cursor_undefined = true;
64         if (cursor_undefined){
65                 cursor = XCreateFontCursor(fl_get_display(), XC_xterm);
66                 XFlush(fl_get_display());
67                 cursor_undefined = false;
68         }
69         XDefineCursor(fl_get_display(), win, cursor);
70         XFlush(fl_get_display());
71 }
72
73
74 BufferView::Pimpl::Pimpl(BufferView * b, LyXView * o,
75              int xpos, int ypos, int width, int height)
76         : bv_(b), owner_(o), cursor_timeout(400)
77 {
78         buffer_ = 0;
79         workarea_ = new WorkArea(xpos, ypos, width, height);
80         // Setup the signals
81         workarea_->scrollCB.connect(slot(this, &BufferView::Pimpl::scrollCB));
82         workarea_->workAreaExpose
83                 .connect(slot(this, &BufferView::Pimpl::workAreaExpose));
84         workarea_->workAreaEnter
85                 .connect(slot(this, &BufferView::Pimpl::enterView));
86         workarea_->workAreaLeave
87                 .connect(slot(this, &BufferView::Pimpl::leaveView));
88         workarea_->workAreaButtonPress
89                 .connect(slot(this, &BufferView::Pimpl::workAreaButtonPress));
90         workarea_->workAreaButtonRelease
91                 .connect(slot(this,
92                               &BufferView::Pimpl::workAreaButtonRelease));
93         workarea_->workAreaMotionNotify
94                 .connect(slot(this, &BufferView::Pimpl::workAreaMotionNotify));
95         workarea_->workAreaDoubleClick
96                 .connect(slot(this, &BufferView::Pimpl::doubleClick));
97         workarea_->workAreaTripleClick
98                 .connect(slot(this, &BufferView::Pimpl::tripleClick));
99         workarea_->workAreaKeyPress
100                 .connect(slot(this, &BufferView::Pimpl::workAreaKeyPress));
101         
102         screen_ = 0;
103
104         cursor_timeout.timeout.connect(slot(this,
105                                             &BufferView::Pimpl::cursorToggle));
106         current_scrollbar_value = 0;
107         cursor_timeout.start();
108         workarea_->setFocus();
109         using_xterm_cursor = false;
110         saved_positions.resize(saved_positions_num);
111 }
112
113
114 Painter & BufferView::Pimpl::painter() 
115 {
116         return workarea_->getPainter();
117 }
118
119
120 void BufferView::Pimpl::buffer(Buffer * b)
121 {
122         lyxerr[Debug::INFO] << "Setting buffer in BufferView ("
123                             << b << ")" << endl;
124         if (buffer_) {
125                 bv_->insetSleep();
126                 buffer_->delUser(bv_);
127
128                 // Put the old text into the TextCache, but
129                 // only if the buffer is still loaded.
130                 // Also set the owner of the test to 0
131                 //              bv_->text->owner(0);
132                 textcache.add(buffer_, workarea_->workWidth(), bv_->text);
133                 if (lyxerr.debugging())
134                         textcache.show(lyxerr, "BufferView::buffer");
135                 
136                 bv_->text = 0;
137         }
138
139         // Set current buffer
140         buffer_ = b;
141
142         if (bufferlist.getState() == BufferList::CLOSING) return;
143         
144         // Nuke old image
145         // screen is always deleted when the buffer is changed.
146         delete screen_;
147         screen_ = 0;
148
149         // If we are closing the buffer, use the first buffer as current
150         if (!buffer_) {
151                 buffer_ = bufferlist.first();
152         }
153
154         if (buffer_) {
155                 lyxerr[Debug::INFO] << "Buffer addr: " << buffer_ << endl;
156                 buffer_->addUser(bv_);
157                 // If we don't have a text object for this, we make one
158                 if (bv_->text == 0) {
159                         resizeCurrentBuffer();
160                 } else {
161                         updateScreen();
162                         updateScrollbar();
163                 }
164                 bv_->text->first = screen_->TopCursorVisible(bv_->text);
165                 owner_->updateMenubar();
166                 owner_->updateToolbar();
167                 // Similarly, buffer-dependent dialogs should be updated or
168                 // hidden. This should go here because some dialogs (eg ToC)
169                 // require bv_->text.
170                 owner_->getDialogs()->updateBufferDependent(true);
171                 redraw();
172                 bv_->insetWakeup();
173         } else {
174                 lyxerr[Debug::INFO] << "  No Buffer!" << endl;
175                 owner_->updateMenubar();
176                 owner_->updateToolbar();
177                 owner_->getDialogs()->hideBufferDependent();
178                 updateScrollbar();
179                 workarea_->redraw();
180
181                 // Also remove all remaining text's from the testcache.
182                 // (there should not be any!) (if there is any it is a
183                 // bug!)
184                 if (lyxerr.debugging())
185                         textcache.show(lyxerr, "buffer delete all");
186                 textcache.clear();
187         }
188         // should update layoutchoice even if we don't have a buffer.
189         owner_->updateLayoutChoice();
190         owner_->getMiniBuffer()->Init();
191         owner_->updateWindowTitle();
192 }
193
194
195 void BufferView::Pimpl::resize(int xpos, int ypos, int width, int height)
196 {
197         workarea_->resize(xpos, ypos, width, height);
198         update(bv_->text, SELECT);
199         redraw();
200 }
201
202
203 void BufferView::Pimpl::resize()
204 {
205         if (buffer_)
206                 resizeCurrentBuffer();
207 }
208
209
210 void BufferView::Pimpl::redraw()
211 {
212         lyxerr[Debug::INFO] << "BufferView::redraw()" << endl;
213         workarea_->redraw();
214 }
215
216
217 bool BufferView::Pimpl::fitCursor(LyXText * text)
218 {
219         Assert(screen_);
220  
221         bool ret = screen_->FitCursor(text, bv_);
222         if (ret)
223             updateScrollbar();
224         return ret;
225 }
226
227
228 void BufferView::Pimpl::redoCurrentBuffer()
229 {
230         lyxerr[Debug::INFO] << "BufferView::redoCurrentBuffer" << endl;
231         if (buffer_ && bv_->text) {
232                 resize();
233                 owner_->updateLayoutChoice();
234         }
235 }
236
237
238 int BufferView::Pimpl::resizeCurrentBuffer()
239 {
240         lyxerr[Debug::INFO] << "resizeCurrentBuffer" << endl;
241         
242         LyXParagraph * par = 0;
243         LyXParagraph * selstartpar = 0;
244         LyXParagraph * selendpar = 0;
245         UpdatableInset * the_locking_inset;
246         
247         int pos = 0;
248         int selstartpos = 0;
249         int selendpos = 0;
250         int selection = 0;
251         int mark_set = 0;
252
253         ProhibitInput(bv_);
254
255         owner_->getMiniBuffer()->Set(_("Formatting document..."));   
256
257         if (bv_->text) {
258                 par = bv_->text->cursor.par();
259                 pos = bv_->text->cursor.pos();
260                 selstartpar = bv_->text->sel_start_cursor.par();
261                 selstartpos = bv_->text->sel_start_cursor.pos();
262                 selendpar = bv_->text->sel_end_cursor.par();
263                 selendpos = bv_->text->sel_end_cursor.pos();
264                 selection = bv_->text->selection;
265                 mark_set = bv_->text->mark_set;
266                 the_locking_inset = bv_->text->the_locking_inset;
267                 delete bv_->text;
268                 bv_->text = new LyXText(bv_);
269         } else {
270                 // See if we have a text in TextCache that fits
271                 // the new buffer_ with the correct width.
272                 bv_->text = textcache.findFit(buffer_, workarea_->workWidth());
273                 if (bv_->text) {
274                         if (lyxerr.debugging()) {
275                                 lyxerr << "Found a LyXText that fits:\n";
276                                 textcache.show(lyxerr, make_pair(buffer_, make_pair(workarea_->workWidth(), bv_->text)));
277                         }
278                         // Set the owner of the newly found text
279                         //      bv_->text->owner(bv_);
280                         if (lyxerr.debugging())
281                                 textcache.show(lyxerr, "resizeCurrentBuffer");
282                 } else {
283                         bv_->text = new LyXText(bv_);
284                 }
285         }
286         updateScreen();
287
288         if (par) {
289                 bv_->text->selection = true;
290                 /* at this point just to avoid the Delete-Empty-Paragraph
291                  * Mechanism when setting the cursor */
292                 bv_->text->mark_set = mark_set;
293                 if (selection) {
294                         bv_->text->SetCursor(bv_, selstartpar, selstartpos);
295                         bv_->text->sel_cursor = bv_->text->cursor;
296                         bv_->text->SetCursor(bv_, selendpar, selendpos);
297                         bv_->text->SetSelection(bv_);
298                         bv_->text->SetCursor(bv_, par, pos);
299                 } else {
300                         bv_->text->SetCursor(bv_, par, pos);
301                         bv_->text->sel_cursor = bv_->text->cursor;
302                         bv_->text->selection = false;
303                 }
304                 // remake the inset locking
305                 bv_->text->the_locking_inset = the_locking_inset;
306         }
307         bv_->text->first = screen_->TopCursorVisible(bv_->text);
308         buffer_->resizeInsets(bv_);
309         // this will scroll the screen such that the cursor becomes visible
310         updateScrollbar();
311         redraw();
312         owner_->getMiniBuffer()->Init();
313         bv_->setState();
314         AllowInput(bv_);
315
316         owner_->getDialogs()->hideSplash();
317  
318         return 0;
319 }
320
321
322 void BufferView::Pimpl::updateScreen()
323 {
324         // Regenerate the screen.
325         delete screen_;
326         screen_ = new LyXScreen(*workarea_);
327 }
328
329
330 void BufferView::Pimpl::updateScrollbar()
331 {
332         /* If the text is smaller than the working area, the scrollbar
333          * maximum must be the working area height. No scrolling will 
334          * be possible */
335
336         if (!buffer_) {
337                 workarea_->setScrollbar(0, 1.0);
338                 return;
339         }
340         
341         static unsigned long max2 = 0;
342         static unsigned long height2 = 0;
343
344         unsigned long cbth = 0;
345         long cbsf = 0;
346
347         if (bv_->text) {
348                 cbth = bv_->text->height;
349                 cbsf = bv_->text->first;
350         }
351
352         // check if anything has changed.
353         if (max2 == cbth &&
354             height2 == workarea_->height() &&
355             current_scrollbar_value == cbsf)
356                 return; // no
357         max2 = cbth;
358         height2 = workarea_->height();
359         current_scrollbar_value = cbsf;
360
361         if (cbth <= height2) { // text is smaller than screen
362                 workarea_->setScrollbar(0, 1.0); // right?
363                 return;
364         }
365
366         long maximum_height = workarea_->height() * 3 / 4 + cbth;
367         long value = cbsf;
368
369         // set the scrollbar
370         double hfloat = workarea_->height();
371         double maxfloat = maximum_height;
372
373         float slider_size = 0.0;
374         int slider_value = value;
375
376         workarea_->setScrollbarBounds(0, bv_->text->height - workarea_->height());
377         double lineh = bv_->text->DefaultHeight();
378         workarea_->setScrollbarIncrements(lineh);
379         if (maxfloat > 0.0) {
380                 if ((hfloat / maxfloat) * float(height2) < 3)
381                         slider_size = 3.0/float(height2);
382                 else
383                         slider_size = hfloat / maxfloat;
384         } else
385                 slider_size = hfloat;
386
387         workarea_->setScrollbar(slider_value, slider_size / workarea_->height());
388 }
389
390
391 // Callback for scrollbar slider
392 void BufferView::Pimpl::scrollCB(double value)
393 {
394         if (!buffer_) return;
395
396         current_scrollbar_value = long(value);
397         if (current_scrollbar_value < 0)
398                 current_scrollbar_value = 0;
399    
400         if (!screen_)
401                 return;
402
403         screen_->Draw(bv_->text, bv_, current_scrollbar_value);
404
405         if (!lyxrc.cursor_follows_scrollbar) {
406                 waitForX();
407                 return;
408         }
409  
410         LyXText * vbt = bv_->text;
411  
412         int const height = vbt->DefaultHeight();
413         int const first = static_cast<int>((bv_->text->first + height));
414         int const last = static_cast<int>((bv_->text->first + workarea_->height() - height));
415
416         if (vbt->cursor.y() < first)
417                 vbt->SetCursorFromCoordinates(bv_, 0, first);
418         else if (vbt->cursor.y() > last)
419                 vbt->SetCursorFromCoordinates(bv_, 0, last);
420
421         waitForX();
422 }
423
424
425 int BufferView::Pimpl::scrollUp(long time)
426 {
427         if (!buffer_) return 0;
428         if (!screen_) return 0;
429    
430         double value = workarea_->getScrollbarValue();
431    
432         if (value == 0) return 0;
433
434         float add_value =  (bv_->text->DefaultHeight()
435                             + float(time) * float(time) * 0.125);
436    
437         if (add_value > workarea_->height())
438                 add_value = float(workarea_->height() -
439                                   bv_->text->DefaultHeight());
440    
441         value -= add_value;
442
443         if (value < 0)
444                 value = 0;
445    
446         workarea_->setScrollbarValue(value);
447    
448         scrollCB(value); 
449         return 0;
450 }
451
452
453 int BufferView::Pimpl::scrollDown(long time)
454 {
455         if (!buffer_) return 0;
456         if (!screen_) return 0;
457    
458         double value= workarea_->getScrollbarValue();
459         pair<float, float> p = workarea_->getScrollbarBounds();
460         double max = p.second;
461         
462         if (value == max) return 0;
463
464         float add_value =  (bv_->text->DefaultHeight()
465                             + float(time) * float(time) * 0.125);
466    
467         if (add_value > workarea_->height())
468                 add_value = float(workarea_->height() -
469                                   bv_->text->DefaultHeight());
470    
471         value += add_value;
472    
473         if (value > max)
474                 value = max;
475
476         workarea_->setScrollbarValue(value);
477         
478         scrollCB(value); 
479         return 0;
480 }
481
482
483 void BufferView::Pimpl::workAreaKeyPress(KeySym keysym, unsigned int state)
484 {
485         bv_->owner()->getLyXFunc()->processKeySym(keysym, state);
486 }
487
488
489 void BufferView::Pimpl::workAreaMotionNotify(int x, int y, unsigned int state)
490 {
491         // Only use motion with button 1
492         if (!(state & Button1MotionMask))
493                 return;
494
495         if (!buffer_ || !screen_) return;
496
497         // Check for inset locking
498         if (bv_->theLockingInset()) {
499                 LyXCursor cursor = bv_->text->cursor;
500                 LyXFont font = bv_->text->GetFont(bv_->buffer(),
501                                                   cursor.par(), cursor.pos());
502                 int width = bv_->theLockingInset()->width(bv_, font);
503                 int inset_x = font.isVisibleRightToLeft()
504                         ? cursor.x() - width : cursor.x();
505                 int start_x = inset_x + bv_->theLockingInset()->scroll();
506                 bv_->theLockingInset()->
507                         InsetMotionNotify(bv_,
508                                           x - start_x,
509                                           y - cursor.y() + bv_->text->first,
510                                           state);
511                 return;
512         }
513    
514         /* The test for not selection possible is needed, that only motion events are 
515          * used, where the bottom press event was on the drawing area too */
516         if (!selection_possible)
517                 return;
518  
519         screen_->HideCursor();
520
521         bv_->text->SetCursorFromCoordinates(bv_, x, y + bv_->text->first);
522       
523         if (!bv_->text->selection)
524                 update(bv_->text, BufferView::UPDATE); // Maybe an empty line was deleted
525       
526         bv_->text->SetSelection(bv_);
527         screen_->ToggleToggle(bv_->text, bv_);
528         fitCursor(bv_->text);
529         screen_->ShowCursor(bv_->text, bv_);
530 }
531
532
533 // Single-click on work area
534 void BufferView::Pimpl::workAreaButtonPress(int xpos, int ypos,
535                                             unsigned int button)
536 {
537         last_click_x = -1;
538         last_click_y = -1;
539
540         if (!buffer_ || !screen_) return;
541
542         Inset * inset_hit = checkInsetHit(bv_->text, xpos, ypos, button);
543
544         // ok ok, this is a hack.
545         if (button == 4 || button == 5) {
546                 switch (button) {
547                 case 4:
548                         scrollUp(lyxrc.wheel_jump); // default 100, set in lyxrc
549                         break;
550                 case 5:
551                         scrollDown(lyxrc.wheel_jump);
552                         break;
553                 }
554         }
555         
556         if (bv_->theLockingInset()) {
557                 // We are in inset locking mode
558                 
559                 /* Check whether the inset was hit. If not reset mode,
560                    otherwise give the event to the inset */
561                 if (inset_hit == bv_->theLockingInset()) {
562                         bv_->theLockingInset()->
563                                 InsetButtonPress(bv_,
564                                                  xpos, ypos,
565                                                  button);
566                         return;
567                 } else {
568                         bv_->unlockInset(bv_->theLockingInset());
569                 }
570         }
571         
572         if (!inset_hit)
573                 selection_possible = true;
574         screen_->HideCursor();
575
576         int const screen_first = bv_->text->first;
577         
578         // Middle button press pastes if we have a selection
579         bool paste_internally = false;
580         if (button == 2
581             && bv_->text->selection) {
582                 owner_->getLyXFunc()->Dispatch(LFUN_COPY);
583                 paste_internally = true;
584         }
585         
586         // Clear the selection
587         screen_->ToggleSelection(bv_->text, bv_);
588         bv_->text->ClearSelection();
589         bv_->text->FullRebreak(bv_);
590         screen_->Update(bv_->text, bv_);
591         updateScrollbar();
592         
593         // Single left click in math inset?
594         if ((inset_hit != 0) &&
595             (inset_hit->Editable()==Inset::HIGHLY_EDITABLE)) {
596                 // Highly editable inset, like math
597                 UpdatableInset * inset = static_cast<UpdatableInset *>(inset_hit);
598                 selection_possible = false;
599                 owner_->updateLayoutChoice();
600                 owner_->getMiniBuffer()->Set(inset->EditMessage());
601                 inset->InsetButtonPress(bv_, xpos, ypos, button);
602                 inset->Edit(bv_, xpos, ypos, button);
603                 return;
604         } 
605         
606         // Right click on a footnote flag opens float menu
607         if (button == 3) { 
608                 selection_possible = false;
609                 return;
610         }
611         
612         if (!inset_hit) // otherwise it was already set in checkInsetHit(...)
613                 bv_->text->SetCursorFromCoordinates(bv_, xpos, ypos + screen_first);
614         bv_->text->FinishUndo();
615         bv_->text->sel_cursor = bv_->text->cursor;
616         bv_->text->cursor.x_fix(bv_->text->cursor.x());
617         
618         owner_->updateLayoutChoice();
619         if (fitCursor(bv_->text)) {
620                 selection_possible = false;
621         }
622         
623         // Insert primary selection with middle mouse
624         // if there is a local selection in the current buffer,
625         // insert this
626         if (button == 2) {
627                 if (paste_internally)
628                         owner_->getLyXFunc()->Dispatch(LFUN_PASTE);
629                 else
630                         owner_->getLyXFunc()->Dispatch(LFUN_PASTESELECTION,
631                                                        "paragraph");
632                 selection_possible = false;
633                 return;
634         }
635 }
636
637
638 void BufferView::Pimpl::doubleClick(int /*x*/, int /*y*/, unsigned int button) 
639 {
640         // select a word
641         if (!buffer_)
642             return;
643
644         LyXText * text = bv_->getLyXText();
645
646         if (text->bv_owner && bv_->theLockingInset())
647             return;
648
649         if (screen_ && button == 1) {
650             screen_->HideCursor();
651             screen_->ToggleSelection(text, bv_);
652             text->SelectWord(bv_);
653             screen_->ToggleSelection(text, bv_, false);
654             /* This will fit the cursor on the screen
655              * if necessary */
656             update(text, BufferView::SELECT|BufferView::FITCUR);
657         }
658 }
659
660
661 void BufferView::Pimpl::tripleClick(int /*x*/, int /*y*/, unsigned int button)
662 {
663         // select a line
664         if (buffer_)
665                 return;
666
667         LyXText * text = bv_->getLyXText();
668
669         if (text->bv_owner && bv_->theLockingInset())
670             return;
671
672         if (screen_ && (button == 1)) {
673                 screen_->HideCursor();
674                 screen_->ToggleSelection(text, bv_);
675                 text->CursorHome(bv_);
676                 text->sel_cursor = text->cursor;
677                 text->CursorEnd(bv_);
678                 text->SetSelection(bv_);
679                 screen_->ToggleSelection(text, bv_, false);
680                 /* This will fit the cursor on the screen
681                  * if necessary */
682                 update(text, BufferView::SELECT|BufferView::FITCUR);
683         }
684 }
685
686
687 void BufferView::Pimpl::enterView()
688 {
689         if (active() && available()) {
690                 SetXtermCursor(workarea_->getWin());
691                 using_xterm_cursor = true;
692         }
693 }
694
695
696 void BufferView::Pimpl::leaveView()
697 {
698         if (using_xterm_cursor) {
699                 XUndefineCursor(fl_get_display(), workarea_->getWin());
700                 using_xterm_cursor = false;
701         }
702 }
703
704
705 void BufferView::Pimpl::workAreaButtonRelease(int x, int y,
706                                               unsigned int button)
707 {
708         if (!buffer_ || !screen_) return;
709
710         // If we hit an inset, we have the inset coordinates in these
711         // and inset_hit points to the inset.  If we do not hit an
712         // inset, inset_hit is 0, and inset_x == x, inset_y == y.
713         Inset * inset_hit = checkInsetHit(bv_->text, x, y, button);
714
715         if (bv_->theLockingInset()) {
716                 // We are in inset locking mode.
717
718                 /* LyX does a kind of work-area grabbing for insets.
719                    Only a ButtonPress Event outside the inset will 
720                    force a InsetUnlock. */
721                 bv_->theLockingInset()->
722                         InsetButtonRelease(bv_, x, y, button);
723                 return;
724         }
725         
726         selection_possible = false;
727         
728         if (button >= 2) return;
729
730         bv_->setState();
731         owner_->showState();
732
733         // Did we hit an editable inset?
734         if (inset_hit) {
735                 // Inset like error, notes and figures
736                 selection_possible = false;
737
738                 // CHECK fix this proper in 0.13
739
740                 // Following a ref shouldn't issue
741                 // a push on the undo-stack
742                 // anylonger, now that we have
743                 // keybindings for following
744                 // references and returning from
745                 // references.  IMHO though, it
746                 // should be the inset's own business
747                 // to push or not push on the undo
748                 // stack. They don't *have* to
749                 // alter the document...
750                 // (Joacim)
751                 // ...or maybe the SetCursorParUndo()
752                 // below isn't necessary at all anylonger?
753                 if (inset_hit->LyxCode() == Inset::REF_CODE) {
754                         bv_->text->SetCursorParUndo(bv_->buffer());
755                 }
756
757                 owner_->getMiniBuffer()->Set(inset_hit->EditMessage());
758                 if (inset_hit->Editable()==Inset::HIGHLY_EDITABLE) {
759                         // Highly editable inset, like math
760                         UpdatableInset *inset = (UpdatableInset *)inset_hit;
761                         inset->InsetButtonRelease(bv_, x, y, button);
762                 } else {
763                         inset_hit->InsetButtonRelease(bv_, x, y, button);
764                         inset_hit->Edit(bv_, x, y, button);
765                 }
766                 return;
767         }
768
769         // check whether we want to open a float
770         if (bv_->text) {
771                 bool hit = false;
772                 char c = ' ';
773                 if (bv_->text->cursor.pos() <
774                     bv_->text->cursor.par()->Last()) {
775                         c = bv_->text->cursor.par()->
776                                 GetChar(bv_->text->cursor.pos());
777                 }
778 #ifndef NEW_INSETS
779                if(!bv_->text->selection)
780                 if (c == LyXParagraph::META_FOOTNOTE
781                     || c == LyXParagraph::META_MARGIN
782                     || c == LyXParagraph::META_FIG
783                     || c == LyXParagraph::META_TAB
784                     || c == LyXParagraph::META_WIDE_FIG
785                     || c == LyXParagraph::META_WIDE_TAB
786                     || c == LyXParagraph::META_ALGORITHM){
787                         hit = true;
788                 } else
789 #endif
790                         if (bv_->text->cursor.pos() - 1 >= 0) {
791                         c = bv_->text->cursor.par()->
792                                 GetChar(bv_->text->cursor.pos() - 1);
793 #ifndef NEW_INSETS
794                         if (c == LyXParagraph::META_FOOTNOTE
795                             || c == LyXParagraph::META_MARGIN
796                             || c == LyXParagraph::META_FIG
797                             || c == LyXParagraph::META_TAB
798                             || c == LyXParagraph::META_WIDE_FIG 
799                             || c == LyXParagraph::META_WIDE_TAB
800                             || c == LyXParagraph::META_ALGORITHM){
801                                 // We are one step too far to the right
802                                 bv_->text->CursorLeft(bv_);
803                                 hit = true;
804                         }
805 #endif
806                 }
807                 if (hit == true) {
808 #ifndef NEW_INSETS
809                         bv_->toggleFloat();
810 #endif
811                         selection_possible = false;
812                         return;
813                 }
814         }
815
816 #ifndef NEW_INSETS
817         // Do we want to close a float? (click on the float-label)
818         if (bv_->text->cursor.row()->par()->footnoteflag == 
819             LyXParagraph::OPEN_FOOTNOTE
820             && bv_->text->cursor.row()->previous() &&
821             bv_->text->cursor.row()->previous()->par()->
822             footnoteflag != LyXParagraph::OPEN_FOOTNOTE){
823                 LyXFont font(LyXFont::ALL_SANE);
824                 font.setSize(LyXFont::SIZE_FOOTNOTE);
825
826                 int box_x = 20; // LYX_PAPER_MARGIN;
827                 box_x += lyxfont::width(" wide-tab ", font);
828
829                 unsigned int screen_first = bv_->text->first;
830
831                 if (x < box_x
832                     && y + screen_first > bv_->text->cursor.y() -
833                     bv_->text->cursor.row()->baseline()
834                     && y + screen_first < bv_->text->cursor.y() -
835                     bv_->text->cursor.row()->baseline()
836                     + lyxfont::maxAscent(font) * 1.2 + lyxfont::maxDescent(font) * 1.2) {
837                         bv_->toggleFloat();
838                         selection_possible = false;
839                         return;
840                 }
841         }
842 #endif
843
844         // Maybe we want to edit a bibitem ale970302
845         if (bv_->text->cursor.par()->bibkey && x < 20 + 
846             bibitemMaxWidth(bv_, textclasslist.
847                             TextClass(buffer_->
848                                       params.textclass).defaultfont())) {
849                 bv_->text->cursor.par()->bibkey->Edit(bv_, 0, 0, 0);
850         }
851
852         return;
853 }
854
855
856 /* 
857  * Returns an inset if inset was hit. 0 otherwise.
858  * If hit, the coordinates are changed relative to the inset. 
859  * Otherwise coordinates are not changed, and false is returned.
860  */
861 Inset * BufferView::Pimpl::checkInsetHit(LyXText * text, int & x, int & y,
862                                          unsigned int /* button */)
863 {
864         if (!screen_)
865                 return 0;
866   
867         int y_tmp = y + text->first;
868   
869         LyXCursor cursor;
870         text->SetCursorFromCoordinates(bv_, cursor, x, y_tmp);
871
872         if (cursor.pos() < cursor.par()->Last()
873             && cursor.par()->GetChar(cursor.pos()) == LyXParagraph::META_INSET
874             && cursor.par()->GetInset(cursor.pos())
875             && cursor.par()->GetInset(cursor.pos())->Editable()) {
876
877                 // Check whether the inset really was hit
878                 Inset * tmpinset = cursor.par()->GetInset(cursor.pos());
879                 LyXFont font = text->GetFont(bv_->buffer(),
880                                                   cursor.par(), cursor.pos());
881                 int width = tmpinset->width(bv_, font);
882                 int inset_x = font.isVisibleRightToLeft()
883                         ? cursor.x() - width : cursor.x();
884                 int start_x = inset_x + tmpinset->scroll();
885                 int end_x = inset_x + width;
886
887                 if (x > start_x && x < end_x
888                     && y_tmp > cursor.y() - tmpinset->ascent(bv_, font)
889                     && y_tmp < cursor.y() + tmpinset->descent(bv_, font)) {
890                         text->SetCursor(bv_, cursor.par(),cursor.pos(),true);
891                         x = x - start_x;
892                         // The origin of an inset is on the baseline
893                         y = y_tmp - (text->cursor.y()); 
894                         return tmpinset;
895                 }
896         }
897
898         if ((cursor.pos() - 1 >= 0) &&
899             (cursor.par()->GetChar(cursor.pos()-1) == LyXParagraph::META_INSET) &&
900             (cursor.par()->GetInset(cursor.pos() - 1)) &&
901             (cursor.par()->GetInset(cursor.pos() - 1)->Editable())) {
902                 Inset * tmpinset = cursor.par()->GetInset(cursor.pos()-1);
903                 LyXFont font = text->GetFont(bv_->buffer(), cursor.par(),
904                                                   cursor.pos()-1);
905                 int width = tmpinset->width(bv_, font);
906                 int inset_x = font.isVisibleRightToLeft()
907                         ? cursor.x() : cursor.x() - width;
908                 int start_x = inset_x + tmpinset->scroll();
909                 int end_x = inset_x + width;
910
911                 if (x > start_x && x < end_x
912                     && y_tmp > cursor.y() - tmpinset->ascent(bv_, font)
913                     && y_tmp < cursor.y() + tmpinset->descent(bv_, font)) {
914 #if 0
915                         if (move_cursor && (tmpinset != bv_->theLockingInset()))
916 #endif
917                                 text->SetCursor(bv_, cursor.par(),cursor.pos()-1,true);
918                         x = x - start_x;
919                         // The origin of an inset is on the baseline
920                         y = y_tmp - (text->cursor.y()); 
921                         return tmpinset;
922                 }
923         }
924         return 0;
925 }
926
927
928 void BufferView::Pimpl::workAreaExpose()
929 {
930         static int work_area_width = 0;
931         static unsigned int work_area_height = 0;
932
933         bool widthChange = workarea_->workWidth() != work_area_width;
934         bool heightChange = workarea_->height() != work_area_height;
935
936         // update from work area
937         work_area_width = workarea_->workWidth();
938         work_area_height = workarea_->height();
939         if (buffer_ != 0) {
940                 if (widthChange) {
941                         // All buffers need a resize
942                         bufferlist.resize();
943
944                         // Remove all texts from the textcache
945                         // This is not _really_ what we want to do. What
946                         // we really want to do is to delete in textcache
947                         // that does not have a BufferView with matching
948                         // width, but as long as we have only one BufferView
949                         // deleting all gives the same result.
950                         if (lyxerr.debugging())
951                                 textcache.show(lyxerr, "Expose delete all");
952                         textcache.clear();
953                 } else if (heightChange) {
954                         // Rebuild image of current screen
955                         updateScreen();
956                         // fitCursor() ensures we don't jump back
957                         // to the start of the document on vertical
958                         // resize
959                         fitCursor(bv_->text);
960
961                         // The main window size has changed, repaint most stuff
962                         redraw();
963                         // ...including the minibuffer
964                         owner_->getMiniBuffer()->Init();
965
966                 } else if (screen_)
967                     screen_->Redraw(bv_->text, bv_);
968         } else {
969                 // Grey box when we don't have a buffer
970                 workarea_->greyOut();
971         }
972
973         // always make sure that the scrollbar is sane.
974         updateScrollbar();
975         owner_->updateLayoutChoice();
976         return;
977 }
978
979
980 void BufferView::Pimpl::update()
981 {
982         if (screen_) screen_->Update(bv_->text, bv_);
983 }
984
985 // Values used when calling update:
986 // -3 - update
987 // -2 - update, move sel_cursor if selection, fitcursor
988 // -1 - update, move sel_cursor if selection, fitcursor, mark dirty
989 //  0 - update, move sel_cursor if selection, fitcursor 
990 //  1 - update, move sel_cursor if selection, fitcursor, mark dirty
991 //  3 - update, move sel_cursor if selection
992 //
993 // update -
994 // a simple redraw of the parts that need refresh
995 //
996 // move sel_cursor if selection -
997 // the text's sel_cursor is moved if there is selection is progress
998 //
999 // fitcursor -
1000 // fitCursor() is called and the scrollbar updated
1001 //
1002 // mark dirty -
1003 // the buffer is marked dirty.
1004 //
1005 // enum {
1006 //       UPDATE = 0,
1007 //       SELECT = 1,
1008 //       FITCUR = 2,
1009 //       CHANGE = 4 
1010 // };
1011 //
1012 // UPDATE_ONLY = UPDATE;
1013 // UPDATE_SELECT = UPDATE | SELECT;
1014 // UPDATE_SELECT_MOVE = UPDATE | SELECT | FITCUR;
1015 // UPDATE_SELECT_MOVE_AFTER_CHANGE = UPDATE | SELECT | FITCUR | CHANGE;
1016 //
1017 // update(-3) -> update(0)         -> update(0) -> update(UPDATE)
1018 // update(-2) -> update(1 + 2)     -> update(3) -> update(SELECT|FITCUR)
1019 // update(-1) -> update(1 + 2 + 4) -> update(7) -> update(SELECT|FITCUR|CHANGE)
1020 // update(1)  -> update(1 + 2 + 4) -> update(7) -> update(SELECT|FITCUR|CHANGE)
1021 // update(3)  -> update(1)         -> update(1) -> update(SELECT)
1022
1023 void BufferView::Pimpl::update(LyXText * text, BufferView::UpdateCodes f)
1024 {
1025         owner_->updateLayoutChoice();
1026
1027         if (!text->selection && (f & SELECT)) {
1028                 text->sel_cursor = text->cursor;
1029         }
1030
1031         text->FullRebreak(bv_);
1032
1033         if (text->inset_owner) {
1034             text->inset_owner->SetUpdateStatus(bv_, InsetText::CURSOR_PAR);
1035             bv_->updateInset(text->inset_owner, true);
1036         } else
1037             update();
1038
1039         if ((f & FITCUR)) {
1040                 fitCursor(text);
1041         }
1042
1043         if ((f & CHANGE)) {
1044                 if (buffer_->isLyxClean()) {
1045                         buffer_->markDirty();
1046                         owner_->getMiniBuffer()->setTimer(4);
1047                 } else {
1048                         buffer_->markDirty();
1049                 }
1050         }
1051 }
1052
1053
1054 // Callback for cursor timer
1055 void BufferView::Pimpl::cursorToggle()
1056 {
1057         // Quite a nice place for asyncron Inset updating, isn't it?
1058         // Actually no! This is run even if no buffer exist... so (Lgb)
1059         if (!buffer_) {
1060                 cursor_timeout.restart();
1061                 return;
1062         }
1063  
1064         int status = 1;
1065         int pid = waitpid(static_cast<pid_t>(0), &status, WNOHANG);
1066         if (pid == -1) // error find out what is wrong
1067                 ; // ignore it for now.
1068         else if (pid > 0)
1069                 sigchldhandler(pid, &status);
1070
1071         updatelist.update(bv_);
1072         
1073         if (!screen_) {
1074                 cursor_timeout.restart();
1075                 return;
1076         }
1077
1078         if (!bv_->theLockingInset()) {
1079                 screen_->CursorToggle(bv_->text, bv_);
1080         } else {
1081                 bv_->theLockingInset()->ToggleInsetCursor(bv_);
1082         }
1083         
1084         cursor_timeout.restart();
1085 }
1086
1087
1088 void BufferView::Pimpl::cursorPrevious(LyXText * text)
1089 {
1090         if (!text->cursor.row()->previous())
1091                 return;
1092         
1093         int y = text->first;
1094         if (text->inset_owner)
1095                 y += bv_->text->first;
1096         Row * cursorrow = text->cursor.row();
1097         text->SetCursorFromCoordinates(bv_, bv_->text->cursor.x_fix(), y);
1098         bv_->text->FinishUndo();
1099         // This is to allow jumping over large insets
1100         if ((cursorrow == text->cursor.row()))
1101                 text->CursorUp(bv_);
1102         
1103         if (text->inset_owner ||
1104             text->cursor.row()->height() < workarea_->height())
1105                 screen_->Draw(bv_->text, bv_,
1106                               text->cursor.y()
1107                               - text->cursor.row()->baseline()
1108                               + text->cursor.row()->height()
1109                               - workarea_->height() + 1 );
1110         updateScrollbar();
1111 }
1112
1113
1114 void BufferView::Pimpl::cursorNext(LyXText * text)
1115 {
1116         if (!text->cursor.row()->next())
1117                 return;
1118         
1119         int y = text->first + workarea_->height();
1120 //      if (text->inset_owner)
1121 //              y += bv_->text->first;
1122         text->GetRowNearY(y);
1123     
1124         Row * cursorrow = text->cursor.row();
1125         text->SetCursorFromCoordinates(bv_, text->cursor.x_fix(), y); // + workarea_->height());
1126         bv_->text->FinishUndo();
1127         // This is to allow jumping over large insets
1128         if ((cursorrow == bv_->text->cursor.row()))
1129                 text->CursorDown(bv_);
1130         
1131         if (text->inset_owner ||
1132             text->cursor.row()->height() < workarea_->height())
1133                 screen_->Draw(bv_->text, bv_, text->cursor.y() -
1134                               text->cursor.row()->baseline());
1135         updateScrollbar();
1136 }
1137
1138
1139 bool BufferView::Pimpl::available() const
1140 {
1141         if (buffer_ && bv_->text) return true;
1142         return false;
1143 }
1144
1145
1146 void BufferView::Pimpl::beforeChange(LyXText * text)
1147 {
1148         toggleSelection();
1149         text->ClearSelection();
1150 }
1151
1152
1153 void BufferView::Pimpl::savePosition(unsigned int i)
1154 {
1155         if (i >= saved_positions_num)
1156                 return;
1157         saved_positions[i] = Position(buffer_->fileName(),
1158                                       bv_->text->cursor.par()->id(),
1159                                       bv_->text->cursor.pos());
1160         if (i > 0)
1161                 owner_->getMiniBuffer()->Set(_("Saved bookmark ") + tostr(i));
1162 }
1163
1164
1165 void BufferView::Pimpl::restorePosition(unsigned int i)
1166 {
1167         if (i >= saved_positions_num)
1168                 return;
1169
1170         string fname = saved_positions[i].filename;
1171
1172         beforeChange(bv_->text);
1173
1174         if (fname != buffer_->fileName()) {
1175                 Buffer * b = bufferlist.exists(fname) ?
1176                         bufferlist.getBuffer(fname) :
1177                         bufferlist.loadLyXFile(fname); // don't ask, just load it
1178                 if (b != 0 ) buffer(b);
1179         }
1180
1181         LyXParagraph * par = bv_->text->GetParFromID(saved_positions[i].par_id);
1182         if (!par)
1183                 return;
1184
1185         bv_->text->SetCursor(bv_, par,
1186                              min(par->Last(), saved_positions[i].par_pos));
1187         update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
1188         if (i > 0)
1189                 owner_->getMiniBuffer()->Set(_("Moved to bookmark ") + tostr(i));
1190 }
1191
1192
1193 bool BufferView::Pimpl::isSavedPosition(unsigned int i)
1194 {
1195         if (i >= saved_positions_num)
1196                 return false;
1197
1198         return !saved_positions[i].filename.empty();
1199 }
1200
1201
1202 void BufferView::Pimpl::setState()
1203 {
1204         if (!lyxrc.rtl_support)
1205                 return;
1206
1207         LyXText * text = bv_->getLyXText();
1208         if (text->real_current_font.isRightToLeft() &&
1209             text->real_current_font.latex() != LyXFont::ON) {
1210                 if (owner_->getIntl()->primarykeymap)
1211                         owner_->getIntl()->KeyMapSec();
1212         } else {
1213                 if (!owner_->getIntl()->primarykeymap)
1214                         owner_->getIntl()->KeyMapPrim();
1215         }
1216 }
1217
1218
1219 void BufferView::Pimpl::insetSleep()
1220 {
1221         if (bv_->theLockingInset() && !bv_->inset_slept) {
1222                 bv_->theLockingInset()->GetCursorPos(bv_, bv_->slx, bv_->sly);
1223                 bv_->theLockingInset()->InsetUnlock(bv_);
1224                 bv_->inset_slept = true;
1225         }
1226 }
1227
1228
1229 void BufferView::Pimpl::insetWakeup()
1230 {
1231         if (bv_->theLockingInset() && bv_->inset_slept) {
1232                 bv_->theLockingInset()->Edit(bv_, bv_->slx, bv_->sly, 0);
1233                 bv_->inset_slept = false;
1234         }
1235 }
1236
1237
1238 void BufferView::Pimpl::insetUnlock()
1239 {
1240         if (bv_->theLockingInset()) {
1241                 if (!bv_->inset_slept)
1242                         bv_->theLockingInset()->InsetUnlock(bv_);
1243                 bv_->theLockingInset(0);
1244                 bv_->text->FinishUndo();
1245                 bv_->inset_slept = false;
1246         }
1247 }
1248
1249
1250 bool BufferView::Pimpl::focus() const
1251 {
1252         return workarea_->hasFocus();
1253 }
1254
1255
1256 void BufferView::Pimpl::focus(bool f)
1257 {
1258         if (f) workarea_->setFocus();
1259 }
1260
1261
1262 bool BufferView::Pimpl::active() const
1263 {
1264         return workarea_->active();
1265 }
1266
1267
1268 bool BufferView::Pimpl::belowMouse() const 
1269 {
1270         return workarea_->belowMouse();
1271 }
1272
1273
1274 void BufferView::Pimpl::showCursor()
1275 {
1276         if (screen_)
1277                 screen_->ShowCursor(bv_->text, bv_);
1278 }
1279
1280
1281 void BufferView::Pimpl::hideCursor()
1282 {
1283         if (screen_)
1284                 screen_->HideCursor();
1285 }
1286
1287
1288 void BufferView::Pimpl::toggleSelection(bool b)
1289 {
1290         if (screen_)
1291                 screen_->ToggleSelection(bv_->text, bv_, b);
1292 }
1293
1294
1295 void BufferView::Pimpl::toggleToggle()
1296 {
1297         if (screen_)
1298                 screen_->ToggleToggle(bv_->text, bv_);
1299 }
1300
1301
1302 void BufferView::Pimpl::center() 
1303 {
1304         beforeChange(bv_->text);
1305         if (bv_->text->cursor.y() > static_cast<int>((workarea_->height() / 2))) {
1306                 screen_->Draw(bv_->text, bv_, bv_->text->cursor.y() - workarea_->height() / 2);
1307         } else {
1308                 screen_->Draw(bv_->text, bv_, 0);
1309         }
1310         update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
1311         redraw();
1312 }
1313
1314
1315 void BufferView::Pimpl::pasteClipboard(bool asPara) 
1316 {
1317         if (!buffer_) return;
1318
1319         screen_->HideCursor();
1320         beforeChange(bv_->text);
1321         
1322         string const clip(workarea_->getClipboard());
1323         
1324         if (clip.empty()) return;
1325
1326         if (asPara) {
1327                 bv_->text->InsertStringB(bv_, clip);
1328         } else {
1329                 bv_->text->InsertStringA(bv_, clip);
1330         }
1331         update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
1332 }
1333
1334
1335 void BufferView::Pimpl::stuffClipboard(string const & stuff) const
1336 {
1337         workarea_->putClipboard(stuff);
1338 }