示例#1
0
	def Create(self):
		""" Create CMD from constructor
		"""
		import Core.Components.Container as Container
		# new containerBlock model
		self.__m = Container.ContainerBlock(self._label, self._inputs, self._outputs)

		# input and output ports
		for i in xrange(self._inputs):
			self.__m.nbiPort += i
			id = self.__m.nbiPort
			iport = Container.iPort(label='IPort %d' % id)
			iport.id = id
			self.__m.AddShape(iport)

		for o in xrange(self._outputs):
			self.__m.nboPort += o
			id = self.__m.nboPort
			oport = Container.oPort(label='OPort %d' % id)
			oport.id = id
			self.__m.AddShape(oport)

		self.__m.python_path = self._python_file
		self.__m.model_path = self._model_file

		return self.__m
示例#2
0
	def CreateBlock(*argv, **kwargs):
		""" Create Block from python_file and other info coming from wizard.
		"""
		import Core.Components.Container as Container

		python_file = kwargs['python_file']
		canvas = kwargs['canvas'] if 'canvas' in kwargs else None
		x = kwargs['x'] if 'x' in kwargs else None
		y = kwargs['y'] if 'y' in kwargs else None

		# associated python class
		cls = GetClass(python_file)

		if inspect.isclass(cls):
			# adding devs model on good graphical model
			if issubclass(cls, DomainBehavior.DomainBehavior):
				amd = AMDComponent(*argv, **kwargs)
				m = amd.Create()
				### move AMD model
				if canvas and x and y:
					### convert coordinate depending on the canvas
					x, y = canvas.GetXY(m, x, y)
					# move model from mouse position
					m.move(x, y)
				return m
			elif issubclass(cls, DomainStructure.DomainStructure):
				cmd = CMDComponent(*argv, **kwargs)
				m = cmd.Create()
				### move CMD model
				if canvas and x and y:
					### convert coordinate depending on the canvas
					x, y = canvas.GetXY(m, x, y)
					# move model from mouse position
					m.move(x, y)
				return m
			elif 'IPort' in cls.__name__:
				label = kwargs['label']
				iid = kwargs['id'] if 'id' in kwargs else canvas.GetDiagram().GetiPortCount()
				m = Container.iPort(label="%s %d" % (label, iid))
				m.id = iid
				m.move(x - 70, y - 70)
				return m
			elif 'OPort' in cls.__name__:
				label = kwargs['label']
				oid = kwargs['id'] if 'id' in kwargs else canvas.GetDiagram().GetoPortCount()
				m = Container.oPort(label="%s %d" % (label, oid))
				m.id = oid
				m.move(x - 70, y - 70)
				return m
			else:
				dial = wx.MessageDialog(None, _('Object not instantiated !\n\n Perhaps there is bad imports.'), _('Exclamation'), wx.OK | wx.ICON_EXCLAMATION)
				dial.ShowModal()
				return False

		### inform user of the existance of error and return None
		else:
			MsgBoxError(None, Utilities.GetActiveWindow(), cls)

		return None	
		
示例#3
0
    def Create(self):
        """ Create CMD from constructor
		"""
        import Core.Components.Container as Container
        # new containerBlock model
        self.__m = Container.ContainerBlock(self._label, self._inputs,
                                            self._outputs)

        # input and output ports
        for i in xrange(self._inputs):
            self.__m.nbiPort += i
            id = self.__m.nbiPort
            iport = Container.iPort(label='IPort %d' % id)
            iport.id = id
            self.__m.AddShape(iport)

        for o in xrange(self._outputs):
            self.__m.nboPort += o
            id = self.__m.nboPort
            oport = Container.oPort(label='OPort %d' % id)
            oport.id = id
            self.__m.AddShape(oport)

        self.__m.python_path = self._python_file
        self.__m.model_path = self._model_file

        return self.__m
