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