Beispiel #1
0
 def __init__(self, parent=None):
     super(Form, self).__init__(parent)
     self.browser = QTextBrowser()
     self.lineedit = QLineEdit("Type an expression and press Enter")
     self.lineedit.selectAll()
     layout = QVBoxLayout()
     layout.addWidget(self.browser)
     layout.addWidget(self.lineedit)
     self.setLayout(layout)
     self.lineedit.setFocus()
     self.lineedit.returnPressed.connect(self.updateUi)
     self.setWindowTitle("Calculate")
    def __init__(self, scheme, parent):
        super(EditorSchemeDesigner, self).__init__(parent, Qt.Dialog)
        self.original_style = copy.copy(resources.CUSTOM_SCHEME)
        self._avoid_on_loading, self.saved, self._components = True, False, {}
        self.setWindowTitle(translations.TR_PREFERENCES_EDITOR_SCHEME_DESIGNER)
        self.setMinimumSize(450, 480)
        self.setMaximumSize(500, 900)
        self.resize(450, 600)

        # all layouts and groupboxes
        group0 = QGroupBox(translations.TR_PROJECT_NAME)  # scheme filename
        group1 = QGroupBox(translations.TR_PROJECT_PROPERTIES)  # properties
        group2 = QGroupBox(translations.TR_PREVIEW)  # quick preview thingy
        group0_hbox, group1_vbox = QHBoxLayout(group0), QVBoxLayout(group1)
        this_dialog_vbox, group2_vbox = QVBoxLayout(self), QVBoxLayout(group2)
        self._grid, scrollArea, frame = QGridLayout(), QScrollArea(), QFrame()

        # widgets
        self.line_name, btnSave = QLineEdit(), QPushButton(
            translations.TR_SAVE)
        self.line_name.setPlaceholderText(getuser().capitalize() + "s_scheme")
        group0_hbox.addWidget(self.line_name)
        group0_hbox.addWidget(btnSave)
        self.connect(btnSave, SIGNAL("clicked()"), self.save_scheme)
        _demo = "<center>" + ascii_letters  # demo text for preview
        self.preview_label1, self.preview_label2 = QLabel(_demo), QLabel(_demo)
        group2_vbox.addWidget(self.preview_label1)
        group2_vbox.addWidget(self.preview_label2)

        # rows titles
        self._grid.addWidget(QLabel("<b>" + translations.TR_PROJECT_NAME), 0,
                             0)
        self._grid.addWidget(QLabel("<b>" + translations.TR_CODE), 0, 1)
        self._grid.addWidget(
            QLabel("<b>" + translations.TR_EDITOR_SCHEME_PICK_COLOR), 0, 2)

        # fill rows
        for key in sorted(tuple(resources.COLOR_SCHEME.keys())):
            self.add_item(key, scheme)
        self.preview_label1.setStyleSheet('background:transparent')
        self.preview_label2.setStyleSheet('color:     transparent')

        # fill the scroll area
        frame.setLayout(self._grid)
        scrollArea.setWidget(frame)
        group1_vbox.addWidget(scrollArea)

        # put groups on the dialog
        this_dialog_vbox.addWidget(group1)
        this_dialog_vbox.addWidget(group2)
        this_dialog_vbox.addWidget(group0)
        self._avoid_on_loading = self._modified = False
    def createCalibrationFormGroupBox(self):
        self.calibrationForm = QGroupBox("Image Calibration")
        self.calibrationLayout = QFormLayout()

        self.slider = QSlider(Qt.Horizontal)
        self.slider.setMinimum(0)
        self.slider.setMaximum(255)
        self.slider.setValue(self.pVal)
        self.slider.setTickPosition(QSlider.TicksBelow)
        self.slider.setTickInterval(10)
        self.slider.valueChanged.connect(self.on_slidervaluechange)
        self.textSlider = QtGui.QLineEdit(str(self.pVal))

        hbox_mn = QtGui.QHBoxLayout()
        hbox_mn.addWidget(self.slider)
        hbox_mn.addWidget(self.textSlider)


        self.slider2 = QSlider(Qt.Horizontal)
        self.slider2.setMinimum(0)
        self.slider2.setMaximum(255)
        self.slider2.setValue(self.pVal_mx)
        self.slider2.setTickPosition(QSlider.TicksBelow)
        self.slider2.setTickInterval(10)
        self.slider2.valueChanged.connect(self.on_slider2valuechange)
        self.textSlider2 = QtGui.QLineEdit(str(self.pVal_mx),self.win)

        hbox_mx = QtGui.QHBoxLayout()
        hbox_mx.addWidget(self.slider2)
        hbox_mx.addWidget(self.textSlider2)

        self.ROIslider= QSlider(Qt.Horizontal)
        self.ROIslider.setMinimum(0)
        self.ROIslider.setMaximum(1000)
        self.ROIslider.setValue(self.area_mn)
        self.ROIslider.setTickPosition(QSlider.TicksBelow)
        self.ROIslider.setTickInterval(100)
        self.ROIslider.valueChanged.connect(self.on_ROIslidervaluechange)
        self.ROItextSlider = QLineEdit(str(self.area_mn))

        hbox = QtGui.QHBoxLayout()
        hbox.addWidget(self.ROIslider)
        hbox.addWidget(self.ROItextSlider)

        self.calibrationLayout.addRow(QLabel("ROI max area:"),hbox)
        self.calibrationLayout.addRow(QLabel("px min:"), hbox_mn)
        self.calibrationLayout.addRow(QLabel("px max:"), hbox_mx)

        self.calibrationForm.setLayout(self.calibrationLayout)
Beispiel #4
0
    def showdialog(self, title):
        d = QDialog(self)
        d.setFixedSize(300, 100)
        label = QLabel(self.Error, d)
        label.move(20, 20)
        self.current = os.listdir(self.files)[0][0:4]
        self.roll = QLineEdit(str(self.current), d)
        self.roll.move(50, 20)

        b1 = QPushButton("Ok",d)
        b1.move(125,50)
        d.setWindowTitle(str(title))

        b1.clicked.connect(self.process_frames)
        d.exec_()
Beispiel #5
0
 def __init__(self, parent):
     QWidget.__init__(self, parent)
     self._layout = QHBoxLayout(self)
     self._label = QLabel("Very important option", self)
     self._layout.addWidget(self._label)
     self.edit = QLineEdit(self)
     self._layout.addWidget(self.edit)
Beispiel #6
0
def test_file_dd_filter_drag_enter_event(qtbot):
    widget = QLineEdit()
    qtbot.addWidget(widget)

    mime = QMimeData()
    mime.setUrls([
        QUrl("file:///path/to/file"),
    ])
    action = Qt.CopyAction | Qt.MoveAction
    point = widget.rect().center()

    event = QDragEnterEvent(point, action, mime, Qt.LeftButton, Qt.NoModifier)

    event_filter = events.FileDragAndDropFilter()
    assert event_filter.eventFilter(widget, event)

    assert event.isAccepted()
Beispiel #7
0
class window(QMainWindow):
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent=None)
        self.files = str(QFileDialog.getExistingDirectory(self, "Select ARRIRAW Clip Directory"))
        self.Error = QString("")
        if self.files != "":
            self.showdialog("Set New Roll Number")
        sys.exit(0)

    def showdialog(self, title):
        d = QDialog(self)
        d.setFixedSize(300, 100)
        label = QLabel(self.Error, d)
        label.move(20, 20)
        self.current = os.listdir(self.files)[0][0:4]
        self.roll = QLineEdit(str(self.current), d)
        self.roll.move(50, 20)

        b1 = QPushButton("Ok",d)
        b1.move(125,50)
        d.setWindowTitle(str(title))

        b1.clicked.connect(self.process_frames)
        d.exec_()

    def process_frames(self):
        self.newRoll = str(self.roll.text()).strip()
        print self.newRoll
        os.chdir(self.files)
        for file in os.listdir(self.files):
            ari = 0
            with open(str(file), "r+b") as f:
                if str(f.read(4)) == "ARRI":
                    f.seek(1272)
                    if os.path.basename(file)[0:4] == f.read(4):
                        f.write(self.newRoll)
                        f.seek(1688)
                        f.write(self.newRoll)
                    f.close
                    ari = 1
            if ari == 1:
                os.system("mv "+str(file)+" "+str(self.newRoll)+str(file)[4:])
        controller.quit()
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)

        # self.le = QLabel()
        self.le = QLineEdit()
        self.le.setObjectName("Empty")
        self.le.setText("Empty")

        self.pb = QPushButton()
        self.pb.setObjectName("browse")
        self.pb.setText("Browse")

        layout = QHBoxLayout()
        layout.addWidget(self.le)
        layout.addWidget(self.pb)

        self.setLayout(layout)
        self.connect(self.pb, SIGNAL("clicked()"), self.button_click)
        self.setWindowTitle("Learning")
