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