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