Class: RSyntaxTree::RSGenerator
- Inherits:
-
Object
- Object
- RSyntaxTree::RSGenerator
- Defined in:
- lib/rsyntaxtree.rb
Constant Summary collapse
- OFF =
Two gates, because neither one alone tells the truth.
Bracket balance catches what the drawing path silently repairs: it closes an unclosed bracket and drops a stray one, so a typo would otherwise draw a tree the writer never asked for.
Parsing catches what balance cannot see: label markup — an unpaired underline in a word, a matrix left open where a raw space split a value — passes the bracket count and then fails at draw time, which is how a caller came to be told "OK" and still get an error.
Passing both means the input is well-formed and really does draw.
Options matter to the second gate:
hyphen: "literal"decides whether a hyphen is an underline, so validating without the caller's options rejects input that draws. An on/off option, read the way someone writing one would mean it. This used to compare against "off" and "false" alone, so every other way of saying no switched the option on:mirror: "no"reversed the tree,transparent: "0"cut the background out, and a capital in "Off" was enough on its own. ["off", "false", "no", "none", "0", ""].freeze
Class Method Summary collapse
Instance Method Summary collapse
- #draw_gif ⇒ Object
- #draw_jpg ⇒ Object
- #draw_lsif ⇒ Object
- #draw_pdf(binary = false) ⇒ Object
- #draw_png(binary = false) ⇒ Object
- #draw_svg ⇒ Object
- #draw_tikz(standalone: false, font: nil) ⇒ Object
-
#initialize(params = {}) ⇒ RSGenerator
constructor
A new instance of RSGenerator.
-
#pdf_surface_for(svg, target) ⇒ Object
The same for PDF, which in practice refuses nothing: a page 400,000 points wide is made without complaint where a raster surface stops at 32,767.
-
#raster_surface_for(svg) ⇒ Object
The surface a raster format needs.
- #switched_on?(value) ⇒ Boolean
-
#validate! ⇒ Object
Generate, and throw the result away.
-
#with_rmagick ⇒ Object
JPG and GIF output converts the PNG through RMagick.
Constructor Details
#initialize(params = {}) ⇒ RSGenerator
Returns a new instance of RSGenerator.
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 231 232 233 234 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 299 300 301 302 303 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 329 330 331 |
# File 'lib/rsyntaxtree.rb', line 149 def initialize(params = {}) new_params = {} fontset = {} params.each do |keystr, value| key = keystr.to_sym # An option given as an empty string is an option not given. An HTML # form posts a field for every control it carries, and a control with # nothing selected posts the empty string — so a form that has outlived # one of its own controls sends `format=` and every other option along # with it. Read as a value, that is a choice nobody can have made, and # it failed the whole request: the web UI's three Download buttons # returned 500 for every input, with the reason nowhere the user could # see it. Read as silence, the default stands, which is what the sender # meant. next if (OPTION_VALUES.key?(key) || NUMERIC_RANGES.key?(key)) && (value.nil? || value.to_s.strip.empty?) if OPTION_VALUES.key?(key) && !OPTION_VALUES[key].include?(value.to_s) raise RSTError.new(+"Error: invalid value for option '#{key}': #{value.inspect}", code: :invalid_option, hint: "'#{key}' must be one of: #{OPTION_VALUES[key].join(', ')}.", retryable: false) end if NUMERIC_RANGES.key?(key) && !NUMERIC_RANGES[key].cover?(value.to_f) range = NUMERIC_RANGES[key] raise RSTError.new(+"Error: invalid value for option '#{key}': #{value.inspect}", code: :invalid_option, hint: "'#{key}' must be in the range of #{range.begin}-#{range.end}.", retryable: false) end case key when :data data = value data = data.gsub('-AMP-', '&') .gsub('-PERCENT-', "%") .gsub('-PRIME-', "'") .gsub('-SCOLON-', ';') .gsub('-OABRACKET-', '<') .gsub('-CABRACKET-', '>') .gsub('¥¥', '\¥') .gsub(/(?<!\\)¥/, "\\") # Penn Treebank input converts to bracket notation here, in the # library, so every path — CLI, web UI, any other caller — sees # the documented automatic conversion. Only '('-leading input is # affected; bracket notation passes through unchanged. new_params[key] = FormatConverter.to_bracket(data) when :tidy # One layout scale from the most spacious to the most dense: # "symmetric" (radical symmetrization, uniform sibling slots), # "off" (the traditional layout), "low" (contour packing with # strict leaf positions), "medium" (packing that may tuck # branches across rows as long as no two leaves swap their # left-right order), "high" (free tucking; leaf order kept per # row only). "on"/"compact" are accepted as legacy aliases of # low/high, legacy tidy_nest: "on" upgrades low to high, and # legacy symmetrize: "on" upgrades "off" to "symmetric" (both # below, in BaseGraph). new_params[key] = case value.to_s when "high", "compact" "high" when "medium" "medium" when "low", "on", "true" "low" when "symmetric" "symmetric" else "off" end when :tidy_nest, :symmetrize, :transparent, :polyline, :hide_default_connectors, :mirror, :derivation new_params[key] = switched_on?(value) when :color new_params[key] = case value.to_s when "modern", "on", "true" "modern" when "traditional" "traditional" when "gray", "grey" "gray" else "off" end when :hyphen new_params[key] = value.to_s == "literal" ? "literal" : "markup" when :fontsize new_params[key] = value.to_i when :linewidth new_params[key] = value.to_f when :vheight, :hspacing, :tidy_spacing new_params[key] = value.to_f when :fontstyle # Fonts are resolved by name through fontconfig (measurement via # Pango, rendering via the SVG font-family attribute), so all a # style needs is its family fallback chain. style = case value.to_s when "noto-sans-mono", "mono" then :mono when "noto-serif", "serif" then :serif when "cjk zenhei", "cjk" then :cjk else :sans end fontset[:family] = FontFamily.for_pango(style) new_params[:fontstyle] = style.to_s else new_params[key] = value end end # Legacy alias: tidy_spacing was the tidy-only horizontal gap factor # before it was generalized to hspacing (all layout modes). if (new_params[:hspacing].nil? || new_params[:hspacing] == 1.0) && new_params[:tidy_spacing] && new_params[:tidy_spacing] != 1.0 new_params[:hspacing] = new_params[:tidy_spacing] end # defaults to the following @params = DEFAULT_OPTS.dup @params.merge! new_params @params[:fontsize] = @params[:fontsize] * FONT_SCALING # fontset is populated above only when :fontstyle is passed explicitly; # fall back to the merged default style otherwise if fontset[:family].nil? fontset[:family] = FontFamily.for_pango(@params[:fontstyle]) end @params[:fontset] = fontset single_x_metrics = FontMetrics.get_metrics("X", fontset[:family], @params[:fontsize], :normal, :normal) @global = {} # A derivation is written down the page: the rule that joins the # premises is a horizontal line across them, and the result sits under # it. Laid out left to right there is nothing for that line to span, and # the drawing came out with rules struck through the categories. There # is no left-to-right convention for a derivation to fall back on, so # the combination is refused rather than approximated. if @params[:derivation] == true && @params[:direction] == "ltr" raise RSTError.new(+"Error: a derivation cannot be drawn left to right", code: :invalid_option, hint: "A derivation runs down the page. Use direction ttb or btt, " \ "or turn derivation off.", retryable: false) end # Hiding the default connectors draws them in the background colour # rather than skipping them. A derivation's rules are drawn as connectors # but they are the figure itself, not a default the drawing adds, so # hiding them leaves rows of categories floating with nothing joining # them. Refused for the same reason as left to right. if @params[:derivation] == true && @params[:hide_default_connectors] == true raise RSTError.new(+"Error: a derivation's rules cannot be hidden", code: :invalid_option, hint: "The rules are what a derivation is drawn with, not a " \ "connector added to it. Turn off hide default connectors, " \ "or turn derivation off.", retryable: false) end @global[:single_x_metrics] = single_x_metrics # A derivation labels each step with the rule it applied, written at the # right end of the line. Elements need to know, because the name is taken # out of the label before it is measured. @global[:derivation] = @params[:derivation] == true @global[:height_connector_to_text] = single_x_metrics.height / 2.0 @global[:single_line_height] = single_x_metrics.height * 2.0 @global[:width_half_x] = single_x_metrics.width / 2.0 @global[:height_connector] = single_x_metrics.height * @params[:vheight] # Horizontal counterpart of vheight: hspacing scales every horizontal # gap (sibling clearance in all layout modes, tidy minimum gap, # margins) the way vheight scales the vertical rhythm. @global[:h_gap_between_nodes] = single_x_metrics.width * 0.8 * (@params[:hspacing] || 1.0).to_f @global[:box_vertical_margin] = single_x_metrics.height * 0.8 # Every stroke follows the type size: linewidth 1 is 5% of it (the # ratio of an ordinary text rule, booktabs' \lightrulewidth), each # 0.5 step of the option adds another 2.5%, and a bold stroke adds # five percentage points. The old formula added absolute units # (linewidth + 1), so "1" actually meant 2 and small type got # disproportionately heavy lines. # Rounded, because these are written into the SVG as text and the # file is something people open and edit. Binary floating point turns # a line width of 1.5 into "2.4000000000000004" otherwise. @global[:stroke_normal] = (@params[:fontsize] * 0.05 * @params[:linewidth]).round(3) @global[:stroke_bold] = (@params[:fontsize] * (0.05 * @params[:linewidth] + 0.05)).round(3) # hyphen: literal swaps the two readings of - when a label is parsed. @global[:literal_hyphen] = @params[:hyphen] == "literal" end |
Class Method Details
.check_data(text, params = {}) ⇒ Object
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 |
# File 'lib/rsyntaxtree.rb', line 362 def self.check_data(text, params = {}) raise RSTError.new(+"Error: input text is empty", code: :empty_input, retryable: false) if text.to_s == "" begin StringParser.valid?(text) new(params.merge(data: text)).validate! rescue RSTError raise rescue StandardError => e # Callers of this are told they get a verdict, and machine callers # are told they get one in JSON. A defect in the drawing code is # still a verdict of "no", so it goes back in the same shape rather # than as a Ruby backtrace — named so it is not mistaken for a # mistake in the input. raise RSTError.new(+"Error: input could not be processed (#{e.class})", code: :internal_error, retryable: false) end end |
Instance Method Details
#draw_gif ⇒ Object
501 502 503 504 505 506 507 508 509 510 511 |
# File 'lib/rsyntaxtree.rb', line 501 def draw_gif with_rmagick do png_data = draw_png images = Magick::Image.from_blob(png_data) image = images.first image.format = 'GIF' blob = image.to_blob images.each(&:destroy!) blob end end |
#draw_jpg ⇒ Object
489 490 491 492 493 494 495 496 497 498 499 |
# File 'lib/rsyntaxtree.rb', line 489 def draw_jpg with_rmagick do png_data = draw_png images = Magick::Image.from_blob(png_data) image = images.first image.format = 'JPEG' blob = image.to_blob images.each(&:destroy!) blob end end |
#draw_lsif ⇒ Object
513 514 515 516 517 518 |
# File 'lib/rsyntaxtree.rb', line 513 def draw_lsif sp = StringParser.new(@params[:data].gsub('&', '&'), @params[:fontset], @params[:fontsize], @global) sp.parse graph = LsifGraph.new(sp.get_elementlist, @params, @global) graph.lsif_data end |
#draw_pdf(binary = false) ⇒ Object
453 454 455 456 457 458 459 460 461 462 463 464 465 466 |
# File 'lib/rsyntaxtree.rb', line 453 def draw_pdf(binary = false) surface = nil context = nil b = nil b = StringIO.new rsvg, surface = pdf_surface_for(draw_svg, b) context = Cairo::Context.new(surface) context.render_rsvg_handle(rsvg) surface.finish binary ? b : b.string ensure b&.close unless binary context&.destroy end |
#draw_png(binary = false) ⇒ Object
437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 |
# File 'lib/rsyntaxtree.rb', line 437 def draw_png(binary = false) surface = nil context = nil b = nil rsvg, surface = raster_surface_for(draw_svg) context = Cairo::Context.new(surface) context.render_rsvg_handle(rsvg) b = StringIO.new surface.write_to_png(b) binary ? b : b.string ensure b&.close unless binary surface&.finish context&.destroy end |
#draw_svg ⇒ Object
468 469 470 471 472 473 |
# File 'lib/rsyntaxtree.rb', line 468 def draw_svg sp = StringParser.new(@params[:data].gsub('&', '&'), @params[:fontset], @params[:fontsize], @global) sp.parse graph = SVGGraph.new(sp.get_elementlist, @params, @global) graph.svg_data end |
#draw_tikz(standalone: false, font: nil) ⇒ Object
520 521 522 523 524 525 |
# File 'lib/rsyntaxtree.rb', line 520 def draw_tikz(standalone: false, font: nil) sp = StringParser.new(@params[:data].gsub('&', '&'), @params[:fontset], @params[:fontsize], @global) sp.parse generator = TikZGenerator.new(sp.get_elementlist, @params) generator.generate(standalone: standalone, font: font) end |
#pdf_surface_for(svg, target) ⇒ Object
The same for PDF, which in practice refuses nothing: a page 400,000 points wide is made without complaint where a raster surface stops at 32,767. Kept in the same shape as the raster path so that validation asks the same question of both, and so a future Cairo that does refuse a page size is heard.
427 428 429 430 431 432 433 434 435 |
# File 'lib/rsyntaxtree.rb', line 427 def pdf_surface_for(svg, target) rsvg = RSVG::Handle.new_from_data(svg) dim = rsvg.dimensions surface = Cairo::PDFSurface.new(target, dim.width, dim.height) yield surface if block_given? [rsvg, surface] rescue Cairo::InvalidSize raise RSTError.new(+"Error: the result syntree is too big", code: :result_too_big, retryable: false) end |
#raster_surface_for(svg) ⇒ Object
The surface a raster format needs. Making it is where a tree too big to draw is found out — Cairo says so, nothing here knows the limit — and it is cheap next to painting the tree onto it, which is why validation makes one and stops there.
412 413 414 415 416 417 418 419 420 |
# File 'lib/rsyntaxtree.rb', line 412 def raster_surface_for(svg) rsvg = RSVG::Handle.new_from_data(svg) dim = rsvg.dimensions surface = Cairo::ImageSurface.new(Cairo::FORMAT_ARGB32, dim.width, dim.height) yield surface if block_given? [rsvg, surface] rescue Cairo::InvalidSize raise RSTError.new(+"Error: the result syntree is too big", code: :result_too_big, retryable: false) end |
#switched_on?(value) ⇒ Boolean
356 357 358 359 360 |
# File 'lib/rsyntaxtree.rb', line 356 def switched_on?(value) return false if value.nil? || value == false !OFF.include?(value.to_s.strip.downcase) end |
#validate! ⇒ Object
Generate, and throw the result away. Parsing alone leaves out the checks that only happen once the tree is laid out — a movement path with one end, a line with three — so validation that stopped at the parser passed input the drawing then rejected, which is the failure this validation exists to prevent.
Which generation depends on the format asked for, because the formats can refuse different things: a tree can be too wide for a raster surface while remaining a perfectly good SVG, and JPG and GIF need a gem that may not be installed. Everything up to the last point where a format is known to say no is done; painting the tree onto the surface, which is most of the cost and refuses nothing this knows of, is not. A surface inside Cairo's limits but large enough to exhaust memory would still fail at that painting, so this is where validation is a strong guess rather than a guarantee.
396 397 398 399 400 401 402 403 404 405 406 |
# File 'lib/rsyntaxtree.rb', line 396 def validate! case @params[:format] when "png" then raster_surface_for(draw_svg, &:finish) when "jpg", "gif" then with_rmagick { raster_surface_for(draw_svg, &:finish) } when "pdf" then pdf_surface_for(draw_svg, StringIO.new, &:finish) when "lsif" then draw_lsif when "tikz" then draw_tikz else draw_svg end true end |
#with_rmagick ⇒ Object
JPG and GIF output converts the PNG through RMagick. The require is lazy: both formats are deprecated and will be removed in 2.0, and the library must load without RMagick for every other format. A missing RMagick is reported as an input-level error, not a bare LoadError.
479 480 481 482 483 484 485 486 487 |
# File 'lib/rsyntaxtree.rb', line 479 def with_rmagick require 'rmagick' yield rescue LoadError raise RSTError.new(+"Error: JPG/GIF output requires ImageMagick and the rmagick gem, " \ "which is not installed. Use PNG instead — JPG and GIF support " \ "is deprecated and will be removed in 2.0.", code: :missing_dependency, retryable: false) end |