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