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