Пример #1
0
    def scan(self, options=OrderedDict()):
        """
            Main scanning function.
            Launches airodump-ng, saves its pid,
            and makes itself xmlrpc representable.

            This implements the plugin system, calling on_before_scan
        """
        pluginmanager.trigger_event(
            "on_before_scan",
            target=self._target,
            session=self,
        )
        final_options = OrderedDict([
            ('dump_prefix', self.target_dir + "/" + self.config["name"]),
            ('wireless', self.mon_iface)
        ])
        final_options.update(options.items())

        result = self.aircrack.airodump(final_options, lambda x: True)

        # We wait default scan time and ask for airodump-ng to re-bump.
        # With this we can have an airodump-ng continuously scanning
        # on background until we want to get to a fixed channel
        # TODO Maybe magic with fixed / hoping channels and different cards?
        pid = result.result().result.pid
        Timer(int(self.config['scan_time']), self.on_scan_bumped, (pid))
        self.pids['airodump-ng'] = pid

        clean_self = clean_to_xmlrpc(self, ['extra_capabilities'])
        clean_self['_target'] = clean_to_xmlrpc(
            clean_self['_target'], ['parent'])
        return clean_self
Пример #2
0
	def OnViewLog(self, event):
		"""	When View button is clicked
		"""
		# The simulation verbose event occurs
		trigger_event('START_SIM_VERBOSE', parent=self)

		# The simulation verbose event occurs
		trigger_event('VIEW_ACTIVITY_REPORT', parent=self, master=self.current_master)
Пример #3
0
	def OnViewLog(self, event):
		"""	When View button is clicked
		"""
		# The simulation verbose event occurs
		trigger_event('START_SIM_VERBOSE', parent=self)

		# The simulation verbose event occurs
		trigger_event('VIEW_ACTIVITY_REPORT', parent=self, master=self.current_master)
Пример #4
0
    def simulate(self, T=sys.maxint):
        """
		"""

        ### ref to cpu time evaluation
        t_start = time.time()
        ### if suspend, we could store the future ref
        old_cpu_time = 0

        ### stopping condition depend on the ntl (no time limit for the simulation)
        condition = (
            lambda clk: HasActiveChild(getFlatPriorityList(self.master, [])) if self._simulator.ntl else clk <= T
        )

        ### simulation time and list of flat models ordered by devs priority
        L = [m.myTimeAdvance for m in self.flat_priority_list if m.myTimeAdvance < INFINITY] or [INFINITY]
        self.ts.Set(min(L))
        formated_priority_list = [
            (1 + i / 10000.0, m, execIntTransition) for i, m in enumerate(self.flat_priority_list)
        ]

        while condition(self.ts.Get()) and self._simulator.end_flag == False:

            ### Optional sleep
            if self._simulator.thread_sleep:
                time.sleep(self._simulator._sleeptime)

            elif self._simulator.thread_suspend:
                ### Optional suspend
                while self._simulator.thread_suspend:
                    time.sleep(1.0)
                    old_cpu_time = self._simulator.cpu_time
                    t_start = time.time()

            else:

                ### The SIM_VERBOSE event occurs
                trigger_event("SIM_VERBOSE", self.master, None, clock=self.ts.Get())

                ### tree-like data structure ordered by devsimpy priority
                priority_scheduler = filter(lambda a: self.ts.Get() == a[1].myTimeAdvance, formated_priority_list)
                heapq.heapify(priority_scheduler)

                ### TODO: execute with process of model are parallel !
                while priority_scheduler:
                    ### get most priority model and apply its internal transition
                    priority, model, transition_fct = heapq.heappop(priority_scheduler)
                    apply(transition_fct, (model,))

                    ### update simulation time
                self.ts.Set(min([m.myTimeAdvance for m in self.flat_priority_list]))

                ### just for progress bar
                self.master.timeLast = self.ts.Get() if self.ts.Get() != INFINITY else self.master.timeLast
                self._simulator.cpu_time = old_cpu_time + (time.time() - t_start)

        self._simulator.terminate()
	def OnLeftDClick(self, event):
		""" Left Double Click has been appeared.
		"""

		# If the frame is call before the simulation process, the atomicModel is not instanciate (Instanciation delegate to the makeDEVSconnection after the run of the simulation process)
		devs = self.getDEVSModel()

		if devs is not None:
			pluginmanager.trigger_event('START_SIG_VIEW', fn = devs.fn, model = self)
		else:
			dial = wx.MessageDialog(None, _('No data available \n Go to the simulation process first !'), 'Info', wx.OK)
			dial.ShowModal()
Пример #6
0
	def simulate(self, T = sys.maxint):
		"""
		"""

		### ref to cpu time evaluation
		t_start = time.time()
		### if suspend, we could store the future ref
		old_cpu_time = 0

		### stopping condition depend on the ntl (no time limit for the simulation)
		condition = lambda clk: HasActiveChild(getFlatPriorityList(self.master, [])) if self._simulator.ntl else clk <= T

		### simulation time and list of flat models ordered by devs priority
		L = [m.myTimeAdvance for m in self.flat_priority_list if m.myTimeAdvance < INFINITY] or [INFINITY]
		self.ts.Set(min(L))
		formated_priority_list = [(1+i/10000.0, m, execIntTransition) for i,m in enumerate(self.flat_priority_list)]

		while condition(self.ts.Get()) and self._simulator.end_flag == False:

			### Optional sleep
			if self._simulator.thread_sleep:
				time.sleep(self._simulator._sleeptime)

			elif self._simulator.thread_suspend:
			### Optional suspend
				while self._simulator.thread_suspend:
					time.sleep(1.0)
					old_cpu_time = self._simulator.cpu_time
					t_start = time.time()

			else:

				### The SIM_VERBOSE event occurs
				trigger_event("SIM_VERBOSE", self.master, None, clock = self.ts.Get())

				### tree-like data structure ordered by devsimpy priority
				priority_scheduler = filter(lambda a: self.ts.Get() == a[1].myTimeAdvance, formated_priority_list)
				heapq.heapify(priority_scheduler)

				### TODO: execute with process of model are parallel !
				while(priority_scheduler):
					### get most priority model and apply its internal transition
					priority, model, transition_fct = heapq.heappop(priority_scheduler)
					apply(transition_fct, (model,))

				### update simulation time
				self.ts.Set(min([m.myTimeAdvance for m in self.flat_priority_list]))

				### just for progress bar
				self.master.timeLast = self.ts.Get() if self.ts.Get() != INFINITY else self.master.timeLast
				self._simulator.cpu_time = old_cpu_time + (time.time()-t_start)

		self._simulator.terminate()
Пример #7
0
	def send(self, d, msg):
		""" Dispatch messages to the right method.
		"""
		if isinstance(d, CoupledDEVS):
			CS = CoupledSolver()
			r = CS.receive(d, msg)
		else:
			AS = AtomicSolver()
			r = AS.receive(d, msg)

			pluginmanager.trigger_event("SIM_BLINK", model=d, msg=msg)
			pluginmanager.trigger_event("SIM_TEST", model=d, msg=msg)

		return r
Пример #8
0
    def send(self, d, msg):
        """ Dispatch messages to the right method.
		"""
        if isinstance(d, CoupledDEVS):
            CS = CoupledSolver()
            r = CS.receive(d, msg)
        else:
            AS = AtomicSolver()
            r = AS.receive(d, msg)

            pluginmanager.trigger_event("SIM_BLINK", model=d, msg=msg)
            pluginmanager.trigger_event("SIM_TEST", model=d, msg=msg)

        return r
Пример #9
0
    def simulate(self, T=sys.maxint):
        """
		"""

        master = self._simulator.getMaster()
        send = self._simulator.send
        #clock = master.myTimeAdvance

        # Initialize the model --- set the simulation clock to 0.
        send(master, (0, [], 0))

        clock = master.myTimeAdvance

        ### ref to cpu time evaluation
        t_start = time.time()

        ### if suspend, we could store the future ref
        old_cpu_time = 0

        ### stoping condition depend on the ntl (no time limit for the simulation)
        condition = lambda clock: HasActiveChild(
            getFlatImmChildrenList(master, [])
        ) if self._simulator.ntl else clock <= T

        # Main loop repeatedly sends $(*,\,t)$ messages to the model's root DEVS.
        while condition(clock) and self._simulator.end_flag == False:

            ##Optional sleep
            if self._simulator.thread_sleep:
                time.sleep(self._simulator._sleeptime)

            elif self._simulator.thread_suspend:
                ### Optional suspend
                while self._simulator.thread_suspend:
                    time.sleep(1.0)
                    old_cpu_time = self._simulator.cpu_time
                    t_start = time.time()

            else:
                # The SIM_VERBOSE event occurs
                trigger_event("SIM_VERBOSE", clock=clock)

                send(master, (1, {}, clock))

                clock = master.myTimeAdvance

                self._simulator.cpu_time = old_cpu_time + (time.time() -
                                                           t_start)

        self._simulator.terminate()
Пример #10
0
    def simulate(self, T=sys.maxint):
        """
		"""

        master = self._simulator.getMaster()
        send = self._simulator.send
        # clock = master.myTimeAdvance

        # Initialize the model --- set the simulation clock to 0.
        send(master, (0, [], 0))

        clock = master.myTimeAdvance

        ### ref to cpu time evaluation
        t_start = time.time()

        ### if suspend, we could store the future ref
        old_cpu_time = 0

        ### stoping condition depend on the ntl (no time limit for the simulation)
        condition = (
            lambda clock: HasActiveChild(getFlatImmChildrenList(master, [])) if self._simulator.ntl else clock <= T
        )

        # Main loop repeatedly sends $(*,\,t)$ messages to the model's root DEVS.
        while condition(clock) and self._simulator.end_flag == False:

            ##Optional sleep
            if self._simulator.thread_sleep:
                time.sleep(self._simulator._sleeptime)

            elif self._simulator.thread_suspend:
                ### Optional suspend
                while self._simulator.thread_suspend:
                    time.sleep(1.0)
                    old_cpu_time = self._simulator.cpu_time
                    t_start = time.time()

            else:
                # The SIM_VERBOSE event occurs
                trigger_event("SIM_VERBOSE", clock=clock)

                send(master, (1, {}, clock))

                clock = master.myTimeAdvance

                self._simulator.cpu_time = old_cpu_time + (time.time() - t_start)

        self._simulator.terminate()
