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