Exemplo n.º 1
0
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        tk.Tk.wm_title(self, "Materials Lab Simulation Tool")
        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        # Initialize Mechanical workshop page
        self.Page1 = MechanicalWorkshopController(container, self)
        self.Page1.page1.grid(row=0, column=0, sticky="nsew")
        self.Page1.page2.grid(row=0, column=0, sticky="nsew")

        # Initialize thermocouple page
        self.Page2 = ThermocoupleController(container, self)
        self.Page2.page1.grid(row=0, column=0, sticky="nsew")

        # Initialize main view
        self.HomePage = MainView(container, self)
        self.HomePage.grid(row=0, column=0, sticky="nsew")

        # Bind buttons to show_frame
        self.HomePage.pages[0].configure(command=lambda: self.show_frame(0))
        self.HomePage.pages[1].configure(command=lambda: self.show_frame(1))
        self.HomePage.tkraise()
Exemplo n.º 2
0
class App(QtWidgets.QApplication):
    def __init__(self, sys_argv):
        super(App, self).__init__(sys_argv)
        self.model = Model()
        self.main_ctrl = MainController(self.model)
        self.main_view = MainView(self.model, self.main_ctrl)
        self.main_view.show()
Exemplo n.º 3
0
    def __init__(self):
        """ Set up some information like, set up the interfaces """
        import locale

        language = None
        try:  # Work around a possible Python3.7 bug on MacOS
            loc = locale.getdefaultlocale()
            if loc:
                for el in loc:
                    if str(el).upper().startswith("FR"):
                        language = "fr"
                        break
        except ValueError:
            pass  # language is still None

        if language is not None:
            set_translator_locale(language)

        self.root = Tk()

        self.root.geometry('768x612')
        self.root.title("MrPython")

        self.mode = "full"
        self.main_view = MainView(self)
        self.editor_list = self.main_view.editor_widget.py_notebook
        self.icon_widget = self.main_view.icon_widget
        self.status_bar = self.main_view.status_bar
        self.console = self.main_view.console
        self.change_mode()
        self.apply_bindings()
        self.root.protocol('WM_DELETE_WINDOW', self.close_all_event)

        self.running_interpreter_proxy = None
        self.running_interpreter_callback = None
Exemplo n.º 4
0
    def __init__(self):
        """ Set up some information like, set up the interfaces """
        import locale

        language = None
        loc = locale.getdefaultlocale()
        if loc:
            for el in loc:
                if str(el).upper().startswith("FR"):
                    language = "fr"
                    break

        if language is not None:
            set_translator_locale(language)

        self.root = Tk()
        StudentRunner.TK_ROOT = self.root
        self.root.title("MrPython")

        self.mode = "full"
        self.main_view = MainView(self)
        self.editor_list = self.main_view.editor_widget.py_notebook
        self.icon_widget = self.main_view.icon_widget
        self.status_bar = self.main_view.status_bar
        self.console = self.main_view.console
        self.change_mode()
        self.apply_bindings()
        self.root.protocol('WM_DELETE_WINDOW', self.close_all_event)
Exemplo n.º 5
0
    def __init__(self):
        """ Set up some information like, set up the interfaces """
        import locale

        language = None
        try:  # Work around a possible Python3.7 bug on MacOS
            loc = locale.getdefaultlocale()
            if loc:
                for el in loc:
                    if str(el).upper().startswith("FR"):
                        language = "fr"
                        break
        except ValueError:
            pass  # language is still None

        if language is not None:
            set_translator_locale(language)

        self.root = Tk()

        self.root.geometry('768x612')
        self.root.title("MrPython")

        self.mode = "full"
        self.main_view = MainView(self)
        self.editor_list = self.main_view.editor_widget.py_notebook
        self.icon_widget = self.main_view.icon_widget
        self.status_bar = self.main_view.status_bar
        self.console = self.main_view.console
        self.change_mode()
        self.apply_bindings()
        self.root.protocol('WM_DELETE_WINDOW', self.close_all_event)

        self.running_interpreter_proxy = None
        self.running_interpreter_callback = None

        # message box to accept tracing or not on first launch by this user
        if tracing.user_first_session():
            user_enabled_tracing = tkMessageBox.askyesno(
                title="Suivi pédagogique",
                message=
                "Acceptez-vous que des traces de vos actions dans MrPython " +
                "soient collectées par le LIP6 ?\n" +
                "Ces traces seront anonymisées et uniquement utilisées dans un but d'amélioration pédagogique "
                + "de MrPython.",
                default=tkMessageBox.YES,
                parent=self.root)
        else:
            user_enabled_tracing = tracing.check_tracing_is_enabled()
        tracing.initialize_tracing(user_enabled_tracing)
        self.icon_widget.switch_icon_tracing(user_enabled_tracing)

        self.root.after(1000, self.check_user_state)
        self.root.after(5000, self.update_active_timestamp)
        self.state = "idle"  # 3 states: idle, interacting or typing
Exemplo n.º 6
0
    def __init__(self):
        gtk.Window.__init__(self)

        self.set_default_size(1024, 768)
        self.connect('destroy', self.on_destroy)
        self.set_title('TASE')
        self.set_border_width(8)

        self.db = MySQLdb.connect(host=dbconn.DB_HOST, user=dbconn.DB_USERNAME, passwd=dbconn.DB_PASSWORD, db=dbconn.DB_SCHEMA)
        
        self.main_view = MainView(self.select_symbol)
        self.add(self.main_view)
        self.main_view.show()
Exemplo n.º 7
0
class TaseBrowser(gtk.Window):

    def __init__(self):
        gtk.Window.__init__(self)

        self.set_default_size(1024, 768)
        self.connect('destroy', self.on_destroy)
        self.set_title('TASE')
        self.set_border_width(8)

        self.db = MySQLdb.connect(host=dbconn.DB_HOST, user=dbconn.DB_USERNAME, passwd=dbconn.DB_PASSWORD, db=dbconn.DB_SCHEMA)
        
        self.main_view = MainView(self.select_symbol)
        self.add(self.main_view)
        self.main_view.show()

    def select_symbol(self, treeview):
        self.main_view.clear()
        path = treeview.get_cursor()
        if path == None:
            return
        selection = treeview.get_selection()
        (model, pathlist) = selection.get_selected_rows()
        iters = [model.get_iter(path) for path in pathlist]
        for treeiter in iters:
            type = model.get_value(treeiter, CompanyView.col_type)
            symbol = model.get_value(treeiter, CompanyView.col_sector)
            date = model.get_value(treeiter, CompanyView.col_buy_date)
            if type == "Portfolio":
                self.main_view.load(symbol, date)
            else:
                self.main_view.load(symbol)

    def on_destroy(self, widget):
        gtk.main_quit()
Exemplo n.º 8
0
    def __init__(self):

        supported_image_formats = ('.png', '.jpg', '.jpeg', '.bmp', '.gif')

        start_scan_callback = lambda scan_directories: self._start_scan_click_callback(
            scan_directories)
        delete_image_callback = lambda path_to_delete: self._delete_file(
            path_to_delete)
        delete_all_duplicates = lambda duplicates: self._delete_all_duplicated_keep_newest(
            duplicates)

        self._main_view = MainView(start_scan_callback, delete_image_callback,
                                   delete_all_duplicates)

        self._imageManager = DuplicateImagesManager(supported_image_formats)
Exemplo n.º 9
0
    def __init__(self):
        """ Set up some information like, set up the interfaces """
        import locale

        language = None
        try: # Work around a possible Python3.7 bug on MacOS
            loc = locale.getdefaultlocale()
            if loc:
                for el in loc:
                    if str(el).upper().startswith("FR"):
                        language = "fr"
                        break
        except ValueError:
            pass # language is still None
                    
        if language is not None:
            set_translator_locale(language)

        self.root = Tk()
        
        self.root.title("MrPython")

        self.mode = "full"
        self.main_view = MainView(self)
        self.editor_list = self.main_view.editor_widget.py_notebook
        self.icon_widget = self.main_view.icon_widget
        self.status_bar = self.main_view.status_bar
        self.console = self.main_view.console
        self.change_mode()
        self.apply_bindings()
        self.root.protocol('WM_DELETE_WINDOW', self.close_all_event)

        self.running_interpreter_proxy = None
        self.running_interpreter_callback = None
Exemplo n.º 10
0
 def setUp(self):
     view = MainView('')
     controller = ControllerMain(view)
     self.args = {
         'parameter': 'dlink_backup',
         'ip_range': '172.1.2.80,172.1.2.82',
         'ip_dst_for_backup': '10.6.224.3',
         'path_work_directory': '/Users/toxa/PycharmProjects/dlink_utility/'
     }
     self.operations_with_ports = OperationsWithPorts(controller)
