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