]> git.lyx.org Git - lyx.git/blob - src/Compare.cpp
cfbfdce45928b4a6d45c195300530338a44fe9b0
[lyx.git] / src / Compare.cpp
1 /**
2  * \file Compare.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Vincent van Ravesteijn
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "Compare.h"
14
15 #include "BufferParams.h"
16 #include "Changes.h"
17
18 #include "insets/InsetText.h"
19
20 #include "support/lassert.h"    
21
22 #include <boost/next_prior.hpp>
23
24 using namespace std;
25 using namespace lyx::support;
26
27
28 namespace lyx {
29
30
31 enum Direction {
32         Forward = 0,
33         Backward
34 };
35
36
37 static void step(DocIterator & dit, Direction direction)
38 {
39         if (direction == Forward)
40                 dit.top().forwardPos();
41         else
42                 dit.top().backwardPos();
43 }
44
45
46 static void step(DocIterator & dit, DocIterator const & end, Direction direction)
47 {
48         if (dit != end)
49                 step(dit, direction);
50 }
51
52
53 /**
54  * A pair of two DocIterators that form a range.
55  */
56 class DocRange {
57 public:
58         DocRange(DocIterator from_, DocIterator to_)
59                 : from(from_), to(to_)
60         {}
61
62         DocRange(Buffer const * buf)
63         {
64                 from = doc_iterator_begin(buf);
65                 to = doc_iterator_end(buf);
66                 to.backwardPos();
67         }
68
69         ///
70         Text * text() const { return from.text(); }
71         ///
72         bool empty() const { return to <= from; }
73         ///
74         size_t length() const;
75
76         /// The begin of the range
77         DocIterator from;
78         /// The end of the range
79         DocIterator to;
80 };
81
82
83 size_t DocRange::length() const
84 {
85         pit_type startpit = from.pit();
86         pit_type endpit = to.pit();
87         ParagraphList const & ps_ = from.text()->paragraphs();
88
89         ParagraphList pars(boost::next(ps_.begin(), startpit),
90                                 boost::next(ps_.begin(), endpit + 1));
91
92         // Remove the end of the last paragraph; afterwards, remove the
93         // beginning of the first paragraph.
94         Paragraph & back = pars.back();
95         back.eraseChars(to.pos(), back.size(), false);
96         Paragraph & front = pars.front();
97         front.eraseChars(0, from.pos(), false);
98
99         ParagraphList::const_iterator pit = pars.begin();
100         ParagraphList::const_iterator end_it = pars.end();
101
102         size_t length = 0;
103         for (; pit != end_it; ++pit)
104                 length += pit->size() + 1;
105
106         // The last paragraph has no paragraph-end
107         --length;
108         return length;  
109 }
110
111
112 class DocPair {
113 public:
114         DocPair() {}
115
116         DocPair(DocIterator o_, DocIterator n_)
117                 : o(o_), n(n_)
118         {}
119
120         bool operator!=(DocPair const & rhs) {
121                 // this might not be intuitive but correct for our purpose
122                 return o != rhs.o && n != rhs.n;
123         }
124         
125
126         DocPair & operator++()
127         {
128                 step(o, Forward);
129                 step(n, Forward);
130                 return *this;
131         }
132
133         DocPair & operator--()
134         {
135                 step(o, Backward);
136                 step(n, Backward);
137                 return *this;
138         }
139         ///
140         DocIterator o;
141         ///
142         DocIterator n;
143 };
144         
145 /**
146  * A pair of two DocRanges.
147  */
148 class DocRangePair {
149 public:
150         DocRangePair(DocRange o_, DocRange n_)
151                 : o(o_), n(n_)
152         {}
153         
154         DocRangePair(DocPair from, DocPair to)
155                 : o(from.o, to.o), n(from.n, to.n)
156         {}
157
158         DocRangePair(Buffer const * o_buf, Buffer const * n_buf)
159                 : o(o_buf), n(n_buf)
160         {}
161
162         /// Returns the from pair
163         DocPair from() const { return DocPair(o.from, n.from); }
164
165         /// Returns the to pair
166         DocPair to() const { return DocPair(o.to, n.to); }
167
168         DocRange o;
169         DocRange n;
170 };
171
172
173 static DocRangePair stepIntoInset(DocPair const & inset_location)
174 {
175         DocRangePair rp(inset_location, inset_location);
176         rp.o.from.forwardPos();
177         rp.n.from.forwardPos();
178         step(rp.o.to, Forward);
179         step(rp.n.to, Forward);
180         rp.o.to.backwardPos();
181         rp.n.to.backwardPos();
182         return rp;
183 }
184
185
186 /**
187  * The implementation of the algorithm that does the comparison
188  * between two documents.
189  */
190 class Compare::Impl {
191 public:
192         ///
193         Impl(Compare const & compare) 
194                 : abort_(false), compare_(compare)
195         {}
196
197         ///
198         ~Impl() {}
199
200         // Algorithm to find the shortest edit string. This algorithm 
201         // only needs a linear amount of memory (linear with the sum
202         // of the number of characters in the two paragraph-lists).
203         bool diff(Buffer const * new_buf, Buffer const * old_buf,
204                 Buffer const * dest_buf);
205
206         /// Set to true to cancel the algorithm
207         bool abort_;
208
209 private:
210         /// Finds the middle snake and returns the length of the
211         /// shortest edit script.
212         int find_middle_snake(DocRangePair const & rp, DocPair & middle_snake);
213
214         /// This function is called recursively by a divide and conquer
215         /// algorithm. Each time, the string is divided into two split
216         /// around the middle snake.
217         void diff_i(DocRangePair const & rp);
218
219         /// Processes the splitted chunks. It either adds them as deleted,
220         /// as added, or call diff_i for further processing.
221         void diff_part(DocRangePair const & rp);
222
223         /// Runs the algorithm for the inset located at /c it and /c it_n 
224         /// and adds the result to /c pars.
225         void diff_inset(Inset * inset, DocPair const & p);
226
227         /// Adds the snake to the destination buffer. The algorithm will
228         /// recursively be applied to any InsetTexts that are within the snake.
229         void process_snake(DocRangePair const & rp);
230
231         /// Writes the range to the destination buffer
232         void writeToDestBuffer(DocRange const & range,
233                 Change::Type type = Change::UNCHANGED);
234         
235         /// Writes the paragraph list to the destination buffer
236         void writeToDestBuffer(ParagraphList const & copy_pars) const;
237
238         /// The length of the old chunk currently processed
239         int N_;
240         /// The length of the new chunk currently processed
241         int M_;
242
243         /// The thread object, used to emit signals to the GUI
244         Compare const & compare_;
245
246         /// The buffer containing text that will be marked as old
247         Buffer const * old_buf_;
248         /// The buffer containing text that will be marked as new
249         Buffer const * new_buf_;
250         /// The buffer containing text that will be marked as new
251         Buffer const * dest_buf_;
252
253         /// The paragraph list of the destination buffer
254         ParagraphList * dest_pars_;
255
256         /// The level of recursion
257         int recursion_level_;
258
259         /// The number of nested insets at this level
260         int nested_inset_level_;
261 };
262
263 /////////////////////////////////////////////////////////////////////
264 //
265 // Compare
266 //
267 /////////////////////////////////////////////////////////////////////
268
269 Compare::Compare(Buffer const * new_buf, Buffer const * old_buf,
270         Buffer * const dest_buf, CompareOptions const & options)
271         : new_buffer(new_buf), old_buffer(old_buf), dest_buffer(dest_buf),
272           options_(options), pimpl_(new Impl(*this))
273 {
274 }
275
276
277 void Compare::run()
278 {
279         if (!dest_buffer || !new_buffer || !old_buffer)
280                 return;
281
282         // Copy the buffer params to the new buffer
283         dest_buffer->params() = options_.settings_from_new
284                 ? new_buffer->params() : old_buffer->params();
285         
286         // do the real work
287         if (!doCompare())
288                 return;
289         
290         finished(pimpl_->abort_);
291         return;
292 }
293
294
295 int Compare::doCompare()
296 {
297         return pimpl_->diff(new_buffer, old_buffer, dest_buffer);
298 }
299
300
301 void Compare::abort()
302 {
303         pimpl_->abort_ = true;
304         condition_.wakeOne();
305         wait();
306         pimpl_->abort_ = false;
307 }
308
309
310 static void get_paragraph_list(DocRange const & range,
311         ParagraphList & pars)
312 {
313         // Clone the paragraphs within the selection.
314         pit_type startpit = range.from.pit();
315         pit_type endpit = range.to.pit();
316         ParagraphList const & ps_ = range.text()->paragraphs();
317         ParagraphList tmp_pars(boost::next(ps_.begin(), startpit),
318                 boost::next(ps_.begin(), endpit + 1));
319
320         // Remove the end of the last paragraph; afterwards, remove the
321         // beginning of the first paragraph. Keep this order - there may only
322         // be one paragraph!
323         Paragraph & back = tmp_pars.back();
324         back.eraseChars(range.to.pos(), back.size(), false);
325         Paragraph & front = tmp_pars.front();
326         front.eraseChars(0, range.from.pos(), false);
327
328         pars.insert(pars.begin(), tmp_pars.begin(), tmp_pars.end());
329 }
330
331
332 static bool equal(Inset const * i_o, Inset const * i_n)
333 {
334         if (!i_o || !i_n)
335                 return false;
336
337         // Different types of insets
338         if (i_o->lyxCode() != i_n->lyxCode())
339                 return false;
340
341         // Editable insets are assumed to be the same as they are of the 
342         // same type. If we later on decide that we insert them in the
343         // document as being unchanged, we will run the algorithm on the
344         // contents of the two insets.
345         // FIXME: This fails if the parameters of the insets differ.
346         // FIXME: We do not recurse into InsetTabulars.
347         // FIXME: We need methods inset->equivalent(inset).
348         if (i_o->editable() && !i_o->asInsetMath()
349                   && i_o->asInsetText())
350                 return true;
351
352         ostringstream o_os;
353         ostringstream n_os;
354         i_o->write(o_os);
355         i_n->write(n_os);
356         return o_os.str() == n_os.str();
357 }
358
359
360 static bool equal(DocIterator & o, DocIterator & n) {
361         Paragraph const & old_par = o.text()->getPar(o.pit());
362         Paragraph const & new_par = n.text()->getPar(n.pit());
363
364         char_type const c_o = old_par.getChar(o.pos());
365         char_type const c_n = new_par.getChar(n.pos());
366         if (c_o != c_n)
367                 return false;
368
369         if (old_par.isInset(o.pos())) {
370                 Inset const * i_o = old_par.getInset(o.pos());
371                 Inset const * i_n = new_par.getInset(n.pos());
372
373                 if (i_o && i_n)
374                         return equal(i_o, i_n);
375         }       
376
377         Font fo = old_par.getFontSettings(o.buffer()->params(), o.pos());
378         Font fn = new_par.getFontSettings(n.buffer()->params(), n.pos());
379         return fo == fn;
380 }
381
382
383 /// Traverses a snake in a certain direction. p points to a 
384 /// position in the old and new file and they are synchronously
385 /// moved along the snake. The function returns true if a snake
386 /// was found.
387 static bool traverse_snake(DocPair & p, DocRangePair const & range,
388         Direction direction)
389 {
390         bool ret = false;
391         DocPair const & p_end = 
392                 direction == Forward ? range.to() : range.from();
393
394         while (p != p_end) {
395                 if (direction == Backward)
396                         --p;
397                 if (!equal(p.o, p.n)) {
398                         if (direction == Backward)
399                                 ++p;
400                         return ret;
401                 }
402                 if (direction == Forward)
403                         ++p;
404                 ret = true;
405         }
406         return ret;
407 }
408
409
410 /////////////////////////////////////////////////////////////////////
411 //
412 // Compare::Impl
413 //
414 /////////////////////////////////////////////////////////////////////
415
416 int Compare::Impl::find_middle_snake(DocRangePair const & rp,
417         DocPair &)
418 {
419         N_ = rp.o.length();
420         M_ = rp.n.length();
421         return M_ + N_;
422 }
423
424
425 bool Compare::Impl::diff(Buffer const * new_buf, Buffer const * old_buf,
426         Buffer const * dest_buf)
427 {
428         if (!new_buf || !old_buf || !dest_buf)
429                 return false;
430
431         old_buf_ = old_buf;
432         new_buf_ = new_buf;
433         dest_buf_ = dest_buf;
434         dest_pars_ = &dest_buf->inset().asInsetText()->paragraphs();
435         dest_pars_->clear();
436
437         recursion_level_ = 0;
438         nested_inset_level_ = 0;
439
440         DocRangePair rp(old_buf_, new_buf_);
441
442         DocPair from = rp.from();
443         traverse_snake(from, rp, Forward);
444         DocRangePair const snake(rp.from(), from);
445         process_snake(snake);
446         
447         // Start the recursive algorithm
448         diff_i(rp);
449
450         for (pit_type p = 0; p < (pit_type)dest_pars_->size(); ++p) {
451                 (*dest_pars_)[p].setBuffer(const_cast<Buffer &>(*dest_buf));
452                 (*dest_pars_)[p].setInsetOwner(&dest_buf_->inset());
453         }
454
455         return true;
456 }
457
458
459 void Compare::Impl::diff_i(DocRangePair const & rp)
460 {
461         // The middle snake
462         DocPair middle_snake;
463
464         // Divides the problem into two smaller problems, split around
465         // the snake in the middle.
466         int const L_ses = find_middle_snake(rp, middle_snake);
467
468         // Set maximum of progress bar
469         if (++recursion_level_ == 1)
470                 compare_.progressMax(L_ses);
471
472         // There are now three possibilities: the strings were the same,
473         // the strings were completely different, or we found a middle
474         // snake and we can split the string into two parts to process.
475         if (L_ses == 0)
476                 // Two the same strings (this must be a very rare case, because
477                 // usually this will be part of a snake adjacent to these strings).
478                 writeToDestBuffer(rp.o);
479
480         else if (middle_snake.o.empty()) {
481                 // Two totally different strings
482                 writeToDestBuffer(rp.o, Change::DELETED);
483                 writeToDestBuffer(rp.n, Change::INSERTED);
484
485         } else {
486                 // Retrieve the complete snake
487                 DocPair first_part_end = middle_snake;
488                 traverse_snake(first_part_end, rp, Backward);
489                 DocRangePair first_part(rp.from(), first_part_end);
490                         
491                 DocPair second_part_begin = middle_snake;
492                 traverse_snake(second_part_begin, rp, Forward);
493                 DocRangePair second_part(second_part_begin, rp.to());
494                                 
495                 // Split the string in three parts:
496                 // 1. in front of the snake
497                 diff_part(first_part);
498
499                 // 2. the snake itself, and
500                 DocRangePair const snake(first_part.to(), second_part.from());
501                 process_snake(snake);
502
503                 // 3. behind the snake.
504                 diff_part(second_part);
505         }
506         --recursion_level_;
507 }
508
509
510 void Compare::Impl::diff_part(DocRangePair const & rp)
511 {
512         // Is there a finite length string in both buffers, if not there
513         // is an empty string and we write the other one to the buffer.
514         if (!rp.o.empty() && !rp.n.empty())
515                 diff_i(rp);
516         
517         else if (!rp.o.empty())
518                 writeToDestBuffer(rp.o, Change::DELETED);
519
520         else if (!rp.n.empty())
521                 writeToDestBuffer(rp.n, Change::INSERTED);
522 }
523
524
525 void Compare::Impl::diff_inset(Inset * inset, DocPair const & p)
526 {
527         // Find the dociterators for the beginning and the
528         // end of the inset, for the old and new document.
529         DocRangePair const rp = stepIntoInset(p);
530
531         // Recurse into the inset. Temporarily replace the dest_pars
532         // paragraph list by the paragraph list of the nested inset.
533         ParagraphList * backup_dest_pars = dest_pars_;
534         dest_pars_ = &inset->asInsetText()->text().paragraphs();
535         dest_pars_->clear();
536         
537         ++nested_inset_level_;
538         diff_i(rp);
539         --nested_inset_level_;
540
541         dest_pars_ = backup_dest_pars;
542 }
543
544
545 void Compare::Impl::process_snake(DocRangePair const & rp)
546 {
547         ParagraphList pars;
548         get_paragraph_list(rp.o, pars);
549
550         // Find insets in this paragaph list
551         DocPair it = rp.from();
552         for (; it.o < rp.o.to; ++it) {
553                 Inset * inset = it.o.text()->getPar(it.o.pit()).getInset(it.o.pos());
554                 if (inset && inset->editable() && inset->asInsetText()) {
555                         // Find the inset in the paragraph list that will be pasted into
556                         // the final document. The contents of the inset will be replaced
557                         // by the output of the algorithm below.
558                         pit_type const pit = it.o.pit() - rp.o.from.pit();
559                         pos_type const pos = pit ? it.o.pos() : it.o.pos() - rp.o.from.pos();
560                         inset = pars[pit].getInset(pos);
561                         LASSERT(inset, /**/);
562                         diff_inset(inset, it);
563                 }
564         }
565         writeToDestBuffer(pars);
566 }
567
568
569 void Compare::Impl::writeToDestBuffer(DocRange const & range,
570         Change::Type type)
571 {
572         ParagraphList pars;
573         get_paragraph_list(range, pars);
574
575         pos_type size = 0;
576
577         // Set the change
578         ParagraphList::iterator it = pars.begin();
579         for (; it != pars.end(); ++it) {
580                 it->setChange(Change(type));
581                 size += it->size();
582         }
583
584         writeToDestBuffer(pars);
585
586         if (nested_inset_level_ == 0)
587                 compare_.progress(size);
588 }
589
590
591 void Compare::Impl::writeToDestBuffer(ParagraphList const & pars) const
592 {
593         pit_type const pit = dest_pars_->size() - 1;
594         dest_pars_->insert(dest_pars_->end(), pars.begin(), pars.end());
595         if (pit >= 0)
596                 mergeParagraph(dest_buf_->params(), *dest_pars_, pit);
597 }
598
599
600 #include "moc_Compare.cpp"
601
602 } // namespace lyx