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