Source

xibgraph / xibgraph.py

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
#!/usr/bin/python

# Copyright (c) 2010 Juri Pakaste
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

# PyObjC is the easiest way to get access to XPath with the default Python
from AppKit import *

import os
import sys


class ParsedConnection(object):
    def __init__(self, sourceref, destinationref, fields):
        self.sourceref = sourceref
        self.destinationref = destinationref
        self.fields = fields


    def __unicode__(self):
        return "<%s.%s object at %#x: sourceref=%s destinationref=%s>" % (self.__module__, self.__class__.__name__, id(self), self.sourceref, self.destinationref)


    @classmethod
    def create_from_element_with_xpaths(klass, elem, xpaths, switch_endpoints = False):
        sources, err = elem.nodesForXPath_error_(
            "reference[@key='source']/@ref", None)
        if err or len(sources) != 1:
            raise Exception("Failed reading source: %s, %s" % (err, sources))
        destinations, err = elem.nodesForXPath_error_(
            "reference[@key='destination']/@ref", None)
        if err or len(destinations) != 1:
            raise Exception(
                "Failed reading destination: %s, %s" % (err, destinations))
        foundvalues = {}
        for name, xpath in xpaths.items():
            xpelems, err = elem.nodesForXPath_error_(xpath, None)
            if err or len(xpelems) != 1:
                raise Exception("Failed reading %s with XPath %s: %s", name, xpath, err)
            foundvalues[name] = xpelems[0].stringValue()

        endpoints = (sources, destinations) if not switch_endpoints else (destinations, sources)
        return klass(*([e[0].stringValue() for e in endpoints] +
                       [foundvalues]))



class Binding(object):
    def __init__(self, source, destination, binding, keypath):
        self.source = source
        self.destination = destination
        self.binding = binding
        self.keypath = keypath


    def __unicode__(self):
        return "<%s.%s object at %#x: source=%#x destination=%#x binding=%s keypath=%s>" % (self.__module__, self.__class__.__name__, id(self), id(self.source), id(self.destination), self.binding, self.keypath)



class ActionConnection(object):
    def __init__(self, label, source, destination):
        self.label = label
        self.source = source
        self.destination = destination


    def __unicode__(self):
        return "<%s.%s object at %#x: label=%s source=%#x destination=%#x>" % (self.__module__, self.__class__.__name__, id(self), self.label, id(self.source), id(self.destination))



class OutletConnection(object):
    def __init__(self, label, source, destination):
        self.label = label
        self.source = source
        self.destination = destination


    def __unicode__(self):
        return "<%s.%s object at %#x: label=%s source=%#x destination=%#x>" % (self.__module__, self.__class__.__name__, id(self), self.label, id(self.source), id(self.destination))



class IBObject(object):
    def __init__(self, identifier, object_class, ibname):
        self.identifier = identifier
        self.object_class = object_class
        self.ibname = ibname
        self.bindings = []
        self.actions = []
        self.outlets = []
        return


    @classmethod
    def create_from_element(klass, elem, identifier, name):
        obclasses, err = elem.nodesForXPath_error_("@class", None)
        if err or len(obclasses) != 1:
            raise Exception("Failed to parse class: %s, %s" % (err, obclasses))
        obclassname = obclasses[0].stringValue()
        if obclassname in ('NSCustomObject', 'NSCustomView'):
            # try to find proper class name
            classnames, err = elem.nodesForXPath_error_(
                "string[@key='NSClassName']/child::text()", None)
            if err:
                raise Exception(
                    "Failed when trying to find NSClassName for %s: %s" % (obclassname, err))
            if len(classnames) == 1:
                obclassname = classnames[0].stringValue()
        return klass(identifier, obclassname, name)


    def __unicode__(self):
        return "<%s.%s object at %#x: identifier=%s object_class=%s ibname=%s>" % (self.__module__, self.__class__.__name__, id(self), self.identifier, self.object_class, self.ibname)



def parse_xib(xiburl):
    doc, err = NSXMLDocument.alloc().initWithContentsOfURL_options_error_(xiburl, 0, None)
    if err:
        raise Exception("Failed to read xml file at %s: %s" % (xiburl, err))
    return doc


def create_strategy_for_document(doc):
    root = doc.rootElement()
    archtypes, err = root.nodesForXPath_error_("@type", None)
    if err or len(archtypes) != 1:
        raise Exception("Couldn't find type for root element: %s, %s", err, archtypes)
    archtype = archtypes[0].stringValue()
    if archtype == "com.apple.InterfaceBuilder3.Cocoa.XIB":
        return CocoaIB3Strategy()
    elif archtype == "com.apple.InterfaceBuilder3.CocoaTouch.XIB":
        return CocoaTouchIB3Strategy()
    raise Exception("Unknown archive type %s" % archtype)


