]> git.lyx.org Git - lyx.git/blob - src/BufferView.C
7daf167b0fad512978e04b1a690f4c4e5aec8c2e
[lyx.git] / src / BufferView.C
1 // -*- C++ -*-
2 /* This file is part of
3  * ====================================================== 
4  * 
5  *           LyX, The Document Processor
6  *        
7  *           Copyright 1995 Matthias Ettrich
8  *           Copyright 1995-1999 The LyX Team.
9  *
10  * ====================================================== */
11
12 #include <config.h>
13
14 #include <algorithm>
15 using std::for_each;
16
17 #include <cstdlib>
18 #include <csignal>
19
20 #include <unistd.h>
21 #include <sys/wait.h>
22
23 #include "support/lstrings.h"
24
25 #ifdef __GNUG__
26 #pragma implementation
27 #endif
28
29 #include "commandtags.h"
30 #include "BufferView.h"
31 #include "bufferlist.h"
32 #include "LyXView.h"
33 #include "lyxfunc.h"
34 #include "insets/lyxinset.h"
35 #include "minibuffer.h"
36 #include "lyxscreen.h"
37 #include "up.xpm"
38 #include "down.xpm"
39 #include "debug.h"
40 #include "lyxdraw.h"
41 #include "lyx_gui_misc.h"
42 #include "BackStack.h"
43 #include "lyxtext.h"
44 #include "lyx_cb.h"
45 #include "gettext.h"
46 #include "layout.h"
47
48 using std::find_if;
49
50 extern BufferList bufferlist;
51 void sigchldhandler(pid_t pid, int * status);
52
53 extern void SetXtermCursor(Window win);
54 extern bool input_prohibited;
55 extern bool selection_possible;
56 extern char ascii_type;
57 //extern int UnlockInset(UpdatableInset * inset);
58 extern void MenuPasteSelection(char at);
59 extern InsetUpdateStruct * InsetUpdateList;
60 extern void UpdateInsetUpdateList();
61 extern void FreeUpdateTimer();
62
63 // This is _very_ temporary
64 FL_OBJECT * figinset_canvas;
65
66 BufferView::BufferView(LyXView * o, int xpos, int ypos,
67                        int width, int height)
68         : owner_(o)
69 {
70         buffer_ = 0;
71         text = 0;
72         screen = 0;
73         work_area = 0;
74         figinset_canvas = 0;
75         scrollbar = 0;
76         button_down = 0;
77         button_up = 0;
78         timer_cursor = 0;
79         current_scrollbar_value = 0;
80         create_view(xpos, ypos, width, height);
81         // Activate the timer for the cursor 
82         fl_set_timer(timer_cursor, 0.4);
83         fl_set_focus_object(owner_->getForm(), work_area);
84         work_area_focus = true;
85         lyx_focus = false;
86         the_locking_inset = 0;
87         inset_slept = false;
88 }
89
90
91 BufferView::~BufferView()
92 {
93         delete text;
94 }
95
96 // This is only the very first implemetation and use of the TextCache,
97 // operations on it needs to be put into a class or a namespace, that part
98 // is _NOT_ finished so don't bother to come with too many comments on it
99 // (unless you have some nice ideas on where/how to do it)
100 //
101 // I think we need a TextCache that is common for all BufferViews,
102 // please tell if you don't agree.
103 //
104 // Q. What are we caching?
105 // A. We are caching the screen representations (LyXText) of the
106 //    documents (Buffer,LyXParagraph) for specific BufferView widths.
107 // Q. Why the cache?
108 // A. It is not really needed, but it speeds things up a lot
109 //    when you have more than one document loaded at once since a total
110 //    rebreak (reformatting) need not be done when switching between
111 //    documents. When the cache is in function a document only needs to be
112 //    formatted upon loading and when the with of the BufferView changes.
113 //    Later it will also be unneccessary to reformat when having two
114 //    BufferViews of equal width with the same document, a simple copy
115 //    of the LyXText structure will do.
116 // Invariant for the TextCache:
117 //        - The buffer of the text  in the TextCache _must_ exists
118 //          in the bufferlist.
119 //        - For a text in the TextCache there _must not_ be an equivalent
120 //          text in any BufferView. (same buffer and width).
121 // Among others this mean:
122 //        - When a document is closed all trace of it must be removed from
123 //          the TextCache.
124 // Scenarios:
125 //    I believe there are only three possible scenarios where the two first
126 //    are also covered by the third.
127 //        - The simplest scenario is what we have now, a single
128 //          BufferView only.  
129 //          o Opening
130 //            Nothing to do with the TextCache is done when opening a file.
131 //          o Switching
132 //            We switch from buffer A to buffer B.
133 //            * A's text is cached in TextCache.
134 //            * We make a search for a text in TextCache that fits B
135 //              (same buffer and same width).
136 //          o Horizontal resize
137 //            If the BufferView's width (LyXView) is horizontally changed all
138 //            the entries in the TextCache are deleted. (This causes
139 //            reformat of all loaded documents when next viewed)
140 //          o Close
141 //            When a buffer is closed we don't have to do anything, because
142 //            to close a single buffer it is required to only exist in the
143 //            BufferView and not in the TextCache. Upon LFUN_QUIT we
144 //            don't really care since everything is deleted anyway.
145 //        - The next scenario is when we have several BufferViews (in one or
146 //          more LyXViews) of equal width.
147 //          o Opening
148 //            Nothing to do with the TextCache is done when opening a file.
149 //          o Switching
150 //            We switch from buffer A to buffer B.
151 //            * If A is in another Bufferview we do not put it into TextCache.
152 //              else we put A into TextCache.
153 //            * If B is viewed in another BufferView we make a copy of its
154 //              text and use that, else we search in TextCache for a match.
155 //              (same buffer same width)
156 //          o Horizontal resize
157 //            If the BufferView's width (LyXView) is horisontaly changed all
158 //            the entries in the TextCache is deleted. (This causes
159 //            reformat of all loaded documents when next viewed)
160 //          o Close
161 //        - The last scenario should cover both the previous ones, this time
162 //          we have several BufferViews (in one or more LyXViews) with no
163 //          limitations on width. (And if you wonder why the two other
164 //          senarios are needed... I used them to get to this one.)
165 //          o Opening
166 //            Nothing to do with the TextCache is done when opening a file.
167 //          o Switching
168 //            We switch from buffer A to buffer B.
169 //          o Horisontal rezize
170 //          o Close
171
172 typedef vector<LyXText*> TextCache;
173 TextCache textcache;
174
175 class text_fits {
176 public:
177         text_fits(Buffer * b, unsigned short p)
178                 : buf(b), pw(p) {}
179         bool operator()(TextCache::value_type & vt) {
180                 if (vt->params == buf && vt->paperWidth() == pw) return true;
181                 return false;
182         }
183 private:
184         Buffer * buf;
185         unsigned short pw;
186 };
187
188
189 class show_text {
190 public:
191         show_text(ostream & o) : os(o) {}
192         void operator()(TextCache::value_type & vt) {
193                 os << "Buffer: " << vt->params
194                    << "\nWidth: " << vt->paperWidth() << endl;
195         }
196 private:
197         ostream & os;
198 };
199
200 void showTextCache(string const & str)
201 {
202         lyxerr << "TextCache: " << str << endl;
203         for_each(textcache.begin(), textcache.end(), show_text(lyxerr));
204 }
205
206               
207 void BufferView::buffer(Buffer * b)
208 {
209         lyxerr[Debug::INFO] << "Setting buffer in BufferView" << endl;
210         if (buffer_) {
211                 insetSleep();
212                 buffer_->delUser(this);
213                 // Put the old text into the TextCache.
214                 textcache.push_back(text);
215                 showTextCache("buffer");
216                 // delete text;
217                 text = 0;
218         }
219
220         // Set current buffer
221         buffer_ = b;
222
223         if (bufferlist.getState() == BufferList::CLOSING) return;
224         
225         // Nuke old image
226         // screen is always deleted when the buffer is changed.
227         if (screen)
228                 delete screen;
229         screen = 0;
230
231         // If we are closing the buffer, use the first buffer as current
232         if (!buffer_) {
233                 buffer_ = bufferlist.first();
234         }
235
236         if (buffer_) {
237                 lyxerr[Debug::INFO] << "  Buffer addr: " << buffer_ << endl;
238                 buffer_->addUser(this);
239                 owner_->getMenus()->showMenus();
240                 // If we don't have a text object for this, we make one
241                 if (text == 0)
242                         resizeCurrentBuffer();
243                 else {
244                         updateScreen();
245                         updateScrollbar();
246                 }
247                 screen->first = screen->TopCursorVisible();
248                 redraw();
249                 updateAllVisibleBufferRelatedPopups();
250                 insetWakeup();
251         } else {
252                 lyxerr[Debug::INFO] << "  No Buffer!" << endl;
253                 owner_->getMenus()->hideMenus();
254                 updateScrollbar();
255                 fl_redraw_object(work_area);
256                 // Also remove all remaining text's from the testcache.
257                 showTextCache("buffer delete all");
258                 while (!textcache.empty()) {
259                         LyXText * tt = textcache.front();
260                         textcache.erase(textcache.begin());
261                         delete tt;
262                 }
263         }
264         // should update layoutchoice even if we don't have a buffer.
265         owner_->updateLayoutChoice();
266         owner_->getMiniBuffer()->Init();
267         owner_->updateWindowTitle();
268 }
269
270
271 void BufferView::updateScreen()
272 {
273         // Regenerate the screen.
274         if (screen)
275                 delete screen;
276         screen = new LyXScreen(FL_ObjWin(work_area),
277                                work_area->w,
278                                work_area->h,
279                                work_area->x,
280                                work_area->y,
281                                text);
282 }
283
284
285 void BufferView::resize()
286 {
287         // This will resize the buffer. (Asger)
288         if (buffer_)
289                 resizeCurrentBuffer();
290 }
291
292
293 static bool lgb_hack = false;
294
295 void BufferView::redraw()
296 {
297         lyxerr[Debug::INFO] << "BufferView::redraw()" << endl;
298         lgb_hack = true;
299         fl_redraw_object(work_area);
300         fl_redraw_object(scrollbar);
301         fl_redraw_object(button_down);
302         fl_redraw_object(button_up);
303         lgb_hack = false;
304 }
305
306
307 void BufferView::fitCursor()
308 {
309         if (screen) screen->FitCursor();
310 }
311
312
313 void BufferView::update()
314 {
315         if (screen) screen->Update();
316 }
317
318
319 void BufferView::updateScrollbar()
320 {
321         /* If the text is smaller than the working area, the scrollbar
322          * maximum must be the working area height. No scrolling will 
323          * be possible */
324
325         if (!buffer_) {
326                 fl_set_slider_value(scrollbar, 0);
327                 fl_set_slider_size(scrollbar, scrollbar->h);
328                 return;
329         }
330         
331         static long max2 = 0;
332         static long height2 = 0;
333
334         long cbth = 0;
335         long cbsf = 0;
336
337         if (text)
338                 cbth = text->height;
339         if (screen)
340                 cbsf = screen->first;
341
342         // check if anything has changed.
343         if (max2 == cbth &&
344             height2 == work_area->h &&
345             current_scrollbar_value == cbsf)
346                 return;       // no
347         
348         max2 = cbth;
349         height2 = work_area->h;
350         current_scrollbar_value = cbsf;
351
352         if (cbth <= height2) { // text is smaller than screen
353                 fl_set_slider_size(scrollbar, scrollbar->h);
354                 return;
355         }
356         
357         long maximum_height = work_area->h * 3 / 4 + cbth;
358         long value = cbsf;
359
360         // set the scrollbar
361         double hfloat = work_area->h;
362         double maxfloat = maximum_height;
363    
364         fl_set_slider_value(scrollbar, value);
365         fl_set_slider_bounds(scrollbar, 0,
366                              maximum_height - work_area->h);
367 #if FL_REVISION > 85
368         double lineh = text->DefaultHeight();
369         fl_set_slider_increment(scrollbar, work_area->h-lineh, lineh);
370 #endif
371         if (maxfloat > 0){
372                 if ((hfloat / maxfloat) * float(height2) < 3)
373                         fl_set_slider_size(scrollbar,
374                                            3 / float(height2));
375                 else
376                         fl_set_slider_size(scrollbar,
377                                            hfloat / maxfloat);
378         } else
379                 fl_set_slider_size(scrollbar, hfloat);
380         fl_set_slider_precision(scrollbar, 0);
381 }
382
383
384 void BufferView::redoCurrentBuffer()
385 {
386         lyxerr[Debug::INFO] << "BufferView::redoCurrentBuffer" << endl;
387         if (buffer_ && text) {
388                 resize();
389                 owner_->updateLayoutChoice();
390         }
391 }
392
393
394 int BufferView::resizeCurrentBuffer()
395 {
396         lyxerr[Debug::INFO] << "resizeCurrentBuffer" << endl;
397         
398         LyXParagraph * par = 0;
399         LyXParagraph * selstartpar = 0;
400         LyXParagraph * selendpar = 0;
401         int pos = 0;
402         int selstartpos = 0;
403         int selendpos = 0;
404         int selection = 0;
405         int mark_set = 0;
406
407         ProhibitInput();
408
409         owner_->getMiniBuffer()->Set(_("Formatting document..."));   
410
411         if (text) {
412                 par = text->cursor.par;
413                 pos = text->cursor.pos;
414                 selstartpar = text->sel_start_cursor.par;
415                 selstartpos = text->sel_start_cursor.pos;
416                 selendpar = text->sel_end_cursor.par;
417                 selendpos = text->sel_end_cursor.pos;
418                 selection = text->selection;
419                 mark_set = text->mark_set;
420                 delete text;
421                 text = new LyXText(work_area->w, buffer_);
422         } else {
423                 // See if we have a text in TextCache that fits
424                 // the new buffer_ with the correct width.
425                 TextCache::iterator it =
426                         find_if(textcache.begin(),
427                                 textcache.end(),
428                                 text_fits(buffer_,
429                                           work_area->w));
430                 if (it != textcache.end()) {
431                         text = *it;
432                         // take it out of textcache.
433                         textcache.erase(it);
434                         showTextCache("resizeCurrentBuffer");
435                 } else {
436                         text = new LyXText(work_area->w, buffer_);
437                 }
438         }
439         updateScreen();
440
441         if (par) {
442                 text->selection = true;
443                 /* at this point just to avoid the Delete-Empty-Paragraph
444                  * Mechanism when setting the cursor */
445                 text->mark_set = mark_set;
446                 if (selection) {
447                         text->SetCursor(selstartpar, selstartpos);
448                         text->sel_cursor = text->cursor;
449                         text->SetCursor(selendpar, selendpos);
450                         text->SetSelection();
451                         text->SetCursor(par, pos);
452                 } else {
453                         text->SetCursor(par, pos);
454                         text->sel_cursor = text->cursor;
455                         text->selection = false;
456                 }
457         }
458         screen->first = screen->TopCursorVisible(); /* this will scroll the
459                                                      * screen such that the
460                                                      * cursor becomes
461                                                      * visible */ 
462         updateScrollbar();
463         redraw();
464         owner_->getMiniBuffer()->Init();
465         AllowInput();
466
467         // Now if the title form still exist kill it
468         TimerCB(0, 0);
469
470         return 0;
471 }
472
473
474 void BufferView::gotoError()
475 {
476         if (!screen)
477                 return;
478    
479         screen->HideCursor();
480         beforeChange();
481         update(-2);
482         LyXCursor tmp;
483
484         if (!text->GotoNextError()) {
485                 if (text->cursor.pos 
486                     || text->cursor.par != text->FirstParagraph()) {
487                         tmp = text->cursor;
488                         text->cursor.par = text->FirstParagraph();
489                         text->cursor.pos = 0;
490                         if (!text->GotoNextError()) {
491                                 text->cursor = tmp;
492                                 owner_->getMiniBuffer()
493                                         ->Set(_("No more errors"));
494                                 LyXBell();
495                         }
496                 } else {
497                         owner_->getMiniBuffer()->Set(_("No more errors"));
498                         LyXBell();
499                 }
500         }
501         update(0);
502         text->sel_cursor = text->cursor;
503 }
504
505
506 extern "C" {
507 // Just a bunch of C wrappers around static members of BufferView
508         void C_BufferView_UpCB(FL_OBJECT * ob, long buf)
509         {
510                 BufferView::UpCB(ob, buf);
511         }
512
513
514         void C_BufferView_DownCB(FL_OBJECT * ob, long buf)
515         {
516                 BufferView::DownCB(ob, buf);
517         }
518
519
520         void C_BufferView_ScrollCB(FL_OBJECT * ob, long buf)
521         {
522                 BufferView::ScrollCB(ob, buf);
523         }
524
525
526         void C_BufferView_CursorToggleCB(FL_OBJECT * ob, long buf)
527         {
528                 BufferView::CursorToggleCB(ob, buf);
529         }
530
531
532         int C_BufferView_work_area_handler(FL_OBJECT * ob, int event,
533                                            FL_Coord, FL_Coord, 
534                                            int key, void * xev)
535         {
536                 return BufferView::work_area_handler(ob, event,
537                                                      0, 0, key, xev);
538         }
539 }
540
541
542 void BufferView::create_view(int xpos, int ypos, int width, int height)
543 {
544         FL_OBJECT * obj;
545         int const bw = abs(fl_get_border_width());
546
547         // a hack for the figinsets (Matthias)
548         // This one first, then it will probably be invisible. (Lgb)
549         ::figinset_canvas = figinset_canvas = obj = 
550                   fl_add_canvas(FL_NORMAL_CANVAS,
551                                 xpos + 1,
552                                 ypos + 1, 1, 1, "");
553         fl_set_object_boxtype(obj, FL_NO_BOX);
554         fl_set_object_resize(obj, FL_RESIZE_ALL);
555         fl_set_object_gravity(obj, NorthWestGravity, NorthWestGravity);
556
557         // a box
558         obj = fl_add_box(FL_BORDER_BOX, xpos, ypos,
559                          width - 15,
560                          height, "");
561         fl_set_object_resize(obj, FL_RESIZE_ALL);
562         fl_set_object_gravity(obj, NorthWestGravity, SouthEastGravity);
563
564         // the free object
565         work_area = obj = fl_add_free(FL_INPUT_FREE,
566                                       xpos + bw, ypos + bw,
567                                       width - 15 - 2 * bw /* scrollbarwidth */,
568                                       height - 2 * bw, "",
569                                       C_BufferView_work_area_handler);
570         obj->wantkey = FL_KEY_TAB;
571         obj->u_vdata = this; /* This is how we pass the BufferView
572                                 to the work_area_handler. */
573         fl_set_object_boxtype(obj, FL_DOWN_BOX);
574         fl_set_object_resize(obj, FL_RESIZE_ALL);
575         fl_set_object_gravity(obj, NorthWestGravity, SouthEastGravity);
576
577         //
578         // THE SCROLLBAR
579         //
580
581         // up - scrollbar button
582 #if FL_REVISION > 85
583         fl_set_border_width(-1);
584 #else
585         fl_set_border_width(-2); // to get visible feedback
586 #endif
587         button_up = obj = fl_add_pixmapbutton(FL_TOUCH_BUTTON,
588                                               width - 15 + 4 * bw,
589                                               ypos,
590                                               15, 15, "");
591         fl_set_object_boxtype(obj, FL_UP_BOX);
592         fl_set_object_color(obj, FL_MCOL, FL_BLUE);
593         fl_set_object_resize(obj, FL_RESIZE_ALL);
594         fl_set_object_gravity(obj, NorthEastGravity, NorthEastGravity);
595         fl_set_object_callback(obj, C_BufferView_UpCB, 0);
596         obj->u_vdata = this;
597         fl_set_pixmapbutton_data(obj, const_cast<char**>(up_xpm));
598
599 #if FL_REVISION > 85
600         // Remove the blue feedback rectangle
601         fl_set_pixmapbutton_focus_outline(obj, 0);
602 #endif  
603
604         // the scrollbar slider
605         fl_set_border_width(-bw);
606         scrollbar = obj = fl_add_slider(FL_VERT_SLIDER,
607                                         width - 15 + 4 * bw,
608                                         ypos + 15,
609                                         15, height - 30, "");
610         fl_set_object_color(obj, FL_COL1, FL_MCOL);
611         fl_set_object_boxtype(obj, FL_UP_BOX);
612         fl_set_object_resize(obj, FL_RESIZE_ALL);
613         fl_set_object_gravity(obj, NorthEastGravity, SouthEastGravity);
614         fl_set_object_callback(obj, C_BufferView_ScrollCB, 0);
615         obj->u_vdata = this;
616         
617         // down - scrollbar button
618 #if FL_REVISION > 85
619         fl_set_border_width(-1);
620 #else
621         fl_set_border_width(-2); // to get visible feedback
622 #endif
623         button_down = obj = fl_add_pixmapbutton(FL_TOUCH_BUTTON,
624                                                 width - 15 + 4 * bw,
625                                                 ypos + height - 15,
626                                                 15, 15, "");
627         fl_set_object_boxtype(obj, FL_UP_BOX);
628         fl_set_object_color(obj, FL_MCOL, FL_BLUE);
629         fl_set_object_resize(obj, FL_RESIZE_ALL);
630         fl_set_object_gravity(obj, SouthEastGravity, SouthEastGravity);
631         fl_set_object_callback(obj, C_BufferView_DownCB, 0);
632         obj->u_vdata = this;
633         fl_set_pixmapbutton_data(obj, const_cast<char**>(down_xpm));
634         fl_set_border_width(-bw);
635
636 #if FL_REVISION > 85
637         // Remove the blue feedback rectangle
638         fl_set_pixmapbutton_focus_outline(obj, 0);
639 #endif  
640
641         //
642         // TIMERS
643         //
644         
645         // timer_cursor
646         timer_cursor = obj = fl_add_timer(FL_HIDDEN_TIMER,
647                                           0, 0, 0, 0, "Timer");
648         fl_set_object_callback(obj, C_BufferView_CursorToggleCB, 0);
649         obj->u_vdata = this;
650 }
651
652
653 // Callback for scrollbar up button
654 void BufferView::UpCB(FL_OBJECT * ob, long)
655 {
656         BufferView * view = static_cast<BufferView*>(ob->u_vdata);
657         
658         if (view->buffer_ == 0) return;
659
660         static long time = 0;
661         XEvent const * ev2 = fl_last_event();
662         if (ev2->type == ButtonPress || ev2->type == ButtonRelease) 
663                 time = 0;
664         int button = fl_get_button_numb(ob);
665         switch (button) {
666         case 3:
667                 view->ScrollUpOnePage(time++); break;
668         case 2:
669                 view->ScrollDownOnePage(time++); break;
670         default:
671                 view->ScrollUp(time++); break;
672         }
673 }
674
675
676 static
677 void waitForX()
678 {
679 #if 0
680         static Window w = 0;
681         static Atom a = 0;
682         if (!a)
683                 a = XInternAtom(fl_display, "WAIT_FOR_X", False);
684         if (w == 0) {
685                 int mask;
686                 XSetWindowAttributes attr;
687                 mask = CWOverrideRedirect;
688                 attr.override_redirect = 1;
689                 w = XCreateWindow(fl_display, fl_root,
690                                   0, 0, 1, 1, 0, CopyFromParent,
691                                   InputOnly, CopyFromParent, mask, &attr);
692                 XSelectInput(fl_display, w, PropertyChangeMask);
693                 XMapWindow(fl_display, w);
694         }
695         static XEvent ev;
696         XChangeProperty(fl_display, w, a, a, 8,
697                         PropModeAppend,
698                         reinterpret_cast<unsigned char*>(""), 0);
699         XWindowEvent(fl_display, w, PropertyChangeMask, &ev);
700 #endif
701         XSync(fl_get_display(), 0);
702 }
703
704
705 // Callback for scrollbar slider
706 void BufferView::ScrollCB(FL_OBJECT * ob, long)
707 {
708         BufferView * view = static_cast<BufferView*>(ob->u_vdata);
709         extern bool cursor_follows_scrollbar;
710         
711         if (view->buffer_ == 0) return;
712
713         view->current_scrollbar_value = long(fl_get_slider_value(ob));
714         if (view->current_scrollbar_value < 0)
715                 view->current_scrollbar_value = 0;
716    
717         if (!view->screen)
718                 return;
719
720         view->screen->Draw(view->current_scrollbar_value);
721
722         if (cursor_follows_scrollbar) {
723                 LyXText * vbt = view->text;
724                 int height = vbt->DefaultHeight();
725                 
726                 if (vbt->cursor.y < view->screen->first + height) {
727                         vbt->SetCursorFromCoordinates(0,
728                                                       view->screen->first +
729                                                       height);
730                 }
731                 else if (vbt->cursor.y >
732                          view->screen->first + view->work_area->h - height) {
733                         vbt->SetCursorFromCoordinates(0,
734                                                       view->screen->first +
735                                                       view->work_area->h  -
736                                                       height);
737                 }
738         }
739         waitForX();
740 }
741
742
743 // Callback for scrollbar down button
744 void BufferView::DownCB(FL_OBJECT * ob, long)
745 {
746         BufferView * view = static_cast<BufferView*>(ob->u_vdata);
747
748         if (view->buffer_ == 0) return;
749         
750         XEvent const * ev2;
751         static long time = 0;
752         ev2 = fl_last_event();
753         if (ev2->type == ButtonPress || ev2->type == ButtonRelease) 
754                 time = 0;
755         int button = fl_get_button_numb(ob);
756         switch (button) {
757         case 2:
758                 view->ScrollUpOnePage(time++); break;
759         case 3:
760                 view->ScrollDownOnePage(time++); break;
761         default:
762                 view->ScrollDown(time++); break;
763         }
764 }
765
766
767 int BufferView::ScrollUp(long time)
768 {
769         if (buffer_ == 0) return 0;
770         if (!screen) return 0;
771    
772         double value = fl_get_slider_value(scrollbar);
773    
774         if (value == 0) return 0;
775
776         float add_value =  (text->DefaultHeight()
777                             + float(time) * float(time) * 0.125);
778    
779         if (add_value > work_area->h)
780                 add_value = float(work_area->h -
781                                   text->DefaultHeight());
782    
783         value -= add_value;
784
785         if (value < 0)
786                 value = 0;
787    
788         fl_set_slider_value(scrollbar, value);
789    
790         ScrollCB(scrollbar, 0); 
791         return 0;
792 }
793
794
795 int BufferView::ScrollDown(long time)
796 {
797         if (buffer_ == 0) return 0;
798         if (!screen) return 0;
799    
800         double value= fl_get_slider_value(scrollbar);
801         double min, max;
802         fl_get_slider_bounds(scrollbar, &min, &max);
803
804         if (value == max) return 0;
805
806         float add_value =  (text->DefaultHeight()
807                             + float(time) * float(time) * 0.125);
808    
809         if (add_value > work_area->h)
810                 add_value = float(work_area->h -
811                                   text->DefaultHeight());
812    
813         value += add_value;
814    
815         if (value > max)
816                 value = max;
817    
818         fl_set_slider_value(scrollbar, value);
819    
820         ScrollCB(scrollbar, 0); 
821         return 0;
822 }
823
824
825 void BufferView::ScrollUpOnePage(long /*time*/)
826 {
827         if (buffer_ == 0) return;
828         if (!screen) return;
829    
830         long y = screen->first;
831
832         if (!y) return;
833
834         Row * row = text->GetRowNearY(y);
835
836         y = y - work_area->h + row->height;
837         
838         fl_set_slider_value(scrollbar, y);
839    
840         ScrollCB(scrollbar, 0); 
841 }
842
843
844 void BufferView::ScrollDownOnePage(long /*time*/)
845 {
846         if (buffer_ == 0) return;
847         if (!screen) return;
848    
849         double min, max;
850         fl_get_slider_bounds(scrollbar, &min, &max);
851         long y = screen->first;
852
853         if (y > text->height - work_area->h)
854                 return;
855    
856         y += work_area->h;
857         text->GetRowNearY(y);
858
859         fl_set_slider_value(scrollbar, y);
860    
861         ScrollCB(scrollbar, 0); 
862 }
863
864
865 int BufferView::work_area_handler(FL_OBJECT * ob, int event,
866                                   FL_Coord, FL_Coord ,
867                                   int /*key*/, void * xev)
868 {
869         static int x_old = -1;
870         static int y_old = -1;
871         static long scrollbar_value_old = -1;
872         
873         XEvent * ev = static_cast<XEvent*>(xev);
874         BufferView * view = static_cast<BufferView*>(ob->u_vdata);
875
876         // If we don't have a view yet; return
877         if (!view || quitting) return 0;
878
879         switch (event){   
880         case FL_DRAW:
881                 view->workAreaExpose(); 
882                 break;
883         case FL_PUSH:
884                 view->WorkAreaButtonPress(ob, 0, 0, 0, ev, 0);
885                 break; 
886         case FL_RELEASE:
887                 view->WorkAreaButtonRelease(ob, 0, 0, 0, ev, 0);
888                 break;
889         case FL_MOUSE:
890                 if (ev->xmotion.x != x_old || 
891                     ev->xmotion.y != y_old ||
892                     view->current_scrollbar_value != scrollbar_value_old) {
893                         x_old = ev->xmotion.x;
894                         y_old = ev->xmotion.y;
895                         scrollbar_value_old = view->current_scrollbar_value;
896                         view->WorkAreaMotionNotify(ob, 0, 0, 0, ev, 0);
897                 }
898                 break;
899                 // Done by the raw callback:
900                 //  case FL_KEYBOARD:
901                 //  WorkAreaKeyPress(ob, 0, 0, 0, ev, 0); break;
902         case FL_FOCUS:
903                 if (!view->owner_->getMiniBuffer()->shows_no_match)
904                         view->owner_->getMiniBuffer()->Init();
905                 view->owner_->getMiniBuffer()->shows_no_match = false;
906                 view->work_area_focus = true;
907                 fl_set_timer(view->timer_cursor, 0.4);
908                 break;
909         case FL_UNFOCUS:
910                 view->owner_->getMiniBuffer()->ExecCommand();
911                 view->work_area_focus = false;
912                 break;
913         case FL_ENTER:
914                 SetXtermCursor(view->owner_->getForm()->window);
915                 // reset the timer
916                 view->lyx_focus = true;
917                 fl_set_timer(view->timer_cursor, 0.4);
918                 break;
919         case FL_LEAVE: 
920                 if (!input_prohibited)
921                         XUndefineCursor(fl_display,
922                                         view->owner_->getForm()->window);
923                 view->lyx_focus = false; // This is not an absolute truth
924                 // but if it is not true, it will be changed within a blink
925                 // of an eye. ... Not good enough... use regulare timeperiod
926                 //fl_set_timer(view->timer_cursor, 0.01); // 0.1 sec blink
927                 fl_set_timer(view->timer_cursor, 0.4); // 0.4 sec blink
928                 break;
929         case FL_DBLCLICK: 
930                 // select a word
931                 if (!view->the_locking_inset) {
932                         if (view->screen && ev->xbutton.button == 1) {
933                                 view->screen->HideCursor();
934                                 view->screen->ToggleSelection();
935                                 view->text->SelectWord();
936                                 view->screen->ToggleSelection(false);
937                                 /* This will fit the cursor on the screen
938                                  * if necessary */
939                                 view->update(0);
940                         }
941                 }
942                 break;
943         case FL_TRPLCLICK:
944                 // select a line
945                 if (view->buffer_ && view->screen && ev->xbutton.button == 1) {
946                         view->screen->HideCursor(); 
947                         view->screen->ToggleSelection();
948                         view->text->CursorHome();
949                         view->text->sel_cursor = view->text->cursor;
950                         view->text->CursorEnd();
951                         view->text->SetSelection();
952                         view->screen->ToggleSelection(false); 
953                         /* This will fit the cursor on the screen
954                          * if necessary */
955                         view->update(0);
956                 }
957                 break;
958         case FL_OTHER:
959                 view->WorkAreaSelectionNotify(ob,
960                                               view->owner_->getForm()->window,
961                                               0, 0, ev, 0); 
962                 break;
963         }
964         return 1;
965 }
966
967 int BufferView::WorkAreaMotionNotify(FL_OBJECT * ob, Window,
968                                      int /*w*/, int /*h*/,
969                                      XEvent * ev, void * /*d*/)
970 {
971         if (buffer_ == 0) return 0;
972         if (!screen) return 0;
973
974         // Check for inset locking
975         if (the_locking_inset) {
976                 LyXCursor cursor = text->cursor;
977                 the_locking_inset->
978                         InsetMotionNotify(ev->xbutton.x - ob->x - cursor.x,
979                                           ev->xbutton.y - ob->y -
980                                           (cursor.y),
981                                           ev->xbutton.state);
982                 return 0;
983         }
984
985         // Only use motion with button 1
986         if (!ev->xmotion.state & Button1MotionMask)
987                 return 0; 
988    
989         /* The selection possible is needed, that only motion events are 
990          * used, where the bottom press event was on the drawing area too */
991         if (selection_possible) {
992                 screen->HideCursor();
993
994                 text->SetCursorFromCoordinates(ev->xbutton.x - ob->x,
995                                                ev->xbutton.y - ob->y +
996                                                screen->first);
997       
998                 if (!text->selection)
999                         update(-3); // Maybe an empty line was deleted
1000       
1001                 text->SetSelection();
1002                 screen->ToggleToggle();
1003                 if (screen->FitCursor())
1004                         updateScrollbar(); 
1005                 screen->ShowCursor();
1006         }
1007         return 0;
1008 }
1009
1010
1011 extern int bibitemMaxWidth(LyXFont const &);
1012
1013 // Single-click on work area
1014 int BufferView::WorkAreaButtonPress(FL_OBJECT * ob, Window,
1015                                     int /*w*/, int /*h*/,
1016                                     XEvent * ev, void */*d*/)
1017 {
1018         last_click_x = -1;
1019         last_click_y = -1;
1020
1021         if (buffer_ == 0) return 0;
1022         if (!screen) return 0;
1023
1024         int const x = ev->xbutton.x - ob->x;
1025         int const y = ev->xbutton.y - ob->y;
1026         // If we hit an inset, we have the inset coordinates in these
1027         // and inset_hit points to the inset.  If we do not hit an
1028         // inset, inset_hit is 0, and inset_x == x, inset_y == y.
1029         int inset_x = x;
1030         int inset_y = y;
1031         Inset * inset_hit = checkInsetHit(inset_x, inset_y);
1032
1033         // ok ok, this is a hack.
1034         int button = ev->xbutton.button;
1035         if (button == 4 || button == 5) goto wheel;
1036
1037         {
1038                 if (the_locking_inset) {
1039                         // We are in inset locking mode
1040                 
1041                         /* Check whether the inset was hit. If not reset mode,
1042                            otherwise give the event to the inset */
1043                         if (inset_hit != 0) {
1044                                 the_locking_inset->
1045                                         InsetButtonPress(inset_x, inset_y,
1046                                                          button);
1047                                 return 0;
1048                         } else {
1049                                 unlockInset(the_locking_inset);
1050                         }
1051                 }
1052
1053                 selection_possible = true;
1054                 screen->HideCursor();
1055         
1056                 // Right button mouse click on a table
1057                 if (button == 3 &&
1058                     (text->cursor.par->table ||
1059                      text->MouseHitInTable(x, y + screen->first))) {
1060                         // Set the cursor to the press-position
1061                         text->SetCursorFromCoordinates(x, y + screen->first);
1062                         bool doit = true;
1063                 
1064                         // Only show the table popup if the hit is in
1065                         // the table, too
1066                         if (!text->HitInTable(text->cursor.row, x))
1067                                 doit = false;
1068                 
1069                         // Hit above or below the table?
1070                         if (doit) {
1071                                 if (!text->selection) {
1072                                         screen->ToggleSelection();
1073                                         text->ClearSelection();
1074                                         text->FullRebreak();
1075                                         screen->Update();
1076                                         updateScrollbar();
1077                                 }
1078                                 // Popup table popup when on a table.
1079                                 // This is obviously temporary, since we
1080                                 // should be able to popup various
1081                                 // context-sensitive-menus with the
1082                                 // the right mouse. So this should be done more
1083                                 // general in the future. Matthias.
1084                                 selection_possible = false;
1085                                 owner_->getLyXFunc()
1086                                         ->Dispatch(LFUN_LAYOUT_TABLE,
1087                                                    "true");
1088                                 return 0;
1089                         }
1090                 }
1091         
1092                 int screen_first = screen->first;
1093         
1094                 // Middle button press pastes if we have a selection
1095                 bool paste_internally = false;
1096                 if (button == 2  // && !buffer_->the_locking_inset
1097                     && text->selection) {
1098                         owner_->getLyXFunc()->Dispatch(LFUN_COPY);
1099                         paste_internally = true;
1100                 }
1101         
1102                 // Clear the selection
1103                 screen->ToggleSelection();
1104                 text->ClearSelection();
1105                 text->FullRebreak();
1106                 screen->Update();
1107                 updateScrollbar();
1108                 
1109                 // Single left click in math inset?
1110                 if (inset_hit != 0 && inset_hit->Editable() == 2) {
1111                         // Highly editable inset, like math
1112                         selection_possible = false;
1113                         owner_->updateLayoutChoice();
1114                         owner_->getMiniBuffer()->Set(inset_hit->EditMessage());
1115                         inset_hit->Edit(inset_x, inset_y);
1116                         return 0;
1117                 } 
1118
1119                 // Right click on a footnote flag opens float menu
1120                 if (button == 3) { 
1121                         selection_possible = false;
1122                         return 0;
1123                 }
1124         
1125                 text->SetCursorFromCoordinates(x, y + screen_first);
1126                 text->FinishUndo();
1127                 text->sel_cursor = text->cursor;
1128                 text->cursor.x_fix = text->cursor.x;
1129         
1130                 owner_->updateLayoutChoice();
1131                 if (screen->FitCursor()){
1132                         updateScrollbar();
1133                         selection_possible = false;
1134                 }
1135
1136                 // Insert primary selection with middle mouse
1137                 // if there is a local selection in the current buffer,
1138                 // insert this
1139                 if (button == 2) { //  && !buffer_->the_locking_inset){
1140                         if (paste_internally)
1141                                 owner_->getLyXFunc()->Dispatch(LFUN_PASTE);
1142                         else
1143                                 owner_->getLyXFunc()->Dispatch(LFUN_PASTESELECTION,
1144                                                                "paragraph");
1145                         selection_possible = false;
1146                         return 0;
1147                 }
1148         }
1149         goto out;
1150   wheel:
1151         {
1152                 // I am not quite sure if this is the correct place to put
1153                 // this, but it will not cause any harm.
1154                 // Patch from Mark Huang (markman@mit.edu) to make LyX
1155                 // recognise button 4 and 5. This enables LyX use use
1156                 // the scrollwhell on certain mice for something useful. (Lgb)
1157                 // Added wheel acceleration detection code. (Rvdk)
1158                 static Time lastTime = 0;
1159                 int diff = ev->xbutton.time - lastTime;
1160                 int scroll = int(1.0 + (4.0 / (abs(diff) + 1.0)) * 200.0);
1161                 switch (button) {
1162                 case 4:
1163                         ScrollUp(scroll);
1164                         break;
1165                 case 5:
1166                         ScrollDown(scroll);
1167                         break;
1168                 }
1169                 lastTime = ev->xbutton.time;
1170                 return 0;
1171         }
1172   out:
1173         last_click_x = x;
1174         last_click_y = y;
1175         
1176         return 0;
1177 }
1178
1179
1180 int BufferView::WorkAreaButtonRelease(FL_OBJECT * ob, Window ,
1181                                       int /*w*/, int /*h*/,
1182                                       XEvent * ev, void * /*d*/)
1183 {
1184         if (buffer_ == 0 || screen == 0) return 0;
1185
1186         int const x = ev->xbutton.x - ob->x;
1187         int const y = ev->xbutton.y - ob->y;
1188
1189         // If we hit an inset, we have the inset coordinates in these
1190         // and inset_hit points to the inset.  If we do not hit an
1191         // inset, inset_hit is 0, and inset_x == x, inset_y == y.
1192         int inset_x = x;
1193         int inset_y = y;
1194         Inset * inset_hit = checkInsetHit(inset_x, inset_y);
1195
1196         if (the_locking_inset) {
1197                 // We are in inset locking mode.
1198
1199                 /* LyX does a kind of work-area grabbing for insets.
1200                    Only a ButtonPress Event outside the inset will 
1201                    force a InsetUnlock. */
1202                 the_locking_inset->
1203                         InsetButtonRelease(inset_x, inset_y, 
1204                                            ev->xbutton.button);
1205                 return 0;
1206         }
1207         
1208         selection_possible = false;
1209         if (text->cursor.par->table) {
1210                 int cell = text->
1211                         NumberOfCell(text->cursor.par,
1212                                      text->cursor.pos);
1213                 if (text->cursor.par->table->IsContRow(cell) &&
1214                     text->cursor.par->table->
1215                     CellHasContRow(text->cursor.par->table->
1216                                    GetCellAbove(cell))<0) {
1217                         text->CursorUp();
1218                 }
1219         }
1220         
1221         if (ev->xbutton.button >= 2)
1222                 return 0;
1223
1224         // Make sure that the press was not far from the release
1225         if ((abs(last_click_x - x) >= 5) ||
1226             (abs(last_click_y - y) >= 5)) {
1227                 return 0;
1228         }
1229
1230         // Did we hit an editable inset?
1231         if (inset_hit != 0) {
1232                 // Inset like error, notes and figures
1233                 selection_possible = false;
1234 #ifdef WITH_WARNINGS
1235 #warning fix this proper in 0.13
1236 #endif
1237                 // Following a ref shouldn't issue
1238                 // a push on the undo-stack
1239                 // anylonger, now that we have
1240                 // keybindings for following
1241                 // references and returning from
1242                 // references.  IMHO though, it
1243                 // should be the inset's own business
1244                 // to push or not push on the undo
1245                 // stack. They don't *have* to
1246                 // alter the document...
1247                 // (Joacim)
1248                 // ...or maybe the SetCursorParUndo()
1249                 // below isn't necessary at all anylonger?
1250                 if (inset_hit->LyxCode() == Inset::REF_CODE) {
1251                         text->SetCursorParUndo();
1252                 }
1253
1254                 owner_->getMiniBuffer()->Set(inset_hit->EditMessage());
1255                 inset_hit->Edit(inset_x, inset_y);
1256                 return 0;
1257         }
1258
1259         // check whether we want to open a float
1260         if (text) {
1261                 bool hit = false;
1262                 char c = ' ';
1263                 if (text->cursor.pos <
1264                     text->cursor.par->Last()) {
1265                         c = text->cursor.par->
1266                                 GetChar(text->cursor.pos);
1267                 }
1268                 if (c == LyXParagraph::META_FOOTNOTE
1269                     || c == LyXParagraph::META_MARGIN
1270                     || c == LyXParagraph::META_FIG
1271                     || c == LyXParagraph::META_TAB
1272                     || c == LyXParagraph::META_WIDE_FIG
1273                     || c == LyXParagraph::META_WIDE_TAB
1274                     || c == LyXParagraph::META_ALGORITHM){
1275                         hit = true;
1276                 } else if (text->cursor.pos - 1 >= 0) {
1277                         c = text->cursor.par->
1278                                 GetChar(text->cursor.pos - 1);
1279                         if (c == LyXParagraph::META_FOOTNOTE
1280                             || c == LyXParagraph::META_MARGIN
1281                             || c == LyXParagraph::META_FIG
1282                             || c == LyXParagraph::META_TAB
1283                             || c == LyXParagraph::META_WIDE_FIG 
1284                             || c == LyXParagraph::META_WIDE_TAB
1285                             || c == LyXParagraph::META_ALGORITHM){
1286                                 // We are one step too far to the right
1287                                 text->CursorLeft();
1288                                 hit = true;
1289                         }
1290                 }
1291                 if (hit == true) {
1292                         toggleFloat();
1293                         selection_possible = false;
1294                         return 0;
1295                 }
1296         }
1297
1298         // Do we want to close a float? (click on the float-label)
1299         if (text->cursor.row->par->footnoteflag == 
1300             LyXParagraph::OPEN_FOOTNOTE
1301             && text->cursor.pos == 0
1302             && text->cursor.row->previous &&
1303             text->cursor.row->previous->par->
1304             footnoteflag != LyXParagraph::OPEN_FOOTNOTE){
1305                 LyXFont font (LyXFont::ALL_SANE);
1306                 font.setSize(LyXFont::SIZE_SMALL);
1307
1308                 int box_x = 20; // LYX_PAPER_MARGIN;
1309                 box_x += font.textWidth("Mwide-figM", 10);
1310
1311                 int screen_first = screen->first;
1312
1313                 if (x < box_x
1314                     && y + screen_first > text->cursor.y -
1315                     text->cursor.row->baseline
1316                     && y + screen_first < text->cursor.y -
1317                     text->cursor.row->baseline
1318                     + font.maxAscent() * 1.2 + font.maxDescent() * 1.2) {
1319                         toggleFloat();
1320                         selection_possible = false;
1321                         return 0;
1322                 }
1323         }
1324
1325         // Maybe we want to edit a bibitem ale970302
1326         if (text->cursor.par->bibkey && x < 20 + 
1327             bibitemMaxWidth(textclasslist
1328                             .TextClass(buffer_->
1329                                        params.textclass).defaultfont())) {
1330                 text->cursor.par->bibkey->Edit(0, 0);
1331         }
1332
1333         return 0;
1334 }
1335
1336
1337 /* 
1338  * Returns an inset if inset was hit. 0 otherwise.
1339  * If hit, the coordinates are changed relative to the inset. 
1340  * Otherwise coordinates are not changed, and false is returned.
1341  */
1342 Inset * BufferView::checkInsetHit(int & x, int & y)
1343 {
1344         if (!getScreen())
1345                 return 0;
1346   
1347         int y_tmp = y + getScreen()->first;
1348   
1349         LyXCursor cursor = text->cursor;
1350         if (cursor.pos < cursor.par->Last() 
1351             && cursor.par->GetChar(cursor.pos) == LyXParagraph::META_INSET
1352             && cursor.par->GetInset(cursor.pos)
1353             && cursor.par->GetInset(cursor.pos)->Editable()) {
1354
1355                 // Check whether the inset really was hit
1356                 Inset * tmpinset = cursor.par->GetInset(cursor.pos);
1357                 LyXFont font = text->GetFont(cursor.par, cursor.pos);
1358                 if (x > cursor.x
1359                     && x < cursor.x + tmpinset->Width(font) 
1360                     && y_tmp > cursor.y - tmpinset->Ascent(font)
1361                     && y_tmp < cursor.y + tmpinset->Descent(font)) {
1362                         x = x - cursor.x;
1363                         // The origin of an inset is on the baseline
1364                         y = y_tmp - (cursor.y); 
1365                         return tmpinset;
1366                 }
1367         } else if (cursor.pos - 1 >= 0 
1368                    && cursor.par->GetChar(cursor.pos - 1) == LyXParagraph::META_INSET
1369                    && cursor.par->GetInset(cursor.pos - 1)
1370                    && cursor.par->GetInset(cursor.pos - 1)->Editable()) {
1371                 text->CursorLeft();
1372                 Inset * result = checkInsetHit(x, y);
1373                 if (result == 0) {
1374                         text->CursorRight();
1375                         return 0;
1376                 } else {
1377                         return result;
1378                 }
1379         }
1380         return 0;
1381 }
1382
1383
1384 int BufferView::workAreaExpose()
1385 {
1386         if (!work_area || !work_area->form->visible) 
1387                 return 1;
1388
1389         // this is a hack to ensure that we only call this through
1390         // BufferView::redraw().
1391         if (!lgb_hack) {
1392                 redraw();
1393         }
1394         
1395         static int work_area_width = work_area->w;
1396         static int work_area_height = work_area->h;
1397
1398         bool widthChange = work_area->w != work_area_width;
1399         bool heightChange = work_area->h != work_area_height;
1400
1401         // update from work area
1402         work_area_width = work_area->w;
1403         work_area_height = work_area->h;
1404         if (buffer_ != 0) {
1405                 if (widthChange) {
1406                         // All buffers need a resize
1407                         bufferlist.resize();
1408
1409                         // Remove all texts from the textcache
1410                         showTextCache("Expose delete all");
1411                         while(!textcache.empty()) {
1412                                 LyXText * tt = textcache.front();
1413                                 textcache.erase(textcache.begin());
1414                                 delete tt;
1415                         }
1416                 } else if (heightChange) {
1417                         // Rebuild image of current screen
1418                         updateScreen();
1419                         // fitCursor() ensures we don't jump back
1420                         // to the start of the document on vertical
1421                         // resize
1422                         fitCursor();
1423
1424                         // The main window size has changed, repaint most stuff
1425                         redraw();
1426                         // ...including the minibuffer
1427                         owner_->getMiniBuffer()->Init();
1428
1429                 } else if (screen) screen->Redraw();
1430         } else {
1431                 // Grey box when we don't have a buffer
1432                 fl_winset(FL_ObjWin(work_area));
1433                 fl_rectangle(1, work_area->x, work_area->y,
1434                              work_area->w, work_area->h, FL_GRAY63);
1435         }
1436
1437         // always make sure that the scrollbar is sane.
1438         updateScrollbar();
1439         owner_->updateLayoutChoice();
1440         return 1;
1441 }
1442
1443
1444 // Callback for cursor timer
1445 void BufferView::CursorToggleCB(FL_OBJECT * ob, long)
1446 {
1447         BufferView * view = static_cast<BufferView*>(ob->u_vdata);
1448         
1449         // Quite a nice place for asyncron Inset updating, isn't it?
1450         // Actually no! This is run even if no buffer exist... so (Lgb)
1451         if (view && !view->buffer_) {
1452                 goto set_timer_and_return;
1453         }
1454
1455         // NOTE:
1456         // On my quest to solve the gs render hangups I am now
1457         // disabling the SIGHUP completely, and will do a wait
1458         // now and then instead. If the guess that xforms somehow
1459         // destroys something is true, this is likely (hopefully)
1460         // to solve the problem...at least I hope so. Lgb
1461
1462         // ...Ok this seems to work...at least it does not make things
1463         // worse so far. However I still see gs processes that hangs.
1464         // I would really like to know _why_ they are hanging. Anyway
1465         // the solution without the SIGCHLD handler seems to be easier
1466         // to debug.
1467
1468         // When attaching gdb to a a running gs that hangs it shows
1469         // that it is waiting for input(?) Is it possible for us to
1470         // provide that input somehow? Or figure what it is expecing
1471         // to read?
1472
1473         // One solution is to, after some time, look if there are some
1474         // old gs processes still running and if there are: kill them
1475         // and re render.
1476
1477         // Another solution is to provide the user an option to rerender
1478         // a picture. This would, for the picture in question, check if
1479         // there is a gs running for it, if so kill it, and start a new
1480         // rendering process.
1481
1482         // these comments posted to lyx@via
1483         {
1484                 int status = 1;
1485                 int pid = waitpid(static_cast<pid_t>(0), &status, WNOHANG);
1486                 if (pid == -1) // error find out what is wrong
1487                         ; // ignore it for now.
1488                 else if (pid > 0)
1489                         sigchldhandler(pid, &status);
1490         }
1491         if (InsetUpdateList) 
1492                 UpdateInsetUpdateList();
1493
1494         if (view && !view->screen){
1495                 goto set_timer_and_return;
1496         }
1497
1498         if (view->lyx_focus && view->work_area_focus) {
1499                 if (!view->the_locking_inset) {
1500                         view->screen->CursorToggle();
1501                 } else {
1502                         view->the_locking_inset->
1503                                 ToggleInsetCursor();
1504                 }
1505                 goto set_timer_and_return;
1506         } else {
1507                 // Make sure that the cursor is visible.
1508                 if (!view->the_locking_inset) {
1509                         view->screen->ShowCursor();
1510                 } else {
1511                         if (!view->the_locking_inset->isCursorVisible())
1512                                 view->the_locking_inset->
1513                                         ToggleInsetCursor();
1514                 }
1515                 // This is only run when work_area_focus or lyx_focus is false.
1516                 Window tmpwin;
1517                 int tmp;
1518                 XGetInputFocus(fl_display, &tmpwin, &tmp);
1519                 if (lyxerr.debugging(Debug::INFO)) {
1520                         lyxerr << "tmpwin: " << tmpwin
1521                                << "\nwindow: " << view->owner_->getForm()->window
1522                                << "\nwork_area_focus: " << view->work_area_focus
1523                                << "\nlyx_focus      : " << view->lyx_focus
1524                                << endl;
1525                 }
1526                 if (tmpwin != view->owner_->getForm()->window) {
1527                         view->lyx_focus = false;
1528                         goto skip_timer;
1529                 } else {
1530                         view->lyx_focus = true;
1531                         if (!view->work_area_focus)
1532                                 goto skip_timer;
1533                         else
1534                                 goto set_timer_and_return;
1535                 }
1536         }
1537
1538   set_timer_and_return:
1539         fl_set_timer(ob, 0.4);
1540   skip_timer:
1541         return;
1542 }
1543
1544
1545 int BufferView::WorkAreaSelectionNotify(FL_OBJECT *, Window win,
1546                                         int /*w*/, int /*h*/,
1547                                         XEvent * event, void */*d*/)
1548 {
1549         if (buffer_ == 0) return 0;
1550         if (event->type != SelectionNotify)
1551                 return 0;
1552
1553         Atom tmpatom;
1554         unsigned long ul1;
1555         unsigned long ul2;
1556         unsigned char * uc = 0;
1557         int tmpint;
1558         screen->HideCursor();
1559         beforeChange();
1560         if (event->xselection.type == XA_STRING
1561             && event->xselection.property) {
1562     
1563                 if (XGetWindowProperty(
1564                         fl_display            /* display */,
1565                         win /* w */,
1566                         event->xselection.property        /* property */,
1567                         0                /* long_offset */,
1568                         0                /* long_length */,
1569                         false                /* delete */,
1570                         XA_STRING                /* req_type */,
1571                         &tmpatom               /* actual_type_return */,
1572                         &tmpint                /* actual_format_return */,
1573                         &ul1      /* nitems_return */,
1574                         &ul2      /* bytes_after_return */,
1575                         &uc     /* prop_return */
1576                         ) != Success) {
1577                         return 0;
1578                 }
1579                 XFlush(fl_display);
1580
1581                 if (uc) {
1582                         free(uc);
1583                         uc = 0;
1584                 }
1585
1586                 if (XGetWindowProperty(
1587                         fl_display           /* display */,
1588                         win              /* w */,
1589                         event->xselection.property           /* property */,
1590                         0                /* long_offset */,
1591                         ul2/4+1                /* long_length */,
1592                         True                /* delete */,
1593                         XA_STRING                /* req_type */,
1594                         &tmpatom               /* actual_type_return */,
1595                         &tmpint                /* actual_format_return */,
1596                         &ul1      /* nitems_return */,
1597                         &ul2      /* bytes_after_return */,
1598                         &uc     /* prop_return */
1599                         ) != Success) {
1600                         return 0;
1601                 }
1602                 XFlush(fl_display);
1603         
1604                 if (uc) {
1605                         if (!ascii_type) {
1606                                 text->InsertStringA(reinterpret_cast<char*>(uc));
1607                         } else {
1608                                 text->InsertStringB(reinterpret_cast<char*>(uc));
1609                         }
1610                         free(uc);
1611                         uc = 0;
1612                 }
1613
1614                 update(1);
1615         }
1616         return 0;
1617 }
1618
1619
1620 void BufferView::cursorPrevious()
1621 {
1622         if (!text->cursor.row->previous) return;
1623         
1624         long y = getScreen()->first;
1625         Row * cursorrow = text->cursor.row;
1626         text->SetCursorFromCoordinates(text->cursor.x_fix, y);
1627         text->FinishUndo();
1628         // This is to allow jumping over large insets
1629         if ((cursorrow == text->cursor.row))
1630                 text->CursorUp();
1631         
1632         if (text->cursor.row->height < work_area->h)
1633                 getScreen()->Draw(text->cursor.y
1634                                   - text->cursor.row->baseline
1635                                   + text->cursor.row->height
1636                                   - work_area->h +1 );
1637 }
1638
1639
1640 void BufferView::cursorNext()
1641 {
1642         if (!text->cursor.row->next) return;
1643         
1644         long y = getScreen()->first;
1645         text->GetRowNearY(y);
1646         Row * cursorrow = text->cursor.row;
1647         text->SetCursorFromCoordinates(text->cursor.x_fix, y + work_area->h);
1648         text->FinishUndo();
1649         // This is to allow jumping over large insets
1650         if ((cursorrow == text->cursor.row))
1651                 text->CursorDown();
1652         
1653         if (text->cursor.row->height < work_area->h)
1654                 getScreen()->Draw(text->cursor.y
1655                                   - text->cursor.row->baseline);
1656 }
1657
1658
1659 bool BufferView::available() const
1660 {
1661         if (buffer_ && text) return true;
1662         return false;
1663 }
1664
1665
1666 void BufferView::beforeChange()
1667 {
1668         getScreen()->ToggleSelection();
1669         text->ClearSelection();
1670         FreeUpdateTimer();
1671 }
1672
1673
1674 void BufferView::savePosition()
1675 {
1676         backstack.push(buffer()->fileName(),
1677                        text->cursor.x,
1678                        text->cursor.y);
1679 }
1680
1681
1682 void BufferView::restorePosition()
1683 {
1684         if (backstack.empty()) return;
1685         
1686         int  x, y;
1687         string fname = backstack.pop(&x, &y);
1688         
1689         beforeChange();
1690         Buffer * b = bufferlist.exists(fname) ?
1691                 bufferlist.getBuffer(fname) :
1692                 bufferlist.loadLyXFile(fname); // don't ask, just load it
1693         buffer(b);
1694         text->SetCursorFromCoordinates(x, y);
1695         update(0);
1696
1697
1698
1699 void BufferView::update(signed char f)
1700 {
1701         owner()->updateLayoutChoice();
1702
1703         if (!text->selection && f > -3)
1704                 text->sel_cursor = text->cursor;
1705         
1706         FreeUpdateTimer();
1707         text->FullRebreak();
1708
1709         update();
1710
1711         if (f != 3 && f != -3) {
1712                 fitCursor();
1713                 updateScrollbar();
1714         }
1715
1716         if (f == 1 || f == -1) {
1717                 if (buffer()->isLyxClean()) {
1718                         buffer()->markDirty();
1719                         owner()->getMiniBuffer()->setTimer(4);
1720                 } else {
1721                         buffer()->markDirty();
1722                 }
1723         }
1724 }
1725
1726
1727 void BufferView::smallUpdate(signed char f)
1728 {
1729         getScreen()->SmallUpdate();
1730         if (getScreen()->TopCursorVisible()
1731             != getScreen()->first) {
1732                 update(f);
1733                 return;
1734         }
1735
1736         fitCursor();
1737         updateScrollbar();
1738
1739         if (!text->selection)
1740                 text->sel_cursor = text->cursor;
1741
1742         if (f == 1 || f == -1) {
1743                 if (buffer()->isLyxClean()) {
1744                         buffer()->markDirty();
1745                         owner()->getMiniBuffer()->setTimer(4);
1746                 } else {
1747                         buffer()->markDirty();
1748                 }
1749         }
1750 }
1751
1752
1753 void BufferView::insetSleep()
1754 {
1755         if (the_locking_inset && !inset_slept) {
1756                 the_locking_inset->GetCursorPos(slx, sly);
1757                 the_locking_inset->InsetUnlock();
1758                 inset_slept = true;
1759         }
1760 }
1761
1762
1763 void BufferView::insetWakeup()
1764 {
1765         if (the_locking_inset && inset_slept) {
1766                 the_locking_inset->Edit(slx, sly);
1767                 inset_slept = false;
1768         }
1769 }
1770
1771
1772 void BufferView::insetUnlock()
1773 {
1774         if (the_locking_inset) {
1775                 if (!inset_slept) the_locking_inset->InsetUnlock();
1776                 the_locking_inset = 0;
1777                 text->FinishUndo();
1778                 inset_slept = false;
1779         }
1780 }