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