forked from PavelTorgashov/FastColoredTextBox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDiffMergeSample.cs
574 lines (492 loc) · 18.9 KB
/
DiffMergeSample.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;
using FastColoredTextBoxNS;
using Tester.DiffMergeStuffs;
namespace Tester
{
public partial class DiffMergeSample : Form
{
int updating;
Style greenStyle;
Style redStyle;
public DiffMergeSample()
{
InitializeComponent();
greenStyle = new MarkerStyle(new SolidBrush(Color.FromArgb(50, Color.Lime)));
redStyle = new MarkerStyle(new SolidBrush(Color.FromArgb(50, Color.Red)));
}
private void btSecond_Click(object sender, EventArgs e)
{
if (ofdFile.ShowDialog() == DialogResult.OK)
tbSecondFile.Text = ofdFile.FileName;
}
private void btFirst_Click(object sender, EventArgs e)
{
if (ofdFile.ShowDialog() == DialogResult.OK)
tbFirstFile.Text = ofdFile.FileName;
}
void tb_VisibleRangeChanged(object sender, EventArgs e)
{
if (updating > 0)
return;
var vPos = (sender as FastColoredTextBox).VerticalScroll.Value;
var curLine = (sender as FastColoredTextBox).Selection.Start.iLine;
if (sender == fctb2)
UpdateScroll(fctb1, vPos, curLine);
else
UpdateScroll(fctb2, vPos, curLine);
fctb1.Refresh();
fctb2.Refresh();
}
void UpdateScroll(FastColoredTextBox tb, int vPos, int curLine)
{
if (updating > 0)
return;
//
BeginUpdate();
//
if (vPos <= tb.VerticalScroll.Maximum)
{
tb.VerticalScroll.Value = vPos;
tb.UpdateScrollbars();
}
if (curLine < tb.LinesCount)
tb.Selection = new Range(tb, 0, curLine, 0, curLine);
//
EndUpdate();
}
private void EndUpdate()
{
updating--;
}
private void BeginUpdate()
{
updating++;
}
private void btCompare_Click(object sender, EventArgs e)
{
if (!File.Exists(tbFirstFile.Text) && !File.Exists(tbSecondFile.Text))
{
MessageBox.Show(this,"Please select a valid file", "Invalid file");
return;
}
fctb1.Clear();
fctb2.Clear();
Cursor = Cursors.WaitCursor;
if (Path.GetExtension(tbFirstFile.Text).ToLower() == ".cs")
fctb1.Language = fctb2.Language = Language.CSharp;
else
fctb1.Language = fctb2.Language = Language.Custom;
var source1 = Lines.Load(tbFirstFile.Text);
var source2 = Lines.Load(tbSecondFile.Text);
source1.Merge(source2);
BeginUpdate();
Process(source1);
EndUpdate();
Cursor = Cursors.Default;
}
private void Process(Lines lines)
{
foreach(var line in lines)
{
switch(line.state)
{
case DiffType.None:
fctb1.AppendText(line.line + Environment.NewLine);
fctb2.AppendText(line.line + Environment.NewLine);
break;
case DiffType.Inserted:
fctb1.AppendText(Environment.NewLine);
fctb2.AppendText(line.line + Environment.NewLine, greenStyle);
break;
case DiffType.Deleted:
fctb1.AppendText(line.line + Environment.NewLine, redStyle);
fctb2.AppendText(Environment.NewLine);
break;
}
if (line.subLines != null)
Process(line.subLines);
}
}
}
#region Merge stuffs
namespace DiffMergeStuffs
{
public class SimpleDiff<T>
{
private IList<T> _left;
private IList<T> _right;
private int[,] _matrix;
private bool _matrixCreated;
private int _preSkip;
private int _postSkip;
private Func<T, T, bool> _compareFunc;
public SimpleDiff(IList<T> left, IList<T> right)
{
_left = left;
_right = right;
InitializeCompareFunc();
}
public event EventHandler<DiffEventArgs<T>> LineUpdate;
public TimeSpan ElapsedTime { get; private set; }
/// <summary>
/// This is the sole public method and it initializes
/// the LCS matrix the first time it's called, and
/// proceeds to fire a series of LineUpdate events
/// </summary>
public void RunDiff()
{
if (!_matrixCreated)
{
Stopwatch sw = new Stopwatch();
sw.Start();
CalculatePreSkip();
CalculatePostSkip();
CreateLCSMatrix();
sw.Stop();
this.ElapsedTime = sw.Elapsed;
}
for (int i = 0; i < _preSkip; i++)
{
FireLineUpdate(DiffType.None, i, -1);
}
int totalSkip = _preSkip + _postSkip;
ShowDiff(_left.Count - totalSkip, _right.Count - totalSkip);
int leftLen = _left.Count;
for (int i = _postSkip; i > 0; i--)
{
FireLineUpdate(DiffType.None, leftLen - i, -1);
}
}
/// <summary>
/// This method is an optimization that
/// skips matching elements at the end of the
/// two arrays being diff'ed.
/// Care's taken so that this will never
/// overlap with the pre-skip.
/// </summary>
private void CalculatePostSkip()
{
int leftLen = _left.Count;
int rightLen = _right.Count;
while (_postSkip < leftLen && _postSkip < rightLen &&
_postSkip < (leftLen - _preSkip) &&
_compareFunc(_left[leftLen - _postSkip - 1], _right[rightLen - _postSkip - 1]))
{
_postSkip++;
}
}
/// <summary>
/// This method is an optimization that
/// skips matching elements at the start of
/// the arrays being diff'ed
/// </summary>
private void CalculatePreSkip()
{
int leftLen = _left.Count;
int rightLen = _right.Count;
while (_preSkip < leftLen && _preSkip < rightLen &&
_compareFunc(_left[_preSkip], _right[_preSkip]))
{
_preSkip++;
}
}
/// <summary>
/// This traverses the elements using the LCS matrix
/// and fires appropriate events for added, subtracted,
/// and unchanged lines.
/// It's recursively called till we run out of items.
/// </summary>
/// <param name="leftIndex"></param>
/// <param name="rightIndex"></param>
private void ShowDiff(int leftIndex, int rightIndex)
{
if (leftIndex > 0 && rightIndex > 0 &&
_compareFunc(_left[_preSkip + leftIndex - 1], _right[_preSkip + rightIndex - 1]))
{
ShowDiff(leftIndex - 1, rightIndex - 1);
FireLineUpdate(DiffType.None, _preSkip + leftIndex - 1, -1);
}
else
{
if (rightIndex > 0 &&
(leftIndex == 0 ||
_matrix[leftIndex, rightIndex - 1] >= _matrix[leftIndex - 1, rightIndex]))
{
ShowDiff(leftIndex, rightIndex - 1);
FireLineUpdate(DiffType.Inserted, -1, _preSkip + rightIndex - 1);
}
else if (leftIndex > 0 &&
(rightIndex == 0 ||
_matrix[leftIndex, rightIndex - 1] < _matrix[leftIndex - 1, rightIndex]))
{
ShowDiff(leftIndex - 1, rightIndex);
FireLineUpdate(DiffType.Deleted, _preSkip + leftIndex - 1, -1);
}
}
}
/// <summary>
/// This is the core method in the entire class,
/// and uses the standard LCS calculation algorithm.
/// </summary>
private void CreateLCSMatrix()
{
int totalSkip = _preSkip + _postSkip;
if (totalSkip >= _left.Count || totalSkip >= _right.Count)
return;
// We only create a matrix large enough for the
// unskipped contents of the diff'ed arrays
_matrix = new int[_left.Count - totalSkip + 1,_right.Count - totalSkip + 1];
for (int i = 1; i <= _left.Count - totalSkip; i++)
{
// Simple optimization to avoid this calculation
// inside the outer loop (may have got JIT optimized
// but my tests showed a minor improvement in speed)
int leftIndex = _preSkip + i - 1;
// Again, instead of calculating the adjusted index inside
// the loop, I initialize it under the assumption that
// incrementing will be a faster operation on most CPUs
// compared to addition. Again, this may have got JIT
// optimized but my tests showed a minor speed difference.
for (int j = 1, rightIndex = _preSkip + 1; j <= _right.Count - totalSkip; j++, rightIndex++)
{
_matrix[i, j] = _compareFunc(_left[leftIndex], _right[rightIndex - 1])
? _matrix[i - 1, j - 1] + 1
: Math.Max(_matrix[i, j - 1], _matrix[i - 1, j]);
}
}
_matrixCreated = true;
}
private void FireLineUpdate(DiffType diffType, int leftIndex, int rightIndex)
{
var local = this.LineUpdate;
if (local == null)
return;
T lineValue = leftIndex >= 0 ? _left[leftIndex] : _right[rightIndex];
local(this, new DiffEventArgs<T>(diffType, lineValue, leftIndex, rightIndex));
}
private void InitializeCompareFunc()
{
// Special case for String types
if (typeof (T) == typeof (String))
{
_compareFunc = StringCompare;
}
else
{
_compareFunc = DefaultCompare;
}
}
/// <summary>
/// This comparison is specifically
/// for strings, and was nearly thrice as
/// fast as the default comparison operation.
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
private bool StringCompare(T left, T right)
{
return Object.Equals(left, right);
}
private bool DefaultCompare(T left, T right)
{
return left.Equals(right);
}
}
[Flags]
public enum DiffType
{
None = 0,
Inserted = 1,
Deleted = 2
}
public class DiffEventArgs<T> : EventArgs
{
public DiffType DiffType { get; set; }
public T LineValue { get; private set; }
public int LeftIndex { get; private set; }
public int RightIndex { get; private set; }
public DiffEventArgs(DiffType diffType, T lineValue, int leftIndex, int rightIndex)
{
this.DiffType = diffType;
this.LineValue = lineValue;
this.LeftIndex = leftIndex;
this.RightIndex = rightIndex;
}
}
/// <summary>
/// Line of file
/// </summary>
public class Line
{
/// <summary>
/// Source string
/// </summary>
public readonly string line;
/// <summary>
/// Inserted strings
/// </summary>
public Lines subLines;
/// <summary>
/// Line state
/// </summary>
public DiffType state;
public Line(string line)
{
this.line = line;
}
/// <summary>
/// Equals
/// </summary>
public override bool Equals(object obj)
{
return Object.Equals(line, ((Line) obj).line);
}
public static bool operator ==(Line line1, Line line2)
{
return Object.Equals(line1.line, line2.line);
}
public static bool operator !=(Line line1, Line line2)
{
return !Object.Equals(line1.line, line2.line);
}
public override string ToString()
{
return line;
}
}
/// <summary>
/// File as list of lines
/// </summary>
public class Lines : List<Line>, IEquatable<Lines>
{
//эта строка нужна для хранения строк, вставленных в самом начале, до первой строки исходного файла
private Line fictiveLine = new Line("===fictive line===") {state = DiffType.Deleted};
public Lines()
{
}
public Lines(int capacity)
: base(capacity)
{
}
public Line this[int i]
{
get
{
if (i == -1) return fictiveLine;
return base[i];
}
set
{
if (i == -1) fictiveLine = value;
base[i] = value;
}
}
/// <summary>
/// Load from file
/// </summary>
public static Lines Load(string fileName, Encoding enc = null)
{
Lines lines = new Lines();
foreach (var line in File.ReadAllLines(fileName, enc ?? Encoding.Default))
lines.Add(new Line(line));
return lines;
}
/// <summary>
/// Merge lines
/// </summary>
public void Merge(Lines lines)
{
SimpleDiff<Line> diff = new SimpleDiff<Line>(this, lines);
int iLine = -1;
diff.LineUpdate += (o, e) =>
{
if (e.DiffType == DiffType.Inserted)
{
if (this[iLine].subLines == null)
this[iLine].subLines = new Lines();
e.LineValue.state = DiffType.Inserted;
this[iLine].subLines.Add(e.LineValue);
}
else
{
iLine++;
this[iLine].state = e.DiffType;
if (iLine > 0 &&
this[iLine - 1].state == DiffType.Deleted &&
this[iLine - 1].subLines == null &&
e.DiffType == DiffType.None)
this[iLine - 1].subLines = new Lines();
}
};
//запускаем алгоритм нахождения максимальной подпоследовательности (LCS)
diff.RunDiff();
}
/// <summary>
/// Clone
/// </summary>
public Lines Clone()
{
Lines result = new Lines(this.Count);
foreach (var line in this)
result.Add(new Line(line.line));
return result;
}
/// <summary>
/// Is lines equal?
/// </summary>
public bool Equals(Lines other)
{
if (Count != other.Count)
return false;
for (int i = 0; i < Count; i++)
if (this[i] != other[i])
return false;
return true;
}
/// <summary>
/// Transform tree to list
/// </summary>
public Lines Expand()
{
return Expand(-1, Count - 1);
}
/// <summary>
/// Transform tree to list
/// </summary>
public Lines Expand(int from, int to)
{
Lines result = new Lines();
for (int i = from; i <= to; i++)
{
if (this[i].state != DiffType.Deleted)
result.Add(this[i]);
if (this[i].subLines != null)
result.AddRange(this[i].subLines.Expand());
}
return result;
}
}
/// <summary>
/// Строка, содержащая несколько конфликтных версий
/// </summary>
public class ConflictedLine : Line
{
public readonly Lines version1;
public readonly Lines version2;
public ConflictedLine(Lines version1, Lines version2)
: base("?")
{
this.version1 = version1;
this.version2 = version2;
}
}
}
#endregion
}