Graph/Utils.pm

filter: Statementstmt 91.3% 21 / 23 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 8 / 8 Podpod n/a totaltotal 93.5% 29 / 31 CC 1 SCAR 0.4
CC
1
Cov
91%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« Graph.pm ↑ Summary
1 package Map::Tube::Plugin::Graph::Utils;
2  
3 2 ▶use version;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 our $VERSION = qv('v1.3.0');
6 our $AUTHORITY = 'cpan:MANWAR';
7  
8 =head1 NAME
9  
10 Map::Tube::Plugin::Graph::Utils - Helper package for Map::Tube::Plugin::Graph.
11  
12 =head1 VERSION
13  
14 Version v1.3.0
15  
16 =cut
17  
18 2 ▶use 5.014;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 2 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
22 # use Data::Dumper;
23 2 ▶use Encode qw(encode);
Subroutine BEGIN: called CC=1 SCAR=0.0
24 2 ▶use File::Which;
Subroutine BEGIN: called CC=1 SCAR=0.0
25 0 ▶use GraphViz2;
Subroutine BEGIN: called CC=1 SCAR=2.6
26 use IPC::Run3;
27 use Map::Tube::Utils qw(is_valid_color);
28 use Map::Tube::Exception::MissingLineName;
29 use Map::Tube::Exception::InvalidLineName;
30 use Map::Tube::Exception::InvalidColorName;
31 use Map::Tube::Exception::InvalidColorHexCode;
32 use parent 'Exporter';
33 use Path::Tiny;
34  
35 our @EXPORT_OK = qw(graph_line_image graph_map_image get_graphviz_supported);
36  
37 our $STYLE = 'dashed';
38 our $NODE_COLOR = 'black';
39 our $EDGE_COLOR = 'brown';
40 our $SHAPE = 'oval';
41 our $DIRECTED = 1;
42 our $ARROWSIZE = 1;
43 our $LABELLOC = 'top';
44 our $BGCOLOR = 'grey';
45  
46 =head1 DESCRIPTION
47  
48 B<FOR INTERNAL USE ONLY>
49  
50 =cut
51  
52 sub graph_line_image {
53 my ($map, $line_name, %args) = @_;
54 $args{format} ||= 'png';
55 $args{format} = lc($args{format});
56 if ( exists $args{output_file} && !defined $args{output_file} ) {
57 $args{output_file} = $map->name() . '_' . $line_name . '.' . $args{format};
58 }
59 $args{output_file} = _clean_path($args{output_file}) if defined($args{output_file});
60  
61 my @caller = caller(0);
62 @caller = caller(2) if $caller[3] eq '(eval)';
63  
64 Map::Tube::Exception::MissingLineName->throw({
65 method => __PACKAGE__."::graph_line_image",
66 message => "ERROR: Missing Line name.",
67 filename => $caller[1],
68 line_number => $caller[2] })
69 unless defined $line_name;
70  
71 my $line = $map->_get_line_object_by_name($line_name);
72 Map::Tube::Exception::InvalidLineName->throw({
73 method => __PACKAGE__."::_validate_param",
74 message => "ERROR: Invalid Line name [$line_name].",
75 filename => $caller[1],
76 line_number => $caller[2] })
77 unless defined $line;
78  
79 my $color = $EDGE_COLOR;
80 $color = $line->color if defined $line->color;
81 $line_name = $line->name;
82 my $bgcolor = $map->bgcolor;
83 $bgcolor = _graph_bgcolor($color) unless defined $bgcolor;
84 my $overlap = exists $args{overlap} ? !!$args{overlap} : 0;
85  
86 my $g = $map->as_graph;
87 $g->set_graph_attribute(graphviz => {
88 edge => { color => $color,
89 arrowsize => $ARROWSIZE },
90 node => { shape => $SHAPE },
91 graph => { label => _graph_line_label($line_name, $map->name),
92 labelloc => $LABELLOC,
93 bgcolor => $bgcolor,
94 overlap => $overlap,
95 }
96 });
97 my $skip = $map->{skip};
98 $g->filter_edges(sub { !exists $skip->{$_[3]}{$_[1]}{$_[2]} }) if defined $skip;
99 my @line_v = $g->copy->filter_edges(sub { $_[3] eq $line_name})
100 ->filter_vertices(sub { !$_[0]->is_isolated_vertex($_[1]) })->vertices;
101 my %line = map +($_=>undef), @line_v;
102 my %neighbour;
103 @neighbour{ map { $g->successors($_) } @line_v } = ();
104 delete @neighbour{ @line_v };
105 $g->filter_vertices(sub { exists $line{$_[1]} || exists $neighbour{$_[1]} });
106 for my $v(@line_v) {
107 my $attrs = $g->get_vertex_attributes($v) // { };
108 $attrs->{graphviz}{color} = $attrs->{graphviz}{fontcolor} = $color;
109 $g->set_vertex_attribute($v, graphviz=>$attrs->{graphviz});
110 }
111 my %seen;
112 $g->filter_edges(sub {
113 return 0 if exists $neighbour{$_[1]}; # zap if from is neighbour
114 return 0 if exists $line{$_[1]} and exists $line{$_[2]} and $_[3] ne $line_name;
115 return 0 if $_[3] ne $line_name and $seen{$_[1]}{$_[2]}++;
116 $g->set_edge_attribute_by_id(@_[1..3], graphviz=>{style => $STYLE})
117 if $_[3] ne $line_name;
118 1; # keep
119 });
120 my $gvgraph = GraphViz2->from_graph($g);
121 my $output;
122 if ( lc($args{format}) eq 'gv' ) {
123 if ( exists($args{output_file}) ) {
124 open( my $outf, '>', $args{output_file} ) or croak "Cannot write output file '$args{output_file}': $!";
125 print $outf $gvgraph->dot_input();
126 close($outf);
127 }
128 $output = $gvgraph->dot_input();
129 } else {
130 $output = $gvgraph->run(%args)->dot_output();
131 }
132 return ( $output, $args{output_file} );
133 }
134  
135 sub graph_map_image {
136 my ($map, %args) = @_;
137 $args{format} ||= 'png';
138 $args{format} = lc($args{format});
139 if ( exists $args{output_file} && !defined $args{output_file} ) {
140 $args{output_file} = $map->name() . '.' . $args{format};
141 }
142 $args{output_file} = _clean_path($args{output_file}) if defined($args{output_file});
143  
144 my $bgcolor = $map->bgcolor;
145 $bgcolor = $BGCOLOR unless defined $bgcolor;
146 my $overlap = exists $args{overlap} ? !!$args{overlap} : 0;
147  
148 my $g = $map->as_graph;
149 $g->set_graph_attribute(graphviz => {
150 node => { shape => $SHAPE, color => $NODE_COLOR, fontcolor => $NODE_COLOR },
151 edge => { arrowsize => $ARROWSIZE },
152 graph => { label => _graph_map_label($map->name),
153 labelloc => $LABELLOC,
154 bgcolor => $bgcolor,
155 overlap => $overlap,
156 },
157 global => { name => 'Map_Tube', },
158 });
159 my $l2c = $g->get_graph_attribute('line2colour');
160 for my $v ($g->vertices) {
161 my %lines; @lines{map $g->get_multiedge_ids(@$_), $g->edges_at($v)} = ();
162 next if keys %lines != 1;
163 my $l = (keys %lines)[0];
164 next unless defined (my $color = $l2c->{$l});
165 my $attrs = $g->get_vertex_attributes($v);
166 $attrs->{graphviz}{color} = $attrs->{graphviz}{fontcolor} = $color;
167 $g->set_vertex_attribute($v, graphviz=>$attrs->{graphviz});
168 }
169 my %seen;
170 $g->filter_edges(sub { !$seen{$_[1]}{$_[2]}++ });
171 my $gvgraph = GraphViz2->from_graph($g);
172 my $output;
173 if ( lc($args{format}) eq 'gv' ) {
174 if ( exists($args{output_file}) ) {
175 open( my $outf, '>', $args{output_file} ) or croak "Cannot write output file '$args{output_file}': $!";
176 print $outf $gvgraph->dot_input();
177 close($outf);
178 }
179 $output = $gvgraph->dot_input();
180 } else {
181 $output = $gvgraph->run(%args)->dot_output();
182 }
183 return ( $output, $args{output_file} );
184 }
185  
186 sub get_graphviz_supported {
187 my ($what) = @_;
188 my $dot_bin = which('dot');
189 return unless $dot_bin;
190 my $dot_out;
191 run3( [ $dot_bin, $what ], \undef, \undef, \$dot_out );
192 return unless $dot_out =~ /Use one of:/s;
193 $dot_out =~ s/.*Use one of:\s*//s;
194 return split( /\s+/, $dot_out );
195 }
196  
197 #
198 #
199 # PRIVATE METHODS
200  
201 sub _graph_line_label {
202 my ($line_name, $map_name) = @_;
203  
204 $map_name = '' unless defined $map_name;
205 return sprintf("%s Map: %s Line (Generated by Map::Tube::Plugin::Graph %s at %s)",
206 $map_name, $line_name, $Map::Tube::Plugin::Graph::VERSION, _graph_timestamp());
207 }
208  
209 sub _graph_map_label {
210 my ($map_name) = @_;
211  
212 $map_name = '' unless defined $map_name;
213 return sprintf("%s Map (Generated by Map::Tube::Plugin::Graph %s at %s)",
214 $map_name, $Map::Tube::Plugin::Graph::VERSION, _graph_timestamp());
215 }
216  
217 sub _graph_timestamp {
218 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime(time);
219 return sprintf("%04d-%02d-%02d %02d:%02d:%02d", $year+1900, $mon+1, $mday, $hour, $min, $sec);
220 }
221  
222 # TODO: Unfinished work, still not getting the right combination.
223 sub _graph_bgcolor {
224 my ($color) = @_;
225  
226 unless ($color =~ /^#(..)(..)(..)$/) {
227 my $hexcode = Map::Tube::Utils::is_valid_color($color);
228 unless ($hexcode) {
229 my @caller = caller(0);
230 @caller = caller(2) if $caller[3] eq '(eval)';
231  
232 Map::Tube::Exception::InvalidColorName->throw({
233 method => __PACKAGE__."::_graph_bgcolor",
234 message => "ERROR: Invalid Color Name [$color].",
235 filename => $caller[1],
236 line_number => $caller[2] });
237 }
238  
239 $color = $hexcode;
240 }
241  
242 return _graph_contrast_color($color);
243 }
244  
245 # Code borrowed from http://www.perlmonks.org/?node_id=261561 provided by msemtd.
246 sub _graph_contrast_color {
247 my ($color) = @_;
248  
249 my @caller = caller(0);
250 @caller = caller(2) if $caller[3] eq '(eval)';
251  
252 Map::Tube::Exception::InvalidColorHexCode->throw({
253 method => __PACKAGE__."::graph_line_image",
254 message => "ERROR: Invalid color hex code.",
255 filename => $caller[1],
256 line_number => $caller[2] })
257 unless ($color =~ /^#(..)(..)(..)$/);
258  
259 my ($r, $g, $b) = (hex($1), hex($2), hex($3));
260 my %oppcolors = (
261 "00" => "FF",
262 "33" => "FF",
263 "66" => "FF",
264 "99" => "FF",
265 "CC" => "00",
266 "FF" => "00",
267 );
268  
269 $r = int($r / 51) * 51;
270 $g = int($g / 51) * 51;
271 $b = int($b / 51) * 51;
272  
273 $r = $oppcolors{sprintf("%02X", $r)};
274 $g = $oppcolors{sprintf("%02X", $g)};
275 $b = $oppcolors{sprintf("%02X", $b)};
276  
277 return "#$r$g$b";
278 }
279  
280 sub _clean_path {
281 my ($tainted_path) = @_;
282  
283 # Force string value (in case of malicious use of dualvars):
284 $tainted_path = "$tainted_path";
285  
286 # Basic file name cleaning; printable characters only
287 $tainted_path =~ /^([[:print:]]+)$/
288 or croak "Non-printable characters detected in file name";
289 my $clean_path = $1;
290  
291 # Exclude redirection characters ( < | > ) from path
292 $clean_path =~ s/[<>\|]//g;
293  
294 # Reduce to basename (no paths allowed):
295 # This ensures the user cannot use "../../" to escape the current directory
296 $clean_path = path($clean_path)->basename;
297 $clean_path = encode( 'UTF-8', $clean_path );
298 $clean_path =~ s/[^\w.]+/_/g;
299  
300 # Confirm it's a regular file, if it already exists:
301 # We check here so the error message contains the simple name, not the absolute path.
302 if (path($clean_path)->exists && !-f $clean_path) {
303 croak "File exists but is not a regular file: $clean_path";
304 }
305  
306 # Canonicalize path (Now safe to make absolute for internal use):
307 # $clean_path = path($clean_path)->realpath;
308  
309 return $clean_path;
310 }
311  
312 =head1 AUTHOR
313  
314 Mohammad Sajid Anwar, C<< <mohammad.anwar at yahoo.com> >>
315  
316 =head1 CONTRIBUTORS
317  
318 =over 2
319  
320 =item * Gisbert W. Selke
321  
322 =item * Ed J
323  
324 =back
325  
326 =head1 REPOSITORY
327  
328 L<https://github.com/manwar/Map-Tube-Plugin-Graph>
329  
330 =head1 BUGS
331  
332 Please report any bugs or feature requests through the web interface at L<https://github.com/manwar/Map-Tube-Plugin-Graph/issues>.
333 I will be notified and then you'll automatically be notified of progress on your
334 bug as I make changes.
335  
336 =head1 SUPPORT
337  
338 You can find documentation for this module with the perldoc command.
339  
340 perldoc Map::Tube::Plugin::Graph::Utils
341  
342 You can also look for information at:
343  
344 =over 4
345  
346 =item * BUG Report
347  
348 L<https://github.com/manwar/Map-Tube-Plugin-Graph/issues>
349  
350 =item * Search MetaCPAN
351  
352 L<https://metacpan.org/dist/Map-Tube-Plugin-Graph>
353  
354 =back
355  
356 =head1 LICENSE AND COPYRIGHT
357  
358 Copyright (C) 2015 - 2026 Mohammad S Anwar.
359  
360 This program is free software; you can redistribute it and/or modify it under
361 the terms of the the Artistic License (2.0). You may obtain a copy of the full
362 license at:
363  
364 L<http://www.perlfoundation.org/artistic_license_2_0>
365  
366 Any use, modification, and distribution of the Standard or Modified Versions is
367 governed by this Artistic License.By using, modifying or distributing the Package,
368 you accept this license. Do not use, modify, or distribute the Package, if you do
369 not accept this license.
370  
371 If your Modified Version has been derived from a Modified Version made by someone
372 other than you,you are nevertheless required to ensure that your Modified Version
373 complies with the requirements of this license.
374  
375 This license does not grant you the right to use any trademark, service mark,
376 tradename, or logo of the Copyright Holder.
377  
378 This license includes the non-exclusive, worldwide, free-of-charge patent license
379 to make, have made, use, offer to sell, sell, import and otherwise transfer the
380 Package with respect to any patent claims licensable by the Copyright Holder that
381 are necessarily infringed by the Package. If you institute patent litigation
382 (including a cross-claim or counterclaim) against any party alleging that the
383 Package constitutes direct or contributory patent infringement,then this Artistic
384 License to you shall terminate on the date that such litigation is filed.
385  
386 Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND
387 CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED
388 WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
389 NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS
390 REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT,
391 INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE
392 OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
393  
394 =cut
395  
396 1; # End of Map::Tube::Plugin::Graph::Utils
« Graph.pm ↑ Summary