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