コード例 #1
0
def main():
    parser = optparse.OptionParser(usage=usage)

    parser.add_option(
        "-a",
        "--attributes",
        dest="attrs",
        action="store_true",
        help="Print class attributes",
    )

    (options, args) = parser.parse_args()

    if len(args) != 1:
        parser.print_help()
        sys.exit(1)

    # The model file to load.
    model = args[0]

    # Create the Gaphor application object.
    session = Session()

    # Get services we need.
    element_factory = session.get_service("element_factory")
    file_manager = session.get_service("file_manager")

    # Load model from file.
    file_manager.load(model)

    # Find all classes using factory select.
    for cls in element_factory.select(UML.Class):

        print(f"Found class {cls.name}")

        if options.attrs:

            for attr in cls.ownedAttribute:

                print(f" Attribute: {attr.name}")
コード例 #2
0
ファイル: test_handletool.py プロジェクト: bellyfat/gaphor
def session():
    session = Session(services=[
        "event_manager",
        "component_registry",
        "element_factory",
        "main_window",
        "properties_manager",
        "properties",
        "namespace",
        "diagrams",
        "toolbox",
        "elementeditor",
        "export_menu",
        "tools_menu",
    ])
    main_window = session.get_service("main_window")
    main_window.open()
    yield session
    session.shutdown()
コード例 #3
0
ファイル: list_classes.py プロジェクト: bellyfat/gaphor
)

(options, args) = parser.parse_args()

if len(args) != 1:
    parser.print_help()
    sys.exit(1)

# The model file to load.
model = args[0]

# Create the Gaphor application object.
session = Session()

# Get services we need.
element_factory = session.get_service("element_factory")
file_manager = session.get_service("file_manager")

# Load model from file.
file_manager.load(model)

# Find all classes using factory select.
for cls in element_factory.select(lambda e: e.isKindOf(UML.Class)):

    print(f"Found class {cls.name}")

    if options.attrs:

        for attr in cls.ownedAttribute:

            print(f" Attribute: {attr.name}")
コード例 #4
0
ファイル: testcase.py プロジェクト: seryafarma/gaphor
class TestCase(unittest.TestCase):

    services = [
        "event_manager",
        "component_registry",
        "element_factory",
        "element_dispatcher",
        "modeling_language",
        "sanitizer",
    ]

    def setUp(self):
        self.session = Session(services=self.services)
        self.element_factory = self.session.get_service("element_factory")
        self.modeling_language = self.session.get_service("modeling_language")
        assert len(list(self.element_factory.select())) == 0, list(
            self.element_factory.select())
        self.diagram = self.element_factory.create(UML.Diagram)
        assert len(list(self.element_factory.select())) == 1, list(
            self.element_factory.select())

    def tearDown(self):
        self.element_factory.shutdown()
        self.session.shutdown()

    def get_service(self, name):
        return self.session.get_service(name)

    def create(self, item_cls: Type[T], subject_cls=None, subject=None) -> T:
        """
        Create an item with specified subject.
        """
        if subject_cls is not None:
            subject = self.element_factory.create(subject_cls)
        item = self.diagram.create(item_cls, subject=subject)
        self.diagram.canvas.update()
        return item

    def allow(self, line, handle, item, port=None):
        """
        Glue line's handle to an item.

        If port is not provided, then first port is used.
        """
        if port is None and len(item.ports()) > 0:
            port = item.ports()[0]

        adapter = Connector(item, line)
        return adapter.allow(handle, port)

    def connect(self, line, handle, item, port=None):
        """
        Connect line's handle to an item.

        If port is not provided, then first port is used.
        """
        canvas = line.canvas
        assert line.canvas is item.canvas

        if port is None and len(item.ports()) > 0:
            port = item.ports()[0]

        sink = ConnectionSink(item, port)
        connector = ConnectorAspect(line, handle)

        connector.connect(sink)

        cinfo = canvas.get_connection(handle)
        assert cinfo.connected is item
        assert cinfo.port is port

    def disconnect(self, line, handle):
        """
        Disconnect line's handle.
        """
        canvas = self.diagram.canvas
        # disconnection on adapter level is performed due to callback, so
        # no adapter look up here
        canvas.disconnect_item(line, handle)
        assert not canvas.get_connection(handle)

    def get_connected(self, handle):
        """
        Get item connected to line via handle.
        """
        cinfo = self.diagram.canvas.get_connection(handle)
        if cinfo:
            return cinfo.connected
        return None

    def get_connection(self, handle):
        """
        Get connection information.
        """
        return self.diagram.canvas.get_connection(handle)

    def can_group(self, parent, item):
        """
        Check if an item can be grouped by parent.
        """
        adapter = Group(parent, item)
        return adapter.can_contain()

    def group(self, parent, item):
        """
        Group item within a parent.
        """
        self.diagram.canvas.reparent(item, parent)
        adapter = Group(parent, item)
        adapter.group()

    def ungroup(self, parent, item):
        """
        Remove item from a parent.
        """
        adapter = Group(parent, item)
        adapter.ungroup()
        self.diagram.canvas.reparent(item, None)

    def kindof(self, cls):
        """
        Find UML metaclass instances using element factory.
        """
        return self.element_factory.lselect(cls)

    def save(self):
        """
        Save diagram into string.
        """
        from gaphor.storage import storage
        from gaphor.storage.xmlwriter import XMLWriter

        f = StringIO()
        storage.save(XMLWriter(f), factory=self.element_factory)
        data = f.getvalue()
        f.close()

        self.element_factory.flush()
        assert not list(self.element_factory.select())
        assert not list(self.element_factory.lselect())
        return data

    def load(self, data):
        """
        Load data from specified string. Update ``TestCase.diagram``
        attribute to hold new loaded diagram.
        """
        from gaphor.storage import storage

        f = StringIO(data)
        storage.load(f,
                     factory=self.element_factory,
                     modeling_language=self.modeling_language)
        f.close()

        self.diagram = self.element_factory.lselect(UML.Diagram)[0]
