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