gpxkit 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,223 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GpxKit
4
+ # Turns the XML layer's element events into Messages (SPECIFICATION.md
5
+ # 6.2). A message is emitted when its element closes; every leaf element
6
+ # and attribute inside it, outside nested messages, becomes one of its
7
+ # Fields. The gpx element itself is the :document message, emitted last.
8
+ # One builder per pass.
9
+ class MessageBuilder
10
+ # Elements left out of field names: "extensions/TrackPointExtension/hr" is hr.
11
+ WRAPPERS = %w[extensions Extensions TrackPointExtension].freeze
12
+
13
+ # Child elements that start messages, by the parent message's kind.
14
+ MESSAGES = {
15
+ document: { "metadata" => :metadata, "wpt" => :waypoint, "rte" => :route, "trk" => :track },
16
+ route: { "rtept" => :route_point },
17
+ track: { "trkseg" => :track_segment },
18
+ track_segment: { "trkpt" => :track_point }
19
+ }.freeze
20
+
21
+ # Indexes counted across the document; the others count within their parent.
22
+ DOCUMENT_COUNTERS = %i[metadata waypoint route track].freeze
23
+
24
+ # What a node in the element stack is: a message element (with its Frame)
25
+ # or a field element (with its Shape).
26
+ Node = Struct.new(:kind, :element, :frame, :shape)
27
+
28
+ # Where an element or attribute sits inside a message: its path, schema
29
+ # key (nil once a segment is outside the known namespaces), field name
30
+ # (the joined names so far, as a String, and as the Symbol fields use)
31
+ # and type. Every point has the same few shapes, so they are made once
32
+ # per message type and reused; a builder makes at most SHAPE_LIMIT,
33
+ # because unknown names come from the file.
34
+ class Shape
35
+ attr_reader :path, :key, :joined_name, :name, :spec
36
+
37
+ def initialize(path:, key:, joined_name:, spec:)
38
+ @path = path
39
+ @key = key
40
+ @joined_name = joined_name
41
+ @name = joined_name.to_sym
42
+ @spec = spec
43
+ @children = {}
44
+ @attributes = {}
45
+ end
46
+
47
+ def child(namespace, name) = @children[namespace]&.[](name)
48
+ def attribute(namespace, name) = @attributes[namespace]&.[](name)
49
+ def add_child(namespace, name, shape) = (@children[namespace] ||= {})[name] = shape
50
+ def add_attribute(namespace, name, shape) = (@attributes[namespace] ||= {})[name] = shape
51
+ end
52
+
53
+ SHAPE_LIMIT = 10_000
54
+
55
+ # A message being collected.
56
+ class Frame
57
+ attr_reader :kind, :element, :context, :fields, :table, :shape
58
+
59
+ def initialize(kind, element, context, table, shape)
60
+ @kind = kind
61
+ @element = element
62
+ @context = context.freeze
63
+ @table = table
64
+ @shape = shape
65
+ @fields = []
66
+ @counters = Hash.new(0)
67
+ end
68
+
69
+ def next_index(kind)
70
+ index = @counters[kind]
71
+ @counters[kind] += 1
72
+ index
73
+ end
74
+
75
+ def to_message
76
+ Message.new(name: kind, element_name: element.name, namespace: element.namespace, context: context,
77
+ line: element.line, column: element.column, fields: fields)
78
+ end
79
+ end
80
+
81
+ attr_reader :version
82
+
83
+ def initialize(&emit)
84
+ @emit = emit
85
+ @nodes = []
86
+ @counters = Hash.new(0)
87
+ @roots = {}.compare_by_identity
88
+ @shapes = 0
89
+ end
90
+
91
+ def handle(type, element)
92
+ type == :start ? start(element) : finish(element)
93
+ end
94
+
95
+ private
96
+
97
+ def start(element)
98
+ parent = @nodes.last
99
+ return start_document(element) unless parent
100
+
101
+ kind = parent.kind == :message && element.namespace == @namespace && MESSAGES.dig(parent.frame.kind, element.name)
102
+ if kind
103
+ @nodes << open_message(kind, element, parent.frame)
104
+ else
105
+ frame = parent.frame
106
+ node = Node.new(:field, element, frame, child_shape(parent.shape, element, frame.table))
107
+ add_attributes(node)
108
+ @nodes << node
109
+ end
110
+ end
111
+
112
+ # The Reader has checked the root: the namespace decides the version, and
113
+ # a root without one is read by its version attribute.
114
+ def start_document(element)
115
+ @namespace = element.namespace
116
+ @version = NAMESPACES[@namespace] || element.attribute("version")&.value
117
+ frame = new_frame(:document, element, {}, Schema.table(@version, :document))
118
+ node = Node.new(:message, element, frame, frame.shape)
119
+ add_attributes(node)
120
+ @nodes << node
121
+ end
122
+
123
+ def finish(element)
124
+ node = @nodes.pop
125
+ case node.kind
126
+ when :message then @emit.call(node.frame.to_message)
127
+ when :field then add_text(node, element) unless element.children?
128
+ end
129
+ end
130
+
131
+ def open_message(kind, element, parent_frame)
132
+ index = DOCUMENT_COUNTERS.include?(kind) ? next_document_index(kind) : parent_frame.next_index(kind)
133
+ context = parent_frame.context.merge(kind => index)
134
+ frame = new_frame(kind, element, context, Schema.table(@version, kind))
135
+ node = Node.new(:message, element, frame, frame.shape)
136
+ add_attributes(node)
137
+ node
138
+ end
139
+
140
+ def new_frame(kind, element, context, table)
141
+ root = @roots[table] ||= Shape.new(path: "", key: "", joined_name: "", spec: nil)
142
+ Frame.new(kind, element, context, table, root)
143
+ end
144
+
145
+ def next_document_index(kind)
146
+ index = @counters[kind]
147
+ @counters[kind] += 1
148
+ index
149
+ end
150
+
151
+ def child_shape(parent, element, table)
152
+ cached = parent.child(element.namespace, element.name)
153
+ return cached if cached
154
+
155
+ key = join_key(parent.key, segment(element))
156
+ shape = Shape.new(path: join(parent.path, element.name, "/"), key: key,
157
+ joined_name: field_name(parent.joined_name, element.name),
158
+ spec: (key && table[key]) || Types::UNKNOWN)
159
+ parent.add_child(element.namespace, element.name, shape) if remember?
160
+ shape
161
+ end
162
+
163
+ def attribute_shape(parent, attribute, table)
164
+ cached = parent.attribute(attribute.namespace, attribute.name)
165
+ return cached if cached
166
+
167
+ key = join_key(parent.key, attribute.namespace.nil? ? "@#{attribute.name}" : nil)
168
+ shape = Shape.new(path: join(parent.path, "@#{attribute.name}", "/"), key: key,
169
+ joined_name: field_name(parent.joined_name, attribute.name),
170
+ spec: (key && table[key]) || Types::UNKNOWN)
171
+ parent.add_attribute(attribute.namespace, attribute.name, shape) if remember?
172
+ shape
173
+ end
174
+
175
+ def remember?
176
+ (@shapes += 1) <= SHAPE_LIMIT
177
+ end
178
+
179
+ def add_attributes(node)
180
+ node.element.attributes.each do |attribute|
181
+ shape = attribute_shape(node.shape, attribute, node.frame.table)
182
+ node.frame.fields << Field.new(name: shape.name, path: shape.path, namespace: attribute.namespace,
183
+ text: attribute.value, spec: shape.spec, line: node.element.line)
184
+ end
185
+ end
186
+
187
+ # An empty wrapper is not a field, and neither is the missing text of an
188
+ # element that only carries attributes (such as <bounds .../>).
189
+ def add_text(node, element)
190
+ return if WRAPPERS.include?(element.name) && element.text.strip.empty?
191
+ return if element.text.empty? && !element.attributes.empty?
192
+
193
+ shape = node.shape
194
+ node.frame.fields << Field.new(name: shape.name, path: shape.path, namespace: element.namespace,
195
+ text: element.text, spec: shape.spec, line: element.line)
196
+ end
197
+
198
+ # The parent's name joined with this element's snake_case name, wrappers
199
+ # left out: "link/@href" is link_href, "extensions/TrackPointExtension/hr" hr.
200
+ def field_name(parent_name, name)
201
+ return parent_name if WRAPPERS.include?(name)
202
+
203
+ join(parent_name, Naming.snake_case(name), "_")
204
+ end
205
+
206
+ def join_key(key, segment)
207
+ key && segment && join(key, segment, "/")
208
+ end
209
+
210
+ def join(left, right, separator)
211
+ left.empty? ? right.dup.freeze : "#{left}#{separator}#{right}".freeze
212
+ end
213
+
214
+ # The schema key of an element, or nil for a namespace the schema does
215
+ # not cover.
216
+ def segment(element)
217
+ return element.name if element.namespace == @namespace
218
+
219
+ prefix = Schema::PREFIXES[element.namespace]
220
+ prefix && "#{prefix}:#{element.name}"
221
+ end
222
+ end
223
+ end
@@ -0,0 +1,112 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GpxKit
4
+ # Streams the messages of a GPX 1.1 or 1.0 document.
5
+ #
6
+ # GpxKit::Reader.new("ride.gpx").each_message { |message| ... }
7
+ #
8
+ # source is a path, a Pathname or an IO-like object that responds to read.
9
+ # Caller-owned IO is closed only with close_io: true. A seekable IO is read
10
+ # from its position at construction on every pass; a non-seekable one can
11
+ # be read once.
12
+ #
13
+ # limits: a GpxKit::Limits, or a Hash of its keywords. Limits::DEFAULT
14
+ # unless given; Limits.none switches them off.
15
+ #
16
+ # Each message is yielded when its element closes, so a segment's points
17
+ # come before the segment and a track's segments before the track; the
18
+ # last message is :document. See Message and SPECIFICATION.md 6.2.
19
+ class Reader
20
+ attr_reader :source_label, :limits
21
+
22
+ def initialize(source, close_io: false, source_label: nil, limits: Limits::DEFAULT)
23
+ @close_io = close_io
24
+ @limits = Limits.coerce(limits)
25
+ @consumed = false
26
+ @closed_by_reader = false
27
+
28
+ # Pathname responds to read (it reads the whole file), so paths come first.
29
+ if source.is_a?(String) || source.is_a?(Pathname)
30
+ @path = source.to_s
31
+ @source_label = source_label || @path
32
+ elsif source.respond_to?(:read)
33
+ @io = source
34
+ @source_label = source_label || (source.respond_to?(:path) ? source.path : source.class.name)
35
+ @initial_position = initial_position(source)
36
+ raise ArgumentError, "close_io requires a closeable IO-like source" if @close_io && !source.respond_to?(:close)
37
+ elsif source.respond_to?(:to_path)
38
+ @path = source.to_path
39
+ @source_label = source_label || @path
40
+ else
41
+ raise ArgumentError, "source must be a filesystem path or an IO-like object"
42
+ end
43
+ end
44
+
45
+ def each_message(&block)
46
+ return enum_for(__method__) unless block
47
+
48
+ io, owned = open_io
49
+ begin
50
+ parser = XML::Parser.new(io, limits: @limits, source_label: @source_label)
51
+ builder = MessageBuilder.new { |message| parser.outside { block.call(message) } }
52
+ parser.each_event do |type, element|
53
+ check_root(element) if type == :start && element.depth == 1
54
+ builder.handle(type, element)
55
+ end
56
+ ensure
57
+ @closed_by_reader = true if @close_io && @io.equal?(io)
58
+ io.close if (owned || @close_io) && io.respond_to?(:close) && !(io.respond_to?(:closed?) && io.closed?)
59
+ end
60
+ nil
61
+ end
62
+
63
+ private
64
+
65
+ # The namespace decides the version. A gpx root without a namespace is
66
+ # read as the version its version attribute names (SPECIFICATION.md,
67
+ # decision 3).
68
+ def check_root(element)
69
+ unsupported(element, "The root element is #{short(element.name)}, not gpx") unless element.name == "gpx"
70
+ return if NAMESPACES.key?(element.namespace)
71
+
72
+ unsupported(element, "gpx is not in the GPX 1.1 or 1.0 namespace") unless element.namespace.nil?
73
+ version = element.attribute("version")&.value
74
+ return if NAMESPACES.value?(version)
75
+
76
+ unsupported(element, "gpx has no namespace and its version is not 1.1 or 1.0")
77
+ end
78
+
79
+ def unsupported(element, message)
80
+ raise UnsupportedFormatError.new(message, source: @source_label, line: element.line, column: element.column)
81
+ end
82
+
83
+ def short(name)
84
+ name.length > 64 ? "#{name[0, 64]}..." : name
85
+ end
86
+
87
+ def initial_position(io)
88
+ return unless io.respond_to?(:pos) && io.respond_to?(:seek)
89
+
90
+ io.pos
91
+ rescue IOError, Errno::ESPIPE
92
+ nil
93
+ end
94
+
95
+ def open_io
96
+ return [File.open(@path, "rb"), true] if @path
97
+
98
+ if @closed_by_reader || (@io.respond_to?(:closed?) && @io.closed?)
99
+ raise Error.new("The IO source is closed", source: @source_label)
100
+ end
101
+
102
+ if @initial_position
103
+ @io.seek(@initial_position)
104
+ elsif @consumed
105
+ raise Error.new("A non-seekable IO source can only be read once", source: @source_label)
106
+ else
107
+ @consumed = true
108
+ end
109
+ [@io, false]
110
+ end
111
+ end
112
+ end
@@ -0,0 +1,169 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GpxKit
4
+ # Field types per message and GPX version, written from TopoGrafix's GPX
5
+ # 1.1 and 1.0 schemas and the extension schemas named below (type names in
6
+ # comments). Extension schemas are not part of this repository.
7
+ #
8
+ # Keys are paths relative to the message element. A segment in the
9
+ # document's GPX namespace is its local name; one in a known extension
10
+ # namespace is the prefix below plus its local name ("tpx2:hr"); an
11
+ # attribute is "@" plus its name. A path with a segment in any other
12
+ # namespace never matches.
13
+ module Schema
14
+ T = Types
15
+
16
+ TRACK_POINT_EXTENSION_V1 = "http://www.garmin.com/xmlschemas/TrackPointExtension/v1"
17
+ TRACK_POINT_EXTENSION_V2 = "http://www.garmin.com/xmlschemas/TrackPointExtension/v2"
18
+ POWER_EXTENSION_V1 = "http://www.garmin.com/xmlschemas/PowerExtension/v1"
19
+ GPXDATA = "http://www.cluetrust.com/XML/GPXDATA/1/0"
20
+
21
+ PREFIXES = {
22
+ TRACK_POINT_EXTENSION_V1 => "tpx1",
23
+ TRACK_POINT_EXTENSION_V2 => "tpx2",
24
+ POWER_EXTENSION_V1 => "pwr",
25
+ GPXDATA => "gpxdata"
26
+ }.freeze
27
+
28
+ NON_NEGATIVE_INTEGER = T.integer(:non_negative_integer, min: 0, max: nil)
29
+ DGPS_STATION = T.integer(:dgps_station, min: 0, max: 1023, signed: true) # dgpsStationType
30
+ FIX = T.enumeration(:fix, %w[none 2d 3d dgps pps], preserve: true) # fixType, based on xsd:string
31
+ ANY_URI = T.token(:any_uri)
32
+
33
+ # latitudeType, longitudeType and degreesType differ between versions:
34
+ # 1.0 allows 180 and 360 themselves.
35
+ LATITUDE = T.decimal(:latitude, min: -90.0, max: 90.0)
36
+ LONGITUDE = {
37
+ "1.1" => T.decimal(:longitude, min: -180.0, max_exclusive: 180.0),
38
+ "1.0" => T.decimal(:longitude, min: -180.0, max: 180.0)
39
+ }.freeze
40
+ DEGREES = {
41
+ "1.1" => T.decimal(:degrees, min: 0.0, max_exclusive: 360.0),
42
+ "1.0" => T.decimal(:degrees, min: 0.0, max: 360.0)
43
+ }.freeze
44
+
45
+ def self.within(prefix, table)
46
+ table.transform_keys { |key| "#{prefix}/#{key}" }
47
+ end
48
+
49
+ def self.link(prefix = "link")
50
+ { "#{prefix}/@href" => ANY_URI, "#{prefix}/text" => T.string, "#{prefix}/type" => T.string }
51
+ end
52
+
53
+ def self.bounds(version)
54
+ { "bounds/@minlat" => LATITUDE, "bounds/@minlon" => LONGITUDE[version],
55
+ "bounds/@maxlat" => LATITUDE, "bounds/@maxlon" => LONGITUDE[version] }
56
+ end
57
+
58
+ # TrackPointExtension_t v1 (Garmin TrackPointExtensionv1.xsd).
59
+ TRACK_POINT_EXTENSION_FIELDS_V1 = {
60
+ "atemp" => T.double(:degrees_celsius),
61
+ "wtemp" => T.double(:degrees_celsius),
62
+ "depth" => T.double(:meters),
63
+ "hr" => T.integer(:beats_per_minute, min: 1, max: 255),
64
+ "cad" => T.integer(:revolutions_per_minute, min: 0, max: 254)
65
+ }.freeze
66
+
67
+ # TrackPointExtension_t v2 adds speed, course and bearing.
68
+ TRACK_POINT_EXTENSION_FIELDS_V2 = TRACK_POINT_EXTENSION_FIELDS_V1.merge(
69
+ "speed" => T.double(:meters_per_second),
70
+ "course" => T.decimal(:degrees_true, min: 0.0, max: 360.0),
71
+ "bearing" => T.decimal(:degrees_true, min: 0.0, max: 360.0)
72
+ ).freeze
73
+
74
+ # Extension elements of a point, as they appear inside it. In GPX 1.1 they
75
+ # sit in <extensions>; GPX 1.0 has no <extensions> and allows them directly.
76
+ POINT_EXTENSIONS = {
77
+ **TRACK_POINT_EXTENSION_FIELDS_V1.to_h { |name, spec| ["tpx1:TrackPointExtension/tpx1:#{name}", spec] },
78
+ **TRACK_POINT_EXTENSION_FIELDS_V2.to_h { |name, spec| ["tpx2:TrackPointExtension/tpx2:#{name}", spec] },
79
+ "pwr:PowerInWatts" => T.integer(:unsigned_short, min: 0, max: 65_535), # PowerExtensionv1.xsd
80
+ "gpxdata:hr" => NON_NEGATIVE_INTEGER, # gpxdata10.xsd
81
+ "gpxdata:cadence" => NON_NEGATIVE_INTEGER,
82
+ "gpxdata:temp" => T.decimal,
83
+ "gpxdata:distance" => T.decimal,
84
+ "gpxdata:distance/@sensor" => T.enumeration(:sensor_kind, %w[wheel pedometer])
85
+ }.freeze
86
+
87
+ # A bare <power> in <extensions>, as several exporters write it. No schema
88
+ # defines it; it is read as a decimal number of watts.
89
+ BARE_POWER = { "extensions/power" => T.decimal(:power) }.freeze
90
+
91
+ def self.point_extensions(version)
92
+ version == "1.1" ? within("extensions", POINT_EXTENSIONS).merge(BARE_POWER) : POINT_EXTENSIONS
93
+ end
94
+
95
+ # wptType (1.1); the waypoint, route point and track point elements (1.0).
96
+ def self.point(version, track_point:)
97
+ table = {
98
+ "@lat" => LATITUDE,
99
+ "@lon" => LONGITUDE[version],
100
+ "ele" => T.decimal,
101
+ "time" => T.date_time,
102
+ "magvar" => DEGREES[version],
103
+ "geoidheight" => T.decimal,
104
+ "name" => T.string, "cmt" => T.string, "desc" => T.string, "src" => T.string,
105
+ "sym" => T.string, "type" => T.string,
106
+ "fix" => FIX,
107
+ "sat" => NON_NEGATIVE_INTEGER,
108
+ "hdop" => T.decimal, "vdop" => T.decimal, "pdop" => T.decimal, "ageofdgpsdata" => T.decimal,
109
+ "dgpsid" => DGPS_STATION
110
+ }
111
+ if version == "1.1"
112
+ table.merge!(link)
113
+ else
114
+ table.merge!("url" => ANY_URI, "urlname" => T.string)
115
+ table.merge!("course" => DEGREES[version], "speed" => T.decimal) if track_point
116
+ end
117
+ table.merge(point_extensions(version)).freeze
118
+ end
119
+
120
+ # rteType and trkType (1.1); rte and trk (1.0, which has no type).
121
+ def self.route_or_track(version)
122
+ table = { "name" => T.string, "cmt" => T.string, "desc" => T.string, "src" => T.string, "number" => NON_NEGATIVE_INTEGER }
123
+ version == "1.1" ? table.merge(link, "type" => T.string).freeze : table.merge("url" => ANY_URI, "urlname" => T.string).freeze
124
+ end
125
+
126
+ # metadataType, personType, copyrightType, boundsType (1.1).
127
+ METADATA = {
128
+ "name" => T.string, "desc" => T.string,
129
+ "author/name" => T.string, "author/email/@id" => T.string, "author/email/@domain" => T.string,
130
+ **link("author/link"),
131
+ "copyright/@author" => T.string, "copyright/year" => T.g_year, "copyright/license" => ANY_URI,
132
+ **link,
133
+ "time" => T.date_time,
134
+ "keywords" => T.string,
135
+ **bounds("1.1")
136
+ }.freeze
137
+
138
+ # The gpx element: version and creator; in 1.0 also its own metadata.
139
+ def self.document(version)
140
+ table = { "@version" => T.string, "@creator" => T.string }
141
+ return table.freeze if version == "1.1"
142
+
143
+ table.merge(
144
+ "name" => T.string, "desc" => T.string, "author" => T.string, "email" => T.string,
145
+ "url" => ANY_URI, "urlname" => T.string, "time" => T.date_time, "keywords" => T.string, **bounds("1.0")
146
+ ).freeze
147
+ end
148
+
149
+ EMPTY = {}.freeze
150
+
151
+ TABLES = %w[1.1 1.0].to_h do |version|
152
+ waypoint = point(version, track_point: false)
153
+ [version, {
154
+ document: document(version),
155
+ metadata: version == "1.1" ? METADATA : EMPTY,
156
+ waypoint: waypoint,
157
+ route: route_or_track(version),
158
+ route_point: waypoint,
159
+ track: route_or_track(version),
160
+ track_segment: EMPTY,
161
+ track_point: point(version, track_point: true)
162
+ }.freeze]
163
+ end.freeze
164
+
165
+ def self.table(version, kind)
166
+ TABLES.fetch(version).fetch(kind, EMPTY)
167
+ end
168
+ end
169
+ end