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