]> git.lyx.org Git - lyx.git/blob - src/BufferView_pimpl.C
Debloatarise.
[lyx.git] / src / BufferView_pimpl.C
1 /**
2  * \file BufferView_pimpl.C
3  * Copyright 2002 the LyX Team
4  * Read the file COPYING
5  *
6  * \author various
7  */
8
9 #include <config.h>
10
11 #ifdef __GNUG__
12 #pragma implementation
13 #endif
14
15 #include "BufferView_pimpl.h"
16 #include "frontends/WorkArea.h"
17 #include "frontends/screen.h"
18 #include "frontends/LyXScreenFactory.h"
19 #include "frontends/WorkAreaFactory.h"
20 #include "frontends/Dialogs.h"
21 #include "frontends/Alert.h"
22 #include "frontends/FileDialog.h"
23 #include "frontends/mouse_state.h"
24 #include "lyxtext.h"
25 #include "lyxrow.h"
26 #include "paragraph.h"
27 #include "frontends/LyXView.h"
28 #include "commandtags.h"
29 #include "lyxfunc.h"
30 #include "debug.h"
31 #include "bufferview_funcs.h"
32 #include "TextCache.h"
33 #include "bufferlist.h"
34 #include "lyxrc.h"
35 #include "intl.h"
36 // added for Dispatch functions
37 #include "lyx_cb.h"
38 #include "lyx_main.h"
39 #include "FloatList.h"
40 #include "gettext.h"
41 #include "ParagraphParameters.h"
42 #include "undo_funcs.h"
43 #include "funcrequest.h"
44
45 #include "insets/insetbib.h"
46 #include "insets/insettext.h"
47 #include "insets/insetlatexaccent.h"
48 #include "insets/insettoc.h"
49 #include "insets/insetindex.h"
50 #include "insets/insetref.h"
51 #include "insets/insetinclude.h"
52 #include "insets/insetcite.h"
53 #include "insets/insetgraphics.h"
54 #include "insets/insetmarginal.h"
55 #include "insets/insetfloatlist.h"
56
57 #include "mathed/formulabase.h"
58
59 #include "graphics/Previews.h"
60
61 #include "support/LAssert.h"
62 #include "support/lstrings.h"
63 #include "support/filetools.h"
64
65 #include <boost/bind.hpp>
66 #include <boost/signals/connection.hpp>
67
68 #include <unistd.h>
69 #include <sys/wait.h>
70
71
72 using std::vector;
73 using std::find_if;
74 using std::find;
75 using std::pair;
76 using std::endl;
77 using std::make_pair;
78 using std::min;
79
80 using lyx::pos_type;
81
82 extern BufferList bufferlist;
83
84
85 namespace {
86
87 unsigned int const saved_positions_num = 20;
88
89 // All the below connection objects are needed because of a bug in some
90 // versions of GCC (<=2.96 are on the suspects list.) By having and assigning
91 // to these connections we avoid a segfault upon startup, and also at exit.
92 // (Lgb)
93
94 boost::signals::connection dispatchcon;
95 boost::signals::connection timecon;
96 boost::signals::connection doccon;
97 boost::signals::connection resizecon;
98 boost::signals::connection kpresscon;
99 boost::signals::connection selectioncon;
100 boost::signals::connection lostcon;
101
102
103 } // anon namespace
104
105
106 BufferView::Pimpl::Pimpl(BufferView * bv, LyXView * owner,
107              int xpos, int ypos, int width, int height)
108         : bv_(bv), owner_(owner), buffer_(0), cursor_timeout(400),
109           using_xterm_cursor(false)
110 {
111         workarea_.reset(WorkAreaFactory::create(xpos, ypos, width, height));
112         screen_.reset(LyXScreenFactory::create(workarea()));
113
114         // Setup the signals
115         doccon = workarea().scrollDocView
116                 .connect(boost::bind(&BufferView::Pimpl::scrollDocView, this, _1));
117         resizecon = workarea().workAreaResize
118                 .connect(boost::bind(&BufferView::Pimpl::workAreaResize, this));
119         dispatchcon = workarea().dispatch
120                 .connect(boost::bind(&BufferView::Pimpl::dispatch, this, _1));
121         kpresscon = workarea().workAreaKeyPress
122                 .connect(boost::bind(&BufferView::Pimpl::workAreaKeyPress, this, _1, _2));
123         selectioncon = workarea().selectionRequested
124                 .connect(boost::bind(&BufferView::Pimpl::selectionRequested, this));
125         lostcon = workarea().selectionLost
126                 .connect(boost::bind(&BufferView::Pimpl::selectionLost, this));
127
128         timecon = cursor_timeout.timeout
129                 .connect(boost::bind(&BufferView::Pimpl::cursorToggle, this));
130         cursor_timeout.start();
131         saved_positions.resize(saved_positions_num);
132 }
133
134
135 WorkArea & BufferView::Pimpl::workarea() const
136 {
137         return *workarea_.get();
138 }
139
140
141 LyXScreen & BufferView::Pimpl::screen() const
142 {
143         return *screen_.get();
144 }
145
146
147 Painter & BufferView::Pimpl::painter() const
148 {
149         return workarea().getPainter();
150 }
151
152
153 void BufferView::Pimpl::buffer(Buffer * b)
154 {
155         lyxerr[Debug::INFO] << "Setting buffer in BufferView ("
156                             << b << ")" << endl;
157         if (buffer_) {
158                 buffer_->delUser(bv_);
159
160                 // Put the old text into the TextCache, but
161                 // only if the buffer is still loaded.
162                 // Also set the owner of the test to 0
163                 //              bv_->text->owner(0);
164                 textcache.add(buffer_, workarea().workWidth(), bv_->text);
165                 if (lyxerr.debugging())
166                         textcache.show(lyxerr, "BufferView::buffer");
167
168                 bv_->text = 0;
169         }
170
171         // set current buffer
172         buffer_ = b;
173
174         if (bufferlist.getState() == BufferList::CLOSING) return;
175
176         // if we are closing the buffer, use the first buffer as current
177         if (!buffer_) {
178                 buffer_ = bufferlist.first();
179         }
180
181         if (buffer_) {
182                 lyxerr[Debug::INFO] << "Buffer addr: " << buffer_ << endl;
183                 buffer_->addUser(bv_);
184
185                 // If we don't have a text object for this, we make one
186                 if (bv_->text == 0) {
187                         resizeCurrentBuffer();
188                 }
189
190                 // FIXME: needed when ?
191                 bv_->text->first_y =
192                         screen().topCursorVisible(bv_->text->cursor, bv_->text->first_y);
193
194                 // Similarly, buffer-dependent dialogs should be updated or
195                 // hidden. This should go here because some dialogs (eg ToC)
196                 // require bv_->text.
197                 owner_->getDialogs().updateBufferDependent(true);
198         } else {
199                 lyxerr[Debug::INFO] << "  No Buffer!" << endl;
200                 owner_->getDialogs().hideBufferDependent();
201
202                 // Also remove all remaining text's from the testcache.
203                 // (there should not be any!) (if there is any it is a
204                 // bug!)
205                 if (lyxerr.debugging())
206                         textcache.show(lyxerr, "buffer delete all");
207                 textcache.clear();
208         }
209
210         repaint();
211         updateScrollbar();
212         owner_->updateMenubar();
213         owner_->updateToolbar();
214         owner_->updateLayoutChoice();
215         owner_->updateWindowTitle();
216
217         if (grfx::Previews::activated() && buffer_)
218                 grfx::Previews::get().generateBufferPreviews(*buffer_);
219 }
220
221
222 bool BufferView::Pimpl::fitCursor()
223 {
224         bool ret;
225
226         if (bv_->theLockingInset()) {
227                 bv_->theLockingInset()->fitInsetCursor(bv_);
228                 ret = true;
229         } else {
230                 ret = screen().fitCursor(bv_->text, bv_);
231         }
232
233         bv_->owner()->getDialogs().updateParagraph();
234         if (ret)
235                 updateScrollbar();
236         return ret;
237 }
238
239
240 void BufferView::Pimpl::redoCurrentBuffer()
241 {
242         lyxerr[Debug::INFO] << "BufferView::redoCurrentBuffer" << endl;
243         if (buffer_ && bv_->text) {
244                 resizeCurrentBuffer();
245                 updateScrollbar();
246                 owner_->updateLayoutChoice();
247                 repaint();
248         }
249 }
250
251
252 int BufferView::Pimpl::resizeCurrentBuffer()
253 {
254         lyxerr[Debug::INFO] << "resizeCurrentBuffer" << endl;
255
256         Paragraph * par = 0;
257         Paragraph * selstartpar = 0;
258         Paragraph * selendpar = 0;
259         UpdatableInset * the_locking_inset = 0;
260
261         pos_type pos = 0;
262         pos_type selstartpos = 0;
263         pos_type selendpos = 0;
264         bool selection = false;
265         bool mark_set  = false;
266
267         owner_->prohibitInput();
268
269         owner_->message(_("Formatting document..."));
270
271         if (bv_->text) {
272                 par = bv_->text->cursor.par();
273                 pos = bv_->text->cursor.pos();
274                 selstartpar = bv_->text->selection.start.par();
275                 selstartpos = bv_->text->selection.start.pos();
276                 selendpar = bv_->text->selection.end.par();
277                 selendpos = bv_->text->selection.end.pos();
278                 selection = bv_->text->selection.set();
279                 mark_set = bv_->text->selection.mark();
280                 the_locking_inset = bv_->theLockingInset();
281                 buffer_->resizeInsets(bv_);
282                 // I don't think the delete and new are necessary here we just could
283                 // call only init! (Jug 20020419)
284                 delete bv_->text;
285                 bv_->text = new LyXText(bv_);
286                 bv_->text->init(bv_);
287         } else {
288                 // See if we have a text in TextCache that fits
289                 // the new buffer_ with the correct width.
290                 bv_->text = textcache.findFit(buffer_, workarea().workWidth());
291                 if (bv_->text) {
292                         if (lyxerr.debugging()) {
293                                 lyxerr << "Found a LyXText that fits:\n";
294                                 textcache.show(lyxerr, make_pair(buffer_, make_pair(workarea().workWidth(), bv_->text)));
295                         }
296                         // Set the owner of the newly found text
297                         //      bv_->text->owner(bv_);
298                         if (lyxerr.debugging())
299                                 textcache.show(lyxerr, "resizeCurrentBuffer");
300  
301                         buffer_->resizeInsets(bv_);
302                 } else {
303                         bv_->text = new LyXText(bv_);
304                         bv_->text->init(bv_);
305                         //buffer_->resizeInsets(bv_);
306                 }
307         }
308
309         if (par) {
310                 bv_->text->selection.set(true);
311                 // At this point just to avoid the Delete-Empty-Paragraph-
312                 // Mechanism when setting the cursor.
313                 bv_->text->selection.mark(mark_set);
314                 if (selection) {
315                         bv_->text->setCursor(bv_, selstartpar, selstartpos);
316                         bv_->text->selection.cursor = bv_->text->cursor;
317                         bv_->text->setCursor(bv_, selendpar, selendpos);
318                         bv_->text->setSelection(bv_);
319                         bv_->text->setCursor(bv_, par, pos);
320                 } else {
321                         bv_->text->setCursor(bv_, par, pos);
322                         bv_->text->selection.cursor = bv_->text->cursor;
323                         bv_->text->selection.set(false);
324                 }
325                 // remake the inset locking
326                 bv_->theLockingInset(the_locking_inset);
327         }
328
329         bv_->text->first_y = screen().topCursorVisible(bv_->text->cursor, bv_->text->first_y);
330
331         switchKeyMap();
332         owner_->allowInput();
333
334         updateScrollbar();
335
336         return 0;
337 }
338
339
340 void BufferView::Pimpl::repaint()
341 {
342         // Regenerate the screen.
343         screen().redraw(bv_->text, bv_);
344 }
345
346
347 void BufferView::Pimpl::updateScrollbar()
348 {
349         if (!bv_->text) {
350                 lyxerr[Debug::GUI] << "no text in updateScrollbar" << endl;
351                 workarea().setScrollbarParams(0, 0, 0);
352                 return;
353         }
354
355         LyXText const & t = *bv_->text;
356
357         lyxerr[Debug::GUI] << "Updating scrollbar: h " << t.height << ", first_y "
358                 << t.first_y << ", default height " << t.defaultHeight() << endl;
359
360         workarea().setScrollbarParams(t.height, t.first_y, t.defaultHeight());
361 }
362
363
364 void BufferView::Pimpl::scrollDocView(int value)
365 {
366         lyxerr[Debug::GUI] << "scrollDocView of " << value << endl;
367
368         if (!buffer_)
369                 return;
370
371         screen().draw(bv_->text, bv_, value);
372
373         if (!lyxrc.cursor_follows_scrollbar)
374                 return;
375
376         LyXText * vbt = bv_->text;
377
378         int const height = vbt->defaultHeight();
379         int const first = static_cast<int>((bv_->text->first_y + height));
380         int const last = static_cast<int>((bv_->text->first_y + workarea().workHeight() - height));
381
382         if (vbt->cursor.y() < first)
383                 vbt->setCursorFromCoordinates(bv_, 0, first);
384         else if (vbt->cursor.y() > last)
385                 vbt->setCursorFromCoordinates(bv_, 0, last);
386 }
387
388
389 void BufferView::Pimpl::scroll(int lines)
390 {
391         if (!buffer_) {
392                 return;
393         }
394
395         LyXText const * t = bv_->text;
396         int const line_height = t->defaultHeight();
397
398         // The new absolute coordinate
399         int new_first_y = t->first_y + lines * line_height;
400
401         // Restrict to a valid value
402         new_first_y = std::min(t->height - 4 * line_height, new_first_y);
403         new_first_y = std::max(0, new_first_y);
404
405         scrollDocView(new_first_y);
406
407         // Update the scrollbar.
408         workarea().setScrollbarParams(t->height, t->first_y, t->defaultHeight());
409 }
410
411
412 void BufferView::Pimpl::workAreaKeyPress(LyXKeySymPtr key,
413                                          key_modifier::state state)
414 {
415         bv_->owner()->getLyXFunc().processKeySym(key, state);
416 }
417
418
419 void BufferView::Pimpl::selectionRequested()
420 {
421         static string sel;
422
423         if (!available())
424                 return;
425
426         LyXText * text = bv_->getLyXText();
427
428         if (text->selection.set() &&
429                 (!bv_->text->xsel_cache.set() ||
430                  text->selection.start != bv_->text->xsel_cache.start ||
431                  text->selection.end != bv_->text->xsel_cache.end))
432         {
433                 bv_->text->xsel_cache = text->selection;
434                 sel = text->selectionAsString(bv_->buffer(), false);
435         } else if (!text->selection.set()) {
436                 sel = string();
437                 bv_->text->xsel_cache.set(false);
438         }
439         if (!sel.empty()) {
440                 workarea().putClipboard(sel);
441         }
442 }
443
444
445 void BufferView::Pimpl::selectionLost()
446 {
447         if (available()) {
448                 hideCursor();
449                 toggleSelection();
450                 bv_->getLyXText()->clearSelection();
451                 showCursor();
452                 bv_->text->xsel_cache.set(false);
453         }
454 }
455
456
457 void BufferView::Pimpl::workAreaResize()
458 {
459         static int work_area_width;
460         static int work_area_height;
461
462         bool const widthChange = workarea().workWidth() != work_area_width;
463         bool const heightChange = workarea().workHeight() != work_area_height;
464
465         // update from work area
466         work_area_width = workarea().workWidth();
467         work_area_height = workarea().workHeight();
468
469         if (buffer_ != 0) {
470                 if (widthChange) {
471                         // The visible LyXView need a resize
472                         resizeCurrentBuffer();
473
474                         // Remove all texts from the textcache
475                         // This is not _really_ what we want to do. What
476                         // we really want to do is to delete in textcache
477                         // that does not have a BufferView with matching
478                         // width, but as long as we have only one BufferView
479                         // deleting all gives the same result.
480                         if (lyxerr.debugging())
481                                 textcache.show(lyxerr, "Expose delete all");
482                         textcache.clear();
483                         // FIXME: this is already done in resizeCurrentBuffer() ??
484                         buffer_->resizeInsets(bv_);
485                 } else if (heightChange) {
486                         // fitCursor() ensures we don't jump back
487                         // to the start of the document on vertical
488                         // resize
489                         fitCursor();
490                 }
491         }
492
493         if (widthChange || heightChange) {
494                 repaint();
495         }
496
497         // always make sure that the scrollbar is sane.
498         updateScrollbar();
499         owner_->updateLayoutChoice();
500         return;
501 }
502
503
504 void BufferView::Pimpl::update()
505 {
506         if (!bv_->theLockingInset() || !bv_->theLockingInset()->nodraw()) {
507                 LyXText::text_status st = bv_->text->status();
508                 screen().update(bv_->text, bv_);
509                 bool fitc = false;
510                 while (bv_->text->status() == LyXText::CHANGED_IN_DRAW) {
511                         bv_->text->fullRebreak(bv_);
512                         st = LyXText::NEED_MORE_REFRESH;
513                         bv_->text->setCursor(bv_, bv_->text->cursor.par(),
514                                              bv_->text->cursor.pos());
515                         if (bv_->text->selection.set()) {
516                                 bv_->text->setCursor(bv_, bv_->text->selection.start,
517                                                      bv_->text->selection.start.par(),
518                                                      bv_->text->selection.start.pos());
519                                 bv_->text->setCursor(bv_, bv_->text->selection.end,
520                                                      bv_->text->selection.end.par(),
521                                                      bv_->text->selection.end.pos());
522                         }
523                         fitc = true;
524                         bv_->text->status(bv_, st);
525                         screen().update(bv_->text, bv_);
526                 }
527                 // do this here instead of in the screen::update because of
528                 // the above loop!
529                 bv_->text->status(bv_, LyXText::UNCHANGED);
530                 if (fitc)
531                         fitCursor();
532         }
533 }
534
535 // Values used when calling update:
536 // -3 - update
537 // -2 - update, move sel_cursor if selection, fitcursor
538 // -1 - update, move sel_cursor if selection, fitcursor, mark dirty
539 //  0 - update, move sel_cursor if selection, fitcursor
540 //  1 - update, move sel_cursor if selection, fitcursor, mark dirty
541 //  3 - update, move sel_cursor if selection
542 //
543 // update -
544 // a simple redraw of the parts that need refresh
545 //
546 // move sel_cursor if selection -
547 // the text's sel_cursor is moved if there is selection is progress
548 //
549 // fitcursor -
550 // fitCursor() is called and the scrollbar updated
551 //
552 // mark dirty -
553 // the buffer is marked dirty.
554 //
555 // enum {
556 //       UPDATE = 0,
557 //       SELECT = 1,
558 //       FITCUR = 2,
559 //       CHANGE = 4
560 // };
561 //
562 // UPDATE_ONLY = UPDATE;
563 // UPDATE_SELECT = UPDATE | SELECT;
564 // UPDATE_SELECT_MOVE = UPDATE | SELECT | FITCUR;
565 // UPDATE_SELECT_MOVE_AFTER_CHANGE = UPDATE | SELECT | FITCUR | CHANGE;
566 //
567 // update(-3) -> update(0)         -> update(0) -> update(UPDATE)
568 // update(-2) -> update(1 + 2)     -> update(3) -> update(SELECT|FITCUR)
569 // update(-1) -> update(1 + 2 + 4) -> update(7) -> update(SELECT|FITCUR|CHANGE)
570 // update(1)  -> update(1 + 2 + 4) -> update(7) -> update(SELECT|FITCUR|CHANGE)
571 // update(3)  -> update(1)         -> update(1) -> update(SELECT)
572
573 void BufferView::Pimpl::update(LyXText * text, BufferView::UpdateCodes f)
574 {
575         owner_->updateLayoutChoice();
576
577         if (!text->selection.set() && (f & SELECT)) {
578                 text->selection.cursor = text->cursor;
579         }
580
581         text->fullRebreak(bv_);
582
583         if (text->inset_owner) {
584                 text->inset_owner->setUpdateStatus(bv_, InsetText::NONE);
585                 updateInset(text->inset_owner, false);
586         } else {
587                 update();
588         }
589
590         if ((f & FITCUR)) {
591                 fitCursor();
592         }
593
594         if ((f & CHANGE)) {
595                 buffer_->markDirty();
596         }
597 }
598
599
600 // Callback for cursor timer
601 void BufferView::Pimpl::cursorToggle()
602 {
603         if (!buffer_) {
604                 cursor_timeout.restart();
605                 return;
606         }
607
608         if (!bv_->theLockingInset()) {
609                 screen().cursorToggle(bv_);
610         } else {
611                 bv_->theLockingInset()->toggleInsetCursor(bv_);
612         }
613
614         cursor_timeout.restart();
615 }
616
617
618 bool BufferView::Pimpl::available() const
619 {
620         if (buffer_ && bv_->text)
621                 return true;
622         return false;
623 }
624
625
626 void BufferView::Pimpl::beforeChange(LyXText * text)
627 {
628         toggleSelection();
629         text->clearSelection();
630 }
631
632
633 void BufferView::Pimpl::savePosition(unsigned int i)
634 {
635         if (i >= saved_positions_num)
636                 return;
637         saved_positions[i] = Position(buffer_->fileName(),
638                                       bv_->text->cursor.par()->id(),
639                                       bv_->text->cursor.pos());
640         if (i > 0) {
641                 ostringstream str;
642                 str << _("Saved bookmark") << ' ' << i;
643                 owner_->message(STRCONV(str.str()));
644         }
645 }
646
647
648 void BufferView::Pimpl::restorePosition(unsigned int i)
649 {
650         if (i >= saved_positions_num)
651                 return;
652
653         string const fname = saved_positions[i].filename;
654
655         beforeChange(bv_->text);
656
657         if (fname != buffer_->fileName()) {
658                 Buffer * b = bufferlist.exists(fname) ?
659                         bufferlist.getBuffer(fname) :
660                         bufferlist.loadLyXFile(fname); // don't ask, just load it
661                 if (b != 0) buffer(b);
662         }
663
664         Paragraph * par = buffer_->getParFromID(saved_positions[i].par_id);
665         if (!par)
666                 return;
667
668         bv_->text->setCursor(bv_, par,
669                              min(par->size(), saved_positions[i].par_pos));
670
671         update(bv_->text, BufferView::SELECT | BufferView::FITCUR);
672         if (i > 0) {
673                 ostringstream str;
674                 str << _("Moved to bookmark") << ' ' << i;
675                 owner_->message(STRCONV(str.str()));
676         }
677 }
678
679
680 bool BufferView::Pimpl::isSavedPosition(unsigned int i)
681 {
682         if (i >= saved_positions_num)
683                 return false;
684
685         return !saved_positions[i].filename.empty();
686 }
687
688
689 void BufferView::Pimpl::switchKeyMap()
690 {
691         if (!lyxrc.rtl_support)
692                 return;
693
694         LyXText * text = bv_->getLyXText();
695         if (text->real_current_font.isRightToLeft()
696             && !(bv_->theLockingInset()
697                  && bv_->theLockingInset()->lyxCode() == Inset::ERT_CODE))
698         {
699                 if (owner_->getIntl().keymap == Intl::PRIMARY)
700                         owner_->getIntl().KeyMapSec();
701         } else {
702                 if (owner_->getIntl().keymap == Intl::SECONDARY)
703                         owner_->getIntl().KeyMapPrim();
704         }
705 }
706
707
708 void BufferView::Pimpl::insetUnlock()
709 {
710         if (bv_->theLockingInset()) {
711                 bv_->theLockingInset()->insetUnlock(bv_);
712                 bv_->theLockingInset(0);
713                 finishUndo();
714         }
715 }
716
717
718 void BufferView::Pimpl::showCursor()
719 {
720         if (bv_->theLockingInset())
721                 bv_->theLockingInset()->showInsetCursor(bv_);
722         else
723                 screen().showCursor(bv_->text, bv_);
724 }
725
726
727 void BufferView::Pimpl::hideCursor()
728 {
729         if (!bv_->theLockingInset())
730                 screen().hideCursor();
731 }
732
733
734 void BufferView::Pimpl::toggleSelection(bool b)
735 {
736         if (bv_->theLockingInset())
737                 bv_->theLockingInset()->toggleSelection(bv_, b);
738         screen().toggleSelection(bv_->text, bv_, b);
739 }
740
741
742 void BufferView::Pimpl::toggleToggle()
743 {
744         screen().toggleToggle(bv_->text, bv_);
745 }
746
747
748 void BufferView::Pimpl::center()
749 {
750         LyXText * t = bv_->text;
751
752         beforeChange(t);
753         int const half_height = workarea().workHeight() / 2;
754         int new_y = 0;
755
756         if (t->cursor.y() > half_height) {
757                 new_y = t->cursor.y() - half_height;
758         }
759
760         // FIXME: can we do this w/o calling screen directly ?
761         // This updates first_y but means the fitCursor() call
762         // from the update(FITCUR) doesn't realise that we might
763         // have moved (e.g. from GOTOPARAGRAPH), so doesn't cause
764         // the scrollbar to be updated as it should, so we have
765         // to do it manually. Any operation that does a center()
766         // and also might have moved first_y must make sure to call
767         // updateScrollbar() currently. Never mind that this is a
768         // pretty obfuscated way of updating t->first_y
769         screen().draw(t, bv_, new_y);
770
771         update(t, BufferView::SELECT | BufferView::FITCUR);
772 }
773
774
775 void BufferView::Pimpl::stuffClipboard(string const & stuff) const
776 {
777         workarea().putClipboard(stuff);
778 }
779
780
781 /*
782  * Dispatch functions for actions which can be valid for BufferView->text
783  * and/or InsetText->text!!!
784  */
785
786
787 Inset * BufferView::Pimpl::getInsetByCode(Inset::Code code)
788 {
789 #if 0
790         LyXCursor cursor = bv_->getLyXText()->cursor;
791         Buffer::inset_iterator it =
792                 find_if(Buffer::inset_iterator(
793                         cursor.par(), cursor.pos()),
794                         buffer_->inset_iterator_end(),
795                         lyx::compare_memfun(&Inset::lyxCode, code));
796         return it != buffer_->inset_iterator_end() ? (*it) : 0;
797 #else
798         // Ok, this is a little bit too brute force but it
799         // should work for now. Better infrastructure is comming. (Lgb)
800
801         Buffer * b = bv_->buffer();
802         LyXCursor cursor = bv_->getLyXText()->cursor;
803
804         Buffer::inset_iterator beg = b->inset_iterator_begin();
805         Buffer::inset_iterator end = b->inset_iterator_end();
806
807         bool cursor_par_seen = false;
808
809         for (; beg != end; ++beg) {
810                 if (beg.getPar() == cursor.par()) {
811                         cursor_par_seen = true;
812                 }
813                 if (cursor_par_seen) {
814                         if (beg.getPar() == cursor.par()
815                             && beg.getPos() >= cursor.pos()) {
816                                 break;
817                         } else if (beg.getPar() != cursor.par()) {
818                                 break;
819                         }
820                 }
821
822         }
823         if (beg != end) {
824                 // Now find the first inset that matches code.
825                 for (; beg != end; ++beg) {
826                         if (beg->lyxCode() == code) {
827                                 return &(*beg);
828                         }
829                 }
830         }
831         return 0;
832 #endif
833 }
834
835
836 void BufferView::Pimpl::MenuInsertLyXFile(string const & filen)
837 {
838         string filename = filen;
839
840         if (filename.empty()) {
841                 // Launch a file browser
842                 string initpath = lyxrc.document_path;
843
844                 if (available()) {
845                         string const trypath = owner_->buffer()->filePath();
846                         // If directory is writeable, use this as default.
847                         if (IsDirWriteable(trypath))
848                                 initpath = trypath;
849                 }
850
851                 FileDialog fileDlg(bv_->owner(),
852                                    _("Select LyX document to insert"),
853                         LFUN_FILE_INSERT,
854                         make_pair(string(_("Documents|#o#O")),
855                                   string(lyxrc.document_path)),
856                         make_pair(string(_("Examples|#E#e")),
857                                   string(AddPath(system_lyxdir, "examples"))));
858
859                 FileDialog::Result result =
860                         fileDlg.open(initpath,
861                                        _("*.lyx| LyX Documents (*.lyx)"));
862
863                 if (result.first == FileDialog::Later)
864                         return;
865
866                 filename = result.second;
867
868                 // check selected filename
869                 if (filename.empty()) {
870                         owner_->message(_("Canceled."));
871                         return;
872                 }
873         }
874
875         // get absolute path of file and add ".lyx" to the filename if
876         // necessary
877         filename = FileSearch(string(), filename, "lyx");
878
879         string const disp_fn(MakeDisplayPath(filename));
880
881         ostringstream s1;
882         s1 << _("Inserting document") << ' '
883            << disp_fn << " ...";
884         owner_->message(STRCONV(s1.str()));
885         bool const res = bv_->insertLyXFile(filename);
886         if (res) {
887                 ostringstream str;
888                 str << _("Document") << ' ' << disp_fn
889                     << ' ' << _("inserted.");
890                 owner_->message(STRCONV(str.str()));
891         } else {
892                 ostringstream str;
893                 str << _("Could not insert document") << ' '
894                     << disp_fn;
895                 owner_->message(STRCONV(str.str()));
896         }
897 }
898
899
900 bool BufferView::Pimpl::dispatch(FuncRequest const & ev)
901 {
902         lyxerr[Debug::ACTION] << "BufferView::Pimpl::Dispatch:"
903                 << " action[" << ev.action <<"]"
904                 << " arg[" << ev.argument << "]"
905                 << " x[" << ev.x << "]"
906                 << " y[" << ev.y << "]"
907                 << " button[" << ev.button() << "]"
908                 << endl;
909
910         // e.g. Qt mouse press when no buffer
911         if (!buffer_)
912                 return false;
913
914         LyXTextClass const & tclass = buffer_->params.getLyXTextClass();
915
916         switch (ev.action) {
917
918         case LFUN_SCROLL_INSET:
919                 // this is not handled here as this function is only active
920                 // if we have a locking_inset and that one is (or contains)
921                 // a tabular-inset
922                 break;
923
924         case LFUN_INSET_GRAPHICS:
925         {
926                 Inset * new_inset = new InsetGraphics;
927                 if (!insertInset(new_inset)) {
928                         delete new_inset;
929                 } else {
930                         // this is need because you don't use a inset->Edit()
931                         updateInset(new_inset, true);
932                         new_inset->edit(bv_);
933                 }
934                 break;
935         }
936
937         case LFUN_LAYOUT_COPY:
938                 bv_->copyEnvironment();
939                 break;
940
941         case LFUN_LAYOUT_PASTE:
942                 bv_->pasteEnvironment();
943                 switchKeyMap();
944                 break;
945
946         case LFUN_DEPTH_MIN:
947                 changeDepth(bv_, bv_->getLyXText(), -1);
948                 break;
949
950         case LFUN_DEPTH_PLUS:
951                 changeDepth(bv_, bv_->getLyXText(), 1);
952                 break;
953
954         case LFUN_FREE:
955                 owner_->getDialogs().setUserFreeFont();
956                 break;
957
958         case LFUN_FILE_INSERT:
959                 MenuInsertLyXFile(ev.argument);
960                 break;
961
962         case LFUN_FILE_INSERT_ASCII_PARA:
963                 InsertAsciiFile(bv_, ev.argument, true);
964                 break;
965
966         case LFUN_FILE_INSERT_ASCII:
967                 InsertAsciiFile(bv_, ev.argument, false);
968                 break;
969
970         case LFUN_LANGUAGE:
971                 lang(bv_, ev.argument);
972                 switchKeyMap();
973                 owner_->view_state_changed();
974                 break;
975
976         case LFUN_EMPH:
977                 emph(bv_);
978                 owner_->view_state_changed();
979                 break;
980
981         case LFUN_BOLD:
982                 bold(bv_);
983                 owner_->view_state_changed();
984                 break;
985
986         case LFUN_NOUN:
987                 noun(bv_);
988                 owner_->view_state_changed();
989                 break;
990
991         case LFUN_CODE:
992                 code(bv_);
993                 owner_->view_state_changed();
994                 break;
995
996         case LFUN_SANS:
997                 sans(bv_);
998                 owner_->view_state_changed();
999                 break;
1000
1001         case LFUN_ROMAN:
1002                 roman(bv_);
1003                 owner_->view_state_changed();
1004                 break;
1005
1006         case LFUN_DEFAULT:
1007                 styleReset(bv_);
1008                 owner_->view_state_changed();
1009                 break;
1010
1011         case LFUN_UNDERLINE:
1012                 underline(bv_);
1013                 owner_->view_state_changed();
1014                 break;
1015
1016         case LFUN_FONT_SIZE:
1017                 fontSize(bv_, ev.argument);
1018                 owner_->view_state_changed();
1019                 break;
1020
1021         case LFUN_FONT_STATE:
1022                 owner_->getLyXFunc().setMessage(currentState(bv_));
1023                 break;
1024
1025         case LFUN_INSERT_LABEL:
1026                 MenuInsertLabel(bv_, ev.argument);
1027                 break;
1028
1029         case LFUN_REF_INSERT:
1030                 if (ev.argument.empty()) {
1031                         InsetCommandParams p("ref");
1032                         owner_->getDialogs().createRef(p.getAsString());
1033                 } else {
1034                         InsetCommandParams p;
1035                         p.setFromString(ev.argument);
1036
1037                         InsetRef * inset = new InsetRef(p, *buffer_);
1038                         if (!insertInset(inset))
1039                                 delete inset;
1040                         else
1041                                 updateInset(inset, true);
1042                 }
1043                 break;
1044
1045         case LFUN_BOOKMARK_SAVE:
1046                 savePosition(strToUnsignedInt(ev.argument));
1047                 break;
1048
1049         case LFUN_BOOKMARK_GOTO:
1050                 restorePosition(strToUnsignedInt(ev.argument));
1051                 break;
1052
1053         case LFUN_REF_GOTO:
1054         {
1055                 string label = ev.argument;
1056                 if (label.empty()) {
1057                         InsetRef * inset =
1058                                 static_cast<InsetRef*>(getInsetByCode(Inset::REF_CODE));
1059                         if (inset) {
1060                                 label = inset->getContents();
1061                                 savePosition(0);
1062                         }
1063                 }
1064
1065                 if (!label.empty()) {
1066                         //bv_->savePosition(0);
1067                         if (!bv_->gotoLabel(label))
1068                                 Alert::alert(_("Error"),
1069                                            _("Couldn't find this label"),
1070                                            _("in current document."));
1071                 }
1072         }
1073         break;
1074
1075         // --- accented characters ---------------------------
1076
1077         case LFUN_UMLAUT:
1078         case LFUN_CIRCUMFLEX:
1079         case LFUN_GRAVE:
1080         case LFUN_ACUTE:
1081         case LFUN_TILDE:
1082         case LFUN_CEDILLA:
1083         case LFUN_MACRON:
1084         case LFUN_DOT:
1085         case LFUN_UNDERDOT:
1086         case LFUN_UNDERBAR:
1087         case LFUN_CARON:
1088         case LFUN_SPECIAL_CARON:
1089         case LFUN_BREVE:
1090         case LFUN_TIE:
1091         case LFUN_HUNG_UMLAUT:
1092         case LFUN_CIRCLE:
1093         case LFUN_OGONEK:
1094                 if (ev.argument.empty()) {
1095                         // As always...
1096                         owner_->getLyXFunc().handleKeyFunc(ev.action);
1097                 } else {
1098                         owner_->getLyXFunc().handleKeyFunc(ev.action);
1099                         owner_->getIntl().getTransManager()
1100                                 .TranslateAndInsert(ev.argument[0], bv_->getLyXText());
1101                         update(bv_->getLyXText(),
1102                                BufferView::SELECT
1103                                | BufferView::FITCUR
1104                                | BufferView::CHANGE);
1105                 }
1106                 break;
1107
1108         case LFUN_MATH_MACRO:
1109         case LFUN_MATH_DELIM:
1110         case LFUN_INSERT_MATRIX:
1111         case LFUN_INSERT_MATH:
1112         case LFUN_MATH_IMPORT_SELECTION: // Imports LaTeX from the X selection
1113         case LFUN_MATH_DISPLAY:          // Open or create a displayed math inset
1114         case LFUN_MATH_MODE:             // Open or create an inlined math inset
1115         case LFUN_GREEK:                 // Insert a single greek letter
1116                 mathDispatch(FuncRequest(bv_, ev.action, ev.argument));
1117                 break;
1118
1119         case LFUN_CITATION_INSERT:
1120         {
1121                 InsetCommandParams p;
1122                 p.setFromString(ev.argument);
1123
1124                 InsetCitation * inset = new InsetCitation(p);
1125                 if (!insertInset(inset))
1126                         delete inset;
1127                 else {
1128                         inset->setLoadingBuffer(bv_->buffer(), false);
1129                         updateInset(inset, true);
1130                 }
1131
1132         }
1133         break;
1134
1135         case LFUN_INSERT_BIBTEX:
1136         {
1137                 // ale970405+lasgoutt970425
1138                 // The argument can be up to two tokens separated
1139                 // by a space. The first one is the bibstyle.
1140                 string const db = token(ev.argument, ' ', 0);
1141                 string bibstyle = token(ev.argument, ' ', 1);
1142                 if (bibstyle.empty())
1143                         bibstyle = "plain";
1144
1145                 InsetCommandParams p("BibTeX", db, bibstyle);
1146                 InsetBibtex * inset = new InsetBibtex(p);
1147
1148                 if (insertInset(inset)) {
1149                         if (ev.argument.empty())
1150                                 inset->edit(bv_);
1151                 } else
1152                         delete inset;
1153         }
1154         break;
1155
1156         // BibTeX data bases
1157         case LFUN_BIBDB_ADD:
1158         {
1159                 InsetBibtex * inset =
1160                         static_cast<InsetBibtex*>(getInsetByCode(Inset::BIBTEX_CODE));
1161                 if (inset) {
1162                         inset->addDatabase(ev.argument);
1163                 }
1164         }
1165         break;
1166
1167         case LFUN_BIBDB_DEL:
1168         {
1169                 InsetBibtex * inset =
1170                         static_cast<InsetBibtex*>(getInsetByCode(Inset::BIBTEX_CODE));
1171                 if (inset)
1172                         inset->delDatabase(ev.argument);
1173         }
1174         break;
1175
1176         case LFUN_BIBTEX_STYLE:
1177         {
1178                 InsetBibtex * inset =
1179                         static_cast<InsetBibtex*>(getInsetByCode(Inset::BIBTEX_CODE));
1180                 if (inset)
1181                         inset->setOptions(ev.argument);
1182         }
1183         break;
1184
1185         case LFUN_CHILD_INSERT:
1186         {
1187                 InsetInclude::Params p;
1188                 if (!ev.argument.empty())
1189                         p.cparams.setFromString(ev.argument);
1190                 p.masterFilename_ = buffer_->fileName();
1191
1192                 InsetInclude * inset = new InsetInclude(p);
1193                 if (!insertInset(inset))
1194                         delete inset;
1195                 else {
1196                         updateInset(inset, true);
1197                         bv_->owner()->getDialogs().showInclude(inset);
1198                 }
1199         }
1200         break;
1201
1202         case LFUN_FLOAT_LIST:
1203                 if (tclass.floats().typeExist(ev.argument)) {
1204                         Inset * inset = new InsetFloatList(ev.argument);
1205                         if (!insertInset(inset, tclass.defaultLayoutName()))
1206                                 delete inset;
1207                 } else {
1208                         lyxerr << "Non-existent float type: "
1209                                << ev.argument << endl;
1210                 }
1211                 break;
1212
1213         case LFUN_THESAURUS_ENTRY:
1214         {
1215                 string arg = ev.argument;
1216
1217                 if (arg.empty()) {
1218                         arg = bv_->getLyXText()->selectionAsString(buffer_,
1219                                                                    false);
1220
1221                         // FIXME
1222                         if (arg.size() > 100 || arg.empty()) {
1223                                 // Get word or selection
1224                                 bv_->getLyXText()->selectWordWhenUnderCursor(bv_, LyXText::WHOLE_WORD);
1225                                 arg = bv_->getLyXText()->selectionAsString(buffer_, false);
1226                                 // FIXME: where is getLyXText()->unselect(bv_) ?
1227                         }
1228                 }
1229
1230                 bv_->owner()->getDialogs().showThesaurus(arg);
1231         }
1232                 break;
1233
1234         case LFUN_UNKNOWN_ACTION:
1235                 ev.errorMessage(N_("Unknown function!"));
1236                 break;
1237
1238         default:
1239                 return bv_->getLyXText()->dispatch(FuncRequest(ev, bv_));
1240         } // end of switch
1241
1242         return true;
1243 }
1244
1245
1246 bool BufferView::Pimpl::insertInset(Inset * inset, string const & lout)
1247 {
1248         // if we are in a locking inset we should try to insert the
1249         // inset there otherwise this is a illegal function now
1250         if (bv_->theLockingInset()) {
1251                 if (bv_->theLockingInset()->insetAllowed(inset))
1252                         return bv_->theLockingInset()->insertInset(bv_, inset);
1253                 return false;
1254         }
1255
1256         // not quite sure if we want this...
1257         setCursorParUndo(bv_);
1258         freezeUndo();
1259
1260         beforeChange(bv_->text);
1261         if (!lout.empty()) {
1262                 update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
1263                 bv_->text->breakParagraph(bv_);
1264                 update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
1265
1266                 if (!bv_->text->cursor.par()->empty()) {
1267                         bv_->text->cursorLeft(bv_);
1268
1269                         bv_->text->breakParagraph(bv_);
1270                         update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
1271                 }
1272
1273                 string lres = lout;
1274                 LyXTextClass const & tclass =
1275                         buffer_->params.getLyXTextClass();
1276                 bool hasLayout = tclass.hasLayout(lres);
1277                 string lay = tclass.defaultLayoutName();
1278
1279                 if (hasLayout != false) {
1280                         // layout found
1281                         lay = lres;
1282                 } else {
1283                         // layout not fount using default
1284                         lay = tclass.defaultLayoutName();
1285                 }
1286
1287                 bv_->text->setLayout(bv_, lay);
1288
1289                 bv_->text->setParagraph(bv_, 0, 0,
1290                                    0, 0,
1291                                    VSpace(VSpace::NONE), VSpace(VSpace::NONE),
1292                                    Spacing(),
1293                                    LYX_ALIGN_LAYOUT,
1294                                    string(),
1295                                    0);
1296                 update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
1297         }
1298
1299         bv_->text->insertInset(bv_, inset);
1300         update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
1301
1302         unFreezeUndo();
1303         return true;
1304 }
1305
1306
1307 void BufferView::Pimpl::updateInset(Inset * inset, bool mark_dirty)
1308 {
1309         if (!inset || !available())
1310                 return;
1311
1312         // first check for locking insets
1313         if (bv_->theLockingInset()) {
1314                 if (bv_->theLockingInset() == inset) {
1315                         if (bv_->text->updateInset(bv_, inset)) {
1316                                 update();
1317                                 if (mark_dirty) {
1318                                         buffer_->markDirty();
1319                                 }
1320                                 updateScrollbar();
1321                                 return;
1322                         }
1323                 } else if (bv_->theLockingInset()->updateInsetInInset(bv_, inset)) {
1324                         if (bv_->text->updateInset(bv_,  bv_->theLockingInset())) {
1325                                 update();
1326                                 if (mark_dirty) {
1327                                         buffer_->markDirty();
1328                                 }
1329                                 updateScrollbar();
1330                                 return;
1331                         }
1332                 }
1333         }
1334
1335         // then check if the inset is a top_level inset (has no owner)
1336         // if yes do the update as always otherwise we have to update the
1337         // toplevel inset where this inset is inside
1338         Inset * tl_inset = inset;
1339         while (tl_inset->owner())
1340                 tl_inset = tl_inset->owner();
1341         hideCursor();
1342         if (tl_inset == inset) {
1343                 update(bv_->text, BufferView::UPDATE);
1344                 if (bv_->text->updateInset(bv_, inset)) {
1345                         if (mark_dirty) {
1346                                 update(bv_->text,
1347                                        BufferView::SELECT
1348                                        | BufferView::FITCUR
1349                                        | BufferView::CHANGE);
1350                         } else {
1351                                 update(bv_->text, SELECT);
1352                         }
1353                         return;
1354                 }
1355         } else if (static_cast<UpdatableInset *>(tl_inset)
1356                            ->updateInsetInInset(bv_, inset))
1357         {
1358                 if (bv_->text->updateInset(bv_, tl_inset)) {
1359                         update();
1360                         updateScrollbar();
1361                 }
1362         }
1363 }