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