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