Exemplo n.º 11
0
    def __init__(self):

        self.root=Tk()
        self.root.title("MrPython")

        self.main_view=MainView(self.root)
        self.pyEditorList=self.main_view.pyEditorList
        self.pyShell=self.main_view.pyShell

        self.apply_bindings()
        self.root.protocol('WM_DELETE_WINDOW',self.close_all_event)
Exemplo n.º 12
0
 def test_backup(self, mock_write_to_log_file,
                 mock_controller_authorisation, mock_model_get_dlink_model,
                 mock_network_receive_data_until, mock_network_send_data):
     argv = ('/Users/toxa/PycharmProjects/dlink_utility/', 'dlink_backup',
             '172.1.2.80,172.1.2.81', '10.6.224.1')
     mock_write_to_log_file.return_value = True
     mock_controller_authorisation.return_value = True
     mock_model_get_dlink_model.return_value = 'DGS-3200'
     mock_network_receive_data_until.return_value = b'success'
     mock_network_send_data.return_value = 'success'
     view = MainView(argv)
     self.assertTrue(view)
Exemplo n.º 13
0
    def __init__(self, settingsManager: ConfigurationManager,
                 zeroPointManager: ZeroPointManager):
        self._settingsManager = settingsManager
        self._zeroPointManager = zeroPointManager
        self._stopTurnTableEvent = Event()
        self._jobThreads = ControllerThreads()
        self._position = Position()

        def connectionFactory(port: int, name: str) -> LANConnection:
            return LANConnection(self._settingsManager.turnTableIPAddress,
                                 port,
                                 name=name,
                                 timeout=self._settingsManager.timeout)

        callbacks = TCPCallbacks(
            getAzimuth=self.getCurrentPosition,
            getElevation=self.getCurrentPosition,
            setAzimuth=self.createGotoPositionJob,
            setElevation=self.createGotoPositionJob,
            stop=self.stop,
        )
        self._tcpServer = TCPServer(callbacks=callbacks,
                                    settingsManager=self._settingsManager)

        self._shaftEncoder = ShaftEncoderModel(connectionFactory(
            self._settingsManager.shaftEncoderPort,
            "Shaft Encoder Connection"),
                                               settingsManager=settingsManager)
        self._motorController = MotorControllerModel(
            watchdogConnection=connectionFactory(
                self._settingsManager.watchdogPort, "Watchdog Connection"),
            motorControllerConnection=connectionFactory(
                self._settingsManager.motorControllerPort,
                "Motor Controller Connection"),
            settingsManager=settingsManager,
        )

        self._mainView = MainView()
        self._settingsManagerView = SettingsView(self._settingsManager)
        self.showMainView()
Exemplo n.º 14
0
 def test_mac_on_ports(self, mock_write_to_log_file,
                       mock_controller_authorisation,
                       mock_model_get_dlink_model,
                       mock_network_receive_data_until,
                       mock_network_send_data, mock_file_settings_exists):
     argv = ('/Users/toxa/PycharmProjects/dlink_utility/', 'mac_on_port',
             '172.1.2.80,172.1.2.81', '1-2')
     mock_write_to_log_file.return_value = True
     mock_controller_authorisation.return_value = True
     mock_model_get_dlink_model.return_value = 'DGS-1210-10P/ME'
     mock_network_receive_data_until.return_value = b'kjhkjhskdf00-C0-34-DA-00-00'
     mock_network_send_data.return_value = 'success'
     mock_file_settings_exists.return_value = True
     # mock_get_mac_on_ports.return_value = {'192.168.1.2': {2:['00-11-22-df-ab-ac', '00-11-22-df-ab-ac'],
     #                                                       3: ['00-11-22-df-ab-ac']},
     #                                       '192.168.1.3': {4: ['00-11-22-df-ab-ac']}}
     view = MainView(argv)
     self.assertTrue(view)
Exemplo n.º 15
0
class Application:
    def __init__(self):

        self.root=Tk()
        self.root.title("MrPython")

        self.main_view=MainView(self.root)
        self.pyEditorList=self.main_view.pyEditorList
        self.pyShell=self.main_view.pyShell

        self.apply_bindings()
        self.root.protocol('WM_DELETE_WINDOW',self.close_all_event)

    def run(self):
        self.main_view.show()

    def apply_bindings(self, keydefs=None):
        #bindings event
        #file
        self.root.bind("<<open-new-window>>", self.newfile)
        self.root.bind('<<open-window-from-file>>',self.open)
        self.root.bind('<<save-window>>',self.pyEditorList.save)
        self.root.bind('<<save-window-as-file>>',self.pyEditorList.save_as)
        self.root.bind('<<save-copy-of-window-as-file>>',self.pyEditorList.save_as_copy)

        self.root.bind('<<close-window>>',self.pyEditorList.close_current_editor)
        self.root.bind('<<close-all-windows>>',self.close_all_event)

        #edit
        self.root.bind('<<undo>>',self.pyEditorList.undo_event)
        self.root.bind('<<redo>>',self.pyEditorList.redo_event)
        self.root.bind('<<cut>>',self.pyEditorList.cut_event)
        self.root.bind('<<copy>>',self.pyEditorList.copy_event)
        self.root.bind('<<paste>>',self.pyEditorList.paste_event)
        self.root.bind('<<select-all>>',self.pyEditorList.select_all_event)
        self.root.bind('<<find>>',self.pyEditorList.find_event)
        self.root.bind('<<find-again>>',self.pyEditorList.find_again_event)
        self.root.bind('<<find-selection>>',self.pyEditorList.find_selection_event)
        self.root.bind('<<find-in-files>>',self.pyEditorList.find_in_files_event)
        self.root.bind('<<replace>>',self.pyEditorList.replace_event)
        self.root.bind('<<goto-line>>',self.pyEditorList.goto_line_event)

        # #format
        self.root.bind('<<indent-region>>',self.pyEditorList.indent_region_event)
        self.root.bind('<<dedent-region>>',self.pyEditorList.dedent_region_event)
        self.root.bind('<<comment-region>>',self.pyEditorList.comment_region_event)
        self.root.bind('<<uncomment-region>>',self.pyEditorList.uncomment_region_event)
        self.root.bind('<<tabify-region>>',self.pyEditorList.tabify_region_event)
        self.root.bind('<<untabify-region>>',self.pyEditorList.untabify_region_event)
        self.root.bind('<<toggle-tabs>>',self.pyEditorList.toggle_tabs_event)
 
        # #run
        self.root.bind('<<check-module>>',self.check_module)
        self.root.bind('<<run-module>>',self.run_module)
        self.root.bind('<Control-Key-Return>',self.run_source)

        # #debug
        self.root.bind('<<goto-file-line>>',self.pyEditorList.goto_line_event)


        #bindings keys
        if keydefs is None:
            keydefs=Bindings.default_keydefs
        for event, keylist in keydefs.items():
            if keylist:
                self.root.event_add(event, *keylist)



    def newfile(self,event=None):
        fileEditor=PyEditor(self.main_view.pyEditorList)
        self.pyEditorList.add(fileEditor,text=fileEditor.get_file_name())

    def open(self, event=None):
        fileEditor=PyEditor(self.main_view.pyEditorList,open=True)
        if(self.pyEditorList.focusOn(fileEditor.long_title())==False):
            if(fileEditor.isOpen()):
                self.pyEditorList.add(fileEditor,text=fileEditor.get_file_name())

    def close_all_event(self,event=None):
        while self.pyEditorList.get_size()>0 :
            reply = self.pyEditorList.close_current_editor()
            if reply == "cancel":
                break;

        if self.pyEditorList.get_size()==0:
            sys.exit(0)

    def run_module(self,event=None):
        reply=self.pyEditorList.get_current_editor().maybesave_run()
        if(reply!="cancel"):
            filename=self.pyEditorList.get_current_editor().long_title()
            self.pyShell.run(filename)

    def check_module(self,event=None):
        reply=self.pyEditorList.get_current_editor().maybesave_run()
        if(reply!="cancel"):
            self.pyShell.check(self.pyEditorList.get_current_editor())

    def run_source(self,event=None):
        filename=self.pyEditorList.get_current_editor().long_title()
        self.pyShell.runit(filename)
from PyQt5.QtWidgets import QApplication

from OmxPlayer import OmxPlayer

import sys

from MainView import MainView

if __name__ == '__main__':

    app = QApplication(sys.argv)
    omx_player = OmxPlayer()
    view = MainView(app)

    omx_player.set_observer(view)

    sys.exit(app.exec_())