Beispiel #9
0
class HtmlBrowser(QWidget):
    def __init__(self,parent=None):
        QWidget.__init__(self,parent)
        
        self.__toolBar = QToolBar(self)
        self.__toolBar.setIconSize(QSize(16,16))
        self.__htmlBrowserView = HtmlBrowserView(self)
        self.__addressinput = QLineEdit(self)
        self.__loadlabel = QLabel(self)

        layout=QVBoxLayout(self)
        layout.setSpacing(0)
        layout.setMargin(0)
        layout.addWidget(self.__toolBar)
        layout.addWidget(self.__htmlBrowserView)
        
        self.__setupToolBarAction()
        
        QObject.connect(self.__addressinput, SIGNAL("returnPressed ()"),self.__evt_load)
        QObject.connect(self.__htmlBrowserView, SIGNAL("loadFinished (bool)"),lambda:self.__loadlabel.setMovie(None))
        QObject.connect(self.__htmlBrowserView, SIGNAL("loadStarted ()"),self.__evt_loadstarted)


    def __evt_loadstarted(self):
        if  not self.__loadlabel.movie():
            movie = QMovie(getPath('iconDir','loading.gif'), QByteArray(), self.__loadlabel)
            movie.setSpeed(50)
            self.__loadlabel.setMovie(movie)
            movie.start()

    
    def __evt_load(self):
        self.__htmlBrowserView.load(QUrl(self.__addressinput.text()))
        
    def setHtml(self,html):
        self.__htmlBrowserView.setHtml(html)
        
    def webview(self):
        return self.__htmlBrowserView
    def __setupToolBarAction(self):
        
        self.__toolBar.addAction(self.__htmlBrowserView.getActions()["pre"])
        self.__toolBar.addAction(self.__htmlBrowserView.getActions()["next"])
        self.__toolBar.addAction(self.__htmlBrowserView.getActions()["stop"])
        self.__toolBar.addAction(self.__htmlBrowserView.getActions()["reload"])
        self.__toolBar.addWidget(self.__loadlabel)
        self.__toolBar.addWidget(self.__addressinput)
        
        action = QAction(QIcon(getPath('iconDir','heditor/go.png')),"go",self,triggered=self.__evt_load)
        
        self.__toolBar.addAction(action)

        self.__toolBar.addAction(self.__htmlBrowserView.getActions()["zoomin"])
        self.__toolBar.addAction(self.__htmlBrowserView.getActions()["zoomreset"])
        self.__toolBar.addAction(self.__htmlBrowserView.getActions()["zoomout"])
    def __init__(self, parent):
        super(ThemeEditor, self).__init__(parent, Qt.Dialog)
        vbox = QVBoxLayout(self)

        hbox = QHBoxLayout()
        self.line_name = QLineEdit()
        self.btn_save = QPushButton(translations.TR_SAVE)
        self.line_name.setPlaceholderText(getuser().capitalize() + "s_theme")
        hbox.addWidget(self.line_name)
        hbox.addWidget(self.btn_save)

        self.edit_qss = QPlainTextEdit()
        css = 'QPlainTextEdit {color: %s; background-color: %s;' \
            'selection-color: %s; selection-background-color: %s;}' \
            % (resources.CUSTOM_SCHEME.get(
                'editor-text', resources.COLOR_SCHEME['Default']),
                resources.CUSTOM_SCHEME.get(
                    'EditorBackground',
                    resources.COLOR_SCHEME['EditorBackground']),
                resources.CUSTOM_SCHEME.get(
                    'EditorSelectionColor',
                    resources.COLOR_SCHEME['EditorSelectionColor']),
                resources.CUSTOM_SCHEME.get(
                    'EditorSelectionBackground',
                    resources.COLOR_SCHEME['EditorSelectionBackground']))
        self.edit_qss.setStyleSheet(css)

        self.btn_apply = QPushButton(self.tr("Apply Style Sheet"))
        hbox2 = QHBoxLayout()
        hbox2.addSpacerItem(
            QSpacerItem(10, 0, QSizePolicy.Expanding, QSizePolicy.Fixed))
        hbox2.addWidget(self.btn_apply)
        hbox2.addSpacerItem(
            QSpacerItem(10, 0, QSizePolicy.Expanding, QSizePolicy.Fixed))

        vbox.addWidget(self.edit_qss)
        vbox.addLayout(hbox)
        vbox.addLayout(hbox2)

        self.connect(self.btn_apply, SIGNAL("clicked()"),
                     self.apply_stylesheet)
        self.connect(self.btn_save, SIGNAL("clicked()"), self.save_stylesheet)
Beispiel #11
0
    def __init__(self,parent=None):
        QWidget.__init__(self,parent)
        
        self.__toolBar = QToolBar(self)
        self.__toolBar.setIconSize(QSize(16,16))
        self.__htmlBrowserView = HtmlBrowserView(self)
        self.__addressinput = QLineEdit(self)
        self.__loadlabel = QLabel(self)

        layout=QVBoxLayout(self)
        layout.setSpacing(0)
        layout.setMargin(0)
        layout.addWidget(self.__toolBar)
        layout.addWidget(self.__htmlBrowserView)
        
        self.__setupToolBarAction()
        
        QObject.connect(self.__addressinput, SIGNAL("returnPressed ()"),self.__evt_load)
        QObject.connect(self.__htmlBrowserView, SIGNAL("loadFinished (bool)"),lambda:self.__loadlabel.setMovie(None))
        QObject.connect(self.__htmlBrowserView, SIGNAL("loadStarted ()"),self.__evt_loadstarted)
    def add_item(self, key, scheme):
        """Take key and scheme arguments and fill up the grid with widgets."""
        row = self._grid.rowCount()
        self._grid.addWidget(QLabel(key), row, 0)
        isnum = isinstance(scheme[key], int)
        text = QLineEdit(str(scheme[key]))
        self._grid.addWidget(text, row, 1)
        if not isnum:
            btn = QPushButton()
            btn.setToolTip(translations.TR_EDITOR_SCHEME_PICK_COLOR)
            self.apply_button_style(btn, scheme[key])
            self._grid.addWidget(btn, row, 2)

            self.connect(text, SIGNAL("textChanged(QString)"),
                         lambda: self.apply_button_style(btn, text.text()))
            self.connect(btn, SIGNAL("clicked()"),
                         lambda: self._pick_color(text, btn))
        else:
            self.connect(text, SIGNAL("textChanged(QString)"),
                         self._preview_style)
        self._components[key] = (text, isnum)
Beispiel #13
0
class Form(QDialog):
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)
        self.browser = QTextBrowser()
        self.lineedit = QLineEdit("Type an expression and press Enter")
        self.lineedit.selectAll()
        layout = QVBoxLayout()
        layout.addWidget(self.browser)
        layout.addWidget(self.lineedit)
        self.setLayout(layout)
        self.lineedit.setFocus()
        self.lineedit.returnPressed.connect(self.updateUi)
        self.setWindowTitle("Calculate")

    def updateUi(self):
        try:
            text = unicode(self.lineedit.text())
            self.browser.append("{0} = <b>{1}</b>".format(text, eval(text)))
        except:
            self.browser.append(
                "<font color=red>{0} is invalid!</font>".format(text))
class Form(QWidget):
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)

        # self.le = QLabel()
        self.le = QLineEdit()
        self.le.setObjectName("Empty")
        self.le.setText("Empty")

        self.pb = QPushButton()
        self.pb.setObjectName("browse")
        self.pb.setText("Browse")

        layout = QHBoxLayout()
        layout.addWidget(self.le)
        layout.addWidget(self.pb)

        self.setLayout(layout)
        self.connect(self.pb, SIGNAL("clicked()"), self.button_click)
        self.setWindowTitle("Learning")

    def button_click(self):
        # absolute_path is a QString object
        absolute_path = QFileDialog.getOpenFileName(self, 'Open file', '.',
                                                    "txt files (*.txt)")
        if absolute_path:
            cur_path = QDir('.')
            relative_path = cur_path.relativeFilePath(absolute_path)
            self.le.setText(relative_path)
            print
            relative_path
Beispiel #15
0
 def __init__(self, parent):
     super(ShortcutDialog, self).__init__()
     self.keys = 0
     #Keyword modifiers!
     self.keyword_modifiers = (Qt.Key_Control, Qt.Key_Meta, Qt.Key_Shift,
                               Qt.Key_Alt, Qt.Key_Menu)
     #main layout
     main_vbox = QVBoxLayout(self)
     self.line_edit = QLineEdit()
     self.line_edit.setReadOnly(True)
     #layout for buttons
     buttons_layout = QHBoxLayout()
     ok_button = QPushButton(translations.TR_ACCEPT)
     cancel_button = QPushButton(translations.TR_CANCEL)
     #add widgets
     main_vbox.addWidget(self.line_edit)
     buttons_layout.addWidget(ok_button)
     buttons_layout.addWidget(cancel_button)
     main_vbox.addLayout(buttons_layout)
     self.line_edit.installEventFilter(self)
     #buttons signals
     self.connect(ok_button, SIGNAL("clicked()"), self.save_shortcut)
     self.connect(cancel_button, SIGNAL("clicked()"), self.close)
Beispiel #16
0
    def invoke(self):
        searchInput = QLineEdit()
        normalInput = QPlainTextEdit()
        normalInput.setMaximumHeight(100)
        searchBtn = QPushButton("Search")
        sayBtn = QPushButton("Hmm..")

        listTops = QWidget()

        layoutWidget = QGridLayout()
        layoutWidget.addWidget(searchInput, 1, 0)
        layoutWidget.addWidget(searchBtn, 1, 1)
        layoutWidget.addWidget(normalInput, 2, 0)
        layoutWidget.addWidget(sayBtn, 2, 1)
        layoutWidget.addWidget(listTops, 3, 0, 8, 1)

        self.setLayout(layoutWidget)
