Beispiel #1
0
    def Render(self, data):
        layer = data.active_layer
        for o in self.objects:
            try:
                od = o.Create()
            except TypeError as e:
                od = None
                dia.message(
                    1,
                    "SVG import limited, consider another importer.\n(Error: "
                    + str(e) + ")")
            if od:
                if o.translation:
                    pos = od.properties["obj_pos"].value
                    #FIXME:  looking at scascale.py this isn't completely correct
                    x1 = pos.x + o.translation[0]
                    y1 = pos.y + o.translation[1]
                    od.move(x1, y1)
                layer.add_object(od)
        # create an 'Unhandled' layer and dump our Unknown
        # create an 'Errors' layer and dump our errors
        if len(list(self.errors.keys())) > 0:
            layer = data.add_layer("Errors")
            s = "To hide the error messages delete or disable the 'Errors' layer\n"
            for e in list(self.errors.keys()):
                s = s + str(e) + " -> " + str(self.errors[e]) + "\n"

            o = Text()
            o.props["fill"] = "red"
            o.Set(s)
            layer.add_object(o.Create())
        # create a 'Description' layer
        data.update_extents()
        return 1
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")
Beispiel #3
0
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")
Beispiel #4
0
 def on_rotate(self, *args):
     s = self.entry.get_text()
     angle = float(s)
     if angle >= 0 and angle <= 360:
         SimpleRotate(self.data, angle)
         self.data.update_extents()
         self.diagram.flush()
     else:
         dia.message(1, "Value out of range!")
     self.win.destroy()
Beispiel #5
0
	def on_scale(self, *args) :
		s = self.entry.get_text()
		scale = float(s)
		if scale > 0.001 and scale < 1000 :
			SimpleScale (self.data, float(s))
			self.data.update_extents ()
			self.diagram.flush()
		else :
			dia.message(1, "Value out of range!")
		self.win.destroy ()
Beispiel #6
0
	def on_rotate(self, *args) :
		s = self.entry.get_text()
		angle = float(s)
		if angle >= 0 and angle <= 360 :
			SimpleRotate (self.data, angle)
			self.data.update_extents()
			self.diagram.flush()
		else :
			dia.message(1, "Please enter an angle between 0 and 360 degrees.")
		self.win.destroy ()
Beispiel #7
0
	def on_rotate(self, *args) :
		s = self.entry.get_text()
		angle = float(s)
		if angle >= 0 and angle <= 360 :
			SimpleRotate (self.diagram, angle)
			self.diagram.update_extents()
			self.diagram.flush()
		else :
			dia.message(1, "Please enter an angle between 0 and 360 degrees.")
		self.win.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?")
