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