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