]> git.lyx.org Git - lyx.git/blobdiff - src/Compare.cpp
Part of r32942. We want to avoid reload flickering when
[lyx.git] / src / Compare.cpp
index 21be36657e94309c9a80b2c33161318a75796e34..95eaf5abaef0f9cc1bf3eacfc89297b7348d8062 100644 (file)
@@ -12,7 +12,6 @@
 
 #include "Compare.h"
 
-#include "Buffer.h"
 #include "BufferParams.h"
 #include "Changes.h"
 
 
 #include <boost/next_prior.hpp>
 
+#include <cmath>
+
 using namespace std;
 using namespace lyx::support;
 
 
 namespace lyx {
 
-void step_forward(DocIterator & dit)
-{
-       dit.top().forwardPos();
-}
 
-
-void step_backward(DocIterator & dit)
-{
-       dit.top().backwardPos();
-}
+enum Direction {
+       Forward = 0,
+       Backward
+};
 
 
-bool step_forward(DocIterator & dit, DocIterator const & end)
+static void step(DocIterator & dit, Direction direction)
 {
-       if (dit == end)
-               return false;
-       step_forward(dit);
-       return true;
+       if (direction == Forward)
+               dit.top().forwardPos();
+       else
+               dit.top().backwardPos();
 }
 
 
-bool step_backward(DocIterator & dit, DocIterator const & beg)
+static void step(DocIterator & dit, DocIterator const & end, Direction direction)
 {
-       if (dit == beg)
-               return false;
-       step_backward(dit);
-       return true;
+       if (dit != end)
+               step(dit, direction);
 }
 
+
 /**
  * A pair of two DocIterators that form a range.
  */
@@ -89,30 +84,14 @@ public:
 
 size_t DocRange::length() const
 {
-       pit_type startpit = from.pit();
-       pit_type endpit = to.pit();
-       ParagraphList const & ps_ = from.text()->paragraphs();
-
-       ParagraphList pars(boost::next(ps_.begin(), startpit),
-                               boost::next(ps_.begin(), endpit + 1));
-
-       // Remove the end of the last paragraph; afterwards, remove the
-       // beginning of the first paragraph.
-       Paragraph & back = pars.back();
-       back.eraseChars(to.pos(), back.size(), false);
-       Paragraph & front = pars.front();
-       front.eraseChars(0, from.pos(), false);
-
-       ParagraphList::const_iterator pit = pars.begin();
-       ParagraphList::const_iterator end_it = pars.end();
-
+       ParagraphList const & ps = from.text()->paragraphs();
        size_t length = 0;
-       for (; pit != end_it; ++pit)
-               length += pit->size() + 1;
-
-       // The last paragraph has no paragraph-end
-       --length;
-       return length;  
+       pit_type pit = from.pit();
+       pit_type const endpit = to.pit();
+       for (; pit < endpit; ++pit)
+               length += ps[pit].size() + 1;
+       length += to.pos() - from.pos();
+       return length;
 }
 
 
@@ -124,10 +103,23 @@ public:
                : o(o_), n(n_)
        {}
 
+       bool operator!=(DocPair const & rhs) {
+               // this might not be intuitive but correct for our purpose
+               return o != rhs.o && n != rhs.n;
+       }
+       
+
        DocPair & operator++()
        {
-               step_forward(o);
-               step_forward(n);
+               step(o, Forward);
+               step(n, Forward);
+               return *this;
+       }
+
+       DocPair & operator--()
+       {
+               step(o, Backward);
+               step(n, Backward);
                return *this;
        }
        ///
@@ -164,19 +156,61 @@ public:
 };
 
 
-DocRangePair stepIntoInset(DocPair const & inset_location)
+static DocRangePair stepIntoInset(DocPair const & inset_location)
 {
        DocRangePair rp(inset_location, inset_location);
        rp.o.from.forwardPos();
        rp.n.from.forwardPos();
-       step_forward(rp.o.to);
-       step_forward(rp.n.to);
+       step(rp.o.to, Forward);
+       step(rp.n.to, Forward);
        rp.o.to.backwardPos();
        rp.n.to.backwardPos();
        return rp;
 }
 
 
