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