Exemplo n.º 17
0
class TurnTableController:
    def __init__(self, settingsManager: ConfigurationManager,
                 zeroPointManager: ZeroPointManager):
        self._settingsManager = settingsManager
        self._zeroPointManager = zeroPointManager
        self._stopTurnTableEvent = Event()
        self._jobThreads = ControllerThreads()
        self._position = Position()

        def connectionFactory(port: int, name: str) -> LANConnection:
            return LANConnection(self._settingsManager.turnTableIPAddress,
                                 port,
                                 name=name,
                                 timeout=self._settingsManager.timeout)

        callbacks = TCPCallbacks(
            getAzimuth=self.getCurrentPosition,
            getElevation=self.getCurrentPosition,
            setAzimuth=self.createGotoPositionJob,
            setElevation=self.createGotoPositionJob,
            stop=self.stop,
        )
        self._tcpServer = TCPServer(callbacks=callbacks,
                                    settingsManager=self._settingsManager)

        self._shaftEncoder = ShaftEncoderModel(connectionFactory(
            self._settingsManager.shaftEncoderPort,
            "Shaft Encoder Connection"),
                                               settingsManager=settingsManager)
        self._motorController = MotorControllerModel(
            watchdogConnection=connectionFactory(
                self._settingsManager.watchdogPort, "Watchdog Connection"),
            motorControllerConnection=connectionFactory(
                self._settingsManager.motorControllerPort,
                "Motor Controller Connection"),
            settingsManager=settingsManager,
        )

        self._mainView = MainView()
        self._settingsManagerView = SettingsView(self._settingsManager)
        self.showMainView()

    def showMainView(self):
        self._mainView.stepSizeSpinBox.setRange(
            self._settingsManager.minimumStepSize,
            self._settingsManager.maximumStepSize)
        self._mainView.gotoPositionSpinBox.setRange(
            self._settingsManager.minimumGotoPosition,
            self._settingsManager.maximumGotoPosition)
        self._mainView.motorVoltageSliderValueSpinBox.setRange(
            self._settingsManager.minimumVoltage,
            self._settingsManager.maximumVoltage)
        self._mainView.motorVoltageSlider.setRange(
            self._settingsManager.minimumVoltage,
            self._settingsManager.maximumVoltage)

        self._mainView.applicationSettingsAction.triggered.connect(
            self._settingsManagerView.show)
        self._mainView.loadZeroPositionDataAction.triggered.connect(
            self.loadZeroPosition)
        self._mainView.saveZeroPositionDataAction.triggered.connect(
            self.saveZeroPosition)
        self._mainView.connectButton.clicked.connect(self.connect)
        self._mainView.disconnectButton.clicked.connect(self.disconnect)
        self._mainView.goPushButton.clicked.connect(self.createGotoPositionJob)
        self._mainView.motorVoltageSlider.doubleValueChanged.connect(
            self.setMotorVoltage)
        self._mainView.resetVoltageButton.clicked.connect(
            self.resetMotorVoltage)
        self._mainView.stopPushButton.clicked.connect(self.stopMotion)
        self._mainView.stepPushButton.clicked.connect(self.stepPosition)
        self._mainView.resetZeroPositionButton.clicked.connect(
            self.resetPositionOffest)
        self._mainView.setCurrentPositionAsZeroButton.clicked.connect(
            self.setPositionOffset)
        self._mainView.applicationClosed.connect(self.stop)

        self._mainView.motorVoltageSlider.setValue(0.000)

        self._mainView.show()

#------------------------------------------------------------------------------
# Starting and Stopping Methods
#------------------------------------------------------------------------------

    def start(self):
        self._jobThreads.updateGUI = TimedJobThread(
            self._settingsManager.GUIUpdatePeriod, self.updateGUI)
        self._jobThreads.updateGUI.start()

    def stop(self):
        logging.debug("Stopping Turn Table Controller")
        self.stopMotion()
        self.disconnect()
        logging.debug("Turn Table Controller Stopped...")

    def stopMotion(self):
        if self._jobThreads.gotoPosition is not None:
            self._stopTurnTableEvent.set()
            self._jobThreads.gotoPosition = None

        if self._motorController.getCurrentVoltage() != 0.000:
            self.resetMotorVoltage()

#------------------------------------------------------------------------------
# Connection Handling Methods
#------------------------------------------------------------------------------

    def connect(self):
        self._motorController.start()
        self._shaftEncoder.start()
        self._tcpServer.connect()

        if self._motorController.isWatchdogConnected(
        ) and self._motorController.isMotorControllerConnected(
        ) and self._shaftEncoder.isConnected() and self._tcpServer.isConnected(
        ):
            self._mainView.toggleControls()

    def disconnect(self):
        self._motorController.stop()
        self._shaftEncoder.stop()
        self._tcpServer.disconnect()

        if self._motorController.isWatchdogConnected(
        ) and self._motorController.isMotorControllerConnected(
        ) and self._shaftEncoder.isConnected() and self._tcpServer.isConnected(
        ):
            self._mainView.toggleControls()

#------------------------------------------------------------------------------
# Position Helper Methods
#------------------------------------------------------------------------------

    def setPositionOffset(self):
        self._position.offset = -self._shaftEncoder.currentPosition

    def resetPositionOffest(self):
        self._position.offset = 0.000

    def getCurrentPosition(self) -> float:
        self._position.current = self._shaftEncoder.currentPosition
        return self._position.current

#------------------------------------------------------------------------------
# GUI Update Helper Methods
#------------------------------------------------------------------------------

    def updateGUI(self):
        shaftEncoderConnectionStatus = self._shaftEncoder.isConnected()
        motorControllerConnectionStatus = self._motorController.isMotorControllerConnected(
        )
        watchdogConnectionStatus = self._motorController.isWatchdogConnected()
        tcpServerConnectionStatus = self._tcpServer.isConnected()

        self._mainView.updateConnectionStatusLineEdits(
            shaftEncoderConnectionStatus, motorControllerConnectionStatus,
            watchdogConnectionStatus, tcpServerConnectionStatus)
        self._mainView.updatePositionLineEdits(self._position)

#------------------------------------------------------------------------------
# Motor Control Methods
#------------------------------------------------------------------------------

    def setMotorVoltage(self, newVoltage: float):
        if (not self._motorController.isEnabled()) and (newVoltage != 0.000):
            self._motorController.toggleEnable()
        self._motorController.setVoltage(newVoltage=newVoltage)

    def resetMotorVoltage(self):
        if self._motorController.isEnabled():
            self._motorController.toggleEnable()
        self._motorController.setVoltage(0.000)

    def createGotoPositionJob(self, targetPosition: float):
        self._jobThreads.gotoPosition = Thread(target=self.gotoPosition,
                                               args=(targetPosition, ))
        self._jobThreads.gotoPosition.start()

    def stepPosition(self, step: float):
        currentPosition = self.getCurrentPosition()
        self.createGotoPositionJob(currentPosition + step)

    def gotoPosition(self, targetPosition: float):
        maxVoltage = self._settingsManager.maximumVoltage
        updatePeriod = self._settingsManager.voltageUpdatePeriod
        KP = self._settingsManager.controlProportionalGain
        KI = self._settingsManager.controlIntegralGain
        KD = self._settingsManager.controlDerivativeGain
        minimumControlSignalValue = self._settingsManager.minimumControlSignalValue
        maximumAllowedError = self._settingsManager.maximumAllowedError

        self._position.target = targetPosition

        if not self._motorController.isEnabled():
            self._motorController.toggleEnable()

        previousError = 0

        if self._stopTurnTableEvent.is_set():
            self._stopTurnTableEvent.clear()

        while True:
            error = self._position.error

            if (abs(error) < maximumAllowedError) or (
                    self._stopTurnTableEvent.is_set()):
                self._motorController.setVoltage(0.000)
                self._motorController.toggleEnable()
                break

            errorDelta = error - previousError
            previousError = error

            voltageControlSignal = (KP * error + KI * error * updatePeriod +
                                    KD * errorDelta / updatePeriod)
            voltageControlSignal = sorted(
                (-maxVoltage, voltageControlSignal, maxVoltage))[1]
            voltageControlSignal = math.copysign(
                max(abs(voltageControlSignal), minimumControlSignalValue),
                voltageControlSignal)

            self._motorController.setVoltage(voltageControlSignal)
            time.sleep(updatePeriod)

    def saveZeroPosition(self):
        saveZeroPoint = SaveZeroPoint(self._position.offset,
                                      self._zeroPointManager)
        saveZeroPoint.exec_()

    def loadZeroPosition(self):
        loadZeroPoint = LoadZeroPointView(self._zeroPointManager)
        loadZeroPoint.exec_()
        self._position.offset = self._zeroPointManager.getOffset()
Exemplo n.º 18
0
from MainView import MainView

if __name__ == "__main__":
    app = MainView()
    app.mainloop()
Exemplo n.º 19
0
 def __init__(self):
     self.__master = MainView()
