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