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