Exemplo n.º 20
0
        self.select['menu'].delete(0, 'end')

        for port in self.ports:
            self.select['menu'].add_command(label=port,
                                            command=tk._setit(
                                                self.selectedPort, port))

    def connect(self):
        self.connection.close()
        if self.selectedPort.get() != 'No hay puertos':
            self.connection.baudrate = BAUDRATE
            self.connection.port = self.selectedPort.get()
            self.connection.open()
            self.onPortChanged(self.connection)

    def disconnect(self):
        self.connection.close()


if __name__ == '__main__':
    window = tk.Tk()
    window.wm_title('Control DataLogger')
    window.configure(background='#E8E9E8')
    selector = SerialSelector()
    device = DevControl(selector.connection)
    mainView = MainView(window, device)
    selector.onPortChanged.append(device.setConnection)
    device.daemon = True
    device.start()
    window.mainloop()
Exemplo n.º 21
0
class Application:
    """
    The main class of the application
    - root is the starting point of the GUI application
    - main_view defines the main window
    - py_editor_list defines the editor interface (from the main_view)
    - py_shell defines the shell interface (white and orange widgets)
    """
    def __init__(self):
        """ Set up some information like, set up the interfaces """
        import locale

        language = None
        try:  # Work around a possible Python3.7 bug on MacOS
            loc = locale.getdefaultlocale()
            if loc:
                for el in loc:
                    if str(el).upper().startswith("FR"):
                        language = "fr"
                        break
        except ValueError:
            pass  # language is still None

        if language is not None:
            set_translator_locale(language)

        self.root = Tk()

        self.root.geometry('768x612')
        self.root.title("MrPython")

        self.mode = "full"
        self.main_view = MainView(self)
        self.editor_list = self.main_view.editor_widget.py_notebook
        self.icon_widget = self.main_view.icon_widget
        self.status_bar = self.main_view.status_bar
        self.console = self.main_view.console
        self.change_mode()
        self.apply_bindings()
        self.root.protocol('WM_DELETE_WINDOW', self.close_all_event)

        self.running_interpreter_proxy = None
        self.running_interpreter_callback = None

        if tracing.user_first_session():
            user_enabled_tracing = tkMessageBox.askyesno(
                title="Suivi pédagogique",
                message=
                "Acceptez-vous que des traces de vos actions dans MrPython " +
                "soient collectées par le LIP6 ?\n" +
                "Ces traces seront anonymisées et uniquement utilisées dans un but d'amélioration pédagogique "
                + "de MrPython.",
                default=tkMessageBox.YES,
                parent=self.root)
        else:
            user_enabled_tracing = tracing.check_tracing_is_enabled()
        tracing.initialize_tracing(user_enabled_tracing)
        self.icon_widget.switch_icon_tracing(user_enabled_tracing)

        self.root.after(1000, self.check_user_state)
        self.root.after(5000, self.update_active_timestamp)
        self.state = "idle"  # 3 states: idle, interacting or typing

    def run(self):
        """ Run the application """
        self.main_view.show()

    def apply_bindings(self, keydefs=None):
        """ Bind the actions to the related event methods """
        self.new_file_button = self.icon_widget.icons['new_file'].wdgt
        self.run_button = self.icon_widget.icons['run'].wdgt
        self.save_button = self.icon_widget.icons['save'].wdgt
        self.open_button = self.icon_widget.icons['open'].wdgt
        self.mode_button = self.icon_widget.icons['mode'].wdgt
        self.tracing_button = self.icon_widget.icons['tracing'].wdgt
        self.new_file_button.bind("<1>", self.new_file)
        self.run_button.bind("<1>", self.run_module)
        self.mode_button.bind("<1>", self.change_mode)
        self.save_button.bind("<1>", self.save)
        self.save_button.bind("<3>", self.editor_list.save_as)
        self.open_button.bind("<1>", self.open)
        self.tracing_button.bind("<1>", self.enable_disable_tracing)

        # File
        self.root.bind("<Control-n>", self.new_file)
        self.root.bind('<Control-o>', self.open)
        self.root.bind('<Control-s>', self.save)
        self.root.bind('<Control-S>', self.editor_list.save_as)
        self.root.bind("<Control-m>", self.change_mode)
        self.root.bind('<<save-window-as-file>>', self.editor_list.save_as)
        self.root.bind('<<save-copy-of-window-as-file>>',
                       self.editor_list.save_as_copy)
        self.root.bind('<Control-w>', self.editor_list.close_current_editor)
        self.root.bind('<<close-all-windows>>', self.close_all_event)
        # Edit
        self.root.bind('<<undo>>', self.editor_list.undo_event)
        self.root.bind('<<redo>>', self.editor_list.redo_event)
        self.root.bind('<<cut>>', self.editor_list.cut_event)
        self.root.bind('<<copy>>', self.editor_list.copy_event)
        self.root.bind('<<paste>>', self.editor_list.paste_event)
        self.root.bind('<<select-all>>', self.editor_list.select_all_event)
        self.root.bind('<<find>>', self.editor_list.find_event)
        self.root.bind('<<find-again>>', self.editor_list.find_again_event)
        self.root.bind('<<find-selection>>',
                       self.editor_list.find_selection_event)
        self.root.bind('<<find-in-files>>',
                       self.editor_list.find_in_files_event)
        self.root.bind('<<replace>>', self.editor_list.replace_event)
        self.root.bind('<<goto-line>>', self.editor_list.goto_line_event)
        # Format
        self.root.bind('<Control-i>', self.editor_list.indent_region_event)
        self.root.bind('<Control-d>', self.editor_list.dedent_region_event)
        self.root.bind('<<comment-region>>',
                       self.editor_list.comment_region_event)
        self.root.bind('<<uncomment-region>>',
                       self.editor_list.uncomment_region_event)
        self.root.bind('<<tabify-region>>',
                       self.editor_list.tabify_region_event)
        self.root.bind('<<untabify-region>>',
                       self.editor_list.untabify_region_event)
        self.root.bind('<<toggle-tabs>>', self.editor_list.toggle_tabs_event)
        self.root.bind('<Control-plus>',
                       self.editor_list.increase_font_size_event)
        self.root.bind('<Control-minus>',
                       self.editor_list.decrease_font_size_event)
        # Code execution
        self.root.bind('<<check-module>>', self.check_module)
        self.root.bind('<Control-r>', self.run_module)
        self.root.bind('<Control-Key-Return>', self.run_source)
        # File change in notebook
        self.root.bind('<<NotebookTabChanged>>', self.update_title)

        # Bind the keys
        if keydefs is None:
            keydefs = Bindings.default_keydefs
        for event, keylist in keydefs.items():
            if keylist:
                self.root.event_add(event, *keylist)

    def check_user_state(self):
        """
        Send a statement of the state of the user. User has 3 state: idle, interacting or typing
        """
        last_typing_time, last_interacting_time = tracing.get_action_timestamps(
        )
        elapsed_typing_time = time.time(
        ) - last_typing_time if last_typing_time else None
        elapsed_interacting_time = time.time(
        ) - last_interacting_time if last_interacting_time else None
        inactivity_threshhold = 30
        new_state = ""
        if elapsed_typing_time is not None and elapsed_interacting_time is not None:
            if self.state == "idle":
                if elapsed_typing_time < inactivity_threshhold:
                    new_state = "typing"
                elif elapsed_interacting_time < inactivity_threshhold:
                    new_state = "interacting"
            elif self.state == "interacting":
                if elapsed_typing_time < inactivity_threshhold:
                    new_state = "typing"
                elif elapsed_interacting_time > inactivity_threshhold:
                    new_state = "idle"
            elif self.state == "typing" and elapsed_typing_time > inactivity_threshhold:
                if elapsed_interacting_time < 30:
                    new_state = "interacting"
        elif elapsed_typing_time is not None:
            if self.state == "idle" and elapsed_typing_time < inactivity_threshhold:
                new_state = "typing"
            elif self.state == "typing" and elapsed_typing_time > inactivity_threshhold:
                new_state = "idle"
        elif elapsed_interacting_time is not None:
            if self.state == "idle" and elapsed_interacting_time < inactivity_threshhold:
                new_state = "interacting"
            elif self.state == "interacting" and elapsed_interacting_time > inactivity_threshhold:
                new_state = "idle"

        if new_state:
            tracing.send_statement("entered", new_state + "-state")
            self.state = new_state
        self.root.after(1000, self.check_user_state)

    def update_active_timestamp(self):
        tracing.update_active_timestamp()
        self.root.after(5000, self.update_active_timestamp)

    def update_title(self, event=None):
        """ Give the title the current filename """
        #print("editor list: ", self.editor_list.index("current"))
        try:
            new_title = self.editor_list.tab(self.editor_list.index("current"),
                                             "text")
        except:
            new_title = "MrPython"
            self.root.title(new_title)
            return

        directory = ""
        if self.editor_list.get_current_editor().io.filename:
            directory = self.editor_list.get_current_editor().io.filename
        if directory != "":
            new_title += " (" + directory + ")"
        new_title += " - MrPython"
        self.root.title(new_title)

    #def maybe_save_run(self, event=None):

    def save(self, event=None):
        """ Save the current file (and display it in the status bar) """
        filename = self.editor_list.save()
        if filename:
            self.status_bar.update_save_label(filename)
            self.update_title()

    def change_mode(self, event=None):
        """ Swap the python mode : full python or student """
        if self.mode == "student":
            self.mode = "full"
        else:
            self.mode = "student"
        self.icon_widget.switch_icon_mode(self.mode)
        self.console.change_mode(tr(self.mode))
        self.status_bar.change_mode(tr(self.mode))
        if event:
            tracing.user_is_interacting()
            tracing.send_statement(
                "switched", "mode", {
                    "https://www.lip6.fr/mocah/invalidURI/extensions/mode":
                    tr(self.mode)
                })

    def new_file(self, event=None):
        """ Creates a new empty editor and put it into the pyEditorList """
        tracing.user_is_interacting()
        file_editor = PyEditorFrame(self.editor_list)
        self.editor_list.add(file_editor,
                             self.main_view.editor_widget,
                             text=file_editor.get_file_name())
        tracing.send_statement("created", "file")

    def open(self, event=None):
        """ Open a file in the text editor """
        tracing.user_is_interacting()
        file_editor = PyEditorFrame(self.editor_list, open=True)
        if (self.editor_list.focusOn(file_editor.long_title()) == False):
            if (file_editor.isOpen()):
                self.editor_list.add(file_editor,
                                     self.main_view.editor_widget,
                                     text=file_editor.get_file_name())
                extensions = {
                    "https://www.lip6.fr/mocah/invalidURI/extensions/filename":
                    file_editor.get_file_name()
                }
                with open(file_editor.long_title(), "r") as source:
                    text = source.read()
                    extensions[
                        "https://www.lip6.fr/mocah/invalidURI/extensions/text"] = text
                    extensions[
                        "https://www.lip6.fr/mocah/invalidURI/extensions/filelength"] = len(
                            text)
                tracing.send_statement("opened", "file", extensions)
            #not clean, io should be handled here and should not require creation of PyEditor widget
            else:
                file_editor.destroy()

    def enable_disable_tracing(self, event=None):
        """ Enable/Disable tracing"""
        tracing.user_is_interacting()
        tracing_enabled = tracing.switch_tracing_enabled_disabled()
        if tracing_enabled:
            msg = "Le suivi a été activé\n"
        else:
            msg = "Le suivi a été désactivé\n"
        self.console.write(msg, tags=('error'))
        self.icon_widget.switch_icon_tracing(tracing_enabled)

    def close_all_event(self, event=None):
        """ Quit all the PyEditor : called when exiting application """

        print("MrPython says 'bye bye!' ...")
        while self.editor_list.get_size() > 0:
            reply = self.editor_list.close_current_editor()
            if reply == "cancel":
                break
        if self.editor_list.get_size() == 0:
            if self.running_interpreter_proxy and self.running_interpreter_proxy.process.is_alive(
            ):
                self.running_interpreter_proxy.process.terminate()
                self.running_interpreter_proxy.process.join()
            tracing.send_statement_close_app()
            sys.exit(0)

    def run_module(self, event=None):
        """ Run the code : give the file name and code will be run from the source file """
        tracing.user_is_interacting()
        # already running
        if self.running_interpreter_callback:
            if self.running_interpreter_proxy and self.running_interpreter_proxy.process.is_alive(
            ):
                report = RunReport()
                report.set_header("\n====== STOP ======\n")
                report.add_execution_error('error',
                                           tr('User interruption'),
                                           class_name='UserTerminatedError')
                report.set_footer("\n==================\n")
                self.running_interpreter_callback(False, report)
            self.running_interpreter_callback = None
            return

        # not (yet) running

        if self.editor_list.get_size() == 0:
            self.main_view.console.no_file_to_run_message()
            return

        reply = self.editor_list.get_current_editor().maybesave_run()
        if (reply != "cancel"):
            self.editor_list.get_current_editor().send_update_changed_line(
                force_sending=True)
            tracing.send_statement(
                "started", "execution", {
                    "https://www.lip6.fr/mocah/invalidURI/extensions/mode":
                    tr(self.mode)
                })
            tracing.save_execution_start()
            file_name = self.editor_list.get_current_editor().long_title()
            self.update_title()
            self.status_bar.update_save_label(file_name)
            self.console.run(file_name)

    def goto_position(self, lineno, col_offset):
        editor = self.editor_list.get_current_editor()
        editor.mark_set("insert", "%d.%d" % (lineno, col_offset))
        editor.see("insert")
        editor.focus()

    # TODO: Continue ?
    def check_module(self, event=None):
        """ Check syntax : compilation """
        reply = self.editor_list.get_current_editor().maybesave_run()
        if (reply != "cancel"):
            self.console.check_syntax(self.editor_list.get_current_editor())

    # TODO: remove ?
    def run_source(self, event=None):
        file_name = self.editor_list.get_current_editor().long_title()
        self.console.runit(file_name)
