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