-
Notifications
You must be signed in to change notification settings - Fork 8
/
PoShLucene.psm1
490 lines (402 loc) · 16.7 KB
/
PoShLucene.psm1
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
using assembly Lucene.Net.dll
using namespace System.IO
using namespace Lucene.Net.Analysis
using namespace Lucene.Net.Analysis.Standard
using namespace Lucene.Net.Documents
using namespace Lucene.Net.Index
using namespace Lucene.Net.QueryParsers
using namespace Lucene.Net.Store
using namespace Lucene.Net.Util
using namespace Lucene.Net.Search
using namespace System.Windows.Documents
Add-Type -AssemblyName presentationframework
Add-Type -AssemblyName System.Windows.Forms
function Invoke-PoshLucene {
$XAML=@'
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="PoShLucene"
Width="850"
Height="500"
Background="#282c34"
WindowStartupLocation="CenterScreen">
<Grid>
<Grid.Resources>
<VisualBrush x:Key="SearchHint"
AlignmentX="Left"
AlignmentY="Top"
Stretch="None">
<VisualBrush.Transform>
<TranslateTransform X="5" Y="7" />
</VisualBrush.Transform>
<VisualBrush.Visual>
<Grid HorizontalAlignment="Left">
<TextBlock HorizontalAlignment="Left"
VerticalAlignment="Center"
FontStyle="Italic"
Foreground="Gray"
Opacity="1"
Text="Search in file contents" />
</Grid>
</VisualBrush.Visual>
</VisualBrush>
</Grid.Resources>
<Grid.RowDefinitions>
<RowDefinition Height="75" />
<RowDefinition />
<RowDefinition Height="45" />
</Grid.RowDefinitions>
<Grid Grid.Row="0" Margin="5">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="50" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Label Grid.Row="0"
Grid.Column="0"
Margin="3"
Content="_Target"
Foreground="#99ffcc" />
<TextBox Name="txtTarget"
Grid.Row="0"
Grid.Column="1"
Margin="3" />
<Label Grid.Row="1"
Grid.Column="0"
Margin="3"
Content="_Query"
Foreground="#99ffcc" />
<TextBox x:Name="query"
Grid.Row="1"
Grid.Column="1"
Margin="3">
<TextBox.Style>
<Style TargetType="{x:Type TextBox}">
<Setter Property="Background" Value="White" />
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=query, Path=Text}" Value="">
<Setter Property="Background" Value="{StaticResource SearchHint}" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
</Grid>
<Grid Grid.Row="1" Margin="5">
<Grid.RowDefinitions>
<RowDefinition Height="100" />
<RowDefinition Height="5" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="150" />
</Grid.ColumnDefinitions>
<ListBox Name="hits"
Grid.Row="0"
Grid.Column="0"
Margin="5"
Background="#282c34"
Foreground="#4cd2ff" />
<StackPanel Grid.Row="0"
Grid.Column="1"
Margin="5">
<Button Name="prevButton"
Content="_Previous Occurrence"
Margin="0,0,0,5" />
<Button Name="nextButton"
Content="_Next Occurrence" />
</StackPanel>
<GridSplitter Grid.Row="1"
Grid.ColumnSpan="2"
Height="3"
Margin="5,0,5,0"
ResizeDirection="Rows"
HorizontalAlignment="Stretch"
Background="#ff265c" />
<RichTextBox Name="OutputPane"
Grid.Row="2"
Grid.ColumnSpan="2"
Margin="5"
Background="#282c34"
Foreground="#ccff99"
IsReadOnly="True"
FontFamily="Consolas"
FontSize="14"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Auto" />
</Grid>
<StackPanel Grid.Row="2"
Grid.Column="1"
Grid.ColumnSpan="2"
Orientation="Horizontal">
<TextBox Name="txtStatus"
Margin="8"
FontStyle="Italic"
Background="#282c34"
Foreground="#99ffcc"
TextWrapping="Wrap"
HorizontalAlignment="Left"
BorderThickness="0" />
<Label x:Name="txtPath"
Margin="8"
FontStyle="Italic"
Foreground="#4cd2ff" />
</StackPanel>
</Grid>
</Window>
'@
$Window = [Windows.Markup.XamlReader]::Load((New-Object System.Xml.XmlNodeReader ([xml]$XAML)))
$txtTarget = $Window.FindName("txtTarget")
$query = $Window.FindName("query")
$hits = $Window.FindName("hits")
$OutputPane = $Window.FindName("OutputPane")
$txtStatus = $Window.FindName("txtStatus")
$txtPath = $Window.FindName("txtPath")
$nextButton = $Window.FindName("nextButton")
$prevButton = $Window.FindName("prevButton")
$null = $txtTarget.Focus()
$analyzer = [StandardAnalyzer]::new("LUCENE_CURRENT")
$directory = [RAMDirectory]::new()
$theIndex=@{name='';indexed=$false}
$highlightMatchColor = "YellowGreen"
$highlightSelectionColor = "Orange"
$lastSelectedResult = -1
$lastSelectedResultOccurrence = -1
function FindTextPosition([TextPointer]$startPos, [int]$offset) {
$i = 0
$currentPos = $startPos
while ($i -lt $offset -and $currentPos) {
if ($currentPos.GetPointerContext([LogicalDirection]::Forward) -eq [TextPointerContext]::Text) {
$i = $i + 1
}
if (!$currentPos.GetPositionAtOffset(1, [LogicalDirection]::Forward)) {
return $currentPos
}
$currentPos = $currentPos.GetPositionAtOffset([LogicalDirection]::Forward)
}
return $currentPos
}
function SetBackgroundColor($occurrence, $backgroundColor) {
$documentStartPos = $OutputPane.Document.ContentStart
$selection = $OutputPane.Selection
$selection.Select($occurrence.StartPosition, $occurrence.EndPosition)
$selection.ApplyPropertyValue([System.Windows.Documents.TextElement]::BackgroundProperty, $backgroundColor);
$selection.Select($documentStartPos, $documentStartPos)
}
function GetFlowDocument ($resultFile) {
if (!$resultFile.FlowDocument) {
$run = New-Object System.Windows.Documents.Run $resultFile.Content
$paragraph = New-Object System.Windows.Documents.Paragraph $run
$OutputPane.Document = New-Object System.Windows.Documents.FlowDocument $paragraph
[void]$OutputPane.Focus()
$documentStartPos = $OutputPane.Document.ContentStart
$lastPos = $documentStartPos
$lastOffset = 0
$positions = @()
$resultFile.Offsets | ForEach-Object {
$startPos = FindTextPosition $lastPos ($_.StartOffset - $lastOffset)
$endPos = FindTextPosition $startPos ($_.EndOffset - $_.StartOffset)
$occurrence = @{ StartPosition = $startPos; EndPosition = $endPos }
SetBackgroundColor $occurrence $highlightMatchColor
$positions += $occurrence
$lastPos = $endPos
$lastOffset = $_.EndOffset
} | Out-Null
$resultFile.FlowDocument = $OutputPane.Document
$resultFile.OccurrencePositions = $positions
}
return $resultFile.FlowDocument
}
function ClearSelectedOccurrence() {
if ($script:lastSelectedResult -gt -1 -and $script:lastSelectedResultOccurrence -gt -1) {
$lastResult = $script:totalDocs[$script:lastSelectedResult]
if ($lastResult -and $lastResult.OccurrencePositions) {
$lastOccurrence = $lastResult.OccurrencePositions[$script:lastSelectedResultOccurrence]
if ($lastOccurrence) {
SetBackgroundColor $lastOccurrence $highlightMatchColor
}
}
}
}
function ShowResult ([int]$resultId, [int]$occurrenceId = 0) {
$resultInfo = $script:totalDocs[$resultId]
if ($resultInfo) {
ClearSelectedOccurrence
$OutputPane.Document = GetFlowDocument $resultInfo
$txtPath.Content = $resultInfo.Path
$occurrence = $resultInfo.OccurrencePositions[$occurrenceId]
if ($occurrence) {
SetBackgroundColor $occurrence $highlightSelectionColor
$occurrence.StartPosition.Parent.BringIntoView()
}
$script:lastSelectedResult = $resultId
$script:lastSelectedResultOccurrence = $occurrenceId
}
}
function BuildResult ([ScoreDoc]$scoredDocument, [string]$queryStr) {
$document = $isearcher.Doc($scoredDocument.Doc)
$indexReader = [IndexReader]::Open($directory, $true)
$termPosVector = $indexReader.GetTermFreqVector($scoredDocument.Doc, "fulltext")
$termIndex = $termPosVector.IndexOf($queryStr.ToLower())
$indexReader.Dispose()
@{
Path = $document.Get("filepath")
Content = $document.Get("fulltext")
Document = $document
Offsets = $termPosVector.GetOffsets($termIndex)
FlowDocument = $null # This will be populated on first display
OccurrencePositions = $null # This will be populated on first display
}
}
function DoIndex ($targetFileList)
{
if($theIndex.name -eq $targetFileList -and $theIndex.index -eq $true) { return }
$timing = Measure-Command {
$iwriter = [IndexWriter]::new($directory, $analyzer, $true, [IndexWriter+MaxFieldLength]::new(25000))
$count = 0
$cmd = "ls -rec {0} -File | % fullname " -f $targetFileList
foreach ($file in ($cmd | Invoke-Expression))
{
try
{
$doc = [Document]::new()
$text = [IO.file]::ReadAllText($file)
Write-Verbose -Message "Analyzed the file: $file"
$doc.Add([Field]::new("fulltext", [string]$text, "YES", "ANALYZED", "WITH_POSITIONS_OFFSETS"))
$doc.Add([Field]::new("filepath", $file, "YES", "ANALYZED"))
$iwriter.AddDocument($doc)
$count++
}
catch [Exception]
{
$errMsg = "Unable to read the file {0} `nException: {1}" -f $file, $_.Exception.ToString()
Write-Error $errMsg
}
}
}
$txtStatus.text = "{0} files indexed in {1} seconds" -f $count, $timing.TotalSeconds
$iwriter.close()
$theIndex.name=$targetFileList
$theIndex.index=$true
}
function DoSearch ($q)
{
try
{
$timing = Measure-Command {
$script:isearcher = [IndexSearcher]::new($directory, $true) # read-only-true
$parser = [QueryParser]::new("LUCENE_CURRENT", "fulltext", $analyzer)
$query = $parser.Parse($q)
$totalHits = $isearcher.Search($query, $null, 1000).ScoreDocs
}
$totalHits | ForEach-Object { BuildResult $_ $q }
$txtStatus.text = "{0}`n{1} hits found in {2} seconds" -f $txtStatus.text, $totalHits.count, $timing.TotalSeconds
}
catch [Exception]
{
$errMsg = "Search failed with the following `nException: {0}" -f $_.Exception.ToString()
Write-Error $errMsg
}
}
$txtTarget.add_PreviewKeyUp({
param($sender, $keyArgs)
if($keyArgs.Key -eq 'Enter') {
[System.Windows.Input.Mouse]::OverrideCursor = [System.Windows.Input.Cursors]::Wait
$txtStatus.text = "[{0}] Indexing..." -f (Get-Date)
[System.Windows.Forms.Application]::DoEvents()
DoIndex $txtTarget.Text -ErrorAction SilentlyContinue
[System.Windows.Input.Mouse]::OverrideCursor = $null
}
})
$query.add_PreviewKeyUp({
param($sender,$keyArgs)
if($keyArgs.Key -eq 'Enter') {
if (!$query.Text) { return }
[System.Windows.Input.Mouse]::OverrideCursor = [System.Windows.Input.Cursors]::Wait
if ($txtTarget.Text -ne $null -and ([String]::IsNullOrWhiteSpace($txtTarget.Text) -ne $true)) {
DoIndex $txtTarget.Text -ErrorAction SilentlyContinue
}
$adding=$true
$script:totalDocs = @(DoSearch $query.Text -ErrorAction SilentlyContinue)
$hits.items.Clear()
$OutputPane.Document = New-Object System.Windows.Documents.FlowDocument
$txtPath.Content = ""
for ($i = 0; $i -lt $totalDocs.count; $i++) {
$hits.Items.Add($script:totalDocs[$i].Path)
}
$adding = $false
if($totalDocs.Count -ge 1) {
$hits.Focus()
$hits.SelectedItem = $hits.Items[0]
}
[System.Windows.Input.Mouse]::OverrideCursor = $null
}
})
function ShowNextOccurrence([bool]$moveBackward = $false) {
if ($script:totalDocs -eq $null -or $script:totalDocs.Count -eq 0) { return }
$nextResultId = $script:lastSelectedResult
$nextResultOccurrence = $script:lastSelectedResultOccurrence
$currentResult = $script:totalDocs[$script:lastSelectedResult]
if ($currentResult) {
if ($moveBackward) {
# Search backward
$nextResultOccurrence -= 1
if ($nextResultOccurrence -eq -1) {
$nextResultId = $script:lastSelectedResult - 1
if ($nextResultId -eq -1) {
$nextResultId = $script:totalDocs.Count - 1
}
$currentResult = $script:totalDocs[$nextResultId]
$nextResultOccurrence = $currentResult.Offsets.Count - 1
}
}
else {
# Search forward
$nextResultOccurrence += 1
if ($nextResultOccurrence -eq $currentResult.Offsets.Count) {
$nextResultOccurrence = 0
$nextResultId = $script:lastSelectedResult + 1
if ($nextResultId -eq $script:totalDocs.Count) { $nextResultId = 0 }
}
}
}
$hits.SelectedIndex = $nextResultId
ShowResult $nextResultId $nextResultOccurrence
$hits.ScrollIntoView($hits.SelectedItem)
}
$Window.add_PreviewKeyUp({
param($sender, $keyArgs)
# Result navigation with F3
if($keyArgs.Key -eq 'F3') {
ShowNextOccurrence ([System.Windows.Input.Keyboard]::IsKeyDown("LeftShift"))
}
})
$nextButton.add_Click({
ShowNextOccurrence $false
})
$prevButton.add_Click({
ShowNextOccurrence $true
})
$hits.add_SelectionChanged({
if($adding) { return }
ShowResult $hits.SelectedIndex
$hitDoc
})
$txtPath.add_MouseEnter({
$txtPath.Cursor = [System.Windows.Input.Cursors]::Hand
})
$txtPath.add_MouseLeftButtonDown({
$fPath = $txtPath.Content
if (Test-Path -Path $fPath) {
Start-Process -FilePath "$env:windir\explorer.exe" -ArgumentList "/select, ""$fPath"""
}
})
[void]$Window.ShowDialog()
if($script:isearcher) { $script:isearcher.Close() }
if($directory) { $directory.Close() }
}
#Export-ModuleMember -Function Invoke-LuceneSearch