+/**
+ *  This class is designed to hold a vector that has both positive as
+ *  negative indices. It is internally represented as two vectors, one
+ *  for non-zero indices and one for negative indices. In this way, the
+ *  vector can grow in both directions.
+ *    If an index is not available in the vector, the default value is
+ *  returned. If an object is put in the vector beyond its size, the
+ *  empty spots in between are also filled with the default value.
+ */
+template<class T>
+class compl_vector {
+public:
+       compl_vector() {}
+
+       void reset(T const & def)
+       {
+               default_ = def;
+               Vp_.clear();
+               Vn_.clear();
+       }
+
+       /// Gets the value at index. If it is not in the vector
+       /// the default value is inserted and returned.
+       T & operator[](int index) {
+               vector<T> & V = index >= 0 ? Vp_ : Vn_;
+               unsigned int const ii = index >= 0 ? index : -index - 1;
+               while (ii >= V.size())
+                       V.push_back(default_);
+               return V[ii];
+       }
+
+private:
+       /// The vector for positive indices
+       vector<T> Vp_;
+       /// The vector for negative indices
+       vector<T> Vn_;
+       /// The default value that is inserted in the vector
+       /// if more space is needed
+       T default_;
+};
+
+
 /**
  * The implementation of the algorithm that does the comparison
  * between two documents.
@@ -201,13 +235,33 @@ public:
        bool abort_;
 
 private:
-       // Finds the middle snake and returns the length of the
-       // shortest edit script.
+       /// Finds the middle snake and returns the length of the
+       /// shortest edit script.
        int find_middle_snake(DocRangePair const & rp, DocPair & middle_snake);
 
-       // This function is called recursively by a divide and conquer
-       // algorithm. Each time, the string is divided into two split
-       // around the middle snake.
+       enum SnakeResult {
+               NoSnake,
+               SingleSnake,
+               NormalSnake
+       };
+
+       /// Retrieve the middle snake when there is overlap between
+       /// the forward and backward path.
+       SnakeResult retrieve_middle_snake(int k, int D, Direction direction,
+               DocPair & middle_snake);
+       
+       /// Find the the furthest reaching D-path (number of horizontal
+       /// and vertical steps; differences between the old and new
+       /// document) in the k-diagonal (vertical minus horizontal steps).
+       void furthest_Dpath_kdiagonal(int D, int k,
+               DocRangePair const & rp, Direction direction);
+
+       /// Is there overlap between the forward and backward path
+       bool overlap(int k, int D);
+       
+       /// This function is called recursively by a divide and conquer
+       /// algorithm. Each time, the string is divided into two split
+       /// around the middle snake.
        void diff_i(DocRangePair const & rp);
 
        /// Processes the splitted chunks. It either adds them as deleted,
@@ -218,8 +272,8 @@ private:
        /// and adds the result to /c pars.
        void diff_inset(Inset * inset, DocPair const & p);
 
-       // Adds the snake to the destination buffer. The algorithm will
-       // recursively be applied to any InsetTexts that are within the snake.
+       /// Adds the snake to the destination buffer. The algorithm will
+       /// recursively be applied to any InsetTexts that are within the snake.
        void process_snake(DocRangePair const & rp);
 
        /// Writes the range to the destination buffer
@@ -229,10 +283,15 @@ private:
        /// Writes the paragraph list to the destination buffer
        void writeToDestBuffer(ParagraphList const & copy_pars) const;
 
-       /// The length of the first chunk currently processed
-       int N;
-       /// The length of the second chunk currently processed
-       int M;
+       /// The length of the old chunk currently processed
+       int N_;
+       /// The length of the new chunk currently processed
+       int M_;
+       /// The offset diagonal of the reverse path of the
+       /// currently processed chunk
+       int offset_reverse_diagonal_;
+       /// Is the offset odd or even ?
+       bool odd_offset_;
 
        /// The thread object, used to emit signals to the GUI
        Compare const & compare_;
@@ -252,6 +311,17 @@ private:
 
        /// The number of nested insets at this level
        int nested_inset_level_;
+
+       /// The position/snake in the old/new document
+       /// of the forward/reverse search
+       compl_vector<DocIterator> ofp;
+       compl_vector<DocIterator> nfp;
+       compl_vector<DocIterator> ofs;
+       compl_vector<DocIterator> nfs;
+       compl_vector<DocIterator> orp;
+       compl_vector<DocIterator> nrp;
+       compl_vector<DocIterator> ors;
+       compl_vector<DocIterator> nrs;
 };
 
 /////////////////////////////////////////////////////////////////////
@@ -301,7 +371,7 @@ void Compare::abort()
 }
 
 
-void get_paragraph_list(DocRange const & range,
+static void get_paragraph_list(DocRange const & range,
        ParagraphList & pars)
 {
        // Clone the paragraphs within the selection.
@@ -323,7 +393,7 @@ void get_paragraph_list(DocRange const & range,
 }
 
 
-bool equal(Inset const * i_o, Inset const * i_n)
+static bool equal(Inset const * i_o, Inset const * i_n)
 {
        if (!i_o || !i_n)
                return false;
@@ -351,70 +421,215 @@ bool equal(Inset const * i_o, Inset const * i_n)
 }
 
 
-bool equal(DocIterator & o, DocIterator & n) {
+static bool equal(DocIterator & o, DocIterator & n) {
        Paragraph const & old_par = o.text()->getPar(o.pit());
        Paragraph const & new_par = n.text()->getPar(n.pit());
 
-       Inset const * i_o = old_par.getInset(o.pos());
-       Inset const * i_n = new_par.getInset(n.pos());
+       char_type const c_o = old_par.getChar(o.pos());
+       char_type const c_n = new_par.getChar(n.pos());
+       if (c_o != c_n)
+               return false;
+
+       if (old_par.isInset(o.pos())) {
+               Inset const * i_o = old_par.getInset(o.pos());
+               Inset const * i_n = new_par.getInset(n.pos());
+
+               if (i_o && i_n)
+                       return equal(i_o, i_n);
+       }       
 
-       if (i_o && i_n)
-               return equal(i_o, i_n);
-       
-       char_type c_o = old_par.getChar(o.pos());
-       char_type c_n = new_par.getChar(n.pos());
        Font fo = old_par.getFontSettings(o.buffer()->params(), o.pos());
        Font fn = new_par.getFontSettings(n.buffer()->params(), n.pos());
-       return c_o == c_n && fo == fn;
+       return fo == fn;
 }
 
 
-void traverse_snake_back(DocRangePair & rp)
+/// Traverses a snake in a certain direction. p points to a 
+/// position in the old and new file and they are synchronously
+/// moved along the snake. The function returns true if a snake
+/// was found.
+static bool traverse_snake(DocPair & p, DocRangePair const & range,
+       Direction direction)
 {
-       while (true) {
-               // Traverse snake
-               if (!step_backward(rp.o.to, rp.o.from))
-                       break;
-
-               if (!step_backward(rp.n.to, rp.n.from)) {
-                       step_forward(rp.o.to);
-                       break;
+       bool ret = false;
+       DocPair const & p_end = 
+               direction == Forward ? range.to() : range.from();
+
+       while (p != p_end) {
+               if (direction == Backward)
+                       --p;
+               if (!equal(p.o, p.n)) {
+                       if (direction == Backward)
+                               ++p;
+                       return ret;
                }
+               if (direction == Forward)
+                       ++p;
+               ret = true;
+       }
+       return ret;
+}
 
-               if (!equal(rp.o.to, rp.n.to)) {
-                       step_forward(rp.o.to);
-                       step_forward(rp.n.to);
-                       break;
-               }
+
+/////////////////////////////////////////////////////////////////////
+//
+// Compare::Impl
+//
+/////////////////////////////////////////////////////////////////////
+
+
+void Compare::Impl::furthest_Dpath_kdiagonal(int D, int k,
+        DocRangePair const & rp, Direction direction)
+{
+       compl_vector<DocIterator> & op = direction == Forward ? ofp : orp;
+       compl_vector<DocIterator> & np = direction == Forward ? nfp : nrp;
+       compl_vector<DocIterator> & os = direction == Forward ? ofs : ors;
+       compl_vector<DocIterator> & ns = direction == Forward ? nfs : nrs;
+
+       // A vertical step means stepping one character in the new document.
+       bool vertical_step = k == -D;
+       if (!vertical_step && k != D) {
+               vertical_step = direction == Forward
+                       ? op[k - 1] < op[k + 1] : op[k - 1] > op[k + 1];
        }
+
+       // Where do we take the step from ?
+       int const kk = vertical_step ? k + 1 : k - 1;
+       DocPair p(op[kk], np[kk]);
+
+       // If D==0 we simulate a vertical step from (0,-1) by doing nothing.
+       if (D != 0) {
+               // Take a step
+               if (vertical_step && direction == Forward)
+                       step(p.n, rp.n.to, direction);
+               else if (vertical_step && direction == Backward)
+                       step(p.n, rp.n.from, direction);
+               else if (!vertical_step && direction == Forward)
+                       step(p.o, rp.o.to, direction);
+               else if (!vertical_step && direction == Backward)
+                       step(p.o, rp.o.from, direction);
+       }       
+       
+       // Traverse snake
+       if (traverse_snake(p, rp, direction)) {
+               // Record last snake
+               os[k] = p.o;
+               ns[k] = p.n;
+       } else {
+               // Copy last snake from the previous step
+               os[k] = os[kk];
+               ns[k] = ns[kk];
+       }
+
+       //Record new position
+       op[k] = p.o;
+       np[k] = p.n;
 }
 
 
-void traverse_snake_forw(DocRangePair & rp)
+bool Compare::Impl::overlap(int k, int D)
 {
-       while (equal(rp.o.from, rp.n.from)) {
-               if (!step_forward(rp.o.from, rp.o.to))
-                       break;
+       // To generalize for the forward and reverse checks
+       int kk = offset_reverse_diagonal_ - k;
+
+       // Can we have overlap ?
+       if (kk <= D && kk >= -D) {
+               // Do we have overlap ?
+               if (odd_offset_)
+                       return ofp[k] >= orp[kk] && nfp[k] >= nrp[kk];
+               else
+                       return ofp[kk] >= orp[k] && nfp[kk] >= nrp[k];
+       }
+       return false;
+}
 
-               if (!step_forward(rp.n.from, rp.n.to)) {
-                       step_backward(rp.o.from);
-                       break;
-               }
+
+Compare::Impl::SnakeResult Compare::Impl::retrieve_middle_snake(
+       int k, int D, Direction direction, DocPair & middle_snake)
+{
+       compl_vector<DocIterator> & os = direction == Forward ? ofs : ors;
+       compl_vector<DocIterator> & ns = direction == Forward ? nfs : nrs;
+       compl_vector<DocIterator> & os_r = direction == Forward ? ors : ofs;
+       compl_vector<DocIterator> & ns_r = direction == Forward ? nrs : nfs;
+
+       // The diagonal while doing the backward search
+       int kk = -k + offset_reverse_diagonal_;
+
+       // Did we find a snake ?
+       if (os[k].empty() && os_r[kk].empty()) {
+               // No, there is no snake at all, in which case
+               // the length of the shortest edit script is M+N.
+               LASSERT(2 * D - odd_offset_ == M_ + N_, /**/);
+               return NoSnake;
+       } 
+       
+       if (os[k].empty()) {
+               // Yes, but there is only 1 snake and we found it in the
+               // reverse path.
+               middle_snake.o = os_r[kk];
+               middle_snake.n = ns_r[kk];
+               return SingleSnake;
        }