Beispiel #17
0
    def test_prop(self):
        w = QWidget()
        layout = QVBoxLayout()
        cb = QCheckBox("Check", w)
        sp = QSpinBox(w)
        le = QLineEdit(w)
        textw = QTextEdit(w, readOnly=True)

        textw.setProperty("checked_", False)
        textw.setProperty("spin_", 0)
        textw.setProperty("line_", "")

        textexpr = PropertyBindingExpr(r"""
("Check box is {0}\n"
 "Spin has value {1}\n"
 "Line contains {2}").format(
    "checked" if checked else "unchecked",
    spin,
    line)
""",
            dict(checked=binding_for(cb, "checked"),
                 spin=binding_for(sp, "value"),
                 line=binding_for(le, "text")),
        )

        layout.addWidget(cb)
        layout.addWidget(sp)
        layout.addWidget(le)
        layout.addWidget(textw)

        manager = BindingManager(submitPolicy=BindingManager.AutoSubmit)

        manager.bind(PropertyBinding(textw, "plainText", "textChanged"),
                     textexpr)

        w.setLayout(layout)
        w.show()

        self.app.exec_()
    def __init__(self, parent):
        super(ManualInstallWidget, self).__init__()
        self._parent = parent
        vbox = QVBoxLayout(self)
        form = QFormLayout()
        self._txtName = QLineEdit()
        self._txtName.setPlaceholderText('my_plugin')
        self._txtVersion = QLineEdit()
        self._txtVersion.setPlaceholderText('0.1')
        form.addRow(translations.TR_PROJECT_NAME, self._txtName)
        form.addRow(translations.TR_VERSION, self._txtVersion)
        vbox.addLayout(form)
        hPath = QHBoxLayout()
        self._txtFilePath = QLineEdit()
        self._txtFilePath.setPlaceholderText(
            os.path.join(os.path.expanduser('~'), 'full', 'path', 'to',
                         'plugin.zip'))
        self._btnFilePath = QPushButton(QIcon(":img/open"), '')
        self.completer, self.dirs = QCompleter(self), QDirModel(self)
        self.dirs.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot)
        self.completer.setModel(self.dirs)
        self._txtFilePath.setCompleter(self.completer)
        hPath.addWidget(QLabel(translations.TR_FILENAME))
        hPath.addWidget(self._txtFilePath)
        hPath.addWidget(self._btnFilePath)
        vbox.addLayout(hPath)
        vbox.addSpacerItem(
            QSpacerItem(0, 1, QSizePolicy.Expanding, QSizePolicy.Expanding))

        hbox = QHBoxLayout()
        hbox.addSpacerItem(QSpacerItem(1, 0, QSizePolicy.Expanding))
        self._btnInstall = QPushButton(translations.TR_INSTALL)
        hbox.addWidget(self._btnInstall)
        vbox.addLayout(hbox)

        #Signals
        self.connect(self._btnFilePath, SIGNAL("clicked()"),
                     self._load_plugin_path)
        self.connect(self._btnInstall, SIGNAL("clicked()"),
                     self.install_plugin)
Beispiel #19
0
    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)

        self.setWindowTitle("Simulation of a random walk")
        self.setFixedSize(900, 600)

        self.threadpool = QThreadPool()

        # layout
        main_layout = QHBoxLayout()
        left_layout = QVBoxLayout()
        right_layout = QVBoxLayout()

        self.label_title = QLabel("Motivational agent simulation")
        self.label_title.setAlignment(Qt.AlignCenter)
        self.label_title.setFixedHeight(20)

        # Creating the painting context
        self.scanvas = SimulationCanvas(self, 500, 500)

        left_layout.addWidget(self.label_title)
        left_layout.addWidget(self.scanvas)
        left_layout.setContentsMargins(0, 0, 0, 0)
        left_layout.setSpacing(0)

        # Right panel
        pw = 350
        ph = 150

        # self.plotView1 = pg.widgets.RemoteGraphicsView.RemoteGraphicsView()
        # self.plotView1.setFixedWidth( pw+10 )
        # self.plotView1.pg.setConfigOptions(antialias=True)

        self.plotTop = pg.PlotWidget()
        self.plotTop.setFixedWidth(pw)
        self.plotTop.setFixedHeight(ph)
        self.plotTopData = self.plotTop.plot([0], [0])
        # self.plotView1.setCentralItem( self.plotTop )

        self.plotMiddle = pg.PlotWidget()
        self.plotMiddle.setFixedWidth(pw)
        self.plotMiddle.setFixedHeight(ph)
        self.plotMiddleData = self.plotMiddle.plot([0], [0])

        self.plotBottom = pg.PlotWidget()
        self.plotBottom.setFixedWidth(pw)
        self.plotBottom.setFixedHeight(ph)
        self.plotBottomData = self.plotBottom.plot([0], [0])

        right_layout.addWidget(self.plotTop)
        right_layout.addWidget(self.plotMiddle)
        right_layout.addWidget(self.plotBottom)
        right_layout.setContentsMargins(0, 0, 0, 0)

        # Building main layour
        main_layout.setContentsMargins(0, 0, 0, 0)
        main_layout.setSpacing(0)
        main_layout.addLayout(left_layout)
        main_layout.addLayout(right_layout)

        self.widget = QWidget()
        self.widget.setLayout(main_layout)
        self.setCentralWidget(self.widget)

        toolbar = QToolBar("Some toolbar")
        self.addToolBar(toolbar)

        self.run_text = QLineEdit("10")
        self.run_text.setFixedWidth(50)
        self.run_action = QAction("Run", self)
        self.run_action.setIcon(QIcon("icons/play.png"))
        self.run_action.setStatusTip("Runs the simulation")
        self.run_action.triggered.connect(self.onRunClick)

        self.pause_action = QAction("Pause", self)
        self.pause_action.setIcon(QIcon("icons/pause.png"))
        self.pause_action.setStatusTip("Pauses the simulation")
        self.pause_action.triggered.connect(self.onPauseClick)
        self.pause_action.setEnabled(False)

        self.stop_action = QAction("Stop", self)
        self.stop_action.setIcon(QIcon("icons/stop.png"))
        self.stop_action.setStatusTip("Stops the simulation")
        self.stop_action.triggered.connect(self.onStopClick)
        self.stop_action.setEnabled(False)

        self.plots_action = QAction("Plots", self)
        self.plots_action.setIcon(QIcon("icons/plot.png"))
        self.plots_action.setStatusTip("Shows additional plots")
        self.plots_action.triggered.connect(self.onPlotsClick)

        self.screenshot_action = QAction("Screenshot", self)
        self.screenshot_action.setStatusTip("Saves screenshot")
        self.screenshot_action.triggered.connect(self.onScreenShotClick)

        # self.plots_action.setEnabled( False )

        self.foodx = QLineEdit("-20")
        self.foodx.setFixedWidth(50)
        self.foody = QLineEdit("20")
        self.foody.setFixedWidth(50)

        toolbar.addAction(self.run_action)
        toolbar.addWidget(self.run_text)
        toolbar.addWidget(QLabel("ms"))
        toolbar.addAction(self.pause_action)
        toolbar.addAction(self.stop_action)
        toolbar.addAction(self.plots_action)
        toolbar.addAction(self.screenshot_action)
        toolbar.addWidget(QLabel("Food position:"))
        toolbar.addWidget(self.foodx)
        toolbar.addWidget(self.foody)

        self.statusb = QStatusBar(self)
        self.setStatusBar(self.statusb)

        self.simulation = None
        self.signals = GraphicSignals()
        self.plots = PlotsWindow(self)

        self.agentPos = [20.0, 40.0]
