1 % (c) 2009-2026 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
5 :- module(dot_graph_generator, [gen_dot_graph/3, gen_dot_graph/5, gen_dot_graph/6,
6 dot_no_same_rank/1, dot_no_subgraph/3,
7 print_graph_header/1,print_graph_footer/0,
8 use_new_dot_attr_pred/7, % annotation for new-style dot predicate
9 get_dot_cluster_name/2,
10 translate_bvalue_to_colour/2, try_translate_bvalue_to_colour/2,
11 translate_int_col/2, list_to_dot_record/2,
12 legend_top_margin/1]).
13
14 :- meta_predicate(gen_dot_graph(*,6,5)).
15 :- meta_predicate(gen_dot_graph(*,6,5,1,3)).
16 :- meta_predicate(gen_dot_graph(*,*,6,5,1,3)).
17 :- meta_predicate(node_id(6,*)).
18 :- meta_predicate(node_predicate_call(6,*,*,*)).
19 :- meta_predicate(trans_predicate_call(:,*,*,*,*,*)). % adds 3 or 5 args
20 :- meta_predicate(merged_call5(5,*,*,*,*,*)). % adds 5 args
21 :- meta_predicate(same_rank_call(1,*)).
22 :- meta_predicate(subgraph_call(3,*,*,*,*,*)).
23 :- meta_predicate(fgen_dot_graph(*,*,6,5,1,3)).
24 :- meta_predicate(print_nodes(*,6,3)).
25 :- meta_predicate(print_nodes2(*,*,6)).
26 :- meta_predicate(print_transitions(*,*,*,5)).
27
28 :- use_module(probsrc(module_information)).
29 :- module_info(group,dot).
30 :- module_info(description,'This a few tools for generating dot graphs.').
31
32 :- use_module(library(lists)).
33 :- use_module(probsrc(preferences)).
34
35 :- use_module(probsrc(debug)).
36 :- use_module(probsrc(self_check)).
37 :- use_module(probsrc(error_manager),[add_internal_error/2, add_message/3]).
38
39 /* --------------------------------------------------- */
40 /* MAIN ENTRY POINTS FOR TCL */
41 /* --------------------------------------------------- */
42
43 gen_dot_graph(F,NodePredicate,TransPredicate) :-
44 gen_dot_graph(F,NodePredicate,TransPredicate,dot_no_same_rank,dot_no_subgraph).
45 gen_dot_graph(F,NodePredicate,TransPredicate,SameRankPred,SubGraphPred) :-
46 gen_dot_graph(F,[],NodePredicate,TransPredicate,SameRankPred,SubGraphPred).
47
48 % Note: you can pass also things like layout/circo in GraphAttrs
49 % Additional meta options in GraphAttrs (not printed as graph attributes):
50 % - graph_name/Name : name of the dot graph (default prob_graph)
51 % - node_defaults/AttrList: default attributes for all nodes, printed as node [...]
52 % - edge_defaults/AttrList: default attributes for all edges, printed as edge [...]
53 % (when node/edge defaults are given, the dot_node_font_size, dot_edge_font_size and dot_edge_penwidth
54 % preferences are added to them rather than to every node/edge, so that the defaults can override them)
55 % - legend_title/Title : title of the legend (default Legend)
56 % - legend_rank/Rank : rank of legend node: min (default), max, source, sink or none
57 % Nodes and edges (from new-style attribute predicates) can carry meta attributes:
58 % - legend/Text : add an entry Text to the legend, drawn like the first node/edge with this Text
59 % - legend_order/Nr : position in the legend (default: nodes 100, edges 200; ties by first occurrence)
60 % A legend is only printed if at least one node or edge has a legend/Text attribute.
61 % Subgraph (cluster) labels can be htmllabel(Html), where Html includes the outer < >.
62 gen_dot_graph(F,GraphAttrs,NodePredicate,TransPredicate,SameRankPred,SubGraphPred) :-
63 formatsilent('% Generating Dot File: ~w~n',[F]),
64 reset_ids,
65 (get_preference(dot_horizontal_layout,true),
66 \+ has_attribute(rankdir,_,GraphAttrs) -> Opts0 = [rankdir/'LR'|GraphAttrs] ; Opts0 = GraphAttrs),
67 (select(no_page_size,Opts0,Opts) -> true
68 ; get_preference(dot_with_page_size,true),
69 \+ has_attribute(page,_,GraphAttrs),
70 \+ has_attribute(size,_,GraphAttrs)
71 -> Opts = [with_page_size|Opts0]
72 ; Opts = Opts0),
73 open(F,write,FStream,[encoding(utf8)]),
74 (fgen_dot_graph(FStream,Opts,NodePredicate,TransPredicate,SameRankPred,SubGraphPred) -> true ; true),
75 close(FStream),
76 formatsilent('% Done~n',[]).
77
78
79 % Placeholder predicates for when caller doesn't need SameRankPred and/or SubGraphPred
80 dot_no_same_rank(_) :- fail.
81 dot_no_subgraph(_, _, _) :- fail.
82
83
84 node_id(P,TNodeID) :-
85 call(P,NodeID,_,_,_,_,_),
86 translate_id(NodeID,TNodeID).
87
88 node_predicate_call(Pred,TNodeID,SubGraph,Attributes) :-
89 get_new_style_node_pred(Pred,NodePredicate),!,
90 call(NodePredicate,NodeID,SubGraph,Attributes), % new style has only 3 arguments with flexible attribute list
91 translate_id(NodeID,TNodeID).
92 node_predicate_call(NodePredicate,TNodeID,SubGraph,[shape/Shape|Attrs]) :-
93 call(NodePredicate,NodeID,SubGraph,NodeDesc,Shape,Style,Color), % has 6 arguments
94 translate_id(NodeID,TNodeID),
95 (Style = none -> Attrs = Attrs2 ; Attrs = [style/Style|Attrs2]),
96 (Color = none -> Attrs2 = Attrs3 ; Attrs2 = [color/Color|Attrs3]),
97 %preference(dot_print_node_ids,true) -> we are not interested in internal ids of this module, are we??
98 Attrs3 = [label/NodeDesc].
99
100 get_new_style_node_pred(use_new_dot_attr_pred(NodePredicate),NodePredicate).
101 get_new_style_node_pred(_:use_new_dot_attr_pred(NodePredicate),NodePredicate).
102
103 % convert a new style Node Predicate which returns a flexible list of attributes
104 % dummy call: real conversion is done in node_predicate_call
105 use_new_dot_attr_pred(NodePredicate,NodeID,SubGraph,none,none,none,none) :-
106 call(NodePredicate,NodeID,SubGraph,_Attributes).
107
108
109 % -------
110
111 trans_predicate_call(Pred,_Opts,TNodeID,TSuccNodeID,Style,Attrs2) :-
112 get_new_style_node_pred(Pred,NodePredicate),!,
113 call(NodePredicate,NodeID,SuccNodeID,Attrs), % new style has only 3 arguments with flexible attribute list
114 % TODO: allow to merge_transitions with same Attrs except label
115 (select_attribute(style,Style,Attrs,Attrs2) -> true ; Style=solid,Attrs2=Attrs),
116 translate_id_for_transition(NodeID,TNodeID),
117 translate_id_for_transition(SuccNodeID,TSuccNodeID).
118 trans_predicate_call(P,Opts,TNodeID,TSuccNodeID,Style,[color/Color,label/Label]) :-
119 (has_attribute(merge_transitions,true,Opts)
120 -> merged_call5(P,NodeID,Label,SuccNodeID,Color,Style)
121 ; call(P,NodeID,Label,SuccNodeID,Color,Style)
122 ),
123 translate_id_for_transition(NodeID,TNodeID),
124 translate_id_for_transition(SuccNodeID,TSuccNodeID).
125
126 :- use_module(probsrc(tools_strings),[ajoin_with_sep/3]).
127 :- use_module(probsrc(tools_meta),[setof4/4]).
128 % merge all labels with the same origin, destination, color and style
129 merged_call5(P,NodeID,Label,SuccNodeID,Color,Style) :-
130 % we use setof4 rather than setof, because test 1033 fails on Intel platforms due to different order of sols
131 setof4(Lbl,[NodeID,SuccNodeID,Color,Style],call(P,NodeID,Lbl,SuccNodeID,Color,Style), Labels),
132 ajoin_with_sep(Labels,',',Label).
133
134
135 same_rank_call(_:dot_no_same_rank,_) :- !,fail.
136 same_rank_call(P,TNodes) :-
137 call(P,Nodes),
138 Nodes \= [], % empty list provides no information
139 maplist(translate_id,Nodes,TNodes).
140 /* should succeed once for every set of NodeIDs which should be of same rank */
141
142 % should succeed once for every subgraph and generate a subgraphID which is passed to the node predicate
143 subgraph_call(_:dot_no_subgraph,_,_,_,_,_) :- !, fail.
144 subgraph_call(P,SubGraphID,Style,Color,Label,OtherAttrs) :-
145 call(P,ID,Style,Color),
146 extract_new_attrs(ID,SubGraphID,Attrs),
147 (select_attribute(label,Label,Attrs,OtherAttrs) -> true
148 ; OtherAttrs=Attrs, Label=SubGraphID).
149 /* Notes: SubGraphID: should be none if not in a subgraph; Style and Color can be none */
150
151 extract_new_attrs(sub_graph_with_attributes(ID,Attrs),SubGraphID,OtherAttrs) :-
152 !, % new style subgraph predicate: additional info
153 SubGraphID=ID, OtherAttrs=Attrs.
154 extract_new_attrs(ID,ID,[]). % old style subgraph predicate: ID is just an atom
155
156 :- dynamic stored_id/2, additional_id/2.
157 :- dynamic next_id/1.
158 next_id(0).
159
160 reset_ids :-
161 retractall(stored_id(_,_)), retractall(next_id(_)),
162 retractall(additional_id(_,_)),
163 assertz(next_id(0)),
164 reset_legend.
165
166 update_next_id_if_necessary(ID) :- next_id(NID),
167 ID >= NID,!, % user specifies a number greater equal to next id
168 N1 is ID+1,
169 retract(next_id(_)),
170 assert(next_id(N1)).
171 update_next_id_if_necessary(_).
172
173 % translate ids to atoms; ensure that dot can deal with them
174 translate_id(ID,TransID) :-
175 (integer(ID) -> TransID=ID, update_next_id_if_necessary(ID)
176 ; var(ID) -> add_internal_error('Illegal variable identifier for dot:',translate_id(ID,TransID)),
177 TransID is -1
178 ; stored_id(ID,SID) -> TransID=SID
179 ; gen_new_node_id(NewAtom),
180 assertz(stored_id(ID,NewAtom)),
181 TransID = NewAtom
182 ).
183
184 gen_new_node_id(NewAtom) :-
185 retract(next_id(NextId)), N1 is NextId+1,
186 assertz(next_id(N1)),
187 number_codes(NextId,NC),
188 append("dot_node_",NC,AC), atom_codes(NewAtom,AC).
189
190 % called in transition creation: we should in principle no longer add new nodes:
191 translate_id_for_transition(ID,TransID) :-
192 (number(ID) -> TransID=ID
193 ; var(ID) -> add_internal_error('Illegal variable identifier for dot:',translate_id(ID,TransID)),
194 TransID is -1
195 ; stored_id(ID,SID) -> TransID=SID
196 ; add_message(dot_graph_generator,'Unknown node: ',ID),
197 gen_new_node_id(NewAtom),
198 assertz(stored_id(ID,NewAtom)),
199 assertz(additional_id(NewAtom,ID)),
200 TransID=NewAtom
201 ).
202
203 print_additional_nodes(FStream) :-
204 additional_id(DotAtom,OriginalID),
205 format(FStream,' ~w [label="~w"];~n',[DotAtom,OriginalID]),
206 fail.
207 print_additional_nodes(_).
208
209 /* ---------------------------------------------------------------------- */
210
211
212 fgen_dot_graph(FStream,GraphAttrs,NodePredicate,TransPredicate,SameRankPred,SubGraphPred) :-
213 (has_attribute(graph_name,GraphName,GraphAttrs) -> true ; GraphName = prob_graph),
214 print_graph_header(FStream,GraphName,GraphAttrs),
215 (node_id(NodePredicate,_) -> true
216 ; (format(user_error,"No nodes in gen_dot_graph: ~w, ~w, ~w, ~w.~n~n",
217 [NodePredicate,TransPredicate,SameRankPred,SubGraphPred]),fail)),
218 print_nodes(FStream,NodePredicate,SubGraphPred),
219 fail.
220 fgen_dot_graph(FStream,_GraphAttrs,_NodePredicate,_TransPredicate,SameRankPred,_SubGraphPred) :-
221 same_rank_call(SameRankPred,Nodes),
222 print_same_ranks(FStream,Nodes),
223 fail.
224 fgen_dot_graph(FStream,GraphAttrs,_NodePredicate,TransPredicate,_SameRankPred,_SubGraphPred) :-
225 print_transitions(FStream,_NodeID,GraphAttrs,TransPredicate),
226 fail.
227 fgen_dot_graph(FStream,GraphAttrs,_,_,_,_) :-
228 print_additional_nodes(FStream),
229 print_legend(FStream,GraphAttrs),
230 print_graph_footer(FStream).
231
232 /* ---------------------------------------------------------------------- */
233
234 print_graph_header(Type) :- print_graph_header(user_output,Type,[with_page_size]).
235 print_graph_header(FStream,Type,Opts) :-
236 (select(with_page_size,Opts,Opts1)
237 -> Opts2 = [page/'8.5, 11',ratio/fill,size/'7.5,10'|Opts1]
238 ; Opts2=Opts),
239 (select(directed/'FALSE',Opts2,Opts3)
240 -> GRAPH = 'graph'
241 ; Opts3=Opts2, GRAPH = 'digraph' % directed graph
242 ),
243 (select(strict/'TRUE',Opts3,Opts4) -> STRICT = 'strict '
244 ; Opts4=Opts3, STRICT = ''
245 ),
246 dot_graph_id(Type,GraphID),
247 format(FStream,'~w~w ~w {~n graph [',[STRICT,GRAPH,GraphID]),
248 % graph [AttrList] sets default attributes
249 print_dot_attrs(Opts4,FStream),
250 format(FStream,'];~n',[]),
251 retractall(defaults_given(_)),
252 print_default_attrs(node_defaults,node,Opts4,FStream),
253 print_default_attrs(edge_defaults,edge,Opts4,FStream).
254 % print('graph [orientation=landscape, page="8.5, 11",ratio=fill,size="7.5,10"];'),nl,
255
256 % print node [...] or edge [...] default attributes if provided as meta option
257 % when defaults are given, the font size and pen width preferences are printed once here
258 % rather than for every node/edge, so that the defaults can override them
259 :- dynamic defaults_given/1.
260 print_default_attrs(Option,Kind,Opts,FStream) :-
261 has_attribute(Option,Attrs0,Opts), Attrs0 \= [], !,
262 assertz(defaults_given(Kind)),
263 add_pref_default_attrs(Kind,Attrs0,Attrs),
264 format(FStream,' ~w [',[Kind]),
265 print_dot_attrs(Attrs,FStream),
266 format(FStream,'];~n',[]).
267 print_default_attrs(_,_,_,_).
268
269 add_pref_default_attrs(node,Attrs,Res) :- !,
270 get_preference(dot_node_font_size,FSize),
271 opt_add_attribute(fontsize,FSize,Attrs,Res).
272 add_pref_default_attrs(edge,Attrs,Res) :- !,
273 get_preference(dot_edge_font_size,FSize),
274 opt_add_attribute(fontsize,FSize,Attrs,Attrs1),
275 (get_preference(dot_edge_penwidth,PenSize),PenSize \= 1
276 -> opt_add_attribute(penwidth,PenSize,Attrs1,Res)
277 ; Res=Attrs1).
278 add_pref_default_attrs(_,Attrs,Attrs).
279
280 % quote graph names which are not simple dot identifiers
281 dot_graph_id(Name,ID) :- atom(Name), atom_codes(Name,[C|Cs]),
282 \+ (C >= 0'0, C =< 0'9),
283 \+ (member(X,[C|Cs]), \+ dot_id_code(X)), !,
284 ID = Name.
285 dot_graph_id(Name,ID) :- simple_dot_string_escape(Name,EName), ajoin(['"',EName,'"'],ID).
286
287 dot_id_code(C) :- C >= 0'a, C =< 0'z, !.
288 dot_id_code(C) :- C >= 0'A, C =< 0'Z, !.
289 dot_id_code(C) :- C >= 0'0, C =< 0'9, !.
290 dot_id_code(0'_).
291
292 print_graph_footer :- print_graph_footer(user_output).
293 print_graph_footer(FStream) :- format(FStream,'}~n',[]).
294
295 is_undirected_graph(GraphAttrs) :- member(directed/FALSE,GraphAttrs),!, FALSE='FALSE'.
296
297 /* ---------------------------------------------------------------------- */
298
299 :- use_module(probsrc(tools_strings),[ajoin/2]).
300 % get the dot name of a logical cluster, also relevant or lhead/ltail edge attributes
301 get_dot_cluster_name(SubGraphID,CN) :- ajoin(['cluster_',SubGraphID],CN).
302
303 % write dot nodes to a stream
304 print_nodes(FStream,NodePredicate,SubGraphPred) :-
305 subgraph_call(SubGraphPred,SubGraphID,Style,Color,Label,OtherAttrs),
306 get_dot_cluster_name(SubGraphID,CN),
307 format(FStream,' subgraph "~w" {~n',[CN]),
308 (Style = none -> true ; format(FStream,' style="~w";~n',[Style])),
309 (Color = none -> true ; format(FStream,' color="~w";~n',[Color])),
310 (Label = htmllabel(HtmlLabel) % HTML label, including the outer < >
311 -> format(FStream,' label=~w;~n',[HtmlLabel])
312 ; simple_dot_string_escape(Label,ESID), % simple escape of unescaped ", avoid disturbing records
313 format(FStream,' label="~w";~n',[ESID])),
314 write(FStream, ' '),
315 print_dot_attrs1(OtherAttrs,';\n ',';\n ',FStream),
316 print_nodes2(FStream,SubGraphID,NodePredicate),
317 write(FStream,'}'),nl(FStream),
318 fail.
319 print_nodes(FStream,NodePredicate,SubGraphPred) :-
320 (SubGraphPred = _:dot_no_subgraph
321 -> true % leave SubGraphID free to print all nodes
322 ; SubGraphID = none),
323 print_nodes2(FStream,SubGraphID,NodePredicate),
324 nl(FStream).
325
326 % If SubGraph can either be none or an ID generated by the subgraph_call
327 print_nodes2(FStream,SubGraph,NodePredicate) :-
328 node_predicate_call(NodePredicate,NodeID,SubGraph,Attrs),
329 print_node(FStream,NodeID,Attrs),
330 record_legend(node,Attrs),
331 fail.
332 print_nodes2(FStream,_Subgraph,_) :- nl(FStream).
333
334 % print an individual DOT node with attributes as list
335 print_node(FStream,NodeID,Attributes) :-
336 format(FStream,' ~w [',[NodeID]),
337 (defaults_given(node) -> Attrs2=Attributes % fontsize already in node defaults
338 ; get_preference(dot_node_font_size,FSize),
339 opt_add_attribute(fontsize,FSize,Attributes,Attrs2)),
340 print_dot_attrs(Attrs2,FStream),
341 format(FStream,'];~n',[]).
342
343 :- use_module(probsrc(tools),[simple_dot_string_escape/2]).
344 % print attributes of a node or edge or graph
345 print_dot_attrs(List,FStream) :- exclude(is_meta_attribute,List,List1),
346 print_dot_attrs1(List1,', ','',FStream).
347 print_dot_attrs1([],_,_,_FStream) :- !.
348 print_dot_attrs1([H|T],Sep,Term,FStream) :- get_attribute(H,Attr,Val),!,
349 (compound_attr(Val,EVal) -> true % we hope no " inside the compound term; for HTML labels ensure that text is escaped before
350 ; simple_dot_string_escape(Val,EVal) % simple escape of unescaped "
351 ),
352 (T=[] -> Last=Term ; Last=Sep),
353 (no_need_to_quote(Val)
354 -> format(FStream,'~w=~w~w',[Attr,EVal,Last])
355 ; format(FStream,'~w="~w"~w',[Attr,EVal,Last])),
356 (T=[] -> true ; print_dot_attrs1(T,Sep,Term,FStream)).
357 print_dot_attrs1(Err,Separator,Terminator,_) :-
358 add_internal_error('Could not print attr:',print_dot_attrs1(Err,Separator,Terminator)).
359
360 get_attribute(Attr/Val,Attr,Val).
361 get_attribute(Attr=Val,Attr,Val).
362
363 compound_attr(htmllabel(Val),Res) :- !, Res=Val. % don't escape " in HTML labels; we could check Attr=label
364 compound_attr(Val,Val) :- compound(Val).
365
366 no_need_to_quote(Val) :- number(Val).
367 no_need_to_quote(htmllabel(_Val)). % special case for HTML-like labels wrapped in < > instead of " "
368 no_need_to_quote(record). % mainly for test 1033
369
370 has_attribute(Name,Val,Attrs) :- member(H,Attrs), get_attribute(H,Name,Val).
371 select_attribute(Name,Val,Attrs,Rest) :- select(H,Attrs,Rest), get_attribute(H,Name,Val).
372
373 is_meta_attribute(H) :- get_attribute(H,Name,_),
374 meta_argument(Name). % attributed not meant for dot, just for controlling the dot graph generator
375
376 meta_argument(deals_with_pref).
377 meta_argument(merge_transitions).
378 meta_argument(graph_name).
379 meta_argument(node_defaults).
380 meta_argument(edge_defaults).
381 meta_argument(legend).
382 meta_argument(legend_order).
383 meta_argument(legend_title).
384 meta_argument(legend_rank).
385
386 opt_add_attribute(Name,_,Attrs,NewAttrs) :- has_attribute(Name,_,Attrs),!,
387 NewAttrs = Attrs.
388 opt_add_attribute(Name,Val,Attrs,[Name/Val|Attrs]).
389
390 % --------------------------
391
392
393 print_transitions(FStream,NodeID,GraphAttrs,TransPredicate) :-
394 (is_undirected_graph(GraphAttrs) -> DotArrow = '--' ; DotArrow = '->'),
395 trans_predicate_call(TransPredicate,GraphAttrs,NodeID,SuccID,Style,Attributes),
396
397 (NodeID=root -> preference(dot_print_root,true) ; true),
398
399 (NodeID \= SuccID -> true
400 ; preference(dot_print_self_loops,true) -> true
401 ; has_attribute(deals_with_pref,dot_print_self_loops,GraphAttrs) -> true % the command itself processes the pref.
402 ),
403
404 format(FStream,' ~w ~w ~w [',[NodeID,DotArrow,SuccID]),
405
406 (defaults_given(edge) -> Attrs2=Attributes % fontsize and penwidth already in edge defaults
407 ; (get_preference(dot_edge_penwidth,PenSize),PenSize \= 1
408 -> opt_add_attribute(penwidth,PenSize,Attributes,Attrs1)
409 ; Attrs1=Attributes
410 ),
411 get_preference(dot_edge_font_size,FSize),
412 opt_add_attribute(fontsize,FSize,Attrs1,Attrs2)
413 ),
414 (preference(dot_print_arc_colors,false),
415 select_attribute(color,_,Attrs2,Attrs3)
416 -> true % remove color attribute
417 ; Attrs3=Attrs2
418 ),
419 % acceptable styles Style ::= solid, bold, dotted, dashed, invis, arrowhead(none,Style), arrowtail(none,Style)
420 print_style(Style,FStream),
421
422 print_dot_attrs(Attrs3,FStream),
423 format(FStream,'];~n',[]), % Note: we may have a trailing comma; but dotty accepts it
424 (Style = solid -> LAttrs = Attrs3 ; LAttrs = [style/Style|Attrs3]),
425 record_legend(edge,LAttrs),
426 fail.
427 print_transitions(FStream,_NodeID,_,_) :- nl(FStream).
428
429 % style term from old-style transition predicates
430 print_style(solid,_) :- !.
431 print_style(arrowhead(AS,S),FStream) :- !, format(FStream,'arrowhead=~w,',[AS]), print_style(S,FStream).
432 print_style(arrowtail(AS,S),FStream) :- !, format(FStream,'dir=both,arrowtail=~w,',[AS]), print_style(S,FStream).
433 print_style(Style,FStream) :- format(FStream,'style="~w",',[Style]).
434
435 /* ---------------------------------------------------------------------- */
436 /* Generic legend: nodes/edges with a legend/Text meta attribute */
437 /* the first node/edge with a given Text determines how the entry is drawn */
438 /* ---------------------------------------------------------------------- */
439
440 :- dynamic legend_entry/4. % legend_entry(Order,Text,node/edge,Attrs)
441 reset_legend :- retractall(legend_entry(_,_,_,_)).
442
443 record_legend(Kind,Attrs) :-
444 has_attribute(legend,Text,Attrs),
445 \+ legend_entry(_,Text,_,_), !,
446 (has_attribute(legend_order,Order,Attrs) -> true ; default_legend_order(Kind,Order)),
447 assertz(legend_entry(Order,Text,Kind,Attrs)).
448 record_legend(_,_).
449
450 default_legend_order(node,100).
451 default_legend_order(edge,200).
452
453 :- use_module(probsrc(tools),[html_escape/2]).
454 print_legend(FStream,GraphAttrs) :-
455 findall(Order-entry(Text,Kind,Attrs),legend_entry(Order,Text,Kind,Attrs),Entries),
456 Entries \= [], !,
457 keysort(Entries,SortedEntries), % stable: entries with same order are kept in order of first occurrence
458 format(FStream,' dot_legend [shape=plain, style="", fontsize=10, label=<~n',[]),
459 legend_top_margin(Margin), % move the legend away from the top and the graph title
460 format(FStream,' <table border="0" cellborder="0" cellspacing="0" cellpadding="0"><tr><td height="~w"></td></tr><tr><td>~n',[Margin]),
461 format(FStream,' <table border="1" color="#BDBDBD" cellborder="0" cellspacing="2" cellpadding="3" style="rounded">~n',[]),
462 (has_attribute(legend_title,Title,GraphAttrs) -> true ; Title = 'Legend'),
463 (Title = '' -> true
464 ; html_escape(Title,ETitle),
465 format(FStream,' <tr><td colspan="2"><b>~w</b></td></tr>~n',[ETitle])),
466 (member(_-entry(Text,Kind,Attrs),SortedEntries),
467 print_legend_row(Kind,Text,Attrs,GraphAttrs,FStream),
468 fail
469 ; true),
470 format(FStream,' </table>~n </td></tr></table>>];~n',[]),
471 (has_attribute(legend_rank,Rank,GraphAttrs) -> true ; Rank = min),
472 (Rank = none -> true ; format(FStream,' { rank=~w; dot_legend; }~n',[Rank])).
473 print_legend(_,_).
474
475 % empty space (in points) above a legend; as the legend is centred on its rank, this is split between the
476 % gap above the legend and the shift of the legend downwards relative to the other nodes in the top rank
477 legend_top_margin(16).
478
479 print_legend_row(node,Text,Attrs,GraphAttrs,FStream) :-
480 (has_attribute(node_defaults,Defaults,GraphAttrs) -> true ; Defaults = []),
481 (legend_attr(color,Attrs,Defaults,C0) -> legend_colour(C0,Col), HasCol=true ; Col = black, HasCol=false),
482 (legend_attr(style,Attrs,Defaults,Style), atom(Style), sub_atom(Style,_,_,_,filled)
483 -> (legend_attr(fillcolor,Attrs,Defaults,F0) -> legend_colour(F0,BG)
484 ; HasCol=true -> BG = Col % dot uses the color as fill colour if there is no fillcolor
485 ; BG = lightgrey)
486 ; BG = white),
487 (legend_attr(penwidth,Attrs,Defaults,PW), number(PW), PW >= 1.75 -> Border = 2 ; Border = 1),
488 (legend_attr(style,Attrs,Defaults,Style2), atom(Style2), sub_atom(Style2,_,_,_,dashed) -> TDStyle=' style="dashed"'
489 ; legend_attr(style,Attrs,Defaults,Style2), atom(Style2), sub_atom(Style2,_,_,_,dotted) -> TDStyle=' style="dotted"'
490 ; TDStyle=''),
491 html_escape(Text,EText),
492 (legend_attr(peripheries,Attrs,Defaults,Per), number(Per), Per >= 2
493 -> format(FStream,' <tr><td><table border="~w" color="~w" bgcolor="white" cellborder="0" cellspacing="2" cellpadding="0"><tr><td bgcolor="~w" border="~w" color="~w" width="12" height="8"> </td></tr></table></td><td align="left">~w</td></tr>~n',
494 [Border,Col,BG,Border,Col,EText])
495 ; format(FStream,' <tr><td bgcolor="~w" color="~w" border="~w"~w width="20"> </td><td align="left">~w</td></tr>~n',
496 [BG,Col,Border,TDStyle,EText])
497 ).
498 print_legend_row(edge,Text,Attrs,GraphAttrs,FStream) :-
499 (has_attribute(edge_defaults,Defaults,GraphAttrs) -> true ; Defaults = []),
500 (legend_attr(color,Attrs,Defaults,C0) -> legend_colour(C0,Col) ; Col = black),
501 (legend_attr(style,Attrs,Defaults,Style0) -> true ; Style0 = solid),
502 (atom(Style0) -> Style=Style0 ; Style0 = arrowhead(_,Style), atom(Style) -> true ; Style = solid),
503 legend_edge_direction(Attrs,Defaults,GraphAttrs,Style0,Dir),
504 legend_edge_symbol(Dir,Style,Arrow),
505 html_escape(Text,EText),
506 format(FStream,' <tr><td><font color="~w" point-size="16"><b>~w</b></font></td><td align="left">~w</td></tr>~n',
507 [Col,Arrow,EText]).
508
509 % direction of an edge for drawing its legend symbol: forward, back or none
510 legend_edge_direction(_,_,GraphAttrs,_,none) :- has_attribute(directed,'FALSE',GraphAttrs), !.
511 legend_edge_direction(Attrs,Defaults,_,_,Dir) :- legend_attr(dir,Attrs,Defaults,D), !,
512 (D=both -> Dir=forward ; Dir=D).
513 legend_edge_direction(_,_,_,arrowhead(none,_),none) :- !.
514 legend_edge_direction(Attrs,Defaults,_,_,none) :- legend_attr(arrowhead,Attrs,Defaults,none), !.
515 legend_edge_direction(_,_,_,_,forward).
516
517 legend_edge_symbol(none,Style,Sym) :- !,
518 (sub_atom(Style,_,_,_,dashed) -> Sym = '– –'
519 ; sub_atom(Style,_,_,_,dotted) -> Sym = '⋯⋯'
520 ; Sym = '——').
521 legend_edge_symbol(back,Style,Sym) :- !,
522 (sub_atom(Style,_,_,_,dashed) -> Sym = '⇠'
523 ; sub_atom(Style,_,_,_,dotted) -> Sym = '←⋯'
524 ; Sym = '←').
525 legend_edge_symbol(_,Style,Sym) :-
526 (sub_atom(Style,_,_,_,dashed) -> Sym = '⇢'
527 ; sub_atom(Style,_,_,_,dotted) -> Sym = '⋯→'
528 ; Sym = '→').
529
530 legend_attr(Name,Attrs,Defaults,Val) :-
531 (has_attribute(Name,V,Attrs) -> Val = V ; has_attribute(Name,Val,Defaults)).
532
533 % use the first colour of a colour list or gradient (e.g., "red:blue" or "red;0.3:blue")
534 legend_colour(Colour,Res) :- atom(Colour),
535 atom_codes(Colour,Codes),
536 append(First,[Sep|_],Codes), member(Sep,":;"), !,
537 atom_codes(C1,First), html_escape(C1,Res).
538 legend_colour(Colour,Res) :- html_escape(Colour,Res).
539
540
541 print_same_ranks(_,[]) :- !,
542 add_message(dot_graph_generator,'Empty same rank result','').
543 print_same_ranks(_,[ID]) :- !,
544 add_message(dot_graph_generator,'Singleton same rank result: ',ID).
545 print_same_ranks(FStream,L) :-
546 write(FStream,' { rank=same; '),
547 print_same_ranks2(FStream,L),
548 write(FStream,' }'),nl(FStream).
549
550 print_same_ranks2(_FStream,[]).
551 print_same_ranks2(FStream,[H|T]) :-
552 write(FStream,H), write(FStream,'; '),
553 print_same_ranks2(FStream,T).
554
555
556 % utilities for converting values into colours:
557
558
559
560 translate_bvalue_to_colour(Val,Col) :-
561 (try_translate_bvalue_to_colour(Val,C) -> Col=C; Col=lightgray).
562
563 try_translate_bvalue_to_colour(int(X),Res) :- !, (translate_int_col(X,Colour) -> Res=Colour ; Res=black).
564 try_translate_bvalue_to_colour(string(X),Colour) :- is_of_type(X,rgb_color),!, X=Colour.
565 try_translate_bvalue_to_colour(fd(X,GS),Colour) :- !, translate_fd_col(X,GS,Colour).
566 try_translate_bvalue_to_colour(pred_true,Colour) :- !, Colour=olivedrab2.
567 try_translate_bvalue_to_colour(pred_false,Colour) :- !, Colour=tomato.
568 try_translate_bvalue_to_colour((A,_),Colour) :- !, try_translate_bvalue_to_colour(A,Colour).
569
570 % TO DO : add string conversions, rgb values , ...
571 :- use_module(probsrc(b_global_sets),[is_b_global_constant_hash/3]).
572
573 translate_fd_col(X,GS,Res) :-
574 is_b_global_constant_hash(GS,X,Colour),
575 is_of_type(Colour,rgb_color),!,
576 Res=Colour.
577 translate_fd_col(X,_,Res) :- number(X), translate_int_col(X,Colour),!, Res=Colour.
578 translate_fd_col(_,_,lightgray).
579
580 translate_int_col(-1,Colour) :- !,Colour=tomato. % special case
581 translate_int_col(Int,Colour) :-
582 Y is abs(Int) mod 15, translate_int_col_aux(Y,Colour).
583 translate_int_col_aux(0,gray95).
584 translate_int_col_aux(1,blue).
585 translate_int_col_aux(2,red).
586 translate_int_col_aux(3,green).
587 translate_int_col_aux(4,lightgray).
588 translate_int_col_aux(5,orange).
589 translate_int_col_aux(6,yellow).
590 translate_int_col_aux(7,brown).
591 translate_int_col_aux(8,violet).
592 translate_int_col_aux(9,tomato).
593 translate_int_col_aux(10,darkslateblue).
594 translate_int_col_aux(11,maroon2).
595 translate_int_col_aux(12,olivedrab2).
596 translate_int_col_aux(13,chartreuse3).
597 translate_int_col_aux(14,grey20).
598 % red,green,blue,yellow,orange,black,white,gray,brown,violet,darkred,tomato,darkblue,
599 % 'DarkGray',darkviolet,darkslateblue,lightblue,lightgray,maroon2,olivedrab2,
600 % steelblue,chartreuse3,chartreuse4
601
602
603 % from a list of fields construct a record { A | .... | D} of horizontally laid out fields
604 list_to_dot_record(Fields,RecordString) :-
605 Fields = [F1|TF],
606 insert_sep(TF,Tail),
607 ajoin(['{',F1|Tail],RecordString).
608 insert_sep([],['}']).
609 insert_sep([none|T],Res) :- !, insert_sep(T,Res).
610 insert_sep([H|T],['|',H|RT]) :- insert_sep(T,RT).