示例#4
0
    def BlockModelAdapter(cls, label="", specific_behavior=""):
        """ Return block model concidering its class hierarchie
			The implementation depends only of the argument of the class. There is no dependance with the collector modul (in comment bellow)
		"""
        import Core.Components.Container as Container
        #from  Domain.Collector import *
        #if issubclass(cls, QuickScope.QuickScope):
        #m = ScopeGUI(label)
        #elif issubclass(cls, (To_Disk.To_Disk, Messagecollector.Messagecollector)):
        #m = DiskGUI(label)
        #else:
        ## mew CodeBlock instance
        #m = CodeBlock()

        # associated python class membre

        clsmbr = getClassMember(inspect.getfile(cls))

        ### args of class
        args = GetArgs(cls)

        ### find if there is filename param on the constructor and if there is no extention
        L = map(lambda a: os.path.isabs(str(a)), args.values())
        filename_without_ext_flag = L.index(True) if True in L else -1
        ### if there is a filename and if there is no extention -> its a to disk like object
        disk_model = filename_without_ext_flag >= 0 and not os.path.splitext(
            args.values()[filename_without_ext_flag])[-1] != ''

        ### find if scope is present in class name
        match = [
            re.match('[-_a-zA-z]*scope[-_a-zA-z]*', s, re.IGNORECASE)
            for s in clsmbr.keys() + [specific_behavior]
        ]
        scope_model = map(lambda a: a.group(0),
                          filter(lambda s: s is not None, match)) != []

        ### find if messagecollector is present in class name
        match = [
            re.match('[-_a-zA-z]*collector[-_a-zA-z]*', s, re.IGNORECASE)
            for s in clsmbr.keys() + [specific_behavior]
        ]
        messagecollector_model = map(lambda a: a.group(0),
                                     filter(lambda s: s is not None,
                                            match)) != []

        # new codeBlcok instance
        if disk_model or messagecollector_model:
            m = Container.DiskGUI(label)
        elif scope_model:
            m = Container.ScopeGUI(label)
        else:
            m = Container.CodeBlock(label)

        # define behavioral args from python class
        m.args = args

        return m
示例#5
0
文件: XML.py 项目: anup5889/devsimpy
	def OnInit(self):
		import Core.Components.Container as Container
		import GUI.ShapeCanvas as ShapeCanvas
		import GUI.DetachedFrame as DetachedFrame
		import __builtin__
		import gettext
		from Core.DomainInterface.DomainStructure import DomainStructure
		from Core.DomainInterface.DomainBehavior import DomainBehavior

		__builtin__.__dict__['ICON_PATH'] = os.path.join('Assets', 'icons')
		__builtin__.__dict__['ICON_PATH_16_16'] = os.path.join(ICON_PATH, '16x16')
		__builtin__.__dict__['NB_HISTORY_UNDO'] = 5
		__builtin__.__dict__['DOMAIN_PATH'] = 'Domain'
		__builtin__.__dict__['FONT_SIZE'] = 12
		__builtin__.__dict__['_'] = gettext.gettext
		__builtin__.__dict__['LOCAL_EDITOR'] = False

		diagram = Container.Diagram()

		self.frame = DetachedFrame.DetachedFrame(None, -1, "Test", diagram)
		newPage = ShapeCanvas.ShapeCanvas(self.frame, wx.NewId(), name='Test')
		newPage.SetDiagram(diagram)

		getDiagramFromXML("Diagram.xml", canvas=newPage)
		#diagram.SetParent(newPage)

		self.frame.Show()

		return True
示例#6
0
    def CheckItem(self, path):
        """
		"""

        item = self.ItemDico[path]
        file_path = "%s.py" % path

        info = Container.CheckClass(file_path)
        ### there is error in file
        if isinstance(info, tuple):
            ### Until it has parent, we redifine icon to inform user
            while item:
                ### change image
                self.SetItemImage(item, self.not_importedidx,
                                  wx.TreeItemIcon_Normal)
                ### next parent item
                item = self.GetItemParent(item)
        else:
            ### recompile if no error
            info = ReloadModule.recompile(Utilities.path_to_module(file_path))

            ### if not error
            if not isinstance(info, (Exception, str)):
                ### change image
                self.SetItemImage(item, self.pythonfileidx,
                                  wx.TreeItemIcon_Normal)