class MyLiveTracker(object):
    def __init__(self, opt=1):

        ##########################
        ##### default saving directory
        ##########################
        self.default_path = '/Users/virginiarutten/Documents/deep_fish/videos'
        self.filename = 'test'
        self.ext = '.avi'

        self.dt = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")[2:]
        self.foldername = self.default_path + '/' + self.dt[:6]
        self.path = self.get_path()
        self.check_dir()

        self.save = False
        self.cameraPort = 1

        self.recording = False
        self.trialOn = False
        self.flowOn = False
        self.ARD = False

        self.trialTime = 10
        self.trialSleepTime = 10

        ##########################
        ##### Arduino settings
        ##########################
        self.flowOffDelay = 1
        self.flowOnDelay = 1

        self.imW = int(640 / 2)
        self.imH = int(360 / 2)
        self.imfps = 25

        self.trialTimer = MyTimer()
        self.trialTimer.restart()

        self.ite = 0

        self.args = self.initialise_tracking_variables()
        self.win = self.initialise_window()
        self.recorder = self.initialise_videorecorder()
        self.Tracker = self.initialise_tracker()

        ##########################
        ##### Arduino
        ##########################
        self.ARDPort = self.ArdPortComboBox.currentData()
        self.Ard = self.initialise_Ard()

        ##########################
        ##### Threads
        ##########################
        self.recordingThread = MyThread(self.start_recording)
        self.recordingThread.start()
        self.trialThread = MyThread(self.start_trial)
        self.trialThread.start()

        self.recording = True

    def check_dir(self):
        ''' check that directory of the day exisits
        and that filename is unique'''
        if not os.path.isdir(self.foldername):
            print('creating directory...')
            os.mkdir(self.foldername)
        file_num = 1
        while os.path.exists(self.path):
            print('file already exisits...\nrenaming')
            print(self.path)
            self.filename = self.filename + str(file_num)
            file_num += 1
            self.path = self.get_path()

    def initialise_tracker(self):
        self.Tracker = MyRealTimeTracker(self.args)
        return self.Tracker

    def initialise_tracking_variables(self):
        ''' default values '''

        self.keypoints = {}
        self.mvAvgFrame = None
        self.fishNum = 4
        self.area_mn = 35
        ## threshold mask value
        self.pVal = 180
        self.pVal_mx = 255
        self.text = None

        self.pre_frames = 5

        self.args = {}
        self.args['pVal'] = self.pVal
        self.args['pVal_mx'] = self.pVal_mx
        self.args['fishNum'] = self.fishNum
        self.args['area_mn'] = self.area_mn
        self.args['keypoints'] = self.keypoints
        self.args['pre_frames'] = self.pre_frames
        return self.args

    def get_path(self):
        return self.foldername + '/' + self.dt + self.filename + self.ext

    def initialise_videorecorder(self):
        ''' initialises recorder'''
        self.num_saved_frame = 0
        self.cameraPort = self.cameraComboBox.currentIndex()
        self.check_dir()
        if self.path[-3:] != 'avi':
            print('please check extension')

        print('initialising recording...\noutput file:{0}'.\
             format(self.path))

        self.recorder = MyVideoRecorder(cameraport = self.cameraPort,\
                                        path = self.path,\
                                        imH = self.imH,\
                                        imW = self.imW,\
                                       fps = self.imfps)

        wasrecording = False
        if self.recording:
            wasrecording = True
            self.recording = False

        self.recorder.initialise_camera()  ### reinitialise camera
        self.camera = self.recorder.camera  ### test camera works
        if self.camera.grab() == False:
            if self.cameraPort == 1:
                self.cameraPort = 0
                self.cameraComboBox.setCurrentIndex(self.cameraPort)
                print('no camera detected... camera changed')
        if wasrecording:
            self.recording = True
        else:
            self.recording = False
            wasrecording = False

        return self.recorder

    def initialise_Ard(self):
        try:
            self.Ard = MyArduino()
            self.ARDport = self.Ard.port
            self.ARD = True
        except:
            print('no valid port found \nplease check')
            self.ARD = False
        return self.Ard

    def load_picture(self):
        file_path = '/Users/virginiarutten/Documents/deep_fish/assets/pavlov_dog.jpg'
        self.bkImage = np.array(Image.open(file_path)).T

    def initialise_window(self):
        self.load_picture()
        self.app = QApplication([])
        self.win = MyQtWidget()

        #####################################
        ## Layout
        #####################################
        self.layout = QGridLayout()
        self.win.setLayout(self.layout)

        self.createRecordGroupBox()
        self.createDefaultGroupBox()
        self.createImageGroupBox()
        self.createSwitchFormGroupBox()
        self.createCalibrationFormGroupBox()
        self.createParamGroupBox()
        self.createPumpGroupBox()
        self.createTextGroupBox()
        self.resetPath()

        self.layout.addWidget(self.imageForm, 0, 0, 1, 3)

        self.layout.addWidget(self.textForm, 0, 4, 1, 3)

        self.layout.addWidget(self.paramForm, 2, 0, 1, 1)
        self.layout.addWidget(self.calibrationForm, 2, 1, 1, 1)
        self.layout.addWidget(self.pumpForm, 2, 2, 1, 1)

        self.layout.addWidget(self.switchForm, 3, 1, 1, 1)
        self.layout.addWidget(self.defaultForm, 3, 2, 1, 1)
        self.layout.addWidget(self.recordForm, 3, 0, 1, 1)

        self.win.show()
        return self.win

    def createImageGroupBox(self):
        self.imageForm = QGroupBox('Imaging')
        self.imageLayout = QGridLayout()

        ##raw image
        self.imv1 = RawImageWidget(scaled=True)
        ## tracking
        self.imv2 = RawImageWidget(scaled=True)
        ## mask
        self.imv3 = RawImageWidget(scaled=True)
        ## avergae
        self.imv4 = RawImageWidget(scaled=True)

        ## set background image
        self.imv1.setImage(self.bkImage)

        self.imageLayout.addWidget(QLabel("Raw:"), 0, 0, 1, 1)
        self.imageLayout.addWidget(QLabel("Detection:"), 0, 1, 1, 1)
        self.imageLayout.addWidget(self.imv1, 1, 0, 1, 1)
        self.imageLayout.addWidget(self.imv2, 1, 1, 1, 1)
        self.imageLayout.addWidget(QLabel("Mask:"), 2, 0, 1, 1)
        self.imageLayout.addWidget(QLabel("Moving average:"), 2, 1, 1, 1)
        self.imageLayout.addWidget(self.imv3, 3, 0, 1, 1)
        self.imageLayout.addWidget(self.imv4, 3, 1, 1, 1)

        self.imageForm.setLayout(self.imageLayout)

    def createTextGroupBox(self):
        self.textForm = QGroupBox('Imaging')
        self.textLayout = QFormLayout()

        ## parameters
        self.maxArea_box = QtGui.QLineEdit()
        self.num_detected_box = QtGui.QLineEdit()
        self.maxArea_box.setText('0')
        self.num_detected_box.setText('0')

        hbox = QtGui.QHBoxLayout()
        hbox.addWidget(QLabel("max area:"))
        hbox.addWidget(self.maxArea_box)
        hboxD = QtGui.QHBoxLayout()
        hboxD.addWidget(QLabel("fish #:"))
        hboxD.addWidget(self.num_detected_box)

        self.textLayout.addRow(hbox)
        self.textLayout.addRow(hboxD)

        self.textForm.setLayout(self.textLayout)

    def createSwitchFormGroupBox(self):
        self.switchForm = QGroupBox("Controller")
        self.switchLayout = QFormLayout()

        ######################
        #### Trial/Lights
        #####################

        self.lightOn_btn = QtGui.QPushButton('Light On', self.win)
        self.lightOn_btn.clicked.connect(self.on_lightOn)

        self.lightOff_btn = QtGui.QPushButton('Light Off', self.win)
        self.lightOff_btn.clicked.connect(self.on_lightOff)

        self.trialOn_btn = QtGui.QPushButton('Start Trial', self.win)
        self.trialOn_btn.clicked.connect(self.on_trialOn)

        self.trialOff_btn = QtGui.QPushButton('Stop Trial', self.win)
        self.trialOff_btn.clicked.connect(self.on_trialOff)
        self.switchLayout.addRow(self.lightOn_btn, self.lightOff_btn)
        self.switchLayout.addRow(self.trialOn_btn, self.trialOff_btn)

        self.switchForm.setLayout(self.switchLayout)

    def createCalibrationFormGroupBox(self):
        self.calibrationForm = QGroupBox("Image Calibration")
        self.calibrationLayout = QFormLayout()

        self.slider = QSlider(Qt.Horizontal)
        self.slider.setMinimum(0)
        self.slider.setMaximum(255)
        self.slider.setValue(self.pVal)
        self.slider.setTickPosition(QSlider.TicksBelow)
        self.slider.setTickInterval(10)
        self.slider.valueChanged.connect(self.on_slidervaluechange)
        self.textSlider = QtGui.QLineEdit(str(self.pVal))

        hbox_mn = QtGui.QHBoxLayout()
        hbox_mn.addWidget(self.slider)
        hbox_mn.addWidget(self.textSlider)

        self.slider2 = QSlider(Qt.Horizontal)
        self.slider2.setMinimum(0)
        self.slider2.setMaximum(255)
        self.slider2.setValue(self.pVal_mx)
        self.slider2.setTickPosition(QSlider.TicksBelow)
        self.slider2.setTickInterval(10)
        self.slider2.valueChanged.connect(self.on_slider2valuechange)
        self.textSlider2 = QtGui.QLineEdit(str(self.pVal_mx), self.win)

        hbox_mx = QtGui.QHBoxLayout()
        hbox_mx.addWidget(self.slider2)
        hbox_mx.addWidget(self.textSlider2)

        self.ROIslider = QSlider(Qt.Horizontal)
        self.ROIslider.setMinimum(0)
        self.ROIslider.setMaximum(1000)
        self.ROIslider.setValue(self.area_mn)
        self.ROIslider.setTickPosition(QSlider.TicksBelow)
        self.ROIslider.setTickInterval(100)
        self.ROIslider.valueChanged.connect(self.on_ROIslidervaluechange)
        self.ROItextSlider = QLineEdit(str(self.area_mn))

        hbox = QtGui.QHBoxLayout()
        hbox.addWidget(self.ROIslider)
        hbox.addWidget(self.ROItextSlider)

        self.calibrationLayout.addRow(QLabel("ROI max area:"), hbox)
        self.calibrationLayout.addRow(QLabel("px min:"), hbox_mn)
        self.calibrationLayout.addRow(QLabel("px max:"), hbox_mx)

        self.calibrationForm.setLayout(self.calibrationLayout)

    def createPumpGroupBox(self):
        self.pumpForm = QGroupBox("Pump settings")
        self.pumpFormLayout = QFormLayout()

        self.flowOff1_btn = QtGui.QPushButton('Increase')
        self.flowOff0_btn = QtGui.QPushButton('Decrease')

        self.flowOn1_btn = QtGui.QPushButton('Increase')
        self.flowOn0_btn = QtGui.QPushButton('Decrease')

        self.flowOn1_btn.clicked.connect(self.on_flowOn1)
        self.flowOn0_btn.clicked.connect(self.on_flowOn0)
        self.flowOff1_btn.clicked.connect(self.on_flowOff1)
        self.flowOff0_btn.clicked.connect(self.on_flowOff0)

        self.ardReset_btn = QtGui.QPushButton('reset flow')
        self.ardReset_btn.clicked.connect(self.on_ARDreset)

        hbox = QtGui.QHBoxLayout()
        hbox.addWidget(self.flowOn0_btn)
        hbox.addWidget(self.flowOn1_btn)

        hboxOff = QtGui.QHBoxLayout()
        hboxOff.addWidget(self.flowOff0_btn)
        hboxOff.addWidget(self.flowOff1_btn)

        self.pumpFormLayout.addRow(QLabel("On time:"), hbox)
        self.pumpFormLayout.addRow(QLabel("Off time:"), hboxOff)
        self.pumpFormLayout.addRow(self.ardReset_btn)
        self.pumpForm.setLayout(self.pumpFormLayout)

    def createParamGroupBox(self):
        self.paramForm = QGroupBox("Trial parameters")
        self.paramFormLayout = QFormLayout()

        self.Timer_tbox = QtGui.QLineEdit()

        self.trialTime_tbox = QtGui.QLineEdit()
        self.trialTime_tbox.textChanged.connect(self.on_trialTime_changed)
        self.trialSleepTime_tbox = QtGui.QLineEdit()
        self.trialSleepTime_tbox.textChanged.connect(
            self.on_trialSleepTime_changed)
        self.trialTime_tbox.setText(str(self.trialTime))
        self.trialSleepTime_tbox.setText(str(self.trialSleepTime))
        self.Timer_tbox.setText(str(0))

        self.paramFormLayout.addRow(QLabel("Trial time:"), self.trialTime_tbox)
        self.paramFormLayout.addRow(QLabel("Stimulus time:"),
                                    self.trialSleepTime_tbox)

        self.paramFormLayout.addRow(QLabel("Time left:"), self.Timer_tbox)

        self.paramFormLayout.addRow(QLabel("Time:"), QSpinBox())
        self.paramForm.setLayout(self.paramFormLayout)

    def createDefaultGroupBox(self):
        self.defaultForm = QtGui.QGroupBox("Video capture")
        self.defaultFormLayout = QFormLayout()

        self.ArdPortComboBox = QComboBox()
        self.ArdPortComboBox.addItem("Port 14511", '/dev/cu.usbmodem14511')
        self.ArdPortComboBox.addItem("Port 14311", '/dev/cu.usbmodem14311')
        self.ArdPortComboBox.addItem("Port 1461", '/dev/cu.usbmodem1461')
        self.ArdPortComboBox.currentIndexChanged.connect(self.on_setARDport)

        self.cameraComboBox = QComboBox()
        self.cameraComboBox.addItem("0", '0')
        self.cameraComboBox.addItem("1", '1')
        self.cameraComboBox.currentIndexChanged.connect(self.on_setcameraport)

        self.start_btn = QtGui.QPushButton('start')
        self.start_btn.clicked.connect(self.on_start)

        ## stop flow button
        self.stop_btn = QtGui.QPushButton('stop')
        self.stop_btn.clicked.connect(self.on_stop)

        ## quit app button
        self.qbtn = QtGui.QPushButton('exit')
        self.qbtn.clicked.connect(self.on_quit)
        self.qbtn.clicked.connect(QtCore.QCoreApplication.instance().quit)

        hbox = QtGui.QHBoxLayout()
        hbox.addWidget(self.start_btn)
        hbox.addWidget(self.stop_btn)
        hbox.addWidget(self.qbtn)

        self.defaultFormLayout.addRow(hbox)

        self.defaultFormLayout.addRow(QLabel("Arduino Port:"),\
                                     self.ArdPortComboBox)

        self.defaultFormLayout.addRow(QLabel("camera:"),\
                                     self.cameraComboBox)

        self.defaultForm.setLayout(self.defaultFormLayout)

    def createRecordGroupBox(self):
        self.recordForm = QtGui.QGroupBox("Video capture")
        self.recordFormLayout = QFormLayout()

        self.path_bx = QtGui.QLineEdit()
        self.resetPath()

        self.file_btn = QtGui.QPushButton("save to")
        self.file_btn.clicked.connect(self.on_getfile)

        self.file_bx = QtGui.QLineEdit()
        self.file_bx.textChanged.connect(self.on_fileChange)
        self.file_bx.setText(self.filename)

        self.save_btn = QtGui.QCheckBox()
        self.save_btn.setChecked(self.save)
        self.save_btn.stateChanged.connect(self.on_saveClick)

        hbox = QtGui.QHBoxLayout()
        self.recordFormLayout.addRow(self.file_btn, self.file_bx)
        self.recordFormLayout.addRow(QLabel("path:"), self.path_bx)
        self.recordFormLayout.addRow(QLabel("save:"), self.save_btn)

        self.recordForm.setLayout(self.recordFormLayout)

    #################
    ### slots
    ################

    @pyqtSlot()
    def on_getfile(self):
        self.foldername = QtGui.QFileDialog.getExistingDirectory()
        self.resetPath()

    @pyqtSlot()
    def on_fileChange(self):
        self.filename = self.file_bx.text()
        self.resetPath()

    @pyqtSlot()
    def on_setcameraport(self):
        self.initialise_videorecorder()

    @pyqtSlot()
    def on_trialTime_changed(self):
        try:
            self.trialTime = int(self.trialTime_tbox.text())

        except:
            self.trialTime_tbox.setText(str(1))
            print('only integrs valid')

    @pyqtSlot()
    def on_trialSleepTime_changed(self):
        try:
            self.trialSleepTime = int(self.trialSleepTime_tbox.text())
        except:
            self.trialSleepTime_tbox.setText(str(1))
            print('only integrs valid')

    @pyqtSlot()
    def on_setARDport(self):
        pass

    #  if self.ARD:
    #      self.ARDPort = self.ArdPortComboBox.currentData()
    #      print('ARD port set to ={0}'.format(self.ARDPort))
    #  else:
    #      print('no ARD detected')

    @pyqtSlot()
    def on_trialOn(self):
        print('trial starting')
        self.flowOn = False
        self.resetARD()
        self.trialTimer.restart()
        self.trialOn = True

    @pyqtSlot()
    def on_trialOff(self):
        print('trial ended')
        self.trialTimer.restart()
        self.trialOn = False
        self.flowOn = False
        self.resetARD()

    @pyqtSlot()
    def on_ARDreset(self):
        print('resetting ARD')
        self.resetFlowRate()

    @pyqtSlot()
    def on_flowOn1(self):
        print('changing flow rate')
        try:
            self.Ard.sendChar('u')
            self.resetARD()
        except:
            pass

    @pyqtSlot()
    def on_flowOn0(self):
        print('changing flow rate')
        try:
            self.Ard.sendChar('d')
            self.resetARD()
        except:
            pass

    @pyqtSlot()
    def on_flowOff1(self):
        print('changing flow rate')
        try:
            self.Ard.sendChar('k')
            self.resetARD()
        except:
            pass

    @pyqtSlot()
    def on_flowOff0(self):
        print('changing flow rate')
        try:
            self.Ard.sendChar('j')
            self.resetARD()
        except:
            pass

    @pyqtSlot()
    def on_lightOn(self):
        self.flowOn = True
        self.resetARD()

    @pyqtSlot()
    def on_lightOff(self):
        self.flowOn = False
        self.resetARD()

    @pyqtSlot()
    def on_slidervaluechange(self):
        self.pVal = int(self.slider.value())
        self.Tracker.pVal = self.pVal
        self.textSlider.setText(str(self.pVal))

    @pyqtSlot()
    def on_slider2valuechange(self):
        self.pVal_mx = int(self.slider2.value())
        self.Tracker.pVal_mx = self.pVal_mx
        self.textSlider2.setText(str(self.pVal_mx))

    @pyqtSlot()
    def on_ROIslidervaluechange(self):
        self.area_mn = int(self.ROIslider.value())
        self.Tracker.area_mn = self.area_mn
        self.ROItextSlider.setText(str(self.area_mn))

    @pyqtSlot()
    def on_start(self):
        if self.recording:
            print('current recording being stopping...')
            print('number of previously saved frames:\n{0}'.\
                  format(self.num_saved_frame))

            self.recording = False
            sleep(0.02)
            try:
                self.recorder.release_writer()
            except:
                pass
            sleep(0.02)
        print('new recording starting...')
        self.initialise_videorecorder()
        self.recording = True

    @pyqtSlot()
    def on_saveClick(self):
        self.on_start()
        if self.save_btn.isChecked():
            try:
                self.recorder.initialise_writer()
                print('writer initialised')
                sleep(0.02)
                self.save = self.save_btn.isChecked()
            except:
                print('couldn\'t initialise writer')
        else:
            try:
                self.recorder.release_writer()
            except:
                print('couldn\'t release writer')
                pass

    @pyqtSlot()
    def on_stop(self):
        print('current recording being stopping...')
        print('number of previously saved frames:\n{0}'.\
                  format(self.num_saved_frame))
        self.recording = False
        self.save = False
        self.save_btn.setChecked(self.save)

        try:
            self.recorder.release_writer()
            self.num_saved_frame = 0
        except:
            pass

    @pyqtSlot()
    def on_ROIinit(self):
        print('initiliase ROI')
        self.initialise_ROI()

    @pyqtSlot()
    def on_quit(self):
        print('stopping threads...')
        self.flowOn = False
        self.resetARD()
        self.recording = False
        self.trialOn = False
        sleep(0.5)
        print('number saved frames:\n{0}'.\
                  format(self.num_saved_frame))
        try:
            self.recorder.release_writer()
        except:
            pass
        try:
            self.recorder.release_camera()
        except:
            pass

        self.recordingThread.stop()
        self.trialThread.stop()

    def resetARD(self):
        if self.flowOn == False:
            if self.ARD:
                print('0')
                self.Ard.sendChar('0')
        if self.flowOn == True:
            if self.ARD:
                self.Ard.sendChar('1')

    def resetFlowRate(self):
        if self.ARD:
            self.Ard.sendChar('r')
            self.resetARD()

    def resetPath(self):
        self.dt = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")[2:]
        self.path = self.get_path()
        self.path_bx.setText(self.path)

    def kill_threads(self):
        self.recording = False
        self.trialOn = False

    def start_recording(self):
        while self.recording:
            self.frame_loop()

    def start_trial(self):
        while self.trialOn:
            self.trial_loop()

    ##########################
    ##### Thread functions
    ##########################
    def trial_loop(self):
        time_ = self.trialTimer.get_time()
        self.time_left = self.trialTime - int(time_)
        self.Timer_tbox.setText(str(self.time_left))
        if time_ > self.trialTime:
            print('new trial')
            self.flowOn = True
            self.resetARD()
            sleep(int(self.trialSleepTime))
            self.flowOn = False
            self.resetARD()
            self.trialTimer.restart()

    def frame_loop(self):
        self.gray = self.grab_frame()
        self.blur = self.Tracker.blur_frame(self.gray)
        self.mvAvgFrame = self.update_avg()
        self.fD = self.Tracker.delta_frame(self.mvAvgFrame, self.blur)

        self.mask, self.masked = self.Tracker.mask_frame(self.fD,
                                                         pVal=self.pVal,
                                                         pVal_mx=self.pVal_mx)

        self.fD_, self.keypoints, self.num_fish_detected, self.max_a\
        = self.Tracker.get_frame_contours(self.masked, self.fD)

        self.maxArea_box.setText(str(self.max_a))
        self.num_detected_box.setText(str(self.num_fish_detected))

        if self.save:
            self.num_saved_frame += 1
            try:
                self.recorder.save_frame(self.gray)
            except:
                print('couldn\'t save file')
        self.show_frame()

    ##########################
    ##### detection functions
    ##########################

    def grab_frame(self):
        try:
            (grabbed, frame) = self.camera.read()
            self.frame = cv2.resize(frame, (self.imW, self.imH))
            self.gray = cv2.cvtColor(self.frame, cv2.COLOR_BGR2GRAY)
            #self.frame = cv2.cvtColor(self.frame , cv2.COLOR_BGR2HSV)[:,:,1] # saturation
        except:
            print('couldn\'t grab frame')
            pass
        return self.gray

    def update_avg(self):
        if self.mvAvgFrame is None:
            self.mvAvgFrame = self.blur
        else:
            self.ite += 1
            fr = self.ite
            if fr > 10000:
                print('reset')
                self.ite = 1
                self.mvAvgFrame = self.mvAvgFrame
            else:
                self.mvAvgFrame = self.mvAvgFrame * (
                    fr / (fr + 1)) + self.blur / (fr + 1)
        return self.mvAvgFrame

    def show_frame(self):
        if self.ite % 4 == 0:
            self.imv1.setImage(self.gray.T)
        elif self.ite % 4 == 1:
            self.imv4.setImage(self.mvAvgFrame.T.astype('uint8'))
        elif self.ite % 4 == 2:
            self.imv2.setImage(self.fD_.swapaxes(0, 1))
        elif self.ite % 4 == 3:
            self.imv3.setImage(self.mask.T)
