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