Ejemplo n.º 1
0
class Environment(QWidget):
	def __init__(self, port, parent=None):
		QWidget.__init__(self, parent=parent)
		self.port = port

		self.sharedMemory = {}
		memFilePath = '{}.mem'.format(port)
		if os.path.isfile(memFilePath):
			try:
				with open(memFilePath) as f:
					self.sharedMemory = pickle.load(f)
					sys.stdout.write(u"[INFO] Wczytano zapisaną pamięć.\n", name=port)
			except:
				sys.stdout.write(u"[BŁĄD] Błąd odczytywania pamięci. Resetuję!\n", name=port)

		#self.sharedMemory = SharedDict(self.sharedMemory)

		try:
			self.client = Client(port)
		except:
			#print "Brak połączenia z serwerem!"
			#self.client = None
			raise NoServerConnection()

		self.workerThread = None
		self.uiUpdateEvent = threading.Event()

		self.snippetQueue = []

		self.context = {}
		self.context['mem'] = self.sharedMemory
		self.context['active'] = None
		self.context['client'] = self.client # TODO: polaczenie z klientem

		self.timer = QTimer()
		self.timer.setInterval(0)
		self.timer.timeout.connect(self.tick)
		self.timer.start()

		self.actions = []
		self.setupUI()

		# Autoload modules
		#for modulePath in filter(lambda x: x[-3:]=='.py', os.listdir('..')):
		for modulePath in [ x for x in os.listdir('..') if x[-3:] == '.py' ]:
			self.strategies.load(os.path.join("..", modulePath))

	def setupUI(self):
		self.setWindowTitle("%d" % self.port)
		self.mdi = QMdiArea()
		self.mdi.setHorizontalScrollBarPolicy( Qt.ScrollBarAsNeeded )
		self.mdi.setVerticalScrollBarPolicy( Qt.ScrollBarAsNeeded )

		self.inter = Interpreter(self.context)
		self.mdi.addSubWindow(self.inter,
							Qt.WindowTitleHint |
							Qt.WindowMinimizeButtonHint |
							Qt.WindowMaximizeButtonHint |
							Qt.WindowMaximized)

		#self.mdi.addSubWindow(FileBrowser())

		# Dock windows

		self.strategies = Strategies()

		#stratDock = QDockWidget("Strategies", self)
		#stratDock.setWidget(self.strategies)
		#self.addDockWidget(Qt.RightDockWidgetArea, stratDock)

		# Actions
		newDocIcon = QIcon(QPixmap("img/newdoc.png"))
		playIcon = QIcon(QPixmap("img/Play.png"))

		newSnippetAction = QAction(newDocIcon, "Nowy skrawek", self)
		newSnippetAction.setShortcut('F1')
		self.actions.append(newSnippetAction)
		runSnippetAction = QAction(playIcon, "Uruchom skrawek", self)
		runSnippetAction.setShortcut('F9')
		self.actions.append(runSnippetAction)

		layout = QHBoxLayout()
		layout.addWidget(self.mdi)
		layout.addWidget(self.strategies)

		self.setLayout(layout)

		# Connecting
		QWidget.connect(self.strategies, SIGNAL('strategyChanged'), self.strategyChanged)
		QWidget.connect(newSnippetAction, SIGNAL('triggered()'), self.newSnippet)
		QWidget.connect(runSnippetAction, SIGNAL('triggered()'), self.runSnippet)

	def strategyChanged(self, old, new):
		if old != None:
			with output(self.port, True): old.remove()
			self.workerThread.work = False
			self.workerThread.join()  # wait for QThread
			self.workerThread = None
			if hasattr(old, '__widget__'):
				self.mdi.removeSubWindow(old.__widget__.parent())
			self.tick()

		self.context['active'] = new

		if new:
			with output(self.port): print "Starting new worker..."
			widget = QWidget()
			widget.setWindowTitle(new.name())
			self.mdi.addSubWindow(widget,
							Qt.WindowTitleHint |
							Qt.WindowMinimizeButtonHint |
							Qt.WindowMaximizeButtonHint |
							Qt.WindowMaximized)
			new.__widget__ = widget
			new.mem = self.sharedMemory
			new.widget = widget
			new.client = self.client

			try:
				with output(self.port): new.install()
			except:
				traceback.print_exc()

			widget.parent().adjustSize()

			self.workerThread = WorkerThread(self.client, new, self.uiUpdateEvent)
			self.workerThread.daemon = True
			self.workerThread.start()

	# czyta stdout dla danego interpretera i robi update GUI
	def tick(self):
		if self.context['active'] and self.uiUpdateEvent.isSet():
			self.uiUpdateEvent.clear()
			with output(self.port, True): self.context['active'].updateUI()


		data = sys.stdout.getOutput(self.port)
		if data:
			count = len( self.inter.out.toPlainText().split('\n') ) - 100
			if count > 0:
				cursor = self.inter.out.textCursor()
				cursor.movePosition( QTextCursor.Start )
				cursor.movePosition( QTextCursor.Down, QTextCursor.KeepAnchor, count)
				cursor.removeSelectedText()

			self.inter.write(data)

	def newSnippet(self):
		w = SnippetEditor()
		QWidget.connect(w, SIGNAL('codeOutput'), self.inter.write)
		self.mdi.addSubWindow(w)
		w.show()

	def runSnippet(self):
		w = self.mdi.activeSubWindow().widget()
		if hasattr(w, 'runCode') and callable(w.runCode):
			w.runCode(self.context)

	def queueSnippet(self):
		w = self.mdi.activeSubWindow().widget()
		if hasattr(w, 'runCode') and callable(w.runCode):
			self.workerThread.snippetQueue.append( (w, self.context) )

	def renameSnippet(self, title):
		#print self.mdi.activeSubWindow().widget()
		if self.mdi.activeSubWindow():
			self.mdi.activeSubWindow().setWindowTitle(title)
		#if hasattr(w, 'runCode') and callable(w.runCode):

	def cleanup(self):
		self.client.close()
		if self.workerThread is not None:
			self.workerThread.work = False