Пример #11
0
    def plugin_scan(self, fmap, plugin):
        results = pluginmanager.trigger_event(plugin + '-SCAN',
                                              infile = fmap,
                                              min_size = self.MIN_SIZE,
                                              max_size = self.MAX_SIZE,
                                              max_search = self.MAX_SEARCH)

        while gtk.events_pending():
            gtk.main_iteration()

        for data in results[0]:
            heapq.heappush(self, data)
Пример #12
0
 def compress(self, infile, flag):
     if flag == 0x10:
         return lzss.compress(infile)
     elif flag == 0x11:
         return onz.compress(infile)
     elif flag == 0x30:
         return rle.compress(infile)
     elif flag in (0x24, 0x28):
         return huffman.compress(infile, (type & 0xf))
     elif flag == 0x40:
         return lz40.compress(infile)
     else:
         return pluginmanager.trigger_event(('%s-COMPRESS' % flag), infile = infile)[0]
Пример #13
0
    def on_scan_bumped(self, pid):
        """
            Callback to execute each time we rebump on scan().
            This schedulles a re-rebump so it's made periodically.
            That's how we'll get periodically (each second) updated csv files

            This implements the plugin system, calling on_after_scan
        """
        self.rebump(pid)
        time.sleep(1)
        Timer(int(self.config['scan_time']), self.on_scan_bumped, (pid))
        return pluginmanager.trigger_event(
            "on_after_scan",
            target=self.target,
            session=self,
        )
Пример #14
0
    def uncompress(self, infile, index):
        flag = self.get_flag(index)
        address = self.get_address(index)

        try:
            if flag == 0x10:
                return lzss.uncompress(infile, address)
            elif flag == 0x11:
                return onz.uncompress(infile, address)
            elif flag == 0x30:
                return rle.uncompress(infile, address)
            elif flag in (0x24, 0x28):
                return huffman.uncompress(infile, address)
            elif flag == 0x40:
                return lz40.uncompress(infile, address)
            else:
                return pluginmanager.trigger_event(('%s-UNCOMPRESS' % flag),
                                                     infile = infile,
                                                     address = address)[0]
        except:
            return False
Пример #15
0
def execIntTransition(m):
	"""
	"""

	ts =  m.ts.Get()

	if m.timeNext != INFINITY:
		m.outputFnc()

	m.elapsed = ts - m.timeLast

	m.intTransition()
	m.timeLast = ts
	m.myTimeAdvance = m.timeAdvance()
	m.timeNext = m.timeLast+m.myTimeAdvance
	if m.myTimeAdvance != INFINITY: m.myTimeAdvance += ts
	m.elapsed = 0.0

	# The SIM_VERBOSE event occurs
	trigger_event("SIM_VERBOSE", model=m, msg=0)
	trigger_event("SIM_BLINK", model=m, msg=[1])
	trigger_event("SIM_TEST", model=m, msg=[1])
Пример #16
0
def execIntTransition(m):
	"""
	"""

	ts =  m.ts.Get()

	if m.timeNext != INFINITY:
		m.outputFnc()

	m.elapsed = ts - m.timeLast

	m.intTransition()
	m.timeLast = ts
	m.myTimeAdvance = m.timeAdvance()
	m.timeNext = m.timeLast+m.myTimeAdvance
	if m.myTimeAdvance != INFINITY: m.myTimeAdvance += ts
	m.elapsed = 0.0

	# The SIM_VERBOSE event occurs
	trigger_event("SIM_VERBOSE", model=m, msg=0)
	trigger_event("SIM_BLINK", model=m, msg=[1])
	trigger_event("SIM_TEST", model=m, msg=[1])
Пример #17
0
def execExtTransition(m):
	"""
	"""

	ts =  m.ts.Get()

	m.elapsed =ts - m.timeLast

	m.extTransition()

	m.timeLast = ts
	m.myTimeAdvance = m.timeAdvance()
	m.timeNext = m.timeLast+m.myTimeAdvance
	if m.myTimeAdvance != INFINITY: m.myTimeAdvance += ts
	m.elapsed = 0.0

	# The SIM_VERBOSE event occurs
	trigger_event("SIM_VERBOSE", model=m, msg=1)
	trigger_event("SIM_BLINK", model=m, msg=[{}])
	trigger_event("SIM_TEST", model=m, msg=[{}])

	return m
Пример #18
0
def execExtTransition(m):
	"""
	"""

	ts =  m.ts.Get()

	m.elapsed =ts - m.timeLast

	m.extTransition()

	m.timeLast = ts
	m.myTimeAdvance = m.timeAdvance()
	m.timeNext = m.timeLast+m.myTimeAdvance
	if m.myTimeAdvance != INFINITY: m.myTimeAdvance += ts
	m.elapsed = 0.0

	# The SIM_VERBOSE event occurs
	trigger_event("SIM_VERBOSE", model=m, msg=1)
	trigger_event("SIM_BLINK", model=m, msg=[{}])
	trigger_event("SIM_TEST", model=m, msg=[{}])

	return m
Пример #19
0
class Zip:
    def __init__(self, fn, files=[]):
        """ Constructor
		"""
        ### local copy
        self.fn = fn

        if files != []:
            self.Create(files)

    def Create(self, add_files=[]):
        dir_name, base_name = os.path.split(self.fn)
        name, ext = os.path.splitext(base_name)

        ### output zip file
        zout = zipfile.ZipFile(self.fn, "w")

        ### for all files wich could be added
        for fn in filter(
                lambda f: os.path.exists(f) or zipfile.is_zipfile(
                    os.path.dirname(f)), add_files):
            fn_dir_name, fn_base_name = os.path.split(fn)
            fn_name, fn_ext = os.path.splitext(fn_base_name)
            ### if adding file is compressed, we decompress and add it
            if zipfile.is_zipfile(fn_dir_name):
                zin = zipfile.ZipFile(fn_dir_name, 'r')
                buffer = zin.read(fn_base_name)
                ### if not .dat file and the name of file is not the same with the zip file
                #if fn_ext == '.py':
                #zout.writestr("%s%s"%(name,fn_ext), buffer)
                #else:
                zout.writestr(fn_base_name, buffer)
                zin.close()
            else:
                zout.write(fn, fn_base_name)

        zout.close()

    def Update(self, replace_files=[]):
        """ Update zip archive with the new replace file names
		"""

        ### delete empty fileName
        replace_files = filter(lambda f: f != '', replace_files)

        # call this function because : http://www.digi.com/wiki/developer/index.php/Error_messages
        self.ClearCache()

        zin = zipfile.ZipFile(self.fn, 'r')
        zout = zipfile.ZipFile("new_arch.zip", 'w')

        exclude_file = []

        ### write all replace file in the new archive
        for fn in replace_files:
            dir_name, base_name = os.path.split(fn)

            if zipfile.is_zipfile(dir_name):
                #print '1'
                z = zipfile.ZipFile(dir_name, 'r')
                data = z.read(base_name)
                ### this line is in comment because is zip file contain image file we can not encode it.
                zout.writestr(base_name, data.encode('utf-8'))
                #zout.writestr(base_name, data)
                z.close()
                #print '11'
                #sys.stdout.write("update %s from compressed %s\n"%(base_name, fn))
            elif os.path.exists(fn):
                #print '2'
                zout.write(fn, base_name)
                #print '22'
                #sys.stdout.write("update %s from %s\n"%(base_name, fn))
            elif os.path.exists(base_name) and dir_name != "":
                #print '3'
                zout.write(base_name, fn)
                #print '33'
                #sys.stdout.write("update %s from %s\n"%(fn, base_name))
            else:
                exclude_file.append(replace_files.index(fn))
                #sys.stdout.write("%s unknown\n"%(fn))

        ### try to rewrite not replaced files from original zip
        info_list = zin.infolist()
        for item in info_list:
            s = os.path.basename(item.filename)
            if s not in map(os.path.basename, replace_files
                            ) and info_list.index(item) not in exclude_file:
                buffer = zin.read(item.filename)
                zout.writestr(item, buffer)
                sys.stdout.write("%s rewrite\n" % (item.filename))

        ### close all files
        zout.close()
        zin.close()

        ### remove and rename the zip file
        self.ClearFiles()

    def Delete(self, delete_files=[]):
        """ Remove file in zip archive
		"""

        ### delete empty fileName
        delete_files = filter(lambda f: f != '', delete_files)

        # call this function because : http://www.digi.com/wiki/developer/index.php/Error_messages
        self.ClearCache()

        zin = zipfile.ZipFile(self.fn, 'r')
        zout = zipfile.ZipFile("new_arch.zip", 'w')

        ###
        info_list = zin.infolist()
        for item in info_list:
            if item.filename not in delete_files:
                buffer = zin.read(item.filename)
                zout.writestr(item, buffer)
                ##sys.stdout.write("%s rewrite\n"%(item.filename))

        ### close all files
        zout.close()
        zin.close()

        ### remove and rename the zip file
        self.ClearFiles()

    def GetImage(self, scaleW=16, scaleH=16):
        """ Get image object from image file stored in zip file.
			scaleH and scaleW are used to rescale image
		"""

        if zipfile.is_zipfile(self.fn):
            return None

        zf = zipfile.ZipFile(self.fn, 'r')

        ### find if python file has same name of model file
        L = filter(lambda f: f.endswith(('.jpg', 'jpeg', 'png', 'bmp')),
                   zf.namelist())

        if L != []:
            import wx
            f = zf.open(L.pop())
            buf = f.read()
            f.close()
            zf.close()
            sbuf = StringIO.StringIO(buf)
            image = wx.ImageFromStream(sbuf)
            sbuf.close()
            image.Rescale(scaleW, scaleH)
            return image
        else:
            zf.close()
            return None

    @staticmethod
    def GetPluginFile(fn):
        """ TODO: comment
		"""
        ### zipfile (amd or cmd)
        zf = zipfile.ZipFile(fn, 'r')
        nl = zf.namelist()
        zf.close()

        L = filter(lambda a: a != [],
                   map(lambda s: re.findall("^(plugins[/]?[\w]*.py)$", s), nl))
        return L.pop(0)[0] if L != [] else ""

    @staticmethod
    def HasPlugin(fn):
        """ TODO: comment
		"""

        ### zipfile (amd or cmd)
        zf = zipfile.ZipFile(fn, 'r')
        nl = zf.namelist()
        zf.close()
        ### plugin file is plugins.pi in root of zipfile or in plugins zipedd directory
        return any(map(lambda s: re.search("^(plugins[/]*[\w]*.py)$", s), nl))

    # BDD Test----------------------------------------------------------------------
    @staticmethod
    def HasTests(fn):
        """ TODO: comment
		"""
        name = os.path.basename(getPythonModelFileName(fn)).split('.')[0]
        zf = zipfile.ZipFile(fn, 'r')
        nl = zf.namelist()
        zf.close()
        return any(
            map(
                lambda s: re.search("^(BDD/[\w*/]*\.py|BDD/[\w*/]*\.feature)$",
                                    s), nl))

    @staticmethod
    def GetTests(fn):
        """ Return feature, steps and environment files from .amd
		"""
        zf = zipfile.ZipFile(fn, 'r')
        nl = zf.namelist()

        zf.close()

        ###
        tests_files = filter(
            lambda a: a != [],
            map(
                lambda s: re.findall(
                    "^(BDD/[\w*/]*\.py|BDD/[\w*/]*\.feature)$", s), nl))
        tests_files = [a[0] for a in tests_files]

        return tests_files

        #### find feature and steps file
        #feat = None
        #steps = None
        #env = None

        #feat = filter(lambda t: t.endswith('.feature'), zf.namelist())[0]

        #if 'steps.py' in zf.namelist():
        #steps = "steps.py"
        #if 'environment.py' in zf.namelist():
        #env = "environment.py"

        #zf.close()

        #return feat, steps, env

    # ------------------------------------------------------------------------------

    def GetModule(self, rcp=False):
        """ Load module from zip file corresponding to the amd or cmd model.
			It used when the tree library is created.
		"""

        module_name = getPythonModelFileName(self.fn)

        # get module name
        try:
            module_name = getPythonModelFileName(self.fn)
        except Exception, info:
            sys.stderr.write(
                _("Error in ZipManager class for GetModule: no python file in the archive\n"
                  ))
            return info

        # if necessary, recompile (for update after editing code source of model)
        #if rcp: recompile(module_name)

        # import module
        try:
            ### clear to clean the import after exporting model (amd or cmd) and reload within the same instance of DEVSimPy
            zipimport._zip_directory_cache.clear()

            trigger_event("IMPORT_STRATEGIES", fn=self.fn)

            importer = zipimport.zipimporter(self.fn)

            ### allows to import the lib from its name (like import MyModel.amd). Dangerous because confuse!
            ### Import can be done using: import Name (ex. import MessageCollector - if MessageCollecor is .amd or .cmd)
            fullname = "".join([
                os.path.basename(os.path.dirname(self.fn)),
                module_name.split('.py')[0]
            ])
            module = importer.load_module(module_name.split('.py')[0])
            module.__name__ = path_to_module(module_name)

            ### allows to import with a reference from the parent directory (like parentName.model).
            ### Now import of .amd or .cmd module is composed by DomainModel (no point!).
            ### Example : import CollectorMessageCollector
            sys.modules[fullname] = module

            ### TODO make a recursive method to go up until the Domain dir, for not external lib!

        except Exception, info:
            msg_i = _("Error in execution: ")
            msg_o = listf(
                format_exception(sys.exc_type, sys.exc_value,
                                 sys.exc_traceback))
            try:
                sys.stderr.write(msg_i + str(sys.exc_info()[0]) + "\r\n" +
                                 msg_o)
            except UnicodeDecodeError:
                sys.stderr.write(
                    msg_i +
                    str(sys.exc_info()[0]).decode('latin-1').encode("utf-8") +
                    "\r\n" + msg_o)
            return info
