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