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