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