Пример #20
0
    def GetModule(self, rcp=False):
        """ Load module from zip file corresponding to the amd or cmd model.
			It used when the tree library is created.
		"""

        module_name = getPythonModelFileName(self.fn)

        # get module name
        try:
            module_name = getPythonModelFileName(self.fn)
        except Exception as info:
            sys.stderr.write(
                _("Error in ZipManager class for GetModule: no python file in the archive\n"
                  ))
            return info

        # if necessary, recompile (for update after editing code source of model)
        #if rcp: recompile(module_name)

        # import module
        try:
            ### clear to clean the import after exporting model (amd or cmd) and reload within the same instance of DEVSimPy
            zipimport._zip_directory_cache.clear()

            trigger_event("IMPORT_STRATEGIES", fn=self.fn)

            importer = zipimport.zipimporter(self.fn)

            ### allows to import the lib from its name (like import MyModel.amd). Dangerous because confuse!
            ### Import can be done using: import Name (ex. import MessageCollector - if MessageCollecor is .amd or .cmd)
            p = os.path.dirname(os.path.dirname(self.fn))
            if p not in sys.path:
                sys.path.append(p)
            fullname = "".join([
                os.path.basename(os.path.dirname(self.fn)),
                module_name.split('.py')[0]
            ])
            module = importer.load_module(module_name.split('.py')[0])
            module.__name__ = path_to_module(module_name)

            ### allows to import with a reference from the parent directory (like parentName.model).
            ### Now import of .amd or .cmd module is composed by DomainModel (no point!).
            ### Example : import CollectorMessageCollector
            sys.modules[fullname] = module

            ### TODO make a recursive method to go up until the Domain dir, for not external lib!

        except Exception as info:
            msg_i = _("Error in execution: ")
            msg_o = listf(
                format_exception(sys.exc_info()[0],
                                 sys.exc_info()[1],
                                 sys.exc_info()[2]))
            try:
                sys.stderr.write(msg_i + str(sys.exc_info()[0]) + "\r\n" +
                                 msg_o)
            except UnicodeDecodeError:
                sys.stderr.write(
                    msg_i +
                    str(sys.exc_info()[0]).decode('latin-1').encode("utf-8") +
                    "\r\n" + msg_o)
            return info

        else:
            return module
Пример #21
0
	def receive(aDEVS, msg):

		# For any received message, the time {\tt t} (time at which the message
		# is sent) is the second item in the list {\tt msg}.
		t = msg[2]

		# $(*,\,t)$ message --- triggers internal transition and returns
		# $(y,\,t)$ message for parent coupled-DEVS:
		if msg[0] == 1:
			if t != aDEVS.timeNext:
				Error("Bad synchronization...1", 1)

			# First call the output function, which (amongst other things) rebuilds
			# the output dictionnary {\tt myOutput}:
			aDEVS.myOutput = {}
			aDEVS.outputFnc()

			aDEVS.elapsed = t - aDEVS.timeLast
			aDEVS.intTransition()

			aDEVS.timeLast = t
			aDEVS.myTimeAdvance = aDEVS.timeAdvance()
			aDEVS.timeNext = aDEVS.timeLast + aDEVS.myTimeAdvance
			if aDEVS.myTimeAdvance != INFINITY: aDEVS.myTimeAdvance += t
			aDEVS.elapsed = 0

			# The SIM_VERBOSE event occurs
			pluginmanager.trigger_event("SIM_VERBOSE", model=aDEVS, msg=0)

			# Return the DEVS' output to the parent coupled-DEVS (rather than
			# sending $(y,\,t)$ message).
			return aDEVS.myOutput

		# ${x,\,t)$ message --- triggers external transition, where $x$ is the
		# input dictionnary to the DEVS:
		elif isinstance(msg[0], dict):
			if not(aDEVS.timeLast <= t <= aDEVS.timeNext):
				Error("Bad synchronization...2", 1)

			aDEVS.myInput = msg[0]

			# update elapsed time. This is necessary for the call to the external
			# transition function, which is used to update the DEVS' state.
			aDEVS.elapsed = t - aDEVS.timeLast
			aDEVS.extTransition()

			# Udpate time variables:
			aDEVS.timeLast = t
			aDEVS.myTimeAdvance = aDEVS.timeAdvance()
			aDEVS.timeNext = aDEVS.timeLast + aDEVS.myTimeAdvance
			if aDEVS.myTimeAdvance != INFINITY: aDEVS.myTimeAdvance += t
			aDEVS.elapsed = 0

			# The SIM_VERBOSE event occurs
			pluginmanager.trigger_event("SIM_VERBOSE", model=aDEVS, msg=1)

		# $(i,\,t)$ message --- sets origin of time at {\tt t}:
		elif msg[0] == 0:
			aDEVS.timeLast = t - aDEVS.elapsed
			aDEVS.myTimeAdvance = aDEVS.timeAdvance()
			aDEVS.timeNext = aDEVS.timeLast + aDEVS.myTimeAdvance
			if aDEVS.myTimeAdvance != INFINITY: aDEVS.myTimeAdvance += t

		else:
			Error("Unrecognized message", 1)
