1 % Heinrich Heine Universitaet Duesseldorf
2 % (c) 2021-2026 Lehrstuhl fuer Softwaretechnik und Programmiersprachen,
3 % This software is licenced under EPL 1.0 (http://www.eclipse.org/org/documents/epl-v10.html)
4
5 :- module(visb_visualiser,[load_visb_file/1,
6 load_visb_definitions_from_list_of_facts/2,
7 load_visb_definitions_from_term/2,
8 load_visb_file_if_necessary/1,
9 visb_file_is_loaded/1, visb_file_is_loaded/3,
10 visb_current_state_can_be_visualised/0, visb_state_can_be_visualised/1,
11 get_default_visb_file/2, extended_static_check_default_visb_file/0,
12 load_default_visb_file_if_necessary/0,
13 tcltk_get_visb_items/1, tcltk_get_visb_events/1,
14 tcltk_get_visb_objects/1, tcltk_get_visb_hovers/1,
15 get_visb_items/1, get_visb_attributes_for_state/2,
16 get_visb_click_events/1, get_visb_hovers/1,
17 perform_visb_click_event/4,
18 tcltk_perform_visb_click_event/1,
19 get_visb_svg_objects/1,
20 % used by visb_html_export:
21 get_change_attribute_for_state/4, get_and_eval_special_definition/6,
22 evaluate_visb_formula/6, b_value_to_string/2, add_visb_lint_message/3,
23 no_svg_available/0, match_operation/2,
24 visb_file_loaded/4, visb_svg_file/5, visb_empty_svg_box_height_width/3,
25 visb_svg_object/5, visb_svg_child/2, visb_svg_parent/2,
26 visb_svg_child_of_object_from_svg_file/1,
27 visb_has_hovers/1, visb_hover/6]).
28
29 :- use_module(probsrc(module_information),[module_info/2]).
30 :- module_info(group,visualization).
31 :- module_info(description,'This module provides VisB visualisation functionality.').
32
33 :- set_prolog_flag(double_quotes, codes).
34
35 % special SVG object attributes treated by VisB
36 % title (creates hover tooltip; currently only works with objects created by VisB itself)
37 % id
38 % svg_class
39 % text
40 % hovers
41 % event, events
42 % predicate
43
44 :- meta_predicate process_repeat(-,-,-,2).
45
46 :- use_module(extrasrc(json_parser), [json_parse_file/3]).
47 :- use_module(library(lists)).
48 :- use_module(probsrc(error_manager)).
49 :- use_module(probsrc(preferences), [get_preference/2, reset_temporary_preference/2,
50 temporary_set_preference/3]).
51 :- use_module(probsrc(debug)).
52 :- use_module(probsrc(state_space), [visited_expression/2, get_constants_id_for_state_id/2,
53 get_constants_state_id_for_id/2, set_context_state/2,
54 clear_context_state/0, transition/3, transition/4,
55 multiple_concrete_constants_exist/0,
56 root_sufficiently_explored/0,
57 is_concrete_constants_state_id/1, current_state_id/1,
58 current_state_corresponds_to_setup_constants_b_machine/0,
59 visited_state_corresponds_to_setup_constants_b_machine/1,
60 time_out_for_node/3, max_reached_for_node/1]).
61 :- use_module(probsrc(translate), [translate_bvalue_to_codes/2,
62 translate_bvalue_to_codes_with_limit/3,
63 translate_bvalue_with_limit/3, pretty_type/2]).
64 :- use_module(probsrc(specfile), [eventb_mode/0, xtl_mode/0,
65 state_corresponds_to_initialised_b_machine/2,
66 state_corresponds_to_set_up_constants_only/2,
67 translate_operation_name/2, classical_b_mode/0, b_or_z_mode/0,
68 csp_with_bz_mode/0]).
69 :- use_module(probsrc(tools), [start_ms_timer/1, stop_ms_walltimer_with_msg/2, ajoin_with_sep/3,
70 split_list/4, get_filename_extension/2, split_chars/3,
71 safe_number_codes/2, safe_atom_codes/2]).
72 :- use_module(probsrc(bmachine), [b_machine_name/1, b_get_definition_name_with_pos/4,
73 bmachine_is_precompiled/0, pre_expand_typing_scope/2,
74 determine_type_of_formula/2, determine_type_of_formula/3,
75 b_load_additional_definitions_file/1,
76 b_load_additional_definitions_from_list_of_facts/1,
77 b_load_additional_definitions_from_term/1,
78 set_additional_filename_as_parsing_default/3,
79 reset_filename_parsing_default/2,
80 b_sorted_b_definition_prefixed/4, b_get_typed_definition/3,
81 b_is_operation_name/1,
82 b_parse_machine_operation_pre_post_predicate/5]).
83 :- use_module(probsrc(bsyntaxtree), [get_texpr_ids/2, get_texpr_pos/2, create_couple/2,
84 create_couple/3, replace_ids_by_exprs/4, create_equality/3,
85 get_texpr_type/2, find_identifier_uses/3,
86 conjunct_predicates/2, map_over_bexpr/2, get_texpr_id/2]).
87 :- use_module(probsrc(tools_lists), [include_maplist/3]).
88 :- use_module(probsrc(tools_matching), [get_all_svg_attributes/1, is_svg_attribute/1,
89 is_virtual_svg_attribute/1, is_svg_number_attribute/2,
90 is_svg_color_attribute/1, svg_attribute_default_value/2,
91 get_possible_fuzzy_matches_and_completions_msg/3,
92 get_all_svg_classes/1, is_svg_shape_class/1, is_html_tag/1,
93 is_html_attribute/1, dotshape2svg_class/2,
94 fix_svg_attribute/2, is_dot_attribute/1]).
95 :- use_module(visb_json_utils, [get_attr/3, get_attr_with_pos/5,
96 del_attr/4, del_attr_with_pos/6, non_det_del_attr_with_pos/6,
97 force_del_attr/5, force_del_attr_with_pos/6,
98 get_attr_true/3, is_optional_json_item/1, is_optional_json_item/3,
99 check_json_string/4,
100 get_pos_from_list/3, construct_prob_pos_term/3,
101 replace_in_json/4, multi_replace_in_json/4,
102 check_all_same_length_json/3]).
103 :- use_module(visb_static_check, [static_check_dynamic_update_def_body/1,
104 static_check_attribute_value_expression/2,
105 check_svg_attribute_value/3]).
106 :- use_module(probsrc(eventhandling), [register_event_listener/3]).
107 :- use_module(probsrc(pref_definitions), [b_get_definition_string_from_spec/3]).
108 :- use_module(library(file_systems), [file_exists/1, file_property/3]).
109 :- use_module(probsrc(tools_strings), [ajoin/2, safe_name/2, atom_prefix/2,
110 is_simple_classical_b_identifier_codes/1]).
111 :- use_module(probsrc(custom_explicit_sets), [try_expand_custom_set_with_catch/3,
112 is_custom_explicit_set/1, is_set_value/2,
113 singleton_set/2]).
114 :- use_module(probsrc(typing_tools), [any_value_for_type/2]).
115 :- use_module(extrasrc(external_functions_svg), [svg_points/4]).
116 :- use_module(probsrc(store), [lookup_value_for_existing_id/3]).
117 :- use_module(probsrc(gensym), [gensym/2]).
118 :- use_module(probsrc(self_check)).
119 :- use_module(probsrc(external_functions), [external_function_requires_state/1]).
120 :- use_module(probsrc(kernel_reals), [is_real/2]).
121 :- use_module(probsrc(b_global_sets), [add_prob_deferred_set_elements_to_store/3]).
122 :- use_module(probsrc(b_interpreter), [b_compute_expression_nowf/7,
123 b_compute_explicit_epression_no_wf/7]).
124
125
126 % --------------------------
127
128 % facts storing loaded JSON VisB file:
129 :- dynamic visb_file_loaded/4, visb_svg_file/5, visb_empty_svg_box_height_width/3,
130 visb_definition/6, visb_special_definition/6,
131 visb_item/7,
132 visb_event/7, visb_hover/6, visb_has_hovers/1, visb_has_visibility_hover/1,
133 visb_event_enable_list/5,
134 visb_svg_object/5, visb_svg_object_debug_info/2,
135 visb_svg_child/2, visb_svg_parent/2, % register parent/child relationships for groups, title, ...
136 visb_svg_child_of_object_from_svg_file/1. % true if parent of object is an SVG in an external file
137 :- dynamic auxiliary_visb_event/6.
138 % visb_svg_file(SVGFile, AbsolutePathSVGFile, JSONFileFromWhichWeImportSVG,PosTerm,ModLocTime)
139 % visb_item(SVGID,Attribute,TypedExpression,UsedIds,Description/Comment,StartPos,OtherMetaInfos)
140 % visb_event(SVGID,Event,PredicateList,ExecutionKind,TypedPredicate,File,Pos) ; ExecutionKind: default, first, random, heuristic, explore_open or min_out_degree
141 % visb_svg_object(SVGID,SVG_Class,AttrList,Description/Comment,Pos) ; AttrList contains svg_attribute(Attr,Val)
142
143 reset_visb :- debug_println(9,resetting_visb),
144 retractall(visb_file_loaded(_,_,_,_)),
145 retractall(visb_empty_svg_box_height_width(_,_,_)),
146 retractall(visb_svg_file(_,_,_,_,_)),
147 retractall(visb_definition(_,_,_,_,_,_)),
148 retractall(visb_special_definition(_,_,_,_,_,_)),
149 retractall(visb_item(_,_,_,_,_,_,_)),
150 retractall(visb_event(_,_,_,_,_,_,_)),
151 retractall(visb_hover(_,_,_,_,_,_)),
152 retractall(visb_has_hovers(_)),
153 retractall(visb_has_visibility_hover(_)),
154 retractall(visb_event_enable_list(_,_,_,_,_)),
155 retractall(auxiliary_visb_event(_,_,_,_,_,_)),
156 retractall(visb_svg_object(_,_,_,_,_)),
157 retractall(visb_svg_object_debug_info(_,_)),
158 retractall(visb_svg_child(_,_)),
159 retractall(visb_svg_child_of_object_from_svg_file(_)),
160 retractall(visb_svg_parent(_,_)),
161 reset_auto_attrs.
162
163 visb_file_is_loaded(JSONFile) :-
164 visb_file_is_loaded(JSONFile,_,true).
165 visb_file_is_loaded(JSONFile,SVGFile,AllowEmpty) :-
166 visb_file_loaded(JSONFile,_,_,_),
167 (visb_svg_file(_,SVGFile,_,_,_) -> true
168 ; visb_empty_svg_box_height_width(_,_,_) -> SVGFile = ''
169 ; user_has_defined_visb_objects -> SVGFile = ''
170 ; JSONFile='' ->
171 AllowEmpty=true,
172 add_warning(visb_visualiser,'No VISB_SVG_FILE or VISB_SVG_OBJECTS specified in DEFINITIONS',''),
173 % Note: warning also generated below No VisB JSON file is specified and no VISB_SVG_OBJECTS were created
174 SVGFile = ''
175 ; add_warning(visb_visualiser,'No SVG file or objects specified for VisB file:',JSONFile),
176 AllowEmpty=true,
177 SVGFile = ''
178 ).
179
180 no_svg_available :-
181 \+ user_has_defined_visb_objects,
182 no_svg_file_available,
183 \+ visb_empty_svg_box_height_width(_,_,_). % no SVG box provided
184
185 no_svg_file_available :- (visb_svg_file(_,SVGFile,_,_,_) -> SVGFile='' ; true).
186 %svg_file_available :- \+ no_svg_file_available.
187
188 visb_state_can_be_visualised(ID) :-
189 (b_or_z_mode -> visited_state_corresponds_to_setup_constants_b_machine(ID)
190 ; ID \= root
191 ).
192 visb_current_state_can_be_visualised :-
193 %visb_file_is_loaded(_), % no longer checked; Tcl/Tk will automatically load VisB file if required
194 current_state_id(ID), visb_state_can_be_visualised(ID).
195
196
197 :- register_event_listener(reset_specification,reset_visb,'Reset VisB information').
198 :- register_event_listener(reset_prob,reset_visb,'Reset VisB information').
199
200 %static_check_visb :- % now done when adding items and not storing multiple items
201 % visb_item(ID,Attr,F1,_,_,Pos1), visb_item(ID,Attr,F2,_,Pos2), F1 @< F2,
202 % add_warning(visb_visualiser,'Multiple formulas for SVG identifier and attribute:',ID/Attr,Pos1),
203 % add_message(visb_visualiser,'Location of second formula for:',ID/Attr,Pos2),
204 % fail.
205 % TO DO: some sanity checks on attributes and values
206 static_check_visb :-
207 no_svg_file_available,
208 visb_hover(SVGID,_ID,Attr,_Enter,_Exit,Pos),
209 \+ svg_id_exists(SVGID),
210 ajoin(['Hover for attribute ',Attr,' has unknown trigger-id (can lead to blank visualisation): '],Msg),
211 add_warning(visb_visualiser,Msg,SVGID,Pos),
212 fail.
213 static_check_visb :-
214 no_svg_file_available,
215 visb_hover(SVGID,ID,Attr,_Enter,_Exit,Pos), ID \= SVGID,
216 \+ svg_id_exists(ID),
217 ajoin(['Hover for attribute ',Attr,' has unknown id (can lead to blank visualisation): '],Msg),
218 add_warning(visb_visualiser,Msg,ID,Pos),
219 fail.
220 static_check_visb :-
221 visb_svg_file(SvgFile,_,_,Pos,_),
222 SvgFile \= '',
223 visb_empty_svg_box_height_width(H,W,ViewBox),
224 ajoin(['VISB_SVG_BOX (width=', W, ', height=', H, ', viewBox=', ViewBox,
225 ') cannot be applied to an existing SVG file (use VISB_SVG_CONTENTS for file or put info into SVG file): '],Msg),
226 add_warning(visb_visualiser,Msg,SvgFile,Pos),
227 fail.
228 static_check_visb.
229
230 svg_id_exists(SVGID) :- visb_svg_object(SVGID,_,_StaticAttrList,_,_ExitPos).
231 svg_id_has_class(SVGID,Class) :- visb_svg_object(SVGID,Class,_StaticAttrList,_,_ExitPos).
232 % --------------------------
233
234
235 get_default_visb_file(Path, Pos) :- get_default_visb_file(Path, _, Pos).
236 get_default_visb_file(Path, Kind, Pos) :- bmachine_is_precompiled,
237 (b_get_definition_string_from_spec('VISB_JSON_FILE', Pos, Path)
238 -> Kind=json % user provided explicit path to VISB JSON file
239 ; b_get_definition_string_from_spec('VISB_DEFINITIONS_FILE', Pos, Path)
240 -> Kind=def % user provided explicit path to VISB DEFINITIONS file
241 % TODO: in future check that file extension is compatible
242 % advantage of VISB_DEFINITIONS_FILE == "File" over "File"
243 % 1) visualisation can be re-loaded without re-loading machine
244 % 2) can be used in TLA+ or similar
245 % 3) avoid clash if definitions file itself defines empty VISB_JSON_FILE
246 % 4) avoid problems with Atelier-B or other tools
247 ; get_default_visb_svg_file(_,Pos)
248 -> Kind=empty, Path='' % user provided SVG file path
249 ; user_has_defined_visb_objects_in_defs
250 -> Kind=empty, Path='' % user provided SVG object definitions
251 ).
252
253 user_has_defined_visb_objects :-
254 (visb_svg_object(_,_,_,_,_) -> true % created in JSON file
255 ; user_has_defined_visb_objects_in_defs).
256
257 user_has_defined_visb_objects_in_defs :-
258 b_sorted_b_definition_prefixed(expression,'VISB_SVG_OBJECTS',_,_).
259
260 % you should use default_visb_svg_abs_file to obtain the absolute path
261 get_default_visb_svg_file(Path, Pos) :-
262 b_get_definition_string_from_spec('VISB_SVG_FILE', Pos, Path).
263
264 % the VISB_SVG_FILE is relative to the main B machine, also when a JSON file is used
265 default_visb_svg_abs_file('',AbsFile) :- !, AbsFile=''. % just dummy empty string provided by user
266 default_visb_svg_abs_file(SvgFile,AbsFile) :-
267 b_absolute_file_name_relative_to_main_machine(SvgFile,AbsFile).
268
269
270 % load default VISB_JSON_FILE if it is specified and not already loaded
271 load_default_visb_file_if_necessary :-
272 get_default_visb_file(File, Pos),!,
273 (load_visb_file_if_necessary(File) -> true
274 ; add_error(visb_visualiser,'Could not load VISB_JSON_FILE:',File,Pos)).
275 load_default_visb_file_if_necessary :-
276 (eventb_mode -> true ; add_message(visb_visualiser,'No VISB_JSON_FILE DEFINITION provided')).
277
278 % --------------------------
279 % Loading a JSON VisB file:
280
281
282 load_visb_file(File) :-
283 temporary_set_preference(allow_arith_operators_on_reals,true,Old),
284 call_cleanup((load_visb_file1(File)),
285 reset_temporary_preference(allow_arith_operators_on_reals,Old)).
286 load_visb_file1(File) :-
287 get_filename_extension(File,def), % a .def B definition file
288 !,
289 add_message(visb_visualiser,'Loading VisB DEFINITIONS from B file: ',File),
290 b_load_additional_definitions_file(File),
291 load_visb_file2('',File).
292 load_visb_file1(File) :- load_visb_file2(File,File).
293
294 load_visb_definitions_from_list_of_facts(DefFilePath, ListOfFacts) :-
295 temporary_set_preference(allow_arith_operators_on_reals,true,Old),
296 call_cleanup(
297 (b_load_additional_definitions_from_list_of_facts(ListOfFacts),
298 load_visb_file2('', DefFilePath)),
299 reset_temporary_preference(allow_arith_operators_on_reals,Old)).
300
301 load_visb_definitions_from_term(DefFilePath, Machine) :-
302 temporary_set_preference(allow_arith_operators_on_reals,true,Old),
303 call_cleanup(
304 (b_load_additional_definitions_from_term(Machine),
305 load_visb_file2('', DefFilePath)),
306 reset_temporary_preference(allow_arith_operators_on_reals,Old)).
307
308 load_visb_file2(JsonFile,OrigFileName) :-
309 reset_visb,
310 load_visb_from_definitions(no_inlining,JsonFile), % TODO: pass InlineObjects?
311 start_ms_timer(T),
312 (JsonFile='' % No JSON file
313 -> (get_default_visb_svg_file(SvgFile,DefaultSVGPos)
314 -> default_visb_svg_abs_file(SvgFile,AbsFile),
315 add_visb_svg_file(SvgFile,AbsFile,'',DefaultSVGPos)
316 ; check_objects_created(JsonFile) % no JSON and SVG file; check we have created objects
317 )
318 ; add_visb_file(JsonFile,[]),
319 stop_ms_walltimer_with_msg(T,'loading VisB JSON file: ')
320 ),
321 static_check_visb,
322 (OrigFileName = ''
323 -> ModTime=0, ModLocTime=0 % We could get modification time of files with VISB_SVG_OBJECTS, ... DEFINITIONS
324 ; file_property(OrigFileName, modify_timestamp, ModTime),
325 file_property(OrigFileName, modify_localtime, ModLocTime)
326 ),
327 constants_status(CS),
328 assertz(visb_file_loaded(OrigFileName,ModTime,ModLocTime,CS)).
329
330 % mainly useful for CSP||B where concrete_constants not directly available upon loading machine
331 % TODO: we could compute the number of constant values available and store this (e.g., when MAX_INITIALISATIONS is 0)
332 constants_status(X) :- root_sufficiently_explored,!, X=available.
333 constants_status(not_available).
334
335 check_objects_created(File) :-
336 (visb_svg_object(_,_,_,_,_) -> true
337 ; add_warning(visb_visualiser,'No VisB JSON file is specified and no VISB_SVG_OBJECTS were created:',File)
338 ).
339
340 load_visb_from_definitions(InlineObjects,JsonFileContext) :-
341 start_ms_timer(T),
342 pre_expand_typing_scope([variables_and_additional_defs],ExpandedScope), % do this only once for all defs
343 get_svg_objects_from_definitions(InlineObjects,ExpandedScope,JsonFileContext),
344 (get_SVG_BOX_definition(InlineObjects) -> true ; true), % TODO: also pass scope
345 stop_ms_walltimer_with_msg(T,'extracting VisB infos from DEFINITIONS: ').
346
347
348 %:- use_module(library(system),[now/1, datime/2]).
349 load_visb_file_if_necessary(File) :-
350 visb_file_loaded(File,ModTime1,_,ConstantsStatus), % this file is already loaded
351 constants_status(ConstantsStatus), % if constants status has changed we need to re-load visualisation
352 (File = '' -> true
353 ; file_exists(File),
354 file_property(File, modify_timestamp, ModTime2), % check if it has the same time stamp
355 debug_println(19,visb_json_already_loaded(File,ModTime1,ModTime2)),
356 ModTime1=ModTime2
357 ),
358 !.
359 load_visb_file_if_necessary(File) :- constants_status(not_available),!,
360 add_message(visb_visualiser,'Not loading VisB file no constants set up yet: ',File).
361 load_visb_file_if_necessary(File) :- load_visb_file(File).
362
363
364 add_visb_file(File,LoadedFiles) :- member(File,LoadedFiles),!,
365 add_error(visb_visualiser,'Circular inclusion of JSON files:',[File|LoadedFiles]).
366 add_visb_file(File,_) :- \+ file_exists(File),!,
367 add_error(visb_visualiser,'JSON file does not exist:',File), fail.
368 add_visb_file(File,LoadedFiles) :-
369 debug_format(19,'Loading JSON File: ~w~n',[File]),
370 set_additional_filename_as_parsing_default(File,NewNr,OldNr),
371 call_cleanup(add_visb_file2(File,LoadedFiles), reset_filename_parsing_default(NewNr,OldNr)).
372
373 add_visb_file2(File,LoadedFiles) :-
374 json_parse_file(File,json(List2),[position_infos(true),multiline_strings(true)]),
375 % tools_printing:trace_print(List2),nl,nl,
376 process_json(List2,File),
377 !,
378 (get_attr_with_pos(include,List2,JsonFileTerm,File,Pos)
379 -> check_json_string(JsonFileTerm,include,Pos,JsonFile),
380 absolute_file_name(JsonFile,AF,[relative_to(File)]),
381 formatsilent('Including JSON file: ~w~n',[JsonFile]),
382 absolute_file_name(File,AbsFile), % File may be relative; we compare absolute paths to detect cycles
383 add_visb_file(AF,[AbsFile|LoadedFiles])
384 ; true
385 ),
386 (LoadedFiles=[], % only check for main included file
387 get_attr_with_pos('model-name',List2,string(ModelName),File,MPos),
388 b_machine_name(Main), Main \= ModelName
389 -> ajoin(['VisB JSON file expects model-name ',ModelName,' instead of: '],MMsg),
390 add_warning(visb_visualiser,MMsg,Main,MPos)
391 ; true
392 ).
393 add_visb_file2(File,_) :-
394 add_error(visb_visualiser,'Unable to process JSON file:',File),
395 fail.
396
397 % process json content of a VisB file:
398 process_json(List,JSONFile) :- visb_svg_file(_,_,_,_,_),!, % we have already determined the SVG file
399 process_json2(List,JSONFile).
400 process_json(List,JSONFile) :-
401 get_attr_with_pos(svg_box,List,json(BoxList),JSONFile,Pos),
402 % json([=(width,400,3-3),=(height,400,3-3)])
403 (get_attr(svg,List,string(SvgFile)) -> SvgFile='' ; true), % check if svg attr empty or non-existant
404 force_get_attr_nr(height,BoxList,H,JSONFile),
405 force_get_attr_nr(width,BoxList,W,JSONFile),!,
406 (get_attr(viewBox,BoxList,string(VB)) -> ViewBox=VB ; ViewBox=''),
407 add_message(visb_visualiser,'Will create empty SVG image with specified dimensions: ',H:W,Pos),
408 assert_visb_empty_svg_box_height_width(H,W,ViewBox,Pos),
409 process_json2(List,JSONFile).
410 process_json(List,JSONFile) :-
411 get_attr_with_pos(svg,List,FileTerm,JSONFile,Pos),
412 check_json_string(FileTerm,svg,Pos,File),
413 (File = '' -> get_default_visb_svg_file(SvgFile, _),
414 default_visb_svg_abs_file(SvgFile,AbsFile) % VISB_SVG_FILE is relative to the B machine
415 ; get_default_visb_svg_file(SvgFile, DPos)
416 -> add_message(visb_visualiser,'Overriding svg file specified in JSON file: ',File,DPos),
417 default_visb_svg_abs_file(SvgFile,AbsFile)
418 ; SvgFile=File,
419 absolute_file_name(SvgFile,AbsFile,[relative_to(JSONFile)])),
420 !,
421 add_visb_svg_file(SvgFile,AbsFile,JSONFile,Pos),
422 process_json2(List,JSONFile).
423 process_json(List,JSONFile) :-
424 get_default_visb_svg_file(SvgFile, Pos), SvgFile \= '',
425 !,
426 default_visb_svg_abs_file(SvgFile,AbsFile),
427 add_visb_svg_file(SvgFile,AbsFile,JSONFile,Pos),
428 process_json2(List,JSONFile).
429 process_json(List,JSONFile) :-
430 process_json2(List,JSONFile),
431 (get_SVG_BOX_definition(no_inlining) -> true % TODO: pass (InlineObjects)
432 ; get_attr_with_pos(svg,List,_,JSONFile,Pos) -> % File is empty
433 add_message(visb_visualiser,'Creating empty SVG image. You can add a declaration like "svg_box": {"width":W,"height":H} to specify dimensions in: ',JSONFile,Pos)
434 ; add_warning(visb_visualiser,'Creating empty SVG image. The JSON file contains no svg attribute (pointing to the SVG file): ',JSONFile)
435 ).
436
437 add_visb_svg_file(SvgFile,AbsFile,JSONFile,Pos) :-
438 (SvgFile='' -> add_message(visb_visualiser,'Empty VisB SVG file:',SvgFile,Pos),
439 ModLocTime=unknown
440 ; file_exists(AbsFile)
441 -> debug_format(19,'SVG file = ~w (~w)~n',[SvgFile, AbsFile]),
442 file_property(AbsFile, modify_localtime, ModLocTime)
443 ; add_error(visb_visualiser,'The specified VisB SVG file does not exist:',SvgFile,Pos),
444 ModLocTime=unknown
445 ),
446 assertz(visb_svg_file(SvgFile,AbsFile,JSONFile,Pos,ModLocTime)).
447
448 process_json2(List,JSONFile) :-
449 process_json_definitions(List,JSONFile),
450 process_json_items(List,JSONFile),
451 process_json_events(List,JSONFile),
452 process_json_new_svg_objects(List,JSONFile).
453
454
455 % ----------------
456
457 % B definitions that can help write items, events more compactly
458 process_json_definitions(List,File) :-
459 get_attr(definitions,List,array(Defs)),!,
460 length(Defs,Len),
461 formatsilent('VisB Definitions: ~w~n',[Len]),
462 maplist(process_json_definition(File),Defs).
463 process_json_definitions(_,_File).
464
465 % VisB items which modify attributes of SVG objects
466 process_json_items(List,File) :-
467 get_attr(items,List,array(Items)),!,
468 length(Items,Len),
469 formatsilent('VisB Item declarations: ~w~n',[Len]),
470 maplist(process_visb_json_item(File),Items).
471 process_json_items(_,File) :- \+ visb_special_definition(visb_updates,_,_,_,_,_),!,
472 add_message(visb_visualiser,'The JSON file contains no items: ',File).
473 process_json_items(_,_).
474
475 % VisB events which react to clicks on SVG objects and display hovers
476 process_json_events(List,File) :-
477 get_attr(events,List,array(Items)),!,
478 length(Items,Len),
479 formatsilent('VisB Event declarations: ~w~n',[Len]),
480 maplist(process_json_event(File),Items).
481 process_json_events(_,_).
482
483 % VisB additional SVG objects added to SVG file
484 process_json_new_svg_objects(List,File) :-
485 get_attr(svg_objects,List,array(Items)),!,
486 length(Items,Len),
487 formatsilent('VisB additional svg_objects declarations: ~w~n',[Len]),
488 maplist(process_json_svg_object(File),Items).
489 process_json_new_svg_objects(List,File) :-
490 get_attr_with_pos(objects,List,array(Items),File,Pos),!,
491 add_warning(visb_visualiser,'Use "svg_objects" attribute instead of "objects" in: ',File,Pos),
492 maplist(process_json_svg_object(File),Items).
493 process_json_new_svg_objects(_,_).
494
495
496 % evaluate all VISB_SVG_OBJECTS... DEFINITIONS and try and extract SVG objects
497 % this must be a set of records with at least id and svg_class field
498 get_svg_objects_from_definitions(InlineObjects,ExpandedScope,_) :-
499 find_and_eval_visb_DEFINITION('VISB_SVG_OBJECTS', visb_objects, SVG_ID, AttrList, Desc, DefName,
500 _DefPos, EvalPos, InlineObjects, allow_separation, ExpandedScope),
501 %formatsilent('Generating new SVG object ~w with attrs ~w~n',[SVG_ID,AttrList]),
502 add_visb_object_from_definition(visb_objects, SVG_ID, AttrList, Desc, DefName, EvalPos),
503 fail.
504 get_svg_objects_from_definitions(InlineObjects,ExpandedScope,_) :-
505 find_and_eval_visb_DEFINITION('VISB_SVG_EVENTS', visb_events, SVG_ID, AttrList, Desc, DefName,
506 _DefPos, EvalPos, InlineObjects, no_separation, ExpandedScope),
507 % attributes: event or events, predicate
508 add_visb_object_from_definition(visb_events, SVG_ID, AttrList, Desc, DefName, EvalPos),
509 fail.
510 get_svg_objects_from_definitions(InlineObjects,ExpandedScope,_) :-
511 find_and_eval_visb_DEFINITION('VISB_SVG_HOVERS', visb_hovers, SVG_ID, AttrList, Desc, DefName,
512 _DefPos, EvalPos, InlineObjects, no_separation, ExpandedScope),
513 % attributes: id, trigger_id (optional), other SVG attributes
514 add_visb_hovers_from_definition(SVG_ID, AttrList, Desc, DefName, EvalPos),
515 fail.
516 get_svg_objects_from_definitions(_InlineObjects,ExpandedScope,JsonFileContext) :- % VISB_SVG_UPDATES
517 precompile_svg_object_updates(ExpandedScope,JsonFileContext).
518
519 % example definition VISB_SVG_HOVERS == rec(`id`:"myid", stroke:"black", stroke_exit:"gray");
520 % a hovers field inside VISB_SVG_OBJECTS can be something like:
521 % rec(.... hovers: (rec(class:"train-hover"),rec(trigger_id:"track_polyline",class:"train-hover")), ...)
522 % also used, e.g., as attribute in VISB_SVG_OBJECTS
523 add_visb_hovers_from_definition(SVG_ID,AttrList, Desc, DefName, DefPos) :-
524 select(svg_attribute(hovers,Hovers),AttrList,AttrList2),
525 !,
526 (AttrList2=[] -> true ; add_warning(visb_visualiser,'Unknown extra hover attributes:',AttrList2,DefPos)),
527 flex_member(Record,Hovers,DefName,DefPos),
528 (get_VISB_record_fields(Record,Fields) -> true
529 ; add_warning(visb_visualiser,'VisB hovers field value is not a record of SVG attributes: ',Record,DefPos),fail),
530 include_maplist(extract_attribute_from_record(DefPos),Fields,HoverAttrList),
531 add_visb_object_from_definition(visb_hovers, SVG_ID, HoverAttrList, Desc, DefName, DefPos).
532 add_visb_hovers_from_definition(SVG_ID,AttrList, Desc, DefName, DefPos) :-
533 add_visb_object_from_definition(visb_hovers, SVG_ID, AttrList, Desc, DefName, DefPos).
534
535
536 % add a VisB record object from a HOVER or OBJECT definition:
537 add_visb_object_from_definition(visb_objects,SVG_ID, AttrList, Desc, DefName, DefPos) :- !,
538 (select(svg_attribute(svg_class,SVG_Class),AttrList,AttrList2)
539 -> true % maybe we should call svg_class svg_shape and
540 % allow html_tag for children of foreignObject
541 ; add_warning(visb_visualiser,'SVG objects have no svg_class field: ',DefName,DefPos),
542 fail
543 ),
544 assert_visb_svg_object(SVG_ID,SVG_Class,AttrList2,Desc,DefName,DefPos).
545 add_visb_object_from_definition(visb_hovers,SVG_ID, AttrList, _Desc, _DefName, DefPos) :- !,
546 (select(svg_attribute(trigger_id,TriggerID),AttrList,AttrList2) -> true
547 ; select(svg_attribute('trigger-id',TriggerID),AttrList,AttrList2) -> true
548 ; TriggerID = SVG_ID, AttrList2=AttrList),
549 member(svg_attribute(Attr,EnterVal),AttrList2), % will backtrack for every SVG attribute
550 \+ get_exit_attribute_name(_,Attr), % it is not an exit attribute
551 get_exit_attribute_name(Attr,AttrExitName),
552 (member(svg_attribute(AttrExitName,ExitVal), AttrList2) -> true % user specified exit value explicitly
553 ; visb_svg_object(SVG_ID,_,StaticAttrList,_,ExitPos)
554 -> (member(svg_attribute(Attr,ExitVal),StaticAttrList) -> true % use value specified in VISB_SVG_OBJECTS
555 ; default_attribute_value(Attr,ExitVal)
556 -> add_message(visb_visualiser,'Assuming default hover exit value for attribute: ',Attr,DefPos)
557 ; Attr = 'svg_class'
558 -> add_warning(visb_visualiser,
559 'svg_class cannot be set in hover for: ',SVG_ID,ExitPos),
560 ExitVal=EnterVal
561 ; (Attr = hover ; Attr = hovers) ->
562 add_error(visb_visualiser,
563 'Only provide SVG attributes here; no need to wrap them in this attribute:',Attr,DefPos),fail
564 ; add_warning(visb_visualiser,
565 'No static (exit) value can be retrieved for hover for attribute (be sure to define a static value for this attribute in a VISB_SVG_OBJECT definition): ',Attr,ExitPos),
566 ExitVal=EnterVal
567 )
568 ; ajoin(['No VISB_SVG_OBJECT for id ',SVG_ID,' and no value for ',AttrExitName,
569 '; cannot retrieve hover exit value for attribute: '],Msg),
570 add_warning(visb_visualiser,Msg,Attr,DefPos),
571 fail %ExitVal=EnterVal
572 ),
573 assert_visb_hover(TriggerID,SVG_ID,Attr,EnterVal,ExitVal,DefPos).
574 add_visb_object_from_definition(visb_events,SVG_ID, AttrList, _Desc, DefName, DefPos) :- !,
575 ( select(svg_attribute(event,Event),AttrList,AttrList1) -> true
576 ; select(svg_attribute(events,Events),AttrList,AttrList1) -> % we have events attributes with multiple events
577 flex_member(EvVal,Events,DefName,DefPos),
578 extract_attr_value(event,EvVal,Event,DefPos)
579 ; AttrList = [_|_], % at least one other attribute than id; otherwise it may stem from separating VISB_SVG_OBJECTS
580 add_warning(visb_visualiser,'Missing event attribute in VisB definition: ',DefName,DefPos),
581 fail
582 ),
583 (select(svg_attribute(predicate,Pred),AttrList1,AttrList2) -> Preds=[Pred]
584 ; member(P,[preds,predicates]),
585 select(svg_attribute(P,Pred),AttrList1,AttrList2)
586 -> Preds=[Pred], add_warning(visb_visualiser,'Use predicate as attribute for VisB events instead of: ',P,DefPos)
587 ; Preds=[], AttrList2=AttrList1
588 ),
589 (select(svg_attribute(execution_kind,EKind),AttrList2,AttrList3)
590 -> check_execution_kind(EKind,SVG_ID,DefPos,ExecKind)
591 ; default_execution_kind(ExecKind), AttrList3=AttrList2
592 ),
593 EnableItems=[],
594 maplist(warn_remaining_attributes(DefName,DefPos),AttrList3),
595 % TODO extract from AttrList2: visb_enable_item(SvgID,Attr,EnabledValExpr,DisabledValExpr,PosAttr)
596 (error_manager:extract_file_number_and_name(DefPos,_,File) -> true ; File='?'),
597 PredPos = DefPos, %TODO: improve
598 add_visb_event(SVG_ID,Event,Preds,ExecKind,[],EnableItems,File,DefPos,PredPos,[]).
599 add_visb_object_from_definition(SpecialClass,_, _, _, _DefName, DefPos) :-
600 add_warning(visb_visualiser,'Unknown special class, cannot add VisB objects for definition: ',SpecialClass,DefPos).
601
602 % for hovers allow to explicitly specify exit value, in case the SVG object comes from an SVG file
603 get_exit_attribute_name(Attr,ExitAttr) :- atom_concat(Attr,'_exit',ExitAttr).
604
605 warn_remaining_attributes(DefName,DefPos,svg_attribute(hover,_)) :- !,
606 add_warning(visb_visualiser,'Attribute hover not supported here (use separate VISB_SVG_HOVERS definition): ',DefName,DefPos).
607 warn_remaining_attributes(DefName,DefPos,svg_attribute(hovers,_)) :- !,
608 add_warning(visb_visualiser,'Attribute hovers not supported here (use separate VISB_SVG_HOVERS definition): ',DefName,DefPos).
609 warn_remaining_attributes(_,DefPos,Attr) :-
610 add_warning(visb_visualiser,'Unrecognised attribute in VISB_SVG_EVENTS definition: ',Attr,DefPos).
611
612
613 default_attribute_value(fill,black). % is remove for animate, ...
614 default_attribute_value(opacity,1).
615 default_attribute_value('stop-dasharray',none).
616 default_attribute_value('stop-opacity',1).
617 default_attribute_value('stroke-opacity',1).
618 default_attribute_value('stroke-width','1px').
619 default_attribute_value(stroke,none).
620 default_attribute_value(transform,none).
621 default_attribute_value(visibility,visible).
622
623 % is called in process_json when no SVG file specified
624 % VISB_SVG_BOX == rec(width:1000,height:1000,viewBox:"minx miny w h"),
625 get_SVG_BOX_definition(InlineObjects) :-
626 get_and_eval_special_definition('VISB_SVG_BOX','VISB_SVG_BOX',visb_box,DefPos,ResValue,InlineObjects),
627 (ResValue=(BH,BW) -> ViewBox=''
628 ; get_VISB_record_fields(ResValue,Fields),
629 select(field(height,BH),Fields,F1),
630 select(field(width,BW),F1,F2)
631 -> (select(field(viewBox,VBVal),F2,F3)
632 -> (VBVal=string(VB) -> ViewBox=VB
633 % Viewbox is "mx my w h" string, ie: minimum_x, minimum_y, width and height
634 ; VBVal = rec(VBFields)
635 -> (VBFields = [field(height,_),field(minx,_),field(miny,_),field(width,_)]
636 -> (get_view_box_rec(VBFields,DefPos,ViewBox) -> true ; ViewBox='') % error already reported
637 ; ViewBox='',
638 add_warning(visb_visualiser,'VISB_SVG_BOX viewBox record has illegal fields (expected minx miny width height):',VBVal,DefPos))
639 ; add_warning(visb_visualiser,'VISB_SVG_BOX viewBox is not a string ("minx miny width height") or record:',VBVal,DefPos),
640 ViewBox=''
641 )
642 ; ViewBox='', F3=F2
643 ),
644 (F3=[] -> true
645 ; add_warning(visb_visualiser,'VISB_SVG_BOX unknown attributes (not height, width, viewBox): ',F3,DefPos))
646 ; add_error(visb_visualiser,'Ignoring VISB_SVG_BOX, must be record or pair of integers (height,width):',ResValue,DefPos),
647 fail),
648 (get_number_from_bvalue(BH,H) -> true
649 ; add_error(visb_visualiser,'Ignoring VISB_SVG_BOX, height is not a number:',ResValue,DefPos), fail),
650 (get_number_from_bvalue(BW,W) -> true
651 ; add_error(visb_visualiser,'Ignoring VISB_SVG_BOX, width is not a number:',ResValue,DefPos), fail),
652 !,
653 assert_visb_empty_svg_box_height_width(H,W,ViewBox,DefPos).
654
655 get_view_box_rec([field(height,VH),field(minx,MXH),field(miny,MYH),field(width,VW)],DefPos,ViewBoxString) :-
656 (get_number_from_bvalue(VH,Height) -> true
657 ; add_error(visb_visualiser,'VISB_SVG_BOX viewBox\'height is not a number:',VH,DefPos),fail),
658 (get_number_from_bvalue(VW,Width) -> true
659 ; add_error(visb_visualiser,'VISB_SVG_BOX viewBox\'width is not a number:',VW,DefPos),fail),
660 (get_number_from_bvalue(MXH,MinX) -> true
661 ; add_error(visb_visualiser,'VISB_SVG_BOX viewBox\'minx is not a number:',MXH,DefPos),fail),
662 (get_number_from_bvalue(MYH,MinY) -> true
663 ; add_error(visb_visualiser,'VISB_SVG_BOX viewBox\'miny is not a number:',MYH,DefPos),fail),
664 ajoin([MinX,' ',MinY,' ', Width,' ',Height],ViewBoxString).
665
666
667 assert_visb_empty_svg_box_height_width(H,W,_ViewBox,Pos) :-
668 retract(visb_empty_svg_box_height_width(OldH,OldW,_)),
669 (OldH,OldW) \= (H,W),
670 add_message(visb_visualiser,'Overriding VisB SVG_BOX default dimensions: ',(OldH,OldW),Pos),
671 fail.
672 assert_visb_empty_svg_box_height_width(H,W,ViewBox,_Pos) :-
673 %add_message(visb_visualiser,'Setting VisB SVG_BOX default dimensions: ',(H,W,ViewBox),Pos),
674 assert(visb_empty_svg_box_height_width(H,W,ViewBox)).
675
676
677 % find DEFINITION with given prefix in name, evaluate it and return SVG_ID and attribute list:
678 % AllowSep = allow_seperation means that the record fields can be separated into static objects and dynamic updates
679 % and only static ones will be retained (dynamic ones dealt with later)
680 find_and_eval_visb_DEFINITION(DEFPREFIX, Kind, SVG_ID, AttrList,Desc, DefName, DefPos,EvalPos,
681 InlineObjects,AllowSep,ExpandedScope) :-
682 ( b_sorted_b_definition_prefixed(expression,DEFPREFIX,DefName,DefPos),
683 if(b_get_typed_definition(DefName,ExpandedScope,Body),true,
684 (add_visb_lint_message('Ignoring VisB DEFINITION due to errors',DefName,DefPos),fail))
685 ; special_backup(DEFPREFIX,Kind),
686 % also look at stored definitions (e.g., from static/dynamic separation of VISB_SVG_OBJECTS)
687 visb_special_definition(Kind,DefName,_Type,Body,_Class,DefPos)
688 ),
689 set_error_context(visb_error_context(definition,DefName,'all_attributes',DefPos)),
690 call_cleanup((get_typed_static_definition_with_constants_state(DefName,Body,
691 ResBody,DefPos,ConstState,InlineObjects,AllowSep),
692 (get_texpr_pos(ResBody,Pos0) -> true ; Pos0=DefPos), % this could be a part of the full definition body
693 get_visb_DEFINITION_svg_object(Kind,DefName,ResBody,Pos0,ConstState,SVG_ID,AttrList,Desc,EvalPos)),
694 clear_error_context).
695
696 special_backup('VISB_SVG_HOVERS',visb_hovers).
697
698 % evaluate a typed body expressions evaluating to a record or set of records
699 % and translate into SVG attribute lists:
700 get_visb_static_svg_object_for_typed_expr(Kind,DefName,Body,DefPos,SVG_ID,AttrList,Desc,InnerPos) :-
701 AllowSep=no_separation,
702 Inline=no_inlining,
703 get_typed_static_definition_with_constants_state(DefName,Body,ResBody,DefPos,ConstState,Inline,AllowSep),
704 get_visb_DEFINITION_svg_object(Kind,DefName,ResBody,DefPos,ConstState,SVG_ID,AttrList,Desc,InnerPos).
705
706
707 flatten_couple(b(couple(A,B),_,_)) --> !,flatten_couple(A),flatten_couple(B).
708 % we could also flatten union(A,B), but at the risk of duplicate warnings when the same element occurs in A and B
709 flatten_couple(A) --> [A].
710
711 get_typed_static_definition_with_constants_state(DefName,Body,ResBody,DefPos,ConstantsState,InlineObjects,AllowSep) :-
712 flatten_couple(Body,TupleList,[]),
713 % the VISB_SVG_OBJECT definition may consist of a tuple (Obj1,Obj2,...) to allow grouping
714 (TupleList = [_,_|_]
715 -> add_debug_message(visb_visualiser,'Decomposed VisB definition body tuple:',DefName,DefPos)
716 ; true),
717 nth1(DefNr,TupleList,TupleBody),
718 (get_texpr_pos(TupleBody,TuplePos) -> true ; TuplePos=DefPos),
719 get_typed_static_definition_with_constants_state3(DefName,DefNr,TupleBody,ResBody,TuplePos,
720 ConstantsState,InlineObjects,AllowSep).
721 get_typed_static_definition_with_constants_state3(DefName,DefNr,Body,ResBody,DefPos,ConstantsState,InlineObjects,AllowSep) :-
722 determine_type_of_visb_formula(Body,TIds,Class),
723 debug_format(19,'Detected VisB DEFINITION ~w (~w)~n',[DefName,Class]),
724 (%Class=requires_variables, % now also useful if event field present
725 AllowSep=allow_separation, % allowed for VISB_SVG_OBJECTS
726 if(separate_into_static_and_dynamic_part(DefName,DefNr,Body,StaticBody,DynamicBody,EventBody,HoverBody),
727 true,
728 (get_texpr_type(Body,Type),
729 (contains_events_or_hovers_field(Type)
730 -> add_warning(visb_visualiser,'Static/Dynamic separation failed for (required for events or hovers): ',DefName,DefPos)
731 % VISB_SVG_OBJECT definition contains events/hovers and as such requires separation; which failed here
732 ; add_debug_message(visb_visualiser,'Static/Dynamic separation failed or not useful for: ',DefName,DefPos)
733 ),
734 fail)),
735 determine_type_of_visb_formula(StaticBody,SIds,SClass),
736 get_unique_initial_state_for_visb(SClass,DefName,DefPos,SIds,ConstantsState)
737 -> Separated=true, ResBody=StaticBody,
738 add_debug_message(visb_visualiser,'Automatically separated fields into static and dynamic: ',DefName,DefPos),
739 %write('STATIC: '),translate:print_bexpr(StaticBody),nl, write('DYNAMIC: '),translate:print_bexpr(DynamicBody),nl,
740 assert_visb_udpate_def_body(visb_updates,DefName,DynamicBody,DefPos),
741 add_visb_events_from_def_body(visb_events,DefName,EventBody,DefPos),
742 assert_visb_udpate_def_body(visb_hovers,DefName,HoverBody,DefPos) % needs to be asserted so that it can be evaluated after svg objects have been created to extract exit value
743 ; get_unique_initial_state_for_visb(Class,DefName,DefPos,TIds,ConstantsState)
744 -> ResBody=Body
745 ; ResBody=Body,
746 (Class=requires_constants ->
747 get_texpr_ids(TIds,Ids),
748 % we could check if values of Ids are identical in all constants solutions
749 (is_concrete_constants_state_id(_)
750 -> BMsg='multiple solutions for used constants exist: '
751 ; \+ root_sufficiently_explored
752 -> BMsg='no constants were setup yet: '
753 % two cases below should not happen; but happen on Linux with CSP||B models
754 ; state_space:logical_transition_from_root(RID),
755 state_space:packed_visited_expression(RID,RSt),
756 functor(RSt,RFun,RArity)
757 -> ajoin(['no constants were found, but logical successor ',RFun,'/',RArity,
758 ' with id ', RID,' of root exists: '],BMsg)
759 ; BMsg='no constants were found: '
760 ),
761 ajoin(['DEFINITION ',DefName, ' requires constants but ',BMsg],Msg),
762 (get_a_constants_state(ConstantsState,StateID,InlineObjects)
763 -> (member(CstID,Ids),
764 other_constant_value_exists_for(CstID,ConstantsState,StateID)
765 -> add_warning(visb_visualiser,Msg,CstID,DefPos)
766 ; ajoin(['DEFINITION ',DefName,
767 ' requires constants and all SETUP_CONSTANTS solutions have same value thus far: '],Msg2),
768 % constraint-based checks or execute by predicate could later create others !
769 add_message(visb_visualiser,Msg2,Ids,DefPos)
770 )
771 ; add_error(visb_visualiser,Msg,Ids,DefPos),
772 fail % avoid other subsequent errors when evaluating with ConstantsState=[]
773 )
774 ; ConstantsState=[]
775 )
776 ),
777 (Class=requires_variables, Separated=false
778 -> get_texpr_ids(TIds,AIds),
779 include(b_is_variable,AIds,VIds),
780 ajoin_with_sep(VIds,',',SVids),
781 (get_preference(visb_allow_variables_for_objects,false)
782 -> ajoin(['Ignoring DEFINITION which requires variables ',SVids,': '],WMsg),
783 add_warning(visb_visualiser,WMsg,DefName,DefPos),fail
784 ; ConstantsState=[]
785 -> add_warning(visb_visualiser,'Ignoring DEFINITION which requires variables, could not find unique initial state: ',DefName,DefPos),fail
786 ; ajoin(['DEFINITION requires variables ',SVids,
787 '; exporting history to HTML may not work correctly'],WMsg),
788 add_visb_lint_message(WMsg,DefName,DefPos)
789 )
790 ; true).
791
792
793 % separate/split/filter VISB_SVG_OBJECTS definitions into a static part and a dynamic part depending on variables
794 % (aka updates/items)
795 separate_into_static_and_dynamic_part(DefName,DefNr,Body,StaticBody,DynamicBody,EventBody,HoverBody) :-
796 separate_static_dyn_aux(DefName,DefNr,[],[],Body,StaticBody,DynamicBody,EventBody,HoverBody).
797
798
799 rewrite_expression(let_expression(Ids,Exprs,Body),NewBody) :-
800 % currently we cannot process LET's here, expand them
801 replace_ids_by_exprs(Body,Ids,Exprs,NewBody). % see also expand_all_lets/2
802
803 separate_static_dyn_aux(DefName,DefNr,OuterQuantifiedIds,Path,b(Expr,_Type,_Info), Static,Dynamic,Event,Hover) :-
804 rewrite_expression(Expr,NewExpr),!,
805 separate_static_dyn_aux(DefName,DefNr,OuterQuantifiedIds,Path,NewExpr, Static,Dynamic,Event,Hover).
806 separate_static_dyn_aux(DefName,DefNr,OuterQuantifiedIds,Path,b(couple(A,B),_,_Info),
807 StaticCouple,DynamicCouple,EventCouple,HoverCouple) :- !,
808 separate_static_dyn_aux(DefName,DefNr,OuterQuantifiedIds,[0|Path],A,SA,DA,EA,HA),
809 separate_static_dyn_aux(DefName,DefNr,OuterQuantifiedIds,[1|Path],B,SB,DB,EB,HB),
810 create_couple(SA,SB,StaticCouple),
811 create_couple(DA,DB,DynamicCouple),
812 create_couple(EA,EB,EventCouple),
813 create_couple(HA,HB,HoverCouple).
814 separate_static_dyn_aux(DefName,DefNr,OuterQuantifiedIds,Path,TExpr,
815 b(StaticSetComp,set(ST),I),
816 b(DynamicSetComp,set(DT),I),
817 b(EventsSetComp,set(ET),I),
818 b(HoversSetComp,set(HT),I)) :-
819 bsyntaxtree:is_eventb_comprehension_set(TExpr,Ids,Pred,Expr),
820 (OuterQuantifiedIds = []
821 -> add_debug_message(visb_visualiser,'Top-level set comprehensions for VISB: ',Ids,TExpr)
822 ; add_message(visb_visualiser,'Nested set comprehensions for VISB: ',OuterQuantifiedIds,TExpr)
823 ),
824 !,
825 determine_type_of_visb_formula(b(exists(Ids,Pred),pred,[]),SIds,Class),
826 (get_unique_initial_state_for_visb(Class,DefName,Pred,SIds,_)
827 -> true % The predicate must be statically executable
828 ; time_out_for_node(root,O,_Type),
829 translate_operation_name(O,Op) ->
830 ajoin(['Due to TIME_OUT of ',Op,' the comprehension set domain cannot be evaluated: '],Msg),
831 add_warning(visb_visualiser,Msg,Pred,Pred),
832 % TODO: avoid other error messages that will occur after that
833 fail
834 ; (root_sufficiently_explored -> RMsg = '' ; RMsg = ' because constants were not set up yet'),
835 (multiple_concrete_constants_exist -> MMsg = ',multiple SETUP_CONSTANTS exist' ; MMsg = ''),
836 ajoin(['Cannot evaluate comprehension set domain (',Class,MMsg,')',RMsg],LMsg),
837 add_visb_lint_message(LMsg,Pred,Pred),
838 % at the moment we require the domain to be computable statically for both static/dynamic attributes
839 fail
840 ),
841 append(OuterQuantifiedIds,Ids,NewOuterQuantifiedIds),
842 separate_static_dyn_aux(DefName,DefNr,NewOuterQuantifiedIds,Path,Expr,
843 StaticRec,DynamicRec,EventRec,HoverRec),
844 get_texpr_type(StaticRec,ST),
845 get_texpr_type(DynamicRec,DT),
846 get_texpr_type(EventRec,ET),
847 get_texpr_type(HoverRec,HT),
848 bsyntaxtree:get_texpr_info(TExpr,I),
849 b_ast_cleanup:rewrite_event_b_comprehension_set(Ids,StaticRec,Pred, set(ST), StaticSetComp),
850 b_ast_cleanup:rewrite_event_b_comprehension_set(Ids,DynamicRec,Pred,set(DT), DynamicSetComp),
851 b_ast_cleanup:rewrite_event_b_comprehension_set(Ids,EventRec,Pred,set(ET), EventsSetComp),
852 b_ast_cleanup:rewrite_event_b_comprehension_set(Ids,HoverRec,Pred,set(HT), HoversSetComp).
853 separate_static_dyn_aux(DefName,DefNr,OuterQuantifiedIds,Path,b(rec(Fields),_,Info),
854 b(rec(StaticFields),record(SFT),Info), % VISB_OBJECTS (static)
855 b(UpdateRecWithDynamicFields,record(DFT),Info), % VISB_UPDATES (dynamic)
856 b(rec(AllEventFields),record(EFT),Info), % VISB_EVENTS
857 b(rec(AllHoverFields),record(HFT),Info) % VISB_HOVERS
858 ) :- !,
859 split_list(is_visb_event_field,Fields,EventFields,ObjectAndHoverFields),
860 (select(field(hovers,HoverRec),ObjectAndHoverFields,ObjectFields)
861 -> HoverFields = [field(hovers,HoverRec)] % record deconstructed in add_visb_hovers_from_definition
862 ; ObjectFields=ObjectAndHoverFields, HoverFields = []),
863 % maplist(check_field_is_supported(Info),ObjectFields), % will lead to duplicate warning messages, check_visb_update_type e.g., will be called for dynamic updates
864 separate_fields(ObjectFields,StaticFields0,DynamicFields,DefName),
865 (member(field(svg_class,_SVG_Class),StaticFields0) -> true
866 ; member(field(svg_class,SVG_Class),DynamicFields)
867 -> add_warning(visb_visualiser,'SVG svg_class field is not static in: ',DefName,SVG_Class),
868 fail
869 ; add_warning(visb_visualiser,'No svg_class field in: ',DefName,Info),
870 fail
871 ),
872 (member(field(id,SVGID),StaticFields0)
873 -> (DynamicFields \= [] ; EventFields \= [] ; HoverFields \= [] % separation is useful for this record
874 ; Path \= [] % we are part of a couple; maybe other records have a dynamic,event or hover part; so proceed
875 ),
876 StaticFields = StaticFields0,
877 TStatic_SVGID = SVGID
878 ; member(field(id,SVGID),DynamicFields)
879 -> add_warning(visb_visualiser,'SVG id field is not static in: ',DefName,SVGID),
880 fail
881 ; OuterQuantifiedIds = []
882 -> gensym(svg_id,GenID),
883 ajoin(['Generated id ',GenID, ' for SVG object without id field in: '],Msg),
884 add_debug_message(visb_visualiser,Msg,DefName,Info),
885 SVGID = b(string(GenID),string,[]),
886 sort([field(id,SVGID) | StaticFields0],StaticFields)
887 ; % the record is quantified within a set comprehension; we need to compute the ID from OuterQuantifiedIds
888 % it has to be identical for VISB_SVG_OBJECTS and VISB_SVG_UPDATES
889 SVGID = b(ExtFunCall,string,[]),
890 convert_path_to_int(Path,IntPath),
891 PathExpr = b(integer(IntPath),integer,[]),
892 create_couple([b(string(DefName),string,[]),b(integer(DefNr),integer,[]),PathExpr|OuterQuantifiedIds],Tuple),
893 % add DefName and DefNr to avoid clash if other Definition has same quantified ids
894 ExtFunCall = external_function_call('SHA_HASH_HEX',[Tuple]),
895 ajoin(['Generated call to compute id for SVG object without id field in ',DefName,': '],Msg),
896 add_debug_message(visb_visualiser,Msg,SVGID,Info),
897 sort([field(id,SVGID) | StaticFields0],StaticFields)
898 ),
899 maplist(get_field_type,StaticFields,SFT),
900 ( (select(field(visibility,VisibExpr),DynamicFields,RestDynamicFields)
901 ; member(field(visibility,VisibExpr),StaticFields0), % the visibility expression is static
902 RestDynamicFields = DynamicFields
903 ),
904 RestDynamicFields = [_|_],
905 \+ hovers_can_set_visibility(HoverFields),
906 (nonvar(TStatic_SVGID), TStatic_SVGID = b(string(Static_SVGID),_,_) % TODO: evaluate properly
907 -> \+ visb_has_visibility_hover(Static_SVGID) % TODO: check no other hover definition added later
908 ; true) % the ID is generated and cannot be accessed by other hovers which could make object visible
909 -> % create IF-THEN-ELSE to avoid evaluating fields when object not visible; also fixes WD issues
910 TRUE = b(boolean_true,boolean,[]),
911 sort([field(id,SVGID),field(visibility,TRUE)|RestDynamicFields],AllDynamicFields),
912 maplist(construct_dummy_value,RestDynamicFields,RestDummyFields),
913 sort([field(id,SVGID),field(visibility,b(boolean_false,boolean,[]))|RestDummyFields],AllDummyFields),
914 create_visibility_check(VisibExpr,VisibilityCond),
915 UpdateRecWithDynamicFields = if_then_else(VisibilityCond,
916 b(rec(AllDynamicFields),record(DFT),Info),
917 b(rec(AllDummyFields),record(DFT),Info)),
918 add_debug_message(visb_visualiser,'Refactoring VisB Record with visibility attribute: ',VisibilityCond)
919 % ,translate:print_bexpr(b(UpdateRecWithDynamicFields,any,[])),nl
920 ; sort([field(id,SVGID)|DynamicFields],AllDynamicFields), % TODO: use kernel_records
921 UpdateRecWithDynamicFields = rec(AllDynamicFields)
922 ),
923 maplist(get_field_type,AllDynamicFields,DFT),
924 sort([field(id,SVGID)|EventFields],AllEventFields), % ditto
925 maplist(get_field_type,AllEventFields,EFT),
926 sort([field(id,SVGID)|HoverFields],AllHoverFields), % ditto
927 maplist(get_field_type,AllHoverFields,HFT).
928 separate_static_dyn_aux(DefName,DefNr,OuterQuantifiedIds,_Path,TEXPR, _, _, _,_) :-
929 ajoin(['Uncovered expression for ',DefName,'-',DefNr,' ',OuterQuantifiedIds],Msg),
930 add_debug_message(visb_visualiser,Msg,TEXPR,TEXPR),fail.
931
932 hovers_can_set_visibility(HoverFields) :- member(field(hovers,Expr),HoverFields),
933 hover_expr_can_set_visibility(Expr).
934
935 hover_expr_can_set_visibility(b(E,_,_)) :- hovers_can_set_visib_aux(E).
936 hovers_can_set_visib_aux(couple(A,B)) :- !, (hover_expr_can_set_visibility(A) ; hover_expr_can_set_visibility(B)).
937 hovers_can_set_visib_aux(rec(Fields)) :- !, member(field(visibility,_),Fields).
938 hovers_can_set_visib_aux(set_extension(L)) :- !, member(E,L), hover_expr_can_set_visibility(E).
939 hovers_can_set_visib_aux(E) :- debug_format(19,'Assuming hover can set visibility: ~w~n',[E]).
940 % TODO: synchronise with flex_expand and check we cover all relevant cases like partial functions
941
942
943 create_visibility_check(VisibExpr,VisibilityCond) :- get_texpr_type(VisibExpr,string),!,
944 static_check_attribute_value_expression(visibility,VisibExpr),
945 VISIBLE = b(string('visible'),string,[]),
946 create_equality(VisibExpr,VISIBLE,VisibilityCond).
947 create_visibility_check(VisibExpr,VisibilityCond) :- get_texpr_type(VisibExpr,boolean),!,
948 TRUE = b(boolean_true,boolean,[]),
949 create_equality(VisibExpr,TRUE,VisibilityCond).
950 create_visibility_check(VisibExpr,b(truth,pred,[])) :-
951 add_warning(visb_visualiser,'The attribute visibility is not of type STRING or BOOL: ',VisibExpr,VisibExpr).
952
953
954 construct_dummy_value(field(Name,TExpr),field(Name,b(value(DummyValue),Type,[]))) :-
955 get_texpr_type(TExpr,Type),
956 get_default_or_dummy_value(Type,Name,DummyValue). % object not visible: do not evaluate expression; use dummy value
957
958 get_default_or_dummy_value(string,Name,DummyValue) :-
959 svg_attribute_default_value(Name,Default),!,
960 DummyValue=string(Default).
961 get_default_or_dummy_value(Type,_Name,DummyValue) :- any_value_for_type(Type,DummyValue).
962
963
964 % treat path of 0,1 as binary number, but add 1 at end to distinguish [0,0] and [0] or [1,0] and [1,0,0]
965 convert_path_to_int([],1).
966 convert_path_to_int([H|T],Res) :- convert_path_to_int(T,IT),
967 Res is IT*2+H.
968
969 % is the name of a field for events inside a VISB_SVG_OBJECT record
970 % example rec(..., event:"BOperation", predicate:"x=TRUE")
971 is_visb_event_field(field(Name,_)) :- is_visb_event_field_name(Name).
972 is_visb_event_field_name(event).
973 is_visb_event_field_name(events). % tuple or set of events inside VISB_SVG_OBJECTS
974 is_visb_event_field_name(predicate).
975 is_visb_event_field_name(predicates). % will generate warning
976 is_visb_event_field_name(preds). % will generate warning
977 is_visb_event_field_name(execution_kind).
978 % is the name of a field for hovers inside a VISB_SVG_OBJECT record
979 is_visb_hover_field_name(hovers).
980 is_visb_hover_field_name(items). % enable items
981 %is_visb_hover_field_name(optional). % not needed ?
982 %is_visb_hover_field_name(override). % not needed ?
983
984 % check if the type of a VISB_SVG_OBJECTS expression requires separation for hovers/events
985 contains_events_or_hovers_field(set(X)) :- contains_events_or_hovers_field(X).
986 contains_events_or_hovers_field(couple(A,B)) :-
987 (contains_events_or_hovers_field(A) -> true ; contains_events_or_hovers_field(B)).
988 contains_events_or_hovers_field(record(F)) :- member(field(Name,_),F),
989 (is_visb_event_field_name(Name) -> true ; is_visb_hover_field_name(Name)).
990
991 get_field_type(field(Name,Expr),field(Name,T)) :- get_texpr_type(Expr,T).
992
993 % separate fields from a SVG/VISB_SVG_OBJECT record into static part and dynamic update expressions
994 separate_fields([],[],[],_).
995 separate_fields([field(Field,Expr)|T],[field(Field,Expr)|TS],TD,DefName) :-
996 is_static_expr(Expr,Field,DefName),!,
997 separate_fields(T,TS,TD,DefName).
998 separate_fields([field(Field,Expr)|T],[field(Field,Default)|TS],[field(Field,Expr)|TD],DefName) :-
999 requires_static_default_value(Field,Default), !,
1000 separate_fields(T,TS,TD,DefName).
1001 separate_fields([H|T],TS,[H|TD],DefName) :-
1002 separate_fields(T,TS,TD,DefName).
1003
1004 % fields which require a static default value; here to set up child SVG objects of title
1005 % static default values could also be useful for hovers in general?
1006 requires_static_default_value(title,b(string('-title-not-set-'),string,[])).
1007
1008 % virtual SVG attributes which are translated to children tags/objects
1009 attribute_automatically_creates_children(title).
1010
1011 is_static_expr(Expr,Field,DefName) :-
1012 determine_type_of_visb_formula(Expr,_TIds,Class), % TODO pass local variables from exists above
1013 (Class=requires_nothing -> true
1014 ; Class=requires_constants,
1015 \+ multiple_concrete_constants_exist, % TODO: check if _TIds have multiple solutions
1016 is_concrete_constants_state_id(_) -> true
1017 ; ajoin(['Detected dynamic expression for field ',Field,' in ',DefName,': '],Msg),
1018 add_debug_message(visb_visualiser,Msg,Expr,Expr),fail
1019 ).
1020
1021 % --------
1022
1023
1024 extract_attribute_from_record(_,field(OrigName,Value),_) :-
1025 opt_rewrite_field_name(OrigName,Name),
1026 deconstruct_singleton_set(Name,Value,'$optional_field_absent'),
1027 !, fail. % optional field (e.g., in TLA+) not present; no error
1028 extract_attribute_from_record(DefPos,field(OrigName,Value),svg_attribute(Name,SVal)) :-
1029 opt_rewrite_field_name(OrigName,Name),
1030 extract_attribute_value(DefPos,Name,Value,SVal).
1031 extract_attribute_from_record(DefPos,F,_) :-
1032 add_error(visb_visualiser,'Extract SVG attribute failed: ',F,DefPos),fail.
1033
1034 % extract a value for a particular field Name
1035 extract_attribute_value(DefPos,Name,Value,SVal) :-
1036 (deconstruct_singleton_set(Name,Value,Element)
1037 -> Element \= '$optional_field_absent',
1038 extract_attr_value(Name,Element,SVal,DefPos)
1039 ; extract_attr_value(Name,Value,SVal,DefPos)
1040 ).
1041
1042
1043 % in TLA+ mode optional record fields have {TRUE|->VALUE} rather than VALUE
1044 % this can also be useful in B to allow mixing different SVG records in a set
1045 % for Alloy mode we may want to also support singleton sets as scalars
1046 deconstruct_singleton_set(Name,Set,Res) :-
1047 singleton_set(Set,El),
1048 detect_partial_records_for_field(Name),
1049 (El=(pred_true,El2)
1050 -> Val=El2 % TLA2B encoding for optional fields that are present
1051 ; Val=El), % Alloy
1052 !,
1053 Res = Val.
1054 deconstruct_singleton_set(Name,[],Res) :-
1055 detect_partial_records_for_field(Name),
1056 Res = '$optional_field_absent'.
1057
1058 detect_partial_records_for_field(points) :- !, fail. % can be set of points
1059 detect_partial_records_for_field(children) :- !, fail. % children field for groups is a set of ids
1060 detect_partial_records_for_field(Name) :-
1061 is_svg_number_attribute(Name),!. % sets never sensible as a numerical value
1062 detect_partial_records_for_field(Name) :- is_id_or_text_attribute(Name),!. % ditto for ids
1063 detect_partial_records_for_field(Name) :- is_svg_color_attribute(Name),!. % ditto for colors
1064 detect_partial_records_for_field(_) :-
1065 \+ classical_b_mode. % TODO: check that we are in TLA or Alloy mode?
1066 % TODO: ensure ProB2 sets animation minor mode for TLA
1067
1068
1069 extract_attr_value(Name,Value,SVal,DefPos) :-
1070 is_svg_number_attribute(Name),!, % we could try and extract svg_class from attribute list above
1071 (get_number_from_bvalue(Value,NrVal)
1072 -> SVal=NrVal % convert to atom?
1073 ; b_value_to_string(Value,SVal),
1074 (is_special_svg_number_form(SVal) -> true
1075 ; atom_codes(SVal,CC),
1076 safe_number_codes(_NrVal,CC) -> true
1077 ; ajoin(['The value of the SVG attribute "',Name,
1078 '" is not a number: '],Msg),
1079 add_warning(visb_visualiser,Msg,SVal,DefPos)
1080 )
1081 ).
1082 extract_attr_value(children,Value,SVal,DefPos) :- !,
1083 (is_set_value(Value,extract_attr_value)
1084 -> (try_expand_custom_set_with_catch(Value,ExpandedSet,extract_attr_value),
1085 maplist(b_value_to_id_string,ExpandedSet,SVal) -> true
1086 ; add_warning(visb_visualiser,'The children attribute should be a finite set of identifiers: ',Value,DefPos),
1087 SVal=[]
1088 )
1089 ; add_warning(visb_visualiser,'The children attribute should be a set of identifiers: ',Value,DefPos),
1090 SVal=[]).
1091 extract_attr_value(points,Value,SVal,DefPos) :- % Class should be polygon or polyline
1092 % automatically translate sequences or sets of pairs of numbers to SVG string format
1093 (Value = [(Nr,_)|_] ; Value = avl_set(node((Nr,_),_,_,_,_))),
1094 is_number(Nr), % TODO: check typing
1095 svg_points(Value,Str,DefPos,no_wf_available),!,
1096 string(SVal)=Str.
1097 extract_attr_value(points,Value,SVal,_DefPos) :- Value = [],!, SVal = ''.
1098 extract_attr_value(visibility,Value,SVal,DefPos) :- !,
1099 % convert TRUE -> visible, FALSE -> hidden
1100 ( Value=pred_true -> TxtVal='visible'
1101 ; Value=pred_false -> TxtVal='hidden'
1102 ; b_value_to_string(Value,TxtVal),
1103 (member(TxtVal,[collapse,hidden,visible]) -> true
1104 ; add_warning(visb_visualiser,'Value of SVG attribute "visibility" must be collapse,hidden or visible and not: ',TxtVal,DefPos))
1105 ),
1106 SVal=TxtVal.
1107 extract_attr_value(Name,Value,_,DefPos) :-
1108 check_svg_attribute_value(Name,Value,DefPos),fail.
1109 extract_attr_value(Name,Value,SVal,_) :-
1110 is_id_or_text_attribute(Name),!,
1111 (Name=text -> b_value_to_string(Value,SVal) % a pure text field; you probably want to see the B value
1112 ; is_text_attribute(Name) % something like transform, predicate, event; here maybe automatic concat can be useful
1113 -> b_value_to_attr_string(Value,SVal)
1114 ; b_value_to_id_string(Value,SVal)). % concatenates e.g. pairs of strings to string without ( |-> )
1115 extract_attr_value(Attr,RawValue,ResValue,_DefPos) :- raw_value_attribute(Attr),!, % keep value intact
1116 ResValue = RawValue.
1117 extract_attr_value(_Name,Value,SVal,_DefPos) :-
1118 b_value_to_string(Value,SVal).
1119
1120 % visb_visualiser:extract_attr_value(text,avl_set(node((fd(1,'Kunden'),int(0)),true,0,empty,empty)),S,unknown).
1121
1122 is_number(int(_)).
1123 is_number(term(floating(_))).
1124
1125 % do not convert to string; these are treated separately
1126 raw_value_attribute(hovers).
1127 raw_value_attribute(events).
1128
1129
1130 % evaluate a DEFINITION to a set of B records representing SVG objects
1131 % returns a possibly refined sub-position corresponding to generated SVG objects as last argument
1132 get_visb_DEFINITION_svg_object(SpecialClass,DefName,Body,_DefPos,ExpandedState,SVG_ID,AttrList,Desc,InnerPos) :-
1133 get_preference(visb_show_debug_infos,true),
1134 bsyntaxtree:is_eventb_comprehension_set(Body,Ids,Pred,Expr),
1135 % try and separate couple in Expr so that we have better position info for source of VISB_SVG_OBJECTS
1136 Body = b(_,Type,II),
1137 Expr = b(couple(_,_),_,_),
1138 !,
1139 couple_member(NewExpr,Expr), % evaluate each part of the couple in isolation, with better position info
1140 get_texpr_pos(NewExpr,InnerPos),
1141 b_ast_cleanup:rewrite_event_b_comprehension_set(Ids,NewExpr,Pred, Type, NewBody),
1142 get_visb_DEF_svg_object_aux(SpecialClass,DefName,b(NewBody,Type,II),InnerPos,ExpandedState,SVG_ID,AttrList,Desc).
1143 get_visb_DEFINITION_svg_object(SpecialClass,DefName,Body,DefPos,ExpandedState,SVG_ID,AttrList,Desc,DefPos) :-
1144 get_visb_DEF_svg_object_aux(SpecialClass,DefName,Body,DefPos,ExpandedState,SVG_ID,AttrList,Desc).
1145
1146 couple_member(TExpr,b(couple(A,B),_,_)) :- !, (couple_member(TExpr,A) ; couple_member(TExpr,B)).
1147 couple_member(TExpr,TExpr).
1148
1149 get_visb_DEF_svg_object_aux(SpecialClass,DefName,Body,DefPos,ExpandedState,SVG_ID,AttrList,Desc) :-
1150 evaluate_visb_formula(Body,DefName,'',ExpandedState,ResValue,DefPos),
1151 flex_expand(ResValue,DefName,DefPos,Expanded,[]),
1152 (Expanded = [] -> add_message(visb_visualiser,'Empty set of SVG object records: ',DefName,DefPos)
1153 ; Expanded =[Record|_] ->
1154 (get_VISB_record_fields(Record,Fs)
1155 % TODO: as we now can have different type of records, check in flex_expand below
1156 -> (member(field(id,_),Fs)
1157 -> true
1158 ; add_message(visb_visualiser,'DEFINITION needs an `id` field if you want to use updates: ',DefName,DefPos)
1159 )
1160 ; ajoin(['DEFINITION ', DefName,' should evaluate to a set of records or tuples of records: '],Msg),
1161 add_warning(visb_visualiser,Msg,Record,DefPos)
1162 )
1163 ),
1164 member(Records,Expanded),
1165 get_VISB_record_fields(Records,Fields),
1166 (select(field(id,VID),Fields,F1)
1167 -> extract_attribute_value(DefPos,id,VID,SVG_ID)
1168 ; gensym(svg_id,SVG_ID), F1=Fields),
1169 (select(field(comment,CC),F1,F2), b_value_to_string(CC,Desc) -> true
1170 ; Desc = '', F2=F1),
1171 (SpecialClass=visb_updates, member(field(visibility,VV),F2),
1172 is_invisible(VV),
1173 \+ visb_has_visibility_hover(SVG_ID) % check for hover which may make object visible
1174 -> AttrList=[svg_attribute(visibility,'hidden')] % do not transmit updates
1175 ; include_maplist(extract_attribute_from_record(DefPos),F2,AttrList0),
1176 exclude(check_unsupported_special_visb_attribute(SpecialClass,DefPos),AttrList0,AttrList),
1177 (select(svg_attribute(svg_class,SVG_Class),AttrList,A2)
1178 -> maplist(check_attribute_is_supported(SVG_Class,DefPos),A2)
1179 ; true)
1180 ).
1181
1182 is_invisible(string(hidden)). % also treat collapse ?
1183 is_invisible(pred_false).
1184
1185 % expand nested tuples/sets to a single list of SVG records (possibly of different types)
1186 flex_expand(Value,DefName,Pos) --> {is_custom_explicit_set(Value)},!,
1187 {try_expand_custom_set_with_catch(Value,ExpandedSet,flex_expand),
1188 (is_custom_explicit_set(ExpandedSet)
1189 -> ajoin(['Could not expand set of SVG object records or tuples thereof for ',DefName,': '],Msg),
1190 add_warning(visb_visualiser,Msg,Value,Pos),
1191 fail
1192 ; true)},
1193 flex_expand(ExpandedSet,DefName,Pos).
1194 flex_expand([],_,_) --> !, [].
1195 flex_expand(L,_DefName,_Pos) --> {L =[(string(_),string(_))|_]}, !,
1196 [L]. % is probably a partial function {"id" |-> ,...}
1197 flex_expand([H|T],DefName,Pos) --> !, flex_expand(H,DefName,Pos), l_flex_expand(T,DefName,Pos).
1198 flex_expand((A,B),DefName,Pos) --> !, flex_expand(A,DefName,Pos), flex_expand(B,DefName,Pos).
1199 flex_expand(T,_,_) --> [T].
1200
1201 l_flex_expand([],_,_) --> !, [].
1202 l_flex_expand([H|T],DefName,Pos) --> !, flex_expand(H,DefName,Pos), l_flex_expand(T,DefName,Pos).
1203 l_flex_expand(T,_,_) --> [T].
1204
1205 flex_member(X,SetPairVal,DefName,Pos) :- flex_expand(SetPairVal,DefName,Pos,List,[]), member(X,List).
1206
1207
1208 % get the fields of a B value record
1209 % also transparently handles alternative representations, like a function from STRING to STRING
1210 get_VISB_record_fields(rec(Fields),Res) :- !, Res=Fields.
1211 get_VISB_record_fields(StringFunction,Fields) :-
1212 is_set_value(StringFunction,get_VISB_record_fields),
1213 try_expand_custom_set_with_catch(StringFunction,Expanded,get_VISB_record_fields),
1214 % TODO: check we have no duplicates
1215 maplist(convert_to_field,Expanded,Fields).
1216 % TODO: support records as generated by READ_XML:
1217 % rec(attributes:{("fill"|->"#90ee90"),("height"|->"360px"),("id"|->"background_rect"),("width"|->"600px"),("x"|->"1px"),("y"|->"2px")},element:"rect",meta:{("xmlLineNumber"|->"3")},pId:5,recId:6)
1218 % for <rect height="360px" x="1px" y="2px" id="background_rect" width="600px" fill="#90ee90"></rect>
1219
1220 convert_to_field((string(FieldName),Value),field(FieldName,Value)).
1221 % TODO: maybe handle enumerated set values as field names
1222
1223
1224 % already extract and type-check VISB_SVG_UPDATES definitions
1225 precompile_svg_object_updates(ExpandedScope,JsonFileContext) :-
1226 b_sorted_b_definition_prefixed(expression,'VISB_SVG_UPDATES',DefName,DefPos),
1227 b_get_typed_definition(DefName,ExpandedScope,TypedExpr),
1228 assert_visb_udpate_def_body(visb_updates,DefName,TypedExpr,DefPos),
1229 add_children_for_visb_update_def_body(TypedExpr,DefName,JsonFileContext),
1230 fail.
1231 precompile_svg_object_updates(_,_).
1232
1233 % assert VisB updates or hovers from B DEFINITION,
1234 % either from VISB_SVG_UPDATES or hovers or dynamic parts of VISB_SVG_OBJECTS:
1235 assert_visb_udpate_def_body(_Kind,DefName,TypedExpr,_DefPos) :-
1236 TypedExpr=b(rec([field(id,_)]),_,Info),!, % can happen when all fields are static
1237 add_debug_message(visb_visualiser,'Useless update/hover (just id field): ',DefName,Info).
1238 assert_visb_udpate_def_body(Kind,DefName,b(couple(A,B),_,_),DefPos) :- !,
1239 % separate couples into individual expressions; in case of WD errors we have more localised errors/problems
1240 assert_visb_udpate_def_body(Kind,DefName,A,DefPos),
1241 assert_visb_udpate_def_body(Kind,DefName,B,DefPos).
1242 assert_visb_udpate_def_body(Kind,DefName,TypedExpr,DefPos) :-
1243 get_texpr_type(TypedExpr,Type),
1244 determine_type_of_visb_formula(TypedExpr,_,FormulaClass),
1245 debug_format(19,'Detected ~w: ~w (~w)~n',[Kind,DefName,FormulaClass]),
1246 assertz(visb_special_definition(Kind,DefName,Type,TypedExpr,FormulaClass,DefPos)),
1247 check_visb_update_type(Kind,Type,DefName,unknown_svg_class,DefPos),
1248 static_check_dynamic_update_def_body(TypedExpr).
1249
1250
1251 % check if we need to add virtual children for an VISB_SVG_UPDATES body:
1252 % (e.g., for title updates to SVG objects coming from an SVG file)
1253 add_children_for_visb_update_def_body(b(couple(A,B),_,_),DefName,JsonFile) :- !,
1254 (add_children_for_visb_update_def_body(A,DefName,JsonFile)
1255 ;
1256 add_children_for_visb_update_def_body(B,DefName,JsonFile)).
1257 add_children_for_visb_update_def_body(b(rec(Fields),_,_),DefName,JsonFile) :-
1258 select(field(id,TParentId),Fields,F2),!,
1259 is_static_expr(TParentId,id,DefName), % we need a static value to create children for it
1260 TParentId = b(_,_,Info),
1261 determine_type_of_visb_formula(TParentId,TIds,Class),
1262 eval_static_def(Class,DefName,'',TParentId,TIds,ResValue,Info), % evaluate in constants state if necessary
1263 b_value_to_id_string(ResValue,ParentId),
1264 \+ svg_id_exists(ParentId),
1265 (\+ get_default_visb_svg_file(_,_), % cannot call no_svg_file_available yet
1266 JsonFile = '', % No JSON file to be loaded after, which could add SVG file or objects
1267 \+ special_definition_exists('VISB_SVG_CONTENTS')
1268 -> ajoin(['Unknown VISB_SVG_OBJECT with id ',ParentId,' in: '],Msg),
1269 add_warning(visb_visualiser,Msg,DefName,Info)
1270 ; select(field(title,TTitle),F2,_),
1271 (TTitle = b(string(Title),_,_) -> true ; Title = 'no-title-set'),
1272 get_texpr_pos(TTitle,Pos),
1273 add_virtual_title_object(Title,DefName,Pos,TitleID),
1274 assert_visb_svg_child(ParentId,Pos,TitleID),
1275 assert(visb_svg_child_of_object_from_svg_file(TitleID))
1276 ),
1277 fail.
1278 % TODO: set comprehensions like {x•x:Obj|rec(id=("obj",x), title=....)}
1279 % TODO: support sets and warn when ID is not statically known?
1280
1281 % assert VisB events or hovers from B DEFINITION, from part of VISB_SVG_OBJECTS:
1282 % supporting event: attribute and optional predicate attribute
1283 % Kind = visb_events %or visb_hovers
1284 add_visb_events_from_def_body(Kind,DefName,Body,DefPos) :-
1285 get_texpr_type(Body,Type),
1286 \+ empty_update_or_hover_type(Type), % at least one more field than just id field
1287 get_visb_static_svg_object_for_typed_expr(Kind,DefName,Body,DefPos,SVG_ID,AttrList,Desc,InnerPos),
1288 add_visb_object_from_definition(Kind, SVG_ID, AttrList, Desc, DefName, InnerPos),
1289 fail.
1290 add_visb_events_from_def_body(_,_,_,_).
1291
1292 empty_update_or_hover_type(record(Fields)) :- !, Fields \= [_,_|_]. % at least one more field than just id field
1293 empty_update_or_hover_type(set(X)) :- !, empty_update_or_hover_type(X).
1294 empty_update_or_hover_type(couple(A,B)) :- !, empty_update_or_hover_type(A), empty_update_or_hover_type(B).
1295
1296 get_svg_object_updates_from_definitions(ExpandedBState,SVG_ID,SvgAttribute,Value,Pos) :-
1297 visb_special_definition(visb_updates,DefName,_Type,BodyTypedExpr,_Class,DefPos),
1298 get_visb_DEFINITION_svg_object(visb_updates,DefName,BodyTypedExpr,DefPos,ExpandedBState,SVG_ID,AttrList,_Desc,Pos),
1299 member(svg_attribute(SvgAttribute,Value),AttrList).
1300
1301 % check types of VisB updates
1302 check_visb_update_type(Kind,Type,DefName,Class,DefPos) :-
1303 get_update_record_fields_type(Type,Fields),
1304 % other types are STRING +-> STRING, ...; this will be checked in get_visb_DEFINITION_svg_object
1305 (memberchk(field('svg_class',_),Fields)
1306 -> add_warning(visb_visualiser,'VisB updates should not set svg_class:',DefName,DefPos)
1307 ; true),
1308 member(field(Name,FieldType),Fields),
1309 (Name = trigger_id ->
1310 (Kind=visb_hovers -> true ;
1311 add_warning(visb_visualiser,'Attribute trigger_id can only be used for hovers:',DefName,DefPos)
1312 )
1313 ; check_attribute_type_and_name(FieldType,Name,DefName,Class,DefPos)
1314 ),
1315 fail.
1316 check_visb_update_type(_,_,_,_,_).
1317
1318 % get a fields type list from a type
1319 get_update_record_fields_type(set(X),Fields) :- !,
1320 get_update_record_fields_type(X,Fields).
1321 get_update_record_fields_type(record(Fields),R) :- !, R=Fields.
1322 get_update_record_fields_type(couple(A,B),Fields) :-
1323 (get_update_record_fields_type(A,Fields)
1324 ; get_update_record_fields_type(B,Fields)).
1325
1326
1327 % check B type of a field for an SVG update or object
1328 check_attribute_type_only(Type,Name,DefName,Class,DefPos) :- alternative_spelling(Name,AName),!,
1329 check_attribute_type_only(Type,AName,DefName,Class,DefPos).
1330 check_attribute_type_only(Type,Name,DefName,Class,DefPos) :- Class \= unknown_svg_class,
1331 check_is_number_attribute(Name,Class,DefPos),!,
1332 (illegal_number_type(Type)
1333 -> ajoin(['Type of field ',Name,' of ', DefName, ' is not a number: '],Msg),
1334 pretty_type(Type,TS),
1335 add_warning(visb_visualiser,Msg,TS,DefPos)
1336 ; true).
1337 check_attribute_type_only(Type,Name,DefName,_,DefPos) :-
1338 is_svg_color_attribute(Name),!,
1339 (illegal_col_type(Type)
1340 -> ajoin(['Type of field ',Name,' of ', DefName, ' is not a color: '],Msg),
1341 pretty_type(Type,TS),
1342 add_warning(visb_visualiser,Msg,TS,DefPos)
1343 ; true).
1344 check_attribute_type_only(_Type,_Name,_DefName,_Class,_DefPos).
1345
1346 check_attribute_type(BType,AttrName,ID,Pos) :-
1347 (svg_id_has_class(ID,Class) -> true ; true),
1348 check_attribute_type_only(BType,AttrName,ID,Class,Pos).
1349 check_attribute_type_and_name(Type,AttrName,DefName,Class,DefPos) :-
1350 check_attribute_type_only(Type,AttrName,DefName,Class,DefPos),
1351 check_attribute_name_is_supported(Class,AttrName,DefPos).
1352
1353 illegal_nr_or_col_type(boolean).
1354 illegal_nr_or_col_type(set(_)).
1355 illegal_nr_or_col_type(seq(_)).
1356 illegal_nr_or_col_type(record(_)).
1357 illegal_nr_or_col_type(couple(A,B)) :- (illegal_nr_or_col_type(A) -> true ; illegal_nr_or_col_type(B)).
1358 % check if couple types can work by concatenating string representations
1359
1360 illegal_col_type(X) :- illegal_nr_or_col_type(X),!.
1361 illegal_col_type(real).
1362 % integer ? or can we map integers to colours using a color scheme like in DOT?
1363
1364 illegal_number_type(X) :- illegal_nr_or_col_type(X),!.
1365 %illegal_number_type(global(_)). % what if we use a global set with weird constants using back-quotes ?
1366
1367 % ----------------
1368
1369 % parse and load an individual JSON VisB item, e.g, :
1370 % { "name":"xscale",
1371 % "value" : "(100.0 / real(TrackElementNumber))"
1372 % }
1373
1374 process_json_definition(File,json(List)) :-
1375 (get_attr_true(ignore,List,File) -> true % ignore this definition
1376 ; process_json_def_lst(File,List)).
1377
1378
1379 process_json_def_lst(File,List) :-
1380 force_del_attr_with_pos(name,List,string(ID),L1,File,NamePos),
1381 force_del_attr_with_pos(value,L1,string(Formula),L2,File,VPos),
1382 debug_format(19,' Processing definition for ~w with value-formula (lines ~w):~w~n',[ID,VPos,Formula]),
1383 !,
1384 set_gen_parse_errors(L2,VPos,GenParseErrors), % treat optional attribute
1385 process_json_definition(ID,NamePos,Formula,VPos,GenParseErrors).
1386 process_json_def_lst(File,List) :- get_pos_from_list(List,File,Pos),
1387 add_error(visb_visualiser,'Illegal VisB Definition:',List,Pos).
1388
1389 % we could also load a classical B Definition file and process its definitions like this:
1390 process_json_definition(ID,NamePos,Formula,VPos,GenParseErrors) :-
1391 atom_codes(Formula,FCodes),
1392 set_error_context(visb_error_context(definition,ID,'value',VPos)),
1393 (b_get_definition_name_with_pos(ID,_Arity,_DefType,_DPos)
1394 -> add_warning(visb_visualiser,'Ignoring VisB definition, DEFINITION of the same name already exists:',ID,NamePos)
1395 ; parse_expr(FCodes,TypedExpr,GenParseErrors)
1396 -> add_visb_json_definition(ID,TypedExpr,VPos)
1397 ; GenParseErrors=false -> formatsilent('Ignoring optional VisB definition for ~w due to error in B formula~n',[ID])
1398 ; add_error(visb_visualiser,'Cannot parse or typecheck VisB formula for definition',ID,VPos)
1399 ),
1400 clear_error_context.
1401
1402 add_visb_json_definition(ID,TypedExpr,VPos) :-
1403 get_texpr_type(TypedExpr,Type),
1404 determine_type_of_visb_formula(TypedExpr,TIds,Class), %write(type(ID,Class,TIds)),nl,
1405 (try_eval_static_def(Class,'static definition', ID,TypedExpr,TIds,StaticValue,VPos)
1406 -> get_texpr_type(TypedExpr,Type),StaticValueExpr = b(value(StaticValue),Type,[]),
1407 assert_visb_json_definition(ID,Type,StaticValueExpr,TIds,Class,VPos)
1408 ; assert_visb_json_definition(ID,Type,TypedExpr,TIds,Class,VPos)
1409 ).
1410
1411 % assert a VisB definition stemming from the JSON definitions section:
1412 assert_visb_json_definition(DefName,Type,TypedExpr,UsedTIds,Class,DefPos) :-
1413 (is_special_visb_def_name(DefName,SpecialClass) -> true ; SpecialClass = regular_def),
1414 assertz(visb_definition(DefName,Type,TypedExpr,Class,DefPos,SpecialClass)),
1415 (SpecialClass \= regular_def
1416 -> formatsilent('Detected special ~w definition ~w (~w)~n',[SpecialClass,DefName,Class]),
1417 add_special_json_definition(SpecialClass,DefName,Type,TypedExpr,UsedTIds,Class,DefPos)
1418 ; true
1419 ).
1420
1421 % register some special definitions, in which a set of objects/hovers/updates can be specified
1422 % by a single definition returning a set of records
1423 add_special_json_definition(visb_updates,DefName,Type,TypedExpr,_,Class,DefPos) :- !,
1424 check_visb_update_type(visb_updates,Type,DefName,Class,DefPos),
1425 assertz(visb_special_definition(visb_updates,DefName,Type,TypedExpr,Class,DefPos)). % will be evaluated later
1426 add_special_json_definition(visb_contents,DefName,Type,TypedExpr,_,Class,DefPos) :- !,
1427 assertz(visb_special_definition(visb_contents,DefName,Type,TypedExpr,Class,DefPos)).
1428 add_special_json_definition(visb_box,DefName,Type,TypedExpr,_,Class,DefPos) :- !,
1429 assertz(visb_special_definition(visb_box,DefName,Type,TypedExpr,Class,DefPos)).
1430 add_special_json_definition(visb_objects,DefName,_Type,TypedExpr,_UsedTIds,_Class,DefPos) :- !,
1431 AllowSep=allow_separation, % TODO: we re-determine the class and used ids below:
1432 get_typed_static_definition_with_constants_state(DefName,TypedExpr,ResBody,DefPos,CS,no_inlining,AllowSep),
1433 (get_visb_DEFINITION_svg_object(visb_objects,DefName,ResBody,DefPos,CS,SVG_ID,AttrList,Desc,InnerPos),
1434 %formatsilent('Adding ~w : ~w (from ~w)~n',[visb_objects,SVG_ID,DefName]),
1435 add_visb_object_from_definition(visb_objects, SVG_ID, AttrList, Desc, DefName, InnerPos),
1436 fail ; true).
1437 add_special_json_definition(SpecialClass,DefName,_Type,TypedExpr,UsedTIds,Class,DefPos) :-
1438 (get_unique_initial_state_for_visb(Class,DefName,DefPos,UsedTIds,ConstantsState) -> true
1439 ; ConstantsState=[]),
1440 get_static_visb_state(ConstantsState,FullState), % add static VisB Defs
1441 (Class=requires_variables,
1442 (get_preference(visb_allow_variables_for_objects,false) ; ConstantsState=[])
1443 -> add_warning(visb_visualiser,'Ignoring VisB definition which requires variables:',DefName,DefPos)
1444 ; (get_visb_DEFINITION_svg_object(SpecialClass,DefName,TypedExpr,DefPos,FullState,SVG_ID,AttrList,Desc,InnerPos),
1445 %formatsilent('Adding ~w : ~w (from ~w)~n',[SpecialClass,SVG_ID,DefName]),
1446 add_visb_object_from_definition(SpecialClass, SVG_ID, AttrList, Desc, DefName, InnerPos),
1447 fail % backtrack to add all objects and all hover attributes
1448 ; true)
1449 ).
1450
1451 is_special_visb_def_name(DefName,visb_updates) :- atom_concat('VISB_SVG_UPDATES',_,DefName).
1452 is_special_visb_def_name(DefName,visb_hovers) :- atom_concat('VISB_SVG_HOVERS',_,DefName).
1453 is_special_visb_def_name(DefName,visb_objects) :- atom_concat('VISB_SVG_OBJECTS',_,DefName).
1454 is_special_visb_def_name(DefName,visb_contents) :- atom_concat('VISB_SVG_CONTENTS',_,DefName).
1455 is_special_visb_def_name(DefName,visb_events) :- atom_concat('VISB_SVG_EVENTS',_,DefName).
1456 is_special_visb_def_name('VISB_SVG_BOX',visb_box).
1457 % TODO: maybe provide VISB_HTML_CONTENTS which appear after the SVG
1458
1459 % evaluate static VisB defs only once or evaluate expressions in svg_objects and loop bounds
1460 eval_static_def(Class,VisBKind,ID,TypedExpr,UsedTIds,StaticValue,VPos) :-
1461 get_unique_initial_state_for_visb(Class,ID,VPos,UsedTIds,ConstantsState),
1462 evaluate_static_visb_formula(TypedExpr,VisBKind,ID,ConstantsState,StaticValue,VPos).
1463
1464 % only evaluate statically if possible; no warnings/messages if not possible (just fail)
1465 try_eval_static_def(requires_variables,_VisBKind,_ID,_TypedExpr,_UsedTIds,_StaticValue,_VPos) :- !,
1466 fail. % do not try to evaluate statically; events will change the variable values anyway
1467 try_eval_static_def(Class,VisBKind,ID,TypedExpr,UsedTIds,StaticValue,VPos) :-
1468 % TODO: disable messages for multiple constants values; just fail
1469 eval_static_def(Class,VisBKind,ID,TypedExpr,UsedTIds,StaticValue,VPos).
1470
1471 % check if a unique constant value exists for a model
1472 get_unique_initial_state_for_visb(requires_nothing,_,_,_,State) :- !, State=[].
1473 get_unique_initial_state_for_visb(Class,DefName,DefPos,_,State) :-
1474 \+ multiple_concrete_constants_exist,
1475 is_concrete_constants_state_id(StateID),!,
1476 (Class=requires_variables
1477 -> get_preference(visb_allow_variables_for_objects,true),
1478 unique_initialisation_id_exists_from(StateID,DefName,DefPos,State)
1479 % Note: variable can still be modified by other events later, e.g., in ProB2-UI
1480 ; visited_expression(StateID,StateTerm),
1481 state_corresponds_to_set_up_constants_only(StateTerm,State)).
1482 get_unique_initial_state_for_visb(requires_constants,DefName,DefPos,Ids,State) :- Ids \= all,
1483 % try and see if all values for Ids are the same; TODO: also support requires_variables
1484 is_concrete_constants_state_id(StateID),!,
1485 visited_expression(StateID,StateTerm),
1486 state_corresponds_to_set_up_constants_only(StateTerm,State),
1487 (member(C,Ids), get_texpr_id(C,CstID),
1488 other_constant_value_exists_for(CstID,State,StateID)
1489 -> ajoin(['Multiple values for constant ',CstID, ' in context of'],Msg),
1490 add_visb_lint_message(Msg,DefName,DefPos),fail
1491 ; true).
1492
1493
1494 get_a_constants_state(State,StateID,inline_objects(SingleStateId)) :-
1495 get_constants_state_id_for_id(SingleStateId,StateID),!,
1496 visited_expression(StateID,StateTerm),
1497 state_corresponds_to_set_up_constants_only(StateTerm,State).
1498 get_a_constants_state(State,StateID,InlineObjects) :-
1499 check_inlining(InlineObjects),
1500 is_concrete_constants_state_id(StateID),!,
1501 visited_expression(StateID,StateTerm),
1502 state_corresponds_to_set_up_constants_only(StateTerm,State).
1503
1504 check_inlining(no_inlining) :- !.
1505 check_inlining(inline_objects(_SingleStateId)) :- !.
1506 check_inlining(X) :- add_internal_error('Invalid inlining value:',check_inlining(X)).
1507
1508
1509 other_constant_value_exists_for(CstID,State,StateId) :-
1510 lookup_value_for_existing_id(CstID,State,Val1),
1511 is_concrete_constants_state_id(StateId2), StateId2 \= StateId,
1512 visited_expression(StateId2,StateTerm2),
1513 state_corresponds_to_set_up_constants_only(StateTerm2,State2),
1514 lookup_value_for_existing_id(CstID,State2,Val2),
1515 Val2 \= Val1.
1516
1517
1518 unique_initialisation_id_exists_from(FromStateId,DefName,DefPos,State) :-
1519 transition(FromStateId,_,StateID),!,
1520 (transition(FromStateId,_,StateID2),
1521 StateID2 \= StateID
1522 -> ajoin(['Multiple initialisations exists (state ids ',StateID,',',StateID2,') for'],Msg),
1523 add_visb_lint_message(Msg,DefName,DefPos),fail
1524 ; true),
1525 visited_expression(StateID,StateTerm),
1526 state_corresponds_to_initialised_b_machine(StateTerm,State).
1527
1528 parse_expr_for_visb(Formula,JsonList,Pos,TypedExpr) :-
1529 set_gen_parse_errors(JsonList,Pos,GenParseErrors),
1530 parse_expr(Formula,TypedExpr,GenParseErrors).
1531
1532 set_gen_parse_errors(JSonList,Pos,GenParseErrors) :-
1533 (is_optional_json_item(JSonList)
1534 -> GenParseErrors=false
1535 ; %get_pos_from_list(JSonList,File,Position),
1536 GenParseErrors=gen_parse_errors_for(Pos)).
1537
1538 % ----------------
1539
1540 % parse and load an individual JSON SVG object listed under svg_objects, e.g, :
1541 % {
1542 % "svg_class":"rect",
1543 % "id":"train_rect",
1544 % "x":"0",
1545 % "y":"0",
1546 % "comment":"..."
1547 % },
1548 process_json_svg_object(File,Json) :-
1549 process_repeat(0,Json,File,add_visb_json_svg_object).
1550
1551 add_visb_json_svg_object(File,json(List)) :- get_attr_true(ignore,List,File), !. % ignore this item
1552 add_visb_json_svg_object(File,json(List)) :-
1553 (del_attr_with_pos(svg_class,List,string(SVG_Class),L1,File,Pos1) -> true % shape: line, rect, ...
1554 ; infer_svg_class(List,SVG_Class,File,Pos1)
1555 -> add_visb_lint_message('Inferred svg_class',SVG_Class,Pos1),L1=List
1556 ; force_del_attr_with_pos(svg_class,List,string(SVG_Class),L1,File,Pos1) % generates error message
1557 ),
1558 force_del_attr(id,L1,string(ID),L2,File),
1559 (del_attr(comment,L2,string(Desc),JsonList3) -> true ; Desc = '', JsonList3=L2),
1560 debug_format(19,' Creating new SVG object ~w with id:~w~n',[SVG_Class,ID]),
1561 add_debug_message(visb_visualiser,'New object: ',ID,Pos1),
1562 % TODO: we could pre-process all attributes not depending on %0, %1, ...
1563 maplist(get_svg_attr(ID,SVG_Class,File),JsonList3,AttrList),
1564 %formatsilent('Adding SVG Object ~w with ID ~w (~w): ~w~n',[SVG_Class,ID,Desc,AttrList]),
1565 assert_visb_svg_object(ID,SVG_Class,AttrList,Desc,'JSON',Pos1),
1566 !.
1567 add_visb_json_svg_object(File,Json) :-
1568 !,
1569 get_pos_from_list(Json,File,Pos),
1570 add_error(visb_visualiser,'Illegal VisB additional SVG object:',Json,Pos).
1571
1572 infer_svg_class(List,line,File,Pos) :- get_attr_with_pos(x1,List,_,File,Pos),!.
1573 infer_svg_class(List,circle,File,Pos) :- get_attr_with_pos(r,List,_,File,Pos),!.
1574 infer_svg_class(List,rect,File,Pos) :- get_attr_with_pos(height,List,_,File,Pos),!.
1575 infer_svg_class(List,rect,File,Pos) :- get_attr_with_pos(width,List,_,File,Pos),!.
1576 infer_svg_class(List,ellipse,File,Pos) :- get_attr_with_pos(rx,List,_,File,Pos),!. % could also be rect
1577 infer_svg_class(List,text,File,Pos) :- get_attr_with_pos(text,List,_,File,Pos),!.
1578 infer_svg_class(List,g,File,Pos) :- get_attr_with_pos(children,List,_,File,Pos),!. % group + foreignObject have children
1579 infer_svg_class(List,use,File,Pos) :- get_attr_with_pos(href,List,_,File,Pos),!. % href can also be used with image, pattern, ...
1580
1581 % assert a new SVG object to be created upon SETUP_CONSTANTS/INITIALISATION:
1582 assert_visb_svg_object(ID,SVG_Class,_AttrList,_Desc,DefName,Pos1) :-
1583 visb_svg_object(ID,_,_,_,_Pos0),!,
1584 ajoin(['SVG object (from ',DefName,', svg_class=',SVG_Class,') with same id already created: '],Msg),
1585 add_warning(visb_visualiser,Msg,ID,Pos1).
1586 assert_visb_svg_object(_ID,_SVG_Class,AttrList,_Desc,_DefName,Pos1) :-
1587 \+ (AttrList=[] ; AttrList=[_|_]),!,
1588 add_error(visb_visualiser,'SVG objects attributes are not a list:',AttrList,Pos1).
1589 assert_visb_svg_object(ID,SVG_Class,AttrList,Desc,DefName,Pos1) :-
1590 add_visb_debug_infos(ID,SVG_Class,AttrList,AttrList2,DefName,Pos1),
1591 sort(AttrList2,SAttrList),
1592 get_all_children(SAttrList,Children,RestAttrs,DefName,Pos1),
1593 (Children = [] -> true
1594 ; svg_shape_can_have_children(SVG_Class) -> true % g, foreignObject, symbol, HTML tags
1595 ; Children = [C1_ID|_], visb_svg_object(C1_ID,CAttr,_,_,_),
1596 attribute_automatically_creates_children(CAttr) % e.g., title object created for title attribute of ID
1597 -> true
1598 ; add_visb_lint_message('Children attribute only useful for certain SVG classes such as groups (g) or foreignObject or when adding title objects (as tooltips)',Children,Pos1)
1599 ),
1600 (select(svg_attribute(group_id,ParentGroupId),RestAttrs,RestAttrs2)
1601 -> assert_visb_svg_child(ParentGroupId,Pos1,ID) % register parent group id
1602 ; RestAttrs2=RestAttrs),
1603 check_svg_shape_class(ID,SVG_Class,Pos1), % after registering group_id, so that the parent is known
1604 compute_auto_attributes(RestAttrs2,RestAttrs2,SVG_Class,NewRestAttrs),
1605 assertz(visb_svg_object(ID,SVG_Class,NewRestAttrs,Desc,Pos1)),
1606 maplist(assert_visb_svg_child(ID,Pos1),Children). % add all children
1607
1608 % adapt visb_svg_object to provide developer debug infos, e.g., in title hover messages
1609 add_visb_debug_infos(ID,SVG_Class,AttrList,NewAttrList,DefName,Pos) :- SVG_Class \= title,
1610 get_preference(visb_show_debug_infos,true),
1611 (select(svg_attribute(title,Title),AttrList,RestAttrs) -> true
1612 ; Title='', RestAttrs=AttrList),
1613 !,
1614 extract_span_description_with_opts(Pos,PosStr,
1615 [relative_file_name,compact_pos_info,
1616 inner_context_separator('\n in ','\n at ')]),
1617 %extract_definition_call_stack_desc(Pos,CS), already displayed in inner context
1618 ajoin(['-- VISB_DEBUG_INFO --\nid=',ID, '\nsvg_class=',SVG_Class, '\nsrc=',DefName,'\n', PosStr],DebugInfo),
1619 (Title='' -> NewTitle=DebugInfo ; ajoin([Title,'\n',DebugInfo],NewTitle)),
1620 %format('~nDEBUG::~n~w~n~w~n---~n',[ID,DebugInfo]),
1621 assert(visb_svg_object_debug_info(ID,DebugInfo)),
1622 NewAttrList = [svg_attribute(title,NewTitle)|RestAttrs].
1623 add_visb_debug_infos(_,_,AttrList,AttrList,_,_).
1624
1625 % compute the value of VisB auto attributes, e.g., automatically
1626 % doing a layout of objects in a grid
1627 % TODO: SVG/special_svg_number already supports auto but not for x,y coordinates?
1628 % TODO: try and determine width of object automatically; keep track of auto objects max height per row
1629 % TODO: support cx,cy
1630 compute_auto_attributes([],_,_,[]).
1631 compute_auto_attributes([svg_attribute(Attr,Val)|T],AllAttrs,SVG_Class,
1632 [svg_attribute(Attr,NewVal)|NT]) :-
1633 (Val=auto, compute_auto_attribute(Attr,AllAttrs,SVG_Class,NewVal)
1634 -> true
1635 ; NewVal=Val),
1636 compute_auto_attributes(T,AllAttrs,SVG_Class,NT).
1637
1638 :- dynamic next_auto_x/1, next_auto_y/2.
1639 next_auto_x(0).
1640 next_auto_y(0,0). % y coordinate and height of the current row of automatically placed objects
1641 reset_auto_attrs :- retractall(next_auto_x(_)),
1642 retractall(next_auto_y(_,_)),
1643 assertz(next_auto_x(0)),
1644 assertz(next_auto_y(0,0)).
1645
1646 get_x_auto_limit(Limit) :- visb_empty_svg_box_height_width(_H,W,_ViewBox),!,
1647 Limit = W. %TODO: inspect viewBox
1648 get_x_auto_limit(400).
1649
1650 compute_auto_attribute(id,_,_,GenID) :- !, gensym(svg_id,GenID).
1651 % Note: x/cx is computed before y/cy (attributes are sorted), so that y/cy uses the row chosen here
1652 compute_auto_attribute(Attr,AllAttrs,SVG_Class,Val) :-
1653 auto_compute_x_coordinate(Attr,Kind),!,
1654 (get_width(SVG_Class,AllAttrs,Width) -> true ; Width=10),
1655 (get_height(SVG_Class,AllAttrs,Height) -> true ; Height=10),
1656 Padding = 2, % TODO: make customisable
1657 get_x_auto_limit(Lim),
1658 retract(next_auto_x(XV)),
1659 retract(next_auto_y(Y,RowHeight)),
1660 (XV > 0, XV+Width > Lim % object does not fit into the current row: start a new row
1661 -> X=0, NewY is Y+RowHeight, NewRowHeight is Height+Padding
1662 ; X=XV, NewY=Y, NewRowHeight is max(RowHeight,Height+Padding)),
1663 NewXV is X+Width+Padding,
1664 assertz(next_auto_x(NewXV)),
1665 assertz(next_auto_y(NewY,NewRowHeight)),
1666 (Kind=left -> Val=X ; Val is X + Width/2).
1667 compute_auto_attribute(Attr,AllAttrs,SVG_Class,Val) :- auto_compute_y_coordinate(Attr,Kind),
1668 next_auto_y(YV,_),
1669 (Kind = top -> Val = YV
1670 ; get_height(SVG_Class,AllAttrs,Height) -> Val is YV + Height/2
1671 ; Val is YV+5).
1672
1673 auto_compute_x_coordinate(x,left). % rect, ..
1674 auto_compute_x_coordinate(cx,center). % circle, ellipse
1675 auto_compute_y_coordinate(y,top). % rect, ..
1676 auto_compute_y_coordinate(cy,center). % circle, ellipse
1677
1678 get_width(rect,Attrs,Wid) :- get_number_attr(width,Attrs,Wid).
1679 get_width(circle,Attrs,Wid) :- get_number_attr(r,Attrs,Radius), Wid is 2*Radius.
1680 get_width(ellipse,Attrs,Wid) :- get_number_attr(rx,Attrs,Radius), Wid is 2*Radius.
1681 get_width(line,Attrs,Wid) :- get_number_attr(x1,Attrs,X1),
1682 get_number_attr(x2,Attrs,X2), Wid is abs(X2-X1).
1683
1684 get_height(rect,Attrs,Wid) :- get_number_attr(height,Attrs,Wid).
1685 get_height(circle,Attrs,Wid) :- get_number_attr(r,Attrs,Radius), Wid is 2*Radius.
1686 get_height(ellipse,Attrs,Wid) :- get_number_attr(ry,Attrs,Radius), Wid is 2*Radius.
1687 get_height(line,Attrs,Wid) :- get_number_attr(y1,Attrs,X1),
1688 get_number_attr(y2,Attrs,X2), Wid is abs(X2-X1).
1689
1690 % get the value of an attribute as a number; fails for values such as 50% or auto
1691 get_number_attr(Attr,Attrs,Nr) :- member(svg_attribute(Attr,Val),Attrs),
1692 (number(Val) -> Nr=Val
1693 ; atom(Val), atom_codes(Val,Codes), catch(number_codes(Nr,Codes),_,fail)).
1694
1695
1696 % register an SVG ID as child of a group
1697 assert_visb_svg_child(_ParentId,Pos,ChildID) :- visb_svg_child(ChildID,OldParent),!,
1698 ajoin(['SVG object already child of group ',OldParent,': '],Msg),
1699 add_warning(visb_visualiser,Msg,ChildID,Pos).
1700 assert_visb_svg_child(ParentId,Pos,ChildID) :- visb_svg_child(ParentId,ChildID),!, % TODO: full cycle detection
1701 ajoin(['SVG object already parent of group ',ParentId,' (cycle): '],Msg),
1702 add_warning(visb_visualiser,Msg,ChildID,Pos).
1703 assert_visb_svg_child(ParentId,_Pos,ChildID) :-
1704 assertz(visb_svg_child(ChildID,ParentId)),
1705 assertz(visb_svg_parent(ParentId,ChildID)).
1706
1707
1708 % we need to translate a title attribute to a separate title object and add it as a child
1709 % see also post_process_visb_item which dispatches title updates to the child object
1710 get_all_children(SAttrList,Children,Rest,DefName,Pos) :-
1711 select(svg_attribute(title,Title),SAttrList,SList2),!,
1712 add_virtual_title_object(Title,DefName,Pos,TitleID),
1713 Children=[TitleID|TChilds],
1714 get_children_attribute(SList2,TChilds,Rest,Pos).
1715 get_all_children(SAttrList,Children,Rest,_,Pos) :-
1716 % get the children explicitly defined by the user:
1717 get_children_attribute(SAttrList,Children,Rest,Pos).
1718
1719 add_virtual_title_object(Title,DefName,Pos,TitleID) :-
1720 gensym(visb_title,TitleID),
1721 assert_visb_svg_object(TitleID,'title',[svg_attribute(text,Title)],'',DefName,Pos),
1722 add_debug_message(visb_visualiser,'Adding virtual title child object: ',TitleID,Pos).
1723
1724 get_children_attribute(SAttrList,Children,Rest,Pos) :-
1725 select(svg_attribute(children,C),SAttrList,R),!,
1726 (is_list(C) -> Children=C
1727 ; add_warning(visb_visualiser,'Children attribute should be a list (of SVG ids): ',C,Pos),
1728 Children=[]),
1729 Rest=R.
1730 get_children_attribute(SAttrList,[],SAttrList,_).
1731
1732
1733 svg_shape_can_have_children(defs).
1734 svg_shape_can_have_children(foreignObject).
1735 svg_shape_can_have_children(g).
1736 svg_shape_can_have_children(pattern).
1737 svg_shape_can_have_children(symbol).
1738 svg_shape_can_have_children(X) :- is_html_tag(X).
1739
1740
1741 % check whether svg_class value seems valid
1742 check_svg_shape_class(ID,Shape,Pos) :-
1743 (is_svg_shape_class(Shape) -> true
1744 ; is_html_tag(Shape) ->
1745 (visb_svg_child(ID,ParentId),
1746 visb_svg_object(ParentId,ParClass,_,_,_),
1747 (is_html_tag(ParClass) -> true ; ParClass=foreignObject)
1748 -> add_debug_message(visb_visualiser,'HTML tag used as svg_class in foreignObject child: ',Shape,Pos)
1749 ; ajoin(['SVG object ', ID, ' has HTML tag as svg_class (and should probably be a child of a foreignObject)'],Msg),
1750 add_visb_lint_message(Msg,Shape,Pos) % probably should be child of foreignObject
1751 )
1752 ; dotshape2svg_class(Shape,Class)
1753 -> ajoin(['SVG object ', ID, ' has unknown svg_class (did you mean ',Class,' ?): '],Msg),
1754 add_warning(visb_visualiser,Msg,Shape,Pos)
1755 ; get_all_svg_classes(Classes),
1756 get_possible_fuzzy_matches_and_completions_msg(Shape,Classes,FMsg)
1757 -> ajoin(['SVG object ', ID, ' has unknown svg_class (did you mean ',FMsg,' ?): '],Msg),
1758 add_warning(visb_visualiser,Msg,Shape,Pos)
1759 ; ajoin(['SVG object ', ID, ' has unknown svg_class'],Msg),
1760 add_visb_lint_message(Msg,Shape,Pos)
1761 ).
1762
1763 % get SVG attribute for a JSON svg_object:
1764 get_svg_attr(ID,SVG_Class,File,'='(Attr,AttrVal,Pos),svg_attribute(Attr,Val)) :- !,
1765 construct_prob_pos_term(Pos,File,PosTerm),
1766 get_svg_static_attribute_value(Attr,ID,SVG_Class,PosTerm,AttrVal,Val),
1767 check_attribute_name_is_supported(SVG_Class,Attr,PosTerm).
1768 get_svg_attr(_,_,File,Json,_) :-
1769 get_pos_from_list([Json],File,Position),
1770 add_error(visb_visualiser,'Illegal SVG object attribute',Json,Position),fail.
1771
1772 get_svg_static_attribute_value(Attr,ID,SVG_Class,Pos,AttrVal,Nr) :-
1773 check_is_number_attribute(Attr,SVG_Class,Pos),
1774 \+ is_special_svg_number_form(AttrVal),
1775 !,
1776 (get_number_value(AttrVal,Nr,Attr,Pos) -> true
1777 ; ajoin(['Illegal number value for attribute ',Attr, ' of svg_object ',ID,':'],Msg),
1778 add_error(visb_visualiser,Msg,AttrVal,Pos), Nr=0).
1779 get_svg_static_attribute_value(_,_,_,_,string(Val),Res) :- !, Res=Val.
1780 % for children we get something like array([string(button1_1),string(button1_2)])
1781 get_svg_static_attribute_value(Attr,ID,SVG_Class,Pos,array(List),ResList) :- !,
1782 maplist(get_svg_static_attribute_value(Attr,ID,SVG_Class,Pos),List,ResList).
1783 get_svg_static_attribute_value(Attr,ID,_,Pos,Val,Val) :-
1784 ajoin(['Illegal value for attribute ',Attr, ' of svg_object ',ID,':'],Msg),
1785 add_warning(visb_visualiser,Msg,Val,Pos).
1786
1787
1788 % detect special SVG number forms, like 50%
1789 is_special_svg_number_form(string(Atom)) :-
1790 atom_codes(Atom,Codes),
1791 special_svg_number(Codes,[]).
1792
1793
1794 :- assert_must_succeed(visb_visualiser:special_svg_number("10%",[])).
1795 :- assert_must_succeed(visb_visualiser:special_svg_number("10 %",[])).
1796 :- assert_must_succeed(visb_visualiser:special_svg_number(" 99em ",[])).
1797 :- assert_must_succeed(visb_visualiser:special_svg_number("1.0em",[])).
1798 :- assert_must_fail(visb_visualiser:special_svg_number("10",[])).
1799 :- assert_must_fail(visb_visualiser:special_svg_number("10+nrcols+%0",[])).
1800 special_svg_number --> " ",!, special_svg_number.
1801 special_svg_number --> [X], {digit(X)},!, special_svg_number2.
1802 special_svg_number --> "auto".
1803 special_svg_number2 --> [X], {digit(X)},!, special_svg_number2.
1804 special_svg_number2 --> ".",!, special_svg_number2. % TODO: only allow one dot; + accept e notation?
1805 special_svg_number2 --> optws,!, svg_unit,!, optws.
1806
1807 % using info from https://oreillymedia.github.io/Using_SVG/guide/units.html
1808 svg_unit --> "%".
1809 svg_unit --> "ch".
1810 svg_unit --> "cm".
1811 svg_unit --> "em".
1812 svg_unit --> "ex".
1813 svg_unit --> "in".
1814 svg_unit --> "mm".
1815 svg_unit --> "pc".
1816 svg_unit --> "pt".
1817 svg_unit --> "px".
1818 svg_unit --> "deg". % angle units
1819 svg_unit --> "grad".
1820 svg_unit --> "rad".
1821 svg_unit --> "turn".
1822 svg_unit --> "rem". % root em
1823 svg_unit --> "vh". % viewport height unit (1%)
1824 svg_unit --> "vw". % viewport width unit (1%)
1825 svg_unit --> "vmin". % min ov vh, vw
1826 svg_unit --> "vmax". % max ov vh, vw
1827
1828
1829 optws --> " ",!,optws.
1830 optws --> [].
1831
1832 digit(X) :- X >= 48, X =< 57.
1833
1834 is_svg_number_attribute(Attr) :- is_svg_number_attribute(Attr,_).
1835
1836
1837 % some checks to see whether the attribute is supported by the given SVG class
1838
1839 check_attribute_is_supported(SVG_Class,DefPos,svg_attribute(Name,_V)) :- !,
1840 (nonvar(SVG_Class), check_is_number_attribute(Name,SVG_Class,DefPos) -> true
1841 % TODO: check color and other attributes, see also check_attribute_type
1842 ; check_attribute_name_is_supported(SVG_Class,Name,DefPos)).
1843 check_attribute_is_supported(S,DefPos,F) :-
1844 add_internal_error('Illegal call:',check_attribute_is_supported(S,DefPos,F)).
1845
1846 % if these special attributes occur here, something went wrong, e.g.,
1847 % when separating static/dynamic parts
1848 check_unsupported_special_visb_attribute(visb_objects,_,_) :- !,fail. % here we can process everything
1849 check_unsupported_special_visb_attribute(SpecialClass,DefPos,svg_attribute(Name,_)) :-
1850 special_visb_attribute_not_allowed_in_dynamic_objects(Name,SpecialClass,Kind),
1851 ajoin(['The VisB special attribute ',Name,' cannot be used here (',SpecialClass,' use separate ',Kind,' definition): '],Msg),
1852 add_warning(visb_visualiser,Msg,Name,DefPos).
1853
1854 special_visb_attribute_not_allowed_in_dynamic_objects(hover,SC,'VISB_SVG_HOVERS') :- SC \= visb_hovers.
1855 special_visb_attribute_not_allowed_in_dynamic_objects(hovers,SC,'VISB_SVG_HOVERS') :- SC \= visb_hovers.
1856 special_visb_attribute_not_allowed_in_dynamic_objects(event,SC,'VISB_SVG_EVENTS') :- SC \= visb_events.
1857 special_visb_attribute_not_allowed_in_dynamic_objects(events,SC,'VISB_SVG_EVENTS') :- SC \= visb_events.
1858 special_visb_attribute_not_allowed_in_dynamic_objects(predicate,SC,'VISB_SVG_EVENTS') :- SC \= visb_events.
1859 special_visb_attribute_not_allowed_in_dynamic_objects(predicates,SC,'VISB_SVG_EVENTS') :- SC \= visb_events.
1860 special_visb_attribute_not_allowed_in_dynamic_objects(preds,SC,'VISB_SVG_EVENTS') :- SC \= visb_events.
1861 special_visb_attribute_not_allowed_in_dynamic_objects(execution_kind,SC,'VISB_SVG_EVENTS') :- SC \= visb_events.
1862
1863
1864 check_attribute_name_is_supported(SVG_Class,Name,DefPos) :-
1865 nonvar(SVG_Class),
1866 is_html_tag(SVG_Class),
1867 \+ is_svg_shape_class(SVG_Class), % script and title can be both SVG and HTML
1868 !,
1869 (is_html_attribute(Name)
1870 -> true % TODO: we could check whether attribute appropriate for Tag
1871 ; is_virtual_svg_attribute(Name) -> true % Virtual VisB attribute like children, text, ...
1872 ; ajoin(['Unknown HTML attribute used inside HTML tag ',SVG_Class],Msg),
1873 add_visb_lint_message(Msg,Name,DefPos)
1874 ).
1875 check_attribute_name_is_supported(_SVG_Class,Name,DefPos) :-
1876 check_attribute_name_is_supported(Name,DefPos).
1877
1878 check_attribute_name_is_supported(Name,DefPos) :-
1879 \+ is_svg_attribute(Name),
1880 !,
1881 (fix_svg_attribute(Name,GraphVizTranslName)
1882 -> ajoin(['Unknown SVG attribute (maybe you want to use ',GraphVizTranslName,' ?): '],Msg),
1883 add_warning(visb_visualiser,Msg,Name,DefPos)
1884 ; get_all_svg_attributes(Attrs),
1885 (get_possible_fuzzy_matches_and_completions_msg(Name,Attrs,FMsg)
1886 -> ajoin(['Unknown SVG attribute (did you mean ',FMsg,' ?): '],Msg),
1887 add_warning(visb_visualiser,Msg,Name,DefPos) % create warning, as it is likely we have made an error
1888 ; is_dot_attribute(Name)
1889 -> add_warning(visb_visualiser,'This Dot/Graphviz attribute is not a valid SVG attribute: ',Name,DefPos)
1890 ; get_preference(visb_strict_checking,false)
1891 -> add_visb_lint_message('Unknown SVG attribute',Name,DefPos)
1892 ; add_warning(visb_visualiser,'Unknown SVG attribute (set VISB_LINT to FALSE to avoid warning): ',Name,DefPos)
1893 )
1894 ).
1895 check_attribute_name_is_supported(_,_).
1896
1897 % add message or warning, depending on VISB_LINT setting
1898 add_visb_lint_message(Msg,Obj,Pos) :- get_preference(visb_strict_checking,false), !,
1899 ajoin([Msg,': '],Msg2),
1900 add_message(visb_visualiser,Msg2,Obj,Pos).
1901 add_visb_lint_message(Msg,Obj,Pos) :-
1902 ajoin([Msg,' (set VISB_LINT to FALSE to avoid warning): '],Msg2),
1903 add_warning(visb_visualiser,Msg2,Obj,Pos).
1904
1905
1906 % succeed if attribute is a number attribute and perform a check the attribute is supported by the class
1907 check_is_number_attribute(Attr,Class,Pos) :-
1908 is_svg_number_attribute(Attr,ClassList),
1909 (nonvar(Class), nonmember(Class,ClassList)
1910 -> (equivalent_attribute(Attr,List2,NewAttr), member(Class,List2)
1911 -> ajoin(['The number attribute ',Attr,' is not supported for SVG class ',Class,', use: '],Msg),
1912 add_warning(visb_visualiser,Msg,NewAttr,Pos)
1913 ; ajoin(['The number attribute ',Attr,' is not supported for this SVG class: '],Msg),
1914 add_warning(visb_visualiser,Msg,Class,Pos)
1915 )
1916 ; true
1917 ).
1918
1919 % optionally rewrite record field to alternative spelling
1920 opt_rewrite_field_name(Name,Res) :-
1921 (alternative_spelling(Name,Alt) -> Res=Alt ; Res=Name).
1922
1923 % these alternatives are useful e.g. in TLA+ without backquote:
1924 alternative_spelling(colour,'color').
1925 alternative_spelling(fill_opacity,'fill-opacity').
1926 alternative_spelling(fill_rule,'fill-rule').
1927 alternative_spelling(font_family,'font-family').
1928 alternative_spelling(font_size,'font-size').
1929 alternative_spelling(font_style,'font-style').
1930 alternative_spelling(font_variant,'font-variant').
1931 alternative_spelling(font_weight,'font-weight').
1932 alternative_spelling(marker_end,'marker-end').
1933 alternative_spelling(marker_start,'marker-start').
1934 alternative_spelling(stroke_opacity,'stroke-opacity').
1935 alternative_spelling(stroke_dasharray,'stroke-dasharray').
1936 alternative_spelling(stroke_linecap,'stroke-linecap').
1937 alternative_spelling(stroke_linejoin,'stroke-linejoin').
1938 alternative_spelling(stroke_width,'stroke-width').
1939
1940
1941 % used to suggest fixing unsupported attributes in SVG objects:
1942 equivalent_attribute(cx,[rect],x).
1943 equivalent_attribute(cy,[rect],y).
1944 equivalent_attribute(x,[circle,ellipse],cx).
1945 equivalent_attribute(x,[line],x1).
1946 equivalent_attribute(y,[circle,ellipse],cy).
1947 equivalent_attribute(y,[line],y1).
1948 equivalent_attribute(r,[rect],rx). % ry also exists
1949 equivalent_attribute(rx,[circle],r).
1950 equivalent_attribute(width,[circle],r).
1951 equivalent_attribute(width,[ellipse],rx).
1952 equivalent_attribute(height,[ellipse],ry).
1953
1954
1955 % ----------------
1956
1957 % parse and load an individual JSON VisB item, e.g, :
1958 % {
1959 % "id":"train_info_text",
1960 % "attr":"x",
1961 % "value":"real(train_rear_end)*100.0/real(TrackElementNumber+1)",
1962 % "comment":"move info field above train"
1963 % },
1964 process_visb_json_item(File,Json) :-
1965 process_repeat(0,Json,File,add_visb_json_item).
1966
1967 add_visb_json_item(File,json(List)) :-
1968 get_attr_true(ignore,List,File), % ignore this item
1969 !.
1970 add_visb_json_item(File,json(List)) :-
1971 del_attr_with_pos(id,List,string(ID),L1,File,PosStartOfItem),
1972 !,
1973 process_visb_json_item_id(File,L1,ID,PosStartOfItem).
1974 add_visb_json_item(File,Json) :-
1975 !,
1976 get_pos_from_list(Json,File,Pos),
1977 add_error(visb_visualiser,'VisB Item has no id attribute:',Json,Pos).
1978
1979 process_visb_json_item_id(File,L1,ID,PosStartOfItem) :-
1980 del_attr_with_pos(attr,L1,string(Attr),L2,File,AttrPos), % VisB has attr and value infos
1981 force_del_attr_with_pos(value,L2,string(Formula),L3,File,PosFormula),
1982 !,
1983 (del_attr(comment,L3,string(Desc),L4) -> true ; Desc = '',L4=L3),
1984 debug_format(19,' Processing id:~w attr:~w : value:~w desc:~w~n',[ID,Attr,Formula,Desc]),
1985 actually_add_visb_json_item(ID,Attr,AttrPos,Formula,Desc,L4,PosStartOfItem,PosFormula,File).
1986 process_visb_json_item_id(File,L1,ID,PosStartOfItem) :-
1987 get_attr_with_pos(SomeSVGAttr,L1,_V,File,_),
1988 is_svg_attribute(SomeSVGAttr),
1989 debug_format(19,'Detected new style VisB JSON declaration with id:~w and SVG attr:~w~n',[ID,SomeSVGAttr]),
1990 !,
1991 % object is in new format with multiple attributes "x":"0" rather than "attr":"x", "value":"0"
1992 (del_attr(comment,L1,string(Desc),L2) -> true ; Desc = '',L2=L1),
1993 (non_det_del_attr_with_pos(SVGATTR,L2,string(Formula),L3,File,PosFormula),
1994 is_visb_item_svg_attribute(PosFormula,SVGATTR,Formula),
1995 debug_format(19,' -> Processing new style id:~w attr:~w : value:~w desc:~w~n',[ID,SVGATTR,Formula,Desc]),
1996 actually_add_visb_json_item(ID,SVGATTR,PosFormula,Formula,Desc,L3,PosStartOfItem,PosFormula,File),
1997 fail
1998 ;
1999 true).
2000 process_visb_json_item_id(_File,_JsonList,ID,PosStartOfItem) :-
2001 !,
2002 add_error(visb_visualiser,'Illegal VisB Item without attr and value fields:',ID,PosStartOfItem).
2003
2004 is_visb_item_svg_attribute(Pos,Attr,Val) :-
2005 Attr \= override, % so we ignore a possible override attribute
2006 (is_svg_attribute(Attr) -> true
2007 ; add_warning(visb_visualiser,'Ignoring unknown attribute: ',Attr=Val,Pos),
2008 fail
2009 ).
2010
2011
2012 actually_add_visb_json_item(ID,Attr,AttrPos,Formula,Desc,JsonList,PosStartOfItem,PosFormula,File) :-
2013 set_error_context(visb_error_context(item,ID,Attr,PosFormula)),
2014 check_attribute_name_is_supported(Attr,AttrPos),
2015 atom_codes(Formula,FormulaC),
2016 (parse_expr_for_visb(FormulaC,JsonList,PosFormula,TypedExpr)
2017 % TO DO: if optional attribute present: avoid generating errors in b_parse_machine_expression_from_codes
2018 -> get_texpr_type(TypedExpr,BType),
2019 check_attribute_type(BType,Attr,ID,PosFormula),
2020 assert_visb_item(ID,Attr,TypedExpr,Desc,PosStartOfItem,JsonList,File)
2021 ; is_optional_json_item(JsonList,File,Pos)
2022 -> formatsilent('Ignoring optional VisB item for ~w (lines ~w) due to error in B formula~n',[ID,Pos])
2023 ; ajoin(['Cannot parse or typecheck VisB formula for ',ID,' and attribute ',Attr,':'],Msg),
2024 add_error(visb_visualiser,Msg,Formula,PosFormula)
2025 ), clear_error_context.
2026
2027
2028 % assert a VISB item (aka VISB_SVG_UPDATE)
2029 assert_visb_item(ID,Attr,_TypedExpr,_Desc,PosStartOfItem,_,_) :-
2030 visb_item(ID,Attr,_,_,_,Pos2,Meta2),
2031 !,
2032 get_file_name_msg(PosStartOfItem,From1,File1),
2033 (member(override,Meta2)
2034 -> ajoin(['Overriding VisB item',From1,File1,' for same SVG ID ',ID,' and attribute '],Msg),
2035 add_debug_message(visb_visualiser,Msg,Attr,Pos2)
2036 ; ajoin(['Overriding VisB item',From1,File1,' for same SVG ID ',ID,
2037 '. Add an \"override\" attribute to remove this warning. Overriden attribute '],Msg),
2038 add_warning(visb_visualiser,Msg,Attr,Pos2),
2039 % error_context already includes attribute and ID
2040 add_message(visb_visualiser,'Overriding this stored formula for ',ID,PosStartOfItem) % provide detailed info
2041 ).
2042 assert_visb_item(ID,Attr,_TypedExpr,_Desc,PosStartOfItem,_JsonList,_File) :-
2043 illegal_attribute_for_visb_item(ID,Attr),!,
2044 add_warning(visb_visualiser,'This attribute cannot be modified in a VisB item: ',Attr,PosStartOfItem).
2045 assert_visb_item(ID,Attr,TypedExpr,Desc,PosStartOfItem,JsonList,File) :-
2046 (get_attr_true(override,JsonList,File) -> Meta = [override] ; Meta=[]),
2047 % determine_type_of_visb_formula(TypedExpr,_,Class) now does take definitions into account; TODO: save info
2048 find_identifier_uses(TypedExpr,[],UsedIds),
2049 assertz(visb_item(ID,Attr,TypedExpr,UsedIds,Desc,PosStartOfItem,Meta)).
2050
2051 illegal_attribute_for_visb_item(_,children).
2052 illegal_attribute_for_visb_item(_,group_id).
2053 illegal_attribute_for_visb_item(_,id).
2054 illegal_attribute_for_visb_item(_,svg_class).
2055
2056
2057 get_file_name_msg(Pos1,' from ',File1) :- extract_tail_file_name(Pos1,File1),!.
2058 get_file_name_msg(_,'',''). % no file info
2059
2060 % ----------------
2061 % FOR-LOOP / REPEAT processing
2062
2063 %process_repeat(RepCounter, Json, FinalCall to be executed repeatedly for each instance with File and Json, File)
2064 % RepCounter tells us which of %0, %1, ... should be replaced next
2065
2066 process_repeat(RepCount,json(JsonList),File,FinalCall) :-
2067 non_det_del_attr_with_pos(FOR_REP,JsonList,Value,RestJsonList,File,ForRepPos),
2068 % find first for or repeat and process it
2069 (FOR_REP=for ; FOR_REP=repeat),
2070 !,
2071 process_first_repeat(FOR_REP,Value,ForRepPos,RepCount,json(RestJsonList),File,FinalCall).
2072 process_repeat(_RepCount,Json,File,FinalCall) :-
2073 % we have processed all for/repeat loops: now perform the final call on the transformed codes
2074 call(FinalCall,File,Json).
2075
2076 process_first_repeat(for,json(ForList),ForPos,RepCount,JsonData,File,FinalCall) :-
2077 !, % we have a for loop like "for": {"from":1, "to":4}
2078 force_get_attr_nr(from,ForList,From,File),
2079 force_get_attr_nr(to,ForList,To,File),
2080 (get_attr_with_pos(step,ForList,StepAttrVal,File,StepPos),
2081 get_number_value(StepAttrVal,Step,step,StepPos)
2082 -> true % there is an explicit step attribute
2083 ; Step=1),
2084 debug_format(19,' -> Iterating %~w from ~w to ~w with step ~w~n',[RepCount,From,To,Step]),
2085 R1 is RepCount+1,
2086 number_codes(RepCount,Pat),
2087 check_between(From,To,Step,ForPos), % check whether step value makes sense
2088 ( between(From,To,Step,IterElem),
2089 number_codes(IterElem,IterElemC), % we will replace the text %Pat by the text of the number IterElem
2090 replace_in_json(Pat,IterElemC,JsonData,ReplacedJsonData), % replace within other for/repeat loops, but also other attributes
2091 process_repeat(R1,ReplacedJsonData,File,FinalCall), % now process next loop or finish
2092 fail
2093 ; true).
2094 process_first_repeat(repeat,array(RepList),RepPos,RepCount,JsonData,File,FinalCall) :-
2095 !, % we have a repetition like "repeat": ["tr1","tr2"] or "repeat": [ ["1","2"] , ...]
2096 (RepList=[array(L1)|_], length(L1,Len)
2097 -> NewRepCount is RepCount+Len, % we have a multi-repeat with list of values to be replaced
2098 LastRepCount is NewRepCount-1,
2099 debug_format(19,' -> Iterating repeat (%~w,...,%~w) over ~w~n',[RepCount,LastRepCount,RepList]),
2100 check_all_same_length_json(RepList,Len,RepPos)
2101 ; NewRepCount is RepCount+1, % next replacement starts at $(RepCount+1)
2102 debug_format(19,' -> Iterating repeat (%~w) over ~w~n',[RepCount,RepList])
2103 ),
2104 ( member(IterElem,RepList),
2105 multi_replace_in_json(IterElem,RepCount,JsonData,ReplacedJsonData), % replace within other for/repeat loops, but also other attributes
2106 process_repeat(NewRepCount,ReplacedJsonData,File,FinalCall), % now process next loop or finish
2107 fail
2108 ; true).
2109
2110 check_between(_,_,Step,ForPos) :- Step =< 0, !,
2111 add_error(visb_visualiser,'The step of a for loop must be positive:',Step,ForPos),fail.
2112 check_between(From,To,Step,ForPos) :- Iters is (To-From)/Step,
2113 Iters > 100000,!,
2114 add_error(visb_visualiser,'Very large for loop:',Iters,ForPos),fail.
2115 check_between(_,_,_,_).
2116
2117
2118 % ----------------
2119
2120 % parse and load VisB events
2121 % A VisB Event looks like:
2122 % {
2123 % "id": "button",
2124 % "event": "toggle_button",
2125 % "execution_kind": "random", (optional: default, first, random, heuristic, explore_open or min_out_degree)
2126 % "hovers": [{ "attr":"stroke-width", "enter":"6", "leave":"1"},
2127 % { "attr":"opacity", "enter":"0.8", "leave":"1.0"}]
2128 % }
2129 process_json_event(File,Json) :-
2130 process_repeat(0,Json,File,add_visb_json_event).
2131
2132 add_visb_json_event(File,json(List)) :- get_attr_true(ignore,List,File), !. % ignore this item
2133 add_visb_json_event(File,json(List)) :-
2134 get_pos_from_list(List,File,Pos),
2135 force_del_attr(id,List,string(ID),L0,File), % for items it could make sense to not specify an id
2136 (del_attr_with_pos(event,L0,EvTerm,L1,File,EvPos)
2137 -> (check_json_string(EvTerm,event,EvPos,Event) -> true ; Event='') % TODO: accept multiple events
2138 ; Event='', L1=L0),
2139 (del_attr_with_pos(predicates,L1,array(Preds),L2,File,PredPos) -> true
2140 ; del_attr_with_pos(preds,L1,array(Preds),L2,File,PredPos) -> true
2141 ; Preds=[], L2=L1, PredPos=unknown),
2142 (del_attr(execution_kind,L2,EKindTerm,L2b)
2143 -> (check_json_string(EKindTerm,execution_kind,Pos,EKind)
2144 -> check_execution_kind(EKind,ID,Pos,ExecKind)
2145 ; default_execution_kind(ExecKind))
2146 ; default_execution_kind(ExecKind), L2b=L2),
2147 (del_attr(hovers,L2b,array(Hovers),L3) -> true ; Hovers=[],L3=L2b),
2148 (del_attr(items,L3,array(EI),L4)
2149 -> (empty_b_event(Event)
2150 -> EnableItems=[],
2151 add_warning(visb_visualiser,'Ignoring enable items; you need to provide an event name:',ID,Pos)
2152 ; EnableItems=EI)
2153 ; EnableItems=[],L4=L3),
2154 debug_format(19,' Processing id:~w event:~w preds:~w kind:~w enable:~w hovers:~w~n',[ID,Event,Preds,ExecKind,EnableItems,Hovers]),
2155 !,
2156 actually_add_visb_json_event(ID,Event,Preds,ExecKind,Hovers,EnableItems,L4,File,Pos,PredPos).
2157 add_visb_json_event(File,Json) :-
2158 !,
2159 get_pos_from_list(Json,File,Pos),
2160 add_error(visb_visualiser,'Illegal VisB Event:',Json,Pos).
2161
2162 actually_add_visb_json_event(ID,Event,JsonPreds,ExecKind,JsonHovers,JsonEnableItems,JsonList,File,Pos,PredPos) :-
2163 check_additional_args(JsonList,File),
2164 maplist(process_json_pred,JsonPreds,Preds),
2165 maplist(process_json_enabling_item(ID,Event,File),JsonEnableItems,EnableItems),
2166 maplist(process_json_hover(ID,File),JsonHovers,Hovers),
2167 add_visb_event(ID,Event,Preds,ExecKind,Hovers,EnableItems,File,Pos,PredPos,JsonList).
2168
2169 % the execution kind determines which transition is executed when a VisB event is clicked
2170 % default means that the preference visb_default_execution_kind is used (looked up when the event is executed)
2171 execution_kind(default).
2172 execution_kind(first).
2173 execution_kind(random).
2174 execution_kind(heuristic).
2175 execution_kind(explore_open).
2176 execution_kind(min_out_degree).
2177 default_execution_kind(default).
2178
2179 check_execution_kind(Kind,_,_,Res) :- execution_kind(Kind), !, Res=Kind.
2180 check_execution_kind(Kind,ID,Pos,Res) :-
2181 default_execution_kind(Res),
2182 ajoin(['Unknown execution_kind ',Kind,' (must be default, first, random, heuristic, explore_open or min_out_degree) using ',Res,' for VisB event of SVG ID: '],Msg),
2183 add_warning(visb_visualiser,Msg,ID,Pos).
2184
2185 % get the execution kind to be used when executing a VisB event
2186 get_actual_execution_kind(default,Kind) :- !, get_preference(visb_default_execution_kind,Kind).
2187 get_actual_execution_kind(Kind,Kind).
2188
2189
2190 add_visb_event(ID,Event,Preds,ExecKind,Hovers,EnableItems,File,Pos,PredPos,JsonList) :-
2191 (retract(visb_event(ID,OldEvent,OldPreds,OldExecKind,OldTypedPred,OldFile,OldPos))
2192 -> (get_attr_true(override,JsonList,File)
2193 -> ajoin(['Overriding VisB event from file ',OldFile,' for ID: '],Msg),
2194 add_debug_message(visb_visualiser,Msg,ID,Pos),
2195 retractall(visb_hover(ID,_,_,_,_,_))
2196 ; (OldFile=File
2197 -> ajoin(['No override attribute: adding VisB event ',Event,
2198 ' (first event ',OldEvent,') for ID: '],Msg)
2199 ; ajoin(['No override attribute: adding VisB event ',Event,
2200 ' (first event ',OldEvent,' in file ',OldFile,') for ID: '],Msg)
2201 ),
2202 add_debug_message(visb_visualiser,Msg,ID,Pos),
2203 assertz(auxiliary_visb_event(ID,OldEvent,OldPreds,OldExecKind,OldTypedPred,OldPos))
2204 ),
2205 assert_visb_event(ID,Event,Preds,ExecKind,Hovers,EnableItems,File,Pos,PredPos)
2206 % ProB2-UI cannot currently support multiple events associated with the same id
2207 % TODO: merge visb_events if we have no override attribute
2208 ; (xtl_mode ; b_is_operation_name_or_external_subst(Event)) ->
2209 assert_visb_event(ID,Event,Preds,ExecKind,Hovers,EnableItems,File,Pos,PredPos)
2210 ; (empty_b_event(Event) ; \+ b_or_z_mode)
2211 -> % for empty event we just want hovers
2212 (Preds = [] -> true
2213 ; add_warning(visb_visualiser,'Ignoring preds for VisB event for SVG ID: ',ID,Pos)
2214 ),
2215 assert_visb_event(ID,Event,[],ExecKind,Hovers,EnableItems,File,Pos,PredPos)
2216 ; is_optional_json_item(JsonList,File,Pos) ->
2217 formatsilent('Ignoring optional VisB event for ~w (lines ~w) due to unknown B operation ~w~n',[ID,Pos,Event])
2218 ; detect_op_call_with_paras(Event,OpName) -> % check if we have a name with parameters inside
2219 add_warning(visb_visualiser,'Ignoring parameters provided in event; use the "predicate" attribute to specify parameters: ',Event,Pos),
2220 assert_visb_event(ID,OpName,Preds,ExecKind,Hovers,EnableItems,File,Pos,PredPos)
2221 ; atom(Event), atom_prefix('{',Event) ->
2222 ajoin(['Unknown B operation ', Event, ' as VisB event for SVG ID (be sure to use the "events" attribute for multiple events): '],Msg),
2223 add_warning(visb_visualiser,Msg,ID,Pos)
2224 ; ajoin(['Unknown B operation ', Event, ' as VisB event for SVG ID: '],Msg),
2225 add_warning(visb_visualiser,Msg,ID,Pos)
2226 ).
2227
2228 b_is_operation_name_or_external_subst(OpName) :- b_is_operation_name(OpName).
2229 b_is_operation_name_or_external_subst(Special) :- special_operation(Special).
2230
2231 % maybe we should provide those via the external substitution interface:
2232 % these are all schedulers which choose among existing enabled operations in some manner
2233 special_operation('MCTS_AUTO_PLAY').
2234 special_operation('RANDOM_ANIMATE').
2235 special_operation('RANDOM_ANIMATE_UNTIL_LTL').
2236 special_operation(F) :- external_fun_as_special_operation(F).
2237 external_fun_as_special_operation('STORE_VALUE').
2238 external_fun_as_special_operation('SET_PREF').
2239 % maybe other special names like random_animate with nr of steps, LTL until, ...
2240 special_operation_enabled('MCTS_AUTO_PLAY',_,_,_) :- mcts_auto_play_available.
2241 special_operation_enabled('RANDOM_ANIMATE',_,_,_). % TODO: check if a transition exists
2242 special_operation_enabled('RANDOM_ANIMATE_UNTIL_LTL',_,_,_).
2243 special_operation_enabled(F,_,_,_) :- external_fun_as_special_operation(F).
2244
2245 % detect simple operation call with parameters
2246 detect_op_call_with_paras(Event,OpName) :- atom(Event),
2247 atom_codes(Event,Codes), parse_op_call_name(OpC,Codes,_),!,
2248 atom_codes(OpName,OpC),
2249 b_is_operation_name_or_external_subst(OpName).
2250
2251 parse_op_call_name([X|T]) --> alpha(X), parse_op_call_name2(T).
2252 parse_op_call_name2([]) --> "(".
2253 parse_op_call_name2([H|T]) --> alphadigit(H), parse_op_call_name2(T).
2254
2255 alpha(X) --> [X],({X>=97, X=<122} ; {X>=65, X=<90}).
2256 alphadigit(X) --> [X], ({X>=97,X=<122} ; {X>=65, X=<90} ; {X=95} ; {X>=48, X=<57}).
2257
2258 empty_b_event('').
2259
2260 assert_visb_event(ID,Event,Preds,ExecKind,Hovers,EnableItems,File,Pos,PredPos) :-
2261 construct_pre_post_predicate(ID,Event,Preds,TypedPred,PredPos),
2262 assertz(visb_event(ID,Event,Preds,ExecKind,TypedPred,File,Pos)),
2263 % process hovers
2264 (member(HoverElement,Hovers),
2265 (HoverElement=visb_hover(HoverID,Attr,EnterVal,ExitVal) -> true ; add_error(visb_visualiser,'Illegal hover term:',HoverElement),fail),
2266 assert_visb_hover(ID,HoverID,Attr,EnterVal,ExitVal,Pos),fail
2267 ; true),
2268 % now process any additional items with disabled and enabled values
2269 assert_visb_enabling_item_list(Event,TypedPred,EnableItems,File,Pos).
2270
2271 process_json_pred(string(P),R) :- !, R=P.
2272 process_json_pred(Json,_) :- !, add_error(visb_visualiser,'Illegal json term for predicate:',Json), fail.
2273
2274 process_json_hover(OriginID,File,json(Hover),visb_hover(ID,Attr,EnterVal,LeaveVal)) :-
2275 force_del_attr(attr,Hover,string(Attr),H2,File),
2276 force_del_attr_with_pos(enter,H2,EV,H3,File,EnterPos),
2277 force_del_attr_with_pos(leave,H3,LV,H4,File,ExitPos),
2278 (is_svg_number_attribute(Attr) % we evaluate number attributes
2279 -> get_number_value(EV,EnterVal,Attr,EnterPos),
2280 get_number_value(LV,LeaveVal,Attr,ExitPos)
2281 ; string(EnterVal)=EV, string(LeaveVal)=LV % return string as is; TODO: also evaluate other attributes
2282 ),
2283 (get_attr(id,H4,string(ID)) -> true ; ID=OriginID).
2284
2285
2286 assert_visb_hover(TriggerID,SVG_ID,Attr,EnterVal,ExitVal,Pos) :-
2287 assert(visb_hover(TriggerID,SVG_ID,Attr,EnterVal,ExitVal,Pos)),
2288 (visb_has_hovers(TriggerID) -> true ; assert(visb_has_hovers(TriggerID))),
2289 (visb_has_visibility_hover(SVG_ID) -> true
2290 ; Attr=visibility -> assert(visb_has_visibility_hover(SVG_ID)) % object SVG_ID can be made visible by hover
2291 ; true),
2292 debug_format(19,'Adding hover for ~w : ~w.~w -> ~w <- ~w~n',[TriggerID,SVG_ID,Attr,EnterVal,ExitVal]).
2293
2294
2295 % process items in event which get translated to enabling/disabling predicates
2296 % "items":[ {"attr":"stroke-width","enabled":"10", "disabled":"1"} ]
2297 process_json_enabling_item(ID,Event,File,json(JsonList),
2298 visb_enable_item(SvgID,Attr,EnabledValExpr,DisabledValExpr,PosAttr)) :-
2299 force_del_attr_with_pos(attr,JsonList,string(Attr),L2,File,PosAttr),
2300 force_del_attr_with_pos('enabled',L2,string(EnVal),L3,File,EPos),
2301 force_del_attr_with_pos('disabled',L3,string(DisVal),L4,File,DPos),
2302 (del_attr(id,L4,string(SvgID),L5) -> true ; SvgID=ID, L4=L5),
2303 atom_codes(EnVal,EC),
2304 parse_expr_for_visb(EC,L5,EPos,EnabledValExpr),
2305 atom_codes(DisVal,DC),
2306 parse_expr_for_visb(DC,L5,DPos,DisabledValExpr),
2307 (debug_mode(off) -> true
2308 ; translate_bexpression_with_limit(EnabledValExpr,30,EVS),
2309 translate_bexpression_with_limit(DisabledValExpr,30,DVS),
2310 formatsilent('Enabling item for event ~w and SVG ID ~w and attribute ~w : ~w <-> ~w~n',[Event,SvgID,Attr,EVS,DVS])
2311 ).
2312
2313 assert_visb_enabling_item_list(Event,TypedPred,EnableList,File,Pos) :-
2314 maplist(check_enabling_item(Event),EnableList),
2315 (EnableList \= []
2316 -> (debug_mode(off)
2317 -> true
2318 ; format('Associating enabling/disabling list with event ~w and predicate: ',[Event]), translate:print_bexpr(TypedPred),nl),
2319 assert(visb_event_enable_list(Event,TypedPred,EnableList,File,Pos))
2320 ; true).
2321
2322 check_enabling_item(Event,visb_enable_item(SvgID,Attr,_,_,PosAttr)) :-
2323 (visb_item(SvgID,Attr,_,_,_Desc,DuplicatePos,_)
2324 -> (extract_span_description(DuplicatePos,DuplPos) -> true; DuplPos=DuplicatePos),
2325 ajoin(['VisB conflict for SVG ID ',SvgID,' and attribute ',Attr,
2326 '. Conflict between VisB item (',DuplPos,') and VisB enable/disable entry for event: '],Msg),
2327 add_warning(visb_visualiser,Msg,Event,PosAttr)
2328 ; true).
2329
2330 valid_additional_attributes(comment).
2331 valid_additional_attributes(description).
2332 valid_additional_attributes(optional).
2333 valid_additional_attributes(override).
2334
2335 % check if there are additional unprocessed args and generate a warning
2336 check_additional_args(JsonList,File) :-
2337 get_attr_with_pos(Attr,JsonList,_,File,Pos),
2338 \+ valid_additional_attributes(Attr),
2339 add_warning(visb_visualiser,'Ignoring unknown JSON field: ',Attr,Pos),
2340 fail.
2341 check_additional_args(_,_).
2342
2343
2344 % construct a pre-post typed predicate for a VisB Event
2345 construct_pre_post_predicate(SvgID,OpName,Preds,TypedPred,Pos) :-
2346 set_error_context(visb_error_context(event,SvgID,OpName,Pos)),
2347 maplist(construct_pre_post_pred(OpName,Pos),Preds,TL),
2348 clear_error_context,
2349 conjunct_predicates(TL,TypedPred).
2350
2351
2352 construct_pre_post_pred(OpName,Pos,PredStr,TypedPred) :- empty_b_event(OpName),!,
2353 add_error(visb_visualiser,'Cannot parse VisB event predicate without event name:',PredStr,Pos),
2354 TypedPred = b(truth,pred,[]).
2355 construct_pre_post_pred(OpName,Pos,String,TypedExpr) :- special_operation(OpName),!,
2356 % we have a special operation; allow to provide an expression with options/parameters
2357 construct_pre_post_for_special(Pos,String,TypedExpr).
2358 construct_pre_post_pred(OpName,Pos,String,TypedPred) :-
2359 atom_codes(String,Codes), replace_special_patterns(Codes,RCodes,Pos), %format("Replaced : ~S~n",[RCodes]),
2360 get_visb_extra_scope([identifier(VisBExtraScope)]),
2361 visb_click_meta_b_type(MetaRecType),
2362 ExtraScope = [identifier([b(identifier('VISB_CLICK_META_INFOS'),MetaRecType,[visb_generated])|VisBExtraScope])],
2363 (b_parse_machine_operation_pre_post_predicate(RCodes,ExtraScope,TypedPred,OpName,gen_parse_errors_for(Pos))
2364 -> true
2365 ; add_error(visb_visualiser,'Error for VisB event predicate:',String,Pos),
2366 TypedPred = b(truth,pred,[])
2367 ).
2368
2369 construct_pre_post_for_special(Pos,Pred,TypedExpr) :- member(Pred,[btrue,bfalse]), !,
2370 add_warning(visb_visualiser,'Special operations require an expression specifying the parameter values, not a predicate: ',Pred,Pos),
2371 TypedExpr = b(integer(0),integer,[]).
2372 construct_pre_post_for_special(Pos,String,TypedExpr) :-
2373 atom_codes(String,Codes),
2374 GenParseErrors=gen_parse_errors_for(Pos),
2375 parse_expr(Codes,TypedExpr,GenParseErrors). % TODO: should we require a predicate instead, and provide arg names?
2376
2377 % replace special patterns by dummy values to avoid error messages in ProB2-UI
2378 replace_special_patterns([],[],_Pos) :- !.
2379 replace_special_patterns([37|T],Res,Pos) :- !, % percentage sign %
2380 replace_aux(T,Res,Pos).
2381 replace_special_patterns([H|T],[H|RT],Pos) :- !, replace_special_patterns(T,RT,Pos).
2382
2383 replace_aux(Input,Res,Pos) :-
2384 replace_pat(PAT,Replacement),
2385 append(PAT,T,Input),
2386 !,
2387 atom_codes(PatAtom,PAT),
2388 ajoin(['The %',PatAtom,' pattern is obsolete. Please use VISB_CLICK_META_INFOS\'',PatAtom,' instead.'],Msg),
2389 add_warning(visb_visualiser,Msg,'',Pos),
2390 append(Replacement,ResT,Res),
2391 replace_special_patterns(T,ResT,Pos).
2392 replace_aux(Input,[37|Res],Pos) :- !, replace_special_patterns(Input,Res,Pos).
2393
2394 replace_pat("shiftKey","VISB_CLICK_META_INFOS'shiftKey").
2395 replace_pat("metaKey","VISB_CLICK_META_INFOS'metaKey").
2396 replace_pat("pageX","VISB_CLICK_META_INFOS'pageX").
2397 replace_pat("pageY","VISB_CLICK_META_INFOS'pageY").
2398
2399
2400 % small utils:
2401 % ----------------
2402
2403 % a variation of between/3 with a step argument
2404 between(From,To,_,_) :- From > To, !,fail.
2405 between(From,_,_,From).
2406 between(From,To,Step,Elem) :- F1 is From+Step, between(F1,To,Step,Elem).
2407
2408
2409 parse_expr(ExprCodes,TypedExpr,_GenParseErrors) :-
2410 is_simple_classical_b_identifier_codes(ExprCodes),
2411 atom_codes(DefID,ExprCodes),
2412 visb_definition(DefID,Type,_DefFormula,Class,_VPos,_),
2413 !,
2414 TypedExpr = b(identifier(DefID),Type,[type_of_formula(Class)]).
2415 parse_expr(ExprCodes,TypedExpr,GenParseErrors) :-
2416 temporary_set_preference(allow_arith_operators_on_reals,true,CHNG),
2417 get_visb_extra_scope(ExtraScope),
2418 % formatsilent('Parsing: ~s (extra ids: ~w)~n',[ExprCodes,ExtraScope]), start_ms_timer(T1),
2419 call_cleanup(bmachine:b_parse_machine_expression_from_codes_with_prob_ids(ExprCodes,ExtraScope,TypedExpr,
2420 GenParseErrors),
2421 reset_temporary_preference(allow_arith_operators_on_reals,CHNG)).
2422 %stop_ms_walltimer_with_msg(T1,'parsing: ').
2423 % TODO: we could share a machine parameter M like in prob2_interface
2424 % so that b_type_expression_for_full_b_machine will load machine only once
2425 % cf b_type_open_predicate_for_full_b_machine
2426
2427 determine_type_of_visb_formula(b(_,_,[type_of_formula(Class)]),all,Res) :- !,
2428 Res = Class. % generated by VisB, TODO: store UsedTIds in type_of_formula(.)
2429 determine_type_of_visb_formula(TypedExpr,TIds,Class) :-
2430 determine_type_of_formula_with_visb_defs(TypedExpr,TIds,Class).
2431
2432 %check for used_ids inside TypedExpr an see what type of visb_definition are used
2433 determine_type_of_formula_with_visb_defs(TypedExpr,TIds,ResClass) :-
2434 determine_type_of_formula(TypedExpr,TIds,Class1), % compute class w/o knowledge of VisB definitions
2435 (class_more_general_than(Class2,Class1),
2436 required_by_visb_def(TIds,Class2) -> Class=Class2
2437 ; Class=Class1),
2438 (Class=requires_variables -> ResClass=Class
2439 ; expression_requires_state(TypedExpr) -> ResClass = requires_variables
2440 ; ResClass=Class).
2441
2442
2443 expression_requires_state(TypedExpr) :-
2444 (map_over_bexpr(sub_expression_requires_state,TypedExpr) -> true ; fail).
2445 % TODO: should we also check is_not_declarative/1 ? e.g., for RANDOM or CHANGED
2446 sub_expression_requires_state(external_pred_call(P,_)) :- external_function_requires_state(P).
2447 sub_expression_requires_state(external_function_call(P,_)) :- external_function_requires_state(P).
2448
2449
2450 class_more_general_than(requires_variables,requires_nothing).
2451 class_more_general_than(requires_variables,requires_constants).
2452 class_more_general_than(requires_constants,requires_nothing).
2453
2454 required_by_visb_def(TIds,Class) :-
2455 member(TID,TIds), get_texpr_id(TID,ID),visb_definition(ID,_,_,Class,_,_).
2456
2457
2458 get_visb_extra_scope([identifier(ExtraIDs)]) :-
2459 get_visb_extra_identifiers(ExtraIDs).
2460 get_visb_extra_identifiers(ExtraIDs) :-
2461 findall(b(identifier(ID),Type,[visb_generated]),visb_definition(ID,Type,_,_,_,_),ExtraIDs).
2462
2463
2464 force_get_attr_nr(Attr,List,Nr,File) :-
2465 force_del_attr_with_pos(Attr,List,AttrVal,_,File,Pos),!,
2466 get_number_value(AttrVal,Nr,Attr,Pos).
2467
2468 get_number_value(AttrVal,Nr,Attr,Pos) :-
2469 (AttrVal = number(Nr) -> true
2470 ; AttrVal = string(StrAttrVal),
2471 atom_codes(StrAttrVal,AttrValC),
2472 parse_expr(AttrValC,TypedExpr,gen_parse_errors_for(Pos)),
2473 determine_type_of_visb_formula(TypedExpr,UsedTIds,Class)
2474 % Class = requires_nothing, requires_constants, requires_variables
2475 ->
2476 (Class = requires_variables
2477 -> ajoin(['The JSON formula for the attribute"',Attr,
2478 '" must not depend on variables:'],Msg),
2479 add_error(visb_visualiser,Msg,StrAttrVal,Pos),fail
2480 ; Class = requires_constants,
2481 \+ is_concrete_constants_state_id(_)
2482 -> ajoin(['The JSON formula for the attribute"',Attr,
2483 '" depends on constants which have not been set up (via SETUP_CONSTANTS):'],Msg),
2484 add_error(visb_visualiser,Msg,StrAttrVal,Pos),fail
2485 ; get_texpr_type(TypedExpr,Type),
2486 is_number_type(Type)
2487 -> (eval_static_def(Class,'VisB attribute',Attr,TypedExpr,UsedTIds,ResVal,Pos)
2488 -> get_number_from_bvalue(ResVal,Nr)
2489 ; Class = requires_constants,
2490 multiple_concrete_constants_exist
2491 -> ajoin(['The JSON formula for the attribute"',Attr,
2492 '" depends on constants and multiple solutions for SETUP_CONSTANTS exist:'],Msg),
2493 add_warning(visb_visualiser,Msg,StrAttrVal,Pos),fail
2494 )
2495 ; get_texpr_type(TypedExpr,Type),
2496 % it could produce a string which is a number; we could try and convert to a number
2497 ajoin(['The type ',Type,' of the JSON value formula for the attribute "',Attr,
2498 '" is not a number:'],Msg),
2499 add_error(visb_visualiser,Msg,StrAttrVal,Pos),fail
2500 )
2501 ; ajoin(['The JSON value for the attribute "',Attr,'" cannot be parsed as a number:'],Msg),
2502 add_error(visb_visualiser,Msg,AttrVal,Pos),fail).
2503
2504 is_number_type(integer).
2505 is_number_type(real).
2506
2507
2508 get_number_from_bvalue(int(Nr),Res) :- !, Res=Nr.
2509 get_number_from_bvalue(Term,Res) :- is_real(Term,Nr),!,Res=Nr.
2510
2511 % ----------------------------------
2512
2513
2514 % computing updates to SVG for a given StateId:
2515 % predicate to obtain required setAttribute changes to visualise StateId
2516 % looks up visb_item facts but also evaluates VISB_SVG_UPDATE definitions
2517 get_change_attribute_for_state(StateId,SvgID,SvgAttribute,Value) :-
2518 visb_state_can_be_visualised(StateId),
2519 set_error_context(checking_context('VisB:','computing attributes for state')),
2520 set_context_state(StateId,get_change_attribute_for_state), % also sets it for external functions
2521 % TODO: also set history so that get_current_history in external_functions is more reliable
2522 call_cleanup((get_expanded_bstate(StateId,ExpandedBState), % inside call_cleanup: contexts cleared if it fails
2523 get_change_aux(StateId,ExpandedBState,SvgID,SvgAttribute,Value)),
2524 (clear_context_state,clear_error_context)).
2525
2526 get_change_aux(StateId,ExpandedBState,SvgID,SvgAttribute,Value) :-
2527 get_aux2(StateId,ExpandedBState,SvgID0,SvgAttribute0,Value0,DefPos),
2528 post_process_visb_item(SvgID0,SvgAttribute0,Value0,DefPos,SvgID,SvgAttribute,Value).
2529 get_aux2(StateId,ExpandedBState,SvgID,SvgAttribute,Value,DefPos) :-
2530 % first get updates from DEFINITIONS which usually return sets of records
2531 get_svg_object_updates_from_definitions(ExpandedBState,SvgID,SvgAttribute,Value,DefPos),
2532 debug_format(19,' VISB_SVG_UPDATE ~w:~w = ~w (in state ~w)~n',[SvgID,SvgAttribute,Value,StateId]).
2533 get_aux2(StateId,ExpandedBState,SvgID,SvgAttribute,Value,Pos) :-
2534 % TODO: check if visibility item exists, and if value is false: do not compute the rest
2535 get_visb_item_formula(SvgID,SvgAttribute,Formula,Pos,ExpandedBState),
2536 % TODO: if UsedIds=[] only set attribute once, if it requires_only_constants : ditto
2537 evaluate_visb_formula(Formula,'VisB item',SvgID,ExpandedBState,FValue,Pos),
2538 %b_value_to_string(FValue,Value),
2539 extract_attr_value(SvgAttribute,FValue,Value,Pos),
2540 debug_format(19,' VisB item ~w:~w = ~w (in state ~w)~n',[SvgID,SvgAttribute,Value,StateId]).
2541
2542 % post-process certain items, like title to adapt the value and id:
2543 % SVG does not support a title attribute; we need a title child and set its text attribute
2544 post_process_visb_item(SvgID,title,Value,Pos,NewID,text,NewValue) :-
2545 (visb_svg_object_debug_info(SvgID,DebugInfo) -> ajoin([Value,'\n',DebugInfo],NewValue) ; NewValue=Value),
2546 (visb_svg_parent(SvgID,TitleID),
2547 visb_svg_object(TitleID,title,_,_,_)
2548 -> NewID=TitleID,
2549 debug_format(9,'Redirecting title update for ~w to child object ~w~n',[SvgID,TitleID])
2550 ; visb_svg_object(SvgID,_SVG_Class,_RestAttrs,_Desc,_Pos1)
2551 -> % this is an object we created
2552 add_warning(visb_visualiser,'Could not find title child object, be sure to define a static title attribute for SVG object: ',SvgID,Pos),
2553 fail
2554 ; add_warning(visb_visualiser,'SVG does not natively support title attributes: ',SvgID,Pos),
2555 fail
2556 ),!.
2557 post_process_visb_item(SvgID,Attr,Value,_,SvgID,Attr,Value).
2558
2559 % ------------------
2560
2561 % convert B value to Json String
2562 b_value_to_string(string(SValue),Res) :- !, Res=SValue. % What about quoting,...?
2563 b_value_to_string(FValue,Res) :-
2564 translate_bvalue_to_codes(FValue,ValCodes),
2565 atom_codes(Res,ValCodes).
2566
2567 % attributes for which we convert pairs to the concatenation of strings
2568 is_id_or_text_attribute(id).
2569 is_id_or_text_attribute('group_id'). % works much like a parent_id; also can be used to attach animate to e.g. a rect
2570 is_id_or_text_attribute('trigger_id').
2571 is_id_or_text_attribute('trigger-id').
2572 is_id_or_text_attribute(A) :- is_text_attribute(A).
2573 % children
2574 is_text_attribute('text').
2575 is_text_attribute('transform').
2576 is_text_attribute('event'). % for VISB_SVG_EVENTS
2577 is_text_attribute('predicate'). % for VISB_SVG_EVENTS
2578 is_text_attribute('svg_class').
2579
2580
2581 b_value_to_id_string(Val,String) :- b_val_to_id_string_aux(Val,add_underscore,String).
2582 b_value_to_attr_string(Val,String) :- b_val_to_id_string_aux(Val,no_underscore,String).
2583
2584 % a special string conversion which e.g., allows to use things like ("ab",2) as id which gets translated to ab2
2585 % also useful for text attributes
2586 b_val_to_id_string_aux(string(SValue),_,Res) :- !, Res=SValue.
2587 b_val_to_id_string_aux((A,B),Add,Res) :- !,
2588 b_val_to_id_string_aux(A,Add,VA), b_val_to_id_string_aux(B,Add,VB),
2589 (Add=add_underscore
2590 -> atom_concat('_',VB,VB1) % introduce separator; in case we have things like numbers so that (12,3) /= (1,23)
2591 ; VB1=VB % for fields like predicate, transform, ... we do not want additional underscores
2592 ),
2593 atom_concat(VA,VB1,Res).
2594 b_val_to_id_string_aux(Set,Add,Res) :- singleton_set(Set,El),!, b_val_to_id_string_aux(El,Add,Res).
2595 % TODO: maybe convert sequence of values using conc
2596 b_val_to_id_string_aux(FValue,_,Res) :- b_value_to_string(FValue,Res).
2597
2598
2599
2600 % get either a regular VisB item or an item associated with a VisB event and its enabled status
2601 get_visb_item_formula(SvgID,SvgAttribute,Formula,Pos,_ExpandedBState) :-
2602 visb_item(SvgID,SvgAttribute,Formula,_UsedIds,_Desc,Pos,_). % regular VisB item
2603 get_visb_item_formula(SvgID,SvgAttribute,Formula,Pos,ExpandedBState) :- % item within VisB event
2604 visb_event_enable_list(OpName,TypedPred,EnableList,_,ItemPos),
2605 debug_format(19,'Checking enabledness of VisB event ~w~n',[OpName]),
2606 (check_enabled(OpName,TypedPred,ExpandedBState,ItemPos)
2607 -> Formula=EnabledValExpr
2608 ; Formula=DisabledValExpr
2609 ),
2610 member(visb_enable_item(SvgID,SvgAttribute,EnabledValExpr,DisabledValExpr,Pos), EnableList).
2611
2612 check_enabled(OpName,Pred,ExpandedBState,Pos) :-
2613 special_operation(OpName),!,
2614 special_operation_enabled(OpName,Pred,ExpandedBState,Pos).
2615 check_enabled(OpName,Pred,ExpandedBState,Pos) :-
2616 b_is_operation_name(OpName),
2617 % TODO: see if we can use GUARD without execution
2618 % TODO: not yet working for XTL mode
2619 execute_operation_by_predicate_in_state_with_pos(ExpandedBState,OpName,Pred,_OpTerm,_NewState,Pos,_).
2620
2621
2622 get_expanded_bstate(StateId,ExpandedBState) :-
2623 \+ b_or_z_mode,!,
2624 StateId \= root,
2625 % in XTL mode we need to access the state via external functions like STATE_PROPERTY
2626 get_static_visb_state([],ExpandedBState).
2627 get_expanded_bstate(StateId,ExpandedBState) :-
2628 visited_expression(StateId,State),
2629 state_corresponds_to_initialised_b_machine(State,BState),
2630 debug_format(19,'Adding VisB definitions to state: ~w~n',[StateId]),
2631 add_prob_deferred_set_elements_to_store(BState,BState2,visible), % add prob_ids
2632 findall(visb_definition(DefID,Type,DefFormula,Class,VPos,Special),
2633 visb_definition(DefID,Type,DefFormula,Class,VPos,Special),DefList),
2634 eval_defs(DefList,BState2,ExpandedBState).
2635
2636
2637 evaluate_static_visb_formula(Formula,Kind,Nr,InState,ResValue,Pos) :-
2638 get_static_visb_state(InState,StaticState),
2639 evaluate_visb_formula(Formula,Kind,Nr,StaticState,ResValue,Pos).
2640
2641 evaluate_visb_formula(Formula,Kind,Nr,BState2,ResValue,Pos) :-
2642 % add_message(visb,'Evaluating: ',Kind:Nr,Pos), debug:nl_time, %set_prolog_flag(profiling,on), print_profile,
2643 (b_compute_explicit_epression_no_wf(Formula,[],BState2,ResValue,Kind,Nr,Pos) -> true
2644 ; add_error(visb_visualiser,'Evaluation of VisB formula failed:',Formula,Pos),
2645 fail).
2646
2647 % evaluate VisB definitions in order one by one, adding values to state
2648 eval_defs([],State,State).
2649 eval_defs([visb_definition(ID,_,TypedExpr,_Class,VPos,Special)|T],State0,State2) :-
2650 (Special \= regular_def
2651 -> State1=State0 % ignore special defs; they are processed separately
2652 ; b_compute_expression_nowf(TypedExpr,[],State0,ResValue,'VisB definition',ID,VPos),
2653 State1 = [bind(ID,ResValue)|State0], % store value for later definitions and VisB items
2654 (debug_level_inactive_for(19)-> true
2655 ; translate_bvalue_to_codes_with_limit(ResValue,2000,RC),
2656 formatsilent(' VisB definition ~w == ~s~n',[ID,RC]))
2657 ),
2658 eval_defs(T,State1,State2).
2659
2660 % check if we have a static value for a VisB definition:
2661 visb_def_static_value(DefID,Value) :-
2662 visb_definition(DefID,_,b(value(Value),_,_),Class,_,SpecialClass),
2663 SpecialClass = regular_def,
2664 (Class = requires_nothing ; Class = requires_constants). % probably we do not need to check this, as we have value/1
2665
2666 get_static_visb_state(InState,FullState) :-
2667 findall(bind(DefID,Value),visb_def_static_value(DefID,Value),FullState,InState).
2668 % TO DO: get state with deferred_set_elements,...
2669
2670 % get a definition either from B DEFINITIONS section, or if not present from the VisB JSON special definition list
2671 get_and_eval_special_definition(Prefix,DefName,JSONBackup,DefPos,ResValue,InlineObjects) :-
2672 (b_sorted_b_definition_prefixed(expression,Prefix,DefName,DefPos),
2673 b_get_typed_definition(DefName,[variables_and_additional_defs],TBody)
2674 ;
2675 visb_special_definition(JSONBackup,DefName,_Type,TBody,_Class,DefPos)
2676 ),
2677 % TODO: warn if we use static SVG
2678 get_typed_static_definition_with_constants_state(DefName,TBody,
2679 Body,DefPos,ConstantsState,InlineObjects,no_separation),
2680 evaluate_visb_formula(Body,DefName,'',ConstantsState,ResValue,DefPos).
2681
2682 % check if we have a DEFINITION with the indicated prefix
2683 special_definition_exists(Prefix) :-
2684 b_sorted_b_definition_prefixed(expression,Prefix,_DefName,_DefPos).
2685
2686 % --------------------------
2687
2688 % debugging features to inspect all created SVG objects
2689 tcltk_get_visb_objects(list([Header|AllObjects])) :-
2690 Header = list(['SVG-ID','svg_class','Attribute','Value']),
2691 findall(list([SvgID,SvgClass,Attr,Value]),
2692 (visb_svg_obj_with_parent(SvgID,SvgClass,AttrList,true),
2693 (member(svg_attribute(Attr,Value),AttrList) ;
2694 visb_svg_parent(SvgID,Value), Attr=children)
2695 ), Childs),
2696 findall(list([SvgID,SvgClass,Attr,Value]),
2697 (visb_svg_obj_with_parent(SvgID,SvgClass,AttrList,false),
2698 member(svg_attribute(Attr,Value),AttrList)
2699 ),AllObjects, Childs).
2700
2701 % debugging features to inspect all created SVG objects
2702 tcltk_get_visb_hovers(list([Header|AllObjects])) :-
2703 Header = list(['SVG-ID','ID','Attribute','EnterValue', 'ExitValue']),
2704 findall(list([SvgID,ID,Attr,EnterVal,ExitVal]),
2705 visb_hover(SvgID,ID,Attr,EnterVal,ExitVal,_Pos), AllObjects).
2706
2707 % debugging features to inspect items
2708 tcltk_get_visb_items(Res) :-
2709 current_state_id(ID),
2710 tcltk_get_visb_items(ID,Res).
2711 tcltk_get_visb_items(_StateId,Res) :-
2712 \+ visb_file_is_loaded(_),!,
2713 Res = list(['No VisB JSON file loaded']).
2714 tcltk_get_visb_items(StateId,list([Header|AllItems])) :-
2715 Header = list(['SVG-ID','Attribute','Value']),
2716 get_preference(translation_limit_for_table_commands,Limit),
2717 findall(list([SvgID,SvgAttribute,Val]),
2718 get_change_attribute_for_state(StateId,SvgID,SvgAttribute,Val),
2719 Items),
2720 findall(list([DefID,'VisB Definition',DValS]),
2721 (get_expanded_bstate(StateId,ExpandedBState),
2722 reverse(ExpandedBState,RS),
2723 member(bind(DefID,DVal),RS),
2724 visb_definition(DefID,_,_,_,_,_),
2725 translate_bvalue_with_limit(DVal,Limit,DValS)),
2726 AllItems, Items).
2727
2728 :- use_module(probsrc(translate),[translate_event_with_limit/3]).
2729 tcltk_get_visb_events(Res) :-
2730 current_state_id(ID),
2731 tcltk_get_visb_events(ID,Res).
2732 tcltk_get_visb_events(_StateId,Res) :-
2733 \+ visb_file_is_loaded(_),!,
2734 Res = list(['No VisB JSON file loaded']).
2735 tcltk_get_visb_events(StateId,list([Header|AllItems])) :-
2736 Header = list(['SVG-ID','Event','Target']),
2737 get_preference(translation_limit_for_table_commands,Limit),
2738 findall(list([SvgID,EventStr,NewStateId]),
2739 (perform_visb_click_event(SvgID,[],StateId,_Event,OpTerm,NewStateId,Res),
2740 (Res=[] -> EventStr='disabled' ; translate_event_with_limit(OpTerm,Limit,EventStr))
2741 ),
2742 AllItems).
2743 % --------------------------
2744
2745 % for ProB2-UI
2746
2747 :- use_module(probsrc(translate),[translate_bexpression_with_limit/3]).
2748 get_visb_items(List) :-
2749 findall(visb_item(SvgID,Attr,TS,Desc,Pos),
2750 (visb_item(SvgID,Attr,TypedExpr,_Used,Desc,Pos,_),
2751 translate_bexpression_with_limit(TypedExpr,1000,TS)), List).
2752
2753 get_visb_attributes_for_state(StateId,List) :-
2754 % some external functions like ENABLED are evaluated in current state; it might be useful to set_current_state
2755 (visb_file_is_loaded(_) -> true
2756 ; add_warning(visb_visualiser,'No VisB visualisation loaded, cannot get attributes for state: ',StateId)),
2757 findall(set_attr(SvgID,SvgAttribute,Val),
2758 get_change_attribute_for_state(StateId,SvgID,SvgAttribute,Val),
2759 List).
2760
2761 % for ProB2-UI
2762 get_visb_click_events(List) :-
2763 findall(execute_event(SvgID,Event,Preds),
2764 get_visb_event(SvgID,Event,Preds), List).
2765 get_visb_event(SvgID,Event,Preds) :- visb_event(SvgID,Event,Preds,_,_,_File,_Pos).
2766 get_visb_event(SvgID,'',[]) :- % add a virtual empty event for SVG Ids with hovers but no events
2767 visb_has_hovers(SvgID),
2768 \+ visb_event(SvgID,_,_,_,_,_File,_Pos).
2769
2770
2771 :- use_module(probsrc(state_space), [extend_trace_by_transition_ids/1]).
2772 % perform a click on a VisB SVG ID in the animator
2773 tcltk_perform_visb_click_event(SvgID) :- current_state_id(StateId),
2774 (perform_visb_click_event(SvgID,[],StateId,TransitionIDs)
2775 -> formatsilent('Clicking on ~w in state ~w resulted in transition id sequence ~w~n',[SvgID,StateId,TransitionIDs]),
2776 extend_trace_by_transition_ids(TransitionIDs)
2777 ; add_error(visb_visualiser,'Cannot perform VisB click on: ',SvgID)
2778 ).
2779
2780 % computes the effect of clicking on an SvgID in StateId
2781 % it returns either empty list if the visb_event is not feasible or a list of transition ids
2782 % it fails if SvgID has no events associated with it
2783 perform_visb_click_event(SvgID,MetaInfos,StateId,ResTransitionIds) :-
2784 perform_visb_click_event(SvgID,MetaInfos,StateId,_,_,_,ResTransitionIds).
2785 perform_visb_click_event(SvgID,MetaInfos,StateId,OpName,OpTerm,NewStateId,ResTransitionIds) :-
2786 get_svgid_with_events(SvgID,_), % check before setting contexts, which would otherwise not be cleared
2787 set_error_context(checking_context('VisB:','performing click event')),
2788 set_context_state(StateId,perform_visb_click_event),
2789 call_cleanup((get_expanded_bstate(StateId,ExpandedBState),
2790 perform_aux(SvgID,StateId,ExpandedBState,OpName,OpTerm,NewStateId,ResTransitionIds,MetaInfos)),
2791 (clear_context_state,clear_error_context)).
2792
2793 get_svgid_with_events(SvgID,FirstOpName) :- visb_event(SvgID,FirstOpName,_,_,_,_File,_Pos).
2794
2795
2796 :- use_module(probsrc(tools),[safe_read_term_from_atom/2]).
2797 :- use_module(probsrc(state_space),[transition/4]).
2798 perform_aux(SvgID,StateId,_ExpandedBState,OpName,OpTerm,NewStateId,ResTransitionIds,_MetaInfos) :-
2799 \+ b_or_z_mode,
2800 % just look up transition/4 entries in state space
2801 % TODO: maybe provide this possibility for B models, even if using explicit parameter values is more robust
2802 get_visb_event_operation(SvgID,OpName,Preds,_ExecKind,_Pred,Pos),
2803 safe_read_term_from_atom(OpName,OpTerm0),
2804 (xtl_mode -> check_xtl_direct_transition_candidate(OpTerm0,Preds,Pos), OpTerm=OpTerm0 ; true), !,
2805 % for XTL: use exec by pred for arity 0, otherwise try to find transition term in state space
2806 if((transition(StateId,OpTerm,TransID,NewStateId),
2807 match_operation(OpTerm,OpName)), % match is relevant if \+xtl_mode
2808 ResTransitionIds = [TransID],
2809 return_disabled(SvgID,StateId,OpName,OpTerm,NewStateId,ResTransitionIds)
2810 ).
2811 perform_aux(SvgID,StateId,ExpandedBState,OpName,OpTerm,NewStateId,ResTransitionIds,MetaInfos) :-
2812 %state_space:portray_state_space,
2813 if(execute_visb_event_by_predicate(SvgID,StateId,ExpandedBState,OpName,OpTerm,NewStateId,TransIds,MetaInfos),
2814 ResTransitionIds = TransIds,
2815 return_disabled(SvgID,StateId,OpName,OpTerm,NewStateId,ResTransitionIds)).
2816
2817 check_xtl_direct_transition_candidate(OpTerm,Preds,Pos) :-
2818 nonvar(OpTerm), % upper case event names are interpreted as Prolog variables -> use exec by pred (or FIXME)
2819 functor(OpTerm,_,Ar), Ar>0, % use exec by pred for arity 0, otherwise try to find transition term in state space
2820 (Preds \= []
2821 -> add_warning(visb_visualiser,'Ignoring predicates for VisB XTL event with explicit transition term (use predicate to provide parameter values): ',OpTerm,Pos)
2822 ; true).
2823
2824 return_disabled(SvgID,StateId,OpName,OpTerm,NewStateId,ResTransitionIds) :-
2825 OpTerm = disabled, NewStateId = StateId,
2826 get_svgid_with_events(SvgID,OpName),
2827 ResTransitionIds = []. % visb_event not enabled
2828
2829 :- use_module(probsrc(tools_strings),[match_atom/2]).
2830 :- use_module(probsrc(specfile),[get_operation_name/2]).
2831 match_operation(OpTerm,OpTerm) :- !.
2832 match_operation(OpTerm,OpName) :- atom(OpName),
2833 (get_operation_name(OpTerm,OpName)
2834 ; match_atom(OpName,OpTerm) % match an atom string with a compound term
2835 ),!.
2836
2837 execute_visb_event_by_predicate(SvgID,StateId,ExpandedBState,OpName,OpTerm,NewStateId,TransIds,MetaInfos) :-
2838 get_visb_event_operation(SvgID,OpName,_,EventExecKind,Pred,Pos),
2839 get_actual_execution_kind(EventExecKind,ExecKind),
2840 build_visb_click_meta_object(MetaInfos,BMetaInfos),
2841 bsyntaxtree:replace_id_by_expr(Pred,'VISB_CLICK_META_INFOS',BMetaInfos,NPred),
2842 exec_aux(SvgID,StateId,ExpandedBState,OpName,ExecKind,NPred,Pos,OpTerm,NewStateId,TransIds).
2843
2844 build_visb_click_meta_object(MetaInfos,BMetaInfos) :-
2845 (member(alt_key,MetaInfos) -> AltKey = pred_true ; AltKey = pred_false),
2846 (member(ctrl_key,MetaInfos) -> CtrlKey = pred_true ; CtrlKey = pred_false),
2847 (member(meta_key,MetaInfos) -> MetaKey = pred_true ; MetaKey = pred_false),
2848 (member(pageX(PageX),MetaInfos) -> true ; PageX = 0), % fallback
2849 (member(pageY(PageY),MetaInfos) -> true ; PageY = 0), % fallback
2850 (member(shift_key,MetaInfos) -> ShiftKey = pred_true ; ShiftKey = pred_false),
2851 findall(','(string(Var),string(VarValue)), member(js_var(Var,VarValue), MetaInfos), JSVars),
2852
2853 visb_click_meta_b_type(BType),
2854 BMetaInfos = b(value(rec([
2855 field(altKey,AltKey),
2856 field(ctrlKey,CtrlKey),
2857 field(jsVars,JSVars),
2858 field(metaKey,MetaKey),
2859 field(pageX,int(PageX)),
2860 field(pageY,int(PageY)),
2861 field(shiftKey,ShiftKey)
2862 ])),BType,[visb_generated]).
2863
2864 visb_click_meta_b_type(record([
2865 field(altKey,boolean),
2866 field(ctrlKey,boolean),
2867 field(jsVars,set(couple(string,string))),
2868 field(metaKey,boolean),
2869 field(pageX,integer),
2870 field(pageY,integer),
2871 field(shiftKey,boolean)
2872 ])).
2873
2874 :- use_module(probsrc(tcltk_interface),[compute_all_transitions_if_necessary/2]).
2875 :- use_module(library(random),[random_member/2]).
2876 :- use_module(extrasrc(mcts_game_play), [mcts_auto_play/4, mcts_auto_play_available/0]).
2877 :- use_module(probsrc(tools_timeout), [time_out_with_factor_call/3]).
2878 :- use_module(probsrc(external_functions),[call_external_function/7]).
2879 :- use_module(probsrc(bsyntaxtree), [is_truth/1]).
2880 :- use_module(probsrc(specfile), [get_specific_max_operations_for_operation/2]).
2881 exec_aux(SvgID,StateId,ExpandedBState,OpName,ExecKind,Pred,_Pos,OpTerm,NewStateId,[TransId]) :-
2882 choose_among_transitions_kind(ExecKind),
2883 b_is_operation_name(OpName),
2884 \+ get_specific_max_operations_for_operation(OpName,0), % otherwise execute by predicate should be done
2885 % TODO: check max_reached_or_timeout_for_node?
2886 compute_all_transitions_if_necessary(StateId,false),
2887 findall(rtr(OpTerm,TransId,NewStateId),
2888 (transition(StateId,OpTerm,TransId,NewStateId),
2889 match_operation(OpTerm,OpName),
2890 transition_satisfies_visb_pred(Pred,SvgID,ExpandedBState,OpName,OpTerm,NewStateId)),
2891 List),
2892 List = [_|_], % otherwise use execute by predicate below, e.g., in case MAX_OPERATIONS was too small
2893 !,
2894 write(random_click_for(SvgID,StateId,OpName,ExecKind)),nl,
2895 choose_transition(ExecKind,List,rtr(OpTerm,TransId,NewStateId)).
2896 exec_aux(SvgID,StateId,ExpandedBState,OpName,_,Pred,Pos,OpTerm,NewStateId,[TransId]) :-
2897 (csp_with_bz_mode -> fail % execute by predicate does not work properly yet with csp_and_b states
2898 ; b_or_z_mode -> b_is_operation_name(OpName)
2899 ; true), !, % note: ignores special definitions below if not B mode
2900 time_out_with_factor_call(
2901 exec_op_by_pred_aux(StateId,ExpandedBState,OpName,Pred,OpTerm,NewState,Pos,TransInfo),
2902 5, % min_max_time_out(10,100,15000)
2903 (ajoin(['TIME-OUT for VisB click on SVG ID ', SvgID,' while executing operation by predicate: '],Msg),
2904 add_warning(visb_visualiser,Msg,OpName,Pos),fail)),
2905 patch_state(NewState,StateId,PatchedNewState),
2906 % add transition to state space:
2907 tcltk_interface:add_trans_id_infos(StateId,OpTerm,PatchedNewState,NewStateId,TransId,TransInfo).
2908 %translate:print_bstate(PatchedNewState),nl.
2909 exec_aux(SvgID,StateId,_ExpandedBState,'MCTS_AUTO_PLAY',_,_Pred,Pos,OpTerm,NewStateId,[TransId]) :- !,
2910 mcts_auto_play_available,
2911 % TODO: allow to set SimRuns, TimeOut in Pred
2912 add_debug_message(visb_visualiser,'Performing MCTS_AUTO_PLAY for click on: ',SvgID,Pos),
2913 mcts_auto_play(StateId,OpTerm,TransId,NewStateId).
2914 % TODO: more general call via call_external_substitution(FunName,Args,InState,OutState,Info,WF)
2915 exec_aux(_SvgID,StateId,_ExpandedBState,'RANDOM_ANIMATE',_,_Pred,_Pos,OpTerm,NewStateId,[TransId]) :- !,
2916 compute_all_transitions_if_necessary(StateId,false),
2917 findall(rtr(OpTerm,TransId,NewStateId),transition(StateId,OpTerm,TransId,NewStateId),List),
2918 random_member(rtr(OpTerm,TransId,NewStateId),List).
2919 % see tcltk_interface:tcltk_random_perform2 and allow Kind: fully_random, no_self_loops, heuristics, ...
2920 % split with ; ?
2921 exec_aux(SvgID,StateId,ExpandedBState,'RANDOM_ANIMATE_UNTIL_LTL',_,LTLExpr,Pos,OpTerm,NewStateId,TransIds) :- !,
2922 OpTerm = 'RANDOM_ANIMATE_UNTIL_LTL',
2923 (get_texpr_type(LTLExpr,string),
2924 evaluate_visb_formula(LTLExpr,'RANDOM_ANIMATE_UNTIL_LTL',SvgID,ExpandedBState,Value,Pos),
2925 Value = string(LTLFormula)
2926 -> tcltk_interface:tcltk_animate_until(LTLFormula,StateId,1000,ltl_state_property,_Steps,_Res,NewStateId,TransIds)
2927 ; add_error(visb_visualiser,'Argument to RANDOM_ANIMATE_UNTIL_LTL must provide LTL formula as string:',StateId),
2928 fail
2929 ).
2930 exec_aux(SvgID,StateId,ExpandedBState,ExternalFun,_,ArgEXPR,Pos,OpTerm,NewStateId,TransIds) :-
2931 external_fun_as_special_operation(ExternalFun),!,
2932 NewStateId=StateId, TransIds=[],
2933 evaluate_visb_formula(ArgEXPR,ExternalFun,1,ExpandedBState,ArgValue,Pos),
2934 convert_arg_value_to_list(ArgEXPR,ArgValue,UnEvalArgs,EvaluatedArgs),
2935 OpTerm =.. [ExternalFun|EvaluatedArgs],
2936 debug_format(9,'VisB event for ~w: calling external function ~w with ~w~n',[SvgID,ExternalFun,EvaluatedArgs]),
2937 % Note: we ignore the return value
2938 call_external_function(ExternalFun,UnEvalArgs,EvaluatedArgs,_Value,any,Pos,no_wf_available).
2939
2940 :- use_module(probsrc(specfile),[get_local_state_for_operation_transition/3]).
2941 :- use_module(probsrc(btypechecker),[prime_atom0/2]).
2942 :- use_module(probsrc(b_interpreter),[b_test_boolean_expression_cs/5]).
2943 % check if an existing transition satisfies the predicate of a VisB event;
2944 % the predicate is evaluated like in execute by predicate: operation parameters and results are in the local state,
2945 % the after state values are accessible by the plain identifiers and the before state values with $0
2946 transition_satisfies_visb_pred(Pred,_,_,_,_,_) :- is_truth(Pred),!.
2947 transition_satisfies_visb_pred(Pred,SvgID,ExpandedBState,OpName,OpTerm,NewStateId) :-
2948 get_local_state_for_operation_transition(OpName,OpTerm,LocalState),
2949 visited_expression(NewStateId,NewState),
2950 state_corresponds_to_initialised_b_machine(NewState,NewBState),
2951 maplist(create_primed_binding,ExpandedBState,PrimedBState),
2952 maplist(get_after_binding(NewBState),ExpandedBState,AfterBState), % VisB definitions keep before values
2953 append(PrimedBState,AfterBState,PredState),
2954 b_test_boolean_expression_cs(Pred,LocalState,PredState,'VisB event',SvgID).
2955
2956 create_primed_binding(bind(ID,Val),bind(PID,Val)) :- prime_atom0(ID,PID).
2957 get_after_binding(NewBState,bind(ID,Val),bind(ID,NewVal)) :-
2958 (member(bind(ID,V),NewBState) -> NewVal=V ; NewVal=Val).
2959
2960 :- use_module(probsrc(state_space_exploration_modes),[heuristic_function_active/0,
2961 compute_heuristic_function_for_state_id/2]).
2962 % execution kinds which choose among the transitions already computed for the operation
2963 choose_among_transitions_kind(random).
2964 choose_among_transitions_kind(heuristic).
2965 choose_among_transitions_kind(explore_open).
2966 choose_among_transitions_kind(min_out_degree).
2967
2968 :- use_module(probsrc(state_space),[not_all_transitions_added/1, out_degree/2]).
2969 choose_transition(heuristic,List,Choice) :- heuristic_function_active,
2970 findall(H-RTR,(member(RTR,List), RTR=rtr(_,_,Dest),
2971 compute_heuristic_function_for_state_id(Dest,int(H))),HList),
2972 choose_with_min_key(HList,Choice),!.
2973 choose_transition(explore_open,List,Choice) :- % prefer transitions leading to states not yet fully explored
2974 include(leads_to_open_state,List,OpenList),
2975 random_member(Choice,OpenList),!.
2976 choose_transition(min_out_degree,List,Choice) :- % prefer successor states with fewest outgoing transitions
2977 findall(D-RTR,(member(RTR,List), RTR=rtr(_,_,Dest),
2978 compute_all_transitions_if_necessary(Dest,false),
2979 out_degree(Dest,D)),DList),
2980 choose_with_min_key(DList,Choice),!.
2981 choose_transition(_,List,Choice) :- random_member(Choice,List).
2982
2983 leads_to_open_state(rtr(_,_,Dest)) :- not_all_transitions_added(Dest).
2984
2985 % choose randomly among the elements with minimal key
2986 choose_with_min_key(KeyList,Choice) :-
2987 keysort(KeyList,[MinKey-_|_]),
2988 findall(RTR,member(MinKey-RTR,KeyList),MinList),
2989 random_member(Choice,MinList).
2990
2991 % convert single argument expression to list; better would be to use a predicate with argument names
2992 convert_arg_value_to_list(b(couple(A,B),_,_),(VA,VB),[A|T],[VA|VT]) :- !, convert_arg_value_to_list(B,VB,T,VT).
2993 convert_arg_value_to_list(Arg,Val,[Arg],[Val]).
2994
2995 :- use_module(probsrc(b_state_model_check),[execute_operation_by_predicate_in_state_with_pos/7,
2996 xtl_execute_operation_by_predicate_in_state/8]).
2997 exec_op_by_pred_aux(StateId,ExpandedBState,OpName,Pred,OpTerm,NewState,Pos,TransInfo) :- xtl_mode,!,
2998 visited_expression(StateId,RawState),
2999 xtl_execute_operation_by_predicate_in_state(ExpandedBState,RawState,OpName,Pred,OpTerm,NewState,Pos,TransInfo).
3000 exec_op_by_pred_aux(_StateId,ExpandedBState,OpName,Pred,OpTerm,NewState,Pos,TransInfo) :-
3001 execute_operation_by_predicate_in_state_with_pos(ExpandedBState,OpName,Pred,OpTerm,NewState,Pos,TransInfo).
3002
3003 :- use_module(probsrc(bmachine), [b_is_variable/1,b_machine_has_constants/0]).
3004
3005 is_var_binding(bind(Var,_)) :- b_or_z_mode, b_is_variable(Var).
3006
3007
3008 % remove constants and VisB Definition entries from state:
3009 patch_state(NewState,_StateId,PatchedState) :-
3010 \+ b_or_z_mode, !, PatchedState=NewState. % XTL state is raw state
3011 patch_state(NewState,StateId,PatchedState) :-
3012 get_constants_id_for_state_id(StateId,ConstId),!,
3013 PatchedState = const_and_vars(ConstId,VarsState),
3014 include(is_var_binding,NewState,VarsState).
3015 patch_state(NewState,StateId,VarsState) :-
3016 (b_machine_has_constants
3017 -> add_error(visb_visualiser,'Could not extract constants id for state:',StateId),
3018 VarsState=NewState
3019 ; include(is_var_binding,NewState,VarsState)).
3020
3021 % the next predicate gets all operations/events associated with SvgID in the order in which they were found
3022 % note that there is only one visb_event (the last one); all others are auxiliary
3023 get_visb_event_operation(SvgID,OpName,Preds,ExecKind,TypedPred,Pos) :- % check if there are more events registered:
3024 auxiliary_visb_event(SvgID,OpName,Preds,ExecKind,TypedPred,Pos).
3025 get_visb_event_operation(SvgID,OpName,Preds,ExecKind,TypedPred,Pos) :-
3026 visb_event(SvgID,OpName,Preds,ExecKind,TypedPred,_File,Pos).
3027
3028 % ---------------
3029
3030 get_visb_hovers(List) :-
3031 findall(hover(SvgID,ID,Attr,EnterVal,ExitVal),
3032 visb_hover(SvgID,ID,Attr,EnterVal,ExitVal,_), List).
3033
3034 get_visb_svg_objects(List) :-
3035 % TODO: remove objects inlined in get_visb_default_svg_file_contents
3036 topological_sort_svg_objects(SvgIDs),
3037 findall(visb_svg_object(SvgID,SvgClass,AttrList),
3038 (member(SvgID,SvgIDs),
3039 visb_svg_obj_with_parent(SvgID,SvgClass,AttrList,_)), List).
3040
3041 visb_svg_obj_with_parent(SvgID,SvgClass,AttrList,IsChild) :-
3042 visb_svg_object(SvgID,SvgClass,List,_Desc,_Pos),
3043 (visb_svg_child(SvgID,ParentId)
3044 -> IsChild=true, AttrList = [svg_attribute(parentId,ParentId)|List] % add parentId attribute for ProB2-UI
3045 ; IsChild=false, AttrList = List).
3046
3047
3048 :- use_module(probsrc(tools),[top_sort/3]).
3049 :- use_module(library(ugraphs),[vertices_edges_to_ugraph/3]).
3050 topological_sort_svg_objects(SortedSVGObjects) :-
3051 findall(SvgID,visb_svg_object(SvgID,_,_,_,_),Vertices),
3052 findall(V-W,visb_svg_parent(V,W),Edges),
3053 vertices_edges_to_ugraph(Vertices,Edges,Graph),
3054 (top_sort(Graph,SortedSVGObjects,UnsortedNr)
3055 -> (UnsortedNr = 0 -> true
3056 ; add_warning(visb_visualiser,'Cycle in SVG_OBJECTS parent/child graph, unsorted objects: ',UnsortedNr)
3057 )
3058 ; SortedSVGObjects=Vertices,
3059 add_error(visb_visualiser,'Topological sorting of SVG_OBJECTS failed: ',Vertices)
3060 ).
3061
3062 % ------------------
3063
3064 :- use_module(probsrc(bmachine),[b_absolute_file_name_relative_to_main_machine/2]).
3065 extended_static_check_default_visb_file :-
3066 (get_default_visb_file(VisBFile,Pos)
3067 % TODO: we could check if we have an visb_history(JSONFile,_,_) option
3068 -> extended_static_check_visb_file(VisBFile,Pos)
3069 ; true).
3070
3071 extended_static_check_visb_file('',_InclusionPos) :- !,
3072 load_visb_file('').
3073 extended_static_check_visb_file(VisBFile,InclusionPos) :-
3074 b_absolute_file_name_relative_to_main_machine(VisBFile,AFile),
3075 (file_exists(AFile)
3076 -> load_visb_file(AFile)
3077 ; add_warning(lint,'VISB_JSON_FILE does not exist: ',AFile,InclusionPos)
3078 ).
3079
3080 % ---------------------------
3081
3082 % portray all VisB items in DEFINITION B syntax
3083 get_visb_ids(SIds) :-
3084 findall(Id,visb_id(Id),Ids),
3085 sort(Ids,SIds).
3086
3087 visb_id(ID) :- visb_svg_object(ID,_,_,_,_). % see svg_id_exists
3088 visb_id(ID) :- visb_item(ID,_,_,_,_,_,_), \+ visb_svg_object(ID,_,_,_,_).
3089 visb_id(ID) :- visb_event(ID,_,_,_,_,_,_), \+ visb_svg_object(ID,_,_,_,_).
3090 visb_id(ID) :- visb_hover(ID,_,_,_,_,_), \+ visb_svg_object(ID,_,_,_,_).
3091
3092 :- public portray_visb/0.
3093 portray_visb:-
3094 get_visb_ids(SIds), nth1(Nr,SIds,ID),
3095 %visb_svg_object(ID,SVG_Class,NewRestAttrs,Desc,Pos1),
3096 findall(field(Attr,b(value(StaticVal),any,[])),
3097 (visb_svg_object(ID,SVG_Class,StaticAttrs,Desc,_Pos1),
3098 ( Attr=svg_class,StaticVal=string(SVG_Class)
3099 ; Attr=comment,StaticVal=string(Desc)
3100 ; member(svg_attribute(Attr,StaticVal),StaticAttrs))
3101 ),
3102 StaticValues),
3103 findall(field(Attr,TypedExpr),
3104 visb_item(ID,Attr,TypedExpr,_UsedIds,_Desc,_PosStartOfItem,_Meta), % meta can contain override
3105 Updates,StaticValues),
3106 % TODO: incorporate events and hovers
3107 UpdateRec = b(rec(Fields),any,[]),
3108 gen_string(ID,IDS),
3109 Fields = [field(id,IDS) | Updates],
3110 (StaticValues=[] -> format('~nVISB_SVG_UPDATES~w == ',[Nr]) ; format('~nVISB_SVG_OBJECTS~w == ',[Nr])),
3111 translate:print_bexpr(UpdateRec), write(';'), nl,
3112 fail.
3113 portray_visb.
3114 gen_string(ID,b(string(ID),string,[])).
3115 % use_module(visbsrc(visb_visualiser)), visb_visualiser:portray_visb.