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