Пример #22
0
	def OnOk(self, event):
		""" When Run button is clicked
		"""

		assert(self.master is not None)

		if self._value.GetValidator().Validate(self._value) or self.ntl:

			### pour prendre en compte les simulations multiples sans relancer un SimulationDialog
			### si le thread n'est pas lancé (pas pendant un suspend)
			if self.thread is not None and not self.thread.thread_suspend:
				diagram = self.master.getBlockModel()
				diagram.Clean()
				self.current_master = Container.Diagram.makeDEVSInstance(diagram)
			else:
				self.current_master = self.master

			if isinstance(self.parent, wx.Panel):
				# redirection du stdout ici dans le cas du Panel (sinon dans OnSimulation)
				mainW = self.parent.GetTopLevelParent()
				sys.stdout = mainW.stdioWin

			### test si le modele et bien charge
			if (self.current_master == None) or (self.current_master.componentSet == []):
				return self.MsgBoxEmptyModel()

			### dont erase the gauge if ntl
			if not self.ntl:
				# stockage du temps de simulation dans le master
				self.current_master.FINAL_TIME = float(self._value.GetValue())
				self._gauge.SetValue(0)
				### if _gauge is wx.Slider
				#self._gauge.SetMax(self.current_master.FINAL_TIME)

			self.statusbar.SetBackgroundColour('')
			self.statusbar.SetStatusText("", 1)
			if self.statusbar.GetFieldsCount() > 2:
				self.statusbar.SetStatusText("", 2)

			if (self.thread is None) or (not self.timer.IsRunning()):

				trigger_event("START_BLINK", parent=self, master=self.current_master)
				trigger_event("START_TEST", parent=self, master=self.current_master)

				### The START_ACTIVITY_TRACKING event occurs
				trigger_event("START_ACTIVITY_TRACKING", parent=self, master=self.current_master)

				### The START_ACTIVITY_TRACKING event occurs
				trigger_event("START_STATE_TRAJECTORY", parent=self, master=self.current_master)

				### The START_CONCURRENT_SIMULATION event occurs
				trigger_event("START_CONCURRENT_SIMULATION", parent=self, master=self.current_master)

				### future call is required because the simulator is flattened during the execution of the strategy 3
				wx.FutureCall(1, trigger_event, 'START_DIAGRAM', parent=self, master=self.current_master)

				### clear all log file
				for fn in filter(lambda f: f.endswith('.devsimpy.log'), os.listdir(gettempdir())):
					os.remove(os.path.join(gettempdir(),fn))

				self.thread = simulator_factory(self.current_master, self.selected_strategy, self.prof, self.ntl, self.verbose)
				self.thread.setName(self.title)

				### si le modele n'a pas de couplage, ou si pas de generateur: alors pas besoin de simuler
				if self.thread.end_flag:
					self.OnTimer(event)
				else:
					self.timer.Start(100)

			else:
				#print self.thread.getAlgorithm().trace
				### for back simulation
				#self.thread.s = shelve.open(self.thread.f.name+'.db',flag='r')
				#self.thread.model = self.thread.s['s'][str(float(self._gauge.GetValue()))]

				### restart the hiding gauge
				if self.ntl:
					self._gauge.Show()

				### restart thread
				self.thread.resume_thread()

			self.Interact(False)

			if self.count >= 100:
				return
Пример #23
0
    def receive(aDEVS, msg):

        # For any received message, the time {\tt t} (time at which the message
        # is sent) is the second item in the list {\tt msg}.
        t = msg[2]

        # $(*,\,t)$ message --- triggers internal transition and returns
        # $(y,\,t)$ message for parent coupled-DEVS:
        if msg[0] == 1:
            if t != aDEVS.timeNext:
                Error("Bad synchronization...1", 1)

            # First call the output function, which (amongst other things) rebuilds
            # the output dictionnary {\tt myOutput}:
            aDEVS.myOutput = {}
            aDEVS.outputFnc()

            aDEVS.elapsed = t - aDEVS.timeLast
            aDEVS.intTransition()

            aDEVS.timeLast = t
            aDEVS.myTimeAdvance = aDEVS.timeAdvance()
            aDEVS.timeNext = aDEVS.timeLast + aDEVS.myTimeAdvance
            if aDEVS.myTimeAdvance != INFINITY: aDEVS.myTimeAdvance += t
            aDEVS.elapsed = 0

            # The SIM_VERBOSE event occurs
            pluginmanager.trigger_event("SIM_VERBOSE", model=aDEVS, msg=0)

            # Return the DEVS' output to the parent coupled-DEVS (rather than
            # sending $(y,\,t)$ message).
            return aDEVS.myOutput

        # ${x,\,t)$ message --- triggers external transition, where $x$ is the
        # input dictionnary to the DEVS:
        elif isinstance(msg[0], dict):
            if not (aDEVS.timeLast <= t <= aDEVS.timeNext):
                Error("Bad synchronization...2", 1)

            aDEVS.myInput = msg[0]

            # update elapsed time. This is necessary for the call to the external
            # transition function, which is used to update the DEVS' state.
            aDEVS.elapsed = t - aDEVS.timeLast
            aDEVS.extTransition()

            # Udpate time variables:
            aDEVS.timeLast = t
            aDEVS.myTimeAdvance = aDEVS.timeAdvance()
            aDEVS.timeNext = aDEVS.timeLast + aDEVS.myTimeAdvance
            if aDEVS.myTimeAdvance != INFINITY: aDEVS.myTimeAdvance += t
            aDEVS.elapsed = 0

            # The SIM_VERBOSE event occurs
            pluginmanager.trigger_event("SIM_VERBOSE", model=aDEVS, msg=1)

        # $(i,\,t)$ message --- sets origin of time at {\tt t}:
        elif msg[0] == 0:
            aDEVS.timeLast = t - aDEVS.elapsed
            aDEVS.myTimeAdvance = aDEVS.timeAdvance()
            aDEVS.timeNext = aDEVS.timeLast + aDEVS.myTimeAdvance
            if aDEVS.myTimeAdvance != INFINITY: aDEVS.myTimeAdvance += t

        else:
            Error("Unrecognized message", 1)
