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