def __init__(self): self.conf_file_path = "configuration.xml" self.recent_files = [] # self.default_directory = "/tmp/%l/%n-%t" from mosaicode.system import System self.default_directory = os.path.join(System.get_user_dir(), "code-gen") self.default_filename = "%n" self.grid = 10 self.port = 49151 # GUI stuff self.width = 900 self.height = 500 self.hpaned_work_area = 150 self.vpaned_bottom = 450 self.vpaned_left = 300 self.connection = "Curve"
def __init__(self, main_window): """ This method is the constructor. """ Gtk.Dialog.__init__(self, title=_("Preferences"), transient_for=main_window) self.add_buttons(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL) self.add_buttons(Gtk.STOCK_OK, Gtk.ResponseType.OK) self.main_window = main_window self.properties = System.get_preferences() box = self.get_content_area() box.set_border_width(3) self.tabs = Gtk.Notebook() box.add(self.tabs) # User preferences # ---------------------------------------------------------------------- self.user_preferences_tab = Gtk.Box() self.user_preferences_tab.set_border_width(10) label = Gtk.Label(label=_("User Preferences")) self.tabs.append_page(self.user_preferences_tab, label) self.__create_user_preferences_tab() # Default directory # ---------------------------------------------------------------------- self.default_directory_tab = Gtk.Box() self.default_directory_tab.set_border_width(10) label = Gtk.Label(label=_("Default Directory")) self.tabs.append_page(self.default_directory_tab, label) self.__create_default_directory_tab() # Grid Preferences # ---------------------------------------------------------------------- self.grid_preferences_tab = Gtk.Box() self.grid_preferences_tab.set_border_width(10) label = Gtk.Label(label=_("Grid Preferences")) self.tabs.append_page(self.grid_preferences_tab, label) self.__create_grid_preferences_tab() self.show_all()
def update(self): languages = [] while self.get_n_pages() > 0: self.remove_page(0) System() for x in System.plugins: instance = System.plugins[x] name = instance.language name += "/" + instance.framework if name in languages: continue languages.append(name) for language in languages: treeview = BlocksTreeView(self.main_window, language) self.append_page(treeview, Gtk.Label(language)) self.show_all()
def save(cls, code_template): """ This method save the code_template in user space. Returns: * **Types** (:class:`boolean<boolean>`) """ from mosaicode.system import System code_template.source = "xml" parser = XMLParser() parser.addTag('MosaicodeCodeTemplate') parser.setTagAttr('MosaicodeCodeTemplate', 'name', code_template.name) parser.setTagAttr('MosaicodeCodeTemplate', 'type', code_template.type) parser.setTagAttr('MosaicodeCodeTemplate', 'description', code_template.description) parser.setTagAttr('MosaicodeCodeTemplate', 'language', code_template.language) parser.setTagAttr('MosaicodeCodeTemplate', 'extension', code_template.extension) parser.setTagAttr('MosaicodeCodeTemplate', 'source', code_template.source) parser.appendToTag('MosaicodeCodeTemplate', 'command').string = str(code_template.command) parser.appendToTag('MosaicodeCodeTemplate', 'code').string = str(code_template.code) try: data_dir = System.get_user_dir() + "/extensions/" data_dir = data_dir + code_template.language + "/" if not os.path.isdir(data_dir): try: os.makedirs(data_dir) except: pass file_name = data_dir + code_template.type + ".xml" code_template_file = file(os.path.expanduser(file_name), 'w') code_template_file.write(parser.prettify()) code_template_file.close() except IOError as e: return False return True
def save_python(cls, plugin): """ This method save the port in user space in python extension. Returns: * **Types** (:class:`boolean<boolean>`) """ from mosaicode.system import System parser = PythonParser() parser.class_name = plugin.label.replace(' ', '') parser.dependencies = [{'from':'mosaicode.model.plugin', 'import':'Plugin'}] parser.inherited_classes = ['Plugin'] parser.setAttribute('id', plugin.id) parser.setAttribute('type', plugin.type) parser.setAttribute('language', plugin.language) parser.setAttribute('framework', 'python') parser.setAttribute('source', plugin.source) parser.setAttribute('help', plugin.help) parser.setAttribute('label', plugin.label) parser.setAttribute('color', plugin.color) parser.setAttribute('group', plugin.group) parser.setAttribute('help', plugin.help) parser.setAttribute('in_ports', plugin.in_ports) parser.setAttribute('out_ports', plugin.out_ports) parser.setAttribute('properties', plugin.properties) parser.setAttribute('codes', plugin.codes) try: data_dir = System.get_user_dir() + "/extensions/" data_dir = data_dir + plugin.language + "/" + plugin.framework + "/" if not os.path.isdir(data_dir): try: os.makedirs(data_dir) except: pass file_name = data_dir + plugin.label.lower().replace(' ', '_') + ".py" parser.save(file_name) except IOError as e: return False return True
def load(cls): """ This method loads the diagram. Returns: * **Types** (:class:`boolean<boolean>`) """ prefs = Preferences() from mosaicode.system import System file_name = System.get_user_dir() + "/" + prefs.conf_file_path file_name = os.path.expanduser(file_name) if os.path.exists(file_name) is False: return prefs parser = XMLParser(file_name) if parser.getTag("MosaicodeProperties") is None: return prefs try: prefs.default_directory = parser.getTagAttr("MosaicodeProperties", "default_directory") prefs.default_filename = parser.getTagAttr("MosaicodeProperties", "default_filename") prefs.grid = int(parser.getTagAttr("MosaicodeProperties","grid")) prefs.width = int(parser.getTagAttr("MosaicodeProperties","width")) prefs.height = int(parser.getTagAttr("MosaicodeProperties", "height")) prefs.hpaned_work_area = int(parser.getTagAttr("MosaicodeProperties", "hpaned_work_area")) prefs.vpaned_bottom = int(parser.getTagAttr("MosaicodeProperties", "vpaned_bottom")) prefs.vpaned_left = int(parser.getTagAttr("MosaicodeProperties", "vpaned_left")) files = parser.getTag("MosaicodeProperties").getTag( "recent_files").getChildTags("name") for file_name in files: prefs.recent_files.append(file_name.getAttr("value")) except: pass return prefs
def update_recent_files(self): """ This method update recent files. """ list_of_recent_files = System.get_preferences().recent_files for widget in self.recent_files_menu.get_children(): self.recent_files_menu.remove(widget) if list_of_recent_files is None or len(list_of_recent_files) == 0: menu_item = Gtk.MenuItem.new_with_label(_("<empty>")) self.recent_files_menu.append(menu_item) self.recent_files_menu.show_all() return False for index, recent_file in enumerate(list_of_recent_files): menu_item = Gtk.MenuItem.new_with_label(recent_file) self.recent_files_menu.append(menu_item) menu_item.connect("activate", self.__load_recent, None) self.recent_files_menu.show_all()
def test_load_ports(self): block = self.create_block() # if it is not a dictionary block.ports.append("x") # if "type" not in port: block.ports.append({"label": "Output", "conn_type": "Output", "name": "output"}) # if "conn_type" not in port block.ports.append({"type": "Output", "label": "Output", "name": "output"}) # Port ok block.ports.append({"type": "Output", "label": "Output", "conn_type": "Output", "name": "output"}) BlockControl.load_ports(block, System.get_ports())
def create_block(self, diagram_control=None): if diagram_control is None: diagram_control = self.create_diagram_control() block_model = BlockModel() port0 = Port() port0.label = "Test0" port0.conn_type = Port.OUTPUT port0.name = "Test0" port0.type = "Test" port0.index = 0 port1 = Port() port1.label = "Test1" port1.conn_type = Port.INPUT port1.name = "Test1" port1.type = "Test" port1.index = 1 block_model.ports = [port0, port1] block_model.help = "Test" block_model.label = "Test" block_model.color = "200:200:25:150" block_model.group = "Test" block_model.codes = {"code0": "Test", "Code1": "Test", "Code2": "Test"} block_model.type = "Test" block_model.language = "Test" block_model.properties = [{ "name": "test", "label": "Test", "value": "0", "type": MOSAICODE_FLOAT }] block_model.extension = "Test" block_model.file = None block = Block(diagram_control.diagram, block_model) System.get_blocks()[block.type] = block return block
def save_python(cls, port): """ This method save the port in user space in python extension. Returns: * **Types** (:class:`boolean<boolean>`) """ from mosaicode.system import System parser = PythonParser() parser.class_name = port.label.replace(' ', '') parser.dependencies = [{'from':'mosaicode.model.port', 'import':'Port'}] parser.inherited_classes = ['Port'] parser.setAttribute('type', port.type) parser.setAttribute('language', port.language) parser.setAttribute('label', port.label) parser.setAttribute('color', port.color) parser.setAttribute('multiple', port.multiple) parser.setAttribute('source', 'python') parser.setAttribute('code', str(port.code)) parser.setAttribute('input_codes', []) parser.setAttribute('output_codes', []) for index, code in enumerate(port.input_codes, start=0): parser.attributes['input_codes'].append(str(port.input_codes[index])) parser.attributes['output_codes'].append(str(port.output_codes[index])) try: data_dir = System.get_user_dir() + "/extensions/" data_dir = data_dir + port.language + "/ports/" if not os.path.isdir(data_dir): try: os.makedirs(data_dir) except: pass file_name = data_dir + port.label.lower().replace(' ', '_') + ".py" parser.save(file_name) except IOError as e: return False return True
def save_python(cls, code_template): """ This method save the codetemplate in user space in python extension. Returns: * **Types** (:class:`boolean<boolean>`) """ from mosaicode.system import System parser = PythonParser() parser.class_name = code_template.name.replace(' ', '') parser.dependencies = [{ 'from': 'mosaicode.model.codetemplate', 'import': 'CodeTemplate' }] parser.inherited_classes = ['CodeTemplate'] parser.setAttribute('type', code_template.type) parser.setAttribute('name', code_template.name) parser.setAttribute('description', code_template.description) parser.setAttribute('language', code_template.language) parser.setAttribute('command', code_template.command) parser.setAttribute('extension', code_template.extension) parser.setAttribute('code', code_template.code) parser.setAttribute('source', 'python') try: data_dir = System.get_user_dir() + "/extensions/" data_dir = data_dir + code_template.language + "/" if not os.path.isdir(data_dir): try: os.makedirs(data_dir) except: pass file_name = data_dir + code_template.name.lower().replace( ' ', '_') + ".py" parser.save(file_name) except IOError as e: return False return True
def __create_side_panel(self, configuration): self.__clean_side_panel() connectors = [] ports = System.get_ports() for key in ports: if ports[key].language == self.block.language: connectors.append(key) data = {"label": _("Port Type"), "name": "type", "values": connectors} field = ComboField(data, None) self.side_panel.pack_start(field, False, False, 1) if configuration is not None: field.set_value(configuration.type) data = { "label": _("Connection Type"), "name": "conn_type", "values": [Port.INPUT, Port.OUTPUT] } field = ComboField(data, None) self.side_panel.pack_start(field, False, False, 1) if configuration is not None: field.set_value(configuration.conn_type) data = {"label": _("Label"), "name": "label"} field = StringField(data, None) self.side_panel.pack_start(field, False, False, 1) if configuration is not None: field.set_value(configuration.label) data = {"label": _("Name"), "name": "name"} field = StringField(data, None) self.side_panel.pack_start(field, False, False, 1) if configuration is not None: field.set_value(configuration.name) button = Gtk.Button.new_with_label("Save") button.connect("clicked", self.__on_save, None) self.side_panel.pack_start(button, False, False, 1) self.side_panel.show_all()
def save(self, save_as=False): """ This method save the file. """ diagram = self.main_window.work_area.get_current_diagram() if diagram is None: return False if diagram.file_name is "Untitled" or save_as: while True: dialog = SaveDialog(self.main_window, title=_("Save Diagram"), filename=System.get_user_dir() + "/" + diagram.file_name, filetype="*.mscd") name = dialog.run() if name is None: continue if not name.endswith("mscd"): name = (("%s" + ".mscd") % name) if os.path.exists(name) is True: msg = _("File exists. Overwrite?") result = ConfirmDialog(msg, self.main_window).run() if result == Gtk.ResponseType.CANCEL: continue diagram.file_name = name self.main_window.work_area.rename_diagram(diagram) break result, message = False, "" if diagram.file_name is not None: if len(diagram.file_name) > 0: result, message = DiagramControl(diagram).save() self.set_recent_files(diagram.file_name) if not result: MessageDialog("Error", message, self.main_window).run()
def save(cls, prefs): """ This method save the diagram. Returns: * **Types** (:class:`boolean<boolean>`) """ parser = XMLParser() parser.addTag('MosaicodeProperties') parser.setTagAttr('MosaicodeProperties','default_directory', prefs.default_directory) parser.setTagAttr('MosaicodeProperties','default_filename', prefs.default_filename) parser.setTagAttr('MosaicodeProperties','grid', prefs.grid) parser.setTagAttr('MosaicodeProperties','width', prefs.width) parser.setTagAttr('MosaicodeProperties','height', prefs.height) parser.setTagAttr('MosaicodeProperties','hpaned_work_area', prefs.hpaned_work_area) parser.setTagAttr('MosaicodeProperties','vpaned_bottom', prefs.vpaned_bottom) parser.setTagAttr('MosaicodeProperties','vpaned_left', prefs.vpaned_left) parser.appendToTag('MosaicodeProperties', 'recent_files') for key in prefs.recent_files: parser.appendToTag('recent_files', 'name', value=key) try: from mosaicode.system import System file_name = System.get_user_dir() + "/" + prefs.conf_file_path confFile = file(os.path.expanduser(file_name), 'w') confFile.write(parser.prettify()) confFile.close() except IOError as e: return False return True
def save_source(cls, diagram=None, codes=None, generator=None): if diagram is None: return False, "Diagram is None" if generator is None: generator, message = CodeGenerator.get_code_generator(diagram) if generator is None: return False, message if codes is None: files = generator.generate_code() else: files = codes for key in files: file_name = System.get_dir_name(diagram) + key try: codeFile = open(file_name, 'w') codeFile.write(files[key]) codeFile.close() except Exception as error: return False, "Could not save file" return True, "Saving code to " + file_name
def __get_code_generator(self, diagram): if diagram.language is None: message = "You shall not generate code of an empty diagram!" Dialog().message_dialog("Error", message, self.main_window) return None template_list = [] code_templates = System.get_code_templates() for key in code_templates: if code_templates[key].language == diagram.language: template_list.append(code_templates[key]) if len(template_list) == 0: message = "Generator not available for the language " + diagram.language + "." Dialog().message_dialog("Error", message, self.main_window) return None if len(template_list) == 1: return CodeGenerator(diagram, template_list[0]) select = SelectCodeTemplate(self.main_window, template_list) code_template = select.get_value() return CodeGenerator(diagram, code_template)
def save(cls, port): """ This method save the port in user space. Returns: * **Types** (:class:`boolean<boolean>`) """ from mosaicode.system import System port.source = "xml" parser = XMLParser() parser.addTag(tag_name) parser.setTagAttr(tag_name, 'type', port.type) parser.setTagAttr(tag_name, 'language', port.language) parser.setTagAttr(tag_name, 'hint', port.hint) parser.setTagAttr(tag_name, 'color', port.color) parser.setTagAttr(tag_name, 'multiple', port.multiple) parser.setTagAttr(tag_name, 'var_name', port.var_name) parser.appendToTag(tag_name, 'code').string = str(port.code) try: data_dir = System.get_user_dir() + "/extensions/" data_dir = data_dir + port.language + "/ports/" if not os.path.isdir(data_dir): try: os.makedirs(data_dir) except: pass file_name = data_dir + port.type + ".xml" port_file = file(os.path.expanduser(file_name), 'w') port_file.write(parser.prettify()) port_file.close() except IOError as e: return False return True
def __valid_connector(self, newCon): """ Parameters: Returns * **Types** (:class:`boolean<boolean>`) """ for oldCon in self.connectors: if oldCon.input == newCon.input \ and oldCon.input_port == newCon.input_port\ and not newCon.input_port.multiple: System.log(_("Connector Already exists")) return False if (newCon.input == newCon.output) or self.__cycle_detection(newCon): System.log(_("Recursive connection is not allowed")) return False if newCon.input_port.type != newCon.output_port.type: System.log(_("Connection Types mismatch")) return False return True
def load(cls, diagram): """ This method load the xml file that represents the diagram. :param diagram: diagram to load. :return: operation status (True or False) """ from mosaicode.control.diagramcontrol import DiagramControl # load the diagram parser = XMLParser(diagram.file_name) zoom = parser.getTag(tag_name).getTag("zoom").getAttr("value") diagram.zoom = float(zoom) try: language = parser.getTag(tag_name).getTag("language").getAttr( "value") diagram.language = language except: pass # new version load blocks = parser.getTag(tag_name).getTag("blocks").getChildTags("block") system_blocks = System.get_blocks() for block in blocks: block_type = block.getAttr("type") if block_type not in system_blocks: System.log("Block " + block_type + " not found") continue block_id = int(block.getAttr("id")) collapsed = False if hasattr(block, "collapsed"): collapsed = block.collapsed == "True" position = block.getTag("position") x = position.getAttr("x") y = position.getAttr("y") properties = block.getChildTags("property") props = {} for prop in properties: if hasattr(prop, 'key') and hasattr(prop, 'value'): props[prop.key] = prop.value new_block = deepcopy(system_blocks[block_type]) new_block.set_properties(props) new_block.id = block_id new_block.x = float(x) new_block.y = float(y) new_block.is_collapsed = collapsed DiagramControl.add_block(diagram, new_block) connections = parser.getTag(tag_name).getTag("connections") connections = connections.getChildTags("connection") for conn in connections: if not hasattr(conn, 'from_block'): continue elif not hasattr(conn, 'to_block'): continue try: from_block = diagram.blocks[int(conn.from_block)] to_block = diagram.blocks[int(conn.to_block)] from_block_out = from_block.ports[int( conn.getAttr("from_out"))] to_block_in = to_block.ports[int(conn.getAttr("to_in"))] except: continue connection = ConnectionModel(diagram, from_block, from_block_out, to_block, to_block_in) DiagramControl.add_connection(diagram, connection) comments = parser.getTag(tag_name).getTag("comments") if comments is not None: comments = comments.getChildTags("comment") for com in comments: comment = CommentModel() comment.x = float(com.getAttr("x")) comment.y = float(com.getAttr("y")) comment.text = com.getAttr("text") diagram.comments.append(comment) return True
def load(cls, diagram): """ This method load the xml file that represents the diagram. :param diagram: diagram to load. :return: operation status (True or False) """ from mosaicode.control.diagramcontrol import DiagramControl dc = DiagramControl(diagram) # load the diagram parser = XMLParser(diagram.file_name) # Loading from tags zoom = parser.getTag(tag_name).getTag("zoom") if zoom is not None: zoom = zoom.getAttr("value") else: zoom = parser.getTagAttr(tag_name, "zoom") diagram.zoom = float(zoom) language = parser.getTag(tag_name).getTag("language") if language is not None: language = language.getAttr("value") else: language = parser.getTagAttr(tag_name, "language") diagram.language = language code_template = parser.getTag(tag_name).getTag("code_template") if code_template is not None and hasattr(code_template, "value"): code_template = code_template.getAttr("value") if code_template not in System.get_code_templates(): System.log("Code Template " + code_template + " not found") else: code_template = System.get_code_templates()[code_template] diagram.code_template = deepcopy(code_template) parser = parser.getTag(tag_name) # new version load blocks = parser.getTag("blocks").getChildTags("block") system_blocks = System.get_blocks() for block in blocks: block_type = block.getAttr("type") if block_type not in system_blocks: System.log("Block " + block_type + " not found") continue block_id = int(block.getAttr("id")) collapsed = False if hasattr(block, "collapsed"): collapsed = block.collapsed == "True" if hasattr(block, "x"): x = block.x if hasattr(block, "y"): y = block.y position = block.getTag("position") if position is not None: x = position.getAttr("x") y = position.getAttr("y") properties = block.getChildTags("property") props = {} for prop in properties: if hasattr(prop, 'key') and hasattr(prop, 'value'): props[prop.key] = prop.value new_block = deepcopy(system_blocks[block_type]) new_block.set_properties(props) new_block.id = block_id new_block.x = float(x) new_block.y = float(y) new_block.is_collapsed = collapsed dc.add_block(new_block) connections = parser.getTag("connections") connections = connections.getChildTags("connection") for conn in connections: if not hasattr(conn, 'from_block'): continue elif not hasattr(conn, 'to_block'): continue try: from_block = diagram.blocks[int(conn.from_block)] to_block = diagram.blocks[int(conn.to_block)] from_block_out = from_block.ports[int( conn.getAttr("from_out"))] to_block_in = to_block.ports[int(conn.getAttr("to_in"))] except: continue connection = ConnectionModel(diagram, from_block, from_block_out, to_block, to_block_in) dc.add_connection(connection) comments = parser.getTag("comments") if comments is not None: comments = comments.getChildTags("comment") for com in comments: comment = CommentModel() comment.x = float(com.getAttr("x")) comment.y = float(com.getAttr("y")) properties = com.getChildTags("property") props = {} for prop in properties: if hasattr(prop, 'key') and hasattr(prop, 'value'): props[prop.key] = prop.value comment.set_properties(props) dc.add_comment(comment) authors = parser.getTag("authors") if authors is not None: authors = authors.getChildTags("author") for author in authors: auth = AuthorModel() auth.name = author.getAttr("author") auth.license = author.getAttr("license") auth.date = author.getAttr("date") diagram.authors.append(auth) diagram.redraw() return True
def create_code_template(self): code_template = CodeTemplate() code_template.name = "webaudio" code_template.type = "Test" code_template.language = "Test" code_template.command = "python\n" code_template.description = "Javascript / webaudio code template" code_template.code_parts = [ "onload", "function", "declaration", "execution", "html" ] code_template.properties = [{ "name": "title", "label": "Title", "value": "Title", "type": MOSAICODE_STRING }] code_template.files["index.html"] = r""" <html> <head> <meta http-equiv="Cache-Control" content="no-store" /> <!-- $author$ $license$ --> <title>$prop[title]$</title> <link rel="stylesheet" type="text/css" href="theme.css"> <script src="functions.js"></script> <script> $single_code[function]$ function loadme(){ $single_code[onload]$ return; } var context = new (window.AudioContext || window.webkitAudioContext)(); //declaration block $code[declaration]$ //execution $code[execution]$ //connections $connections$ </script> </head> <body onload='loadme();'> $code[html]$ </body> </html> """ code_template.files["theme.css"] = r""" /* Developed by: $author$ */ html, body { background: #ffeead; color: #ff6f69; } h1, p { color: #ff6f69; } #navbar a { color: #ff6f69; } .item { background: #ffcc5c; } button { background: #ff6f69; color: #ffcc5c; } """ code_template.files["functions.js"] = r""" /* Developed by: $author$ */ $single_code[function]$ """ System.add_code_template(code_template) return code_template
def adjust_position(self): position = self.get_position() grid = System.get_preferences().grid new_x = position[0] - position[0] % grid new_y = position[1] - position[1] % grid self.translate(new_x - position[0], new_y - position[1])
def save(cls, diagram): """ This method save a file. Returns: * **Types** (:class:`boolean<boolean>`) """ parser = XMLParser() parser.addTag(tag_name) parser.setTagAttr(tag_name, 'version', value=System.VERSION) parser.setTagAttr(tag_name, 'zoom', value=diagram.zoom) parser.setTagAttr(tag_name, 'language', value=diagram.language) parser.appendToTag(tag_name, 'code_template', value=diagram.code_template) parser.appendToTag(tag_name, 'blocks') for block_id in diagram.blocks: block = diagram.blocks[block_id] pos = block.get_position() parser.appendToTag('blocks', 'block', type=block.type, id=block.id, collapsed=block.is_collapsed, x=pos[0], y=pos[1]) props = block.get_properties() for prop in props: parser.appendToLastTag('block', 'property', key=str(prop["name"]), value=str(prop["value"])) parser.appendToTag(tag_name, 'connections') for connector in diagram.connectors: parser.appendToTag('connections', 'connection', from_block=connector.output.id, from_out=int(connector.output_port.index), to_block=connector.input.id, to_in=int(connector.input_port.index)) parser.appendToTag(tag_name, 'comments') for comment in diagram.comments: pos = comment.get_position() parser.appendToTag('comments', 'comment', x=pos[0], y=pos[1]) props = comment.get_properties() for prop in props: parser.appendToLastTag('comment', 'property', key=str(prop["name"]), value=str(prop["value"])) auth = AuthorModel() auth.name = System.get_preferences().author auth.license = System.get_preferences().license auth.date = datetime.now() diagram.authors.insert(0, auth) parser.appendToTag(tag_name, 'authors') for author in diagram.authors: parser.appendToTag('authors', 'author', author=author.name, license=author.license, date=author.date) try: save_file = open(str(diagram.file_name), "w") save_file.write(parser.prettify()) save_file.close() except IOError as e: System.log(e.strerror) return False, e.strerror diagram.set_modified(False) return True, "Success"
def load(cls, diagram): """ This method load the JSON file that represents the diagram. :param diagram: diagram to load. :return: operation status (True or False) """ if os.path.exists(diagram.file_name) is False: System.log("Problem loading the diagram. File does not exist.") return None if not isinstance(diagram, DiagramModel): System.log("Problem loading the diagram. Is this a Diagram?") return False from mosaicode.control.diagramcontrol import DiagramControl dc = DiagramControl(diagram) # load the diagram data = "" try: data_file = open(diagram.file_name, 'r') data = json.load(data_file) data_file.close() if data["data"] != "DIAGRAM": System.log("Problem loading the diagram. Are you sure this is a valid file?") return False if "zoom" in data: diagram.zoom = float(data["zoom"]) if "language" in data: diagram.language = data["language"] # Loading Code Template if "code_template" in data: code_template_data = data["code_template"] if "type" in code_template_data: code_template = code_template_data["type"] if code_template not in System.get_code_templates(): System.log("Code Template " + code_template + " not found") else: code_template = System.get_code_templates()[code_template] diagram.code_template = deepcopy(code_template) if "properties" in code_template_data: properties = code_template_data["properties"] props = {} for prop in properties: props[prop["key"]] = prop["value"] diagram.code_template.set_properties(props) # Loading Blocks if "blocks" in data: blocks = data["blocks"] system_blocks = System.get_blocks() for block in blocks: block_type = block["type"] if block_type not in system_blocks: System.log("Block " + block_type + " not found") continue block_id = int(block["id"]) collapsed = block["collapsed"] x = block["x"] y = block["y"] properties = block["properties"] props = {} for prop in properties: props[prop["key"]] = prop["value"] new_block = deepcopy(system_blocks[block_type]) new_block.set_properties(props) new_block.id = block_id new_block.x = float(x) new_block.y = float(y) new_block.is_collapsed = collapsed dc.add_block(new_block) # Loading connections connections = data["connections"] for conn in connections: try: from_block = diagram.blocks[int(conn["from_block"])] to_block = diagram.blocks[int(conn["to_block"])] port_index = int(conn["from_out"]) if port_index >= 0 and port_index < len(from_block.ports): from_block_out = from_block.ports[port_index] if from_block_out.is_input(): System.log("Diagram error: Output port is an input port") continue else: System.log("Diagram error: invalid output port index " + str(port_index)) continue port_index = int(conn["to_in"]) if port_index >= 0 and port_index < len(to_block.ports): to_block_in = to_block.ports[port_index] if not to_block_in.is_input(): System.log("Diagram error: Input port is an output port") continue else: System.log("Diagram error: invalid input port index " + str(port_index)) continue except Exception as e: System.log("Diagram error:" + str(e)) continue connection = ConnectionModel(diagram, from_block, from_block_out, to_block, to_block_in) dc.add_connection(connection) # Loading comments comments = data["comments"] for com in comments: comment = CommentModel() comment.x = float(com["x"]) comment.y = float(com["y"]) properties = com["properties"] props = {} for prop in properties: props[prop["key"]] = prop["value"] comment.set_properties(props) dc.add_comment(comment) # Loading authors authors = data["authors"] for author in authors: auth = AuthorModel() auth.name = author["author"] auth.license = author["license"] auth.date = author["date"] diagram.authors.append(auth) diagram.redraw() except Exception as e: System.log(e) return False return True
def export_python(cls): from mosaicode.system import System as System System() for plugin in System.plugins: print "Exporting plugin " + plugin BlockPersistence.save_python(System.plugins[plugin])
def save(cls, diagram): """ This method save a file. Returns: * **Types** (:class:`boolean<boolean>`) """ x = { "source": "JSON", "data": "DIAGRAM", "version": System.VERSION, "zoom": diagram.zoom, "language": diagram.language, "code_template": {}, "blocks": [], "connections": [], "comments": [], "authors": [] } if diagram.code_template: code_template_data = { "type": diagram.code_template.type, "properties": [] } props = diagram.code_template.properties for prop in props: code_template_data["properties"].append({ "key": str(prop["name"]), "value": str(prop["value"]) }) x["code_template"] = code_template_data for block_id in diagram.blocks: block = diagram.blocks[block_id] pos = block.get_position() block_data = { "type": block.type, "id": block.id, "collapsed": block.is_collapsed, "x": pos[0], "y": pos[1], "properties": [] } props = block.get_properties() for prop in props: block_data["properties"].append({ "key": str(prop["name"]), "value": str(prop["value"]) } ) x["blocks"].append(block_data) for connector in diagram.connectors: x["connections"].append({ "from_block": connector.output.id, "from_out": int(connector.output_port.index), "to_block": connector.input.id, "to_in": int(connector.input_port.index) }) for comment in diagram.comments: pos = comment.get_position() comment_data = { "x": pos[0], "y": pos[1], "properties": [] } props = comment.get_properties() for prop in props: comment_data["properties"].append({ "key": str(prop["name"]), "value": str(prop["value"]) }) x["comments"].append(comment_data) auth = AuthorModel() auth.name = System.get_preferences().author auth.license = System.get_preferences().license auth.date = str(datetime.now()) diagram.authors.insert(0,auth) for author in diagram.authors: x["authors"].append({ "author": author.name, "license": author.license, "date": author.date }) try: save_file = open(str(diagram.file_name), "w") save_file.write(json.dumps(x, indent=4)) save_file.close() except IOError as e: System.log(e.strerror) return False, e.strerror diagram.set_modified(False) return True, "Success"
def test_update_blocks(self): blocks = System.get_blocks() self.assertIsNone(self.block_notebook.update_blocks(blocks), "Failed to update blocks")
def test_export_xml(self): System() System.reload() BlockControl.export_xml()
def test_set_log(self): System.set_log(Log())
def test_log(self): System.log("Hello World")