Пример #24
0
    def __init__(self, shape, event):
        """ Constructor.
		"""

        wx.Menu.__init__(self)

        self.__canvas = event.GetEventObject()

        rotate_subMenu = wx.Menu()
        rotate_all_subMenu = wx.Menu()
        rotate_input_subMenu = wx.Menu()
        rotate_output_subMenu = wx.Menu()

        export_subMenu = wx.Menu()
        connectable_subMenu = wx.Menu()
        edit_subMenu = wx.Menu()

        edit = wx.MenuItem(self, ID_EDIT_SHAPE, _("Edit"), _("Edit the code"))
        editModel = wx.MenuItem(self, ID_EDIT_MODEL_SHAPE, _("Model"),
                                _("Edit the model code"))
        editTest = wx.MenuItem(self, ID_TESTING_SHAPE, _("Tests"),
                               _("Edit the tests code"))
        log = wx.MenuItem(self, ID_LOG_SHAPE, _("Log"), _("View log file"))
        copy = wx.MenuItem(self, ID_COPY_SHAPE, _("&Copy\tCtrl+C"),
                           _("Copy the model"))
        paste = wx.MenuItem(self, ID_PASTE_SHAPE, _("&Paste\tCtrl+V"),
                            _("Paste the model"))
        cut = wx.MenuItem(self, ID_CUT_SHAPE, _("&Cut\tCtrl+X"),
                          _("Cut the model"))
        rotateAll = wx.MenuItem(self, ID_ROTATE_ALL_SHAPE, _("&All"),
                                _("Rotate all ports"))
        rotateInput = wx.MenuItem(self, ID_ROTATE_INPUT_SHAPE,
                                  _("&Input ports"), _("Rotate input ports"))
        rotateOutput = wx.MenuItem(self, ID_ROTATE_OUTPUT_SHAPE,
                                   _("&Output ports"),
                                   _("Rotate output ports"))
        rotateR = wx.MenuItem(self, ID_RIGHT_ROTATE_SHAPE,
                              _("&Right Rotate\tCtrl+R"),
                              _("Rotate on the right"))
        rotateL = wx.MenuItem(self, ID_LEFT_ROTATE_SHAPE,
                              _("&Left Rotate\tCtrl+L"),
                              _("Rotate on the left"))
        rotateIR = wx.MenuItem(self, ID_RIGHT_ROTATE_INPUT_SHAPE,
                               _("&Right Rotate\tCtrl+R"),
                               _("Rotate on the right"))
        rotateIL = wx.MenuItem(self, ID_LEFT_ROTATE_INPUT_SHAPE,
                               _("&Left Rotate\tCtrl+L"),
                               _("Rotate on the left"))
        rotateOR = wx.MenuItem(self, ID_RIGHT_ROTATE_OUTPUT_SHAPE,
                               _("&Right Rotate\tCtrl+R"),
                               _("Rotate on the right"))
        rotateOL = wx.MenuItem(self, ID_LEFT_ROTATE_OUTPUT_SHAPE,
                               _("&Left Rotate\tCtrl+L"),
                               _("Rotate on the left"))
        rename = wx.MenuItem(self, ID_RENAME_SHAPE, _("&Rename"),
                             _("Rename the label of the model"))
        delete = wx.MenuItem(self, ID_DELETE_SHAPE, _("Delete"),
                             _("Delete the model"))
        lock = wx.MenuItem(self, ID_LOCK_SHAPE, _("Lock"), _("Lock the link"))
        unlock = wx.MenuItem(self, ID_UNLOCK_SHAPE, _("Unlock"),
                             _("Unlock the link"))
        export = wx.MenuItem(self, ID_EXPORT_SHAPE, _("Export"),
                             _("Export the model"))
        exportAMD = wx.MenuItem(self, ID_EXPORT_AMD_SHAPE, _("AMD"),
                                _("Model exported to a amd file"))
        exportCMD = wx.MenuItem(self, ID_EXPORT_CMD_SHAPE, _("CMD"),
                                _("Model exported to a cmd file"))
        exportXML = wx.MenuItem(self, ID_EXPORT_XML_SHAPE, _("XML"),
                                _("Model exported to a xml file"))
        exportJS = wx.MenuItem(self, ID_EXPORT_JS_SHAPE, _("JS"),
                               _("Model exported to a js (join) file"))
        plugin = wx.MenuItem(self, ID_PLUGINS_SHAPE, _("Plug-in"),
                             _("Plug-in manager"))
        properties = wx.MenuItem(self, ID_PROPERTIES_SHAPE, _("Properties"),
                                 _("Edit the attributes"))

        edit.SetBitmap(
            wx.Image(os.path.join(ICON_PATH_16_16, 'edit.png'),
                     wx.BITMAP_TYPE_PNG).ConvertToBitmap())
        editModel.SetBitmap(
            wx.Image(os.path.join(ICON_PATH_16_16, 'edit.png'),
                     wx.BITMAP_TYPE_PNG).ConvertToBitmap())
        editTest.SetBitmap(
            wx.Image(os.path.join(ICON_PATH_16_16, 'test.png'),
                     wx.BITMAP_TYPE_PNG).ConvertToBitmap())
        log.SetBitmap(
            wx.Image(os.path.join(ICON_PATH_16_16, 'log.png'),
                     wx.BITMAP_TYPE_PNG).ConvertToBitmap())
        copy.SetBitmap(
            wx.Image(os.path.join(ICON_PATH_16_16, 'copy.png'),
                     wx.BITMAP_TYPE_PNG).ConvertToBitmap())
        paste.SetBitmap(
            wx.Image(os.path.join(ICON_PATH_16_16, 'paste.png'),
                     wx.BITMAP_TYPE_PNG).ConvertToBitmap())
        cut.SetBitmap(
            wx.Image(os.path.join(ICON_PATH_16_16, 'cut.png'),
                     wx.BITMAP_TYPE_PNG).ConvertToBitmap())
        rotateL.SetBitmap(
            wx.Image(os.path.join(ICON_PATH_16_16, 'rotateL.png'),
                     wx.BITMAP_TYPE_PNG).ConvertToBitmap())
        rotateR.SetBitmap(
            wx.Image(os.path.join(ICON_PATH_16_16, 'rotateR.png'),
                     wx.BITMAP_TYPE_PNG).ConvertToBitmap())
        rotateIL.SetBitmap(
            wx.Image(os.path.join(ICON_PATH_16_16, 'rotateL.png'),
                     wx.BITMAP_TYPE_PNG).ConvertToBitmap())
        rotateIR.SetBitmap(
            wx.Image(os.path.join(ICON_PATH_16_16, 'rotateR.png'),
                     wx.BITMAP_TYPE_PNG).ConvertToBitmap())
        rotateOL.SetBitmap(
            wx.Image(os.path.join(ICON_PATH_16_16, 'rotateL.png'),
                     wx.BITMAP_TYPE_PNG).ConvertToBitmap())
        rotateOR.SetBitmap(
            wx.Image(os.path.join(ICON_PATH_16_16, 'rotateR.png'),
                     wx.BITMAP_TYPE_PNG).ConvertToBitmap())
        rename.SetBitmap(
            wx.Image(os.path.join(ICON_PATH_16_16, 'rename.png'),
                     wx.BITMAP_TYPE_PNG).ConvertToBitmap())
        export.SetBitmap(
            wx.Image(os.path.join(ICON_PATH_16_16, 'export.png'),
                     wx.BITMAP_TYPE_PNG).ConvertToBitmap())
        delete.SetBitmap(
            wx.Image(os.path.join(ICON_PATH_16_16, 'delete.png'),
                     wx.BITMAP_TYPE_PNG).ConvertToBitmap())
        lock.SetBitmap(
            wx.Image(os.path.join(ICON_PATH_16_16, 'lock.png'),
                     wx.BITMAP_TYPE_PNG).ConvertToBitmap())
        unlock.SetBitmap(
            wx.Image(os.path.join(ICON_PATH_16_16, 'unlock.png'),
                     wx.BITMAP_TYPE_PNG).ConvertToBitmap())
        plugin.SetBitmap(
            wx.Image(os.path.join(ICON_PATH_16_16, 'plugin.png'),
                     wx.BITMAP_TYPE_PNG).ConvertToBitmap())
        properties.SetBitmap(
            wx.Image(os.path.join(ICON_PATH_16_16, 'properties.png'),
                     wx.BITMAP_TYPE_PNG).ConvertToBitmap())

        if isinstance(shape, Container.ConnectionShape):
            self.AppendItem(delete)
            self.AppendItem(lock)
            self.AppendItem(unlock)

            self.__canvas.Bind(wx.EVT_MENU,
                               self.__canvas.OnDelete,
                               id=ID_DELETE_SHAPE)
            self.__canvas.Bind(wx.EVT_MENU,
                               self.__canvas.OnLock,
                               id=ID_LOCK_SHAPE)
            self.__canvas.Bind(wx.EVT_MENU,
                               self.__canvas.OnUnLock,
                               id=ID_UNLOCK_SHAPE)

        elif isinstance(shape, Container.ResizeableNode):
            Delete_menu = self.AppendItem(delete)

        elif isinstance(shape, Container.Node):
            pass
            #port_number=wx.MenuItem(self, wx.NewId(), _("Enable port number"), _("Port number"),wx.ITEM_CHECK)
            #self.AppendItem(port_number)

            #rename_menu = self.AppendItem(rename)
            #self.__canvas.Bind(wx.EVT_MENU, shape.OnRename, id=ID_RENAME_SHAPE)
        else:
            if isinstance(shape, Container.CodeBlock) and shape.isAMD():
                Edit_menu = self.AppendMenu(-1, _("Edit"), edit_subMenu)
                Edit_SubMenu1 = edit_subMenu.AppendItem(editModel)
                Edit_SubMenu2 = edit_subMenu.AppendItem(editTest)
            else:
                Edit_menu = self.AppendItem(edit)

            Log_menu = self.AppendItem(log)
            self.AppendSeparator()

            Copy_menu = self.AppendItem(copy)
            Paste_menu = self.AppendItem(paste)
            Cut_menu = self.AppendItem(cut)
            Lock_item = self.AppendItem(lock)
            UnLock_item = self.AppendItem(unlock)

            ### for port, just right of left rotation
            if isinstance(shape, Container.Port):
                Rotate_SubMenu1 = rotate_subMenu.AppendItem(rotateR)
                Rotate_SubMenu2 = rotate_subMenu.AppendItem(rotateL)
            else:

                Rotate_SubMenu11 = rotate_all_subMenu.AppendItem(rotateR)
                Rotate_SubMenu12 = rotate_all_subMenu.AppendItem(rotateL)
                Rotate_SubMenu21 = rotate_input_subMenu.AppendItem(rotateIR)
                Rotate_SubMenu22 = rotate_input_subMenu.AppendItem(rotateIL)
                Rotate_SubMenu31 = rotate_output_subMenu.AppendItem(rotateOR)
                Rotate_SubMenu32 = rotate_output_subMenu.AppendItem(rotateOL)

                Rotate_all_menu = rotate_subMenu.AppendMenu(
                    ID_ROTATE_ALL_SHAPE, _("All"), rotate_all_subMenu)
                Rotate_in_menu = rotate_subMenu.AppendMenu(
                    ID_ROTATE_INPUT_SHAPE, _("Input"), rotate_input_subMenu)
                Rotate_out_menu = rotate_subMenu.AppendMenu(
                    ID_ROTATE_OUTPUT_SHAPE, _("Output"), rotate_output_subMenu)

            Rotate_menu = self.AppendMenu(ID_ROTATE_SHAPE, _("Rotate"),
                                          rotate_subMenu)
            Rename_menu = self.AppendItem(rename)

            self.AppendSeparator()
            # pour tout les model sur le canvas ormis les connection et le model que l'on veut connecter (la source)
            for i, item in enumerate(
                    filter(
                        lambda a: a != shape and not isinstance(
                            a, Container.ConnectionShape),
                        self.__canvas.GetDiagram().GetShapeList())):
                # on evite de proposer les connections suivante: iPort->iPort, oPort->oPort
                if (isinstance(shape, Container.iPort)
                        and not isinstance(item, Container.iPort)
                    ) or (isinstance(shape, Container.oPort) and
                          not isinstance(item, Container.oPort)) or isinstance(
                              shape, Container.Block):
                    new_item = wx.MenuItem(connectable_subMenu, wx.NewId(),
                                           item.label)
                    connectable_subMenu.AppendItem(new_item)
                    self.__canvas.Bind(wx.EVT_MENU,
                                       self.__canvas.OnConnectTo,
                                       id=new_item.GetId())
            self.AppendMenu(-1, _('Connect to'), connectable_subMenu)

            if isinstance(shape, Container.CodeBlock):
                self.AppendSeparator()
                Export_menu = self.AppendMenu(-1, _("Export"), export_subMenu)
                Export_SubMenu1 = export_subMenu.AppendItem(exportAMD)

                ### if Wcomp general plugin is enabled, sub menu appear in contextual menu of amd (right clic)
                pluginmanager.trigger_event("ADD_WCOMP_EXPORT_MENU",
                                            parent=self,
                                            model=shape,
                                            submenu=export_subMenu)

            elif isinstance(shape, Container.ContainerBlock):
                self.AppendSeparator()
                Export_menu = self.AppendMenu(-1, _("Export"), export_subMenu)
                Export_SubMenu1 = export_subMenu.AppendItem(exportCMD)
                Export_SubMenu2 = export_subMenu.AppendItem(exportXML)
                Export_SubMenu3 = export_subMenu.AppendItem(exportJS)

            else:
                self.Enable(ID_EDIT_SHAPE, False)

            self.AppendSeparator()
            Delete_menu = self.AppendItem(delete)

            ### Plug-in manager only for Block model
            if isinstance(shape, Container.CodeBlock) or isinstance(
                    shape, Container.ContainerBlock):
                ### only for amd or cmd
                if shape.model_path != "":
                    self.AppendSeparator()
                    #if ZipManager.Zip.HasPlugin(shape.model_path):
                    Plugin_menu = self.AppendItem(plugin)
                    self.__canvas.Bind(wx.EVT_MENU,
                                       shape.OnPluginsManager,
                                       id=ID_PLUGINS_SHAPE)

                    ### if Wcomp general plug-in is enabled, sub menu appear in contextual menu of amd (right clic)
                    pluginmanager.trigger_event("ADD_WCOMP_STRATEGY_MENU",
                                                parent=self,
                                                model=shape)

                ### if state trajectory general plug-in is enabled, sub menu appear in contextual menu (right clic)
                pluginmanager.trigger_event("ADD_STATE_TRAJECTORY_MENU",
                                            parent=self,
                                            model=shape)

            self.AppendSeparator()
            Properties_menu = self.AppendItem(properties)

            self.Enable(ID_PASTE_SHAPE, not Container.clipboard == [])
            self.Enable(ID_LOG_SHAPE, shape.getDEVSModel() is not None)

            # binding events
            if not isinstance(shape, Container.Port):
                self.__canvas.Bind(wx.EVT_MENU,
                                   shape.OnRotateInputR,
                                   id=ID_RIGHT_ROTATE_INPUT_SHAPE)
                self.__canvas.Bind(wx.EVT_MENU,
                                   shape.OnRotateInputL,
                                   id=ID_LEFT_ROTATE_INPUT_SHAPE)
                self.__canvas.Bind(wx.EVT_MENU,
                                   shape.OnRotateOutputR,
                                   id=ID_RIGHT_ROTATE_OUTPUT_SHAPE)
                self.__canvas.Bind(wx.EVT_MENU,
                                   shape.OnRotateOutputL,
                                   id=ID_LEFT_ROTATE_OUTPUT_SHAPE)

            self.__canvas.Bind(wx.EVT_MENU,
                               shape.OnRotateR,
                               id=ID_RIGHT_ROTATE_SHAPE)
            self.__canvas.Bind(wx.EVT_MENU,
                               shape.OnRenameFromMenu,
                               id=ID_RENAME_SHAPE)
            self.__canvas.Bind(wx.EVT_MENU,
                               shape.OnRotateL,
                               id=ID_LEFT_ROTATE_SHAPE)
            self.__canvas.Bind(wx.EVT_MENU,
                               self.__canvas.OnDelete,
                               id=ID_DELETE_SHAPE)
            self.__canvas.Bind(wx.EVT_MENU,
                               self.__canvas.OnCut,
                               id=ID_CUT_SHAPE)
            self.__canvas.Bind(wx.EVT_MENU,
                               self.__canvas.OnCopy,
                               id=ID_COPY_SHAPE)
            self.__canvas.Bind(wx.EVT_MENU,
                               self.__canvas.OnPaste,
                               id=ID_PASTE_SHAPE)
            self.__canvas.Bind(wx.EVT_MENU,
                               self.__canvas.OnLock,
                               id=ID_LOCK_SHAPE)
            self.__canvas.Bind(wx.EVT_MENU,
                               self.__canvas.OnUnLock,
                               id=ID_UNLOCK_SHAPE)
            self.__canvas.Bind(wx.EVT_MENU,
                               self.__canvas.OnProperties,
                               id=ID_PROPERTIES_SHAPE)

            # Codeblock specific binding
            if isinstance(shape, Container.CodeBlock):
                self.__canvas.Bind(wx.EVT_MENU,
                                   shape.OnEditor,
                                   id=ID_EDIT_MODEL_SHAPE)
                self.__canvas.Bind(wx.EVT_MENU, shape.OnLog, id=ID_LOG_SHAPE)
                self.__canvas.Bind(wx.EVT_MENU,
                                   shape.OnExport,
                                   id=ID_EXPORT_AMD_SHAPE)

                # AMD specific binding
                if shape.isAMD():
                    self.__canvas.Bind(wx.EVT_MENU,
                                       shape.OnTestEditor,
                                       id=ID_TESTING_SHAPE)
                else:
                    self.__canvas.Bind(wx.EVT_MENU,
                                       shape.OnEditor,
                                       id=ID_EDIT_SHAPE)

            # ContainerBlock specific binding
            elif isinstance(shape, Container.ContainerBlock):
                self.__canvas.Bind(wx.EVT_MENU,
                                   shape.OnEditor,
                                   id=ID_EDIT_SHAPE)
                self.__canvas.Bind(wx.EVT_MENU,
                                   shape.OnExport,
                                   id=ID_EXPORT_CMD_SHAPE)
                self.__canvas.Bind(wx.EVT_MENU,
                                   shape.OnExport,
                                   id=ID_EXPORT_XML_SHAPE)
                self.__canvas.Bind(wx.EVT_MENU,
                                   shape.OnExport,
                                   id=ID_EXPORT_JS_SHAPE)

        if isinstance(shape, Container.ResizeableNode):
            shape.OnDeleteNode(event)
