1 % (c) 2009-2025 Lehrstuhl fuer Softwaretechnik und Programmiersprachen,
2 % Heinrich Heine Universitaet Duesseldorf
3 % This software is licenced under EPL 1.0 (http://www.eclipse.org/org/documents/epl-v10.html)
4 :- module(graphical_state_viewer_images,[tcltk_get_image_list/6,
5
6 tcltk_can_react_to_item_right_click/2,
7 tcltk_react_to_item_right_click/2,
8
9 tcltk_can_react_to_item_drag/3,
10 tcltk_react_to_item_drag/2,
11
12 get_animation_images/1, % only get animation image list
13 get_animation_image_grid/6,
14 get_react_to_item_right_click_options/4,
15 react_to_item_right_click/6,
16
17 html_print_history/1, html_print_history/2
18 ]).
19
20 /* ------------------------------------------------------------------ */
21
22 :- use_module(probsrc(module_information)).
23 :- module_info(group,visualization).
24 :- module_info(description,'This module can provide a Tk graphical representation of a B state.').
25
26
27
28 :- use_module(probsrc(bmachine),[b_get_machine_animation_function/2,
29 bmachine_is_precompiled/0, b_get_definition_string_from_machine/2,
30 get_animation_image/2]).
31
32 /* First argument: image list of pairs: ImageName, ImageFilePath
33 Second argument: list of triplets {type framename label}
34 */
35
36 :- use_module(probsrc(error_manager)).
37 :- use_module(probsrc(debug)).
38 :- use_module(probsrc(state_space),[current_expression/2]).
39 :- use_module(probsrc(tools_strings),[ajoin/2]).
40
41 :- set_prolog_flag(double_quotes, codes).
42
43
44 eval_definition_funs([],_,[]).
45 eval_definition_funs([anim_fun(Nr,AnimFunction1)|T],BState,Result) :-
46 eval_definition_fun(AnimFunction1, Nr, BState, FunctionRes1),
47 eval_definition_funs(T,BState,FunctionRes0),
48 override_anim_fun(FunctionRes1,FunctionRes0,Result).
49
50 :- use_module(probsrc(xtl_interface),[xtl_animation_function_result/2, xtl_animation_image/2]).
51 :- use_module(probsrc(specfile),[animation_mode/1, b_or_z_mode/0]).
52
53
54 tcltk_get_image_list(list(ImageList),MinRow,MaxRow,MinCol,MaxCol,list(FramesAndItems)) :-
55 animation_mode(Mode),
56 animation_function_possibly_active(Mode),
57 get_animation_images(Mode,ImageList),
58 current_expression(_CurID,State),
59 evaluate_animation_function(Mode,State,FunctionRes),
60 get_min_max_col(FunctionRes,MinCol,MaxCol),
61 display_animation_function_result(FunctionRes,MinRow,MaxRow,FramesAndItems).
62
63 :- use_module(probsrc(specfile),[state_corresponds_to_fully_setup_b_machine/2]).
64
65 animation_function_possibly_active(xtl) :- !.
66 animation_function_possibly_active(_) :- bmachine_is_precompiled,
67 b_get_machine_animation_function(_,_),!.
68
69 evaluate_animation_function(xtl,State,FunctionRes) :- !,
70 xtl_animation_function_result(State,FunctionRes).
71 evaluate_animation_function(_,State,FunctionRes) :- % Mode will be 'b'
72 state_corresponds_to_fully_setup_b_machine(State,BState),
73 findall(anim_fun(Nr,AF),b_get_machine_animation_function(AF,Nr),AnimFuns),
74 AnimFuns \= [],
75 sort(AnimFuns,SAnimFuns),
76 %print(animation_images(ImageList)),
77 % print('Animation Function: '),
78 % translate:print_bexpr(SAnimFuns),
79 eval_definition_funs(SAnimFuns, BState, FunctionRes).
80 % print('full_fun'(FunctionRes)),nl.
81
82 display_animation_function_result(FunctionRes,MinRow,MaxRow,FramesAndItems) :-
83 get_min_max_row(FunctionRes,MinRow,MaxRow),
84 debug_println(9,visualization_matrix_min_max(MinRow,MaxRow)),
85 setup_frames(MinRow,MaxRow,Frames), %debug_println(9,frames(Frames)),
86 sort(FunctionRes,SortedFR),
87 get_frame_items(SortedFR,Items),
88 % print(items(Items)),nl,
89 pad_text_frame_items(Items,PItems),
90 append(Frames,PItems,FramesAndItems).
91
92
93 :- use_module(probsrc(tools),[ split_last/4, split_chars/3 ]).
94 tcltk_can_react_to_item_right_click(TkPath,list(Names)) :-
95 convert_tk_path_to_coordinates(TkPath,XCoord,YCoord),
96 animation_mode(M),
97 current_state_id(CurID),
98 debug_println(19,start_right_clicked_object(XCoord,YCoord,mode(M),state(CurID))),
99 findall(Name,can_react_to_item_right_click(CurID,M,XCoord,YCoord,_,Name,_),Names).
100
101 % for ProB 2:
102 get_react_to_item_right_click_options(CurID,XCoord,YCoord,Names) :-
103 animation_mode(M),
104 findall(Name,can_react_to_item_right_click(CurID,M,XCoord,YCoord,_,Name,_),Names).
105
106 tcltk_react_to_item_right_click(TkPath,ActionStr) :-
107 % print(right_clicked_tk_path(TkPath)),nl,
108 convert_tk_path_to_coordinates(TkPath,XCoord,YCoord),
109 current_state_id(CurID),
110 react_to_item_right_click(CurID,XCoord,YCoord,ActionStr,_,_).
111
112 :- use_module(probsrc(state_space),[current_state_id/1, transition/4]).
113 :- use_module(probsrc(xtl_interface),[xtl_animation_image_right_click_transition/4]).
114 :- use_module(probsrc(translate),[translate_event_with_src_and_target_id/4]).
115 :- use_module(probsrc(bmachine),[b_get_definition/5,b_get_definition_with_pos/6,type_with_errors/4, b_top_level_operation/1]).
116 :- use_module(library(lists),[maplist/3]).
117 :- use_module(probsrc(preferences),[temporary_set_preference/3,reset_temporary_preference/2]).
118
119 can_react_to_item_right_click(CurID,Mode,X,Y,TransitionTemplateList,Str,TransitionID) :-
120 get_right_click_template(Mode,CurID,X,Y,TransitionTemplateList),
121 get_template(TransitionTemplateList,Template), % deals with list templates
122 transition(CurID,TransitionTerm,TransitionID,DestID),
123 match_template(Template,TransitionTerm),
124 translate_event_with_src_and_target_id(TransitionTerm,CurID,DestID,Str).
125
126 match_template(T,T) :- !.
127 match_template(T,'-->'(ActionWoResults,_Results)) :- !, match_template(T,ActionWoResults).
128 match_template(Template,Action) :-
129 atom(Template), % with get_preference(show_eventb_any_arguments,true) we have extra arguments
130 get_operation_name(Action,Template).
131
132
133 get_right_click_template(xtl,CurID,ColX,RowY,Template) :-
134 visited_expression(CurID,State),
135 xtl_animation_image_right_click_transition(RowY,ColX,Template,State).
136 get_right_click_template(b,CurID,X,Y,Template) :-
137 Def_Name = 'ANIMATION_RIGHT_CLICK',
138 b_get_click_subst_definition(Def_Name,2,_RawSubst,DefPos),
139 temporary_set_preference(allow_local_operation_calls,true,CHNG),
140 Scope = [prob_ids(visible),operation_bodies], % do not include variables; otherwise clash warnings
141 % type definition call:
142 type_with_errors(definition(DefPos,'ANIMATION_RIGHT_CLICK',[integer(Pos,X),integer(Pos,Y)]),Scope,subst,Typed),
143 reset_temporary_preference(allow_local_operation_calls,CHNG),
144 get_b_template_for(CurID,Typed,[],Template).
145
146
147 b_get_click_subst_definition(Def_Name,NrArgs,RawSubst,DefPos) :-
148 b_get_definition_with_pos(Def_Name,Kind,DefPos,Args,RawBody,_Deps),
149 length(Args,Len),
150 (Len=NrArgs -> true
151 ; ajoin([Def_Name,' should take ',NrArgs,' arguments, not: '],Msg),
152 add_warning(state_viewer_images,Msg,Len,DefPos),
153 fail
154 ),
155 (Kind=substitution -> RawSubst=RawBody
156 ; translate_expr_to_op_call(RawBody,OP,PosOp,RawSubst) ->
157 add_warning(state_viewer_images,'ANIMATION_(RIGHT_)CLICK is not a substitution, wrap call to operation into BEGIN END block: ',OP,PosOp),
158 fail % TODO: use translated RawSubst instead of typing definition call
159 ; add_warning(state_viewer_images,'ANIMATION_(RIGHT_)CLICK is not a substitution but: ',Kind,DefPos),
160 fail
161 ).
162
163 % for some reason the parser maps simple operation calls to function call expressions
164 translate_expr_to_op_call(function(Pos1,identifier(Pos2,OP),[A,B]),OP,Pos1,
165 operation_call(Pos1,identifier(Pos2,OP),[A,B])) :- b_top_level_operation(OP).
166
167 % ANIMATION_RIGHT_CLICK can use the following in B:
168 % ANY, LET: to introduce wild cards; predicates will not (yet) be evaluated !!
169 % IF-ELSIF-ELSE: conditions have to be evaluable using the parameters only
170 % CHOICE: to provide multiple right click actions
171
172 % Operation Calls: the arguments must evaluable without access to variables and constants at the moment
173
174 :- use_module(probsrc(specfile), [state_corresponds_to_set_up_constants/2]).
175 get_b_template_for(CurID,Subst,LV,Template) :-
176 visited_expression(CurID,State),
177 state_corresponds_to_set_up_constants(State,BState),
178 % expand_const_and_vars_to_full_store
179 get_b_template(Subst,LV,BState,Template).
180
181 get_b_template(Typed,LocalVars,State,Template) :-
182 (Typed=b(sequence([A|Rest]),_,_)
183 -> Template = [TA|Rest], % we assume Rest has no guard; currently we only support MCTS_AUTO_PLAY
184 get_b_template(A,LocalVars,State,TA)
185 % TODO: detect MCTS_AUTO_PLAY on its own
186 ; get_b_template2(Typed,LocalVars,State,Template)
187 ).
188
189 % get template to match against enabled transitions:
190 get_b_template2(b(E,subst,_),LocalVars,State,Template) :- get_b_template_aux(E,LocalVars,State,Template).
191
192 :- use_module(probsrc(bsyntaxtree), [get_texpr_id/2, def_get_texpr_id/2]).
193 get_b_template_aux(any(Paras,_Pred,Body),LocalVars,State,Template) :- !,
194 append(Paras,LocalVars,LV2),
195 get_b_template2(Body,LV2,State,Template).
196 get_b_template_aux(let(Paras,_Pred,Body),LocalVars,State,Template) :- !,
197 append(Paras,LocalVars,LV2),
198 get_b_template2(Body,LV2,State,Template).
199 get_b_template_aux(var(Paras,Body),LocalVars,State,Template) :- !,
200 append(Paras,LocalVars,LV2),
201 get_b_template2(Body,LV2,State,Template).
202 get_b_template_aux(choice(Options),LocalVars,State,Template) :- !,
203 member(A,Options),
204 get_b_template2(A,LocalVars,State,Template).
205 get_b_template_aux(if(Options),LocalVars,State,Template) :- !,
206 get_b_template_for_if(Options,LocalVars,State,Template).
207 get_b_template_aux(precondition(Test,Body), LocalVars,State,Template) :- !,
208 b_test_boolean_expression_cs(Test,[],State,'ANIMATION_(RIGHT_)CLICK',0),
209 get_b_template2(Body,LocalVars,State,Template).
210 get_b_template_aux(operation_call(TOpID,_Result,Parameters),LocalVars,State,Template) :- !,
211 def_get_texpr_id(TOpID,op(OpID)),
212 % TO DO: deal with Result
213 maplist(eval_parameter(LocalVars,State,OpID),Parameters,TemplateArgs),
214 Template =.. [OpID|TemplateArgs].
215 get_b_template_aux(Subst,_LocalVars,_State,_) :-
216 add_error('ANIMATION_(RIGHT_)CLICK','Uncovered substitution in ANIMATION_(RIGHT_)CLICK: ',b(Subst,subst,[])),fail.
217
218 :- use_module(probsrc(b_interpreter),[b_test_boolean_expression_cs/5,
219 b_compute_expression_nowf/6, b_compute_explicit_epression_no_wf/6]).
220 get_b_template_for_if([b(if_elsif(Test,Body),_,_)|_], LocalVars,State,Template) :-
221 b_test_boolean_expression_cs(Test,[],State,'ANIMATION_RIGHT_CLICK',0),!,
222 get_b_template2(Body,LocalVars,State,Template).
223 get_b_template_for_if([_|T],LV,State,Template) :- get_b_template_for_if(T,LV,State,Template).
224
225 eval_parameter(LocalVars,_State,_,Parameter,Result) :-
226 get_texpr_id(Parameter,PID),
227 member(LV,LocalVars), get_texpr_id(LV,PID),
228 !,
229 Result = _.
230 eval_parameter(_LocalVars,State,OpId,Parameter,Result) :-
231 b_compute_expression_nowf(Parameter,[],State,Result,'operation parameter',OpId).
232
233
234 react_to_item_right_click(CurID,X,Y,ActionStr,ResTransitionID,ResNewID) :- % print(react(CurID,X,Y,ActionStr)),nl,
235 animation_mode(Mode),
236 ( can_react_to_item_right_click(CurID,Mode,X,Y,TransitionTemplateList,ActionStr,TransitionID),
237 get_template(TransitionTemplateList,TransitionTemplate),
238 tcltk_interface:tcltk_perform_action(CurID,TransitionTerm,TransitionID,NewID),
239 match_template(TransitionTemplate,TransitionTerm)
240 -> debug_format(19,'Performed: ~w~n',[TransitionTemplate]),
241 (get_template_rest(TransitionTemplateList,Rest)
242 -> % there are other actions to execute (automatically after a user-click; useful for chess,...)
243 execute_rest(Rest,TT), % currently only happens in XTL mode
244 ResTransitionID = [TransitionID|TT], ResNewID = unknown
245 % NewID points to first NewID, not to target; TO DO: modify command in case we support XTL in ProB2 UI
246 ; ResTransitionID = TransitionID, ResNewID=NewID
247 )
248 ; format('Cannot execute transition ~w~n Right-Click on (~w,~w)~n',[ActionStr,X,Y]),
249 fail
250 ).
251
252 % note: a single click is also a item_drag from an object to itself
253 tcltk_can_react_to_item_drag(FromTkPath,ToTkPath,Image) :-
254 animation_mode(M),
255 convert_tk_path_to_coordinates(FromTkPath,FromX,FromY),
256 convert_tk_path_to_coordinates(ToTkPath,ToX,ToY),
257 can_react_to_item_drag(M,FromX,FromY,ToX,ToY,ImageNr),
258 (ImageNr=none -> Image=''
259 ; get_animation_image_and_label(M,ImageNr,_,Lbl) -> Image=Lbl
260 ; Image='').
261
262 tcltk_react_to_item_drag(FromTkPath,ToTkPath) :-
263 convert_tk_path_to_coordinates(FromTkPath,FromX,FromY),
264 convert_tk_path_to_coordinates(ToTkPath,ToX,ToY),
265 debug_println(20,dragged_object(FromX,FromY,ToX,ToY)),
266 animation_mode(M),
267 react_to_item_drag(M,FromX,FromY,ToX,ToY).
268
269 :- use_module(probsrc(xtl_interface),[xtl_animation_image_click_transition/6]).
270 can_react_to_item_drag(Mode,FromX,FromY,ToX,ToY,ImageNr) :-
271 current_state_id(CurID),
272 get_item_drag_template_and_image(Mode,FromX,FromY,ToX,ToY,TransitionTemplateList,ImageNr),
273 get_template(TransitionTemplateList,TransitionTemplate),
274 transition(CurID,TransitionTemplate,_ActId,_DestID).
275
276 % transition templates can also be lists; we just check if first action is feasible
277 get_template([H|_],Template) :- !, % in XTL mode we allow lists of actions
278 Template=H.
279 get_template(Template,Template). % in B,TLA,Z,... mode we only execute a single event
280
281 get_template_rest([_|T],T).
282
283 get_item_drag_template_and_image(xtl,ColFromX,RowFromY,ToX,ToY,TransitionTemplate,ImageNr) :- !,
284 xtl_animation_image_click_transition(RowFromY,ColFromX,ToY,ToX,TransitionTemplate,ImageNr).
285 get_item_drag_template_and_image(b,FromX,FromY,ToX,ToY,Template,1000) :-
286 % TO DO: provide a way to return image number
287 Def_Name = 'ANIMATION_CLICK',
288 b_get_click_subst_definition(Def_Name,NrArgs,_RawSubst,DefPos),
289 temporary_set_preference(allow_local_operation_calls,true,CHNG),
290 Scope = [prob_ids(visible),operation_bodies], % do not include variables; otherwise clash warnings; variables already included in operation_bodies
291 (NrArgs = 2 -> DArgs = [integer(DefPos,ToX),integer(DefPos,ToY)]
292 ; NrArgs = 4 -> DArgs = [integer(DefPos,FromX),integer(DefPos,FromY),integer(DefPos,ToX),integer(DefPos,ToY)]
293 ; add_warning(state_viewer_images,'ANIMATION_CLICK should take 2 or 4 arguments, not: ',NrArgs,DefPos),
294 fail
295 ),
296 type_with_errors(definition(DefPos,'ANIMATION_CLICK',DArgs),Scope,subst,Typed),
297 reset_temporary_preference(allow_local_operation_calls,CHNG),
298 State = [], % TO DO: get full state like for right click
299 get_b_template(Typed,[],State,Template).
300
301
302 react_to_item_drag(Mode,FromX,FromY,ToX,ToY) :-
303 get_item_drag_template_and_image(Mode,FromX,FromY,ToX,ToY,TransitionTemplateList,_),
304 (get_template(TransitionTemplateList,TransitionTemplate),
305 tcltk_interface:tcltk_perform_action(TransitionTemplate,_)
306 -> (get_template_rest(TransitionTemplateList,Rest)
307 -> % there are other actions to execute
308 execute_rest(Rest,_)
309 ; true
310 )
311 ; format('Cannot execute transition ~w~n Mouse Drag (~w,~w)->(~w,~w)~n',
312 [TransitionTemplateList,FromX,FromY,ToX,ToY]),
313 fail
314 ).
315
316 % execute remaining templates of action
317 execute_rest([],Res) :- !, Res=[].
318 execute_rest([H|T],[TransitionID|TT]) :-
319 execute_rest_action(H,TransitionID), !,
320 execute_rest(T,TT).
321 execute_rest(T,[]) :- format('~n*** Cannot execute rest of transition template ~w~n',[T]).
322
323 execute_rest_action(b(Subst,subst,Info),TransId) :- !,
324 execute_b_rest(Subst,Info,TransId).
325 execute_rest_action(H,TransitionID) :-
326 current_state_id(CurID), %print(try_auto_play(CurID,H)),nl,
327 tcltk_interface:compute_all_transitions_if_necessary,
328 current_state_id(CurID),
329 (H=mcts_auto_play, tcltk_interface:mcts_auto_play_available
330 -> tcltk_interface:tcltk_mcts_auto_play(TransitionID)
331 ; tcltk_interface:tcltk_perform_action(CurID,H,TransitionID,_NewID)
332 ). %print(perf(H,_NewID)),nl,
333
334 execute_b_rest(external_subst_call('MCTS_AUTO_PLAY',_),Info,TransId) :- !,
335 (\+ tcltk_interface:mcts_auto_play_available ->
336 add_error(state_viewer_images,'MCTS_AUTO_PLAY not available, add GAME_PLAYER, ... defintions','',Info),fail
337 ; tcltk_interface:tcltk_mcts_auto_play(TransId) -> true
338 ; add_message(state_viewer_images,'MCTS_AUTO_PLAY not possible (end of game reached?)','',Info),fail
339 ).
340 execute_b_rest(RestAction,Info,_) :-
341 add_error(state_viewer_images,'Currently only MCTS_AUTO_PLAY supported here:',b(RestAction,subst,Info),Info),
342 fail.
343
344 % if successful convert a Tk Widget Path like .stateviewer.sviewFrame.frame1.item1_3
345 % to coordinates of the state_viewer module: (1,3)
346 convert_tk_path_to_coordinates(TkPath,XCoord,YCoord) :-
347 split_last(TkPath,'.',_,NameOfItemClicked),
348 atom_codes(NameOfItemClicked,Codes),
349 get_suffix(Codes,Rest),
350 !,
351 split_chars(Rest,"_",[YCC,XCC]), % note: coordinates reversed in label
352 number_codes(XCoord,XCC),
353 number_codes(YCoord,YCC).
354 convert_tk_path_to_coordinates(TkPath,_,_) :- format('*** Cannot convert TkPath ~w~n',[TkPath]),fail.
355
356 get_suffix(Codes,Rest) :- append("item",Rest,Codes),!.
357 get_suffix(Codes,Rest) :- append("text",Rest,Codes),!.
358 get_suffix(Codes,Rest) :- append("frame",Rest,Codes),!.
359
360 :- use_module(probsrc(custom_explicit_sets),[try_expand_custom_set_with_catch/3, is_set_value/2]).
361
362 eval_definition_fun(AnimFunction,Nr,BState, FunctionRes) :-
363 on_enumeration_warning(
364 b_compute_explicit_epression_no_wf(AnimFunction,[],BState,FunctionResCl,'ANIMATION_FUNCTION',Nr),
365 fail),
366 %% nl, print('FunctionResult'(FunctionResCl)),nl,
367 is_set_value(FunctionResCl,eval_definition_fun),
368 try_expand_custom_set_with_catch(FunctionResCl, ExpCl, eval_definition_fun),
369 (translate_to_ints(ExpCl, FunctionRes)
370 -> true /* already translate to ints so that override will work properly */
371 ; check_anim_function(ExpCl),fail
372 ) % ,print('fres'(FunctionRes)),nl
373 .
374
375 check_anim_function([]) :- !.
376 %check_anim_function(int(_)) :- !. % just a single picture; now gets converted by translate_to_ints
377 check_anim_function([H|_]) :- !,
378 (H = (RowCol,_Img), get_pair(RowCol,Row,Col) ->
379 (get_int(Row,_),get_int(Col,_) -> true
380 ; add_error(state_viewer_images,'Elements of ANIMATION_FUNCTION should be convertible to (INT*INT)*INT: ',H)
381 )
382 ; H = (Row,ColImg), get_pair(ColImg,Col,_Img) ->
383 (get_int(Row,_),get_int(Col,_) -> true
384 ; add_error(state_viewer_images,'Elements of ANIMATION_FUNCTION should be convertible to INT*(INT*INT): ',H)
385 )
386 ; add_error(state_viewer_images,
387 'Elements of the ANIMATION_FUNCTION should be of type (INT*INT)*INT: ',H)
388 ).
389 check_anim_function((A,B)) :- !,
390 add_error(state_viewer_images,'ANIMATION_FUNCTION should be a set of pairs, not a pair: ',(A,B)).
391 check_anim_function(X) :- !,
392 add_error(state_viewer_images,'ANIMATION_FUNCTION should be of type (INT*INT) +-> INT (or similar): ',X).
393
394 :- use_module(library(avl)).
395
396 translate_to_ints(In,Out) :- empty_avl(E),translate_to_ints(In,E,Out).
397 translate_to_ints([],_,[]) :-!.
398 translate_to_ints(X,_,Res) :- get_int(X,IX),!,Res=[((1,1),int(IX))]. % a single picture
399 translate_to_ints([H|T], AVL, Res) :-
400 translate_element(H,AVL, NewAVL, Res, NewRes),
401 translate_to_ints(T,NewAVL,NewRes).
402
403 translate_element((RowCol,Img),AVL, NewAVL, Res, NewRes) :- get_pair(RowCol,Row,Col),!,
404 get_int(Row,RI), get_int(Col,CI), (Img=II),
405 add_image(RI,CI,II, AVL, NewAVL, Res, NewRes).
406 translate_element((Row,ColImg),AVL, NewAVL, Res, NewRes) :- get_pair(ColImg,Col,Img),!,
407 translate_element(((Row,Col),Img), AVL, NewAVL, Res, NewRes).
408 translate_element((Row,Set),AVL,NewAVL,Res,NewRes) :- % Set can be relation or sequence
409 % expand Set and associate elements with Row
410 is_set_value(Set,translate_element),
411 try_expand_custom_set_with_catch(Set, ESet,translate_element),
412 findall((Row,El),member(El,ESet),All),
413 l_translate(All,AVL,NewAVL,Res,NewRes).
414
415
416
417 l_translate([],AVL,AVL,Res,Res).
418 l_translate([H|T],AVL,NewAVL,Res,NewRes) :- translate_element(H,AVL,NewAVL1,Res,NewRes1),
419 l_translate(T,NewAVL1,NewAVL,NewRes1,NewRes).
420
421 add_image(RI,CI,II, AVL, NewAVL, Res, NewRes) :-
422 (avl_fetch((RI,CI),AVL,ExistingValue)
423 -> add_error(state_viewer_images,
424 'Animation function defines two images for (Row,Col):[img1,img2] = ',((RI,CI):[ExistingValue,II])),
425 NewAVL = AVL, Res=NewRes
426 ; avl_store((RI,CI),AVL,II,NewAVL), Res=[((RI,CI),II)|NewRes]
427 ).
428
429 /* a version of override which does not worry about correct typing */
430 % override_anim_fun(Fun1, Fun2, Res) :: Fun2 overrides Fun1
431 override_anim_fun([],Fun2,Res) :- !, Res=Fun2.
432 override_anim_fun(int(_),Fun2,Res) :- !, Res=Fun2.
433 override_anim_fun([((RowT,Col),Img)|T],Fun2,Res) :- !,
434 (member(((RowT,Col),_),Fun2)
435 -> Res = ResT % we use version from Fun2
436 ; Res = [((RowT,Col),Img)|ResT]
437 ), override_anim_fun(T,Fun2,ResT).
438 override_anim_fun(X,F,R) :-
439 add_error(state_viewer_images,'Unknown Format for ANIMATION_FUNCTION_DEFAULT', X),
440 R=F.
441
442 % get minimum and maximum index for rows
443 get_min_max_row([((Row,_Col),_Img)|T],Min,Max) :- !,
444 number(Row), % this is already in a format for Tcl/Tk; not int(.)
445 get_min_max_row2(T,Row,Row,Min,Max).
446 get_min_max_row([],_,_) :- !,
447 print('**** Empty ANIMATION_FUNCTION result'),nl, fail.
448 get_min_max_row(Res,_,_) :-
449 add_error(state_viewer_images,
450 'Unknown Format for ANIMATION_FUNCTION result, must be of type INT or (INT*INT)+->INT',Res),
451 fail.
452
453 get_min_max_row2([],Min,Max,Min,Max).
454 get_min_max_row2([((Row,_Col),_Img)|T],Min,Max,MinR,MaxR) :-
455 (Row<Min -> Min1=Row ; Min1=Min),
456 (Row>Max -> Max1=Row ; Max1=Max),
457 get_min_max_row2(T,Min1,Max1,MinR,MaxR).
458
459 % get minimum and maximum index for columns
460 get_min_max_col([((_Row,Col),_Img)|T],Min,Max) :- !,
461 number(Col), % this is already in a format for Tcl/Tk; not int(.)
462 get_min_max_col2(T,Col,Col,Min,Max).
463 get_min_max_col2([],Min,Max,Min,Max).
464 get_min_max_col2([((_Row,Col),_Img)|T],Min,Max,MinR,MaxR) :-
465 (Col<Min -> Min1=Col ; Min1=Min),
466 (Col>Max -> Max1=Col ; Max1=Max),
467 get_min_max_col2(T,Min1,Max1,MinR,MaxR).
468
469 get_int(Nr,R) :- number(Nr),!,R=Nr.
470 get_int(int(R),R).
471 get_int(fd(R,_Name),R).
472 get_int(pred_true /* bool_true */,1).
473 get_int(pred_false /* bool_false */,0).
474 /* can sometimes do unwanted conversions and show images where we do not want them:
475 get_int(string(A),Integer) :- % convert something like "Train1" -> 1
476 atom_codes(A,Codes), reverse(Codes,RC),
477 get_number_prefix(RC,Prefix),
478 Prefix \= [], reverse(Prefix,RP),
479 number_codes(Integer,RP).
480
481 get_number_prefix([N|T],[N|RT]) :- N >= 48, N =< 57, % Ascii of a digit 0-9
482 !, get_number_prefix(T,RT).
483 get_number_prefix(_,[]).
484 */
485
486 get_pair((A,B),A,B).
487 get_pair(avl_set(node((int(1),A),true,1,empty,node((int(2),B),true,0,empty,empty))),A,B). % in TLA: <<a,b>> sometimes translated as sequence
488
489
490 :- use_module(probsrc(bmachine),[b_get_true_expression_definition/1]).
491 % add extra whitespace to make all text fields the same length
492 % TO DO: maybe only pad within a column; not overall
493 pad_text_frame_items(FrameItems,NewFrameItems) :- b_or_z_mode,
494 (b_get_true_expression_definition('ANIMATION_STR_JUSTIFY_LEFT') ;
495 b_get_true_expression_definition('ANIMATION_STR_JUSTIFY_RIGHT') ),
496 longest_text(FrameItems,0,Len),
497 Len>0,
498 !,
499 %print(longest(Len)),nl,
500 pad_text_frame_items_to(FrameItems,Len,NewFrameItems).
501 pad_text_frame_items(F,F).
502
503
504 pad_text_frame_items_to([],_,[]).
505 pad_text_frame_items_to([ItemLabel,Frame,Text|TR],Len,[ItemLabel,Frame,NewText|NTR]) :-
506 (is_text_type(ItemLabel)
507 -> atom_codes(Text,Codes),
508 length(Codes,TLen),
509 AdditionalSpaces is Len-TLen, gen_spaces(AdditionalSpaces,AS),
510 (b_get_true_expression_definition('ANIMATION_STR_JUSTIFY_RIGHT')
511 -> append(AS,Codes,NewCodes)
512 ; append(Codes,AS,NewCodes) % 34 -> ' 39 -> "
513 ),
514 atom_codes(NewText,NewCodes)
515 ; NewText=Text),
516 pad_text_frame_items_to(TR,Len,NTR).
517
518 gen_spaces(Nr,R) :- Nr<1,R=[]. % 34 -> '
519 gen_spaces(Nr,[32|T]) :- N1 is Nr-1, gen_spaces(N1,T).
520
521
522 % find longest text label; so that we can pad the other ones with spaces
523 longest_text([],R,R).
524 longest_text([ItemLabel,_Frame,Text|TR],Acc,R) :-
525 is_text_type(ItemLabel),!,
526 atom_length(Text,Len),
527 (Len>Acc -> NAcc = Len ; NAcc=Acc),
528 longest_text(TR,NAcc,R).
529 longest_text([_,_,_|TR],Acc,R) :- longest_text(TR,Acc,R).
530
531 is_text_type(ItemLabel) :- atom_codes(ItemLabel,Codes), append("text",_,Codes).
532
533 get_frame_items([],[]).
534 get_frame_items([((Row,Col),Img)|T],[ItemLbl,FrameLbl,ImageLbl|TR]) :-
535 convert_nr_into_tk_label(Row,"frame",FrameLbl),
536 (get_int(Img,ImgNr),images(ImgNr,_,ImageLbl)
537 -> convert_2nr_into_tk_label(Row,Col,"item",ItemLbl)
538 ; convert_2nr_into_tk_label(Row,Col,"text",ItemLbl),
539 (get_int(Img,ImgNr),get_animation_string(ImgNr,ImageLbl) -> true
540 ; translate_value_for_tk_text(Img,ImageLbl)
541 )
542 ),
543 get_frame_items(T,TR).
544
545 setup_frames(Min,Max,[]) :- Min>Max,!.
546 setup_frames(Min,Max,[frame, FrameLbl, top |T]) :-
547 convert_nr_into_tk_label(Min,"frame",FrameLbl), M1 is Min+1,
548 setup_frames(M1,Max,T).
549
550 :- dynamic images/3.
551
552
553 get_animation_images(Mode,Res) :- clear_animation_images,
554 findall( img(Nr,ImgFilename,Lbl), get_animation_image_and_label(Mode,Nr,ImgFilename,Lbl), List),
555 flatten_img_list(List,Res).
556 clear_animation_images :- retractall(images(_,_,_)).
557
558 flatten_img_list([],[]).
559 flatten_img_list([img(Nr,ImgFilename,Lbl)|T],[Lbl,ImgFilename|FT]) :-
560 assertz(images(Nr,ImgFilename,Lbl)), flatten_img_list(T,FT).
561
562
563 get_animation_image_and_label(Mode,Nr,ImgFilename,Lbl) :-
564 get_animation_image_in_mode(Mode,Nr,ImgFilename),
565 convert_nr_into_tk_label(Nr,"IMG",Lbl).
566
567 get_animation_image_in_mode(xtl,Nr,S) :- !, xtl_animation_image(Nr,S).
568 get_animation_image_in_mode(b,Nr,S) :- !, get_animation_image(Nr,S).
569 get_animation_image_in_mode(csp_and_b,Nr,S) :- get_animation_image(Nr,S).
570 % csp not covered
571
572 get_animation_string(Nr,S) :- b_or_z_mode,
573 number_codes(Nr,TailCodes),
574 /* ANIMATION_STR */
575 atom_codes(Def_Name,[65,78,73,77,65,84,73,79,78,95,83,84,82|TailCodes]),
576 b_get_definition_string_from_machine(Def_Name,S).
577
578
579 convert_nr_into_tk_label(Nr,Prefix,Label) :- number_codes(Nr,Codes),
580 append(Prefix,Codes,C),
581 atom_codes(Label,C).
582
583 :- use_module(library(lists),[append/2]).
584 convert_2nr_into_tk_label(Nr1,Nr2,Prefix,Label) :-
585 number_codes(Nr1,Codes1), number_codes(Nr2,Codes2),
586 append([Prefix,Codes1,"_",Codes2],C),
587 atom_codes(Label,C).
588
589 % --------------------------
590
591 % a function for Java FX or other graphical frameworks
592 % | ?- get_animation_images(L).
593 % L = [image_file(0,'images/empty_box_white.gif'),...,image_file(6,'images/F.gif')] ?
594
595 get_animation_images(SList) :-
596 animation_mode(Mode),
597 findall( image_file(Nr,File), get_animation_image_in_mode(Mode,Nr,File), List),
598 sort(List,SList).
599
600 get_animation_image_numbers(SList) :-
601 animation_mode(Mode),
602 findall( Nr, get_animation_image_in_mode(Mode,Nr,_File), List), % TO DO: also get animation strings
603 sort(List,SList).
604
605 % a function for Java FX or other graphical frameworks
606 % | ?- get_animation_image_grid(1,G,M,X).
607 %G = [entry(1,1,image(0)),entry(1,2,image(0)),entry(1,3,image(0)),entry(1,4,image(0)),...,entry(Row,Col,image(...)),(...,...)|...],
608 %M = 1,
609 %X = 6 ?
610
611 :- use_module(probsrc(state_space),[visited_expression/2]).
612 :- use_module(library(lists)).
613 get_animation_image_grid(ID,Matrix,MinRow,MaxRow,MinCol,MaxCol) :-
614 animation_mode(Mode),
615 animation_function_possibly_active(Mode), % avoid expanding state; can be expensive
616 visited_expression(ID,State),
617 evaluate_animation_function(Mode,State,FunctionRes),
618 get_min_max_row(FunctionRes,MinRow,MaxRow),
619 get_min_max_col(FunctionRes,MinCol,MaxCol),
620 get_animation_image_numbers(ImageNumbers),
621 maplist(convert_animation_function(Mode,ImageNumbers),FunctionRes,Matrix).
622
623
624 :- use_module(library(ordsets),[ord_member/2]).
625 :- use_module(library(codesio),[write_to_codes/2]).
626
627 convert_animation_function(Mode,ImageNumbers,((Row,Col),Res),
628 entry(Row,Col,TranslatedRes)) :-
629 convert_aux(Mode,ImageNumbers,Res,TranslatedRes).
630 convert_aux(_Mode,ImageNumbers,Img,image(ImgNr)) :- get_int(Img,ImgNr),ord_member(ImgNr,ImageNumbers),!.
631 convert_aux(_Mode,_,Str,text(StringLbl)) :- get_int(Str,StrNr),get_animation_string(StrNr,StringLbl),!.
632 convert_aux(b,_,Value,text(PPValue)) :- translate_value_for_tk_text(Value,PPValue),!.
633 convert_aux(_,_,Value,text(AtomValue)) :- compound(Value),
634 !,
635 write_to_codes(Value,VC), atom_codes(AtomValue,VC).
636 convert_aux(_,_,Value,text(Value)).
637
638 translate_value_for_tk_text(string(Str),Res) :- !, % show string without quotes
639 Res=Str. % TO DO: do we need to escape something here?
640 translate_value_for_tk_text(Value,PPValue) :- translate:translate_bvalue(Value,PPValue),!.
641
642 % export to HTML
643 %html_print_animation_image_grid(ID) :- html_print_animation_image_grid(user_output,ID,'').
644
645 html_print_animation_image_grid(Stream,ID,FilePrefix) :-
646 get_animation_image_grid(ID,Matrix,MinRow,_MaxRow,_MinCol,_MaxCol),
647 sort(Matrix,SortedMatrix),
648 start_tag(Stream,table),
649 start_tag(Stream,tr),animation_mode(Mode),
650 html_print(SortedMatrix,Stream,MinRow,Mode,FilePrefix),
651 end_tag(Stream,table).
652
653 html_print([],Stream,_,_,_FilePrefix) :- end_tag(Stream,tr).
654 html_print([entry(Row,_Col,Img)|T],Stream,LastRow,Mode,FilePrefix) :-
655 (Row>LastRow -> end_tag(Stream,tr),start_tag(Stream,tr) ; true),
656 % TO DO: insert empty cells when we jump over Columns
657 html_image(Img,Stream,Mode,FilePrefix),
658 html_print(T,Stream,Row,Mode,FilePrefix).
659
660 html_image(image(ImgNr),Stream,Mode,FilePrefix) :- get_animation_image_in_mode(Mode,ImgNr,File),!,
661 ((FilePrefix='' ; is_absolute_path(File))
662 -> format(Stream,' <th><img src="~w"></th>~n',[File])
663 ; format(Stream,' <th><img src="~w~w"></th>~n',[FilePrefix,File])
664 ).
665 html_image(text(T),Stream,_,_) :- !,
666 format(Stream,' <th><tt>~w</tt></th>~n',[T]).
667 html_image(T,Stream,_,_) :-
668 format(Stream,' <th>ERROR: ~w</th>~n',[T]).
669
670 start_tag(Stream,T) :- format(Stream,'<~w>~n',[T]).
671 end_tag(Stream,T) :- format(Stream,'</~w>~n',[T]).
672
673 :- use_module(probsrc(bmachine),[b_get_machine_animation_expression/2]).
674 :- use_module(probsrc(translate),[translate_bvalue/2,translate_bexpression/2]).
675 html_print_animation_expression(Stream,StateID) :-
676 get_animation_expression_label_and_value(StateID,S1,S2),
677 format(Stream,'~w=~w~n',[S1,S2]).
678 html_print_animation_expression(_,_).
679
680 get_animation_expression_label_and_value(StateID,S1,S2) :- b_or_z_mode,
681 b_get_machine_animation_expression('ANIMATION_EXPRESSION',AExpr),
682 visited_expression(StateID,State),
683 state_corresponds_to_fully_setup_b_machine(State,BState),
684 b_compute_expression_nowf(AExpr,[],BState,AValue,'ANIMATION_EXPRESSION',0),
685 translate_bexpression(AExpr,S1),
686 translate_bvalue(AValue,S2).
687
688 :- use_module(probsrc(state_space), [transition/4,visited_expression/2,
689 current_expression/2, current_state_id/1,
690 get_action_term_trace/1, get_state_id_trace/1]).
691
692
693 html_print_history(File) :- html_print_history(File,3).
694 html_print_history(File,MaxOpDebugLevel) :-
695 get_state_id_trace([root|StateIds]),
696 get_action_term_trace(RAT), reverse(RAT,Actions),
697 % TO DO: adapt path of images so that they work in File
698 (currently_opened_file(SpecFile), atom(SpecFile)
699 -> get_parent_directory(SpecFile,SParent),
700 absolute_file_name(SParent, SAbsParent), %, [relative_to(Directory)]),
701 get_parent_directory(File,TParent),
702 absolute_file_name(TParent, TAbsParent), %, [relative_to(Directory)]),
703 compute_prefix(SAbsParent,TAbsParent,FilePrefix)
704 ; SpecFile=unknown, FilePrefix='.'),
705 open(File,write,Stream,[encoding(utf8)]),
706 html_header(Stream,true),
707 html_info(Stream,Actions,SpecFile),
708 html_print_history2(Stream,1,Actions,StateIds,none,FilePrefix,MaxOpDebugLevel),
709 html_footer(Stream),
710 close(Stream).
711
712 :- use_module(probsrc(tools_strings),[ajoin_with_sep/3]).
713 :- use_module(probsrc(tools),[split_atom/3,is_absolute_path/1]).
714
715 % compute a file prefix that needs to be added to relocate relative path for OldPath to paths for NewPath:
716 compute_prefix(OldPath,NewPath,FilePrefix) :-
717 %print(old(OldPath)),nl, print(new(NewPath)),nl,
718 split_atom(OldPath,['/'],O1),
719 split_atom(NewPath,['/'],N1),
720 max_prefix(O1,N1,_CommonPrefix,O2,N2), %print(common(CommonPrefix)),nl,
721 maplist(gendotdot,N2,N3),
722 append(N3,O2,UpdatePath),
723 (UpdatePath=[] -> FilePrefix = ''
724 ; append(UpdatePath,[''],U1),
725 ajoin_with_sep(U1,'/',FilePrefix)),
726 debug_println(9,update_prefix_for_images(FilePrefix)).
727
728 gendotdot(_,'..').
729
730 max_prefix([H|T],[H|T2],[H|PT],Suffix1,Suffix2) :- !,
731 max_prefix(T,T2,PT,Suffix1,Suffix2).
732 max_prefix(S1,S2,[],S1,S2).
733
734 html_print_state(Stream,ID,FilePrefix) :-
735 (html_print_animation_image_grid(Stream,ID,FilePrefix)
736 -> true ; format(Stream,'No visualisation available for state id ~w~n',[ID])),
737 html_print_animation_expression(Stream,ID).
738
739 :- use_module(probsrc(translate),[translate_event/2]).
740 html_print_history2(_,_,[],[],_,_,_).
741 html_print_history2(Stream,_,[],[ID|_],_,FilePrefix,_) :-
742 html_print_state(Stream,ID,FilePrefix).
743 html_print_history2(Stream,StepNr,[Action|AT],[ID|T],PreviousID,FilePrefix,MaxOpDebugLevel) :-
744 translate_event(Action,AS),
745 format(Stream,'~n~n<h2>~w. ~w</h2>~n',[StepNr,AS]), flush_output(Stream),
746 html_print_action(Stream,Action,PreviousID,ID,MaxOpDebugLevel),
747 html_print_state(Stream,ID,FilePrefix),
748 S1 is StepNr+1,
749 html_print_history2(Stream,S1,AT,T,ID,FilePrefix,MaxOpDebugLevel).
750
751 :- use_module(probsrc(specfile),[get_operation_name/2]). %get_operation_arguments
752 :- use_module(extrasrc(bvisual2),[html_debug_operation_for_stateid/4]).
753 html_print_action(Stream,Action,PreviousID,_ID,MaxLevel) :-
754 MaxLevel > 0, PreviousID \= none,
755 get_operation_name(Action,OpName),
756 !,
757 % print operation guards up to MaxLevel nesting, TODO: use parameter values for this action
758 (html_debug_operation_for_stateid(Stream,OpName,PreviousID,MaxLevel) % fails for INITIALISATION, SETUP_CONSTANTS
759 -> true
760 ; true). %add_internal_error('Failed: ',html_debug_operation_for_stateid(OpName,ID,MaxLevel))).
761 html_print_action(_,_,_,_,_).
762
763 html_header(Stream,Border) :-
764 format(Stream,'<html>~n<head>~n<style>~ntable, th, td {~n',[]),
765 (Border=true -> format(Stream,' border: 1px solid black;~n',[]) ; true),
766 format(Stream,' border-collapse: collapse;~n}~nth, td {~n padding: 0px;~n}~n</style>~n</head>~n<body>',[]).
767
768
769 html_footer(Stream) :-
770 format(Stream,'</body>~n</html>~n',[]).
771
772 :- use_module(probsrc(version), [version_str/1, revision/1, lastchangeddate/1]).
773 :- use_module(library(system),[ datime/1]).
774 :- use_module(probsrc(specfile),[currently_opened_file/1]).
775 html_info(Stream,A,SpecFile) :-
776 format(Stream,'<h2>Information</h2>~n<ul>~n',[]),
777 datime(datime(Year,Month,Day,Hour,Min,_Sec)),
778 format(Stream,' <li>Trace generated on ~w.~w.~w at ~w:~w</li>~n',[Day,Month,Year,Hour,Min]),
779 length(A,Len),
780 format(Stream,' <li>Trace length: ~w</li>~n',[Len]),
781 animation_mode(Mode),
782 format(Stream,' <li>Specification file (~w): ~w</li>~n',[Mode,SpecFile]),
783 ((SpecFile \= unknown,get_file_revision_info(SpecFile,GitRev))
784 -> format(Stream,' <li>Git revision of file: ~s</li>~n',[GitRev]) ; true),
785 ((SpecFile \= unknown,get_HEAD_revision_info(SpecFile,GitHeadRev))
786 -> format(Stream,' <li>Git revision of repository HEAD: ~s</li>~n',[GitHeadRev]) ; true),
787 version_str(V), revision(R), lastchangeddate(LD),
788 format(Stream,' <li>ProB version: ~w</li>~n',[V]),
789 format(Stream,' <li>ProB revision: ~w (~w)</li>~n',[R, LD]),
790 format(Stream,'</ul>~n',[]).
791
792 % b_get_main_filename -> Project Info:, Model Version/Revision ? Can we ask git ?
793 % git ls-files -s VSS_TrainStatus_HL3.mch diff
794 % git rev-parse HEAD
795
796 :- use_module(probsrc(system_call),[get_command_path/2, system_call_with_options/6]).
797 :- use_module(probsrc(tools),[get_parent_directory/2]).
798
799 get_file_revision_info(File,GitOutputText) :-
800 get_parent_directory(File,CurWorkingDir),
801 run_git_command(['ls-files','-s',File],CurWorkingDir,GitOutputText).
802 get_HEAD_revision_info(ReferenceFile,GitOutputText) :-
803 get_parent_directory(ReferenceFile,CurWorkingDir),
804 run_git_command(['rev-parse','HEAD'],CurWorkingDir,GitOutputText).
805
806
807 run_git_command(COMMAND,CurWorkingDir,GitOutputText) :-
808 get_command_path(git,GitPath),
809 (debug_mode(on) -> format(user_output,'Git: ~w with CWD: ~w~n',[GitPath,CurWorkingDir]) ; true),
810 catch(
811 system_call_with_options(GitPath,COMMAND,[cwd(CurWorkingDir)],GitOutputText,GitError,ExitCode),
812 E,
813 (debug_format(9,'Git exception: ~w~n',[E]),fail)),
814 (debug_mode(on)
815 -> format(user_output,'git command ~w~n:~s~nError: ~s~nExitCode:~w~n',
816 [COMMAND,GitOutputText,GitError,ExitCode]) ; true),
817 ExitCode = exit(0), GitError=[].
818
819