def OnPageChanged(self, evt):
        """ Page has been changed
		"""

        id = self.GetSelection()

        ### id is -1 when DEVSimPy is starting
        if id != -1 and self.GetPageCount() > 0:

            canvas = self.GetPage(id)
            self.print_canvas = canvas
            self.print_size = self.GetSize()

            ### action history
            if hasattr(self.parent, 'tb'):
                self.parent.tb.EnableTool(wx.ID_UNDO,
                                          not len(canvas.stockUndo) == 0)
                self.parent.tb.EnableTool(wx.ID_REDO,
                                          not len(canvas.stockRedo) == 0)

            ### refresh canvas
            canvas.deselect()
            canvas.Refresh()

            ### update status bar depending on the diagram modification
            if hasattr(self.parent, 'statusbar'):
                diagram = canvas.GetDiagram()
                txt = _('%s modified') % (
                    self.GetPageText(id)) if diagram.modify else ""
                printOnStatusBar(self.parent.statusbar, {0: txt})

        ### propagate event also error in OnClosePage because GetSelection is wrong
        evt.Skip()
Beispiel #2
0
    def OnLeftClick(self, evt):
        """ Left click has been invoked.
		"""

        self.UnselectAll()
        mainW = wx.GetApp().GetTopWindow()
        printOnStatusBar(mainW.statusbar, {0: '', 1: ''})
        #self.SetFocus()
        evt.Skip()
Beispiel #3
0
    def SetFields(self):
        """
		"""
        if wx.VERSION_STRING < '4.0':
            self.statusbar.SetFields([""] * self.statusbar.GetFieldsCount())
        else:
            printOnStatusBar(
                self.statusbar,
                {i: ''
                 for i in range(self.statusbar.GetFieldsCount())})
Beispiel #4
0
    def OnSuspend(self, event):
        """ When suspend button is clicked
		"""

        self.Interact()
        self.thread.suspend()

        if self.ntl:
            self._gauge.Hide()

        if self.count == 0 or self.count >= 100 or not self.timer.IsRunning():
            return

        printOnStatusBar(self.statusbar, {0: _('Suspended')})

        # way to interact with the model
        #self.parent.Enable(True)
        wx.Bell()
Beispiel #5
0
    def EnableGraphIcon(self, msg):
        """ Enable graph button when loading data is finished and clear the statusbar.
		"""

        ### update the column width
        try:
            activePage = self.notebook.GetSelection()
        except Exception as info:
            activePage = 0
            sys.stdout.write(_("Error in SpreadSheet: %s" % info))

        try:
            sheet = self.notebook.GetPage(activePage)
            sheet.UpdateColWidth()
        except Exception as info:
            sys.stdout.write(_("Error in SpreadSheet: %s" % info))
        else:
            toolbar = self.GetToolBar()
            toolbar.EnableTool(self.chart.GetId(), msg)
            printOnStatusBar(self.statusbar, {0: ""})
Beispiel #6
0
    def OnStop(self, event):
        """ When Stop button is clicked
		"""

        self.Interact()
        if self.thread:
            self.thread.terminate(False)
        self.timer.Stop()
        wx.Bell()

        self._gauge.SetValue(0)
        self.statusbar.SetBackgroundColour('')
        printOnStatusBar(self.statusbar, {0: _('Interrupted')})
        printOnStatusBar(self.statusbar, {1: ""})
        if self.statusbar.GetFieldsCount() > 2:
            printOnStatusBar(self.statusbar, {2: ""})
Beispiel #7
0
    def OnTimer(self, event):
        """ Give the pourcentage of simulation progress
		"""

        ### if no time limit, gauge pulse
        if self.ntl:
            self._gauge.Pulse()
        else:
            if not isinstance(self.thread.model.timeLast, tuple):
                timeLast = self.thread.model.timeLast
            else:
                timeLast = self.thread.model.timeLast[0]

            self.count = (timeLast / self.thread.model.FINAL_TIME) * 100

            self._gauge.SetValue(self.count)

        ### if simulation is over
        if self.thread.end_flag:

            ### update the status of buttons
            self._btn1.Enable(True)
            self._btn2.Disable()
            self._btn3.Disable()
            self._value.Enable(not self.ntl)
            self._cp.Enable()

            ### check if gauge is full (can appear if timer is too slow)
            if self.count != 100 or self.ntl:
                self.count = 100
                self._gauge.SetValue(self.count)

            ### update the status bar
            self.statusbar.SetBackgroundColour('')
            printOnStatusBar(self.statusbar, {
                0: _("Completed!"),
                1: self.GetClock()
            })

            ### is no time limit add some informations in status bar
            if not self.ntl:
                if self.statusbar.GetFieldsCount() > 2:
                    printOnStatusBar(self.statusbar, {2: str(100) + "%"})

            ### stop the timer
            self.timer.Stop()

        ### if the simulation is suspended
        elif not self.thread.thread_suspend:

            ### udpate the status bar
            self.statusbar.SetBackgroundColour('GREY')
            printOnStatusBar(self.statusbar, {
                0: _("Processing..."),
                1: self.GetClock()
            })

            ### is no time limit, add some information in status bar
            if not self.ntl:
                if self.statusbar.GetFieldsCount() > 2:
                    printOnStatusBar(self.statusbar,
                                     {2: str(self.count)[:4] + "%"})

            #wx.Yield()
            wx.YieldIfNeeded()