Пример #25
0
	def __init__(self, shape, event):
		""" Constructor.
		"""

		wx.Menu.__init__(self)

		self.__canvas = event.GetEventObject()

		rotate_subMenu = wx.Menu()
		rotate_all_subMenu = wx.Menu()
		rotate_input_subMenu = wx.Menu()
		rotate_output_subMenu = wx.Menu()

		export_subMenu = wx.Menu()
		connectable_subMenu = wx.Menu()
		edit_subMenu = wx.Menu()

		edit=wx.MenuItem(self, ID_EDIT_SHAPE, _("Edit"), _("Edit the code"))
		editModel=wx.MenuItem(self, ID_EDIT_MODEL_SHAPE, _("Model"), _("Edit the model code"))
		editTest=wx.MenuItem(self, ID_TESTING_SHAPE, _("Tests"), _("Edit the tests code"))
		log = wx.MenuItem(self, ID_LOG_SHAPE, _("Log"), _("View log file"))
		copy=wx.MenuItem(self, ID_COPY_SHAPE, _("&Copy\tCtrl+C"), _("Copy the model"))
		paste=wx.MenuItem(self, ID_PASTE_SHAPE, _("&Paste\tCtrl+V"), _("Paste the model"))
		cut=wx.MenuItem(self, ID_CUT_SHAPE, _("&Cut\tCtrl+X"), _("Cut the model"))
		rotateAll=wx.MenuItem(self, ID_ROTATE_ALL_SHAPE, _("&All"), _("Rotate all ports"))
		rotateInput=wx.MenuItem(self, ID_ROTATE_INPUT_SHAPE, _("&Input ports"), _("Rotate input ports"))
		rotateOutput=wx.MenuItem(self, ID_ROTATE_OUTPUT_SHAPE, _("&Output ports"), _("Rotate output ports"))
		rotateR=wx.MenuItem(self, ID_RIGHT_ROTATE_SHAPE, _("&Right Rotate\tCtrl+R"), _("Rotate on the right"))
		rotateL=wx.MenuItem(self, ID_LEFT_ROTATE_SHAPE, _("&Left Rotate\tCtrl+L"), _("Rotate on the left"))
		rotateIR=wx.MenuItem(self, ID_RIGHT_ROTATE_INPUT_SHAPE, _("&Right Rotate\tCtrl+R"), _("Rotate on the right"))
		rotateIL=wx.MenuItem(self, ID_LEFT_ROTATE_INPUT_SHAPE, _("&Left Rotate\tCtrl+L"), _("Rotate on the left"))
		rotateOR=wx.MenuItem(self, ID_RIGHT_ROTATE_OUTPUT_SHAPE, _("&Right Rotate\tCtrl+R"), _("Rotate on the right"))
		rotateOL=wx.MenuItem(self, ID_LEFT_ROTATE_OUTPUT_SHAPE, _("&Left Rotate\tCtrl+L"), _("Rotate on the left"))
		rename=wx.MenuItem(self, ID_RENAME_SHAPE, _("&Rename"), _("Rename the label of the model"))
		delete=wx.MenuItem(self, ID_DELETE_SHAPE, _("Delete"), _("Delete the model"))
		lock=wx.MenuItem(self, ID_LOCK_SHAPE, _("Lock"), _("Lock the link"))
		unlock=wx.MenuItem(self, ID_UNLOCK_SHAPE, _("Unlock"), _("Unlock the link"))
		export=wx.MenuItem(self, ID_EXPORT_SHAPE, _("Export"), _("Export the model"))
		exportAMD=wx.MenuItem(self, ID_EXPORT_AMD_SHAPE, _("AMD"), _("Model exported to a amd file"))
		exportCMD=wx.MenuItem(self, ID_EXPORT_CMD_SHAPE, _("CMD"), _("Model exported to a cmd file"))
		exportXML=wx.MenuItem(self, ID_EXPORT_XML_SHAPE, _("XML"), _("Model exported to a xml file"))
		exportJS=wx.MenuItem(self, ID_EXPORT_JS_SHAPE, _("JS"), _("Model exported to a js (join) file"))
		plugin = wx.MenuItem(self, ID_PLUGINS_SHAPE, _("Plug-in"), _("Plug-in manager"))
		properties=wx.MenuItem(self, ID_PROPERTIES_SHAPE, _("Properties"), _("Edit the attributes"))

		edit.SetBitmap(wx.Image(os.path.join(ICON_PATH_16_16,'edit.png'), wx.BITMAP_TYPE_PNG).ConvertToBitmap())
		editModel.SetBitmap(wx.Image(os.path.join(ICON_PATH_16_16,'edit.png'), wx.BITMAP_TYPE_PNG).ConvertToBitmap())
		editTest.SetBitmap(wx.Image(os.path.join(ICON_PATH_16_16, 'test.png'), wx.BITMAP_TYPE_PNG).ConvertToBitmap())
		log.SetBitmap(wx.Image(os.path.join(ICON_PATH_16_16,'log.png'), wx.BITMAP_TYPE_PNG).ConvertToBitmap())
		copy.SetBitmap(wx.Image(os.path.join(ICON_PATH_16_16,'copy.png'), wx.BITMAP_TYPE_PNG).ConvertToBitmap())
		paste.SetBitmap(wx.Image(os.path.join(ICON_PATH_16_16,'paste.png'), wx.BITMAP_TYPE_PNG).ConvertToBitmap())
		cut.SetBitmap(wx.Image(os.path.join(ICON_PATH_16_16,'cut.png'), wx.BITMAP_TYPE_PNG).ConvertToBitmap())
		rotateL.SetBitmap(wx.Image(os.path.join(ICON_PATH_16_16,'rotateL.png'), wx.BITMAP_TYPE_PNG).ConvertToBitmap())
		rotateR.SetBitmap(wx.Image(os.path.join(ICON_PATH_16_16,'rotateR.png'), wx.BITMAP_TYPE_PNG).ConvertToBitmap())
		rotateIL.SetBitmap(wx.Image(os.path.join(ICON_PATH_16_16,'rotateL.png'), wx.BITMAP_TYPE_PNG).ConvertToBitmap())
		rotateIR.SetBitmap(wx.Image(os.path.join(ICON_PATH_16_16,'rotateR.png'), wx.BITMAP_TYPE_PNG).ConvertToBitmap())
		rotateOL.SetBitmap(wx.Image(os.path.join(ICON_PATH_16_16,'rotateL.png'), wx.BITMAP_TYPE_PNG).ConvertToBitmap())
		rotateOR.SetBitmap(wx.Image(os.path.join(ICON_PATH_16_16,'rotateR.png'), wx.BITMAP_TYPE_PNG).ConvertToBitmap())
		rename.SetBitmap(wx.Image(os.path.join(ICON_PATH_16_16,'rename.png'), wx.BITMAP_TYPE_PNG).ConvertToBitmap())
		export.SetBitmap(wx.Image(os.path.join(ICON_PATH_16_16,'export.png'), wx.BITMAP_TYPE_PNG).ConvertToBitmap())
		delete.SetBitmap(wx.Image(os.path.join(ICON_PATH_16_16,'delete.png'), wx.BITMAP_TYPE_PNG).ConvertToBitmap())
		lock.SetBitmap(wx.Image(os.path.join(ICON_PATH_16_16,'lock.png'), wx.BITMAP_TYPE_PNG).ConvertToBitmap())
		unlock.SetBitmap(wx.Image(os.path.join(ICON_PATH_16_16,'unlock.png'), wx.BITMAP_TYPE_PNG).ConvertToBitmap())
		plugin.SetBitmap(wx.Image(os.path.join(ICON_PATH_16_16,'plugin.png'), wx.BITMAP_TYPE_PNG).ConvertToBitmap())
		properties.SetBitmap(wx.Image(os.path.join(ICON_PATH_16_16,'properties.png'), wx.BITMAP_TYPE_PNG).ConvertToBitmap())

		if isinstance(shape, Container.ConnectionShape):
			self.AppendItem(delete)
			self.AppendItem(lock)
			self.AppendItem(unlock)

			self.__canvas.Bind(wx.EVT_MENU, self.__canvas.OnDelete, id=ID_DELETE_SHAPE)
			self.__canvas.Bind(wx.EVT_MENU, self.__canvas.OnLock, id=ID_LOCK_SHAPE)
			self.__canvas.Bind(wx.EVT_MENU, self.__canvas.OnUnLock, id=ID_UNLOCK_SHAPE)


		elif isinstance(shape, Container.ResizeableNode):
			Delete_menu = self.AppendItem(delete)

		elif isinstance(shape, Container.Node):
			pass
			#port_number=wx.MenuItem(self, wx.NewId(), _("Enable port number"), _("Port number"),wx.ITEM_CHECK)
			#self.AppendItem(port_number)

			#rename_menu = self.AppendItem(rename)
			#self.__canvas.Bind(wx.EVT_MENU, shape.OnRename, id=ID_RENAME_SHAPE)
		else:
			if isinstance(shape, Container.CodeBlock) and shape.isAMD():
				Edit_menu=self.AppendMenu(-1, _("Edit"), edit_subMenu)
				Edit_SubMenu1 = edit_subMenu.AppendItem(editModel)
				Edit_SubMenu2 = edit_subMenu.AppendItem(editTest)
			else:
				Edit_menu=self.AppendItem(edit)

			Log_menu=self.AppendItem(log)
			self.AppendSeparator()

			Copy_menu=self.AppendItem(copy)
			Paste_menu=self.AppendItem(paste)
			Cut_menu=self.AppendItem(cut)
			Lock_item = self.AppendItem(lock)
			UnLock_item = self.AppendItem(unlock)

			### for port, just right of left rotation
			if isinstance(shape, Container.Port):
				Rotate_SubMenu1 = rotate_subMenu.AppendItem(rotateR)
				Rotate_SubMenu2 = rotate_subMenu.AppendItem(rotateL)
			else:

				Rotate_SubMenu11 = rotate_all_subMenu.AppendItem(rotateR)
				Rotate_SubMenu12 = rotate_all_subMenu.AppendItem(rotateL)
				Rotate_SubMenu21 = rotate_input_subMenu.AppendItem(rotateIR)
				Rotate_SubMenu22 = rotate_input_subMenu.AppendItem(rotateIL)
				Rotate_SubMenu31 = rotate_output_subMenu.AppendItem(rotateOR)
				Rotate_SubMenu32 = rotate_output_subMenu.AppendItem(rotateOL)

				Rotate_all_menu = rotate_subMenu.AppendMenu(ID_ROTATE_ALL_SHAPE, _("All"), rotate_all_subMenu)
				Rotate_in_menu = rotate_subMenu.AppendMenu(ID_ROTATE_INPUT_SHAPE, _("Input"), rotate_input_subMenu)
				Rotate_out_menu = rotate_subMenu.AppendMenu(ID_ROTATE_OUTPUT_SHAPE, _("Output"), rotate_output_subMenu)

			Rotate_menu = self.AppendMenu(ID_ROTATE_SHAPE, _("Rotate"), rotate_subMenu)
			Rename_menu = self.AppendItem(rename)

			self.AppendSeparator()
			# pour tout les model sur le canvas ormis les connection et le model que l'on veut connecter (la source)
			for i, item in enumerate(filter(lambda a: a != shape and not isinstance(a, Container.ConnectionShape), self.__canvas.GetDiagram().GetShapeList())):
				# on evite de proposer les connections suivante: iPort->iPort, oPort->oPort
				if (isinstance(shape, Container.iPort) and not isinstance(item, Container.iPort)) or (isinstance(shape, Container.oPort) and not isinstance(item, Container.oPort)) or isinstance(shape, Container.Block):
					new_item = wx.MenuItem(connectable_subMenu, wx.NewId(), item.label)
					connectable_subMenu.AppendItem(new_item)
					self.__canvas.Bind(wx.EVT_MENU, self.__canvas.OnConnectTo,id = new_item.GetId())
			self.AppendMenu(-1, _('Connect to'), connectable_subMenu)

			if isinstance(shape, Container.CodeBlock):
				self.AppendSeparator()
				Export_menu = self.AppendMenu(-1, _("Export"), export_subMenu)
				Export_SubMenu1 = export_subMenu.AppendItem(exportAMD)

				### if Wcomp general plugin is enabled, sub menu appear in contextual menu of amd (right clic)
				pluginmanager.trigger_event("ADD_WCOMP_EXPORT_MENU", parent=self, model=shape, submenu= export_subMenu)

			elif isinstance(shape, Container.ContainerBlock):
				self.AppendSeparator()
				Export_menu = self.AppendMenu(-1, _("Export"), export_subMenu)
				Export_SubMenu1 = export_subMenu.AppendItem(exportCMD)
				Export_SubMenu2 = export_subMenu.AppendItem(exportXML)
				Export_SubMenu3 = export_subMenu.AppendItem(exportJS)

			else:
				self.Enable(ID_EDIT_SHAPE, False)

			self.AppendSeparator()
			Delete_menu = self.AppendItem(delete)

			### Plug-in manager only for Block model
			if isinstance(shape, Container.CodeBlock) or isinstance(shape, Container.ContainerBlock):
				### only for amd or cmd
				if shape.model_path != "":
					self.AppendSeparator()
					#if ZipManager.Zip.HasPlugin(shape.model_path):
					Plugin_menu = self.AppendItem(plugin)
					self.__canvas.Bind(wx.EVT_MENU, shape.OnPluginsManager, id=ID_PLUGINS_SHAPE)

					### if Wcomp general plug-in is enabled, sub menu appear in contextual menu of amd (right clic)
					pluginmanager.trigger_event("ADD_WCOMP_STRATEGY_MENU", parent=self, model=shape)

				### if state trajectory general plug-in is enabled, sub menu appear in contextual menu (right clic)
				pluginmanager.trigger_event("ADD_STATE_TRAJECTORY_MENU", parent=self, model=shape)

			self.AppendSeparator()
			Properties_menu = self.AppendItem(properties)

			self.Enable(ID_PASTE_SHAPE, not Container.clipboard == [])
			self.Enable(ID_LOG_SHAPE, shape.getDEVSModel() is not None)

			# binding events
			if not isinstance(shape, Container.Port):
				self.__canvas.Bind(wx.EVT_MENU, shape.OnRotateInputR, id=ID_RIGHT_ROTATE_INPUT_SHAPE)
				self.__canvas.Bind(wx.EVT_MENU, shape.OnRotateInputL, id=ID_LEFT_ROTATE_INPUT_SHAPE)
				self.__canvas.Bind(wx.EVT_MENU, shape.OnRotateOutputR, id=ID_RIGHT_ROTATE_OUTPUT_SHAPE)
				self.__canvas.Bind(wx.EVT_MENU, shape.OnRotateOutputL, id=ID_LEFT_ROTATE_OUTPUT_SHAPE)

			self.__canvas.Bind(wx.EVT_MENU, shape.OnRotateR, id=ID_RIGHT_ROTATE_SHAPE)
			self.__canvas.Bind(wx.EVT_MENU, shape.OnRenameFromMenu, id=ID_RENAME_SHAPE)
			self.__canvas.Bind(wx.EVT_MENU, shape.OnRotateL, id=ID_LEFT_ROTATE_SHAPE)
			self.__canvas.Bind(wx.EVT_MENU, self.__canvas.OnDelete, id=ID_DELETE_SHAPE)
			self.__canvas.Bind(wx.EVT_MENU, self.__canvas.OnCut, id=ID_CUT_SHAPE)
			self.__canvas.Bind(wx.EVT_MENU, self.__canvas.OnCopy, id=ID_COPY_SHAPE)
			self.__canvas.Bind(wx.EVT_MENU, self.__canvas.OnPaste, id=ID_PASTE_SHAPE)
			self.__canvas.Bind(wx.EVT_MENU, self.__canvas.OnLock, id=ID_LOCK_SHAPE)
			self.__canvas.Bind(wx.EVT_MENU, self.__canvas.OnUnLock, id=ID_UNLOCK_SHAPE)
			self.__canvas.Bind(wx.EVT_MENU, self.__canvas.OnProperties, id=ID_PROPERTIES_SHAPE)

			# Codeblock specific binding
			if isinstance(shape, Container.CodeBlock):
				self.__canvas.Bind(wx.EVT_MENU, shape.OnEditor, id=ID_EDIT_MODEL_SHAPE)
				self.__canvas.Bind(wx.EVT_MENU, shape.OnLog, id=ID_LOG_SHAPE)
				self.__canvas.Bind(wx.EVT_MENU, shape.OnExport, id=ID_EXPORT_AMD_SHAPE)

				# AMD specific binding
				if shape.isAMD():
				 	self.__canvas.Bind(wx.EVT_MENU, shape.OnTestEditor, id=ID_TESTING_SHAPE)
				else:
					self.__canvas.Bind(wx.EVT_MENU, shape.OnEditor, id=ID_EDIT_SHAPE)

			# ContainerBlock specific binding
			elif isinstance(shape, Container.ContainerBlock):
				self.__canvas.Bind(wx.EVT_MENU, shape.OnLog, id=ID_LOG_SHAPE)
				self.__canvas.Bind(wx.EVT_MENU, shape.OnEditor, id=ID_EDIT_SHAPE)
				self.__canvas.Bind(wx.EVT_MENU, shape.OnExport, id=ID_EXPORT_CMD_SHAPE)
				self.__canvas.Bind(wx.EVT_MENU, shape.OnExport, id=ID_EXPORT_XML_SHAPE)
				self.__canvas.Bind(wx.EVT_MENU, shape.OnExport, id=ID_EXPORT_JS_SHAPE)

		if isinstance(shape, Container.ResizeableNode):
			shape.OnDeleteNode(event)
