]> git.lyx.org Git - features.git/blob - src/Compare.cpp
64662ac9ce29cecce3d0337dfd1ef921efdc0738
[features.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 void step_forward(DocIterator & dit)
31 {
32         dit.top().forwardPos();
33 }
34
35
36 void step_backward(DocIterator & dit)
37 {
38         dit.top().backwardPos();
39 }
40
41
42 bool step_forward(DocIterator & dit, DocIterator const & end)
43 {
44         if (dit == end)
45                 return false;
46         step_forward(dit);
47         return true;
48 }
49
50
51 bool step_backward(DocIterator & dit, DocIterator const & beg)
52 {
53         if (dit == beg)
54                 return false;
55         step_backward(dit);
56         return true;
57 }
58
59 /**
60  * A pair of two DocIterators that form a range.
61  */
62 class DocRange {
63 public:
64         DocRange(DocIterator from_, DocIterator to_)
65                 : from(from_), to(to_)
66         {}
67
68         DocRange(Buffer const * buf)
69         {
70                 from = doc_iterator_begin(buf);
71                 to = doc_iterator_end(buf);
72                 to.backwardPos();
73         }
74
75         ///
76         Text * text() const { return from.text(); }
77         ///
78         bool empty() const { return to <= from; }
79         ///
80         size_t length() const;
81
82         /// The begin of the range
83         DocIterator from;
84         /// The end of the range
85         DocIterator to;
86 };
87
88
89 size_t DocRange::length() const
90 {
91         pit_type startpit = from.pit();
92         pit_type endpit = to.pit();
93         ParagraphList const & ps_ = from.text()->paragraphs();
94
95         ParagraphList pars(boost::next(ps_.begin(), startpit),
96                                 boost::next(ps_.begin(), endpit + 1));
97
98         // Remove the end of the last paragraph; afterwards, remove the
99         // beginning of the first paragraph.
100         Paragraph & back = pars.back();
101         back.eraseChars(to.pos(), back.size(), false);
102         Paragraph & front = pars.front();
103         front.eraseChars(0, from.pos(), false);
104
105         ParagraphList::const_iterator pit = pars.begin();
106         ParagraphList::const_iterator end_it = pars.end();
107
108         size_t length = 0;
109         for (; pit != end_it; ++pit)
110                 length += pit->size() + 1;
111
112         // The last paragraph has no paragraph-end
113         --length;
114         return length;  
115 }
116
117
118 class DocPair {
119 public:
120         DocPair() {}
121
122         DocPair(DocIterator o_, DocIterator n_)
123                 : o(o_), n(n_)
124         {}
125
126         DocPair & operator++()
127         {
128                 step_forward(o);
129                 step_forward(n);
130                 return *this;
131         }
132         ///
133         DocIterator o;
134         ///
135         DocIterator n;
136 };
137         
138 /**
139  * A pair of two DocRanges.
140  */
141 class DocRangePair {
142 public:
143         DocRangePair(DocRange o_, DocRange n_)
144                 : o(o_), n(n_)
145         {}
146         
147         DocRangePair(DocPair from, DocPair to)
148                 : o(from.o, to.o), n(from.n, to.n)
149         {}
150
151         DocRangePair(Buffer const * o_buf, Buffer const * n_buf)
152                 : o(o_buf), n(n_buf)
153         {}
154
155         /// Returns the from pair
156         DocPair from() const { return DocPair(o.from, n.from); }
157
158         /// Returns the to pair
159         DocPair to() const { return DocPair(o.to, n.to); }
160
161         DocRange o;
162         DocRange n;
163 };
164
165
166 DocRangePair stepIntoInset(DocPair const & inset_location)
167 {
168         DocRangePair rp(inset_location, inset_location);
169         rp.o.from.forwardPos();
170         rp.n.from.forwardPos();
171         step_forward(rp.o.to);
172         step_forward(rp.n.to);
173         rp.o.to.backwardPos();
174         rp.n.to.backwardPos();
175         return rp;
176 }
177
178
179 /**
180  * The implementation of the algorithm that does the comparison
181  * between two documents.
182  */
183 class Compare::Impl {
184 public:
185         ///
186         Impl(Compare const & compare) 
187                 : abort_(false), compare_(compare)
188         {}
189
190         ///
191         ~Impl() {}
192
193         // Algorithm to find the shortest edit string. This algorithm 
194         // only needs a linear amount of memory (linear with the sum
195         // of the number of characters in the two paragraph-lists).
196         bool diff(Buffer const * new_buf, Buffer const * old_buf,
197                 Buffer const * dest_buf);
198
199         /// Set to true to cancel the algorithm
200         bool abort_;
201
202 private:
203         /// Finds the middle snake and returns the length of the
204         /// shortest edit script.
205         int find_middle_snake(DocRangePair const & rp, DocPair & middle_snake);
206
207         /// This function is called recursively by a divide and conquer
208         /// algorithm. Each time, the string is divided into two split
209         /// around the middle snake.
210         void diff_i(DocRangePair const & rp);
211
212         /// Processes the splitted chunks. It either adds them as deleted,
213         /// as added, or call diff_i for further processing.
214         void diff_part(DocRangePair const & rp);
215
216         /// Runs the algorithm for the inset located at /c it and /c it_n 
217         /// and adds the result to /c pars.
218         void diff_inset(Inset * inset, DocPair const & p);
219
220         /// Adds the snake to the destination buffer. The algorithm will
221         /// recursively be applied to any InsetTexts that are within the snake.
222         void process_snake(DocRangePair const & rp);
223
224         /// Writes the range to the destination buffer
225         void writeToDestBuffer(DocRange const & range,
226                 Change::Type type = Change::UNCHANGED);
227         
228         /// Writes the paragraph list to the destination buffer
229         void writeToDestBuffer(ParagraphList const & copy_pars) const;
230
231         /// The length of the old chunk currently processed
232         int N;
233         /// The length of the new chunk currently processed
234         int M;
235
236         /// The thread object, used to emit signals to the GUI
237         Compare const & compare_;
238
239         /// The buffer containing text that will be marked as old
240         Buffer const * old_buf_;
241         /// The buffer containing text that will be marked as new
242         Buffer const * new_buf_;
243         /// The buffer containing text that will be marked as new
244         Buffer const * dest_buf_;
245
246         /// The paragraph list of the destination buffer
247         ParagraphList * dest_pars_;
248
249         /// The level of recursion
250         int recursion_level_;
251
252         /// The number of nested insets at this level
253         int nested_inset_level_;
254 };
255
256 /////////////////////////////////////////////////////////////////////
257 //
258 // Compare
259 //
260 /////////////////////////////////////////////////////////////////////
261
262 Compare::Compare(Buffer const * new_buf, Buffer const * old_buf,
263         Buffer * const dest_buf, CompareOptions const & options)
264         : new_buffer(new_buf), old_buffer(old_buf), dest_buffer(dest_buf),
265           options_(options), pimpl_(new Impl(*this))
266 {
267 }
268
269
270 void Compare::run()
271 {
272         if (!dest_buffer || !new_buffer || !old_buffer)
273                 return;
274
275         // Copy the buffer params to the new buffer
276         dest_buffer->params() = options_.settings_from_new
277                 ? new_buffer->params() : old_buffer->params();
278         
279         // do the real work
280         if (!doCompare())
281                 return;
282         
283         finished(pimpl_->abort_);
284         return;
285 }
286
287
288 int Compare::doCompare()
289 {
290         return pimpl_->diff(new_buffer, old_buffer, dest_buffer);
291 }
292
293
294 void Compare::abort()
295 {
296         pimpl_->abort_ = true;
297         condition_.wakeOne();
298         wait();
299         pimpl_->abort_ = false;
300 }
301
302
303 void get_paragraph_list(DocRange const & range,
304         ParagraphList & pars)
305 {
306         // Clone the paragraphs within the selection.
307         pit_type startpit = range.from.pit();
308         pit_type endpit = range.to.pit();
309         ParagraphList const & ps_ = range.text()->paragraphs();
310         ParagraphList tmp_pars(boost::next(ps_.begin(), startpit),
311                 boost::next(ps_.begin(), endpit + 1));
312
313         // Remove the end of the last paragraph; afterwards, remove the
314         // beginning of the first paragraph. Keep this order - there may only
315         // be one paragraph!
316         Paragraph & back = tmp_pars.back();
317         back.eraseChars(range.to.pos(), back.size(), false);
318         Paragraph & front = tmp_pars.front();
319         front.eraseChars(0, range.from.pos(), false);
320
321         pars.insert(pars.begin(), tmp_pars.begin(), tmp_pars.end());
322 }
323
324
325 bool equal(Inset const * i_o, Inset const * i_n)
326 {
327         if (!i_o || !i_n)
328                 return false;
329
330         // Different types of insets
331         if (i_o->lyxCode() != i_n->lyxCode())
332                 return false;
333
334         // Editable insets are assumed to be the same as they are of the 
335         // same type. If we later on decide that we insert them in the
336         // document as being unchanged, we will run the algorithm on the
337         // contents of the two insets.
338         // FIXME: This fails if the parameters of the insets differ.
339         // FIXME: We do not recurse into InsetTabulars.
340         // FIXME: We need methods inset->equivalent(inset).
341         if (i_o->editable() && !i_o->asInsetMath()
342                   && i_o->asInsetText())
343                 return true;
344
345         ostringstream o_os;
346         ostringstream n_os;
347         i_o->write(o_os);
348         i_n->write(n_os);
349         return o_os.str() == n_os.str();
350 }
351
352
353 bool equal(DocIterator & o, DocIterator & n) {
354         Paragraph const & old_par = o.text()->getPar(o.pit());
355         Paragraph const & new_par = n.text()->getPar(n.pit());
356
357         char_type const c_o = old_par.getChar(o.pos());
358         char_type const c_n = new_par.getChar(n.pos());
359         if (c_o != c_n)
360                 return false;
361
362         if (old_par.isInset(o.pos())) {
363                 Inset const * i_o = old_par.getInset(o.pos());
364                 Inset const * i_n = new_par.getInset(n.pos());
365
366                 if (i_o && i_n)
367                         return equal(i_o, i_n);
368         }       
369
370         Font fo = old_par.getFontSettings(o.buffer()->params(), o.pos());
371         Font fn = new_par.getFontSettings(n.buffer()->params(), n.pos());
372         return fo == fn;
373 }
374
375
376 void traverse_snake_back(DocRangePair & rp)
377 {
378         while (true) {
379                 // Traverse snake
380                 if (!step_backward(rp.o.to, rp.o.from))
381                         break;
382
383                 if (!step_backward(rp.n.to, rp.n.from)) {
384                         step_forward(rp.o.to);
385                         break;
386                 }
387
388                 if (!equal(rp.o.to, rp.n.to)) {
389                         step_forward(rp.o.to);
390                         step_forward(rp.n.to);
391                         break;
392                 }
393         }
394 }
395
396
397 void traverse_snake_forw(DocRangePair & rp)
398 {
399         while (equal(rp.o.from, rp.n.from)) {
400                 if (!step_forward(rp.o.from, rp.o.to))
401                         break;
402
403                 if (!step_forward(rp.n.from, rp.n.to)) {
404                         step_backward(rp.o.from);
405                         break;
406                 }
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_forw(rp);
444         DocRangePair const snake(from, rp.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                 DocRangePair first_part(rp.from(), middle_snake);
488                 traverse_snake_back(first_part);
489                         
490                 DocRangePair second_part(middle_snake, rp.to());
491                 traverse_snake_forw(second_part);
492                         
493                 // Split the string in three parts:
494                 // 1. in front of the snake
495                 diff_part(first_part);
496
497                 // 2. the snake itself, and
498                 DocRangePair const snake(first_part.to(), second_part.from());
499                 process_snake(snake);
500
501                 // 3. behind the snake.
502                 diff_part(second_part);
503         }
504         --recursion_level_;
505 }
506
507
508 void Compare::Impl::diff_part(DocRangePair const & rp)
509 {
510         // Is there a finite length string in both buffers, if not there
511         // is an empty string and we write the other one to the buffer.
512         if (!rp.o.empty() && !rp.n.empty())
513                 diff_i(rp);
514         
515         else if (!rp.o.empty())
516                 writeToDestBuffer(rp.o, Change::DELETED);
517
518         else if (!rp.n.empty())
519                 writeToDestBuffer(rp.n, Change::INSERTED);
520 }
521
522
523 void Compare::Impl::diff_inset(Inset * inset, DocPair const & p)
524 {
525         // Find the dociterators for the beginning and the
526         // end of the inset, for the old and new document.
527         DocRangePair const rp = stepIntoInset(p);
528
529         // Recurse into the inset. Temporarily replace the dest_pars
530         // paragraph list by the paragraph list of the nested inset.
531         ParagraphList * backup_dest_pars = dest_pars_;
532         dest_pars_ = &inset->asInsetText()->text().paragraphs();
533         dest_pars_->clear();
534         
535         ++nested_inset_level_;
536         diff_i(rp);
537         --nested_inset_level_;
538
539         dest_pars_ = backup_dest_pars;
540 }
541
542
543 void Compare::Impl::process_snake(DocRangePair const & rp)
544 {
545         ParagraphList pars;
546         get_paragraph_list(rp.o, pars);
547
548         // Find insets in this paragaph list
549         DocPair it = rp.from();
550         for (; it.o < rp.o.to; ++it) {
551                 Inset * inset = it.o.text()->getPar(it.o.pit()).getInset(it.o.pos());
552                 if (inset && inset->editable() && inset->asInsetText()) {
553                         // Find the inset in the paragraph list that will be pasted into
554                         // the final document. The contents of the inset will be replaced
555                         // by the output of the algorithm below.
556                         pit_type const pit = it.o.pit() - rp.o.from.pit();
557                         pos_type const pos = pit ? it.o.pos() : it.o.pos() - rp.o.from.pos();
558                         inset = pars[pit].getInset(pos);
559                         LASSERT(inset, /**/);
560                         diff_inset(inset, it);
561                 }
562         }
563         writeToDestBuffer(pars);
564 }
565
566
567 void Compare::Impl::writeToDestBuffer(DocRange const & range,
568         Change::Type type)
569 {
570         ParagraphList pars;
571         get_paragraph_list(range, pars);
572
573         pos_type size = 0;
574
575         // Set the change
576         ParagraphList::iterator it = pars.begin();
577         for (; it != pars.end(); ++it) {
578                 it->setChange(Change(type));
579                 size += it->size();
580         }
581
582         writeToDestBuffer(pars);
583
584         if (nested_inset_level_ == 0)
585                 compare_.progress(size);
586 }
587
588
589 void Compare::Impl::writeToDestBuffer(ParagraphList const & pars) const
590 {
591         pit_type const pit = dest_pars_->size() - 1;
592         dest_pars_->insert(dest_pars_->end(), pars.begin(), pars.end());
593         if (pit >= 0)
594                 mergeParagraph(dest_buf_->params(), *dest_pars_, pit);
595 }
596
597
598 #include "moc_Compare.cpp"
599
600 } // namespace lyx