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