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