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