]> git.lyx.org Git - lyx.git/blob - src/BufferView_pimpl.C
79ec08c71b4b898cd0b8a11ba9f163fe4a45dbdf
[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 Braunstein
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/insetref.h"
49 #include "insets/insettext.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 "support/filetools.h"
63 #include "support/globbing.h"
64 #include "support/path_defines.h"
65 #include "support/tostr.h"
66
67 #include <boost/bind.hpp>
68
69 using lyx::pos_type;
70
71 using lyx::support::AddPath;
72 using lyx::support::bformat;
73 using lyx::support::FileFilterList;
74 using lyx::support::FileSearch;
75 using lyx::support::IsDirWriteable;
76 using lyx::support::MakeDisplayPath;
77 using lyx::support::strToUnsignedInt;
78 using lyx::support::system_lyxdir;
79
80 using std::endl;
81 using std::istringstream;
82 using std::make_pair;
83 using std::min;
84 using std::string;
85
86
87 extern BufferList bufferlist;
88
89
90 namespace {
91
92 unsigned int const saved_positions_num = 20;
93
94 // All the below connection objects are needed because of a bug in some
95 // versions of GCC (<=2.96 are on the suspects list.) By having and assigning
96 // to these connections we avoid a segfault upon startup, and also at exit.
97 // (Lgb)
98
99 boost::signals::connection dispatchcon;
100 boost::signals::connection timecon;
101 boost::signals::connection doccon;
102 boost::signals::connection resizecon;
103 boost::signals::connection kpresscon;
104 boost::signals::connection selectioncon;
105 boost::signals::connection lostcon;
106
107
108 } // anon namespace
109
110
111 BufferView::Pimpl::Pimpl(BufferView & bv, LyXView * owner,
112              int xpos, int ypos, int width, int height)
113         : bv_(&bv), owner_(owner), buffer_(0), cursor_timeout(400),
114           using_xterm_cursor(false), cursor_(bv)
115 {
116         xsel_cache_.set = false;
117
118         workarea_.reset(WorkAreaFactory::create(xpos, ypos, width, height));
119         screen_.reset(LyXScreenFactory::create(workarea()));
120
121         // Setup the signals
122         doccon = workarea().scrollDocView
123                 .connect(boost::bind(&BufferView::Pimpl::scrollDocView, this, _1));
124         resizecon = workarea().workAreaResize
125                 .connect(boost::bind(&BufferView::Pimpl::workAreaResize, this));
126         dispatchcon = workarea().dispatch
127                 .connect(boost::bind(&BufferView::Pimpl::workAreaDispatch, this, _1));
128         kpresscon = workarea().workAreaKeyPress
129                 .connect(boost::bind(&BufferView::Pimpl::workAreaKeyPress, this, _1, _2));
130         selectioncon = workarea().selectionRequested
131                 .connect(boost::bind(&BufferView::Pimpl::selectionRequested, this));
132         lostcon = workarea().selectionLost
133                 .connect(boost::bind(&BufferView::Pimpl::selectionLost, this));
134
135         timecon = cursor_timeout.timeout
136                 .connect(boost::bind(&BufferView::Pimpl::cursorToggle, this));
137         cursor_timeout.start();
138         saved_positions.resize(saved_positions_num);
139 }
140
141
142 void BufferView::Pimpl::addError(ErrorItem const & ei)
143 {
144         errorlist_.push_back(ei);
145 }
146
147
148 void BufferView::Pimpl::showReadonly(bool)
149 {
150         owner_->updateWindowTitle();
151         owner_->getDialogs().updateBufferDependent(false);
152 }
153
154
155 void BufferView::Pimpl::connectBuffer(Buffer & buf)
156 {
157         if (errorConnection_.connected())
158                 disconnectBuffer();
159
160         errorConnection_ =
161                 buf.error.connect(
162                         boost::bind(&BufferView::Pimpl::addError, this, _1));
163
164         messageConnection_ =
165                 buf.message.connect(
166                         boost::bind(&LyXView::message, owner_, _1));
167
168         busyConnection_ =
169                 buf.busy.connect(
170                         boost::bind(&LyXView::busy, owner_, _1));
171
172         titleConnection_ =
173                 buf.updateTitles.connect(
174                         boost::bind(&LyXView::updateWindowTitle, owner_));
175
176         timerConnection_ =
177                 buf.resetAutosaveTimers.connect(
178                         boost::bind(&LyXView::resetAutosaveTimer, owner_));
179
180         readonlyConnection_ =
181                 buf.readonly.connect(
182                         boost::bind(&BufferView::Pimpl::showReadonly, this, _1));
183
184         closingConnection_ =
185                 buf.closing.connect(
186                         boost::bind(&BufferView::Pimpl::setBuffer, this, (Buffer *)0));
187 }
188
189
190 void BufferView::Pimpl::disconnectBuffer()
191 {
192         errorConnection_.disconnect();
193         messageConnection_.disconnect();
194         busyConnection_.disconnect();
195         titleConnection_.disconnect();
196         timerConnection_.disconnect();
197         readonlyConnection_.disconnect();
198         closingConnection_.disconnect();
199 }
200
201
202 void BufferView::Pimpl::newFile(string const & filename, string const & tname,
203         bool isNamed)
204 {
205         setBuffer(::newFile(filename, tname, isNamed));
206 }
207
208
209 bool BufferView::Pimpl::loadLyXFile(string const & filename, bool tolastfiles)
210 {
211         // get absolute path of file and add ".lyx" to the filename if
212         // necessary
213         string s = FileSearch(string(), filename, "lyx");
214
215         bool const found = !s.empty();
216
217         if (!found)
218                 s = filename;
219
220         // file already open?
221         if (bufferlist.exists(s)) {
222                 string const file = MakeDisplayPath(s, 20);
223                 string text = bformat(_("The document %1$s is already "
224                                         "loaded.\n\nDo you want to revert "
225                                         "to the saved version?"), file);
226                 int const ret = Alert::prompt(_("Revert to saved document?"),
227                         text, 0, 1,  _("&Revert"), _("&Switch to document"));
228
229                 if (ret != 0) {
230                         setBuffer(bufferlist.getBuffer(s));
231                         return true;
232                 }
233                 // FIXME: should be LFUN_REVERT
234                 if (!bufferlist.close(bufferlist.getBuffer(s), false))
235                         return false;
236                 // Fall through to new load. (Asger)
237         }
238
239         Buffer * b;
240
241         if (found) {
242                 b = bufferlist.newBuffer(s);
243                 connectBuffer(*b);
244                 if (!::loadLyXFile(b, s)) {
245                         bufferlist.release(b);
246                         return false;
247                 }
248         } else {
249                 string text = bformat(_("The document %1$s does not yet "
250                                         "exist.\n\nDo you want to create "
251                                         "a new document?"), s);
252                 int const ret = Alert::prompt(_("Create new document?"),
253                          text, 0, 1, _("&Create"), _("Cancel"));
254
255                 if (ret == 0)
256                         b = ::newFile(s, string(), true);
257                 else
258                         return false;
259         }
260
261         setBuffer(b);
262         bv_->showErrorList(_("Parse"));
263
264         if (tolastfiles)
265                 LyX::ref().lastfiles().newFile(b->fileName());
266
267         return true;
268 }
269
270
271 WorkArea & BufferView::Pimpl::workarea() const
272 {
273         return *workarea_.get();
274 }
275
276
277 LyXScreen & BufferView::Pimpl::screen() const
278 {
279         return *screen_.get();
280 }
281
282
283 Painter & BufferView::Pimpl::painter() const
284 {
285         return workarea().getPainter();
286 }
287
288
289 void BufferView::Pimpl::top_y(int y)
290 {
291         top_y_ = y;
292 }
293
294
295 int BufferView::Pimpl::top_y() const
296 {
297         return top_y_;
298 }
299
300
301 void BufferView::Pimpl::setBuffer(Buffer * b)
302 {
303         lyxerr[Debug::INFO] << "Setting buffer in BufferView ("
304                             << b << ')' << endl;
305         if (buffer_)
306                 disconnectBuffer();
307
308         // set current buffer
309         buffer_ = b;
310
311         // reset old cursor
312         top_y_ = 0;
313         cursor_ = LCursor(*bv_);
314
315         // if we're quitting lyx, don't bother updating stuff
316         if (quitting)
317                 return;
318
319         if (buffer_) {
320                 lyxerr[Debug::INFO] << "Buffer addr: " << buffer_ << endl;
321                 connectBuffer(*buffer_);
322
323                 cursor_.push(buffer_->inset());
324                 cursor_.resetAnchor();
325                 buffer_->text().init(bv_);
326
327                 // If we don't have a text object for this, we make one
328                 //if (bv_->text() == 0)
329                 //      resizeCurrentBuffer();
330
331                 // Buffer-dependent dialogs should be updated or
332                 // hidden. This should go here because some dialogs (eg ToC)
333                 // require bv_->text.
334                 owner_->getDialogs().updateBufferDependent(true);
335                 owner_->setLayout(bv_->text()->getPar(0)->layout()->name());
336         } else {
337                 lyxerr[Debug::INFO] << "  No Buffer!" << endl;
338                 // we are closing the buffer, use the first buffer as current
339                 buffer_ = bufferlist.first();
340                 owner_->getDialogs().hideBufferDependent();
341         }
342
343         update();
344         updateScrollbar();
345         owner_->updateMenubar();
346         owner_->updateToolbar();
347         owner_->updateLayoutChoice();
348         owner_->updateWindowTitle();
349
350         if (lyx::graphics::Previews::activated() && buffer_)
351                 lyx::graphics::Previews::get().generateBufferPreviews(*buffer_);
352 }
353
354
355 bool BufferView::Pimpl::fitCursor()
356 {
357         if (!screen().fitCursor(bv_))
358                 return false;
359         updateScrollbar();
360         return true;
361 }
362
363
364 void BufferView::Pimpl::redoCurrentBuffer()
365 {
366         lyxerr[Debug::INFO] << "BufferView::redoCurrentBuffer" << endl;
367         if (buffer_ && bv_->text()) {
368                 resizeCurrentBuffer();
369                 updateScrollbar();
370                 owner_->updateLayoutChoice();
371         }
372 }
373
374
375 void BufferView::Pimpl::resizeCurrentBuffer()
376 {
377         lyxerr[Debug::INFO] << "resizeCurrentBuffer" << endl;
378
379         owner_->busy(true);
380
381         owner_->message(_("Formatting document..."));
382
383         LyXText * text = bv_->text();
384         lyxerr << "### resizeCurrentBuffer: text " << text << endl;
385         if (!text)
386                 return;
387
388         // save the cursor mangled in init
389         LCursor cur = bv_->cursor();
390         text->init(bv_);
391         update();
392         bv_->cursor() = cur;
393         bv_->cursor().updatePos();
394         fitCursor();
395
396         switchKeyMap();
397         owner_->busy(false);
398
399         // reset the "Formatting..." message
400         owner_->clearMessage();
401
402         updateScrollbar();
403 }
404
405
406 void BufferView::Pimpl::updateScrollbar()
407 {
408         if (!bv_->text()) {
409                 lyxerr[Debug::GUI] << "no text in updateScrollbar" << endl;
410                 lyxerr << "no text in updateScrollbar" << endl;
411                 workarea().setScrollbarParams(0, 0, 0);
412                 return;
413         }
414
415         LyXText const & t = *bv_->text();
416
417         lyxerr[Debug::GUI]
418                 << "Updating scrollbar: height: " << t.height()
419                 << " top_y: " << top_y()
420                 << " default height " << defaultRowHeight() << endl;
421
422         workarea().setScrollbarParams(t.height(), top_y(), defaultRowHeight());
423 }
424
425
426 void BufferView::Pimpl::scrollDocView(int value)
427 {
428         lyxerr[Debug::GUI] << "scrollDocView of " << value << endl;
429
430         if (!buffer_)
431                 return;
432
433         screen().hideCursor();
434
435         top_y(value);
436         screen().redraw(*bv_);
437
438         if (!lyxrc.cursor_follows_scrollbar)
439                 return;
440
441         int const height = defaultRowHeight();
442         int const first = top_y() + height;
443         int const last = top_y() + workarea().workHeight() - height;
444
445         bv_->cursor().reset(bv_->buffer()->inset());
446         LyXText * text = bv_->text();
447         int y = text->cursorY(bv_->cursor().front());
448         if (y < first)
449                 y = first;
450         if (y > last)
451                 y = last;
452         text->setCursorFromCoordinates(bv_->cursor(), 0, y);
453
454         owner_->updateLayoutChoice();
455 }
456
457
458 void BufferView::Pimpl::scroll(int lines)
459 {
460         if (!buffer_)
461                 return;
462
463         LyXText const * t = bv_->text();
464         int const line_height = defaultRowHeight();
465
466         // The new absolute coordinate
467         int new_top_y = top_y() + lines * line_height;
468
469         // Restrict to a valid value
470         new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
471         new_top_y = std::max(0, new_top_y);
472
473         scrollDocView(new_top_y);
474
475         // Update the scrollbar.
476         workarea().setScrollbarParams(t->height(), top_y(), defaultRowHeight());
477 }
478
479
480 void BufferView::Pimpl::workAreaKeyPress(LyXKeySymPtr key,
481                                          key_modifier::state state)
482 {
483         bv_->owner()->getLyXFunc().processKeySym(key, state);
484
485         /* This is perhaps a bit of a hack. When we move
486          * around, or type, it's nice to be able to see
487          * the cursor immediately after the keypress. So
488          * we reset the toggle timeout and force the visibility
489          * of the cursor. Note we cannot do this inside
490          * dispatch() itself, because that's called recursively.
491          */
492         if (available()) {
493                 cursor_timeout.restart();
494                 screen().showCursor(*bv_);
495         }
496 }
497
498
499 void BufferView::Pimpl::selectionRequested()
500 {
501         static string sel;
502
503         if (!available())
504                 return;
505
506         LCursor & cur = bv_->cursor();
507
508         if (!cur.selection()) {
509                 xsel_cache_.set = false;
510                 return;
511         }
512
513         if (!xsel_cache_.set ||
514             cur.back() != xsel_cache_.cursor ||
515             cur.anchor_.back() != xsel_cache_.anchor)
516         {
517                 xsel_cache_.cursor = cur.back();
518                 xsel_cache_.anchor = cur.anchor_.back();
519                 xsel_cache_.set = cur.selection();
520                 sel = cur.selectionAsString(false);
521                 if (!sel.empty())
522                         workarea().putClipboard(sel);
523         } 
524 }
525
526
527 void BufferView::Pimpl::selectionLost()
528 {
529         if (available()) {
530                 screen().hideCursor();
531                 bv_->cursor().clearSelection();
532                 xsel_cache_.set = false;
533         }
534 }
535
536
537 void BufferView::Pimpl::workAreaResize()
538 {
539         static int work_area_width;
540         static int work_area_height;
541
542         bool const widthChange = workarea().workWidth() != work_area_width;
543         bool const heightChange = workarea().workHeight() != work_area_height;
544
545         // update from work area
546         work_area_width = workarea().workWidth();
547         work_area_height = workarea().workHeight();
548
549         if (buffer_ && widthChange) {
550                 // The visible LyXView need a resize
551                 resizeCurrentBuffer();
552         }
553
554         if (widthChange || heightChange)
555                 update();
556
557         // always make sure that the scrollbar is sane.
558         updateScrollbar();
559         owner_->updateLayoutChoice();
560 }
561
562
563 void BufferView::Pimpl::update()
564 {
565         //lyxerr << "BufferView::Pimpl::update(), buffer: " << buffer_ << endl;
566         // fix cursor coordinate cache in case something went wrong
567
568         // check needed to survive LyX startup
569         if (buffer_) {
570                 // update all 'visible' paragraphs
571                 ParagraphList::iterator beg;
572                 ParagraphList::iterator end;
573                 getParsInRange(buffer_->paragraphs(),
574                                top_y(), top_y() + workarea().workHeight(),
575                                beg, end);
576                 bv_->text()->redoParagraphs(beg, end);
577                 updateScrollbar();
578         }
579         screen().redraw(*bv_);
580         bv_->owner()->view_state_changed();
581 }
582
583
584 // Callback for cursor timer
585 void BufferView::Pimpl::cursorToggle()
586 {
587         if (buffer_)
588                 screen().toggleCursor(*bv_);
589         cursor_timeout.restart();
590 }
591
592
593 bool BufferView::Pimpl::available() const
594 {
595         return buffer_ && bv_->text();
596 }
597
598
599 Change const BufferView::Pimpl::getCurrentChange()
600 {
601         if (!bv_->buffer()->params().tracking_changes)
602                 return Change(Change::UNCHANGED);
603
604         LyXText * text = bv_->getLyXText();
605         LCursor & cur = bv_->cursor();
606
607         if (!cur.selection())
608                 return Change(Change::UNCHANGED);
609
610         return text->getPar(cur.selBegin())
611                 ->lookupChangeFull(cur.selBegin().pos());
612 }
613
614
615 void BufferView::Pimpl::savePosition(unsigned int i)
616 {
617         if (i >= saved_positions_num)
618                 return;
619         BOOST_ASSERT(bv_->cursor().inTexted());
620         saved_positions[i] = Position(buffer_->fileName(),
621                                       bv_->cursor().paragraph().id(),
622                                       bv_->cursor().pos());
623         if (i > 0)
624                 owner_->message(bformat(_("Saved bookmark %1$s"), tostr(i)));
625 }
626
627
628 void BufferView::Pimpl::restorePosition(unsigned int i)
629 {
630         if (i >= saved_positions_num)
631                 return;
632
633         string const fname = saved_positions[i].filename;
634
635         bv_->cursor().clearSelection();
636
637         if (fname != buffer_->fileName()) {
638                 Buffer * b = 0;
639                 if (bufferlist.exists(fname))
640                         b = bufferlist.getBuffer(fname);
641                 else {
642                         b = bufferlist.newBuffer(fname);
643                         ::loadLyXFile(b, fname); // don't ask, just load it
644                 }
645                 if (b)
646                         setBuffer(b);
647         }
648
649         ParIterator par = buffer_->getParFromID(saved_positions[i].par_id);
650         if (par == buffer_->par_iterator_end())
651                 return;
652
653         bv_->text()->setCursor(
654                 bv_->cursor(),
655                 bv_->text()->parOffset(par.pit()),
656                 min(par->size(), saved_positions[i].par_pos));
657
658         if (i > 0)
659                 owner_->message(bformat(_("Moved to bookmark %1$s"), tostr(i)));
660 }
661
662
663 bool BufferView::Pimpl::isSavedPosition(unsigned int i)
664 {
665         return i < saved_positions_num && !saved_positions[i].filename.empty();
666 }
667
668
669 void BufferView::Pimpl::switchKeyMap()
670 {
671         if (!lyxrc.rtl_support)
672                 return;
673
674         Intl & intl = owner_->getIntl();
675         if (bv_->getLyXText()->real_current_font.isRightToLeft()) {
676                 if (intl.keymap == Intl::PRIMARY)
677                         intl.KeyMapSec();
678         } else {
679                 if (intl.keymap == Intl::SECONDARY)
680                         intl.KeyMapPrim();
681         }
682 }
683
684
685 void BufferView::Pimpl::center()
686 {
687         LyXText * text = bv_->text();
688
689         bv_->cursor().clearSelection();
690         int const half_height = workarea().workHeight() / 2;
691         int new_y = text->cursorY(bv_->cursor().front()) - half_height;
692         if (new_y < 0)
693                 new_y = 0;
694
695         // FIXME: look at this comment again ...
696         // This updates top_y() but means the fitCursor() call
697         // from the update(FITCUR) doesn't realise that we might
698         // have moved (e.g. from GOTOPARAGRAPH), so doesn't cause
699         // the scrollbar to be updated as it should, so we have
700         // to do it manually. Any operation that does a center()
701         // and also might have moved top_y() must make sure to call
702         // updateScrollbar() currently. Never mind that this is a
703         // pretty obfuscated way of updating text->top_y()
704         top_y(new_y);
705 }
706
707
708 void BufferView::Pimpl::stuffClipboard(string const & stuff) const
709 {
710         workarea().putClipboard(stuff);
711 }
712
713
714 InsetBase * BufferView::Pimpl::getInsetByCode(InsetBase::Code code)
715 {
716 #warning Does not work for mathed
717         // Ok, this is a little bit too brute force but it
718         // should work for now. Better infrastructure is coming. (Lgb)
719
720         Buffer * buf = bv_->buffer();
721         Buffer::inset_iterator beg = buf->inset_iterator_begin();
722         Buffer::inset_iterator end = buf->inset_iterator_end();
723
724         bool cursor_par_seen = false;
725
726         LCursor & cur = bv_->cursor();
727         ParagraphList::iterator pit =  bv_->getLyXText()->getPar(cur.par());
728
729         for (; beg != end; ++beg) {
730                 if (beg.getPar() == pit)
731                         cursor_par_seen = true;
732                 if (cursor_par_seen) {
733                         if (beg.getPar() == pit && beg.getPos() >= cur.pos())
734                                 break;
735                         if (beg.getPar() != pit)
736                                 break;
737                 }
738         }
739         if (beg != end) {
740                 // Now find the first inset that matches code.
741                 for (; beg != end; ++beg) {
742                         if (beg->lyxCode() == code)
743                                 return &(*beg);
744                 }
745         }
746         return 0;
747 }
748
749
750 void BufferView::Pimpl::MenuInsertLyXFile(string const & filenm)
751 {
752         string filename = filenm;
753
754         if (filename.empty()) {
755                 // Launch a file browser
756                 string initpath = lyxrc.document_path;
757
758                 if (available()) {
759                         string const trypath = owner_->buffer()->filePath();
760                         // If directory is writeable, use this as default.
761                         if (IsDirWriteable(trypath))
762                                 initpath = trypath;
763                 }
764
765                 FileDialog fileDlg(_("Select LyX document to insert"),
766                         LFUN_FILE_INSERT,
767                         make_pair(string(_("Documents|#o#O")),
768                                   string(lyxrc.document_path)),
769                         make_pair(string(_("Examples|#E#e")),
770                                   string(AddPath(system_lyxdir(), "examples"))));
771
772                 FileDialog::Result result =
773                         fileDlg.open(initpath,
774                                      FileFilterList(_("LyX Documents (*.lyx)")),
775                                      string());
776
777                 if (result.first == FileDialog::Later)
778                         return;
779
780                 filename = result.second;
781
782                 // check selected filename
783                 if (filename.empty()) {
784                         owner_->message(_("Canceled."));
785                         return;
786                 }
787         }
788
789         // get absolute path of file and add ".lyx" to the filename if
790         // necessary
791         filename = FileSearch(string(), filename, "lyx");
792
793         string const disp_fn = MakeDisplayPath(filename);
794         owner_->message(bformat(_("Inserting document %1$s..."), disp_fn));
795         if (bv_->insertLyXFile(filename))
796                 owner_->message(bformat(_("Document %1$s inserted."),
797                                         disp_fn));
798         else
799                 owner_->message(bformat(_("Could not insert document %1$s"),
800                                         disp_fn));
801 }
802
803
804 void BufferView::Pimpl::trackChanges()
805 {
806         Buffer * buf = bv_->buffer();
807         bool const tracking = buf->params().tracking_changes;
808
809         if (!tracking) {
810                 ParIterator const end = buf->par_iterator_end();
811                 for (ParIterator it = buf->par_iterator_begin(); it != end; ++it)
812                         it->trackChanges();
813                 buf->params().tracking_changes = true;
814
815                 // we cannot allow undos beyond the freeze point
816                 buf->undostack().clear();
817         } else {
818                 update();
819                 bv_->text()->setCursor(bv_->cursor(), 0, 0);
820 #warning changes FIXME
821                 bool found = lyx::find::findNextChange(bv_);
822                 if (found) {
823                         owner_->getDialogs().show("changes");
824                         return;
825                 }
826
827                 ParIterator const end = buf->par_iterator_end();
828                 for (ParIterator it = buf->par_iterator_begin(); it != end; ++it)
829                         it->untrackChanges();
830                 buf->params().tracking_changes = false;
831         }
832
833         buf->redostack().clear();
834 }
835
836
837 bool BufferView::Pimpl::workAreaDispatch(FuncRequest const & cmd0)
838 {
839         //
840         // this is only called for mouse related events (including
841         // LFUN_FILE_OPEN generated by drag-and-drop)
842         //
843         FuncRequest cmd = cmd0;
844         cmd.y += bv_->top_y();
845         //lyxerr << "*** workAreaDispatch: request: " << cmd << std::endl;
846         LCursor cur(*bv_);
847         cur.push(bv_->buffer()->inset());
848         cur.resetAnchor();
849         cur.selection() = bv_->cursor().selection();
850         switch (cmd.action) {
851
852 #if 0
853         case LFUN_MOUSE_MOTION: {
854                 if (!available())
855                         return false;
856                 FuncRequest cmd1 = cmd;
857                 DispatchResult res = cur.inset().dispatch(cur, cmd);
858                 if (fitCursor() || res.update()) {
859                         update();
860                         cur.updatePos();
861                 }
862                 return true;
863         }
864 #else
865         case LFUN_MOUSE_MOTION: 
866 #endif
867
868         case LFUN_MOUSE_PRESS:
869         case LFUN_MOUSE_RELEASE:
870         case LFUN_MOUSE_DOUBLE:
871         case LFUN_MOUSE_TRIPLE: {
872                 // We pass those directly to the Bufferview, since
873                 // otherwise selection handling breaks down
874
875                 // Doesn't go through lyxfunc, so we need to update
876                 // the layout choice etc. ourselves
877
878                 // e.g. Qt mouse press when no buffer
879                 if (!available())
880                         return false;
881
882                 screen().hideCursor();
883
884                 // either the inset under the cursor or the
885                 // surrounding LyXText will handle this event.
886
887                 // built temporary path to inset
888                 InsetBase * inset = bv_->text()->editXY(cur, cmd.x, cmd.y);
889                 lyxerr << "hit inset at tip: " << inset << endl;
890                 lyxerr << "created temp cursor:\n" << cur << endl;
891
892                 // Try to dispatch to an non-editable inset near this position
893                 DispatchResult res;
894                 if (inset)
895                         inset->dispatch(cur, cmd);
896
897                 // Dispatch to the temp cursor.
898                 // An inset (or LyXText) can assign this to bv->cursor()
899                 // if it wishes to do so.
900                 if (!res.dispatched())
901                         res = cur.dispatch(cmd);
902
903                 if (fitCursor() || res.update())
904                         update();
905
906                 // see workAreaKeyPress
907                 cursor_timeout.restart();
908                 screen().showCursor(*bv_);
909
910                 // skip these when selecting
911                 if (cmd.action != LFUN_MOUSE_MOTION) {
912                         owner_->updateLayoutChoice();
913                         owner_->updateToolbar();
914                 }
915
916                 // slight hack: this is only called currently when we
917                 // clicked somewhere, so we force through the display
918                 // of the new status here.
919                 owner_->clearMessage();
920                 return true;
921         }
922
923         case LFUN_FILE_OPEN:
924                 owner_->dispatch(cmd);
925                 return true;
926
927         default:
928                 BOOST_ASSERT(false);
929         }
930         return true;
931 }
932
933
934 bool BufferView::Pimpl::dispatch(FuncRequest const & cmd)
935 {
936         //lyxerr << "BufferView::Pimpl::dispatch  cmd: " << cmd << std::endl;
937         // Make sure that the cached BufferView is correct.
938         lyxerr[Debug::ACTION] << "BufferView::Pimpl::Dispatch:"
939                 << " action[" << cmd.action << ']'
940                 << " arg[" << cmd.argument << ']'
941                 << " x[" << cmd.x << ']'
942                 << " y[" << cmd.y << ']'
943                 << " button[" << cmd.button() << ']'
944                 << endl;
945
946         LCursor & cur = bv_->cursor();
947
948         switch (cmd.action) {
949
950         case LFUN_UNDO:
951                 if (available()) {
952                         cur.message(_("Undo"));
953                         cur.clearSelection();
954                         if (!textUndo(*bv_))
955                                 cur.message(_("No further undo information"));
956                         update();
957                         switchKeyMap();
958                 }
959                 break;
960
961         case LFUN_REDO:
962                 if (available()) {
963                         cur.message(_("Redo"));
964                         cur.clearSelection();
965                         if (!textRedo(*bv_))
966                                 cur.message(_("No further redo information"));
967                         update();
968                         switchKeyMap();
969                 }
970                 break;
971
972         case LFUN_FILE_INSERT:
973                 MenuInsertLyXFile(cmd.argument);
974                 break;
975
976         case LFUN_FILE_INSERT_ASCII_PARA:
977                 InsertAsciiFile(bv_, cmd.argument, true);
978                 break;
979
980         case LFUN_FILE_INSERT_ASCII:
981                 InsertAsciiFile(bv_, cmd.argument, false);
982                 break;
983
984         case LFUN_FONT_STATE:
985                 cur.message(cur.currentState());
986                 break;
987
988         case LFUN_INSERT_LABEL: {
989                 // Try and generate a valid label
990                 string const contents = cmd.argument.empty() ?
991                         cur.getPossibleLabel() : cmd.argument;
992                 InsetCommandParams icp("label", contents);
993                 string data = InsetCommandMailer::params2string("label", icp);
994                 owner_->getDialogs().show("label", data, 0);
995                 break;
996         }
997
998         case LFUN_BOOKMARK_SAVE:
999                 savePosition(strToUnsignedInt(cmd.argument));
1000                 break;
1001
1002         case LFUN_BOOKMARK_GOTO:
1003                 restorePosition(strToUnsignedInt(cmd.argument));
1004                 break;
1005
1006         case LFUN_REF_GOTO: {
1007                 string label = cmd.argument;
1008                 if (label.empty()) {
1009                         InsetRef * inset =
1010                                 static_cast<InsetRef*>(getInsetByCode(InsetBase::REF_CODE));
1011                         if (inset) {
1012                                 label = inset->getContents();
1013                                 savePosition(0);
1014                         }
1015                 }
1016
1017                 if (!label.empty())
1018                         bv_->gotoLabel(label);
1019                 break;
1020         }
1021
1022         case LFUN_TRACK_CHANGES:
1023                 trackChanges();
1024                 break;
1025
1026         case LFUN_MERGE_CHANGES:
1027                 owner_->getDialogs().show("changes");
1028                 break;
1029
1030         case LFUN_ACCEPT_ALL_CHANGES: {
1031                 bv_->cursor().reset(bv_->buffer()->inset());
1032 #warning FIXME changes
1033                 while (lyx::find::findNextChange(bv_))
1034                         bv_->getLyXText()->acceptChange(bv_->cursor());
1035                 update();
1036                 break;
1037         }
1038
1039         case LFUN_REJECT_ALL_CHANGES: {
1040                 bv_->cursor().reset(bv_->buffer()->inset());
1041 #warning FIXME changes
1042                 while (lyx::find::findNextChange(bv_))
1043                         bv_->getLyXText()->rejectChange(bv_->cursor());
1044                 update();
1045                 break;
1046         }
1047
1048         case LFUN_WORD_FIND:
1049                 lyx::find::find(bv_, cmd);
1050                 break;
1051
1052         case LFUN_WORD_REPLACE:
1053                 lyx::find::replace(bv_, cmd);
1054                 break;
1055
1056         case LFUN_MARK_OFF:
1057                 cur.clearSelection();
1058                 update();
1059                 cur.resetAnchor();
1060                 cur.message(N_("Mark off"));
1061                 break;
1062
1063         case LFUN_MARK_ON:
1064                 cur.clearSelection();
1065                 cur.mark() = true;
1066                 update();
1067                 cur.resetAnchor();
1068                 cur.message(N_("Mark on"));
1069                 break;
1070
1071         case LFUN_SETMARK:
1072                 cur.clearSelection();
1073                 if (cur.mark()) {
1074                         cur.mark() = false;
1075                         cur.message(N_("Mark removed"));
1076                 } else {
1077                         cur.mark() = true;
1078                         cur.message(N_("Mark set"));
1079                 }
1080                 cur.resetAnchor();
1081                 update();
1082                 break;
1083
1084         case LFUN_UNKNOWN_ACTION:
1085                 cur.errorMessage(N_("Unknown function!"));
1086                 break;
1087
1088         case LFUN_CENTER:
1089                 bv_->center();
1090                 break;
1091
1092         case LFUN_BEGINNINGBUFSEL:
1093                 bv_->cursor().reset(bv_->buffer()->inset());
1094                 if (!cur.selection())
1095                         cur.resetAnchor();
1096                 bv_->text()->cursorTop(cur);
1097                 finishUndo();
1098                 break;
1099
1100         case LFUN_ENDBUFSEL:
1101                 bv_->cursor().reset(bv_->buffer()->inset());
1102                 if (!cur.selection())
1103                         cur.resetAnchor();
1104                 bv_->text()->cursorBottom(cur);
1105                 finishUndo();
1106                 break;
1107
1108         default:
1109                 return false;
1110         }
1111
1112         return true;
1113 }