Пример #26
0
    def OnOk(self, event):
        """ When Run button is clicked
		"""

        assert (self.master is not None)

        if self._value.GetValidator().Validate(self._value) or self.ntl:

            ### pour prendre en compte les simulations multiples sans relancer un SimulationDialog
            ### si le thread n'est pas lancé (pas pendant un suspend)
            if self.thread is not None and not self.thread.thread_suspend:
                diagram = self.master.getBlockModel()
                diagram.Clean()
                self.current_master = Container.Diagram.makeDEVSInstance(
                    diagram)
            else:
                self.current_master = self.master

            if isinstance(self.parent, wx.Panel):
                # redirection du stdout ici dans le cas du Panel (sinon dans OnSimulation)
                mainW = self.parent.GetTopLevelParent()
                sys.stdout = mainW.stdioWin

            ### test si le modele et bien charge
            if (self.current_master
                    == None) or (self.current_master.componentSet == []):
                return self.MsgBoxEmptyModel()

            ### dont erase the gauge if ntl
            if not self.ntl:
                # stockage du temps de simulation dans le master
                self.current_master.FINAL_TIME = float(self._value.GetValue())
                self._gauge.SetValue(0)
                ### if _gauge is wx.Slider
                #self._gauge.SetMax(self.current_master.FINAL_TIME)

            self.statusbar.SetBackgroundColour('')
            self.statusbar.SetStatusText("", 1)
            if self.statusbar.GetFieldsCount() > 2:
                self.statusbar.SetStatusText("", 2)

            if (self.thread is None) or (not self.timer.IsRunning()):

                trigger_event("START_BLINK",
                              parent=self,
                              master=self.current_master)
                trigger_event("START_TEST",
                              parent=self,
                              master=self.current_master)

                ### The START_ACTIVITY_TRACKING event occurs
                trigger_event("START_ACTIVITY_TRACKING",
                              parent=self,
                              master=self.current_master)

                ### The START_ACTIVITY_TRACKING event occurs
                trigger_event("START_STATE_TRAJECTORY",
                              parent=self,
                              master=self.current_master)

                ### The START_CONCURRENT_SIMULATION event occurs
                trigger_event("START_CONCURRENT_SIMULATION",
                              parent=self,
                              master=self.current_master)

                ### future call is required because the simulator is flattened during the execution of the strategy 3
                wx.FutureCall(1,
                              trigger_event,
                              'START_DIAGRAM',
                              parent=self,
                              master=self.current_master)

                ### clear all log file
                for fn in filter(lambda f: f.endswith('.devsimpy.log'),
                                 os.listdir(gettempdir())):
                    os.remove(os.path.join(gettempdir(), fn))

                self.thread = simulator_factory(self.current_master,
                                                self.selected_strategy,
                                                self.prof, self.ntl,
                                                self.verbose)
                self.thread.setName(self.title)

                ### si le modele n'a pas de couplage, ou si pas de generateur: alors pas besoin de simuler
                if self.thread.end_flag:
                    self.OnTimer(event)
                else:
                    self.timer.Start(100)

            else:
                #print self.thread.getAlgorithm().trace
                ### for back simulation
                #self.thread.s = shelve.open(self.thread.f.name+'.db',flag='r')
                #self.thread.model = self.thread.s['s'][str(float(self._gauge.GetValue()))]

                ### restart the hiding gauge
                if self.ntl:
                    self._gauge.Show()

                ### restart thread
                self.thread.resume_thread()

            self.Interact(False)

            if self.count >= 100:
                return
