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