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