Repository navigation
Expand file tree
/
Copy pathProperty explorer.lua
More file actions
896 lines (806 loc) · 31.4 KB
/
Copy pathProperty explorer.lua
File metadata and controls
896 lines (806 loc) · 31.4 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
local sim = require 'sim-2'
local simUI
local cbor
local settings
function sysCall_info()
return {menu = 'Developer tools\nProperty explorer'}
end
function sysCall_init()
if sim.app.headlessMode ~= sim.headlessMode.disabled then
sim.app:logWarn('Property Explorer cannot start in headless mode')
return {cmd = 'cleanup'}
end
cbor = require 'simCBOR'
cbor.NULL_VALUE = setmetatable({}, {__tostring = function() return 'null' end})
cbor.SIMPLE[22] = function(pos) return cbor.NULL_VALUE, pos, 'null' end
settings = sim.PropertyGroup(sim.app, {prefix = 'customData.propertyExplorer'})
simUI = require 'simUI'
disableDuringSim = not not settings.disableDuringSim
settings.disableDuringSim = disableDuringSim
target = sim.scene
superTarget = target
selectedProperty = ''
filterMatching = '*'
filterInvert = false
uiCollapseProps = {}
uiTargetRadio = 1
uiSize = {350, 600}
local ok, err = pcall(function()
uiPos = settings.uiPos or uiPos
uiSize = settings.uiSize or uiSize
uiPropsState = settings.uiPropsState or uiPropsState
uiCollapseProps = settings.uiCollapseProps or uiCollapseProps
uiTargetRadio = settings.uiTargetRadio or uiTargetRadio
end)
if not ok then
sim.app:logError('Failed to restore saved settings: ' .. err)
end
if uiTargetRadio == 1 then target = sim.app end
createUi()
apidoc = require('sim.apidoc')
end
function sysCall_beforeSimulation()
disableDuringSim = settings.disableDuringSim == true
if disableDuringSim then
restoreAfterSimulation = {target = target}
destroyUi()
end
end
function sysCall_afterSimulation()
if restoreAfterSimulation then
setTarget(restoreAfterSimulation.target, 'afterSimulation')
createUi()
onTargetChanged()
restoreAfterSimulation = nil
end
end
function sysCall_addOnScriptSuspend()
return {cmd = 'cleanup'}
end
function sysCall_cleanup()
destroyUi()
end
function sysCall_afterInstanceSwitch()
setTarget(sim.scene, 'afterInstanceSwitch') -- otherwise we get a crash (is it still needed after the change to sim.app.current?)
-- force a target change event, otherwise switching scene where the same
-- handle is selected won't trigger a target change:
onTargetChanged()
oldTarget = target
end
function sysCall_suspended()
if leaveNow then return {cmd = 'cleanup'} end
checkTargetChanged()
end
function sysCall_nonSimulation()
if leaveNow then return {cmd = 'cleanup'} end
checkTargetChanged()
end
function sysCall_sensing()
if leaveNow then return {cmd = 'cleanup'} end
checkTargetChanged()
end
function sysCall_event(events)
if not ui then return end
if target == nil or propertiesInfos == nil then return end
if not target:isValid() then
-- target was removed. switch to superTarget:
if superTarget == target then superTarget = sim.scene end
setTarget(superTarget, 'sysCall_event:removed')
onTargetChanged()
return
end
events = cbor.decode(events)
local b, plistChanged = false, false
for _, e in ipairs(events) do
if e.handle == target.handle and e.event == 'objectChanged' then
b = true
for k, v in pairs(e.data) do
if propertiesInfos[k] == nil and v ~= cbor.NULL_VALUE then
plistChanged = true
elseif propertiesInfos[k] ~= nil and v == cbor.NULL_VALUE then
plistChanged = true
end
end
end
end
if not b then return end
if plistChanged then
-- some property was added or removed
onTargetChanged()
return
end
local changedRows = {}
for _, e in ipairs(events) do
if e.handle == target.handle and e.event == 'objectChanged' then
for pname, pvalue in pairs(e.data) do
local i = propertyNameToIndex[pname]
if i then
updateTableRow(i)
changedRows[i - 1] = {
pname = tableRows.pname[i],
ptype = tableRows.ptype[i],
pvalue = tableRows.pvalue[i],
pflag = tableRows.pflags[i],
pdisplayk = tableRows.pdisplayk[i],
pdisplayv = tableRows.pdisplayv[i],
icon = tableRows.icon[i],
description = tableRows.description[i],
}
end
end
end
end
local changedIndexes = {}
local pnames = {}
local ptypes = {}
local pvalues = {}
local pflags = {}
local pdisplayk = {}
local pdisplayv = {}
local icons = {}
local descriptions = {}
for i, chg in pairs(changedRows) do
table.insert(changedIndexes, i)
table.insert(pnames, chg.pname)
table.insert(ptypes, chg.ptype)
table.insert(pvalues, chg.pvalue)
table.insert(pflags, chg.pflag)
table.insert(pdisplayk, chg.pdisplayk)
table.insert(pdisplayv, chg.pdisplayv)
table.insert(icons, chg.icon)
table.insert(descriptions, chg.description)
end
if #changedIndexes > 0 then
simUI.setPropertiesRows(ui, ui_properties, changedIndexes, pnames, ptypes, pvalues, pflags, pdisplayk, pdisplayv, icons, descriptions)
end
end
function getObjectName(o)
if o.name then
return o.name
elseif o.scriptName then
return o.scriptName
end
end
function getTitle()
local t = 'Property Explorer'
if target then
t = t .. ': ' .. target.type .. ' ' .. target.handle
local n = getObjectName(target)
if n then
t = t .. ' (' .. n .. ')'
end
end
return t
end
function getSubObjects(obj)
if obj == sim.app then
return table.add(
sim.app.addOns,
sim.app.customClasses,
sim.app.customObjects,
sim.app.customSceneObjectClasses
)
elseif obj == sim.scene then
return table.add(
{mainScript},
sim.scene.collections,
sim.scene.customObjects,
sim.scene.drawingObjects
)
elseif obj.type == 'shape' then
return obj.meshes
elseif obj.type == 'scriptObject' then
return {obj.script}
end
end
function getSuperObject(obj)
if obj.type == 'collection' or obj.type == 'drawingObject' then
return sim.scene
elseif obj.type == 'mesh' then
return obj.shape
elseif obj.type == 'script' then
if table.find(sim.app.addOns, obj) then
return sim.app
end
for _, obj1 in ipairs(sim.scene.objects) do
if obj1.type == 'scriptObject' and obj1.script == obj then
return obj1
end
end
elseif table.find(sim.app.customClasses, obj) then
return sim.app
elseif table.find(sim.app.customObjects, obj) then
return sim.app
elseif table.find(sim.app.customSceneObjectClasses, obj) then
return sim.app
elseif table.find(sim.scene.customObjects, obj) then
return sim.scene
end
return obj
end
function checkTargetChanged()
target = sim.app.current
if target ~= oldTarget then
onTargetChanged()
oldTarget = target
end
end
function setTarget(t)
target = t
superTarget = getSuperObject(t)
end
function onSubTargetChanged(ui, id, i)
local obj = sim.Object:toobject(comboHandles[i + 1])
setTarget(obj, 'onSubTargetChanged')
end
function getFilteringPattern()
local pat = filterMatching
pat = string.gsub(pat, '%.', '%%.')
pat = string.gsub(pat, '%*', '.*')
pat = '^' .. pat .. '$'
return pat
end
local CLASS_PRIORITY = {
object = 1,
sceneObject = 2,
}
local function classOrder(ca, cb)
local pa = CLASS_PRIORITY[ca] or 100
local pb = CLASS_PRIORITY[cb] or 100
if pa ~= pb then
return pa < pb
else
return ca < cb
end
end
function propertyOrder(a, b)
local ca = propertiesInfos[a].class
local cb = propertiesInfos[b].class
if ca ~= cb then
return classOrder(ca, cb)
else
return a < b
end
end
function generateTree(pnames)
-- 1) insert nodes
-- 2) generate propertyNameToIndex table
tableRows = {type = {}, icon = {}, pname = {}, ptype = {}, pvalue = {}, pflags = {}, pdisplayk = {}, pdisplayv = {}, description = {}}
propertyNameToIndex = {} -- index for single row update
local function isCollapsed(pa)
for i = 1, #pa do
local p = table.join(table.slice(pa, 1, i), '.')
if uiCollapseProps[p .. '.'] then return true end
end
end
local function indent(i)
return string.rep(' ', i - 1)
end
local lastPClass = nil
local prefix, prefixa = '', {}
local newPrefix, newPrefixa
for _, pname in ipairs(pnames) do
local pnamea = string.split(pname, '%.')
-- insert header at class break:
local pclass = propertiesInfos[pname].class
if pclass ~= lastPClass then
table.insert(tableRows.type, 'classHeader')
table.insert(tableRows.icon, 0)
table.insert(tableRows.pname, pclass)
table.insert(tableRows.pdisplayk, '[' .. pclass .. ']')
lastPClass = pclass
propertyNameToIndex[pclass] = #tableRows.pname
end
-- check for prefix, add header & strip prefix from names:
newPrefixa = table.slice(pnamea, 1, #pnamea - 1)
newPrefix = table.join(newPrefixa, '.') .. '.'
if newPrefix ~= prefix then
local m = 0
while prefixa[m+1] == newPrefixa[m+1] and (prefixa[m+1] or newPrefixa[m+1]) do m = m + 1 end
for i = m + 1, #newPrefixa do
local px = table.join(table.slice(newPrefixa, 1, i), '.') .. '.'
if i <= 1 or not isCollapsed(table.slice(newPrefixa, 1, i - 1)) then
table.insert(tableRows.type, 'treeNode')
table.insert(tableRows.icon, uiCollapseProps[px] and 2 or 1)
table.insert(tableRows.pname, px)
table.insert(tableRows.pdisplayk, indent(i) .. newPrefixa[i])
propertyNameToIndex[px] = #tableRows.pname
end
end
end
prefix, prefixa = newPrefix, newPrefixa
if not isCollapsed(prefixa) then
table.insert(tableRows.type, 'property')
table.insert(tableRows.icon, 0)
table.insert(tableRows.pname, pname)
table.insert(tableRows.pdisplayk, indent(#pnamea) .. pnamea[#pnamea])
propertyNameToIndex[pname] = #tableRows.pname
end
end
end
function readTargetProperties()
propertiesValues = target:getProperties{skipLarge = true}
propertiesInfos = target:getPropertiesInfos()
matchingPropertiesNames = {}
methods = {}
local pat = getFilteringPattern()
local strFindError
for pname, pinfo in pairs(propertiesInfos) do
local ok, m = pcall(string.find, pname, pat)
if ok then
if (m and not filterInvert) or (not m and filterInvert) then
if pinfo.type == sim.propertytype_group then
-- groups are deduced from properties names; ignored
elseif pinfo.type == sim.propertytype_method then
table.insert(methods, pname)
else
table.insert(matchingPropertiesNames, pname)
end
end
else
strFindError = strFindError or m
end
end
simUI.setStyleSheet(ui, ui_filter, strFindError and 'border: 1px solid red' or '')
table.sort(matchingPropertiesNames, propertyOrder)
table.sort(methods, propertyOrder)
generateTree(matchingPropertiesNames)
end
function toSimpleString(v, pname)
if v == nil then return '' end
local impr = settings.impr ~= false
local ptype = propertiesInfos[pname].type
if ptype == sim.propertytype_handle or ptype == sim.propertytype_handlearray then
v = v.handle
elseif ptype == sim.propertytype_enum then
v = string.format('%d (%s)', target:getIntProperty(pname), target:getStringProperty(pname))
elseif table.find({
sim.propertytype_color,
sim.propertytype_vector2,
sim.propertytype_vector3,
sim.propertytype_matrix3x3,
sim.propertytype_matrix4x4,
sim.propertytype_matrix,
sim.propertytype_quaternion,
sim.propertytype_pose
}, ptype) then
v = v:data()
elseif impr and pname:endswith 'Time' and (ptype == sim.propertytype_float or ptype == sim.propertytype_int) then
local seconds = math.floor(v)
local milliseconds = math.floor((v - seconds) * 1000)
if seconds > 60 * 60 * 24 then
v = os.date("%Y-%m-%d %H:%M:%S", seconds) .. string.format(".%03d", milliseconds)
else
v = string.format("%02d:%02d:%02d.%03d", seconds // 3600, (seconds // 60) % 60, seconds % 60, milliseconds)
end
end
return string.anytostring(v, {omitQuotes = true})
end
function convertPropertyValue(value, fromType, toType)
if fromType == toType then
return value
elseif fromType == sim.propertytype_string then
local fn, err = loadstring(
'local sim = require "sim-2"; ' ..
'local simEigen = require "simEigen"; ' ..
'return ' .. value
)
if not fn then return nil, err end
local ok, val = pcall(fn)
if ok then return val, nil else return nil, val end
elseif toType == sim.propertytype_string then
return string.anytostring(value)
end
error 'unsupported type of conversion'
end
function updateTableRow(i, updateSingle)
local pname = tableRows.pname[i]
if tableRows.type[i] == 'classHeader' then
-- class group header
tableRows.ptype[i] = ''
tableRows.pvalue[i] = ''
tableRows.pflags[i] = -1
tableRows.pdisplayv[i] = ''
tableRows.description[i] = ''
elseif tableRows.type[i] == 'treeNode' then
-- prefix group header
tableRows.ptype[i] = '...'
tableRows.pvalue[i] = ''
tableRows.pflags[i] = -2
local prefixa = string.split(pname, '%.')
tableRows.pdisplayv[i] = ''
tableRows.description[i] = ''
elseif tableRows.type[i] == 'property' then
-- normal row
propertiesInfos[pname] = target:getPropertyInfos(pname, {label=true})
local flags = propertiesInfos[pname].flags
if flags.readable then
if not flags.large then
propertiesValues[pname] = target:getProperty(pname)
end
end
local ptypeStr = sim.app:getPropertyTypeString(propertiesInfos[pname].type)
ptypeStr = ptypeStr:gsub('array(%d+)$', '[%1]')
ptypeStr = ptypeStr:gsub('array$', '[]')
tableRows.ptype[i] = ptypeStr
tableRows.pvalue[i] = convertPropertyValue(propertiesValues[pname], propertiesInfos[pname].type, sim.propertytype_string)
tableRows.description[i] = propertiesInfos[pname].description or ''
if tableRows.pvalue[i] == nil then tableRows.pvalue[i] = '' end
tableRows.pflags[i] = flags.value
if flags.large then
tableRows.pdisplayv[i] = '<big data>'
tableRows.pflags[i] = -3
elseif flags.silent then
tableRows.pdisplayv[i] = '<silent>'
tableRows.pflags[i] = -3
elseif not flags.readable then
tableRows.pdisplayv[i] = flags.writable and '<write-only>' or '<not readable>'
tableRows.pflags[i] = -3
else
tableRows.pdisplayv[i] = toSimpleString(propertiesValues[pname], pname)
tableRows.pdisplayv[i] = string.elide(tableRows.pdisplayv[i], 30, {truncateAtNewLine=true})
end
if ptypeStr == 'buffer' and tableRows.pflags[i] >= 0 then
tableRows.pflags[i] = -3
end
end
if updateSingle then
simUI.setPropertiesRow(ui, ui_properties, i - 1, tableRows.pname[i], tableRows.ptype[i], tableRows.pvalue[i], tableRows.pflags[i], tableRows.pdisplayk[i], tableRows.pdisplayv[i], tableRows.icon[i], tableRows.description[i])
end
end
function onTargetChanged()
readTargetProperties()
simUI.setTitle(ui, getTitle())
selectedRow = -1
for i, pname in ipairs(tableRows.pname) do
if selectedProperty == pname then
selectedRow = i
end
updateTableRow(i)
end
simUI.setProperties(ui, ui_properties, tableRows.pname, tableRows.ptype, tableRows.pvalue, tableRows.pflags, tableRows.pdisplayk, tableRows.pdisplayv, tableRows.icon, tableRows.description)
if selectedRow ~= -1 then
simUI.setPropertiesSelection(ui, ui_properties, selectedRow - 1, false)
end
local simCBOR = require 'simCBOR'
local methodListItems = {}
for i, method in ipairs(methods) do
local className = propertiesInfos[method].class or 'N/A'
table.insert(methodListItems, {method, className})
end
simUI.setItems(ui, ui_methods_list, simCBOR.encode(methodListItems))
updateContextMenuForSelectedProperty()
sim.self:setEventFilters{[target] = {}}
end
function updateContextMenuForSelectedProperty()
canAssign = false
canEdit = false
canRemove = false
contextMenuKeys, contextMenuTitles = {}, {}
local function addContextMenu(key, title, enabled)
enabled = enabled ~= false
table.insert(contextMenuKeys, (enabled and '' or '#') .. key)
table.insert(contextMenuTitles, title)
end
if selectedProperty and propertiesInfos[selectedProperty] and selectedProperty:sub(1, 1) ~= '#' then
local f = propertiesInfos[selectedProperty].flags
canAssign = f.readable
canEdit = f.readable and f.writable and propertiesInfos[selectedProperty].type ~= sim.propertytype_buffer
canRemove = f.removable
if propertiesInfos[selectedProperty].label then
addContextMenu('#', propertiesInfos[selectedProperty].label)
addContextMenu('--', '')
end
addContextMenu('#', 'Name:')
addContextMenu('#', ' ' .. selectedProperty)
addContextMenu('copy', ' Copy name to clipboard')
addContextMenu('printDescription', ' Print description to console', (propertiesInfos[selectedProperty].description or '') ~= '')
addContextMenu('printInfo', ' Print info to console', true)
addContextMenu('--', '')
addContextMenu('#', 'Value:')
addContextMenu('copyValue', ' Copy value to clipboard', canAssign)
addContextMenu('printValue', ' Print value', canAssign)
if propertiesInfos[selectedProperty].type == sim.propertytype_buffer then
addContextMenu('printValueHexDump', ' Print value as hexdump', canAssign)
end
if canAssign then
addContextMenu('editInCodeEditor', ' ' .. (canEdit and 'Edit' or 'View') .. ' in code editor...', true)
end
addContextMenu('loadValueFromFile', ' Load value from file...', canEdit)
addContextMenu('saveValueToFile', ' Save value to file...', canAssign)
local ptypeStr = sim.app:getPropertyTypeString(propertiesInfos[selectedProperty].type)
if ptypeStr == 'handle' or ptypeStr == 'handlearray' then
local objects = propertiesValues[selectedProperty]
if ptypeStr == 'handle' then objects = {objects} end
if #objects > 0 then
addContextMenu('--', '')
end
local prefix = 'settarget_:'
if #objects > 1 then
addContextMenu('settarget/', 'Inspect subobject')
prefix = 'settarget/:'
end
for _, object in ipairs(objects) do
local n = getObjectName(object)
n = n and (' (' .. n .. ')') or ''
addContextMenu(prefix .. object.handle, 'Inspect subobject ' .. object.handle .. n .. '...')
end
end
addContextMenu('--', '')
addContextMenu('remove', 'Remove property', canRemove)
elseif selectedProperty and selectedProperty:endswith '.' then
local cando = true
for pname, pinfo in pairs(propertiesInfos) do
if pname:startswith(selectedProperty) and not pinfo.flags.removable then
cando = false
break
end
end
addContextMenu('removeall', 'Remove ' .. selectedProperty .. '*', cando)
end
simUI.setPropertiesContextMenu(ui, ui_properties, contextMenuKeys, contextMenuTitles)
end
function onPropertyContextMenuTriggered(ui, id, key)
local args = string.split(key, ':')
key = table.remove(args, 1)
key = string.gsub(key, '/', '_')
assert(#args == 0 or #args == 1, 'invalid format')
if #args == 1 then
local json = require 'dkjson'
args = json.decode('[' .. args[1] .. ']')
end
local func = 'onContextMenu_' .. key
assert(_G[func], 'no such function: ' .. func)
_G[func](table.unpack(args))
end
function onContextMenu_printDescription()
local targetStr = gen_getObject(target)
local code = string.format('%s:getPropertyInfos(\'%s\').description',
targetStr,
selectedProperty
)
local simCmd = require 'simCmd'
simCmd.exec('lua', code)
end
function onContextMenu_printInfo()
local targetStr = gen_getObject(target)
local code = string.format('%s:getPropertyInfos(\'%s\')',
targetStr,
selectedProperty
)
local simCmd = require 'simCmd'
simCmd.exec('lua', code)
end
function onContextMenu_printValue()
printValue()
end
function onContextMenu_printValueHexDump()
printValueHexDump()
end
function onContextMenu_copy()
simUI.setClipboardText(selectedProperty)
end
function onContextMenu_copyValue()
local pvalue = target:getProperty(selectedProperty)
pvalue = convertPropertyValue(pvalue, propertiesInfos[selectedProperty].type, sim.propertytype_string)
simUI.setClipboardText(pvalue)
end
function gen_getObject(o)
if o.getName ~= nil then
return string.format('scene:getObject(\'%s\')', o:getName{mode = 'fullPath'})
elseif o == sim.scene then
return 'scene'
elseif o == sim.app then
return 'app'
else
return string.format('sim.Object(%d)', o.handle)
end
end
function onContextMenu_editInCodeEditor()
propertiesValues[selectedProperty] = target:getProperty(selectedProperty)
initialEditorContent = convertPropertyValue(propertiesValues[selectedProperty], propertiesInfos[selectedProperty].type, sim.propertytype_string)
local sz = 2 * math.min(500, #initialEditorContent)
local w = math.max(200, math.min(800, 60 * math.log(sz) + 85.21))
local h = math.max(40, math.min(1200, 50 * math.pow(sz, 0.353)))
editorHandle = sim.textEditorOpen(initialEditorContent, '<editor title="' .. (propertiesInfos[selectedProperty].flags.writable and 'Edit' or 'View') .. ' "' .. selectedProperty .. '" value" editable="' .. tostring(propertiesInfos[selectedProperty].flags.writable) .. '" searchable="true" tab-width="4" toolbar="false" statusbar="false" resizable="true" modal="true" on-close="editValueFinished" closeable="true" size="' .. math.floor(w) .. ' ' .. math.floor(h) .. '" placement="center" activate="true" line-numbers="false"></editor>')
end
function editValueFinished()
if editorHandle then
local newValue, err = sim.textEditorGetInfo(editorHandle), nil
if newValue ~= initialEditorContent then
newValue, err = convertPropertyValue(newValue, sim.propertytype_string, propertiesInfos[selectedProperty].type)
if err then
simUI.msgBox(simUI.msgbox_type.critical, simUI.msgbox_buttons.ok, 'Error', 'Failed to convert value: ' .. err)
elseif propertiesInfos[selectedProperty].flags.writable then
target:setProperty(selectedProperty, newValue)
end
end
sim.textEditorClose(editorHandle)
initialEditorContent = nil
editorHandle = nil
end
end
function onContextMenu_loadValueFromFile()
local lfsx = require 'lfsx'
local sceneDir = lfsx.dirname(sim.scene.scenePath)
local result = simUI.fileDialog(simUI.filedialog_type.load, 'Load file', sceneDir, '', '', '', true)
if #result == 1 then
local file = io.open(result[1], 'r')
local newValue = file:read('*all')
file:close()
newValue, err = convertPropertyValue(newValue, sim.propertytype_string, propertiesInfos[selectedProperty].type)
if err then
simUI.msgBox(simUI.msgbox_type.critical, simUI.msgbox_buttons.ok, 'Error', 'Failed to convert value: ' .. err)
elseif propertiesInfos[selectedProperty].flags.writable then
target:setProperty(selectedProperty, newValue)
end
end
end
function onContextMenu_saveValueToFile()
propertiesValues[selectedProperty] = target:getProperty(selectedProperty)
local value = convertPropertyValue(propertiesValues[selectedProperty], propertiesInfos[selectedProperty].type, sim.propertytype_string)
local lfsx = require 'lfsx'
local sceneDir = lfsx.dirname(sim.scene.scenePath)
local result = simUI.fileDialog(simUI.filedialog_type.save, 'Save file', sceneDir, '', '', '', true)
if #result == 1 then
local file = io.open(result[1], 'w')
file:write(value)
file:close()
print('Value of "' .. selectedProperty .. '" saved to ' .. result[1])
end
end
function onContextMenu_settarget_(handle)
sim.app.current = handle
end
function onContextMenu_remove()
if not selectedProperty then return end
if not propertiesInfos[selectedProperty] then return end
if not propertiesInfos[selectedProperty].flags.removable then return end
local targetStr = gen_getObject(target)
local code = string.format('%s:removeProperty(\'%s\')',
targetStr,
selectedProperty
)
local simCmd = require 'simCmd'
simCmd.exec('lua', code)
end
function onContextMenu_removeall()
if not selectedProperty:endswith('.') then return end
local targetStr = gen_getObject(target)
local code = string.format(
'while true do\n' ..
' n = %s:getPropertyName(0, {prefix = \'%s\'})\n' ..
' if n then %s:removeProperty(n) else break end\n' ..
'end',
targetStr,
selectedProperty,
targetStr
)
local simCmd = require 'simCmd'
simCmd.exec('lua', code)
end
function onRowSelected(ui, id, row)
if row == -1 then
selectedProperty = nil
else
selectedProperty = tableRows.pname[row + 1]
end
selectedRow = row
updateContextMenuForSelectedProperty()
end
function onRowDoubleClicked(ui, id, row, col)
if string.endswith(selectedProperty, '.') then -- it is a group
-- toggle collapse
if uiCollapseProps[selectedProperty] then
uiCollapseProps[selectedProperty] = nil
else
uiCollapseProps[selectedProperty] = true
end
settings.uiCollapseProps = uiCollapseProps
onTargetChanged()
return
end
if canAssign then printValue() end
end
function onKeyPress(ui, id, key, keystr, mods)
if key == simUI.key.F and mods.control then
filterVisible = not filterVisible
simUI.setWidgetVisibility(ui, ui_filter_grp, filterVisible)
if filterVisible then
simUI.setCurrentEditWidget(ui, ui_filter)
end
end
end
function onPropertyEdit(ui, id, key, value)
local newValue, err = convertPropertyValue(value, sim.propertytype_string, propertiesInfos[key].type)
if err then
simUI.msgBox(simUI.msgbox_type.critical, simUI.msgbox_buttons.ok, 'Error', 'Failed to convert value: ' .. err)
elseif propertiesInfos[selectedProperty].flags.writable then
target:setProperty(selectedProperty, newValue)
end
end
function onClose()
if selectedRow >= 0 then
simUI.setPropertiesSelection(ui, ui_properties, -1, false)
else
settings.autoStart = false
leaveNow = true
end
end
function onMethodSelected(ui, id, methodIndex)
local methodName = methods[methodIndex + 1]
local pclass = propertiesValues.type
local methodinfo = apidoc.getMethod(pclass, methodName)
local info = methodinfo and methodinfo:getDoc() or methodName
simUI.setText(ui, ui_methods, info)
end
function setFilter(flt, inv)
simUI.setEditValue(ui, ui_filter, flt)
simUI.setCheckboxValue(ui, ui_filter_invert, inv and 2 or 0)
updateFilter()
end
function updateFilter()
filterMatching = simUI.getEditValue(ui, ui_filter)
filterInvert = simUI.getCheckboxValue(ui, ui_filter_invert) > 0
onTargetChanged()
end
function printValue()
local simCmd = require 'simCmd'
local targetStr = gen_getObject(target)
local code = string.format('%s.%s', targetStr, selectedProperty)
simCmd.exec('lua', code)
end
function printValueHexDump()
local simCmd = require 'simCmd'
local targetStr = gen_getObject(target)
local code = string.format('utils.hexdump(%s.%s)', targetStr, selectedProperty)
simCmd.exec('lua', code)
end
function createUi()
if not ui then
local pos, sz = 'position="-30,160" placement="relative"', ''
if uiPos then
pos = ' position="' .. uiPos[1] .. ',' .. uiPos[2] .. '" placement="absolute"'
end
if uiSize then
sz = ' size="' .. uiSize[1] .. ',' .. uiSize[2] .. '"'
end
xml = '<ui title="Property Explorer" spacing="0" activate="false" closeable="true" on-close="onClose" resizable="true"' .. pos .. sz .. '>'
xml = xml .. '<group id="${ui_filter_grp}" visible="false" flat="true" layout="hbox" content-margins="0,0,0,0">'
xml = xml .. '<label text="Filter:" />'
xml = xml .. '<edit id="${ui_filter}" value="' .. filterMatching .. '" on-change="updateFilter" />'
xml = xml .. '<checkbox id="${ui_filter_invert}" text="Invert" checked="' .. tostring(filterInvert) .. '" on-change="updateFilter" />'
xml = xml .. '</group>'
xml = xml .. '<tabs document-mode="true" tab-position="south">'
xml = xml .. '<tab title="Properties" content-margins="0,0,0,0">'
xml = xml .. '<properties id="${ui_properties}" on-selection-change="onRowSelected" on-double-click="onRowDoubleClicked" on-property-edit="onPropertyEdit" on-context-menu-triggered="onPropertyContextMenuTriggered" on-key-press="onKeyPress">'
xml = xml .. '</properties>'
xml = xml .. '</tab>'
xml = xml .. '<tab title="Methods" content-margins="0,0,0,0">'
xml = xml .. '<table id="${ui_methods_list}" selection-mode="row" show-horizontal-header="false" on-selection-change="onMethodSelected">'
xml = xml .. '<header><item>Method</item><item>Class</item></header>'
xml = xml .. '</table>'
xml = xml .. '<text-browser id="${ui_methods}">'
xml = xml .. '</text-browser>'
xml = xml .. '</tab>'
xml = xml .. '</tabs>'
xml = xml .. '</ui>'
ui = simUI.create(xml)
if uiPropsState then
simUI.setPropertiesState(ui, ui_properties, uiPropsState)
end
end
end
function destroyUi()
if ui then
uiPos = {simUI.getPosition(ui)}
uiSize = {simUI.getSize(ui)}
uiPropsState = simUI.getPropertiesState(ui, ui_properties)
settings.uiPos = uiPos
settings.uiSize = uiSize
settings.uiPropsState = uiPropsState
simUI.destroy(ui)
ui = nil
end
end
require('addOns.autoStart').setup{ns = 'propertyExplorer'}