-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiff.cpp
More file actions
2337 lines (2104 loc) · 67.4 KB
/
diff.cpp
File metadata and controls
2337 lines (2104 loc) · 67.4 KB
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
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/***************************************************************************
diff.cpp - description
-------------------
begin : Mon Mar 18 2002
copyright : (C) 2002-2007 by Joachim Eibl
email : joachim.eibl at gmx.de
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "stable.h"
#include <cstdlib>
#include "diff.h"
#include "fileaccess.h"
#include "gnudiff_diff.h"
#include "options.h"
#include "progress.h"
#include <kmessagebox.h>
#include <klocale.h>
#include <QFileInfo>
#include <QDir>
#include <QTextCodec>
#include <QTextStream>
#include <QProcess>
#include <map>
#include <assert.h>
#include <ctype.h>
#include <iostream>
using namespace std;
int LineData::width(int tabSize) const
{
int w=0;
int j=0;
for( int i=0; i<size; ++i )
{
if ( pLine[i]=='\t' )
{
for(j %= tabSize; j<tabSize; ++j)
++w;
j=0;
}
else
{
++w;
++j;
}
}
return w;
}
// The bStrict flag is true during the test where a nonmatching area ends.
// Then the equal()-function requires that the match has more than 2 nonwhite characters.
// This is to avoid matches on trivial lines (e.g. with white space only).
// This choice is good for C/C++.
bool equal( const LineData& l1, const LineData& l2, bool bStrict )
{
if ( l1.pLine==0 || l2.pLine==0) return false;
if ( bStrict && g_bIgnoreTrivialMatches )//&& (l1.occurances>=5 || l2.occurances>=5) )
return false;
// Ignore white space diff
const QChar* p1 = l1.pLine;
const QChar* p1End = p1 + l1.size;
const QChar* p2 = l2.pLine;
const QChar* p2End = p2 + l2.size;
if ( g_bIgnoreWhiteSpace )
{
int nonWhite = 0;
for(;;)
{
while( isWhite( *p1 ) && p1!=p1End ) ++p1;
while( isWhite( *p2 ) && p2!=p2End ) ++p2;
if ( p1 == p1End && p2 == p2End )
{
if ( bStrict && g_bIgnoreTrivialMatches )
{ // Then equality is not enough
return nonWhite>2;
}
else // equality is enough
return true;
}
else if ( p1 == p1End || p2 == p2End )
return false;
if( *p1 != *p2 )
return false;
++p1;
++p2;
++nonWhite;
}
}
else
{
if ( l1.size==l2.size && memcmp(p1, p2, l1.size)==0)
return true;
else
return false;
}
}
static bool isLineOrBufEnd( const QChar* p, int i, int size )
{
return
i>=size // End of file
|| isEndOfLine(p[i]) // Normal end of line
// No support for Mac-end of line yet, because incompatible with GNU-diff-routines.
// || ( p[i]=='\r' && (i>=size-1 || p[i+1]!='\n')
// && (i==0 || p[i-1]!='\n') ) // Special case: '\r' without '\n'
;
}
/* Features of class SourceData:
- Read a file (from the given URL) or accept data via a string.
- Allocate and free buffers as necessary.
- Run a preprocessor, when specified.
- Run the line-matching preprocessor, when specified.
- Run other preprocessing steps: Uppercase, ignore comments,
remove carriage return, ignore numbers.
Order of operation:
1. If data was given via a string then save it to a temp file. (see setData())
2. If the specified file is nonlocal (URL) copy it to a temp file.
3. If a preprocessor was specified, run the input file through it.
4. Read the output of the preprocessor.
5. If Uppercase was specified: Turn the read data to uppercase.
6. Write the result to a temp file.
7. If a line-matching preprocessor was specified, run the temp file through it.
8. Read the output of the line-matching preprocessor.
9. If ignore numbers was specified, strip the LMPP-output of all numbers.
10. If ignore comments was specified, strip the LMPP-output of comments.
Optimizations: Skip unneeded steps.
*/
SourceData::SourceData()
{
m_pOptions = 0;
reset();
}
SourceData::~SourceData()
{
reset();
}
void SourceData::reset()
{
m_pEncoding = 0;
m_fileAccess = FileAccess();
m_normalData.reset();
m_lmppData.reset();
if ( !m_tempInputFileName.isEmpty() )
{
FileAccess::removeFile( m_tempInputFileName );
m_tempInputFileName = "";
}
}
void SourceData::setFilename( const QString& filename )
{
if (filename.isEmpty())
{
reset();
}
else
{
FileAccess fa( filename );
setFileAccess( fa );
}
}
bool SourceData::isEmpty()
{
return getFilename().isEmpty();
}
bool SourceData::hasData()
{
return m_normalData.m_pBuf != 0;
}
bool SourceData::isValid()
{
return isEmpty() || hasData();
}
void SourceData::setOptions( Options* pOptions )
{
m_pOptions = pOptions;
}
QString SourceData::getFilename()
{
return m_fileAccess.absoluteFilePath();
}
QString SourceData::getAliasName()
{
return m_aliasName.isEmpty() ? m_fileAccess.prettyAbsPath() : m_aliasName;
}
void SourceData::setAliasName( const QString& name )
{
m_aliasName = name;
}
void SourceData::setFileAccess( const FileAccess& fileAccess )
{
m_fileAccess = fileAccess;
m_aliasName = QString();
if ( !m_tempInputFileName.isEmpty() )
{
FileAccess::removeFile( m_tempInputFileName );
m_tempInputFileName = "";
}
}
void SourceData::setEncoding(QTextCodec* pEncoding)
{
m_pEncoding = pEncoding;
}
QStringList SourceData::setData( const QString& data )
{
QStringList errors;
// Create a temp file for preprocessing:
if ( m_tempInputFileName.isEmpty() )
{
m_tempInputFileName = FileAccess::tempFileName();
}
FileAccess f( m_tempInputFileName );
QByteArray ba = QTextCodec::codecForName("UTF-8")->fromUnicode(data);
bool bSuccess = f.writeFile( ba.constData(), ba.length() );
if ( !bSuccess )
{
errors.append( i18n("Writing clipboard data to temp file failed.") );
}
else
{
m_aliasName = i18n("From Clipboard");
m_fileAccess = FileAccess(""); // Effect: m_fileAccess.isValid() is false
}
return errors;
}
const LineData* SourceData::getLineDataForDiff() const
{
if ( m_lmppData.m_pBuf==0 )
return m_normalData.m_v.size()>0 ? &m_normalData.m_v[0] : 0;
else
return m_lmppData.m_v.size()>0 ? &m_lmppData.m_v[0] : 0;
}
const LineData* SourceData::getLineDataForDisplay() const
{
return m_normalData.m_v.size()>0 ? &m_normalData.m_v[0] : 0;
}
int SourceData::getSizeLines() const
{
return m_normalData.m_vSize;
}
int SourceData::getSizeBytes() const
{
return m_normalData.m_size;
}
const char* SourceData::getBuf() const
{
return m_normalData.m_pBuf;
}
const QString& SourceData::getText() const
{
return m_normalData.m_unicodeBuf;
}
bool SourceData::isText()
{
return m_normalData.m_bIsText;
}
bool SourceData::isIncompleteConversion()
{
return m_normalData.m_bIncompleteConversion;
}
bool SourceData::isFromBuffer()
{
return !m_fileAccess.isValid();
}
bool SourceData::isBinaryEqualWith( const SourceData& other ) const
{
return m_fileAccess.exists() && other.m_fileAccess.exists() &&
getSizeBytes() == other.getSizeBytes() &&
( getSizeBytes()==0 || memcmp( getBuf(), other.getBuf(), getSizeBytes() )==0 );
}
void SourceData::FileData::reset()
{
delete[] (char*)m_pBuf;
m_pBuf = 0;
m_v.clear();
m_size = 0;
m_vSize = 0;
m_bIsText = true;
m_bIncompleteConversion = false;
m_eLineEndStyle = eLineEndStyleUndefined;
}
bool SourceData::FileData::readFile( const QString& filename )
{
reset();
if ( filename.isEmpty() ) { return true; }
FileAccess fa( filename );
m_size = fa.sizeForReading();
char* pBuf;
m_pBuf = pBuf = new char[m_size+100]; // Alloc 100 byte extra: Savety hack, not nice but does no harm.
// Some extra bytes at the end of the buffer are needed by
// the diff algorithm. See also GnuDiff::diff_2_files().
bool bSuccess = fa.readFile( pBuf, m_size );
if ( !bSuccess )
{
delete pBuf;
m_pBuf = 0;
m_size = 0;
}
return bSuccess;
}
bool SourceData::saveNormalDataAs( const QString& fileName )
{
return m_normalData.writeFile( fileName );
}
bool SourceData::FileData::writeFile( const QString& filename )
{
if ( filename.isEmpty() ) { return true; }
FileAccess fa( filename );
bool bSuccess = fa.writeFile(m_pBuf, m_size);
return bSuccess;
}
void SourceData::FileData::copyBufFrom( const FileData& src )
{
reset();
char* pBuf;
m_size = src.m_size;
m_pBuf = pBuf = new char[m_size+100];
memcpy( pBuf, src.m_pBuf, m_size );
}
// Convert the input file from input encoding to output encoding and write it to the output file.
static bool convertFileEncoding( const QString& fileNameIn, QTextCodec* pCodecIn,
const QString& fileNameOut, QTextCodec* pCodecOut )
{
QFile in( fileNameIn );
if ( ! in.open(QIODevice::ReadOnly ) )
return false;
QTextStream inStream( &in );
inStream.setCodec( pCodecIn );
inStream.setAutoDetectUnicode( false );
QFile out( fileNameOut );
if ( ! out.open( QIODevice::WriteOnly ) )
return false;
QTextStream outStream( &out );
outStream.setCodec( pCodecOut );
QString data = inStream.readAll();
outStream << data;
return true;
}
static QTextCodec* getEncodingFromTag( const QByteArray& s, const QByteArray& encodingTag )
{
int encodingPos = s.indexOf( encodingTag );
if ( encodingPos>=0 )
{
int apostrophPos = s.indexOf( '"', encodingPos + encodingTag.length() );
int apostroph2Pos = s.indexOf( '\'', encodingPos + encodingTag.length() );
char apostroph = '"';
if ( apostroph2Pos>=0 && ( apostrophPos<0 || (apostrophPos>=0 && apostroph2Pos < apostrophPos) ) )
{
apostroph = '\'';
apostrophPos = apostroph2Pos;
}
int encodingEnd = s.indexOf( apostroph, apostrophPos+1 );
if ( encodingEnd>=0 ) // e.g.: <meta charset="utf-8"> or <?xml version="1.0" encoding="ISO-8859-1"?>
{
QByteArray encoding = s.mid( apostrophPos+1, encodingEnd - (apostrophPos + 1) );
return QTextCodec::codecForName( encoding );
}
else // e.g.: <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
{
QByteArray encoding = s.mid( encodingPos+encodingTag.length(), apostrophPos - ( encodingPos+encodingTag.length() ) );
return QTextCodec::codecForName( encoding );
}
}
return 0;
}
static QTextCodec* detectEncoding( const char* buf, qint64 size, qint64& skipBytes )
{
if (size>=2)
{
if (buf[0]=='\xFF' && buf[1]=='\xFE' )
{
skipBytes = 2;
return QTextCodec::codecForName( "UTF-16LE" );
}
if (buf[0]=='\xFE' && buf[1]=='\xFF' )
{
skipBytes = 2;
return QTextCodec::codecForName( "UTF-16BE" );
}
}
if (size>=3)
{
if (buf[0]=='\xEF' && buf[1]=='\xBB' && buf[2]=='\xBF' )
{
skipBytes = 3;
return QTextCodec::codecForName( "UTF-8-BOM" );
}
}
skipBytes = 0;
QByteArray s( buf, size );
int xmlHeaderPos = s.indexOf( "<?xml" );
if ( xmlHeaderPos >= 0 )
{
int xmlHeaderEnd = s.indexOf( "?>", xmlHeaderPos );
if ( xmlHeaderEnd>=0 )
{
QTextCodec* pCodec = getEncodingFromTag( s.mid( xmlHeaderPos, xmlHeaderEnd - xmlHeaderPos ), "encoding=" );
if (pCodec)
return pCodec;
}
}
else // HTML
{
int metaHeaderPos = s.indexOf( "<meta" );
while ( metaHeaderPos >= 0)
{
int metaHeaderEnd = s.indexOf( ">", metaHeaderPos );
if (metaHeaderEnd>=0)
{
QTextCodec* pCodec = getEncodingFromTag( s.mid( metaHeaderPos, metaHeaderEnd - metaHeaderPos ), "charset=" );
if (pCodec)
return pCodec;
metaHeaderPos = s.indexOf( "<meta", metaHeaderEnd );
}
else
break;
}
}
return 0;
}
QTextCodec* SourceData::detectEncoding( const QString& fileName, QTextCodec* pFallbackCodec )
{
QFile f(fileName);
if ( f.open(QIODevice::ReadOnly) )
{
char buf[200];
qint64 size = f.read( buf, sizeof(buf) );
qint64 skipBytes = 0;
QTextCodec* pCodec = ::detectEncoding( buf, size, skipBytes );
if (pCodec)
return pCodec;
}
return pFallbackCodec;
}
/* Split the command line into arguments.
* Normally split at white space separators except when quoting with " or '.
* Backslash is treated as meta character within single quotes ' only.
* Detect parsing errors like unclosed quotes.
* The first item in the list will be the command itself.
* Returns the error reasor as string or an empty string on success.
* Eg. >"1" "2"< => >1<, >2<
* Eg. >'\'\\'< => >'\< backslash is a meta character between single quotes
* Eg. > "\\" < => >\\< but not between double quotes
* Eg. >"c:\sed" 's/a/\' /g'< => >c:\sed<, >s/a/' /g<
*/
static QString getArguments( QString cmd, QString& program, QStringList& args )
{
program = QString();
args.clear();
for ( int i=0; i<cmd.length(); ++i )
{
while ( i<cmd.length() && cmd[i].isSpace() )
{
++i;
}
if ( cmd[i]=='"' || cmd[i]=='\'' ) // argument beginning with a quote
{
QChar quoteChar = cmd[i];
++i;
int argStart = i;
bool bSkip = false;
while ( i<cmd.length() && ( cmd[i]!=quoteChar || bSkip ) )
{
if ( bSkip )
{
bSkip = false;
if ( cmd[i]=='\\' || cmd[i]==quoteChar )
{
cmd.remove( i-1, 1 ); // remove the backslash '\'
continue;
}
}
else if ( cmd[i]=='\\' && quoteChar=='\'')
bSkip = true;
++i;
}
if ( i<cmd.length() )
{
args << cmd.mid( argStart, i-argStart );
if ( i+1<cmd.length() && !cmd[i+1].isSpace() )
return i18n("Expecting space after closing apostroph.");
}
else
return i18n("Not matching apostrophs.");
continue;
}
else
{
int argStart = i;
//bool bSkip = false;
while ( i<cmd.length() && ( !cmd[i].isSpace() /*|| bSkip*/ ) )
{
/*if ( bSkip )
{
bSkip = false;
if ( cmd[i]=='\\' || cmd[i]=='"' || cmd[i]=='\'' || cmd[i].isSpace() )
{
cmd.remove( i-1, 1 ); // remove the backslash '\'
continue;
}
}
else if ( cmd[i]=='\\' )
bSkip = true;
else */
if ( cmd[i]=='"' || cmd[i]=='\'' )
return i18n("Unexpected apostroph within argument.");
++i;
}
args << cmd.mid( argStart, i-argStart );
}
}
if ( args.isEmpty() )
return i18n("No program specified.");
else
{
program = args[0];
args.pop_front();
#ifdef WIN32
if ( program=="sed" )
{
QString prg = QCoreApplication::applicationDirPath() + "/bin/sed.exe"; // in subdir bin
if ( QFile::exists( prg ) )
{
program = prg;
}
else
{
prg = QCoreApplication::applicationDirPath() + "/sed.exe"; // in same dir
if ( QFile::exists( prg ) )
{
program = prg;
}
}
}
#endif
}
return QString();
}
QStringList SourceData::readAndPreprocess( QTextCodec* pEncoding, bool bAutoDetectUnicode )
{
m_pEncoding = pEncoding;
QString fileNameIn1;
QString fileNameOut1;
QString fileNameIn2;
QString fileNameOut2;
QStringList errors;
bool bTempFileFromClipboard = !m_fileAccess.isValid();
// Detect the input for the preprocessing operations
if ( !bTempFileFromClipboard )
{
if ( m_fileAccess.isLocal() )
{
fileNameIn1 = m_fileAccess.absoluteFilePath();
}
else // File is not local: create a temporary local copy:
{
if ( m_tempInputFileName.isEmpty() ) { m_tempInputFileName = FileAccess::tempFileName(); }
m_fileAccess.copyFile(m_tempInputFileName);
fileNameIn1 = m_tempInputFileName;
}
if ( bAutoDetectUnicode )
{
m_pEncoding = detectEncoding( fileNameIn1, pEncoding );
}
}
else // The input was set via setData(), probably from clipboard.
{
fileNameIn1 = m_tempInputFileName;
m_pEncoding = QTextCodec::codecForName("UTF-8");
}
QTextCodec* pEncoding1 = m_pEncoding;
QTextCodec* pEncoding2 = m_pEncoding;
m_normalData.reset();
m_lmppData.reset();
FileAccess faIn(fileNameIn1);
int fileInSize = faIn.size();
if ( faIn.exists() ) // fileInSize > 0 )
{
#if defined(_WIN32) || defined(Q_OS_OS2)
QString catCmd = "type";
fileNameIn1.replace( '/', "\\" );
#else
QString catCmd = "cat";
#endif
// Run the first preprocessor
if ( m_pOptions->m_PreProcessorCmd.isEmpty() )
{
// No preprocessing: Read the file directly:
m_normalData.readFile( fileNameIn1 );
}
else
{
QString fileNameInPP = fileNameIn1;
if ( pEncoding1 != m_pOptions->m_pEncodingPP )
{
// Before running the preprocessor convert to the format that the preprocessor expects.
fileNameInPP = FileAccess::tempFileName();
pEncoding1 = m_pOptions->m_pEncodingPP;
convertFileEncoding( fileNameIn1, pEncoding, fileNameInPP, pEncoding1 );
}
QString ppCmd = m_pOptions->m_PreProcessorCmd;
fileNameOut1 = FileAccess::tempFileName();
QProcess ppProcess;
ppProcess.setStandardInputFile( fileNameInPP );
ppProcess.setStandardOutputFile( fileNameOut1 );
QString program;
QStringList args;
QString errorReason = getArguments(ppCmd, program, args);
if ( errorReason.isEmpty() )
{
ppProcess.start( program, args );
ppProcess.waitForFinished(-1);
}
else
errorReason = "\n("+errorReason+")";
//QString cmd = catCmd + " \"" + fileNameInPP + "\" | " + ppCmd + " >\"" + fileNameOut1+"\"";
//::system( encodeString(cmd) );
bool bSuccess = errorReason.isEmpty() && m_normalData.readFile( fileNameOut1 );
if ( fileInSize >0 && ( !bSuccess || m_normalData.m_size==0 ) )
{
errors.append(
i18n("Preprocessing possibly failed. Check this command:\n\n %1"
"\n\nThe preprocessing command will be disabled now."
).arg(ppCmd) + errorReason );
m_pOptions->m_PreProcessorCmd = "";
m_normalData.readFile( fileNameIn1 );
pEncoding1 = m_pEncoding;
}
if (fileNameInPP != fileNameIn1)
{
FileAccess::removeTempFile( fileNameInPP );
}
}
// LineMatching Preprocessor
if ( ! m_pOptions->m_LineMatchingPreProcessorCmd.isEmpty() )
{
fileNameIn2 = fileNameOut1.isEmpty() ? fileNameIn1 : fileNameOut1;
QString fileNameInPP = fileNameIn2;
pEncoding2 = pEncoding1;
if ( pEncoding2 != m_pOptions->m_pEncodingPP )
{
// Before running the preprocessor convert to the format that the preprocessor expects.
fileNameInPP = FileAccess::tempFileName();
pEncoding2 = m_pOptions->m_pEncodingPP;
convertFileEncoding( fileNameIn2, pEncoding1, fileNameInPP, pEncoding2 );
}
QString ppCmd = m_pOptions->m_LineMatchingPreProcessorCmd;
fileNameOut2 = FileAccess::tempFileName();
QProcess ppProcess;
ppProcess.setStandardInputFile( fileNameInPP );
ppProcess.setStandardOutputFile( fileNameOut2 );
QString program;
QStringList args;
QString errorReason = getArguments(ppCmd, program, args);
if ( errorReason.isEmpty() )
{
ppProcess.start( program, args );
ppProcess.waitForFinished(-1);
}
else
errorReason = "\n("+errorReason+")";
//QString cmd = catCmd + " \"" + fileNameInPP + "\" | " + ppCmd + " >\"" + fileNameOut2 + "\"";
//::system( encodeString(cmd) );
bool bSuccess = errorReason.isEmpty() && m_lmppData.readFile( fileNameOut2 );
if ( FileAccess(fileNameIn2).size()>0 && ( !bSuccess || m_lmppData.m_size==0 ) )
{
errors.append(
i18n("The line-matching-preprocessing possibly failed. Check this command:\n\n %1"
"\n\nThe line-matching-preprocessing command will be disabled now."
).arg(ppCmd) + errorReason );
m_pOptions->m_LineMatchingPreProcessorCmd = "";
m_lmppData.readFile( fileNameIn2 );
}
FileAccess::removeTempFile( fileNameOut2 );
if (fileNameInPP != fileNameIn2)
{
FileAccess::removeTempFile( fileNameInPP );
}
}
else if ( m_pOptions->m_bIgnoreComments || m_pOptions->m_bIgnoreCase )
{
// We need a copy of the normal data.
m_lmppData.copyBufFrom( m_normalData );
}
else
{ // We don't need any lmpp data at all.
m_lmppData.reset();
}
}
m_normalData.preprocess( m_pOptions->m_bPreserveCarriageReturn, pEncoding1 );
m_lmppData.preprocess( false, pEncoding2 );
if ( m_lmppData.m_vSize < m_normalData.m_vSize )
{
// This probably is the fault of the LMPP-Command, but not worth reporting.
m_lmppData.m_v.resize( m_normalData.m_vSize );
for(int i=m_lmppData.m_vSize; i<m_normalData.m_vSize; ++i )
{ // Set all empty lines to point to the end of the buffer.
m_lmppData.m_v[i].pLine = m_lmppData.m_unicodeBuf.unicode()+m_lmppData.m_unicodeBuf.length();
}
m_lmppData.m_vSize = m_normalData.m_vSize;
}
// Internal Preprocessing: Uppercase-conversion
if ( m_pOptions->m_bIgnoreCase )
{
int i;
QChar* pBuf = const_cast<QChar*>(m_lmppData.m_unicodeBuf.unicode());
int ucSize = m_lmppData.m_unicodeBuf.length();
for(i=0; i<ucSize; ++i)
{
pBuf[i] = pBuf[i].toUpper();
}
}
// Ignore comments
if ( m_pOptions->m_bIgnoreComments )
{
m_lmppData.removeComments();
int vSize = min2(m_normalData.m_vSize, m_lmppData.m_vSize);
for(int i=0; i<vSize; ++i )
{
m_normalData.m_v[i].bContainsPureComment = m_lmppData.m_v[i].bContainsPureComment;
}
}
// Remove unneeded temporary files. (A temp file from clipboard must not be deleted.)
if ( !bTempFileFromClipboard && !m_tempInputFileName.isEmpty() )
{
FileAccess::removeTempFile( m_tempInputFileName );
m_tempInputFileName = "";
}
if ( !fileNameOut1.isEmpty() )
{
FileAccess::removeTempFile( fileNameOut1 );
fileNameOut1="";
}
return errors;
}
/** Prepare the linedata vector for every input line.*/
void SourceData::FileData::preprocess( bool bPreserveCR, QTextCodec* pEncoding )
{
//m_unicodeBuf = decodeString( m_pBuf, m_size, eEncoding );
qint64 i;
// detect line end style
QVector<e_LineEndStyle> vOrigDataLineEndStyle;
m_eLineEndStyle = eLineEndStyleUndefined;
for( i=0; i<m_size; ++i )
{
if ( m_pBuf[i]=='\r' )
{
if ( i+1<m_size && m_pBuf[i+1]=='\n' ) // not 16-bit unicode
{
vOrigDataLineEndStyle.push_back( eLineEndStyleDos );
++i;
}
else if( i>0 && i+2<m_size && m_pBuf[i-1]=='\0' && m_pBuf[i+1]=='\0' && m_pBuf[i+2]=='\n' ) // 16-bit unicode
{
vOrigDataLineEndStyle.push_back( eLineEndStyleDos );
i+=2;
}
else // old mac line end style ?
{
vOrigDataLineEndStyle.push_back( eLineEndStyleUndefined );
const_cast<char*>(m_pBuf)[i]='\n'; // fix it in original data
}
}
else if ( m_pBuf[i]=='\n' )
{
vOrigDataLineEndStyle.push_back( eLineEndStyleUnix );
}
}
if ( ! vOrigDataLineEndStyle.isEmpty() )
m_eLineEndStyle = vOrigDataLineEndStyle[0];
qint64 skipBytes = 0;
QTextCodec* pCodec = ::detectEncoding( m_pBuf, m_size, skipBytes );
if ( pCodec != pEncoding )
skipBytes=0;
QByteArray ba = QByteArray::fromRawData( m_pBuf+skipBytes, m_size-skipBytes );
QTextStream ts( ba, QIODevice::ReadOnly | QIODevice::Text );
ts.setCodec( pEncoding);
ts.setAutoDetectUnicode( false );
m_unicodeBuf = ts.readAll();
ba.clear();
int ucSize = m_unicodeBuf.length();
const QChar* p = m_unicodeBuf.unicode();
m_bIsText = true;
int lines = 1;
m_bIncompleteConversion = false;
for( i=0; i<ucSize; ++i )
{
if ( i>=ucSize || p[i]=='\n' )
{
++lines;
}
if ( p[i]=='\0' )
{
m_bIsText = false;
}
if ( p[i]==QChar::ReplacementCharacter )
{
m_bIncompleteConversion = true;
}
}
m_v.resize( lines+5 );
int lineIdx=0;
int lineLength=0;
bool bNonWhiteFound = false;
int whiteLength = 0;
for( i=0; i<=ucSize; ++i )
{
if ( i>=ucSize || p[i]=='\n' )
{
m_v[lineIdx].pLine = &p[ i-lineLength ];
while ( /*!bPreserveCR &&*/ lineLength>0 && m_v[lineIdx].pLine[lineLength-1]=='\r' )
{
--lineLength;
}
m_v[lineIdx].pFirstNonWhiteChar = m_v[lineIdx].pLine + min2(whiteLength,lineLength);
m_v[lineIdx].size = lineLength;
if ( lineIdx < vOrigDataLineEndStyle.count() && bPreserveCR && i<ucSize)
{
++m_v[lineIdx].size;
const_cast<QChar*>(m_v[lineIdx].pLine)[lineLength] = '\r';
//switch ( vOrigDataLineEndStyle[lineIdx] )
//{
//case eLineEndStyleUnix: const_cast<QChar*>(m_v[lineIdx].pLine)[lineLength] = '\n'; break;
//case eLineEndStyleDos: const_cast<QChar*>(m_v[lineIdx].pLine)[lineLength] = '\r'; break;
//case eLineEndStyleUndefined: const_cast<QChar*>(m_v[lineIdx].pLine)[lineLength] = '\x0b'; break;
//}
}
lineLength = 0;
bNonWhiteFound = false;
whiteLength = 0;
++lineIdx;
}
else
{
++lineLength;
if ( ! bNonWhiteFound && isWhite( p[i] ) )
++whiteLength;
else
bNonWhiteFound = true;
}
}
assert( lineIdx == lines );
m_vSize = lines;
}
// Must not be entered, when within a comment.
// Returns either at a newline-character p[i]=='\n' or when i==size.
// A line that contains only comments is still "white".
// Comments in white lines must remain, while comments in
// non-white lines are overwritten with spaces.
static void checkLineForComments(
QChar* p, // pointer to start of buffer
int& i, // index of current position (in, out)
int size, // size of buffer
bool& bWhite, // false if this line contains nonwhite characters (in, out)
bool& bCommentInLine, // true if any comment is within this line (in, out)
bool& bStartsOpenComment // true if the line ends within an comment (out)
)
{
bStartsOpenComment = false;
for(; i<size; ++i )
{
// A single apostroph ' has prio over a double apostroph " (e.g. '"')
// (if not in a string)
if ( p[i]=='\'' )
{
bWhite = false;
++i;
for( ; !isLineOrBufEnd(p,i,size) && p[i]!='\''; ++i)
;
if (p[i]=='\'') ++i;
}
// Strings have priority over comments: e.g. "/* Not a comment, but a string. */"
else if ( p[i]=='"' )
{
bWhite = false;
++i;
for( ; !isLineOrBufEnd(p,i,size) && !(p[i]=='"' && p[i-1]!='\\'); ++i)
;
if (p[i]=='"') ++i;
}
// C++-comment
else if ( p[i]=='/' && i+1<size && p[i+1] =='/' )
{
int commentStart = i;
bCommentInLine = true;
i+=2;
for( ; !isLineOrBufEnd(p,i,size); ++i)
;
if ( !bWhite )