Ejemplo n.º 2
0
class QtMdiArea(QtConstraintsWidget, ProxyMdiArea):
    """ A Qt implementation of an Enaml ProxyMdiArea.

    """
    #: A reference to the widget created by the proxy.
    widget = Typed(QMdiArea)

    #--------------------------------------------------------------------------
    # Initialization API
    #--------------------------------------------------------------------------
    def create_widget(self):
        """ Create the underlying QMdiArea widget.

        """
        self.widget = QMdiArea(self.parent_widget())

    def init_layout(self):
        """ Initialize the layout for the underlying control.

        """
        super(QtMdiArea, self).init_layout()
        widget = self.widget
        for window in self.mdi_windows():
            widget.addSubWindow(window)
        widget.subWindowActivated.connect(self.on_subwindow_activated)

    #--------------------------------------------------------------------------
    # Utility Methods
    #--------------------------------------------------------------------------
    def mdi_windows(self):
        """ Get the mdi windows defined for the area.

        """
        for window in self.declaration.mdi_windows():
            widget = window.proxy.widget
            if widget:
                yield widget

    #--------------------------------------------------------------------------
    # Signal Handlers
    #--------------------------------------------------------------------------
    def on_subwindow_activated(self, window):
        """ The handler for the 'subWindowActivated' signal.

        """
        # On OSX there is painting bug where a subwindow is not repainted
        # properly when it is activated. This handler ensures an update.
        if window:
            window.update()

    #--------------------------------------------------------------------------
    # Child Events
    #--------------------------------------------------------------------------
    def child_added(self, child):
        """ Handle the child added event for a QtMdiArea.

        """
        # The size hint of a QMdiArea is typically quite large and the
        # size hint constraints are usually ignored. There is no need
        # to notify of a change in size hint here.
        super(QtMdiArea, self).child_added(child)
        if isinstance(child, QtMdiWindow):
            self.widget.addSubWindow(child.widget)

    def child_removed(self, child):
        """ Handle the child removed event for a QtMdiArea.

        """
        if isinstance(child, QtMdiWindow):
            self.widget.removeSubWindow(child.widget)
        else:
            super(QtMdiArea, self).child_removed(child)