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