This repository was archived by the owner on Feb 20, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathwxscoder.cpp
More file actions
639 lines (553 loc) · 18.6 KB
/
Copy pathwxscoder.cpp
File metadata and controls
639 lines (553 loc) · 18.6 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
/*
* This file is part of wxSmith plugin for Code::Blocks Studio
* Copyright (C) 2006-2007 Bartlomiej Swiecki
*
* wxSmith 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 3 of the License, or
* (at your option) any later version.
*
* wxSmith is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with wxSmith. If not, see <http://www.gnu.org/licenses/>.
*
* $Revision$
* $Id$
* $HeadURL$
*/
#include "wxscoder.h"
#include <manager.h>
#include <editormanager.h>
#include <configmanager.h>
#include <logmanager.h>
#include <filemanager.h>
#include <encodingdetector.h>
#include <globals.h>
#include <wx/file.h>
#include <wx/intl.h>
#include "cbstyledtextctrl.h"
#include <editormanager.h>
#include <projectmanager.h>
#include <pluginmanager.h>
#include "sdk_events.h"
//namespace
//{
// EncodingDetector* LoadFile(const wxString& FileName)
// {
// if ( !wxFileExists(FileName) ) return nullptr;
//
// LoaderBase* Loader = FileManager::Get()->Load(FileName,false);
// if ( !Loader ) return nullptr;
//
// EncodingDetector* Detector = new EncodingDetector(Loader);
// delete Loader;
//
// if ( !Detector->IsOK() )
// {
// delete Detector;
// return nullptr;
// }
//
// return Detector;
// }
//}
static wxsCoder SingletonObject;
wxsCoder* wxsCoder::Singleton = &SingletonObject;
wxsCoder::wxsCoder()
{
FlushTimer.SetOwner(this,1);
Connect(wxEVT_TIMER,(wxObjectEventFunction)&wxsCoder::FlushTimerEvent);
}
wxsCoder::~wxsCoder()
{
FlushAll();
}
void wxsCoder::AddCode(const wxString& FileName,const wxString& Header,const wxString& End,const wxString& Code,bool Immediately,bool CodeHasHeader,bool CodeHasEnd)
{
wxMutexLocker Lock(DataMutex);
wxString FixedFileName = NormalizeFileName(FileName);
if ( FixedFileName.IsEmpty() )
{
return;
}
// Find changing file
int Index = CodeChangesFiles.Index(FileName);
if ( Index==wxNOT_FOUND )
{
Index = CodeChangesFiles.Count();
CodeChangesFiles.Add(FileName);
CodeChanges.Add(0);
}
// Add entry to list of waiting changes
CodeChange* Change = new CodeChange;
Change->Header = Header;
Change->End = End;
Change->Code = Code;
Change->CodeHasHeader = CodeHasHeader;
Change->CodeHasEnd = CodeHasEnd;
Change->Next = CodeChanges[Index];
CodeChanges[Index] = Change;
// If the change has already been put onto queue, delete it
for ( CodeChange *Prev=Change, *This=Prev->Next; This; Prev=This, This=This->Next )
{
if ( This->Header==Header && This->End==End )
{
Prev->Next = This->Next;
delete This;
This = Prev;
}
}
if ( Immediately )
{
FlushFile(FixedFileName);
}
}
wxString wxsCoder::GetCode(const wxString& FileName,const wxString& Header,const wxString& End,bool IncludeHeader,bool IncludeEnd)
{
wxMutexLocker Lock(DataMutex);
wxString FixedFileName = NormalizeFileName(FileName);
FlushFile(FixedFileName);
int TabSize = Manager::Get()->GetConfigManager(_T("editor"))->ReadInt(_T("/tab_size"), 4);
// Checking if editor is opened
EditorManager* EM = Manager::Get()->GetEditorManager();
assert ( EM != 0 );
cbEditor* Editor = EM->GetBuiltinEditor(FixedFileName);
if ( Editor )
{
cbStyledTextCtrl* Ctrl = Editor->GetControl();
Ctrl->SetSearchFlags(wxSCI_FIND_MATCHCASE);
Ctrl->SetTargetStart(0);
Ctrl->SetTargetEnd(Ctrl->GetLength());
int Position = Ctrl->SearchInTarget(Header);
if ( Position == -1 ) return _T("");
// Counting number of indentation spaces which will be removed at
// the beginning of each line
int SpacesCut = 0;
int SpacesPos = Position;
while ( --SpacesPos >= 0 )
{
wxChar ch = Ctrl->GetCharAt(SpacesPos);
if ( ch == _T('\t') ) SpacesCut += TabSize;
else if ( (ch==_T('\n')) || (ch==_T('\r')) ) break;
else SpacesCut++;
}
Ctrl->SetTargetStart(Position);
Ctrl->SetTargetEnd(Ctrl->GetLength());
int EndPosition = Ctrl->SearchInTarget(End);
if ( EndPosition == -1 ) return _T("");
// Fixing up positions to include / exclude header and/or ending sequence
if ( !IncludeHeader ) Position += Header.Length();
if ( IncludeEnd ) EndPosition += End.Length();
return CutSpaces(Ctrl->GetTextRange(Position,EndPosition),SpacesCut);
}
else
{
EncodingDetector Detector(FixedFileName);
if ( !Detector.IsOK() ) return _T("");
wxString Content = Detector.GetWxStr();
int Position = Content.First(Header);
if ( Position == -1 ) return _T("");
int SpacesCut = 0;
int SpacesPos = Position;
while ( --SpacesPos >= 0 )
{
wxChar ch = Content.GetChar(SpacesPos);
if ( ch == _T('\t') ) SpacesCut += TabSize;
else if ( (ch==_T('\n')) || (ch==_T('\r')) ) break;
else SpacesCut++;
}
if ( !IncludeHeader ) Position += Header.Length();
Content.Remove(0,Position);
int EndPosition = Content.First(End);
if ( EndPosition == -1 ) return _T("");
if ( IncludeEnd ) EndPosition += End.Length();
Content.Remove(EndPosition);
return CutSpaces(Content,SpacesCut);
}
}
wxString wxsCoder::GetFullCode(const wxString& FileName,wxFontEncoding& Encoding,bool &UseBOM)
{
wxMutexLocker Lock(DataMutex);
wxString FixedFileName = NormalizeFileName(FileName);
FlushFile(FixedFileName);
// Checking if editor is opened
EditorManager* EM = Manager::Get()->GetEditorManager();
assert ( EM != 0 );
cbEditor* Editor = EM->GetBuiltinEditor(FixedFileName);
if ( Editor )
{
Encoding = Editor->GetEncoding();
UseBOM = Editor->GetUseBom();
cbStyledTextCtrl* Ctrl = Editor->GetControl();
return Ctrl->GetText();
}
else
{
EncodingDetector Detector(FixedFileName);
Encoding = Detector.GetFontEncoding();
UseBOM = Detector.GetBOMSizeInBytes() > 0;
return Detector.IsOK() ? Detector.GetWxStr() : _T("");
}
}
void wxsCoder::PutFullCode(const wxString& FileName,const wxString& Code,wxFontEncoding Encoding,bool UseBOM)
{
wxMutexLocker Lock(DataMutex);
wxString FixedFileName = NormalizeFileName(FileName);
int Index = CodeChangesFiles.Index(FixedFileName);
if ( Index != wxNOT_FOUND )
{
for ( CodeChange* Change=CodeChanges[Index]; Change; )
{
CodeChange* Next = Change->Next;
delete Change;
Change = Next;
}
CodeChanges[Index] = 0;
}
// Searching for file in opened file list
EditorManager* EM = Manager::Get()->GetEditorManager();
assert ( EM != 0 );
cbEditor* Editor = EM->GetBuiltinEditor(FixedFileName);
if ( Editor )
{
Editor->GetControl()->SetText(Code);
}
else
{
if ( !cbSaveToFile(FixedFileName,Code,Encoding,UseBOM) )
{
Manager::Get()->GetLogManager()->Log(F(_("wxSmith: Couldn't write file '%s'"),FixedFileName.wx_str()));
}
}
}
void wxsCoder::FlushFile(const wxString& FileName)
{
int Index = CodeChangesFiles.Index(FileName);
if ( Index == wxNOT_FOUND ) return;
CodeChange* Changes = CodeChanges[Index];
if ( !Changes ) return;
// Searching for file in opened file list
EditorManager* EM = Manager::Get()->GetEditorManager();
assert ( EM != 0 );
cbEditor* Editor = EM->GetBuiltinEditor(FileName);
if ( Editor )
{
while ( Changes )
{
CodeChange* Next = Changes->Next;
ApplyChangesEditor(Editor,Changes->Header,Changes->End,Changes->Code,Changes->CodeHasHeader,Changes->CodeHasEnd);
delete Changes;
Changes = Next;
}
}
else
{
// Reading file content
bool HasChanged = false;
//wxStopWatch SW;
EncodingDetector Detector(FileName);
if ( !Detector.IsOK() )
{
Manager::Get()->GetLogManager()->Log(F(_("wxSmith: Couldn't open and properly read file '%s'"),FileName.wx_str()));
return;
}
//Manager::Get()->GetLogManager()->DebugLog(F(_T("File read time: %d ms"),SW.Time()));
wxString Content = Detector.GetWxStr();
while ( Changes )
{
CodeChange* Next = Changes->Next;
ApplyChangesString(Content,Changes->Header,Changes->End,Changes->Code,Changes->CodeHasHeader,Changes->CodeHasEnd,HasChanged);
delete Changes;
Changes = Next;
}
if ( HasChanged )
{
// Storing the result
//wxStopWatch SW;
if ( !cbSaveToFile(FileName,Content,Detector.GetFontEncoding(),Detector.GetBOMSizeInBytes()>0) )
{
Manager::Get()->GetLogManager()->Log(F(_("wxSmith: Couldn't write data to file '%s'"),FileName.wx_str()));
}
else
{
CodeBlocksEvent event(cbEVT_PROJECT_FILE_CHANGED);
event.SetString(FileName);
Manager::Get()->GetPluginManager()->NotifyPlugins(event);
}
//Manager::Get()->GetLogManager()->DebugLog(F(_T("File write time: %d ms"),SW.Time()));
}
}
CodeChanges[Index] = 0;
}
void wxsCoder::GetLineEndingIndentation(const wxString& line, wxString& indentation, wxString& lineending)
{
const size_t length = line.length();
// Fetching indentation
if(cbDetectTabStrAutomatically() && !line.IsEmpty() )
{
wxString BaseIndentation;
size_t IndentPos = length;
while ( --IndentPos >= 0 )
{
wxChar ch = line.GetChar(IndentPos);
if ( (ch == _T('\n')) || (ch == _T('\r')) ) break;
}
while ( ++IndentPos < length )
{
wxChar ch = line.GetChar(IndentPos);
BaseIndentation.Append(
( ch == _T('\t') ) ? _T('\t') : _T(' '));
}
indentation = BaseIndentation;
}
else {
indentation = cbGetTabStr();
}
if ( cbEnsureLineEndingConsistency() && !line.IsEmpty() )
{
// Detecting EOL style in source
for ( int i=0; i<length; i++ )
{
wxChar ch = line.GetChar(i);
if ( ch==_T('\n') || ch==_T('\r') )
{
lineending = ch;
if ( ++i < length )
{
wxChar ch2 = line.GetChar(i);
if ( (ch2==_T('\n') || ch2==_T('\r')) && ch!=ch2 )
{
lineending.Append(ch2);
}
}
break;
}
}
}
else
{
lineending = GetEOLStr(-1);
}
}
bool wxsCoder::ApplyChangesEditor(cbEditor* Editor,const wxString& Header,const wxString& End,wxString& Code,bool CodeHasHeader,bool CodeHasEnd)
{
cbStyledTextCtrl* Ctrl = Editor->GetControl();
int FullLength = Ctrl->GetLength();
// Searching for beginning of section to replace
Ctrl->SetSearchFlags(wxSCI_FIND_MATCHCASE);
Ctrl->SetTargetStart(0);
Ctrl->SetTargetEnd(FullLength);
int Position = Ctrl->SearchInTarget(Header);
if ( Position == -1 )
{
Manager::Get()->GetLogManager()->DebugLog(F(_("wxSmith: Couldn't find code with header:\n\t\"%s\"\nin file '%s'"),
Header.wx_str(),
Editor->GetFilename().wx_str()));
return false;
}
wxString EOL;
wxString tab;
GetLineEndingIndentation(Ctrl->GetLine(Ctrl->LineFromPosition(Position)) , tab, EOL);
// Beginning of this code block is in Position, now searching for end
Ctrl->SetTargetStart(Position);
Ctrl->SetTargetEnd(FullLength);
int EndPosition = Ctrl->SearchInTarget(End);
if ( EndPosition == -1 )
{
Manager::Get()->GetLogManager()->DebugLog(F(_("wxSmith: Unfinished block of auto-generated code with header:\n\t\"%s\"\nin file '%s'"),
Header.wx_str(),
Editor->GetFilename().wx_str()));
return false;
}
// Fetching indentation
wxString BaseIndentation;
int IndentPos = Position;
while ( --IndentPos >= 0 )
{
wxChar ch = Ctrl->GetCharAt(IndentPos);
if ( (ch == _T('\n')) || (ch == _T('\r')) ) break;
}
while ( ++IndentPos < Position )
{
wxChar ch = Ctrl->GetCharAt(IndentPos);
BaseIndentation.Append(
( ch == _T('\t') ) ? _T('\t') : _T(' '));
}
Code = RebuildCode(BaseIndentation, Code.c_str(),(int)Code.Length(), EOL, tab);
// Fixing up positions to contain or not header / ending sequence
if ( !CodeHasHeader ) Position += Header.Length();
if ( CodeHasEnd ) EndPosition += End.Length();
// Checking of code has really changed
if ( Ctrl->GetTextRange(Position,EndPosition) == Code )
{
return true;
}
// Make sure that the code we're replacing is not folded. Otherwise scintilla
// does some weird things
int lineEnd = Ctrl->LineFromPosition(EndPosition);
for ( int line = Ctrl->LineFromPosition(Position); line <= lineEnd; line++ )
{
Ctrl->EnsureVisible(line);
}
// Replacing code
Ctrl->SetTargetStart(Position);
Ctrl->SetTargetEnd(EndPosition);
Ctrl->ReplaceTarget(Code);
Editor->SetModified();
return true;
}
bool wxsCoder::ApplyChangesString(wxString& BaseContent,const wxString& Header,const wxString& End,wxString& Code,bool CodeHasHeader,bool CodeHasEnd,bool& HasChanged)
{
wxString Content = BaseContent;
// Search for header
int Position = Content.First(Header);
if ( Position == -1 )
{
Manager::Get()->GetLogManager()->DebugLog(F(_("wxSmith: Couldn't find code with header:\n\t\"%s\""),Header.wx_str()));
return false;
}
wxString EOL;
wxString tab;
int start = BaseContent.rfind('\n', Position);
GetLineEndingIndentation(BaseContent.substr(start < 0 ? 0 : start) , tab, EOL);
// Skipping header if necessary
int IndentPos = Position;
int IndentMax = Position;
if ( !CodeHasHeader ) Position += Header.Length();
wxString Result = Content.Left(Position);
Content.Remove(0,Position);
int EndPosition = Content.First(End);
if ( EndPosition == -1 )
{
Manager::Get()->GetLogManager()->DebugLog(F(_("wxSmith: Unfinished block of auto-generated code with header:\n\t\"%s\""),Header.wx_str()));
return false;
}
// Including ending sequence if necessary
if ( CodeHasEnd ) EndPosition += End.Length();
// Fetching indentation
wxString BaseIndentation;
while ( --IndentPos >= 0 )
{
wxChar ch = Result.GetChar(IndentPos);
if ( (ch == _T('\n')) || (ch == _T('\r')) ) break;
}
while ( ++IndentPos < IndentMax )
{
wxChar ch = Result.GetChar(IndentPos);
BaseIndentation.Append(
( ch == _T('\t') ) ? _T('\t') : _T(' '));
}
Code = RebuildCode(BaseIndentation,Code.c_str(), Code.Length(), EOL, tab);
// Checking if code has really changed
if ( Content.Mid(0,EndPosition) == Code )
{
return true;
}
HasChanged = true;
Result += Code;
Result += Content.Remove(0,EndPosition);
BaseContent = Result;
return true;
}
wxString wxsCoder::RebuildCode(wxString& BaseIndentation, const wxChar* Code, int CodeLen, wxString EOL, const wxString& tab)
{
const bool UseTab = tab == _("\t");
if ( EOL.IsEmpty() )
EOL = GetEOLStr();
BaseIndentation.Prepend(EOL);
wxString Result;
Result.reserve(CodeLen+10);
while ( *Code )
{
switch ( *Code )
{
case _T('\n'):
{
while (!Result.IsEmpty() &&
(Result.Last() == _T(' ') || Result.Last() == _T('\t')))
Result.RemoveLast();
Result << BaseIndentation;
break;
}
case _T('\t'): if ( !UseTab ) { Result << tab; break; }
default: Result << *Code;
}
Code++;
}
return Result;
}
wxString wxsCoder::CutSpaces(wxString Code,int Count)
{
int TabSize = Manager::Get()->GetConfigManager(_T("editor"))->ReadInt(_T("/tab_size"), 4);
if ( TabSize < 1 ) TabSize = 4;
// Changing to \n line end mode
wxString Result;
for(;;)
{
int PosN = Code.Find(_T("\n"));
int PosR = Code.Find(_T("\r"));
if ( ( PosN < 0 ) && ( PosR < 0 ) ) break;
int Pos;
if ( PosN < 0 ) Pos = PosR;
else if ( PosR < 0 ) Pos = PosN;
else Pos = (PosN < PosR) ? PosN : PosR;
Result.Append(Code.Left(Pos));
Code.Remove(0,Pos);
while ( Code.Length() )
{
if ( ( Code[0] != _T('\n') ) &&
( Code[0] != _T('\r') ) ) break;
Code.Remove(0,1);
}
int LeftSpaces = Count;
while ( Code.Length() && LeftSpaces > 0 )
{
if ( Code[0] == _T(' ') ) LeftSpaces--;
else if ( Code[0] == _T('\t') ) LeftSpaces -= TabSize;
else break;
Code.Remove(0,1);
}
Result.Append(_T('\n'));
}
Result.Append(Code);
return Result;
}
wxString wxsCoder::NormalizeFileName(const wxString& FileName)
{
// Updating the file name in case there are some ".." or "." enteries which prevents from finding
// opened editor for file
wxFileName FixedNameObject(FileName);
FixedNameObject.Normalize(wxPATH_NORM_DOTS);
return FixedNameObject.GetFullPath();
}
void wxsCoder::Flush(int Delay)
{
if ( Delay<=0 )
{
FlushTimer.Stop();
FlushAll();
}
else
{
FlushTimer.Start(Delay,true);
}
}
void wxsCoder::FlushAll()
{
//wxStopWatch SW;
for ( int i=0; i<(int)CodeChangesFiles.Count(); i++ )
{
FlushFile(CodeChangesFiles[i]);
}
CodeChanges.Clear();
CodeChangesFiles.Clear();
//Manager::Get()->GetLogManager()->DebugLog(F(_T("wxSmith: Flushing of code done in %d ms"),SW.Time()));
}
void wxsCoder::FlushTimerEvent(cb_unused wxTimerEvent& event)
{
FlushAll();
}