Beispiel #1
0
    def synonyms(self, key):

        """See openexp._keyboard.legacy"""

        # Respond correctly if a keycode is passed, rather than a Unicode string
        # key description.
        if type(key) == int:
            l = [key, pyglet.window.key.symbol_string(key).lower()]
            if l[-1].upper() != l[-1].lower():
                l.append(l[-1].upper())
            return l

            # Sanity check
        if not isinstance(key, basestring):
            raise openexp.exceptions("Key names should be string or numeric, not %s" % type(key))

            # Make a list of all conceivable ways that a key might be referred to.
        l = [key, key.upper()]
        if key.upper() != key.lower():
            l.append(key.lower())
        for char, name in self.keymap.items():
            if key == char:
                l.append(name)
            if key.lower() == name:
                l.append(char)
                # Make sure that we can deal with None/ timeout responses
        if key.lower() == "none":
            l.append(None)
            # Make sure that we convert numeric strings to ints as well
        try:
            i = int(key)
            l.append(i)
        except:
            pass
        return l
Beispiel #2
0
    def synonyms(self, key):
        """See openexp._keyboard.legacy"""

        # Respond correctly if a keycode is passed, rather than a Unicode string
        # key description.
        if type(key) == int:
            l = [key, pyglet.window.key.symbol_string(key).lower()]
            if l[-1].upper() != l[-1].lower():
                l.append(l[-1].upper())
            return l

        # Sanity check
        if not isinstance(key, basestring):
            raise osexception( \
             'Key names should be string or numeric, not %s' % type(key))

        # Make a list of all conceivable ways that a key might be referred to.
        l = [key, key.upper()]
        if key.upper() != key.lower():
            l.append(key.lower())
        for char, name in self.keymap.items():
            if key == char:
                l.append(name)
            if key.lower() == name:
                l.append(char)
        # Make sure that we can deal with None/ timeout responses
        if key.lower() == 'none':
            l.append(None)
        # Make sure that we convert numeric strings to ints as well
        try:
            i = int(key)
            l.append(i)
        except:
            pass
        return l
Beispiel #3
0
	def synonyms(self, key):

		"""See openexp._keyboard.legacy"""

		if type(key) == int:
			l = [pyglet.window.key.symbol_string(key).lower()]
			if l[-1].upper() != l[-1].lower():
				l.append(l[-1].upper())
			return l
		if key.upper() == key.lower():
			return key
		return [key.upper(), key.lower()]
Beispiel #4
0
 def on_mouse_press(self, x, y, button, modifiers):
     value = self.phases.handle_click(x, y)
     if value:
         key, state, label = value
         if key.lower() in self.stops:
             self.stops.remove(key.lower())
             state.alpha = 1.0
             label.scale = 0.8
             col = label.main_text.color
             label.main_text.color = (col[0], col[1], col[2], 1.0)
         else:
             self.stops.add(key.lower())
             state.alpha = self.dim
             label.scale = 0.6
             col = label.main_text.color
             label.main_text.color = (col[0], col[1], col[2], self.dim)
     return True
Beispiel #5
0
 def on_mouse_press(self, x, y, button, modifiers):
     value = self.phases.handle_click(x, y)
     if value:
         key, state, label = value
         if key.lower() in self.stops:
             self.stops.remove(key.lower())
             state.alpha = 1.0
             label.scale = 0.8
             col = label.main_text.color
             label.main_text.color = (col[0], col[1], col[2], 1.0)
         else:
             self.stops.add(key.lower())
             state.alpha = self.dim
             label.scale = 0.6
             col = label.main_text.color
             label.main_text.color = (col[0], col[1], col[2], self.dim)
     return True
Beispiel #6
0
	def synonyms(self, key):

		"""
		Gives a list of synonyms for a key, either codes or names

		Returns:
		A list of synonyms
		"""

		if type(key) == int:
			l = [pyglet.window.key.symbol_string(key).lower()]
			if l[-1].upper() != l[-1].lower():
				l.append(l[-1].upper())
			return l
		if key.upper() == key.lower():
			return key
		return [key.upper(), key.lower()]
