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