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