def SimpleRotate(data, angle): # Rotation center xm = 0.0 ym = 0.0 # Convert to radians angle_rad = 2 * math.pi - 2 * math.pi * angle / 360 objs = data.get_sorted_selected() if len(objs) == 0: objs = data.active_layer.objects scaleFailed = {} for o in objs: for h in o.handles: x = math.cos(angle_rad) * (h.pos.x + xm) - math.sin(angle_rad) * ( h.pos.y + ym) y = math.sin(angle_rad) * (h.pos.x + xm) + math.cos(angle_rad) * (h.pos.y) o.move_handle(h, (x, y), 0, 0) data.update_extents() dia.active_display().add_update_all() def rotate_cb(data, flags): dlg = CRotateDialog(dia.active_display().diagram, data) dia.register_action("ObjectsSimplerotation", "Simple Rotation", "/DisplayMenu/Objects/ObjectsExtensionStart", rotate_cb)
my = 0.0 pkg = packages[sp] for st in pkg : if st == "Group" : continue # can't create empty group #print st o, h1, h2 = dia.get_object_type(st).create (cx, cy) # to make the resulting diagram more interesting we set every sting property with it's name set_object_string (o) w = o.bounding_box.right - o.bounding_box.left h = o.bounding_box.bottom - o.bounding_box.top o.move (cx, cy) cx += w * 1.5 if h > my : my = h n += 1 if n % 10 == 0 : cx = 0.0 cy += my * 1.5 my = 0 layer.add_object (o) layer.update_extents() data.update_extents() if diagram : diagram.display() diagram.flush() return data dia.register_action ("HelpAObjects", "All Objects", "/ToolboxMenu/Help/HelpExtensionStart", aobjects_cb)
renderer=PrintRenderer() builder=Dia2umlTreeBuilder(dia_objects, uml_obj_factory) #uml_objects=[] #for i in dia_objects: # uml_objects.append(uml_obj_factory.new_uml_obj(i)) #init new uml project root_package= LargePackage(project_name,path=folder) root_package.accept(builder) root_package.accept(renderer) #init strategy and language #convert dia object to uml #build hierarchy #generate code pass def start_uml_update(data,flags): print "starting uml_update",data,flags pass dia.register_action("DialogsGenerateCode", "generate code", "/DisplayMenu/Dialogs/DialogsExtensionStart", start_codegen) dia.register_action("DialogsUpdateUML", "update uml", "/DisplayMenu/Dialogs/DialogsExtensionStart", start_uml_update)
except Exception, e: dia.message(gtk.MESSAGE_ERROR, repr(e)) if dia.active_display(): dia.active_display().add_update_all() dia.active_display().flush() def show(self): self.dlg.show() def hide(self, *args): self.dlg.hide() def run(self): return self.dlg.run() def dia_group_resize_db(data, flags): diagram = dia.active_display().diagram group = diagram.get_sorted_selected() if len(group) > 0: win = ResizeWindow(group, data) win.show() else: dia.message(gtk.MESSAGE_INFO, "Please select a group of objects") dia.register_action("ObjectGroupResize", "Group Resize", "/DisplayMenu/Objects/ObjectsExtensionStart", dia_group_resize_db)
import os exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] dia.message(2, "{0}, {1}, {2}, {3}".format(exc_type, e.message, fname, exc_tb.tb_lineno) ) else: dia.update_all() self._on_cancel() def _on_cancel(self, *args): self.window.destroy() def main(data, flags): try: active_display = dia.active_display() diagram = active_display.diagram active_layer = diagram.data.active_layer PgImportDialog(active_layer) except ImportError: dia.message(0, "Dialog creation failed. Missing pygtk?") dia.register_action("PgImport", "Import PostgreSQL Tables", "/DisplayMenu/Dialogs/DialogsExtensionStart", main)
s = w * h if s > smax: smax = s if s < smin: smin = s objs = data.active_layer.objects for o in objs: w = o.bounding_box.right - o.bounding_box.left h = o.bounding_box.bottom - o.bounding_box.top s = w * h if s >= smin and s <= smax: data.select(o) data.flush() dia.register_action("SelectByName", _("_Name"), "/DisplayMenu/Select/SelectBy/SelectByExtensionStart", select_by_name_cb) dia.register_action("SelectByFillcolor", _("_Fill Color"), "/DisplayMenu/Select/SelectBy/SelectByExtensionStart", select_by_fill_color_cb) dia.register_action("SelectByLinecolor", _("_Line Color"), "/DisplayMenu/Select/SelectBy/SelectByExtensionStart", select_by_line_color_cb) dia.register_action("SelectByTextcolor", _("_Text Color"), "/DisplayMenu/Select/SelectBy/SelectByExtensionStart", select_by_text_color_cb) dia.register_action("SelectBySize", _("_Size"), "/DisplayMenu/Select/SelectBy/SelectByExtensionStart", select_by_size_cb)
# XXX: there really should be a way to safely delete an object. This one will crash: # - when the object got added somewhere # - any object method gets called afterwards if not o_real is None : o_real.destroy() del o_real cx = oc.bounding_box.right if maxy < oc.bounding_box.bottom : maxy = oc.bounding_box.bottom if maxx < cx : maxx = cx # wrapping too long lines if cx > 300 : cx = 0 cy = maxy h = op.handles[7] # adjust the package size to fit the objects op.move_handle(h,(maxx + 1.0, maxy + 1.0), 0, 0) cy = maxy + 2.0 maxx = 0 # every package a new size data.update_extents() if diagram : diagram.display() diagram.flush() # make it work standalone return data dia.register_action ("HelpOtypes", _("Dia Object _Types"), "/ToolboxMenu/Help/HelpExtensionStart", otypes_cb)
def dia_debug_cb (data, flags) : "gets passed in the active diagram, flags are unused at the moment" for layer in data.layers : print "Layer :", layer.name for o in layer.objects : print str(o), str(o.bounding_box) def dia_debug_props_cb (data, flags) : for layer in data.layers : print "Layer :", layer.name for o in layer.objects : print str(o) props = o.properties for s in props.keys() : print props[s].type + " " + s + " (visible=%d)" % props[s].visible try : p = props[s].value except : p = None print "\t" + str(p) # dia-python keeps a reference to the renderer class and uses it on demand dia.register_action ("DebugBoundingbox", "Dia BoundingBox Debugger", "/DisplayMenu/Debug/DebugExtensionStart", dia_debug_cb) dia.register_action ("DebugProperty", "Dia Property API Debugger", "/DisplayMenu/Debug/DebugExtensionStart", dia_debug_props_cb)
else : # (name,type,value,comment,visibility,abstract,class_scope) attributes.append((m,tt,'',doc,0,0,0)) o.properties["operations"] = methods o.properties["attributes"] = attributes if stereotype != "" : o.properties["stereotype"] = stereotype # build the module object o, h1, h2 = oType.create (0,0) # p.x, p.y layer.add_object (o) # set the objects name o.properties["name"] = "dia" o.properties["comment"] = eval("dia.__doc__") methods = [] for s in theGlobals : if string.find(s[0], "swigregister") >= 0 : continue # just noise methods.append((s[0],'',s[1],'',0,0,0,1,())) o.properties["operations"] = methods # all objects got there bounding box, distribute them distribute_objects (layer.objects) if diagram : diagram.update_extents() diagram.flush() # work with bindings test return data dia.register_action ("HelpPydia", "PyDia Docs", "/ToolboxMenu/Help/HelpExtensionStart", autodoc_cb)
hbox.show() self.win.set_position(gtk.WIN_POS_CENTER) self.win.show() # set up as a dia plugin try : import dia def open_dialog_import(data, flags): ImportDbDialog(data, "import") def open_dialog_export(data, flags): ImportDbDialog(data, "export") dia.register_action ("DialogsPostgresImp", "Import Postgres database", "/DisplayMenu/Dialogs/DialogsExtensionStart", open_dialog_import) dia.register_action ("DialogsPostgresExp", "Export diagram to Postgres", "/DisplayMenu/Dialogs/DialogsExtensionStart", open_dialog_export) dia.register_export ("Postgres SQL Export", "sql", SQLRenderer()) except : print 'Failed to import Dia ...' ImportDbDialog(None, "import") gtk.main()
# get selected execution dir self.baseDir = str(self.wT.get_widget("baseDirChooser").get_filename()) shellCmd = str(self.wT.get_widget("miniPrompt").get_text()) # execute command in shell subprocess proc = subprocess.Popen(shellCmd, cwd=self.baseDir, shell=True, \ stdout=subprocess.PIPE, stderr=subprocess.STDOUT, \ env=os.environ) # print output # TODO update script output in real time executionLog = self.wT.get_widget("executionLog") output = self.baseDir + ": " + shellCmd + "\n\n" + proc.communicate()[0] executionLog.get_buffer().set_text(output) #set focus to output window executionLog.grab_focus() # reset mini prompt entry self.wT.get_widget("miniPrompt").set_text('') def launch_scriptlauncher(data, flags): L = ScriptLauncher() dia.register_action("DialogsScriptlauncher", "Script launcher", "/DisplayMenu/Dialogs/DialogsExtensionStart", launch_scriptlauncher)
if allProps[s].num < numProps : del allProps[s] # ... and all props already equal for s in allProps.keys() : o1 = allProps[s].opts[0] for o in allProps[s].opts : if o1.value != o.value : o1 = None break if o1 != None : del allProps[s] else : # if there is something left ensure unique values uniques = {} for o in allProps[s].opts : if uniques.has_key(o.value) : continue uniques[o.value] = o allProps[s].opts = [] for v in uniques.keys() : allProps[s].opts.append(uniques[v]) # display the dialog try : dlg = CPropsDialog(d, data, allProps) except ImportError : dia.message(0, "Dialog creation failed. Missing pygtk?") dia.register_action ("DialogsGroupproperties", "Dia Group Properties", "/DisplayMenu/Dialogs/DialogsExtensionStart", dia_objects_props_cb)
offsets = [] for i in range(0, rows) : offsets.append(0) dx *= 1.4 dy *= 1.8 for t in bst : y = t[1] # t[1] = 0 : start, noone uses it # correction to move further down c = rows - (rows * t[2] / aw) if t[1] : # the less users the far below if t[2] == 0 : y = rows - 1 elif t[1] >= rows : # compensate for some of the weight, FIXME: better guess needed y = int(rows - 2 * aw / (t[2] + t[1])) print t[0].properties["name"].value, t[1], t[2], y, c # move the object to it's new place x = offsets[y] t[0].move (x * dx, y * dy) offsets[y] += 1 data.update_extents () # this module is loaded by some other plug-ins but can also work on it's own # if it is loaded first as Dia plug-in and later as Python module everything works # fine due to Pythoninitializing the module only once #dia.register_callback ("Arrange Objects", "<Display>/Objects/Arrange", arrange_connected) dia.register_action ("Arrange", "Arrange Objects", "/DisplayMenu/Dialogs/DialogsExtensionStart", arrange_connected)
ptype = dia.get_object_type('Standard - Polygon') for o in objs : if o.type.name == 'Standard - Box' : r = o.properties['obj_bb'].value p = ptype.create(0,0) p = p[0] p.properties['poly_points'] = [(r.left, r.top), (r.right, r.top), (r.right, r.bottom), (r.left, r.bottom)] p.properties['line_width'] = o.properties['line_width'] p.properties['line_colour'] = o.properties['line_colour'] p.properties['line_style'] = o.properties['line_style'] p.properties['line_colour'] = o.properties['line_colour'] p.properties['fill_colour'] = o.properties['fill_colour'] p.properties['show_background'] = o.properties['show_background'] data.active_layer.add_object(p) data.active_layer.remove_object(o) o = p for h in o.handles: x = math.cos(angle_rad)*(h.pos.x+xm)-math.sin(angle_rad)*(h.pos.y+ym) y = math.sin(angle_rad)*(h.pos.x+xm)+math.cos(angle_rad)*(h.pos.y) o.move_handle(h, (x,y), 0, 0) data.update_extents () dia.active_display().add_update_all() def rotate_cb(data, flags) : dlg = CRotateDialog(dia.active_display().diagram, data) dia.register_action ("ObjectsSimplerotation", "Simple Rotation", "/DisplayMenu/Objects/ObjectsExtensionStart", rotate_cb)
my = 0.0 pkg = packages[sp] for st in pkg: if st == "Group": continue # can't create empty group #print st o, h1, h2 = dia.get_object_type(st).create(cx, cy) # to make the resulting diagram more interesting we set every sting property with it's name set_object_string(o) w = o.bounding_box.right - o.bounding_box.left h = o.bounding_box.bottom - o.bounding_box.top o.move(cx, cy) cx += w * 1.5 if h > my: my = h n += 1 if n % 10 == 0: cx = 0.0 cy += my * 1.5 my = 0 layer.add_object(o) layer.update_extents() data.update_extents() if diagram: diagram.display() diagram.flush() return data dia.register_action("HelpAObjects", _("All _Objects"), "/ToolboxMenu/Help/HelpExtensionStart", aobjects_cb)
# This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. import dia def select_empty_cb(data, flags): diagram = dia.active_display().diagram objs = data.active_layer.objects for o in objs: if o.bounding_box.right == o.bounding_box.left \ or o.bounding_box.top == o.bounding_box.bottom : diagram.select(o) dia.register_action("SelectEmpty", "Empty", "/DisplayMenu/Select/By/SelectByExtensionStart", select_empty_cb)
cons.show() win.show() cons.init() # set up as a dia plugin try: import dia def open_console(data, flags): gtk_console( { '__builtins__': __builtins__, '__name__': '__main__', '__doc__': None, 'dia': dia }, 'Python Dia Console') dia.register_action("DialogsPythonconsole", "Python Console", "/DisplayMenu/Dialogs/DialogsExtensionStart", open_console) except: print 'Failed to import Dia ...' gtk_console({ '__builtins__': __builtins__, '__name__': '__main__', '__doc__': None }) gtk.main()
button2.set_active(cfg.header_file) button2.connect("toggled",header_file_callback,cfg) vbox.pack_start(button2, True, True, 3) button3 = gtk.CheckButton("Log state changes of the FSM") button3.set_active(cfg.debug_state_change) button3.connect("toggled",debug_state_change_cb,cfg) vbox.pack_start(button3, True, True, 3) button4 = gtk.CheckButton("Enable multithreading code") button4.set_active(cfg.multithread_enable) button4.connect("toggled",multithread_enable_cb,cfg) vbox.pack_start(button4, True, True, 3) button.show() button2.show() button3.show() button4.show() vbox.show() window.show() return 0 dia.register_action ("sm_export_cfg", "Configuration of FSM exporting tool", "/DisplayMenu/Dialogs/DialogsExtensionStart", sm_export_cfg_cb) dia.register_action ("sm_export_version", "FSM exporting tool version", "/DisplayMenu/Dialogs/DialogsExtensionStart", sm_export_version_cb)
b, h1, h2 = box_type.create(bb.left, bb.top) b.move_handle(b.handles[7], (bb.right, bb.bottom), 0, 0) b.properties["show_background"] = 0 b.properties["line_width"] = 0 b.properties["line_colour"] = 'red' dest.add_object(b) def annotate_cb(data, flags): layer = data.active_layer dest = data.add_layer("Annotated '%s' (%s)" % (layer.name, sys.platform), -1) ann_type = dia.get_object_type("Standard - Text") for o in layer.objects: bb = o.bounding_box a, h1, h2 = ann_type.create(bb.right, bb.top) a.properties["text"] = "h: %g w: %g" % (bb.bottom - bb.top, bb.right - bb.left) dest.add_object(a) dia.register_action("DrawBoundingbox", "Draw BoundingBox", "/DisplayMenu/Debug/DebugExtensionStart", bbox_cb) dia.register_action("AnnotateMeasurements", "Annotate", "/DisplayMenu/Debug/DebugExtensionStart", annotate_cb)
hbox.show() self.win.set_position(gtk.WIN_POS_CENTER) self.win.show() # set up as a dia plugin try: import dia def open_dialog_import(data, flags): ImportDbDialog(data, "import") def open_dialog_export(data, flags): ImportDbDialog(data, "export") dia.register_action("DialogsPostgresImp", "Import Postgres database", "/DisplayMenu/Dialogs/DialogsExtensionStart", open_dialog_import) dia.register_action("DialogsPostgresExp", "Export diagram to Postgres", "/DisplayMenu/Dialogs/DialogsExtensionStart", open_dialog_export) dia.register_export("Postgres SQL Export", "sql", SQLRenderer()) except: print 'Failed to import Dia ...' ImportDbDialog(None, "import") gtk.main()
del allProps[s] # ... and all props already equal for s in allProps.keys(): o1 = allProps[s].opts[0] for o in allProps[s].opts: if o1.value != o.value: o1 = None break if o1 != None: del allProps[s] else: # if there is something left ensure unique values uniques = {} for o in allProps[s].opts: if uniques.has_key(o.value): continue uniques[o.value] = o allProps[s].opts = [] for v in uniques.keys(): allProps[s].opts.append(uniques[v]) # display the dialog try: dlg = CPropsDialog(d, data, allProps) except ImportError: dia.message(0, "Dialog creation failed. Missing pygtk?") dia.register_action("DialogsGroupproperties", "Dia Group Properties", "/DisplayMenu/Dialogs/DialogsExtensionStart", dia_objects_props_cb)
except Exception,e: dia.message(gtk.MESSAGE_ERROR, repr(e)) if dia.active_display(): dia.active_display().add_update_all() dia.active_display().flush() def show(self): self.dlg.show() def hide(self, *args): self.dlg.hide() def run(self): return self.dlg.run() def dia_group_resize_db (data,flags): diagram = dia.active_display().diagram group = diagram.get_sorted_selected() if len(group) > 0: win = ResizeWindow(group, data) win.show() else: dia.message(gtk.MESSAGE_INFO, "Please select a group of objects") dia.register_action("ObjectGroupResize", "Group Resize", "/DisplayMenu/Objects/ObjectsExtensionStart", dia_group_resize_db)
# all objects got there bounding box, distribute the fresh ones distribute_objects (fresh) if diagram : diagram.update_extents() diagram.flush() # work with bindings test return data def autodoc_html_cb (data, flags) : import pydoc import os try : path = os.environ["TEMP"] except KeyError : # with os.tmpnam() we get a RuntimeWarning so fall back to path = "/tmp/" os.chdir(path) pydoc.writedoc(dia) dia.message(0, path + os.path.sep + "dia.html saved.") dia.register_action ("HelpPydia2", "PyDia HTML Docs", "/ToolboxMenu/Help/HelpExtensionStart", autodoc_html_cb) dia.register_action ("HelpPydia", "PyDia Docs", "/ToolboxMenu/Help/HelpExtensionStart", autodoc_fresh_cb) dia.register_action ("UpdatePydia", "PyDia Docs Update", "/DisplayMenu/Help/HelpExtensionStart", autodoc_update_cb)
# XXX: there really should be a way to safely delete an object. This one will crash: # - when the object got added somewhere # - any object method gets called afterwards if not o_real is None : o_real.destroy() del o_real cx = oc.bounding_box.right if maxy < oc.bounding_box.bottom : maxy = oc.bounding_box.bottom if maxx < cx : maxx = cx # wrapping too long lines if cx > 300 : cx = 0 cy = maxy h = op.handles[7] # adjust the package size to fit the objects op.move_handle(h,(maxx + 1.0, maxy + 1.0), 0, 0) cy = maxy + 2.0 maxx = 0 # every package a new size data.update_extents() if diagram : diagram.display() diagram.flush() # make it work standalone return data dia.register_action ("HelpOtypes", "Dia Object Types", "/ToolboxMenu/Help/HelpExtensionStart", otypes_cb)
Плагин для изучения API python dia. Доступ к свойствам графических объектов, наблюдение реакции, вывод в консоль отладочной информации. """ import dia def research(data, flags) : print dia.active_display().diagram.get_sorted_selected() print data print flags objs = dia.active_display().diagram.get_sorted_selected() print " " for obj in objs: print "obj.type = ", obj.type print "obj.properties = ", obj.properties.keys() print "prop obj_bb = ", obj.properties['obj_bb'].value print "prop meta = ",obj.properties.get('meta').value dia.register_action ("ObjectsResearch", "researcher", "/DisplayMenu/Objects", research)
cons = Console(namespace=ns, copyright=copyright, quit_cb=quit) if menu: box = gtk.VBox() win.add(box) box.show() box.pack_start(menu, expand=False) menu.show() box.pack_start(cons) else: win.add(cons) cons.show() win.show() cons.init() # set up as a dia plugin try : import dia def open_console(data, flags): gtk_console({'__builtins__': __builtins__, '__name__': '__main__', '__doc__': None, 'dia': dia}, 'Python Dia Console') dia.register_action ("DialogsPythonconsole", "Python Console", "/DisplayMenu/Dialogs/DialogsExtensionStart", open_console) except : print 'Failed to import Dia ...' gtk_console({'__builtins__': __builtins__, '__name__': '__main__', '__doc__': None}) gtk.main()
if diagram : diagram.update_extents() diagram.flush() # work with bindings test return data def autodoc_html_cb (data, flags) : import pydoc import os import webbrowser try : path = os.environ["TEMP"] except KeyError : # with os.tmpnam() we get a RuntimeWarning so fall back to path = "/tmp/" os.chdir(path) pydoc.writedoc(dia) dia.message(0, path + os.path.sep + "dia.html saved.") webbrowser.open('file://' + os.path.realpath(path + os.path.sep + "dia.html")) dia.register_action ("HelpPydia2", "PyDia HTML Docs", "/ToolboxMenu/Help/HelpExtensionStart", autodoc_html_cb) dia.register_action ("HelpPydia", "PyDia Docs", "/ToolboxMenu/Help/HelpExtensionStart", autodoc_fresh_cb) dia.register_action ("UpdatePydia", "PyDia Docs Update", "/DisplayMenu/Help/HelpExtensionStart", autodoc_update_cb)
print "Mix-up:", ot.name else : # sheet referencing a type not available missing.append (ot.name) # from the dictionary removed every type referenced just once? print types def isheets_cb (data, flags) : sheets = dia.registered_sheets () check_objecttype_overlap (sheets) path = os.environ["TEMP"] + os.path.sep + "dia-sheets.html" f = open (path, "w") f.write (""" <html><head><title>Dia Sheets</title></head><body> <table> """) for sheet in sheets : info = "Namespace: [%s]<br>%i object types" % (so_get_namespace (sheet.objects), len(sheet.objects)) sname = sheet.name if not sheet.user : sname = "<b>" + sname + "</b>" f.write ("<tr><td>%s</td><td>%s</td><td>%s</td></tr>\n" % (sname, sheet.description, info)) f.write ("""</table> </body></html> """) dia.message(0, "'" + path + "' saved.") dia.register_action ("HelpInspectSheets", "Dia Sheets Inspection", "/ToolboxMenu/Help/HelpExtensionStart", isheets_cb)
def get_zigzag_line_length(o) : return get_multi_p2p_legnth(o.properties['orth_points'].value) def get_poly_line_length(o): return get_multi_p2p_legnth(o.properties['poly_points'].value) def get_selected_line_length(data) : total_len = 0 s_str = "" objs = data.get_sorted_selected() if len(objs) == 0: return "No line selected" for o in objs : if hasattr(o,"properties") : if o.properties.has_key ('start_point') and o.properties.has_key ('end_point') : total_len += get_standard_line_length(o) elif o.properties.has_key ('orth_points') : total_len += get_zigzag_line_length(o) elif o.properties.has_key ('poly_points') : total_len += get_poly_line_length(o) else : return "Object is not a known line type" else : return "Object does not have properties" return "%s" % total_len def GetSelectedLineLength(data, flags) : dlg = CLengthDialog(dia.active_display().diagram,data) dia.register_action ("GetSelectLineLength", "Get Selected Line(s) Length","/DisplayMenu/Objects/GetSelectLineLength",GetSelectedLineLength)
"gets passed in the active diagram, flags are unused at the moment" for layer in data.layers: print "Layer :", layer.name for o in layer.objects: print str(o), str(o.bounding_box) def dia_debug_props_cb(data, flags): for layer in data.layers: print "Layer :", layer.name for o in layer.objects: print str(o) props = o.properties for s in props.keys(): print props[ s].type + " " + s + " (visible=%d)" % props[s].visible try: p = props[s].value except: p = None print "\t" + str(p) # dia-python keeps a reference to the renderer class and uses it on demand dia.register_action("DebugBoundingbox", "Dia BoundingBox Debugger", "/DisplayMenu/Debug/DebugExtensionStart", dia_debug_cb) dia.register_action("DebugProperty", "Dia Property API Debugger", "/DisplayMenu/Debug/DebugExtensionStart", dia_debug_props_cb)
energy[0] += mass * math.pow (velocity[0], 2) / 2 energy[1] += mass * math.pow (velocity[1], 2) / 2 return energy def layout_force_cb(data, flags): # the things (nodes) we are moving around are all connected 'elements', # connection objects are only moving as a side effect nodes = [] for o in data.selected : for cpt in o.connections : # ConnectionPoint if len (cpt.connected) > 0 : nodes.append (o) break # this ususally is an iterative process, finished if no energy is left #FIXME: layout_force (nodes, 2.0, 2.0, 0.2, 0.5) PASSES 0.0, 0.0 e = layout_force (nodes, 2.0, 3.0, 2e-1, 5e-1) n = 0 # arbitrary limit to avoid endless loop while (e[0] > 1 or e[1] > 1) and n < 100 : e = layout_force (nodes, 2.0, 3.0, 2e-1, 5e-1) n += 1 for o in nodes : data.update_connections (o) data.active_layer.update_extents() # data/diagram _update_extents don't recalculate? data.update_extents () data.flush() print(n, "iterations") dia.register_action ("LayoutForcePy", _("_Layout (force)"), "/DisplayMenu/Test/TestExtensionStart", layout_force_cb)
# along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. import dia, string class CSimusol: def __init__(self, d, data): import os, subprocess, time filename = dia.active_display().diagram.filename sFilename = '%s' % (filename) subprocess.Popen([ 'xterm', '-hold', '-title', 'Simular', '-e', 'simusol', sFilename ]) time.sleep(10) def log_to_file(message, content=""): with open("/home/lorena/output.txt", "a") as file: file.write("message:: %s\n" % message) file.write("content:: %s\n" % content) file.write("\n\n") def simu(data, flags): dlg = CSimusol(dia.active_display().diagram, data) dia.register_action("SimusolScripts", "Simular", "/DisplayMenu/Simusol/SimusolScript", simu)
вывод в консоль отладочной информации. path: <home_dir>/.dia/python/ """ import dia def research(data, flags): print "argument 'data' = ", data print "argument 'flags' = ", flags print "sorted_selected = ", dia.active_display( ).diagram.get_sorted_selected() objs = dia.active_display().diagram.get_sorted_selected() print " " for obj in objs: print "obj.type = ", obj.type print "obj.properties = ", obj.properties.keys() print "prop obj_bb = ", obj.properties['obj_bb'].value print "prop meta = ", obj.properties.get('meta').value dia.register_action( "ObjectsResearch", # Имя регистрируемого Action. "researcher", # Название пункта отображаемого в меню. "/DisplayMenu/Objects", # "Родительский" пункт меню. research) # Функция- обработчик Action.
# from the dictionary removed every type referenced just once? print types def isheets_cb(data, flags): sheets = dia.registered_sheets() check_objecttype_overlap(sheets) path = tempfile.gettempdir() + os.path.sep + "dia-sheets.html" f = open(path, "w") f.write(""" <html><head><title>Dia Sheets</title></head><body> <table> """) for sheet in sheets: info = "Namespace: [%s]<br>%i object types" % (so_get_namespace( sheet.objects), len(sheet.objects)) sname = sheet.name if not sheet.user: sname = "<b>" + sname + "</b>" f.write("<tr><td>%s</td><td>%s</td><td>%s</td></tr>\n" % (sname, sheet.description, info)) f.write("""</table> </body></html> """) dia.message(0, "'" + path + "' saved.") webbrowser.open('file://' + os.path.realpath(path)) dia.register_action("HelpInspectSheets", _("Dia _Sheets Inspection"), "/ToolboxMenu/Help/HelpExtensionStart", isheets_cb)
d = dia.active_display().diagram grp = data.get_sorted_selected() bFoundAny = 0 for o in grp : if o.properties.has_key(name) : select_by (d, data, name, o.properties[name].value) bFoundAny = 1 if not bFoundAny : dia.message(0, "No selected object has the property '%s'." % name) data.update_extents () def select_by_fill_color_cb (data, flags) : select_by_selected (data, "fill_colour") def select_by_line_color_cb (data, flags) : select_by_selected (data, "line_colour") def select_by_text_color_cb (data, flags) : select_by_selected (data, "text_colour") dia.register_action ("SelectByName", "Name", "/DisplayMenu/Select/SelectBy/SelectByExtensionStart", select_by_name_cb) dia.register_action ("SelectByFillcolor", "Fill Color", "/DisplayMenu/Select/SelectBy/SelectByExtensionStart", select_by_fill_color_cb) dia.register_action ("SelectByLinecolor", "Line Color", "/DisplayMenu/Select/SelectBy/SelectByExtensionStart", select_by_line_color_cb) dia.register_action ("SelectByTextcolor", "Text Color", "/DisplayMenu/Select/SelectBy/SelectByExtensionStart", select_by_text_color_cb)
for o in data.selected : print 'selected: ', o if use_max: o.properties["elem_width"] = max_w else : o.properties["elem_width"] = min_w data.active_layer.update_extents() diagram.add_update_all() diagram.update_extents () diagram.flush() return width_eq dia.register_action ("LayoutForcePy1", "Width - ", "/DisplayMenu/ning/adjust_width_1", width_sub) dia.register_action ("LayoutForcePy2", "Width + ", "/DisplayMenu/ning/adjust_width_2", width_add) dia.register_action ("LayoutForcePy3", "Width = max(w)", "/DisplayMenu/ning/adjust_width_3", eq_warper(use_max=1, use_min=0)) dia.register_action ("LayoutForcePy4", "Width = min(w)", "/DisplayMenu/ning/adjust_width_4", eq_warper(use_max=0, use_min=1)) dia.register_action ("LayoutForcePy5", "Line v ", "/DisplayMenu/ning/adjust_width_5", line_v_sub)
y = pos.y * factor handles = [] for h in o.handles : #if 0 == h.type : # HANDLE_NON_MOVABLE # continue handles.append((h, (x + (h.pos.x - pos.x) * factor, y + (h.pos.y - pos.y) * factor))) # handles are not necessary independent for h in handles : o.move_handle(h[0], h[1], 0, 0) ScaleLens(o, factor) except RuntimeError, msg : if scaleFailed.has_key(o.type.name) : scaleFailed[o.type.name] += 1 else : scaleFailed[o.type.name] = 1 if len(scaleFailed.keys()) > 0 : sMsg = "Scaling failed for : " for s in scaleFailed.keys() : sMsg = sMsg + "\n%s (%d)" % (s, scaleFailed[s]) dia.message(1, sMsg) data.update_extents () dia.active_display().add_update_all() def scale_cb(data, flags) : dlg = CScaleDialog(dia.active_display().diagram, data) dia.register_action ("ObjectsSimplescaling", "Simple Scaling", "/DisplayMenu/Objects/ObjectsExtensionStart", scale_cb)
# Select empyt objects # Copyright (c) 2008, Hans Breuer <*****@*****.**> # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. import dia def select_empty_cb(data, flags): diagram = dia.active_display().diagram objs = data.active_layer.objects for o in objs: if o.bounding_box.right == o.bounding_box.left or o.bounding_box.top == o.bounding_box.bottom: diagram.select(o) dia.register_action("SelectEmpty", "Empty", "/DisplayMenu/Select/By/SelectByExtensionStart", select_empty_cb)
# * * * * * * * * * * * * * * * * def newModel(self ) : modelName = "Nuevo1" data = newDiagram( modelName ) o1 = newObject ( "O1", data ) o2 = newObject ( "O1", data ) l1 = newAssociation( "L1", data ) layer = data.active_layer distribute_objects (layer.objects) dia.register_action ("ImportProto", "Import Proto", "/ToolboxMenu/Help/HelpExtensionStart", newModel) o.properties["name"] = pname o.properties["template"] = 1 o.properties["templates"] = [(p.type, '')] # coloring depending on use o.properties["fill_colour"] = "lightblue" o.properties["fill_colour"] = "lightcyan" o.properties["fill_colour"] = "lightgreen" o.properties["fill_colour"] = "lightyellow"
else: # (name,type,value,comment,visibility,abstract,class_scope) attributes.append((m, tt, '', doc, 0, 0, 0)) o.properties["operations"] = methods o.properties["attributes"] = attributes if stereotype != "": o.properties["stereotype"] = stereotype # build the module object o, h1, h2 = oType.create(0, 0) # p.x, p.y layer.add_object(o) # set the objects name o.properties["name"] = "dia" o.properties["comment"] = eval("dia.__doc__") methods = [] for s in theGlobals: if string.find(s[0], "swigregister") >= 0: continue # just noise methods.append((s[0], '', s[1], '', 0, 0, 0, 1, ())) o.properties["operations"] = methods # all objects got there bounding box, distribute them distribute_objects(layer.objects) if diagram: diagram.update_extents() diagram.flush() # work with bindings test return data dia.register_action("HelpPydia", "PyDia Docs", "/ToolboxMenu/Help/HelpExtensionStart", autodoc_cb)
for o in layer.objects : bb = o.bounding_box b, h1, h2 = box_type.create (bb.left, bb.top) b.move_handle (b.handles[7], (bb.right, bb.bottom), 0, 0) b.properties["show_background"] = 0 b.properties["line_width"] = 0 b.properties["line_colour"] = 'red' dest.add_object (b) def annotate_cb (data, flags) : layer = data.active_layer dest = data.add_layer ("Annotated '%s' (%s)" % (layer.name, sys.platform), -1) ann_type = dia.get_object_type ("Standard - Text") for o in layer.objects : bb = o.bounding_box a, h1, h2 = ann_type.create (bb.right, bb.top) a.properties["text"] = "h: %g w: %g" % (bb.bottom - bb.top, bb.right - bb.left) dest.add_object (a) dia.register_action ("DrawBoundingbox", "Draw BoundingBox", "/DisplayMenu/Debug/DebugExtensionStart", bbox_cb) dia.register_action ("AnnotateMeasurements", "Annotate", "/DisplayMenu/Debug/DebugExtensionStart", annotate_cb)
t.properties["text_vert_alignment"] = 2 # center if cp.flags & 0x3 : #CP_FLAGS_MAIN t.properties["text_alignment"] = 1 # middle elif cp.directions & 0x2: # east t.properties["text_alignment"] = 0 # left elif cp.directions & 0x8: # west t.properties["text_alignment"] = 2 # right else : t.properties["text_alignment"] = 1 # middle # tint it with the connection point color if cp.flags & 0x3 : #CP_FLAGS_MAIN t.properties["text_colour"] = "red" elif cp.directions == 0 : # not necessarily a bug t.properties["text_colour"] = "green" else : t.properties["text_colour"] = "blue" # add it to the diagram layer.add_object(t) # connect the object with the cp at hand h2.connect(cp) # update the object and it's connected? data.update_extents () adisp = dia.active_display() if adisp : adisp.diagram.update_extents() adisp.diagram.flush() dia.register_action("DebugMarkConnectionPoints", "Mark Connection Points", "/DisplayMenu/Debug/DebugExtensionStart", mark_cps)
t.properties["text_vert_alignment"] = 2 # center if cp.flags & 0x3 : #CP_FLAGS_MAIN t.properties["text_alignment"] = 1 # middle elif cp.directions & 0x2: # east t.properties["text_alignment"] = 0 # left elif cp.directions & 0x8: # west t.properties["text_alignment"] = 2 # right else : t.properties["text_alignment"] = 1 # middle # tint it with the connection point color if cp.flags & 0x3 : #CP_FLAGS_MAIN t.properties["text_colour"] = "red" elif cp.directions == 0 : # not necessarily a bug t.properties["text_colour"] = "green" else : t.properties["text_colour"] = "blue" # add it to the diagram layer.add_object(t) # connect the object with the cp at hand h2.connect(cp) # update the object and it's connected? data.update_extents () adisp = dia.active_display() if adisp : adisp.diagram.update_extents() adisp.diagram.flush() dia.register_action("DebugMarkConnectionPoints", _("_Mark Connection Points"), "/DisplayMenu/Debug/DebugExtensionStart", mark_cps)
o.properties["fill_colour"] = "lightcyan" elif len(names) > 1 : o.properties["fill_colour"] = "lightyellow" # if there is only one user show it if len(names) == 1 : o.properties["comment"] = names[0] o.properties["visible_comments"] = 1 o.properties["comment_line_length"] = 60 else : o.properties["comment"] = string.join(names, "; ") o.properties["visible_comments"] = 0 o.properties["comment_line_length"] = 60 # store position for next in row x += (dx + o.properties["elem_width"].value) grid[p.type] = (x,y) layer.add_object(o) layer.update_extents() data.update_extents() if diagram : diagram.display() diagram.flush() if len(name_type_clashes) > 0 : dia.message(0, "One name, one type?!\n" + string.join(name_type_clashes, "\n")) return data dia.register_action ("HelpAllPropts", "All Object Properties", "/ToolboxMenu/Help/HelpExtensionStart", allprops_cb)
elif len(names) > 1: o.properties["fill_colour"] = "lightyellow" # if there is only one user show it if len(names) == 1: o.properties["comment"] = names[0] o.properties["visible_comments"] = 1 o.properties["comment_line_length"] = 60 else: o.properties["comment"] = string.join(names, "; ") o.properties["visible_comments"] = 0 o.properties["comment_line_length"] = 60 # store position for next in row x += (dx + o.properties["elem_width"].value) grid[p.type] = (x, y) layer.add_object(o) layer.update_extents() data.update_extents() if diagram: diagram.display() diagram.flush() if len(name_type_clashes) > 0: dia.message( 0, "One name, one type?!\n" + string.join(name_type_clashes, "\n")) return data dia.register_action("HelpAllPropts", "All Object Properties", "/ToolboxMenu/Help/HelpExtensionStart", allprops_cb)
class PropInfo : def __init__ (self, t, n, o) : self.num = 1 self.type = t self.name = n self.opts = [o] def __str__ (self) : return self.name + ":" + str(self.opts) def Add (self, o) : self.num = self.num + 1 self.opts.append(o) def dia_objects_props_cb (data, flags) : d = dia.active_display().diagram # display the dialog data = None allProps = None dlg = CuonDia(d, data, allProps) dia.register_action ("CuonDia", "Cuon Dia ", "/DisplayMenu/Dialogs/DialogsExtensionStart", dia_objects_props_cb)