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