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