Beispiel #7
0
    def synonyms(self, key):
        """See openexp._keyboard.legacy"""

        if type(key) == int:
            l = [pyglet.window.key.symbol_string(key).lower()]
            if l[-1].upper() != l[-1].lower():
                l.append(l[-1].upper())
            return l

        l = [key.upper()]
        if key.upper() != key.lower():
            l.append(key.lower())
        for char, name in self.keymap.items():
            if key == char:
                l.append(name)
            if key.lower() == name:
                l.append(char)
        return l
Beispiel #8
0
	def synonyms(self, key):

		"""See openexp._keyboard.legacy"""

		if type(key) == int:
			l = [pyglet.window.key.symbol_string(key).lower()]
			if l[-1].upper() != l[-1].lower():
				l.append(l[-1].upper())
			return l
		
		l = [key.upper()]
		if key.upper() != key.lower():
			l.append(key.lower())
		for char, name in self.keymap.items():
			if key == char:
				l.append(name)
			if key.lower() == name:
				l.append(char)												
		return l
Beispiel #9
0
 def activate(self, other=False):
     self.phases.visible = 1
     self.other = other
     if not other: self.stops = self.phases.my_turn_stops
     else: self.stops = self.phases.opponent_turn_stops
     self.phases.toggle_select(other)
     for key, (i, val) in self.phases.state_map.items():
         state = self.phases.states[i]
         label = self.phases.state_labels[i]
         if other: label.main_text.halign = "right"
         else: label.main_text.halign = "left"
         if key == "Untap" or key == "Cleanup":
             state.visible = 0
             label.visible = 0
         elif key.lower() in self.stops:
             state.alpha = self.dim
             label.scale = 0.6
             col = label.main_text.color
             label.main_text.color = (col[0], col[1], col[2], self.dim)
     director.window.push_handlers(self)
Beispiel #10
0
 def activate(self, other=False):
     self.phases.visible = 1
     self.other = other
     if not other:
         self.stops = self.phases.my_turn_stops
     else:
         self.stops = self.phases.opponent_turn_stops
     self.phases.toggle_select(other)
     for key, (i, val) in self.phases.state_map.items():
         state = self.phases.states[i]
         label = self.phases.state_labels[i]
         if other:
             label.main_text.halign = "right"
         else:
             label.main_text.halign = "left"
         if key == "Untap" or key == "Cleanup":
             state.visible = 0
             label.visible = 0
         elif key.lower() in self.stops:
             state.alpha = self.dim
             label.scale = 0.6
             col = label.main_text.color
             label.main_text.color = (col[0], col[1], col[2], self.dim)
     director.window.push_handlers(self)
