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