class ThemeEditor(QDialog):
    """ThemeEditor Scheme Designer Class Widget"""
    def __init__(self, parent):
        super(ThemeEditor, self).__init__(parent, Qt.Dialog)
        vbox = QVBoxLayout(self)

        hbox = QHBoxLayout()
        self.line_name = QLineEdit()
        self.btn_save = QPushButton(translations.TR_SAVE)
        self.line_name.setPlaceholderText(getuser().capitalize() + "s_theme")
        hbox.addWidget(self.line_name)
        hbox.addWidget(self.btn_save)

        self.edit_qss = QPlainTextEdit()
        css = 'QPlainTextEdit {color: %s; background-color: %s;' \
            'selection-color: %s; selection-background-color: %s;}' \
            % (resources.CUSTOM_SCHEME.get(
                'editor-text', resources.COLOR_SCHEME['Default']),
                resources.CUSTOM_SCHEME.get(
                    'EditorBackground',
                    resources.COLOR_SCHEME['EditorBackground']),
                resources.CUSTOM_SCHEME.get(
                    'EditorSelectionColor',
                    resources.COLOR_SCHEME['EditorSelectionColor']),
                resources.CUSTOM_SCHEME.get(
                    'EditorSelectionBackground',
                    resources.COLOR_SCHEME['EditorSelectionBackground']))
        self.edit_qss.setStyleSheet(css)

        self.btn_apply = QPushButton(self.tr("Apply Style Sheet"))
        hbox2 = QHBoxLayout()
        hbox2.addSpacerItem(
            QSpacerItem(10, 0, QSizePolicy.Expanding, QSizePolicy.Fixed))
        hbox2.addWidget(self.btn_apply)
        hbox2.addSpacerItem(
            QSpacerItem(10, 0, QSizePolicy.Expanding, QSizePolicy.Fixed))

        vbox.addWidget(self.edit_qss)
        vbox.addLayout(hbox)
        vbox.addLayout(hbox2)

        self.connect(self.btn_apply, SIGNAL("clicked()"),
                     self.apply_stylesheet)
        self.connect(self.btn_save, SIGNAL("clicked()"), self.save_stylesheet)

    def apply_stylesheet(self):
        qss = self.edit_qss.toPlainText()
        QApplication.instance().setStyleSheet(qss)

    def save_stylesheet(self):
        try:
            file_name = "%s.qss" % self.line_name.text()
            if not self._is_valid_scheme_name(file_name):
                QMessageBox.information(self,
                                        translations.TR_PREFERENCES_THEME,
                                        translations.TR_SCHEME_INVALID_NAME)
            file_name = ('{0}.qss'.format(
                file_manager.create_path(resources.NINJA_THEME_DOWNLOAD,
                                         file_name)))
            content = self.edit_qss.toPlainText()
            answer = True
            if file_manager.file_exists(file_name):
                answer = QMessageBox.question(
                    self, translations.TR_PREFERENCES_THEME,
                    translations.TR_WANT_OVERWRITE_FILE +
                    ": {0}?".format(file_name), QMessageBox.Yes,
                    QMessageBox.No)

            if answer in (QMessageBox.Yes, True):
                self.apply_stylesheet()
                file_manager.store_file_content(file_name,
                                                content,
                                                newFile=True)
                self.close()
        except file_manager.NinjaFileExistsException as ex:
            QMessageBox.information(
                self, self.tr("File Already Exists"),
                (self.tr("Invalid File Name: the file '%s' already exists.") %
                 ex.filename))

    def _is_valid_scheme_name(self, name):
        """Check if a given name is a valid name for an editor scheme.
        Params:
            name := the name to check
        Returns:
            True if and only if the name is okay to use for a scheme. """
        return name not in ('', 'Default')
