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