示例#7
0
    def Load(filename, label):
        """ Load CMD from filename
		"""
        import Core.Components.Container as Container

        assert (filename.endswith('.cmd'))

        ### new ContainerBlock instance
        m = Container.ContainerBlock()

        load_file_result = m.LoadFile(filename)

        if isinstance(load_file_result, Exception):
            wx.MessageBox(
                _('Error loading %s model : %s' %
                  (label, str(load_file_result))), _('Error'),
                wx.OK | wx.ICON_ERROR)
            return None

        else:
            ### mandatory due to the LoadFile call before
            m.label = label

            # coupled input ports
            m.input = 0
            m.output = 0
            for s in m.shapes:
                if isinstance(s, Container.iPort):
                    m.input += 1
                elif isinstance(s, Container.oPort):
                    m.output += 1

            return m
示例#8
0
def makeSimulation(filename, T):
    """
	"""

    a = Container.Diagram()

    if not isinstance(a.LoadFile(filename), Exception):
        sys.stdout.write("\nFichier charge\n")

        try:
            master = Container.Diagram.makeDEVSInstance(a)
        except:
            return False
        else:
            sim = runSimulation(master, T)
            thread = sim.Run()

            # first_time = time.time()
            # while(thread.isAlive()):
            # new_time = time.time()
            # Printer(new_time - first_time)

            sys.stdout.write("\nTime : %s" % str(master.FINAL_TIME))
            sys.stdout.write("\nFin.\n")
    else:
        sys.stdout.write(
            "\n/!\ Il y a eu une erreur. Le fichier n'a pas ete charge. /!\ \n"
        )
示例#9
0
    def AddEditPage(self, title, defaultDiagram=None):
        """
		Adds a new page for editing to the notebook and keeps track of it.
		
		@type title: string
		@param title: Title for a new page
		"""

        ### title page list
        title_pages = map(lambda p: p.name, self.pages)

        ### occurence of title in existing title pages
        c = title_pages.count(title)

        title = title + "(%d)" % c if c != 0 else title

        ### new page
        newPage = ShapeCanvas.ShapeCanvas(self, wx.NewId(), name=title)

        ### new diagram
        d = defaultDiagram or Container.Diagram()
        d.SetParent(newPage)

        ### diagram and background newpage setting
        newPage.SetDiagram(d)

        ### print canvas variable setting
        self.print_canvas = newPage
        self.print_size = self.GetSize()

        self.pages.append(newPage)
        self.AddPage(newPage, title, imageId=0)
        self.SetSelection(self.GetPageCount() - 1)
示例#10
0
def makeJS(filename):
    """
	"""

    a = Container.Diagram()
    if a.LoadFile(filename):
        sys.stdout.write("\nFichier charge\n")
        master = Container.Diagram.makeDEVSInstance(a)

        addInner = []
        liaison = []
        model = {}
        labelEnCours = str(os.path.basename(a.last_name_saved).split('.')[0])

        # path = os.path.join(os.getcwd(),os.path.basename(a.last_name_saved).split('.')[0] + ".js") # genere le fichier js dans le dossier de devsimpy
        # path = filename.split('.')[0] + ".js" # genere le fichier js dans le dossier du dsp charge.

        #Position initial du 1er modele
        x = [40]
        y = [40]
        myBool = True

        model, liaison, addInner = Join.makeJoin(a, addInner, liaison, model,
                                                 myBool, x, y, labelEnCours)
        Join.makeDEVSConf(model, liaison, addInner, "%s.js" % labelEnCours)
    else:
        return False
示例#11
0
    def Load(filename, label, canvas):
        """ Load component from filename
		"""
        import Core.Components.Container as Container
        #assert(filename.endswith('.dsp'))

        # its possible to use the orignal copy of the droped diagram
        dial = wx.MessageDialog(
            canvas, _('Do you want to open the orignal diagram in a new tab?'),
            'Question', wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)

        new_tab = dial.ShowModal() == wx.ID_YES

        # load diagram in a new page
        if new_tab:
            diagram = Container.Diagram()
        else:
            diagram = canvas.GetDiagram()

        ### if diagram is instanciated
        if diagram:
            load_file_result = diagram.LoadFile(filename)

            ### if diagram is loaded
            if not isinstance(load_file_result, Exception):

                mainW = canvas.GetTopLevelParent()
                nb2 = mainW.nb2

                ### if new tab
                if new_tab:
                    nb2.AddEditPage(label, diagram)
                else:
                    selection = nb2.GetSelection()
                    nb2.SetPageText(selection, label)

                # Add as new recent file
                if filename not in mainW.openFileList:
                    mainW.openFileList.insert(0, filename)
                    del mainW.openFileList[-1]
                    mainW.cfg.Write("openFileList",
                                    str(eval("mainW.openFileList")))
                    mainW.cfg.Flush()

                return True
            else:
                info = _(
                    'Error opening file \n file : %s \n object : %s \n error : %s '
                ) % (filename, load_file_result[1], load_file_result[0])
                wx.MessageBox(info, _('Error'), wx.OK | wx.ICON_ERROR)
                return False
