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