class CocoaTouchIB3Strategy(object):
    def find_nodes_with_path(self, doc, path):
        root = doc.rootElement()
        nodes, err = root.nodesForXPath_error_(path, None)
        if err:
            raise Exception("Failed finding nodes with XPath: %s" % err)
        return nodes


    def find_binding_nodes(self, doc):
        return []


    def find_object_node(self, doc, ref):
        root = doc.rootElement()
        object_nodes, err = root.nodesForXPath_error_(
            "//object[@id='%s']" % ref,
            None)
        if err:
            raise Exception("Failed finding object node with XPath: %s", err)
        if len(object_nodes) != 1:
            raise Exception("Expected one object node, got %s", str(object_nodes))
        return object_nodes[0]


    def find_object_name(self, doc, ref):
        root = doc.rootElement()
        nodes, err = root.nodesForXPath_error_(
            "//object[@class='IBObjectRecord']/reference[@ref='%s'][@key='object']/parent::*/string[@key='objectName']/child::text()" % ref,
            None)
        if err:
            raise Exception("Failed finding object name with XPath: %s", err)
        if len(nodes) > 1:
            raise Exception("Too many nodes found: %s" % str(nodes))
        return nodes[0].stringValue() if nodes else None


    def find_action_connections(self, doc):
        elems = self.find_nodes_with_path(
            doc,
            "//object[@class='IBCocoaTouchEventConnection'][@key='connection']")
        return [ParsedConnection.create_from_element_with_xpaths(
                elem,
                {"label": "string[@key='label']/child::text()"}, switch_endpoints = False)
                for elem in elems]


    def find_outlet_nodes(self, doc):
        return self.find_nodes_with_path(
            doc,
            "//object[@class='IBCocoaTouchOutletConnection'][@key='connection']")


class CocoaIB3Strategy(object):
    def find_nodes_with_path(self, doc, path):
        root = doc.rootElement()
        nodes, err = root.nodesForXPath_error_(path, None)
        if err:
            raise Exception("Failed finding nodes with XPath: %s" % err)
        return nodes


    def find_binding_nodes(self, doc):
        return self.find_nodes_with_path(doc, "//object[@class='IBBindingConnection']")
    
    
    def find_object_node(self, doc, ref):
        root = doc.rootElement()
        object_nodes, err = root.nodesForXPath_error_(
            "//object[@id='%s']" % ref,
            None)
        if err:
            raise Exception("Failed finding object node with XPath: %s", err)
        if len(object_nodes) != 1:
            raise Exception("Expected one object node, got %s", str(object_nodes))
        return object_nodes[0]


    def find_object_name(self, doc, ref):
        root = doc.rootElement()
        nodes, err = root.nodesForXPath_error_(
            "//object[@class='IBObjectRecord']/reference[@ref='%s'][@key='object']/parent::*/string[@key='objectName']/child::text()" % ref,
            None)
        if err:
            raise Exception("Failed finding object name with XPath: %s", err)
        if len(nodes) > 1:
            raise Exception("Too many nodes found: %s" % str(nodes))
        return nodes[0].stringValue() if nodes else None


    def find_action_connections(self, doc):
        elems = self.find_nodes_with_path(
            doc,
            "//object[@class='IBActionConnection'][@key='connection']")
        return [ParsedConnection.create_from_element_with_xpaths(
                elem,
                {"label": "string[@key='label']/child::text()"}, switch_endpoints = True)
                for elem in elems]


    def find_outlet_nodes(self, doc):
        return self.find_nodes_with_path(
            doc,
            "//object[@class='IBOutletConnection'][@key='connection']")




