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