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