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