コード例 #5
0
def main(argv=sys.argv[1:]):
    def message(msg):
        """
        Print message if user set verbose mode.
        """
        if options.verbose:
            print(msg, file=sys.stderr)

    usage = "usage: %prog [options] file1 file2..."

    parser = optparse.OptionParser(usage=usage)

    parser.add_option("-v",
                      "--verbose",
                      dest="verbose",
                      action="store_true",
                      help="verbose output")
    parser.add_option(
        "-u",
        "--use-underscores",
        dest="underscores",
        action="store_true",
        help="use underscores instead of spaces for output filenames",
    )
    parser.add_option("-d",
                      "--dir",
                      dest="dir",
                      metavar="directory",
                      help="output to directory")
    parser.add_option(
        "-f",
        "--format",
        dest="format",
        metavar="format",
        help="output file format, default pdf",
        default="pdf",
        choices=["pdf", "svg", "png"],
    )
    parser.add_option(
        "-r",
        "--regex",
        dest="regex",
        metavar="regex",
        help="process diagrams which name matches given regular expresion;"
        " name includes package name; regular expressions are case insensitive",
    )

    (options, args) = parser.parse_args(argv)

    if not args:
        parser.print_help()

    session = Session(
        services=["event_manager", "component_registry", "element_factory"])
    factory = session.get_service("element_factory")

    name_re = None
    if options.regex:
        name_re = re.compile(options.regex, re.I)

    # we should have some gaphor files to be processed at this point
    for model in args:
        message(f"loading model {model}")
        storage.load(model, factory)
        message("ready for rendering")

        for diagram in factory.select(lambda e: e.isKindOf(UML.Diagram)):
            odir = pkg2dir(diagram.package)

            # just diagram name
            dname = diagram.name
            # full diagram name including package path
            pname = f"{odir}/{dname}"

            if options.underscores:
                odir = odir.replace(" ", "_")
                dname = dname.replace(" ", "_")

            if name_re and not name_re.search(pname):
                message(f"skipping {pname}")
                continue

            if options.dir:
                odir = f"{options.dir}/{odir}"

            outfilename = f"{odir}/{dname}.{options.format}"

            if not os.path.exists(odir):
                message(f"creating dir {odir}")
                os.makedirs(odir)

            message(f"rendering: {pname} -> {outfilename}...")

            view = View(diagram.canvas)
            view.painter = ItemPainter()

            tmpsurface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 0, 0)
            tmpcr = cairo.Context(tmpsurface)
            view.update_bounding_box(tmpcr)
            tmpcr.show_page()
            tmpsurface.flush()

            w, h = view.bounding_box.width, view.bounding_box.height
            if options.format == "pdf":
                surface = cairo.PDFSurface(outfilename, w, h)
            elif options.format == "svg":
                surface = cairo.SVGSurface(outfilename, w, h)
            elif options.format == "png":
                surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, int(w + 1),
                                             int(h + 1))
            else:
                assert False, f"unknown format {options.format}"
            cr = cairo.Context(surface)
            view.matrix.translate(-view.bounding_box.x, -view.bounding_box.y)
            paint(view, cr)
            cr.show_page()

            if options.format == "png":
                surface.write_to_png(outfilename)

            surface.flush()
            surface.finish()
コード例 #6
0
ファイル: gaphorconvert.py プロジェクト: tuxcell/gaphor
def main(argv=sys.argv[1:]):

    options, args = parse_options(argv)

    def message(msg):
        if options.verbose:
            print(msg, file=sys.stderr)

    session = Session(
        services=[
            "event_manager",
            "component_registry",
            "element_factory",
            "element_dispatcher",
            "modeling_language",
            "diagram_export",
        ]
    )
    factory = session.get_service("element_factory")
    modeling_language = session.get_service("modeling_language")
    diagram_export = session.get_service("diagram_export")

    name_re = None
    if options.regex:
        name_re = re.compile(options.regex, re.I)

    # we should have some gaphor files to be processed at this point
    for model in args:
        message(f"loading model {model}")
        storage.load(model, factory, modeling_language)
        message("ready for rendering")

        for diagram in factory.select(Diagram):
            odir = pkg2dir(diagram.package)

            # just diagram name
            dname = diagram.name
            # full diagram name including package path
            pname = f"{odir}/{dname}"

            if options.underscores:
                odir = odir.replace(" ", "_")
                dname = dname.replace(" ", "_")

            if name_re and not name_re.search(pname):
                message(f"skipping {pname}")
                continue

            if options.dir:
                odir = f"{options.dir}/{odir}"

            outfilename = f"{odir}/{dname}.{options.format}"

            if not os.path.exists(odir):
                message(f"creating dir {odir}")
                os.makedirs(odir)

            message(f"rendering: {pname} -> {outfilename}...")

            if options.format == "pdf":
                diagram_export.save_pdf(outfilename, diagram)
            elif options.format == "svg":
                diagram_export.save_svg(outfilename, diagram)
            elif options.format == "png":
                diagram_export.save_png(outfilename, diagram)
            else:
                raise RuntimeError(f"Unknown file format: {options.format}")