Exemplo n.º 22
0
class Application:
    """
    The main class of the application
    - root is the starting point of the GUI application
    - main_view defines the main window
    - py_editor_list defines the editor interface (from the main_view)
    - py_shell defines the shell interface (white and orange widgets)
    """

    def __init__(self):
        """ Set up some information like, set up the interfaces """
        import locale

        language = None
        loc = locale.getdefaultlocale()
        if loc:
            for el in loc:
                if str(el).upper().startswith("FR"):
                    language = "fr"
                    break

        if language is not None:
            set_translator_locale(language)

        self.root = Tk()
        StudentRunner.TK_ROOT = self.root
        self.root.title("MrPython")

        self.mode = "full"
        self.main_view = MainView(self)
        self.editor_list = self.main_view.editor_widget.py_notebook
        self.icon_widget = self.main_view.icon_widget
        self.status_bar = self.main_view.status_bar
        self.console = self.main_view.console
        self.change_mode()
        self.apply_bindings()
        self.root.protocol('WM_DELETE_WINDOW', self.close_all_event)

    def run(self):
        """ Run the application """
        self.main_view.show()


    def apply_bindings(self, keydefs=None):
        """ Bind the actions to the related event methods """
        self.new_file_button = self.icon_widget.icons['new_file'].wdgt
        self.run_button = self.icon_widget.icons['run'].wdgt
        self.save_button = self.icon_widget.icons['save'].wdgt
        self.open_button = self.icon_widget.icons['open'].wdgt
        self.mode_button = self.icon_widget.icons['mode'].wdgt
        self.new_file_button.bind("<1>", self.new_file)
        self.run_button.bind("<1>", self.run_module)
        self.mode_button.bind("<1>", self.change_mode)
        self.save_button.bind("<1>", self.save)
        self.open_button.bind("<1>", self.open)

        # File
        self.root.bind("<Control-n>", self.new_file)
        self.root.bind('<Control-o>', self.open)
        self.root.bind('<Control-s>', self.save)
        self.root.bind("<Control-m>", self.change_mode)
        self.root.bind('<<save-window-as-file>>', self.editor_list.save_as)
        self.root.bind('<<save-copy-of-window-as-file>>',
                       self.editor_list.save_as_copy)
        self.root.bind('<Control-w>',
                       self.editor_list.close_current_editor)
        self.root.bind('<<close-all-windows>>', self.close_all_event)
        # Edit
        self.root.bind('<<undo>>', self.editor_list.undo_event)
        self.root.bind('<<redo>>', self.editor_list.redo_event)
        self.root.bind('<<cut>>', self.editor_list.cut_event)
        self.root.bind('<<copy>>', self.editor_list.copy_event)
        self.root.bind('<<paste>>', self.editor_list.paste_event)
        self.root.bind('<<select-all>>', self.editor_list.select_all_event)
        self.root.bind('<<find>>', self.editor_list.find_event)
        self.root.bind('<<find-again>>', self.editor_list.find_again_event)
        self.root.bind('<<find-selection>>',
                       self.editor_list.find_selection_event)
        self.root.bind('<<find-in-files>>',
                       self.editor_list.find_in_files_event)
        self.root.bind('<<replace>>', self.editor_list.replace_event)
        self.root.bind('<<goto-line>>', self.editor_list.goto_line_event)
        # Format
        self.root.bind('<Control-i>', self.editor_list.indent_region_event)
        self.root.bind('<Control-d>', self.editor_list.dedent_region_event)
        self.root.bind('<<comment-region>>', self.editor_list.comment_region_event)
        self.root.bind('<<uncomment-region>>', self.editor_list.uncomment_region_event)
        self.root.bind('<<tabify-region>>', self.editor_list.tabify_region_event)
        self.root.bind('<<untabify-region>>', self.editor_list.untabify_region_event)
        self.root.bind('<<toggle-tabs>>', self.editor_list.toggle_tabs_event)
        # Code execution
        self.root.bind('<<check-module>>', self.check_module)
        self.root.bind('<Control-r>', self.run_module)
        self.root.bind('<Control-Key-Return>', self.run_source)
        # File change in notebook
        self.root.bind('<<NotebookTabChanged>>', self.update_title)

        # Bind the keys
        if keydefs is None:
            keydefs = Bindings.default_keydefs
        for event, keylist in keydefs.items():
            if keylist:
                self.root.event_add(event, *keylist)


    def update_title(self, event=None):
        """ Give the title the current filename """
        #print("editor list: ", self.editor_list.index("current"))
        try:
            new_title = self.editor_list.tab(self.editor_list.index("current"), "text")
        except:
            new_title = "MrPython"
            self.root.title(new_title)
            return
            
        directory = ""
        if self.editor_list.get_current_editor().io.filename:
            directory = self.editor_list.get_current_editor().io.filename
        if directory != "":
            new_title += " (" + directory + ")"
        new_title += " - MrPython"
        self.root.title(new_title)


    #def maybe_save_run(self, event=None):

    def save(self, event=None):
        """ Save the current file (and display it in the status bar) """
        filename = self.editor_list.save()
        if filename:
            self.status_bar.update_save_label(filename)
            self.update_title()


    def change_mode(self, event=None):
        """ Swap the python mode : full python or student """
        if self.mode == "student":
            self.mode = "full"
        else:
            self.mode = "student"
        self.icon_widget.switch_icon_mode(self.mode)
        self.console.change_mode(tr(self.mode))
        self.status_bar.change_mode(tr(self.mode))


    def new_file(self, event=None):
        """ Creates a new empty editor and put it into the pyEditorList """
        file_editor = PyEditor(self.editor_list)
        self.editor_list.add(file_editor, text=file_editor.get_file_name())

    def open(self, event=None):
        """ Open a file in the text editor """
        file_editor = PyEditor(self.editor_list, open=True)
        if (self.editor_list.focusOn(file_editor.long_title()) == False):
            if (file_editor.isOpen()):
                self.editor_list.add(file_editor, text=file_editor.get_file_name())


    def close_all_event(self, event=None):
        """ Quit all the PyEditor : called when exiting application """
        while self.editor_list.get_size() > 0:
            reply = self.editor_list.close_current_editor()
            if reply == "cancel":
                break
        if self.editor_list.get_size() == 0:
            sys.exit(0)


    def run_module(self, event=None):
        """ Run the code : give the file name and code will be run from the source file """
        if self.editor_list.get_size() == 0:
            self.main_view.console.no_file_to_run_message()
            return
        reply = self.editor_list.get_current_editor().maybesave_run()
        if (reply != "cancel"):
            file_name = self.editor_list.get_current_editor().long_title()
            self.update_title()
            self.status_bar.update_save_label(file_name)
            self.console.run(file_name)


    # TODO: Continue ?
    def check_module(self, event=None):
        """ Check syntax : compilation """
        reply = self.editor_list.get_current_editor().maybesave_run()
        if (reply != "cancel"):
            self.console.check_syntax(self.editor_list.get_current_editor())


    # TODO: remove ?
    def run_source(self,event=None):
        file_name = self.editor_list.get_current_editor().long_title()
        self.console.runit(file_name)
