]> git.lyx.org Git - lyx.git/blob - src/BufferView_pimpl.C
change "support/std_sstream.h" to <sstream>
[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 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(*owner_, 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         } else {
342                 lyxerr[Debug::INFO] << "  No Buffer!" << endl;
343                 // we are closing the buffer, use the first buffer as current
344                 buffer_ = bufferlist.first();
345                 owner_->getDialogs().hideBufferDependent();
346         }
347
348         update();
349         updateScrollbar();
350         owner_->updateMenubar();
351         owner_->updateToolbars();
352         owner_->updateLayoutChoice();
353         owner_->updateWindowTitle();
354
355         // This is done after the layout combox has been populated
356         if (buffer_)
357                 owner_->setLayout(cursor_.paragraph().layout()->name());
358                 
359
360         if (buffer_ && lyx::graphics::Previews::status() != LyXRC::PREVIEW_OFF)
361                 lyx::graphics::Previews::get().generateBufferPreviews(*buffer_);
362 }
363
364
365 bool BufferView::Pimpl::fitCursor()
366 {
367         // to get the correct y cursor info
368         lyxerr[Debug::DEBUG] << "BufferView::fitCursor" << std::endl;
369         lyx::par_type const pit = bv_->cursor().bottom().par();
370         bv_->text()->redoParagraph(pit);
371         refreshPar(*bv_, *bv_->text(), pit);
372
373         if (!screen().fitCursor(bv_))
374                 return false;
375         updateScrollbar();
376         return true;
377 }
378
379
380 void BufferView::Pimpl::redoCurrentBuffer()
381 {
382         lyxerr[Debug::DEBUG] << "BufferView::redoCurrentBuffer" << endl;
383         if (buffer_ && bv_->text()) {
384                 resizeCurrentBuffer();
385                 updateScrollbar();
386                 owner_->updateLayoutChoice();
387         }
388 }
389
390
391 void BufferView::Pimpl::resizeCurrentBuffer()
392 {
393         lyxerr[Debug::DEBUG] << "resizeCurrentBuffer" << endl;
394         owner_->busy(true);
395         owner_->message(_("Formatting document..."));
396
397         LyXText * text = bv_->text();
398         if (!text)
399                 return;
400
401         text->init(bv_);
402         update();
403         fitCursor();
404
405         switchKeyMap();
406         owner_->busy(false);
407
408         // reset the "Formatting..." message
409         owner_->clearMessage();
410
411         updateScrollbar();
412 }
413
414
415 void BufferView::Pimpl::updateScrollbar()
416 {
417         if (!bv_->text()) {
418                 lyxerr[Debug::DEBUG] << "no text in updateScrollbar" << endl;
419                 workarea().setScrollbarParams(0, 0, 0);
420                 return;
421         }
422
423         LyXText const & t = *bv_->text();
424
425         lyxerr[Debug::GUI]
426                 << "Updating scrollbar: height: " << t.height()
427                 << " top_y: " << top_y()
428                 << " default height " << defaultRowHeight() << endl;
429
430         workarea().setScrollbarParams(t.height(), top_y(), defaultRowHeight());
431 }
432
433
434 void BufferView::Pimpl::scrollDocView(int value)
435 {
436         lyxerr[Debug::GUI] << "scrollDocView of " << value << endl;
437
438         if (!buffer_)
439                 return;
440
441         screen().hideCursor();
442
443         top_y(value);
444         screen().redraw(*bv_);
445
446         if (!lyxrc.cursor_follows_scrollbar)
447                 return;
448
449         int const height = defaultRowHeight();
450         int const first = top_y() + height;
451         int const last = top_y() + workarea().workHeight() - height;
452
453         bv_->cursor().reset(bv_->buffer()->inset());
454         LyXText * text = bv_->text();
455         int y = text->cursorY(bv_->cursor().front());
456         if (y < first)
457                 y = first;
458         if (y > last)
459                 y = last;
460         text->setCursorFromCoordinates(bv_->cursor(), 0, y);
461
462         owner_->updateLayoutChoice();
463 }
464
465
466 void BufferView::Pimpl::scroll(int lines)
467 {
468         if (!buffer_)
469                 return;
470
471         LyXText const * t = bv_->text();
472         int const line_height = defaultRowHeight();
473
474         // The new absolute coordinate
475         int new_top_y = top_y() + lines * line_height;
476
477         // Restrict to a valid value
478         new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
479         new_top_y = std::max(0, new_top_y);
480
481         scrollDocView(new_top_y);
482
483         // Update the scrollbar.
484         workarea().setScrollbarParams(t->height(), top_y(), defaultRowHeight());
485 }
486
487
488 void BufferView::Pimpl::workAreaKeyPress(LyXKeySymPtr key,
489                                          key_modifier::state state)
490 {
491         bv_->owner()->getLyXFunc().processKeySym(key, state);
492
493         /* This is perhaps a bit of a hack. When we move
494          * around, or type, it's nice to be able to see
495          * the cursor immediately after the keypress. So
496          * we reset the toggle timeout and force the visibility
497          * of the cursor. Note we cannot do this inside
498          * dispatch() itself, because that's called recursively.
499          */
500         if (available()) {
501                 cursor_timeout.restart();
502                 screen().showCursor(*bv_);
503         }
504 }
505
506
507 void BufferView::Pimpl::selectionRequested()
508 {
509         static string sel;
510
511         if (!available())
512                 return;
513
514         LCursor & cur = bv_->cursor();
515
516         if (!cur.selection()) {
517                 xsel_cache_.set = false;
518                 return;
519         }
520
521         if (!xsel_cache_.set ||
522             cur.back() != xsel_cache_.cursor ||
523             cur.anchor_.back() != xsel_cache_.anchor)
524         {
525                 xsel_cache_.cursor = cur.back();
526                 xsel_cache_.anchor = cur.anchor_.back();
527                 xsel_cache_.set = cur.selection();
528                 sel = cur.selectionAsString(false);
529                 if (!sel.empty())
530                         workarea().putClipboard(sel);
531         }
532 }
533
534
535 void BufferView::Pimpl::selectionLost()
536 {
537         if (available()) {
538                 screen().hideCursor();
539                 bv_->cursor().clearSelection();
540                 xsel_cache_.set = false;
541         }
542 }
543
544
545 void BufferView::Pimpl::workAreaResize()
546 {
547         static int work_area_width;
548         static int work_area_height;
549
550         bool const widthChange = workarea().workWidth() != work_area_width;
551         bool const heightChange = workarea().workHeight() != work_area_height;
552
553         // update from work area
554         work_area_width = workarea().workWidth();
555         work_area_height = workarea().workHeight();
556
557         if (buffer_ && widthChange) {
558                 // The visible LyXView need a resize
559                 resizeCurrentBuffer();
560         }
561
562         if (widthChange || heightChange)
563                 update();
564
565         // always make sure that the scrollbar is sane.
566         updateScrollbar();
567         owner_->updateLayoutChoice();
568 }
569
570
571 void BufferView::Pimpl::update()
572 {
573         //lyxerr << "BufferView::Pimpl::update(), buffer: " << buffer_ << endl;
574         // fix cursor coordinate cache in case something went wrong
575
576         // check needed to survive LyX startup
577         if (buffer_) {
578                 // update macro store
579                 buffer_->buildMacros();
580
581                 // update all 'visible' paragraphs
582                 lyx::par_type beg, end;
583                 getParsInRange(buffer_->paragraphs(),
584                                top_y(), top_y() + workarea().workHeight(),
585                                beg, end);
586                 bv_->text()->redoParagraphs(beg, end);
587
588                 // and the scrollbar
589                 updateScrollbar();
590         }
591         screen().redraw(*bv_);
592         bv_->owner()->view_state_changed();
593 }
594
595
596 // Callback for cursor timer
597 void BufferView::Pimpl::cursorToggle()
598 {
599         if (buffer_) {
600                 screen().toggleCursor(*bv_);
601
602                 // Use this opportunity to deal with any child processes that
603                 // have finished but are waiting to communicate this fact
604                 // to the rest of LyX.
605                 ForkedcallsController & fcc = ForkedcallsController::get();
606                 if (fcc.processesCompleted())
607                         fcc.handleCompletedProcesses();
608         }
609
610         cursor_timeout.restart();
611 }
612
613
614 bool BufferView::Pimpl::available() const
615 {
616         return buffer_ && bv_->text();
617 }
618
619
620 Change const BufferView::Pimpl::getCurrentChange()
621 {
622         if (!bv_->buffer()->params().tracking_changes)
623                 return Change(Change::UNCHANGED);
624
625         LyXText * text = bv_->getLyXText();
626         LCursor & cur = bv_->cursor();
627
628         if (!cur.selection())
629                 return Change(Change::UNCHANGED);
630
631         return text->getPar(cur.selBegin().par()).
632                         lookupChangeFull(cur.selBegin().pos());
633 }
634
635
636 void BufferView::Pimpl::savePosition(unsigned int i)
637 {
638         if (i >= saved_positions_num)
639                 return;
640         BOOST_ASSERT(bv_->cursor().inTexted());
641         saved_positions[i] = Position(buffer_->fileName(),
642                                       bv_->cursor().paragraph().id(),
643                                       bv_->cursor().pos());
644         if (i > 0)
645                 owner_->message(bformat(_("Saved bookmark %1$s"), tostr(i)));
646 }
647
648
649 void BufferView::Pimpl::restorePosition(unsigned int i)
650 {
651         if (i >= saved_positions_num)
652                 return;
653
654         string const fname = saved_positions[i].filename;
655
656         bv_->cursor().clearSelection();
657
658         if (fname != buffer_->fileName()) {
659                 Buffer * b = 0;
660                 if (bufferlist.exists(fname))
661                         b = bufferlist.getBuffer(fname);
662                 else {
663                         b = bufferlist.newBuffer(fname);
664                         ::loadLyXFile(b, fname); // don't ask, just load it
665                 }
666                 if (b)
667                         setBuffer(b);
668         }
669
670         ParIterator par = buffer_->getParFromID(saved_positions[i].par_id);
671         if (par == buffer_->par_iterator_end())
672                 return;
673
674         bv_->text()->setCursor(bv_->cursor(), par.pit(),
675                 min(par->size(), saved_positions[i].par_pos));
676
677         if (i > 0)
678                 owner_->message(bformat(_("Moved to bookmark %1$s"), tostr(i)));
679 }
680
681
682 bool BufferView::Pimpl::isSavedPosition(unsigned int i)
683 {
684         return i < saved_positions_num && !saved_positions[i].filename.empty();
685 }
686
687
688 void BufferView::Pimpl::switchKeyMap()
689 {
690         if (!lyxrc.rtl_support)
691                 return;
692
693         Intl & intl = owner_->getIntl();
694         if (bv_->getLyXText()->real_current_font.isRightToLeft()) {
695                 if (intl.keymap == Intl::PRIMARY)
696                         intl.KeyMapSec();
697         } else {
698                 if (intl.keymap == Intl::SECONDARY)
699                         intl.KeyMapPrim();
700         }
701 }
702
703
704 void BufferView::Pimpl::center()
705 {
706         LyXText * text = bv_->text();
707
708         bv_->cursor().clearSelection();
709         int const half_height = workarea().workHeight() / 2;
710         int new_y = text->cursorY(bv_->cursor().front()) - half_height;
711         if (new_y < 0)
712                 new_y = 0;
713
714         // FIXME: look at this comment again ...
715         // This updates top_y() but means the fitCursor() call
716         // from the update(FITCUR) doesn't realise that we might
717         // have moved (e.g. from GOTOPARAGRAPH), so doesn't cause
718         // the scrollbar to be updated as it should, so we have
719         // to do it manually. Any operation that does a center()
720         // and also might have moved top_y() must make sure to call
721         // updateScrollbar() currently. Never mind that this is a
722         // pretty obfuscated way of updating text->top_y()
723         top_y(new_y);
724 }
725
726
727 void BufferView::Pimpl::stuffClipboard(string const & stuff) const
728 {
729         workarea().putClipboard(stuff);
730 }
731
732
733 InsetBase * BufferView::Pimpl::getInsetByCode(InsetBase::Code code)
734 {
735 #ifdef WITH_WARNINGS
736 #warning Does not work for mathed. (Still true?)
737 #endif
738         // Ok, this is a little bit too brute force but it
739         // should work for now. Better infrastructure is coming. (Lgb)
740         LCursor & cur = bv_->cursor();
741         DocIterator it = cur;
742         for (it.forwardInset(); it; it.forwardInset()) {
743                 BOOST_ASSERT(it.nextInset());
744                 if (it.nextInset()->lyxCode() == code)
745                                 return it.nextInset();
746         }
747         return 0;
748 }
749
750
751 void BufferView::Pimpl::MenuInsertLyXFile(string const & filenm)
752 {
753         string filename = filenm;
754
755         if (filename.empty()) {
756                 // Launch a file browser
757                 string initpath = lyxrc.document_path;
758
759                 if (available()) {
760                         string const trypath = owner_->buffer()->filePath();
761                         // If directory is writeable, use this as default.
762                         if (IsDirWriteable(trypath))
763                                 initpath = trypath;
764                 }
765
766                 FileDialog fileDlg(_("Select LyX document to insert"),
767                         LFUN_FILE_INSERT,
768                         make_pair(string(_("Documents|#o#O")),
769                                   string(lyxrc.document_path)),
770                         make_pair(string(_("Examples|#E#e")),
771                                   string(AddPath(system_lyxdir(), "examples"))));
772
773                 FileDialog::Result result =
774                         fileDlg.open(initpath,
775                                      FileFilterList(_("LyX Documents (*.lyx)")),
776                                      string());
777
778                 if (result.first == FileDialog::Later)
779                         return;
780
781                 filename = result.second;
782
783                 // check selected filename
784                 if (filename.empty()) {
785                         owner_->message(_("Canceled."));
786                         return;
787                 }
788         }
789
790         // get absolute path of file and add ".lyx" to the filename if
791         // necessary
792         filename = FileSearch(string(), filename, "lyx");
793
794         string const disp_fn = MakeDisplayPath(filename);
795         owner_->message(bformat(_("Inserting document %1$s..."), disp_fn));
796         if (bv_->insertLyXFile(filename))
797                 owner_->message(bformat(_("Document %1$s inserted."),
798                                         disp_fn));
799         else
800                 owner_->message(bformat(_("Could not insert document %1$s"),
801                                         disp_fn));
802 }
803
804
805 void BufferView::Pimpl::trackChanges()
806 {
807         Buffer * buf = bv_->buffer();
808         bool const tracking = buf->params().tracking_changes;
809
810         if (!tracking) {
811                 ParIterator const end = buf->par_iterator_end();
812                 for (ParIterator it = buf->par_iterator_begin(); it != end; ++it)
813                         it->trackChanges();
814                 buf->params().tracking_changes = true;
815
816                 // we cannot allow undos beyond the freeze point
817                 buf->undostack().clear();
818         } else {
819                 update();
820                 bv_->text()->setCursor(bv_->cursor(), 0, 0);
821 #ifdef WITH_WARNINGS
822 #warning changes FIXME
823 #endif
824                 bool found = lyx::find::findNextChange(bv_);
825                 if (found) {
826                         owner_->getDialogs().show("changes");
827                         return;
828                 }
829
830                 ParIterator const end = buf->par_iterator_end();
831                 for (ParIterator it = buf->par_iterator_begin(); it != end; ++it)
832                         it->untrackChanges();
833                 buf->params().tracking_changes = false;
834         }
835
836         buf->redostack().clear();
837 }
838
839
840 bool BufferView::Pimpl::workAreaDispatch(FuncRequest const & cmd0)
841 {
842         //lyxerr << "BufferView::Pimpl::workAreaDispatch: request: "
843         //  << cmd << std::endl;
844         // this is only called for mouse related events including
845         // LFUN_FILE_OPEN generated by drag-and-drop.
846         FuncRequest cmd = cmd0;
847
848         // handle drag&drop
849         if (cmd.action == LFUN_FILE_OPEN) {
850                 owner_->dispatch(cmd);
851                 return true;
852         }
853
854         cmd.y += bv_->top_y();
855         if (!bv_->buffer())
856                 return false;
857
858         LCursor cur(*bv_);
859         cur.push(bv_->buffer()->inset());
860         cur.selection() = bv_->cursor().selection();
861
862         // Doesn't go through lyxfunc, so we need to update
863         // the layout choice etc. ourselves
864
865         // e.g. Qt mouse press when no buffer
866         if (!available())
867                 return false;
868
869         screen().hideCursor();
870
871         // Either the inset under the cursor or the
872         // surrounding LyXText will handle this event.
873
874         // Build temporary cursor.
875         InsetBase * inset = bv_->text()->editXY(cur, cmd.x, cmd.y);
876         lyxerr << "hit inset at tip: " << inset << endl;
877         lyxerr << "created temp cursor:\n" << cur << endl;
878
879         // Put anchor at the same position.
880         cur.resetAnchor();
881
882         // Try to dispatch to an non-editable inset near this position
883         // via the temp cursor. If the inset wishes to change the real
884         // cursor it has to do so explicitly by using
885         //  cur.bv().cursor() = cur;  (or similar)'
886         DispatchResult res;
887         if (inset)
888                 inset->dispatch(cur, cmd);
889
890         // Now dispatch to the temporary cursor. If the real cursor should
891         // be modified, the inset's dispatch has to do so explicitly.
892         if (!res.dispatched())
893                 res = cur.dispatch(cmd);
894
895         if (res.dispatched()) {
896                 // Redraw if requested or necessary.
897                 if (fitCursor() || res.update())
898                         update();
899         }
900
901         // see workAreaKeyPress
902         cursor_timeout.restart();
903         screen().showCursor(*bv_);
904
905         // skip these when selecting
906         if (cmd.action != LFUN_MOUSE_MOTION) {
907                 owner_->updateLayoutChoice();
908                 owner_->updateToolbars();
909         }
910
911         // slight hack: this is only called currently when we
912         // clicked somewhere, so we force through the display
913         // of the new status here.
914         owner_->clearMessage();
915         return true;
916 }
917
918
919 FuncStatus BufferView::Pimpl::getStatus(FuncRequest const & cmd)
920 {
921         Buffer * buf = bv_->buffer();
922
923         FuncStatus flag;
924
925         switch (cmd.action) {
926
927         case LFUN_UNDO:
928                 flag.enabled(!buf->undostack().empty());
929                 break;
930         case LFUN_REDO:
931                 flag.enabled(!buf->redostack().empty());
932                 break;
933         case LFUN_FILE_INSERT:
934         case LFUN_FILE_INSERT_ASCII_PARA:
935         case LFUN_FILE_INSERT_ASCII:
936         case LFUN_FONT_STATE:
937         case LFUN_INSERT_LABEL:
938         case LFUN_BOOKMARK_SAVE:
939         case LFUN_REF_GOTO:
940         case LFUN_WORD_FIND:
941         case LFUN_WORD_REPLACE:
942         case LFUN_MARK_OFF:
943         case LFUN_MARK_ON:
944         case LFUN_SETMARK:
945         case LFUN_CENTER:
946         case LFUN_BEGINNINGBUFSEL:
947         case LFUN_ENDBUFSEL:
948                 flag.enabled(true);
949                 break;
950         case LFUN_BOOKMARK_GOTO:
951                 flag.enabled(bv_->isSavedPosition(strToUnsignedInt(cmd.argument)));
952                 break;
953         case LFUN_TRACK_CHANGES:
954                 flag.enabled(true);
955                 flag.setOnOff(buf->params().tracking_changes);
956                 break;
957
958         case LFUN_MERGE_CHANGES:
959         case LFUN_ACCEPT_CHANGE: // what about these two
960         case LFUN_REJECT_CHANGE: // what about these two
961         case LFUN_ACCEPT_ALL_CHANGES:
962         case LFUN_REJECT_ALL_CHANGES:
963                 flag.enabled(buf && buf->params().tracking_changes);
964                 break;
965         default:
966                 flag.enabled(false);
967         }
968
969         return flag;
970 }
971
972
973
974 bool BufferView::Pimpl::dispatch(FuncRequest const & cmd)
975 {
976         //lyxerr << "BufferView::Pimpl::dispatch  cmd: " << cmd << std::endl;
977         // Make sure that the cached BufferView is correct.
978         lyxerr[Debug::ACTION] << "BufferView::Pimpl::Dispatch:"
979                 << " action[" << cmd.action << ']'
980                 << " arg[" << cmd.argument << ']'
981                 << " x[" << cmd.x << ']'
982                 << " y[" << cmd.y << ']'
983                 << " button[" << cmd.button() << ']'
984                 << endl;
985
986         LCursor & cur = bv_->cursor();
987
988         switch (cmd.action) {
989
990         case LFUN_UNDO:
991                 if (available()) {
992                         cur.message(_("Undo"));
993                         cur.clearSelection();
994                         if (!textUndo(*bv_))
995                                 cur.message(_("No further undo information"));
996                         update();
997                         switchKeyMap();
998                 }
999                 break;
1000
1001         case LFUN_REDO:
1002                 if (available()) {
1003                         cur.message(_("Redo"));
1004                         cur.clearSelection();
1005                         if (!textRedo(*bv_))
1006                                 cur.message(_("No further redo information"));
1007                         update();
1008                         switchKeyMap();
1009                 }
1010                 break;
1011
1012         case LFUN_FILE_INSERT:
1013                 MenuInsertLyXFile(cmd.argument);
1014                 break;
1015
1016         case LFUN_FILE_INSERT_ASCII_PARA:
1017                 InsertAsciiFile(bv_, cmd.argument, true);
1018                 break;
1019
1020         case LFUN_FILE_INSERT_ASCII:
1021                 InsertAsciiFile(bv_, cmd.argument, false);
1022                 break;
1023
1024         case LFUN_FONT_STATE:
1025                 cur.message(cur.currentState());
1026                 break;
1027
1028         case LFUN_BOOKMARK_SAVE:
1029                 savePosition(strToUnsignedInt(cmd.argument));
1030                 break;
1031
1032         case LFUN_BOOKMARK_GOTO:
1033                 restorePosition(strToUnsignedInt(cmd.argument));
1034                 break;
1035
1036         case LFUN_REF_GOTO: {
1037                 string label = cmd.argument;
1038                 if (label.empty()) {
1039                         InsetRef * inset =
1040                                 static_cast<InsetRef*>(getInsetByCode(InsetBase::REF_CODE));
1041                         if (inset) {
1042                                 label = inset->getContents();
1043                                 savePosition(0);
1044                         }
1045                 }
1046
1047                 if (!label.empty())
1048                         bv_->gotoLabel(label);
1049                 break;
1050         }
1051
1052         case LFUN_TRACK_CHANGES:
1053                 trackChanges();
1054                 break;
1055
1056         case LFUN_MERGE_CHANGES:
1057                 owner_->getDialogs().show("changes");
1058                 break;
1059
1060         case LFUN_ACCEPT_ALL_CHANGES: {
1061                 bv_->cursor().reset(bv_->buffer()->inset());
1062 #ifdef WITH_WARNINGS
1063 #warning FIXME changes
1064 #endif
1065                 while (lyx::find::findNextChange(bv_))
1066                         bv_->getLyXText()->acceptChange(bv_->cursor());
1067                 update();
1068                 break;
1069         }
1070
1071         case LFUN_REJECT_ALL_CHANGES: {
1072                 bv_->cursor().reset(bv_->buffer()->inset());
1073 #ifdef WITH_WARNINGS
1074 #warning FIXME changes
1075 #endif
1076                 while (lyx::find::findNextChange(bv_))
1077                         bv_->getLyXText()->rejectChange(bv_->cursor());
1078                 break;
1079         }
1080
1081         case LFUN_WORD_FIND:
1082                 lyx::find::find(bv_, cmd);
1083                 break;
1084
1085         case LFUN_WORD_REPLACE:
1086                 lyx::find::replace(bv_, cmd);
1087                 break;
1088
1089         case LFUN_MARK_OFF:
1090                 cur.clearSelection();
1091                 cur.resetAnchor();
1092                 cur.message(N_("Mark off"));
1093                 break;
1094
1095         case LFUN_MARK_ON:
1096                 cur.clearSelection();
1097                 cur.mark() = true;
1098                 cur.resetAnchor();
1099                 cur.message(N_("Mark on"));
1100                 break;
1101
1102         case LFUN_SETMARK:
1103                 cur.clearSelection();
1104                 if (cur.mark()) {
1105                         cur.mark() = false;
1106                         cur.message(N_("Mark removed"));
1107                 } else {
1108                         cur.mark() = true;
1109                         cur.message(N_("Mark set"));
1110                 }
1111                 cur.resetAnchor();
1112                 break;
1113
1114         case LFUN_CENTER:
1115                 bv_->center();
1116                 break;
1117
1118         case LFUN_BEGINNINGBUFSEL:
1119                 bv_->cursor().reset(bv_->buffer()->inset());
1120                 if (!cur.selection())
1121                         cur.resetAnchor();
1122                 bv_->text()->cursorTop(cur);
1123                 finishUndo();
1124                 break;
1125
1126         case LFUN_ENDBUFSEL:
1127                 bv_->cursor().reset(bv_->buffer()->inset());
1128                 if (!cur.selection())
1129                         cur.resetAnchor();
1130                 bv_->text()->cursorBottom(cur);
1131                 finishUndo();
1132                 break;
1133
1134         default:
1135                 return false;
1136         }
1137
1138         return true;
1139 }