class ManualInstallWidget(QWidget):
    """Manually Installed plugins widget"""
    def __init__(self, parent):
        super(ManualInstallWidget, self).__init__()
        self._parent = parent
        vbox = QVBoxLayout(self)
        form = QFormLayout()
        self._txtName = QLineEdit()
        self._txtName.setPlaceholderText('my_plugin')
        self._txtVersion = QLineEdit()
        self._txtVersion.setPlaceholderText('0.1')
        form.addRow(translations.TR_PROJECT_NAME, self._txtName)
        form.addRow(translations.TR_VERSION, self._txtVersion)
        vbox.addLayout(form)
        hPath = QHBoxLayout()
        self._txtFilePath = QLineEdit()
        self._txtFilePath.setPlaceholderText(
            os.path.join(os.path.expanduser('~'), 'full', 'path', 'to',
                         'plugin.zip'))
        self._btnFilePath = QPushButton(QIcon(":img/open"), '')
        self.completer, self.dirs = QCompleter(self), QDirModel(self)
        self.dirs.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot)
        self.completer.setModel(self.dirs)
        self._txtFilePath.setCompleter(self.completer)
        hPath.addWidget(QLabel(translations.TR_FILENAME))
        hPath.addWidget(self._txtFilePath)
        hPath.addWidget(self._btnFilePath)
        vbox.addLayout(hPath)
        vbox.addSpacerItem(
            QSpacerItem(0, 1, QSizePolicy.Expanding, QSizePolicy.Expanding))

        hbox = QHBoxLayout()
        hbox.addSpacerItem(QSpacerItem(1, 0, QSizePolicy.Expanding))
        self._btnInstall = QPushButton(translations.TR_INSTALL)
        hbox.addWidget(self._btnInstall)
        vbox.addLayout(hbox)

        #Signals
        self.connect(self._btnFilePath, SIGNAL("clicked()"),
                     self._load_plugin_path)
        self.connect(self._btnInstall, SIGNAL("clicked()"),
                     self.install_plugin)

    def _load_plugin_path(self):
        """Ask the user a plugin filename"""
        path = QFileDialog.getOpenFileName(self,
                                           translations.TR_SELECT_PLUGIN_PATH)
        if path:
            self._txtFilePath.setText(path)

    def install_plugin(self):
        """Install a plugin manually"""
        if self._txtFilePath.text() and self._txtName.text():
            plug = []
            plug.append(self._txtName.text())
            plug.append(self._txtVersion.text())
            plug.append('')
            plug.append('')
            plug.append('')
            plug.append(self._txtFilePath.text())
            self._parent.install_plugins_manually([plug])
