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