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