Debian Codegraph @

CodeLite/search_thread.cpp

raw
1 //////////////////////////////////////////////////////////////////////////////
2 //////////////////////////////////////////////////////////////////////////////
3 //
4 // copyright : (C) 2008 by Eran Ifrah
5 // file name : search_thread.cpp
6 //
7 // -------------------------------------------------------------------------
8 // A
9 // _____ _ _ _ _
10 // / __ \ | | | | (_) |
11 // | / \/ ___ __| | ___| | _| |_ ___
12 // | | / _ \ / _ |/ _ \ | | | __/ _ )
13 // | \__/\ (_) | (_| | __/ |___| | || __/
14 // \____/\___/ \__,_|\___\_____/_|\__\___|
15 //
16 // F i l e
17 //
18 // This program is free software; you can redistribute it and/or modify
19 // it under the terms of the GNU General Public License as published by
20 // the Free Software Foundation; either version 2 of the License, or
21 // (at your option) any later version.
22 //
23 //////////////////////////////////////////////////////////////////////////////
24 //////////////////////////////////////////////////////////////////////////////
25 #include "search_thread.h"
26
27 #include "clFilesCollector.h"
28 #include "clWildMatch.hpp"
29 #include "dirtraverser.h"
30 #include "file_logger.h"
31 #include "fileutils.h"
32 #include "macros.h"
33
34 #include <algorithm>
35 #include <iostream>
36 #include <set>
37 #include <wx/dir.h>
38 #include <wx/event.h>
39 #include <wx/fontmap.h>
40 #include <wx/log.h>
41 #include <wx/stopwatch.h>
42 #include <wx/tokenzr.h>
43 #include <wx/txtstrm.h>
44 #include <wx/wfstream.h>
45
46 #if !wxUSE_GUI
47 #include "cl_command_event.h" // Needed for the definition of wxCommandEvent
48 #endif
49
50 wxDEFINE_EVENT(wxEVT_SEARCH_THREAD_MATCHFOUND, wxCommandEvent);
51 wxDEFINE_EVENT(wxEVT_SEARCH_THREAD_SEARCHEND, wxCommandEvent);
52 wxDEFINE_EVENT(wxEVT_SEARCH_THREAD_SEARCHCANCELED, wxCommandEvent);
53 wxDEFINE_EVENT(wxEVT_SEARCH_THREAD_SEARCHSTARTED, wxCommandEvent);
54
55 #define SEND_ST_EVENT() \
56 if(owner) { \
57 wxPostEvent(owner, event); \
58 } else if(m_notifiedWindow) { \
59 wxPostEvent(m_notifiedWindow, event); \
60 }
61
62 //----------------------------------------------------------------
63 // SearchData
64 //----------------------------------------------------------------
65 namespace
66 {
67 bool is_word_char(wxChar ch) { return ch == '_' || wxIsalnum(ch); }
68
69 // Minumum of 10ms between events that this thread is sending to the main thread
70 constexpr long MIN_SEND_INTERVAL_MS = 1;
71 size_t send_count = 0;
72
73 } // namespace
74
75 const wxString& SearchData::GetExtensions() const { return m_validExt; }
76 SearchData& SearchData::operator=(const SearchData& rhs) { return Copy(rhs); }
77 SearchData& SearchData::Copy(const SearchData& other)
78 {
79 if(this == &other) {
80 return *this;
81 }
82 m_findString = other.m_findString.c_str();
83 m_flags = other.m_flags;
84 m_validExt = other.m_validExt.c_str();
85 m_rootDirs = other.m_rootDirs;
86 m_newTab = other.m_newTab;
87 m_owner = other.m_owner;
88 m_encoding = other.m_encoding.c_str();
89 m_replaceWith = other.m_replaceWith;
90 m_excludePatterns.clear();
91 m_excludePatterns.insert(m_excludePatterns.end(), other.m_excludePatterns.begin(), other.m_excludePatterns.end());
92 m_files.clear();
93 m_files.reserve(other.m_files.size());
94 m_file_scanner_flags = other.m_file_scanner_flags;
95 for(size_t i = 0; i < other.m_files.size(); ++i) {
96 m_files.Add(other.m_files.Item(i).c_str());
97 }
98 return *this;
99 }
100
101 //----------------------------------------------------------------
102 // SearchThread
103 //----------------------------------------------------------------
104
105 SearchThread::SearchThread()
106 : WorkerThread()
107 , m_reExpr(wxT(""))
108 {
109 m_stopWatch.Start();
110 }
111
112 SearchThread::~SearchThread() {}
113
114 wxRegEx& SearchThread::GetRegex(const wxString& expr, bool matchCase)
115 {
116 if(m_reExpr == expr && matchCase == m_matchCase) {
117 return m_regex;
118 } else {
119 m_reExpr = expr;
120 m_matchCase = matchCase;
121 #ifndef __WXMAC__
122 int flags = wxRE_ADVANCED;
123 #else
124 int flags = wxRE_DEFAULT;
125 #endif
126
127 if(!matchCase)
128 flags |= wxRE_ICASE;
129 m_regex.Compile(m_reExpr, flags);
130 }
131 return m_regex;
132 }
133
134 void SearchThread::PerformSearch(const SearchData& data) { Add(new SearchData(data)); }
135
136 void SearchThread::ProcessRequest(ThreadRequest* req)
137 {
138 FileLogger::RegisterThread(wxThread::GetCurrentId(), "Search Thread");
139 wxStopWatch sw;
140 m_summary = SearchSummary();
141 DoSearchFiles(req);
142 m_summary.SetElapsedTime(sw.Time());
143
144 SearchData* sd = (SearchData*)req;
145 m_summary.SetFindWhat(sd->GetFindString());
146 m_summary.SetReplaceWith(sd->GetReplaceWith());
147
148 // Send search end event
149 SendEvent(wxEVT_SEARCH_THREAD_SEARCHEND, sd->GetOwner());
150 }
151
152 void SearchThread::GetFiles(const SearchData* data, wxArrayString& files)
153 {
154 wxStopWatch sw;
155 clDEBUG() << "Building list of files ..." << endl;
156 wxStringSet_t scannedFiles;
157
158 const wxArrayString& rootDirs = data->GetRootDirs();
159 files = data->GetFiles();
160
161 // Populate "scannedFiles" with list of files to scan
162 scannedFiles.insert(files.begin(), files.end());
163 files.reserve(5000);
164 clDEBUG() << "Scanning directories..." << endl;
165 sw.Start();
166
167 clFileExtensionMatcher ext_matcher{ data->GetExtensions() };
168 clPathExcluder path_excluder{ data->GetExcludePatterns() };
169
170 wxStringSet_t visited_dirs;
171 for(size_t i = 0; i < rootDirs.size(); ++i) {
172 clDEBUG() << " scanning root directory:" << rootDirs.Item(i) << endl;
173 // collect only unique files that are matching the pattern
174 auto on_files = [&](const wxArrayString& paths) {
175 files.reserve(files.size() + paths.size());
176 for(const wxString& fullpath : paths) {
177 if(scannedFiles.insert(fullpath).second && ext_matcher.matches(fullpath)) {
178 files.Add(fullpath);
179 }
180 }
181 };
182
183 // do not traverse into excluded directories or directories that
184 // we already visited
185 auto on_folder = [&](const wxString& fullpath) -> bool {
186 return
187 // first time visiting this directory
188 visited_dirs.insert(fullpath).second &&
189 // is not excluded
190 !path_excluder.is_exclude_path(fullpath);
191 };
192
193 // make sure it's really a dir (not a fifo, etc.)
194 clFilesScanner scanner;
195 scanner.ScanWithCallbacks(rootDirs.Item(i), on_folder, on_files, data->GetFileScannerFlags());
196 clDEBUG() << " scanning root directory:" << rootDirs.Item(i) << "..done" << endl;
197 }
198
199 wxString duration;
200 duration << sw.Time() / 1000 << "." << sw.Time() % 1000;
201 clDEBUG() << "Scanning directories... done (" << duration << ")" << endl;
202 clDEBUG() << "Found" << files.size() << "files" << endl;
203
204 // sort the files found
205 clDEBUG() << "Sorting the matches..." << endl;
206 files.Sort([](const wxString& f1, const wxString& f2) -> int { return f1.CmpNoCase(f2); });
207 clDEBUG() << "Sorting the matches... done" << endl;
208 }
209
210 void SearchThread::DoSearchFiles(ThreadRequest* req)
211 {
212 SearchData* data = static_cast<SearchData*>(req);
213
214 // Get all files
215 if(data->GetFindString().IsEmpty()) {
216 SendEvent(wxEVT_SEARCH_THREAD_SEARCHSTARTED, data->GetOwner());
217 return;
218 }
219
220 StopSearch(false);
221 wxArrayString fileList;
222 GetFiles(data, fileList);
223
224 wxStopWatch sw;
225
226 // Send startup message to main thread
227 if(m_notifiedWindow || data->GetOwner()) {
228 wxCommandEvent event(wxEVT_SEARCH_THREAD_SEARCHSTARTED, GetId());
229 event.SetClientData(new SearchData(*data));
230 if(data->GetOwner()) {
231 ::wxPostEvent(data->GetOwner(), event);
232 } else {
233 // since we are in if ( m_notifiedWindow || data->GetOwner() ) block...
234 ::wxPostEvent(m_notifiedWindow, event);
235 }
236 }
237
238 for(size_t i = 0; i < fileList.Count(); i++) {
239 m_summary.SetNumFileScanned((int)i + 1);
240
241 // give user chance to cancel the search ...
242 if(TestStopSearch()) {
243 // Send cancel event
244 SendEvent(wxEVT_SEARCH_THREAD_SEARCHCANCELED, data->GetOwner());
245 StopSearch(false);
246 break;
247 }
248 DoSearchFile(fileList.Item(i), data);
249 }
250 }
251
252 bool SearchThread::TestStopSearch()
253 {
254 bool stop = false;
255 {
256 wxCriticalSectionLocker locker(m_cs);
257 stop = m_stopSearch;
258 }
259 return stop;
260 }
261
262 void SearchThread::StopSearch(bool stop)
263 {
264 wxCriticalSectionLocker locker(m_cs);
265 m_stopSearch = stop;
266 }
267
268 void SearchThread::DoSearchFile(const wxString& fileName, const SearchData* data)
269 {
270 // Process single lines
271 int lineNumber = 1;
272 if(!wxFileName::FileExists(fileName)) {
273 return;
274 }
275
276 // ignore binary executables
277 if(FileUtils::IsBinaryExecutable(fileName)) {
278 return;
279 }
280
281 size_t size = FileUtils::GetFileSize(fileName);
282 if(size == 0) {
283 return;
284 }
285 wxString fileData;
286 fileData.Alloc(size);
287
288 #if wxUSE_GUI
289 // support for other encoding
290 wxFontEncoding enc = wxFontMapper::GetEncodingFromName(data->GetEncoding().c_str());
291 wxCSConv fontEncConv(enc);
292 if(!FileUtils::ReadFileContent(fileName, fileData, fontEncConv)) {
293 m_summary.GetFailedFiles().Add(fileName);
294 return;
295 }
296 #else
297 if(!FileUtils::ReadFileContent(fileName, fileData, wxConvLibc)) {
298 m_summary.GetFailedFiles().Add(fileName);
299 return;
300 }
301 #endif
302 wxArrayString lines = ::wxStringTokenize(fileData, wxT("\n"), wxTOKEN_RET_EMPTY_ALL);
303
304 int lineOffset = 0;
305 if(data->IsRegularExpression()) {
306 // regular expression search
307 for(const wxString& line : lines) {
308 // Read the next line
309 DoSearchLineRE(line, lineNumber, lineOffset, fileName, data);
310 lineOffset += line.Length() + 1;
311 lineNumber++;
312 }
313 } else {
314 // simple search
315 wxString findString;
316 wxArrayString filters;
317 findString = data->GetFindString();
318 if(data->IsEnablePipeSupport()) {
319 if(data->GetFindString().Find('|') != wxNOT_FOUND) {
320 findString = data->GetFindString().BeforeFirst('|');
321
322 wxString filtersString = data->GetFindString().AfterFirst('|');
323 filters = ::wxStringTokenize(filtersString, "|", wxTOKEN_STRTOK);
324 if(!data->IsMatchCase()) {
325 for(size_t i = 0; i < filters.size(); ++i) {
326 filters.Item(i).MakeLower();
327 }
328 }
329 }
330 }
331
332 // Dont search for empty strings
333 if(findString.empty()) {
334 return;
335 }
336
337 if(!data->IsMatchCase()) {
338 findString.MakeLower();
339 }
340 for(const wxString& line : lines) {
341 DoSearchLine(line, lineNumber, lineOffset, fileName, data, findString, filters);
342 lineOffset += line.Length() + 1;
343 lineNumber++;
344 }
345 }
346
347 if(m_results.empty() == false) {
348 SendEvent(wxEVT_SEARCH_THREAD_MATCHFOUND, data->GetOwner());
349 }
350 }
351
352 void SearchThread::DoSearchLineRE(const wxString& line, const int lineNum, const int lineOffset,
353 const wxString& fileName, const SearchData* data)
354 {
355 wxRegEx& re = GetRegex(data->GetFindString(), data->IsMatchCase());
356 size_t col = 0;
357 int iCorrectedCol = 0;
358 int iCorrectedLen = 0;
359 wxString modLine = line;
360 if(re.IsValid()) {
361 while(re.Matches(modLine)) {
362 size_t start, len;
363 re.GetMatch(&start, &len);
364 col += start;
365
366 // Notify our match
367 // correct search Pos and Length owing to non plain ASCII multibyte characters
368 iCorrectedCol = FileUtils::UTF8Length(line.c_str(), col);
369 iCorrectedLen = FileUtils::UTF8Length(line.c_str(), col + len) - iCorrectedCol;
370 SearchResult result;
371 result.SetPosition(lineOffset + col);
372 result.SetColumnInChars((int)col);
373 result.SetColumn(iCorrectedCol);
374 result.SetLineNumber(lineNum);
375 result.SetPattern(line);
376 result.SetFileName(fileName);
377 result.SetLenInChars((int)len);
378 result.SetLen(iCorrectedLen);
379 result.SetFlags(data->m_flags);
380 result.SetFindWhat(data->GetFindString());
381 wxArrayString regexCaptures;
382 for(size_t i = 0; i < re.GetMatchCount(); ++i) {
383 regexCaptures.Add(re.GetMatch(modLine, i));
384 }
385 result.SetRegexCaptures(regexCaptures);
386
387 // Make sure our match is not on a comment
388 m_results.push_back(result);
389 m_summary.SetNumMatchesFound(m_summary.GetNumMatchesFound() + 1);
390
391 col += len;
392
393 // adjust the line
394 if(line.Length() - col <= 0)
395 break;
396 modLine = modLine.Right(line.Length() - col);
397 }
398 }
399 }
400
401 void SearchThread::DoSearchLine(const wxString& line, const int lineNum, const int lineOffset, const wxString& fileName,
402 const SearchData* data, const wxString& findWhat, const wxArrayString& filters)
403 {
404 wxString modLine = line;
405
406 if(!data->IsMatchCase()) {
407 modLine.MakeLower();
408 }
409
410 int pos = 0;
411 int col = 0;
412 int iCorrectedCol = 0;
413 int iCorrectedLen = 0;
414 while(pos != wxNOT_FOUND) {
415 pos = modLine.Find(findWhat);
416 if(pos != wxNOT_FOUND) {
417 col += pos;
418
419 // Pipe support
420 bool allFiltersOK = true;
421 if(!filters.IsEmpty()) {
422 // Apply the filters
423 for(size_t i = 0; i < filters.size() && allFiltersOK; ++i) {
424 allFiltersOK = (modLine.Find(filters.Item(i)) != wxNOT_FOUND);
425 }
426 }
427
428 // Pipe filtes OK?
429 if(!allFiltersOK)
430 return;
431
432 // we have a match
433 if(data->IsMatchWholeWord()) {
434
435 // make sure that the word before is not in the wordChars map
436 if(pos > 0 && is_word_char(modLine.GetChar(pos - 1))) {
437 if(!AdjustLine(modLine, pos, findWhat)) {
438 break;
439 } else {
440 col += (int)findWhat.Length();
441 continue;
442 }
443 }
444 // if we have more characters to the right, make sure that the first char does not match any
445 // in the wordCharsMap
446 if(pos + findWhat.Length() <= modLine.Length()) {
447 wxChar nextCh = modLine.GetChar(pos + findWhat.Length());
448 if(is_word_char(nextCh)) {
449 if(!AdjustLine(modLine, pos, findWhat)) {
450 break;
451 } else {
452 col += (int)findWhat.Length();
453 continue;
454 }
455 }
456 }
457 }
458
459 // Notify our match
460 // correct search Pos and Length owing to non plain ASCII multibyte characters
461 iCorrectedCol = FileUtils::UTF8Length(line.c_str(), col);
462 iCorrectedLen = FileUtils::UTF8Length(findWhat.c_str(), findWhat.Length());
463 SearchResult result;
464 result.SetPosition(lineOffset + col);
465 result.SetColumnInChars(col);
466 result.SetColumn(iCorrectedCol);
467 result.SetLineNumber(lineNum);
468 // Dont use match pattern larger than 500 chars
469 result.SetPattern(line.length() > 500 ? line.Mid(0, 500) : line);
470 result.SetFileName(fileName);
471 result.SetLenInChars((int)findWhat.Length());
472 result.SetLen(iCorrectedLen);
473 result.SetFindWhat(data->GetFindString());
474 result.SetFlags(data->m_flags);
475
476 m_results.push_back(result);
477 m_summary.SetNumMatchesFound(m_summary.GetNumMatchesFound() + 1);
478
479 if(!AdjustLine(modLine, pos, findWhat)) {
480 break;
481 }
482 col += (int)findWhat.Length();
483 }
484 }
485 }
486
487 bool SearchThread::AdjustLine(wxString& line, int& pos, const wxString& findString)
488 {
489 // adjust the current line
490 if(line.Length() - (pos + findString.Length()) >= findString.Length()) {
491 line = line.Right(line.Length() - (pos + findString.Length()));
492 pos += (int)findString.Length();
493 return true;
494 } else {
495 return false;
496 }
497 }
498
499 void SearchThread::SendEvent(wxEventType type, wxEvtHandler* owner)
500 {
501 if(!m_notifiedWindow && !owner)
502 return;
503
504 wxCommandEvent event(type, GetId());
505 if(type == wxEVT_SEARCH_THREAD_MATCHFOUND) {
506 // match found and we scanned 10 files
507 event.SetClientData(new SearchResultList(m_results));
508 m_results.clear();
509 SEND_ST_EVENT();
510
511 } else if((type == wxEVT_SEARCH_THREAD_SEARCHEND) || (type == wxEVT_SEARCH_THREAD_SEARCHCANCELED)) {
512 // search eneded, if we got any matches "buffered" send them before the
513 // the summary event
514 if(m_results.empty() == false) {
515 wxCommandEvent evt(wxEVT_SEARCH_THREAD_MATCHFOUND, GetId());
516 evt.SetClientData(new SearchResultList(m_results));
517 if(owner) {
518 wxPostEvent(owner, evt);
519 } else if(m_notifiedWindow) {
520 wxPostEvent(m_notifiedWindow, evt);
521 }
522 }
523 m_results.clear();
524 // Now send the summary event
525 event.SetClientData(type == wxEVT_SEARCH_THREAD_SEARCHEND ? new SearchSummary(m_summary) : nullptr);
526 SEND_ST_EVENT();
527 }
528 // to avoid flooding the UI with search events, sleep for 1ms after each
529 // send_event call
530 ++send_count;
531 if(send_count >= 10) {
532 wxThread::Sleep(1);
533 send_count = 0;
534 }
535 }
536
537 void SearchThread::FilterFiles(wxArrayString& files, const SearchData* data)
538 {
539 wxArrayString tmpFiles;
540 std::set<wxString> uniqueFiles;
541 const wxArrayString& excludePatterns = data->GetExcludePatterns();
542 const wxString& mask = data->GetExtensions();
543 std::for_each(files.begin(), files.end(), [&](const wxString& filename) {
544 if(uniqueFiles.count(filename))
545 return;
546 uniqueFiles.insert(filename);
547 if(FileUtils::WildMatch(mask, filename) && !FileUtils::WildMatch(excludePatterns, filename)) {
548 tmpFiles.Add(filename);
549 }
550 });
551 files.swap(tmpFiles);
552 files.Sort([](const wxString& f1, const wxString& f2) -> int { return f1.CmpNoCase(f2); });
553 }
554
555 static SearchThread* gs_SearchThread = NULL;
556 void SearchThreadST::Free()
557 {
558 if(gs_SearchThread) {
559 delete gs_SearchThread;
560 }
561 gs_SearchThread = NULL;
562 }
563
564 SearchThread* SearchThreadST::Get()
565 {
566 if(gs_SearchThread == NULL)
567 gs_SearchThread = new SearchThread;
568 return gs_SearchThread;
569 }
570
571 JSONItem SearchResult::ToJSON() const
572 {
573 JSONItem json = JSONItem::createObject();
574 json.addProperty("file", m_fileName);
575 json.addProperty("line", m_lineNumber);
576 json.addProperty("col", m_column);
577 json.addProperty("pos", m_position);
578 json.addProperty("pattern", m_pattern);
579 json.addProperty("len", m_len);
580 json.addProperty("flags", m_flags);
581 json.addProperty("columnInChars", m_columnInChars);
582 json.addProperty("lenInChars", m_lenInChars);
583 json.addProperty("regexCaptures", m_regexCaptures);
584 return json;
585 }
586
587 void SearchResult::FromJSON(const JSONItem& json)
588 {
589 m_position = json.namedObject("pos").toInt(m_position);
590 m_column = json.namedObject("col").toInt(m_column);
591 m_lineNumber = json.namedObject("line").toInt(m_lineNumber);
592 m_pattern = json.namedObject("pattern").toString(m_pattern);
593 m_fileName = json.namedObject("file").toString(m_fileName);
594 m_len = json.namedObject("len").toInt(m_len);
595 m_flags = json.namedObject("flags").toSize_t(m_flags);
596 m_columnInChars = json.namedObject("columnInChars").toInt(m_columnInChars);
597 m_lenInChars = json.namedObject("lenInChars").toInt(m_lenInChars);
598 m_regexCaptures = json.namedObject("regexCaptures").toArrayString();
599 }
600
601 JSONItem SearchSummary::ToJSON() const
602 {
603 JSONItem json = JSONItem::createObject();
604 json.addProperty("filesScanned", m_fileScanned);
605 json.addProperty("matchesFound", m_matchesFound);
606 json.addProperty("elapsed", m_elapsed);
607 json.addProperty("failedFiles", m_failedFiles);
608 json.addProperty("findWhat", m_findWhat);
609 json.addProperty("replaceWith", m_replaceWith);
610 return json;
611 }
612
613 void SearchSummary::FromJSON(const JSONItem& json)
614 {
615 m_fileScanned = json.namedObject("filesScanned").toInt(m_fileScanned);
616 m_matchesFound = json.namedObject("matchesFound").toInt(m_matchesFound);
617 m_elapsed = json.namedObject("elapsed").toInt(m_elapsed);
618 m_failedFiles = json.namedObject("failedFiles").toArrayString();
619 m_findWhat = json.namedObject("findWhat").toString();
620 m_replaceWith = json.namedObject("replaceWith").toString();
621 }