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