-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathforeach.lic
2209 lines (2002 loc) · 96.9 KB
/
foreach.lic
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
=begin
Executes a series of commands for each item matching the criteria you specify.
Some examples:
;foreach box in inv; move to locker
;foreach box in locker; move to backpack
;foreach gem in cloak; get item; appraise item; put item in container
;foreach gem in red sack; move to gemcutter; turn gemcutter; move to blue sack
;foreach scroll in inv; read item
;foreach gem in backpack; get item; prep 704; cast item; put item in container (Note: won't check mana)
;foreach reagent in inv; get item; sell item
;foreach gem in backpack; get item; ;my_script item; put item in container
;foreach name=*quartz orb in inv; get item; put item in locker
Basic usage:
;foreach [UNIQUE] [FIRST #] [AFTER #] [[ATTRIBUTE]=VALUE] in <CONTAINER>[; command; command; ...]
Type ;foreach or ;foreach help for more details and information on functionality, or visit:
https://github.com/dewiniaid/gs4-lich-scripts/blob/master/Foreach.md
;foreach is blind to closed containers.
author: LostRanger (thisgenericname@gmail.com)
game: any
tags: utility
required: Lich >= 4.6.0.
version: 1.0.1 (2019-11-21)
changelog:
version 1.0.1 (2019-11-21)
* Fixes to avoid items possibly being missed under certain circumstances due to Lich limitations. This was
most likely to happen in `;foreach ... in inv...` on large inventories on certain combinations of hardware
and internet connectivity.
version 1.0 (2019-10-21)
* Now handles collective containers. Example:
If you have "You see three mannequins. Looking at the mannequins, you see a dark grey mannequin, [...]"
;foreach on mannequins will ;foreach every mannequin in the list.
version 0.10.8 (2019-08-07)
* Fix WAITFOR being broken since 0.10
version 0.10.7 (2019-08-07)
* Fix issue with commands that cause RT (and other statusbar-related updates) causing crashes on non-StormFront
clients.
version 0.10.6 (2019-07-26)
* Fix the new pattern matching syntax being too greedy, which could break some Foreach scripts.
version 0.10.5 (2019-07-25)
* Properly unsilence ourselves when we send actual commands. Previously, people who trusted Foreach could not
see the commands it sent. Now, only commands related to determining your initial inventory are squelched.
* You can now `;foreach q=/pattern/ in ...` to do regular expression matches.
version 0.10.4 (2019-06-20)
* Made multiple fixes to 'giveitem'. It should actually be recognized as a command again.
* Added a new 'fastinv'/'qinv' target, which is similar to 'inv' but skips the INV FULL step. This allows for
slightly faster startup at the cost of being unable to check marked/registered status and being potentially
unaware of the contents of containers that you have not previously LOOKed in.
version 0.10.3 (2019-06-13)
* Overhauled Stormfront status bar updates. They should no longer significantly slow down the script.
Additionally, status bar updates are less frequent (except when they are the result of the script pausing
or resuming)
* Running ;foreach while ;foreach is already running (i.e. with ;force) no longer clobbers the statusbar in Stormfront.
* Immediate !commands now delay every 5 consecutive immediate commands rather than on every fifth item.
* `;foreach ... in backpack on table` should now work correctly.
- Note that a quirk in GS4's item parsing code means you will frequently need to use 'get item in container'
syntax when using foreach in this way.
version 0.10.2 (2019-06-12)
* Sorting is now case-insensitive.
* Read, Look, Analyze and Inspect now add an implicit 'item' if needed.
* Giveitem now searches for a matching PC in the room at startup and autocompletes to that PC's full name.
- It will error out immediately if no matching PCs are found or more than one matching PC is found.
- It will no longer fail when you do not type the character's name entirely with proper capitalization.
* Unspported: Commands can be prefixed with a "!" to ignore various checks on usability in favor of speed.
Use at your own risk!
version 0.10.1 (2019-06-11)
* Fix marked/unmarked/registered/unregistered filters not working in some cases.
version 0.10 (2019-06-10)
* Foreach now reports its status to the shortcut bar in Stormfront, and can be paused, unpaused and killed from
that location.
* You can now ;foreach ... under|behind ... instead of just ;foreach ... in and ;foreach ... on
* You can now ;foreach over multiple targets (;foreach in backpack,cloak,disk...)
* Pattern matching is no longer case-sensitive.
;foreach q=elan*pack in pack should match "an Elanthian Guilds voucher pack"
* `;foreach sorted ... in ...` will iterate over items alphabetically within their respective containers.
Articles a/an/some/the are ignored when sorting. The order of which container is evaluated first is unchanged.
* `;foreach reversed ... in ...` will iterate over items backwards within their respective containers.
This can be used to avoid changing container/room order, or in conjunction with 'sorted' to sort descending.
* Completely overhauled the item matching engine to make it easier to maintain going forward.
* `;foreach type=none in ...` will now match items that have no explicit type."
version 0.9.9 (2019-05-24)
* Add UNMARK shortcut for MARK <item> REMOVE
* Improved documentation, including updating the online documentation
* Convenience shortcuts for in-game verbs should now trigger when abbreviated:
DRop, PLACe, SELl, APpraise, SELl, and REGister.
* If the first command is `get`, `take`, `register`, `mark` or `unmark`, an implicit "get item" or
"remove item" will be added beforehand. This behavior already existed for drop, place, sell and appraise.
* If the only command is appraise, register, mark, or unmark, items will be RETURNed
afterwards in addition to the implicit get/remove item at the start.
version 0.9.3 (2019-05-24)
* No longer times out if you `;foreach in empty container` and have FLAG SORTEDVIEW ON
* Improved error messaging when targetting empty, closed or nonexistant containers.
* Fix ;foreach quick when using multiple patterns (;foreach q=red,blue in ...)
* `move to locker` automatically opens your locker just like `foreach in locker` does
version 0.9.2 (2019-05-22)
* Now correctly works with locker manifests, even if there's nothing on your armor stand.
version 0.9.1 (2019-05-21)
* You can now ;foreach quick=phrase in ... or ;foreach q=phrase in ... as an alternate method for matching items
This is equivalent to ;foreach fullname=*phrase* in ... (note wildcards!)
This feature was documented in 0.9, but was not implemented in that release.
version 0.9 (2019-05-20)
* You can now further filter displayed items with ';foreach [un]registered ... in ...` and
`;foreach [un]marked ... in ...``
* `;foreach in locker` will now open your locker if it is not already, and will close your locker when it exits
if it originally opened it.
* `;foreach in locker` in a premium locker will now try to use your locker manifest to avoid needing to scan
multiple containers. This adds a substantial startup speed boost. If this attempt fails, it is still
improved in that it will no longer examine the curtain, your disk, or any other non-locker containers in the
room.
* Added some more pretty formatting to ;foreach help (Stormfront only)
* Make a second attempt at improving compatibility with the Profanity FE
version 0.8 (2019-05-09)
* `;foreach in locker` should now work for non-premium lockers.
* Improve compatibility with the Profanity FE
* Fix an issue which caused Foreach to stall briefly in some cases.
* No longer prompts to install xmlpatch on first launch
* Add waitcastrt, waitcastrt? and waitrt? commands
* Add sleep X command, where X is a duration.
* Add UNIQUE, FIRST # and AFTER # modifiers.
For a full changelog, see https://github.com/dewiniaid/gs4-lich-scripts/blob/master/Foreach.md
version 0.1 (2017-06-18)
* Initial release
=end
# [JUST UPDATED] ;foreach 0.10, featuring lots of updates, a few bugfixes, support for multiple targets, sorting, and more. ;repo info foreach -- ;repo download foreach -- ;foreach help
# [JUST UPDATED] ;foreach 0.9, featuring filtering by marked/registered status, faster scans of premium lockers, and automatic locker opening/closing. ;repo info foreach -- ;repo download foreach -- ;foreach help
EXPERIMENTAL_EXPIRES = nil
# EXPERIMENTAL_EXPIRES = Time.at(1560644027)
class ItemMatcher
attr_accessor :first, :after, :unique, :sorted, :reversed, :item_filter
attr_reader :total_items, :status_filter
attr_reader :container_names, :container_contents
HELP_URL = "https://github.com/dewiniaid/gs4-lich-scripts/blob/master/Foreach.md"
UNREGISTERED = 1 << 0
REGISTERED = 1 << 1
UNMARKED = 1 << 2
MARKED = 1 << 3
INVFULL_PATTERN = /^( {2,})([^<]*)<a exist="(-?\d+)" noun="([^"]*)">([^<]*)<\/a>(?: ([^(]*)(?:$|(?= \()))?(?: (\(.*\)))?$/
# Matches: 1 = leading space, 2 = prename, 3 = id, 4 = noun, 5 = name, 6 = postname, 7 = registered/marked attributes
# You are carrying nothing at this time. -- no inventory
# INV_PATTERN = /(?:(?:Peering into|[IO]n) .* <a exist="(-?\d+)"[^>]*>([^<]*)<\/a>,? you see )|(?:[OI]n the <a exist="(-?\d+)"[^>]*>([^<]*)<\/a>:\s*$)|(There is nothing [io]n the|That is closed.|I could not find what you were referring to\.)/
INV_PATTERN = /(?:(?:Peering into|In|On|Under|Behind) .* <a exist="(-?\d+)"[^>]*>([^<]*)<\/a>,? you see )|(?:[OI]n the <a exist="(-?\d+)"[^>]*>([^<]*)<\/a>:\s*$)|(There is nothing (?:in|on|under|behind) the|That is closed.|I could not find what you were referring to\.)|^You see <a.*?<\/a>\.\s+Looking at the <a.*?<\/a>, you see (.*)\.\s*$/
LOCKER_PATTERNS = {
:start => /^(?:(Looking in front of you, you see)|Thinking back, you recall) the contents of your locker/,
:end => /^Obvious items:|^There are no items in this locker./,
:container => /^<pushBold\/>[IO]n .* <a .* noun="(.*)">/,
:item => /^(?:<popBold\/>)? {6}(?! )([^<]*)<a exist="(-?\d+)" noun="([^"]*)">([^<]*)<\/a>(?: ([^(]*)(?:$|(?= \()))?(?: (\(.*\)))?$/,
:town_locales => /(Landing|Illistim|Vaalor|Mist Harbor|Kharam|Teras|Icemule|Solhaven|River's Rest)/
}
def initialize(first: nil, after: nil, unique: false, sorted: false, reversed: false, marked: nil, registered: nil)
@first = first
@after = after
@unique = unique
@sorted = sorted
@reversed = reversed
@item_filter = nil
@status_filter = 0
self.marked = marked
self.registered = registered
@container_names = {}
@container_contents = {}
@item_statuses = {}
@pending_ingests = {}
@scanned_inv = false
@scanned_hands = false
@scanned_locker = false
@seen_ids = Set.new
@total_items = nil
@command_cache = {}
end
def add_item!(item, container, container_name=nil, status_text=nil)
return unless @seen_ids.add?(item.id)
(@container_contents[container] ||= []) << item
@container_names[container] ||= container_name
@item_statuses[item.id] = ItemMatcher.status_from_text(status_text) if status_text
return item
end
def add_item(item, container_id, container_name=nil, status_text=nil)
return nil if @item_filter and not @item_filter.call(item)
return add_item!(item, container_id, container_name, status_text)
end
def marked
return true if (@status_filter & MARKED) != 0
return false if (@status_filter & UNMARKED) != 0
return nil
end
def marked=(v)
@status_filter &= (MARKED|UNMARKED)
@status_filter |= MARKED if v == true
@status_filter |= UNMARKED if v == false
end
def registered
return true if (@status_filter & REGISTERED) != 0
return false if (@status_filter & UNREGISTERED) != 0
return nil
end
def registered=(v)
@status_filter &= (REGISTERED|UNREGISTERED)
@status_filter |= REGISTERED if v == true
@status_filter |= UNREGISTERED if v == false
end
def self.status_from_text(text)
value = 0
return UNREGISTERED | UNMARKED unless text
if text =~ /registered/i
value |= REGISTERED
else
value |= UNREGISTERED
end
if text =~ /marked/i
value |= MARKED
else
value |= UNMARKED
end
end
def _get_inventory(command)
return @command_cache[command] unless @command_cache[command].nil?
lines = ForeachScript.quiet_command(
command,
/^(?:You are carrying nothing at this time|You are currently (?:wearing and )?carrying)/,
/(?:<prompt)|(?:.*items? displayed\.\)$)/,
# /(?:<prompt)|(?:items displayed.\)\b)/,
true,
5
)
unless lines
echo "Inventory request timed out."
exit
end
return (@command_cache[command] = lines)
end
def _get_locker_containers
containers = {}
GameObj.loot.each do |item|
containers[item.noun] = item if ForeachScript::PREMIUM_LOCKER_CONTAINERS[item.full_name]
end
return containers if containers.length == ForeachScript::PREMIUM_LOCKER_CONTAINERS.length
end
def _get_locker_town
if Room.current and Room.current.id
loc = Room.current.location
else
loc = Map.get_location
end
unless loc
echo "Unable to determine what location this locker is in."
return nil
end
unless loc =~ LOCKER_PATTERNS[:town_locales]
echo "Location of this room is not familiar. Unable to determine what town this locker is in."
return nil
end
return $1
end
def _get_locker_manifest
return @command_cache[:locker_manifest] if @command_cache[:locker_manifest]
@scanned_locker = true
locker_containers = _get_locker_containers
return nil unless locker_containers
return nil unless (town = _get_locker_town)
manifest_command = "locker manifest #{town}"
lines = ForeachScript.quiet_command(manifest_command, LOCKER_PATTERNS[:start])
unless lines
echo "Locker manifest request timed out."
exit
end
to_return = []
lines.each do |line|
if line =~ LOCKER_PATTERNS[:start]
unless $1 # Remote locker, not local locker
echo "Location of this room appears to be incorrect, or your locker is not open."
return nil
end
elsif line =~ LOCKER_PATTERNS[:end]
return @command_cache[:locker_manifest] = to_return
elsif line =~ LOCKER_PATTERNS[:container] or line =~ LOCKER_PATTERNS[:item]
to_return << line
end
end
echo "Locker manifest read was incomplete"
return nil
end
def ingest_locker_from_manifest
finished = false
locker_containers = _get_locker_containers
container_id = container_name = nil
lines = _get_locker_manifest
return false unless lines
lines.each do |line|
if line =~ LOCKER_PATTERNS[:container]
unless (t = locker_containers[$1])
echo "Unrecognized container noun: #{$1}"
return nil
end
container_id = t.id
container_name = t.full_name
elsif line =~ LOCKER_PATTERNS[:item]
unless container_id
manifest_command = "locker manifest #{town}"
echo "I found an item in a container before I found my first container. This shouldn't happen."
echo "Please save a copy of #{manifest_command.upcase} and contact LostRanger"
exit
end
add_item(
GameObj.new($2.dup, $3.dup, $4.dup, $1.dup, $5.dup),
container_id, container_name, $6 || ''
)
end
end
return true
end
def _ingest_inventory(command)
container_id = container_name = nil
_get_inventory(command).each do |line|
next unless line =~ INVFULL_PATTERN
case $1.length
when 2
container_id = $3
container_name = $5
@item_statuses[container_id] = ItemMatcher.status_from_text($7)
when 6
unless container_id
echo "I found an item in a container before I found my first container. This shouldn't happen."
echo "Please save a copy of INV FULL and contact LostRanger"
exit
end
add_item(
GameObj.new($3.dup, $4.dup, $5.dup, $2.dup, $6.dup),
container_id, container_name, ($7 || '')
)
else
next
end
end
return true
end
def ingest_inventory
@scanned_inv = true
return _ingest_inventory('inventory full')
end
def ingest_hands
@scanned_hands = true
return _ingest_inventory('inventory hands full')
end
def _status_from_inventory(command)
_get_inventory(command).each do |line|
next unless line =~ INVFULL_PATTERN
@item_statuses[$3] = ItemMatcher.status_from_text($7 || '')
end
end
def status_from_inventory
return if @scanned_inv
_status_from_inventory('inventory full')
end
def status_from_hands
return if @scanned_hands
_status_from_inventory('inventory hands full')
end
def ingest_container(container_id, container_name, items)
items.each {|item| add_item(item, container_id, container_name)}
end
def schedule_container(container, location='in')
h = (@pending_ingests[container.id] ||= {})
h[:item] ||= container
(h[:locations] ||= Set.new).add(location)
return h
end
def ingest_legacy_locker
GameObj.loot.each{|x|
if (loc = ForeachScript::PREMIUM_LOCKER_CONTAINERS[x.full_name])
schedule_container(x, loc)
end
}
end
def ingest_loot(location='in')
# @pending_ingests += GameObj.loot.map{|item| item.id}
GameObj.loot.each{|x| schedule_container(x, location)}
end
def ingest_desc
# @pending_ingests += GameObj.loot.map{|item| item.id}
GameObj.room_desc.each do |item|
add_item(item, "_desc", "In the room")
end
end
def ingest_ground
GameObj.loot.each do |item|
add_item(item, "_ground", "On the ground")
end
end
def ingest_worn
GameObj.inv.each do |item|
add_item(item, "_worn", "On your person")
end
end
def ingest_previous(other)
other.container_contents.each do |container_id, items|
container_name = other.container_names[container_id]
items.each{|item| add_item(item, container_id, container_name)}
end
end
def self.quiet_inv_scan_hook(xml)
if @in_sorted_view
@in_sorted_view = false if xml =~ /Total items: \d+$/
return nil
end
return nil if xml =~ /^<prompt|^s*$/
return xml unless xml =~ INV_PATTERN
@in_sorted_view = true if $3
return nil
#
# (xml =~ INV_PATTERN or xml =~ /^<prompt/ or xml =~ /^\s*$/) ? nil : xml
end
def maybe_fetch_status_data(exist)
return true if @status_filter == 0
return true if @item_statuses[exist]
return fetch_status_data(exist)
end
def fetch_status_data(exist)
if GameObj.right_hand.id == exist or GameObj.left_hand.id == exist
status_from_hands
else
status_from_inventory
status_from_hands unless @item_statuses[exist]
end
return @item_statuses[exist] && true
end
def ingest_from_name(target, position='in')
begin
ForeachScript.stop_scripts
xml = dothistimeout("look #{position} #{target}", 15, INV_PATTERN)
unless xml =~ INV_PATTERN
echo "Timed out waiting for inventory command."
exit
end
collection = $6
error = $5
exist = ($1 or $3)
name = ($2 or $4)
ensure
ForeachScript.resume_scripts
end
if error
if error.start_with?("There") # is nothing in there
echo "Container '#{target}' is empty."
return false # Not a hard error.
elsif error.start_with?("That") # is closed
echo "Container '#{target}' is closed."
exit
else
echo "Container '#{target}' was not found."
exit
end
end
if collection
# Collection of items
items = collection.split(/(?:\s*,\s*)|(?:\s+and\s+(?=[^,]*<a))/)
items.each{|item|
next unless item =~ /^(?:(.+)\s+)?<a exist="(-?\d+)" noun="([^"]*)">([^<]*)<\/a>(?:\s+(.+))?/
ingest_from_name("##{$2}", position)
}
return
end
unless exist
echo "Item ID for container '#{target}' could not be determined."
exit
end
unless GameObj.containers[exist]
echo "Inventory for container '#{target}' was not available."
exit
end
ingest_container(exist, name, GameObj.containers[exist] || [])
unless maybe_fetch_status_data(exist)
echo "The container '#{container_names[exist]}' does not appear to be in your inventory, which means that marked/registered information cannot be obtained from it."
exit
end
end
def ingest_all_pending
return if @pending_ingests.length == 0
begin
ForeachScript.stop_scripts
remaining = @pending_ingests.length
echo "Scanning #{remaining} inventor#{remaining==1 ? 'y' : 'ies'}, please wait..." # if $SAFE == 0
hook = ForeachScript.anon_hook
@in_sorted_view = false
DownstreamHook.add(hook, proc {|xml| ItemMatcher.quiet_inv_scan_hook(xml)})
@pending_ingests.each do |id, ingest|
container = ingest[:item]
if remaining != @pending_ingests.length and remaining % ForeachScript::CONTAINER_UPDATE_INTERVAL == 0
echo "Still scanning #{remaining} inventor#{remaining==1 ? 'y' : 'ies'}, please wait..." # if $SAFE == 0
end
ingest[:locations].each{|location| fput "look #{location} ##{container.id}"}
remaining -= 1
end
waitfor '<prompt'
@pending_ingests.each do |id, ingest|
ingest_container(id, ingest[:item].full_name, GameObj.containers[id] || [])
unless maybe_fetch_status_data(id)
echo "The container '#{container_names[id]}' does not appear to be in your inventory, which means that marked/registered information cannot be obtained from it."
exit
end
end
@pending_ingests.clear
ensure
ForeachScript.resume_scripts
end
end
def finalize
ingest_all_pending
seen_names = @unique && Set.new || nil
skip = @after || 0
first = @first
final_contents = {}
final_names = {}
total_items = 0
@container_contents.each do |container, contents|
# Filter by status/uniqueness
if @status_filter > 0
contents.each{|item|
unless maybe_fetch_status_data(item.id)
echo "Failed to retrieve marked/registered info for '#{item.full_name}'. Most likely this is because it is in a container not in your inventory."
exit
end
}
if @unique
contents.select!{|item| ((@item_statuses[item.id] & @status_filter) == @status_filter) && seen_names.add?(item.full_name)}
else
contents.select!{|item| (@item_statuses[item.id] & @status_filter) == @status_filter}
end
elsif @unique
contents.select!{|item| seen_names.add?(item.full_name)}
end
# Sort
if @sorted == :noun
contents.sort_by!{|x| "#{x.noun.downcase}#{x.full_name.gsub(/^(a|an|some|the)\s+/, '').downcase}"}
elsif @sorted
contents.sort_by!{|x| x.full_name.gsub(/^(a|an|some|the)\s+/, '').downcase} if @sorted
end
# Reverse
contents.reverse! if @reversed
# Handle skips
if skip >= contents.length
skip -= contents.length
next
elsif skip > 0
contents = contents.drop(skip)
skip = 0
end
if first
if first >= contents.length
first -= contents.length
else
contents = contents.first(first)
first = 0
end
end
final_contents[container] = contents
final_names[container] = @container_names[container]
total_items += contents.length
end
@container_contents = final_contents
@container_names = final_names
@total_items = total_items
@command_cache.clear
@seen_ids.clear
return total_items > 0
end
end
class DummyStatusUpdater
def status_until(status, cond=true, &block)
block.call
end
def set(*a, **kw)
# Dummy
end
end
class StatusUpdater
def initialize(script, level=1)
@script = script
@level = level
@id = "quick-foreach-#{@level}"
if @level > 1
@title = "Foreach[#{@level}]: "
@previous_quickbar = "quick-foreach-#{@level-1}"
else
@title = "Foreach: "
@previous_quickbar = 'quick'
end
@unpaused_status = 'Running'
root = REXML::Element.new("openDialog")
root.attributes['id'] = @id
root.attributes['location'] = 'quickBar'
root.attributes['title'] = 'foreach'
@xml_root = root
@xml_data = data = root.add_element(
"dialogData",
{
'id' => @id,
'clear' => true
})
data.add_element('label', {'id' => "foreachLabel-#{@level}", 'value' => @title})
@xml_status = data.add_element('label', {'id' => "foreachStatusLabel-#{@level}", 'value' => @unpaused_status})
data.add_element("sep")
data.add_element("link", {
'id' => "foreachKill-#{@level}",
'value' => "stop",
'cmd' => "#{$lich_char}kill #{@script.name}"
})
data.add_element("sep")
@xml_pause = data.add_element("link", {'id' => "foreachPauseResume-#{@level}" })
data.add_element("sep")
@xml_item = data.add_element("sep", {'id' => "foreachItemData-#{@level}"})
@xml = nil
@last_was_paused = @script.paused?
@watchdog_thread = nil
@updater_thread = nil
@hook_name = nil
before_dying { cleanup }
end
def cleanup
UpstreamHook.remove(@hook_name) if @hook_name
@watchdog_thread.kill if @watchdog_thread
@updater_thread.kill if @updater_thread
@watchdog_thread = @updater_thread = nil
if @xml
puts "<switchQuickBar id=\"#{@previous_quickbar}\" />"
puts "<closeDialog id=\"#{@id}\" />"
end
end
def set_hook
now = Time.now
@hook_name = "Foreach/QB::#{now.tv_sec}.#{now.tv_usec}-#{Random.rand(10000)}"
UpstreamHook.add(@hook_name, proc{|line|
next line unless line =~ /<c>_qlink change (.*)$/
qb = $1
if qb == @id
puts "<switchQuickBar id=\"#{@id}\"/>"
next nil
elsif qb =~ /^quick-foreach-(\d+)$/
level = $1.to_i
next if level > @level
end
@previous_quickbar = qb
next line
})
end
def start_watchdog
return if @watchdog_thread
paused = @script.paused
@watchdog_thread = Thread.new {
while true
sleep 0.25
new_paused = @script.paused?
if new_paused != paused
paused = new_paused
set
# @updater_thread.wakeup if @updater_thread
end
end
}
end
def start_monitor
return if @updater_thread
last_xml = @xml
@updater_thread = Thread.new {
while true
sleep 2
xml = @xml
unless xml == last_xml
last_xml = xml
_respond xml
end
end
}
end
def set(status: nil, item: nil, items_processed: nil, items_total: nil, percent: nil, immediate: false)
@unpaused_status = status if status
is_paused = @script.paused || status == 'Paused'
if is_paused
status = 'Paused'
else
status = @unpaused_status
end
@xml_status.attributes['value'] = status if status
a = @xml_pause.attributes
if is_paused
a['value'] = "resume"
a['cmd'] = "#{$lich_char}unpause #{@script.name}"
else
a['value'] = "pause"
a['cmd'] = "#{$lich_char}pause #{@script.name}"
end
if item
type = item.type
type = '(no type)' if type == '' || type.nil?
@xml_item.attributes['value'] = "[#{items_processed+1}/#{items_total}] (#{percent}%) ##{item.id} \"#{item.full_name}\" (#{type})"
end
new_xml = @xml_data.to_s
return if new_xml == @xml
first_run = @xml.nil?
@xml = new_xml
if first_run
puts "#{@xml_root.to_s}<switchQuickBar id=\"#{@id}\" />"
set_hook
start_watchdog
start_monitor
elsif (is_paused != @last_was_paused) || immediate
last_was_paused = is_paused
@updater_thread.wakeup # End sleep early to force an immediate update if our paused status changed.
end
end
def status_until(status, cond=true, &block)
set(status: status) if cond
block.call
set(status: 'Running') if cond
end
end
module ForeachScript
VERSION = '1.0.1 (2019-11-21)'
VERSION_INT = 1_000_001
CONFIG_VERSION = 2
# FILTER_PATTERN = /^(?:(?:(?:(.+)=)?(.+)\s+(in|on|under|behind)\s+)|(in|on|under|behind)\s+)(.+)$/
FILTER_PATTERN = /^(?:(in|on|under|behind)|(?:(?:(.+)=)?(.+?)\s+(in|on|under|behind)))\s+(.+)$/
# INV_PATTERN = /(?:(?:Peering into|In|On|Under|Behind) .* <a exist="(-?\d+)"[^>]*>([^<]*)<\/a>,? you see )|(?:[OI]n the <a exist="(-?\d+)"[^>]*>([^<]*)<\/a>:\s*$)|(There is nothing (?:in|on|under|behind) the|That is closed.|I could not find what you were referring to\.)/
HOOK = 'foreach_script_temp_hook'
HELP_URL = "https://github.com/dewiniaid/gs4-lich-scripts/blob/master/Foreach.md"
# INVFULL_PATTERN = /^( {2,})([^<]*)<a exist="(-?\d+)" noun="([^"]*)">([^<]*)<\/a>(?: ([^(]*)(?:$|(?= \()))?(?: (\(.*\)))?$/
# # Matches: 1 = leading space, 2 = prename, 3 = id, 4 = noun, 5 = name, 6 = postname, 7 = registered/marked attributes
# # You are carrying nothing at this time. -- no inventory
#
CONTAINER_UPDATE_INTERVAL = 10 # How often do we notify how many more containers are being scanned
ITEM_UPDATE_INTERVAL = 10 # How often do we notify how many more items are being processed?
COMMAND_PATTERNS = {
:move => /^(f(?:ast)?)?(?:move|mv)\s+(?:(.+)\s+)?to\s+(.*)$/i,
}
PREMIUM_LOCKER_CONTAINERS = {
'armor stand' => 'on',
'weapon rack' => 'on',
'magical item bin' => 'in',
'clothing wardrobe' => 'in',
'deep chest' => 'in'
}
@previous_matcher ||= nil
def self.puts(msg)
_respond msg
end
def self.zput(what, fast)
if fast
put what
else
fput what
end
end
def self.anon_hook(prefix = '')
now = Time.now
"Foreach::#{prefix}-#{now.tv_sec}.#{now.tv_usec}-#{Random.rand(10000)}"
end
def self.cleanup
[DownstreamHook, UpstreamHook].each{|provider|
provider.list.find_all{|name| name.start_with?('Foreach::')}.each{|name| provider.remove(name)}
}
end
def self.send_formatted(msg, mono=true)
if @stormfront
msg = REXML::Text.new(msg, respect_whitespace: true).to_s
msg.gsub!(/\*\*(.*?)\*\*/, '<preset id="whisper">\1</preset>')
msg = "<output class=\"mono\" />\n#{msg}\n<output class=\"\" />" if mono
puts msg
else
msg.gsub!('**', '')
respond msg
end
end
def self.send_help_formatted(msg)
if @stormfront
msg = REXML::Text.new(msg, respect_whitespace: true).to_s
msg.gsub!(/\*\*(.*?)\*\*/, '<preset id="whisper">\1</preset>')
msg.gsub!(/`(.*?)`/, '<preset id="speech">\1</preset>')
msg.gsub!("#{name} help", "</preset><d cmd=\"#{name} help\">#{name} help</d><preset id=\"whisper\">")
puts "<output class=\"mono\" />\n#{msg}\n<output class=\"\" />"
else
msg.gsub!('**', '')
msg.gsub!('`', '')
respond msg
end
end
def self.first_time_setup(force = false)
return if GameSettings['version'] == CONFIG_VERSION and not force
return if EXPERIMENTAL_EXPIRES
send = "#{$lich_char}send to #{@script.name}"
option = proc{|what|
cmd = "#{send} #{what.upcase}"
if @stormfront
puts " <d cmd=\"#{cmd}\">#{cmd}</d>"
else
puts " #{cmd}"
end
}
unless force
if GameSettings['version'] == 1
echo "Migrating settings from a previous version of Foreach..."
if Script.exists?('GameObjAddMore.lic')
unless Script.exists?('xmlpatch.lic')
echo "You have GameObjAddMore installed, which is deprecated and will be removed soon."
echo "The script 'xmlpatch' replaces it. I'll go install that for you now."
Script.run('repository', 'download xmlpatch.lic')
Script.run('xmlpatch')
end
echo "Done!"
puts "\nTo see what's new in this verison and view examples on how to use #{$lich_char}foreach, read the following:"
respond " #{HELP_URL}"
GameSettings['version'] = CONFIG_VERSION
return
end
end
end
echo "Starting one time setup..."
msg = ["**Welcome to ForEach version #{VERSION}**"]
msg << "**#{'-' * (msg[0].length-4)}**"
msg << "This one-time setup process will help you get started with ForEach and configure it for future use."
msg << "Once you've answered a few quick questions, you won't see these messages again."
msg << ''
if @stormfront
msg << "Click on your answers to the questions, or type '#{send} <answer>, where <answer> is your answer."
else
msg << "Type '#{send} <answer>' to answer these questions, where <answer> is your answer."
end
msg << ''
send_formatted(msg.join("\n"), false)
while true
puts "Would you like Lich to check for updates to this script on startup?\n"
option.call('yes')
option.call('no')
response = unique_get.strip.downcase
if response =~ /^y(?:es)?$/
Script.run('repository', "set-updatable #{@script.name}.lic")
Script.run('autostart', "add --global repository download-updates")
respond "If you change your mind later, enter #{$lich_char}repository unset-updatable #{@script.name}.lic"
break
elsif response =~ /^no?$/
Script.run('repository', "unset-updatable #{@script.name}.lic")
respond "If you change your mind later, enter #{$lich_char}repository set-updatable #{@script.name}.lic"
break
else
echo 'Please answer YES or NO'
end
end
puts ''
sleep 1
gameobjadd = false
gameobjaddmore = false
#
# while true
# puts [
# "ForEach has the ability to filter items by type using some functionality built-in to Lich. However,",
# " the data included in Lich is a bit outdated so some items may have the wrong type -- or have no type",
# " at all.\n",
# "\n",
# "I've written a script called 'xmlpatch' that is designed to run on startup and update Lich's data",
# " about spells and items. This script exits afterwards and requires no additional resources beyond that",