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