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