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