示例#12
0
	def OnInit(self):

		import gettext
		import Core.Components.Container as Container
		import __builtin__

		__builtin__.__dict__['NB_HISTORY_UNDO'] = 5
		__builtin__.__dict__['ICON_PATH'] = os.path.join('Assets','icons')
		__builtin__.__dict__['ICON_PATH_16_16'] = os.path.join(ICON_PATH,'16x16')
		__builtin__.__dict__['_'] = gettext.gettext

		diagram = Container.Diagram()

		self.frame = DetachedFrame(None, -1, "Test", diagram)
		self.frame.Show()
		return True
示例#13
0
    def ShowAttributes(self, event):
        """
		"""
        import Core.Components.Container as Container

        canvas = event.GetEventObject()
        diagram = canvas.GetDiagram()

        if isinstance(
                self,
            (Container.Block, Container.Port)) and event.ControlDown():

            old_label = self.label

            d = LabelGUI.LabelDialog(canvas, self)
            d.ShowModal()

            ### update priority list
            if self.label in diagram.priority_list and old_label != self.label:
                ### find index of label priority list and replace it
                i = diagram.priority_list.index(self.label)
                diagram.priority_list[i] = new_label

                ### if block we adapt the font according to the new label size
                if " " not in new_label and isinstance(self, Container.Block):
                    font = wx.Font(self.font[0], self.font[1], self.font[2],
                                   self.font[3], False, self.font[4])
                    ln = len(self.label) * font.GetPointSize()
                    w = self.x[1] - self.x[0]

                    if ln > w:
                        a = ln - w
                        self.x[0] -= a / 2
                        self.x[1] += a / 2

                ### update of panel properties
                mainW = wx.GetApp().GetTopWindow()
                nb1 = mainW.nb1

                ### si le panel est actif, on update
                if nb1.GetSelection() == 1:
                    newContent = Container.AttributeEditor(
                        nb1.propPanel, wx.ID_ANY, self, canvas)
                    nb1.UpdatePropertiesPage(newContent)

        event.Skip()
示例#14
0
    def Update(self, concret_subject=None):
        """ Update method that manages the panel propertie depending of the selected model in the canvas
		"""

        state = concret_subject.GetState()
        canvas = state['canvas']
        model = state['model']

        if self.GetSelection() == 1:
            if model:
                if model != self.selected_model:
                    newContent = Container.AttributeEditor(
                        self.propPanel, wx.ID_ANY, model, canvas)
                    self.UpdatePropertiesPage(newContent)
                    self.selected_model = model
                    self.propPanel.SetToolTipString(self.propToolTip[1])
            else:
                self.UpdatePropertiesPage(self.defaultPropertiesPage())
                self.selected_model = None
                self.propPanel.SetToolTipString(self.propToolTip[0])
示例#15
0
    def OnMotion(self, evt):
        """ Motion engine over item.
		"""
        item, flags = self.HitTest(evt.GetPosition())

        if item and self.IsSelected(item) and (
                flags & wx.TREE_HITTEST_ONITEMLABEL) and not evt.LeftIsDown():

            path = self.GetItemPyData(item)

            if os.path.isdir(path):
                model_list = self.GetModelList(path)
                domain_list = self.GetDomainList(path)
                if domain_list:
                    tip = '\n'.join(domain_list)
                elif model_list:
                    tip = '\n'.join(model_list)
                else:
                    tip = ""
            ### is last item
            else:
                module = Components.BlockFactory.GetModule(path)
                info = Container.CheckClass(path)

                if isinstance(info, tuple):
                    doc = str(info)
                elif isinstance(module, tuple):
                    doc = str(module)
                else:
                    doc = inspect.getdoc(module)

                tip = doc if doc is not None else _(
                    "No documentation for selected model.")

            self.SetToolTipString(tip.decode('utf-8'))

        else:
            self.SetToolTip(None)

        ### else the drag and drop dont run
        evt.Skip()
