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