class Xib(object):
    def __init__(self, doc, doc_strategy):
        self.doc = doc
        self.doc_strategy = doc_strategy
        self.objects = {}


    def endpoints_from_parsed_connection(self, pcon):
        if self.objects.has_key(pcon.sourceref):
            sourceob = self.objects[pcon.sourceref]
        else:
            sourcenode = self.doc_strategy.find_object_node(self.doc, pcon.sourceref)
            sourcename = self.doc_strategy.find_object_name(self.doc, pcon.sourceref)
            sourceob = IBObject.create_from_element(
                sourcenode, pcon.sourceref, sourcename)
            self.objects[pcon.sourceref] = sourceob

        if self.objects.has_key(pcon.destinationref):
            destob = self.objects[pcon.destinationref]
        else:
            destnode = self.doc_strategy.find_object_node(self.doc, pcon.destinationref)
            destname = self.doc_strategy.find_object_name(self.doc, pcon.destinationref)
            destob = IBObject.create_from_element(
                destnode, pcon.destinationref, destname)
            self.objects[pcon.destinationref] = destob
        return (sourceob, destob)


    def find_objects_and_bindings(self):
        bindingelems = self.doc_strategy.find_binding_nodes(self.doc)
        bindings = []
        boundobjects = {}
        cxpath = "object[@class='NSNibBindingConnector']"
        for binding in bindingelems:
            pb = ParsedConnection.create_from_element_with_xpaths(
                binding,
                {"binding": "%s/string[@key='NSBinding']/child::text()" % cxpath,
                 "keypath": "%s/string[@key='NSKeyPath']/child::text()" % cxpath})
            sourceob, destob = self.endpoints_from_parsed_connection(pb)

            boundobjects[pb.sourceref] = sourceob
            boundobjects[pb.destinationref] = destob

            bindob = Binding(sourceob, destob, pb.fields['binding'], pb.fields['keypath'])
            sourceob.bindings.append(bindob)
            bindings.append(bindob)

        return (boundobjects, bindings)


    def find_objects_and_actions(self):
        parsedactions = self.doc_strategy.find_action_connections(self.doc)
        actions = []
        actionobjects = {}
        for pa in parsedactions:
            sourceob, destob = self.endpoints_from_parsed_connection(pa)

            actionobjects[pa.sourceref] = sourceob
            actionobjects[pa.destinationref] = destob

            actionob = ActionConnection(pa.fields['label'], sourceob, destob)
            sourceob.actions.append(actionob)
            actions.append(actionob)

        return (actionobjects, actions)


    def find_objects_and_outlets(self):
        elems = self.doc_strategy.find_outlet_nodes(self.doc)
        outlets = []
        outletobjects = {}
        for outlet in elems:
            pa = ParsedConnection.create_from_element_with_xpaths(
                outlet,
                {"label": "string[@key='label']/child::text()"})
            sourceob, destob = self.endpoints_from_parsed_connection(pa)

            outletobjects[pa.sourceref] = sourceob
            outletobjects[pa.destinationref] = destob

            outletob = OutletConnection(pa.fields['label'], sourceob, destob)
            sourceob.outlets.append(outletob)
            outlets.append(outletob)

        return (outletobjects, outlets)



def output_text(objects, bindings, actions, outlets, stream=sys.stdout, **kwargs):
    for ob in objects.values():
        stream.write((u"object: %s\n" % ob).encode("utf-8"))
    for b in bindings:
        stream.write((u"binding: %s\n" % b).encode("utf-8"))
    for a in actions:
        stream.write((u"action: %s\n" % a).encode("utf-8"))
    for o in outlets:
        stream.write((u"outlet: %s\n" % o).encode("utf-8"))


def output_dot(objects, bindings, actions, outlets, stream=sys.stdout, **kwargs):
    try:
        import pydot
    except Exception, e:
        raise Exception("Couldn't import pydot, unable to generate dot: %s" % e)

    graph = pydot.Graph(fontname="Helvetica", charset="UTF-8")
    name_counts = {}
    used_names = {}
    node_count = 0
    for object in objects.values():
        basename = object.ibname if object.ibname else "Unnamed"
        name_count = name_counts.get(basename, 0)
        name_counts[basename] = name_count + 1
        if name_count:
            name = "%s %d" % (basename, name_count + 1)
        else:
            name = basename
        if kwargs.has_key('no_dot_html'):
            fmtname = "%s\\n%s" % (name, object.object_class)
            shape = "record"
        else:
            fmtname = "<<font point-size=\"10\">%s</font><BR/><font point-size=\"8\">%s</font>>" % (name, object.object_class)
            shape = "ellipse"

        nodeid = "node %d" % node_count
        node_count += 1
        used_names[object] = nodeid

        fillcolor = "transparent"
        if object.object_class.startswith("UI") or object.object_class.startswith("NS"):
            # different bg color for apple's classes
            fillcolor = "#f0f0f0"

        node = pydot.Node(nodeid, shape=shape, label=fmtname,
                          fontname="Helvetica", fillcolor=fillcolor,
                          style="filled")
        graph.add_node(node)

    for binding in bindings:
        if kwargs.has_key('no_dot_html'):
            label = "Controller Key = %s\\nKey Path = %s" % (binding.binding, binding.keypath)
        else:
            label = "<Controller Key: %s<BR/>Key Path: %s>" % (binding.binding, binding.keypath)

        edge = pydot.Edge(used_names[binding.source],
                          used_names[binding.destination],
                          label=label,
                          fontname="Helvetica",
                          fontsize="10")
        graph.add_edge(edge)

    for action in actions:
        if kwargs.has_key('no_dot_html'):
            label = "Message = %s" % action.label
        else:
            label = "<Message: %s>" % action.label
        edge = pydot.Edge(used_names[action.source],
                          used_names[action.destination],
                          label=label,
                          fontname="Helvetica",
                          fontsize="10",
                          arrowhead="vee")
        graph.add_edge(edge)

    for outlet in outlets:
        if kwargs.has_key('no_dot_html'):
            label = "Name = %s" % outlet.label
        else:
            label = "<Name: %s>" % outlet.label
        edge = pydot.Edge(used_names[outlet.source],
                          used_names[outlet.destination],
                          label=label,
                          fontname="Helvetica",
                          fontsize="10",
                          arrowhead="empty")
        graph.add_edge(edge)

    stream.write(graph.to_string().encode("utf-8"))


