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