Class: RSyntaxTree::SVGGraph
- Defined in:
- lib/rsyntaxtree/svg_graph.rb
Constant Summary collapse
- REGION_DEFAULT_COLOR =
Default color for a region shade drawn with bare '%' (no color spec). An explicit '%@color:' is always honored, even in color-off mode, to stay consistent with how the @color: node-text color behaves.
"#888888"- REGION_FILL_OPACITY =
Fill opacity for region shades; low enough that nested/overlapping shades stack naturally without obscuring the tree underneath.
0.2- REGION_STROKE_OPACITY =
The border reuses the fill color but at a higher opacity, so it reads as a darker shade of the same color — keeping the region clearly bounded on a white page without a per-color "darker shade" lookup.
0.55- SHEAR_PLANE_FILL_OPACITY =
The plane a sheared figure lies on. Lighter than a region shade: a region marks part of a figure out from the rest, and the plane is behind all of it — at the region's own opacity the whole page darkens.
0.12
Constants inherited from BaseGraph
BaseGraph::LINK_ARROW_CLEARANCE, BaseGraph::TIDY_BASE_SPACING, BaseGraph::TIDY_CONVERGENCE, BaseGraph::TIDY_EXTRA_CAP, BaseGraph::TIDY_HEIGHT_BUDGET, BaseGraph::TIDY_LEVEL_BALANCE, BaseGraph::TIDY_MAX_ITERATIONS
Instance Attribute Summary collapse
-
#height ⇒ Object
Returns the value of attribute height.
-
#width ⇒ Object
Returns the value of attribute width.
Instance Method Summary collapse
-
#along(from, to, distance) ⇒ Object
A point the given distance from
fromalong the line towardsto. -
#bothways_arrows(x1, y1, x2, y2, col, swidth) ⇒ Object
Two arrowheads back to back at the midpoint of a link, drawn as filled triangles sized to the link itself.
-
#collect_region_shades ⇒ Object
Collect a background rectangle for every element flagged with '%'.
- #connector_edges(child, parent) ⇒ Object
- #draw_a_path(s_x, s_y, t_x, t_y, target_arrow = :none) ⇒ Object
- #draw_bracket(x1, y1, width, height, col, bline = false) ⇒ Object
- #draw_element(element) ⇒ Object
- #draw_paths ⇒ Object
- #draw_rectangle(x1, y1, width, height, col, bline = false) ⇒ Object
-
#draw_rule_name(parent, right, y) ⇒ Object
The name of the rule, set beside the end of its own line and smaller than the categories, which is where a derivation puts it and how it keeps the name from reading as part of either row.
-
#element_visual_box(el) ⇒ Object
Visual bounding box of a single element as actually drawn: the label / enclosure box (which starts hctt*3/4 below vertical_indent, i.e. below the connector gap) widened to include any enclosure bracket/rectangle that is painted beyond the content width.
- #generate_connectors(x1, y1, x2, y2, col, dashed = false, s_arrow = false, t_arrow = false, bline = false) ⇒ Object
- #generate_line(x1, y1, x2, y2, col, dashed = false, arrow = false, bline = false) ⇒ Object
-
#generate_path(points, col, dashed: false, radius: 0, start_arrow: false, end_arrow: false) ⇒ Object
One stroke rather than three lines meeting at right angles.
-
#initialize(element_list, params, global) ⇒ SVGGraph
constructor
A new instance of SVGGraph.
-
#ink_over(element) ⇒ Object
Where a connector clears an element on the vmargin geometry: the row's ink for a plain label, the drawn edge for an enclosed one.
- #ink_under(element) ⇒ Object
- #line_to_parent(parent, child) ⇒ Object
-
#note_path_extent(points) ⇒ Object
Where the movement paths have been, as a box.
-
#region_subtree_bounds(id) ⇒ Object
Union of element_visual_box over the subtree rooted at
id, in final drawing coordinates. -
#render_matrix(e, this_x, text_y, element, col) ⇒ Object
Draws a matrix nested in a label: its own rows and columns, laid out from the sizes Element#measure_lines worked out, inside its own brackets.
-
#render_run(e, this_x, text_y, element, col) ⇒ Object
Draws one run of a label — a stretch of text with its decorations, or the box, circle or bar drawn around it — at the given pen position, and reports where the pen ends up.
-
#rounded_polyline_d(points, radius) ⇒ Object
The
dof a polyline whose corners are eased into quarter turns. -
#row_ink ⇒ Object
Where a connector meets each box in a vertical layout: the underside of whichever sits higher and the top of whichever sits lower.
-
#rule_to_parent(parent, children) ⇒ Object
Draw a line between child/parent elements.
- #set_tspan(this_x, this_y, style, decoration, fontstyle, text) ⇒ Object
- #svg_data ⇒ Object
-
#triangle_to_parent(parent, child) ⇒ Object
Draw a triangle between child/parent elements.
Methods inherited from BaseGraph
#ancestor_ids, #calculate_height, #calculate_indent, #calculate_level, #calculate_width, #child_spread, #connector_height_for, #contour_clearance, #derivation_row_extent, #derivation_rule_band, #draw_connector, #draw_elements, #effective_rect, #finalize_ltr, #flip_vertical, #get_leftmost, #get_rightmost, #layout_overlaps?, #layout_snapshot, #level_connector_heights, #level_derivation_rows, #link_connection_pairs, #make_balance, #middle_child_alignment, #mirror_layout, #node_centering, #normalize_horizontal, #parse_list, #prepare_ltr, #restore_layout, #restore_middle_child_alignment, #rule_name_room, #shift_subtree, #spread_linked_pairs, #subtree_height, #subtree_leaf_center_span, #subtree_leaf_span, #subtree_rects, #subtree_right, #tidy_compress, #tidy_gap, #triangle_asked_for?
Constructor Details
#initialize(element_list, params, global) ⇒ SVGGraph
Returns a new instance of SVGGraph.
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
# File 'lib/rsyntaxtree/svg_graph.rb', line 34 def initialize(element_list, params, global) super(element_list, params, global) @height = 0 @width = 0 @extra_lines = [] @region_shades = [] @fontset = params[:fontset] @fontsize = params[:fontsize] @linewidth = params[:linewidth] @transparent = params[:transparent] == true @color = params[:color] @fontstyle = params[:fontstyle] @polyline = params[:polyline] == true @direction = params[:direction] || "ttb" # The angle arrives in degrees, positive leaning the top to the right. # What the transform wants is the x-shift per unit of y, and y grows # downward here, so the tangent changes sign on the way in. @shear_deg = (params[:shear] || 0).to_f @shear_k = (-Math.tan(@shear_deg * Math::PI / 180)).round(3) @shear_plane = params[:shear_plane] || "on" @line_styles = "<line style='fill: none; stroke:#{@col_line}; stroke-width:#{@global[:stroke_normal]}; stroke-linejoin:round; stroke-linecap:round;' x1='X1' y1='Y1' x2='X2' y2='Y2' />\n" @polyline_styles = "<polyline style='stroke:#{@col_line}; stroke-width:#{@global[:stroke_normal]}; fill:none; stroke-linejoin:round; stroke-linecap:round;' points='CHIX CHIY MIDX1 MIDY1 MIDX2 MIDY2 PARX PARY' />\n" @polygon_styles = "<polygon style='fill: none; stroke: #{@col_connector}; stroke-width:#{@global[:stroke_normal]}; stroke-linejoin:round;stroke-linecap:round;' points='X1 Y1 X2 Y2 X3 Y3' />\n" @text_styles = "<text white-space='pre' alignment-baseline='text-top' style='fill: COLOR; stroke-width: 0; font-size: fontsize' x='X_VALUE' y='Y_VALUE'>CONTENT</text>\n" @tree_data = String.new @visited_x = {} @visited_y = {} @global = global end |
Instance Attribute Details
#height ⇒ Object
Returns the value of attribute height.
32 33 34 |
# File 'lib/rsyntaxtree/svg_graph.rb', line 32 def height @height end |
#width ⇒ Object
Returns the value of attribute width.
32 33 34 |
# File 'lib/rsyntaxtree/svg_graph.rb', line 32 def width @width end |
Instance Method Details
#along(from, to, distance) ⇒ Object
A point the given distance from from along the line towards to.
346 347 348 349 350 351 352 353 |
# File 'lib/rsyntaxtree/svg_graph.rb', line 346 def along(from, to, distance) dx = to[0] - from[0] dy = to[1] - from[1] length = Math.sqrt((dx * dx) + (dy * dy)) return from.dup if length.zero? [from[0] + (dx / length * distance), from[1] + (dy / length * distance)] end |
#bothways_arrows(x1, y1, x2, y2, col, swidth) ⇒ Object
Two arrowheads back to back at the midpoint of a link, drawn as filled triangles sized to the link itself. The arrowBothways marker this replaces was one fixed size — three inter-node gaps wide — so on a short link between narrow-spaced boxes it spilled over both of them.
1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 |
# File 'lib/rsyntaxtree/svg_graph.rb', line 1052 def bothways_arrows(x1, y1, x2, y2, col, swidth) len = Math.hypot(x2 - x1, y2 - y1) return "" if len.zero? ux = (x2 - x1) / len uy = (y2 - y1) / len mx = (x1 + x2) / 2 my = (y1 + y2) / 2 # Same proportions the marker had — three inter-node gaps end to end, # one deep, two heads with a shaft's worth of daylight between them — # so a link long enough to hold it looks as it always did. What is new # is that a shorter link gets the same shape at a smaller size instead # of the one fixed size spilling over the boxes on either side. span = [@global[:h_gap_between_nodes] * 3, len * 0.8].min head = span / 3.0 half = head / 2.0 arrow = lambda do |dir| tip_x = mx + ux * (span / 2.0) * dir tip_y = my + uy * (span / 2.0) * dir base_x = mx + ux * half * dir base_y = my + uy * half * dir "<polygon points='#{tip_x},#{tip_y} " \ "#{base_x - uy * half},#{base_y + ux * half} " \ "#{base_x + uy * half},#{base_y - ux * half}' " \ "style='fill:#{col}; stroke:none;' />" end arrow.call(1) + "\n" + arrow.call(-1) end |
#collect_region_shades ⇒ Object
Collect a background rectangle for every element flagged with '%'. Outer (shallower) regions are emitted first so deeper ones layer on top; with low opacity the overlap reads as a darker nesting.
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 |
# File 'lib/rsyntaxtree/svg_graph.rb', line 235 def collect_region_shades hctt = @global[:height_connector_to_text] pad = @global[:h_gap_between_nodes] # generous padding for the non-parent-facing edges pad_parent = hctt / 2.0 # tighter margin on the parent-facing edge of the root radius = hctt / 2.0 stroke_width = @global[:stroke_normal] half = stroke_width / 2.0 @element_list.get_elements.each do |element| next unless element.region b = region_subtree_bounds(element.id) left = b[:left] - pad right = b[:right] + pad top = b[:top] - pad bottom = b[:bottom] + pad # The edge facing the parent is handled specially so the incoming # connector neither overlaps nor touches the plane. That edge is the # TOP in top-to-bottom layout and the LEFT in left-to-right layout; the # other edges keep the generous padding. For a non-root node the edge # is placed midway between the connector anchor and the content edge # (even gap on both sides); the tree root has no incoming connector, so # it just gets a tighter-but-consistent margin there. is_root = element.parent.zero? if @direction == "ltr" anchor = element.horizontal_indent - hctt left = if is_root b[:left] - pad_parent elsif anchor < b[:left] (b[:left] + anchor) / 2.0 else left end else anchor = element.vertical_indent + hctt / 2.0 top = if is_root b[:top] - pad_parent elsif anchor < b[:top] (b[:top] + anchor) / 2.0 else top end end x = left y = top w = right - left h = bottom - top # An explicit shade color is always honored (consistent with the # @color: node-text color); bare '%' falls back to gray. color = element.region_color || REGION_DEFAULT_COLOR @region_shades << "<rect x='#{x}' y='#{y}' width='#{w}' height='#{h}' rx='#{radius}' ry='#{radius}' " \ "fill='#{color}' fill-opacity='#{REGION_FILL_OPACITY}' " \ "stroke='#{color}' stroke-opacity='#{REGION_STROKE_OPACITY}' stroke-width='#{stroke_width}' />\n" # Track the union of region extents (the stroke straddles the edge, so # it reaches half a stroke-width outside the rect) for canvas growth. rb = (@region_bounds ||= { min_x: x - half, min_y: y - half, max_x: x + w + half, max_y: y + h + half }) rb[:min_x] = x - half if x - half < rb[:min_x] rb[:min_y] = y - half if y - half < rb[:min_y] rb[:max_x] = x + w + half if x + w + half > rb[:max_x] rb[:max_y] = y + h + half if y + h + half > rb[:max_y] end end |
#connector_edges(child, parent) ⇒ Object
1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 |
# File 'lib/rsyntaxtree/svg_graph.rb', line 1207 def connector_edges(child, parent) hctt = @global[:height_connector_to_text] child_above = child.vertical_indent <= parent.vertical_indent # Each endpoint decides for itself. A line through a chain of invisible # joints keeps one real label at most, and when the pair had to agree # on a geometry, the segments beside a joint fell back to the box # measure while their neighbours took the ink one — a row of leaves # under example 080's joints ended thirteen units apart. # # An element whose ink went unrecorded falls back to the measure the # boxes gave. Nothing reaches that now — every drawn label records its # ink — and it is kept as the answer for a label that somehow has none # rather than as a second geometry anyone can ask for. m = @global[:single_x_metrics].height * @global[:vmargin] child_y = if child.empty_label? child.vertical_indent + child.content_height / 2 elsif child_above if m && child.ink_bottom ink_under(child) + m else child.vertical_indent + child.content_height + hctt end elsif m && child.ink_top ink_over(child) - m else child.vertical_indent + hctt / 2 end parent_y = if parent.empty_label? parent.vertical_indent + parent.content_height / 2 elsif child_above if m && parent.ink_top ink_over(parent) - m else parent.vertical_indent + hctt / 2 end elsif m && parent.ink_bottom ink_under(parent) + m else parent.vertical_indent + parent.content_height + hctt end # A tight pitch can put the two endpoints past each other — the gap # between the inks smaller than the clearance on both sides — and a # crossed pair draws the stroke back up through a label. Both then # settle at the middle of the gap, which is the one point that is # clear of the ink on either side whenever the gap exists at all. if m upper_pt, lower_pt = child_above ? [child_y, parent_y] : [parent_y, child_y] if upper_pt > lower_pt mid = (upper_pt + lower_pt) / 2.0 child_y = mid parent_y = mid end end [child_y, parent_y] end |
#draw_a_path(s_x, s_y, t_x, t_y, target_arrow = :none) ⇒ Object
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 |
# File 'lib/rsyntaxtree/svg_graph.rb', line 430 def draw_a_path(s_x, s_y, t_x, t_y, target_arrow = :none) spacing = @global[:h_gap_between_nodes] * 1.25 min_bulge = @global[:height_connector_to_text] # Small enough that the turn reads as an eased corner rather than as an # arc, and taken from a layout measure so it holds at every font size. corner_radius = min_bulge / 2.0 # Centered offset for multiple lines at the same endpoint s_key = "#{s_x.round}" t_key = "#{t_x.round}" @visited_x[s_key] = (@visited_x[s_key] || 0) + 1 @visited_x[t_key] = (@visited_x[t_key] || 0) + 1 s_offset = ((@visited_x[s_key] - 1) - (@visited_x[s_key] - 1) / 2.0) * spacing t_offset = ((@visited_x[t_key] - 1) - (@visited_x[t_key] - 1) / 2.0) * spacing dashed = true if target_arrow == :none if @direction == "ltr" # LTR: route to the RIGHT of the tree (⊃ shape / reversed C) # Source → right → vertical → left → Target xmax = [s_x, t_x].max bulge = [min_bulge, (s_y - t_y).abs * 0.3 + min_bulge].min # Ensure paths don't overlap: extend beyond previous paths new_x = if xmax < @width @width + bulge else xmax + bulge end new_s_y = s_y + s_offset new_t_y = t_y + t_offset note_path_extent([[s_x, new_s_y], [new_x, new_s_y], [new_x, new_t_y], [t_x, new_t_y]]) @extra_lines << generate_path([[s_x, new_s_y], [new_x, new_s_y], [new_x, new_t_y], [t_x, new_t_y]], @col_path, dashed: dashed, radius: corner_radius, start_arrow: target_arrow == :double, end_arrow: target_arrow != :none) @width = new_x if new_x > @width else # TTB: route BELOW the tree (U shape) # Source → down → horizontal → up → Target ymax = [s_y, t_y].max # Proportional bulge: based on distance between endpoints, # not the full tree height bulge = [min_bulge, (s_x - t_x).abs * 0.3 + min_bulge].min new_y = ymax + bulge new_s_x = s_x - s_offset new_t_x = t_x - t_offset note_path_extent([[new_s_x, s_y], [new_s_x, new_y], [new_t_x, new_y], [new_t_x, t_y]]) @extra_lines << generate_path([[new_s_x, s_y], [new_s_x, new_y], [new_t_x, new_y], [new_t_x, t_y]], @col_path, dashed: dashed, radius: corner_radius, start_arrow: target_arrow == :double, end_arrow: target_arrow != :none) @height = new_y if new_y > @height end end |
#draw_bracket(x1, y1, width, height, col, bline = false) ⇒ Object
822 823 824 825 826 827 828 829 |
# File 'lib/rsyntaxtree/svg_graph.rb', line 822 def draw_bracket(x1, y1, width, height, col, bline = false) swidth = bline ? @global[:stroke_bold] : @global[:stroke_normal] slwidth = @global[:h_gap_between_nodes] / 2 @extra_lines << "<polyline style='stroke:#{col}; stroke-width:#{swidth}; fill:none; stroke-linejoin:round; stroke-linecap:round;' points='#{x1 + slwidth},#{y1} #{x1},#{y1} #{x1},#{y1 + height} #{x1 + slwidth},#{y1 + height}' />\n" @extra_lines << "<polyline style='stroke:#{col}; stroke-width:#{swidth}; fill:none; stroke-linejoin:round; stroke-linecap:round;' points='#{x1 + width - slwidth},#{y1} #{x1 + width},#{y1} #{x1 + width},#{y1 + height} #{x1 + width - slwidth},#{y1 + height}' />\n" end |
#draw_element(element) ⇒ Object
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 |
# File 'lib/rsyntaxtree/svg_graph.rb', line 493 def draw_element(element) top = element.vertical_indent left = element.horizontal_indent right = left + element.content_width txt_pos = left + (right - left) / 2 # Use element's custom color if specified, otherwise use default based on type col = if element.color element.color elsif element.type == ETYPE_LEAF @col_leaf else @col_node end text_data = @text_styles.sub(/COLOR/, col) text_data = text_data.sub(/fontsize/, @fontsize.to_s + "px;") # The node is laid out at the width of its label plus the room its own # enclosure needs, so the text starts that far inside the node's left # edge and the enclosure is drawn on the edge itself. enclosure_room = element.label_enclosure_room text_x = txt_pos - element.content_width / 2 + enclosure_room text_y = top + @global[:single_line_height] - @global[:height_connector_to_text] text_data = text_data.sub(/X_VALUE/, text_x.to_s) text_data = text_data.sub(/Y_VALUE/, text_y.to_s) new_text = +"" this_x = 0 this_y = 0 prev_line_height = nil first_baseline = nil bc = { x: text_x - enclosure_room, y: top, width: element.content_width, height: nil } element.content.each_with_index do |l, idx| case l[:type] when :border, :bborder x1 = text_x if idx.zero? text_y -= l[:height] else text_y += l[:height] end y1 = text_y - @global[:single_line_height] / 8 x2 = text_x + element.text_width y2 = y1 case l[:type] when :border stroke_width = @global[:stroke_normal] when :bborder stroke_width = @global[:stroke_bold] end @extra_lines << "<line style=\"stroke:#{col}; fill:none; stroke-linecap:round; stroke-width:#{stroke_width}; \" x1=\"#{x1}\" y1=\"#{y1}\" x2=\"#{x2}\" y2=\"#{y2}\"></line>" else if @direction == "ltr" && element.type == ETYPE_LEAF # LTR leaves: left-align text at the node's left edge. A leaf # with its own enclosure starts one enclosure room inside, the # same as in TTB, or the bracket would sit on the glyphs. this_x = left + enclosure_room elsif element.enclosure == :brackets this_x = text_x else ewidth = 0 l[:elements].each do |e| ewidth += e[:width] end this_x = txt_pos - (ewidth / 2) end # Advance by the height of the line just drawn, not of this one: a # row holding a nested matrix is as tall as the matrix, and the row # after it has to clear all of it. text_y += prev_line_height if idx != 0 && prev_line_height text_y += l[:top_room].to_f first_baseline ||= text_y prev_line_height = l[:elements].map { |e| e[:height] }.max l[:elements].each do |e| if e[:decoration].include?(:matrix) markup, this_x = render_matrix(e, this_x, text_y, element, col) new_text << markup next end markup, this_x = render_run(e, this_x, text_y, element, col) new_text << markup end end @height = text_y if text_y > @height end bc[:y] = bc[:y] + @global[:height_connector_to_text] * 3 / 4 # text_y is the baseline of the last line. A line holding a nested matrix # reaches further down than a line of text, so the label has to be given # the rest of it. overhang = prev_line_height.to_f - @global[:single_x_metrics].height bc[:height] = text_y - bc[:y] + @global[:height_connector_to_text] + [overhang, 0].max case element.enclosure when :brackets draw_bracket(bc[:x], bc[:y], bc[:width], bc[:height], col) when :rectangle draw_rectangle(bc[:x], bc[:y], bc[:width], bc[:height], col) when :brectangle draw_rectangle(bc[:x], bc[:y], bc[:width], bc[:height], col, true) end element.content_height = bc[:height] # Where the label's ink is, for the symmetric clearances of vmargin. # A drawn shape — an enclosure, or a label that is one matrix — hands # over its own edges; a plain label hands over the font's band around # its first and last baselines, so the connectors of one level start # level with each other whatever letters happen to hang below. drawn_shape = element.enclosure != :none || element.content.any? do |line| line[:type] == :text && line[:elements].any? { |e| e[:decoration].include?(:matrix) } end if drawn_shape element.ink_top = bc[:y] element.ink_bottom = bc[:y] + bc[:height] elsif first_baseline # The label's own ink, not the font's whole band: measured from the # first and last lines of text as drawn. What the connectors then # keep clear of is the union of these across a row (see row_ink), so # the ends stay level within a row while a row of capitals pays no # tax for descenders nobody wrote. text_lines = element.content.select { |l| l[:type] == :text } first_text = text_lines.first[:elements].map { |e| e[:text].to_s }.join.gsub(WHITESPACE_BLOCK, " ") last_text = text_lines.last[:elements].map { |e| e[:text].to_s }.join.gsub(WHITESPACE_BLOCK, " ") f_m = FontMetrics.get_metrics(first_text.strip.empty? ? "X" : first_text, @fontset[:family], @fontsize.to_f, :normal, :normal) l_m = FontMetrics.get_metrics(last_text.strip.empty? ? "X" : last_text, @fontset[:family], @fontsize.to_f, :normal, :normal) element.ink_top = first_baseline - f_m.ink_above element.ink_bottom = text_y + (l_m.ink_height - l_m.ink_above) end @tree_data += text_data.sub(/CONTENT/, new_text) end |
#draw_paths ⇒ Object
839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 |
# File 'lib/rsyntaxtree/svg_graph.rb', line 839 def draw_paths paths = [] path_pool_target = {} path_pool_other = {} path_pool_source = {} path_flags = [] line_pool = {} line_flags = [] elist = @element_list.get_elements elist.each do |element| if @direction == "ltr" # LTR anchors: paths attach at left/right edges, vertically centered hctt = @global[:height_connector_to_text] y_center = element.vertical_indent + (element.content_height + hctt * 1.5) / 2 x0 = element.horizontal_indent - hctt x1 = element.horizontal_indent + element.content_width + hctt x2 = element.horizontal_indent + element.content_width + hctt * 2 y0 = y_center y1 = y_center # A line-type connection, though, wants the box's own geometry. # The path anchors sit a clearance off the box — right for a curve # leaving a node, but a straight link anchored there floats off # both boxes, or lands inside them when the gap is narrow. lgeom = { left: element.horizontal_indent, right: element.horizontal_indent + element.content_width, top: y_center - element.content_height / 2, bottom: y_center + element.content_height / 2, cx: element.horizontal_indent + element.content_width / 2, cy: y_center } else # x0/x2 are the box's own edges: a link between two nodes runs # between these plus a small margin. Anchoring a full h_gap # outside the box left links too short in wide gaps and pushed # them into the boxes in narrow ones. Only the line pool uses # x0/x2; movement paths read x1, which is unchanged. x0 = element.horizontal_indent x1 = element.horizontal_indent + element.content_width / 2 x2 = element.horizontal_indent + element.content_width y0 = element.vertical_indent + @global[:height_connector_to_text] / 2 y1 = element.vertical_indent + element.content_height + @global[:height_connector_to_text] lgeom = nil end et = element.path et.each do |tr| if /\A-(>|<)?(\d+)\z/ =~ tr arrow = $1 tr = $2 if line_pool[tr] line_pool[tr] << { x: { left: x0, center: x1, right: x2 }, y: { top: y0, center: y0 + (y1 - y0) / 2, bottom: y1 }, arrow: arrow, geom: lgeom } else line_pool[tr] = [{ x: { left: x0, center: x1, right: x2 }, y: { top: y0, center: y0 + (y1 - y0) / 2, bottom: y1 }, arrow: arrow, geom: lgeom }] end line_flags << tr elsif /\A(?:>|<)(\d+)\z/ =~ tr tr = $1 if path_pool_target[tr] path_pool_target[tr] << [x1, y1] else path_pool_target[tr] = [[x1, y1]] end path_flags << tr elsif path_pool_source[tr] if path_pool_other[tr] path_pool_other[tr] << [x1, y1] else path_pool_other[tr] = [[x1, y1]] end path_flags << tr else path_pool_source[tr] = [x1, y1] path_flags << tr end raise RSTError.new(+"Error: input text contains a path having more than two ends:\n > #{tr}", code: :path_multiple_ends, hint: "A path or line takes exactly two ends; check the numbers.", retryable: true) if path_flags.tally.any? { |_k, v| v > 2 } || line_flags.tally.any? { |_k, v| v > 2 } end end path_flags.tally.each do |k, v| raise RSTError.new(+"Error: input text contains a path having only one end:\n > #{k}", code: :path_single_end, hint: "A path takes two ends: one '+N' on each of two nodes.", retryable: true) if v == 1 end # A line-type connection is subject to the same rule as a path: it takes # two ends. Without this the drawing walked off a nil pool below. line_flags.tally.each do |k, v| raise RSTError.new(+"Error: input text contains a line having only one end:\n > #{k}", code: :path_single_end, hint: "A line connection takes two ends: '+-N' on each of two nodes.", retryable: true) if v == 1 end path_pool_source.each do |k, v| path_flags.delete(k) if (targets = path_pool_target[k]) targets.each do |t| paths << { x1: v[0], y1: v[1], x2: t[0], y2: t[1], arrow: :single } end elsif (others = path_pool_other[k]) others.each do |t| paths << { x1: v[0], y1: v[1], x2: t[0], y2: t[1], arrow: :none } end end end path_flags.uniq.each do |k| targets = path_pool_target[k] next if targets.nil? || targets.empty? fst = targets.shift next if fst.nil? targets.each do |t| paths << { x1: fst[0], y1: fst[1], x2: t[0], y2: t[1], arrow: :double } end end paths.each do |t| draw_a_path(t[:x1], t[:y1], t[:x2], t[:y2], t[:arrow]) end line_pool.each do |_k, v| a = v[0] b = v[1] # A straight link stops a small margin short of each box. The margin # scales with the inter-node gap and is clamped so an endpoint can # never cross the facing edge. margin = @global[:h_gap_between_nodes] * 0.25 inset = ->(gap) { [[margin, gap / 2 - 1].min, 0].max } if @direction == "ltr" # LTR: use x-position to determine depth relationship, # y-position for sibling relationship ga = a[:geom] gb = b[:geom] if ga[:left] > gb[:right] m = inset.call(ga[:left] - gb[:right]) generate_connectors(ga[:left] - m, ga[:cy], gb[:right] + m, gb[:cy], @col_extra, false, a[:arrow], b[:arrow]) elsif ga[:right] < gb[:left] m = inset.call(gb[:left] - ga[:right]) generate_connectors(gb[:left] - m, gb[:cy], ga[:right] + m, ga[:cy], @col_extra, false, b[:arrow], a[:arrow]) elsif ga[:cy] < gb[:cy] m = inset.call(gb[:top] - ga[:bottom]) generate_connectors(ga[:cx], ga[:bottom] + m, ga[:cx], gb[:top] - m, @col_extra, false, a[:arrow], b[:arrow]) else m = inset.call(ga[:top] - gb[:bottom]) generate_connectors(gb[:cx], gb[:bottom] + m, gb[:cx], ga[:top] - m, @col_extra, false, b[:arrow], a[:arrow]) end else # TTB: use y-position to determine depth relationship if a[:y][:top] > b[:y][:bottom] generate_connectors(a[:x][:center], a[:y][:top], b[:x][:center], b[:y][:bottom], @col_extra, false, a[:arrow], b[:arrow]) elsif a[:y][:bottom] < b[:y][:top] generate_connectors(b[:x][:center], b[:y][:top], a[:x][:center], a[:y][:bottom], @col_extra, false, b[:arrow], a[:arrow]) elsif a[:x][:center] < b[:x][:center] m = inset.call(b[:x][:left] - a[:x][:right]) if a[:y][:top] == b[:y][:top] upper_y = a[:y][:center] < b[:y][:center] ? a[:y][:center] : b[:y][:center] generate_connectors(a[:x][:right] + m, upper_y, b[:x][:left] - m, upper_y, @col_extra, false, a[:arrow], b[:arrow]) else generate_connectors(a[:x][:right] + m, a[:y][:center], b[:x][:left] - m, b[:y][:center], @col_extra, false, a[:arrow], b[:arrow]) end elsif a[:y][:top] == b[:y][:top] upper_y = a[:y][:center] < b[:y][:center] ? a[:y][:center] : b[:y][:center] m = inset.call(a[:x][:left] - b[:x][:right]) generate_connectors(b[:x][:right] + m, upper_y, a[:x][:left] - m, upper_y, @col_extra, false, b[:arrow], a[:arrow]) else m = inset.call(a[:x][:left] - b[:x][:right]) generate_connectors(b[:x][:right] + m, b[:y][:center], a[:x][:left] - m, a[:y][:center], @col_extra, false, b[:arrow], a[:arrow]) end end end paths.size + line_pool.keys.size end |
#draw_rectangle(x1, y1, width, height, col, bline = false) ⇒ Object
816 817 818 819 820 |
# File 'lib/rsyntaxtree/svg_graph.rb', line 816 def draw_rectangle(x1, y1, width, height, col, bline = false) swidth = bline ? @global[:stroke_bold] : @global[:stroke_normal] @extra_lines << "<polygon style='stroke:#{col}; stroke-width:#{swidth}; fill:none; stroke-linejoin:round; stroke-linecap:round;' points='#{x1},#{y1} #{x1 + width},#{y1} #{x1 + width},#{y1 + height} #{x1},#{y1 + height}' />\n" end |
#draw_rule_name(parent, right, y) ⇒ Object
The name of the rule, set beside the end of its own line and smaller than the categories, which is where a derivation puts it and how it keeps the name from reading as part of either row.
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 |
# File 'lib/rsyntaxtree/svg_graph.rb', line 1151 def draw_rule_name(parent, right, y) name = parent.rule_name return if name.nil? || name.empty? size = (@fontsize * 0.8).round(2) # Level with the rule, by the same reckoning an enclosure uses to sit # level with what it encloses. baseline = y + FontMetrics.visual_centre(@fontset[:family], size) x = right + @global[:width_half_x] # The name is the one thing drawn outside every element's own box, so the # canvas has to be told where it ends or the last step's name is cut off # at the edge of the image. edge = x + FontMetrics.get_metrics(name, @fontset[:family], size, :normal, :normal).width @rule_name_edge = edge if edge > @rule_name_edge.to_f @tree_data += @text_styles.sub(/COLOR/, @col_line) .sub(/fontsize/, size.to_s + "px;") .sub(/X_VALUE/, x.to_s) .sub(/Y_VALUE/, baseline.round(2).to_s) .sub(/CONTENT/) { CGI.escapeHTML(name) } end |
#element_visual_box(el) ⇒ Object
Visual bounding box of a single element as actually drawn: the label / enclosure box (which starts hctt*3/4 below vertical_indent, i.e. below the connector gap) widened to include any enclosure bracket/rectangle that is painted beyond the content width.
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 |
# File 'lib/rsyntaxtree/svg_graph.rb', line 304 def element_visual_box(el) hctt = @global[:height_connector_to_text] box_top = el.vertical_indent + hctt * 3 / 4 # bc[:y]: line-height / enclosure box top box_bottom = box_top + el.content_height left = el.horizontal_indent right = el.horizontal_indent + el.content_width if [:brackets, :rectangle, :brectangle].include?(el.enclosure) # The room the enclosure needs is already part of content_width; only # the stroke straddling the edge reaches beyond it. ext = @global[:stroke_bold] left -= ext right += ext sw = @global[:stroke_bold] top = box_top - sw bottom = box_bottom + sw else # No enclosure box is painted, so hug the actual glyphs rather than the # taller line-height box: the line box carries ~hctt*3/4 of leading both # above the cap top and below the baseline, which would otherwise leave # too much empty space above and below a plain label. top = el.vertical_indent + hctt * 3 / 2 bottom = box_bottom - hctt * 3 / 4 end { left: left, top: top, right: right, bottom: bottom } end |
#generate_connectors(x1, y1, x2, y2, col, dashed = false, s_arrow = false, t_arrow = false, bline = false) ⇒ Object
1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 |
# File 'lib/rsyntaxtree/svg_graph.rb', line 1014 def generate_connectors(x1, y1, x2, y2, col, dashed = false, s_arrow = false, t_arrow = false, bline = false) string = if s_arrow && t_arrow "" # bothways arrowheads are drawn as chevrons below elsif s_arrow "marker-mid='url(#arrowForward)' " elsif t_arrow "marker-mid='url(#arrowBackward)' " else "" end dash = @fontsize / 4.0 dasharray = dashed ? "stroke-dasharray='#{dash} #{dash}'" : "" swidth = bline ? @global[:stroke_bold] : @global[:stroke_normal] if s_arrow && t_arrow @extra_lines << "<line x1='#{x1}' y1='#{y1}' x2='#{x2}' y2='#{y2}' style='fill: none; stroke: #{col}; stroke-width:#{swidth}; stroke-linecap:round;' #{dasharray}/>" @extra_lines << bothways_arrows(x1, y1, x2, y2, col, swidth) elsif s_arrow || t_arrow x_mid = if x2 > x1 x1 + (x2 - x1) / 2 else x1 - (x1 - x2) / 2 end y_mid = if y2 > y1 y1 + (y2 - y1) / 2 else y1 - (y1 - y2) / 2 end @extra_lines << "<path d='M#{x1},#{y1} L#{x_mid},#{y_mid} L#{x2}, #{y2}' style='fill: none; stroke: #{col}; stroke-width:#{swidth}; stroke-linecap:round;' #{dasharray} #{string}/>" else @extra_lines << "<line x1='#{x1}' y1='#{y1}' x2='#{x2}' y2='#{y2}' style='fill: none; stroke: #{col}; stroke-width:#{swidth}; stroke-linecap:round;' #{dasharray} #{string}/>" end end |
#generate_line(x1, y1, x2, y2, col, dashed = false, arrow = false, bline = false) ⇒ Object
1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 |
# File 'lib/rsyntaxtree/svg_graph.rb', line 1084 def generate_line(x1, y1, x2, y2, col, dashed = false, arrow = false, bline = false) string = if arrow "marker-end='url(#arrow)' " else "" end dash = @fontsize / 4.0 dasharray = dashed ? "stroke-dasharray='#{dash} #{dash}'" : "" swidth = bline ? @global[:stroke_bold] : @global[:stroke_normal] "<line x1='#{x1}' y1='#{y1}' x2='#{x2}' y2='#{y2}' style='fill: none; stroke: #{col}; stroke-width:#{swidth}; stroke-linecap:round;' #{dasharray} #{string}/>" end |
#generate_path(points, col, dashed: false, radius: 0, start_arrow: false, end_arrow: false) ⇒ Object
One stroke rather than three lines meeting at right angles. Drawn this way the dash pattern runs round each turn instead of restarting at it, and an arrowhead is the end of the stroke rather than a marker on whichever line happens to finish last.
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 |
# File 'lib/rsyntaxtree/svg_graph.rb', line 385 def generate_path(points, col, dashed: false, radius: 0, start_arrow: false, end_arrow: false) # An arrowhead is drawn back along the run it ends, so the corner before # it has to leave that run its full length. Without this the shorter of # the two end runs — which is only as long as the path's bulge — lost half # of itself to the turn and the head came out sitting on the curve. arrow_length = @global[:h_gap_between_nodes] leg = ->(a, b) { Math.sqrt(((a[0] - b[0])**2) + ((a[1] - b[1])**2)) } radius = [radius, leg.call(points[0], points[1]) - arrow_length].min if start_arrow radius = [radius, leg.call(points[-2], points[-1]) - arrow_length].min if end_arrow radius = [radius, 0].max dash = @fontsize / 4.0 dasharray = dashed ? "stroke-dasharray='#{dash} #{dash}' " : "" markers = +"" markers << "marker-start='url(#arrowStart)' " if start_arrow markers << "marker-end='url(#arrow)' " if end_arrow # A round cap is half the stroke's width of ink past the point the stroke # ends at, and an arrowhead has its tip at exactly that point — so the # line came through the tip: 13% ink on the pixel beyond the head of a # path, and 81% beyond its tail, where the marker's apex sits on the # anchor rather than behind it. Squared off, the stroke stops where the # head begins. Only where there is a head: a path without one is the # dashed form, and every dash of it wants its round ends. linecap = start_arrow || end_arrow ? "butt" : "round" "<path d='#{rounded_polyline_d(points, radius)}' style='fill: none; stroke: #{col}; " \ "stroke-width:#{@global[:stroke_normal]}; stroke-linecap:#{linecap}; stroke-linejoin:round;' " \ "#{dasharray}#{markers}/>" end |
#ink_over(element) ⇒ Object
Where a connector clears an element on the vmargin geometry: the row's ink for a plain label, the drawn edge for an enclosed one.
1197 1198 1199 1200 |
# File 'lib/rsyntaxtree/svg_graph.rb', line 1197 def ink_over(element) row = element.enclosure == :none && row_ink[element.vertical_indent.round(1)] row ? row[:top] : element.ink_top end |
#ink_under(element) ⇒ Object
1202 1203 1204 1205 |
# File 'lib/rsyntaxtree/svg_graph.rb', line 1202 def ink_under(element) row = element.enclosure == :none && row_ink[element.vertical_indent.round(1)] row ? row[:bottom] : element.ink_bottom end |
#line_to_parent(parent, child) ⇒ Object
1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 |
# File 'lib/rsyntaxtree/svg_graph.rb', line 1268 def line_to_parent(parent, child) return if child.horizontal_indent.zero? if @direction == "ltr" # LTR: parent's right side → child's left side # Y center = midpoint between TTB top-connection and bottom-connection # top = vi + hctt/2, bottom = vi + content_height + hctt # midpoint = vi + (content_height + hctt * 1.5) / 2 hctt = @global[:height_connector_to_text] y1 = child.vertical_indent + (child.content_height + hctt * 1.5) / 2 y2 = parent.vertical_indent + (parent.content_height + hctt * 1.5) / 2 x1 = child.empty_label? ? child.horizontal_indent + child.content_width / 2 : child.horizontal_indent - hctt x2 = parent.empty_label? ? parent.horizontal_indent + parent.content_width / 2 : parent.horizontal_indent + parent.content_width + hctt if @polyline mid_x1 = x2 + (x1 - x2) / 2 mid_y1 = y1 mid_x2 = mid_x1 mid_y2 = y2 @tree_data += @polyline_styles.sub(/CHIX/, x1.to_s) .sub(/CHIY/, y1.to_s) .sub(/MIDX1/, mid_x1.to_s) .sub(/MIDY1/, mid_y1.to_s) .sub(/MIDX2/, mid_x2.to_s) .sub(/MIDY2/, mid_y2.to_s) .sub(/PARX/, x2.to_s) .sub(/PARY/, y2.to_s) else line_data = @line_styles.sub(/X1/, x1.to_s) line_data = line_data.sub(/Y1/, y1.to_s) line_data = line_data.sub(/X2/, x2.to_s) @tree_data += line_data.sub(/Y2/, y2.to_s) end else # TTB: parent's bottom → child's top if @polyline chi_x = child.horizontal_indent + child.content_width / 2 par_x = parent.horizontal_indent + parent.content_width / 2 chi_y, par_y = connector_edges(child, parent) mid_x1 = chi_x mid_y1 = par_y + (chi_y - par_y) / 2 mid_x2 = par_x mid_y2 = mid_y1 @tree_data += @polyline_styles.sub(/CHIX/, chi_x.to_s) .sub(/CHIY/, chi_y.to_s) .sub(/MIDX1/, mid_x1.to_s) .sub(/MIDY1/, mid_y1.to_s) .sub(/MIDX2/, mid_x2.to_s) .sub(/MIDY2/, mid_y2.to_s) .sub(/PARX/, par_x.to_s) .sub(/PARY/, par_y.to_s) else x1 = child.horizontal_indent + child.content_width / 2 x2 = parent.horizontal_indent + parent.content_width / 2 y1, y2 = connector_edges(child, parent) line_data = @line_styles.sub(/X1/, x1.to_s) line_data = line_data.sub(/Y1/, y1.to_s) line_data = line_data.sub(/X2/, x2.to_s) @tree_data += line_data.sub(/Y2/, y2.to_s) end end end |
#note_path_extent(points) ⇒ Object
Where the movement paths have been, as a box. The canvas learns of a rail through @width and @height, which only say how far right and down anything got; the plane behind a sheared figure has to enclose the rail on every side, so the corners themselves are kept.
420 421 422 423 424 425 426 427 428 |
# File 'lib/rsyntaxtree/svg_graph.rb', line 420 def note_path_extent(points) xs = points.map(&:first) ys = points.map(&:last) b = (@path_bounds ||= { min_x: xs.min, min_y: ys.min, max_x: xs.max, max_y: ys.max }) b[:min_x] = [b[:min_x], xs.min].min b[:min_y] = [b[:min_y], ys.min].min b[:max_x] = [b[:max_x], xs.max].max b[:max_y] = [b[:max_y], ys.max].max end |
#region_subtree_bounds(id) ⇒ Object
Union of element_visual_box over the subtree rooted at id, in final
drawing coordinates. Used to size region shades so the whole subtree
(labels, enclosures, brackets) sits inside the plane.
333 334 335 336 337 338 339 340 341 342 343 |
# File 'lib/rsyntaxtree/svg_graph.rb', line 333 def region_subtree_bounds(id) b = element_visual_box(@element_list.get_id(id)) @element_list.get_id(id).children.each do |c| cb = region_subtree_bounds(c) b[:left] = cb[:left] if cb[:left] < b[:left] b[:right] = cb[:right] if cb[:right] > b[:right] b[:top] = cb[:top] if cb[:top] < b[:top] b[:bottom] = cb[:bottom] if cb[:bottom] > b[:bottom] end b end |
#render_matrix(e, this_x, text_y, element, col) ⇒ Object
Draws a matrix nested in a label: its own rows and columns, laid out from the sizes Element#measure_lines worked out, inside its own brackets.
752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 |
# File 'lib/rsyntaxtree/svg_graph.rb', line 752 def render_matrix(e, this_x, text_y, element, col) out = +"" advance = e[:width] # The room measured in front of the block, if it follows something in # the same cell. Taken off this_x here so the bracket starts after it, # and left in the advance so the row is as wide as it was measured. lead = e[:matrix_lead].to_f this_x += lead inner_x = this_x + @global[:width_half_x] * MATRIX_BRACKET_ROOM baseline = text_y prev_height = nil e[:matrix].each_with_index do |line, idx| # A rule across the matrix, the way one runs across a label: it takes # a row of its own and spans the width inside the brackets, so a # feature structure can separate its type from its features and a # tableau its header from its candidates. if %i[border bborder].include?(line[:type]) # Placed from the baseline above it, the way a rule across a label # is: a third of a line under the row before, the rest of the gap # under the rule. Measuring from the row it is about to open # instead put the space on the wrong side — more above the rule # than below, where the ascenders of the next row need it. above = baseline baseline += prev_height if idx.positive? && prev_height prev_height = line[:height].to_f y = if idx.zero? above - prev_height - @global[:single_line_height] / 8 else above + prev_height - @global[:single_line_height] / 8 end inner_w = e[:width] - (inner_x - this_x) * 2 stroke = line[:type] == :bborder ? @global[:stroke_bold] : @global[:stroke_normal] @extra_lines << "<line style=\"stroke:#{col}; fill:none; stroke-linecap:round; " \ "stroke-width:#{stroke}; \" x1=\"#{inner_x}\" y1=\"#{y}\" " \ "x2=\"#{inner_x + inner_w}\" y2=\"#{y}\"></line>" next end next unless line[:type] == :text baseline += prev_height if idx.positive? && prev_height baseline += line[:top_room].to_f prev_height = line[:elements].map { |x| x[:height] }.max pen = inner_x line[:elements].each do |cell| markup, pen = if cell[:decoration].include?(:matrix) render_matrix(cell, pen, baseline, element, col) else render_run(cell, pen, baseline, element, col) end out << markup end end # The bracket encloses the matrix and its own padding. The separation # from the rows either side is already in the baseline this was called # with, so taking it off here again would cancel it out and leave two # stacked blocks touching. padding = @global[:single_x_metrics].height * MATRIX_VERTICAL_ROOM top = text_y - @global[:single_x_metrics].height * 0.8 - padding draw_bracket(this_x, top, e[:width] - lead, e[:matrix_height] + padding * 2, col) [out, this_x + advance - lead] end |
#render_run(e, this_x, text_y, element, col) ⇒ Object
Draws one run of a label — a stretch of text with its decorations, or the box, circle or bar drawn around it — at the given pen position, and reports where the pen ends up. A nested matrix draws its own runs through here, so this could no longer live inside the drawing loop.
633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 |
# File 'lib/rsyntaxtree/svg_graph.rb', line 633 def render_run(e, this_x, text_y, element, col) out = +"" this_y = text_y escaped_text = e[:text].gsub('>', '>').gsub('<', '<'); decorations = [] decorations << "overline" if e[:decoration].include?(:overline) decorations << "underline" if e[:decoration].include?(:underline) decorations << "line-through" if e[:decoration].include?(:linethrough) decoration = "text-decoration=\"" + decorations.join(" ") + "\"" style = "style=\"" if e[:decoration].include?(:small) style += "font-size: #{(SUBSCRIPT_CONST.to_f * 100).to_i}%; " this_y = text_y - ((@global[:single_x_metrics].height - @global[:single_x_metrics].height * SUBSCRIPT_CONST) / 4) + @fontsize / 16.0 elsif e[:decoration].include?(:superscript) style += "font-size: #{(SUBSCRIPT_CONST.to_f * 100).to_i}%; " this_y = text_y - (@global[:single_x_metrics].height / 4) + @fontsize / 32.0 elsif e[:decoration].include?(:subscript) style += "font-size: #{(SUBSCRIPT_CONST.to_f * 100).to_i}%; " this_y = text_y + @fontsize / 8.0 else this_y = text_y end style += "font-weight: bold; fill: #{@col_emph}; " if e[:decoration].include?(:bold) || e[:decoration].include?(:bolditalic) style += "font-style: italic; " if e[:decoration].include?(:italic) || e[:decoration].include?(:bolditalic) style += "\"" fontstyle = FontFamily.for_svg(@fontstyle) if e[:decoration].include?(:box) || e[:decoration].include?(:circle) || e[:decoration].include?(:bar) # Measured around the enclosed marks in Element#setup; the line # height would draw the shape taller than what it encloses. enc_height = e[:enc_height] || e[:height] enc_y = this_y - (e[:enc_above] || e[:height] * 0.8) enc_width = e[:width] enc_x = this_x if e[:decoration].include?(:hatched) case element.type when ETYPE_LEAF fill = if @color "url(#hatchForLeaf)" else "url(#hatchBlack)" end when ETYPE_NODE fill = if @color "url(#hatchForNode)" else "url(#hatchBlack)" end end else fill = "none" end enc = nil stroke_width = if e[:decoration].include?(:bstroke) @global[:stroke_bold] else @global[:stroke_normal] end if e[:decoration].include?(:box) enc = "<rect style='stroke: #{col}; stroke-linejoin:round; stroke-width:#{stroke_width};' x='#{enc_x}' y='#{enc_y}' width='#{enc_width}' height='#{enc_height}' fill='#{fill}' />\n" elsif e[:decoration].include?(:circle) enc = "<rect style='stroke: #{col}; stroke-width:#{stroke_width};' x='#{enc_x}' y='#{enc_y}' rx='#{enc_height / 2}' ry='#{enc_height / 2}' width='#{enc_width}' height='#{enc_height}' fill='#{fill}' />\n" elsif e[:decoration].include?(:bar) x1 = enc_x y1 = enc_y + enc_height / 2 x2 = enc_x + enc_width y2 = y1 ar_hwidth = e[:width] / 4.0 = "<line style='fill:none; stroke:#{col}; stroke-linejoin:round; stroke-linecap:round; stroke-width:#{stroke_width};' x1='#{x1 + stroke_width / 2}' y1='#{y1}' x2='#{x2 - stroke_width / 2}' y2='#{y2}'></line>\n" @extra_lines << if e[:decoration].include?(:arrow_to_l) l_arrowhead = "<polyline stroke-linejoin='round' stroke-linecap='round' fill='none' stroke='#{col}' stroke-width='#{stroke_width}' points='#{x1 + ar_hwidth},#{y1 + ar_hwidth / 2} #{x1 + stroke_width / 2},#{y1} #{x1 + ar_hwidth},#{y1 - ar_hwidth / 2}' />\n" @extra_lines << l_arrowhead end if e[:decoration].include?(:arrow_to_r) r_arrowhead = "<polyline stroke-linejoin='round' stroke-linecap='round' fill='none' stroke='#{col}' stroke-width='#{stroke_width}' points='#{x2 - ar_hwidth},#{y2 - ar_hwidth / 2} #{x2 - stroke_width / 2},#{y2} #{x2 - ar_hwidth},#{y2 + ar_hwidth / 2}' />\n" @extra_lines << r_arrowhead end end @extra_lines << enc if enc # Centre the marks in the shape. e[:width] is the shape's width, # e[:content_width] the marks' own, so half the difference is the # left inset — the line height used to stand in for the shape's # width here, which left the glyph off-centre once the shape was # measured from its content instead. inset = (e[:width] - e[:content_width]) / 2 this_x += inset out << set_tspan(this_x, this_y, style, decoration, fontstyle, escaped_text) this_x += e[:content_width] + inset elsif e[:decoration].include?(:whitespace) return [out, this_x + e[:width]] else out << set_tspan(this_x, this_y, style, decoration, fontstyle, escaped_text) this_x += e[:width] end [out, this_x] end |
#rounded_polyline_d(points, radius) ⇒ Object
The d of a polyline whose corners are eased into quarter turns.
The radius is clamped to half of each of the two runs meeting at a corner, so a short leg can never be swallowed by its own turn and two adjacent corners can never overlap — which is the whole of the arithmetic that rounding a right angle needs, and why it can be a constant everywhere else.
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 |
# File 'lib/rsyntaxtree/svg_graph.rb', line 362 def rounded_polyline_d(points, radius) return +"" if points.size < 2 at = ->(p) { "#{p[0].round(3)},#{p[1].round(3)}" } d = +"M#{at.call(points[0])}" points.each_cons(3) do |before, corner, after| r = [radius, Math.sqrt(((corner[0] - before[0])**2) + ((corner[1] - before[1])**2)) / 2.0, Math.sqrt(((after[0] - corner[0])**2) + ((after[1] - corner[1])**2)) / 2.0].min if r < 0.01 d << " L#{at.call(corner)}" else d << " L#{at.call(along(corner, before, r))}" \ " Q#{at.call(corner)} #{at.call(along(corner, after, r))}" end end d << " L#{at.call(points.last)}" end |
#row_ink ⇒ Object
Where a connector meets each box in a vertical layout: the underside of
whichever sits higher and the top of whichever sits lower. Turned over,
the parent is the lower of the two, and keeping the top-to-bottom edges
sent the line back up through both labels. An empty label has no text to
clear, so the line runs to its middle.
The ink extents of a row: the union, across every plain label standing
at one height, of where its type actually reaches. An endpoint measured
from the label's own ink alone gives every label equal air but leaves
the ends of a row's connectors ragged — a line reaches lower over on
than over the; measured from the whole font's band the ends are level
but a row of capitals pays for descenders nobody wrote. The row's own
union keeps the ends level and charges only for what the row contains.
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 |
# File 'lib/rsyntaxtree/svg_graph.rb', line 1184 def row_ink @row_ink ||= @element_list.get_elements.each_with_object({}) do |e, rows| next unless e.ink_top && e.ink_bottom next if e.enclosure != :none row = (rows[e.vertical_indent.round(1)] ||= { top: e.ink_top, bottom: e.ink_bottom }) row[:top] = [row[:top], e.ink_top].min row[:bottom] = [row[:bottom], e.ink_bottom].max end end |
#rule_to_parent(parent, children) ⇒ Object
Draw a line between child/parent elements. An empty-label element (see Element#empty_label?) is a pass-through joint: the line runs to its center instead of stopping at its (invisible) text box, so the segments on both sides connect without a gap. One rule across all the premises, in place of a line to each. The rule runs the width of what it combines — the span from the leftmost child's left edge to the rightmost child's right edge — because that span is what the step applies to, and reading it off the children is what keeps it right when the layout moves.
Drawn at the parent's edge facing the children, so it sits between the material above it and the result below in a derivation, and between a node and its daughters in an ordinary tree.
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 |
# File 'lib/rsyntaxtree/svg_graph.rb', line 1110 def rule_to_parent(parent, children) return if children.empty? # The whole of what the step combines, not the labels of its premises: # a premise stands over a derivation of its own, and the rule is drawn # across all of it. Taken from the subtree extents, which is what the # layout already computes for the same purpose. left = children.map { |c| get_leftmost(c.id) }.min right = children.map { |c| get_rightmost(c.id) }.max # The parent may be wider than everything it combines, which happens when # a category is longer than the words under it. The rule covers both, so # that the label it belongs to is never wider than its own rule. left = [left, parent.horizontal_indent].min right = [right, parent.horizontal_indent + parent.content_width].max hctt = @global[:height_connector_to_text] above, below = derivation_rule_band(parent) y = if above (above + hctt + below) / 2.0 else child_edge = children.map { |c| c.vertical_indent + c.content_height }.max parent_top = parent.vertical_indent if parent_top >= child_edge # The parent sits below: the rule goes between the two. (child_edge + hctt + parent_top) / 2.0 else # The parent sits above (an ordinary top-to-bottom tree). (parent.vertical_indent + parent.content_height + hctt + children.map(&:vertical_indent).min) / 2.0 end end @tree_data += @line_styles.sub(/X1/, left.to_s).sub(/Y1/, y.to_s) .sub(/X2/, right.to_s).sub(/Y2/, y.to_s) draw_rule_name(parent, right, y) end |
#set_tspan(this_x, this_y, style, decoration, fontstyle, text) ⇒ Object
831 832 833 834 835 836 837 |
# File 'lib/rsyntaxtree/svg_graph.rb', line 831 def set_tspan(this_x, this_y, style, decoration, fontstyle, text) text.gsub!(/■+/) do |x| num_spaces = x.size "<tspan style='fill:none;'>" + "■" * num_spaces + "</tspan>" end "<tspan x='#{this_x}' y='#{this_y}' #{style} #{decoration} font-family=\"#{fontstyle}\">#{text}</tspan>\n" end |
#svg_data ⇒ Object
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 |
# File 'lib/rsyntaxtree/svg_graph.rb', line 65 def svg_data metrics = parse_list # Region shades depend on the final element positions and on the node # content_height that draw_element recomputes, so collect them only # after parse_list (which runs draw_elements) has completed. collect_region_shades @width = metrics[:width] + @global[:h_gap_between_nodes] * 2 @height = metrics[:height] + @global[:height_connector_to_text] / 2 x1 = 0 - @global[:h_gap_between_nodes] y1 = 0 x2 = @width + @global[:h_gap_between_nodes] y2 = @height + @global[:height_connector_to_text] / 2 # Grow the canvas so region shades that reach past the tree's own bounds # (e.g. a region on the root node, or one whose padded edge extends beyond # the deepest leaf) keep a margin instead of touching the image edge. A # margin is added around the region extents before unioning with the tree # bounds. x2/y2 are the viewBox width/height, so right = x1 + x2. if @region_bounds rb = @region_bounds m = @global[:h_gap_between_nodes] left = [x1, rb[:min_x] - m].min top = [y1, rb[:min_y] - m].min right = [x1 + x2, rb[:max_x] + m].max bottom = [y1 + y2, rb[:max_y] + m].max new_x2 = right - left new_y2 = bottom - top @width += new_x2 - x2 @height += new_y2 - y2 x1 = left y1 = top x2 = new_x2 y2 = new_y2 end # A sheared figure needs a canvas of its own shape. The plane is laid # out in the space the tree was drawn in — everything inside the shear # group shares it — so it is the union of all the ink there: the # elements, the region shades, the movement rails, and a rule's name # hanging past the last box. The canvas is that plane's four corners # after the shear, with the usual margin around them. unless @shear_k.zero? gap = @global[:h_gap_between_nodes] els = @element_list.get_elements ink_l = els.map(&:horizontal_indent).min ink_t = els.map(&:vertical_indent).min ink_r = els.map { |e| e.horizontal_indent + e.content_width }.max ink_b = els.map { |e| e.vertical_indent + e.content_height }.max ink_r = @rule_name_edge if @rule_name_edge.to_f > ink_r [@region_bounds, @path_bounds].compact.each do |b| ink_l = [ink_l, b[:min_x]].min ink_t = [ink_t, b[:min_y]].min ink_r = [ink_r, b[:max_x]].max ink_b = [ink_b, b[:max_y]].max end pad = gap * 1.5 @plane_rect = { x: (ink_l - pad).round(3), y: (ink_t - pad).round(3), w: (ink_r - ink_l + pad * 2).round(3), h: (ink_b - ink_t + pad * 2).round(3) } cx0 = @plane_rect[:x] - gap cx1 = @plane_rect[:x] + @plane_rect[:w] + gap cy0 = @plane_rect[:y] - gap cy1 = @plane_rect[:y] + @plane_rect[:h] + gap sheared = [cx0 + @shear_k * cy0, cx0 + @shear_k * cy1, cx1 + @shear_k * cy0, cx1 + @shear_k * cy1] x1 = sheared.min.round(3) x2 = (sheared.max - sheared.min).round(3) y1 = cy0.round(3) y2 = (cy1 - cy0).round(3) @width = x2 @height = y2 end extra_lines = @extra_lines.join("\n") # Rounded like the stroke widths are: the arithmetic leaves float dust # (13.600000000000001) in an attribute of every figure, and the SVG is a # deliverable people open in editors. as2 = (@global[:h_gap_between_nodes] * 1.0).round(3) as4 = (as2 * 3).round(3) # The hatch density follows the type size the way the enclosure it # fills does: the cell is 10/32 of the font size, the line 4/32 — # the ratios the absolute 10 and 4 had at the default size. hatch_cell = @fontsize * 0.3125 hatch_stroke = @fontsize * 0.125 header = <<~HDR <?xml version="1.0" standalone="no"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg width="#{x2}" height="#{y2}" viewBox="#{x1}, #{y1}, #{x2}, #{y2}" version="1.1" xmlns="http://www.w3.org/2000/svg"> <defs> <marker id="arrow" markerUnits="userSpaceOnUse" viewBox="0 0 10 10" refX="10" refY="5" markerWidth="#{as2}" markerHeight="#{as2}" orient="auto"> <path d="M 0 0 L 10 5 L 0 10" fill="#{@col_extra}"/> </marker> <marker id="arrowStart" markerUnits="userSpaceOnUse" viewBox="0 0 10 10" refX="0" refY="5" markerWidth="#{as2}" markerHeight="#{as2}" orient="auto"> <path d="M 10 0 L 0 5 L 10 10" fill="#{@col_extra}"/> </marker> <marker id="arrowBackward" markerUnits="userSpaceOnUse" viewBox="0 0 10 10" refX="5" refY="5" markerWidth="#{as2}" markerHeight="#{as2}" orient="auto"> <path d="M 0 0 L 10 5 L 0 10 z" fill="#{@col_extra}"/> </marker> <marker id="arrowForward" markerUnits="userSpaceOnUse" viewBox="0 0 10 10" refX="5" refY="5" markerWidth="#{as2}" markerHeight="#{as2}" orient="auto"> <path d="M 10 0 L 0 5 L 10 10 z" fill="#{@col_extra}"/> </marker> <marker id="arrowBothways" markerUnits="userSpaceOnUse" viewBox="0 0 30 10" refX="15" refY="5" markerWidth="#{as4}" markerHeight="#{as2}" orient="auto"> <path d="M 0 5 L 10 0 L 10 5 L 20 5 L 20 0 L 30 5 L 20 10 L 20 5 L 10 5 L 10 10 z" fill="#{@col_extra}"/> </marker> <pattern id="hatchBlack" x="10" y="10" width="#{hatch_cell}" height="#{hatch_cell}" patternUnits="userSpaceOnUse" patternTransform="rotate(45)"> <line x1="0" y="0" x2="0" y2="#{hatch_cell}" stroke="black" stroke-width="#{hatch_stroke}"></line> </pattern> <pattern id="hatchForNode" x="10" y="10" width="#{hatch_cell}" height="#{hatch_cell}" patternUnits="userSpaceOnUse" patternTransform="rotate(45)"> <line x1="0" y="0" x2="0" y2="#{hatch_cell}" stroke="#{@col_node}" stroke-width="#{hatch_stroke}"></line> </pattern> <pattern id="hatchForLeaf" x="10" y="10" width="#{hatch_cell}" height="#{hatch_cell}" patternUnits="userSpaceOnUse" patternTransform="rotate(45)"> <line x1="0" y="0" x2="0" y2="#{hatch_cell}" stroke="#{@col_leaf}" stroke-width="#{hatch_stroke}"></line> </pattern> </defs> HDR rect = <<~RCT <rect x="#{x1}" y="#{y1}" width="#{x2}" height="#{y2}" stroke="none" fill="white" /> RCT = "</svg>" # Region shades go at the very back: above the white background but # below tree connectors and labels. shades = @region_shades.join if @shear_k.zero? if @transparent header + shades + @tree_data + extra_lines + else header + rect + shades + @tree_data + extra_lines + end else # The whole picture shears as one: the plane, the shades, the tree # and the rails all live inside the group, so an affine map carries # every incidence with it — nothing can newly touch or cross. The # background stays outside, painted to the sheared canvas. # No plane on a transparent background: what a clear background is # for is laying the figure over something else, and an opaque sheet # under it is the one thing that would defeat that. plane = +"" if @shear_plane != "off" && !@transparent color = @shear_plane == "on" ? REGION_DEFAULT_COLOR : @shear_plane radius = @global[:height_connector_to_text] / 2.0 # Fill alone, no edge. A region shade is bounded because it marks # one part of a figure off from the rest; the plane is under all of # it, and a line around the whole drawing reads as a frame. plane = "<rect x=\"#{@plane_rect[:x]}\" y=\"#{@plane_rect[:y]}\" " \ "width=\"#{@plane_rect[:w]}\" height=\"#{@plane_rect[:h]}\" " \ "rx=\"#{radius}\" ry=\"#{radius}\" " \ "fill=\"#{color}\" fill-opacity=\"#{SHEAR_PLANE_FILL_OPACITY}\" " \ "stroke=\"none\" />\n" end body = "<g transform=\"matrix(1,0,#{@shear_k},1,0,0)\">\n" + plane + shades + @tree_data + extra_lines + "</g>\n" if @transparent header + body + else header + rect + body + end end end |
#triangle_to_parent(parent, child) ⇒ Object
Draw a triangle between child/parent elements
1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 |
# File 'lib/rsyntaxtree/svg_graph.rb', line 1336 def triangle_to_parent(parent, child) return if child.horizontal_indent.zero? if @direction == "ltr" # LTR: triangle opens vertically (top-bottom of child), # apex at parent's right side. # Use same vertical reference and dimensions as TTB uses horizontally. hctt = @global[:height_connector_to_text] child_y_center = child.vertical_indent + (child.content_height + hctt * 1.5) / 2 parent_y_center = parent.vertical_indent + (parent.content_height + hctt * 1.5) / 2 tri_half = @global[:single_x_metrics].height / 2 x1 = child.horizontal_indent - @global[:height_connector_to_text] / 2 y1 = child_y_center - tri_half x2 = child.horizontal_indent - @global[:height_connector_to_text] / 2 y2 = child_y_center + tri_half x3 = parent.horizontal_indent + parent.content_width + @global[:height_connector_to_text] y3 = parent_y_center else # The triangle spans the child's text and points at the parent. Which # way it points is the question the connectors ask as `child_above`, # and the answer is not always the same: bottom-to-top turns the # finished layout over, so the child sits above the parent there and # the base and the apex trade sides. Drawn as though the child were # always below, a bottom-to-top triangle came out inside out — its # base struck through the leaf and its apex through the node — for as # long as the option has existed. No gallery figure carries one: the # bottom-to-top examples are derivations, which draw rules instead. x1 = child.horizontal_indent x2 = child.horizontal_indent + child.content_width x3 = parent.horizontal_indent + parent.content_width / 2 child_above = child.vertical_indent <= parent.vertical_indent m = child.ink_top && parent.ink_bottom ? @global[:single_x_metrics].height * @global[:vmargin] : nil if child_above y1 = m ? ink_under(child) + m : child.vertical_indent + child.content_height + @global[:height_connector_to_text] y3 = m ? ink_over(parent) - m : parent.vertical_indent + @global[:height_connector_to_text] / 2 # The apex must stay clear of the base, or the figure folds through # itself; where there is no room for both clearances they meet in # the middle of what room there is. if m && y3 < y1 mid = (y1 + y3) / 2.0 y1 = mid y3 = mid end else y1 = m ? ink_over(child) - m : child.vertical_indent + @global[:height_connector_to_text] / 2 y3 = m ? ink_under(parent) + m : parent.vertical_indent + parent.content_height + @global[:height_connector_to_text] if m && y3 > y1 mid = (y1 + y3) / 2.0 y1 = mid y3 = mid end end y2 = y1 end polygon_data = @polygon_styles.sub(/X1/, x1.to_s) polygon_data = polygon_data.sub(/Y1/, y1.to_s) polygon_data = polygon_data.sub(/X2/, x2.to_s) polygon_data = polygon_data.sub(/Y2/, y2.to_s) polygon_data = polygon_data.sub(/X3/, x3.to_s) @tree_data += polygon_data.sub(/Y3/, y3.to_s) end |