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,
11 get_default_visb_file/2, extended_static_check_default_visb_file/0,
12 load_default_visb_file_if_necessary/0,
13 generate_visb_html_for_history/1, generate_visb_html_for_history/2,
14 generate_visb_html_for_history_with_vars/1,
15 generate_visb_html_for_history_with_source/1,
16 generate_visb_html_for_current_state/1, generate_visb_html_for_current_state/2,
17 generate_visb_html_codes_for_states/3,
18 generate_visb_html/3,
19 tcltk_get_visb_items/1, tcltk_get_visb_events/1,
20 tcltk_get_visb_objects/1, tcltk_get_visb_hovers/1,
21 get_visb_items/1, get_visb_attributes_for_state/2,
22 get_visb_click_events/1, get_visb_hovers/1,
23 perform_visb_click_event/4,
24 tcltk_perform_visb_click_event/1,
25 get_visb_default_svg_file_contents/1,
26 get_visb_svg_objects/1]).
27
28 :- use_module(probsrc(module_information),[module_info/2]).
29 :- module_info(group,visualization).
30 :- module_info(description,'This module provides VisB visualisation functionality.').
31
32 % special SVG object attributes treated by VisB
33 % title (creates hover tooltip; currently only works with objects created by VisB itself)
34 % id
35 % svg_class
36 % text
37 % hovers
38 % event, events
39 % predicate
40
41 :- meta_predicate process_repeat(-,-,-,2).
42
43 :- use_module(extrasrc(json_parser), [json_parse_file/3]).
44 :- use_module(library(lists)).
45 :- use_module(probsrc(error_manager)).
46 :- use_module(probsrc(preferences), [get_preference/2, reset_temporary_preference/2,
47 temporary_set_preference/3]).
48 :- use_module(probsrc(debug)).
49 :- use_module(probsrc(state_space), [visited_expression/2,
50 visited_state_corresponds_to_initialised_b_machine/1,
51 get_constants_id_for_state_id/2,
52 get_constants_state_id_for_id/2, set_context_state/2,
53 clear_context_state/0, transition/3, transition/4,
54 invariant_violated/1, invariant_not_yet_checked/1,
55 multiple_concrete_constants_exist/0,
56 is_concrete_constants_state_id/1, current_state_id/1,
57 current_state_corresponds_to_setup_constants_b_machine/0,
58 time_out_for_node/3, get_action_trace_with_limit/2,
59 get_state_id_trace/1, max_reached_for_node/1]).
60 :- use_module(probsrc(translate), [translate_bvalue_to_codes/2,
61 translate_bvalue_to_codes_with_limit/3,
62 translate_bvalue_with_limit/3, pretty_type/2, set_unicode_mode/0,
63 unset_unicode_mode/0, translate_event_with_src_and_target_id/5]).
64 :- use_module(probsrc(specfile), [eventb_mode/0, xtl_mode/0,
65 state_corresponds_to_initialised_b_machine/2,
66 state_corresponds_to_fully_setup_b_machine/2,
67 state_corresponds_to_set_up_constants_only/2,
68 expand_to_constants_and_variables/3,
69 extract_variables_from_state/2, translate_operation_name/2,
70 classical_b_mode/0, currently_opened_file/1,
71 get_internal_representation/1,
72 get_operation_description_for_transition/4, b_or_z_mode/0,
73 get_specification_description/2]).
74 :- use_module(probsrc(tools), [start_ms_timer/1, stop_ms_walltimer_with_msg/2, ajoin_with_sep/3,
75 split_list/4, html_escape_codes/2, read_string_from_file/2,
76 get_filename_extension/2, split_chars/3, safe_number_codes/2,
77 safe_atom_codes/2, b_string_escape_codes/2, gen_relative_path/3,
78 string_escape/2]).
79 :- use_module(probsrc(tools_io), [safe_open_file/4, with_open_stream_to_codes/4,
80 write_file_to_stream/2]).
81 :- use_module(probsrc(bmachine), [b_machine_name/1, b_get_definition_name_with_pos/4,
82 bmachine_is_precompiled/0, pre_expand_typing_scope/2,
83 determine_type_of_formula/2, determine_type_of_formula/3,
84 b_load_additional_definitions_file/1,
85 b_load_additional_definitions_from_list_of_facts/1,
86 b_load_additional_definitions_from_term/1,
87 set_additional_filename_as_parsing_default/3,
88 reset_filename_parsing_default/2,
89 b_sorted_b_definition_prefixed/4, b_get_typed_definition/3,
90 b_is_operation_name/1,
91 b_parse_machine_operation_pre_post_predicate/5,
92 b_get_machine_variables/1, b_get_machine_constants/1,
93 b_top_level_operation/1, b_get_machine_animation_expression/2,
94 b_get_operation_variant/3, b_nth1_non_ignored_invariant/3,
95 b_get_machine_operation_signature/2, b_get_machine_operation_max/2]).
96 :- use_module(probsrc(bsyntaxtree), [get_texpr_ids/2, get_texpr_pos/2, create_couple/2,
97 create_couple/3, replace_ids_by_exprs/4, create_equality/3,
98 get_texpr_type/2, find_identifier_uses/3,
99 conjunct_predicates/2, map_over_bexpr/2, get_texpr_id/2,
100 get_texpr_description/2, safe_create_texpr/3]).
101 :- use_module(probsrc(tools_lists), [include_maplist/3]).
102 :- use_module(probsrc(tools_matching), [get_all_svg_attributes/1, is_svg_attribute/1,
103 is_virtual_svg_attribute/1, is_svg_number_attribute/2,
104 is_svg_color_attribute/1, svg_attribute_default_value/2,
105 get_possible_fuzzy_matches_and_completions_msg/3,
106 get_all_svg_classes/1, is_svg_shape_class/1, is_html_tag/1,
107 is_html_attribute/1, dotshape2svg_class/2,
108 fix_svg_attribute/2, is_dot_attribute/1]).
109 :- use_module(visb_static_check, [static_check_dynamic_update_def_body/1,
110 static_check_attribute_value_expression/2,
111 check_svg_attribute_value/3]).
112 :- use_module(probsrc(eventhandling), [register_event_listener/3]).
113 :- use_module(probsrc(pref_definitions), [b_get_definition_string_from_spec/3]).
114 :- use_module(library(file_systems), [file_exists/1, file_property/3]).
115 :- use_module(probsrc(tools_strings), [ajoin/2, safe_name/2, atom_prefix/2,
116 is_simple_classical_b_identifier_codes/1,
117 number_codes_min_length/3, format_modified_info/2,
118 atom_tail_to_lower_case/2]).
119 :- use_module(probsrc(custom_explicit_sets), [try_expand_custom_set_with_catch/3,
120 is_custom_explicit_set/1, is_set_value/2,
121 singleton_set/2]).
122 :- use_module(probsrc(typing_tools), [any_value_for_type/2]).
123 :- use_module(extrasrc(external_functions_svg), [svg_points/4]).
124 :- use_module(probsrc(store), [lookup_value_for_existing_id/3]).
125 :- use_module(probsrc(gensym), [gensym/2]).
126 :- use_module(probsrc(self_check)).
127 :- use_module(probsrc(external_functions), [external_function_requires_state/1]).
128 :- use_module(probsrc(kernel_reals), [is_real/2]).
129 :- use_module(probsrc(b_global_sets), [add_prob_deferred_set_elements_to_store/3]).
130 :- use_module(probsrc(b_interpreter), [b_compute_expression_nowf/7,
131 b_compute_explicit_epression_no_wf/7]).
132 :- use_module(library(system), [datime/1]).
133 :- use_module(probsrc(version), [version_str/1]).
134 :- use_module(extrasrc(bvisual2), [bv_get_top_level/1, bv_get_value_unlimited/3, bv_top_level_set/2]).
135
136
137 % --------------------------
138
139 % facts storing loaded JSON VisB file:
140 :- dynamic visb_file_loaded/3, visb_svg_file/5, visb_empty_svg_box_height_width/3,
141 visb_definition/6, visb_special_definition/6,
142 visb_item/7,
143 visb_event/6, visb_hover/6, visb_has_hovers/1, visb_has_visibility_hover/1,
144 visb_event_enable_list/5,
145 visb_svg_object/5, visb_svg_object_debug_info/2,
146 visb_svg_child/2, visb_svg_parent/2, % register parent/child relationships for groups, title, ...
147 visb_svg_child_of_object_from_svg_file/1. % true if parent of object is an SVG in an external file
148 :- dynamic auxiliary_visb_event/5.
149 % visb_svg_file(SVGFile, AbsolutePathSVGFile, JSONFileFromWhichWeImportSVG,PosTerm,ModLocTime)
150 % visb_item(SVGID,Attribute,TypedExpression,UsedIds,Description/Comment,StartPos,OtherMetaInfos)
151 % visb_event(SVGID,Event,PredicateList,TypedPredicate,File,Pos)
152 % visb_svg_object(SVGID,SVG_Class,AttrList,Description/Comment,Pos) ; AttrList contains svg_attribute(Attr,Val)
153
154 reset_visb :- debug_println(9,resetting_visb),
155 retractall(visb_file_loaded(_,_,_)),
156 retractall(visb_empty_svg_box_height_width(_,_,_)),
157 retractall(visb_svg_file(_,_,_,_,_)),
158 retractall(visb_definition(_,_,_,_,_,_)),
159 retractall(visb_special_definition(_,_,_,_,_,_)),
160 retractall(visb_item(_,_,_,_,_,_,_)),
161 retractall(visb_event(_,_,_,_,_,_)),
162 retractall(visb_hover(_,_,_,_,_,_)),
163 retractall(visb_has_hovers(_)),
164 retractall(visb_has_visibility_hover(_)),
165 retractall(visb_event_enable_list(_,_,_,_,_)),
166 retractall(auxiliary_visb_event(_,_,_,_,_)),
167 retractall(visb_svg_object(_,_,_,_,_)),
168 retractall(visb_svg_object_debug_info(_,_)),
169 retractall(visb_svg_child(_,_)),
170 retractall(visb_svg_child_of_object_from_svg_file(_)),
171 retractall(visb_svg_parent(_,_)),
172 reset_auto_attrs.
173
174 visb_file_is_loaded(JSONFile) :-
175 visb_file_is_loaded(JSONFile,_,true).
176 visb_file_is_loaded(JSONFile,SVGFile,AllowEmpty) :-
177 visb_file_loaded(JSONFile,_,_),
178 (visb_svg_file(_,SVGFile,_,_,_) -> true
179 ; visb_empty_svg_box_height_width(_,_,_) -> SVGFile = ''
180 ; user_has_defined_visb_objects -> SVGFile = ''
181 ; JSONFile='' ->
182 AllowEmpty=true,
183 add_warning(visb_visualiser,'No VISB_SVG_FILE or VISB_SVG_OBJECTS specified in DEFINITIONS',''),
184 % Note: warning also generated below No VisB JSON file is specified and no VISB_SVG_OBJECTS were created
185 SVGFile = ''
186 ; add_warning(visb_visualiser,'No SVG file or objects specified for VisB file:',JSONFile),
187 AllowEmpty=true,
188 SVGFile = ''
189 ).
190
191 no_svg_available :-
192 \+ user_has_defined_visb_objects,
193 no_svg_file_available,
194 \+ visb_empty_svg_box_height_width(_,_,_). % no SVG box provided
195
196 no_svg_file_available :- (visb_svg_file(_,SVGFile,_,_,_) -> SVGFile='' ; true).
197 %svg_file_available :- \+ no_svg_file_available.
198
199
200 visb_current_state_can_be_visualised :-
201 %visb_file_is_loaded(_), % no longer checked; Tcl/Tk will automatically load VisB file if required
202 (b_or_z_mode -> current_state_corresponds_to_setup_constants_b_machine
203 ; \+ current_state_id(root)
204 ).
205
206
207 :- register_event_listener(reset_specification,reset_visb,'Reset VisB information').
208 :- register_event_listener(reset_prob,reset_visb,'Reset VisB information').
209
210 %static_check_visb :- % now done when adding items and not storing multiple items
211 % visb_item(ID,Attr,F1,_,_,Pos1), visb_item(ID,Attr,F2,_,Pos2), F1 @< F2,
212 % add_warning(visb_visualiser,'Multiple formulas for SVG identifier and attribute:',ID/Attr,Pos1),
213 % add_message(visb_visualiser,'Location of second formula for:',ID/Attr,Pos2),
214 % fail.
215 % TO DO: some sanity checks on attributes and values
216 static_check_visb :-
217 no_svg_file_available,
218 ? visb_hover(SVGID,_ID,Attr,_Enter,_Exit,Pos),
219 \+ svg_id_exists(SVGID),
220 ajoin(['Hover for attribute ',Attr,' has unknown trigger-id (can lead to blank visualisation): '],Msg),
221 add_warning(visb_visualiser,Msg,SVGID,Pos),
222 fail.
223 static_check_visb :-
224 no_svg_file_available,
225 ? visb_hover(SVGID,ID,Attr,_Enter,_Exit,Pos), ID \= SVGID,
226 \+ svg_id_exists(ID),
227 ajoin(['Hover for attribute ',Attr,' has unknown id (can lead to blank visualisation): '],Msg),
228 add_warning(visb_visualiser,Msg,ID,Pos),
229 fail.
230 static_check_visb :-
231 visb_svg_file(SvgFile,_,_,Pos,_),
232 SvgFile \= '',
233 visb_empty_svg_box_height_width(H,W,ViewBox),
234 ajoin(['VISB_SVG_BOX (width=', W, ', height=', H, ', viewBox=', ViewBox,
235 ') cannot be applied to an existing SVG file (use VISB_SVG_CONTENTS for file or put info into SVG file): '],Msg),
236 add_warning(visb_visualiser,Msg,SvgFile,Pos),
237 fail.
238 static_check_visb.
239
240 svg_id_exists(SVGID) :- visb_svg_object(SVGID,_,_StaticAttrList,_,_ExitPos).
241 % --------------------------
242
243
244 % store templates as facts, so that compiled version of probcli does not need to find files
245 :- dynamic visb_template_file_codes/2.
246
247 assert_from_template(Filename) :- %formatsilent('Loading ~w~n',[Filename]),
248 absolute_file_name(visbsrc(Filename), Absolute, []),
249 read_string_from_file(Absolute,String),
250 assertz(visb_template_file_codes(Filename,String)).
251
252 :- assert_from_template('visb_template_header.html').
253 :- assert_from_template('visb_template_svg_downloads.html').
254 :- assert_from_template('visb_template_replayTrace.html').
255 :- assert_from_template('visb_template_middle.html').
256 :- assert_from_template('visb_template_footer.html').
257
258 write_visb_template(HtmlFile,Stream) :-
259 visb_template_file_codes(HtmlFile,Codes),
260 format(Stream,'~s~n',[Codes]).
261
262
263 % --------------------------
264
265
266 get_default_visb_file(Path, Pos) :- get_default_visb_file(Path, _, Pos).
267 get_default_visb_file(Path, Kind, Pos) :- bmachine_is_precompiled,
268 (b_get_definition_string_from_spec('VISB_JSON_FILE', Pos, Path)
269 -> Kind=json % user provided explicit path to VISB JSON file
270 ; b_get_definition_string_from_spec('VISB_DEFINITIONS_FILE', Pos, Path)
271 -> Kind=def % user provided explicit path to VISB DEFINITIONS file
272 % TODO: in future check that file extension is compatible
273 % advantage of VISB_DEFINITIONS_FILE == "File" over "File"
274 % 1) visualisation can be re-loaded without re-loading machine
275 % 2) can be used in TLA+ or similar
276 % 3) avoid clash if definitions file itself defines empty VISB_JSON_FILE
277 % 4) avoid problems with Atelier-B or other tools
278 ; get_default_visb_svg_file(_,Pos)
279 -> Kind=empty, Path='' % user provided SVG file path
280 ; user_has_defined_visb_objects_in_defs
281 -> Kind=empty, Path='' % user provided SVG object definitions
282 ).
283
284 user_has_defined_visb_objects :-
285 ? (visb_svg_object(_,_,_,_,_) -> true % created in JSON file
286 ; user_has_defined_visb_objects_in_defs).
287
288 user_has_defined_visb_objects_in_defs :-
289 b_sorted_b_definition_prefixed(expression,'VISB_SVG_OBJECTS',_,_).
290
291 % you should do b_absolute_file_name_relative_to_main_machine
292 get_default_visb_svg_file(Path, Pos) :-
293 b_get_definition_string_from_spec('VISB_SVG_FILE', Pos, Path).
294
295
296 % load default VISB_JSON_FILE if it is specified and not already loaded
297 load_default_visb_file_if_necessary :-
298 get_default_visb_file(File, Pos),!,
299 (load_visb_file_if_necessary(File) -> true
300 ; add_error(visb_visualiser,'Could not load VISB_JSON_FILE:',File,Pos)).
301 load_default_visb_file_if_necessary :-
302 (eventb_mode -> true ; add_message(visb_visualiser,'No VISB_JSON_FILE DEFINITION provided')).
303
304 % --------------------------
305 % Loading a JSON VisB file:
306
307
308 load_visb_file(File) :-
309 temporary_set_preference(allow_arith_operators_on_reals,true,Old),
310 call_cleanup((load_visb_file1(File)),
311 reset_temporary_preference(allow_arith_operators_on_reals,Old)).
312 load_visb_file1(File) :-
313 get_filename_extension(File,def), % a .def B definition file
314 !,
315 add_message(visb_visualiser,'Loading VisB DEFINITIONS from B file: ',File),
316 b_load_additional_definitions_file(File),
317 load_visb_file2('',File).
318 load_visb_file1(File) :- load_visb_file2(File,File).
319
320 load_visb_definitions_from_list_of_facts(DefFilePath, ListOfFacts) :-
321 temporary_set_preference(allow_arith_operators_on_reals,true,Old),
322 call_cleanup(
323 (b_load_additional_definitions_from_list_of_facts(ListOfFacts),
324 load_visb_file2('', DefFilePath)),
325 reset_temporary_preference(allow_arith_operators_on_reals,Old)).
326
327 load_visb_definitions_from_term(DefFilePath, Machine) :-
328 temporary_set_preference(allow_arith_operators_on_reals,true,Old),
329 call_cleanup(
330 (b_load_additional_definitions_from_term(Machine),
331 load_visb_file2('', DefFilePath)),
332 reset_temporary_preference(allow_arith_operators_on_reals,Old)).
333
334 load_visb_file2(JsonFile,OrigFileName) :-
335 reset_visb,
336 load_visb_from_definitions(no_inlining,JsonFile), % TODO: pass InlineObjects?
337 start_ms_timer(T),
338 (JsonFile='' % No JSON file
339 -> (get_default_visb_svg_file(SvgFile,DefaultSVGPos)
340 -> (SvgFile='' -> AbsFile=SvgFile % just dummy empty string provided by user
341 ; b_absolute_file_name_relative_to_main_machine(SvgFile,AbsFile)
342 ),
343 add_visb_svg_file(SvgFile,AbsFile,'',DefaultSVGPos)
344 ; check_objects_created(JsonFile) % no JSON and SVG file; check we have created objects
345 )
346 ; add_visb_file(JsonFile,[]),
347 stop_ms_walltimer_with_msg(T,'loading VisB JSON file: ')
348 ),
349 static_check_visb,
350 (OrigFileName = ''
351 -> ModTime=0, ModLocTime=0 % We could get modification time of files with VISB_SVG_OBJECTS, ... DEFINITIONS
352 ; file_property(OrigFileName, modify_timestamp, ModTime),
353 file_property(OrigFileName, modify_localtime, ModLocTime)
354 ),
355 assertz(visb_file_loaded(OrigFileName,ModTime,ModLocTime)).
356
357 check_objects_created(File) :-
358 ? (visb_svg_object(_,_,_,_,_) -> true
359 ; add_warning(visb_visualiser,'No VisB JSON file is specified and no VISB_SVG_OBJECTS were created:',File)
360 ).
361
362 load_visb_from_definitions(InlineObjects,JsonFileContext) :-
363 start_ms_timer(T),
364 pre_expand_typing_scope([variables_and_additional_defs],ExpandedScope), % do this only once for all defs
365 get_svg_objects_from_definitions(InlineObjects,ExpandedScope,JsonFileContext),
366 (get_SVG_BOX_definition(InlineObjects) -> true ; true), % TODO: also pass scope
367 stop_ms_walltimer_with_msg(T,'extracting VisB infos from DEFINITIONS: ').
368
369
370 %:- use_module(library(system),[now/1, datime/2]).
371 load_visb_file_if_necessary(File) :-
372 visb_file_loaded(File,ModTime1,_), % this file is already loaded
373 (File = '' -> true
374 ; file_exists(File),
375 file_property(File, modify_timestamp, ModTime2), % check if it has the same time stamp
376 debug_println(19,visb_json_already_loaded(File,ModTime1,ModTime2)),
377 ModTime1=ModTime2
378 ),
379 !.
380 load_visb_file_if_necessary(File) :- load_visb_file(File).
381
382
383 add_visb_file(File,LoadedFiles) :- member(File,LoadedFiles),!,
384 add_error(visb_visualiser,'Circular inclusion of JSON files:',[File|LoadedFiles]).
385 add_visb_file(File,_) :- \+ file_exists(File),!,
386 add_error(visb_visualiser,'JSON file does not exist:',File), fail.
387 add_visb_file(File,LoadedFiles) :-
388 debug_format(19,'Loading JSON File: ~w~n',[File]),
389 set_additional_filename_as_parsing_default(File,NewNr,OldNr),
390 call_cleanup(add_visb_file2(File,LoadedFiles), reset_filename_parsing_default(NewNr,OldNr)).
391
392 add_visb_file2(File,LoadedFiles) :-
393 json_parse_file(File,json(List2),[position_infos(true),multiline_strings(true)]),
394 % tools_printing:trace_print(List2),nl,nl,
395 process_json(List2,File),
396 !,
397 (get_attr_with_pos(include,List2,JsonFileTerm,File,Pos)
398 -> check_json_string(JsonFileTerm,include,Pos,JsonFile),
399 absolute_file_name(JsonFile,AF,[relative_to(File)]),
400 formatsilent('Including JSON file: ~w~n',[JsonFile]),
401 add_visb_file(AF,[File|LoadedFiles])
402 ; true
403 ),
404 (LoadedFiles=[], % only check for main included file
405 ? get_attr_with_pos('model-name',List2,string(ModelName),File,MPos),
406 b_machine_name(Main), Main \= ModelName
407 -> ajoin(['VisB JSON file expects model-name ',ModelName,' instead of: '],MMsg),
408 add_warning(visb_visualiser,MMsg,Main,MPos)
409 ; true
410 ).
411 add_visb_file2(File,_) :-
412 add_error(visb_visualiser,'Unable to process JSON file:',File),
413 fail.
414
415 % process json content of a VisB file:
416 process_json(List,JSONFile) :- visb_svg_file(_,_,_,_,_),!, % we have already determined the SVG file
417 process_json2(List,JSONFile).
418 process_json(List,JSONFile) :-
419 ? get_attr_with_pos(svg_box,List,json(BoxList),JSONFile,Pos),
420 % json([=(width,400,3-3),=(height,400,3-3)])
421 ? (get_attr(svg,List,string(SvgFile)) -> SvgFile='' ; true), % check if svg attr empty or non-existant
422 force_get_attr_nr(height,BoxList,H,JSONFile),
423 force_get_attr_nr(width,BoxList,W,JSONFile),!,
424 (get_attr(viewBox,BoxList,string(VB)) -> ViewBox=VB ; ViewBox=''),
425 add_message(visb_visualiser,'Will create empty SVG image with specified dimensions: ',H:W,Pos),
426 assert_visb_empty_svg_box_height_width(H,W,ViewBox,Pos),
427 process_json2(List,JSONFile).
428 process_json(List,JSONFile) :-
429 ? get_attr_with_pos(svg,List,FileTerm,JSONFile,Pos),
430 check_json_string(FileTerm,svg,Pos,File),
431 (File = '' -> get_default_visb_svg_file(SvgFile, _)
432 ; get_default_visb_svg_file(SvgFile, DPos)
433 -> add_message(visb_visualiser,'Overriding svg file specified in JSON file: ',File,DPos)
434 ; SvgFile=File),
435 !,
436 absolute_file_name(SvgFile,AbsFile,[relative_to(JSONFile)]),
437 add_visb_svg_file(SvgFile,AbsFile,JSONFile,Pos),
438 process_json2(List,JSONFile).
439 process_json(List,JSONFile) :-
440 get_default_visb_svg_file(SvgFile, Pos), SvgFile \= '',
441 !,
442 absolute_file_name(SvgFile,AbsFile,[]), % relative to B machine??
443 add_visb_svg_file(SvgFile,AbsFile,JSONFile,Pos),
444 process_json2(List,JSONFile).
445 process_json(List,JSONFile) :-
446 process_json2(List,JSONFile),
447 (get_SVG_BOX_definition(no_inlining) -> true % TODO: pass (InlineObjects)
448 ; get_attr_with_pos(svg,List,_,JSONFile,Pos) -> % File is empty
449 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)
450 ; add_warning(visb_visualiser,'Creating empty SVG image. The JSON file contains no svg attribute (pointing to the SVG file): ',JSONFile)
451 ).
452
453 add_visb_svg_file(SvgFile,AbsFile,JSONFile,Pos) :-
454 (SvgFile='' -> add_message(visb_visualiser,'Empty VisB SVG file:',SvgFile,Pos)
455 ; file_exists(AbsFile)
456 -> debug_format(19,'SVG file = ~w (~w)~n',[SvgFile, AbsFile]),
457 file_property(AbsFile, modify_localtime, ModLocTime)
458 ; add_error(visb_visualiser,'The specified VisB SVG file does not exist:',SvgFile,Pos),
459 ModLocTime=unknown
460 ),
461 assertz(visb_svg_file(SvgFile,AbsFile,JSONFile,Pos,ModLocTime)).
462
463 process_json2(List,JSONFile) :-
464 process_json_definitions(List,JSONFile),
465 process_json_items(List,JSONFile),
466 process_json_events(List,JSONFile),
467 process_json_new_svg_objects(List,JSONFile).
468
469
470 check_json_string(Term,_,_,Atom) :- Term = string(Atom), atom(Atom), !.
471 check_json_string(Term,Attr,Pos,_) :- !,
472 ajoin(['Illegal JSON attribute ',Attr,', expected a JSON string:'],Msg),
473 add_error(visb_visualiser,Msg,Term,Pos),fail.
474 % ----------------
475
476 % B definitions that can help write items, events more compactly
477 process_json_definitions(List,File) :-
478 ? get_attr(definitions,List,array(Defs)),!,
479 length(Defs,Len),
480 formatsilent('VisB Definitions: ~w~n',[Len]),
481 maplist(process_json_definition(File),Defs).
482 process_json_definitions(_,_File).
483
484 % VisB items which modify attributes of SVG objects
485 process_json_items(List,File) :-
486 ? get_attr(items,List,array(Items)),!,
487 length(Items,Len),
488 formatsilent('VisB Item declarations: ~w~n',[Len]),
489 maplist(process_visb_json_item(File),Items).
490 process_json_items(_,File) :- \+ visb_special_definition(visb_updates,_,_,_,_,_),!,
491 add_message(visb_visualiser,'The JSON file contains no items: ',File).
492 process_json_items(_,_).
493
494 % VisB events which react to clicks on SVG objects and display hovers
495 process_json_events(List,File) :-
496 get_attr(events,List,array(Items)),!,
497 length(Items,Len),
498 formatsilent('VisB Event declarations: ~w~n',[Len]),
499 maplist(process_json_event(File),Items).
500 process_json_events(_,_).
501
502 % VisB additional SVG objects added to SVG file
503 process_json_new_svg_objects(List,File) :-
504 ? get_attr(svg_objects,List,array(Items)),!,
505 length(Items,Len),
506 formatsilent('VisB additional svg_objects declarations: ~w~n',[Len]),
507 maplist(process_json_svg_object(File),Items).
508 process_json_new_svg_objects(List,File) :-
509 get_attr_with_pos(objects,List,array(Items),File,Pos),!,
510 add_warning(visb_visualiser,'Use "svg_objects" attribute instead of "objects" in: ',File,Pos),
511 maplist(process_json_svg_object(File),Items).
512 process_json_new_svg_objects(_,_).
513
514
515 % evaluate all VISB_SVG_OBJECTS... DEFINITIONS and try and extract SVG objects
516 % this must be a set of records with at least id and svg_class field
517 get_svg_objects_from_definitions(InlineObjects,ExpandedScope,_) :-
518 ? find_and_eval_visb_DEFINITION('VISB_SVG_OBJECTS', visb_objects, SVG_ID, AttrList, Desc, DefName,
519 _DefPos, EvalPos, InlineObjects, allow_separation, ExpandedScope),
520 %formatsilent('Generating new SVG object ~w with attrs ~w~n',[SVG_ID,AttrList]),
521 add_visb_object_from_definition(visb_objects, SVG_ID, AttrList, Desc, DefName, EvalPos),
522 fail.
523 get_svg_objects_from_definitions(InlineObjects,ExpandedScope,_) :-
524 find_and_eval_visb_DEFINITION('VISB_SVG_EVENTS', visb_events, SVG_ID, AttrList, Desc, DefName,
525 _DefPos, EvalPos, InlineObjects, no_separation, ExpandedScope),
526 % attributes: event or events, predicate
527 add_visb_object_from_definition(visb_events, SVG_ID, AttrList, Desc, DefName, EvalPos),
528 fail.
529 get_svg_objects_from_definitions(InlineObjects,ExpandedScope,_) :-
530 ? find_and_eval_visb_DEFINITION('VISB_SVG_HOVERS', visb_hovers, SVG_ID, AttrList, Desc, DefName,
531 _DefPos, EvalPos, InlineObjects, no_separation, ExpandedScope),
532 % attributes: id, trigger_id (optional), other SVG attributes
533 add_visb_hovers_from_definition(SVG_ID, AttrList, Desc, DefName, EvalPos),
534 fail.
535 get_svg_objects_from_definitions(_InlineObjects,ExpandedScope,JsonFileContext) :- % VISB_SVG_UPDATES
536 precompile_svg_object_updates(ExpandedScope,JsonFileContext).
537
538 % example definition VISB_SVG_HOVERS == rec(`id`:"myid", stroke:"black", stroke_exit:"gray");
539 % a hovers field inside VISB_SVG_OBJECTS can be something like:
540 % rec(.... hovers: (rec(class:"train-hover"),rec(trigger_id:"track_polyline",class:"train-hover")), ...)
541 % also used, e.g., as attribute in VISB_SVG_OBJECTS
542 add_visb_hovers_from_definition(SVG_ID,AttrList, Desc, DefName, DefPos) :-
543 select(svg_attribute(hovers,Hovers),AttrList,AttrList2),
544 !,
545 (AttrList2=[] -> true ; add_warning(visb_visualiser,'Unknown extra hover attributes:',AttrList2,DefPos)),
546 flex_member(Record,Hovers,DefName,DefPos),
547 (get_VISB_record_fields(Record,Fields) -> true
548 ; add_warning(visb_visualiser,'VisB hovers field value is not a record of SVG attributes: ',Record,DefPos),fail),
549 include_maplist(extract_attribute_from_record(DefPos),Fields,HoverAttrList),
550 add_visb_object_from_definition(visb_hovers, SVG_ID, HoverAttrList, Desc, DefName, DefPos).
551 add_visb_hovers_from_definition(SVG_ID,AttrList, Desc, DefName, DefPos) :-
552 add_visb_object_from_definition(visb_hovers, SVG_ID, AttrList, Desc, DefName, DefPos).
553
554
555 % add a VisB record object from a HOVER or OBJECT definition:
556 add_visb_object_from_definition(visb_objects,SVG_ID, AttrList, Desc, DefName, DefPos) :- !,
557 ? (select(svg_attribute(svg_class,SVG_Class),AttrList,AttrList2)
558 -> true % maybe we should call svg_class svg_shape and
559 % allow html_tag for children of foreignObject
560 ; add_warning(visb_visualiser,'SVG objects have no svg_class field: ',DefName,DefPos),
561 fail
562 ),
563 assert_visb_svg_object(SVG_ID,SVG_Class,AttrList2,Desc,DefName,DefPos).
564 add_visb_object_from_definition(visb_hovers,SVG_ID, AttrList, _Desc, _DefName, DefPos) :- !,
565 (select(svg_attribute(trigger_id,TriggerID),AttrList,AttrList2) -> true
566 ; select(svg_attribute('trigger-id',TriggerID),AttrList,AttrList2) -> true
567 ; TriggerID = SVG_ID, AttrList2=AttrList),
568 member(svg_attribute(Attr,EnterVal),AttrList2), % will backtrack for every SVG attribute
569 \+ get_exit_attribute_name(_,Attr), % it is not an exit attribute
570 get_exit_attribute_name(Attr,AttrExitName),
571 (member(svg_attribute(AttrExitName,ExitVal), AttrList2) -> true % user specified exit value explicitly
572 ; visb_svg_object(SVG_ID,_,StaticAttrList,_,ExitPos)
573 -> (member(svg_attribute(Attr,ExitVal),StaticAttrList) -> true % use value specified in VISB_SVG_OBJECTS
574 ; default_attribute_value(Attr,ExitVal)
575 -> add_message(visb_visualiser,'Assuming default hover exit value for attribute: ',Attr,DefPos)
576 ; Attr = 'svg_class'
577 -> add_warning(visb_visualiser,
578 'svg_class cannot be set in hover for: ',SVG_ID,ExitPos),
579 ExitVal=EnterVal
580 ; (Attr = hover ; Attr = hovers) ->
581 add_error(visb_visualiser,
582 'Only provide SVG attributes here; no need to wrap them in this attribute:',Attr,DefPos),fail
583 ; add_warning(visb_visualiser,
584 '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),
585 ExitVal=EnterVal
586 )
587 ; ajoin(['No VISB_SVG_OBJECT for id ',SVG_ID,' and no value for ',AttrExitName,
588 '; cannot retrieve hover exit value for attribute: '],Msg),
589 add_warning(visb_visualiser,Msg,Attr,DefPos),
590 fail %ExitVal=EnterVal
591 ),
592 assert_visb_hover(TriggerID,SVG_ID,Attr,EnterVal,ExitVal,DefPos).
593 add_visb_object_from_definition(visb_events,SVG_ID, AttrList, _Desc, DefName, DefPos) :- !,
594 ( select(svg_attribute(event,Event),AttrList,AttrList1) -> true
595 ; select(svg_attribute(events,Events),AttrList,AttrList1) -> % we have events attributes with multiple events
596 flex_member(EvVal,Events,DefName,DefPos),
597 extract_attr_value(event,EvVal,Event,DefPos)
598 ; AttrList = [_|_], % at least one other attribute than id; otherwise it may stem from separating VISB_SVG_OBJECTS
599 add_warning(visb_visualiser,'Missing event attribute in VisB definition: ',DefName,DefPos),
600 fail
601 ),
602 (select(svg_attribute(predicate,Pred),AttrList1,AttrList2) -> Preds=[Pred]
603 ; member(P,[preds,predicates]),
604 select(svg_attribute(P,Pred),AttrList1,AttrList2)
605 -> Preds=[Pred], add_warning(visb_visualiser,'Use predicate as attribute for VisB events instead of: ',P,DefPos)
606 ; Preds=[], AttrList2=AttrList1
607 ),
608 EnableItems=[],
609 maplist(warn_remaining_attributes(DefName,DefPos),AttrList2),
610 % TODO extract from AttrList2: visb_enable_item(SvgID,Attr,EnabledValExpr,DisabledValExpr,PosAttr)
611 (error_manager:extract_file_number_and_name(DefPos,_,File) -> true ; File='?'),
612 PredPos = DefPos, %TODO: improve
613 add_visb_event(SVG_ID,Event,Preds,[],EnableItems,File,DefPos,PredPos,[]).
614 add_visb_object_from_definition(SpecialClass,_, _, _, _DefName, DefPos) :-
615 add_warning(visb_visualiser,'Unknown special class, cannot add VisB objects for definition: ',SpecialClass,DefPos).
616
617 % for hovers allow to explicitly specify exit value, in case the SVG object comes from an SVG file
618 get_exit_attribute_name(Attr,ExitAttr) :- atom_concat(Attr,'_exit',ExitAttr).
619
620 warn_remaining_attributes(DefName,DefPos,svg_attribute(hover,_)) :- !,
621 add_warning(visb_visualiser,'Attribute hover not supported here (use separate VISB_SVG_HOVERS definition): ',DefName,DefPos).
622 warn_remaining_attributes(DefName,DefPos,svg_attribute(hovers,_)) :- !,
623 add_warning(visb_visualiser,'Attribute hovers not supported here (use separate VISB_SVG_HOVERS definition): ',DefName,DefPos).
624 warn_remaining_attributes(_,DefPos,Attr) :-
625 add_warning(visb_visualiser,'Unrecognised attribute in VISB_SVG_EVENTS definition: ',Attr,DefPos).
626
627
628 default_attribute_value(fill,black). % is remove for animate, ...
629 default_attribute_value(opacity,1).
630 default_attribute_value('stop-dasharray',none).
631 default_attribute_value('stop-opacity',1).
632 default_attribute_value('stroke-opacity',1).
633 default_attribute_value('stroke-width','1px').
634 default_attribute_value(stroke,none).
635 default_attribute_value(transform,none).
636 default_attribute_value(visibility,visible).
637
638 % is called in process_json when no SVG file specified
639 % VISB_SVG_BOX == rec(width:1000,height:1000,viewBox:"minx miny w h"),
640 get_SVG_BOX_definition(InlineObjects) :-
641 ? get_and_eval_special_definition('VISB_SVG_BOX','VISB_SVG_BOX',visb_box,DefPos,ResValue,InlineObjects),
642 (ResValue=(BH,BW) -> ViewBox=''
643 ; get_VISB_record_fields(ResValue,Fields),
644 ? select(field(height,BH),Fields,F1),
645 ? select(field(width,BW),F1,F2)
646 ? -> (select(field(viewBox,VBVal),F2,F3)
647 -> (VBVal=string(VB) -> ViewBox=VB
648 % Viewbox is "mx my w h" string, ie: minimum_x, minimum_y, width and height
649 ; VBVal = rec(VBFields)
650 -> (get_view_box_rec(VBFields,DefPos,ViewBox) -> true
651 ; ViewBox='',
652 add_warning(visb_visualiser,'VISB_SVG_BOX viewBox record has illegal fields (expected minx miny width height):',VBVal,DefPos))
653 ; add_warning(visb_visualiser,'VISB_SVG_BOX viewBox is not a string ("minx miny width height") or record:',VBVal,DefPos),
654 ViewBox=''
655 )
656 ; ViewBox='', F3=F2
657 ),
658 (F3=[] -> true
659 ; add_warning(visb_visualiser,'VISB_SVG_BOX unknown attributes (not height, width, viewBox): ',F2,DefPos))
660 ; add_error(visb_visualiser,'Ignoring VISB_SVG_BOX, must be record or pair of integers (height,width):',ResValue,DefPos)),
661 (get_number_from_bvalue(BH,H) -> true
662 ; add_error(visb_visualiser,'VISB_SVG_BOX Height is not a number:',ResValue,DefPos)),
663 (get_number_from_bvalue(BW,W) -> true
664 ; add_error(visb_visualiser,'VISB_SVG_BOX Width is not a number:',ResValue,DefPos)),
665 !,
666 assert_visb_empty_svg_box_height_width(H,W,ViewBox,DefPos).
667
668 get_view_box_rec([field(height,VH),field(minx,MXH),field(miny,MYH),field(width,VW)],DefPos,ViewBoxString) :-
669 (get_number_from_bvalue(VH,Height) -> true
670 ; add_error('VISB_SVG_BOX viewBox\'height is not a number:',VH,DefPos),fail),
671 (get_number_from_bvalue(VW,Width) -> true
672 ; add_error('VISB_SVG_BOX viewBox\'width is not a number:',VH,DefPos),fail),
673 (get_number_from_bvalue(MXH,MinX) -> true
674 ; add_error('VISB_SVG_BOX viewBox\'minx is not a number:',VH,DefPos),fail),
675 (get_number_from_bvalue(MYH,MinY) -> true
676 ; add_error('VISB_SVG_BOX viewBox\'miny is not a number:',VH,DefPos),fail),
677 ajoin([MinX,' ',MinY,' ', Width,' ',Height],ViewBoxString).
678
679
680 assert_visb_empty_svg_box_height_width(H,W,_ViewBox,Pos) :-
681 retract(visb_empty_svg_box_height_width(OldH,OldW,_)),
682 (OldH,OldW) \= (H,W),
683 add_message(visb_visualiser,'Overriding VisB SVG_BOX default dimensions: ',(OldH,OldW),Pos),
684 fail.
685 assert_visb_empty_svg_box_height_width(H,W,ViewBox,_Pos) :-
686 %add_message(visb_visualiser,'Setting VisB SVG_BOX default dimensions: ',(H,W,ViewBox),Pos),
687 assert(visb_empty_svg_box_height_width(H,W,ViewBox)).
688
689
690 % find DEFINITION with given prefix in name, evaluate it and return SVG_ID and attribute list:
691 % AllowSep = allow_seperation means that the record fields can be separated into static objects and dynamic updates
692 % and only static ones will be retained (dynamic ones dealt with later)
693 find_and_eval_visb_DEFINITION(DEFPREFIX, Kind, SVG_ID, AttrList,Desc, DefName, DefPos,EvalPos,
694 InlineObjects,AllowSep,ExpandedScope) :-
695 ? ( b_sorted_b_definition_prefixed(expression,DEFPREFIX,DefName,DefPos),
696 ? if(b_get_typed_definition(DefName,ExpandedScope,Body),true,
697 (add_visb_lint_message('Ignoring VisB DEFINITION due to errors',DefName,DefPos),fail))
698 ; special_backup(DEFPREFIX,Kind),
699 % also look at stored definitions (e.g., from static/dynamic separation of VISB_SVG_OBJECTS)
700 visb_special_definition(Kind,DefName,_Type,Body,_Class,DefPos)
701 ),
702 set_error_context(visb_error_context(definition,DefName,'all_attributes',DefPos)),
703 ? call_cleanup((get_typed_static_definition_with_constants_state(DefName,Body,
704 ResBody,DefPos,ConstState,InlineObjects,AllowSep),
705 (get_texpr_pos(ResBody,Pos0) -> true ; Pos0=DefPos), % this could be a part of the full definition body
706 get_visb_DEFINITION_svg_object(Kind,DefName,ResBody,Pos0,ConstState,SVG_ID,AttrList,Desc,EvalPos)),
707 clear_error_context).
708
709 special_backup('VISB_SVG_HOVERS',visb_hovers).
710
711 % evaluate a typed body expressions evaluating to a record or set of records
712 % and translate into SVG attribute lists:
713 get_visb_static_svg_object_for_typed_expr(Kind,DefName,Body,DefPos,SVG_ID,AttrList,Desc,InnerPos) :-
714 AllowSep=no_separation,
715 Inline=no_inlining,
716 get_typed_static_definition_with_constants_state(DefName,Body,ResBody,DefPos,ConstState,Inline,AllowSep),
717 get_visb_DEFINITION_svg_object(Kind,DefName,ResBody,DefPos,ConstState,SVG_ID,AttrList,Desc,InnerPos).
718
719
720 flatten_couple(b(couple(A,B),_,_)) --> !,flatten_couple(A),flatten_couple(B).
721 % we could also flatten union(A,B), but at the risk of duplicate warnings when the same element occurs in A and B
722 flatten_couple(A) --> [A].
723
724 get_typed_static_definition_with_constants_state(DefName,Body,ResBody,DefPos,ConstantsState,InlineObjects,AllowSep) :-
725 flatten_couple(Body,TupleList,[]),
726 % the VISB_SVG_OBJECT definition may consist of a tuple (Obj1,Obj2,...) to allow grouping
727 (TupleList = [_,_|_]
728 -> add_debug_message(visb_visualiser,'Decomposed VisB definition body tuple:',DefName,DefPos)
729 ; true),
730 ? nth1(DefNr,TupleList,TupleBody),
731 (get_texpr_pos(TupleBody,TuplePos) -> true ; TuplePos=DefPos),
732 get_typed_static_definition_with_constants_state3(DefName,DefNr,TupleBody,ResBody,TuplePos,
733 ConstantsState,InlineObjects,AllowSep).
734 get_typed_static_definition_with_constants_state3(DefName,DefNr,Body,ResBody,DefPos,ConstantsState,InlineObjects,AllowSep) :-
735 determine_type_of_visb_formula(Body,TIds,Class),
736 debug_format(19,'Detected VisB DEFINITION ~w (~w)~n',[DefName,Class]),
737 (%Class=requires_variables, % now also useful if event field present
738 AllowSep=allow_separation, % allowed for VISB_SVG_OBJECTS
739 ? if(separate_into_static_and_dynamic_part(DefName,DefNr,Body,StaticBody,DynamicBody,EventBody,HoverBody),
740 true,
741 (get_texpr_type(Body,Type),
742 (contains_events_or_hovers_field(Type)
743 -> add_warning(visb_visualiser,'Static/Dynamic separation failed for (required for events or hovers): ',DefName,DefPos)
744 % VISB_SVG_OBJECT definition contains events/hovers and as such requires separation; which failed here
745 ; add_debug_message(visb_visualiser,'Static/Dynamic separation failed or not useful for: ',DefName,DefPos)
746 ),
747 fail)),
748 determine_type_of_visb_formula(StaticBody,SIds,SClass),
749 get_unique_initial_state_for_visb(SClass,DefName,DefPos,SIds,ConstantsState)
750 -> Separated=true, ResBody=StaticBody,
751 add_debug_message(visb_visualiser,'Automatically separated fields into static and dynamic: ',DefName,DefPos),
752 %write('STATIC: '),translate:print_bexpr(StaticBody),nl, write('DYNAMIC: '),translate:print_bexpr(DynamicBody),nl,
753 assert_visb_udpate_def_body(visb_updates,DefName,DynamicBody,DefPos),
754 add_visb_events_from_def_body(visb_events,DefName,EventBody,DefPos),
755 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
756 ; get_unique_initial_state_for_visb(Class,DefName,DefPos,TIds,ConstantsState)
757 -> ResBody=Body
758 ; ResBody=Body,
759 (Class=requires_constants ->
760 get_texpr_ids(TIds,Ids),
761 % we could check if values of Ids are identical in all constants solutions
762 (is_concrete_constants_state_id(_)
763 -> BMsg='multiple solutions for used constants exist: '
764 ; BMsg='but no constants were found or setup yet: '
765 ),
766 ajoin(['DEFINITION ',DefName, ' requires constants but ',BMsg],Msg),
767 (get_a_constants_state(ConstantsState,StateID,InlineObjects)
768 -> (member(CstID,Ids),
769 other_constant_value_exists_for(CstID,ConstantsState,StateID)
770 -> add_warning(visb_visualiser,Msg,CstID,DefPos)
771 ; ajoin(['DEFINITION ',DefName,
772 ' requires constants and all SETUP_CONSTANTS solutions have same value thus far: '],Msg2),
773 % constraint-based checks or execute by predicate could later create others !
774 add_message(visb_visualiser,Msg2,Ids,DefPos)
775 )
776 ; add_error(visb_visualiser,Msg,Ids,DefPos), ConstantsState=[]
777 )
778 ; ConstantsState=[]
779 )
780 ),
781 (Class=requires_variables, Separated=false
782 -> get_texpr_ids(TIds,AIds),
783 include(b_is_variable,AIds,VIds),
784 ajoin_with_sep(VIds,',',SVids),
785 (get_preference(visb_allow_variables_for_objects,false)
786 -> ajoin(['Ignoring DEFINITION which requires variables ',SVids,': '],WMsg),
787 add_warning(visb_visualiser,WMsg,DefName,DefPos),fail
788 ; ConstantsState=[]
789 -> add_warning(visb_visualiser,'Ignoring DEFINITION which requires variables, could not find unique initial state: ',DefName,DefPos),fail
790 ; ajoin(['DEFINITION requires variables ',SVids,
791 '; exporting history to HTML may not work correctly'],WMsg),
792 add_visb_lint_message(WMsg,DefName,DefPos)
793 )
794 ; true).
795
796
797 % separate/split/filter VISB_SVG_OBJECTS definitions into a static part and a dynamic part depending on variables
798 % (aka updates/items)
799 separate_into_static_and_dynamic_part(DefName,DefNr,Body,StaticBody,DynamicBody,EventBody,HoverBody) :-
800 ? separate_static_dyn_aux(DefName,DefNr,[],[],Body,StaticBody,DynamicBody,EventBody,HoverBody).
801
802
803 rewrite_expression(let_expression(Ids,Exprs,Body),NewBody) :-
804 % currently we cannot process LET's here, expand them
805 replace_ids_by_exprs(Body,Ids,Exprs,NewBody). % see also expand_all_lets/2
806
807 separate_static_dyn_aux(DefName,DefNr,OuterQuantifiedIds,Path,b(Expr,_Type,_Info), Static,Dynamic,Event,Hover) :-
808 rewrite_expression(Expr,NewExpr),!,
809 separate_static_dyn_aux(DefName,DefNr,OuterQuantifiedIds,Path,NewExpr, Static,Dynamic,Event,Hover).
810 separate_static_dyn_aux(DefName,DefNr,OuterQuantifiedIds,Path,b(couple(A,B),_,_Info),
811 StaticCouple,DynamicCouple,EventCouple,HoverCouple) :- !,
812 separate_static_dyn_aux(DefName,DefNr,OuterQuantifiedIds,[0|Path],A,SA,DA,EA,HA),
813 separate_static_dyn_aux(DefName,DefNr,OuterQuantifiedIds,[1|Path],B,SB,DB,EB,HB),
814 create_couple(SA,SB,StaticCouple),
815 create_couple(DA,DB,DynamicCouple),
816 create_couple(EA,EB,EventCouple),
817 create_couple(HA,HB,HoverCouple).
818 separate_static_dyn_aux(DefName,DefNr,OuterQuantifiedIds,Path,TExpr,
819 b(StaticSetComp,set(ST),I),
820 b(DynamicSetComp,set(DT),I),
821 b(EventsSetComp,set(ET),I),
822 b(HoversSetComp,set(HT),I)) :-
823 ? bsyntaxtree:is_eventb_comprehension_set(TExpr,Ids,Pred,Expr),
824 (OuterQuantifiedIds = []
825 -> add_debug_message(visb_visualiser,'Top-level set comprehensions for VISB: ',Ids,TExpr)
826 ; add_message(visb_visualiser,'Nested set comprehensions for VISB: ',OuterQuantifiedIds,TExpr)
827 ),
828 !,
829 determine_type_of_visb_formula(b(exists(Ids,Pred),pred,[]),SIds,Class),
830 (get_unique_initial_state_for_visb(Class,DefName,Pred,SIds,_)
831 -> true % The predicate must be statically executable
832 ; time_out_for_node(root,O,_Type),
833 translate_operation_name(O,Op) ->
834 ajoin(['Due to TIME_OUT of ',Op,' the comprehension set domain cannot be evaluated: '],Msg),
835 add_warning(visb_visualiser,Msg,Pred,Pred),
836 % TODO: avoid other error messages that will occur after that
837 fail
838 ; add_visb_lint_message('Cannot statically evaluate comprehension set domain',Pred,Pred),
839 % at the moment we require the domain to be computable statically for both static/dynamic attributes
840 fail
841 ),
842 append(OuterQuantifiedIds,Ids,NewOuterQuantifiedIds),
843 ? separate_static_dyn_aux(DefName,DefNr,NewOuterQuantifiedIds,Path,Expr,
844 StaticRec,DynamicRec,EventRec,HoverRec),
845 get_texpr_type(StaticRec,ST),
846 get_texpr_type(DynamicRec,DT),
847 get_texpr_type(EventRec,ET),
848 get_texpr_type(HoverRec,HT),
849 bsyntaxtree:get_texpr_info(TExpr,I),
850 b_ast_cleanup:rewrite_event_b_comprehension_set(Ids,StaticRec,Pred, set(ST), StaticSetComp),
851 b_ast_cleanup:rewrite_event_b_comprehension_set(Ids,DynamicRec,Pred,set(DT), DynamicSetComp),
852 b_ast_cleanup:rewrite_event_b_comprehension_set(Ids,EventRec,Pred,set(ET), EventsSetComp),
853 b_ast_cleanup:rewrite_event_b_comprehension_set(Ids,HoverRec,Pred,set(HT), HoversSetComp).
854 separate_static_dyn_aux(DefName,DefNr,OuterQuantifiedIds,Path,b(rec(Fields),_,Info),
855 b(rec(StaticFields),record(SFT),Info), % VISB_OBJECTS (static)
856 b(UpdateRecWithDynamicFields,record(DFT),Info), % VISB_UPDATES (dynamic)
857 b(rec(AllEventFields),record(EFT),Info), % VISB_EVENTS
858 b(rec(AllHoverFields),record(HFT),Info) % VISB_HOVERS
859 ) :- !,
860 split_list(is_visb_event_field,Fields,EventFields,ObjectAndHoverFields),
861 (select(field(hovers,HoverRec),ObjectAndHoverFields,ObjectFields)
862 -> HoverFields = [field(hovers,HoverRec)] % record deconstructed in add_visb_hovers_from_definition
863 ; ObjectFields=ObjectAndHoverFields, HoverFields = []),
864 % 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
865 separate_fields(ObjectFields,StaticFields0,DynamicFields,DefName),
866 ? (member(field(svg_class,_SVG_Class),StaticFields0) -> true
867 ; member(field(svg_class,SVG_Class),DynamicFields)
868 -> add_warning(visb_visualiser,'SVG svg_class field is not static in: ',DefName,SVG_Class),
869 fail
870 ; add_warning(visb_visualiser,'No svg_class field in: ',DefName,Info),
871 fail
872 ),
873 ? (member(field(id,SVGID),StaticFields0)
874 -> (DynamicFields \= [] ; EventFields \= [] ; HoverFields \= [] % separation is useful for this record
875 ; Path \= [] % we are part of a couple; maybe other records have a dynamic,event or hover part; so proceed
876 ),
877 StaticFields = StaticFields0,
878 TStatic_SVGID = SVGID
879 ; member(field(id,SVGID),DynamicFields)
880 -> add_warning(visb_visualiser,'SVG id field is not static in: ',DefName,SVGID),
881 fail
882 ; OuterQuantifiedIds = []
883 -> gensym(svg_id,GenID),
884 ajoin(['Generated id ',GenID, ' for SVG object without id field in: '],Msg),
885 add_debug_message(visb_visualiser,Msg,DefName,Info),
886 SVGID = b(string(GenID),string,[]),
887 sort([field(id,SVGID) | StaticFields0],StaticFields)
888 ; % the record is quantified within a set comprehension; we need to compute the ID from OuterQuantifiedIds
889 % it has to be identical for VISB_SVG_OBJECTS and VISB_SVG_UPDATES
890 SVGID = b(ExtFunCall,string,[]),
891 convert_path_to_int(Path,IntPath),
892 PathExpr = b(integer(IntPath),integer,[]),
893 create_couple([b(string(DefName),string,[]),b(integer(DefNr),integer,[]),PathExpr|OuterQuantifiedIds],Tuple),
894 % add DefName and DefNr to avoid clash if other Definition has same quantified ids
895 ExtFunCall = external_function_call('SHA_HASH_HEX',[Tuple]),
896 add_debug_message(visb_visualiser,'Generated SHA_HASH_HEX call for id of SVG objects without id field in: ',DefName,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) :- write(assume_hover_can_set_visibility(E)),nl.
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 the name of a field for hovers inside a VISB_SVG_OBJECT record
978 is_visb_hover_field_name(hovers).
979 is_visb_hover_field_name(items). % enable items
980 %is_visb_hover_field_name(optional). % not needed ?
981 %is_visb_hover_field_name(override). % not needed ?
982
983 % check if the type of a VISB_SVG_OBJECTS expression requires separation for hovers/events
984 contains_events_or_hovers_field(set(X)) :- contains_events_or_hovers_field(X).
985 contains_events_or_hovers_field(couple(A,B)) :-
986 (contains_events_or_hovers_field(A) -> true ; contains_events_or_hovers_field(B)).
987 contains_events_or_hovers_field(record(F)) :- member(field(Name,_),F),
988 (is_visb_event_field_name(Name) -> true ; is_visb_hover_field_name(Name)).
989
990 get_field_type(field(Name,Expr),field(Name,T)) :- get_texpr_type(Expr,T).
991
992 % separate fields from a SVG/VISB_SVG_OBJECT record into static part and dynamic update expressions
993 separate_fields([],[],[],_).
994 separate_fields([field(Field,Expr)|T],[field(Field,Expr)|TS],TD,DefName) :-
995 is_static_expr(Expr,Field,DefName),!,
996 separate_fields(T,TS,TD,DefName).
997 separate_fields([field(Field,Expr)|T],[field(Field,Default)|TS],[field(Field,Expr)|TD],DefName) :-
998 requires_static_default_value(Field,Default), !,
999 separate_fields(T,TS,TD,DefName).
1000 separate_fields([H|T],TS,[H|TD],DefName) :-
1001 separate_fields(T,TS,TD,DefName).
1002
1003 % fields which require a static default value; here to set up child SVG objects of title
1004 % static default values could also be useful for hovers in general?
1005 requires_static_default_value(title,b(string('-title-not-set-'),string,[])).
1006
1007 % virtual SVG attributes which are translated to children tags/objects
1008 attribute_automatically_creates_children(title).
1009
1010 is_static_expr(Expr,Field,DefName) :-
1011 determine_type_of_visb_formula(Expr,_TIds,Class), % TODO pass local variables from exists above
1012 (Class=requires_nothing -> true
1013 ; Class=requires_constants,
1014 \+ multiple_concrete_constants_exist, % TODO: check if _TIds have multiple solutions
1015 is_concrete_constants_state_id(_) -> true
1016 ; ajoin(['Detected dynamic expression for field ',Field,' in ',DefName,': '],Msg),
1017 add_debug_message(visb_visualiser,Msg,Expr,Expr),fail
1018 ).
1019
1020 % --------
1021
1022
1023 extract_attribute_from_record(DefPos,field(OrigName,Value),svg_attribute(Name,SVal)) :-
1024 opt_rewrite_field_name(OrigName,Name),
1025 extract_attribute_value(DefPos,Name,Value,SVal).
1026 extract_attribute_from_record(DefPos,F,_) :-
1027 add_error(bvisualiser,'Extract SVG attribute failed: ',F,DefPos),fail.
1028
1029 % extract a value for a particular field Name
1030 extract_attribute_value(DefPos,Name,Value,SVal) :-
1031 (deconstruct_singleton_set(Name,Value,Element)
1032 -> Element \= '$optional_field_absent',
1033 extract_attr_value(Name,Element,SVal,DefPos)
1034 ; extract_attr_value(Name,Value,SVal,DefPos)
1035 ).
1036
1037
1038 % in TLA+ mode optional record fields have {TRUE|->VALUE} rather than VALUE
1039 % this can also be useful in B to allow mixing different SVG records in a set
1040 % for Alloy mode we may want to also support singleton sets as scalars
1041 deconstruct_singleton_set(Name,Set,Res) :-
1042 singleton_set(Set,El),
1043 detect_partial_records_for_field(Name),
1044 (El=(pred_true,El2)
1045 -> Val=El2 % TLA2B encoding for optional fields that are present
1046 ; Val=El), % Alloy
1047 !,
1048 Res = Val.
1049 deconstruct_singleton_set(Name,[],Res) :-
1050 detect_partial_records_for_field(Name),
1051 Res = '$optional_field_absent'.
1052
1053 detect_partial_records_for_field(points) :- !, fail. % can be set of points
1054 detect_partial_records_for_field(children) :- !, fail. % children field for groups is a set of ids
1055 detect_partial_records_for_field(Name) :-
1056 is_svg_number_attribute(Name),!. % sets never sensible as a numerical value
1057 detect_partial_records_for_field(Name) :- is_id_or_text_attribute(Name),!. % ditto for ids
1058 detect_partial_records_for_field(Name) :- is_svg_color_attribute(Name),!. % ditto for colors
1059 detect_partial_records_for_field(_) :-
1060 \+ classical_b_mode. % TODO: check that we are in TLA or Alloy mode?
1061 % TODO: ensure ProB2 sets animation minor mode for TLA
1062
1063
1064 extract_attr_value(Name,Value,SVal,DefPos) :-
1065 is_svg_number_attribute(Name),!, % we could try and extract svg_class from attribute list above
1066 (get_number_from_bvalue(Value,NrVal)
1067 -> SVal=NrVal % convert to atom?
1068 ; b_value_to_string(Value,SVal),
1069 (is_special_svg_number_form(SVal) -> true
1070 ; atom_codes(SVal,CC),
1071 safe_number_codes(_NrVal,CC) -> true
1072 ; ajoin(['The value of the SVG attribute "',Name,
1073 '" is not a number: '],Msg),
1074 add_warning(visb_visualiser,Msg,SVal,DefPos)
1075 )
1076 ).
1077 extract_attr_value(children,Value,SVal,DefPos) :- !,
1078 (is_set_value(Value,extract_attr_value)
1079 -> (try_expand_custom_set_with_catch(Value,ExpandedSet,extract_attr_value),
1080 maplist(b_value_to_id_string,ExpandedSet,SVal) -> true
1081 ; add_warning(visb_visualiser,'The children attribute should be a finite set of identifiers: ',Value,DefPos),
1082 SVal=[]
1083 )
1084 ; add_warning(visb_visualiser,'The children attribute should be a set of identifiers: ',Value,DefPos),
1085 SVal=[]).
1086 extract_attr_value(points,Value,SVal,DefPos) :- % Class should be polygon or polyline
1087 % automatically translate sequences or sets of pairs of numbers to SVG string format
1088 (Value = [(Nr,_)|_] ; Value = avl_set(node((Nr,_),_,_,_,_))),
1089 is_number(Nr), % TODO: check typing
1090 svg_points(Value,Str,DefPos,no_wf_available),!,
1091 string(SVal)=Str.
1092 extract_attr_value(points,Value,SVal,_DefPos) :- Value = [],!, SVal = ''.
1093 extract_attr_value(visibility,Value,SVal,DefPos) :- !,
1094 % convert TRUE -> visible, FALSE -> hidden
1095 ( Value=pred_true -> TxtVal='visible'
1096 ; Value=pred_false -> TxtVal='hidden'
1097 ; b_value_to_text_string(Value,TxtVal),
1098 ? (member(TxtVal,[collapse,hidden,visible]) -> true
1099 ; add_warning(visb_visualiser,'Value of SVG attribute "visibility" must be collapse,hidden or visible and not: ',TxtVal,DefPos))
1100 ),
1101 SVal=TxtVal.
1102 extract_attr_value(Name,Value,_,DefPos) :-
1103 check_svg_attribute_value(Name,Value,DefPos),fail.
1104 extract_attr_value(Name,Value,SVal,_) :-
1105 ? is_id_or_text_attribute(Name),!,
1106 (is_text_attribute(Name)
1107 -> b_value_to_text_string(Value,SVal)
1108 ; b_value_to_id_string(Value,SVal)). % concatenates e.g. pairs of strings to string without ( |-> )
1109 extract_attr_value(Attr,RawValue,ResValue,_DefPos) :- raw_value_attribute(Attr),!, % keep value intact
1110 ResValue = RawValue.
1111 extract_attr_value(_Name,Value,SVal,_DefPos) :-
1112 b_value_to_string(Value,SVal).
1113
1114
1115 is_number(int(_)).
1116 is_number(term(floating(_))).
1117
1118 % do not convert to string; these are treated separately
1119 raw_value_attribute(hovers).
1120 raw_value_attribute(events).
1121
1122
1123 % evaluate a DEFINITION to a set of B records representing SVG objects
1124 % returns a possibly refined sub-position corresponding to generated SVG objects as last argument
1125 get_visb_DEFINITION_svg_object(SpecialClass,DefName,Body,_DefPos,ExpandedState,SVG_ID,AttrList,Desc,InnerPos) :-
1126 get_preference(visb_show_debug_infos,true),
1127 bsyntaxtree:is_eventb_comprehension_set(Body,Ids,Pred,Expr),
1128 % try and separate couple in Expr so that we have better position info for source of VISB_SVG_OBJECTS
1129 Body = b(_,Type,II),
1130 Expr = b(couple(_,_),_,_),
1131 !,
1132 couple_member(NewExpr,Expr), % evaluate each part of the couple in isolation, with better position info
1133 get_texpr_pos(NewExpr,InnerPos),
1134 b_ast_cleanup:rewrite_event_b_comprehension_set(Ids,NewExpr,Pred, Type, NewBody),
1135 get_visb_DEF_svg_object_aux(SpecialClass,DefName,b(NewBody,Type,II),InnerPos,ExpandedState,SVG_ID,AttrList,Desc).
1136 get_visb_DEFINITION_svg_object(SpecialClass,DefName,Body,DefPos,ExpandedState,SVG_ID,AttrList,Desc,DefPos) :-
1137 ? get_visb_DEF_svg_object_aux(SpecialClass,DefName,Body,DefPos,ExpandedState,SVG_ID,AttrList,Desc).
1138
1139 couple_member(TExpr,b(couple(A,B),_,_)) :- !, (couple_member(TExpr,A) ; couple_member(TExpr,B)).
1140 couple_member(TExpr,TExpr).
1141
1142 get_visb_DEF_svg_object_aux(SpecialClass,DefName,Body,DefPos,ExpandedState,SVG_ID,AttrList,Desc) :-
1143 evaluate_visb_formula(Body,DefName,'',ExpandedState,ResValue,DefPos),
1144 flex_expand(ResValue,DefName,DefPos,Expanded,[]),
1145 (Expanded = [] -> add_message(visb_visualiser,'Empty set of SVG object records: ',DefName,DefPos)
1146 ; Expanded =[Record|_] ->
1147 (get_VISB_record_fields(Record,Fs)
1148 % TODO: as we now can have different type of records, check in flex_expand below
1149 ? -> (member(field(id,_),Fs)
1150 -> true
1151 ; add_message(visb_visualiser,'DEFINITION needs an `id` field if you want to use updates: ',DefName,DefPos)
1152 )
1153 ; ajoin(['DEFINITION ', DefName,' should evaluate to a set of records or tuples of records: '],Msg),
1154 add_warning(visb_visualiser,Msg,Record,DefPos)
1155 )
1156 ),
1157 ? member(Records,Expanded),
1158 get_VISB_record_fields(Records,Fields),
1159 ? (select(field(id,VID),Fields,F1)
1160 -> extract_attribute_value(DefPos,id,VID,SVG_ID)
1161 ; gensym(svg_id,SVG_ID), F1=Fields),
1162 (select(field(comment,CC),F1,F2), b_value_to_string(CC,Desc) -> true
1163 ; Desc = '', F2=F1),
1164 (SpecialClass=visb_updates, member(field(visibility,VV),F2),
1165 is_invisible(VV),
1166 \+ visb_has_visibility_hover(SVG_ID) % check for hover which may make object visible
1167 -> AttrList=[svg_attribute(visibility,'hidden')] % do not transmit updates
1168 ; include_maplist(extract_attribute_from_record(DefPos),F2,AttrList0),
1169 exclude(check_unsupported_special_visb_attribute(SpecialClass,DefPos),AttrList0,AttrList),
1170 ? (select(svg_attribute(svg_class,SVG_Class),AttrList,A2)
1171 -> maplist(check_attribute_is_supported(SVG_Class,DefPos),A2)
1172 ; true)
1173 ).
1174
1175 is_invisible(string(hidden)). % also treat collapse ?
1176 is_invisible(pred_false).
1177
1178 % expand nested tuples/sets to a single list of SVG records (possibly of different types)
1179 flex_expand(Value,DefName,Pos) --> {is_custom_explicit_set(Value)},!,
1180 {try_expand_custom_set_with_catch(Value,ExpandedSet,flex_expand),
1181 (is_custom_explicit_set(ExpandedSet)
1182 -> ajoin(['Could not expand set of SVG object records or tuples thereof for ',DefName,': '],Msg),
1183 add_warning(visb_visualiser,Msg,Value,Pos),
1184 fail
1185 ; true)},
1186 flex_expand(ExpandedSet,DefName,Pos).
1187 flex_expand([],_,_) --> !, [].
1188 flex_expand(L,_DefName,_Pos) --> {L =[(string(_),string(_))|_]}, !,
1189 [L]. % is probably a partial function {"id" |-> ,...}
1190 flex_expand([H|T],DefName,Pos) --> !, flex_expand(H,DefName,Pos), l_flex_expand(T,DefName,Pos).
1191 flex_expand((A,B),DefName,Pos) --> !, flex_expand(A,DefName,Pos), flex_expand(B,DefName,Pos).
1192 flex_expand(T,_,_) --> [T].
1193
1194 l_flex_expand([],_,_) --> !, [].
1195 l_flex_expand([H|T],DefName,Pos) --> !, flex_expand(H,DefName,Pos), l_flex_expand(T,DefName,Pos).
1196 l_flex_expand(T,_,_) --> [T].
1197
1198 flex_member(X,SetPairVal,DefName,Pos) :- flex_expand(SetPairVal,DefName,Pos,List,[]), member(X,List).
1199
1200
1201 % get the fields of a B value record
1202 % also transparently handles alternative representations, like a function from STRING to STRING
1203 get_VISB_record_fields(rec(Fields),Res) :- !, Res=Fields.
1204 get_VISB_record_fields(StringFunction,Fields) :-
1205 is_set_value(StringFunction,get_VISB_record_fields),
1206 try_expand_custom_set_with_catch(StringFunction,Expanded,get_VISB_record_fields),
1207 % TODO: check we have no duplicates
1208 maplist(convert_to_field,Expanded,Fields).
1209 % TODO: support records as generated by READ_XML:
1210 % rec(attributes:{("fill"|->"#90ee90"),("height"|->"360px"),("id"|->"background_rect"),("width"|->"600px"),("x"|->"1px"),("y"|->"2px")},element:"rect",meta:{("xmlLineNumber"|->"3")},pId:5,recId:6)
1211 % for <rect height="360px" x="1px" y="2px" id="background_rect" width="600px" fill="#90ee90"></rect>
1212
1213 convert_to_field((string(FieldName),Value),field(FieldName,Value)).
1214 % TODO: maybe handle enumerated set values as field names
1215
1216
1217 % already extract and type-check VISB_SVG_UPDATES definitions
1218 precompile_svg_object_updates(ExpandedScope,JsonFileContext) :-
1219 b_sorted_b_definition_prefixed(expression,'VISB_SVG_UPDATES',DefName,DefPos),
1220 b_get_typed_definition(DefName,ExpandedScope,TypedExpr),
1221 assert_visb_udpate_def_body(visb_updates,DefName,TypedExpr,DefPos),
1222 add_children_for_visb_update_def_body(TypedExpr,DefName,JsonFileContext),
1223 fail.
1224 precompile_svg_object_updates(_,_).
1225
1226 % assert VisB updates or hovers from B DEFINITION,
1227 % either from VISB_SVG_UPDATES or hovers or dynamic parts of VISB_SVG_OBJECTS:
1228 assert_visb_udpate_def_body(_Kind,DefName,TypedExpr,_DefPos) :-
1229 TypedExpr=b(rec([field(id,_)]),_,Info),!, % can happen when all fields are static
1230 add_debug_message(visb_visualiser,'Useless update/hover (just id field): ',DefName,Info).
1231 assert_visb_udpate_def_body(Kind,DefName,b(couple(A,B),_,_),DefPos) :- !,
1232 % separate couples into individual expressions; in case of WD errors we have more localised errors/problems
1233 assert_visb_udpate_def_body(Kind,DefName,A,DefPos),
1234 assert_visb_udpate_def_body(Kind,DefName,B,DefPos).
1235 assert_visb_udpate_def_body(Kind,DefName,TypedExpr,DefPos) :-
1236 get_texpr_type(TypedExpr,Type),
1237 determine_type_of_visb_formula(TypedExpr,_,FormulaClass),
1238 debug_format(19,'Detected ~w: ~w (~w)~n',[Kind,DefName,FormulaClass]),
1239 assertz(visb_special_definition(Kind,DefName,Type,TypedExpr,FormulaClass,DefPos)),
1240 check_visb_update_type(Kind,Type,DefName,unknown_svg_class,DefPos),
1241 static_check_dynamic_update_def_body(TypedExpr).
1242
1243
1244 % check if we need to add virtual children for an VISB_SVG_UPDATES body:
1245 % (e.g., for title updates to SVG objects coming from an SVG file)
1246 add_children_for_visb_update_def_body(b(couple(A,B),_,_),DefName,JsonFile) :- !,
1247 (add_children_for_visb_update_def_body(A,DefName,JsonFile)
1248 ;
1249 add_children_for_visb_update_def_body(B,DefName,JsonFile)).
1250 add_children_for_visb_update_def_body(b(rec(Fields),_,_),DefName,JsonFile) :-
1251 select(field(id,TParentId),Fields,F2),!,
1252 is_static_expr(TParentId,id,DefName), % we need a static value to create children for it
1253 TParentId = b(_,_,Info),
1254 evaluate_static_visb_formula(TParentId,DefName,'',[],ResValue,Info),
1255 b_value_to_id_string(ResValue,ParentId),
1256 \+ svg_id_exists(ParentId),
1257 (\+ get_default_visb_svg_file(_,_), % cannot call no_svg_file_available yet
1258 JsonFile = '', % No JSON file to be loaded after, which could add SVG file or objects
1259 \+ special_definition_exists('VISB_SVG_CONTENTS')
1260 -> ajoin(['Unknown VISB_SVG_OBJECT with id ',ParentId,' in: '],Msg),
1261 add_warning(visb_visualiser,Msg,DefName,Info)
1262 ; select(field(title,TTitle),F2,_),
1263 (TTitle = b(string(Title),_,_) -> true ; Title = 'no-title-set'),
1264 get_texpr_pos(TTitle,Pos),
1265 add_virtual_title_object(Title,DefName,Pos,TitleID),
1266 assert_visb_svg_child(ParentId,Pos,TitleID),
1267 assert(visb_svg_child_of_object_from_svg_file(TitleID))
1268 ),
1269 fail.
1270 % TODO: set comprehensions like {x•x:Obj|rec(id=("obj",x), title=....)}
1271 % TODO: support sets and warn when ID is not statically known?
1272
1273 % assert VisB events or hovers from B DEFINITION, from part of VISB_SVG_OBJECTS:
1274 % supporting event: attribute and optional predicate attribute
1275 % Kind = visb_events %or visb_hovers
1276 add_visb_events_from_def_body(Kind,DefName,Body,DefPos) :-
1277 get_texpr_type(Body,Type),
1278 \+ empty_update_or_hover_type(Type), % at least one more field than just id field
1279 get_visb_static_svg_object_for_typed_expr(Kind,DefName,Body,DefPos,SVG_ID,AttrList,Desc,InnerPos),
1280 add_visb_object_from_definition(Kind, SVG_ID, AttrList, Desc, DefName, InnerPos),
1281 fail.
1282 add_visb_events_from_def_body(_,_,_,_).
1283
1284 empty_update_or_hover_type(record(Fields)) :- !, Fields \= [_,_|_]. % at least one more field than just id field
1285 empty_update_or_hover_type(set(X)) :- !, empty_update_or_hover_type(X).
1286 empty_update_or_hover_type(couple(A,B)) :- !, empty_update_or_hover_type(A), empty_update_or_hover_type(B).
1287
1288 get_svg_object_updates_from_definitions(ExpandedBState,SVG_ID,SvgAttribute,Value,Pos) :-
1289 ? visb_special_definition(visb_updates,DefName,_Type,BodyTypedExpr,_Class,DefPos),
1290 ? get_visb_DEFINITION_svg_object(visb_updates,DefName,BodyTypedExpr,DefPos,ExpandedBState,SVG_ID,AttrList,_Desc,Pos),
1291 ? member(svg_attribute(SvgAttribute,Value),AttrList).
1292
1293 % check types of VisB updates
1294 check_visb_update_type(Kind,Type,DefName,Class,DefPos) :-
1295 get_update_record_fields_type(Type,Fields),
1296 % other types are STRING +-> STRING, ...; this will be checked in get_visb_DEFINITION_svg_object
1297 (memberchk(field('svg_class',_),Fields)
1298 -> add_warning(visb_visualiser,'VisB updates should not set svg_class:',DefName,DefPos)
1299 ; true),
1300 ? member(field(Name,FieldType),Fields),
1301 (Name = trigger_id ->
1302 (Kind=visb_hovers -> true ;
1303 add_warning(visb_visualiser,'Attribute trigger_id can only be used for hovers:',DefName,DefPos)
1304 )
1305 ; check_attribute_type(FieldType,Name,DefName,Class,DefPos)
1306 ),
1307 fail.
1308 check_visb_update_type(_,_,_,_,_).
1309
1310 % get a fields type list from a type
1311 get_update_record_fields_type(set(X),Fields) :- !,
1312 get_update_record_fields_type(X,Fields).
1313 get_update_record_fields_type(record(Fields),R) :- !, R=Fields.
1314 get_update_record_fields_type(couple(A,B),Fields) :-
1315 (get_update_record_fields_type(A,Fields)
1316 ; get_update_record_fields_type(B,Fields)).
1317
1318
1319 % check B type of a field for an SVG update or object
1320 check_attribute_type(Type,Name,DefName,Class,DefPos) :- alternative_spelling(Name,AName),!,
1321 check_attribute_type(Type,AName,DefName,Class,DefPos).
1322 check_attribute_type(Type,Name,DefName,Class,DefPos) :- Class \= unknown_svg_class,
1323 check_is_number_attribute(Name,Class,DefPos),!,
1324 illegal_number_type(Type),
1325 ajoin(['Type of field ',Name,' of ', DefName, ' is not a number: '],Msg),
1326 pretty_type(Type,TS),
1327 add_warning(visb_visualiser,Msg,TS,DefPos).
1328 check_attribute_type(Type,Name,DefName,_,DefPos) :-
1329 is_svg_color_attribute(Name),!,
1330 illegal_col_type(Type),
1331 ajoin(['Type of field ',Name,' of ', DefName, ' is not a color: '],Msg),
1332 pretty_type(Type,TS),
1333 add_warning(visb_visualiser,Msg,TS,DefPos).
1334 check_attribute_type(_Type,Name,_DefName,Class,DefPos) :-
1335 check_attribute_name_is_supported(Class,Name,DefPos).
1336
1337 illegal_nr_or_col_type(boolean).
1338 illegal_nr_or_col_type(set(_)).
1339 illegal_nr_or_col_type(seq(_)).
1340 illegal_nr_or_col_type(record(_)).
1341 illegal_nr_or_col_type(couple(A,B)) :- (illegal_nr_or_col_type(A) -> true ; illegal_nr_or_col_type(B)).
1342 % check if couple types can work by concatenating string representations
1343
1344 illegal_col_type(X) :- illegal_nr_or_col_type(X),!.
1345 illegal_col_type(real).
1346 % integer ? or can we map integers to colours using a color scheme like in DOT?
1347
1348 illegal_number_type(X) :- illegal_nr_or_col_type(X),!.
1349 %illegal_number_type(global(_)). % what if we use a global set with weird constants using back-quotes ?
1350
1351 % ----------------
1352
1353 % parse and load an individual JSON VisB item, e.g, :
1354 % { "name":"xscale",
1355 % "value" : "(100.0 / real(TrackElementNumber))"
1356 % }
1357
1358 process_json_definition(File,json(List)) :-
1359 (get_attr_true(ignore,List,File) -> true % ignore this definition
1360 ; process_json_def_lst(File,List)).
1361
1362
1363 process_json_def_lst(File,List) :-
1364 force_del_attr_with_pos(name,List,string(ID),L1,File,NamePos),
1365 force_del_attr_with_pos(value,L1,string(Formula),L2,File,VPos),
1366 debug_format(19,' Processing definition for ~w with value-formula (lines ~w):~w~n',[ID,VPos,Formula]),
1367 !,
1368 set_gen_parse_errors(L2,VPos,GenParseErrors), % treat optional attribute
1369 process_json_definition(ID,NamePos,Formula,VPos,GenParseErrors).
1370 process_json_def_lst(File,List) :- get_pos_from_list(List,File,Pos),
1371 add_error(visb_visualiser,'Illegal VisB Definition:',List,Pos).
1372
1373 % we could also load a classical B Definition file and process its definitions like this:
1374 process_json_definition(ID,NamePos,Formula,VPos,GenParseErrors) :-
1375 atom_codes(Formula,FCodes),
1376 set_error_context(visb_error_context(definition,ID,'value',VPos)),
1377 (b_get_definition_name_with_pos(ID,_Arity,_DefType,_DPos)
1378 -> add_warning(visb_visualiser,'Ignoring VisB definition, DEFINITION of the same name already exists:',ID,NamePos)
1379 ; parse_expr(FCodes,TypedExpr,GenParseErrors)
1380 -> add_visb_json_definition(ID,TypedExpr,VPos)
1381 ; GenParseErrors=false -> formatsilent('Ignoring optional VisB definition for ~w due to error in B formula~n',[ID])
1382 ; add_error(visb_visualiser,'Cannot parse or typecheck VisB formula for definition',ID,VPos)
1383 ),
1384 clear_error_context.
1385
1386 add_visb_json_definition(ID,TypedExpr,VPos) :-
1387 get_texpr_type(TypedExpr,Type),
1388 determine_type_of_visb_formula(TypedExpr,TIds,Class), %write(type(ID,Class,TIds)),nl,
1389 (try_eval_static_def(Class,'static definition', ID,TypedExpr,TIds,StaticValue,VPos)
1390 -> get_texpr_type(TypedExpr,Type),StaticValueExpr = b(value(StaticValue),Type,[]),
1391 assert_visb_json_definition(ID,Type,StaticValueExpr,TIds,Class,VPos)
1392 ; assert_visb_json_definition(ID,Type,TypedExpr,TIds,Class,VPos)
1393 ).
1394
1395 % assert a VisB definition stemming from the JSON definitions section:
1396 assert_visb_json_definition(DefName,Type,TypedExpr,UsedTIds,Class,DefPos) :-
1397 ? (is_special_visb_def_name(DefName,SpecialClass) -> true ; SpecialClass = regular_def),
1398 assertz(visb_definition(DefName,Type,TypedExpr,Class,DefPos,SpecialClass)),
1399 (SpecialClass \= regular_def
1400 -> formatsilent('Detected special ~w definition ~w (~w)~n',[SpecialClass,DefName,Class]),
1401 add_special_json_definition(SpecialClass,DefName,Type,TypedExpr,UsedTIds,Class,DefPos)
1402 ; true
1403 ).
1404
1405 % register some special definitions, in which a set of objects/hovers/updates can be specified
1406 % by a single definition returning a set of records
1407 add_special_json_definition(visb_updates,DefName,Type,TypedExpr,_,Class,DefPos) :- !,
1408 check_visb_update_type(visb_updates,Type,DefName,Class,DefPos),
1409 assertz(visb_special_definition(visb_updates,DefName,Type,TypedExpr,Class,DefPos)). % will be evaluated later
1410 add_special_json_definition(visb_contents,DefName,Type,TypedExpr,_,Class,DefPos) :- !,
1411 assertz(visb_special_definition(visb_contents,DefName,Type,TypedExpr,Class,DefPos)).
1412 add_special_json_definition(visb_box,DefName,Type,TypedExpr,_,Class,DefPos) :- !,
1413 assertz(visb_special_definition(visb_box,DefName,Type,TypedExpr,Class,DefPos)).
1414 add_special_json_definition(visb_objects,DefName,_Type,TypedExpr,_UsedTIds,_Class,DefPos) :- !,
1415 AllowSep=allow_separation, % TODO: we re-determine the class and used ids below:
1416 get_typed_static_definition_with_constants_state(DefName,TypedExpr,ResBody,DefPos,CS,no_inlining,AllowSep),
1417 (get_visb_DEFINITION_svg_object(visb_objects,DefName,ResBody,DefPos,CS,SVG_ID,AttrList,Desc,InnerPos),
1418 %formatsilent('Adding ~w : ~w (from ~w)~n',[visb_objects,SVG_ID,DefName]),
1419 add_visb_object_from_definition(visb_objects, SVG_ID, AttrList, Desc, DefName, InnerPos),
1420 fail ; true).
1421 add_special_json_definition(SpecialClass,DefName,_Type,TypedExpr,UsedTIds,Class,DefPos) :-
1422 (get_unique_initial_state_for_visb(Class,DefName,DefPos,UsedTIds,ConstantsState) -> true
1423 ; ConstantsState=[]),
1424 get_static_visb_state(ConstantsState,FullState), % add static VisB Defs
1425 (Class=requires_variables,
1426 (get_preference(visb_allow_variables_for_objects,false) ; ConstantsState=[])
1427 -> add_warning(visb_visualiser,'Ignoring VisB definition which requires variables:',DefName,DefPos)
1428 ; get_visb_DEFINITION_svg_object(SpecialClass,DefName,TypedExpr,DefPos,FullState,SVG_ID,AttrList,Desc,InnerPos),
1429 %formatsilent('Adding ~w : ~w (from ~w)~n',[SpecialClass,SVG_ID,DefName]),
1430 add_visb_object_from_definition(SpecialClass, SVG_ID, AttrList, Desc, DefName, InnerPos)
1431 ; true).
1432
1433 is_special_visb_def_name(DefName,visb_updates) :- atom_concat('VISB_SVG_UPDATES',_,DefName).
1434 is_special_visb_def_name(DefName,visb_hovers) :- atom_concat('VISB_SVG_HOVERS',_,DefName).
1435 is_special_visb_def_name(DefName,visb_objects) :- atom_concat('VISB_SVG_OBJECTS',_,DefName).
1436 is_special_visb_def_name(DefName,visb_contents) :- atom_concat('VISB_SVG_CONTENTS',_,DefName).
1437 is_special_visb_def_name(DefName,visb_events) :- atom_concat('VISB_SVG_EVENTS',_,DefName).
1438 is_special_visb_def_name('VISB_SVG_BOX',visb_box).
1439 % TODO: maybe provide VISB_HTML_CONTENTS which appear after the SVG
1440
1441 % evaluate static VisB defs only once or evaluate expressions in svg_objects and loop bounds
1442 eval_static_def(Class,VisBKind,ID,TypedExpr,UsedTIds,StaticValue,VPos) :-
1443 get_unique_initial_state_for_visb(Class,ID,VPos,UsedTIds,ConstantsState),
1444 evaluate_static_visb_formula(TypedExpr,VisBKind,ID,ConstantsState,StaticValue,VPos).
1445
1446 % only evaluate statically if possible; no warnings/messages if not possible (just fail)
1447 try_eval_static_def(requires_variables,_VisBKind,_ID,_TypedExpr,_UsedTIds,_StaticValue,_VPos) :- !,
1448 fail. % do not try to evaluate statically; events will change the variable values anyway
1449 try_eval_static_def(Class,VisBKind,ID,TypedExpr,UsedTIds,StaticValue,VPos) :-
1450 % TODO: disable messages for multiple constants values; just fail
1451 eval_static_def(Class,VisBKind,ID,TypedExpr,UsedTIds,StaticValue,VPos).
1452
1453 % check if a unique constant value exists for a model
1454 get_unique_initial_state_for_visb(requires_nothing,_,_,_,State) :- !, State=[].
1455 get_unique_initial_state_for_visb(Class,DefName,DefPos,_,State) :-
1456 \+ multiple_concrete_constants_exist,
1457 is_concrete_constants_state_id(StateID),!,
1458 (Class=requires_variables
1459 -> get_preference(visb_allow_variables_for_objects,true),
1460 unique_initialisation_id_exists_from(StateID,DefName,DefPos,State)
1461 % Note: variable can still be modified by other events later, e.g., in ProB2-UI
1462 ; visited_expression(StateID,StateTerm),
1463 state_corresponds_to_set_up_constants_only(StateTerm,State)).
1464 get_unique_initial_state_for_visb(requires_constants,DefName,DefPos,Ids,State) :- Ids \= all,
1465 % try and see if all values for Ids are the same; TODO: also support requires_variables
1466 is_concrete_constants_state_id(StateID),!,
1467 visited_expression(StateID,StateTerm),
1468 state_corresponds_to_set_up_constants_only(StateTerm,State),
1469 (member(C,Ids), get_texpr_id(C,CstID),
1470 other_constant_value_exists_for(CstID,State,StateID)
1471 -> ajoin(['Multiple values for constant ',CstID, ' in context of'],Msg),
1472 add_visb_lint_message(Msg,DefName,DefPos),fail
1473 ; true).
1474
1475 get_a_constants_state(State,StateID,inline_objects(SingleStateId)) :-
1476 get_constants_state_id_for_id(SingleStateId,StateID),!,
1477 visited_expression(StateID,StateTerm),
1478 state_corresponds_to_set_up_constants_only(StateTerm,State).
1479 get_a_constants_state(State,StateID,InlineObjects) :-
1480 check_inlining(InlineObjects),
1481 is_concrete_constants_state_id(StateID),!,
1482 visited_expression(StateID,StateTerm),
1483 state_corresponds_to_set_up_constants_only(StateTerm,State).
1484
1485 check_inlining(no_inlining) :- !.
1486 check_inlining(inline_objects(_SingleStateId)) :- !.
1487 check_inlining(X) :- add_internal_error('Invalid inlining value:',check_inlining(X)).
1488
1489
1490 other_constant_value_exists_for(CstID,State,StateId) :-
1491 lookup_value_for_existing_id(CstID,State,Val1),
1492 is_concrete_constants_state_id(StateId2), StateId2 \= StateId,
1493 visited_expression(StateId2,StateTerm2),
1494 state_corresponds_to_set_up_constants_only(StateTerm2,State2),
1495 lookup_value_for_existing_id(CstID,State2,Val2),
1496 Val2 \= Val1.
1497
1498
1499 unique_initialisation_id_exists_from(FromStateId,DefName,DefPos,State) :-
1500 transition(FromStateId,_,StateID),!,
1501 (transition(FromStateId,_,StateID2),
1502 StateID2 \= StateID
1503 -> ajoin(['Multiple initialisations exists (state ids ',StateID,',',StateID2,') for'],Msg),
1504 add_visb_lint_message(Msg,DefName,DefPos),fail
1505 ; true),
1506 visited_expression(StateID,StateTerm),
1507 state_corresponds_to_initialised_b_machine(StateTerm,State).
1508
1509 parse_expr_for_visb(Formula,JsonList,Pos,TypedExpr) :-
1510 set_gen_parse_errors(JsonList,Pos,GenParseErrors),
1511 parse_expr(Formula,TypedExpr,GenParseErrors).
1512
1513 set_gen_parse_errors(JSonList,Pos,GenParseErrors) :-
1514 (get_attr(optional,JSonList,_)
1515 -> GenParseErrors=false
1516 ; %get_pos_from_list(JSonList,File,Position),
1517 GenParseErrors=gen_parse_errors_for(Pos)).
1518
1519 % ----------------
1520
1521 % parse and load an individual JSON SVG object listed under svg_objects, e.g, :
1522 % {
1523 % "svg_class":"rect",
1524 % "id":"train_rect",
1525 % "x":"0",
1526 % "y":"0",
1527 % "comment":"..."
1528 % },
1529 process_json_svg_object(File,Json) :-
1530 process_repeat(0,Json,File,add_visb_json_svg_object).
1531
1532 add_visb_json_svg_object(File,json(List)) :- get_attr_true(ignore,List,File), !. % ignore this item
1533 add_visb_json_svg_object(File,json(List)) :-
1534 (force_del_attr_with_pos(svg_class,List,string(SVG_Class),L1,File,Pos1) -> true % shape: line, rect, ...
1535 ; infer_svg_class(List,SVG_Class,File,Pos1)
1536 -> add_visb_lint_message('Inferred svg_class',SVG_Class,Pos1),L1=List),
1537 force_del_attr(id,L1,string(ID),L2,File),
1538 (del_attr(comment,L2,string(Desc),JsonList3) -> true ; Desc = '', JsonList3=L2),
1539 debug_format(19,' Creating new SVG object ~w with id:~w~n',[SVG_Class,ID]),
1540 add_debug_message(visb_visualiser,'New object: ',ID,Pos1),
1541 % TODO: we could pre-process all attributes not depending on %0, %1, ...
1542 maplist(get_svg_attr(SVG_Class,File),JsonList3,AttrList),
1543 %formatsilent('Adding SVG Object ~w with ID ~w (~w): ~w~n',[SVG_Class,ID,Desc,AttrList]),
1544 assert_visb_svg_object(ID,SVG_Class,AttrList,Desc,'JSON',Pos1),
1545 !.
1546 add_visb_json_svg_object(File,Json) :-
1547 !,
1548 get_pos_from_list(Json,File,Pos),
1549 add_error(visb_visualiser,'Illegal VisB additional SVG object:',Json,Pos).
1550
1551 infer_svg_class(List,line,File,Pos) :- get_attr_with_pos(x1,List,_,File,Pos),!.
1552 infer_svg_class(List,circle,File,Pos) :- get_attr_with_pos(r,List,_,File,Pos),!.
1553 infer_svg_class(List,rect,File,Pos) :- get_attr_with_pos(height,List,_,File,Pos),!.
1554 infer_svg_class(List,rect,File,Pos) :- get_attr_with_pos(width,List,_,File,Pos),!.
1555 infer_svg_class(List,ellipse,File,Pos) :- get_attr_with_pos(rx,List,_,File,Pos),!. % could also be rect
1556 infer_svg_class(List,text,File,Pos) :- get_attr_with_pos(text,List,_,File,Pos),!.
1557 infer_svg_class(List,g,File,Pos) :- get_attr_with_pos(children,List,_,File,Pos),!. % group + foreignObject have children
1558 infer_svg_class(List,use,File,Pos) :- get_attr_with_pos(href,List,_,File,Pos),!. % href can also be used with image, pattern, ...
1559
1560 % assert a new SVG object to be created upon SETUP_CONSTANTS/INITIALISATION:
1561 assert_visb_svg_object(ID,SVG_Class,_AttrList,_Desc,DefName,Pos1) :-
1562 visb_svg_object(ID,_,_,_,_Pos0),!,
1563 ajoin(['SVG object (from ',DefName,', svg_class=',SVG_Class,') with same id already created: '],Msg),
1564 add_warning(visb_visualiser,Msg,ID,Pos1).
1565 assert_visb_svg_object(_ID,_SVG_Class,AttrList,_Desc,_DefName,Pos1) :-
1566 \+ (AttrList=[] ; AttrList=[_|_]),!,
1567 add_error(visb_visualiser,'SVG objects attributes are not a list:',AttrList,Pos1).
1568 assert_visb_svg_object(ID,SVG_Class,AttrList,Desc,DefName,Pos1) :-
1569 check_svg_shape_class(ID,SVG_Class,Pos1),
1570 add_visb_debug_infos(ID,SVG_Class,AttrList,AttrList2,DefName,Pos1),
1571 sort(AttrList2,SAttrList),
1572 get_all_children(SAttrList,Children,RestAttrs,DefName,Pos1),
1573 (Children = [] -> true
1574 ? ; svg_shape_can_have_children(SVG_Class) -> true % g, foreignObject, symbol, HTML tags
1575 ; Children = [C1_ID|_], visb_svg_object(C1_ID,CAttr,_,_,_),
1576 attribute_automatically_creates_children(CAttr) % e.g., title object created for title attribute of ID
1577 -> true
1578 ; 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)
1579 ),
1580 ? (select(svg_attribute(group_id,ParentGroupId),RestAttrs,RestAttrs2)
1581 -> assert_visb_svg_child(ParentGroupId,Pos1,ID) % register parent group id
1582 ; RestAttrs2=RestAttrs),
1583 compute_auto_attributes(RestAttrs,RestAttrs2,SVG_Class,NewRestAttrs),
1584 assertz(visb_svg_object(ID,SVG_Class,NewRestAttrs,Desc,Pos1)),
1585 maplist(assert_visb_svg_child(ID,Pos1),Children). % add all children
1586
1587 % adapt visb_svg_object to provide developer debug infos, e.g., in title hover messages
1588 add_visb_debug_infos(ID,SVG_Class,AttrList,NewAttrList,DefName,Pos) :- SVG_Class \= title,
1589 get_preference(visb_show_debug_infos,true),
1590 (select(svg_attribute(title,Title),AttrList,RestAttrs) -> true
1591 ; Title='', RestAttrs=AttrList),
1592 !,
1593 extract_span_description_with_opts(Pos,PosStr,
1594 [relative_file_name,compact_pos_info,
1595 inner_context_separator('\n in ','\n at ')]),
1596 %extract_definition_call_stack_desc(Pos,CS), already displayed in inner context
1597 ajoin(['-- VISB_DEBUG_INFO --\nid=',ID, '\nsvg_class=',SVG_Class, '\nsrc=',DefName,'\n', PosStr],DebugInfo),
1598 (Title='' -> NewTitle=DebugInfo ; ajoin([Title,'\n',DebugInfo],NewTitle)),
1599 %format('~nDEBUG::~n~w~n~w~n---~n',[ID,DebugInfo]),
1600 assert(visb_svg_object_debug_info(ID,DebugInfo)),
1601 NewAttrList = [svg_attribute(title,NewTitle)|RestAttrs].
1602 add_visb_debug_infos(_,_,AttrList,AttrList,_,_).
1603
1604 % compute the value of VisB auto attributes, e.g., automatically
1605 % doing a layout of objects in a grid
1606 % TODO: SVG/special_svg_number already supports auto but not for x,y coordinates?
1607 % TODO: try and determine width of object automatically; keep track of auto objects max height per row
1608 % TODO: support cx,cy
1609 compute_auto_attributes([],_,_,[]).
1610 compute_auto_attributes([svg_attribute(Attr,Val)|T],AllAttrs,SVG_Class,
1611 [svg_attribute(Attr,NewVal)|NT]) :-
1612 (Val=auto, compute_auto_attribute(Attr,AllAttrs,SVG_Class,NewVal)
1613 -> true
1614 ; NewVal=Val),
1615 compute_auto_attributes(T,AllAttrs,SVG_Class,NT).
1616
1617 :- dynamic next_auto_x/1, next_auto_y/2.
1618 next_auto_x(0).
1619 next_auto_y(0,10).
1620 reset_auto_attrs :- retractall(next_auto_x(_)),
1621 retractall(next_auto_y(_,_)),
1622 assertz(next_auto_x(0)),
1623 assertz(next_auto_y(0,10)).
1624
1625 get_x_auto_limit(Limit) :- visb_empty_svg_box_height_width(_H,W,_ViewBox),!,
1626 Limit = W. %TODO: inspect viewBox
1627 get_x_auto_limit(400).
1628
1629 compute_auto_attribute(id,_,_,GenID) :- !, gensym(svg_id,GenID).
1630 compute_auto_attribute(Attr,AllAttrs,SVG_Class,Val) :-
1631 auto_compute_x_coordinate(Attr,Kind),!,
1632 retract(next_auto_x(XV)),
1633 (get_width(SVG_Class,AllAttrs,Offset) -> true ; Offset=10),
1634 Padding = 2, % TODO: make customisable
1635 NewXV is XV+Offset+Padding,
1636 get_x_auto_limit(Lim),
1637 (NewXV > Lim
1638 -> NewVal=0, retract(next_auto_y(OldY,YOffset)),
1639 (get_height(SVG_Class,AllAttrs,Offset) -> true ; Offset = 10),
1640 NewY is OldY+YOffset,
1641 assert(next_auto_y(NewY,YOffset))
1642 ; NewVal=NewXV),
1643 assertz(next_auto_x(NewVal)),
1644 (Kind=left -> Val=XV ; Val is XV + Offset/2).
1645 compute_auto_attribute(Attr,AllAttrs,SVG_Class,Val) :- auto_compute_y_coordinate(Attr,Kind),
1646 next_auto_y(YV,_),
1647 (Kind = top -> Val = YV
1648 ; get_height(SVG_Class,AllAttrs,Height) -> Val is YV + Height/2
1649 ; Val is YV+5).
1650
1651 auto_compute_x_coordinate(x,left). % rect, ..
1652 auto_compute_x_coordinate(cx,center). % circle, ellipse
1653 auto_compute_y_coordinate(y,top). % rect, ..
1654 auto_compute_y_coordinate(cy,center). % circle, ellipse
1655
1656 get_width(rect,Attrs,Wid) :- member(svg_attribute(width,Wid),Attrs).
1657 get_width(circle,Attrs,Wid) :- member(svg_attribute(r,Radius),Attrs), Wid is 2*Radius.
1658 get_width(ellipse,Attrs,Wid) :- member(svg_attribute(rx,Radius),Attrs), Wid is 2*Radius.
1659 get_width(line,Attrs,Wid) :- member(svg_attribute(x1,X1),Attrs),
1660 member(svg_attribute(x2,X2),Attrs), Wid is abs(X2-X1).
1661
1662 get_height(rect,Attrs,Wid) :- member(svg_attribute(height,Wid),Attrs).
1663 get_height(circle,Attrs,Wid) :- member(svg_attribute(r,Radius),Attrs), Wid is 2*Radius.
1664 get_height(ellipse,Attrs,Wid) :- member(svg_attribute(ry,Radius),Attrs), Wid is 2*Radius.
1665 get_height(line,Attrs,Wid) :- member(svg_attribute(y1,X1),Attrs),
1666 member(svg_attribute(y2,X2),Attrs), Wid is abs(X2-X1).
1667
1668
1669 % register an SVG ID as child of a group
1670 assert_visb_svg_child(_ParentId,Pos,ChildID) :- visb_svg_child(ChildID,OldParent),!,
1671 ajoin(['SVG object already child of group ',OldParent,': '],Msg),
1672 add_warning(visb_visualiser,Msg,ChildID,Pos).
1673 assert_visb_svg_child(ParentId,Pos,ChildID) :- visb_svg_child(ParentId,ChildID),!, % TODO: full cycle detection
1674 ajoin(['SVG object already parent of group ',ParentId,' (cycle): '],Msg),
1675 add_warning(visb_visualiser,Msg,ChildID,Pos).
1676 assert_visb_svg_child(ParentId,_Pos,ChildID) :-
1677 assertz(visb_svg_child(ChildID,ParentId)),
1678 assertz(visb_svg_parent(ParentId,ChildID)).
1679
1680
1681 % we need to translate a title attribute to a separate title object and add it as a child
1682 % see also post_process_visb_item which dispatches title updates to the child object
1683 get_all_children(SAttrList,Children,Rest,DefName,Pos) :-
1684 ? select(svg_attribute(title,Title),SAttrList,SList2),!,
1685 add_virtual_title_object(Title,DefName,Pos,TitleID),
1686 Children=[TitleID|TChilds],
1687 get_children_attribute(SList2,TChilds,Rest,Pos).
1688 get_all_children(SAttrList,Children,Rest,_,Pos) :-
1689 % get the children explicitly defined by the user:
1690 get_children_attribute(SAttrList,Children,Rest,Pos).
1691
1692 add_virtual_title_object(Title,DefName,Pos,TitleID) :-
1693 gensym(visb_title,TitleID),
1694 assert_visb_svg_object(TitleID,'title',[svg_attribute(text,Title)],'',DefName,Pos),
1695 add_debug_message(visb_visualiser,'Adding virtual title child object: ',TitleID,Pos).
1696
1697 get_children_attribute(SAttrList,Children,Rest,Pos) :-
1698 ? select(svg_attribute(children,C),SAttrList,R),!,
1699 (is_list(C) -> Children=C
1700 ; add_warning(visb_visualiser,'Children attribute should be a list (of SVG ids): ',C,Pos),
1701 Children=[]),
1702 Rest=R.
1703 get_children_attribute(SAttrList,[],SAttrList,_).
1704
1705
1706 svg_shape_can_have_children(defs).
1707 svg_shape_can_have_children(foreignObject).
1708 svg_shape_can_have_children(g).
1709 svg_shape_can_have_children(pattern).
1710 svg_shape_can_have_children(symbol).
1711 svg_shape_can_have_children(X) :- is_html_tag(X).
1712
1713
1714 % check whether svg_class value seems valid
1715 check_svg_shape_class(ID,Shape,Pos) :-
1716 (is_svg_shape_class(Shape) -> true
1717 ; is_html_tag(Shape) ->
1718 (visb_svg_child(ID,ParentId),
1719 visb_svg_object(ParentId,ParClass,_,_,_),
1720 (is_html_tag(ParClass) -> true ; ParClass=foreignObject)
1721 -> add_debug_message(visb_visualiser,'HTML tag used as svg_class in foreignObject child: ',Shape,Pos)
1722 ; ajoin(['SVG object ', ID, ' has HTML tag as svg_class (and should probably be a child of a foreignObject)'],Msg),
1723 add_visb_lint_message(Msg,Shape,Pos) % probably should be child of foreignObject
1724 )
1725 ; dotshape2svg_class(Shape,Class)
1726 -> ajoin(['SVG object ', ID, ' has unknown svg_class (did you mean ',Class,' ?): '],Msg),
1727 add_warning(visb_visualiser,Msg,Shape,Pos)
1728 ; get_all_svg_classes(Classes),
1729 get_possible_fuzzy_matches_and_completions_msg(Shape,Classes,FMsg)
1730 -> ajoin(['SVG object ', ID, ' has unknown svg_class (did you mean ',FMsg,' ?): '],Msg),
1731 add_warning(visb_visualiser,Msg,Shape,Pos)
1732 ; ajoin(['SVG object ', ID, ' has unknown svg_class'],Msg),
1733 add_visb_lint_message(Msg,Shape,Pos)
1734 ).
1735
1736 % get SVG attribute for an svg_object:
1737 get_svg_attr(SVG_Class,File,'='(Attr,AttrVal,Pos),svg_attribute(Attr,Val)) :- !,
1738 construct_prob_pos_term(Pos,File,PosTerm),
1739 get_svg_static_attribute_value(Attr,SVG_Class,PosTerm,AttrVal,Val).
1740 get_svg_attr(_,File,Json,_) :-
1741 get_pos_from_list([Json],File,Position),
1742 add_error(visb_visualiser,'Illegal SVG object attribute',Json,Position),fail.
1743
1744 get_svg_static_attribute_value(Attr,SVG_Class,Pos,AttrVal,Nr) :-
1745 check_is_number_attribute(Attr,SVG_Class,Pos),
1746 \+ is_special_svg_number_form(AttrVal),
1747 !,
1748 (get_number_value(AttrVal,Nr,Attr,Pos) -> true
1749 ; add_error(visb_visualiser,'Illegal number value:',AttrVal,Pos), Nr=0).
1750 get_svg_static_attribute_value(_,_,_,string(Val),Res) :- !, Res=Val.
1751 % for children we get something like array([string(button1_1),string(button1_2)])
1752 get_svg_static_attribute_value(Attr,SVG_Class,Pos,array(List),ResList) :- !,
1753 maplist(get_svg_static_attribute_value(Attr,SVG_Class,Pos),List,ResList).
1754 get_svg_static_attribute_value(_Attr,_,Pos,Val,Val) :-
1755 add_warning(visb_visualiser,'Illegal SVG object attribute value: ',Val,Pos).
1756
1757
1758 % detect special SVG number forms, like 50%
1759 is_special_svg_number_form(string(Atom)) :-
1760 atom_codes(Atom,Codes),
1761 special_svg_number(Codes,[]).
1762
1763
1764 :- assert_must_succeed(visb_visualiser:special_svg_number("10%",[])).
1765 :- assert_must_succeed(visb_visualiser:special_svg_number("10 %",[])).
1766 :- assert_must_succeed(visb_visualiser:special_svg_number(" 99em ",[])).
1767 :- assert_must_succeed(visb_visualiser:special_svg_number("1.0em",[])).
1768 :- assert_must_fail(visb_visualiser:special_svg_number("10",[])).
1769 :- assert_must_fail(visb_visualiser:special_svg_number("10+nrcols+%0",[])).
1770 special_svg_number --> " ",!, special_svg_number.
1771 special_svg_number --> [X], {digit(X)},!, special_svg_number2.
1772 special_svg_number --> "auto".
1773 special_svg_number2 --> [X], {digit(X)},!, special_svg_number2.
1774 special_svg_number2 --> ".",!, special_svg_number2. % TODO: only allow one dot; + accept e notation?
1775 ?special_svg_number2 --> optws,!, svg_unit,!, optws.
1776
1777 % using info from https://oreillymedia.github.io/Using_SVG/guide/units.html
1778 svg_unit --> "%".
1779 svg_unit --> "ch".
1780 svg_unit --> "cm".
1781 svg_unit --> "em".
1782 svg_unit --> "ex".
1783 svg_unit --> "in".
1784 svg_unit --> "mm".
1785 svg_unit --> "pc".
1786 svg_unit --> "pt".
1787 svg_unit --> "px".
1788 svg_unit --> "deg". % angle units
1789 svg_unit --> "grad".
1790 svg_unit --> "rad".
1791 svg_unit --> "turn".
1792 svg_unit --> "rem". % root em
1793 svg_unit --> "vh". % viewport height unit (1%)
1794 svg_unit --> "vw". % viewport width unit (1%)
1795 svg_unit --> "vmin". % min ov vh, vw
1796 svg_unit --> "vmax". % max ov vh, vw
1797
1798
1799 optws --> " ",!,optws.
1800 optws --> [].
1801
1802 digit(X) :- X >= 48, X =< 57.
1803
1804 is_svg_number_attribute(Attr) :- is_svg_number_attribute(Attr,_).
1805
1806
1807 % some checks to see whether the attribute is supported by the given SVG class
1808
1809 check_attribute_is_supported(SVG_Class,DefPos,svg_attribute(Name,_V)) :- !,
1810 (nonvar(SVG_Class), check_is_number_attribute(Name,SVG_Class,DefPos) -> true
1811 % TODO: check color and other attributes, see also check_attribute_type
1812 ; check_attribute_name_is_supported(SVG_Class,Name,DefPos)).
1813 check_attribute_is_supported(S,DefPos,F) :-
1814 add_internal_error('Illegal call:',check_attribute_is_supported(S,DefPos,F)).
1815
1816 % if these special attributes occur here, something went wrong, e.g.,
1817 % when separating static/dynamic parts
1818 check_unsupported_special_visb_attribute(visb_objects,_,_) :- !,fail. % here we can process everything
1819 check_unsupported_special_visb_attribute(SpecialClass,DefPos,svg_attribute(Name,_)) :-
1820 special_visb_attribute_not_allowed_in_dynamic_objects(Name,SpecialClass,Kind),
1821 ajoin(['The VisB special attribute ',Name,' cannot be used here (',SpecialClass,' use separate ',Kind,' definition): '],Msg),
1822 add_warning(visb_visualiser,Msg,Name,DefPos).
1823
1824 special_visb_attribute_not_allowed_in_dynamic_objects(hover,SC,'VISB_SVG_HOVERS') :- SC \= visb_hovers.
1825 special_visb_attribute_not_allowed_in_dynamic_objects(hovers,SC,'VISB_SVG_HOVERS') :- SC \= visb_hovers.
1826 special_visb_attribute_not_allowed_in_dynamic_objects(event,SC,'VISB_SVG_EVENTS') :- SC \= visb_events.
1827 special_visb_attribute_not_allowed_in_dynamic_objects(events,SC,'VISB_SVG_EVENTS') :- SC \= visb_events.
1828 special_visb_attribute_not_allowed_in_dynamic_objects(predicate,SC,'VISB_SVG_EVENTS') :- SC \= visb_events.
1829 special_visb_attribute_not_allowed_in_dynamic_objects(predicates,SC,'VISB_SVG_EVENTS') :- SC \= visb_events.
1830 special_visb_attribute_not_allowed_in_dynamic_objects(preds,SC,'VISB_SVG_EVENTS') :- SC \= visb_events.
1831
1832
1833 check_attribute_name_is_supported(SVG_Class,Name,DefPos) :-
1834 nonvar(SVG_Class),
1835 is_html_tag(SVG_Class),
1836 \+ is_svg_shape_class(SVG_Class), % script and title can be both SVG and HTML
1837 !,
1838 (is_html_attribute(Name)
1839 -> true % TODO: we could check whether attribute appropriate for Tag
1840 ; is_virtual_svg_attribute(Name) -> true % Virtual VisB attribute like children, text, ...
1841 ; ajoin(['Unknown HTML attribute used inside HTML tag ',SVG_Class],Msg),
1842 add_visb_lint_message(Msg,Name,DefPos)
1843 ).
1844 check_attribute_name_is_supported(_SVG_Class,Name,DefPos) :-
1845 ? \+ is_svg_attribute(Name),
1846 !,
1847 (fix_svg_attribute(Name,GraphVizTranslName)
1848 -> ajoin(['Unknown SVG attribute (maybe you want to use ',GraphVizTranslName,' ?): '],Msg),
1849 add_warning(visb_visualiser,Msg,Name,DefPos)
1850 ; get_all_svg_attributes(Attrs),
1851 (get_possible_fuzzy_matches_and_completions_msg(Name,Attrs,FMsg)
1852 -> ajoin(['Unknown SVG attribute (did you mean ',FMsg,' ?): '],Msg),
1853 add_warning(visb_visualiser,Msg,Name,DefPos) % create warning, as it is likely we have made an error
1854 ; is_dot_attribute(Name)
1855 -> add_warning(visb_visualiser,'This Dot/Graphviz attribute is not a valid SVG attribute: ',Name,DefPos)
1856 ; get_preference(visb_strict_checking,false)
1857 -> add_visb_lint_message('Unknown SVG attribute',Name,DefPos)
1858 ; add_warning(visb_visualiser,'Unknown SVG attribute (set VISB_LINT to FALSE to avoid warning): ',Name,DefPos)
1859 )
1860 ).
1861 check_attribute_name_is_supported(_,_,_).
1862
1863 % add message or warning, depending on VISB_LINT setting
1864 add_visb_lint_message(Msg,Obj,Pos) :- get_preference(visb_strict_checking,false), !,
1865 ajoin([Msg,': '],Msg2),
1866 add_message(visb_visualiser,Msg2,Obj,Pos).
1867 add_visb_lint_message(Msg,Obj,Pos) :-
1868 ajoin([Msg,' (set VISB_LINT to FALSE to avoid warning): '],Msg2),
1869 add_warning(visb_visualiser,Msg2,Obj,Pos).
1870
1871
1872 % succeed if attribute is a number attribute and perform a check the attribute is supported by the class
1873 check_is_number_attribute(Attr,Class,Pos) :-
1874 is_svg_number_attribute(Attr,ClassList),
1875 (nonvar(Class), nonmember(Class,ClassList)
1876 -> (equivalent_attribute(Attr,List2,NewAttr), member(Class,List2)
1877 -> ajoin(['The number attribute ',Attr,' is not supported for SVG class ',Class,', use: '],Msg),
1878 add_warning(visb_visualiser,Msg,NewAttr,Pos)
1879 ; ajoin(['The number attribute ',Attr,' is not supported for this SVG class: '],Msg),
1880 add_warning(visb_visualiser,Msg,Class,Pos)
1881 )
1882 ; true
1883 ).
1884
1885 % optionally rewrite record field to alternative spelling
1886 opt_rewrite_field_name(Name,Res) :-
1887 (alternative_spelling(Name,Alt) -> Res=Alt ; Res=Name).
1888
1889 % these alternatives are useful e.g. in TLA+ without backquote:
1890 alternative_spelling(colour,'color').
1891 alternative_spelling(fill_opacity,'fill-opacity').
1892 alternative_spelling(fill_rule,'fill-rule').
1893 alternative_spelling(font_family,'font-family').
1894 alternative_spelling(font_size,'font-size').
1895 alternative_spelling(font_style,'font-style').
1896 alternative_spelling(font_variant,'font-variant').
1897 alternative_spelling(font_weight,'font-weight').
1898 alternative_spelling(marker_end,'marker-end').
1899 alternative_spelling(marker_start,'marker-start').
1900 alternative_spelling(stroke_opacity,'stroke-opacity').
1901 alternative_spelling(stroke_dasharray,'stroke-dasharray').
1902 alternative_spelling(stroke_linecap,'stroke-linecap').
1903 alternative_spelling(stroke_linejoin,'stroke-linejoin').
1904 alternative_spelling(stroke_width,'stroke-width').
1905
1906
1907 % used to suggest fixing unsupported attributes in SVG objects:
1908 equivalent_attribute(cx,[rect],x).
1909 equivalent_attribute(cy,[rect],y).
1910 equivalent_attribute(x,[circle,ellipse],cx).
1911 equivalent_attribute(x,[line],x1).
1912 equivalent_attribute(y,[circle,ellipse],cy).
1913 equivalent_attribute(y,[line],y1).
1914 equivalent_attribute(r,[rect],rx). % ry also exists
1915 equivalent_attribute(rx,[circle],r).
1916 equivalent_attribute(width,[circle],r).
1917 equivalent_attribute(width,[ellipse],rx).
1918 equivalent_attribute(height,[ellipse],ry).
1919
1920
1921 % ----------------
1922
1923 % parse and load an individual JSON VisB item, e.g, :
1924 % {
1925 % "id":"train_info_text",
1926 % "attr":"x",
1927 % "value":"real(train_rear_end)*100.0/real(TrackElementNumber+1)",
1928 % "comment":"move info field above train"
1929 % },
1930 process_visb_json_item(File,Json) :-
1931 process_repeat(0,Json,File,add_visb_json_item).
1932
1933 add_visb_json_item(File,json(List)) :-
1934 get_attr_true(ignore,List,File), % ignore this item
1935 !.
1936 add_visb_json_item(File,json(List)) :-
1937 del_attr_with_pos(id,List,string(ID),L1,File,PosStartOfItem),
1938 !,
1939 process_visb_json_item_id(File,L1,ID,PosStartOfItem).
1940 add_visb_json_item(File,Json) :-
1941 !,
1942 get_pos_from_list(Json,File,Pos),
1943 add_error(visb_visualiser,'VisB Item has no id attribute:',Json,Pos).
1944
1945 process_visb_json_item_id(File,L1,ID,PosStartOfItem) :-
1946 ? del_attr(attr,L1,string(Attr),L2), % VisB has attr and value infos
1947 force_del_attr_with_pos(value,L2,string(Formula),L3,File,PosFormula),
1948 !,
1949 ? (del_attr(comment,L3,string(Desc),L4) -> true ; Desc = '',L4=L3),
1950 debug_format(19,' Processing id:~w attr:~w : value:~w desc:~w~n',[ID,Attr,Formula,Desc]),
1951 actually_add_visb_json_item(ID,Attr,Formula,Desc,L4,PosStartOfItem,PosFormula,File).
1952 process_visb_json_item_id(File,L1,ID,PosStartOfItem) :-
1953 get_attr(SomeSVGAttr,L1,_V),
1954 ? is_svg_attribute(SomeSVGAttr),
1955 debug_format(19,'Detected new style VisB JSON declaration with id:~w and SVG attr:~w~n',[ID,SomeSVGAttr]),
1956 !,
1957 % object is in new format with multiple attributes "x":"0" rather than "attr":"x", "value":"0"
1958 (del_attr(comment,L1,string(Desc),L2) -> true ; Desc = '',L2=L1),
1959 ? (non_det_del_attr_with_pos(SVGATTR,L2,string(Formula),L3,File,PosFormula),
1960 is_visb_item_svg_attribute(PosFormula,SVGATTR,Formula),
1961 debug_format(19,' -> Processing new style id:~w attr:~w : value:~w desc:~n',[ID,SVGATTR,Formula,Desc]),
1962 actually_add_visb_json_item(ID,SVGATTR,Formula,Desc,L3,PosStartOfItem,PosFormula,File),
1963 fail
1964 ;
1965 true).
1966 process_visb_json_item_id(_File,_JsonList,ID,PosStartOfItem) :-
1967 !,
1968 add_error(visb_visualiser,'Illegal VisB Item without attr and value fields:',ID,PosStartOfItem).
1969
1970 is_visb_item_svg_attribute(Pos,Attr,Val) :-
1971 Attr \= override, % so we ignore a possible override attribute
1972 ? (is_svg_attribute(Attr) -> true
1973 ; add_warning(visb_visualiser,'Ignoring unknown attribute: ',Attr=Val,Pos),
1974 fail
1975 ).
1976
1977
1978 actually_add_visb_json_item(ID,Attr,Formula,Desc,JsonList,PosStartOfItem,PosFormula,File) :-
1979 set_error_context(visb_error_context(item,ID,Attr,PosFormula)),
1980 atom_codes(Formula,FormulaC),
1981 (parse_expr_for_visb(FormulaC,JsonList,PosFormula,TypedExpr)
1982 % TO DO: if optional attribute present: avoid generating errors in b_parse_machine_expression_from_codes
1983 -> assert_visb_item(ID,Attr,TypedExpr,Desc,PosStartOfItem,JsonList,File)
1984 ; get_attr_with_pos(optional,JsonList,_,File,Pos)
1985 -> formatsilent('Ignoring optional VisB item for ~w (lines ~w) due to error in B formula~n',[ID,Pos])
1986 ; ajoin(['Cannot parse or typecheck VisB formula for ',ID,' and attribute ',Attr,':'],Msg),
1987 add_error(visb_visualiser,Msg,Formula,PosFormula)
1988 ), clear_error_context.
1989
1990
1991 % assert a VISB item (aka VISB_SVG_UPDATE)
1992 assert_visb_item(ID,Attr,_TypedExpr,_Desc,PosStartOfItem,_,_) :-
1993 visb_item(ID,Attr,_,_,_,Pos2,Meta2),
1994 !,
1995 get_file_name_msg(PosStartOfItem,From1,File1),
1996 (member(override,Meta2)
1997 -> ajoin(['Overriding VisB item',From1,File1,' for same SVG ID ',ID,' and attribute '],Msg),
1998 add_debug_message(visb_visualiser,Msg,Attr,Pos2)
1999 ; ajoin(['Overriding VisB item',From1,File1,' for same SVG ID ',ID,
2000 '. Add an \"override\" attribute to remove this warning. Overriden attribute '],Msg),
2001 add_warning(visb_visualiser,Msg,Attr,Pos2),
2002 % error_context already includes attribute and ID
2003 add_message(visb_visualiser,'Overriding this stored formula for ',ID,PosStartOfItem) % provide detailed info
2004 ).
2005 assert_visb_item(ID,Attr,_TypedExpr,_Desc,PosStartOfItem,_JsonList,_File) :-
2006 illegal_attribute_for_visb_item(ID,Attr),!,
2007 add_warning(visb_visualiser,'This attribute cannot be modified in a VisB item: ',Attr,PosStartOfItem).
2008 assert_visb_item(ID,Attr,TypedExpr,Desc,PosStartOfItem,JsonList,File) :-
2009 (get_attr_true(override,JsonList,File) -> Meta = [override] ; Meta=[]),
2010 % determine_type_of_visb_formula(TypedExpr,_,Class) now does take definitions into account; TODO: save info
2011 find_identifier_uses(TypedExpr,[],UsedIds),
2012 assertz(visb_item(ID,Attr,TypedExpr,UsedIds,Desc,PosStartOfItem,Meta)).
2013
2014 illegal_attribute_for_visb_item(_,children).
2015 illegal_attribute_for_visb_item(_,group_id).
2016 illegal_attribute_for_visb_item(_,id).
2017 illegal_attribute_for_visb_item(_,svg_class).
2018
2019
2020 get_file_name_msg(Pos1,' from ',File1) :- extract_tail_file_name(Pos1,File1),!.
2021 get_file_name_msg(_,'',''). % no file info
2022
2023 % ----
2024
2025 get_attr_true(Attr,JsonList,File) :-
2026 get_attr_with_pos(Attr,JsonList,TRUE,File,Pos),
2027 (json_true_value(TRUE) -> true
2028 ; json_false_value(TRUE) -> fail
2029 ; ajoin(['Value for attribute ',Attr,' is not true or false: '],Msg),
2030 add_warning(visb_visualiser,Msg,TRUE,Pos)
2031 ).
2032
2033 json_true_value(@(true)).
2034 json_true_value(string(true)).
2035 json_true_value(number(1)).
2036
2037 json_false_value(@(false)).
2038 json_false_value(string(false)).
2039 json_false_value(number(0)).
2040
2041 % ----------------
2042 % FOR-LOOP / REPEAT processing
2043
2044 %process_repeat(RepCounter, Json, FinalCall to be executed repeatedly for each instance with File and Json, File)
2045 % RepCounter tells us which of %0, %1, ... should be replaced next
2046
2047 process_repeat(RepCount,json(JsonList),File,FinalCall) :-
2048 ? non_det_del_attr_with_pos(FOR_REP,JsonList,Value,RestJsonList,File,ForRepPos),
2049 % find first for or repeat and process it
2050 (FOR_REP=for ; FOR_REP=repeat),
2051 !,
2052 process_first_repeat(FOR_REP,Value,ForRepPos,RepCount,json(RestJsonList),File,FinalCall).
2053 process_repeat(_RepCount,Json,File,FinalCall) :-
2054 % we have processed all for/repeat loops: now perform the final call on the transformed codes
2055 call(FinalCall,File,Json).
2056
2057 process_first_repeat(for,json(ForList),ForPos,RepCount,JsonData,File,FinalCall) :-
2058 !, % we have a for loop like "for": {"from":1, "to":4}
2059 force_get_attr_nr(from,ForList,From,File),
2060 force_get_attr_nr(to,ForList,To,File),
2061 (get_attr_with_pos(step,ForList,StepAttrVal,File,StepPos),
2062 get_number_value(StepAttrVal,Step,step,StepPos)
2063 -> true % there is an explicit step attribute
2064 ; Step=1),
2065 debug_format(19,' -> Iterating %~w from ~w to ~w with step ~w~n',[RepCount,From,To,Step]),
2066 R1 is RepCount+1,
2067 number_codes(RepCount,Pat),
2068 check_between(From,To,Step,ForPos), % check whether step value makes sense
2069 ? ( between(From,To,Step,IterElem),
2070 number_codes(IterElem,IterElemC), % we will replace the text %Pat by the text of the number IterElem
2071 replace_in_json(Pat,IterElemC,JsonData,ReplacedJsonData), % replace within other for/repeat loops, but also other attributes
2072 process_repeat(R1,ReplacedJsonData,File,FinalCall), % now process next loop or finish
2073 fail
2074 ; true).
2075 process_first_repeat(repeat,array(RepList),RepPos,RepCount,JsonData,File,FinalCall) :-
2076 !, % we have a repetition like "repeat": ["tr1","tr2"] or "repeat": [ ["1","2"] , ...]
2077 (RepList=[array(L1)|_], length(L1,Len)
2078 -> NewRepCount is RepCount+Len, % we have a multi-repeat with list of values to be replaced
2079 LastRepCount is NewRepCount-1,
2080 debug_format(19,' -> Iterating repeat (%~w,...,%~w) over ~w~n',[RepCount,LastRepCount,RepList]),
2081 check_all_same_length_json(RepList,Len,RepPos)
2082 ; NewRepCount is RepCount+1, % next replacement starts at $(RepCount+1)
2083 debug_format(19,' -> Iterating repeat (%~w) over ~w~n',[RepCount,RepList])
2084 ),
2085 ? ( member(IterElem,RepList),
2086 multi_replace_in_json(IterElem,RepCount,JsonData,ReplacedJsonData), % replace within other for/repeat loops, but also other attributes
2087 process_repeat(NewRepCount,ReplacedJsonData,File,FinalCall), % now process next loop or finish
2088 fail
2089 ; true).
2090
2091 check_all_same_length_json(List,ExpectedLen,Pos) :-
2092 nth1(Nr,List,Json),
2093 (Json=array(SubList),length(SubList,Len) -> Len \= ExpectedLen ; Len='not a list'),
2094 !,
2095 ajoin(['The element number ',Nr,' of the repeat list has not the expected length of ',ExpectedLen,', length is: '],Msg),
2096 add_warning(visb_visualiser,Msg,Len,Pos).
2097 check_all_same_length_json(_,_,_).
2098
2099 json_value_to_codes(@(Literal), C) :- atom(Literal), !, atom_codes(Literal, C).
2100 json_value_to_codes(number(Number), C) :- number(Number), !, number_codes(Number, C).
2101 json_value_to_codes(string(String), C) :- atom(String), !, atom_codes(String, C).
2102 json_value_to_codes(Json, _) :- !, add_error(json_value_to_codes,'Cannot convert json term to codes:', Json), fail.
2103
2104 % replace (possibly) multiple patterns at once
2105 multi_replace_in_json(array([]),_RepCount,JsonIn,JsonOut) :- !, JsonOut=JsonIn.
2106 multi_replace_in_json(array([IterElem|TIT]),RepCount,JsonIn,JsonOut) :-
2107 !,
2108 number_codes(RepCount,Pat),
2109 json_value_to_codes(IterElem,IterElemC),
2110 %format('Replacing in JSON: ~s -> ~s~n',[Pat,IterElemC]),
2111 replace_in_json(Pat,IterElemC,JsonIn,Json),
2112 R1 is RepCount+1,
2113 multi_replace_in_json(array(TIT),R1,Json,JsonOut).
2114 multi_replace_in_json(IterElem,RepCount,JsonIn,JsonOut) :- % a value, not a list
2115 !,
2116 number_codes(RepCount,Pat),
2117 json_value_to_codes(IterElem,IterElemC),
2118 %format('Replacing in JSON: ~s -> ~s~n',[Pat,IterElemC]),
2119 replace_in_json(Pat,IterElemC,JsonIn,JsonOut).
2120
2121 check_between(_,_,Step,ForPos) :- Step =< 0, !,
2122 add_error(visb_visualiser,'The step of a for loop must be positive:',Step,ForPos),fail.
2123 check_between(From,To,Step,ForPos) :- Iters is (To-From)/Step,
2124 Iters > 100000,!,
2125 add_error(visb_visualiser,'Very large for loop:',Iters,ForPos),fail.
2126 check_between(_,_,_,_).
2127
2128
2129 % ----------------
2130
2131 % parse and load VisB events
2132 % A VisB Event looks like:
2133 % {
2134 % "id": "button",
2135 % "event": "toggle_button",
2136 % "hovers": [{ "attr":"stroke-width", "enter":"6", "leave":"1"},
2137 % { "attr":"opacity", "enter":"0.8", "leave":"1.0"}]
2138 % }
2139 process_json_event(File,Json) :-
2140 process_repeat(0,Json,File,add_visb_json_event).
2141
2142 add_visb_json_event(File,json(List)) :- get_attr_true(ignore,List,File), !. % ignore this item
2143 add_visb_json_event(File,json(List)) :-
2144 get_pos_from_list(List,File,Pos),
2145 force_del_attr(id,List,string(ID),L0,File), % for items it could make sense to not specify an id
2146 ? (del_attr(event,L0,string(Event),L1) -> true ; Event='', L1=L0),
2147 (del_attr_with_pos(predicates,L1,array(Preds),L2,File,PredPos) -> true
2148 ; del_attr_with_pos(preds,L1,array(Preds),L2,File,PredPos) -> true
2149 ; Preds=[], L2=L1, PredPos=unknown),
2150 ? (del_attr(hovers,L2,array(Hovers),L3) -> true ; Hovers=[],L3=L2),
2151 (del_attr(items,L3,array(EI),L4)
2152 -> (empty_b_event(Event)
2153 -> EnableItems=[],
2154 add_warning(visb_visualiser,'Ignoring enable items; you need to provide an event name:',ID,Pos)
2155 ; EnableItems=EI)
2156 ; EnableItems=[],L4=L3),
2157 debug_format(19,' Processing id:~w event:~w preds:~w enable:~w hovers:~w~n',[ID,Event,Preds,EnableItems,Hovers]),
2158 !,
2159 actually_add_visb_json_event(ID,Event,Preds,Hovers,EnableItems,L4,File,Pos,PredPos).
2160 add_visb_json_event(File,Json) :-
2161 !,
2162 get_pos_from_list(Json,File,Pos),
2163 add_error(visb_visualiser,'Illegal VisB Event:',Json,Pos).
2164
2165 actually_add_visb_json_event(ID,Event,JsonPreds,JsonHovers,JsonEnableItems,JsonList,File,Pos,PredPos) :-
2166 check_additional_args(JsonList,File),
2167 maplist(process_json_pred,JsonPreds,Preds),
2168 maplist(process_json_enabling_item(ID,Event,File),JsonEnableItems,EnableItems),
2169 maplist(process_json_hover(ID,File),JsonHovers,Hovers),
2170 add_visb_event(ID,Event,Preds,Hovers,EnableItems,File,Pos,PredPos,JsonList).
2171
2172
2173 add_visb_event(ID,Event,Preds,Hovers,EnableItems,File,Pos,PredPos,JsonList) :-
2174 (retract(visb_event(ID,OldEvent,OldPreds,OldTypedPred,OldFile,OldPos))
2175 -> (get_attr_true(override,JsonList,File)
2176 -> ajoin(['Overriding VisB event from file ',OldFile,' for ID: '],Msg),
2177 add_debug_message(visb_visualiser,Msg,ID,Pos),
2178 retractall(visb_hover(ID,_,_,_,_,_))
2179 ; (OldFile=File
2180 -> ajoin(['No override attribute: adding VisB event ',Event,
2181 ' (first event ',OldEvent,') for ID: '],Msg)
2182 ; ajoin(['No override attribute: adding VisB event ',Event,
2183 ' (first event ',OldEvent,' in file ',OldFile,') for ID: '],Msg)
2184 ),
2185 add_debug_message(visb_visualiser,Msg,ID,Pos),
2186 assertz(auxiliary_visb_event(ID,OldEvent,OldPreds,OldTypedPred,OldPos))
2187 ),
2188 assert_visb_event(ID,Event,Preds,Hovers,EnableItems,File,Pos,PredPos)
2189 % ProB2-UI cannot currently support multiple events associated with the same id
2190 % TODO: merge visb_events if we have no override attribute
2191 ? ; (xtl_mode ; b_is_operation_name_or_external_subst(Event)) ->
2192 assert_visb_event(ID,Event,Preds,Hovers,EnableItems,File,Pos,PredPos)
2193 ; (empty_b_event(Event) ; \+ b_or_z_mode)
2194 -> % for empty event we just want hovers
2195 (Preds = [] -> true
2196 ; add_warning(visb_visualiser,'Ignoring preds for VisB event for SVG ID: ',ID,Pos)
2197 ),
2198 assert_visb_event(ID,Event,[],Hovers,EnableItems,File,Pos,PredPos)
2199 ; get_attr_with_pos(optional,JsonList,_,File,Pos) ->
2200 formatsilent('Ignoring optional VisB event for ~w (lines ~w) due to unknown B operation ~w~n',[ID,Pos,Event])
2201 ; detect_op_call_with_paras(Event,OpName) -> % check if we have a name with parameters inside
2202 add_warning(visb_visualiser,'Ignoring parameters provided in event; use the "predicate" attribute to specify parameters: ',Event,Pos),
2203 assert_visb_event(ID,OpName,Preds,Hovers,EnableItems,File,Pos,PredPos)
2204 ; atom(Event), atom_prefix('{',Event) ->
2205 ajoin(['Unknown B operation ', Event, ' as VisB event for SVG ID (be sure to use the "events" attribute for multiple events): '],Msg),
2206 add_warning(visb_visualiser,Msg,ID,Pos)
2207 ; ajoin(['Unknown B operation ', Event, ' as VisB event for SVG ID: '],Msg),
2208 add_warning(visb_visualiser,Msg,ID,Pos)
2209 ).
2210
2211 b_is_operation_name_or_external_subst(OpName) :- b_is_operation_name(OpName).
2212 b_is_operation_name_or_external_subst(Special) :- special_operation(Special).
2213
2214 % maybe we should provide those via the external substitution interface:
2215 % these are all schedulers which choose among existing enabled operations in some manner
2216 special_operation('MCTS_AUTO_PLAY').
2217 special_operation('RANDOM_ANIMATE').
2218 special_operation('RANDOM_ANIMATE_UNTIL_LTL').
2219 special_operation(F) :- external_fun_as_special_operation(F).
2220 external_fun_as_special_operation('STORE_VALUE').
2221 external_fun_as_special_operation('SET_PREF').
2222 % maybe other special names like random_animate with nr of steps, LTL until, ...
2223 special_operation_enabled('MCTS_AUTO_PLAY',_,_,_) :- mcts_auto_play_available.
2224 special_operation_enabled('RANDOM_ANIMATE',_,_,_). % TODO: check if a transition exists
2225 special_operation_enabled('RANDOM_ANIMATE_UNTIL_LTL',_,_,_).
2226 special_operation_enabled(F,_,_,_) :- external_fun_as_special_operation(F).
2227
2228 % detect simple operation call with parameters
2229 detect_op_call_with_paras(Event,OpName) :- atom(Event),
2230 atom_codes(Event,Codes), parse_op_call_name(OpC,Codes,_),!,
2231 atom_codes(OpName,OpC),
2232 b_is_operation_name_or_external_subst(OpName).
2233
2234 parse_op_call_name([X|T]) --> alpha(X), parse_op_call_name2(T).
2235 parse_op_call_name2([]) --> "(".
2236 parse_op_call_name2([H|T]) --> alphadigit(H), parse_op_call_name2(T).
2237
2238 alpha(X) --> [X],({X>=97, X=<122} ; {X>=65, X=<90}).
2239 alphadigit(X) --> [X], ({X>=97,X=<122} ; {X>=65, X=<90} ; {X=95} ; {X>=48, X=<57}).
2240
2241 empty_b_event('').
2242
2243 assert_visb_event(ID,Event,Preds,Hovers,EnableItems,File,Pos,PredPos) :-
2244 construct_pre_post_predicate(ID,Event,Preds,TypedPred,PredPos),
2245 assertz(visb_event(ID,Event,Preds,TypedPred,File,Pos)),
2246 % process hovers
2247 ? (member(HoverElement,Hovers),
2248 (HoverElement=visb_hover(HoverID,Attr,EnterVal,ExitVal) -> true ; add_error(visb_visualiser,'Illegal hover term:',HoverElement),fail),
2249 assert_visb_hover(ID,HoverID,Attr,EnterVal,ExitVal,Pos),fail
2250 ; true),
2251 % now process any additional items with disabled and enabled values
2252 assert_visb_enabling_item_list(Event,TypedPred,EnableItems,File,Pos).
2253
2254 process_json_pred(string(P),R) :- !, R=P.
2255 process_json_pred(Json,_) :- !, add_error(visb_visualiser,'Illegal json term for predicate:',Json), fail.
2256
2257 process_json_hover(OriginID,File,json(Hover),visb_hover(ID,Attr,EnterVal,LeaveVal)) :-
2258 force_del_attr(attr,Hover,string(Attr),H2,File),
2259 force_del_attr_with_pos(enter,H2,EV,H3,File,EnterPos),
2260 force_del_attr_with_pos(leave,H3,LV,H4,File,ExitPos),
2261 (is_svg_number_attribute(Attr) % we evaluate number attributes
2262 -> get_number_value(EV,EnterVal,Attr,EnterPos),
2263 get_number_value(LV,LeaveVal,Attr,ExitPos)
2264 ; string(EnterVal)=EV, string(LeaveVal)=LV % return string as is; TODO: also evaluate other attributes
2265 ),
2266 (get_attr(id,H4,string(ID)) -> true ; ID=OriginID).
2267
2268
2269 assert_visb_hover(TriggerID,SVG_ID,Attr,EnterVal,ExitVal,Pos) :-
2270 assert(visb_hover(TriggerID,SVG_ID,Attr,EnterVal,ExitVal,Pos)),
2271 (visb_has_hovers(TriggerID) -> true ; assert(visb_has_hovers(TriggerID))),
2272 (visb_has_visibility_hover(SVG_ID) -> true
2273 ; Attr=visibility -> assert(visb_has_visibility_hover(TriggerID)) % object can be made visible by hover
2274 ; true),
2275 debug_format(19,'Adding hover for ~w : ~w.~w -> ~w <- ~w~n',[TriggerID,SVG_ID,Attr,EnterVal,ExitVal]).
2276
2277
2278 % process items in event which get translated to enabling/disabling predicates
2279 % "items":[ {"attr":"stroke-width","enabled":"10", "disabled":"1"} ]
2280 process_json_enabling_item(ID,Event,File,json(JsonList),
2281 visb_enable_item(SvgID,Attr,EnabledValExpr,DisabledValExpr,PosAttr)) :-
2282 force_del_attr_with_pos(attr,JsonList,string(Attr),L2,File,PosAttr),
2283 force_del_attr_with_pos('enabled',L2,string(EnVal),L3,File,EPos),
2284 force_del_attr_with_pos('disabled',L3,string(DisVal),L4,File,DPos),
2285 (del_attr(id,L4,string(SvgID),L5) -> true ; SvgID=ID, L4=L5),
2286 atom_codes(EnVal,EC),
2287 parse_expr_for_visb(EC,L5,EPos,EnabledValExpr),
2288 atom_codes(DisVal,DC),
2289 parse_expr_for_visb(DC,L5,DPos,DisabledValExpr),
2290 (debug_mode(off) -> true
2291 ; translate_bexpression_with_limit(EnabledValExpr,30,EVS),
2292 translate_bexpression_with_limit(DisabledValExpr,30,DVS),
2293 formatsilent('Enabling item for event ~w and SVG ID ~w and attribute ~w : ~w <-> ~w~n',[Event,SvgID,Attr,EVS,DVS])
2294 ).
2295
2296 assert_visb_enabling_item_list(Event,TypedPred,EnableList,File,Pos) :-
2297 maplist(check_enabling_item(Event),EnableList),
2298 (EnableList \= []
2299 -> (debug_mode(off)
2300 -> true
2301 ; format('Associating enabling/disabling list with event ~w and predicate: ',[Event]), translate:print_bexpr(TypedPred),nl),
2302 assert(visb_event_enable_list(Event,TypedPred,EnableList,File,Pos))
2303 ; true).
2304
2305 check_enabling_item(Event,visb_enable_item(SvgID,Attr,_,_,PosAttr)) :-
2306 (visb_item(SvgID,Attr,_,_,_Desc,DuplicatePos,_)
2307 -> (extract_span_description(DuplicatePos,DuplPos) -> true; DuplPos=DuplicatePos),
2308 ajoin(['VisB conflict for SVG ID ',SvgID,' and attribute ',Attr,
2309 '. Conflict between VisB item (',DuplPos,') and VisB enable/disable entry for event: '],Msg),
2310 add_warning(visb_visualiser,Msg,Event,PosAttr)
2311 ; true).
2312
2313 valid_additional_attributes(comment).
2314 valid_additional_attributes(description).
2315 valid_additional_attributes(optional).
2316 valid_additional_attributes(override).
2317
2318 % check if there are additional unprocessed args and generate a warning
2319 check_additional_args(JsonList,File) :-
2320 get_attr_with_pos(Attr,JsonList,_,File,Pos),
2321 \+ valid_additional_attributes(Attr),
2322 add_warning(visb_visualiser,'Ignoring unknown JSON field: ',Attr,Pos),
2323 fail.
2324 check_additional_args(_,_).
2325
2326
2327 % construct a pre-post typed predicate for a VisB Event
2328 construct_pre_post_predicate(SvgID,OpName,Preds,TypedPred,Pos) :-
2329 set_error_context(visb_error_context(event,SvgID,OpName,Pos)),
2330 maplist(construct_pre_post_pred(OpName,Pos),Preds,TL),
2331 clear_error_context,
2332 conjunct_predicates(TL,TypedPred).
2333
2334
2335 construct_pre_post_pred(OpName,Pos,PredStr,TypedPred) :- empty_b_event(OpName),!,
2336 add_error(visb_visualiser,'Cannot parse VisB event predicate without event name:',PredStr,Pos),
2337 TypedPred = b(truth,pred,[]).
2338 construct_pre_post_pred(OpName,Pos,String,TypedExpr) :- special_operation(OpName),!,
2339 % we have a special operation; allow to provide an expression with options/parameters
2340 construct_pre_post_for_special(Pos,String,TypedExpr).
2341 construct_pre_post_pred(OpName,Pos,String,TypedPred) :-
2342 atom_codes(String,Codes), replace_special_patterns(Codes,RCodes,Pos), %format("Replaced : ~S~n",[RCodes]),
2343 get_visb_extra_scope([identifier(VisBExtraScope)]),
2344 visb_click_meta_b_type(MetaRecType),
2345 ExtraScope = [identifier([b(identifier('VISB_CLICK_META_INFOS'),MetaRecType,[visb_generated])|VisBExtraScope])],
2346 (b_parse_machine_operation_pre_post_predicate(RCodes,ExtraScope,TypedPred,OpName,gen_parse_errors_for(Pos))
2347 -> true
2348 ; add_error(visb_visualiser,'Error for VisB event predicate:',String,Pos),
2349 TypedPred = b(truth,pred,[])
2350 ).
2351
2352 construct_pre_post_for_special(Pos,Pred,TypedExpr) :- member(Pred,[btrue,bfalse]), !,
2353 add_warning(visb_visualiser,'Special operations require an expression specifying the parameter values, not a predicate: ',Pred,Pos),
2354 TypedExpr = b(integer(0),integer,[]).
2355 construct_pre_post_for_special(Pos,String,TypedExpr) :-
2356 atom_codes(String,Codes),
2357 GenParseErrors=gen_parse_errors_for(Pos),
2358 parse_expr(Codes,TypedExpr,GenParseErrors). % TODO: should we require a predicate instead, and provide arg names?
2359
2360 % replace special patterns by dummy values to avoid error messages in ProB2-UI
2361 replace_special_patterns([],[],_Pos) :- !.
2362 replace_special_patterns([37|T],Res,Pos) :- !, % percentage sign %
2363 replace_aux(T,Res,Pos).
2364 replace_special_patterns([H|T],[H|RT],Pos) :- !, replace_special_patterns(T,RT,Pos).
2365
2366 replace_aux(Input,Res,Pos) :-
2367 replace_pat(PAT,Replacement),
2368 append(PAT,T,Input),
2369 !,
2370 atom_codes(PatAtom,PAT),
2371 ajoin(['The %',PatAtom,' pattern is obsolete. Please use VISB_CLICK_META_INFOS\'',PatAtom,' instead.'],Msg),
2372 add_warning(visb_visualiser,Msg,'',Pos),
2373 append(Replacement,ResT,Res),
2374 replace_special_patterns(T,ResT,Pos).
2375 replace_aux(Input,[37|Res],Pos) :- !, replace_special_patterns(Input,Res,Pos).
2376
2377 replace_pat("shiftKey","VISB_CLICK_META_INFOS'shiftKey").
2378 replace_pat("metaKey","VISB_CLICK_META_INFOS'metaKey").
2379 replace_pat("pageX","VISB_CLICK_META_INFOS'pageX").
2380 replace_pat("pageY","VISB_CLICK_META_INFOS'pageY").
2381
2382
2383 % small utils:
2384 % ----------------
2385
2386 % a variation of between/3 with a step argument
2387 between(From,To,_,_) :- From > To, !,fail.
2388 between(From,_,_,From).
2389 ?between(From,To,Step,Elem) :- F1 is From+Step, between(F1,To,Step,Elem).
2390
2391
2392 parse_expr(ExprCodes,TypedExpr,_GenParseErrors) :-
2393 is_simple_classical_b_identifier_codes(ExprCodes),
2394 atom_codes(DefID,ExprCodes),
2395 visb_definition(DefID,Type,_DefFormula,Class,_VPos,_),
2396 !,
2397 TypedExpr = b(identifier(DefID),Type,[type_of_formula(Class)]).
2398 parse_expr(ExprCodes,TypedExpr,GenParseErrors) :-
2399 temporary_set_preference(allow_arith_operators_on_reals,true,CHNG),
2400 get_visb_extra_scope(ExtraScope),
2401 % formatsilent('Parsing: ~s (extra ids: ~w)~n',[ExprCodes,ExtraScope]), start_ms_timer(T1),
2402 call_cleanup(bmachine:b_parse_machine_expression_from_codes_with_prob_ids(ExprCodes,ExtraScope,TypedExpr,
2403 GenParseErrors),
2404 reset_temporary_preference(allow_arith_operators_on_reals,CHNG)).
2405 %stop_ms_walltimer_with_msg(T1,'parsing: ').
2406 % TODO: we could share a machine parameter M like in prob2_interface
2407 % so that b_type_expression_for_full_b_machine will load machine only once
2408 % cf b_type_open_predicate_for_full_b_machine
2409
2410 determine_type_of_visb_formula(b(_,_,[type_of_formula(Class)]),all,Res) :- !,
2411 Res = Class. % generated by VisB, TODO: store UsedTIds in type_of_formula(.)
2412 determine_type_of_visb_formula(TypedExpr,TIds,Class) :-
2413 determine_type_of_formula_with_visb_defs(TypedExpr,TIds,Class).
2414
2415 %check for used_ids inside TypedExpr an see what type of visb_definition are used
2416 determine_type_of_formula_with_visb_defs(TypedExpr,TIds,ResClass) :-
2417 determine_type_of_formula(TypedExpr,TIds,Class1), % compute class w/o knowledge of VisB definitions
2418 ? (class_more_general_than(Class2,Class1),
2419 ? required_by_visb_def(TIds,Class2) -> Class=Class2
2420 ; Class=Class1),
2421 (Class=requires_variables -> ResClass=Class
2422 ; expression_requires_state(TypedExpr) -> ResClass = requires_variables
2423 ; ResClass=Class).
2424
2425
2426 expression_requires_state(TypedExpr) :-
2427 (map_over_bexpr(sub_expression_requires_state,TypedExpr) -> true ; fail).
2428 % TODO: should we also check is_not_declarative/1 ? e.g., for RANDOM or CHANGED
2429 sub_expression_requires_state(external_pred_call(P,_)) :- external_function_requires_state(P).
2430 sub_expression_requires_state(external_function_call(P,_)) :- external_function_requires_state(P).
2431
2432
2433 class_more_general_than(requires_variables,requires_nothing).
2434 class_more_general_than(requires_variables,requires_constants).
2435 class_more_general_than(requires_constants,requires_nothing).
2436
2437 required_by_visb_def(TIds,Class) :-
2438 ? member(TID,TIds), get_texpr_id(TID,ID),visb_definition(ID,_,_,Class,_,_).
2439
2440
2441 get_visb_extra_scope([identifier(ExtraIDs)]) :-
2442 get_visb_extra_identifiers(ExtraIDs).
2443 get_visb_extra_identifiers(ExtraIDs) :-
2444 findall(b(identifier(ID),Type,[visb_generated]),visb_definition(ID,Type,_,_,_,_),ExtraIDs).
2445
2446 % replace a pattern code prefixed by % by another code list
2447 replace_in_json(Pattern,RepStr,string(Val),string(NewVal)) :- !, replace_atom(Pattern,RepStr,Val,NewVal).
2448 replace_in_json(Pattern,RepStr,array(Vals),array(NewVals)) :- !, maplist(replace_in_json(Pattern,RepStr),Vals,NewVals).
2449 replace_in_json(Pattern,RepStr,json(Vals),json(NewVals)) :- !, maplist(replace_in_json_pair(Pattern,RepStr),Vals,NewVals).
2450 replace_in_json(_,_,Val,Val). % number/literal (no replacement necessary)
2451
2452 replace_in_json_pair(Pattern,RepStr,'='(KIn,VIn,Pos),'='(KOut,VOut,Pos)) :-
2453 replace_atom(Pattern,RepStr,KIn,KOut),
2454 replace_in_json(Pattern,RepStr,VIn,VOut).
2455
2456 replace_atom(Pattern,RepStr,Val,NewVal) :-
2457 atom_codes(Val,Codes),
2458 replace_pat(Pattern,RepStr,NewCodes,Codes,[]),
2459 atom_codes(NewVal,NewCodes). % TO DO: keep as codes for efficiency
2460
2461 :- assert_must_succeed((visb_visualiser: replace_pat("0","_1_",Res,"ab%0cd",[]), Res == "ab_1_cd")).
2462 :- assert_must_succeed((visb_visualiser: replace_pat("0","",Res,"ab%0%0cd%0",[]), Res == "abcd")).
2463 % dcg utility to replace %Pat by NewStr constructing Res
2464 replace_pat(Pat,NewStr,Res) --> "%", Pat, !, {append(NewStr,TR,Res)}, replace_pat(Pat,NewStr,TR).
2465 replace_pat(Pat,RepStr,[H|T]) --> [H],!, replace_pat(Pat,RepStr,T).
2466 replace_pat(_,_,[]) --> [].
2467
2468
2469 % small JSON utils:
2470 % ----------------
2471
2472 ?get_attr(Attr,List,Val) :- member('='(Attr,Val,_),List).
2473 get_attr_with_pos(Attr,List,Val,File,Pos) :-
2474 El = '='(Attr,Val,_),
2475 ? member(El,List),
2476 get_pos_from_list([El],File,Pos).
2477
2478 ?del_attr(Attr,List,Val,Rest) :- select('='(Attr,Val,_Pos),List,Rest).
2479 %del_attr_with_pos(Attr,List,Val,Rest,Pos) :- select('='(Attr,Val,Pos),List,Rest).
2480 ?del_attr_with_pos(Attr,List,Val,Rest,File,PosTerm) :- select('='(Attr,Val,From-To),List,Rest),!,
2481 PosTerm = src_position_with_filename_and_ec(From,1,To,1,File).
2482 ?non_det_del_attr_with_pos(Attr,List,Val,Rest,File,PosTerm) :- select('='(Attr,Val,From-To),List,Rest),
2483 PosTerm = src_position_with_filename_and_ec(From,1,To,1,File).
2484
2485 force_del_attr(Attr,List,Val,Rest,File) :- force_del_attr_with_pos(Attr,List,Val,Rest,File,_).
2486
2487 ?force_del_attr_with_pos(Attr,List,Val,Rest,File,PosTerm) :- select('='(Attr,Val,From-To),List,Rest),!,
2488 %TODO: we would ideally want to extract the exact column position of Val, for this we need to extend the JSON parser first
2489 PosTerm = src_position_with_filename_and_ec(From,1,To,1,File).
2490 force_del_attr_with_pos(Attr,List,_,_,File,_) :- get_pos_from_list(List,File,Pos),!,
2491 add_error(visb_visualiser,'The JSON object has no attribute:',Attr,Pos),fail.
2492
2493 construct_prob_pos_term(From-To,File,PosTerm) :- !,
2494 PosTerm = src_position_with_filename_and_ec(From,1,To,1,File).
2495 construct_prob_pos_term(Pos,_,Pos).
2496
2497 force_get_attr_nr(Attr,List,Nr,File) :-
2498 force_del_attr_with_pos(Attr,List,AttrVal,_,File,Pos),!,
2499 get_number_value(AttrVal,Nr,Attr,Pos).
2500
2501 get_number_value(AttrVal,Nr,Attr,Pos) :-
2502 (AttrVal = number(Nr) -> true
2503 ; AttrVal = string(StrAttrVal),
2504 atom_codes(StrAttrVal,AttrValC),
2505 parse_expr(AttrValC,TypedExpr,gen_parse_errors_for(Pos)),
2506 determine_type_of_visb_formula(TypedExpr,UsedTIds,Class)
2507 % Class = requires_nothing, requires_constants, requires_variables
2508 ->
2509 (Class = requires_variables
2510 -> ajoin(['The JSON formula for the attribute"',Attr,
2511 '" must not depend on variables:'],Msg),
2512 add_error(visb_visualiser,Msg,StrAttrVal,Pos),fail
2513 ; Class = requires_constants,
2514 \+ is_concrete_constants_state_id(_)
2515 -> ajoin(['The JSON formula for the attribute"',Attr,
2516 '" depends on constants which have not been set up (via SETUP_CONSTANTS):'],Msg),
2517 add_error(visb_visualiser,Msg,StrAttrVal,Pos),fail
2518 ; Class = requires_constants,
2519 multiple_concrete_constants_exist,
2520 ajoin(['The JSON formula for the attribute"',Attr,
2521 '" depends on constants and multiple solutions for SETUP_CONSTANTS exist:'],Msg),
2522 add_warning(visb_visualiser,Msg,StrAttrVal,Pos),fail
2523 ; get_texpr_type(TypedExpr,Type),
2524 is_number_type(Type)
2525 -> eval_static_def(Class,'VisB attribute',Attr,TypedExpr,UsedTIds,ResVal,Pos),
2526 get_number_from_bvalue(ResVal,Nr)
2527 ; get_texpr_type(TypedExpr,Type),
2528 % it could produce a string which is a number; we could try and convert to a number
2529 ajoin(['The type ',Type,' of the JSON value formula for the attribute "',Attr,
2530 '" is not a number:'],Msg),
2531 add_error(visb_visualiser,Msg,StrAttrVal,Pos),fail
2532 )
2533 ; ajoin(['The JSON value for the attribute "',Attr,'" cannot be parsed as a number:'],Msg),
2534 add_error(visb_visualiser,Msg,AttrVal,Pos),fail).
2535
2536 is_number_type(integer).
2537 is_number_type(real).
2538
2539
2540 get_number_from_bvalue(int(Nr),Res) :- !, Res=Nr.
2541 get_number_from_bvalue(Term,Res) :- is_real(Term,Nr),!,Res=Nr.
2542
2543 get_pos_from_list(json(List),File,Pos) :- !, get_pos_from_list(List,File,Pos).
2544 get_pos_from_list([H|T],File,RPos) :-
2545 H='='(_,_,From-_),
2546 last([H|T],
2547 '='(_,_,_-To)),
2548 !,
2549 RPos=src_position_with_filename_and_ec(From,1,To,1,File).
2550 get_pos_from_list(_,File,File). % should we provide another term?
2551
2552 % ----------------------------------
2553
2554
2555 % computing updates to SVG for a given StateId:
2556 % predicate to obtain required setAttribute changes to visualise StateId
2557 % looks up visb_item facts but also evaluates VISB_SVG_UPDATE definitions
2558 get_change_attribute_for_state(StateId,SvgID,SvgAttribute,Value) :-
2559 set_error_context(checking_context('VisB:','computing attributes for state')),
2560 get_expanded_bstate(StateId,ExpandedBState),
2561 set_context_state(StateId,get_change_attribute_for_state), % also sets it for external functions
2562 % TODO: also set history so that get_current_history in external_functions is more reliable
2563 ? call_cleanup(get_change_aux(StateId,ExpandedBState,SvgID,SvgAttribute,Value),
2564 (clear_context_state,clear_error_context)).
2565
2566 get_change_aux(StateId,ExpandedBState,SvgID,SvgAttribute,Value) :-
2567 ? get_aux2(StateId,ExpandedBState,SvgID0,SvgAttribute0,Value0,DefPos),
2568 post_process_visb_item(SvgID0,SvgAttribute0,Value0,DefPos,SvgID,SvgAttribute,Value).
2569 get_aux2(StateId,ExpandedBState,SvgID,SvgAttribute,Value,DefPos) :-
2570 % first get updates from DEFINITIONS which usually return sets of records
2571 ? get_svg_object_updates_from_definitions(ExpandedBState,SvgID,SvgAttribute,Value,DefPos),
2572 debug_format(19,' VISB_SVG_UPDATE ~w:~w = ~w (in state ~w)~n',[SvgID,SvgAttribute,Value,StateId]).
2573 get_aux2(StateId,ExpandedBState,SvgID,SvgAttribute,Value,Pos) :-
2574 % TODO: check if visibility item exists, and if value is false: do not compute the rest
2575 ? get_visb_item_formula(SvgID,SvgAttribute,Formula,Pos,ExpandedBState),
2576 % TODO: if UsedIds=[] only set attribute once, if it requires_only_constants : ditto
2577 evaluate_visb_formula(Formula,'VisB item',SvgID,ExpandedBState,FValue,Pos),
2578 %b_value_to_string(FValue,Value),
2579 extract_attr_value(SvgAttribute,FValue,Value,Pos),
2580 debug_format(19,' VisB item ~w:~w = ~w (in state ~w)~n',[SvgID,SvgAttribute,Value,StateId]).
2581
2582 % post-process certain items, like title to adapt the value and id:
2583 % SVG does not support a title attribute; we need a title child and set its text attribute
2584 post_process_visb_item(SvgID,title,Value,Pos,NewID,text,NewValue) :-
2585 (visb_svg_object_debug_info(SvgID,DebugInfo) -> ajoin([Value,'\n',DebugInfo],NewValue) ; NewValue=Value),
2586 ? (visb_svg_parent(SvgID,TitleID),
2587 visb_svg_object(TitleID,title,_,_,_)
2588 -> NewID=TitleID,
2589 debug_format(9,'Redirecting title update for ~w to child object ~w~n',[SvgID,TitleID])
2590 ; visb_svg_object(SvgID,_SVG_Class,_RestAttrs,_Desc,_Pos1)
2591 -> % this is an object we created
2592 add_warning(visb_visualiser,'Could not find title child object, be sure to define a static title attribute for SVG object: ',SvgID,Pos),
2593 fail
2594 ; add_warning(visb_visualiser,'SVG does not natively support title attributes: ',SvgID,Pos),
2595 fail
2596 ),!.
2597 post_process_visb_item(SvgID,Attr,Value,_,SvgID,Attr,Value).
2598
2599 % ------------------
2600
2601 % convert B value to Json String
2602 b_value_to_string(string(SValue),Res) :- !, Res=SValue. % What about quoting,...?
2603 b_value_to_string(FValue,Res) :-
2604 translate_bvalue_to_codes(FValue,ValCodes),
2605 atom_codes(Res,ValCodes).
2606
2607 % attributes for which we convert pairs to the concatenation of strings
2608 is_id_or_text_attribute(id).
2609 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
2610 is_id_or_text_attribute('trigger_id').
2611 is_id_or_text_attribute('trigger-id').
2612 is_id_or_text_attribute(A) :- is_text_attribute(A).
2613 % children
2614 is_text_attribute('text').
2615 is_text_attribute('transform').
2616 is_text_attribute('event'). % for VISB_SVG_EVENTS
2617 is_text_attribute('predicate'). % for VISB_SVG_EVENTS
2618 is_text_attribute('svg_class').
2619
2620
2621 b_value_to_id_string(Val,String) :- b_val_to_id_string_aux(Val,add_underscore,String).
2622 b_value_to_text_string(Val,String) :- b_val_to_id_string_aux(Val,no_underscore,String).
2623
2624 % a special string conversion which e.g., allows to use things like ("ab",2) as id which gets translated to ab2
2625 % also useful for text attributes
2626 b_val_to_id_string_aux(string(SValue),_,Res) :- !, Res=SValue.
2627 b_val_to_id_string_aux((A,B),Add,Res) :- !,
2628 b_val_to_id_string_aux(A,Add,VA), b_val_to_id_string_aux(B,Add,VB),
2629 (Add=add_underscore
2630 -> atom_concat('_',VB,VB1) % introduce separator; in case we have things like numbers so that (12,3) /= (1,23)
2631 ; VB1=VB % for fields like predicate, transform, ... we do not want additional underscores
2632 ),
2633 atom_concat(VA,VB1,Res).
2634 b_val_to_id_string_aux(Set,Add,Res) :- singleton_set(Set,El),!, b_val_to_id_string_aux(El,Add,Res).
2635 % TODO: maybe convert sequence of values using conc
2636 b_val_to_id_string_aux(FValue,_,Res) :-
2637 translate_bvalue_to_codes(FValue,ValCodes),
2638 atom_codes(Res,ValCodes).
2639
2640 % get either a regular VisB item or an item associated with a VisB event and its enabled status
2641 get_visb_item_formula(SvgID,SvgAttribute,Formula,Pos,_ExpandedBState) :-
2642 ? visb_item(SvgID,SvgAttribute,Formula,_UsedIds,_Desc,Pos,_). % regular VisB item
2643 get_visb_item_formula(SvgID,SvgAttribute,Formula,Pos,ExpandedBState) :- % item within VisB event
2644 visb_event_enable_list(OpName,TypedPred,EnableList,_,ItemPos),
2645 debug_format(19,'Checking enabledness of VisB event ~w~n',[OpName]),
2646 (check_enabled(OpName,TypedPred,ExpandedBState,ItemPos)
2647 -> Formula=EnabledValExpr
2648 ; Formula=DisabledValExpr
2649 ),
2650 member(visb_enable_item(SvgID,SvgAttribute,EnabledValExpr,DisabledValExpr,Pos), EnableList).
2651
2652 check_enabled(OpName,Pred,ExpandedBState,Pos) :-
2653 special_operation(OpName),!,
2654 special_operation_enabled(OpName,Pred,ExpandedBState,Pos).
2655 check_enabled(OpName,Pred,ExpandedBState,Pos) :-
2656 b_is_operation_name(OpName),
2657 % TODO: see if we can use GUARD without execution
2658 % TODO: not yet working for XTL mode
2659 execute_operation_by_predicate_in_state_with_pos(ExpandedBState,OpName,Pred,_OpTerm,_NewState,Pos,_).
2660
2661
2662 get_expanded_bstate(StateId,ExpandedBState) :-
2663 \+ b_or_z_mode,!,
2664 StateId \= root,
2665 % in XTL mode we need to access the state via external functions like STATE_PROPERTY
2666 get_static_visb_state([],ExpandedBState).
2667 get_expanded_bstate(StateId,ExpandedBState) :-
2668 visited_expression(StateId,State),
2669 state_corresponds_to_initialised_b_machine(State,BState),
2670 debug_format(19,'Adding VisB definitions to state: ~w~n',[StateId]),
2671 add_prob_deferred_set_elements_to_store(BState,BState2,visible), % add prob_ids
2672 findall(visb_definition(DefID,Type,DefFormula,Class,VPos,Special),
2673 visb_definition(DefID,Type,DefFormula,Class,VPos,Special),DefList),
2674 eval_defs(DefList,BState2,ExpandedBState).
2675
2676
2677 evaluate_static_visb_formula(Formula,Kind,Nr,InState,ResValue,Pos) :-
2678 get_static_visb_state(InState,StaticState),
2679 evaluate_visb_formula(Formula,Kind,Nr,StaticState,ResValue,Pos).
2680
2681 evaluate_visb_formula(Formula,Kind,Nr,BState2,ResValue,Pos) :-
2682 % add_message(visb,'Evaluating: ',Kind:Nr,Pos), debug:nl_time, %set_prolog_flag(profiling,on), print_profile,
2683 ? (b_compute_explicit_epression_no_wf(Formula,[],BState2,ResValue,Kind,Nr,Pos) -> true
2684 ; add_error(visb_visualiser,'Evaluation of VisB formula failed:',Formula,Pos),
2685 fail).
2686
2687 % evaluate VisB definitions in order one by one, adding values to state
2688 eval_defs([],State,State).
2689 eval_defs([visb_definition(ID,_,TypedExpr,_Class,VPos,Special)|T],State0,State2) :-
2690 (Special \= regular_def
2691 -> State1=State0 % ignore special defs; they are processed separately
2692 ; b_compute_expression_nowf(TypedExpr,[],State0,ResValue,'VisB definition',ID,VPos),
2693 State1 = [bind(ID,ResValue)|State0], % store value for later definitions and VisB items
2694 (debug_mode(off) -> true
2695 ; translate_bvalue_to_codes_with_limit(ResValue,2000,RC),
2696 formatsilent(' VisB definition ~w == ~s~n',[ID,RC]))
2697 ),
2698 eval_defs(T,State1,State2).
2699
2700 % check if we have a static value for a VisB definition:
2701 visb_def_static_value(DefID,Value) :-
2702 ? visb_definition(DefID,_,b(value(Value),_,_),Class,_,SpecialClass),
2703 SpecialClass = regular_def,
2704 (Class = requires_nothing ; Class = requires_constants). % probably we do not need to check this, as we have value/1
2705
2706 get_static_visb_state(InState,FullState) :-
2707 findall(bind(DefID,Value),visb_def_static_value(DefID,Value),FullState,InState).
2708 % TO DO: get state with deferred_set_elements,...
2709
2710 % ----------------------------------
2711
2712 % generate a stand-alone HTML file with a visualisation for all states in the list
2713
2714 generate_visb_html(StateIds,File,Options) :-
2715 safe_open_file(File,write,Stream,[encoding(utf8)]),
2716 generate_html_to_stream(StateIds,Stream,[html_file/File|Options]),
2717 close(Stream).
2718
2719 generate_visb_html_to_codes(StateIds,Options,Codes) :-
2720 with_open_stream_to_codes(
2721 generate_html_to_stream(StateIds,Stream,Options),
2722 Stream,Codes,[]).
2723
2724
2725 % generate an HTML file to visualise the given StateId
2726 generate_html_to_stream(StateIds,Stream,Options) :-
2727 set_id_namespace_prefix_for_states(StateIds,Options),
2728 write_visb_template('visb_template_header.html',Stream),
2729 (member(show_svg_downloads,Options) -> write_visb_template('visb_template_svg_downloads.html',Stream) ; true),
2730 format(Stream,' <script>~n',[]),
2731 retractall(js_generated_function(_)),
2732 length(StateIds,Len),
2733 format(Stream,' const differences = [~n',[]),
2734 maplist(gen_visb_visualise_function(Stream,Options,Len,StateIds),StateIds),
2735 write_visb_template('visb_template_replayTrace.html',Stream),
2736 format(Stream,' </script>~n~n',[]),
2737 gen_registerHovers_scipt(Stream,Options),
2738 write_visb_template('visb_template_middle.html',Stream),
2739 (no_svg_available
2740 -> format(Stream,' <button type="button" class="collapsible-style">No SVG Visualisation Available</button>~n',[])
2741 ; % generate SVG section
2742 (member(no_header,Options) -> true
2743 ; format(Stream,' <button type="button" class="collapsible collapsible-style active">SVG Visualisation</button>~n',[])
2744 ),
2745 format(Stream,' <div style="position: relative;">~n',[]), % container for SVG download buttons
2746 format(Stream,' <div text-align="left" id="visb_svg_outer_container" class="svg-outer-container">~n',[]),
2747 format(Stream,' <div id="visb_svg_inner_container" class="svg-inner-container">~n',[]),
2748 %format(Stream,' <fieldset> <legend>Visualisation:</legend>~n',[]), % comment in to draw a border
2749 (StateIds = [SingleStateId] -> GenForState=SingleStateId ; GenForState=root),
2750 copy_svg_file_and_gen_objects(Stream,GenForState,_SVGinlined),
2751 % TO DO: avoid creating JS code below if _SVGinlined
2752 %format(Stream,' </fieldset>~n',[]),
2753 format(Stream,' </div>~n',[]), % inner container
2754 format(Stream,' </div>~n',[]), % outer container
2755 format(Stream,' <button id="btnResetScale" class="visualisation-button" onclick="resetScale()">Reset View</button>~n',[]),
2756 (member(show_svg_downloads,Options) ->
2757 format(Stream,' <button onclick="downloadSVG()">Save SVG (Current State)</button>~n',[]),
2758 format(Stream,' <button onclick="downloadAllSVGs()">Save all SVGs</button>~n',[])
2759 ; true),
2760 format(Stream,' </div>~n',[]) % container for SVG download buttons
2761 ),
2762 (Len>1, memberchk(show_sequence_chart,Options) % don't export PlantUML for list of state IDs (sequence chart depends on trace)
2763 -> (create_temp_puml_files(Len,Files),
2764 uml_generator:write_uml_sequence_chart_all_states(Files), % generate .puml files
2765 tools_commands:gen_plantuml_output(Files,svg,[]) % generate .svg files
2766 -> format(Stream,' <button type="button" class="collapsible collapsible-style active">Sequence Chart Visualisation</button>~n',[]),
2767 format(Stream,' <div class="seq-chart-container">~n',[]),
2768 reverse(Files,RFiles),
2769 write_temp_puml_outputs(1,RFiles,Stream), % write SVG contents to HTML
2770 format(Stream,' </div>~n',[])
2771 ; add_warning(visb_visualiser,'HTML export: did not write the Sequence Diagram Visualisation due to an error in the PlantUML call.'),
2772 format(Stream,' <button type="button" class="collapsible-style">No Sequence Chart Visualisation Available</button>~n',[])
2773 )
2774 ; true),
2775 (Len>1
2776 -> %format(Stream,'~n<h3>Run Trace</h3>~n',[]),
2777 format(Stream,' <button type="button" class="collapsible-style">Replay Trace</button>~n',[]),
2778 format(Stream,' <div class="coll-content-vis">~n',[]),
2779 format(Stream,' <button id="btnPrev" onclick="backStep()" title="Go back one step">« Back</button>~n',[]),
2780 format(Stream,' <button id="btnNext" onclick="forwardStep()" title="Go forward one step">Forward »</button>~n',[]),
2781 format(Stream,' <button onclick="runAll(10)" title="Fast replay of entire trace">Run Trace (10 ms delay)</button>~n',[]),
2782 format(Stream,' <button onclick="runAll(500)" title="Slow replay of entire trace">Run Trace (500 ms delay)</button>~n',[]),
2783 format(Stream,' <button onclick="runAll(parseInt(delayInput.value))" title="Custom replay of entire trace">Run Trace with Delay (ms):</button>~n',[]),
2784 format(Stream,' <input id="delayInput" type="number" value="1000" min="0" step="100" onkeydown="if(event.key===\'Enter\') runAll(parseInt(this.value))">~n',[]),
2785 format(Stream,' <label class="visb-messages" style="float:right">~n',[]),
2786 format(Stream,' <input type="checkbox" id="checkbox_focus_svg"> Focus changes in SVG~n',[]),
2787 format(Stream,' </label>~n',[]),
2788 % We could decide to provide an option/preference for generating the visb_debug_messages field:
2789 % (check that ProB2-UI also generates this text field)
2790 format(Stream,' <br><label id="visb_debug_messages" class="visb-messages"> </label>~n',[]),
2791 format(Stream,' </div>~n',[]),
2792 format(Stream,' <progress id="trace_meter" min="0" max="~w" value="0"></progress>~n',[Len]) % progress of trace replay; note <meter> element also works
2793 ; true
2794 ),
2795 % generate a table with variables, constants, ...
2796 gen_state_table(Stream,Options,StateIds),
2797 gen_source_code_section(Stream,Options),
2798 % generate a table with the saved trace steps:
2799 (Len>1 -> gen_trace_table(Stream,StateIds) ; true),
2800 write_version_info(Stream,Options),
2801 (last(StateIds,_)
2802 -> format(Stream,' <script> replayStep(~w,false); </script>~n',[Len])
2803 % show the visualisation of the last state by default (without focussing affected elements)
2804 ; true % trace is empty, there is no last item
2805 ),
2806 write_visb_template('visb_template_footer.html',Stream),
2807 clear_id_namespace_prefix.
2808
2809 create_temp_puml_files(Len,[]) :- Len<1, !.
2810 create_temp_puml_files(Len,[Path|T]) :-
2811 system_call:get_temporary_filename('for_html.puml',Path),
2812 NewLen is Len-1,
2813 create_temp_puml_files(NewLen,T).
2814
2815
2816 write_temp_puml_outputs(_,[],_).
2817 write_temp_puml_outputs(Nr,[File|T],Stream) :-
2818 tools:split_filename(File,FileRoot,_Ext),
2819 ajoin([FileRoot,'.svg'],SvgFile),
2820 format(Stream,' <div id="seq_chart_~w" style="display:none">~n',[Nr]), % container for seq. charts
2821 write_file_to_stream(SvgFile,Stream),
2822 format(Stream,' </div>~n',[]), % container for seq. charts
2823 NNr is Nr+1,
2824 write_temp_puml_outputs(NNr,T,Stream).
2825
2826 % -----------------
2827
2828
2829 write_version_info(_,Options) :-
2830 member(no_version_info,Options),!.
2831 write_version_info(Stream,Options) :-
2832 version_str(Str),datime(datime(Yr,Mon,Day,Hr,Min,_Sec)),
2833 number_codes_min_length(Min,2,MC),
2834 format(Stream,' <button type="button" class="collapsible-style" title="Information about ProB and model">Info</button>~n',[]),
2835 format(Stream,'<div class="coll-content-vis visb-messages">~n',[]),
2836 format(Stream,'Generated on ~w/~w/~w at ~w:~s using <a href="https://prob.hhu.de/">ProB</a> version ~w~n',[Day,Mon,Yr,Hr,MC,Str]),
2837 (currently_opened_file(File)
2838 -> (File=package(Type) ->
2839 format(Stream,'<br>Main specification package: ~w~n',[Type])
2840 ; atom(File), get_relative_path(File,Options,Suffix) ->
2841 format(Stream,'<br>Main specification file: ~w',[Suffix]),
2842 format_file_info(Stream,File)
2843 ; format(Stream,'<br>Unknown main specification file: ~w~n',[File])
2844 )
2845 ; true),
2846 (b_machine_name(MainName)
2847 -> format(Stream,'<br>Main specification name: ~w~n',[MainName]) ; true),
2848 (visb_file_loaded(JSONFile,_,ModLocTime),
2849 JSONFile \= ''
2850 -> get_relative_path(JSONFile,Options,JSuffix),
2851 format(Stream,'<br>Main VisB JSON file: ~w',[JSuffix]),
2852 format_modified_info(Stream,ModLocTime),
2853 (get_non_empty_svg_file(SVGFile,ModLocTime2)
2854 -> get_relative_path(SVGFile,Options,SSuffix),
2855 format(Stream,'<br>VisB SVG file: ~w',[SSuffix]),
2856 format_modified_info(Stream,ModLocTime2)
2857 ; true
2858 )
2859 ; true).
2860
2861 get_non_empty_svg_file(SVGFile,ModLocTime2) :-
2862 visb_svg_file(RelFile,SVGFile,_,_,ModLocTime2),
2863 RelFile \= ''.
2864
2865 format_file_info(Stream,File) :-
2866 catch(file_property(File, modify_localtime, ModLocTime),
2867 E,
2868 (add_visb_lint_message('Could not obtain modification time for file',E,unknown), fail)),
2869 !,
2870 format_modified_info(Stream,ModLocTime).
2871 format_file_info(Stream,_) :- nl(Stream).
2872
2873
2874 get_relative_path(File,Options,RelPath) :-
2875 ? member(html_file/HF,Options),
2876 absolute_file_name(File,AF,[]),
2877 absolute_file_name(HF,AHF,[]),
2878 !,
2879 gen_relative_path(AF,AHF,RelPath). % only print relative information
2880 get_relative_path(File,_,File).
2881
2882
2883 % -----------------
2884
2885 % gen a table with all the individual steps of the trace
2886 gen_trace_table(Stream,StateIds) :-
2887 length(StateIds,Len),
2888 %format(Stream,'~n<h3>Trace (length=~w)</h3>~n',[Len]),
2889 format(Stream,' <button type="button" class="collapsible collapsible-style active">Trace (length=~w)</button>~n',[Len]),
2890 format(Stream,'<div class="coll-content-vis">~n',[]),
2891 ? (member(Obj,StateIds), get_state_and_action(Obj,_,_,DescStr), DescStr \= ''
2892 -> Opt=with_description ; Opt=no_description),
2893 gen_trace_table2(Stream,StateIds,Opt).
2894
2895 gen_trace_table2(Stream,StateIds,no_description) :-
2896 format(Stream,' <table> <tr> <th>Nr</th> <th>Event</th> <th>Target State ID</th> </tr>~n',[]),
2897 ? nth1(Nr,StateIds,Obj),
2898 get_state_and_action(Obj,StateId,ActionStr,_),
2899 ((visited_state_corresponds_to_initialised_b_machine(StateId) ; xtl_mode) % allow onclick to all rows in xtl_mode
2900 -> (invariant_violated(StateId) -> BtnStyle='style="background-color:rgb(255,179,179);border-radius:6px" ' ; BtnStyle=''),
2901 format(Stream,'~n <tr id="row~w" onclick="replayStep(~w)"><td>~w</td><td style="cursor:pointer">~w</td><td><button ~wonclick="replayStep(~w);">State ~w</button></td></tr>~n',
2902 [Nr,Nr,Nr,ActionStr,BtnStyle,Nr,StateId])
2903 ; format(Stream,'~n <tr id="row~w"><td>~w</td><td style="cursor:not-allowed">~w</td><td>State ~w</td></tr>~n',
2904 [Nr,Nr,ActionStr,StateId])
2905 ),
2906 fail.
2907 gen_trace_table2(Stream,StateIds,with_description) :-
2908 format(Stream,' <table> <tr> <th>Nr</th> <th>Event</th> <th>Description</th> <th>Target State ID</th> </tr>~n',[]),
2909 ? nth1(Nr,StateIds,Obj),
2910 get_state_and_action(Obj,StateId,ActionStr,DescStr),
2911 atom_codes(ActionStr,ActionCodes),html_escape_codes(ActionCodes,EAS),
2912 atom_codes(DescStr,DescCodes),html_escape_codes(DescCodes,EDS),
2913 ((visited_state_corresponds_to_initialised_b_machine(StateId) ; xtl_mode) % allow onclick to all rows in xtl_mode
2914 -> (invariant_violated(StateId) -> BtnStyle='style="background-color:rgb(255,179,179);border-radius:6px" ' ; BtnStyle=''),
2915 format(Stream,'~n <tr id="row~w" onclick="replayStep(~w)"><td>~w</td><td style="cursor:pointer">~s</td><td>~s</td><td><button ~wonclick="replayStep(~w);">State ~w</button></td></tr>~n',
2916 [Nr,Nr,Nr,EAS,EDS,BtnStyle, Nr,StateId])
2917 ; format(Stream,'~n <tr id="row~w"><td>~w</td><td style="cursor:not-allowed">~s</td><td>~s</td><td>State ~w</td></tr>~n',
2918 [Nr,Nr,EAS,EDS,StateId])
2919 ),
2920 fail.
2921 gen_trace_table2(Stream,_,_) :-
2922 format(Stream,' </table>~n </div>~n',[]).
2923
2924
2925 % utility to allow passing information about name of event/operation/action leading to state
2926 get_state_and_action(change_to_state_via_action(StateId,ActionStr,DescStr),StateId,ActionStr,DescStr) :- !.
2927 get_state_and_action(StateId,StateId,'','').
2928
2929 % -----------------
2930
2931 % inline provided svg file into html file:
2932 % second argument is either root or a particular state id for which the SVG file is to be created
2933 % the last argument is static_svg_inlined if all SVG objects were "inlined" into a single
2934 % SVG object (rather than via JavaScript functions to create the objects)
2935 copy_svg_file_and_gen_objects(Stream,_,static_svg_not_inlined) :- visb_svg_file(_,File,_,_,_), file_exists(File),
2936 !,
2937 write_file_to_stream(File,Stream),
2938 ( get_visb_contents_def(Contents,DefName,DefPos,static_svg_not_inlined),
2939 ajoin(['Copying ',DefName,' *after* SVG file: '],Msg),
2940 add_message(visb_visualiser,Msg,File,DefPos),
2941 format(Stream,'~w~n',[Contents]),
2942 fail
2943 ; true
2944 ),
2945 gen_new_svg_objects(Stream).
2946 copy_svg_file_and_gen_objects(_,_,_) :-
2947 visb_svg_file(File,AFile,_,Pos,_),
2948 File \= '',
2949 add_error(visb_visualiser,'The specified VisB SVG file does not exist:',AFile,Pos),
2950 fail.
2951 copy_svg_file_and_gen_objects(Stream,SingleStateId,static_svg_inlined) :- % copy an empty SVG stub
2952 visb_file_loaded(_,_,_),!,
2953 write_default_svg_contents(Stream,inline_objects(SingleStateId)).
2954 copy_svg_file_and_gen_objects(_,_,static_svg_not_inlined). % no SVG required; we have no items or events: probably just want HTML export of variables,...
2955
2956 % TODO: precompile and always assert as visb_special_definition (we could also evaluate it; could use template strings):
2957 get_visb_contents_def(Contents,DefName,DefPos,InlineObjects) :-
2958 ? get_and_eval_special_definition('VISB_SVG_CONTENTS',DefName,visb_contents,DefPos,ResValue,InlineObjects),
2959 b_value_to_string(ResValue,Contents).
2960 get_visb_contents_def(Contents,default_svg_contents,unknown,_InlineObjects) :-
2961 % default content, for VISB_CLICK_META_INFOS'jsVars
2962 Contents = '<script>let visb_vars = {};</script>'.
2963
2964 % get a definition either from B DEFINITIONS section, or if not present from the VisB JSON special definition list
2965 get_and_eval_special_definition(Prefix,DefName,JSONBackup,DefPos,ResValue,InlineObjects) :-
2966 (b_sorted_b_definition_prefixed(expression,Prefix,DefName,DefPos),
2967 ? b_get_typed_definition(DefName,[variables_and_additional_defs],TBody)
2968 ;
2969 visb_special_definition(JSONBackup,DefName,_Type,TBody,_Class,DefPos)
2970 ),
2971 % TODO: warn if we use static SVG
2972 ? get_typed_static_definition_with_constants_state(DefName,TBody,
2973 Body,DefPos,ConstantsState,InlineObjects,no_separation),
2974 evaluate_visb_formula(Body,DefName,'',ConstantsState,ResValue,DefPos).
2975
2976 % check if we have a DEFINITION with the indicated prefix
2977 special_definition_exists(Prefix) :-
2978 b_sorted_b_definition_prefixed(expression,Prefix,_DefName,_DefPos).
2979
2980 write_default_svg_contents(Stream,InlineObjects) :-
2981 (visb_empty_svg_box_height_width(H,W,ViewBox) -> true ; H=400, W=400, ViewBox=''),
2982 format(Stream,'<svg xmlns=\"http://www.w3.org/2000/svg\"~n',[]),
2983 (ViewBox=''
2984 -> format(Stream,' width="~w" height="~w" viewBox="0 0 ~w ~w" >~n',[W,H,W,H])
2985 ; format(Stream,' width="~w" height="~w" viewBox="~w" >~n',[W,H,ViewBox])
2986 ),
2987 ? ( get_visb_contents_def(Contents,_,_,InlineObjects),
2988 format(Stream,'~w~n',[Contents]),
2989 fail
2990 ; true),
2991 (InlineObjects=inline_objects(StateID) -> inline_new_svg_objects(Stream,StateID) ; true),
2992 format(Stream,'</svg>~n',[]).
2993
2994 % get SVG file contents in case no SVG file is provided by user
2995 get_visb_default_svg_file_contents(Codes) :-
2996 with_open_stream_to_codes(
2997 write_default_svg_contents(Stream,inline_objects(root)),
2998 % allow inlining for groups and title children in ProB2-UI
2999 Stream,
3000 Codes, []).
3001
3002 % -----------------
3003
3004 % create a script to add all additional SVG objects
3005 gen_new_svg_objects(_) :- \+ visb_svg_object(_,_,_,_,_),!.
3006 gen_new_svg_objects(Stream) :-
3007 format(Stream, '<script>~n',[]),
3008 format(Stream, ' const svg = document.querySelector("svg");~n',[]),
3009 format(Stream, ' const svgns = "http://www.w3.org/2000/svg";~n',[]),
3010 (gen_new_svg_object(Stream,svg_root,_),fail ; true),
3011 format(Stream, '</script>~n',[]).
3012
3013 % generate JS script to create an individual new object
3014 gen_new_svg_object(Stream,ParentID,SVGID) :-
3015 visb_svg_object(SVGID,SVG_Class,AttrList,_,_Pos),
3016 (ParentID=svg_root
3017 -> (visb_svg_child(SVGID,RealParentID) % only generate root svg objects that have no parents
3018 -> visb_svg_child_of_object_from_svg_file(SVGID) % unless the parent will not be created here in this loop
3019 ; RealParentID=ParentID
3020 )
3021 ; RealParentID=ParentID),
3022 add_svg_id_prefix(SVGID,SVGID2),
3023 format(Stream,' if(document.getElementById("~w") == null) {~n',[SVGID2]),
3024 format(Stream,' var new___obj = document.createElementNS(svgns,"~w");~n',[SVG_Class]),
3025 format(Stream,' new___obj.setAttribute("~w","~w");~n',[id,SVGID2]),
3026 maplist(gen_new_svg_attr(Stream,SVGID2),AttrList),
3027 (RealParentID \= svg_root
3028 -> format(Stream,' document.getElementById("~w").appendChild(new___obj);~n',[RealParentID])
3029 ; format(Stream,' svg.appendChild(new___obj);~n',[])
3030 ),
3031 format(Stream,' }~n',[]),
3032 (visb_svg_parent(SVGID,ChildID), % we can now generate the children
3033 gen_new_svg_object(Stream,SVGID,ChildID),
3034 fail
3035 ; true).
3036
3037 gen_new_svg_attr(Stream,_SVGID,svg_attribute(text,Val)) :- !,
3038 format(Stream,' new___obj.textContent = "~w";~n',[Val]).
3039 gen_new_svg_attr(Stream,_SVGID,svg_attribute(Attr,Val)) :-
3040 format(Stream,' new___obj.setAttribute("~w","~w");~n',[Attr,Val]).
3041
3042 % instead of creating a script to create new SVG objects,
3043 % create an inlined textual XML representation of the objects
3044 % this can be used to obtain a static SVG file which can be modified in an editor
3045 % and then later used instead of the VISB_SVG_OBJECTS definitions
3046 inline_new_svg_objects(Stream,StateId) :-
3047 get_dynamic_svgid_attributes_for_state(StateId,DynUpdateList), % compute updates only once
3048 ? visb_svg_object(SVGID,_,_,_,_), % lookup static SVG object
3049 \+ visb_svg_child(SVGID,_), % children will be created in the scope of their parent
3050 inline_new_svg_object(Stream,StateId,DynUpdateList,0,unknown,SVGID),
3051 fail.
3052 inline_new_svg_objects(_,_).
3053
3054 inline_new_svg_object(Stream,StateId,DynUpdateList,IndentLevel,ParentPos,SVGID) :-
3055 (visb_svg_object(SVGID,SVG_Class,StaticAttrList,_,Pos) -> true % lookup static SVG object
3056 ; add_warning(visb_visualiser,'Unknown SVG child object: ',SVGID,ParentPos),fail
3057 ),
3058 add_svg_id_prefix(SVGID,SVGID2), % for Jupyter
3059 indent_ws(Stream,IndentLevel),
3060 format(Stream,' <~w id="~w"',[SVG_Class,SVGID2]),
3061 (member(svgid_updates(SVGID,DynAttrList),DynUpdateList) % TODO: use avl_fetch
3062 -> override_attributes(StaticAttrList,DynAttrList,AttrList)
3063 ; AttrList=StaticAttrList),
3064 maplist(format_new_svg_attr(Stream,SVGID,Pos,TextContent),AttrList),
3065 (TextContent=''
3066 -> EscapedTextContent="" % set Text variable to empty if unbound
3067 ; do_not_escape_text_for_class(SVG_Class) -> atom_codes(TextContent,EscapedTextContent)
3068 ; atom_codes(TextContent,TCC), html_escape_codes(TCC,EscapedTextContent)),
3069 format(Stream,'>~s',[EscapedTextContent]), % Note: this text is not inside quotes, we need HTML escape
3070 IL1 is IndentLevel+1,
3071 ? ( visb_svg_parent(SVGID,Child),
3072 nl(Stream),
3073 inline_new_svg_object(Stream,StateId,DynUpdateList,IL1,Pos,Child),
3074 fail
3075 ; true),
3076 format(Stream,'</~w>~n',[SVG_Class]), % end marker
3077 fail.
3078 inline_new_svg_object(_,_,_,_,_,_).
3079
3080 % for foreignObjects the text may contain HTML tags which should not be escaped:
3081 do_not_escape_text_for_class(foreignObject).
3082 do_not_escape_text_for_class(script). % otherwise " quotes will be escaped to "
3083
3084 indent_ws(_,X) :- X<1,!.
3085 indent_ws(Stream,X) :- write(Stream,' '), X1 is X-1, indent_ws(Stream,X1).
3086
3087 % combinde svg_attribute/2 terms from two sorted lists, giving precedence to second list
3088 override_attributes([],L,R) :- !, R=L.
3089 override_attributes(L,[],R) :- !, R=L.
3090 override_attributes([svg_attribute(Attr1,Val1)|T1],[svg_attribute(Attr2,Val2)|T2],[svg_attribute(Attr3,Val3)|T3]) :-
3091 (Attr1=Attr2
3092 -> Attr3=Attr1, Val3=Val2, % dynamic value Val2 takes precedence
3093 override_attributes(T1,T2,T3)
3094 ; Attr1 @< Attr2 -> Attr3=Attr1, Val3=Val1, override_attributes(T1,[svg_attribute(Attr2,Val2)|T2],T3)
3095 ; Attr3=Attr2, Val3=Val2, override_attributes([svg_attribute(Attr1,Val1)|T1],T2,T3)
3096 ).
3097
3098 % get dynamic svg_attribute/2 list for a given state and SVG ID
3099 get_dynamic_svgid_attributes_for_state(root,List) :- !, List=[].
3100 get_dynamic_svgid_attributes_for_state(StateId,UpdateList) :-
3101 get_visb_attributes_for_state(StateId,List),
3102 sort(List,SList),
3103 group_set_attr(SList,'$$UNKNOWN$$',_,UpdateList).
3104
3105 group_set_attr([],_,[],[]).
3106 group_set_attr([set_attr(SvgID,Attr,Val)|T],SvgID,[svg_attribute(Attr,Val)|T1],T2) :- !,
3107 group_set_attr(T,SvgID,T1,T2).
3108 group_set_attr([set_attr(SvgID,Attr,Val)|T],_OldID,[],[svgid_updates(SvgID,L)|T2]) :- % a new SVGId is encountered
3109 group_set_attr([set_attr(SvgID,Attr,Val)|T],SvgID,L,T2).
3110
3111 % print svg attribute and extract text attribute
3112 format_new_svg_attr(Stream,SVGID,Pos,TextContent,svg_attribute(Attr,Val)) :- % TODO: text content
3113 (Attr=text
3114 -> (TextContent=Val -> true % TextContent is initially a variable and can be unified once
3115 ; add_warning(inline_new_svg_objects,'Multiple text attributes for: ',SVGID,Pos),
3116 add_debug_message(inline_new_svg_objects,' * Using text 1: ',TextContent),
3117 add_debug_message(inline_new_svg_objects,' * Ignoring text 2: ',Val)
3118 )
3119 ; number(Val) ->
3120 format(Stream,' ~w="~w"',[Attr,Val])
3121 ; escape_value_to_codes_for_js(Val,ECodes) ->
3122 format(Stream,' ~w="~s"',[Attr,ECodes])
3123 ; compound(Val), functor(Val,F,N) ->
3124 ajoin(['Cannot escape ',Attr,' *compound* ',F,'/',N,' value for ', SVGID,': '],Msg),
3125 add_error(visb_visualiser,Msg,Val,Pos),
3126 format(Stream,' ~w="~w"',[Attr,Val])
3127 ; ajoin(['Cannot escape ',Attr,' value for ', SVGID,': '],Msg),
3128 add_error(visb_visualiser,Msg,Val,Pos),
3129 format(Stream,' ~w="~w"',[Attr,Val])
3130 ).
3131
3132
3133 :- dynamic id_namespace_prefix/1.
3134 % prefix that can be useful for Jupyter notebooks so that for each state we have a different namespace
3135 % can also be useful for exporting a trace into a single HTML
3136 % TODO: does not work with JSON and SVG files
3137
3138
3139 set_id_namespace_prefix_for_states(_,Options) :-
3140 member(id_namespace_prefix(Pre),Options),!,
3141 (Pre = auto
3142 -> gensym('visb',ID), % for Jupyter this relies on the fact the gensym is *not* reset when loading another spec
3143 atom_concat(ID,'.',Prefix)
3144 ; Prefix=Pre
3145 ), set_id_namespace_prefix(Prefix).
3146 set_id_namespace_prefix_for_states(_,_).
3147
3148 set_id_namespace_prefix(Prefix) :- clear_id_namespace_prefix,
3149 assert(id_namespace_prefix(Prefix)).
3150 clear_id_namespace_prefix :- retractall(id_namespace_prefix(_)).
3151
3152 % add a namespace prefix to an SVG ID
3153 add_svg_id_prefix(SvgID,Res) :- id_namespace_prefix(Prefix),!,
3154 % option where we prefix all Ids with a namespace for Jupyter to combine multiple SVGs in single HTML page
3155 atom_concat(Prefix,SvgID,Res).
3156 add_svg_id_prefix(SvgID,SvgID).
3157
3158 % only add for known objects
3159 opt_add_svg_id_prefix(SvgID,Res) :- id_namespace_prefix(Prefix),
3160 visb_svg_object(SvgID,_,_,_,_),!, % only add prefix for SVG objects we know about (that were created by VisB)
3161 % option where we prefix all Ids with a namespace for Jupyter to combine multiple SVGs in single HTML page
3162 atom_concat(Prefix,SvgID,Res).
3163 opt_add_svg_id_prefix(SvgID,SvgID).
3164
3165 % -----------------
3166
3167 :- dynamic js_generated_function/1.
3168 :- dynamic last_attribute_values/3.
3169
3170 % define a visualise JS function to set the attributes for the given StateId
3171 gen_visb_visualise_function(Stream,Options,Len,StateIds,Obj) :-
3172 get_state_and_action(Obj,StateId,ActionStr,DescStr),
3173 ? nth1(Nr,StateIds,Obj),
3174 \+ js_generated_function(Nr), !,
3175 assertz(js_generated_function(Nr)),
3176 (Nr > 1 ->
3177 PrevNr is Nr-1, nth1(PrevNr,StateIds,PrevObj), get_state_and_action(PrevObj,PrevStateId,_,_)
3178 ; PrevStateId = -1),
3179 visb_visualise_function_aux(Stream,Options,Len,StateId,PrevStateId,Nr,ActionStr,DescStr),
3180 (Nr == Len ->
3181 retractall(last_attribute_values(_,_,_)),
3182 format(Stream,' ]~n',[])
3183 ; true).
3184 gen_visb_visualise_function(_,_,_,_,_).
3185
3186
3187 visb_visualise_function_aux(Stream,_,Len,StateId,_,Nr,ActionStr,DescStr) :-
3188 format(Stream,' [~n',[]),
3189 (Len>1 -> format(Stream,' {id: "trace_meter", attr: "value", val: "~w"},~n',[Nr]) ; true),
3190 (escape_value_to_codes_for_js(ActionStr,EAS), escape_value_to_codes_for_js(DescStr,EDS) ->
3191 % was only string_escape before; however, this turns e.g. |-> into ↦ which we don't want (we are in JS part here)
3192 format(Stream,' {id: "visb_debug_messages", attr: "text", val: "Step ~w/~w, State ID: ~w, Event: ~s ~s"},~n',[Nr,Len,StateId,EAS,EDS])
3193 ; string_escape(ActionStr,SEAS), string_escape(DescStr,SEDS), % fallback
3194 format(Stream,' {id: "visb_debug_messages", attr: "text", val: "Step ~w/~w, State ID: ~w, Event: ~w ~w"},~n',[Nr,Len,StateId,SEAS,SEDS])
3195 ),
3196 ? get_change_attribute_for_state(StateId,SvgID,SvgAttribute,Value),
3197 \+ last_attribute_values(SvgID,SvgAttribute,Value),
3198 retractall(last_attribute_values(SvgID,SvgAttribute,_)),
3199 assertz(last_attribute_values(SvgID,SvgAttribute,Value)),
3200 opt_add_svg_id_prefix(SvgID,SvgID2),
3201 (escape_value_to_codes_for_js(Value,ECodes)
3202 -> format(Stream,' {id: "~w", attr: "~w", val: "~s"},~n',[SvgID2,SvgAttribute,ECodes])
3203 ; format(Stream,' {id: "~w", attr: "~w", val: "~w"},~n',[SvgID2,SvgAttribute,Value])
3204 ),
3205 fail.
3206 visb_visualise_function_aux(Stream,Options,Len,StateId,PrevStateId,_,_,_) :-
3207 b_or_z_mode,
3208 member(show_variables(VarList),Options),
3209
3210 visited_expression(StateId,State),
3211 (visited_expression(PrevStateId,PrevState) -> true ; PrevState=root),
3212
3213 show_var_in_visb(VarList,ID),
3214 ? get_state_value_change(StateId,State,ID,Options,ResValCodes),
3215
3216 % current value:
3217 ajoin(['bVar_',ID],SvgID),
3218 change_svg_attribute_differences_aux(Stream,SvgID,'text',ResValCodes),
3219
3220 Len > 1, % don't add previous value and change markers for state-only HTML
3221 (state_corresponds_to_fully_setup_b_machine(PrevState,_), % don't show prev values before initialisation
3222 ? get_state_value_change(PrevStateId,PrevState,ID,Options,PrevResValCodes)
3223 -> true
3224 ; PrevResValCodes = "?"),
3225
3226 % mark row if value has changed in the last step
3227 ajoin(['row_bVar_',ID],SvgRowID),
3228 (ResValCodes = PrevResValCodes -> RowColor = white; RowColor = '#fffacd'),
3229 change_svg_attribute_differences_aux(Stream,SvgRowID,'bgcolor',RowColor),
3230
3231 % previous value:
3232 ajoin(['bVarPrev_',ID],SvgPrevID),
3233 change_svg_attribute_differences_aux(Stream,SvgPrevID,'text',PrevResValCodes),
3234
3235 fail.
3236 visb_visualise_function_aux(Stream,_Options,Len,StateId,PrevStateId,_,_,_) :-
3237 xtl_mode,
3238
3239 bv_get_top_level(IDs),
3240 member(ID,IDs),
3241 (bv_get_value_unlimited(ID,StateId,v(Val))
3242 -> atom_codes(Val,ResValCodes)
3243 ; ResValCodes = ""),
3244
3245 % current value:
3246 ajoin(['bVar_',ID],SvgID),
3247 change_svg_attribute_differences_aux(Stream,SvgID,'text',ResValCodes),
3248
3249 Len > 1, % don't add previous value and change markers for state-only HTML
3250 (PrevStateId \= root,
3251 bv_get_value_unlimited(ID,PrevStateId,v(PrevVal))
3252 -> atom_codes(PrevVal,PrevResValCodes)
3253 ; PrevResValCodes = ""),
3254
3255 % mark row if value has changed in the last step
3256 ajoin(['row_bVar_',ID],SvgRowID),
3257 (ResValCodes = PrevResValCodes -> RowColor = white; RowColor = '#fffacd'),
3258 change_svg_attribute_differences_aux(Stream,SvgRowID,'bgcolor',RowColor),
3259
3260 % previous value:
3261 ajoin(['bVarPrev_',ID],SvgPrevID),
3262 change_svg_attribute_differences_aux(Stream,SvgPrevID,'text',PrevResValCodes),
3263
3264 fail.
3265 visb_visualise_function_aux(Stream,Options,_,StateId,_,_,_,_) :-
3266 member(show_events(OpList),Options),
3267 get_state_value_enabled_operation_status(StateId,OpID,Enabled,ResValCodes,TransStr),
3268 show_var_in_visb(OpList,OpID),
3269 ajoin(['bOperation_',OpID],SvgID),
3270 \+ last_attribute_values(SvgID,'text',ResValCodes),
3271 retractall(last_attribute_values(SvgID,'text',_)),
3272 assertz(last_attribute_values(SvgID,'text',ResValCodes)),
3273 format(Stream,' {id: "~w", attr: "text", val: "~s"},~n',[SvgID,ResValCodes]),
3274 (Enabled=true -> BGCol=white ; BGCol='#f1f1f1'),
3275 format(Stream,' {id: "row_~w", attr: "bgcolor", val: "~s"},~n',[SvgID,BGCol]),
3276 escape_value_to_codes_for_js(TransStr,ETS),
3277 format(Stream,' {id: "name_~w", attr: "text", val: "~s"},~n',[SvgID,ETS]),
3278 % TO DO: highlight next event in trace, but then function needs one more parameter
3279 fail.
3280 visb_visualise_function_aux(Stream,Options,Len,_,_,Nr,_,_) :-
3281 (Len>1, member(show_sequence_chart,Options)
3282 -> format(Stream,' {id: "seq_chart_~w", attr: "style", val: "display:block"},~n',[Nr]),
3283 (Nr>1
3284 -> PNr is Nr-1, format(Stream,' {id: "seq_chart_~w", attr: "style", val: "display:none"},~n',[PNr])
3285 ; gen_seq_charts_setup(Stream,Len))), % all sequence charts except the first should be invisible
3286 fail.
3287 visb_visualise_function_aux(Stream,_,Len,_,_,Nr,_,_) :-
3288 Nr == Len ->
3289 format(Stream,' ]~n',[])
3290 ; format(Stream,' ],~n',[]).
3291
3292 gen_seq_charts_setup(_,Len) :- Len<2, !.
3293 gen_seq_charts_setup(Stream,Len) :-
3294 format(Stream,' {id: "seq_chart_~w", attr: "style", val: "display:none"},~n',[Len]),
3295 NLen is Len-1,
3296 gen_seq_charts_setup(Stream,NLen).
3297
3298 escape_value_to_codes_for_js(Atom,ECodes) :- atom(Atom),
3299 atom_codes(Atom,Codes), b_string_escape_codes(Codes,ECodes).
3300
3301 change_svg_attribute_differences_aux(Stream,ID,Attr,ValueCodes) :-
3302 (last_attribute_values(ID,Attr,ValueCodes)
3303 -> true
3304 ; retractall(last_attribute_values(ID,Attr,_)),
3305 assertz(last_attribute_values(ID,Attr,ValueCodes)),
3306 format(Stream,' {id: "~w", attr: "~w", val: "~s"},~n',[ID,Attr,ValueCodes])
3307 ).
3308
3309
3310 % generate JS script to register hovers
3311 ?gen_registerHovers_scipt(Stream,Options) :- \+ visb_has_hovers(_),
3312 nonmember(debugging_hovers,Options),
3313 !, % no hover exists
3314 format(Stream,' <script> function registerHovers() {} </script>~n',[]).
3315 gen_registerHovers_scipt(Stream,Options) :-
3316 (member(debugging_hovers,Options) -> GenDebug=true ; GenDebug=false), % gen debugging hovers
3317 % Jquery is no longer required:
3318 %format(Stream,' <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>~n',[]),
3319 format(Stream,' <script>~n',[]),
3320 format(Stream,' function registerHovers() {~n',[]),
3321 format(Stream,' var obj;~n',[]),
3322 ? visb_has_hovers(SVGID), % only generate hover function if necessary; TODO: examine other IDs for GenDebug
3323 opt_add_svg_id_prefix(SVGID,SVGID2),
3324 format(Stream,' obj = document.getElementById("~w");~n',[SVGID2]),
3325 format(Stream,' obj.onmouseover = function(ev){~n',[]),
3326 ? (visb_hover(SVGID,ID,Attr,EnterVal,_,_),
3327 opt_add_svg_id_prefix(ID,ID2),
3328 (GenDebug=false -> true
3329 ; format(Stream,' setAttr("~w","~w","SVG ID: ~w")~n',[visb_debug_messages,text,SVGID2])),
3330 format(Stream,' setAttr("~w","~w","~w")~n',[ID2,Attr,EnterVal]), fail ;
3331 format(Stream,' };~n',[])
3332 ),
3333 format(Stream,' obj.onmouseout = function(){~n',[]),
3334 ? (visb_hover(SVGID,ID,Attr,_,LeaveVal,_),
3335 opt_add_svg_id_prefix(ID,ID2),
3336 (GenDebug=false -> true
3337 ; format(Stream,' setAttr("~w","~w","~w")~n',[visb_debug_messages,text,'...'])
3338 ),
3339 format(Stream,' setAttr("~w","~w","~w")~n',[ID2,Attr,LeaveVal]), fail ;
3340 format(Stream,' };~n',[])
3341 ),
3342 fail.
3343 gen_registerHovers_scipt(Stream,_) :-
3344 format(Stream,' }~n </script>~n',[]).
3345
3346
3347 % ----------------------------------
3348
3349
3350 generate_visb_html_for_history_with_source(File) :-
3351 generate_visb_html_for_history(File,
3352 [show_constants(all),show_sets(all),show_variables(all),show_events(all),show_invariants,show_source]).
3353 generate_visb_html_for_history_with_vars(File) :-
3354 generate_visb_html_for_history(File,[show_constants(all),show_sets(all),show_variables(all),show_events(all)]).
3355 generate_visb_html_for_history(File) :-
3356 generate_visb_html_for_history(File,[]).
3357 generate_visb_html_for_history(File,Options) :-
3358 start_ms_timer(Timer),
3359 get_state_id_trace(T),
3360 T = [root|StateIds],
3361 set_unicode_mode,
3362 call_cleanup(get_action_trace_with_limit(120,Actions), % TODO: also get description of JSON traces
3363 unset_unicode_mode),
3364 reverse(Actions,FActions),
3365 combine_state_and_actions(StateIds,[root|StateIds],FActions,List),
3366 generate_visb_html(List,File,Options),
3367 stop_ms_walltimer_with_msg(Timer,'exporting history to VisB HTML file: ').
3368
3369
3370 combine_state_and_actions([],_,[],[]).
3371 combine_state_and_actions([StateId|TS],[PrevId|TP],[action(ActionStr,ATerm)|TA],
3372 [change_to_state_via_action(StateId,ActionStr,Desc)|TRes]) :-
3373 (get_operation_description_for_transition(PrevId,ATerm,StateId,D) -> Desc=D ; Desc=''),
3374 combine_state_and_actions(TS,TP,TA,TRes).
3375
3376 generate_visb_html_for_current_state(File) :-
3377 generate_visb_html_for_current_state(File,[show_variables(all)]).
3378 generate_visb_html_for_current_state(File,Options) :-
3379 start_ms_timer(Timer),
3380 current_state_id(ID),
3381 generate_visb_html([ID],File,Options),
3382 stop_ms_walltimer_with_msg(Timer,'exporting current state to VisB HTML file: ').
3383 generate_visb_html_codes_for_states(StateIds,Options,Codes) :-
3384 generate_visb_html_to_codes(StateIds,Options,Codes). % write to codes list
3385
3386 % ------------------------------
3387
3388
3389 show_typed_var_in_visb(all,_) :- !.
3390 show_typed_var_in_visb(VarList,b(identifier(ID),_,_)) :- !, show_var_in_visb(VarList,ID).
3391 show_var_in_visb(VarList,ID ) :- (VarList=all -> true ; member(ID,VarList) -> true).
3392
3393 % generate a table for the state (we could use bvisual2)
3394 gen_state_table(Stream,Options,StateIds) :-
3395 b_or_z_mode,
3396 member(show_variables(VarList),Options),
3397 b_get_machine_variables(TypedVars),
3398 % is this useful if Len > 1, but StateIds are not from a trace? (see also below for formulas)
3399 (length(StateIds,Len), Len > 1 -> NOptions = [show_prev_value|Options] ; NOptions = Options),
3400 gen_state_table_aux(Stream,NOptions,'Variables',TypedVars,VarList,[],'Value','bVar_'),fail.
3401 gen_state_table(Stream,Options,StateIds) :-
3402 b_or_z_mode,
3403 member(show_variables(VarList),Options),
3404 b_get_machine_expressions(AExprs,Options), AExprs \= [],
3405 (length(StateIds,Len), Len > 1 -> NOptions = [show_prev_value|Options] ; NOptions = Options),
3406 gen_state_table_aux(Stream,NOptions,'Formulas',AExprs,VarList,[],'Value','bVar_'),fail.
3407 gen_state_table(Stream,Options,StateIds) :-
3408 b_or_z_mode,
3409 ? member(show_constants(IDList),Options),
3410 b_get_machine_constants(TypedVars),
3411 last(StateIds,Last), % we assume there is only one constant valuation in the trace; TO DO: generalise
3412 get_state_and_action(Last,LastId,_,_),
3413 visited_expression(LastId,BState),
3414 expand_to_constants_and_variables(BState,ConstState,_),
3415 gen_state_table_aux(Stream,Options,'Constants',TypedVars,IDList,ConstState,'Value','bConstant_'),fail.
3416 gen_state_table(Stream,Options,_) :-
3417 b_or_z_mode,
3418 ? member(show_sets(IDList),Options),
3419 findall(TSet,bv_top_level_set(TSet,_),TypedVars),
3420 findall(bind(Set,Val),(bv_top_level_set(TSet,Val),get_texpr_id(TSet,Set)),BState),
3421 gen_state_table_aux(Stream,Options,'Sets',TypedVars,IDList,BState,'Value','bSet_'),fail.
3422 % TO DO: maybe show also top-level guards specfile_possible_trans_name or get_top_level_guard
3423 gen_state_table(Stream,Options,_StateIds) :-
3424 b_or_z_mode,
3425 member(show_events(IDList),Options),
3426 get_specification_description(operations,SN),
3427 atom_tail_to_lower_case(SN,SectionName),
3428 findall(b(identifier(OpName),subst,[]),b_top_level_operation(OpName),TypedVars),
3429 % TODO: op(Params,Results) instead of subst
3430 gen_state_table_aux(Stream,Options,SectionName,TypedVars,IDList,[],'Enabled','bOperation_'),fail.
3431 gen_state_table(Stream,Options,StateIds) :-
3432 xtl_mode,
3433 (length(StateIds,Len), Len > 1 -> NOptions = [show_prev_value|Options] ; NOptions = Options),
3434 bv_get_top_level(IDs),
3435 findall(b(identifier(ID),string,[]), member(ID,IDs), Props),
3436 gen_state_table_aux(Stream,NOptions,'Properties',Props,IDs,[],'Value','bVar_'), fail.
3437 gen_state_table(_Stream,_,_).
3438
3439
3440 gen_source_code_section(Stream,Options) :-
3441 member(show_source,Options), % we could also include original sources, rather than just internal rep.
3442 !,
3443 Section = 'Source',
3444 format(Stream,' <button type="button" class="collapsible collapsible-style" title="Inspect source code of internal representation of ProB of model">~w</button>~n',[Section]),
3445 format(Stream,'<div class="coll-content-hid">~n',[]),
3446 get_internal_representation(PP),
3447 format(Stream,'<pre>~s</pre>~n',[PP]),
3448 format(Stream,'</div>~n',[]).
3449 gen_source_code_section(_Stream,_).
3450
3451
3452 % creates a HTML table with header name Section and including one row per ID in TypedVars;
3453 % id of value for ID is prefixed with IDPrefix
3454 % VarListToShow is either all or a list of ids
3455 gen_state_table_aux(Stream,Options,Section,TypedVars,VarListToShow,BState,ValueStr,IDPrefix) :-
3456 include(show_typed_var_in_visb(VarListToShow),TypedVars,SVars), % check which ids should be shown
3457 length(SVars,SLen), SLen>0,
3458 length(TypedVars,Len),
3459 (SLen=Len
3460 -> format(Stream,' <button type="button" class="collapsible collapsible-style">~w (~w)</button>~n',[Section,SLen])
3461 ; format(Stream,' <button type="button" class="collapsible collapsible-style">~w (~w/~w)</button>~n',
3462 [Section,SLen,Len])
3463 ),
3464 format(Stream,'<div class="coll-content-hid">~n',[]),
3465 ? (member(show_prev_value,Options) % add extra column for previous value of variables (and animation expressions)
3466 -> format(Stream,' <table> <tr> <th>Nr</th> <th>Name</th> <th>Value</th> <th>Previous Value</th> </tr>~n',[])
3467 ; format(Stream,' <table> <tr> <th>Nr</th> <th>Name</th> <th>~w</th> </tr>~n',[ValueStr])),
3468 ? ( nth1(Nr,SVars,IDorExprToShow),
3469 get_state_table_name_and_expr(IDorExprToShow,ID,LongID,TExpr),
3470 ? (get_state_value_codes_for_id(BState,ID,Options,_,ValCodes)
3471 -> html_escape_codes(ValCodes,EVC) % Value provided in BState; may be overriden in trace export
3472 ; EVC = "?"),
3473 get_table_hover_message_codes(ID,TExpr,HoverMsgC),
3474 ? (member(show_prev_value,Options) % add previous value of variables (and animation expressions)
3475 -> % for variables the values are added later in JS
3476 % do we want to show the previous value in the state only HTML?
3477 format(Stream,'~n <tr id="row_~w~w" title="~s"> <td>~w</td> <td id="name_~w~w">~w</td> <td id="~w~w">?</td> <td id="bVarPrev_~w">?</td> </tr>~n',
3478 [IDPrefix,ID, HoverMsgC, Nr, IDPrefix,ID,LongID, IDPrefix,ID, ID ])
3479 ;
3480 format(Stream,'~n <tr id="row_~w~w" title="~s"> <td>~w</td> <td id="name_~w~w">~w</td> <td id="~w~w">~s</td> </tr>~n',
3481 [IDPrefix,ID, HoverMsgC, Nr, IDPrefix,ID,LongID, IDPrefix,ID,EVC])),
3482 fail
3483 ;
3484 format(Stream,' </table>~n </div>~n',[])
3485 ).
3486
3487 %get_state_table_name_and_expr(bexpr(Kind,TExpr),Name,LongName,Expr) :- !, % we have special expression to show
3488 % Name=Kind,LongName=Kind,Expr=TExpr.
3489 get_state_table_name_and_expr(bexpr(Kind,TExpr),ID,LongName,Expr) :- !, % we have special expression to show
3490 ID=Kind, % ID for SVG updates, ...
3491 translate_bexpression_with_limit(TExpr,200,TS),
3492 ajoin([Kind,' == ',TS],LongName),
3493 Expr=TExpr.
3494 get_state_table_name_and_expr(TID,ID,ID,TID) :- get_texpr_id(TID,ID). % normal case: variable name
3495
3496
3497 visb_machine_animation_expression(variant,AEName,Variant,_) :-
3498 b_get_operation_variant(Name,ConvOrAnt,Variant),
3499 ajoin(['Variant for ',Name, ' (',ConvOrAnt,')'],AEName).
3500 visb_machine_animation_expression(animation_expression,Name,TExpr,_) :-
3501 b_get_machine_animation_expression(Name,TExpr).
3502 visb_machine_animation_expression(invariant,Name,TPred,Options) :-
3503 member(show_invariants,Options),
3504 b_nth1_non_ignored_invariant(Nr,TPred,_),
3505 ajoin(['INVARIANT-',Nr],Name).
3506 % TODO: we should also adapt get_state_value_change to return true when invariant_violated is false for the state
3507 % we could also only include this section when there is an invariant violation in the trace?
3508
3509 b_get_machine_expressions(List,Options) :-
3510 findall(bexpr(AE_Name,AExpr),visb_machine_animation_expression(_,AE_Name,AExpr,Options),List).
3511 % 'ANIMATION_EXPRESSION' or invariants or variants
3512
3513
3514 % get hover message for entries in variables/constants/... rows:
3515 get_table_hover_message_codes(ID,TExpr,EscHoverMsg) :-
3516 get_texpr_type(TExpr,Type),
3517 (Type=subst,b_get_machine_operation_signature(ID,TS)
3518 -> ajoin(['Operation: ',TS],HoverMsg)
3519 ; pretty_type(Type,TS),
3520 (get_texpr_description(TExpr,Desc)
3521 -> ajoin(['Type: ',TS,'\nDesc: ',Desc],HoverMsg)
3522 ; ajoin(['Type: ',TS],HoverMsg)
3523 )
3524 ),
3525 atom_codes(HoverMsg,HoverCodes),
3526 html_escape_codes(HoverCodes,EscHoverMsg).
3527
3528 % get the values that should be displayed in the variables table
3529 get_state_value_change(StateId,State,ID,Options,ECodes) :-
3530 extract_variables_from_state(State,VariableBState),
3531 ? ( get_state_value_codes_for_id(VariableBState,ID,Options,Val,ValCodes) % look up variable values
3532 ; visb_machine_animation_expression(_,_,_,Options) ->
3533 state_corresponds_to_fully_setup_b_machine(State,FullState),
3534 get_state_value_codes_for_anim_expr(StateId,FullState,ID,Options,Val,ValCodes) % evaluate animation expressions
3535 ),
3536 escape_if_necessary(Val,ValCodes,ECodes). % change " to \" for JavaScript
3537 % formatsilent('Value for ~w~nunescaped: "~s",~n escaped: "~s"~n',[ID,ValCodes,ECodes]).
3538
3539 % avoid unnecessary escaping traversals:
3540 escape_if_necessary([],ValCodes,Res) :- !, Res=ValCodes.
3541 escape_if_necessary(int(_),ValCodes,Res) :- !, Res=ValCodes.
3542 escape_if_necessary(pred_true,ValCodes,Res) :- !, Res=ValCodes.
3543 escape_if_necessary(pred_false,ValCodes,Res) :- !, Res=ValCodes.
3544 escape_if_necessary(_,ValCodes,ECodes) :- b_string_escape_codes(ValCodes,ECodes).
3545
3546
3547 get_state_value_codes_for_id(BState,ID,Options,Val,ValCodes) :-
3548 ? member(bind(ID,Val),BState),
3549 translate_values_for_state_table(Val,Options,ValCodes).
3550
3551 % translate a value for display in state table (not yet escaped)
3552 translate_values_for_state_table(Val,Options,ValCodes) :-
3553 (member(limit_for_values(Nr),Options)
3554 -> translate_bvalue_to_codes_with_limit(Val,Nr,ValCodes)
3555 ; get_preference(expand_avl_upto,Max), Max<0
3556 -> translate_bvalue_to_codes(Val,ValCodes) % unlimited
3557 ; translate_bvalue_to_codes_with_limit(Val,10000,ValCodes)
3558 ).
3559
3560
3561 get_state_value_codes_for_anim_expr(StateId,BState,AE_Name,Options,ResValue,ValCodes) :-
3562 visb_machine_animation_expression(Kind,AE_Name,AExpr,Options),
3563 (Kind=invariant
3564 -> ((invariant_not_yet_checked(StateId) ; invariant_violated(StateId))
3565 -> (safe_create_texpr(convert_bool(AExpr),boolean,TExpr),
3566 evaluate_visb_formula(TExpr,AE_Name,'',BState,ResValue,unknown)
3567 -> translate_pred_val(ResValue,ValCodes)
3568 ; ResValue=pred_unknown, ValCodes = "?" % WD error?
3569 )
3570 ; ResValue=pred_true, translate_pred_val(pred_true,ValCodes) % no need to evaluate invariant
3571 )
3572 ; evaluate_visb_formula(AExpr,AE_Name,'',BState,ResValue,unknown),
3573 translate_values_for_state_table(ResValue,Options,ValCodes)
3574 ).
3575 translate_pred_val(pred_true,[8868]). % see translate:unicode_translation(truth,X).
3576 translate_pred_val(pred_false,[8869]). % see translate:unicode_translation(falsity,X).
3577
3578
3579 get_state_value_enabled_operation_status(StateId,OpName,Enabled,EnabledValue,TransStr) :-
3580 b_top_level_operation(OpName),
3581 findall(TransID, (transition(StateId,OpTerm,TransID,_NewStateId),
3582 match_operation(OpTerm,OpName)), TransList),
3583 length(TransList,Len),
3584 (Len>0
3585 -> Enabled=true,
3586 EnabledValue = "\x2705\", % green check mark, TRUE alternatives \x2705\ \x2713\ \x2714\
3587 (TransList=[TID], transition(StateId,OpTerm,TID,NewStateId),
3588 translate_event_with_src_and_target_id(OpTerm,StateId,NewStateId,200,TransStr)
3589 -> true
3590 ; ajoin([OpName,' (',Len,'\xd7\)'],TransStr) %
3591 )
3592 ; time_out_for_node(StateId,OpName,TypeOfTimeOut) ->
3593 Enabled=TypeOfTimeOut,
3594 EnabledValue = [8987], % four o'clock symbol
3595 TransStr = OpName
3596 %ajoin(['No transition found due to: ',TypeOfTimeOut],HoverMsg)
3597 ; get_preference(maxNrOfEnablingsPerOperation,0) ->
3598 Enabled=not_computed,
3599 EnabledValue = [10067], % red question mark
3600 TransStr = OpName
3601 %'No transitions were computed because MAX_OPERATIONS = 0' = HoverMsg
3602 ; b_get_machine_operation_max(OpName,0) ->
3603 Enabled=not_computed,
3604 EnabledValue = [10067], % red question mark
3605 TransStr = OpName
3606 %ajoin(['No transitions were computed because MAX_OPERATIONS_',OpName,' = 0'],HoverMsg)
3607 ; Enabled=false,
3608 EnabledValue = [9940], % stop sign, FALSE, alternatives \x10102\
3609 TransStr = OpName
3610 %ajoin(['Not enabled'],HoverMsg)
3611 ). % TO DO: show whether this is the next step in the trace
3612
3613 % --------------------------
3614
3615 % debugging features to inspect all created SVG objects
3616 tcltk_get_visb_objects(list([Header|AllObjects])) :-
3617 Header = list(['SVG-ID','svg_class','Attribute','Value']),
3618 findall(list([SvgID,SvgClass,Attr,Value]),
3619 (visb_svg_obj_with_parent(SvgID,SvgClass,AttrList,true),
3620 (member(svg_attribute(Attr,Value),AttrList) ;
3621 visb_svg_parent(SvgID,Value), Attr=children)
3622 ), Childs),
3623 findall(list([SvgID,SvgClass,Attr,Value]),
3624 (visb_svg_obj_with_parent(SvgID,SvgClass,AttrList,false),
3625 member(svg_attribute(Attr,Value),AttrList)
3626 ),AllObjects, Childs).
3627
3628 % debugging features to inspect all created SVG objects
3629 tcltk_get_visb_hovers(list([Header|AllObjects])) :-
3630 Header = list(['SVG-ID','ID','Attribute','EnterValue', 'ExitValue']),
3631 findall(list([SvgID,ID,Attr,EnterVal,ExitVal]),
3632 visb_hover(SvgID,ID,Attr,EnterVal,ExitVal,_Pos), AllObjects).
3633
3634 % debugging features to inspect items
3635 tcltk_get_visb_items(Res) :-
3636 current_state_id(ID),
3637 tcltk_get_visb_items(ID,Res).
3638 tcltk_get_visb_items(_StateId,Res) :-
3639 \+ visb_file_is_loaded(_),!,
3640 Res = list(['No VisB JSON file loaded']).
3641 tcltk_get_visb_items(StateId,list([Header|AllItems])) :-
3642 Header = list(['SVG-ID','Attribute','Value']),
3643 get_preference(translation_limit_for_table_commands,Limit),
3644 findall(list([SvgID,SvgAttribute,Val]),
3645 get_change_attribute_for_state(StateId,SvgID,SvgAttribute,Val),
3646 Items),
3647 findall(list([DefID,'VisB Definition',DValS]),
3648 (get_expanded_bstate(StateId,ExpandedBState),
3649 reverse(ExpandedBState,RS),
3650 member(bind(DefID,DVal),RS),
3651 visb_definition(DefID,_,_,_,_,_),
3652 translate_bvalue_with_limit(DVal,Limit,DValS)),
3653 AllItems, Items).
3654
3655 :- use_module(probsrc(translate),[translate_event_with_limit/3]).
3656 tcltk_get_visb_events(Res) :-
3657 current_state_id(ID),
3658 tcltk_get_visb_events(ID,Res).
3659 tcltk_get_visb_events(_StateId,Res) :-
3660 \+ visb_file_is_loaded(_),!,
3661 Res = list(['No VisB JSON file loaded']).
3662 tcltk_get_visb_events(StateId,list([Header|AllItems])) :-
3663 Header = list(['SVG-ID','Event','Target']),
3664 get_preference(translation_limit_for_table_commands,Limit),
3665 findall(list([SvgID,EventStr,NewStateId]),
3666 (perform_visb_click_event(SvgID,[],StateId,_Event,OpTerm,NewStateId,Res),
3667 (Res=[] -> EventStr='disabled' ; translate_event_with_limit(OpTerm,Limit,EventStr))
3668 ),
3669 AllItems).
3670 % --------------------------
3671
3672 % for ProB2-UI
3673
3674 :- use_module(probsrc(translate),[translate_bexpression_with_limit/3]).
3675 get_visb_items(List) :-
3676 findall(visb_item(SvgID,Attr,TS,Desc,Pos),
3677 (visb_item(SvgID,Attr,TypedExpr,_Used,Desc,Pos,_),
3678 translate_bexpression_with_limit(TypedExpr,1000,TS)), List).
3679
3680 get_visb_attributes_for_state(StateId,List) :-
3681 % some external functions like ENABLED are evaluated in current state; it might be useful to set_current_state
3682 (visb_file_is_loaded(_) -> true
3683 ; add_warning(visb_visualiser,'No VisB visualisation loaded, cannot get attributes for state: ',StateId)),
3684 findall(set_attr(SvgID,SvgAttribute,Val),
3685 get_change_attribute_for_state(StateId,SvgID,SvgAttribute,Val),
3686 List).
3687
3688 % for ProB2-UI
3689 get_visb_click_events(List) :-
3690 findall(execute_event(SvgID,Event,Preds),
3691 get_visb_event(SvgID,Event,Preds), List).
3692 get_visb_event(SvgID,Event,Preds) :- visb_event(SvgID,Event,Preds,_,_File,_Pos).
3693 get_visb_event(SvgID,'',[]) :- % add a virtual empty event for SVG Ids with hovers but no events
3694 visb_has_hovers(SvgID),
3695 \+ visb_event(SvgID,_,_,_,_File,_Pos).
3696
3697
3698 :- use_module(probsrc(state_space), [extend_trace_by_transition_ids/1]).
3699 % perform a click on a VisB SVG ID in the animator
3700 tcltk_perform_visb_click_event(SvgID) :- current_state_id(StateId),
3701 (perform_visb_click_event(SvgID,[],StateId,TransitionIDs)
3702 -> formatsilent('Clicking on ~w in state ~w resulted in transition id sequence ~w~n',[SvgID,StateId,TransitionIDs]),
3703 extend_trace_by_transition_ids(TransitionIDs)
3704 ; add_error(visb_visualiser,'Cannot perform VisB click on: ',SvgID)
3705 ).
3706
3707 % computes the effect of clicking on an SvgID in StateId
3708 % it returns either empty list if the visb_event is not feasible or a list of transition ids
3709 % it fails if SvgID has no events associated with it
3710 perform_visb_click_event(SvgID,MetaInfos,StateId,ResTransitionIds) :-
3711 perform_visb_click_event(SvgID,MetaInfos,StateId,_,_,_,ResTransitionIds).
3712 perform_visb_click_event(SvgID,MetaInfos,StateId,OpName,OpTerm,NewStateId,ResTransitionIds) :-
3713 get_expanded_bstate(StateId,ExpandedBState),
3714 set_error_context(checking_context('VisB:','performing click event')),
3715 set_context_state(StateId,perform_visb_click_event),
3716 get_svgid_with_events(SvgID,_),
3717 call_cleanup(perform_aux(SvgID,StateId,ExpandedBState,OpName,OpTerm,NewStateId,ResTransitionIds,MetaInfos),
3718 (clear_context_state,clear_error_context)).
3719
3720 get_svgid_with_events(SvgID,FirstOpName) :- visb_event(SvgID,FirstOpName,_,_,_File,_Pos).
3721
3722
3723 :- use_module(probsrc(tools),[safe_read_term_from_atom/2]).
3724 :- use_module(probsrc(state_space),[transition/4]).
3725 perform_aux(SvgID,StateId,_ExpandedBState,OpName,OpTerm,NewStateId,ResTransitionIds,_MetaInfos) :-
3726 \+ b_or_z_mode,
3727 % just look up transition/4 entries in state space
3728 % TODO: maybe provide this possibility for B models, even if using explicit parameter values is more robust
3729 get_visb_event_operation(SvgID,OpName,Preds,_Pred,Pos),
3730 safe_read_term_from_atom(OpName,OpTerm0),
3731 (xtl_mode -> check_xtl_direct_transition_candidate(OpTerm0,Preds,Pos), OpTerm=OpTerm0 ; true), !,
3732 % for XTL: use exec by pred for arity 0, otherwise try to find transition term in state space
3733 if((transition(StateId,OpTerm,TransID,NewStateId),
3734 match_operation(OpTerm,OpName)), % match is relevant if \+xtl_mode
3735 ResTransitionIds = [TransID],
3736 return_disabled(SvgID,StateId,OpName,OpTerm,NewStateId,ResTransitionIds)
3737 ).
3738 perform_aux(SvgID,StateId,ExpandedBState,OpName,OpTerm,NewStateId,ResTransitionIds,MetaInfos) :-
3739 %state_space:portray_state_space,
3740 if(execute_visb_event_by_predicate(SvgID,StateId,ExpandedBState,OpName,OpTerm,NewStateId,TransIds,MetaInfos),
3741 ResTransitionIds = TransIds,
3742 return_disabled(SvgID,StateId,OpName,OpTerm,NewStateId,ResTransitionIds)).
3743
3744 check_xtl_direct_transition_candidate(OpTerm,Preds,Pos) :-
3745 nonvar(OpTerm), % upper case event names are interpreted as Prolog variables -> use exec by pred (or FIXME)
3746 functor(OpTerm,_,Ar), Ar>0, % use exec by pred for arity 0, otherwise try to find transition term in state space
3747 (Preds \= []
3748 -> add_warning(visb_visualiser,'Ignoring predicates for VisB XTL event with explicit transition term (use predicate to provide parameter values): ',OpTerm,Pos)
3749 ; true).
3750
3751 return_disabled(SvgID,StateId,OpName,OpTerm,NewStateId,ResTransitionIds) :-
3752 OpTerm = disabled, NewStateId = StateId,
3753 get_svgid_with_events(SvgID,OpName),
3754 ResTransitionIds = []. % visb_event not enabled
3755
3756 :- use_module(probsrc(tools_strings),[match_atom/2]).
3757 :- use_module(probsrc(specfile),[get_operation_name/2]).
3758 match_operation(OpTerm,OpTerm) :- !.
3759 match_operation(OpTerm,OpName) :- atom(OpName),
3760 (get_operation_name(OpTerm,OpName)
3761 ; match_atom(OpName,OpTerm) % match an atom string with a compound term
3762 ),!.
3763
3764 execute_visb_event_by_predicate(SvgID,StateId,ExpandedBState,OpName,OpTerm,NewStateId,TransIds,MetaInfos) :-
3765 get_visb_event_operation(SvgID,OpName,_,Pred,Pos),
3766 build_visb_click_meta_object(MetaInfos,BMetaInfos),
3767 bsyntaxtree:replace_id_by_expr(Pred,'VISB_CLICK_META_INFOS',BMetaInfos,NPred),
3768 exec_aux(SvgID,StateId,ExpandedBState,OpName,NPred,Pos,OpTerm,NewStateId,TransIds).
3769
3770 build_visb_click_meta_object(MetaInfos,BMetaInfos) :-
3771 (member(alt_key,MetaInfos) -> AltKey = pred_true ; AltKey = pred_false),
3772 (member(ctrl_key,MetaInfos) -> CtrlKey = pred_true ; CtrlKey = pred_false),
3773 (member(meta_key,MetaInfos) -> MetaKey = pred_true ; MetaKey = pred_false),
3774 (member(pageX(PageX),MetaInfos) -> true ; PageX = 0), % fallback
3775 (member(pageY(PageY),MetaInfos) -> true ; PageY = 0), % fallback
3776 (member(shift_key,MetaInfos) -> ShiftKey = pred_true ; ShiftKey = pred_false),
3777 findall(','(string(Var),string(VarValue)), member(js_var(Var,VarValue), MetaInfos), JSVars),
3778
3779 visb_click_meta_b_type(BType),
3780 BMetaInfos = b(value(rec([
3781 field(altKey,AltKey),
3782 field(ctrlKey,CtrlKey),
3783 field(jsVars,JSVars),
3784 field(metaKey,MetaKey),
3785 field(pageX,int(PageX)),
3786 field(pageY,int(PageY)),
3787 field(shiftKey,ShiftKey)
3788 ])),BType,[visb_generated]).
3789
3790 visb_click_meta_b_type(record([
3791 field(altKey,boolean),
3792 field(ctrlKey,boolean),
3793 field(jsVars,set(couple(string,string))),
3794 field(metaKey,boolean),
3795 field(pageX,integer),
3796 field(pageY,integer),
3797 field(shiftKey,boolean)
3798 ])).
3799
3800 :- use_module(probsrc(tcltk_interface),[compute_all_transitions_if_necessary/2]).
3801 :- use_module(library(random),[random_member/2]).
3802 :- use_module(extrasrc(mcts_game_play), [mcts_auto_play/4, mcts_auto_play_available/0]).
3803 :- use_module(probsrc(tools_timeout), [time_out_with_factor_call/3]).
3804 :- use_module(probsrc(external_functions),[call_external_function/7]).
3805 exec_aux(SvgID,StateId,ExpandedBState,OpName,Pred,Pos,OpTerm,NewStateId,[TransId]) :-
3806 (b_or_z_mode -> b_is_operation_name(OpName) ; true), !, % note: ignores special definitions below if not B mode
3807 time_out_with_factor_call(
3808 exec_op_by_pred_aux(StateId,ExpandedBState,OpName,Pred,OpTerm,NewState,Pos,TransInfo),
3809 5, % min_max_time_out(10,100,15000)
3810 (ajoin(['TIME-OUT for VisB click on SVG ID ', SvgID,' while executing operation by predicate: '],Msg),
3811 add_warning(visb_visualiser,Msg,OpName,Pos),fail)),
3812 patch_state(NewState,StateId,PatchedNewState),
3813 % add transition to state space:
3814 tcltk_interface:add_trans_id_infos(StateId,OpTerm,PatchedNewState,NewStateId,TransId,TransInfo).
3815 %translate:print_bstate(PatchedNewState),nl.
3816 exec_aux(SvgID,StateId,_ExpandedBState,'MCTS_AUTO_PLAY',_Pred,Pos,OpTerm,NewStateId,[TransId]) :- !,
3817 mcts_auto_play_available,
3818 % TODO: allow to set SimRuns, TimeOut in Pred
3819 add_debug_message(visb_visualiser,'Performing MCTS_AUTO_PLAY for click on: ',SvgID,Pos),
3820 mcts_auto_play(StateId,OpTerm,TransId,NewStateId).
3821 % TODO: more general call via call_external_substitution(FunName,Args,InState,OutState,Info,WF)
3822 exec_aux(_SvgID,StateId,_ExpandedBState,'RANDOM_ANIMATE',_Pred,_Pos,OpTerm,NewStateId,[TransId]) :- !,
3823 compute_all_transitions_if_necessary(StateId,false),
3824 findall(rtr(OpTerm,TransId,NewStateId),transition(StateId,OpTerm,TransId,NewStateId),List),
3825 random_member(rtr(OpTerm,TransId,NewStateId),List).
3826 % see tcltk_interface:tcltk_random_perform2 and allow Kind: fully_random, no_self_loops, heuristics, ...
3827 % split with ; ?
3828 exec_aux(SvgID,StateId,ExpandedBState,'RANDOM_ANIMATE_UNTIL_LTL',LTLExpr,Pos,OpTerm,NewStateId,TransIds) :- !,
3829 OpTerm = 'RANDOM_ANIMATE_UNTIL_LTL',
3830 (get_texpr_type(LTLExpr,string),
3831 evaluate_visb_formula(LTLExpr,'RANDOM_ANIMATE_UNTIL_LTL',SvgID,ExpandedBState,Value,Pos),
3832 Value = string(LTLFormula)
3833 -> tcltk_interface:tcltk_animate_until(LTLFormula,StateId,1000,ltl_state_property,_Steps,_Res,NewStateId,TransIds)
3834 ; add_error(visb_visualiser,'Argument to RANDOM_ANIMATE_UNTIL_LTL must provide LTL formula as string:',StateId)
3835 ).
3836 exec_aux(SvgID,StateId,ExpandedBState,ExternalFun,ArgEXPR,Pos,OpTerm,NewStateId,TransIds) :-
3837 external_fun_as_special_operation(ExternalFun),!,
3838 NewStateId=StateId, TransIds=[],
3839 evaluate_visb_formula(ArgEXPR,ExternalFun,1,ExpandedBState,ArgValue,Pos),
3840 convert_arg_value_to_list(ArgEXPR,ArgValue,UnEvalArgs,EvaluatedArgs),
3841 OpTerm =.. [ExternalFun|EvaluatedArgs],
3842 debug_format(9,'VisB event for ~w: calling external function ~w with ~w~n',[SvgID,ExternalFun,EvaluatedArgs]),
3843 % Note: we ignore the return value
3844 call_external_function(ExternalFun,UnEvalArgs,EvaluatedArgs,_Value,any,Pos,no_wf_available).
3845
3846 % convert single argument expression to list; better would be to use a predicate with argument names
3847 convert_arg_value_to_list(b(couple(A,B),_,_),(VA,VB),[A|T],[VA|VT]) :- !, convert_arg_value_to_list(B,VB,T,VT).
3848 convert_arg_value_to_list(Arg,Val,[Arg],[Val]).
3849
3850 :- use_module(probsrc(b_state_model_check),[execute_operation_by_predicate_in_state_with_pos/7,
3851 xtl_execute_operation_by_predicate_in_state/8]).
3852 exec_op_by_pred_aux(StateId,ExpandedBState,OpName,Pred,OpTerm,NewState,Pos,TransInfo) :- xtl_mode,!,
3853 visited_expression(StateId,RawState),
3854 xtl_execute_operation_by_predicate_in_state(ExpandedBState,RawState,OpName,Pred,OpTerm,NewState,Pos,TransInfo).
3855 exec_op_by_pred_aux(_StateId,ExpandedBState,OpName,Pred,OpTerm,NewState,Pos,TransInfo) :-
3856 execute_operation_by_predicate_in_state_with_pos(ExpandedBState,OpName,Pred,OpTerm,NewState,Pos,TransInfo).
3857
3858 :- use_module(probsrc(bmachine), [b_is_variable/1,b_machine_has_constants/0]).
3859
3860 is_var_binding(bind(Var,_)) :- b_or_z_mode, b_is_variable(Var).
3861
3862
3863 % remove constants and VisB Definition entries from state:
3864 patch_state(NewState,_StateId,PatchedState) :-
3865 \+ b_or_z_mode, !, PatchedState=NewState. % XTL state is raw state
3866 patch_state(NewState,StateId,PatchedState) :-
3867 get_constants_id_for_state_id(StateId,ConstId),!,
3868 PatchedState = const_and_vars(ConstId,VarsState),
3869 include(is_var_binding,NewState,VarsState).
3870 patch_state(NewState,StateId,VarsState) :-
3871 (b_machine_has_constants
3872 -> add_error(visb_visualiser,'Could not extract constants id for state:',StateId),
3873 VarsState=NewState
3874 ; include(is_var_binding,NewState,VarsState)).
3875
3876 % the next predicate gets all operations/events associated with SvgID in the order in which they were found
3877 % note that there is only one visb_event (the last one); all others are auxiliary
3878 get_visb_event_operation(SvgID,OpName,Preds,TypedPred,Pos) :- % check if there are more events registered:
3879 auxiliary_visb_event(SvgID,OpName,Preds,TypedPred,Pos).
3880 get_visb_event_operation(SvgID,OpName,Preds,TypedPred,Pos) :-
3881 visb_event(SvgID,OpName,Preds,TypedPred,_File,Pos).
3882
3883 % ---------------
3884
3885 get_visb_hovers(List) :-
3886 findall(hover(SvgID,ID,Attr,EnterVal,ExitVal),
3887 visb_hover(SvgID,ID,Attr,EnterVal,ExitVal,_), List).
3888
3889 get_visb_svg_objects(List) :-
3890 % TODO: remove objects inlined in get_visb_default_svg_file_contents
3891 topological_sort_svg_objects(SvgIDs),
3892 findall(visb_svg_object(SvgID,SvgClass,AttrList),
3893 (member(SvgID,SvgIDs),
3894 visb_svg_obj_with_parent(SvgID,SvgClass,AttrList,_)), List).
3895
3896 visb_svg_obj_with_parent(SvgID,SvgClass,AttrList,IsChild) :-
3897 visb_svg_object(SvgID,SvgClass,List,_Desc,_Pos),
3898 (visb_svg_child(SvgID,ParentId)
3899 -> IsChild=true, AttrList = [svg_attribute(parentId,ParentId)|List] % add parentId attribute for ProB2-UI
3900 ; IsChild=false, AttrList = List).
3901
3902
3903 :- use_module(probsrc(tools),[top_sort/3]).
3904 :- use_module(library(ugraphs),[vertices_edges_to_ugraph/3]).
3905 topological_sort_svg_objects(SortedSVGObjects) :-
3906 findall(SvgID,visb_svg_object(SvgID,_,_,_,_),Vertices),
3907 findall(V-W,visb_svg_parent(V,W),Edges),
3908 vertices_edges_to_ugraph(Vertices,Edges,Graph),
3909 (top_sort(Graph,SortedSVGObjects,UnsortedNr)
3910 -> (UnsortedNr = 0 -> true
3911 ; add_warning(visb_visualiser,'Cycle in SVG_OBJECTS parent/child graph, unsorted objects: ',UnsortedNr)
3912 )
3913 ; SortedSVGObjects=Vertices,
3914 add_error(visb_visualiser,'Topological sorting of SVG_OBJECTS failed: ',Vertices)
3915 ).
3916
3917 % ------------------
3918
3919 :- use_module(probsrc(bmachine),[b_absolute_file_name_relative_to_main_machine/2]).
3920 extended_static_check_default_visb_file :-
3921 (get_default_visb_file(VisBFile,Pos)
3922 % TODO: we could check if we have an visb_history(JSONFile,_,_) option
3923 -> extended_static_check_visb_file(VisBFile,Pos)
3924 ; true).
3925
3926 extended_static_check_visb_file('',_InclusionPos) :- !,
3927 load_visb_file('').
3928 extended_static_check_visb_file(VisBFile,InclusionPos) :-
3929 b_absolute_file_name_relative_to_main_machine(VisBFile,AFile),
3930 (file_exists(AFile)
3931 -> load_visb_file(AFile)
3932 ; add_warning(lint,'VISB_JSON_FILE does not exist: ',AFile,InclusionPos)
3933 ).
3934
3935 % ---------------------------
3936
3937 % portray all VisB items in DEFINITION B syntax
3938 get_visb_ids(SIds) :-
3939 findall(Id,visb_id(Id),Ids),
3940 sort(Ids,SIds).
3941
3942 visb_id(ID) :- visb_svg_object(ID,_,_,_,_). % see svg_id_exists
3943 visb_id(ID) :- visb_item(ID,_,_,_,_,_,_), \+ visb_svg_object(ID,_,_,_,_).
3944 visb_id(ID) :- visb_event(ID,_,_,_,_,_), \+ visb_svg_object(ID,_,_,_,_).
3945 visb_id(ID) :- visb_hover(ID,_,_,_,_,_), \+ visb_svg_object(ID,_,_,_,_).
3946
3947 :- public portray_visb/0.
3948 portray_visb:-
3949 get_visb_ids(SIds), nth1(Nr,SIds,ID),
3950 %visb_svg_object(ID,SVG_Class,NewRestAttrs,Desc,Pos1),
3951 findall(field(Attr,b(value(StaticVal),any,[])),
3952 (visb_svg_object(ID,SVG_Class,StaticAttrs,Desc,_Pos1),
3953 ( Attr=svg_class,StaticVal=string(SVG_Class)
3954 ; Attr=comment,StaticVal=string(Desc)
3955 ; member(svg_attribute(Attr,StaticVal),StaticAttrs))
3956 ),
3957 StaticValues),
3958 findall(field(Attr,TypedExpr),
3959 visb_item(ID,Attr,TypedExpr,_UsedIds,_Desc,_PosStartOfItem,_Meta), % meta can contain override
3960 Updates,StaticValues),
3961 % TODO: incorporate events and hovers
3962 UpdateRec = b(rec(Fields),any,[]),
3963 gen_string(ID,IDS),
3964 Fields = [field(id,IDS) | Updates],
3965 (StaticValues=[] -> format('~nVISB_SVG_UPDATES~w == ',[Nr]) ; format('~nVISB_SVG_OBJECTS~w == ',[Nr])),
3966 translate:print_bexpr(UpdateRec), write(';'), nl,
3967 fail.
3968 portray_visb.
3969 gen_string(ID,b(string(ID),string,[])).
3970 % use_module(visbsrc(visb_visualiser)), visb_visualiser:portray_visb.