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