]> git.lyx.org Git - lyx.git/blob - src/BufferView_pimpl.C
98bd903d04472940ee13f80ecd7ea841e92e0328
[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
50 #include "frontends/Alert.h"
51 #include "frontends/Dialogs.h"
52 #include "frontends/FileDialog.h"
53 #include "frontends/LyXView.h"
54 #include "frontends/LyXScreenFactory.h"
55 #include "frontends/screen.h"
56 #include "frontends/WorkArea.h"
57 #include "frontends/WorkAreaFactory.h"
58
59 #include "graphics/Previews.h"
60
61 #include "support/filetools.h"
62 #include "support/globbing.h"
63 #include "support/path_defines.h"
64 #include "support/tostr.h"
65
66 #include <boost/bind.hpp>
67
68 using lyx::pos_type;
69
70 using lyx::support::AddPath;
71 using lyx::support::bformat;
72 using lyx::support::FileFilterList;
73 using lyx::support::FileSearch;
74 using lyx::support::IsDirWriteable;
75 using lyx::support::MakeDisplayPath;
76 using lyx::support::strToUnsignedInt;
77 using lyx::support::system_lyxdir;
78
79 using std::endl;
80 using std::istringstream;
81 using std::make_pair;
82 using std::min;
83 using std::string;
84
85
86 extern BufferList bufferlist;
87
88
89 namespace {
90
91 unsigned int const saved_positions_num = 20;
92
93 // All the below connection objects are needed because of a bug in some
94 // versions of GCC (<=2.96 are on the suspects list.) By having and assigning
95 // to these connections we avoid a segfault upon startup, and also at exit.
96 // (Lgb)
97
98 boost::signals::connection dispatchcon;
99 boost::signals::connection timecon;
100 boost::signals::connection doccon;
101 boost::signals::connection resizecon;
102 boost::signals::connection kpresscon;
103 boost::signals::connection selectioncon;
104 boost::signals::connection lostcon;
105
106
107 } // anon namespace
108
109
110 BufferView::Pimpl::Pimpl(BufferView & bv, LyXView * owner,
111              int xpos, int ypos, int width, int height)
112         : bv_(&bv), owner_(owner), buffer_(0), cursor_timeout(400),
113           using_xterm_cursor(false), cursor_(bv)
114 {
115         xsel_cache_.set = false;
116
117         workarea_.reset(WorkAreaFactory::create(xpos, ypos, width, height));
118         screen_.reset(LyXScreenFactory::create(workarea()));
119
120         // Setup the signals
121         doccon = workarea().scrollDocView
122                 .connect(boost::bind(&BufferView::Pimpl::scrollDocView, this, _1));
123         resizecon = workarea().workAreaResize
124                 .connect(boost::bind(&BufferView::Pimpl::workAreaResize, this));
125         dispatchcon = workarea().dispatch
126                 .connect(boost::bind(&BufferView::Pimpl::workAreaDispatch, this, _1));
127         kpresscon = workarea().workAreaKeyPress
128                 .connect(boost::bind(&BufferView::Pimpl::workAreaKeyPress, this, _1, _2));
129         selectioncon = workarea().selectionRequested
130                 .connect(boost::bind(&BufferView::Pimpl::selectionRequested, this));
131         lostcon = workarea().selectionLost
132                 .connect(boost::bind(&BufferView::Pimpl::selectionLost, this));
133
134         timecon = cursor_timeout.timeout
135                 .connect(boost::bind(&BufferView::Pimpl::cursorToggle, this));
136         cursor_timeout.start();
137         saved_positions.resize(saved_positions_num);
138 }
139
140
141 void BufferView::Pimpl::addError(ErrorItem const & ei)
142 {
143         errorlist_.push_back(ei);
144 }
145
146
147 void BufferView::Pimpl::showReadonly(bool)
148 {
149         owner_->updateWindowTitle();
150         owner_->getDialogs().updateBufferDependent(false);
151 }
152
153
154 void BufferView::Pimpl::connectBuffer(Buffer & buf)
155 {
156         if (errorConnection_.connected())
157                 disconnectBuffer();
158
159         errorConnection_ =
160                 buf.error.connect(boost::bind(&BufferView::Pimpl::addError, this, _1));
161         messageConnection_ =
162                 buf.message.connect(boost::bind(&LyXView::message, owner_, _1));
163         busyConnection_ =
164                 buf.busy.connect(boost::bind(&LyXView::busy, owner_, _1));
165         titleConnection_ =
166                 buf.updateTitles.connect(boost::bind(&LyXView::updateWindowTitle, owner_));
167         timerConnection_ =
168                 buf.resetAutosaveTimers.connect(boost::bind(&LyXView::resetAutosaveTimer, owner_));
169         readonlyConnection_ =
170                 buf.readonly.connect(boost::bind(&BufferView::Pimpl::showReadonly, this, _1));
171         closingConnection_ =
172                 buf.closing.connect(boost::bind(&BufferView::Pimpl::buffer, this, (Buffer *)0));
173 }
174
175
176 void BufferView::Pimpl::disconnectBuffer()
177 {
178         errorConnection_.disconnect();
179         messageConnection_.disconnect();
180         busyConnection_.disconnect();
181         titleConnection_.disconnect();
182         timerConnection_.disconnect();
183         readonlyConnection_.disconnect();
184         closingConnection_.disconnect();
185 }
186
187
188 bool BufferView::Pimpl::newFile(string const & filename,
189                                 string const & tname,
190                                 bool isNamed)
191 {
192         Buffer * b = ::newFile(filename, tname, isNamed);
193         buffer(b);
194         return true;
195 }
196
197
198 bool BufferView::Pimpl::loadLyXFile(string const & filename, bool tolastfiles)
199 {
200         // get absolute path of file and add ".lyx" to the filename if
201         // necessary
202         string s = FileSearch(string(), filename, "lyx");
203
204         bool const found = !s.empty();
205
206         if (!found)
207                 s = filename;
208
209         // file already open?
210         if (bufferlist.exists(s)) {
211                 string const file = MakeDisplayPath(s, 20);
212                 string text = bformat(_("The document %1$s is already "
213                                         "loaded.\n\nDo you want to revert "
214                                         "to the saved version?"), file);
215                 int const ret = Alert::prompt(_("Revert to saved document?"),
216                         text, 0, 1,  _("&Revert"), _("&Switch to document"));
217
218                 if (ret != 0) {
219                         buffer(bufferlist.getBuffer(s));
220                         return true;
221                 } else {
222                         // FIXME: should be LFUN_REVERT
223                         if (!bufferlist.close(bufferlist.getBuffer(s), false))
224                                 return false;
225                         // Fall through to new load. (Asger)
226                 }
227         }
228
229         Buffer * b;
230
231         if (found) {
232                 b = bufferlist.newBuffer(s);
233                 connectBuffer(*b);
234                 if (!::loadLyXFile(b, s)) {
235                         bufferlist.release(b);
236                         return false;
237                 }
238         } else {
239                 string text = bformat(_("The document %1$s does not yet "
240                                         "exist.\n\nDo you want to create "
241                                         "a new document?"), s);
242                 int const ret = Alert::prompt(_("Create new document?"),
243                          text, 0, 1, _("&Create"), _("Cancel"));
244
245                 if (ret == 0)
246                         b = ::newFile(s, string(), true);
247                 else
248                         return false;
249         }
250
251         buffer(b);
252         bv_->showErrorList(_("Parse"));
253
254         if (tolastfiles)
255                 LyX::ref().lastfiles().newFile(b->fileName());
256
257         return true;
258 }
259
260
261 WorkArea & BufferView::Pimpl::workarea() const
262 {
263         return *workarea_.get();
264 }
265
266
267 LyXScreen & BufferView::Pimpl::screen() const
268 {
269         return *screen_.get();
270 }
271
272
273 Painter & BufferView::Pimpl::painter() const
274 {
275         return workarea().getPainter();
276 }
277
278
279 void BufferView::Pimpl::top_y(int y)
280 {
281         top_y_ = y;
282 }
283
284
285 int BufferView::Pimpl::top_y() const
286 {
287         return top_y_;
288 }
289
290
291 void BufferView::Pimpl::buffer(Buffer * b)
292 {
293         lyxerr[Debug::INFO] << "Setting buffer in BufferView ("
294                             << b << ')' << endl;
295         if (buffer_) {
296                 disconnectBuffer();
297                 //delete bv_->text();
298                 //bv_->setText(0);
299         }
300
301         // reset old cursor
302         cursor_.reset();
303
304         // set current buffer
305         buffer_ = b;
306
307         top_y_ = 0;
308
309         // if we're quitting lyx, don't bother updating stuff
310         if (quitting)
311                 return;
312
313         // if we are closing the buffer, use the first buffer as current
314         if (!buffer_)
315                 buffer_ = bufferlist.first();
316
317         if (buffer_) {
318                 lyxerr[Debug::INFO] << "Buffer addr: " << buffer_ << endl;
319                 connectBuffer(*buffer_);
320
321                 buffer_->text().init(bv_);
322
323                 // If we don't have a text object for this, we make one
324                 if (bv_->text() == 0)
325                         resizeCurrentBuffer();
326
327                 // Buffer-dependent dialogs should be updated or
328                 // hidden. This should go here because some dialogs (eg ToC)
329                 // require bv_->text.
330                 owner_->getDialogs().updateBufferDependent(true);
331         } else {
332                 lyxerr[Debug::INFO] << "  No Buffer!" << endl;
333                 owner_->getDialogs().hideBufferDependent();
334         }
335
336         update();
337         updateScrollbar();
338         owner_->updateMenubar();
339         owner_->updateToolbar();
340         owner_->updateLayoutChoice();
341         owner_->updateWindowTitle();
342
343         // Don't forget to update the Layout
344         if (buffer_)
345                 owner_->setLayout(bv_->text()->getPar(0)->layout()->name());
346
347         if (lyx::graphics::Previews::activated() && buffer_)
348                 lyx::graphics::Previews::get().generateBufferPreviews(*buffer_);
349 }
350
351
352 bool BufferView::Pimpl::fitCursor()
353 {
354         if (screen().fitCursor(bv_)) {
355                 updateScrollbar();
356                 return true;
357         }
358         return false;
359 }
360
361
362 void BufferView::Pimpl::redoCurrentBuffer()
363 {
364         lyxerr[Debug::INFO] << "BufferView::redoCurrentBuffer" << endl;
365         if (buffer_ && bv_->text()) {
366                 resizeCurrentBuffer();
367                 updateScrollbar();
368                 owner_->updateLayoutChoice();
369         }
370 }
371
372
373 void BufferView::Pimpl::resizeCurrentBuffer()
374 {
375         lyxerr[Debug::INFO] << "resizeCurrentBuffer" << endl;
376
377         owner_->busy(true);
378
379         owner_->message(_("Formatting document..."));
380
381         LyXText * text = bv_->text();
382         lyxerr << "### resizeCurrentBuffer: text " << text << endl;
383         if (!text)
384                 return;
385
386         // save the cursor mangled in init
387         LCursor cur = bv_->cursor();
388         text->init(bv_);
389         update();
390         bv_->cursor() = cur;
391         bv_->cursor().updatePos();
392         fitCursor();
393
394         switchKeyMap();
395         owner_->busy(false);
396
397         // reset the "Formatting..." message
398         owner_->clearMessage();
399
400         updateScrollbar();
401 }
402
403
404 void BufferView::Pimpl::updateScrollbar()
405 {
406         if (!bv_->text()) {
407                 lyxerr[Debug::GUI] << "no text in updateScrollbar" << endl;
408                 workarea().setScrollbarParams(0, 0, 0);
409                 return;
410         }
411
412         LyXText const & t = *bv_->text();
413
414         lyxerr[Debug::GUI] << "Updating scrollbar: h" << t.height()
415                            << ", top_y()" << top_y() << ", default height "
416                            << defaultRowHeight() << endl;
417
418         workarea().setScrollbarParams(t.height(), top_y(), defaultRowHeight());
419 }
420
421
422 void BufferView::Pimpl::scrollDocView(int value)
423 {
424         lyxerr[Debug::GUI] << "scrollDocView of " << value << endl;
425
426         if (!buffer_)
427                 return;
428
429         screen().hideCursor();
430
431         top_y(value);
432         screen().redraw(*bv_);
433
434         if (!lyxrc.cursor_follows_scrollbar)
435                 return;
436
437         int const height = defaultRowHeight();
438         int const first = top_y() + height;
439         int const last = top_y() + workarea().workHeight() - height;
440
441         bv_->cursor().reset();
442         LyXText * text = bv_->text();
443         CursorSlice & cur = bv_->cursor().front();
444         int y = text->cursorY(cur);
445         if (y < first)
446                 text->setCursorFromCoordinates(bv_->cursor(), 0, first);
447         else if (y > last)
448                 text->setCursorFromCoordinates(bv_->cursor(), 0, last);
449
450         owner_->updateLayoutChoice();
451 }
452
453
454 void BufferView::Pimpl::scroll(int lines)
455 {
456         if (!buffer_)
457                 return;
458
459         LyXText const * t = bv_->text();
460         int const line_height = defaultRowHeight();
461
462         // The new absolute coordinate
463         int new_top_y = top_y() + lines * line_height;
464
465         // Restrict to a valid value
466         new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
467         new_top_y = std::max(0, new_top_y);
468
469         scrollDocView(new_top_y);
470
471         // Update the scrollbar.
472         workarea().setScrollbarParams(t->height(), top_y(), defaultRowHeight());
473 }
474
475
476 void BufferView::Pimpl::workAreaKeyPress(LyXKeySymPtr key,
477                                          key_modifier::state state)
478 {
479         bv_->owner()->getLyXFunc().processKeySym(key, state);
480
481         /* This is perhaps a bit of a hack. When we move
482          * around, or type, it's nice to be able to see
483          * the cursor immediately after the keypress. So
484          * we reset the toggle timeout and force the visibility
485          * of the cursor. Note we cannot do this inside
486          * dispatch() itself, because that's called recursively.
487          */
488         if (available()) {
489                 cursor_timeout.restart();
490                 screen().showCursor(*bv_);
491         }
492 }
493
494
495 void BufferView::Pimpl::selectionRequested()
496 {
497         static string sel;
498
499         if (!available())
500                 return;
501
502         LCursor & cur = bv_->cursor();
503
504         if (!cur.selection()) {
505                 xsel_cache_.set = false;
506                 return;
507         }
508
509         if (!xsel_cache_.set ||
510             cur.back() != xsel_cache_.cursor ||
511             cur.anchor_.back() != xsel_cache_.anchor)
512         {
513                 xsel_cache_.cursor = cur.back();
514                 xsel_cache_.anchor = cur.anchor_.back();
515                 xsel_cache_.set = cur.selection();
516                 sel = cur.selectionAsString(false);
517                 if (!sel.empty())
518                         workarea().putClipboard(sel);
519         } 
520 }
521
522
523 void BufferView::Pimpl::selectionLost()
524 {
525         if (available()) {
526                 screen().hideCursor();
527                 bv_->cursor().clearSelection();
528                 xsel_cache_.set = false;
529         }
530 }
531
532
533 void BufferView::Pimpl::workAreaResize()
534 {
535         static int work_area_width;
536         static int work_area_height;
537
538         bool const widthChange = workarea().workWidth() != work_area_width;
539         bool const heightChange = workarea().workHeight() != work_area_height;
540
541         // update from work area
542         work_area_width = workarea().workWidth();
543         work_area_height = workarea().workHeight();
544
545         if (buffer_ && widthChange) {
546                 // The visible LyXView need a resize
547                 resizeCurrentBuffer();
548         }
549
550         if (widthChange || heightChange)
551                 update();
552
553         // always make sure that the scrollbar is sane.
554         updateScrollbar();
555         owner_->updateLayoutChoice();
556 }
557
558
559 void BufferView::Pimpl::update()
560 {
561         //lyxerr << "BufferView::update()" << endl;
562         // fix cursor coordinate cache in case something went wrong
563
564         // check needed to survive LyX startup
565         if (bv_->getLyXText()) {
566                 // update all 'visible' paragraphs
567                 ParagraphList::iterator beg;
568                 ParagraphList::iterator end;
569                 getParsInRange(buffer_->paragraphs(),
570                                top_y(), top_y() + workarea().workHeight(),
571                                beg, end);
572                 bv_->text()->redoParagraphs(beg, end);
573                 updateScrollbar();
574         }
575         screen().redraw(*bv_);
576         bv_->owner()->view_state_changed();
577 }
578
579
580 // Callback for cursor timer
581 void BufferView::Pimpl::cursorToggle()
582 {
583         if (buffer_)
584                 screen().toggleCursor(*bv_);
585         cursor_timeout.restart();
586 }
587
588
589 bool BufferView::Pimpl::available() const
590 {
591         return buffer_ && bv_->text();
592 }
593
594
595 Change const BufferView::Pimpl::getCurrentChange()
596 {
597         if (!bv_->buffer()->params().tracking_changes)
598                 return Change(Change::UNCHANGED);
599
600         LyXText * text = bv_->getLyXText();
601         LCursor & cur = bv_->cursor();
602
603         if (!cur.selection())
604                 return Change(Change::UNCHANGED);
605
606         return text->getPar(cur.selBegin())
607                 ->lookupChangeFull(cur.selBegin().pos());
608 }
609
610
611 void BufferView::Pimpl::savePosition(unsigned int i)
612 {
613         if (i >= saved_positions_num)
614                 return;
615         saved_positions[i] = Position(buffer_->fileName(),
616                                       bv_->text()->cursorPar()->id(),
617                                       bv_->text()->cursor().pos());
618         if (i > 0)
619                 owner_->message(bformat(_("Saved bookmark %1$s"), tostr(i)));
620 }
621
622
623 void BufferView::Pimpl::restorePosition(unsigned int i)
624 {
625         if (i >= saved_positions_num)
626                 return;
627
628         string const fname = saved_positions[i].filename;
629
630         bv_->cursor().clearSelection();
631
632         if (fname != buffer_->fileName()) {
633                 Buffer * b = 0;
634                 if (bufferlist.exists(fname))
635                         b = bufferlist.getBuffer(fname);
636                 else {
637                         b = bufferlist.newBuffer(fname);
638                         ::loadLyXFile(b, fname); // don't ask, just load it
639                 }
640                 if (b)
641                         buffer(b);
642         }
643
644         ParIterator par = buffer_->getParFromID(saved_positions[i].par_id);
645         if (par == buffer_->par_iterator_end())
646                 return;
647
648         bv_->text()->setCursor(
649                 bv_->cursor(),
650                 bv_->text()->parOffset(par.pit()),
651                 min(par->size(), saved_positions[i].par_pos));
652
653         if (i > 0)
654                 owner_->message(bformat(_("Moved to bookmark %1$s"), tostr(i)));
655 }
656
657
658 bool BufferView::Pimpl::isSavedPosition(unsigned int i)
659 {
660         return i < saved_positions_num && !saved_positions[i].filename.empty();
661 }
662
663
664 void BufferView::Pimpl::switchKeyMap()
665 {
666         if (!lyxrc.rtl_support)
667                 return;
668
669         Intl & intl = owner_->getIntl();
670         if (bv_->getLyXText()->real_current_font.isRightToLeft()) {
671                 if (intl.keymap == Intl::PRIMARY)
672                         intl.KeyMapSec();
673         } else {
674                 if (intl.keymap == Intl::SECONDARY)
675                         intl.KeyMapPrim();
676         }
677 }
678
679
680 void BufferView::Pimpl::center()
681 {
682         LyXText * text = bv_->text();
683
684         bv_->cursor().clearSelection();
685         int const half_height = workarea().workHeight() / 2;
686         int new_y = text->cursorY(bv_->cursor().front()) - half_height;
687         if (new_y < 0)
688                 new_y = 0;
689
690         // FIXME: look at this comment again ...
691         // This updates top_y() but means the fitCursor() call
692         // from the update(FITCUR) doesn't realise that we might
693         // have moved (e.g. from GOTOPARAGRAPH), so doesn't cause
694         // the scrollbar to be updated as it should, so we have
695         // to do it manually. Any operation that does a center()
696         // and also might have moved top_y() must make sure to call
697         // updateScrollbar() currently. Never mind that this is a
698         // pretty obfuscated way of updating text->top_y()
699         top_y(new_y);
700 }
701
702
703 void BufferView::Pimpl::stuffClipboard(string const & stuff) const
704 {
705         workarea().putClipboard(stuff);
706 }
707
708
709 InsetBase * BufferView::Pimpl::getInsetByCode(InsetBase::Code code)
710 {
711 #warning Does not work for mathed
712         // Ok, this is a little bit too brute force but it
713         // should work for now. Better infrastructure is coming. (Lgb)
714
715         Buffer * buf = bv_->buffer();
716         Buffer::inset_iterator beg = buf->inset_iterator_begin();
717         Buffer::inset_iterator end = buf->inset_iterator_end();
718
719         bool cursor_par_seen = false;
720
721         LCursor & cur = bv_->cursor();
722         ParagraphList::iterator pit =  bv_->getLyXText()->getPar(cur.par());
723
724         for (; beg != end; ++beg) {
725                 if (beg.getPar() == pit)
726                         cursor_par_seen = true;
727                 if (cursor_par_seen) {
728                         if (beg.getPar() == pit && beg.getPos() >= cur.pos())
729                                 break;
730                         if (beg.getPar() != pit)
731                                 break;
732                 }
733         }
734         if (beg != end) {
735                 // Now find the first inset that matches code.
736                 for (; beg != end; ++beg) {
737                         if (beg->lyxCode() == code)
738                                 return &(*beg);
739                 }
740         }
741         return 0;
742 }
743
744
745 void BufferView::Pimpl::MenuInsertLyXFile(string const & filenm)
746 {
747         string filename = filenm;
748
749         if (filename.empty()) {
750                 // Launch a file browser
751                 string initpath = lyxrc.document_path;
752
753                 if (available()) {
754                         string const trypath = owner_->buffer()->filePath();
755                         // If directory is writeable, use this as default.
756                         if (IsDirWriteable(trypath))
757                                 initpath = trypath;
758                 }
759
760                 FileDialog fileDlg(_("Select LyX document to insert"),
761                         LFUN_FILE_INSERT,
762                         make_pair(string(_("Documents|#o#O")),
763                                   string(lyxrc.document_path)),
764                         make_pair(string(_("Examples|#E#e")),
765                                   string(AddPath(system_lyxdir(), "examples"))));
766
767                 FileDialog::Result result =
768                         fileDlg.open(initpath,
769                                      FileFilterList(_("LyX Documents (*.lyx)")),
770                                      string());
771
772                 if (result.first == FileDialog::Later)
773                         return;
774
775                 filename = result.second;
776
777                 // check selected filename
778                 if (filename.empty()) {
779                         owner_->message(_("Canceled."));
780                         return;
781                 }
782         }
783
784         // get absolute path of file and add ".lyx" to the filename if
785         // necessary
786         filename = FileSearch(string(), filename, "lyx");
787
788         string const disp_fn = MakeDisplayPath(filename);
789         owner_->message(bformat(_("Inserting document %1$s..."), disp_fn));
790         if (bv_->insertLyXFile(filename))
791                 owner_->message(bformat(_("Document %1$s inserted."),
792                                         disp_fn));
793         else
794                 owner_->message(bformat(_("Could not insert document %1$s"),
795                                         disp_fn));
796 }
797
798
799 void BufferView::Pimpl::trackChanges()
800 {
801         Buffer * buf = bv_->buffer();
802         bool const tracking = buf->params().tracking_changes;
803
804         if (!tracking) {
805                 ParIterator const end = buf->par_iterator_end();
806                 for (ParIterator it = buf->par_iterator_begin(); it != end; ++it)
807                         it->trackChanges();
808                 buf->params().tracking_changes = true;
809
810                 // we cannot allow undos beyond the freeze point
811                 buf->undostack().clear();
812         } else {
813                 update();
814                 bv_->text()->setCursor(bv_->cursor(), 0, 0);
815 #warning changes FIXME
816                 bool found = lyx::find::findNextChange(bv_);
817                 if (found) {
818                         owner_->getDialogs().show("changes");
819                         return;
820                 }
821
822                 ParIterator const end = buf->par_iterator_end();
823                 for (ParIterator it = buf->par_iterator_begin(); it != end; ++it)
824                         it->untrackChanges();
825                 buf->params().tracking_changes = false;
826         }
827
828         buf->redostack().clear();
829 }
830
831
832 bool BufferView::Pimpl::workAreaDispatch(FuncRequest const & cmd0)
833 {
834         //
835         // this is only called for mouse related events (including
836         // LFUN_FILE_OPEN generated by drag-and-drop)
837         //
838         FuncRequest cmd = cmd0;
839         cmd.y += bv_->top_y();
840         //lyxerr << "*** workAreaDispatch: request: " << cmd << std::endl;
841         LCursor cur(*bv_);
842         cur.selection() = bv_->cursor().selection();
843         switch (cmd.action) {
844
845 #if 0
846         case LFUN_MOUSE_MOTION: {
847                 if (!available())
848                         return false;
849                 FuncRequest cmd1 = cmd;
850                 InsetBase * inset = cur.inset();
851                 DispatchResult res;
852                 if (inset) {
853                         res = inset->dispatch(cur, cmd);
854                 } else {
855                         res = bv_->text()->dispatch(cur, cmd);
856                 }
857
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: request: " << 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();
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();
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         default:
1093                 return false;
1094         }
1095
1096         return true;
1097 }