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