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