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