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