]> git.lyx.org Git - lyx.git/blob - src/BufferView.C
c412f6e2d3fe47daa0cb61c58059d776f5407aa1
[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, button);
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         if (!inset_hit) // otherwise it was already set in checkInsetHit(...)
753                 text->SetCursorFromCoordinates(xpos, ypos + screen_first);
754         text->FinishUndo();
755         text->sel_cursor = text->cursor;
756         text->cursor.x_fix = text->cursor.x;
757         
758         owner_->updateLayoutChoice();
759         if (screen->FitCursor()){
760                 updateScrollbar();
761                 selection_possible = false;
762         }
763         
764         // Insert primary selection with middle mouse
765         // if there is a local selection in the current buffer,
766         // insert this
767         if (button == 2) {
768                 if (paste_internally)
769                         owner_->getLyXFunc()->Dispatch(LFUN_PASTE);
770                 else
771                         owner_->getLyXFunc()->Dispatch(LFUN_PASTESELECTION,
772                                                        "paragraph");
773                 selection_possible = false;
774                 return;
775         }
776 }
777
778
779 void BufferView::doubleClick(int /*x*/, int /*y*/, unsigned int button) 
780 {
781         // select a word
782         if (buffer_ && !the_locking_inset) {
783                 if (screen && button == 1) {
784                         screen->HideCursor();
785                         screen->ToggleSelection();
786                         text->SelectWord();
787                         screen->ToggleSelection(false);
788                         /* This will fit the cursor on the screen
789                          * if necessary */
790                         update(0);
791                 }
792         }            
793 }
794
795
796 void BufferView::tripleClick(int /*x*/, int /*y*/, unsigned int button)
797 {
798         // select a line
799         if (buffer_ && screen && button == 1) {
800                 screen->HideCursor();
801                 screen->ToggleSelection();
802                 text->CursorHome();
803                 text->sel_cursor = text->cursor;
804                 text->CursorEnd();
805                 text->SetSelection();
806                 screen->ToggleSelection(false);
807                 /* This will fit the cursor on the screen
808                  * if necessary */
809                 update(0);
810         }
811 }
812
813
814 void BufferView::workAreaButtonRelease(int x, int y, unsigned int button)
815 {
816         if (buffer_ == 0 || screen == 0) return;
817
818         // If we hit an inset, we have the inset coordinates in these
819         // and inset_hit points to the inset.  If we do not hit an
820         // inset, inset_hit is 0, and inset_x == x, inset_y == y.
821         Inset * inset_hit = checkInsetHit(x, y, button);
822
823         if (the_locking_inset) {
824                 // We are in inset locking mode.
825
826                 /* LyX does a kind of work-area grabbing for insets.
827                    Only a ButtonPress Event outside the inset will 
828                    force a InsetUnlock. */
829                 the_locking_inset->
830                         InsetButtonRelease(this, x, y, button);
831                 return;
832         }
833         
834         selection_possible = false;
835         if (text->cursor.par->table) {
836                 int cell = text->
837                         NumberOfCell(text->cursor.par,
838                                      text->cursor.pos);
839                 if (text->cursor.par->table->IsContRow(cell) &&
840                     text->cursor.par->table->
841                     CellHasContRow(text->cursor.par->table->
842                                    GetCellAbove(cell))<0) {
843                         text->CursorUp();
844                 }
845         }
846         
847         if (button >= 2) return;
848
849         setState();
850         owner_->getMiniBuffer()->Set(CurrentState());
851
852         // Did we hit an editable inset?
853         if (inset_hit != 0) {
854                 // Inset like error, notes and figures
855                 selection_possible = false;
856 #ifdef WITH_WARNINGS
857 #warning fix this proper in 0.13
858 #endif
859                 // Following a ref shouldn't issue
860                 // a push on the undo-stack
861                 // anylonger, now that we have
862                 // keybindings for following
863                 // references and returning from
864                 // references.  IMHO though, it
865                 // should be the inset's own business
866                 // to push or not push on the undo
867                 // stack. They don't *have* to
868                 // alter the document...
869                 // (Joacim)
870                 // ...or maybe the SetCursorParUndo()
871                 // below isn't necessary at all anylonger?
872                 if (inset_hit->LyxCode() == Inset::REF_CODE) {
873                         text->SetCursorParUndo();
874                 }
875
876                 owner_->getMiniBuffer()->Set(inset_hit->EditMessage());
877                 if (inset_hit->Editable()==Inset::HIGHLY_EDITABLE) {
878                         // Highly editable inset, like math
879                         UpdatableInset *inset = (UpdatableInset *)inset_hit;
880                         inset->InsetButtonRelease(this, x, y, button);
881                 } else {
882                         inset_hit->Edit(this, x, y, button);
883                 }
884                 return;
885         }
886
887         // check whether we want to open a float
888         if (text) {
889                 bool hit = false;
890                 char c = ' ';
891                 if (text->cursor.pos <
892                     text->cursor.par->Last()) {
893                         c = text->cursor.par->
894                                 GetChar(text->cursor.pos);
895                 }
896                 if (c == LyXParagraph::META_FOOTNOTE
897                     || c == LyXParagraph::META_MARGIN
898                     || c == LyXParagraph::META_FIG
899                     || c == LyXParagraph::META_TAB
900                     || c == LyXParagraph::META_WIDE_FIG
901                     || c == LyXParagraph::META_WIDE_TAB
902                     || c == LyXParagraph::META_ALGORITHM){
903                         hit = true;
904                 } else if (text->cursor.pos - 1 >= 0) {
905                         c = text->cursor.par->
906                                 GetChar(text->cursor.pos - 1);
907                         if (c == LyXParagraph::META_FOOTNOTE
908                             || c == LyXParagraph::META_MARGIN
909                             || c == LyXParagraph::META_FIG
910                             || c == LyXParagraph::META_TAB
911                             || c == LyXParagraph::META_WIDE_FIG 
912                             || c == LyXParagraph::META_WIDE_TAB
913                             || c == LyXParagraph::META_ALGORITHM){
914                                 // We are one step too far to the right
915                                 text->CursorLeft();
916                                 hit = true;
917                         }
918                 }
919                 if (hit == true) {
920                         toggleFloat();
921                         selection_possible = false;
922                         return;
923                 }
924         }
925
926         // Do we want to close a float? (click on the float-label)
927         if (text->cursor.row->par->footnoteflag == 
928             LyXParagraph::OPEN_FOOTNOTE
929             //&& text->cursor.pos == 0
930             && text->cursor.row->previous &&
931             text->cursor.row->previous->par->
932             footnoteflag != LyXParagraph::OPEN_FOOTNOTE){
933                 LyXFont font(LyXFont::ALL_SANE);
934                 font.setSize(LyXFont::SIZE_FOOTNOTE);
935
936                 int box_x = 20; // LYX_PAPER_MARGIN;
937                 box_x += font.textWidth(" wide-tab ", 10);
938
939                 int screen_first = screen->first;
940
941                 if (x < box_x
942                     && y + screen_first > text->cursor.y -
943                     text->cursor.row->baseline
944                     && y + screen_first < text->cursor.y -
945                     text->cursor.row->baseline
946                     + font.maxAscent() * 1.2 + font.maxDescent() * 1.2) {
947                         toggleFloat();
948                         selection_possible = false;
949                         return;
950                 }
951         }
952
953         // Maybe we want to edit a bibitem ale970302
954         if (text->cursor.par->bibkey && x < 20 + 
955             bibitemMaxWidth(painter(),
956                             textclasslist
957                             .TextClass(buffer_->
958                                        params.textclass).defaultfont())) {
959                 text->cursor.par->bibkey->Edit(this, 0, 0, 0);
960         }
961
962         return;
963 }
964
965
966 /* 
967  * Returns an inset if inset was hit. 0 otherwise.
968  * If hit, the coordinates are changed relative to the inset. 
969  * Otherwise coordinates are not changed, and false is returned.
970  */
971 Inset * BufferView::checkInsetHit(int & x, int & y, unsigned int button)
972 {
973         if (!screen)
974                 return 0;
975   
976         int y_tmp = y + screen->first;
977   
978         LyXCursor cursor;
979         text->SetCursorFromCoordinates(cursor, x, y_tmp);
980 #if 1
981         bool move_cursor = true;
982 #else
983         bool move_cursor = ((cursor.par != text->cursor.par) ||
984                             (cursor.pos != text->cursor.pos)) && (button < 2);
985 #endif
986
987         if (cursor.pos < cursor.par->Last()
988             && cursor.par->GetChar(cursor.pos) == LyXParagraph::META_INSET
989             && cursor.par->GetInset(cursor.pos)
990             && cursor.par->GetInset(cursor.pos)->Editable()) {
991
992                 // Check whether the inset really was hit
993                 Inset * tmpinset = cursor.par->GetInset(cursor.pos);
994                 LyXFont font = text->GetFont(cursor.par, cursor.pos);
995                 bool is_rtl = font.isVisibleRightToLeft();
996                 int start_x, end_x;
997
998                 if (is_rtl) {
999                         start_x = cursor.x - tmpinset->width(painter(), font);
1000                         end_x = cursor.x;
1001                 } else {
1002                         start_x = cursor.x;
1003                         end_x = cursor.x + tmpinset->width(painter(), font);
1004                 }
1005
1006                 if (x > start_x && x < end_x
1007                     && y_tmp > cursor.y - tmpinset->ascent(painter(), font)
1008                     && y_tmp < cursor.y + tmpinset->descent(painter(), font)) {
1009                         if (move_cursor)
1010                                 text->SetCursorFromCoordinates(x, y_tmp);
1011                         x = x - start_x;
1012                         // The origin of an inset is on the baseline
1013                         y = y_tmp - (text->cursor.y); 
1014                         return tmpinset;
1015                 }
1016         }
1017
1018         if ((cursor.pos - 1 >= 0) &&
1019             (cursor.par->GetChar(cursor.pos-1) == LyXParagraph::META_INSET) &&
1020             (cursor.par->GetInset(cursor.pos - 1)) &&
1021             (cursor.par->GetInset(cursor.pos - 1)->Editable())) {
1022                 Inset * tmpinset = cursor.par->GetInset(cursor.pos-1);
1023                 LyXFont font = text->GetFont(cursor.par, cursor.pos-1);
1024                 bool is_rtl = font.isVisibleRightToLeft();
1025                 int start_x, end_x;
1026
1027                 if (!is_rtl) {
1028                         start_x = cursor.x - tmpinset->width(painter(), font);
1029                         end_x = cursor.x;
1030                 } else {
1031                         start_x = cursor.x;
1032                         end_x = cursor.x + tmpinset->width(painter(), font);
1033                 }
1034                 if (x > start_x && x < end_x
1035                     && y_tmp > cursor.y - tmpinset->ascent(painter(), font)
1036                     && y_tmp < cursor.y + tmpinset->descent(painter(), font)) {
1037                         if (move_cursor)
1038                                 text->SetCursorFromCoordinates(x, y_tmp);
1039                         x = x - start_x;
1040                         // The origin of an inset is on the baseline
1041                         y = y_tmp - (text->cursor.y); 
1042                         return tmpinset;
1043                 }
1044         }
1045         return 0;
1046 }
1047
1048 void BufferView::workAreaExpose()
1049 {
1050         // this is a hack to ensure that we only call this through
1051         // BufferView::redraw().
1052         //if (!lgb_hack) {
1053         //      redraw();
1054         //}
1055         
1056         static int work_area_width = -1;
1057         static int work_area_height = -1;
1058
1059         bool widthChange = workarea->workWidth() != work_area_width;
1060         bool heightChange = workarea->height() != work_area_height;
1061
1062         // update from work area
1063         work_area_width = workarea->workWidth();
1064         work_area_height = workarea->height();
1065         if (buffer_ != 0) {
1066                 if (widthChange) {
1067                         // All buffers need a resize
1068                         bufferlist.resize();
1069
1070                         // Remove all texts from the textcache
1071                         // This is not _really_ what we want to do. What
1072                         // we really want to do is to delete in textcache
1073                         // that does not have a BufferView with matching
1074                         // width, but as long as we have only one BufferView
1075                         // deleting all gives the same result.
1076                         if (lyxerr.debugging())
1077                                 textcache.show(lyxerr, "Expose delete all");
1078                         textcache.clear();
1079                 } else if (heightChange) {
1080                         // Rebuild image of current screen
1081                         updateScreen();
1082                         // fitCursor() ensures we don't jump back
1083                         // to the start of the document on vertical
1084                         // resize
1085                         fitCursor();
1086
1087                         // The main window size has changed, repaint most stuff
1088                         redraw();
1089                         // ...including the minibuffer
1090                         owner_->getMiniBuffer()->Init();
1091
1092                 } else if (screen) screen->Redraw();
1093         } else {
1094                 // Grey box when we don't have a buffer
1095                 workarea->greyOut();
1096         }
1097
1098         // always make sure that the scrollbar is sane.
1099         updateScrollbar();
1100         owner_->updateLayoutChoice();
1101         return;
1102 }
1103
1104
1105 // Callback for cursor timer
1106 void BufferView::cursorToggleCB(FL_OBJECT * ob, long)
1107 {
1108         BufferView * view = static_cast<BufferView*>(ob->u_vdata);
1109         
1110         // Quite a nice place for asyncron Inset updating, isn't it?
1111         // Actually no! This is run even if no buffer exist... so (Lgb)
1112         if (view && !view->buffer_) {
1113                 goto set_timer_and_return;
1114         }
1115
1116         // NOTE:
1117         // On my quest to solve the gs render hangups I am now
1118         // disabling the SIGHUP completely, and will do a wait
1119         // now and then instead. If the guess that xforms somehow
1120         // destroys something is true, this is likely (hopefully)
1121         // to solve the problem...at least I hope so. Lgb
1122
1123         // ...Ok this seems to work...at least it does not make things
1124         // worse so far. However I still see gs processes that hangs.
1125         // I would really like to know _why_ they are hanging. Anyway
1126         // the solution without the SIGCHLD handler seems to be easier
1127         // to debug.
1128
1129         // When attaching gdb to a a running gs that hangs it shows
1130         // that it is waiting for input(?) Is it possible for us to
1131         // provide that input somehow? Or figure what it is expecing
1132         // to read?
1133
1134         // One solution is to, after some time, look if there are some
1135         // old gs processes still running and if there are: kill them
1136         // and re render.
1137
1138         // Another solution is to provide the user an option to rerender
1139         // a picture. This would, for the picture in question, check if
1140         // there is a gs running for it, if so kill it, and start a new
1141         // rendering process.
1142
1143         // these comments posted to lyx@via
1144         {
1145                 int status = 1;
1146                 int pid = waitpid(static_cast<pid_t>(0), &status, WNOHANG);
1147                 if (pid == -1) // error find out what is wrong
1148                         ; // ignore it for now.
1149                 else if (pid > 0)
1150                         sigchldhandler(pid, &status);
1151         }
1152
1153         view->updatelist.update(view);
1154         
1155         if (view && !view->screen){
1156                 goto set_timer_and_return;
1157         }
1158
1159         if (view->lyx_focus && view->work_area_focus) {
1160                 if (!view->the_locking_inset) {
1161                         view->screen->CursorToggle();
1162                 } else {
1163                         view->the_locking_inset->
1164                                 ToggleInsetCursor(view);
1165                 }
1166                 goto set_timer_and_return;
1167         } else {
1168                 // Make sure that the cursor is visible.
1169                 if (!view->the_locking_inset) {
1170                         view->screen->ShowCursor();
1171                 } else {
1172                         if (!view->the_locking_inset->isCursorVisible())
1173                                 view->the_locking_inset->
1174                                         ToggleInsetCursor(view);
1175                 }
1176                 // This is only run when work_area_focus or lyx_focus is false.
1177                 Window tmpwin;
1178                 int tmp;
1179                 XGetInputFocus(fl_display, &tmpwin, &tmp);
1180                 // Commenting this out, we have not had problems with this
1181                 // for a long time. We will probably work on this code later
1182                 // and we can reenable this debug code then. Now it only
1183                 // anoying when debugging. (Lgb)
1184                 //if (lyxerr.debugging(Debug::INFO)) {
1185                 //      lyxerr << "tmpwin: " << tmpwin
1186                 //             << "\nwindow: " << view->owner_->getForm()->window
1187                 //             << "\nwork_area_focus: " << view->work_area_focus
1188                 //             << "\nlyx_focus      : " << view->lyx_focus
1189                 //             << endl;
1190                 //}
1191                 if (tmpwin != view->owner_->getForm()->window) {
1192                         view->lyx_focus = false;
1193                         goto skip_timer;
1194                 } else {
1195                         view->lyx_focus = true;
1196                         if (!view->work_area_focus)
1197                                 goto skip_timer;
1198                         else
1199                                 goto set_timer_and_return;
1200                 }
1201         }
1202
1203   set_timer_and_return:
1204         fl_set_timer(ob, 0.4);
1205   skip_timer:
1206         return;
1207 }
1208
1209
1210 static
1211 string fromClipboard(Window win, XEvent * event)
1212 {
1213         string strret;
1214         if (event->xselection.type == XA_STRING
1215             && event->xselection.property) {
1216                 Atom tmpatom;
1217                 unsigned long ul1;
1218                 unsigned long ul2;
1219                 unsigned char * uc = 0;
1220                 int tmpint;
1221                 if (XGetWindowProperty(
1222                         event->xselection.display,  // display
1223                         win,                        // w
1224                         event->xselection.property, // property
1225                         0,                          // long_offset      
1226                         0,                          // logn_length      
1227                         False,                      // delete   
1228                         XA_STRING,                  // req_type 
1229                         &tmpatom,                   // actual_type_return
1230                         &tmpint,                    // actual_format_return
1231                         &ul1,
1232                         &ul2,
1233                         &uc                         // prop_return      
1234                         ) != Success) {
1235                         return strret;
1236                 }
1237                 if (uc) {
1238                         free(uc);
1239                         uc = 0;
1240                 }
1241                 if (XGetWindowProperty(
1242                         event->xselection.display,             // display
1243                         win,                        // w
1244                         event->xselection.property, // property
1245                         0,                          // long_offset
1246                         ul2/4+1,                    // long_length
1247                         True,                       // delete
1248                         XA_STRING,                  // req_type
1249                         &tmpatom,                   // actual_type_return
1250                         &tmpint,                    // actual_format_return
1251                         &ul1,                       // nitems_return
1252                         &ul2,                       // bytes_after_return
1253                         &uc                         // prop_return */
1254                         ) != Success) {
1255                         return strret;
1256                 }
1257                 if (uc) {
1258                         strret = reinterpret_cast<char*>(uc);
1259                         free(uc); // yes free!
1260                         uc = 0;
1261                 }
1262         }
1263         return strret;
1264 }
1265
1266
1267 void BufferView::workAreaSelectionNotify(Window win, XEvent * event)
1268 {
1269         if (buffer_ == 0) return;
1270
1271         screen->HideCursor();
1272         beforeChange();
1273         string clb = fromClipboard(win, event);
1274         if (!clb.empty()) {
1275                 if (!ascii_type)
1276                         text->InsertStringA(clb);
1277                 else
1278                         text->InsertStringB(clb);
1279
1280                 update(1);
1281                 
1282         }
1283 }
1284
1285
1286 void BufferView::cursorPrevious()
1287 {
1288         if (!text->cursor.row->previous) return;
1289         
1290         long y = screen->first;
1291         Row * cursorrow = text->cursor.row;
1292         text->SetCursorFromCoordinates(text->cursor.x_fix, y);
1293         text->FinishUndo();
1294         // This is to allow jumping over large insets
1295         if ((cursorrow == text->cursor.row))
1296                 text->CursorUp();
1297         
1298         if (text->cursor.row->height < workarea->height())
1299                 screen->Draw(text->cursor.y
1300                                   - text->cursor.row->baseline
1301                                   + text->cursor.row->height
1302                                   - workarea->height() + 1 );
1303 }
1304
1305
1306 void BufferView::cursorNext()
1307 {
1308         if (!text->cursor.row->next) return;
1309         
1310         long y = screen->first;
1311         text->GetRowNearY(y);
1312         Row * cursorrow = text->cursor.row;
1313         text->SetCursorFromCoordinates(text->cursor.x_fix, y
1314                                        + workarea->height());
1315         text->FinishUndo();
1316         // This is to allow jumping over large insets
1317         if ((cursorrow == text->cursor.row))
1318                 text->CursorDown();
1319         
1320         if (text->cursor.row->height < workarea->height())
1321                 screen->Draw(text->cursor.y
1322                                   - text->cursor.row->baseline);
1323 }
1324
1325
1326 bool BufferView::available() const
1327 {
1328         if (buffer_ && text) return true;
1329         return false;
1330 }
1331
1332
1333 void BufferView::beforeChange()
1334 {
1335         toggleSelection();
1336         text->ClearSelection();
1337         FreeUpdateTimer();
1338 }
1339
1340
1341 void BufferView::savePosition()
1342 {
1343         backstack.push(buffer()->fileName(),
1344                        text->cursor.x,
1345                        text->cursor.y);
1346 }
1347
1348
1349 void BufferView::restorePosition()
1350 {
1351         if (backstack.empty()) return;
1352         
1353         int  x, y;
1354         string fname = backstack.pop(&x, &y);
1355         
1356         beforeChange();
1357         Buffer * b = bufferlist.exists(fname) ?
1358                 bufferlist.getBuffer(fname) :
1359                 bufferlist.loadLyXFile(fname); // don't ask, just load it
1360         buffer(b);
1361         text->SetCursorFromCoordinates(x, y);
1362         update(0);
1363
1364
1365
1366 void BufferView::update(signed char f)
1367 {
1368         owner()->updateLayoutChoice();
1369
1370         if (!text->selection && f > -3)
1371                 text->sel_cursor = text->cursor;
1372         
1373         FreeUpdateTimer();
1374         text->FullRebreak();
1375
1376         update();
1377
1378         if (f != 3 && f != -3) {
1379                 fitCursor();
1380                 updateScrollbar();
1381         }
1382
1383         if (f == 1 || f == -1) {
1384                 if (buffer()->isLyxClean()) {
1385                         buffer()->markDirty();
1386                         owner()->getMiniBuffer()->setTimer(4);
1387                 } else {
1388                         buffer()->markDirty();
1389                 }
1390         }
1391 }
1392
1393
1394 void BufferView::smallUpdate(signed char f)
1395 {
1396         screen->SmallUpdate();
1397         if (screen->TopCursorVisible()
1398             != screen->first) {
1399                 update(f);
1400                 return;
1401         }
1402
1403         fitCursor();
1404         updateScrollbar();
1405
1406         if (!text->selection)
1407                 text->sel_cursor = text->cursor;
1408
1409         if (f == 1 || f == -1) {
1410                 if (buffer()->isLyxClean()) {
1411                         buffer()->markDirty();
1412                         owner()->getMiniBuffer()->setTimer(4);
1413                 } else {
1414                         buffer()->markDirty();
1415                 }
1416         }
1417 }
1418
1419
1420 void BufferView::setState()
1421 {
1422         if (!lyxrc.rtl_support)
1423                 return;
1424
1425         if (text->real_current_font.isVisibleRightToLeft()) {
1426                 if (owner_->getIntl()->primarykeymap)
1427                         owner_->getIntl()->KeyMapSec();
1428         } else {
1429                 if (!owner_->getIntl()->primarykeymap)
1430                         owner_->getIntl()->KeyMapPrim();
1431         }
1432 }
1433
1434
1435 void BufferView::insetSleep()
1436 {
1437         if (the_locking_inset && !inset_slept) {
1438                 the_locking_inset->GetCursorPos(slx, sly);
1439                 the_locking_inset->InsetUnlock(this);
1440                 inset_slept = true;
1441         }
1442 }
1443
1444
1445 void BufferView::insetWakeup()
1446 {
1447         if (the_locking_inset && inset_slept) {
1448                 the_locking_inset->Edit(this, slx, sly, 0);
1449                 inset_slept = false;
1450         }
1451 }
1452
1453
1454 void BufferView::insetUnlock()
1455 {
1456         if (the_locking_inset) {
1457                 if (!inset_slept) the_locking_inset->InsetUnlock(this);
1458                 the_locking_inset = 0;
1459                 text->FinishUndo();
1460                 inset_slept = false;
1461         }
1462 }
1463
1464
1465 bool BufferView::focus() const
1466 {
1467         return workarea->hasFocus();
1468 }
1469
1470
1471 void BufferView::focus(bool f)
1472 {
1473         if (f) workarea->setFocus();
1474 }
1475
1476
1477 bool BufferView::active() const
1478 {
1479         return workarea->active();
1480 }
1481
1482
1483 Painter & BufferView::getPainter() const
1484 {
1485     return workarea->getPainter();
1486 }
1487
1488
1489 unsigned short BufferView::paperWidth() const
1490 {
1491     return text->paperWidth();
1492 }
1493
1494
1495 bool BufferView::belowMouse() const 
1496 {
1497         return workarea->belowMouse();
1498 }
1499
1500
1501 void BufferView::showCursor()
1502 {
1503         if (screen)
1504                 screen->ShowCursor();
1505 }
1506
1507
1508 void BufferView::hideCursor()
1509 {
1510         if (screen)
1511                 screen->HideCursor();
1512 }
1513
1514
1515 void BufferView::toggleSelection(bool b)
1516 {
1517         if (screen)
1518                 screen->ToggleSelection(b);
1519 }
1520
1521
1522 void BufferView::toggleToggle()
1523 {
1524         if (screen)
1525                 screen->ToggleToggle();
1526 }
1527
1528
1529 void BufferView::center() 
1530 {
1531         beforeChange();
1532         if (text->cursor.y > workarea->height() / 2) {
1533                 screen->Draw(text->cursor.y - workarea->height() / 2);
1534         } else {
1535                 screen->Draw(0);
1536         }
1537         update(0);
1538         redraw();
1539 }