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