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