Beispiel #9
0
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.")
Beispiel #10
0
def select_by_selected(data, name):
    grp = data.get_sorted_selected()
    bFoundAny = 0
    for o in grp:
        if name in o.properties:
            select_by(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()
    data.flush()
Beispiel #11
0
 def EditConfig(self, widget):
     if not self.config.has_section("ScriptLauncher") or \
        not self.config.has_option("ScriptLauncher", "editor"):
         dia.message(2, "Editor not configured.\n" + \
                         "Set it or edit script list in " + self.configFile)
         return
     subprocess.Popen(self.config.get("ScriptLauncher", "editor") + " " + self.configFile, \
                      shell=True, \
                      stdout=subprocess.PIPE, \
                      stderr=subprocess.PIPE)
     self.wT.get_widget("scriptWindow").destroy()
Beispiel #12
0
 def _bezier(self, bezpoints):
     for bp in bezpoints:
         if bp.type == 0:  # BEZ_MOVE_TO
             self.f.write('M %.3f,%.3f ' % (bp.p1.x, bp.p1.y))
         elif bp.type == 1:  # BEZ_LINE_TO
             self.f.write('L %.3f,%.3f ' % (bp.p1.x, bp.p1.y))
         elif bp.type == 2:  # BEZ_CURVE_TO
             self.f.write ('C %.3f,%.3f %.3f,%.3f %.3f,%.3f ' \
              % (bp.p1.x, bp.p1.y, bp.p2.x, bp.p2.y, bp.p3.x, bp.p3.y))
         else:
             dia.message(2, "Invalid BezPoint type (%d)" * bp.type)
Beispiel #13
0
	def _bezier (self, bezpoints) :
		for bp in bezpoints :
			if bp.type == 0 : # BEZ_MOVE_TO
				self.f.write('M %.3f,%.3f ' % (bp.p1.x, bp.p1.y))
			elif bp.type == 1 : # BEZ_LINE_TO
				self.f.write('L %.3f,%.3f ' % (bp.p1.x, bp.p1.y))
			elif bp.type == 2 : # BEZ_CURVE_TO
				self.f.write ('C %.3f,%.3f %.3f,%.3f %.3f,%.3f ' \
					% (bp.p1.x, bp.p1.y, bp.p2.x, bp.p2.y, bp.p3.x, bp.p3.y))
			else :
				dia.message(2, "Invalid BezPoint type (%d)" * bp.type)
Beispiel #14
0
def select_by_selected (data, name) :
	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 ()
Beispiel #15
0
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.")
Beispiel #16
0
def _eval (s, _locals) :
	# eval() can be used to execute aribitray code, see e.g. http://bugzilla.gnome.org/show_bug.cgi?id=317637
	# here using *any* builtins is an abuse
	try :
		return eval (s, {'__builtins__' : None }, _locals)
	except NameError :
		try :
			import dia
			dia.message(2, "***Possible exploit attempt***:\n" + s)
		except ImportError :
			print "***Possible exploit***:", s
	return None
Beispiel #17
0
def _eval(s, _locals):
    # eval() can be used to execute aribitray code, see e.g. http://bugzilla.gnome.org/show_bug.cgi?id=317637
    # here using *any* builtins is an abuse
    try:
        return eval(s, {'__builtins__': None}, _locals)
    except NameError:
        try:
            import dia
            dia.message(2, "***Possible exploit attempt***:\n" + s)
        except ImportError:
            print("***Possible exploit***:", s)
    return None
Beispiel #18
0
def SimpleScale(data, factor):
    objs = data.get_sorted_selected()
    if len(objs) == 0:
        objs = data.active_layer.objects
    scaleFailed = {}
    for o in objs:
        pos = o.properties["obj_pos"].value
        hSE = None  # the 'south east' handle to size the object
        if "elem_width" in o.properties:
            hLR = o.handles[7]  # HANDLE_RESIZE_SE
            try:
                #if 0 == hLR.type : # HANDLE_NON_MOVABLE
                #	raise RuntimeError, "non moveable handle"
                x = pos.x * factor
                y = pos.y * factor
                x2 = x + (hLR.pos.x - pos.x) * factor
                y2 = y + (hLR.pos.y - pos.y) * factor
                # calculate all points before movement, handle is still connected and move moves it too
                o.move(x, y)
                o.move_handle(hLR, (x2, y2), 0, 0)
                ScaleLens(o, factor)
            except RuntimeError as msg:
                if o.type.name in scaleFailed:
                    scaleFailed[o.type.name] += 1
                else:
                    scaleFailed[o.type.name] = 1
        else:
            # must move all handles
            try:
                x = pos.x * factor
                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 as msg:
                if o.type.name in scaleFailed:
                    scaleFailed[o.type.name] += 1
                else:
                    scaleFailed[o.type.name] = 1
    if len(list(scaleFailed.keys())) > 0:
        sMsg = "Scaling failed for : "
        for s in list(scaleFailed.keys()):
            sMsg = sMsg + "\n%s (%d)" % (s, scaleFailed[s])
        dia.message(1, sMsg)
    data.update_extents()
    dia.active_display().add_update_all()
Beispiel #19
0
 def draw_bezier( me, bezpoints, color, _fill =False):
     points = []
     for bp in bezpoints:
         if bp.type == 0: # BEZ_MOVE_TO
             points.append( bp.p1 )
         elif bp.type == 1: # BEZ_LINE_TO
             points.append( bp.p1 )
         elif bp.type == 2: # BEZ_CURVE_TO
             points.append( bp.p1 )
             points.append( bp.p2 )
             points.append( bp.p3 )
         else:
             dia.message( 2, "Invalid BezPoint type (%d)" * bp.type)
     me.draw_polygon( points, color, _smooth =True, _fill=_fill)
Beispiel #20
0
	def fill_bezier (self, bezpoints, color) :
		self.f.write('<path stroke="none" fill="%s" stroke-width="%.3f" d="' \
					% (self._rgb(color), self.line_width))
		for bp in bezpoints :
			if bp.type == 0 : # BEZ_MOVE_TO
				self.f.write('M %.3f,%.3f ' % (bp.p1.x, bp.p1.y))
			elif bp.type == 1 : # BEZ_LINE_TO
				self.f.write('L %.3f,%.3f ' % (bp.p1.x, bp.p1.y))
			elif bp.type == 2 : # BEZ_CURVE_TO
				self.f.write ('C %.3f,%.3f %.3f,%.3f %.3f,%.3f ' \
					% (bp.p1.x, bp.p1.y, bp.p2.x, bp.p2.y, bp.p3.x, bp.p3.y))
			else :
				dia.message(2, "Invalid BezPoint type (%d)" * bp.type)
		self.f.write('"/>\n')
Beispiel #21
0
 def fill_bezier(self, bezpoints, color):
     self.f.write('<path stroke="none" fill="%s" stroke-width="%.3f" d="' \
        % (self._rgb(color), self.line_width))
     for bp in bezpoints:
         if bp.type == 0:  # BEZ_MOVE_TO
             self.f.write('M %.3f,%.3f ' % (bp.p1.x, bp.p1.y))
         elif bp.type == 1:  # BEZ_LINE_TO
             self.f.write('L %.3f,%.3f ' % (bp.p1.x, bp.p1.y))
         elif bp.type == 2:  # BEZ_CURVE_TO
             self.f.write ('C %.3f,%.3f %.3f,%.3f %.3f,%.3f ' \
              % (bp.p1.x, bp.p1.y, bp.p2.x, bp.p2.y, bp.p3.x, bp.p3.y))
         else:
             dia.message(2, "Invalid BezPoint type (%d)" * bp.type)
     self.f.write('"/>\n')
Beispiel #22
0
	def Render(self,data) :
		layer = data.active_layer
		for o in self.objects :
			try :
				od = o.Create()
			except TypeError, e :
				od = None
				dia.message(1, "SVG import limited, consider another importer.\n(Error: " + str(e) + ")")
			if od :
				if o.translation :
					pos = od.properties["obj_pos"].value
					#FIXME:  looking at scascale.py this isn't completely correct
					x1 = pos.x + o.translation[0]
					y1 = pos.y + o.translation[1]
					od.move(x1, y1)
				layer.add_object(od)
Beispiel #23
0
 def Render(self, data):
     layer = data.active_layer
     for o in self.objects:
         try:
             od = o.Create()
         except TypeError, e:
             od = None
             dia.message(1, "SVG import limited, consider another importer.\n(Error: " + str(e) + ")")
         if od:
             if o.translation:
                 pos = od.properties["obj_pos"].value
                 # FIXME:  looking at scascale.py this isn't completely correct
                 x1 = pos.x + o.translation[0]
                 y1 = pos.y + o.translation[1]
                 od.move(x1, y1)
             layer.add_object(od)
Beispiel #24
0
def mark_cps (data, flags) :
	objs = data.get_sorted_selected()
	layer = data.active_layer
	if len(objs) == 0 :
		dia.message (1, "Select objects for marking it's connection points!")
		return
	textType = dia.get_object_type("Standard - Text")
	for o in objs:
		for i in range(0, len(o.connections)):
			cp = o.connections[i]
			t, h1, h2 = textType.create (cp.pos.x, cp.pos.y)
			t.properties["text"] = str(i)
			# align the text based on the given directions
			if cp.flags & 0x3 : #CP_FLAGS_MAIN
				t.properties["text_vert_alignment"] = 3 # first line
			if cp.directions & 0x1: # north
				t.properties["text_vert_alignment"] = 1 # bottom
			elif cp.directions & 0x4: # south
				t.properties["text_vert_alignment"] = 0 # top
			else :
				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()
Beispiel #25
0
def mark_cps (data, flags) :
	objs = data.get_sorted_selected()
	layer = data.active_layer
	if len(objs) == 0 :
		dia.message (1, "Select objects for marking it's connection points!")
		return
	textType = dia.get_object_type("Standard - Text")
	for o in objs:
		for i in range(0, len(o.connections)):
			cp = o.connections[i]
			t, h1, h2 = textType.create (cp.pos.x, cp.pos.y)
			t.properties["text"] = str(i)
			# align the text based on the given directions
			if cp.flags & 0x3 : #CP_FLAGS_MAIN
				t.properties["text_vert_alignment"] = 3 # first line
			if cp.directions & 0x1: # north
				t.properties["text_vert_alignment"] = 1 # bottom
			elif cp.directions & 0x4: # south
				t.properties["text_vert_alignment"] = 0 # top
			else :
				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()
Beispiel #26
0
def dia_objects_props_cb(data, flags):
    d = dia.active_display().diagram
    grp = d.get_sorted_selected()
    allProps = {}
    numProps = len(grp)
    # check for properties common to all select objects
    for o in grp:
        props = o.properties
        for s in props.keys():
            if props[s].visible:
                if allProps.has_key(s):
                    allProps[s].Add(props[s])
                else:
                    allProps[s] = PropInfo(props[s].type, props[s].name,
                                           props[s])
    # now eliminate all props not common ...
    for s in allProps.keys():
        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?")
    def clickAplicar(self, *args):
        optWidth = self.getSelectedGroupOption(self.widthOptions)
        optHeight = self.getSelectedGroupOption(self.heightOptions)

        try:
            if optWidth[0] != 'ignore':
                width = self.getValue(optWidth[0], optWidth[1], 'elem_width')
                self.adjustWidth(width)
            if optHeight[0] != 'ignore':
                height = self.getValue(optHeight[0], optHeight[1], 'elem_height')
                self.adjustHeight(height)

            if dia.active_display():
                diagram = dia.active_display().diagram
                for obj in self.group:
                    diagram.update_connections(obj)
                    
        except Exception,e:
            dia.message(gtk.MESSAGE_ERROR, repr(e))
Beispiel #28
0
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.")
Beispiel #29
0
def dia_objects_props_cb (data, flags) :
	d = dia.active_display().diagram
	grp = d.get_sorted_selected()
	allProps = {}
	numProps = len(grp)
	# check for properties common to all select objects
	for o in grp :
		props = o.properties
		for s in props.keys() :
			if props[s].visible :
				if allProps.has_key(s) :
					allProps[s].Add(props[s])
				else :
					allProps[s] = PropInfo(props[s].type, props[s].name, props[s])
	# now eliminate all props not common ...
	for s in allProps.keys() :
		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?")
Beispiel #30
0
    def end_render(self):
        if self.generate_files:
            self.cfg.load()
            f = open(self.filename + self.file_extension, "w")
            self.write_machine_generated_warning(f)
            self.write_fsm_file_sentinel(f)
            if self.cfg.header_file:
                h = open(self.filename + ".h", "w")
                self.write_machine_generated_warning(h)
                self.write_header_file_sentinel(h)
                self.generate_includes(h)
                self.generate_events_defines(h)
                self.generate_states_typedef(h)
                self.generate_object(h)
                self.write_header_file_end_sentinel(h)
                f.write("#include \"%s\"\n" % (self.basename + ".h"))
                f.write("\n")
            else:
                self.generate_includes(f)
                self.generate_events_defines(f)
                self.generate_states_typedef(f)
                self.generate_object(f)

            self.generate_funcs_decl(f)
            self.generate_internal_funcs_decl(f)
            self.generate_st_change_func(f)
            self.generate_raw_funcs(f)
            self.generate_events_fire_funcs(f)
            self.generate_init_func(f)
            self.generate_get_state_func(f)
            self.write_fsm_file_end_sentinel(f)
            f.close()
            if self.cfg.header_file:
                h.close()
            if self.show_priority_warning and self.cfg.warn_connections:
                #Launch a warning(1) message
                dia.message(
                    1,
                    "Not all transitions has priority assigned!\nDiagram has been exported but is up to you if transitions are right\n"
                )
        else:
            print("File will be generated in blank until errors are solved.")
Beispiel #31
0
    def clickAplicar(self, *args):
        optWidth = self.getSelectedGroupOption(self.widthOptions)
        optHeight = self.getSelectedGroupOption(self.heightOptions)

        try:
            if optWidth[0] != 'ignore':
                width = self.getValue(optWidth[0], optWidth[1], 'elem_width')
                self.adjustWidth(width)
            if optHeight[0] != 'ignore':
                height = self.getValue(optHeight[0], optHeight[1],
                                       'elem_height')
                self.adjustHeight(height)

            if dia.active_display():
                diagram = dia.active_display().diagram
                for obj in self.group:
                    diagram.update_connections(obj)

        except Exception, e:
            dia.message(gtk.MESSAGE_ERROR, repr(e))
Beispiel #32
0
    def __init__(self):
        scriptLauncherDataPath = os.path.split(__file__)[0] + "/scriptlauncher/"
        # load gui
        self.wT = gtk.glade.XML(scriptLauncherDataPath + "scriptlauncher.glade")
        
        # load config
        self.configFile = scriptLauncherDataPath + "scriptlauncher.cfg"
        self.config = ConfigParser.ConfigParser()
        
        proxyPort = 0    # default proxy port
        try: 
            self.config.read(self.configFile)
            
            # set additional paths from config
            if self.config.get("ScriptLauncher", "paths"):
               os.environ["PATH"] += ":" + self.config.get("ScriptLauncher", "paths") 
            
            # get proxy port
            if self.config.get("ScriptLauncher", "proxy_port"):
               proxyPort = int(self.config.get("ScriptLauncher", "proxy_port"))
            
        except ConfigParser.ParsingError:
            dia.message(2, "Dia Script Launcher config file parse error")
        except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
            pass

        # init current diagram informations
        self.UpdateCurrentDiagramAndDir()
    
        # import proxy python and start proxy thread
        sys.path.append(scriptLauncherDataPath)
        self.proxy = DiaProxyThread(proxyPort)
        if proxyPort > 0:
            self.proxy.start()

        # init and start gui
        self.InitGui()
Beispiel #33
0
def allprops_cb(data, flags):

    # copied from otypes.py
    if data:
        diagram = None  # we may be running w/o GUI
    else:
        diagram = dia.new("All Object Properties.dia")
        data = diagram.data
    layer = data.active_layer

    props_by_name = {}
    otypes = dia.registered_types()
    name_type_clashes = []

    for oname in otypes:
        try:
            obj, h1, h2 = dia.get_object_type(oname).create(0, 0)
        except:
            print "Huh?", oname
            continue
        prop_keys = obj.properties.keys()
        for k in prop_keys:
            p = obj.properties[k]
            if props_by_name.has_key(k):
                # check if it is the same type
                p0, names = props_by_name[k]
                try:
                    if p0.type != p.type:
                        # construct a unique name
                        uname = p.name + "<" + p.type + ">"
                        if props_by_name.has_key(uname):
                            props_by_name[uname][1].append(oname)
                        else:
                            props_by_name[uname] = (p, [oname])
                            name_type_clashes.append(oname + "::" + p.name +
                                                     " as " + p0.type +
                                                     " and " + p.type)
                    else:
                        # remember the origin of the property
                        props_by_name[k][1].append(oname)
                except KeyError:
                    print oname, "::", k, p, "?"
            else:
                props_by_name[k] = (p, [oname])
        obj.destroy(
        )  # unsave delete, any method call will fail/crash afterweards
        obj = None

    grid = {}  # one type per row
    dx = 1.0
    dy = 5.0
    ot = dia.get_object_type("UML - Class")

    props_keys = props_by_name.keys()
    # alpha-numeric sorting by type; after by number of users
    props_keys.sort(
        lambda a, b: len(props_by_name[b][1]) - len(props_by_name[a][1]))
    props_keys.sort(
        lambda a, b: cmp(props_by_name[a][0].type, props_by_name[b][0].type))

    almost_all = 98 * len(otypes) / 100  # 98 %

    for pname in props_keys:

        p, names = props_by_name[pname]

        x = 0.0
        y = 0.0
        if grid.has_key(p.type):
            x, y = grid[p.type]
        else:
            x = 0.0
            y = len(grid.keys()) * dy
        o, h1, h2 = ot.create(x, y)
        o.properties["name"] = pname
        o.properties["template"] = 1
        o.properties["templates"] = [(p.type, '')]
        # coloring depending on use
        if len(names) > almost_all:
            o.properties["fill_colour"] = "lightgreen"
        elif len(names) > 100:
            o.properties["fill_colour"] = "lightblue"
        elif len(names) > 2:
            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
Beispiel #34
0
    def begin_render(self, data, filename):
        self.states = {}
        self.transitions = []
        self.generate_files = True
        self.filename, self.file_extension = os.path.splitext(filename)
        self.basename = os.path.splitext(
            os.path.basename(self.filename + self.file_extension))[0]
        for layer in data.layers:
            for o in layer.objects:
                if o.type.name == "UML - State":
                    state = State()
                    # properties are: ['obj_pos', 'obj_bb', 'elem_corner', 'elem_width' ,'elem_height', 'type','line_colour', 'fill_colour', 'text_font', 'text_height', 'text_colour', 'text', 'entry_action', 'do_action', 'exit_action' ]
                    state.set_name(o.properties["text"].value.text.strip())

                    try:
                        p = o.properties["do_action"].value
                    except:
                        p = None
                    state.set_do_action(str(p))

                    try:
                        p = o.properties["entry_action"].value
                    except:
                        p = None
                    state.set_input_action(str(p))

                    try:
                        p = o.properties["exit_action"].value
                    except:
                        p = None
                    state.set_output_action(str(p))
                    state.set_type(STANDARD_STATE)
                    self.states[state.name] = state
                #elif o.type.name == "UML - State Term" :
                # properties are:[ 'obj_pos', 'obj_bb', 'elem_corner', 'elem_width', 'elem_height', 'is_final']
                elif o.type.name == "UML - Transition":
                    # properties are: ['obj_pos', 'obj_bb', 'orth_points', 'orth_orient', 'orth_autoroute', 'trigger', 'action', 'guard', 'trigger_text_pos', 'guard_text_pos', 'direction_inverted']
                    transition = Transition()
                    try:
                        source = o.handles[0].connected_to.object
                    except AttributeError:
                        #Launch an error(2) message
                        dia.message(
                            2,
                            "The source of '%s' transition is wrong connected.\nDiagram will not be exported until the error is solved.\n"
                            % o.properties["trigger"].value)
                        self.generate_files = False

                    try:
                        target = o.handles[1].connected_to.object
                    except AttributeError:
                        #Launch an error(2) message
                        dia.message(
                            2,
                            "The destination of '%s' transition is wrong connected.\nDiagram will not be exported until the error is solved.\n"
                            % o.properties["trigger"].value)
                        self.generate_files = False

                    if source.type.name == "UML - State Term":
                        if not source.properties["is_final"].value:
                            transition.set_source("INITIAL_STATE")
                    elif source.type.name == "UML - State":
                        transition.set_source(
                            source.properties["text"].value.text)

                    if target.type.name == "UML - State Term":
                        if target.properties["is_final"].value:
                            transition.set_target("FINAL_STATE")
                    elif target.type.name == "UML - State":
                        transition.set_target(
                            target.properties["text"].value.text)

                    try:
                        trigger = o.properties["trigger"].value
                    except:
                        trigger = ""

                    priority_assigned = transition.set_trigger(str(trigger))
                    if not priority_assigned:
                        self.show_priority_warning = True

                    try:
                        guard = o.properties["guard"].value
                    except:
                        guard = ""
                    if len(guard) > 0:
                        transition.set_guard(str(guard))

                    try:
                        transition.set_action(o.properties["action"].value)
                    except:
                        action = ""
                    self.transitions.append(transition)
Beispiel #35
0
				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)
