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