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