Beispiel #36
0
def hello_callback(data, flags):
    dia.message(2, "Hello, World!\n")
Beispiel #37
0
def allprops_cb(data, flags) :

	# copied from otypes.py
	if data :
		diagram = None # we may be running w/o GUI
	else :
		diagram = dia.new("All Object Properties.dia")
		data = diagram.data
	layer = data.active_layer

	props_by_name = {}
	otypes = dia.registered_types()
	name_type_clashes = []

	for oname in otypes :
		try :
			obj, h1, h2 = dia.get_object_type(oname).create (0, 0)
		except :
			print "Huh?", oname
			continue
		prop_keys = obj.properties.keys()
		for k in prop_keys :
			p = obj.properties[k]
			if props_by_name.has_key(k) :
				# check if it is the same type
				p0, names = props_by_name[k]
				try :
					if p0.type != p.type :
						# construct a unique name
						uname = p.name + "<" + p.type + ">"
						if props_by_name.has_key(uname) :
							props_by_name[uname][1].append(oname)
						else :
							props_by_name[uname] = (p, [oname])
							name_type_clashes.append (oname + "::" + p.name + " as " + p0.type + " and " + p.type)
					else :
						# remember the origin of the property
						props_by_name[k][1].append(oname)
				except KeyError :
					print oname, "::", k, p, "?"
			else :
				props_by_name[k] = (p, [oname])
		obj.destroy() # unsave delete, any method call will fail/crash afterweards
		obj = None

	grid = {} # one type per row
	dx = 1.0
	dy = 5.0
	ot = dia.get_object_type("UML - Class")

	props_keys = props_by_name.keys()
	# alpha-numeric sorting by type; after by number of users
	props_keys.sort (lambda a,b : len(props_by_name[b][1]) - len(props_by_name[a][1]))
	props_keys.sort (lambda a,b : cmp(props_by_name[a][0].type, props_by_name[b][0].type))
	
	almost_all = 98 * len(otypes) / 100 # 98 %

	for pname in props_keys :
	
		p, names = props_by_name[pname]

		x = 0.0
		y = 0.0
		if grid.has_key(p.type) :
			x, y = grid[p.type]
		else :
			x = 0.0
			y = len(grid.keys()) * dy
		o, h1, h2 = ot.create (x,y)
		o.properties["name"] = pname
		o.properties["template"] = 1
		o.properties["templates"] = [(p.type, '')]
		# coloring depending on use
		if len(names) > almost_all :
			o.properties["fill_colour"] = "lightgreen"
		elif len(names) > 100 :
			o.properties["fill_colour"] = "lightblue"
		elif len(names) > 2 :
			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
    def _on_import_btn_click(self, *args):

        SPACING = 3
        MAX_X = 100

        try:
            Connection.connect(host=self.host_entry.get_text(),
                               port=self.port_entry.get_text(),
                               user=self.user_entry.get_text(),
                               passwd=self.passwd_entry.get_text(),
                               db=self.db_entry.get_text())

            schema = Schema.with_name(self.schema_entry.get_text())
            table_name = self.table_entry.get_text().strip()

            if table_name:

                rel = Relation.with_name(schema, table_name)

                if isinstance(rel, Table):
                    self._add_table(rel, 0, 0, self.prefix_opt.get_active())
                elif isinstance(rel, View):
                    self._add_view(rel, 0, 0, self.prefix_opt.get_active())
                else:
                    dia.message(2, "Table not found")

            else:
                x, y, max_y = 0, 0, 0

                for table in schema.tables:

                    dia_table = self._add_table(table, x, y,
                                                self.prefix_opt.get_active())

                    x = dia_table.bounding_box.right + SPACING
                    max_y = max(max_y, dia_table.bounding_box.bottom)

                    if x > MAX_X:
                        x = 0
                        y = max_y + SPACING

                for view in schema.views:

                    dia_table = self._add_view(view, x, y,
                                               self.prefix_opt.get_active())

                    x = dia_table.bounding_box.right + SPACING
                    max_y = max(max_y, dia_table.bounding_box.bottom)

                    if x > MAX_X:
                        x = 0
                        y = max_y + SPACING

        except Exception as e:
            import sys
            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()