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