def output_json(objects, bindings, actions, outlets, stream=sys.stdout, **kwargs):
    import json

    class XIBEncoder(json.JSONEncoder):
        def default(self, obj):
            if isinstance(obj, IBObject):
                return {'object': id(obj),
                        'class': obj.object_class,
                        'name': obj.ibname}
            elif isinstance(obj, Binding):
                return {'source': id(obj.source),
                        'destination': id(obj.destination),
                        'controller_key': obj.binding,
                        'keypath': obj.keypath}
            elif isinstance(obj, ActionConnection):
                return {'source': id(obj.source),
                        'destination': id(obj.destination),
                        'message': obj.label}
            elif isinstance(obj, OutletConnection):
                return {'source': id(obj.source),
                        'destination': id(obj.destination),
                        'name': obj.label}

            return json.JSONEncoder.default(self, obj)
    
    json.dump({'objects': objects.values(),
               'bindings': bindings,
               'actions': actions,
               'outlets': outlets},
              stream, cls=XIBEncoder, sort_keys=True, indent=4)

    

def run_command():
    from optparse import OptionParser

    parser = OptionParser()
    parser.set_defaults(format="json")
    parser.set_defaults(format_flags=[])
    parser.set_defaults(connections=[])
    parser.add_option("-t", "--text", action="store_const", const="text",
                      dest="format", help="Output in textual format")
    parser.add_option("-d", "--dot", action="store_const", const="dot",
                      dest="format", help="Output in DOT format")
    parser.add_option("-j", "--json", action="store_const", const="json",
                      dest="format", help="Output in JSON format [default]")
    parser.add_option("", "--no-dot-html", action="append_const", const="no_dot_html",
                      dest="format_flags", help="Don't use HTML in DOT output")
    parser.add_option("-a", "--actions", action="append_const", const="actions",
                      dest="connections", help="Output actions")
    parser.add_option("-b", "--bindings", action="append_const", const="bindings",
                      dest="connections", help="Output bindings")
    parser.add_option("-o", "--outlets", action="append_const", const="outlets",
                      dest="connections", help="Output outlets")

    options, args = parser.parse_args()

    if len(args) != 1:
        parser.error("one argument file name is required")

    p = os.path.abspath(args[0])
    url = NSURL.fileURLWithPath_(p)
    xibdoc = parse_xib(url)
    doc_strategy = create_strategy_for_document(xibdoc)
    xib = Xib(xibdoc, doc_strategy)
    objects = {}
    bindings = []
    actions = []
    outlets = []

    if "bindings" in options.connections:
        (bobjects, bindings) = xib.find_objects_and_bindings()
        objects.update(bobjects)

    if "actions" in options.connections:
        (aobjects, actions) = xib.find_objects_and_actions()
        objects.update(aobjects)

    if "outlets" in options.connections:
        (oobjects, outlets) = xib.find_objects_and_outlets()
        objects.update(oobjects)

    flagargs = dict(zip(options.format_flags, (True,)*len(options.format_flags)))

    output_fun = globals()['output_' + options.format]
    output_fun(objects, bindings, actions, outlets, **flagargs)
    


if __name__ == '__main__':
    run_command()