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