-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpe_query.py
More file actions
1720 lines (1537 loc) · 69.6 KB
/
Copy pathpe_query.py
File metadata and controls
1720 lines (1537 loc) · 69.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
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
#!/usr/bin/env python3
# Copyright (c) 2025-2026 Gigasoft, Inc. All rights reserved.
"""
pe_query.py - ProEssentials AI Query Tool v4.3
=================================================
Provides token-efficient access to the full ProEssentials API documentation.
AI assistants run this to get specific property, enum, event, function,
and example data on demand.
v4.3 CHANGES:
SCORING: Usage weight added to feature search scoring. Feature groups
with more examples rank higher (capped at +20). Improves
ranking for heavily-used features like manual-scaling.
v4.2 CHANGES:
FEATURES: pe-feature-index.json -- 69 feature groups, 590+ synonyms,
canonical enums/methods/events per group, 116 examples indexed.
New commands: features, example-features, features --list.
v4 ARCHITECTURE:
PRIMARY: net-complete-enriched.json -- .NET paths extracted from DLL binary (ground truth)
DESCRIPTIONS: ProEssentials_unified-docs.json -- rich descriptions, comments, seeAlso, keywords
EXAMPLES: ProEssentials_allExamples.json -- 116 C# & C++ examples with code
Usage:
python pe_query_v4.py props "Subsets,Points,Y,X"
python pe_query_v4.py props --category data --object Pesgo
python pe_query_v4.py search "real-time circular"
python pe_query_v4.py enum "GraphPlottingMethod"
python pe_query_v4.py events [--object Pego]
python pe_query_v4.py functions [--type net|dll]
python pe_query_v4.py methods "PeData.Y"
python pe_query_v4.py examples --feature "real-time"
python pe_query_v4.py examples --prop "CircularBuffers"
python pe_query_v4.py example 145 [--lang csharp|cpp]
python pe_query_v4.py related "CircularBuffers"
python pe_query_v4.py recipe "real-time"
python pe_query_v4.py validate "PeColor.Desk,PeData.Y,PeColor.DeskColor"
Output is always compact text optimized for AI context windows, never JSON.
Designed to run in the same folder as the JSON data files.
"""
import json
import sys
import re
import os
import argparse
from pathlib import Path
# -
# Constants
# -
VERSION = "4.3"
BASIC_EXAMPLES = ["000", "100", "200", "300", "400"]
UBIQUITOUS_THRESHOLD = 20
MAX_EXAMPLE_BADGES = 3
OBJ_SHORT = {
"Pego": "Pg", "Pesgo": "Sg", "Pe3do": "3D",
"Pepso": "Po", "Pepco": "Pi"
}
OBJ_ALL = list(OBJ_SHORT.keys())
# -
# Data Loading & Index Building
# -
class PEDocs:
"""Loads ProEssentials JSON data and provides query methods.
v4: enriched.json is primary truth source for .NET paths and types.
unified-docs.json provides rich descriptions, comments, seeAlso.
"""
def __init__(self, enriched_path, unified_path, examples_path, feature_index_path=None):
enriched = json.load(open(enriched_path, encoding="utf-8"))
unified = json.load(open(unified_path, encoding="utf-8"))
self.examples = json.load(open(examples_path, encoding="utf-8"))
# Feature index (synonym-based feature search)
self.feature_index = None
if feature_index_path:
try:
self.feature_index = json.load(open(feature_index_path, encoding="utf-8"))
except Exception:
pass
# - PRIMARY: enriched data (correct paths from DLL) -
self.properties = enriched.get("properties", [])
self.methods = enriched.get("methods", [])
self.events_list = enriched.get("events", [])
self.enums_list = enriched.get("enums", [])
self.structs = enriched.get("structs", [])
# - SECONDARY: unified-docs (descriptions, seeAlso, examples) -
self.unified_props = unified.get("properties", [])
self.unified_enums = unified.get("enums", {})
self.unified_functions = unified.get("functions", {})
self.unified_events = unified.get("events", {})
self.unified_structures = unified.get("structures", [])
# Build enriched enum dict: name -> enum
self.enums = {}
for e in self.enums_list:
self.enums[e["name"]] = e
# - INDEX: property lookup by path, name, dll constant -
self._prop_by_path = {} # "PeColor.Desk" -> prop
self._prop_by_name = {} # "deskcolor" -> prop (lowercase)
self._prop_by_dll = {} # "PEP_dwDESKCOLOR" -> prop
self._all_paths = set()
for p in self.properties:
path = p.get("path", "")
name = p.get("name", "")
dlls = p.get("dllConstants", [])
if path:
self._prop_by_path[path] = p
self._prop_by_path[path.lower()] = p
self._all_paths.add(path)
if name:
key = name.lower()
# Don't overwrite with less-specific path
if key not in self._prop_by_name or len(path) < len(self._prop_by_name[key].get("path", "")):
self._prop_by_name[key] = p
for dll in dlls:
if dll.startswith("PEP_"):
self._prop_by_dll[dll] = p
self._prop_by_dll[dll.lower()] = p
# - INDEX: method lookup by parent path -
self._methods_by_parent = {} # "PeData.Y" -> [method, ...]
for m in self.methods:
mpath = m.get("path", "")
parts = mpath.rsplit(".", 1)
if len(parts) == 2:
parent = parts[0]
# Strip overload suffix (#2, #3, etc.)
self._methods_by_parent.setdefault(parent, []).append(m)
# - INDEX: unified description lookup by DLL constant -
self._unified_by_dll = {}
self._unified_by_name = {}
for up in self.unified_props:
cpp = up.get("cppConstant", "")
if cpp:
self._unified_by_dll[cpp] = up
uname = up.get("name", "")
if uname:
self._unified_by_name[uname.lower()] = up
# - INDEX: unified event lookup -
self._unified_net_events = {}
for e in self.unified_events.get("net", []):
self._unified_net_events[e["name"]] = e
self._unified_msg_events = {}
for e in self.unified_events.get("messages", []):
self._unified_msg_events[e["name"]] = e
self._build_crossref_index()
def _get_rich_desc(self, prop, max_len=500):
"""Get rich description from unified-docs by matching DLL constant."""
dlls = prop.get("dllConstants", [])
up = None
for dll in dlls:
up = self._unified_by_dll.get(dll)
if up:
break
if not up:
up = self._unified_by_name.get(prop.get("name", "").lower())
if not up:
return prop.get("description", "")
desc = up.get("description", "")
comments = up.get("commentsHtml", "") or up.get("comments", "")
if comments and len(desc) < max_len:
cleaned = self._clean_desc(comments, max_len - len(desc))
if cleaned:
desc = desc.rstrip() + " " + cleaned
return desc
def _get_see_also(self, prop):
"""Get seeAlso from unified-docs."""
dlls = prop.get("dllConstants", [])
up = None
for dll in dlls:
up = self._unified_by_dll.get(dll)
if up:
break
if not up:
up = self._unified_by_name.get(prop.get("name", "").lower())
if up:
return up.get("seeAlso", [])
return []
def _build_crossref_index(self):
"""Port of DocumentationArea.js exampleIndex builder."""
self.prop_map = {}
self.func_map = {}
self.event_map = {}
prop_re = re.compile(r"(?:Pego|Pesgo|Pepso|Pe3do|Pepco)\d*\.(Pe\w+(?:\.\w+)*)")
func_re = re.compile(r"PeFunction\.(\w+)")
evt_re1 = re.compile(r"(?:Pego|Pesgo|Pepso|Pe3do|Pepco)\d*\.(Pe\w+)\s*\+=")
evt_re2 = re.compile(r"(?:Pego|Pesgo|Pepso|Pe3do|Pepco)\d*_(Pe\w+)")
for ex in self.examples.values():
code = ""
if isinstance(ex.get("csharp"), dict):
code = ex["csharp"].get("code", "")
if not code:
continue
lines = code.count("\n") + 1
entry = {"id": ex["id"], "title": ex.get("title", ""), "lines": lines}
seen = set()
for m in prop_re.finditer(code):
p = m.group(1)
if p not in seen:
seen.add(p)
self.prop_map.setdefault(p, []).append(entry)
seen_f = set()
for m in func_re.finditer(code):
f = m.group(1)
if f not in seen_f:
seen_f.add(f)
self.func_map.setdefault(f, []).append(entry)
seen_e = set()
for m in evt_re1.finditer(code):
e = m.group(1)
if e not in seen_e:
seen_e.add(e)
self.event_map.setdefault(e, []).append(entry)
for m in evt_re2.finditer(code):
e = m.group(1)
if e not in seen_e:
seen_e.add(e)
self.event_map.setdefault(e, []).append(entry)
for mp in (self.prop_map, self.func_map, self.event_map):
for k in mp:
mp[k].sort(key=lambda x: x["lines"])
# -
# Example Badge Logic
# -
def _get_example_badges(self, item_key, scan_map, max_badges=MAX_EXAMPLE_BADGES):
code_scan = scan_map.get(item_key, [])
if not code_scan:
return []
if len(code_scan) >= UBIQUITOUS_THRESHOLD:
basic = None
for bid in BASIC_EXAMPLES:
for cs in code_scan:
if cs["id"] == bid:
basic = cs
break
if basic:
break
pick = basic or code_scan[0]
return [{"id": pick["id"], "title": pick["title"]}]
return [{"id": cs["id"], "title": cs["title"]} for cs in code_scan[:max_badges]]
# -
# Formatting Helpers
# -
def _applies_short(self, applies_to):
if not applies_to:
return "all"
return "|".join(OBJ_SHORT.get(o, o) for o in applies_to)
def _format_example_badges(self, badges, scan_count=0):
if not badges:
return ""
parts = []
for b in badges:
title = b.get("title", "")
if title and title != f"Example {b['id']}":
parts.append(f"{b['id']} ({title})")
else:
parts.append(b["id"])
text = ", ".join(parts)
if scan_count >= UBIQUITOUS_THRESHOLD:
text += f" (ubiquitous - in {scan_count}+ examples)"
return text
def _clean_desc(self, desc, max_len=300):
if not desc:
return ""
text = re.sub(r"<[^>]+>", "", desc)
text = re.sub(r"\s+", " ", text).strip()
if max_len and len(text) > max_len:
text = text[:max_len].rsplit(" ", 1)[0] + "..."
return text
def _resolve_type(self, p, obj=None):
"""Resolve the correct type for a property, using per-control overrides when available.
If obj is specified and typeByControl has an entry for it, returns that type.
Otherwise returns the default type."""
tbc = p.get("typeByControl")
if tbc and obj:
# Normalize obj name to match typeByControl keys (e.g., "pe3do" -> "Pe3do")
for ctrl, ctype in tbc.items():
if ctrl.lower() == obj.lower():
return ctype
return p.get("type", "")
# -
# COMMAND: props
# -
def _resolve_prop(self, name):
"""Resolve a property by name, path, or DLL constant."""
name_s = name.strip()
name_l = name_s.lower()
# Exact path match (case insensitive)
p = self._prop_by_path.get(name_l)
if p:
return p
# Exact name match
p = self._prop_by_name.get(name_l)
if p:
return p
# DLL constant
p = self._prop_by_dll.get(name_s) or self._prop_by_dll.get(name_l)
if p:
return p
# Try matching last segment of path
matches = [pr for pr in self.properties if pr.get("path", "").rsplit(".", 1)[-1].lower() == name_l]
if len(matches) == 1:
return matches[0]
if matches:
# Return shortest path (most general)
return min(matches, key=lambda pr: len(pr.get("path", "")))
# Partial match (3+ chars)
if len(name_l) >= 3:
matches = [pr for pr in self.properties if name_l in pr.get("name", "").lower() or name_l in pr.get("path", "").lower()]
if len(matches) == 1:
return matches[0]
return None
def cmd_props(self, names=None, category=None, obj=None, list_mode=False):
results = []
if names:
for name in names:
prop = self._resolve_prop(name)
if not prop:
# Try partial match for ambiguity message
name_l = name.strip().lower()
if len(name_l) >= 3:
matches = [p for p in self.properties if name_l in p.get("name", "").lower()]
else:
matches = []
if matches:
results.append(f"=== {name} === AMBIGUOUS ({len(matches)} matches)")
for m in matches[:10]:
results.append(f" {m['path']} ({self._applies_short(m.get('appliesTo'))})")
else:
results.append(f"=== {name} === NOT FOUND")
continue
results.append(self._format_property(prop, obj=obj))
else:
filtered = self.properties
if category:
# Map enriched sourceClass to categories
cat_l = category.lower()
filtered = [p for p in filtered if self._matches_category(p, cat_l)]
if obj:
obj_l = obj.lower()
filtered = [p for p in filtered if any(o.lower() == obj_l for o in p.get("appliesTo", []))]
if list_mode or (not names and not category and not obj):
if not filtered:
return "No properties found."
lines = [f"=== Properties ({len(filtered)} results) ==="]
for p in filtered:
lines.append(f" {p['path']}|{self._resolve_type(p, obj)}|{self._applies_short(p.get('appliesTo'))}")
return "\n".join(lines)
for p in filtered:
results.append(self._format_property(p, obj=obj))
return "\n\n".join(results) if results else "No properties found."
def _matches_category(self, prop, cat_l):
"""Match property to a category keyword."""
path = prop.get("path", "").lower()
source = prop.get("sourceClass", "").lower()
name = prop.get("name", "").lower()
# Use enriched path prefix for categorization
cat_map = {
"data": ["pedata."],
"color": ["pecolor."],
"plot": ["peplot."],
"grid": ["pegrid."],
"axis": ["pegrid.configure.", "pegrid.option.axis", "pegrid.zoom."],
"font": ["pefont."],
"annotation": ["peannotation."],
"interaction": ["peuserinterface."],
"ui": ["peuserinterface."],
"legend": ["pelegen."],
"string": ["pestring."],
"special": ["pespecial."],
"configure": ["peconfigure."],
"function": ["pefunction."],
"table": ["petable.", "peannotation.table."],
"realtime": [], # Special: match on property names
"export": ["peuserinterface.dialog.export", "peuserinterface.dialog.allow"],
}
prefixes = cat_map.get(cat_l, [])
for prefix in prefixes:
if path.startswith(prefix):
return True
# Fallback: check unified category
up = self._unified_by_name.get(name)
if up and up.get("category", "").lower() == cat_l:
return True
return False
def _format_property(self, p, obj=None):
lines = []
path = p.get("path", "")
name = p.get("name", "")
ptype = self._resolve_type(p, obj)
dlls = p.get("dllConstants", [])
dll_str = dlls[0] if dlls else ""
applies = self._applies_short(p.get("appliesTo"))
lines.append(f"=== {name} ===")
lines.append(f"{path}|{dll_str}|{ptype}|{applies}")
# Show per-control type overrides when they exist
tbc = p.get("typeByControl")
if tbc:
overrides = ", ".join(f"{c}:{t}" for c, t in sorted(tbc.items()))
lines.append(f"TypeByControl: default={p.get('type','')}, {overrides}")
# Rich description from unified
desc = self._get_rich_desc(p, max_len=500)
if desc:
lines.append(self._clean_desc(desc, max_len=500))
elif p.get("description"):
lines.append(self._clean_desc(p["description"], max_len=500))
# Methods on this property (from enriched methods list)
methods = self._methods_by_parent.get(path, [])
if methods:
method_strs = []
seen = set()
for m in methods:
mname = m.get("name", "").split("#")[0] # Strip overload suffix
params = ", ".join(f"{pp.get('type','')} {pp.get('name','')}" for pp in m.get("parameters", []))
ret = m.get("returnType", "void")
sig = f"{ret} {mname}({params})"
if sig not in seen:
seen.add(sig)
method_strs.append(sig)
if method_strs:
lines.append(f"Methods: {'; '.join(method_strs[:8])}")
if len(method_strs) > 8:
lines.append(f" ... and {len(method_strs)-8} more methods")
# SeeAlso from unified
see_also = self._get_see_also(p)
if see_also:
sa_names = [s.get("name", s.get("filename", "")) for s in see_also]
lines.append(f"SeeAlso: {', '.join(sa_names[:8])}")
# Example badges
key = path # Use enriched path directly
scan_count = len(self.prop_map.get(key, []))
badges = self._get_example_badges(key, self.prop_map)
if not badges:
# Try without the first prefix segment for cross-ref compatibility
# e.g. code uses "PeData.Subsets" but enriched path is "PeData.Subsets"
badges = self._get_example_badges(key, self.prop_map)
badge_str = self._format_example_badges(badges, scan_count)
if badge_str:
lines.append(f"Examples: {badge_str}")
return "\n".join(lines)
# -
# COMMAND: methods (NEW in v4)
# -
def cmd_methods(self, parent_path):
"""List all methods on a property array (e.g., PeData.Y)."""
parent = parent_path.strip()
methods = self._methods_by_parent.get(parent, [])
if not methods:
# Try case-insensitive
parent_l = parent.lower()
for k, v in self._methods_by_parent.items():
if k.lower() == parent_l:
methods = v
parent = k
break
if not methods:
return f"No methods found for '{parent_path}'. Try: PeData.Y, PeData.X, PeString.PointLabels, etc."
lines = [f"=== Methods on {parent} ({len(methods)}) ==="]
seen = set()
for m in methods:
mname = m.get("name", "").split("#")[0]
params = ", ".join(f"{pp.get('type','')} {pp.get('name','')}" for pp in m.get("parameters", []))
ret = m.get("returnType", "void")
sig = f"{ret} {mname}({params})"
if sig not in seen:
seen.add(sig)
desc = self._clean_desc(m.get("description", ""), max_len=120)
lines.append(f" {sig}")
if desc:
lines.append(f" {desc}")
return "\n".join(lines)
# -
# COMMAND: validate (NEW in v4)
# -
def cmd_validate(self, paths):
"""Validate .NET paths against the enriched truth source."""
lines = [f"=== Path Validation ==="]
for path in paths:
path = path.strip()
if not path:
continue
if path in self._all_paths:
p = self._prop_by_path.get(path.lower())
tbc = p.get('typeByControl')
tbc_note = ''
if tbc:
tbc_note = ' TypeByControl: ' + ', '.join(f'{c}:{t}' for c, t in sorted(tbc.items()))
lines.append(f" VALID {path} - {p.get('type','')} [{self._applies_short(p.get('appliesTo'))}]{tbc_note}")
else:
# Try to suggest correction
last = path.rsplit(".", 1)[-1].lower()
suggestions = [pr["path"] for pr in self.properties if pr.get("name","").lower() == last]
if suggestions:
lines.append(f" INVALID {path} - did you mean: {', '.join(suggestions[:3])}?")
else:
lines.append(f" INVALID {path}")
return "\n".join(lines)
# -
# COMMAND: search
# -
def cmd_search(self, term, max_results=20):
term_l = term.lower()
terms = term_l.split()
sections = []
# Search properties (enriched + unified descriptions)
props = []
for p in self.properties:
rich_desc = self._get_rich_desc(p, max_len=1000)
searchable = " ".join(filter(None, [
p.get("name", ""), p.get("path", ""),
" ".join(p.get("dllConstants", [])),
rich_desc, p.get("description", ""),
])).lower()
if all(t in searchable for t in terms):
props.append(p)
if props:
sections.append(f"=== Properties ({len(props)} matches) ===")
for p in props[:max_results]:
desc = self._clean_desc(p.get("description", ""), max_len=80)
sections.append(f" {p['path']}|{p.get('type','')}|{self._applies_short(p.get('appliesTo'))}|{desc}")
if len(props) > max_results:
sections.append(f" ... and {len(props)-max_results} more")
# Search DLL functions from unified
funcs = []
for ftype in ("dll", "net", "ocx"):
for f in self.unified_functions.get(ftype, []):
searchable = " ".join(filter(None, [
f.get("name", ""), f.get("description", ""),
f.get("syntax", ""),
])).lower()
if all(t in searchable for t in terms):
funcs.append((ftype, f))
if funcs:
sections.append(f"\n=== Functions ({len(funcs)} matches) ===")
for ftype, f in funcs[:max_results]:
desc = self._clean_desc(f.get("description", ""), max_len=80)
sections.append(f" [{ftype}] {f['name']}|{desc}")
# Search enriched events
evts = []
for e in self.events_list:
searchable = " ".join(filter(None, [e.get("name", ""), e.get("handlerType", "")])).lower()
if all(t in searchable for t in terms):
evts.append(e)
# Also search unified events for descriptions
for etype in ("net", "messages"):
for e in self.unified_events.get(etype, []):
searchable = " ".join(filter(None, [e.get("name", ""), e.get("description", "")])).lower()
if all(t in searchable for t in terms):
if not any(x.get("name") == e.get("name") for x in evts):
evts.append(e)
if evts:
sections.append(f"\n=== Events ({len(evts)} matches) ===")
for e in evts[:max_results]:
desc = self._clean_desc(e.get("description", ""), max_len=80)
sections.append(f" {e['name']}|{desc}")
# Search enums
enum_matches = []
for name, val in self.enums.items():
searchable = " ".join(filter(None, [
name, " ".join(v.get("name", "") for v in val.get("values", []))
])).lower()
if all(t in searchable for t in terms):
enum_matches.append((name, val))
if enum_matches:
sections.append(f"\n=== Enums ({len(enum_matches)} matches) ===")
for name, val in enum_matches[:max_results]:
sections.append(f" {name} ({len(val.get('values',[]))} values)")
if not sections:
return f"No results for '{term}'."
return "\n".join(sections)
# -
# COMMAND: enum
# -
def cmd_enum(self, name):
val = self.enums.get(name)
if not val:
name_l = name.lower()
for k, v in self.enums.items():
if k.lower() == name_l:
val = v
name = k
break
if not val:
name_l = name.lower()
matches = [(k, v) for k, v in self.enums.items() if name_l in k.lower()]
if len(matches) == 1:
name, val = matches[0]
elif matches:
lines = [f"=== Ambiguous enum '{name}' ({len(matches)} matches) ==="]
for k, v in matches:
lines.append(f" {k} ({len(v.get('values',[]))} values)")
return "\n".join(lines)
else:
return f"Enum '{name}' not found."
lines = [f"=== {name} ==="]
# Get description from unified enums
uval = self.unified_enums.get(name, {})
desc = self._clean_desc(uval.get("description", ""), max_len=200)
if desc:
lines.append(desc)
# Properties using this enum
using = [p["path"] for p in self.properties if name.lower() in p.get("type","").lower()]
if using:
lines.append(f"Used by: {', '.join(using[:8])}")
lines.append("Values:")
for v in val.get("values", []):
vname = v.get("name", "")
vval = v.get("value", "")
lines.append(f" {vname}={vval}")
return "\n".join(lines)
# -
# COMMAND: events
# -
def cmd_events(self, obj=None):
lines = []
items = self.events_list
if obj:
obj_l = obj.lower()
items = [e for e in items if any(o.lower() == obj_l for o in e.get("appliesTo", OBJ_ALL))]
if not items:
return "No events found."
lines.append(f"=== .NET Events ({len(items)}) ===")
for e in items:
name = e.get("name", "")
handler = e.get("handlerType", "")
applies = self._applies_short(e.get("appliesTo"))
# Get description from unified
ue = self._unified_net_events.get(name, {})
desc = self._clean_desc(ue.get("description", ""), max_len=100)
lines.append(f" {name}|{handler}|{applies}")
if desc:
lines.append(f" {desc}")
# Example badges
scan_count = len(self.event_map.get(name, []))
badges = self._get_example_badges(name, self.event_map)
badge_str = self._format_example_badges(badges, scan_count)
if badge_str:
lines.append(f" Examples: {badge_str}")
return "\n".join(lines)
def cmd_event(self, name):
name_l = name.lower()
# Search enriched events
for e in self.events_list:
if e.get("name", "").lower() == name_l:
return self._format_event_detail(e)
return f"Event '{name}' not found."
def _format_event_detail(self, e):
name = e.get("name", "")
lines = [f"=== {name} ==="]
lines.append(f"Handler: {e.get('handlerType','')}")
lines.append(f"EventArgs: {e.get('eventArgsType','')}")
lines.append(f"AppliesTo: {self._applies_short(e.get('appliesTo'))}")
# Rich detail from unified
ue = self._unified_net_events.get(name, {})
if ue.get("eventDeclaration"):
lines.append(f"Declaration: {ue['eventDeclaration']}")
if ue.get("arguments"):
lines.append("Arguments:")
for a in ue["arguments"]:
lines.append(f" {a.get('type','')} {a.get('name','')} - {a.get('description','')}")
desc = self._clean_desc(ue.get("description", ""), max_len=500)
if desc:
lines.append(desc)
badges = self._get_example_badges(name, self.event_map)
badge_str = self._format_example_badges(badges, len(self.event_map.get(name, [])))
if badge_str:
lines.append(f"Examples: {badge_str}")
return "\n".join(lines)
# -
# COMMAND: functions (uses unified-docs which has the rich function data)
# -
def cmd_functions(self, func_type=None, obj=None):
sections = []
types_to_show = [func_type] if func_type else ["net", "dll", "ocx"]
for ftype in types_to_show:
items = self.unified_functions.get(ftype, [])
if obj:
obj_l = obj.lower()
items = [f for f in items if any(o.lower() == obj_l for o in f.get("appliesTo", OBJ_ALL))]
if not items:
continue
sections.append(f"=== {ftype.upper()} Functions ({len(items)}) ===")
for f in items:
name = f.get("name", "")
desc = self._clean_desc(f.get("description", ""), max_len=100)
if ftype in ("net", "ocx"):
syntax = f.get("syntax", "")
applies = self._applies_short(f.get("appliesTo"))
sections.append(f" {name}|{applies}")
if syntax:
sections.append(f" {syntax}")
else:
syntax = f.get("syntax", "")
sections.append(f" {name}")
if syntax:
sections.append(f" {syntax}")
if desc:
sections.append(f" {desc}")
return "\n".join(sections) if sections else "No functions found."
def cmd_function(self, name):
name_l = name.lower()
for ftype in ("net", "dll", "ocx"):
for f in self.unified_functions.get(ftype, []):
if f.get("name", "").lower() == name_l:
return self._format_function_detail(f, ftype)
return f"Function '{name}' not found."
def _format_function_detail(self, f, ftype):
lines = [f"=== {f['name']} [{ftype}] ==="]
if f.get("syntax"):
lines.append(f"Syntax: {f['syntax']}")
if f.get("appliesTo"):
lines.append(f"AppliesTo: {self._applies_short(f['appliesTo'])}")
if f.get("parameters"):
lines.append("Parameters:")
for p in f["parameters"]:
lines.append(f" {p.get('type','')} {p.get('name','')} - {self._clean_desc(p.get('description',''), 150)}")
desc = self._clean_desc(f.get("description", ""), max_len=500)
if desc:
lines.append(desc)
see_also = f.get("seeAlso", [])
if see_also:
sa_names = [s.get("name", s.get("filename", "")) for s in see_also]
lines.append(f"SeeAlso: {', '.join(sa_names)}")
badges = self._get_example_badges(f["name"], self.func_map)
badge_str = self._format_example_badges(badges, len(self.func_map.get(f["name"], [])))
if badge_str:
lines.append(f"Examples: {badge_str}")
return "\n".join(lines)
# -
# COMMAND: examples
# -
def cmd_examples(self, feature=None, prop=None, obj=None):
results = []
if prop:
prop_l = prop.strip().lower()
p_obj = self._resolve_prop(prop)
key = p_obj.get("path", "") if p_obj else None
scan = self.prop_map.get(key, []) if key else []
if not scan:
for k in self.prop_map:
if prop_l in k.lower():
scan = self.prop_map[k]
key = k
break
if scan:
results.append(f"=== Examples using {key or prop} ({len(scan)} found) ===")
for s in scan[:15]:
results.append(f" {s['id']}|{s['title']}|{s['lines']} lines")
else:
results.append(f"No examples found using property '{prop}'.")
return "\n".join(results)
if feature:
# Try feature index synonym search first
if self.feature_index:
fi_groups = self.feature_index.get("feature_groups", {})
fi_examples = self.feature_index.get("examples", {})
terms = feature.lower().split()
matched_groups = []
for gid, gdef in fi_groups.items():
if gid in self._SUPPRESSED_GROUPS:
continue
usage_weight = min(len(gdef.get("examples_using", [])), 20)
if feature.lower() == gid or feature.lower() == gid.replace("-", " "):
matched_groups.append((gid, gdef, 100 + usage_weight))
continue
# Substring group ID match
if feature.lower() in gid:
matched_groups.append((gid, gdef, 30 + usage_weight))
continue
for syn in gdef.get("synonyms", []):
syn_l = syn.lower()
if feature.lower() in syn_l or all(t in syn_l for t in terms):
matched_groups.append((gid, gdef, 20 + usage_weight))
break
else:
desc_l = gdef.get("description", "").lower()
if all(t in desc_l for t in terms):
matched_groups.append((gid, gdef, 10 + usage_weight))
if matched_groups:
matched_groups.sort(key=lambda x: -x[2])
all_eids = []
for gid, gdef, _ in matched_groups:
for eid in gdef.get("examples_using", []):
if eid not in all_eids:
ex_data = fi_examples.get(eid, {})
if obj and not any(o.lower() == obj.lower() for o in ex_data.get("chartObjects", [])):
continue
all_eids.append(eid)
gnames = ", ".join(self._display_group_id(g[0]) for g in matched_groups[:3])
results.append(f"=== Examples for '{feature}' via groups: {gnames} ({len(all_eids)} found) ===")
for eid in all_eids[:20]:
ex = self.examples.get(eid, {})
fi_ex = fi_examples.get(eid, {})
dist = fi_ex.get("distinctive_groups", [])
star = "*" if any(g[0] in dist for g in matched_groups) else ""
results.append(f" {eid}{star}|{ex.get('chartObject','')}|{ex.get('title','')}")
if all_eids:
results.append(f" (* = feature is distinctive for that example)")
return "\n".join(results)
# Fallback: text search in example titles/descriptions/code
terms = feature.lower().split()
matches = []
for ex in self.examples.values():
searchable = " ".join(filter(None, [
ex.get("title", ""), ex.get("description", ""),
ex.get("chartObject", ""),
ex.get("csharp", {}).get("code", "")[:500]
])).lower()
if all(t in searchable for t in terms):
matches.append(ex)
if matches:
results.append(f"=== Examples matching '{feature}' ({len(matches)} found) ===")
for ex in matches[:20]:
results.append(f" {ex['id']}|{ex.get('chartObject','')}|{ex.get('title','')}")
else:
results.append(f"No examples matching '{feature}'.")
return "\n".join(results)
if obj:
obj_l = obj.lower()
matches = [ex for ex in self.examples.values() if ex.get("chartObject", "").lower() == obj_l]
if matches:
results.append(f"=== {obj} Examples ({len(matches)}) ===")
for ex in matches:
results.append(f" {ex['id']}|{ex.get('title','')}")
else:
results.append(f"No examples for '{obj}'.")
return "\n".join(results)
results.append(f"=== All Examples ({len(self.examples)}) ===")
for eid in sorted(self.examples.keys()):
ex = self.examples[eid]
results.append(f" {eid}|{ex.get('chartObject','')}|{ex.get('title','')}")
return "\n".join(results)
def cmd_example(self, example_id, lang="csharp"):
eid = str(example_id).zfill(3)
ex = self.examples.get(eid)
if not ex:
return f"Example '{eid}' not found."
lines = [f"=== Example {eid}: {ex.get('title','')} ==="]
lines.append(f"ChartObject: {ex.get('chartObject','')} ({ex.get('chartObjectFull','')})")
if ex.get("description") and ex["description"] != ex.get("title"):
lines.append(f"Description: {ex['description']}")
lang_key = lang.lower()
if lang_key in ("cs", "c#"):
lang_key = "csharp"
elif lang_key in ("c++", "c"):
lang_key = "cpp"
elif lang_key in ("vb", "vbnet", "vb.net"):
lang_key = "csharp"
lines.append("Note: VB.NET property syntax is identical to C# - same paths, same enum names, different keywords only.")
code_obj = ex.get(lang_key, {})
code = code_obj.get("code", "") if isinstance(code_obj, dict) else ""
if code:
lines.append(f"\n--- {lang_key} code ---")
lines.append(code)
else:
alt = "cpp" if lang_key == "csharp" else "csharp"
alt_obj = ex.get(alt, {})
if isinstance(alt_obj, dict) and alt_obj.get("code"):
lines.append(f"\n(No {lang_key} code, showing {alt})")
lines.append(alt_obj["code"])
else:
lines.append("No code available.")
return "\n".join(lines)
# -
# COMMAND: related
# -
def cmd_related(self, name):
prop = self._resolve_prop(name)
if not prop:
return f"Property '{name}' not found."
lines = [f"=== Related to {prop['path']} ==="]
see_also = self._get_see_also(prop)
if see_also:
lines.append(f"\nSeeAlso ({len(see_also)}):")
for sa in see_also:
sa_name = sa.get("name", sa.get("filename", ""))
sa_prop = self._resolve_prop(sa_name)
if sa_prop:
lines.append(f" {sa_prop['path']}|{sa_prop.get('type','')}|{self._applies_short(sa_prop.get('appliesTo'))}")
else:
lines.append(f" {sa_name}")
# Same path prefix siblings
path = prop.get("path", "")
prefix = path.rsplit(".", 1)[0] + "." if "." in path else ""
if prefix:
siblings = [p for p in self.properties if p.get("path","").startswith(prefix) and p["path"] != path]
if siblings:
lines.append(f"\nSame group '{prefix}*' ({len(siblings)} properties):")
for p in siblings[:20]:
lines.append(f" {p['path']}|{p.get('type','')}")
if len(siblings) > 20:
lines.append(f" ... and {len(siblings)-20} more")