Пример #27
0
            module_name = getPythonModelFileName(self.fn)
        except Exception, info:
            sys.stderr.write(
                _("Error in ZipManager class for GetModule: no python file in the archive\n"
                  ))
            return info

        # if necessary, recompile (for update after editing code source of model)
        #if rcp: recompile(module_name)

        # import module
        try:
            ### clear to clean the import after exporting model (amd or cmd) and reload within the same instance of DEVSimPy
            zipimport._zip_directory_cache.clear()

            trigger_event("IMPORT_STRATEGIES", fn=self.fn)

            importer = zipimport.zipimporter(self.fn)

            ### allows to import the lib from its name (like import MyModel.amd). Dangerous because confuse!
            ### Import can be done using: import Name (ex. import MessageCollector - if MessageCollecor is .amd or .cmd)
            fullname = "".join([
                os.path.basename(os.path.dirname(self.fn)),
                module_name.split('.py')[0]
            ])
            module = importer.load_module(module_name.split('.py')[0])
            module.__name__ = path_to_module(module_name)

            ### allows to import with a reference from the parent directory (like parentName.model).
            ### Now import of .amd or .cmd module is composed by DomainModel (no point!).
            ### Example : import CollectorMessageCollector
Пример #28
0
    def run(self, fd, data, palette, type, bios, plugins):

        o_address = int(self.cmp_image_offset.get_value())

        self.rb_bios_comp.set_active(True)
        self.cb_bios_comp.set_sensitive(True)

        self.keys = [[],[],[]]
        self.values = [[],[],[]]

        _keys = []
        for key in [0x10, 0x11, 0x24, 0x28, 0x30]: # 0x40
            _keys.append(key)
#        _keys = sorted(_keys)
        self.keys[0] = _keys
        self.values[0] = [bios.FLAGS[key] for key in _keys]

        for _dict in plugins:
            if "Type" not in _dict:
                pass
            elif _dict["Type"] in ("Full", "Compression-Only"):
                self.keys[1].append(_dict['Prefix'])
                self.values[1].append(_dict['Name'])
            elif _dict["Type"] in ("Pointer-Only",):
                self.keys[2].append(_dict['Prefix'])
                self.values[2].append(_dict['Name'])
            elif _dict["Type"] in ("Full+Pointer",):
                self.keys[1].append(_dict['Prefix'])
                self.values[1].append(_dict['Name'])
                self.keys[2].append(_dict['Prefix'])
                self.values[2].append(_dict['Name'])

        populate_combo_box(self.cb_bios_comp, ["Compressões da BIOS"] + self.values[0])
        populate_combo_box(self.cb_plugins_comp, ["Compressões dos Plugins"] + self.values[1])
        populate_combo_box(self.cb_pointers, ["Atualização Padrão"] + self.values[2])

        self.cb_bios_comp.set_active(0)
        self.cb_plugins_comp.set_active(0)
        self.cb_pointers.set_active(0)

        self.f_pal_import.set_active(False)

        if palette:
            self.f_pal_import.set_sensitive(True)
        else:
            self.f_pal_import.set_sensitive(False)

        self.compression = None
        self.pointer_type = None

        while True:
            if self.dialog.run() == gtk.RESPONSE_OK:
                if not self.compression and self.f_img_compress.get_active():
                    default.Error(self.dialog, '''Nenhuma compressão foi selecionada.''')
                else:
                    break
            else:
                self.cb_bios_comp.get_model().clear()
                self.cb_bios_comp.clear()
                self.cb_plugins_comp.get_model().clear()
                self.cb_plugins_comp.clear()

                self.dialog.set_sensitive(True)
                self.dialog.hide()
                return False  # <------- Ver os retornos

        actions = {}

        self.dialog.set_sensitive(False)
        address = int(self.cmp_image_offset.get_value())

        #usize = data.size()
        usize = len(data)
        # Verifica se deve ou não comprimir
        if self.f_img_compress.get_active():
            buffer = bios.compress(data, self.compression)
            csize = len(buffer)
        else:
            buffer = array.array('c', data.read(len(data)))
            csize = len(buffer)

        actions.update({'data':[address, buffer]})

        ret = False
        # Verifica se deve atualizar os ponteiros
        if self.f_img_pointers.get_active():
            if self.pointer_type == None:
            # Atualização padrão
                if type[0] == 'gba':
                    ret = getGbaPointer(fd, address)
                    if not ret:
                        default.Warning(self.dialog, gtk.BUTTONS_OK, "O endereço original não foi encontrado na ROM.")
                elif type[0] == 'nds':
                    ret = getNdsFatEntry(fd, address, type[1])
                    if not ret:
                        default.Warning(self.dialog, gtk.BUTTONS_OK, "O endereço original não foi encontrado na FAT.")
                else:
                    default.Warning(self.dialog, gtk.BUTTONS_OK, "O arquivo aberto pelo lazynds não suporta atualização de ponteiros.")

                actions.update({'pointer':[struct.pack('<L', address), ret]})
            else:
                address, ret =  pluginmanager.trigger_event(('%s-POINTER' % self.pointer_type), infile = fd,
                                                                   old_address = o_address,
                                                                   new_address = address,
                                                                   csize = csize,
                                                                   usize = usize)[0]
            # Address: O que será escrito
            # Ret: lugares onde address será escrito
                actions.update({'pointer':[address, ret]})

        # Verifica se deve importar a paleta

        # Confirmar esta parte
        if self.f_pal_import.get_active():
            address = int(self.palette_offset.get_text(), 16)
            actions.update({'palette':[address, palette]})

        self.cb_bios_comp.get_model().clear()
        self.cb_bios_comp.clear()
        self.cb_plugins_comp.get_model().clear()
        self.cb_plugins_comp.clear()
        self.cb_pointers.get_model().clear()
        self.cb_pointers.clear()


        self.dialog.set_sensitive(True)
        self.dialog.hide()
        return actions