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