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