]> git.lyx.org Git - lyx.git/blob - src/BufferView_pimpl.C
The qt2 frontend
[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::vector;
37 using std::make_pair;
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 "C" void TimerCB(FL_OBJECT *, long); 
47 extern void sigchldhandler(pid_t pid, int * status);
48 extern int bibitemMaxWidth(BufferView *, LyXFont const &);
49
50
51 static inline
52 void waitForX()
53 {
54         XSync(fl_get_display(), 0);
55 }
56
57
58 static
59 void SetXtermCursor(Window win)
60 {
61         static Cursor cursor;
62         static bool cursor_undefined = true;
63         if (cursor_undefined){
64                 cursor = XCreateFontCursor(fl_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 }
114
115
116 Painter & BufferView::Pimpl::painter() 
117 {
118         return workarea_->getPainter();
119 }
120
121
122 void BufferView::Pimpl::buffer(Buffer * b)
123 {
124         lyxerr[Debug::INFO] << "Setting buffer in BufferView ("
125                             << b << ")" << endl;
126         if (buffer_) {
127                 bv_->insetSleep();
128                 buffer_->delUser(bv_);
129
130                 // Put the old text into the TextCache, but
131                 // only if the buffer is still loaded.
132                 // Also set the owner of the test to 0
133                 //              bv_->text->owner(0);
134                 textcache.add(buffer_, workarea_->workWidth(), bv_->text);
135                 if (lyxerr.debugging())
136                         textcache.show(lyxerr, "BufferView::buffer");
137                 
138                 bv_->text = 0;
139         }
140
141         // Set current buffer
142         buffer_ = b;
143
144         if (bufferlist.getState() == BufferList::CLOSING) return;
145         
146         // Nuke old image
147         // screen is always deleted when the buffer is changed.
148         delete screen_;
149         screen_ = 0;
150
151         // If we are closing the buffer, use the first buffer as current
152         if (!buffer_) {
153                 buffer_ = bufferlist.first();
154         }
155
156         if (buffer_) {
157                 lyxerr[Debug::INFO] << "Buffer addr: " << buffer_ << endl;
158                 buffer_->addUser(bv_);
159                 // If we don't have a text object for this, we make one
160                 if (bv_->text == 0) {
161                         resizeCurrentBuffer();
162                 } else {
163                         updateScreen();
164                         updateScrollbar();
165                 }
166                 bv_->text->first = screen_->TopCursorVisible(bv_->text);
167                 owner_->updateMenubar();
168                 owner_->updateToolbar();
169                 // Similarly, buffer-dependent dialogs should be updated or
170                 // hidden. This should go here because some dialogs (eg ToC)
171                 // require bv_->text.
172                 owner_->getDialogs()->updateBufferDependent(true);
173                 redraw();
174                 bv_->insetWakeup();
175         } else {
176                 lyxerr[Debug::INFO] << "  No Buffer!" << endl;
177                 owner_->updateMenubar();
178                 owner_->updateToolbar();
179                 owner_->getDialogs()->hideBufferDependent();
180                 updateScrollbar();
181                 workarea_->redraw();
182
183                 // Also remove all remaining text's from the testcache.
184                 // (there should not be any!) (if there is any it is a
185                 // bug!)
186                 if (lyxerr.debugging())
187                         textcache.show(lyxerr, "buffer delete all");
188                 textcache.clear();
189         }
190         // should update layoutchoice even if we don't have a buffer.
191         owner_->updateLayoutChoice();
192         owner_->getMiniBuffer()->Init();
193         owner_->updateWindowTitle();
194 }
195
196
197 void BufferView::Pimpl::resize(int xpos, int ypos, int width, int height)
198 {
199         workarea_->resize(xpos, ypos, width, height);
200         update(SELECT);
201         redraw();
202 }
203
204
205 void BufferView::Pimpl::resize()
206 {
207         // This will resize the buffer. (Asger)
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_); // it is a programming error to call fitCursor
223         // without a valid screen.
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         // Now if the title form still exist kill it
315         TimerCB(0, 0);
316
317         return 0;
318 }
319
320
321 void BufferView::Pimpl::updateScreen()
322 {
323         // Regenerate the screen.
324         delete screen_;
325         screen_ = new LyXScreen(*workarea_);
326 }
327
328
329 void BufferView::Pimpl::updateScrollbar()
330 {
331         /* If the text is smaller than the working area, the scrollbar
332          * maximum must be the working area height. No scrolling will 
333          * be possible */
334
335         if (!buffer_) {
336                 workarea_->setScrollbar(0, 1.0);
337                 return;
338         }
339         
340         static unsigned long max2 = 0;
341         static unsigned long height2 = 0;
342
343         unsigned long cbth = 0;
344         long cbsf = 0;
345
346         if (bv_->text) {
347                 cbth = bv_->text->height;
348                 cbsf = bv_->text->first;
349         }
350
351         // check if anything has changed.
352         if (max2 == cbth &&
353             height2 == workarea_->height() &&
354             current_scrollbar_value == cbsf)
355                 return; // no
356         max2 = cbth;
357         height2 = workarea_->height();
358         current_scrollbar_value = cbsf;
359
360         if (cbth <= height2) { // text is smaller than screen
361                 workarea_->setScrollbar(0, 1.0); // right?
362                 return;
363         }
364
365         long maximum_height = workarea_->height() * 3 / 4 + cbth;
366         long value = cbsf;
367
368         // set the scrollbar
369         double hfloat = workarea_->height();
370         double maxfloat = maximum_height;
371
372         float slider_size = 0.0;
373         int slider_value = value;
374
375         workarea_->setScrollbarBounds(0, bv_->text->height - workarea_->height());
376         double lineh = bv_->text->DefaultHeight();
377         workarea_->setScrollbarIncrements(lineh);
378         if (maxfloat > 0.0) {
379                 if ((hfloat / maxfloat) * float(height2) < 3)
380                         slider_size = 3.0/float(height2);
381                 else
382                         slider_size = hfloat / maxfloat;
383         } else
384                 slider_size = hfloat;
385
386         workarea_->setScrollbar(slider_value, slider_size / workarea_->height());
387 }
388
389
390 // Callback for scrollbar slider
391 void BufferView::Pimpl::scrollCB(double value)
392 {
393         if (buffer_ == 0) return;
394
395         current_scrollbar_value = long(value);
396         if (current_scrollbar_value < 0)
397                 current_scrollbar_value = 0;
398    
399         if (!screen_)
400                 return;
401
402         screen_->Draw(bv_->text, bv_, current_scrollbar_value);
403
404         if (lyxrc.cursor_follows_scrollbar) {
405                 LyXText * vbt = bv_->text;
406                 int height = vbt->DefaultHeight();
407                 
408                 if (vbt->cursor.y() < static_cast<int>((bv_->text->first + height))) {
409                         vbt->SetCursorFromCoordinates(bv_, 0,
410                                                       bv_->text->first +
411                                                       height);
412                 } else if (vbt->cursor.y() >
413                            static_cast<int>((bv_->text->first+workarea_->height()-height)))
414                 {
415                         vbt->SetCursorFromCoordinates(bv_, 0,
416                                                       bv_->text->first +
417                                                       workarea_->height()  -
418                                                       height);
419                 }
420         }
421         waitForX();
422 }
423
424
425 int BufferView::Pimpl::scrollUp(long time)
426 {
427         if (buffer_ == 0) 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_ == 0) 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_ == 0 || !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 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                 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         return;
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_ == 0 || !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();
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_ && !bv_->theLockingInset()) {
642                 if (screen_ && button == 1) {
643                         screen_->HideCursor();
644                         screen_->ToggleSelection(bv_->text, bv_);
645                         bv_->text->SelectWord(bv_);
646                         screen_->ToggleSelection(bv_->text, bv_, false);
647                         /* This will fit the cursor on the screen
648                          * if necessary */
649                         update(BufferView::SELECT|BufferView::FITCUR);
650                 }
651         }   
652 }
653
654
655 void BufferView::Pimpl::tripleClick(int /*x*/, int /*y*/, unsigned int button)
656 {
657         // select a line
658         if (buffer_ && screen_ && !bv_->theLockingInset() && (button == 1)) {
659                 screen_->HideCursor();
660                 screen_->ToggleSelection(bv_->text, bv_);
661                 bv_->text->CursorHome(bv_);
662                 bv_->text->sel_cursor = bv_->text->cursor;
663                 bv_->text->CursorEnd(bv_);
664                 bv_->text->SetSelection();
665                 screen_->ToggleSelection(bv_->text, bv_, false);
666                 /* This will fit the cursor on the screen
667                  * if necessary */
668                 update(BufferView::SELECT|BufferView::FITCUR);
669         }
670 }
671
672
673 void BufferView::Pimpl::enterView()
674 {
675         if (active() && available()) {
676                 SetXtermCursor(workarea_->getWin());
677                 using_xterm_cursor = true;
678         }
679 }
680
681
682 void BufferView::Pimpl::leaveView()
683 {
684         if (using_xterm_cursor) {
685                 XUndefineCursor(fl_get_display(), workarea_->getWin());
686                 using_xterm_cursor = false;
687         }
688 }
689
690
691 void BufferView::Pimpl::workAreaButtonRelease(int x, int y,
692                                               unsigned int button)
693 {
694         if (buffer_ == 0 || screen_ == 0) return;
695
696         // If we hit an inset, we have the inset coordinates in these
697         // and inset_hit points to the inset.  If we do not hit an
698         // inset, inset_hit is 0, and inset_x == x, inset_y == y.
699         Inset * inset_hit = checkInsetHit(bv_->text, x, y, button);
700
701         if (bv_->theLockingInset()) {
702                 // We are in inset locking mode.
703
704                 /* LyX does a kind of work-area grabbing for insets.
705                    Only a ButtonPress Event outside the inset will 
706                    force a InsetUnlock. */
707                 bv_->theLockingInset()->
708                         InsetButtonRelease(bv_, x, y, button);
709                 return;
710         }
711         
712         selection_possible = false;
713         
714         if (button >= 2) return;
715
716         bv_->setState();
717         owner_->showState();
718
719         // Did we hit an editable inset?
720         if (inset_hit != 0) {
721                 // Inset like error, notes and figures
722                 selection_possible = false;
723
724                 // CHECK fix this proper in 0.13
725
726                 // Following a ref shouldn't issue
727                 // a push on the undo-stack
728                 // anylonger, now that we have
729                 // keybindings for following
730                 // references and returning from
731                 // references.  IMHO though, it
732                 // should be the inset's own business
733                 // to push or not push on the undo
734                 // stack. They don't *have* to
735                 // alter the document...
736                 // (Joacim)
737                 // ...or maybe the SetCursorParUndo()
738                 // below isn't necessary at all anylonger?
739                 if (inset_hit->LyxCode() == Inset::REF_CODE) {
740                         bv_->text->SetCursorParUndo(bv_->buffer());
741                 }
742
743                 owner_->getMiniBuffer()->Set(inset_hit->EditMessage());
744                 if (inset_hit->Editable()==Inset::HIGHLY_EDITABLE) {
745                         // Highly editable inset, like math
746                         UpdatableInset *inset = (UpdatableInset *)inset_hit;
747                         inset->InsetButtonRelease(bv_, x, y, button);
748                 } else {
749                         inset_hit->InsetButtonRelease(bv_, x, y, button);
750                         inset_hit->Edit(bv_, x, y, button);
751                 }
752                 return;
753         }
754
755         // check whether we want to open a float
756         if (bv_->text) {
757                 bool hit = false;
758                 char c = ' ';
759                 if (bv_->text->cursor.pos() <
760                     bv_->text->cursor.par()->Last()) {
761                         c = bv_->text->cursor.par()->
762                                 GetChar(bv_->text->cursor.pos());
763                 }
764 #ifndef NEW_INSETS
765                if(!bv_->text->selection)
766                 if (c == LyXParagraph::META_FOOTNOTE
767                     || c == LyXParagraph::META_MARGIN
768                     || c == LyXParagraph::META_FIG
769                     || c == LyXParagraph::META_TAB
770                     || c == LyXParagraph::META_WIDE_FIG
771                     || c == LyXParagraph::META_WIDE_TAB
772                     || c == LyXParagraph::META_ALGORITHM){
773                         hit = true;
774                 } else
775 #endif
776                         if (bv_->text->cursor.pos() - 1 >= 0) {
777                         c = bv_->text->cursor.par()->
778                                 GetChar(bv_->text->cursor.pos() - 1);
779 #ifndef NEW_INSETS
780                         if (c == LyXParagraph::META_FOOTNOTE
781                             || c == LyXParagraph::META_MARGIN
782                             || c == LyXParagraph::META_FIG
783                             || c == LyXParagraph::META_TAB
784                             || c == LyXParagraph::META_WIDE_FIG 
785                             || c == LyXParagraph::META_WIDE_TAB
786                             || c == LyXParagraph::META_ALGORITHM){
787                                 // We are one step too far to the right
788                                 bv_->text->CursorLeft(bv_);
789                                 hit = true;
790                         }
791 #endif
792                 }
793                 if (hit == true) {
794 #ifndef NEW_INSETS
795                         bv_->toggleFloat();
796 #endif
797                         selection_possible = false;
798                         return;
799                 }
800         }
801
802 #ifndef NEW_INSETS
803         // Do we want to close a float? (click on the float-label)
804         if (bv_->text->cursor.row()->par()->footnoteflag == 
805             LyXParagraph::OPEN_FOOTNOTE
806             && bv_->text->cursor.row()->previous() &&
807             bv_->text->cursor.row()->previous()->par()->
808             footnoteflag != LyXParagraph::OPEN_FOOTNOTE){
809                 LyXFont font(LyXFont::ALL_SANE);
810                 font.setSize(LyXFont::SIZE_FOOTNOTE);
811
812                 int box_x = 20; // LYX_PAPER_MARGIN;
813                 box_x += lyxfont::width(" wide-tab ", font);
814
815                 unsigned int screen_first = bv_->text->first;
816
817                 if (x < box_x
818                     && y + screen_first > bv_->text->cursor.y() -
819                     bv_->text->cursor.row()->baseline()
820                     && y + screen_first < bv_->text->cursor.y() -
821                     bv_->text->cursor.row()->baseline()
822                     + lyxfont::maxAscent(font) * 1.2 + lyxfont::maxDescent(font) * 1.2) {
823                         bv_->toggleFloat();
824                         selection_possible = false;
825                         return;
826                 }
827         }
828 #endif
829
830         // Maybe we want to edit a bibitem ale970302
831         if (bv_->text->cursor.par()->bibkey && x < 20 + 
832             bibitemMaxWidth(bv_, textclasslist.
833                             TextClass(buffer_->
834                                       params.textclass).defaultfont())) {
835                 bv_->text->cursor.par()->bibkey->Edit(bv_, 0, 0, 0);
836         }
837
838         return;
839 }
840
841
842 /* 
843  * Returns an inset if inset was hit. 0 otherwise.
844  * If hit, the coordinates are changed relative to the inset. 
845  * Otherwise coordinates are not changed, and false is returned.
846  */
847 Inset * BufferView::Pimpl::checkInsetHit(LyXText * text, int & x, int & y,
848                                          unsigned int /* button */)
849 {
850         if (!screen_)
851                 return 0;
852   
853         int y_tmp = y + text->first;
854   
855         LyXCursor cursor;
856         text->SetCursorFromCoordinates(bv_, cursor, x, y_tmp);
857
858         if (cursor.pos() < cursor.par()->Last()
859             && cursor.par()->GetChar(cursor.pos()) == LyXParagraph::META_INSET
860             && cursor.par()->GetInset(cursor.pos())
861             && cursor.par()->GetInset(cursor.pos())->Editable()) {
862
863                 // Check whether the inset really was hit
864                 Inset * tmpinset = cursor.par()->GetInset(cursor.pos());
865                 LyXFont font = text->GetFont(bv_->buffer(),
866                                                   cursor.par(), cursor.pos());
867                 int width = tmpinset->width(bv_, font);
868                 int inset_x = font.isVisibleRightToLeft()
869                         ? cursor.x() - width : cursor.x();
870                 int start_x = inset_x + tmpinset->scroll();
871                 int end_x = inset_x + width;
872
873                 if (x > start_x && x < end_x
874                     && y_tmp > cursor.y() - tmpinset->ascent(bv_, font)
875                     && y_tmp < cursor.y() + tmpinset->descent(bv_, font)) {
876                         text->SetCursor(bv_, cursor.par(),cursor.pos(),true);
877                         x = x - start_x;
878                         // The origin of an inset is on the baseline
879                         y = y_tmp - (text->cursor.y()); 
880                         return tmpinset;
881                 }
882         }
883
884         if ((cursor.pos() - 1 >= 0) &&
885             (cursor.par()->GetChar(cursor.pos()-1) == LyXParagraph::META_INSET) &&
886             (cursor.par()->GetInset(cursor.pos() - 1)) &&
887             (cursor.par()->GetInset(cursor.pos() - 1)->Editable())) {
888                 Inset * tmpinset = cursor.par()->GetInset(cursor.pos()-1);
889                 LyXFont font = text->GetFont(bv_->buffer(), cursor.par(),
890                                                   cursor.pos()-1);
891                 int width = tmpinset->width(bv_, font);
892                 int inset_x = font.isVisibleRightToLeft()
893                         ? cursor.x() : cursor.x() - width;
894                 int start_x = inset_x + tmpinset->scroll();
895                 int end_x = inset_x + width;
896
897                 if (x > start_x && x < end_x
898                     && y_tmp > cursor.y() - tmpinset->ascent(bv_, font)
899                     && y_tmp < cursor.y() + tmpinset->descent(bv_, font)) {
900 #if 0
901                         if (move_cursor && (tmpinset != bv_->theLockingInset()))
902 #endif
903                                 text->SetCursor(bv_, cursor.par(),cursor.pos()-1,true);
904                         x = x - start_x;
905                         // The origin of an inset is on the baseline
906                         y = y_tmp - (text->cursor.y()); 
907                         return tmpinset;
908                 }
909         }
910         return 0;
911 }
912
913
914 void BufferView::Pimpl::workAreaExpose()
915 {
916         // this is a hack to ensure that we only call this through
917         // BufferView::redraw().
918         //if (!lgb_hack) {
919         //      redraw();
920         //}
921         
922         static int work_area_width = 0;
923         static unsigned int work_area_height = 0;
924
925         bool widthChange = workarea_->workWidth() != work_area_width;
926         bool heightChange = workarea_->height() != work_area_height;
927
928         // update from work area
929         work_area_width = workarea_->workWidth();
930         work_area_height = workarea_->height();
931         if (buffer_ != 0) {
932                 if (widthChange) {
933                         // All buffers need a resize
934                         bufferlist.resize();
935
936                         // Remove all texts from the textcache
937                         // This is not _really_ what we want to do. What
938                         // we really want to do is to delete in textcache
939                         // that does not have a BufferView with matching
940                         // width, but as long as we have only one BufferView
941                         // deleting all gives the same result.
942                         if (lyxerr.debugging())
943                                 textcache.show(lyxerr, "Expose delete all");
944                         textcache.clear();
945                 } else if (heightChange) {
946                         // Rebuild image of current screen
947                         updateScreen();
948                         // fitCursor() ensures we don't jump back
949                         // to the start of the document on vertical
950                         // resize
951                         fitCursor(bv_->text);
952
953                         // The main window size has changed, repaint most stuff
954                         redraw();
955                         // ...including the minibuffer
956                         owner_->getMiniBuffer()->Init();
957
958                 } else if (screen_)
959                     screen_->Redraw(bv_->text, bv_);
960         } else {
961                 // Grey box when we don't have a buffer
962                 workarea_->greyOut();
963         }
964
965         // always make sure that the scrollbar is sane.
966         updateScrollbar();
967         owner_->updateLayoutChoice();
968         return;
969 }
970
971
972 void BufferView::Pimpl::update()
973 {
974         if (screen_) screen_->Update(bv_->text, bv_);
975 }
976
977 // Values used when calling update:
978 // -3 - update
979 // -2 - update, move sel_cursor if selection, fitcursor
980 // -1 - update, move sel_cursor if selection, fitcursor, mark dirty
981 //  0 - update, move sel_cursor if selection, fitcursor 
982 //  1 - update, move sel_cursor if selection, fitcursor, mark dirty
983 //  3 - update, move sel_cursor if selection
984 //
985 // update -
986 // a simple redraw of the parts that need refresh
987 //
988 // move sel_cursor if selection -
989 // the text's sel_cursor is moved if there is selection is progress
990 //
991 // fitcursor -
992 // fitCursor() is called and the scrollbar updated
993 //
994 // mark dirty -
995 // the buffer is marked dirty.
996 //
997 // enum {
998 //       UPDATE = 0,
999 //       SELECT = 1,
1000 //       FITCUR = 2,
1001 //       CHANGE = 4 
1002 // };
1003 //
1004 // UPDATE_ONLY = UPDATE;
1005 // UPDATE_SELECT = UPDATE | SELECT;
1006 // UPDATE_SELECT_MOVE = UPDATE | SELECT | FITCUR;
1007 // UPDATE_SELECT_MOVE_AFTER_CHANGE = UPDATE | SELECT | FITCUR | CHANGE;
1008 //
1009 // update(-3) -> update(0)         -> update(0) -> update(UPDATE)
1010 // update(-2) -> update(1 + 2)     -> update(3) -> update(SELECT|FITCUR)
1011 // update(-1) -> update(1 + 2 + 4) -> update(7) -> update(SELECT|FITCUR|CHANGE)
1012 // update(1)  -> update(1 + 2 + 4) -> update(7) -> update(SELECT|FITCUR|CHANGE)
1013 // update(3)  -> update(1)         -> update(1) -> update(SELECT)
1014
1015 void BufferView::Pimpl::update(BufferView::UpdateCodes f)
1016 {
1017         owner_->updateLayoutChoice();
1018
1019         if (!bv_->text->selection && (f & SELECT)) {
1020                 bv_->text->sel_cursor = bv_->text->cursor;
1021         }
1022
1023         bv_->text->FullRebreak(bv_);
1024
1025         update();
1026
1027         if ((f & FITCUR)) {
1028                 fitCursor(bv_->text);
1029         }
1030
1031         if ((f & CHANGE)) {
1032                 if (buffer_->isLyxClean()) {
1033                         buffer_->markDirty();
1034                         owner_->getMiniBuffer()->setTimer(4);
1035                 } else {
1036                         buffer_->markDirty();
1037                 }
1038         }
1039 }
1040
1041
1042 // Callback for cursor timer
1043 void BufferView::Pimpl::cursorToggle()
1044 {
1045         // Quite a nice place for asyncron Inset updating, isn't it?
1046         // Actually no! This is run even if no buffer exist... so (Lgb)
1047         if (!buffer_) {
1048                 goto set_timer_and_return;
1049         }
1050
1051         // NOTE:
1052         // On my quest to solve the gs render hangups I am now
1053         // disabling the SIGHUP completely, and will do a wait
1054         // now and then instead. If the guess that xforms somehow
1055         // destroys something is true, this is likely (hopefully)
1056         // to solve the problem...at least I hope so. Lgb
1057
1058         // ...Ok this seems to work...at least it does not make things
1059         // worse so far. However I still see gs processes that hangs.
1060         // I would really like to know _why_ they are hanging. Anyway
1061         // the solution without the SIGCHLD handler seems to be easier
1062         // to debug.
1063
1064         // When attaching gdb to a a running gs that hangs it shows
1065         // that it is waiting for input(?) Is it possible for us to
1066         // provide that input somehow? Or figure what it is expecing
1067         // to read?
1068
1069         // One solution is to, after some time, look if there are some
1070         // old gs processes still running and if there are: kill them
1071         // and re render.
1072
1073         // Another solution is to provide the user an option to rerender
1074         // a picture. This would, for the picture in question, check if
1075         // there is a gs running for it, if so kill it, and start a new
1076         // rendering process.
1077
1078         // these comments posted to lyx@via
1079         {
1080                 int status = 1;
1081                 int pid = waitpid(static_cast<pid_t>(0), &status, WNOHANG);
1082                 if (pid == -1) // error find out what is wrong
1083                         ; // ignore it for now.
1084                 else if (pid > 0)
1085                         sigchldhandler(pid, &status);
1086         }
1087
1088         updatelist.update(bv_);
1089         
1090         if (!screen_) {
1091                 goto set_timer_and_return;
1092         }
1093
1094         if (!bv_->theLockingInset()) {
1095                 screen_->CursorToggle(bv_->text, bv_);
1096         } else {
1097                 bv_->theLockingInset()->ToggleInsetCursor(bv_);
1098         }
1099         
1100   set_timer_and_return:
1101         cursor_timeout.restart();
1102         return;
1103 }
1104
1105
1106 void BufferView::Pimpl::cursorPrevious(LyXText * text)
1107 {
1108         if (!text->cursor.row()->previous())
1109                 return;
1110         
1111         int y = text->first;
1112         if (text->inset_owner)
1113                 y += bv_->text->first;
1114         Row * cursorrow = text->cursor.row();
1115         text->SetCursorFromCoordinates(bv_, bv_->text->cursor.x_fix(), y);
1116         bv_->text->FinishUndo();
1117         // This is to allow jumping over large insets
1118         if ((cursorrow == text->cursor.row()))
1119                 text->CursorUp(bv_);
1120         
1121         if (text->inset_owner ||
1122             text->cursor.row()->height() < workarea_->height())
1123                 screen_->Draw(bv_->text, bv_,
1124                               text->cursor.y()
1125                               - text->cursor.row()->baseline()
1126                               + text->cursor.row()->height()
1127                               - workarea_->height() + 1 );
1128         updateScrollbar();
1129 }
1130
1131
1132 void BufferView::Pimpl::cursorNext(LyXText * text)
1133 {
1134         if (!text->cursor.row()->next())
1135                 return;
1136         
1137         int y = text->first + workarea_->height();
1138 //      if (text->inset_owner)
1139 //              y += bv_->text->first;
1140         text->GetRowNearY(y);
1141     
1142         Row * cursorrow = text->cursor.row();
1143         text->SetCursorFromCoordinates(bv_, text->cursor.x_fix(), y); // + workarea_->height());
1144         bv_->text->FinishUndo();
1145         // This is to allow jumping over large insets
1146         if ((cursorrow == bv_->text->cursor.row()))
1147                 text->CursorDown(bv_);
1148         
1149         if (text->inset_owner ||
1150             text->cursor.row()->height() < workarea_->height())
1151                 screen_->Draw(bv_->text, bv_, text->cursor.y() -
1152                               text->cursor.row()->baseline());
1153         updateScrollbar();
1154 }
1155
1156
1157 bool BufferView::Pimpl::available() const
1158 {
1159         if (buffer_ && bv_->text) return true;
1160         return false;
1161 }
1162
1163
1164 void BufferView::Pimpl::beforeChange()
1165 {
1166         toggleSelection();
1167         bv_->text->ClearSelection();
1168
1169         // CHECK
1170         //owner_->update_timeout.stop();
1171 }
1172
1173
1174 void BufferView::Pimpl::savePosition()
1175 {
1176         backstack.push(buffer_->fileName(),
1177                        bv_->text->cursor.x(),
1178                        bv_->text->cursor.y());
1179 }
1180
1181
1182 void BufferView::Pimpl::restorePosition()
1183 {
1184         if (backstack.empty()) return;
1185         
1186         int  x, y;
1187         string fname = backstack.pop(&x, &y);
1188
1189         beforeChange();
1190
1191         if (fname != buffer_->fileName()) {
1192                 Buffer * b = bufferlist.exists(fname) ?
1193                         bufferlist.getBuffer(fname) :
1194                         bufferlist.loadLyXFile(fname); // don't ask, just load it
1195                 if (b != 0 ) buffer(b);
1196         }
1197
1198         bv_->text->SetCursorFromCoordinates(bv_, x, y);
1199         update(BufferView::SELECT|BufferView::FITCUR);
1200 }
1201
1202
1203 bool BufferView::Pimpl::NoSavedPositions()
1204 {
1205         return backstack.empty();
1206 }
1207
1208
1209 void BufferView::Pimpl::setState()
1210 {
1211         if (!lyxrc.rtl_support)
1212                 return;
1213
1214         LyXText * text = bv_->getLyXText();
1215         if (text->real_current_font.isRightToLeft() &&
1216             text->real_current_font.latex() != LyXFont::ON) {
1217                 if (owner_->getIntl()->primarykeymap)
1218                         owner_->getIntl()->KeyMapSec();
1219         } else {
1220                 if (!owner_->getIntl()->primarykeymap)
1221                         owner_->getIntl()->KeyMapPrim();
1222         }
1223 }
1224
1225
1226 void BufferView::Pimpl::insetSleep()
1227 {
1228         if (bv_->theLockingInset() && !bv_->inset_slept) {
1229                 bv_->theLockingInset()->GetCursorPos(bv_, bv_->slx, bv_->sly);
1230                 bv_->theLockingInset()->InsetUnlock(bv_);
1231                 bv_->inset_slept = true;
1232         }
1233 }
1234
1235
1236 void BufferView::Pimpl::insetWakeup()
1237 {
1238         if (bv_->theLockingInset() && bv_->inset_slept) {
1239                 bv_->theLockingInset()->Edit(bv_, bv_->slx, bv_->sly, 0);
1240                 bv_->inset_slept = false;
1241         }
1242 }
1243
1244
1245 void BufferView::Pimpl::insetUnlock()
1246 {
1247         if (bv_->theLockingInset()) {
1248                 if (!bv_->inset_slept)
1249                         bv_->theLockingInset()->InsetUnlock(bv_);
1250                 bv_->theLockingInset(0);
1251                 bv_->text->FinishUndo();
1252                 bv_->inset_slept = false;
1253         }
1254 }
1255
1256
1257 bool BufferView::Pimpl::focus() const
1258 {
1259         return workarea_->hasFocus();
1260 }
1261
1262
1263 void BufferView::Pimpl::focus(bool f)
1264 {
1265         if (f) workarea_->setFocus();
1266 }
1267
1268
1269 bool BufferView::Pimpl::active() const
1270 {
1271         return workarea_->active();
1272 }
1273
1274
1275 bool BufferView::Pimpl::belowMouse() const 
1276 {
1277         return workarea_->belowMouse();
1278 }
1279
1280
1281 void BufferView::Pimpl::showCursor()
1282 {
1283         if (screen_)
1284                 screen_->ShowCursor(bv_->text, bv_);
1285 }
1286
1287
1288 void BufferView::Pimpl::hideCursor()
1289 {
1290         if (screen_)
1291                 screen_->HideCursor();
1292 }
1293
1294
1295 void BufferView::Pimpl::toggleSelection(bool b)
1296 {
1297         if (screen_)
1298                 screen_->ToggleSelection(bv_->text, bv_, b);
1299 }
1300
1301
1302 void BufferView::Pimpl::toggleToggle()
1303 {
1304         if (screen_)
1305                 screen_->ToggleToggle(bv_->text, bv_);
1306 }
1307
1308
1309 void BufferView::Pimpl::center() 
1310 {
1311         beforeChange();
1312         if (bv_->text->cursor.y() > static_cast<int>((workarea_->height() / 2))) {
1313                 screen_->Draw(bv_->text, bv_, bv_->text->cursor.y() - workarea_->height() / 2);
1314         } else {
1315                 screen_->Draw(bv_->text, bv_, 0);
1316         }
1317         update(BufferView::SELECT|BufferView::FITCUR);
1318         redraw();
1319 }
1320
1321
1322 void BufferView::Pimpl::pasteClipboard(bool asPara) 
1323 {
1324         if (buffer_ == 0) return;
1325
1326         screen_->HideCursor();
1327         bv_->beforeChange();
1328         
1329         string const clip(workarea_->getClipboard());
1330         
1331         if (clip.empty()) return;
1332
1333         if (asPara) {
1334                 bv_->text->InsertStringB(bv_, clip);
1335         } else {
1336                 bv_->text->InsertStringA(bv_, clip);
1337         }
1338         update(BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
1339 }
1340
1341
1342 void BufferView::Pimpl::stuffClipboard(string const & stuff) const
1343 {
1344         workarea_->putClipboard(stuff);
1345 }