Exemplo n.º 23
0
def main():

    ct = Controller()
    mv = MainView(ct)
    mv.run()
Exemplo n.º 24
0
class Application:
    """
    The main class of the application
    - root is the starting point of the GUI application
    - main_view defines the main window
    - py_editor_list defines the editor interface (from the main_view)
    - py_shell defines the shell interface (white and orange widgets)
    """

    def __init__(self):
        """ Set up some information like, set up the interfaces """
        import locale

        language = None
        try: # Work around a possible Python3.7 bug on MacOS
            loc = locale.getdefaultlocale()
            if loc:
                for el in loc:
                    if str(el).upper().startswith("FR"):
                        language = "fr"
                        break
        except ValueError:
            pass # language is still None
                    
        if language is not None:
            set_translator_locale(language)

        self.root = Tk()
        
        self.root.title("MrPython")

        self.mode = "full"
        self.main_view = MainView(self)
        self.editor_list = self.main_view.editor_widget.py_notebook
        self.icon_widget = self.main_view.icon_widget
        self.status_bar = self.main_view.status_bar
        self.console = self.main_view.console
        self.change_mode()
        self.apply_bindings()
        self.root.protocol('WM_DELETE_WINDOW', self.close_all_event)

        self.running_interpreter_proxy = None
        self.running_interpreter_callback = None

    def run(self):
        """ Run the application """
        self.main_view.show()


    def apply_bindings(self, keydefs=None):
        """ Bind the actions to the related event methods """
        self.new_file_button = self.icon_widget.icons['new_file'].wdgt
        self.run_button = self.icon_widget.icons['run'].wdgt
        self.save_button = self.icon_widget.icons['save'].wdgt
        self.open_button = self.icon_widget.icons['open'].wdgt
        self.mode_button = self.icon_widget.icons['mode'].wdgt
        self.new_file_button.bind("<1>", self.new_file)
        self.run_button.bind("<1>", self.run_module)
        self.mode_button.bind("<1>", self.change_mode)
        self.save_button.bind("<1>", self.save)
        self.save_button.bind("<3>", self.editor_list.save_as)
        self.open_button.bind("<1>", self.open)

        # File
        self.root.bind("<Control-n>", self.new_file)
        self.root.bind('<Control-o>', self.open)
        self.root.bind('<Control-s>', self.save)
        self.root.bind('<Control-S>', self.editor_list.save_as)
        self.root.bind("<Control-m>", self.change_mode)
        self.root.bind('<<save-window-as-file>>', self.editor_list.save_as)
        self.root.bind('<<save-copy-of-window-as-file>>',
                       self.editor_list.save_as_copy)
        self.root.bind('<Control-w>',
                       self.editor_list.close_current_editor)
        self.root.bind('<<close-all-windows>>', self.close_all_event)
        # Edit
        self.root.bind('<<undo>>', self.editor_list.undo_event)
        self.root.bind('<<redo>>', self.editor_list.redo_event)
        self.root.bind('<<cut>>', self.editor_list.cut_event)
        self.root.bind('<<copy>>', self.editor_list.copy_event)
        self.root.bind('<<paste>>', self.editor_list.paste_event)
        self.root.bind('<<select-all>>', self.editor_list.select_all_event)
        self.root.bind('<<find>>', self.editor_list.find_event)
        self.root.bind('<<find-again>>', self.editor_list.find_again_event)
        self.root.bind('<<find-selection>>',
                       self.editor_list.find_selection_event)
        self.root.bind('<<find-in-files>>',
                       self.editor_list.find_in_files_event)
        self.root.bind('<<replace>>', self.editor_list.replace_event)
        self.root.bind('<<goto-line>>', self.editor_list.goto_line_event)
        # Format
        self.root.bind('<Control-i>', self.editor_list.indent_region_event)
        self.root.bind('<Control-d>', self.editor_list.dedent_region_event)
        self.root.bind('<<comment-region>>', self.editor_list.comment_region_event)
        self.root.bind('<<uncomment-region>>', self.editor_list.uncomment_region_event)
        self.root.bind('<<tabify-region>>', self.editor_list.tabify_region_event)
        self.root.bind('<<untabify-region>>', self.editor_list.untabify_region_event)
        self.root.bind('<<toggle-tabs>>', self.editor_list.toggle_tabs_event)
        self.root.bind('<Control-plus>', self.editor_list.increase_font_size_event)
        self.root.bind('<Control-minus>', self.editor_list.decrease_font_size_event)
        # Code execution
        self.root.bind('<<check-module>>', self.check_module)
        self.root.bind('<Control-r>', self.run_module)
        self.root.bind('<Control-Key-Return>', self.run_source)
        # File change in notebook
        self.root.bind('<<NotebookTabChanged>>', self.update_title)

        # Bind the keys
        if keydefs is None:
            keydefs = Bindings.default_keydefs
        for event, keylist in keydefs.items():
            if keylist:
                self.root.event_add(event, *keylist)


    def update_title(self, event=None):
        """ Give the title the current filename """
        #print("editor list: ", self.editor_list.index("current"))
        try:
            new_title = self.editor_list.tab(self.editor_list.index("current"), "text")
        except:
            new_title = "MrPython"
            self.root.title(new_title)
            return

        directory = ""
        if self.editor_list.get_current_editor().io.filename:
            directory = self.editor_list.get_current_editor().io.filename
        if directory != "":
            new_title += " (" + directory + ")"
        new_title += " - MrPython"
        self.root.title(new_title)


    #def maybe_save_run(self, event=None):

    def save(self, event=None):
        """ Save the current file (and display it in the status bar) """
        filename = self.editor_list.save()
        if filename:
            self.status_bar.update_save_label(filename)
            self.update_title()


    def change_mode(self, event=None):
        """ Swap the python mode : full python or student """
        if self.mode == "student":
            self.mode = "full"
        else:
            self.mode = "student"
        self.icon_widget.switch_icon_mode(self.mode)
        self.console.change_mode(tr(self.mode))
        self.status_bar.change_mode(tr(self.mode))


    def new_file(self, event=None):
        """ Creates a new empty editor and put it into the pyEditorList """
        file_editor = PyEditor(self.editor_list)
        self.editor_list.add(file_editor, self.main_view.editor_widget, text=file_editor.get_file_name())

    def open(self, event=None):
        """ Open a file in the text editor """
        file_editor = PyEditor(self.editor_list, open=True)
        if (self.editor_list.focusOn(file_editor.long_title()) == False):
            if (file_editor.isOpen()):
                self.editor_list.add(file_editor, self.main_view.editor_widget, text=file_editor.get_file_name())


    def close_all_event(self, event=None):
        """ Quit all the PyEditor : called when exiting application """

        print("MrPython says 'bye bye!' ...")
        while self.editor_list.get_size() > 0:
            reply = self.editor_list.close_current_editor()
            if reply == "cancel":
                break
        if self.editor_list.get_size() == 0:
            if self.running_interpreter_proxy and self.running_interpreter_proxy.process.is_alive():                
                self.running_interpreter_proxy.process.terminate()
                self.running_interpreter_proxy.process.join()
            sys.exit(0)


    def run_module(self, event=None):
        """ Run the code : give the file name and code will be run from the source file """

        # already running
        if self.running_interpreter_callback:
            if self.running_interpreter_proxy and self.running_interpreter_proxy.process.is_alive():
                report = RunReport()
                report.set_header("\n====== STOP ======\n")
                report.add_execution_error('error', tr('User interruption'))
                report.set_footer("\n==================\n")
                self.running_interpreter_callback(False, report)
            self.running_interpreter_callback = None
            return

        # not (yet) running
        
        if self.editor_list.get_size() == 0:
            self.main_view.console.no_file_to_run_message()
            return
        reply = self.editor_list.get_current_editor().maybesave_run()
        if (reply != "cancel"):
            file_name = self.editor_list.get_current_editor().long_title()
            self.update_title()
            self.status_bar.update_save_label(file_name)
            self.console.run(file_name)

    def goto_position(self, lineno, col_offset):
        editor = self.editor_list.get_current_editor()
        editor.mark_set("insert", "%d.%d" % (lineno, col_offset))
        editor.see("insert")
        editor.focus()

    # TODO: Continue ?
    def check_module(self, event=None):
        """ Check syntax : compilation """
        reply = self.editor_list.get_current_editor().maybesave_run()
        if (reply != "cancel"):
            self.console.check_syntax(self.editor_list.get_current_editor())


    # TODO: remove ?
    def run_source(self,event=None):
        file_name = self.editor_list.get_current_editor().long_title()
        self.console.runit(file_name)