示例#16
0
    def OnItemDocumentation(self, evt):
        """ Display the item's documentation on miniFrame.
		"""

        item = self.GetSelection()
        path = self.GetItemPyData(item)
        name = self.GetItemText(item)

        module = Components.BlockFactory.GetModule(path)
        info = Container.CheckClass(path)

        if isinstance(info, tuple):
            doc = str(info)
        elif isinstance(module, tuple):
            doc = str(module)
        else:
            doc = inspect.getdoc(module)

        if doc:
            dlg = wx.lib.dialogs.ScrolledMessageDialog(self, doc, name)
            dlg.CenterOnParent(wx.BOTH)
            dlg.ShowModal()
        else:
            wx.MessageBox(_('No documentation for %s') % name, 'Info', wx.OK)
示例#17
0
    def InsertNewDomain(self, dName, parent, L=None):
        """ Recurcive function that insert new Domain on library panel.
		"""
        if not L: L = []

        ### au depard seulement pour le parent de plus haut niveau (comme PowerSystem)
        if dName not in self.ItemDico.keys():
            label = os.path.basename(
                dName) if not dName.startswith('http') else filter(
                    lambda a: a != '', dName.split('/'))[-1]
            id = self.InsertItemBefore(parent, 0, label)
            self.SetItemImage(id, self.fldridx, wx.TreeItemIcon_Normal)
            self.SetItemImage(id, self.fldropenidx, wx.TreeItemIcon_Expanded)
            self.SetItemBold(id)
            self.ItemDico.update({dName: id})
            self.SetPyData(id, dName)

        ### fin de la recursion
        if not L:
            return
        else:
            item = L.pop(0)
            assert not isinstance(item, unicode), _("Warning unicode item !")
            ### element a faire remonter dans la liste
            D = []
            ### si le fils est un modele construit dans DEVSimPy
            if isinstance(item, str):

                ### le parent est recupere dans le Dico
                parent = self.ItemDico[dName]
                assert parent is not None

                ### path correspondant au parent
                parentPath = self.GetPyData(parent)

                ### remplacement des espaces
                item = item.strip()

                come_from_net = parentPath.startswith('http')

                ### suppression de l'extention su .cmd (model atomic lue a partir de __init__ donc pas d'extention)
                if item.endswith('.cmd'):
                    ### gestion de l'importation de module (.py) associe au .cmd si le fichier .py n'a jamais ete decompressse (pour edition par exemple)
                    if not come_from_net:
                        path = os.path.join(parentPath, item)
                        zf = ZipManager.Zip(path)
                        module = zf.GetModule()
                        image_file = zf.GetImage()
                    else:
                        path = parentPath + '/' + item + '.py'
                        module = load_module_from_net(path)

                    ### check error
                    error = isinstance(module, Exception)

                    ### change icon depending on the error and the presence of image in amd
                    if error:
                        img = self.not_importedidx
                    elif image_file is not None:
                        img = self.il.Add(image_file.ConvertToBitmap())
                    else:
                        img = self.coupledidx

                    ### insertion dans le tree
                    id = self.InsertItemBefore(parent, 0,
                                               os.path.splitext(item)[0], img,
                                               img)
                    self.SetPyData(id, path)

                elif item.endswith('.amd'):
                    ### gestion de l'importation de module (.py) associe au .amd si le fichier .py n'a jamais ete decompressse (pour edition par exemple)
                    if not come_from_net:
                        path = os.path.join(parentPath, item)
                        zf = ZipManager.Zip(path)
                        module = zf.GetModule()
                        image_file = zf.GetImage()
                    else:
                        path = parentPath + '/' + item + '.py'
                        module = load_module_from_net(path)

                    ### check error
                    error = isinstance(module, Exception)

                    ### change icon depending on the error and the presence of image in amd
                    if error:
                        img = self.not_importedidx
                    elif image_file is not None:
                        img = self.il.Add(image_file.ConvertToBitmap())
                    else:
                        img = self.atomicidx

                    ### insertion dans le tree
                    id = self.InsertItemBefore(parent, 0,
                                               os.path.splitext(item)[0], img,
                                               img)
                    self.SetPyData(id, path)

                else:

                    path = os.path.join(
                        parentPath, item + '.py') if not parentPath.startswith(
                            'http') else parentPath + '/' + item + '.py'

                    info = Container.CheckClass(path)

                    error = isinstance(info, tuple)
                    img = self.not_importedidx if error else self.pythonfileidx
                    ### insertion dans le tree
                    id = self.InsertItemBefore(parent, 0, item, img, img)
                    self.SetPyData(id, path)

                ### error info back propagation
                if error:
                    while parent:
                        self.SetItemImage(parent, self.not_importedidx,
                                          wx.TreeItemIcon_Normal)
                        ### next parent item
                        parent = self.GetItemParent(parent)

                ### insertion des donnees dans l'item et gestion du ItemDico
                self.ItemDico.update({os.path.join(
                    parentPath,
                    item,
                ): id})

            ### si le fils est un sous repertoire contenant au moins un fichier (all dans __init__.py different de [])
            elif isinstance(item, dict) and item.values() != [[]]:

                ### nom a inserer dans l'arbe
                dName = os.path.basename(item.keys()[0])

                ### nouveau parent
                parent = self.ItemDico[os.path.dirname(
                    item.keys()[0])] if not dName.startswith(
                        'http') else self.ItemDico[item.keys()[0].replace(
                            '/' + dName, '')]

                assert (parent is not None)
                ### insertion de fName sous parent
                id = self.InsertItemBefore(parent, 0, dName)

                self.SetItemImage(id, self.fldridx, wx.TreeItemIcon_Normal)
                self.SetItemImage(id, self.fldropenidx,
                                  wx.TreeItemIcon_Expanded)
                ### stockage du parent avec pour cle le chemin complet avec extention (pour l'import du moule dans le Dnd)
                self.ItemDico.update({item.keys()[0]: id})
                self.SetPyData(id, item.keys()[0])
                ### pour les fils du sous domain
                for elem in item.values()[0]:
                    # si elem simple (modele couple ou atomic)
                    if isinstance(elem, str):
                        ### remplacement des espaces
                        elem = elem.strip()  #replace(' ','')
                        ### parent provisoir
                        p = self.ItemDico[item.keys()[0]]
                        assert (p is not None)
                        come_from_net = item.keys()[0].startswith('http')
                        ### si model atomic
                        if elem.endswith('.cmd'):
                            ### gestion de l'importation de module (.py) associe au .amd si le fichier .py n'a jamais ete decompressse (pour edition par exemple)
                            if not come_from_net:
                                path = os.path.join(item.keys()[0], elem)
                                zf = ZipManager.Zip(path)
                                module = zf.GetModule()
                                image_file = zf.GetImage()
                            else:
                                path = item.keys()[0] + '/' + elem + '.py'
                                moduel = load_module_from_net(path)

                            ### check error
                            error = isinstance(module, Exception)

                            ### change icon depending on the error and the presence of image in amd
                            if error:
                                img = self.not_importedidx
                            elif image_file is not None:
                                img = self.il.Add(image_file.ConvertToBitmap())
                            else:
                                img = self.coupledidx

                            ### insertion dans le tree
                            id = self.InsertItemBefore(
                                p, 0,
                                os.path.splitext(elem)[0], img, img)
                            self.SetPyData(id, path)
                        elif elem.endswith('.amd'):
                            ### gestion de l'importation de module (.py) associe au .amd si le fichier .py n'a jamais ete decompressse (pour edition par exemple)
                            if not come_from_net:
                                path = os.path.join(item.keys()[0], elem)
                                zf = ZipManager.Zip(path)
                                module = zf.GetModule()
                                image_file = zf.GetImage()
                            else:
                                path = item.keys()[0] + '/' + elem + '.py'
                                moduel = load_module_from_net(path)

                            ### check error
                            error = isinstance(module, Exception)

                            ### change icon depending on the error and the presence of image in amd
                            if error:
                                img = self.not_importedidx
                            elif image_file is not None:
                                img = self.il.Add(image_file.ConvertToBitmap())
                            else:
                                img = self.atomicidx

                            ### insertion dans le tree
                            id = self.InsertItemBefore(
                                p, 0,
                                os.path.splitext(elem)[0], img, img)
                            self.SetPyData(id, path)
                        else:

                            path = os.path.join(
                                item.keys()[0], elem +
                                '.py') if not item.keys()[0].startswith(
                                    'http'
                                ) else item.keys()[0] + '/' + elem + '.py'
                            info = Container.CheckClass(path)

                            error = isinstance(info, tuple)
                            img = self.not_importedidx if error else self.pythonfileidx

                            ### insertion dans le tree
                            id = self.InsertItemBefore(p, 0, elem, img, img)
                            self.SetPyData(id, path)

                        ### error info back propagation
                        if error:
                            ### insert error to the doc field
                            while p:
                                self.SetItemImage(p, self.not_importedidx,
                                                  wx.TreeItemIcon_Normal)
                                ### next parent item
                                p = self.GetItemParent(p)

                        self.ItemDico.update({
                            os.path.join(item.keys()[0],
                                         os.path.splitext(elem)[0]):
                            id
                        })

                    else:
                        ### pour faire remonter l'info dans la liste
                        D.append(elem)

                ### mise a jour avec le nom complet
                dName = item.keys()[0]

            ### for spash screen
            try:
                ### format the string depending the nature of the item
                if isinstance(item, dict):
                    item = "%s from %s" % (
                        os.path.basename(item.keys()[0]),
                        os.path.basename(os.path.dirname(item.keys()[0])))
                else:
                    item = "%s from %s" % (item, os.path.basename(dName))

                pub.sendMessage('object.added', 'Loading %s domain...' % item)
            except:
                pass

            ### gestion de la recursion
            if D:
                return self.InsertNewDomain(dName, parent, L + D)
            else:
                return self.InsertNewDomain(dName, parent, L)
