]> git.lyx.org Git - lyx.git/blob - src/BufferView_pimpl.C
re-enable bv::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         lyxerr << "BufferView::Pimpl::fitCursor." << endl;
359         if (screen().fitCursor(bv_)) {
360                 updateScrollbar();
361                 return true;
362         }
363         return false;
364 }
365
366
367 void BufferView::Pimpl::redoCurrentBuffer()
368 {
369         lyxerr[Debug::INFO] << "BufferView::redoCurrentBuffer" << endl;
370         if (buffer_ && bv_->text()) {
371                 resizeCurrentBuffer();
372                 updateScrollbar();
373                 owner_->updateLayoutChoice();
374         }
375 }
376
377
378 void BufferView::Pimpl::resizeCurrentBuffer()
379 {
380         lyxerr[Debug::INFO] << "resizeCurrentBuffer" << endl;
381
382         int par = -1;
383         int selstartpar = -1;
384         int selendpar = -1;
385
386         pos_type pos = 0;
387         pos_type selstartpos = 0;
388         pos_type selendpos = 0;
389         bool sel = false;
390         bool mark_set  = false;
391
392         owner_->busy(true);
393
394         owner_->message(_("Formatting document..."));
395
396         LyXText * text = bv_->text();
397         lyxerr << "### resizeCurrentBuffer: text " << text << endl;
398         if (!text)
399                 return;
400
401         LCursor & cur = bv_->cursor();
402         par = cur.par();
403         pos = cur.pos();
404         selstartpar = cur.selBegin().par();
405         selstartpos = cur.selBegin().pos();
406         selendpar = cur.selEnd().par();
407         selendpos = cur.selEnd().pos();
408         sel = cur.selection();
409         mark_set = cur.mark();
410         text->textwidth_ = bv_->workWidth();
411         text->fullRebreak();
412         update();
413
414         if (par != -1) {
415                 cur.selection() = true;
416                 // At this point just to avoid the Delete-Empty-Paragraph-
417                 // Mechanism when setting the cursor.
418                 cur.mark() = mark_set;
419                 if (sel) {
420                         text->setCursor(selstartpar, selstartpos);
421                         cur.resetAnchor();
422                         text->setCursor(selendpar, selendpos);
423                         cur.setSelection();
424                         text->setCursor(par, pos);
425                 } else {
426                         text->setCursor(par, pos);
427                         cur.resetAnchor();
428                         cur.selection() = false;
429                 }
430         }
431
432         fitCursor();
433
434         switchKeyMap();
435         owner_->busy(false);
436
437         // reset the "Formatting..." message
438         owner_->clearMessage();
439
440         updateScrollbar();
441 }
442
443
444 void BufferView::Pimpl::updateScrollbar()
445 {
446         if (!bv_->text()) {
447                 lyxerr[Debug::GUI] << "no text in updateScrollbar" << endl;
448                 workarea().setScrollbarParams(0, 0, 0);
449                 return;
450         }
451
452         LyXText const & t = *bv_->text();
453
454         lyxerr[Debug::GUI] << "Updating scrollbar: h " << t.height << ", top_y() "
455                 << top_y() << ", default height " << defaultRowHeight() << endl;
456
457         workarea().setScrollbarParams(t.height, top_y(), defaultRowHeight());
458 }
459
460
461 void BufferView::Pimpl::scrollDocView(int value)
462 {
463         lyxerr[Debug::GUI] << "scrollDocView of " << value << endl;
464
465         if (!buffer_)
466                 return;
467
468         screen().hideCursor();
469
470         top_y(value);
471         screen().redraw(*bv_);
472
473         if (!lyxrc.cursor_follows_scrollbar)
474                 return;
475
476         int const height = defaultRowHeight();
477         int const first = top_y() + height;
478         int const last = top_y() + workarea().workHeight() - height;
479
480         LyXText * text = bv_->text();
481         int y = text->cursorY(bv_->cursor().cursor_.front());
482         if (y < first)
483                 text->setCursorFromCoordinates(0, first);
484         else if (y > last)
485                 text->setCursorFromCoordinates(0, last);
486
487         owner_->updateLayoutChoice();
488 }
489
490
491 void BufferView::Pimpl::scroll(int lines)
492 {
493         if (!buffer_)
494                 return;
495
496         LyXText const * t = bv_->text();
497         int const line_height = defaultRowHeight();
498
499         // The new absolute coordinate
500         int new_top_y = top_y() + lines * line_height;
501
502         // Restrict to a valid value
503         new_top_y = std::min(t->height - 4 * line_height, new_top_y);
504         new_top_y = std::max(0, new_top_y);
505
506         scrollDocView(new_top_y);
507
508         // Update the scrollbar.
509         workarea().setScrollbarParams(t->height, top_y(), defaultRowHeight());
510 }
511
512
513 void BufferView::Pimpl::workAreaKeyPress(LyXKeySymPtr key,
514                                          key_modifier::state state)
515 {
516         bv_->owner()->getLyXFunc().processKeySym(key, state);
517
518         /* This is perhaps a bit of a hack. When we move
519          * around, or type, it's nice to be able to see
520          * the cursor immediately after the keypress. So
521          * we reset the toggle timeout and force the visibility
522          * of the cursor. Note we cannot do this inside
523          * dispatch() itself, because that's called recursively.
524          */
525         if (available()) {
526                 cursor_timeout.restart();
527                 screen().showCursor(*bv_);
528         }
529 }
530
531
532 void BufferView::Pimpl::selectionRequested()
533 {
534         static string sel;
535
536         if (!available())
537                 return;
538
539         LCursor & cur = bv_->cursor();
540
541         if (!cur.selection()) {
542                 xsel_cache_.set = false;
543                 return;
544         }
545
546         if (!xsel_cache_.set ||
547             cur.cursor_.back() != xsel_cache_.cursor ||
548             cur.anchor_.back() != xsel_cache_.anchor)
549         {
550                 xsel_cache_.cursor = cur.cursor_.back();
551                 xsel_cache_.anchor = cur.anchor_.back();
552                 xsel_cache_.set = cur.selection();
553                 sel = bv_->getLyXText()->selectionAsString(*bv_->buffer(), false);
554                 if (!sel.empty())
555                         workarea().putClipboard(sel);
556         } 
557 }
558
559
560 void BufferView::Pimpl::selectionLost()
561 {
562         if (available()) {
563                 screen().hideCursor();
564                 bv_->cursor().clearSelection();
565                 xsel_cache_.set = false;
566         }
567 }
568
569
570 void BufferView::Pimpl::workAreaResize()
571 {
572         static int work_area_width;
573         static int work_area_height;
574
575         bool const widthChange = workarea().workWidth() != work_area_width;
576         bool const heightChange = workarea().workHeight() != work_area_height;
577
578         // update from work area
579         work_area_width = workarea().workWidth();
580         work_area_height = workarea().workHeight();
581
582         if (buffer_ != 0) {
583                 if (widthChange) {
584                         // The visible LyXView need a resize
585                         resizeCurrentBuffer();
586                 }
587         }
588
589         if (widthChange || heightChange)
590                 update();
591
592         // always make sure that the scrollbar is sane.
593         updateScrollbar();
594         owner_->updateLayoutChoice();
595 }
596
597
598 void BufferView::Pimpl::update()
599 {
600         //lyxerr << "BufferView::update()" << endl;
601         // fix cursor coordinate cache in case something went wrong
602
603         // check needed to survive LyX startup
604         if (bv_->getLyXText()) {
605                 // update all 'visible' paragraphs
606                 ParagraphList::iterator beg;
607                 ParagraphList::iterator end;
608                 getParsInRange(buffer_->paragraphs(),
609                                top_y(), top_y() + workarea().workHeight(),
610                                beg, end);
611                 bv_->text()->redoParagraphs(beg, end);
612                 updateScrollbar();
613         }
614         screen().redraw(*bv_);
615 }
616
617
618 // Callback for cursor timer
619 void BufferView::Pimpl::cursorToggle()
620 {
621         if (!buffer_) {
622                 cursor_timeout.restart();
623                 return;
624         }
625
626         screen().toggleCursor(*bv_);
627         cursor_timeout.restart();
628 }
629
630
631 bool BufferView::Pimpl::available() const
632 {
633         return buffer_ && bv_->text();
634 }
635
636
637 Change const BufferView::Pimpl::getCurrentChange()
638 {
639         if (!bv_->buffer()->params().tracking_changes)
640                 return Change(Change::UNCHANGED);
641
642         LyXText * text = bv_->getLyXText();
643         LCursor & cur = bv_->cursor();
644
645         if (!cur.selection())
646                 return Change(Change::UNCHANGED);
647
648         return text->getPar(cur.selBegin())
649                 ->lookupChangeFull(cur.selBegin().pos());
650 }
651
652
653 void BufferView::Pimpl::savePosition(unsigned int i)
654 {
655         if (i >= saved_positions_num)
656                 return;
657         saved_positions[i] = Position(buffer_->fileName(),
658                                       bv_->text()->cursorPar()->id(),
659                                       bv_->text()->cursor().pos());
660         if (i > 0)
661                 owner_->message(bformat(_("Saved bookmark %1$s"), tostr(i)));
662 }
663
664
665 void BufferView::Pimpl::restorePosition(unsigned int i)
666 {
667         if (i >= saved_positions_num)
668                 return;
669
670         string const fname = saved_positions[i].filename;
671
672         bv_->cursor().clearSelection();
673
674         if (fname != buffer_->fileName()) {
675                 Buffer * b = 0;
676                 if (bufferlist.exists(fname))
677                         b = bufferlist.getBuffer(fname);
678                 else {
679                         b = bufferlist.newBuffer(fname);
680                         ::loadLyXFile(b, fname); // don't ask, just load it
681                 }
682                 if (b)
683                         buffer(b);
684         }
685
686         ParIterator par = buffer_->getParFromID(saved_positions[i].par_id);
687         if (par == buffer_->par_iterator_end())
688                 return;
689
690         bv_->text()->setCursor(par.pit(),
691                              min(par->size(), saved_positions[i].par_pos));
692
693         if (i > 0)
694                 owner_->message(bformat(_("Moved to bookmark %1$s"), tostr(i)));
695 }
696
697
698 bool BufferView::Pimpl::isSavedPosition(unsigned int i)
699 {
700         return i < saved_positions_num && !saved_positions[i].filename.empty();
701 }
702
703
704 void BufferView::Pimpl::switchKeyMap()
705 {
706         if (!lyxrc.rtl_support)
707                 return;
708
709         Intl & intl = owner_->getIntl();
710         if (bv_->getLyXText()->real_current_font.isRightToLeft()) {
711                 if (intl.keymap == Intl::PRIMARY)
712                         intl.KeyMapSec();
713         } else {
714                 if (intl.keymap == Intl::SECONDARY)
715                         intl.KeyMapPrim();
716         }
717 }
718
719
720 void BufferView::Pimpl::center()
721 {
722         LyXText * text = bv_->text();
723
724         bv_->cursor().clearSelection();
725         int const half_height = workarea().workHeight() / 2;
726         int new_y = text->cursorY(bv_->cursor().cursor_.front()) - half_height;
727         if (new_y < 0)
728                 new_y = 0;
729
730         // FIXME: look at this comment again ...
731         // This updates top_y() but means the fitCursor() call
732         // from the update(FITCUR) doesn't realise that we might
733         // have moved (e.g. from GOTOPARAGRAPH), so doesn't cause
734         // the scrollbar to be updated as it should, so we have
735         // to do it manually. Any operation that does a center()
736         // and also might have moved top_y() must make sure to call
737         // updateScrollbar() currently. Never mind that this is a
738         // pretty obfuscated way of updating text->top_y()
739         top_y(new_y);
740 }
741
742
743 void BufferView::Pimpl::stuffClipboard(string const & stuff) const
744 {
745         workarea().putClipboard(stuff);
746 }
747
748
749 InsetBase * BufferView::Pimpl::getInsetByCode(InsetBase::Code code)
750 {
751 #if 0
752         CursorSlice cursor = bv_->getLyXText()->cursor;
753         Buffer::inset_iterator it =
754                 find_if(Buffer::inset_iterator(
755                         cursorPar(), cursor().pos()),
756                         buffer_->inset_iterator_end(),
757                         lyx::compare_memfun(&Inset::lyxCode, code));
758         return it != buffer_->inset_iterator_end() ? (*it) : 0;
759 #else
760         // Ok, this is a little bit too brute force but it
761         // should work for now. Better infrastructure is coming. (Lgb)
762
763         Buffer * b = bv_->buffer();
764         LyXText * text = bv_->getLyXText();
765
766         Buffer::inset_iterator beg = b->inset_iterator_begin();
767         Buffer::inset_iterator end = b->inset_iterator_end();
768
769         bool cursor_par_seen = false;
770
771         for (; beg != end; ++beg) {
772                 if (beg.getPar() == text->cursorPar()) {
773                         cursor_par_seen = true;
774                 }
775                 if (cursor_par_seen) {
776                         if (beg.getPar() == text->cursorPar()
777                             && beg.getPos() >= text->cursor().pos()) {
778                                 break;
779                         }
780                         if (beg.getPar() != text->cursorPar()) {
781                                 break;
782                         }
783                 }
784
785         }
786         if (beg != end) {
787                 // Now find the first inset that matches code.
788                 for (; beg != end; ++beg) {
789                         if (beg->lyxCode() == code)
790                                 return &(*beg);
791                 }
792         }
793         return 0;
794 #endif
795 }
796
797
798 void BufferView::Pimpl::MenuInsertLyXFile(string const & filenm)
799 {
800         string filename = filenm;
801
802         if (filename.empty()) {
803                 // Launch a file browser
804                 string initpath = lyxrc.document_path;
805
806                 if (available()) {
807                         string const trypath = owner_->buffer()->filePath();
808                         // If directory is writeable, use this as default.
809                         if (IsDirWriteable(trypath))
810                                 initpath = trypath;
811                 }
812
813                 FileDialog fileDlg(_("Select LyX document to insert"),
814                         LFUN_FILE_INSERT,
815                         make_pair(string(_("Documents|#o#O")),
816                                   string(lyxrc.document_path)),
817                         make_pair(string(_("Examples|#E#e")),
818                                   string(AddPath(system_lyxdir(), "examples"))));
819
820                 FileDialog::Result result =
821                         fileDlg.open(initpath,
822                                      FileFilterList(_("LyX Documents (*.lyx)")),
823                                      string());
824
825                 if (result.first == FileDialog::Later)
826                         return;
827
828                 filename = result.second;
829
830                 // check selected filename
831                 if (filename.empty()) {
832                         owner_->message(_("Canceled."));
833                         return;
834                 }
835         }
836
837         // get absolute path of file and add ".lyx" to the filename if
838         // necessary
839         filename = FileSearch(string(), filename, "lyx");
840
841         string const disp_fn = MakeDisplayPath(filename);
842         owner_->message(bformat(_("Inserting document %1$s..."), disp_fn));
843         if (bv_->insertLyXFile(filename))
844                 owner_->message(bformat(_("Document %1$s inserted."),
845                                         disp_fn));
846         else
847                 owner_->message(bformat(_("Could not insert document %1$s"),
848                                         disp_fn));
849 }
850
851
852 void BufferView::Pimpl::trackChanges()
853 {
854         Buffer * buf = bv_->buffer();
855         bool const tracking(buf->params().tracking_changes);
856
857         if (!tracking) {
858                 ParIterator const end = buf->par_iterator_end();
859                 for (ParIterator it = buf->par_iterator_begin(); it != end; ++it)
860                         it->trackChanges();
861                 buf->params().tracking_changes = true;
862
863                 // we cannot allow undos beyond the freeze point
864                 buf->undostack().clear();
865         } else {
866                 update();
867                 bv_->text()->setCursor(0, 0);
868 #warning changes FIXME
869                 bool found = lyx::find::findNextChange(bv_);
870                 if (found) {
871                         owner_->getDialogs().show("changes");
872                         return;
873                 }
874
875                 ParIterator const end = buf->par_iterator_end();
876                 for (ParIterator it = buf->par_iterator_begin(); it != end; ++it)
877                         it->untrackChanges();
878                 buf->params().tracking_changes = false;
879         }
880
881         buf->redostack().clear();
882 }
883
884
885 bool BufferView::Pimpl::workAreaDispatch(FuncRequest const & cmd0)
886 {
887         //
888         // this is only called for mouse related events.
889         //
890         FuncRequest cmd = cmd0;
891         cmd.y += bv_->top_y();
892         lyxerr << "*** workAreaDispatch: request: " << cmd << std::endl;
893         LCursor cur(*bv_);
894         switch (cmd.action) {
895 #if 0
896         case LFUN_MOUSE_MOTION: {
897                 if (!available())
898                         return false;
899                 FuncRequest cmd1 = cmd;
900                 InsetBase * inset = cur.inset();
901                 DispatchResult res;
902                 if (inset) {
903                         res = inset->dispatch(cur, cmd);
904                 } else {
905                         res = bv_->text()->dispatch(cur, cmd);
906                 }
907
908                 if (fitCursor() || res.update()) {
909                         bv_->update();
910                         cur.updatePos();
911                 }
912                 return true;
913         }
914 #endif
915
916         case LFUN_MOUSE_MOTION:
917         case LFUN_MOUSE_PRESS:
918         case LFUN_MOUSE_RELEASE:
919         case LFUN_MOUSE_DOUBLE:
920         case LFUN_MOUSE_TRIPLE: {
921                 // We pass those directly to the Bufferview, since
922                 // otherwise selection handling breaks down
923
924                 // Doesn't go through lyxfunc, so we need to update
925                 // the layout choice etc. ourselves
926
927                 // e.g. Qt mouse press when no buffer
928                 if (!available())
929                         return false;
930
931                 screen().hideCursor();
932
933                 // either the inset under the cursor or the
934                 // surrounding LyXText will handle this event.
935
936                 // built temporary path to inset
937                 LyXText * text = bv_->text();
938                 InsetBase * const inset_hit = text->checkInsetHit(cmd.x, cmd.y);
939                 if (inset_hit) 
940                         inset_hit->edit(cur, cmd.x, cmd.y);
941                 else
942                         text->setCursorFromCoordinates(cur.current(), cmd.x, cmd.y);
943                 lyxerr << "created temp cursor: " << cur << endl;
944
945                 // Dispatch to the temp cursor.
946                 // An inset (or LyXText) can assign this to bv->cursor()
947                 // if it wishes to do so.
948                 DispatchResult res = cur.dispatch(cmd);
949
950                 if (fitCursor() || res.update())
951                         bv_->update();
952
953                 // see workAreaKeyPress
954                 cursor_timeout.restart();
955                 screen().showCursor(*bv_);
956
957                 // skip these when selecting
958                 if (cmd.action != LFUN_MOUSE_MOTION) {
959                         owner_->updateLayoutChoice();
960                         owner_->updateToolbar();
961                 }
962
963                 // slight hack: this is only called currently when we
964                 // clicked somewhere, so we force through the display
965                 // of the new status here.
966                 owner_->clearMessage();
967                 return true;
968         }
969
970         default:
971                 lyxerr << "*** UNDISPATCHED: " << cmd;
972                 //owner_->dispatch(cmd);
973         }
974         return true;
975 }
976
977
978 bool BufferView::Pimpl::dispatch(FuncRequest const & cmd)
979 {
980         lyxerr << "*** BufferView::Pimpl: request: " << cmd << std::endl;
981         // Make sure that the cached BufferView is correct.
982         lyxerr[Debug::ACTION] << "BufferView::Pimpl::Dispatch:"
983                 << " action[" << cmd.action << ']'
984                 << " arg[" << cmd.argument << ']'
985                 << " x[" << cmd.x << ']'
986                 << " y[" << cmd.y << ']'
987                 << " button[" << cmd.button() << ']'
988                 << endl;
989
990         LyXTextClass const & tclass = buffer_->params().getLyXTextClass();
991         LCursor & cur = bv_->cursor();
992
993         switch (cmd.action) {
994
995         case LFUN_SCROLL_INSET:
996                 // this is not handled here as this function is only active
997                 // if we have a locking_inset and that one is (or contains)
998                 // a tabular-inset
999                 break;
1000
1001         case LFUN_FILE_INSERT:
1002                 MenuInsertLyXFile(cmd.argument);
1003                 break;
1004
1005         case LFUN_FILE_INSERT_ASCII_PARA:
1006                 InsertAsciiFile(bv_, cmd.argument, true);
1007                 break;
1008
1009         case LFUN_FILE_INSERT_ASCII:
1010                 InsertAsciiFile(bv_, cmd.argument, false);
1011                 break;
1012
1013         case LFUN_FONT_STATE:
1014                 owner_->getLyXFunc().setMessage(currentState(bv_));
1015                 break;
1016
1017         case LFUN_INSERT_LABEL: {
1018                 // Try and generate a valid label
1019                 string const contents = cmd.argument.empty() ?
1020                         getPossibleLabel(*bv_) : cmd.argument;
1021                 InsetCommandParams icp("label", contents);
1022                 string data = InsetCommandMailer::params2string("label", icp);
1023                 owner_->getDialogs().show("label", data, 0);
1024                 break;
1025         }
1026
1027         case LFUN_BOOKMARK_SAVE:
1028                 savePosition(strToUnsignedInt(cmd.argument));
1029                 break;
1030
1031         case LFUN_BOOKMARK_GOTO:
1032                 restorePosition(strToUnsignedInt(cmd.argument));
1033                 break;
1034
1035         case LFUN_REF_GOTO: {
1036                 string label = cmd.argument;
1037                 if (label.empty()) {
1038                         InsetRef * inset =
1039                                 static_cast<InsetRef*>(getInsetByCode(InsetBase::REF_CODE));
1040                         if (inset) {
1041                                 label = inset->getContents();
1042                                 savePosition(0);
1043                         }
1044                 }
1045
1046                 if (!label.empty())
1047                         bv_->gotoLabel(label);
1048         }
1049         break;
1050
1051         // --- accented characters ---------------------------
1052
1053         case LFUN_UMLAUT:
1054         case LFUN_CIRCUMFLEX:
1055         case LFUN_GRAVE:
1056         case LFUN_ACUTE:
1057         case LFUN_TILDE:
1058         case LFUN_CEDILLA:
1059         case LFUN_MACRON:
1060         case LFUN_DOT:
1061         case LFUN_UNDERDOT:
1062         case LFUN_UNDERBAR:
1063         case LFUN_CARON:
1064         case LFUN_SPECIAL_CARON:
1065         case LFUN_BREVE:
1066         case LFUN_TIE:
1067         case LFUN_HUNG_UMLAUT:
1068         case LFUN_CIRCLE:
1069         case LFUN_OGONEK:
1070                 if (cmd.argument.empty()) {
1071                         // As always...
1072                         owner_->getLyXFunc().handleKeyFunc(cmd.action);
1073                 } else {
1074                         owner_->getLyXFunc().handleKeyFunc(cmd.action);
1075                         owner_->getIntl().getTransManager()
1076                                 .TranslateAndInsert(cmd.argument[0], bv_->getLyXText());
1077                         update();
1078                 }
1079                 break;
1080
1081         case LFUN_INSET_INSERT: {
1082                 // Same as above.
1083                 BOOST_ASSERT(false);
1084                 InsetBase * inset = createInset(bv_, cmd);
1085                 if (!inset || !insertInset(inset))
1086                         delete inset;
1087                 break;
1088         }
1089
1090         case LFUN_FLOAT_LIST:
1091                 if (tclass.floats().typeExist(cmd.argument)) {
1092                         InsetBase * inset = new InsetFloatList(cmd.argument);
1093                         if (!insertInset(inset, tclass.defaultLayoutName()))
1094                                 delete inset;
1095                 } else {
1096                         lyxerr << "Non-existent float type: "
1097                                << cmd.argument << endl;
1098                 }
1099                 break;
1100
1101         case LFUN_LAYOUT_PARAGRAPH: {
1102                 string data;
1103                 params2string(*bv_->getLyXText()->cursorPar(), data);
1104                 data = "show\n" + data;
1105                 bv_->owner()->getDialogs().show("paragraph", data);
1106                 break;
1107         }
1108
1109         case LFUN_PARAGRAPH_UPDATE:
1110                 updateParagraphDialog();
1111                 break;
1112
1113         case LFUN_PARAGRAPH_APPLY:
1114                 setParagraphParams(*bv_, cmd.argument);
1115                 break;
1116
1117         case LFUN_THESAURUS_ENTRY: {
1118                 string arg = cmd.argument;
1119
1120                 if (arg.empty()) {
1121                         arg = bv_->getLyXText()->selectionAsString(*buffer_,
1122                                                                    false);
1123
1124                         // FIXME
1125                         if (arg.size() > 100 || arg.empty()) {
1126                                 // Get word or selection
1127                                 bv_->getLyXText()->selectWordWhenUnderCursor(lyx::WHOLE_WORD);
1128                                 arg = bv_->getLyXText()->selectionAsString(*buffer_, false);
1129                                 // FIXME: where is getLyXText()->unselect(bv_) ?
1130                         }
1131                 }
1132
1133                 bv_->owner()->getDialogs().show("thesaurus", arg);
1134                 break;
1135         }
1136
1137         case LFUN_TRACK_CHANGES:
1138                 trackChanges();
1139                 break;
1140
1141         case LFUN_MERGE_CHANGES:
1142                 owner_->getDialogs().show("changes");
1143                 break;
1144
1145         case LFUN_ACCEPT_ALL_CHANGES: {
1146                 bv_->text()->setCursor(0, 0);
1147 #warning FIXME changes
1148                 while (lyx::find::findNextChange(bv_))
1149                         bv_->getLyXText()->acceptChange();
1150                 update();
1151                 break;
1152         }
1153
1154         case LFUN_REJECT_ALL_CHANGES: {
1155                 bv_->text()->setCursor(0, 0);
1156 #warning FIXME changes
1157                 while (lyx::find::findNextChange(bv_))
1158                         bv_->getLyXText()->rejectChange();
1159                 update();
1160                 break;
1161         }
1162
1163         case LFUN_ACCEPT_CHANGE: {
1164                 bv_->getLyXText()->acceptChange();
1165                 update();
1166                 break;
1167         }
1168
1169         case LFUN_REJECT_CHANGE: {
1170                 bv_->getLyXText()->rejectChange();
1171                 update();
1172                 break;
1173         }
1174
1175         case LFUN_WORD_FIND:
1176                 lyx::find::find(bv_, cmd);
1177                 break;
1178
1179         case LFUN_WORD_REPLACE:
1180                 lyx::find::replace(bv_, cmd);
1181                 break;
1182
1183         case LFUN_MARK_OFF:
1184                 cur.clearSelection();
1185                 bv_->update();
1186                 cur.resetAnchor();
1187                 cmd.message(N_("Mark off"));
1188                 break;
1189
1190         case LFUN_MARK_ON:
1191                 cur.clearSelection();
1192                 cur.mark() = true;
1193                 bv_->update();
1194                 cur.resetAnchor();
1195                 cmd.message(N_("Mark on"));
1196                 break;
1197
1198         case LFUN_SETMARK:
1199                 cur.clearSelection();
1200                 if (cur.mark()) {
1201                         cmd.message(N_("Mark removed"));
1202                 } else {
1203                         cur.mark() = true;
1204                         cmd.message(N_("Mark set"));
1205                 }
1206                 cur.resetAnchor();
1207                 bv_->update();
1208                 break;
1209
1210         case LFUN_UNKNOWN_ACTION:
1211                 cmd.errorMessage(N_("Unknown function!"));
1212                 break;
1213
1214         default:
1215                 return false;
1216         }
1217
1218         return true;
1219 }
1220
1221
1222 bool BufferView::Pimpl::insertInset(InsetBase * inset, string const & lout)
1223 {
1224         // not quite sure if we want this...
1225         bv_->text()->recUndo(bv_->text()->cursor().par());
1226         freezeUndo();
1227
1228         bv_->cursor().clearSelection();
1229         if (!lout.empty()) {
1230                 bv_->text()->breakParagraph(bv_->buffer()->paragraphs());
1231
1232                 if (!bv_->text()->cursorPar()->empty()) {
1233                         bv_->text()->cursorLeft(bv_);
1234                         bv_->text()->breakParagraph(bv_->buffer()->paragraphs());
1235                 }
1236
1237                 string lres = lout;
1238                 LyXTextClass const & tclass = buffer_->params().getLyXTextClass();
1239                 bool hasLayout = tclass.hasLayout(lres);
1240
1241                 bv_->text()->setLayout(hasLayout ? lres : tclass.defaultLayoutName());
1242                 bv_->text()->setParagraph(Spacing(), LYX_ALIGN_LAYOUT, string(), 0);
1243         }
1244         bv_->cursor().innerText()->insertInset(inset);
1245         unFreezeUndo();
1246         return true;
1247 }
1248
1249
1250 bool BufferView::Pimpl::ChangeInsets(InsetBase::Code code,
1251                                      string const & from, string const & to)
1252 {
1253         bool need_update = false;
1254         CursorSlice cur = bv_->text()->cursor();
1255
1256         ParIterator end = bv_->buffer()->par_iterator_end();
1257         for (ParIterator it = bv_->buffer()->par_iterator_begin();
1258              it != end; ++it) {
1259                 bool changed_inset = false;
1260                 for (InsetList::iterator it2 = it->insetlist.begin();
1261                      it2 != it->insetlist.end(); ++it2) {
1262                         if (it2->inset->lyxCode() == code) {
1263                                 InsetCommand * inset = static_cast<InsetCommand *>(it2->inset);
1264                                 if (inset->getContents() == from) {
1265                                         inset->setContents(to);
1266                                         changed_inset = true;
1267                                 }
1268                         }
1269                 }
1270                 if (changed_inset) {
1271                         need_update = true;
1272
1273                         // FIXME
1274
1275                         // The test it.size() == 1 was needed to prevent crashes.
1276                         // How to set the cursor correctly when it.size() > 1 ??
1277                         if (it.size() == 1) {
1278                                 bv_->text()->setCursorIntern(bv_->text()->parOffset(it.pit()), 0);
1279                                 bv_->text()->redoParagraph(bv_->text()->cursorPar());
1280                         }
1281                 }
1282         }
1283         bv_->text()->setCursorIntern(cur.par(), cur.pos());
1284         return need_update;
1285 }
1286
1287
1288 void BufferView::Pimpl::updateParagraphDialog()
1289 {
1290         if (!bv_->owner()->getDialogs().visible("paragraph"))
1291                 return;
1292         CursorSlice const & cur = bv_->cursor().innerTextSlice();
1293         LyXText * text = bv_->cursor().innerText();
1294         Paragraph const & par = *text->getPar(cur.par());
1295         string data;
1296         params2string(par, data);
1297
1298         // Will the paragraph accept changes from the dialog?
1299         InsetBase * const inset = cur.inset();
1300         bool const accept =
1301                 !(inset && inset->forceDefaultParagraphs(inset));
1302
1303         data = "update " + tostr(accept) + '\n' + data;
1304         bv_->owner()->getDialogs().update("paragraph", data);
1305 }