1
1
mirror of https://github.com/exyte/Macaw.git synced 2024-09-21 01:47:44 +03:00
Macaw/Source/svg/SVGParser.swift

1731 lines
68 KiB
Swift
Raw Normal View History

2016-04-21 12:06:16 +03:00
import Foundation
import CoreGraphics
2016-04-21 12:06:16 +03:00
#if !CARTHAGE
2018-04-04 17:59:28 +03:00
import SWXMLHash
#endif
2016-08-16 16:45:09 +03:00
///
/// This class used to parse SVG file and build corresponding Macaw scene
///
open class SVGParser {
2017-10-19 11:09:09 +03:00
2016-11-24 13:45:16 +03:00
/// Parse an SVG file identified by the specified bundle, name and file extension.
/// - returns: Root node of the corresponding Macaw scene.
open class func parse(bundle: Bundle, path: String, ofType: String = "svg") throws -> Node {
2017-05-14 20:36:34 +03:00
guard let fullPath = bundle.path(forResource: path, ofType: ofType) else {
throw SVGParserError.noSuchFile(path: "\(path).\(ofType)")
}
let text = try String(contentsOfFile: fullPath, encoding: String.Encoding.utf8)
return try SVGParser.parse(text: text)
2016-11-24 13:45:16 +03:00
}
2017-10-19 11:09:09 +03:00
2016-11-24 13:45:16 +03:00
/// Parse an SVG file identified by the specified name and file extension.
/// - returns: Root node of the corresponding Macaw scene.
open class func parse(path: String, ofType: String = "svg") throws -> Node {
return try SVGParser.parse(bundle: Bundle.main, path: path, ofType: ofType)
2016-11-24 13:45:16 +03:00
}
2017-10-19 11:09:09 +03:00
2016-11-24 13:45:16 +03:00
/// Parse the specified content of an SVG file.
/// - returns: Root node of the corresponding Macaw scene.
open class func parse(text: String) throws -> Node {
2016-11-24 13:45:16 +03:00
return SVGParser(text).parse()
}
2017-10-19 11:09:09 +03:00
let availableStyleAttributes = ["stroke", "stroke-width", "stroke-opacity", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit",
2018-06-07 13:42:57 +03:00
"fill", "fill-rule", "fill-opacity", "clip-path", "mask",
"opacity", "color", "stop-color", "stop-opacity",
"font-family", "font-size", "font-weight", "text-anchor",
"visibility"]
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
fileprivate let xmlString: String
fileprivate let initialPosition: Transform
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
fileprivate var nodes = [Node]()
2017-12-20 11:46:33 +03:00
fileprivate var defNodes = [String: XMLIndexer]()
2017-05-14 20:36:34 +03:00
fileprivate var defFills = [String: Fill]()
2018-06-14 13:26:22 +03:00
fileprivate var defMasks = [String: UserSpaceNode]()
2018-06-06 07:06:20 +03:00
fileprivate var defClip = [String: UserSpaceLocus]()
fileprivate var defEffects = [String: Effect]()
2017-05-14 20:36:34 +03:00
fileprivate enum PathCommandType {
case moveTo
case lineTo
case lineV
case lineH
case curveTo
case smoothCurveTo
case closePath
case none
}
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
fileprivate typealias PathCommand = (type: PathCommandType, expression: String, absolute: Bool)
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
fileprivate init(_ string: String, pos: Transform = Transform()) {
self.xmlString = string
self.initialPosition = pos
}
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
fileprivate func parse() -> Group {
let parsedXml = SWXMLHash.parse(xmlString)
2018-05-16 19:40:04 +03:00
2018-05-07 12:14:06 +03:00
var layout: NodeLayout?
2018-04-03 09:17:43 +03:00
for child in parsedXml.children {
if let element = child.element {
if element.name == "svg" {
2018-05-07 11:26:05 +03:00
layout = parseViewBox(element)
2018-04-03 09:17:43 +03:00
prepareSvg(child.children)
break
}
}
}
parseSvg(parsedXml.children)
2018-05-16 19:40:04 +03:00
2018-05-07 11:26:05 +03:00
if let layout = layout {
return SVGCanvas(layout: layout, contents: nodes)
2018-04-03 09:17:43 +03:00
}
2018-04-13 07:13:58 +03:00
return Group(contents: nodes)
2017-05-14 20:36:34 +03:00
}
2018-05-16 19:40:04 +03:00
fileprivate func prepareSvg(_ children: [XMLIndexer]) {
children.forEach { child in
2018-04-03 09:17:43 +03:00
prepareSvg(child)
}
}
2018-04-04 17:59:28 +03:00
fileprivate func prepareSvg(_ node: XMLIndexer) {
if let element = node.element {
2018-05-16 19:40:04 +03:00
if element.name == "defs" {
parseDefinitions(node)
2018-05-16 19:40:04 +03:00
} else if element.name == "style" {
parseStyle(node)
2018-05-16 19:40:04 +03:00
} else if element.name == "g" {
node.children.forEach { child in
prepareSvg(child)
}
}
}
}
fileprivate func parseSvg(_ children: [XMLIndexer]) {
2017-05-14 20:36:34 +03:00
children.forEach { child in
if let element = child.element {
if element.name == "svg" {
parseSvg(child.children)
2017-05-14 20:36:34 +03:00
} else if let node = parseNode(child) {
self.nodes.append(node)
}
}
}
}
2018-05-16 19:40:04 +03:00
2018-06-26 13:17:37 +03:00
fileprivate func parseViewBox(_ element: SWXMLHash.XMLElement) -> SVGNodeLayout? {
if element.allAttributes["width"] == nil && element.allAttributes["height"] == nil && element.allAttributes["viewBox"] == nil {
return .none
}
let w = getDimensionValue(element, attribute: "width") ?? SVGLength(percent: 100)
let h = getDimensionValue(element, attribute: "height") ?? SVGLength(percent: 100)
let svgSize = SVGSize(width: w, height: h)
2018-05-16 19:40:04 +03:00
var viewBox: Rect?
if let viewBoxString = element.allAttributes["viewBox"]?.text {
2018-05-16 19:40:04 +03:00
let nums = viewBoxString.components(separatedBy: .whitespaces).map { Double($0) }
if nums.count == 4, let x = nums[0], let y = nums[1], let w = nums[2], let h = nums[3] {
viewBox = Rect(x: x, y: y, w: w, h: h)
}
}
2018-05-16 19:40:04 +03:00
var xAligningMode, yAligningMode: Align?
var scalingMode: AspectRatio?
if let contentModeString = element.allAttributes["preserveAspectRatio"]?.text {
let strings = contentModeString.components(separatedBy: CharacterSet(charactersIn: " "))
if strings.count == 1 { // none
scalingMode = parseAspectRatio(strings[0])
return SVGNodeLayout(svgSize: svgSize, viewBox: viewBox, scaling: scalingMode)
}
guard strings.count == 2 else { fatalError("Invalid content mode") }
2018-05-16 19:40:04 +03:00
let alignString = strings[0]
var xAlign = alignString.prefix(4).lowercased()
xAlign.remove(at: xAlign.startIndex)
xAligningMode = parseAlign(xAlign)
2018-05-16 19:40:04 +03:00
var yAlign = alignString.suffix(4).lowercased()
yAlign.remove(at: yAlign.startIndex)
yAligningMode = parseAlign(yAlign)
2018-05-16 19:40:04 +03:00
scalingMode = parseAspectRatio(strings[1])
}
2018-05-16 19:40:04 +03:00
return SVGNodeLayout(svgSize: svgSize, viewBox: viewBox, scaling: scalingMode, xAlign: xAligningMode, yAlign: yAligningMode)
}
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
fileprivate func parseNode(_ node: XMLIndexer, groupStyle: [String: String] = [:]) -> Node? {
var result: Node? = nil
2017-05-14 20:36:34 +03:00
if let element = node.element {
2018-05-16 19:40:04 +03:00
switch element.name {
case "g":
result = parseGroup(node, groupStyle: groupStyle)
case "clipPath":
if let id = element.allAttributes["id"]?.text, let clip = parseClip(node) {
self.defClip[id] = clip
}
case "style", "defs":
// do nothing - it was parsed on first iteration
return .none
default:
result = parseElement(node, groupStyle: groupStyle)
}
if let result = result, let filterString = element.allAttributes["filter"]?.text ?? groupStyle["filter"], let filterId = parseIdFromUrl(filterString), let effect = defEffects[filterId] {
result.effect = effect
2017-05-14 20:36:34 +03:00
}
}
return result
2017-05-14 20:36:34 +03:00
}
2017-10-19 11:09:09 +03:00
fileprivate var styleTable: [String: [String: String]] = [:]
fileprivate func parseStyle(_ styleNode: XMLIndexer) {
if let rawStyle = styleNode.element?.text {
var styleAttributes: [String: String] = [:]
let parts = rawStyle.trimmingCharacters(in: .whitespacesAndNewlines).split(separator: "{")
2017-10-03 13:11:13 +03:00
if parts.count == 2 {
let className = String(parts[0].dropFirst())
if !className.isEmpty {
let style = String(parts[1].dropLast())
let styleParts = style.replacingOccurrences(of: " ", with: "").components(separatedBy: ";")
styleParts.forEach { styleAttribute in
let currentStyle = styleAttribute.components(separatedBy: ":")
if currentStyle.count == 2 {
styleAttributes.updateValue(currentStyle[1], forKey: currentStyle[0])
}
}
styleTable[className] = styleAttributes
}
}
}
}
2018-04-18 13:29:28 +03:00
fileprivate func parseDefinitions(_ defs: XMLIndexer, groupStyle: [String: String] = [:]) {
defs.children.forEach(parseDefinition(_:))
}
2018-05-16 19:40:04 +03:00
private func parseDefinition(_ child: XMLIndexer) {
guard let id = child.element?.allAttributes["id"]?.text, let element = child.element else {
return
}
if element.name == "fill", let fill = parseFill(child) {
defFills[id] = fill
} else if element.name == "mask", let mask = parseMask(child) {
defMasks[id] = mask
} else if element.name == "filter", let effect = parseEffect(child) {
defEffects[id] = effect
} else if element.name == "clip", let clip = parseClip(child) {
defClip[id] = clip
} else if let _ = parseNode(child) {
// TODO we don't really need to parse node
defNodes[id] = child
2017-05-14 20:36:34 +03:00
}
}
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
fileprivate func parseElement(_ node: XMLIndexer, groupStyle: [String: String] = [:]) -> Node? {
2018-05-16 19:40:04 +03:00
guard let element = node.element else {
return .none
}
let nodeStyle = getStyleAttributes(groupStyle, element: element)
if nodeStyle["display"] == "none" {
return .none
}
if nodeStyle["visibility"] == "hidden" {
return .none
}
2018-05-16 19:40:04 +03:00
guard let parsedNode = parseElementInternal(node, groupStyle: nodeStyle) else {
return .none
}
return parsedNode
}
fileprivate func parseElementInternal(_ node: XMLIndexer, groupStyle: [String: String] = [:]) -> Node? {
2018-05-16 19:40:04 +03:00
guard let element = node.element else {
return .none
}
let id = node.element?.allAttributes["id"]?.text
let styleAttributes = groupStyle
let position = getPosition(element)
switch element.name {
case "path":
2018-04-26 12:03:09 +03:00
if var path = parsePath(node) {
if let rule = getFillRule(styleAttributes) {
path = Path(segments: path.segments, fillRule: rule)
}
2018-06-14 13:26:22 +03:00
return Shape(form: path, fill: getFillColor(styleAttributes, groupStyle: styleAttributes), stroke: getStroke(styleAttributes, groupStyle: styleAttributes), place: position, opacity: getOpacity(styleAttributes), clip: getClipPath(styleAttributes, locus: path), mask: getMask(styleAttributes, locus: path), tag: getTag(element))
}
case "line":
if let line = parseLine(node) {
2018-06-14 13:26:22 +03:00
return Shape(form: line, fill: getFillColor(styleAttributes, groupStyle: styleAttributes), stroke: getStroke(styleAttributes, groupStyle: styleAttributes), place: position, opacity: getOpacity(styleAttributes), clip: getClipPath(styleAttributes, locus: line), mask: getMask(styleAttributes, locus: line), tag: getTag(element))
}
case "rect":
if let rect = parseRect(node) {
2018-06-14 13:26:22 +03:00
return Shape(form: rect, fill: getFillColor(styleAttributes, groupStyle: styleAttributes), stroke: getStroke(styleAttributes, groupStyle: styleAttributes), place: position, opacity: getOpacity(styleAttributes), clip: getClipPath(styleAttributes, locus: rect), mask: getMask(styleAttributes, locus: rect), tag: getTag(element))
}
case "circle":
if let circle = parseCircle(node) {
2018-06-14 13:26:22 +03:00
return Shape(form: circle, fill: getFillColor(styleAttributes, groupStyle: styleAttributes), stroke: getStroke(styleAttributes, groupStyle: styleAttributes), place: position, opacity: getOpacity(styleAttributes), clip: getClipPath(styleAttributes, locus: circle), mask: getMask(styleAttributes, locus: circle), tag: getTag(element))
2017-05-14 20:36:34 +03:00
}
case "ellipse":
if let ellipse = parseEllipse(node) {
2018-06-14 13:26:22 +03:00
return Shape(form: ellipse, fill: getFillColor(styleAttributes, groupStyle: styleAttributes), stroke: getStroke(styleAttributes, groupStyle: styleAttributes), place: position, opacity: getOpacity(styleAttributes), clip: getClipPath(styleAttributes, locus: ellipse), mask: getMask(styleAttributes, locus: ellipse), tag: getTag(element))
}
case "polygon":
if let polygon = parsePolygon(node) {
2018-06-14 13:26:22 +03:00
return Shape(form: polygon, fill: getFillColor(styleAttributes, groupStyle: styleAttributes), stroke: getStroke(styleAttributes, groupStyle: styleAttributes), place: position, opacity: getOpacity(styleAttributes), clip: getClipPath(styleAttributes, locus: polygon), mask: getMask(styleAttributes, locus: polygon), tag: getTag(element))
}
case "polyline":
if let polyline = parsePolyline(node) {
2018-06-14 13:26:22 +03:00
return Shape(form: polyline, fill: getFillColor(styleAttributes, groupStyle: styleAttributes), stroke: getStroke(styleAttributes, groupStyle: styleAttributes), place: position, opacity: getOpacity(styleAttributes), clip: getClipPath(styleAttributes, locus: polyline), mask: getMask(styleAttributes, locus: polyline), tag: getTag(element))
}
case "image":
2018-06-07 09:35:06 +03:00
return parseImage(node, opacity: getOpacity(styleAttributes), pos: position, clip: getClipPath(styleAttributes, locus: nil))
case "text":
return parseText(node, textAnchor: getTextAnchor(styleAttributes), fill: getFillColor(styleAttributes, groupStyle: styleAttributes),
stroke: getStroke(styleAttributes, groupStyle: styleAttributes), opacity: getOpacity(styleAttributes), fontName: getFontName(styleAttributes), fontSize: getFontSize(styleAttributes), fontWeight: getFontWeight(styleAttributes), pos: position)
case "use":
return parseUse(node, groupStyle: styleAttributes, place: position)
case "linearGradient", "radialGradient", "fill":
if let fill = parseFill(node), let id = id {
defFills[id] = fill
}
case "filter":
if let effect = parseEffect(node), let id = id {
defEffects[id] = effect
}
case "mask":
if let mask = parseMask(node), let id = id {
defMasks[id] = mask
}
case "title":
break
default:
print("SVG parsing error. Shape \(element.name) not supported")
return .none
2017-05-14 20:36:34 +03:00
}
2017-05-14 20:36:34 +03:00
return .none
}
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
fileprivate func parseFill(_ fill: XMLIndexer) -> Fill? {
guard let element = fill.element else {
return .none
}
2018-04-18 13:29:28 +03:00
let style = getStyleAttributes([:], element: element)
2017-05-14 20:36:34 +03:00
switch element.name {
case "linearGradient":
2018-04-18 13:29:28 +03:00
return parseLinearGradient(fill, groupStyle: style)
2017-05-14 20:36:34 +03:00
case "radialGradient":
2018-04-18 13:29:28 +03:00
return parseRadialGradient(fill, groupStyle: style)
2017-05-14 20:36:34 +03:00
default:
return .none
}
}
2018-04-04 17:59:28 +03:00
2018-03-28 10:15:19 +03:00
fileprivate func parseGroup(_ group: XMLIndexer, groupStyle: [String: String] = [:]) -> Group? {
2017-05-14 20:36:34 +03:00
guard let element = group.element else {
return .none
}
var groupNodes: [Node] = []
let style = getStyleAttributes(groupStyle, element: element)
group.children.forEach { child in
2018-03-28 10:15:19 +03:00
if let node = parseNode(child, groupStyle: style) {
2017-05-14 20:36:34 +03:00
groupNodes.append(node)
}
}
2018-06-14 13:26:22 +03:00
return Group(contents: groupNodes, place: getPosition(element), tag: getTag(element))
2016-12-16 15:40:47 +03:00
}
2017-10-19 11:09:09 +03:00
fileprivate func getPosition(_ element: SWXMLHash.XMLElement) -> Transform {
2017-05-14 20:36:34 +03:00
guard let transformAttribute = element.allAttributes["transform"]?.text else {
2017-12-20 11:46:33 +03:00
return Transform.identity
2017-05-14 20:36:34 +03:00
}
return parseTransformationAttribute(transformAttribute)
}
2018-05-16 19:40:04 +03:00
2018-04-03 09:17:43 +03:00
fileprivate func parseAlign(_ string: String) -> Align {
if string == "min" {
return .min
}
if string == "mid" {
return .mid
}
return .max
}
2018-05-16 19:40:04 +03:00
2018-04-03 09:17:43 +03:00
fileprivate func parseAspectRatio(_ string: String) -> AspectRatio {
if string == "meet" {
return .meet
}
if string == "slice" {
return .slice
}
return .none
}
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
var count = 0
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
fileprivate func parseTransformationAttribute(_ attributes: String, transform: Transform = Transform()) -> Transform {
guard let matcher = SVGParserRegexHelper.getTransformAttributeMatcher() else {
return transform
}
2018-05-16 19:40:04 +03:00
let attributes = attributes.replacingOccurrences(of: "\n", with: "")
2017-05-14 20:36:34 +03:00
var finalTransform = transform
2017-11-29 10:24:00 +03:00
let fullRange = NSRange(location: 0, length: attributes.count)
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
if let matchedAttribute = matcher.firstMatch(in: attributes, options: .reportCompletion, range: fullRange) {
2017-10-19 11:09:09 +03:00
2017-08-28 10:56:52 +03:00
let attributeName = (attributes as NSString).substring(with: matchedAttribute.range(at: 1))
let values = parseTransformValues((attributes as NSString).substring(with: matchedAttribute.range(at: 2)))
2017-05-14 20:36:34 +03:00
if values.isEmpty {
return transform
}
switch attributeName {
case "translate":
if let x = Double(values[0]) {
var y: Double = 0
if values.indices.contains(1) {
y = Double(values[1]) ?? 0
}
finalTransform = transform.move(dx: x, dy: y)
}
case "scale":
if let x = Double(values[0]) {
var y: Double = x
if values.indices.contains(1) {
y = Double(values[1]) ?? x
}
finalTransform = transform.scale(sx: x, sy: y)
}
case "rotate":
if let angle = Double(values[0]) {
if values.count == 1 {
finalTransform = transform.rotate(angle: degreesToRadians(angle))
} else if values.count == 3 {
if let x = Double(values[1]), let y = Double(values[2]) {
finalTransform = transform.move(dx: x, dy: y).rotate(angle: degreesToRadians(angle)).move(dx: -x, dy: -y)
}
}
}
case "skewX":
if let x = Double(values[0]) {
2017-10-16 12:23:35 +03:00
let v = tan((x * Double.pi) / 180.0)
finalTransform = transform.shear(shx: v, shy: 0)
2017-05-14 20:36:34 +03:00
}
case "skewY":
if let y = Double(values[0]) {
2017-10-16 12:23:35 +03:00
let y = tan((y * Double.pi) / 180.0)
2017-05-14 20:36:34 +03:00
finalTransform = transform.shear(shx: 0, shy: y)
}
case "matrix":
if values.count != 6 {
return transform
}
if let m11 = Double(values[0]), let m12 = Double(values[1]),
let m21 = Double(values[2]), let m22 = Double(values[3]),
let dx = Double(values[4]), let dy = Double(values[5]) {
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
let transformMatrix = Transform(m11: m11, m12: m12, m21: m21, m22: m22, dx: dx, dy: dy)
2018-06-13 11:11:08 +03:00
finalTransform = transform.concat(with: transformMatrix)
2017-05-14 20:36:34 +03:00
}
2017-10-19 11:09:09 +03:00
default:
break
2017-05-14 20:36:34 +03:00
}
let rangeToRemove = NSRange(location: 0, length: matchedAttribute.range.location + matchedAttribute.range.length)
let newAttributeString = (attributes as NSString).replacingCharacters(in: rangeToRemove, with: "")
return parseTransformationAttribute(newAttributeString, transform: finalTransform)
} else {
return transform
}
}
2017-10-19 11:09:09 +03:00
/// Parse an RGB
/// - returns: Color for the corresponding SVG color string in RGB notation.
fileprivate func parseRGBNotation(colorString: String) -> Color {
2017-11-29 10:24:00 +03:00
let from = colorString.index(colorString.startIndex, offsetBy: 4)
let inPercentage = colorString.contains("%")
let sp = String(colorString.suffix(from: from))
.replacingOccurrences(of: "%", with: "")
.replacingOccurrences(of: ")", with: "")
.replacingOccurrences(of: " ", with: "")
let x = sp.components(separatedBy: ",")
var red = 0.0
var green = 0.0
var blue = 0.0
2017-10-19 11:09:09 +03:00
if x.count == 3 {
2017-08-16 10:16:18 +03:00
if let r = Double(x[0]), let g = Double(x[1]), let b = Double(x[2]) {
blue = b
green = g
red = r
}
}
if inPercentage {
red *= 2.55
green *= 2.55
blue *= 2.55
}
return Color.rgb(r: Int(red.rounded(.up)),
g: Int(green.rounded(.up)),
b: Int(blue.rounded(.up)))
}
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
fileprivate func parseTransformValues(_ values: String, collectedValues: [String] = []) -> [String] {
guard let matcher = SVGParserRegexHelper.getTransformMatcher() else {
return collectedValues
}
var updatedValues: [String] = collectedValues
2017-11-29 10:24:00 +03:00
let fullRange = NSRange(location: 0, length: values.count)
2017-05-14 20:36:34 +03:00
if let matchedValue = matcher.firstMatch(in: values, options: .reportCompletion, range: fullRange) {
let value = (values as NSString).substring(with: matchedValue.range)
updatedValues.append(value)
let rangeToRemove = NSRange(location: 0, length: matchedValue.range.location + matchedValue.range.length)
let newValues = (values as NSString).replacingCharacters(in: rangeToRemove, with: "")
return parseTransformValues(newValues, collectedValues: updatedValues)
}
return updatedValues
}
2017-10-19 11:09:09 +03:00
fileprivate func getStyleAttributes(_ groupAttributes: [String: String], element: SWXMLHash.XMLElement) -> [String: String] {
2017-05-14 20:36:34 +03:00
var styleAttributes: [String: String] = groupAttributes
2017-12-20 19:18:00 +03:00
if let className = element.allAttributes["class"]?.text, let styleAttributesFromTable = styleTable[className] {
for (att, val) in styleAttributesFromTable {
if styleAttributes.index(forKey: att) == nil {
styleAttributes.updateValue(val, forKey: att)
}
}
}
2017-05-14 20:36:34 +03:00
if let style = element.allAttributes["style"]?.text {
let styleParts = style.replacingOccurrences(of: " ", with: "").components(separatedBy: ";")
styleParts.forEach { styleAttribute in
let currentStyle = styleAttribute.components(separatedBy: ":")
if currentStyle.count == 2 {
styleAttributes.updateValue(currentStyle[1], forKey: currentStyle[0])
}
}
}
2017-12-20 19:18:00 +03:00
self.availableStyleAttributes.forEach { availableAttribute in
2018-04-18 13:29:28 +03:00
if let styleAttribute = element.allAttributes[availableAttribute]?.text, styleAttribute != "inherit" {
2017-12-20 19:18:00 +03:00
styleAttributes.updateValue(styleAttribute, forKey: availableAttribute)
}
}
2017-12-20 19:18:00 +03:00
2017-05-14 20:36:34 +03:00
return styleAttributes
}
2017-10-19 11:09:09 +03:00
fileprivate func createColorFromHex(_ hexString: String, opacity: Double = 1) -> Color {
2017-05-14 20:36:34 +03:00
var cleanedHexString = hexString
if hexString.hasPrefix("#") {
cleanedHexString = hexString.replacingOccurrences(of: "#", with: "")
}
2017-11-29 10:24:00 +03:00
if cleanedHexString.count == 3 {
let x = Array(cleanedHexString)
cleanedHexString = "\(x[0])\(x[0])\(x[1])\(x[1])\(x[2])\(x[2])"
}
2017-10-19 11:09:09 +03:00
var rgbValue: UInt32 = 0
Scanner(string: cleanedHexString).scanHexInt32(&rgbValue)
2017-10-19 11:09:09 +03:00
let red = CGFloat((rgbValue >> 16) & 0xff)
let green = CGFloat((rgbValue >> 08) & 0xff)
let blue = CGFloat((rgbValue >> 00) & 0xff)
2017-10-19 11:09:09 +03:00
return Color.rgba(r: Int(red), g: Int(green), b: Int(blue), a: opacity)
2017-05-14 20:36:34 +03:00
}
2017-10-19 11:09:09 +03:00
fileprivate func createColor(_ colorString: String, opacity: Double = 1) -> Color? {
if colorString == "none" || colorString == "transparent" {
return .none
}
let opacity = min(max(opacity, 0), 1)
if let defaultColor = SVGConstants.colorList[colorString] {
let color = Color(val: defaultColor)
return opacity != 1 ? color.with(a: opacity) : color
}
if colorString.hasPrefix("rgb") {
let color = parseRGBNotation(colorString: colorString)
return opacity != 1 ? color.with(a: opacity) : color
}
return createColorFromHex(colorString, opacity: opacity)
}
2018-04-18 13:29:28 +03:00
fileprivate func getFillColor(_ styleParts: [String: String], groupStyle: [String: String] = [:]) -> Fill? {
var opacity: Double = 1
if let fillOpacity = styleParts["fill-opacity"] {
opacity = Double(fillOpacity.replacingOccurrences(of: " ", with: "")) ?? 1
}
2018-04-18 13:29:28 +03:00
guard var fillColor = styleParts["fill"] else {
return Color.black.with(a: opacity)
2017-05-14 20:36:34 +03:00
}
if let colorId = parseIdFromUrl(fillColor) {
return defFills[colorId]
2017-05-14 20:36:34 +03:00
}
2018-04-18 13:29:28 +03:00
if fillColor == "currentColor", let currentColor = groupStyle["color"] {
fillColor = currentColor
}
return createColor(fillColor.replacingOccurrences(of: " ", with: ""), opacity: opacity)
2017-05-14 20:36:34 +03:00
}
2017-10-19 11:09:09 +03:00
2018-04-18 13:29:28 +03:00
fileprivate func getStroke(_ styleParts: [String: String], groupStyle: [String: String] = [:]) -> Stroke? {
guard var strokeColor = styleParts["stroke"] else {
2017-05-14 20:36:34 +03:00
return .none
}
2018-04-18 13:29:28 +03:00
if strokeColor == "currentColor", let currentColor = groupStyle["color"] {
strokeColor = currentColor
}
2017-05-14 20:36:34 +03:00
var opacity: Double = 1
if let strokeOpacity = styleParts["stroke-opacity"] {
opacity = Double(strokeOpacity.replacingOccurrences(of: " ", with: "")) ?? 1
2018-05-07 14:29:31 +03:00
opacity = min(max(opacity, 0), 1)
2017-05-14 20:36:34 +03:00
}
var fill: Fill?
if let colorId = parseIdFromUrl(strokeColor) {
fill = defFills[colorId]
2017-05-14 20:36:34 +03:00
} else {
fill = createColor(strokeColor.replacingOccurrences(of: " ", with: ""), opacity: opacity)
}
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
if let strokeFill = fill {
return Stroke(fill: strokeFill,
width: getStrokeWidth(styleParts),
cap: getStrokeCap(styleParts),
join: getStrokeJoin(styleParts),
miterLimit: getStrokeMiterLimit(styleParts),
dashes: getStrokeDashes(styleParts),
offset: getStrokeOffset(styleParts))
2017-05-14 20:36:34 +03:00
}
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
return .none
}
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
fileprivate func getStrokeWidth(_ styleParts: [String: String]) -> Double {
2018-04-28 09:29:46 +03:00
if let strokeWidth = styleParts["stroke-width"], let value = doubleFromString(strokeWidth) {
return value
2017-05-14 20:36:34 +03:00
}
2016-12-16 16:04:36 +03:00
return 1
2017-05-14 20:36:34 +03:00
}
2017-10-19 11:09:09 +03:00
fileprivate func getStrokeMiterLimit(_ styleParts: [String: String]) -> Double {
if let strokeWidth = styleParts["stroke-miterlimit"], let value = doubleFromString(strokeWidth) {
return value
}
return 4
}
2017-05-14 20:36:34 +03:00
fileprivate func getStrokeCap(_ styleParts: [String: String]) -> LineCap {
var cap = LineCap.butt
2017-05-14 20:36:34 +03:00
if let strokeCap = styleParts["stroke-linecap"] {
switch strokeCap {
case "round":
cap = .round
2017-05-14 20:36:34 +03:00
case "butt":
cap = .butt
case "square":
cap = .square
default:
break
}
}
return cap
}
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
fileprivate func getStrokeJoin(_ styleParts: [String: String]) -> LineJoin {
var join = LineJoin.miter
if let strokeJoin = styleParts["stroke-linejoin"] {
switch strokeJoin {
case "round":
join = .round
2017-05-14 20:36:34 +03:00
case "miter":
join = .miter
case "bevel":
join = .bevel
default:
break
}
}
return join
}
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
fileprivate func getStrokeDashes(_ styleParts: [String: String]) -> [Double] {
var dashes = [Double]()
if let strokeDashes = styleParts["stroke-dasharray"] {
2018-05-25 12:11:47 +03:00
let separatedValues = strokeDashes.components(separatedBy: CharacterSet(charactersIn: " ,"))
2017-05-14 20:36:34 +03:00
separatedValues.forEach { value in
if let doubleValue = doubleFromString(value) {
2017-05-14 20:36:34 +03:00
dashes.append(doubleValue)
}
}
}
return dashes
}
2018-05-16 19:40:04 +03:00
2018-05-25 12:11:47 +03:00
fileprivate func getMatrix(_ element: SWXMLHash.XMLElement, attribute: String) -> [Double] {
var result = [Double]()
if let values = element.allAttributes[attribute]?.text {
let separatedValues = values.components(separatedBy: CharacterSet(charactersIn: " ,"))
separatedValues.forEach { value in
if let doubleValue = doubleFromString(value) {
result.append(doubleValue)
}
}
}
return result
}
2018-05-16 19:40:04 +03:00
fileprivate func getStrokeOffset(_ styleParts: [String: String]) -> Double {
2018-06-27 10:10:25 +03:00
if let strokeOffset = styleParts["stroke-dashoffset"], let offset = doubleFromString(strokeOffset) {
return offset
}
return 0
}
2017-10-19 11:09:09 +03:00
fileprivate func getTag(_ element: SWXMLHash.XMLElement) -> [String] {
2017-05-14 20:36:34 +03:00
let id = element.allAttributes["id"]?.text
return id != nil ? [id!] : []
}
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
fileprivate func getOpacity(_ styleParts: [String: String]) -> Double {
if let opacityAttr = styleParts["opacity"] {
return Double(opacityAttr.replacingOccurrences(of: " ", with: "")) ?? 1
}
return 1
}
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
fileprivate func parseLine(_ line: XMLIndexer) -> Line? {
guard let element = line.element else {
return .none
}
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
return Line(x1: getDoubleValue(element, attribute: "x1") ?? 0,
y1: getDoubleValue(element, attribute: "y1") ?? 0,
x2: getDoubleValue(element, attribute: "x2") ?? 0,
y2: getDoubleValue(element, attribute: "y2") ?? 0)
}
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
fileprivate func parseRect(_ rect: XMLIndexer) -> Locus? {
guard let element = rect.element,
let width = getDoubleValue(element, attribute: "width"),
2017-10-19 11:09:09 +03:00
let height = getDoubleValue(element, attribute: "height"), width > 0 && height > 0 else {
2017-05-14 20:36:34 +03:00
return .none
}
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
let resultRect = Rect(x: getDoubleValue(element, attribute: "x") ?? 0, y: getDoubleValue(element, attribute: "y") ?? 0, w: width, h: height)
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
let rxOpt = getDoubleValue(element, attribute: "rx")
let ryOpt = getDoubleValue(element, attribute: "ry")
if let rx = rxOpt, let ry = ryOpt {
return RoundRect(rect: resultRect, rx: rx, ry: ry)
}
let rOpt = rxOpt ?? ryOpt
2017-10-19 11:09:09 +03:00
if let r = rOpt, r >= 0 {
2017-05-14 20:36:34 +03:00
return RoundRect(rect: resultRect, rx: r, ry: r)
}
return resultRect
}
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
fileprivate func parseCircle(_ circle: XMLIndexer) -> Circle? {
2017-10-19 11:09:09 +03:00
guard let element = circle.element, let r = getDoubleValue(element, attribute: "r"), r > 0 else {
2017-05-14 20:36:34 +03:00
return .none
}
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
return Circle(cx: getDoubleValue(element, attribute: "cx") ?? 0, cy: getDoubleValue(element, attribute: "cy") ?? 0, r: r)
}
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
fileprivate func parseEllipse(_ ellipse: XMLIndexer) -> Arc? {
guard let element = ellipse.element,
let rx = getDoubleValue(element, attribute: "rx"),
2017-10-19 11:09:09 +03:00
let ry = getDoubleValue(element, attribute: "ry"), rx > 0 && ry > 0 else {
2017-05-14 20:36:34 +03:00
return .none
2016-12-16 15:40:47 +03:00
}
return Arc(
ellipse: Ellipse(cx: getDoubleValue(element, attribute: "cx") ?? 0, cy: getDoubleValue(element, attribute: "cy") ?? 0, rx: rx, ry: ry),
shift: 0,
extent: degreesToRadians(360)
)
2017-05-14 20:36:34 +03:00
}
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
fileprivate func parsePolygon(_ polygon: XMLIndexer) -> Polygon? {
guard let element = polygon.element else {
return .none
}
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
if let points = element.allAttributes["points"]?.text {
return Polygon(points: parsePoints(points))
}
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
return .none
}
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
fileprivate func parsePolyline(_ polyline: XMLIndexer) -> Polyline? {
guard let element = polyline.element else {
return .none
}
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
if let points = element.allAttributes["points"]?.text {
return Polyline(points: parsePoints(points))
}
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
return .none
}
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
fileprivate func parsePoints(_ pointsString: String) -> [Double] {
var resultPoints: [Double] = []
let pointPairs = pointsString.replacingOccurrences(of: "-", with: " -").components(separatedBy: " ")
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
pointPairs.forEach { pointPair in
let points = pointPair.components(separatedBy: ",")
points.forEach { point in
if let resultPoint = Double(point) {
resultPoints.append(resultPoint)
}
}
}
2017-10-19 11:09:09 +03:00
if resultPoints.count % 2 == 1 {
resultPoints.removeLast()
}
2017-05-14 20:36:34 +03:00
return resultPoints
}
2017-10-19 11:09:09 +03:00
fileprivate func parseImage(_ image: XMLIndexer, opacity: Double, pos: Transform = Transform(), clip: Locus?) -> Image? {
2017-05-14 20:36:34 +03:00
guard let element = image.element, let link = element.allAttributes["xlink:href"]?.text else {
return .none
}
let position = pos.move(dx: getDoubleValue(element, attribute: "x") ?? 0, dy: getDoubleValue(element, attribute: "y") ?? 0)
return Image(src: link, w: getIntValue(element, attribute: "width") ?? 0, h: getIntValue(element, attribute: "height") ?? 0, place: position, clip: clip, tag: getTag(element))
2017-05-14 20:36:34 +03:00
}
2017-10-19 11:09:09 +03:00
fileprivate func parseText(_ text: XMLIndexer, textAnchor: String?, fill: Fill?, stroke: Stroke?, opacity: Double, fontName: String?, fontSize: Int?, fontWeight: String?, pos: Transform = Transform()) -> Node? {
2017-05-14 20:36:34 +03:00
guard let element = text.element else {
return .none
}
if text.children.isEmpty {
return parseSimpleText(element, textAnchor: textAnchor, fill: fill, stroke: stroke, opacity: opacity, fontName: fontName, fontSize: fontSize, fontWeight: fontWeight)
2017-05-14 20:36:34 +03:00
} else {
guard let matcher = SVGParserRegexHelper.getTextElementMatcher() else {
return .none
}
let elementString = element.description
2017-11-29 10:24:00 +03:00
let fullRange = NSRange(location: 0, length: elementString.count)
2017-05-14 20:36:34 +03:00
if let match = matcher.firstMatch(in: elementString, options: .reportCompletion, range: fullRange) {
2017-08-28 10:56:52 +03:00
let tspans = (elementString as NSString).substring(with: match.range(at: 1))
return Group(contents: collectTspans(tspans, textAnchor: textAnchor, fill: fill, stroke: stroke, opacity: opacity, fontName: fontName, fontSize: fontSize, fontWeight: fontWeight, bounds: Rect(x: getDoubleValue(element, attribute: "x") ?? 0, y: getDoubleValue(element, attribute: "y") ?? 0)),
2017-05-14 20:36:34 +03:00
place: pos, tag: getTag(element))
}
}
return .none
}
2017-10-19 11:09:09 +03:00
fileprivate func anchorToAlign(_ textAnchor: String?) -> Align {
if let anchor = textAnchor {
if anchor == "middle" {
return .mid
2018-04-28 07:59:17 +03:00
} else if anchor == "end" {
return .max
}
}
return Align.min
}
2017-10-19 11:09:09 +03:00
fileprivate func parseSimpleText(_ text: SWXMLHash.XMLElement, textAnchor: String?, fill: Fill?, stroke: Stroke?, opacity: Double, fontName: String?, fontSize: Int?, fontWeight: String?, pos: Transform = Transform()) -> Text? {
let string = text.text
let position = pos.move(dx: getDoubleValue(text, attribute: "x") ?? 0, dy: getDoubleValue(text, attribute: "y") ?? 0)
2017-10-19 11:09:09 +03:00
return Text(text: string, font: getFont(fontName: fontName, fontWeight: fontWeight, fontSize: fontSize), fill: fill ?? Color.black, stroke: stroke, align: anchorToAlign(textAnchor), baseline: .bottom, place: position, opacity: opacity, tag: getTag(text))
2017-05-14 20:36:34 +03:00
}
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
// REFACTOR
2017-10-19 11:09:09 +03:00
fileprivate func collectTspans(_ tspan: String, collectedTspans: [Node] = [], withWhitespace: Bool = false, textAnchor: String?, fill: Fill?, stroke: Stroke?, opacity: Double, fontName: String?, fontSize: Int?, fontWeight: String?, bounds: Rect) -> [Node] {
2017-05-14 20:36:34 +03:00
let fullString = tspan.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) as NSString
// exit recursion
if fullString.isEqual(to: "") {
return collectedTspans
}
var collection = collectedTspans
let tagRange = fullString.range(of: "<tspan".lowercased())
if tagRange.location == 0 {
// parse as <tspan> element
let closingTagRange = fullString.range(of: "</tspan>".lowercased())
let tspanString = fullString.substring(to: closingTagRange.location + closingTagRange.length)
let tspanXml = SWXMLHash.parse(tspanString)
guard let indexer = tspanXml.children.first,
let text = parseTspan(indexer, withWhitespace: withWhitespace, textAnchor: textAnchor, fill: fill, stroke: stroke, opacity: opacity, fontName: fontName, fontSize: fontSize, fontWeight: fontWeight, bounds: bounds) else {
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
// skip this element if it can't be parsed
return collectTspans(fullString.substring(from: closingTagRange.location + closingTagRange.length), collectedTspans: collectedTspans, textAnchor: textAnchor, fill: fill, stroke: stroke, opacity: opacity,
fontName: fontName, fontSize: fontSize, fontWeight: fontWeight, bounds: bounds)
2017-05-14 20:36:34 +03:00
}
collection.append(text)
let nextString = fullString.substring(from: closingTagRange.location + closingTagRange.length) as NSString
var withWhitespace = false
if nextString.rangeOfCharacter(from: CharacterSet.whitespacesAndNewlines).location == 0 {
withWhitespace = true
}
2018-06-21 09:05:38 +03:00
return collectTspans(fullString.substring(from: closingTagRange.location + closingTagRange.length), collectedTspans: collection, withWhitespace: withWhitespace, textAnchor: textAnchor, fill: fill, stroke: stroke, opacity: opacity, fontName: fontName, fontSize: fontSize, fontWeight: fontWeight, bounds: Rect(x: bounds.x, y: bounds.y, w: bounds.w + text.bounds.w, h: bounds.h))
2017-05-14 20:36:34 +03:00
}
// parse as regular text element
var textString: NSString
if tagRange.location >= fullString.length {
textString = fullString
} else {
textString = fullString.substring(to: tagRange.location) as NSString
}
var nextStringWhitespace = false
var trimmedString = textString.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
2017-11-29 10:24:00 +03:00
if trimmedString.count != textString.length {
2017-05-14 20:36:34 +03:00
nextStringWhitespace = true
}
trimmedString = withWhitespace ? " \(trimmedString)" : trimmedString
let text = Text(text: trimmedString, font: getFont(fontName: fontName, fontWeight: fontWeight, fontSize: fontSize),
fill: fill ?? Color.black, stroke: stroke, align: anchorToAlign(textAnchor), baseline: .alphabetic,
2017-05-14 20:36:34 +03:00
place: Transform().move(dx: bounds.x + bounds.w, dy: bounds.y), opacity: opacity)
collection.append(text)
2018-05-07 11:10:12 +03:00
if tagRange.location >= fullString.length { // leave recursion
return collection
}
return collectTspans(fullString.substring(from: tagRange.location), collectedTspans: collection,
2017-10-19 11:09:09 +03:00
withWhitespace: nextStringWhitespace, textAnchor: textAnchor, fill: fill, stroke: stroke,
2018-06-21 09:05:38 +03:00
opacity: opacity, fontName: fontName, fontSize: fontSize, fontWeight: fontWeight, bounds: Rect(x: bounds.x, y: bounds.y, w: bounds.w + text.bounds.w, h: bounds.h))
2017-05-14 20:36:34 +03:00
}
fileprivate func parseTspan(_ tspan: XMLIndexer, withWhitespace: Bool = false, textAnchor: String?, fill: Fill?, stroke: Stroke?, opacity: Double, fontName: String?, fontSize: Int?, fontWeight: String?, bounds: Rect) -> Text? {
2017-10-19 11:09:09 +03:00
2017-08-28 10:56:52 +03:00
guard let element = tspan.element else {
2017-05-14 20:36:34 +03:00
return .none
}
2017-10-19 11:09:09 +03:00
2017-08-28 10:56:52 +03:00
let string = element.text
2017-05-14 20:36:34 +03:00
var shouldAddWhitespace = withWhitespace
let pos = getTspanPosition(element, bounds: bounds, withWhitespace: &shouldAddWhitespace)
let text = shouldAddWhitespace ? " \(string)" : string
let attributes = getStyleAttributes([:], element: element)
2017-10-19 11:09:09 +03:00
return Text(text: text, font: getFont(attributes, fontName: fontName, fontWeight: fontWeight, fontSize: fontSize),
2018-05-07 11:10:12 +03:00
fill: ((attributes["fill"] != nil) ? getFillColor(attributes)! : fill) ?? Color.black, stroke: stroke ?? getStroke(attributes),
align: anchorToAlign(textAnchor ?? getTextAnchor(attributes)), baseline: .alphabetic,
2017-05-14 20:36:34 +03:00
place: pos, opacity: getOpacity(attributes), tag: getTag(element))
}
2017-10-19 11:09:09 +03:00
fileprivate func getFont(_ attributes: [String: String] = [:], fontName: String?, fontWeight: String?, fontSize: Int?) -> Font {
2017-05-14 20:36:34 +03:00
return Font(
name: getFontName(attributes) ?? fontName ?? "Serif",
size: getFontSize(attributes) ?? fontSize ?? 12,
weight: getFontWeight(attributes) ?? fontWeight ?? "normal")
2017-05-14 20:36:34 +03:00
}
2017-10-19 11:09:09 +03:00
fileprivate func getTspanPosition(_ element: SWXMLHash.XMLElement, bounds: Rect, withWhitespace: inout Bool) -> Transform {
2017-05-14 20:36:34 +03:00
var xPos: Double
var yPos: Double
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
if let absX = getDoubleValue(element, attribute: "x") {
xPos = absX
withWhitespace = false
} else if let relX = getDoubleValue(element, attribute: "dx") {
xPos = bounds.x + bounds.w + relX
} else {
xPos = bounds.x + bounds.w
}
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
if let absY = getDoubleValue(element, attribute: "y") {
yPos = absY
} else if let relY = getDoubleValue(element, attribute: "dy") {
yPos = bounds.y + relY
} else {
yPos = bounds.y
}
2017-12-20 11:46:33 +03:00
return Transform.move(dx: xPos, dy: yPos)
2017-05-14 20:36:34 +03:00
}
2017-10-19 11:09:09 +03:00
2017-12-20 11:46:33 +03:00
fileprivate func parseUse(_ use: XMLIndexer, groupStyle: [String: String] = [:], place: Transform = .identity) -> Node? {
2017-05-14 20:36:34 +03:00
guard let element = use.element, let link = element.allAttributes["xlink:href"]?.text else {
return .none
}
var id = link
if id.hasPrefix("#") {
id = id.replacingOccurrences(of: "#", with: "")
}
2017-12-20 11:46:33 +03:00
if let referenceNode = self.defNodes[id] {
if let node = parseNode(referenceNode, groupStyle: groupStyle) {
node.place = place.move(dx: getDoubleValue(element, attribute: "x") ?? 0, dy: getDoubleValue(element, attribute: "y") ?? 0)
return node
2017-12-20 11:46:33 +03:00
}
2017-05-14 20:36:34 +03:00
}
2017-12-20 11:46:33 +03:00
return .none
2017-05-14 20:36:34 +03:00
}
2017-10-19 11:09:09 +03:00
2018-06-06 07:06:20 +03:00
fileprivate func parseClip(_ clip: XMLIndexer) -> UserSpaceLocus? {
2018-06-05 14:08:54 +03:00
var userSpace = true
if let units = clip.element?.allAttributes["clipPathUnits"]?.text, units == "objectBoundingBox" {
userSpace = false
}
2018-06-08 07:29:54 +03:00
if clip.children.isEmpty {
2018-06-06 07:06:20 +03:00
return .none
}
2018-06-09 13:46:27 +03:00
2018-06-06 07:06:20 +03:00
if clip.children.count == 1 {
let shape = parseNode(clip.children.first!) as! Shape
2018-06-26 00:37:39 +03:00
if shape.place != Transform.identity {
let locus = TransformedLocus(locus: shape.form, transform: shape.place)
return UserSpaceLocus(locus: locus, userSpace: userSpace)
}
2018-06-06 07:06:20 +03:00
return UserSpaceLocus(locus: shape.form, userSpace: userSpace)
}
var path: Path? = .none
clip.children.forEach { indexer in
if let shape = parseNode(indexer) as? Shape {
if let p = path {
2018-06-06 07:06:20 +03:00
path = Path(segments: p.segments + shape.form.toPath().segments, fillRule: p.fillRule)
} else {
2018-06-06 07:06:20 +03:00
path = Path(segments: shape.form.toPath().segments)
}
}
}
2018-06-06 07:06:20 +03:00
return UserSpaceLocus(locus: path!, userSpace: userSpace)
}
2018-06-14 13:26:22 +03:00
fileprivate func parseMask(_ mask: XMLIndexer) -> UserSpaceNode? {
var userSpace = true
if let units = mask.element?.allAttributes["maskContentUnits"]?.text, units == "objectBoundingBox" {
userSpace = false
}
if mask.children.isEmpty {
return .none
}
if mask.children.count == 1 {
return UserSpaceNode(node: parseNode(mask.children.first!)!, userSpace: userSpace)
}
var nodes = [Node]()
mask.children.forEach { indexer in
let position = getPosition(indexer.element!)
if let useNode = parseUse(indexer, place: position) {
nodes.append(useNode)
} else if let contentNode = parseNode(indexer) {
nodes.append(contentNode)
}
}
return UserSpaceNode(node: Group(contents: nodes), userSpace: userSpace)
}
fileprivate func parseEffect(_ filterNode: XMLIndexer) -> Effect? {
let defaultSource = "SourceGraphic"
var effects = [String: Effect]()
2018-06-05 11:24:26 +03:00
for child in filterNode.children {
guard let element = child.element else { continue }
2018-06-09 07:27:06 +03:00
let filterIn = element.allAttributes["in"]?.text ?? defaultSource
2018-06-05 11:24:26 +03:00
var currentEffect = effects[filterIn]
if currentEffect == nil && filterIn == "SourceAlpha" {
currentEffect = AlphaEffect(input: nil)
} else if currentEffect == nil && filterIn != defaultSource {
fatalError("Filter parsing: Incorrect effects order")
}
effects.removeValue(forKey: filterIn)
let filterOut = element.allAttributes["result"]?.text
var resultingEffect: Effect? = .none
switch element.name {
case "feOffset":
if let dx = getDoubleValue(element, attribute: "dx"), let dy = getDoubleValue(element, attribute: "dy") {
2018-06-05 11:24:26 +03:00
resultingEffect = OffsetEffect(dx: dx, dy: dy, input: currentEffect)
}
case "feGaussianBlur":
if let radius = getDoubleValue(element, attribute: "stdDeviation") {
resultingEffect = GaussianBlur(r: radius, input: currentEffect)
}
2018-05-25 12:11:47 +03:00
case "feColorMatrix":
2018-05-29 10:06:54 +03:00
if let type = element.allAttributes["type"]?.text {
var matrix: ColorMatrix?
2018-05-29 10:06:54 +03:00
if type == "saturate" {
matrix = ColorMatrix(saturate: getDoubleValue(element, attribute: "values")!)
} else if type == "hueRotate" {
2018-05-29 14:36:46 +03:00
let degrees = getDoubleValue(element, attribute: "values")!
matrix = ColorMatrix(hueRotate: degrees / 180 * Double.pi)
} else if type == "luminanceToAlpha" {
matrix = .luminanceToAlpha
2018-05-29 10:06:54 +03:00
} else { // "matrix"
matrix = ColorMatrix(values: getMatrix(element, attribute: "values"))
2018-05-29 10:06:54 +03:00
}
resultingEffect = ColorMatrixEffect(matrix: matrix!, input: currentEffect)
2018-05-25 12:11:47 +03:00
}
case "feBlend":
if let filterIn2 = element.allAttributes["in2"]?.text {
2018-06-05 11:24:26 +03:00
if currentEffect != nil {
resultingEffect = BlendEffect(input: currentEffect)
} else if let currentEffect = effects[filterIn2] {
resultingEffect = BlendEffect(input: currentEffect)
}
}
default:
print("SVG parsing error. Filter \(element.name) not supported")
continue
}
2018-06-05 11:24:26 +03:00
if filterOut == nil {
return resultingEffect
}
effects[filterOut!] = resultingEffect
}
2018-06-05 11:24:26 +03:00
if effects.count == 1 {
return effects.first?.value
}
return nil
}
2018-04-18 13:29:28 +03:00
fileprivate func parseLinearGradient(_ gradient: XMLIndexer, groupStyle: [String: String] = [:]) -> Fill? {
2017-05-14 20:36:34 +03:00
guard let element = gradient.element else {
return .none
}
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
var parentGradient: Gradient?
2017-10-19 11:09:09 +03:00
if let link = element.allAttributes["xlink:href"]?.text.replacingOccurrences(of: " ", with: ""), link.hasPrefix("#") {
2017-05-14 20:36:34 +03:00
let id = link.replacingOccurrences(of: "#", with: "")
parentGradient = defFills[id] as? Gradient
}
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
var stopsArray: [Stop]?
if gradient.children.isEmpty {
stopsArray = parentGradient?.stops
} else {
2018-04-18 13:29:28 +03:00
stopsArray = parseStops(gradient.children, groupStyle: groupStyle)
2017-05-14 20:36:34 +03:00
}
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
guard let stops = stopsArray else {
return .none
}
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
switch stops.count {
case 0:
return .none
case 1:
return stops.first?.color
default:
break
}
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
let parentLinearGradient = parentGradient as? LinearGradient
var x1 = getDoubleValueFromPercentage(element, attribute: "x1") ?? parentLinearGradient?.x1 ?? 0
var y1 = getDoubleValueFromPercentage(element, attribute: "y1") ?? parentLinearGradient?.y1 ?? 0
var x2 = getDoubleValueFromPercentage(element, attribute: "x2") ?? parentLinearGradient?.x2 ?? 1
var y2 = getDoubleValueFromPercentage(element, attribute: "y2") ?? parentLinearGradient?.y2 ?? 0
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
var userSpace = false
2017-10-19 11:09:09 +03:00
if let gradientUnits = element.allAttributes["gradientUnits"]?.text, gradientUnits == "userSpaceOnUse" {
2017-05-14 20:36:34 +03:00
userSpace = true
} else if let parent = parentGradient {
userSpace = parent.userSpace
}
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
if let gradientTransform = element.allAttributes["gradientTransform"]?.text {
let transform = parseTransformationAttribute(gradientTransform)
let cgTransform = transform.toCG()
2018-04-04 17:59:28 +03:00
let point1 = CGPoint(x: x1, y: y1).applying(cgTransform)
x1 = point1.x.doubleValue
y1 = point1.y.doubleValue
2018-04-04 17:59:28 +03:00
let point2 = CGPoint(x: x2, y: y2).applying(cgTransform)
x2 = point2.x.doubleValue
y2 = point2.y.doubleValue
}
return LinearGradient(x1: x1, y1: y1, x2: x2, y2: y2, userSpace: userSpace, stops: stops)
2017-05-14 20:36:34 +03:00
}
2017-10-19 11:09:09 +03:00
2018-04-18 13:29:28 +03:00
fileprivate func parseRadialGradient(_ gradient: XMLIndexer, groupStyle: [String: String] = [:]) -> Fill? {
2017-05-14 20:36:34 +03:00
guard let element = gradient.element else {
return .none
}
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
var parentGradient: Gradient?
2017-10-19 11:09:09 +03:00
if let link = element.allAttributes["xlink:href"]?.text.replacingOccurrences(of: " ", with: ""), link.hasPrefix("#") {
2017-05-14 20:36:34 +03:00
let id = link.replacingOccurrences(of: "#", with: "")
parentGradient = defFills[id] as? Gradient
}
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
var stopsArray: [Stop]?
if gradient.children.isEmpty {
stopsArray = parentGradient?.stops
} else {
2018-04-18 13:29:28 +03:00
stopsArray = parseStops(gradient.children, groupStyle: groupStyle)
2017-05-14 20:36:34 +03:00
}
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
guard let stops = stopsArray else {
return .none
}
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
switch stops.count {
case 0:
return .none
case 1:
return stops.first?.color
default:
break
}
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
let parentRadialGradient = parentGradient as? RadialGradient
var cx = getDoubleValueFromPercentage(element, attribute: "cx") ?? parentRadialGradient?.cx ?? 0.5
var cy = getDoubleValueFromPercentage(element, attribute: "cy") ?? parentRadialGradient?.cy ?? 0.5
var fx = getDoubleValueFromPercentage(element, attribute: "fx") ?? parentRadialGradient?.fx ?? cx
var fy = getDoubleValueFromPercentage(element, attribute: "fy") ?? parentRadialGradient?.fy ?? cy
2017-05-14 20:36:34 +03:00
let r = getDoubleValueFromPercentage(element, attribute: "r") ?? parentRadialGradient?.r ?? 0.5
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
var userSpace = false
2017-10-19 11:09:09 +03:00
if let gradientUnits = element.allAttributes["gradientUnits"]?.text, gradientUnits == "userSpaceOnUse" {
2017-05-14 20:36:34 +03:00
userSpace = true
} else if let parent = parentGradient {
userSpace = parent.userSpace
}
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
if let gradientTransform = element.allAttributes["gradientTransform"]?.text {
let transform = parseTransformationAttribute(gradientTransform)
let cgTransform = transform.toCG()
2018-04-04 17:59:28 +03:00
let point1 = CGPoint(x: cx, y: cy).applying(cgTransform)
cx = point1.x.doubleValue
cy = point1.y.doubleValue
2018-04-04 17:59:28 +03:00
let point2 = CGPoint(x: fx, y: fy).applying(cgTransform)
fx = point2.x.doubleValue
fy = point2.y.doubleValue
}
return RadialGradient(cx: cx, cy: cy, fx: fx, fy: fy, r: r, userSpace: userSpace, stops: stops)
2017-05-14 20:36:34 +03:00
}
2017-10-19 11:09:09 +03:00
2018-04-18 13:29:28 +03:00
fileprivate func parseStops(_ stops: [XMLIndexer], groupStyle: [String: String] = [:]) -> [Stop] {
2017-05-14 20:36:34 +03:00
var result = [Stop]()
stops.forEach { stopXML in
2018-04-18 13:29:28 +03:00
if let stop = parseStop(stopXML, groupStyle: groupStyle) {
2017-05-14 20:36:34 +03:00
result.append(stop)
}
}
return result
}
2017-10-19 11:09:09 +03:00
2018-04-18 13:29:28 +03:00
fileprivate func parseStop(_ stop: XMLIndexer, groupStyle: [String: String] = [:]) -> Stop? {
2017-05-14 20:36:34 +03:00
guard let element = stop.element else {
return .none
}
guard let offset = getDoubleValueFromPercentage(element, attribute: "offset") else {
2017-05-14 20:36:34 +03:00
return .none
}
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
var opacity: Double = 1
if let stopOpacity = getStyleAttributes([:], element: element)["stop-opacity"], let doubleValue = Double(stopOpacity) {
opacity = doubleValue
}
var color = Color.black
2018-04-18 13:29:28 +03:00
if var stopColor = getStyleAttributes([:], element: element)["stop-color"] {
if stopColor == "currentColor", let currentColor = groupStyle["color"] {
stopColor = currentColor
}
color = createColor(stopColor.replacingOccurrences(of: " ", with: ""), opacity: opacity)!
2017-05-14 20:36:34 +03:00
}
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
return Stop(offset: offset, color: color)
}
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
fileprivate func parsePath(_ path: XMLIndexer) -> Path? {
if let d = path.element?.allAttributes["d"]?.text {
return Path(segments: PathDataReader(input: d).read())
2017-05-14 20:36:34 +03:00
}
return .none
}
2017-10-19 11:09:09 +03:00
fileprivate func parseIdFromUrl(_ urlString: String) -> String? {
if urlString.hasPrefix("url") {
return urlString.substringWithOffset(fromStart: 5, fromEnd: 1)
}
return .none
}
fileprivate func getDoubleValue(_ element: SWXMLHash.XMLElement, attribute: String) -> Double? {
guard let attributeValue = element.allAttributes[attribute]?.text else {
2017-05-14 20:36:34 +03:00
return .none
}
return doubleFromString(attributeValue)
}
2018-05-16 19:40:04 +03:00
2018-05-10 08:55:00 +03:00
fileprivate func getDimensionValue(_ element: SWXMLHash.XMLElement, attribute: String) -> SVGLength? {
guard let attributeValue = element.allAttributes[attribute]?.text else {
return .none
}
return dimensionFromString(attributeValue)
}
2018-05-16 19:40:04 +03:00
2018-05-10 08:55:00 +03:00
fileprivate func dimensionFromString(_ string: String) -> SVGLength? {
if let value = doubleFromString(string) {
2018-05-10 08:55:00 +03:00
return SVGLength(pixels: value)
}
if string.hasSuffix("%") {
2018-05-10 08:55:00 +03:00
return SVGLength(percent: Double(string.dropLast())!)
}
return .none
}
2018-05-16 19:40:04 +03:00
fileprivate func doubleFromString(_ string: String) -> Double? {
if let doubleValue = Double(string) {
return doubleValue
}
if string == "none" {
return 0
}
2018-05-16 19:40:04 +03:00
guard let matcher = SVGParserRegexHelper.getUnitsIdenitifierMatcher() else {
return .none
}
2018-04-23 13:08:12 +03:00
let fullRange = NSRange(location: 0, length: string.count)
if let match = matcher.firstMatch(in: string, options: .reportCompletion, range: fullRange) {
2018-05-16 19:40:04 +03:00
2018-04-23 13:08:12 +03:00
let unitString = (string as NSString).substring(with: match.range(at: 1))
let numberString = String(string.dropLast(unitString.count))
let value = Double(numberString)!
2018-04-23 13:08:12 +03:00
switch unitString {
case "px" :
return value
2018-04-23 13:08:12 +03:00
default:
print("SVG parsing error. Unit \(unitString) not supported")
return value
}
}
return .none
2017-05-14 20:36:34 +03:00
}
2017-10-19 11:09:09 +03:00
fileprivate func getDoubleValueFromPercentage(_ element: SWXMLHash.XMLElement, attribute: String) -> Double? {
2017-05-14 20:36:34 +03:00
guard let attributeValue = element.allAttributes[attribute]?.text else {
return .none
}
2016-09-29 14:17:59 +03:00
if !attributeValue.contains("%") {
2017-05-14 20:36:34 +03:00
return self.getDoubleValue(element, attribute: attribute)
} else {
let value = attributeValue.replacingOccurrences(of: "%", with: "")
if let doubleValue = Double(value) {
return doubleValue / 100
}
}
return .none
}
2017-10-19 11:09:09 +03:00
fileprivate func getIntValue(_ element: SWXMLHash.XMLElement, attribute: String) -> Int? {
if let attributeValue = element.allAttributes[attribute]?.text {
if let doubleValue = Double(attributeValue) {
return Int(doubleValue)
}
2017-05-14 20:36:34 +03:00
}
return .none
2017-05-14 20:36:34 +03:00
}
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
fileprivate func getFontName(_ attributes: [String: String]) -> String? {
2018-04-27 12:42:03 +03:00
return attributes["font-family"]?.trimmingCharacters(in: .whitespacesAndNewlines)
2017-05-14 20:36:34 +03:00
}
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
fileprivate func getFontSize(_ attributes: [String: String]) -> Int? {
guard let fontSize = attributes["font-size"], let size = doubleFromString(fontSize) else {
2017-05-14 20:36:34 +03:00
return .none
}
return Int(round(size))
2017-05-14 20:36:34 +03:00
}
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
fileprivate func getFontStyle(_ attributes: [String: String], style: String) -> Bool? {
guard let fontStyle = attributes["font-style"] else {
return .none
}
if fontStyle.lowercased() == style {
return true
}
return false
}
2017-10-19 11:09:09 +03:00
fileprivate func getFontWeight(_ attributes: [String: String]) -> String? {
guard let fontWeight = attributes["font-weight"] else {
return .none
}
return fontWeight
}
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
fileprivate func getFontWeight(_ attributes: [String: String], style: String) -> Bool? {
guard let fontWeight = attributes["font-weight"] else {
return .none
}
if fontWeight.lowercased() == style {
return true
}
return false
}
2018-06-14 13:26:22 +03:00
fileprivate func transformBoundingBoxLocus(respectiveLocus: Locus, absoluteLocus: Locus) -> Transform {
let absoluteBounds = absoluteLocus.bounds()
let respectiveBounds = respectiveLocus.bounds()
let finalSize = Size(w: absoluteBounds.w * respectiveBounds.w,
h: absoluteBounds.h * respectiveBounds.h)
let scale = ContentLayout.of(contentMode: .scaleToFill).layout(size: respectiveBounds.size(), into: finalSize)
return Transform.move(dx: absoluteBounds.x, dy: absoluteBounds.y).concat(with: scale)
}
2018-06-07 09:35:06 +03:00
fileprivate func getClipPath(_ attributes: [String: String], locus: Locus?) -> Locus? {
2018-06-26 00:18:47 +03:00
if let clipPath = attributes["clip-path"], let id = parseIdFromUrl(clipPath) {
2018-06-06 07:06:20 +03:00
if let userSpaceLocus = defClip[id] {
if !userSpaceLocus.userSpace {
2018-06-26 00:18:47 +03:00
guard let locus = locus else { return .none }
2018-06-14 13:26:22 +03:00
let transform = transformBoundingBoxLocus(respectiveLocus: userSpaceLocus.locus, absoluteLocus: locus)
2018-06-06 07:06:20 +03:00
return TransformedLocus(locus: userSpaceLocus.locus, transform: transform)
2018-06-05 14:08:54 +03:00
}
2018-06-06 07:06:20 +03:00
return userSpaceLocus.locus
}
}
return .none
}
2018-06-14 13:26:22 +03:00
fileprivate func getMask(_ attributes: [String: String], locus: Locus?) -> Node? {
guard let maskName = attributes["mask"], let id = parseIdFromUrl(maskName), let userSpaceNode = defMasks[id], let locus = locus else {
return .none
}
if !userSpaceNode.userSpace {
if let group = userSpaceNode.node as? Group {
for node in group.contents {
if let shape = node as? Shape {
shape.place = transformBoundingBoxLocus(respectiveLocus: shape.form, absoluteLocus: locus)
}
}
return group
}
if let shape = userSpaceNode.node as? Shape {
shape.place = transformBoundingBoxLocus(respectiveLocus: shape.form, absoluteLocus: locus)
return shape
} else {
fatalError("Mask: Unsupported node type")
}
}
return userSpaceNode.node
}
fileprivate func getTextAnchor(_ attributes: [String: String]) -> String? {
guard let textAnchor = attributes["text-anchor"] else {
return .none
}
return textAnchor
}
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
fileprivate func getTextDecoration(_ attributes: [String: String], decoration: String) -> Bool? {
guard let textDecoration = attributes["text-decoration"] else {
return .none
}
if textDecoration.contains(decoration) {
return true
}
return false
}
2018-05-16 19:40:04 +03:00
2018-04-26 12:03:09 +03:00
fileprivate func getFillRule(_ attributes: [String: String]) -> FillRule? {
if let rule = attributes["fill-rule"] {
switch rule {
case "nonzero":
return .nonzero
case "evenodd":
return .evenodd
default:
return .none
}
}
return .none
}
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
fileprivate func copyNode(_ referenceNode: Node) -> Node? {
let pos = referenceNode.place
let opaque = referenceNode.opaque
let visible = referenceNode.visible
let clip = referenceNode.clip
let tag = referenceNode.tag
2017-10-19 11:09:09 +03:00
2017-05-14 20:36:34 +03:00
if let shape = referenceNode as? Shape {
return Shape(form: shape.form, fill: shape.fill, stroke: shape.stroke, place: pos, opaque: opaque, clip: clip, visible: visible, tag: tag)
}
if let text = referenceNode as? Text {
return Text(text: text.text, font: text.font, fill: text.fill, stroke: text.stroke, align: text.align, baseline: text.baseline, place: pos, opaque: opaque, clip: clip, visible: visible, tag: tag)
2017-05-14 20:36:34 +03:00
}
if let image = referenceNode as? Image {
return Image(src: image.src, xAlign: image.xAlign, yAlign: image.yAlign, aspectRatio: image.aspectRatio, w: image.w, h: image.h, place: pos, opaque: opaque, clip: clip, visible: visible, tag: tag)
}
if let group = referenceNode as? Group {
var contents = [Node]()
group.contents.forEach { node in
if let copy = copyNode(node) {
contents.append(copy)
}
}
return Group(contents: contents, place: pos, opaque: opaque, clip: clip, visible: visible, tag: tag)
}
return .none
}
2017-10-19 11:09:09 +03:00
fileprivate func degreesToRadians(_ degrees: Double) -> Double {
return degrees * .pi / 180
}
2017-10-19 11:09:09 +03:00
2016-08-03 12:16:30 +03:00
}
private class PathDataReader {
2018-04-04 17:59:28 +03:00
private let input: String
private var current: UnicodeScalar?
2018-03-12 19:50:17 +03:00
private var previous: UnicodeScalar?
private var iterator: String.UnicodeScalarView.Iterator
init(input: String) {
self.input = input
self.iterator = input.unicodeScalars.makeIterator()
}
2018-04-04 17:59:28 +03:00
public func read() -> [PathSegment] {
2018-04-04 17:59:28 +03:00
_ = readNext()
var segments = [PathSegment]()
while let array = readSegments() {
segments.append(contentsOf: array)
}
return segments
}
private func readSegments() -> [PathSegment]? {
if let type = readSegmentType() {
2018-05-16 19:40:04 +03:00
let argCount = getArgCount(segment: type)
if argCount == 0 {
return [PathSegment(type: type)]
}
var result = [PathSegment]()
let data = readData()
var index = 0
var isFirstSegment = true
while index < data.count {
2018-05-16 19:40:04 +03:00
let end = index + argCount
if end > data.count {
// TODO need to generate error:
// "Path '\(type)' has invalid number of arguments: \(data.count)"
break
}
var currentType = type
if type == .M && !isFirstSegment {
currentType = .L
}
if type == .m && !isFirstSegment {
currentType = .l
}
result.append(PathSegment(type: currentType, data: Array(data[index..<end])))
isFirstSegment = false
index = end
}
return result
}
return nil
}
private func readData() -> [Double] {
var data = [Double]()
2018-05-16 19:40:04 +03:00
while true {
skipSpaces()
if let value = readNum() {
data.append(value)
} else {
return data
}
}
}
private func skipSpaces() {
var ch = current
while ch != nil && "\n\r\t ,".contains(String(ch!)) {
ch = readNext()
}
}
fileprivate func readNum() -> Double? {
guard let ch = current else {
return nil
}
if (ch >= "0" && ch <= "9") || ch == "." || ch == "-" {
var chars = [ch]
var hasDot = ch == "."
while let ch = readDigit(&hasDot) {
chars.append(ch)
}
var buf = ""
buf.unicodeScalars.append(contentsOf: chars)
return Double(buf)
}
return nil
}
fileprivate func readDigit(_ hasDot: inout Bool) -> UnicodeScalar? {
if let ch = readNext() {
2018-05-16 19:40:04 +03:00
if (ch >= "0" && ch <= "9") || ch == "e" || (previous == "e" && ch == "-") {
return ch
2018-05-16 19:40:04 +03:00
} else if ch == "." && !hasDot {
hasDot = true
return ch
}
}
return nil
}
fileprivate func isNum(ch: UnicodeScalar, hasDot: inout Bool) -> Bool {
2018-05-16 19:40:04 +03:00
switch ch {
case "0"..."9":
return true
case ".":
if hasDot {
return false
}
hasDot = true
default:
return true
}
return false
}
private func readNext() -> UnicodeScalar? {
2018-03-12 19:50:17 +03:00
previous = current
current = iterator.next()
return current
}
2018-04-04 17:59:28 +03:00
private func isAcceptableSeparator(_ ch: UnicodeScalar?) -> Bool {
if let ch = ch {
return "\n\r\t ,".contains(String(ch))
}
return false
}
private func readSegmentType() -> PathSegmentType? {
2018-05-16 19:40:04 +03:00
while true {
if let type = getPathSegmentType() {
2018-04-04 17:59:28 +03:00
_ = readNext()
return type
}
2018-05-16 19:40:04 +03:00
if readNext() == nil {
return nil
}
}
}
2018-04-04 17:59:28 +03:00
fileprivate func getPathSegmentType() -> PathSegmentType? {
if let ch = current {
2018-05-16 19:40:04 +03:00
switch ch {
case "M":
return .M
case "m":
return .m
case "L":
return .L
case "l":
return .l
case "C":
return .C
case "c":
return .c
case "Q":
return .Q
case "q":
return .q
case "A":
return .A
case "a":
return .a
case "z", "Z":
return .z
case "H":
return .H
case "h":
return .h
case "V":
return .V
case "v":
return .v
case "S":
return .S
case "s":
return .s
case "T":
return .T
case "t":
return .t
default:
break
}
}
return nil
}
2018-04-04 17:59:28 +03:00
fileprivate func getArgCount(segment: PathSegmentType) -> Int {
2018-05-16 19:40:04 +03:00
switch segment {
case .H, .h, .V, .v:
return 1
case .M, .m, .L, .l, .T, .t:
return 2
case .S, .s, .Q, .q:
return 4
case .C, .c:
return 6
case .A, .a:
return 7
default:
return 0
}
}
}
fileprivate extension String {
func substringWithOffset(fromStart: Int, fromEnd: Int) -> String {
let start = index(startIndex, offsetBy: fromStart)
let end = index(endIndex, offsetBy: -fromEnd)
return String(self[start..<end])
}
}
2018-06-05 14:08:54 +03:00
2018-06-06 07:06:20 +03:00
fileprivate class UserSpaceLocus {
let locus: Locus
2018-06-05 14:08:54 +03:00
let userSpace: Bool
2018-06-06 07:06:20 +03:00
init(locus: Locus, userSpace: Bool) {
self.locus = locus
2018-06-05 14:08:54 +03:00
self.userSpace = userSpace
}
}
2018-06-14 13:26:22 +03:00
fileprivate class UserSpaceNode {
let node: Node
let userSpace: Bool
init(node: Node, userSpace: Bool) {
self.node = node
self.userSpace = userSpace
}
}