Beispiel #8
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.getComponentSet() == []):
                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('')
            printOnStatusBar(self.statusbar, {1: ""})
            if self.statusbar.GetFieldsCount() > 2:
                printOnStatusBar(self.statusbar, {2: ""})

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

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

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

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

                ### The START_CONCURRENT_SIMULATION event occurs
                PluginManager.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,
                              PluginManager.trigger_event,
                              'START_DIAGRAM',
                              parent=self,
                              master=self.current_master)

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

                self.thread = simulator_factory(self.current_master,
                                                self.selected_strategy,
                                                self.prof, self.ntl,
                                                self.verbose,
                                                self.dynamic_structure_flag,
                                                self.real_time_flag)
                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)

                ### timer for real time
                if self.real_time_flag:
                    self.t = timer()

            else:
                ### 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
Beispiel #9
0
    def OnProgress(self, msg):
        """ Update status bar with loading data progression
		"""
        pourcent = 100 * float(msg)
        printOnStatusBar(self.statusbar,
                         {0: _("Loading data... (%d %%)") % int(pourcent)})
Beispiel #10
0
	def OnEditor(self, event):
		""" Method that edit the python code of associated devs model of the Block
		"""
		from Container import ShapeCanvas

		python_path = self.python_path
		model_path = os.path.dirname(python_path)
		name = os.path.basename(python_path)

		### trying to get parent window
		mainW = GetActiveWindow(event)

		if isinstance(mainW, ShapeCanvas):
			mainW = mainW.GetParent()

		if not builtins.__dict__['LOCAL_EDITOR'] and not zipfile.is_zipfile(model_path) and not python_path.startswith('http'):
			dial = wx.MessageDialog(mainW, _('Do you want to use your local programmer software?\n\n If you always want use the DEVSimPy code editor\n change the option in Editor panel preferences.'), name, wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
			val = dial.ShowModal()
		else:
			val = wx.ID_NO

		### if local editor
		if val == wx.ID_YES:
			### open with local editor
			if wx.Platform == '__WXMAC__':
				subprocess.call(" ".join(['open',python_path]), shell=True)
			elif "wxMSW" in wx.PlatformInfo:
				os.startfile(python_path)
			elif "wxGTK" in wx.PlatformInfo:
				### with gnome
				if os.system('pidof gedit') == 256:
					try:
						soft = which('gedit')
					except:
						sys.stdout.write(_("Local programmer software not found!\n"))
					else:
						subprocess.call(" ".join([soft,python_path]), shell=True)

				### with kde
				elif os.system('pidof ksmserver') == 256:
					try:
						soft = which('kfmclient')
					except:
						sys.stdout.write(_("Local programmer software not found!\n"))
					else:
						os.system(soft+" openURL " + python_path)
				else:
					sys.stdout.write(_("Unknown Windows Manager!\n"))

		elif val != wx.ID_CANCEL:
			# loading file in DEVSimPy editor windows (self.text)
			try:

				editorFrame = Editor.GetEditor(None, wx.NewIdRef(), ''.join([name,' - ',model_path]), obj=self, file_type='block')

				# if zipfile.is_zipfile(model_path):
				# 	importer = zipimport.zipimporter(model_path)
				# 	text = importer.get_source(os.path.splitext(name)[0])

				if not zipfile.is_zipfile(model_path):
					### if file is localized on the net
					if python_path.startswith('http'):
						### with internet python file, the editorFrame is read only
						editorFrame.SetReadOnly(True)

						printOnStatusBar(editorFrame.statusbar, {0:_('read only')})

						### parse url to extract the path(/devsimpy/domain...) and the network location (lcapocchi.free.fr)
						o = urlparse(python_path)
						### open connection
						c = httplib.HTTPConnection(o.netloc)
						### request with GET mode
						c.request('GET', o.path)
						### get response of request
						r = c.getresponse()
						### convert file into string
						text = r.read()

					else:

						### if python_path is not found (because have an external origin)
						if not os.path.exists(python_path):
							if os.path.basename(DOMAIN_PATH) in python_path.split(os.sep):
								python_path = os.path.join(HOME_PATH, python_path[python_path.index(os.path.basename(DOMAIN_PATH)):].strip('[]'))
								self.python_path = python_path

						# ### only with python 2.6
						# with codecs.open(python_path, 'r', 'utf-8') as f:
						# 	text = f.read()

				name = os.path.basename(python_path)

				editorFrame.AddEditPage(name, python_path)
				editorFrame.Show()

				printOnStatusBar(editorFrame.statusbar,{1:''})

				return editorFrame

			except Exception as info:
				dlg = wx.MessageDialog(mainW, _('Editor frame not instanciated: %s\n'%info), name, wx.OK|wx.ICON_ERROR)
				dlg.ShowModal()
				return False