class EditorSchemeDesigner(QDialog):
    """Editor Scheme Designer Class Widget"""
    def __init__(self, scheme, parent):
        super(EditorSchemeDesigner, self).__init__(parent, Qt.Dialog)
        self.original_style = copy.copy(resources.CUSTOM_SCHEME)
        self._avoid_on_loading, self.saved, self._components = True, False, {}
        self.setWindowTitle(translations.TR_PREFERENCES_EDITOR_SCHEME_DESIGNER)
        self.setMinimumSize(450, 480)
        self.setMaximumSize(500, 900)
        self.resize(450, 600)

        # all layouts and groupboxes
        group0 = QGroupBox(translations.TR_PROJECT_NAME)  # scheme filename
        group1 = QGroupBox(translations.TR_PROJECT_PROPERTIES)  # properties
        group2 = QGroupBox(translations.TR_PREVIEW)  # quick preview thingy
        group0_hbox, group1_vbox = QHBoxLayout(group0), QVBoxLayout(group1)
        this_dialog_vbox, group2_vbox = QVBoxLayout(self), QVBoxLayout(group2)
        self._grid, scrollArea, frame = QGridLayout(), QScrollArea(), QFrame()

        # widgets
        self.line_name, btnSave = QLineEdit(), QPushButton(
            translations.TR_SAVE)
        self.line_name.setPlaceholderText(getuser().capitalize() + "s_scheme")
        group0_hbox.addWidget(self.line_name)
        group0_hbox.addWidget(btnSave)
        self.connect(btnSave, SIGNAL("clicked()"), self.save_scheme)
        _demo = "<center>" + ascii_letters  # demo text for preview
        self.preview_label1, self.preview_label2 = QLabel(_demo), QLabel(_demo)
        group2_vbox.addWidget(self.preview_label1)
        group2_vbox.addWidget(self.preview_label2)

        # rows titles
        self._grid.addWidget(QLabel("<b>" + translations.TR_PROJECT_NAME), 0,
                             0)
        self._grid.addWidget(QLabel("<b>" + translations.TR_CODE), 0, 1)
        self._grid.addWidget(
            QLabel("<b>" + translations.TR_EDITOR_SCHEME_PICK_COLOR), 0, 2)

        # fill rows
        for key in sorted(tuple(resources.COLOR_SCHEME.keys())):
            self.add_item(key, scheme)
        self.preview_label1.setStyleSheet('background:transparent')
        self.preview_label2.setStyleSheet('color:     transparent')

        # fill the scroll area
        frame.setLayout(self._grid)
        scrollArea.setWidget(frame)
        group1_vbox.addWidget(scrollArea)

        # put groups on the dialog
        this_dialog_vbox.addWidget(group1)
        this_dialog_vbox.addWidget(group2)
        this_dialog_vbox.addWidget(group0)
        self._avoid_on_loading = self._modified = False

    def add_item(self, key, scheme):
        """Take key and scheme arguments and fill up the grid with widgets."""
        row = self._grid.rowCount()
        self._grid.addWidget(QLabel(key), row, 0)
        isnum = isinstance(scheme[key], int)
        text = QLineEdit(str(scheme[key]))
        self._grid.addWidget(text, row, 1)
        if not isnum:
            btn = QPushButton()
            btn.setToolTip(translations.TR_EDITOR_SCHEME_PICK_COLOR)
            self.apply_button_style(btn, scheme[key])
            self._grid.addWidget(btn, row, 2)

            self.connect(text, SIGNAL("textChanged(QString)"),
                         lambda: self.apply_button_style(btn, text.text()))
            self.connect(btn, SIGNAL("clicked()"),
                         lambda: self._pick_color(text, btn))
        else:
            self.connect(text, SIGNAL("textChanged(QString)"),
                         self._preview_style)
        self._components[key] = (text, isnum)

    def apply_button_style(self, btn, color_name):
        """Take a button widget and color name and apply as stylesheet."""
        if QColor(color_name).isValid():
            self._modified = True
            btn.setStyleSheet('background:' + color_name)
            self.preview_label1.setStyleSheet('background:' + color_name)
            self.preview_label2.setStyleSheet('color:' + color_name)
            self._preview_style()

    def _pick_color(self, lineedit, btn):
        """Pick a color name using lineedit and button data."""
        color = QColorDialog.getColor(QColor(lineedit.text()), self,
                                      translations.TR_EDITOR_SCHEME_PICK_COLOR)
        if color.isValid():
            lineedit.setText(str(color.name()))
            self.apply_button_style(btn, color.name())

    def _preview_style(self):
        """Live preview style on editor."""
        if self._avoid_on_loading:
            return
        scheme = {}
        keys = sorted(tuple(resources.COLOR_SCHEME.keys()))
        for key in keys:
            isnum = self._components[key][1]
            if isnum:
                num = self._components[key][0].text()
                if num.isdigit():
                    scheme[key] = int(num)
                else:
                    scheme[key] = 0
            else:
                scheme[key] = self._components[key][0].text()
        resources.CUSTOM_SCHEME = scheme
        editorWidget = self._get_editor()
        if editorWidget is not None:
            editorWidget.restyle(editorWidget.lang)
            editorWidget.highlight_current_line()
        return scheme

    def _get_editor(self):
        """Return current Editor."""
        main_container = IDE.get_service("main_container")
        editorWidget = main_container.get_current_editor()
        return editorWidget

    def reject(self):
        """Reject this dialog."""
        if self._modified:
            answer = QMessageBox.No
            answer = QMessageBox.question(
                self, translations.TR_PREFERENCES_EDITOR_SCHEME_DESIGNER,
                (translations.TR_IDE_CONFIRM_EXIT_TITLE + ".\n" +
                 translations.TR_PREFERENCES_GENERAL_CONFIRM_EXIT + "?"),
                QMessageBox.Yes, QMessageBox.No)
            if answer == QMessageBox.No:
                return
        super(EditorSchemeDesigner, self).reject()

    def hideEvent(self, event):
        """Handle Hide event on this dialog."""
        super(EditorSchemeDesigner, self).hideEvent(event)
        resources.CUSTOM_SCHEME = self.original_style
        editorWidget = self._get_editor()
        if editorWidget is not None:
            editorWidget.restyle(editorWidget.lang)

    def _is_valid_scheme_name(self, name):
        """Check if a given name is a valid name for an editor scheme.
        Params:
            name := the name to check
        Returns:
            True if and only if the name is okay to use for a scheme. """
        return name not in ('', 'default')

    def save_scheme(self):
        """Save current scheme."""
        name = self.line_name.text().strip()
        if not self._is_valid_scheme_name(name):
            QMessageBox.information(
                self, translations.TR_PREFERENCES_EDITOR_SCHEME_DESIGNER,
                translations.TR_SCHEME_INVALID_NAME)
            return
        fileName = ('{0}.color'.format(
            file_manager.create_path(resources.EDITOR_SKINS, name)))
        answer = True
        if file_manager.file_exists(fileName):
            answer = QMessageBox.question(
                self, translations.TR_PREFERENCES_EDITOR_SCHEME_DESIGNER,
                translations.TR_WANT_OVERWRITE_FILE +
                ": {0}?".format(fileName), QMessageBox.Yes, QMessageBox.No)

        if answer in (QMessageBox.Yes, True):
            scheme = self._preview_style()
            self.original_style = copy.copy(scheme)
            json_manager.save_editor_skins(fileName, scheme)
            self._modified = False
            self.saved = True
            qsettings = IDE.ninja_settings()
            qsettings.setValue('preferences/editor/scheme', name)
            QMessageBox.information(
                self, translations.TR_PREFERENCES_EDITOR_SCHEME_DESIGNER,
                translations.TR_SCHEME_SAVED + ": {0}.".format(fileName))
            self.close()
        elif answer == QMessageBox.Yes:
            QMessageBox.information(
                self, translations.TR_PREFERENCES_EDITOR_SCHEME_DESIGNER,
                translations.TR_INVALID_FILENAME)
Beispiel #24
0
class ShortcutDialog(QDialog):
    """
    Dialog to set a shortcut for an action
    this class emit the follow signals:
        shortcutChanged(QKeySequence)
    """
    def __init__(self, parent):
        super(ShortcutDialog, self).__init__()
        self.keys = 0
        #Keyword modifiers!
        self.keyword_modifiers = (Qt.Key_Control, Qt.Key_Meta, Qt.Key_Shift,
                                  Qt.Key_Alt, Qt.Key_Menu)
        #main layout
        main_vbox = QVBoxLayout(self)
        self.line_edit = QLineEdit()
        self.line_edit.setReadOnly(True)
        #layout for buttons
        buttons_layout = QHBoxLayout()
        ok_button = QPushButton(translations.TR_ACCEPT)
        cancel_button = QPushButton(translations.TR_CANCEL)
        #add widgets
        main_vbox.addWidget(self.line_edit)
        buttons_layout.addWidget(ok_button)
        buttons_layout.addWidget(cancel_button)
        main_vbox.addLayout(buttons_layout)
        self.line_edit.installEventFilter(self)
        #buttons signals
        self.connect(ok_button, SIGNAL("clicked()"), self.save_shortcut)
        self.connect(cancel_button, SIGNAL("clicked()"), self.close)

    def save_shortcut(self):
        """Save a new Shortcut"""
        self.hide()
        shortcut = QKeySequence(self.line_edit.text())
        self.emit(SIGNAL('shortcutChanged'), shortcut)

    def set_shortcut(self, txt):
        """Setup a shortcut"""
        self.line_edit.setText(txt)

    def eventFilter(self, watched, event):
        """Event Filter handling"""
        if event.type() == QEvent.KeyPress:
            self.keyPressEvent(event)
            return True

        return False

    def keyPressEvent(self, evt):
        """Key Press handling"""
        #modifier can not be used as shortcut
        if evt.key() in self.keyword_modifiers:
            return

        #save the key
        if evt.key() == Qt.Key_Backtab and evt.modifiers() & Qt.ShiftModifier:
            self.keys = Qt.Key_Tab
        else:
            self.keys = evt.key()

        if evt.modifiers() & Qt.ShiftModifier:
            self.keys += Qt.SHIFT
        if evt.modifiers() & Qt.ControlModifier:
            self.keys += Qt.CTRL
        if evt.modifiers() & Qt.AltModifier:
            self.keys += Qt.ALT
        if evt.modifiers() & Qt.MetaModifier:
            self.keys += Qt.META
        #set the keys
        self.set_shortcut(QKeySequence(self.keys).toString())