+
+       middle_snake.o = os[k];
+       middle_snake.n = ns[k];
+       return NormalSnake;
 }
 
-/////////////////////////////////////////////////////////////////////
-//
-// Compare::Impl
-//
-/////////////////////////////////////////////////////////////////////
 
 int Compare::Impl::find_middle_snake(DocRangePair const & rp,
        DocPair & middle_snake)
 {
-       N = rp.o.length();
-       M = rp.n.length();
-       return M+N;
+       // The lengths of the old and new chunks.
+       N_ = rp.o.length();
+       M_ = rp.n.length();
+
+       // Forward paths are centered around the 0-diagonal; reverse paths
+       // are centered around the diagonal N - M. (Delta in the article)
+       offset_reverse_diagonal_ = N_ - M_;
+
+       // If the offset is odd, only check for overlap while extending forward
+    // paths, otherwise only check while extending reverse paths.
+       odd_offset_ = (offset_reverse_diagonal_ % 2 != 0);
+
+       ofp.reset(rp.o.from);
+       nfp.reset(rp.n.from);
+       ofs.reset(DocIterator());
+       nfs.reset(DocIterator());
+       orp.reset(rp.o.to);
+       nrp.reset(rp.n.to);
+       ors.reset(DocIterator());
+       nrs.reset(DocIterator());
+
+       // D is the number of horizontal and vertical steps, i.e.
+       // different characters in the old and new chunk.
+       int const D_max = ceil(((double)M_ + N_)/2);
+       for (int D = 0; D <= D_max; ++D) {
+
+               // Forward and reverse paths
+               for (int f = 0; f < 2; ++f) {
+                       Direction direction = f == 0 ? Forward : Backward;
+
+                       // Diagonals between -D and D can be reached by a D-path
+                       for (int k = -D; k <= D; k += 2) {                      
+                               // Find the furthest reaching D-path on this diagonal
+                               furthest_Dpath_kdiagonal(D, k, rp, direction);
+
+                               // Only check for overlap for forward paths if the offset is odd
+                               // and only for reverse paths if the offset is even.
+                               if (odd_offset_ == (direction == Forward)) {
+
+                                       // Do the forward and backward paths overlap ?
+                                       if (overlap(k, D - odd_offset_)) {
+                                               retrieve_middle_snake(k, D, direction, middle_snake);
+                                               return 2 * D - odd_offset_;
+                                       }
+                               }
+                       }
+               }
+       }
+       // This should never be reached
+       return -2;
 }
 
 