Exemplo n.º 25
0
# This Python file uses the following encoding: utf-8
import sys
import shiboken2
from PySide2.QtWidgets import (QApplication)
from MainView import MainView
import logging

if __name__ == "__main__":
    app = QApplication([])
    logging.basicConfig(filename='../log/EaraQuake.log', level=logging.WARNING)
    window = MainView(_app=app)
    window.show()
    sys.exit(app.exec_())
Exemplo n.º 26
0
class DuplicateImagesController:
    """ Controller for 'Duplicate image finder' application.
        Implements the 'Controller' from MVC design pattern.
    """
    def __init__(self):

        supported_image_formats = ('.png', '.jpg', '.jpeg', '.bmp', '.gif')

        start_scan_callback = lambda scan_directories: self._start_scan_click_callback(
            scan_directories)
        delete_image_callback = lambda path_to_delete: self._delete_file(
            path_to_delete)
        delete_all_duplicates = lambda duplicates: self._delete_all_duplicated_keep_newest(
            duplicates)

        self._main_view = MainView(start_scan_callback, delete_image_callback,
                                   delete_all_duplicates)

        self._imageManager = DuplicateImagesManager(supported_image_formats)

    def Start(self) -> None:

        self._main_view.Init()

    def _start_scan_click_callback(self, scan_directories: [str]) -> None:
        """ Handler method for click on 'start scan' button.
        """

        core.log_debug(
            'DuplicateImagesController - starting scan on dirs [%s]' %
            (scan_directories))

        self._main_view.ShowScanInProgressWindow()

        scan_start_time = datetime.now()

        self._imageManager.CleanResults()
        self._imageManager.ScanDirectories(scan_directories)
        duplicates = self._imageManager.GetDuplicates()

        scan_end_time = datetime.now()

        scan_duration_in_secs = (scan_end_time -
                                 scan_start_time).total_seconds()

        core.log_debug(
            'DuplicateImagesController - Scan duration in secs is [%d]' %
            scan_duration_in_secs)

        self._main_view.ShowResultsWindows(duplicates)

    def _delete_file(self, file_path):

        try:
            core.log_debug('DuplicateImagesController - deleting file [%s]' %
                           (file_path))
            os.remove(file_path)

        except Exception as e:
            core.log_error(
                'DuplicateImagesController - delete file  [%s] failed with exception [%s]'
                % (file_path, e))

    def _delete_all_duplicated_keep_newest(
            self, duplicates: FileMetaDataList) -> FileMetaDataList:

        updated_duplicate_list = []

        for duplicate_file_list in duplicates:
            newest_file = self._get_newest_file(duplicate_file_list)

            for file in duplicate_file_list:
                if file.GetPath() == newest_file.GetPath():
                    continue
                else:
                    self._delete_file(file.GetPath())

            updated_duplicate_list.append([newest_file])

        return updated_duplicate_list

    def _get_newest_file(self, files: FileMetaDataList):
        return max(files, key=lambda file: file.GetLastEditTime())
Exemplo n.º 27
0
def main():
    window = arcade.Window(SCREEN_WIDTH, SCREEN_HEIGHT, TITLE)
    main_view = MainView()
    window.show_view(main_view)
    main_view.setup()
    arcade.run()
Exemplo n.º 28
0
 def __init__(self, sys_argv):
     super(App, self).__init__(sys_argv)
     self.model = Model()
     self.main_ctrl = MainController(self.model)
     self.main_view = MainView(self.model, self.main_ctrl)
     self.main_view.show()
Exemplo n.º 29
0
'''
Created on 2015-11-26

@author: Xuewei (Harvey) Wu
'''
from MainView import MainView
import sys

from PyQt4.QtGui import *

app = QApplication(sys.argv)
mw = MainView()
mw.show()
sys.exit(app.exec_()) 
Exemplo n.º 30
0
def mainView():
    from MainView import MainView
    return MainView()