Beispiel #25
0
class MainWindow(QMainWindow):
    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)

        self.setWindowTitle("Simulation of a random walk")
        self.setFixedSize(900, 600)

        self.threadpool = QThreadPool()

        # layout
        main_layout = QHBoxLayout()
        left_layout = QVBoxLayout()
        right_layout = QVBoxLayout()

        self.label_title = QLabel("Motivational agent simulation")
        self.label_title.setAlignment(Qt.AlignCenter)
        self.label_title.setFixedHeight(20)

        # Creating the painting context
        self.scanvas = SimulationCanvas(self, 500, 500)

        left_layout.addWidget(self.label_title)
        left_layout.addWidget(self.scanvas)
        left_layout.setContentsMargins(0, 0, 0, 0)
        left_layout.setSpacing(0)

        # Right panel
        pw = 350
        ph = 150

        # self.plotView1 = pg.widgets.RemoteGraphicsView.RemoteGraphicsView()
        # self.plotView1.setFixedWidth( pw+10 )
        # self.plotView1.pg.setConfigOptions(antialias=True)

        self.plotTop = pg.PlotWidget()
        self.plotTop.setFixedWidth(pw)
        self.plotTop.setFixedHeight(ph)
        self.plotTopData = self.plotTop.plot([0], [0])
        # self.plotView1.setCentralItem( self.plotTop )

        self.plotMiddle = pg.PlotWidget()
        self.plotMiddle.setFixedWidth(pw)
        self.plotMiddle.setFixedHeight(ph)
        self.plotMiddleData = self.plotMiddle.plot([0], [0])

        self.plotBottom = pg.PlotWidget()
        self.plotBottom.setFixedWidth(pw)
        self.plotBottom.setFixedHeight(ph)
        self.plotBottomData = self.plotBottom.plot([0], [0])

        right_layout.addWidget(self.plotTop)
        right_layout.addWidget(self.plotMiddle)
        right_layout.addWidget(self.plotBottom)
        right_layout.setContentsMargins(0, 0, 0, 0)

        # Building main layour
        main_layout.setContentsMargins(0, 0, 0, 0)
        main_layout.setSpacing(0)
        main_layout.addLayout(left_layout)
        main_layout.addLayout(right_layout)

        self.widget = QWidget()
        self.widget.setLayout(main_layout)
        self.setCentralWidget(self.widget)

        toolbar = QToolBar("Some toolbar")
        self.addToolBar(toolbar)

        self.run_text = QLineEdit("10")
        self.run_text.setFixedWidth(50)
        self.run_action = QAction("Run", self)
        self.run_action.setIcon(QIcon("icons/play.png"))
        self.run_action.setStatusTip("Runs the simulation")
        self.run_action.triggered.connect(self.onRunClick)

        self.pause_action = QAction("Pause", self)
        self.pause_action.setIcon(QIcon("icons/pause.png"))
        self.pause_action.setStatusTip("Pauses the simulation")
        self.pause_action.triggered.connect(self.onPauseClick)
        self.pause_action.setEnabled(False)

        self.stop_action = QAction("Stop", self)
        self.stop_action.setIcon(QIcon("icons/stop.png"))
        self.stop_action.setStatusTip("Stops the simulation")
        self.stop_action.triggered.connect(self.onStopClick)
        self.stop_action.setEnabled(False)

        self.plots_action = QAction("Plots", self)
        self.plots_action.setIcon(QIcon("icons/plot.png"))
        self.plots_action.setStatusTip("Shows additional plots")
        self.plots_action.triggered.connect(self.onPlotsClick)

        self.screenshot_action = QAction("Screenshot", self)
        self.screenshot_action.setStatusTip("Saves screenshot")
        self.screenshot_action.triggered.connect(self.onScreenShotClick)

        # self.plots_action.setEnabled( False )

        self.foodx = QLineEdit("-20")
        self.foodx.setFixedWidth(50)
        self.foody = QLineEdit("20")
        self.foody.setFixedWidth(50)

        toolbar.addAction(self.run_action)
        toolbar.addWidget(self.run_text)
        toolbar.addWidget(QLabel("ms"))
        toolbar.addAction(self.pause_action)
        toolbar.addAction(self.stop_action)
        toolbar.addAction(self.plots_action)
        toolbar.addAction(self.screenshot_action)
        toolbar.addWidget(QLabel("Food position:"))
        toolbar.addWidget(self.foodx)
        toolbar.addWidget(self.foody)

        self.statusb = QStatusBar(self)
        self.setStatusBar(self.statusb)

        self.simulation = None
        self.signals = GraphicSignals()
        self.plots = PlotsWindow(self)

        self.agentPos = [20.0, 40.0]

    def onScreenShotClick(self, ev):
        pixmap = QPixmap(self.widget.rect().width(),
                         self.widget.rect().height())
        painter = QPainter()
        painter.begin(pixmap)
        self.widget.render(painter, QPoint(), QRegion(self.widget.rect()))
        painter.end()
        pixmap.save("screen" +
                    str(datetime.datetime.now().strftime("%I_%M_%S")) + ".png")

    def onPlotsClick(self, ev):
        self.plots.show()

    def showEvent(self, ev):
        print("main window shown")
        super(MainWindow, self).showEvent(ev)
        self.scanvas.initCanvas()

    def initPlots(self, model):
        self.plotUpdater = PlotUpdater(self)
        # self.threadpool.start( self.plotUpdater )

        ao = model.getObservedAgent()

        self.topPlotData = {'name': 'Rho'}
        self.middlePlotData = {'name': 'Tb'}
        self.bottomPlotData = {'name': 'E'}

        self.plotTop.setTitle(self.topPlotData['name'])
        self.plotTop.setXRange(0, self.simulation.maxT)
        self.plotTop.setYRange(-0.5, 1.5)
        # Middle plot
        self.plotMiddle.setTitle(self.middlePlotData['name'])
        vp = ao.brain.getPreferredValue(self.middlePlotData['name'])
        self.plotMiddle.plot([0, self.simulation.maxT], [vp, vp], pen=(5, 9))
        self.plotMiddle.setXRange(0, self.simulation.maxT)
        self.plotMiddle.setYRange(15, 50)
        # Bottom plot
        self.plotBottom.setTitle(self.bottomPlotData['name'])
        vp = ao.brain.getPreferredValue(self.bottomPlotData['name'])
        self.plotBottom.plot([0, self.simulation.maxT], [vp, vp], pen=(5, 9))
        self.plotBottom.setXRange(0, self.simulation.maxT)
        self.plotBottom.setYRange(0, 1.5)

        # Initializing plots window
        if self.plots is not None:
            self.plots.populate(model)

    def draw(self, model):
        self.plotUpdater.collectData(model)
        self.scanvas.updateGraphics(model)
        pm = "(paused)" if self.simulation.is_pause else ""
        self.statusb.showMessage("Simulation running t = " +
                                 str(self.simulation.t) + pm)

        self.plotUpdater.updatePlots(model)

    def start(self):
        print("Simulation started")
        self.run_action.setEnabled(False)
        self.pause_action.setEnabled(True)
        self.stop_action.setEnabled(True)

    def finish(self):
        self.statusb.showMessage("Simulation finished")
        self.run_action.setEnabled(True)
        self.pause_action.setEnabled(False)
        self.stop_action.setEnabled(False)
        self.plotUpdater.stop()

    def pause(self):
        self.statusb.showMessage("Simulation paused")

    def onStopClick(self, s):
        self.simulation.stop()

    def onPauseClick(self, s):
        self.simulation.pause()

    def onRunClick(self, s):
        maxT = int(self.run_text.text())
        self.runSimulation(maxT)

    def runSimulation(self, maxT):
        xmin = -self.scanvas.viewPort.getWidth() / 2.0
        xmax = self.scanvas.viewPort.getWidth() / 2.0

        self.simulation = Simulation(xmin, xmax, maxT)
        #a = AgentBuilder.buildSimpleTemperatureAgent( self.simulation.model.environment, 20.0, 20.0 )
        a = AgentBuilder.buildMotivationalAgent(
            self.simulation.model.environment, self.agentPos[0],
            self.agentPos[1])

        self.simulation.model.addAgent(a)
        self.simulation.model.addFoodSource(float(self.foodx.text()),
                                            float(self.foody.text()))

        self.initPlots(self.simulation.model)

        self.simulation.signals.draw.connect(self.draw)
        self.simulation.signals.start.connect(self.start)
        self.simulation.signals.finish.connect(self.finish)
        self.simulation.signals.pause.connect(self.pause)
        self.signals.plottingCompleted.connect(self.simulation.resume)

        self.threadpool.start(self.simulation)
Beispiel #26
0
    def __init__(self, config_in, ncols=2):
        super(DictGui, self).__init__()

        self.setWindowTitle('Lisa Config')
        self.config = ConfigManager()
        self.ncols = ncols
# used with other module. If it is set, lisa config is deleted
        self.reset_config = False

        CHOICE_A = "{pairwise_alpha_per_mm2: 45, return_only_object_with_seeds: true}"
        # CHOICE_A = 23

        CHOICE_B = 2
        CHOICE_C = 3
        CHOICE_D = 4

        map_dict = {
            'Graph-Cut': CHOICE_A,
            'Choice B': CHOICE_B,
            'Choice C': CHOICE_C,
            'Choice D': CHOICE_D,
        }
        config_def = {
            'working_voxelsize_mm': 2.0,
            'save_filetype': 'pklz',
            # 'manualroi': True,
            'segparams': CHOICE_A,
        }
        
        config_def.update(config_in)
        
        self.config.set_defaults(config_def)

        gd = QGridLayout()
        gd_max_i = 0
        for key, value in config_in.items():
            if type(value) is int:
                sb = QSpinBox()
                sb.setRange(-100000, 100000)
            elif type(value) is float:
                sb = QDoubleSpinBox()
            elif type(value) is str:
                sb = QLineEdit()
            elif type(value) is bool:
                sb = QCheckBox()
            else:
                logger.error("Unexpected type in config dictionary")

            row = gd_max_i / self.ncols
            col = (gd_max_i % self.ncols) * 2

            gd.addWidget(QLabel(key),row, col +1) 
            gd.addWidget(sb, row, col + 2)
            self.config.add_handler(key, sb)
            gd_max_i += 1




        # gd.addWidget(QLabel("save filetype"), 1, 1)
        # te = QLineEdit()
        # gd.addWidget(te, 1, 2)
        # self.config.add_handler('save_filetype', te)
        #
        # gd.addWidget(QLabel("segmentation parameters"), 2, 1)
        # te = QLineEdit()
        # gd.addWidget(te, 2, 2)
        # self.config.add_handler('segparams', te)

        # cb = QCheckBox()
        # gd.addWidget(cb, 2, 2)
        # self.config.add_handler('active', cb)

        # gd.addWidget(QLabel("segmentation parameters"), 3, 1)
        # cmb = QComboBox()
        # cmb.addItems(map_dict.keys())
        # gd.addWidget(cmb, 3, 2)
        # self.config.add_handler('segparams', cmb, mapper=map_dict)

        self.current_config_output = QTextEdit()
        # rid.setColumnMinimumWidth(3, logo.width()/2)
        text_col = (self.ncols * 2) + 3
        gd.setColumnMinimumWidth(text_col, 500)
        gd.addWidget(self.current_config_output, 1, text_col, (gd_max_i/2)-1, 1)

        btn_reset_config = QPushButton("Default", self)
        btn_reset_config.clicked.connect(self.btnResetConfig)
        gd.addWidget(btn_reset_config, 0, text_col)

        btn_save_config = QPushButton("Ok", self)
        btn_save_config.clicked.connect(self.btnSaveConfig)
        gd.addWidget(btn_save_config, (gd_max_i / 2), text_col)

        self.config.updated.connect(self.show_config)

        self.show_config()

        # my line
        self.setLayout(gd)