示例#18
0
    def CreateBlock(*argv, **kwargs):
        """ Create Block from python_file and other info coming from wizard.
		"""
        import Core.Components.Container as Container

        python_file = kwargs['python_file']
        canvas = kwargs['canvas'] if 'canvas' in kwargs else None
        x = kwargs['x'] if 'x' in kwargs else None
        y = kwargs['y'] if 'y' in kwargs else None

        # associated python class
        cls = GetClass(python_file)

        if inspect.isclass(cls):
            # adding devs model on good graphical model
            if issubclass(cls, DomainBehavior.DomainBehavior):
                amd = AMDComponent(*argv, **kwargs)
                m = amd.Create()
                ### move AMD model
                if canvas and x and y:
                    ### convert coordinate depending on the canvas
                    x, y = canvas.GetXY(m, x, y)
                    # move model from mouse position
                    m.move(x, y)
                return m
            elif issubclass(cls, DomainStructure.DomainStructure):
                cmd = CMDComponent(*argv, **kwargs)
                m = cmd.Create()
                ### move CMD model
                if canvas and x and y:
                    ### convert coordinate depending on the canvas
                    x, y = canvas.GetXY(m, x, y)
                    # move model from mouse position
                    m.move(x, y)
                return m
            elif 'IPort' in cls.__name__:
                label = kwargs['label']
                iid = kwargs['id'] if 'id' in kwargs else canvas.GetDiagram(
                ).GetiPortCount()
                m = Container.iPort(label="%s %d" % (label, iid))
                m.id = iid
                m.move(x - 70, y - 70)
                return m
            elif 'OPort' in cls.__name__:
                label = kwargs['label']
                oid = kwargs['id'] if 'id' in kwargs else canvas.GetDiagram(
                ).GetoPortCount()
                m = Container.oPort(label="%s %d" % (label, oid))
                m.id = oid
                m.move(x - 70, y - 70)
                return m
            else:
                dial = wx.MessageDialog(
                    None,
                    _('Object not instantiated !\n\n Perhaps there is bad imports.'
                      ), _('Exclamation'), wx.OK | wx.ICON_EXCLAMATION)
                dial.ShowModal()
                return False

        ### inform user of the existance of error and return None
        else:
            MsgBoxError(None, Utilities.GetActiveWindow(), cls)

        return None