@@ -436,8 +651,8 @@ bool Compare::Impl::diff(Buffer const * new_buf, Buffer const * old_buf,
        DocRangePair rp(old_buf_, new_buf_);
 
        DocPair from = rp.from();
-       traverse_snake_forw(rp);
-       DocRangePair const snake(from, rp.from());
+       traverse_snake(from, rp, Forward);
+       DocRangePair const snake(rp.from(), from);
        process_snake(snake);
        
        // Start the recursive algorithm
@@ -480,12 +695,14 @@ void Compare::Impl::diff_i(DocRangePair const & rp)
 
        } else {
                // Retrieve the complete snake
-               DocRangePair first_part(rp.from(), middle_snake);
-               traverse_snake_back(first_part);
-                       
-               DocRangePair second_part(middle_snake, rp.to());
-               traverse_snake_forw(second_part);
+               DocPair first_part_end = middle_snake;
+               traverse_snake(first_part_end, rp, Backward);
+               DocRangePair first_part(rp.from(), first_part_end);
                        
+               DocPair second_part_begin = middle_snake;
+               traverse_snake(second_part_begin, rp, Forward);
+               DocRangePair second_part(second_part_begin, rp.to());
+                               
                // Split the string in three parts:
                // 1. in front of the snake
                diff_part(first_part);