Beispiel #11
0
    def check(self, parent):
        """Checks python syntax of code snippets, and for self-reference.

        Note: code snippets simply use existing names in the namespace,
        like from condition-file headers. They do not add to the
        namespace (unlike Name fields).

        Code snippets in param fields will often be user-defined
        vars, especially condition names. Can also be expressions like
        random(1,100). Hard to know what will be problematic.
        But its always the case that self-reference is wrong.
        """

        # first check if there's anything to validate (and return if not)

        def _checkParamUpdates(parent):
            """Checks whether param allows updates. Returns bool."""
            if parent.params[self.fieldName].allowedUpdates is not None:
                # Check for new set with elements common to lists compared - True if any elements are common
                return bool(
                    set(parent.params[self.fieldName].allowedUpdates)
                    & set(allowedUpdates))

        def _highlightParamVal(parent, error=False):
            """Highlights text containing error - defaults to black"""
            try:
                if error:
                    parent.paramCtrls[
                        self.fieldName].valueCtrl.SetForegroundColour("Red")
                else:
                    parent.paramCtrls[
                        self.fieldName].valueCtrl.SetForegroundColour("Black")
            except KeyError:
                pass

        # Get attributes of value control
        control = self.GetWindow()
        if not hasattr(control, 'GetValue'):
            return '', True
        val = control.GetValue()  # same as parent.params[self.fieldName].val
        if not isinstance(val, basestring):
            return '', True
        field = self.fieldName
        allowedUpdates = ['set every repeat', 'set every frame']
        # Set initials
        msg, OK = '', True  # until we find otherwise
        _highlightParamVal(parent)
        # What valType should code be treated as?
        codeWanted = psychopy.experiment.utils.unescapedDollarSign_re.search(
            val)
        isCodeField = bool(parent.params[self.fieldName].valType == 'code')

        # Validate as list
        allKeyBoardKeys = list(
            key._key_names.values()) + [str(num) for num in range(10)]
        allKeyBoardKeys = [key.lower() for key in allKeyBoardKeys]
        if self.fieldName == 'correctAns' and not val.startswith('$'):
            keyList = listFromString(val)
            if isinstance(keyList, str):
                keyList = [keyList]
            potentialVars = list(
                set(keyList) - set(allKeyBoardKeys)
            )  # Elements of keyList not in allKeyBoardKeys
            _highlightParamVal(parent, bool(potentialVars))
            if len(potentialVars):
                msg = _translate(
                    "It looks like your 'Correct answer' contains a variable - prepend variables with '$' e.g. ${val}"
                )
                msg = msg.format(val=potentialVars[0].lower())

        # Validate as code
        if codeWanted or isCodeField:
            # get var names from val, check against namespace:
            code = experiment.getCodeFromParamStr(val)
            try:
                names = compile(code, '', 'exec').co_names
            except (SyntaxError, TypeError) as e:
                # empty '' compiles to a syntax error, ignore
                if not code.strip() == '':
                    _highlightParamVal(parent, True)
                    msg = _translate('Python syntax error in field `{}`:  {}')
                    msg = msg.format(self.displayName, code)
                    OK = False
            else:
                # Check whether variable param entered as a constant
                if isCodeField and _checkParamUpdates(parent):
                    if parent.paramCtrls[
                            self.fieldName].getUpdates() not in allowedUpdates:
                        try:
                            eval(code)
                        except NameError as e:
                            _highlightParamVal(parent, True)
                            msg = _translate(
                                f"Looks like your variable '{code}' in '{self.displayName}' should be set to update."
                            )
                            msg = msg.format(code=code,
                                             displayName=self.displayName)
                        except SyntaxError as e:
                            msg = ''

                # namespace = parent.frame.exp.namespace
                # parent.params['name'].val is not in namespace for new params
                # and is not fixed as .val until dialog closes. Use getvalue()
                # to handle dynamic changes to Name field:
                if 'name' in parent.paramCtrls:  # some components don't have names
                    parentName = parent.paramCtrls['name'].getValue()
                    for name in names:
                        # `name` means a var name within a compiled code snippet
                        if name == parentName:
                            _highlightParamVal(parent, True)
                            msg = _translate(
                                'Python var `{}` in `{}` is same as Name')
                            msg = msg.format(name, self.displayName)
                            OK = True

                    for newName in names:
                        namespace = parent.frame.exp.namespace
                        if newName in [
                                *namespace.user, *namespace.builder,
                                *namespace.constants
                        ]:
                            # Continue if name is a variable
                            continue
                        if newName in [
                                *namespace.nonUserBuilder, *namespace.numpy
                        ] and not re.search(newName + "(?!\(\))", val):
                            # Continue if name is an external function being called correctly
                            continue
                        used = namespace.exists(newName)
                        sameAsOldName = bool(
                            newName == parent.params['name'].val)
                        if used and not sameAsOldName:
                            msg = _translate(
                                f"Variable name ${newName} is in use (by {_translate(used)}). Try another name."
                            )
                            # let the user continue if this is what they intended
                            OK = True

        parent.warningsDict[field] = msg
        return msg, OK