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