Exemplo n.º 31
0
class Application:
    """
    The main class of the application
    - root is the starting point of the GUI application
    - main_view defines the main window
    - py_editor_list defines the editor interface (from the main_view)
    - py_shell defines the shell interface (white and orange widgets)
    """
    def __init__(self):
        """ Set up some information like, set up the interfaces """
        import locale

        language = None
        try:  # Work around a possible Python3.7 bug on MacOS
            loc = locale.getdefaultlocale()
            if loc:
                for el in loc:
                    if str(el).upper().startswith("FR"):
                        language = "fr"
                        break
        except ValueError:
            pass  # language is still None

        if language is not None:
            set_translator_locale(language)

        self.root = Tk()

        self.root.geometry('768x612')
        self.root.title("MrPython")

        self.mode = "full"
        self.main_view = MainView(self)
        self.editor_list = self.main_view.editor_widget.py_notebook
        self.icon_widget = self.main_view.icon_widget
        self.status_bar = self.main_view.status_bar
        self.console = self.main_view.console
        self.change_mode()
        self.apply_bindings()
        self.root.protocol('WM_DELETE_WINDOW', self.close_all_event)

        self.running_interpreter_proxy = None
        self.running_interpreter_callback = None

    def run(self):
        """ Run the application """
        self.main_view.show()

    def apply_bindings(self, keydefs=None):
        """ Bind the actions to the related event methods """
        self.new_file_button = self.icon_widget.icons['new_file'].wdgt
        self.run_button = self.icon_widget.icons['run'].wdgt
        self.save_button = self.icon_widget.icons['save'].wdgt
        self.open_button = self.icon_widget.icons['open'].wdgt
        self.mode_button = self.icon_widget.icons['mode'].wdgt
        self.new_file_button.bind("<1>", self.new_file)
        self.run_button.bind("<1>", self.run_module)
        self.mode_button.bind("<1>", self.change_mode)
        self.save_button.bind("<1>", self.save)
        self.save_button.bind("<3>", self.editor_list.save_as)
        self.open_button.bind("<1>", self.open)

        # File
        self.root.bind("<Control-n>", self.new_file)
        self.root.bind('<Control-o>', self.open)
        self.root.bind('<Control-s>', self.save)
        self.root.bind('<Control-S>', self.editor_list.save_as)
        self.root.bind("<Control-m>", self.change_mode)
        self.root.bind('<<save-window-as-file>>', self.editor_list.save_as)
        self.root.bind('<<save-copy-of-window-as-file>>',
                       self.editor_list.save_as_copy)
        self.root.bind('<Control-w>', self.editor_list.close_current_editor)
        self.root.bind('<<close-all-windows>>', self.close_all_event)
        # Edit
        self.root.bind('<<undo>>', self.editor_list.undo_event)
        self.root.bind('<<redo>>', self.editor_list.redo_event)
        self.root.bind('<<cut>>', self.editor_list.cut_event)
        self.root.bind('<<copy>>', self.editor_list.copy_event)
        self.root.bind('<<paste>>', self.editor_list.paste_event)
        self.root.bind('<<select-all>>', self.editor_list.select_all_event)
        self.root.bind('<<find>>', self.editor_list.find_event)
        self.root.bind('<<find-again>>', self.editor_list.find_again_event)
        self.root.bind('<<find-selection>>',
                       self.editor_list.find_selection_event)
        self.root.bind('<<find-in-files>>',
                       self.editor_list.find_in_files_event)
        self.root.bind('<<replace>>', self.editor_list.replace_event)
        self.root.bind('<<goto-line>>', self.editor_list.goto_line_event)
        # Format
        self.root.bind('<Control-i>', self.editor_list.indent_region_event)
        self.root.bind('<Control-d>', self.editor_list.dedent_region_event)
        self.root.bind('<<comment-region>>',
                       self.editor_list.comment_region_event)
        self.root.bind('<<uncomment-region>>',
                       self.editor_list.uncomment_region_event)
        self.root.bind('<<tabify-region>>',
                       self.editor_list.tabify_region_event)
        self.root.bind('<<untabify-region>>',
                       self.editor_list.untabify_region_event)
        self.root.bind('<<toggle-tabs>>', self.editor_list.toggle_tabs_event)
        self.root.bind('<Control-plus>',
                       self.editor_list.increase_font_size_event)
        self.root.bind('<Control-minus>',
                       self.editor_list.decrease_font_size_event)
        # Code execution
        self.root.bind('<<check-module>>', self.check_module)
        self.root.bind('<Control-r>', self.run_module)
        self.root.bind('<Control-Key-Return>', self.run_source)
        # File change in notebook
        self.root.bind('<<NotebookTabChanged>>', self.update_title)

        # Bind the keys
        if keydefs is None:
            keydefs = Bindings.default_keydefs
        for event, keylist in keydefs.items():
            if keylist:
                self.root.event_add(event, *keylist)

    def update_title(self, event=None):
        """ Give the title the current filename """
        #print("editor list: ", self.editor_list.index("current"))
        try:
            new_title = self.editor_list.tab(self.editor_list.index("current"),
                                             "text")
        except:
            new_title = "MrPython"
            self.root.title(new_title)
            return

        directory = ""
        if self.editor_list.get_current_editor().io.filename:
            directory = self.editor_list.get_current_editor().io.filename
        if directory != "":
            new_title += " (" + directory + ")"
        new_title += " - MrPython"
        self.root.title(new_title)

    #def maybe_save_run(self, event=None):

    def save(self, event=None):
        """ Save the current file (and display it in the status bar) """
        filename = self.editor_list.save()
        if filename:
            self.status_bar.update_save_label(filename)
            self.update_title()

    def change_mode(self, event=None):
        """ Swap the python mode : full python or student """
        if self.mode == "student":
            self.mode = "full"
        else:
            self.mode = "student"
        self.icon_widget.switch_icon_mode(self.mode)
        self.console.change_mode(tr(self.mode))
        self.status_bar.change_mode(tr(self.mode))

    def new_file(self, event=None):
        """ Creates a new empty editor and put it into the pyEditorList """
        file_editor = PyEditorFrame(self.editor_list)
        self.editor_list.add(file_editor,
                             self.main_view.editor_widget,
                             text=file_editor.get_file_name())

    def open(self, event=None):
        """ Open a file in the text editor """
        file_editor = PyEditorFrame(self.editor_list, open=True)
        if (self.editor_list.focusOn(file_editor.long_title()) == False):
            if (file_editor.isOpen()):
                self.editor_list.add(file_editor,
                                     self.main_view.editor_widget,
                                     text=file_editor.get_file_name())
            #not clean, io should be handled here and should not require creation of PyEditor widget
            else:
                file_editor.destroy()

    def close_all_event(self, event=None):
        """ Quit all the PyEditor : called when exiting application """

        print("MrPython says 'bye bye!' ...")
        while self.editor_list.get_size() > 0:
            reply = self.editor_list.close_current_editor()
            if reply == "cancel":
                break
        if self.editor_list.get_size() == 0:
            if self.running_interpreter_proxy and self.running_interpreter_proxy.process.is_alive(
            ):
                self.running_interpreter_proxy.process.terminate()
                self.running_interpreter_proxy.process.join()
            sys.exit(0)

    def run_module(self, event=None):
        """ Run the code : give the file name and code will be run from the source file """

        # already running
        if self.running_interpreter_callback:
            if self.running_interpreter_proxy and self.running_interpreter_proxy.process.is_alive(
            ):
                report = RunReport()
                report.set_header("\n====== STOP ======\n")
                report.add_execution_error('error', tr('User interruption'))
                report.set_footer("\n==================\n")
                self.running_interpreter_callback(False, report)
            self.running_interpreter_callback = None
            return

        # not (yet) running

        if self.editor_list.get_size() == 0:
            self.main_view.console.no_file_to_run_message()
            return

        reply = self.editor_list.get_current_editor().maybesave_run()
        if (reply != "cancel"):
            file_name = self.editor_list.get_current_editor().long_title()
            self.update_title()
            self.status_bar.update_save_label(file_name)
            self.console.run(file_name)

    def goto_position(self, lineno, col_offset):
        editor = self.editor_list.get_current_editor()
        editor.mark_set("insert", "%d.%d" % (lineno, col_offset))
        editor.see("insert")
        editor.focus()

    # TODO: Continue ?
    def check_module(self, event=None):
        """ Check syntax : compilation """
        reply = self.editor_list.get_current_editor().maybesave_run()
        if (reply != "cancel"):
            self.console.check_syntax(self.editor_list.get_current_editor())

    # TODO: remove ?
    def run_source(self, event=None):
        file_name = self.editor_list.get_current_editor().long_title()
        self.console.runit(file_name)
Exemplo n.º 32
0
'''
Created on 6 Nov 2015

@author: wnm24546
'''
import sys
from PyQt4.QtGui import (QHBoxLayout, QWidget, QPushButton, QApplication,
                         QDialog)
from MainView import MainView

if __name__ == "__main__":
    app = QApplication(sys.argv)
    w = MainView()
    w.show()
    sys.exit(app.exec_())
Exemplo n.º 33
0
class MainApp():
    def __init__(self):
        self.__master = MainView()

    def run(self):
        self.__master.mainloop()
Exemplo n.º 34
0
 def __init__(self):
     MainView.__init__(self, None)
     self.SetTitle(u"淘宝放大图片下载工具")
     self.current_dir = None
Exemplo n.º 35
0
'''
Created on 6 Nov 2015

@author: wnm24546
'''
import sys
from PyQt4.QtGui import (QHBoxLayout, QWidget, QPushButton, QApplication, QDialog)
from MainView import MainView

if __name__ == "__main__":
    app = QApplication(sys.argv)
    w = MainView()
    w.show()
    sys.exit(app.exec_())
Exemplo n.º 36
0
#!/usr/bin/python3.8

import tkinter as tk
from MainView import MainView

if __name__ == "__main__":
    root = tk.Tk(className=" Mail User Agent")
    main = MainView(root)
    main.pack(side="top", fill="both", expand=True)
    root.wm_geometry("800x600")
    root.mainloop()