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