id
int64 0
458k
| file_name
stringlengths 4
119
| file_path
stringlengths 14
227
| content
stringlengths 24
9.96M
| size
int64 24
9.96M
| language
stringclasses 1
value | extension
stringclasses 14
values | total_lines
int64 1
219k
| avg_line_length
float64 2.52
4.63M
| max_line_length
int64 5
9.91M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 7
101
| repo_stars
int64 100
139k
| repo_forks
int64 0
26.4k
| repo_open_issues
int64 0
2.27k
| repo_license
stringclasses 12
values | repo_extraction_date
stringclasses 433
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5,800
|
__init__.py
|
psychopy_psychopy/psychopy/app/coder/__init__.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Coder is the python IDE for PsychoPy
"""
from .coder import CoderFrame, BaseCodeEditor # pylint: disable=W0401
| 164
|
Python
|
.py
| 6
| 26
| 70
| 0.717949
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,801
|
repl.py
|
psychopy_psychopy/psychopy/app/coder/repl.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Classes and functions for the REPL shell in PsychoPy Coder."""
# Part of the PsychoPy library
# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd.
# Distributed under the terms of the GNU General Public License (GPL).
import sys
import wx
import wx.richtext
from psychopy.app.stdout import StdOutRich
from psychopy.app.themes import handlers, colors, icons, fonts
from psychopy.localization import _translate
import os
class ConsoleTextCtrl(StdOutRich, handlers.ThemeMixin):
"""Class for the console text control. This is needed to allow for theming.
"""
def __init__(self, parent, id_=wx.ID_ANY, value="", pos=wx.DefaultPosition,
size=wx.DefaultSize, style=0,
name=wx.TextCtrlNameStr):
StdOutRich.__init__(
self, parent, style, size=size
)
class PythonREPLCtrl(wx.Panel, handlers.ThemeMixin):
"""Class for a Python REPL control.
An interactive shell (REPL) for interfacing with a Python interpreter in
another process owned by the control.
This class does not emulate a terminal/console perfectly, so things like
'curses' and control characters (e.g., Ctrl+C) do not work. Unresponsive
scripts must be stopped manually, resulting in a loss of the objects in the
namespace. Therefore, it is recommended that users push lines to the
shell using the script editor.
"""
class PythonREPLToolbar(wx.Panel, handlers.ThemeMixin):
def __init__(self, parent):
wx.Panel.__init__(self, parent, size=(30, -1))
self.parent = parent
# Setup sizer
self.borderBox = wx.BoxSizer(wx.VERTICAL)
self.SetSizer(self.borderBox)
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.borderBox.Add(self.sizer, border=6, flag=wx.ALL)
# Start button
self.startBtn = wx.Button(self, size=(16, 16), style=wx.BORDER_NONE)
self.startBtn.SetToolTip(_translate(
"Close the current shell."
))
self.startBtn.SetBitmap(
icons.ButtonIcon(stem="start", size=16).bitmap
)
self.sizer.Add(self.startBtn, border=6, flag=wx.BOTTOM)
self.startBtn.Bind(wx.EVT_BUTTON, self.parent.start)
# Restart button
self.restartBtn = wx.Button(self, size=(16, 16), style=wx.BORDER_NONE)
self.restartBtn.SetToolTip(_translate(
"Close the current shell and start a new one, this will clear any variables."
))
self.restartBtn.SetBitmap(
icons.ButtonIcon(stem="restart", size=16).bitmap
)
self.sizer.Add(self.restartBtn, border=6, flag=wx.BOTTOM)
self.restartBtn.Bind(wx.EVT_BUTTON, self.parent.restart)
# Stop button
self.stopBtn = wx.Button(self, size=(16, 16), style=wx.BORDER_NONE)
self.stopBtn.SetToolTip(_translate(
"Close the current shell."
))
self.stopBtn.SetBitmap(
icons.ButtonIcon(stem="stop", size=16).bitmap
)
self.sizer.Add(self.stopBtn, border=6, flag=wx.BOTTOM)
self.stopBtn.Bind(wx.EVT_BUTTON, self.parent.close)
# Clear button
self.clrBtn = wx.Button(self, size=(16, 16), style=wx.BORDER_NONE)
self.clrBtn.SetToolTip(_translate(
"Clear all previous output."
))
self.clrBtn.SetBitmap(
icons.ButtonIcon(stem="clear", size=16).bitmap
)
self.sizer.Add(self.clrBtn, border=6, flag=wx.BOTTOM)
self.clrBtn.Bind(wx.EVT_BUTTON, self.parent.clear)
self.update()
self.Layout()
def update(self):
self.startBtn.Show(not self.parent.isStarted)
self.restartBtn.Show(self.parent.isStarted)
self.stopBtn.Show(self.parent.isStarted)
self.Layout()
def _applyAppTheme(self):
# Set background
self.SetBackgroundColour(fonts.coderTheme.base.backColor)
# Style buttons
for btn in (self.startBtn, self.stopBtn, self.clrBtn, self.restartBtn):
btn.SetBackgroundColour(fonts.coderTheme.base.backColor)
self.Refresh()
self.Update()
def __init__(self,
parent,
id_=wx.ID_ANY,
pos=wx.DefaultPosition,
size=wx.DefaultSize,
style=wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL,
name=wx.EmptyString):
wx.Panel.__init__(self, parent, id=id_, pos=pos, size=size, style=style,
name=name)
self.tabIcon = "coderpython"
# sizer for the panel
self.sizer = wx.BoxSizer(wx.HORIZONTAL)
# Toolbar
self.toolbar = self.PythonREPLToolbar(self)
self.sizer.Add(self.toolbar, border=6, flag=wx.EXPAND | wx.TOP | wx.BOTTOM)
# Sep
self.sep = wx.Window(self, size=(1, -1))
self.sizer.Add(self.sep, border=12, flag=wx.EXPAND | wx.TOP | wx.BOTTOM)
# TextCtrl used to display the text from the terminal
styleFlags = (wx.HSCROLL | wx.TE_MULTILINE | wx.TE_PROCESS_ENTER |
wx.TE_PROCESS_TAB | wx.NO_BORDER)
self.txtTerm = ConsoleTextCtrl(
self,
wx.ID_ANY,
wx.EmptyString,
wx.DefaultPosition,
wx.DefaultSize,
styleFlags)
self.sizer.Add(self.txtTerm, proportion=1, border=6, flag=wx.ALL | wx.EXPAND)
self.SetSizer(self.sizer)
self.Layout()
# capture keypresses
if wx.Platform == '__WXMAC__' or wx.Platform == '__WXMSW__':
# need to use this on MacOS and Windows
keyDownBindingId = wx.EVT_KEY_DOWN
else:
keyDownBindingId = wx.EVT_CHAR
self.txtTerm.Bind(keyDownBindingId, self.onChar)
self.txtTerm.Bind(wx.EVT_TEXT_MAXLEN, self.onMaxLength)
# history
self._history = []
self._historyIdx = 0
# idle event
self.Bind(wx.EVT_IDLE, self.onIdle)
# hooks for the process we're communicating with
self._process = self._pid = None
# interpreter state information
self._isBusy = self._suppress = False
self._stdin_buffer = []
self._lastTextPos = 0
# Disable smart substitutions for quotes and slashes, uses illegal
# characters that cannot be evaluated by the interpreter correctly.
# if wx.Platform == '__WXMAC__':
# self.txtTerm.OSXDisableAllSmartSubstitutions()
# self.txtTerm.MacCheckSpelling(False)
self.txtTerm.write(_translate("Hit [Return] to start a Python session."))
self._lastTextPos = self.txtTerm.GetLastPosition()
def onTerminate(self, event):
# hooks for the process we're communicating with
self._process = self._pid = None
# interpreter state information
self._isBusy = self._suppress = False
self._stdin_buffer = []
self.txtTerm.Clear()
self.txtTerm.write(_translate("Hit [Return] to start a Python shell."))
self._lastTextPos = self.txtTerm.GetLastPosition()
self.toolbar.update()
@property
def isStarted(self):
"""`True` if the interpreter process has been started."""
return self.process is not None
@property
def isBusy(self):
"""`True` if the interpreter process is busy."""
return self._isBusy
@property
def suppressed(self):
"""`True` if the interpreter output is suppressed."""
return self._suppress
@property
def process(self):
"""Process object for the interpreter (`wx.Process`)."""
if hasattr(self, "_process"):
return self._process
@property
def pid(self):
"""Process ID for the interpreter (`int`)."""
return self.getPid()
def getPid(self):
"""Get the process ID for the active interpreter (`int`)."""
return self._pid
# def getPwd(self):
# """Get the present working directory for the interpreter.
# """
# pass
#
# def setPwd(self):
# """Set the present working directory for the interpreter.
# """
# pass
def setFonts(self):
"""Set the font for the console."""
self.txtTerm._applyAppTheme()
def getNamespace(self):
"""Get variable names in the current namespace.
"""
self.push('dir()') # get namespace values
def onIdle(self, event):
"""Idle event.
This is hooked into the main application even loop. When idle, the
input streams are checked and any data is written to the text box.
Output from `stderr` is ignored until there is nothing left to read from
the input stream.
"""
# don't do anything unless we have an active process
if not self.isStarted:
return
# we have new characters
newChars = False
# reset
stdin_text = ''
stderr_text = ''
# check if we have input text to process
if self._process.IsInputAvailable():
stdin_text = self._process.InputStream.read()
txt = stdin_text.decode('utf-8')
self.txtTerm.write(txt)
# special stuff
if txt == '\r': # handle carriage returns at some point
pass
# hack to get the interactive help working
try:
if self.txtTerm.GetValue()[-6:] == 'help> ':
self._isBusy = False
except IndexError:
pass
newChars = True
else:
# check if the input stream has bytes to process
if self._process.IsErrorAvailable():
stderr_text = self._process.ErrorStream.read()
self.txtTerm.write(stderr_text.decode('utf-8'))
self._isBusy = False
newChars = True
# If we have received new character from either stream, advance the
# boundary of the editable area.
if newChars:
self._lastTextPos = self.txtTerm.GetLastPosition()
self.txtTerm.SetInsertionPoint(-1)
self.txtTerm.ShowPosition(self._lastTextPos)
def resetCaret(self):
"""Place the caret at the entry position if not in an editable region.
"""
if self.txtTerm.GetInsertionPoint() < self._lastTextPos:
self.txtTerm.SetInsertionPoint(self._lastTextPos)
return
def push(self, lines):
"""Push a line to the interpreter.
Parameter
---------
line : str
Lines to push to the terminal.
"""
if not self.isStarted:
return
# convert to bytes
for line in lines.split('\n'):
self.submit(line)
def submit(self, line):
"""Submit the current line to the interpreter.
"""
if not self.isStarted:
return
if not line.endswith('\n'):
line += '\n'
self._process.OutputStream.write(line.encode())
self._process.OutputStream.flush()
self._isBusy = True
def start(self, evt=None):
"""Start a new interpreter process.
"""
if self.isStarted: # nop if started already
self.toolbar.update()
return
# inform the user that we're starting the console
self.txtTerm.Clear()
self.txtTerm.write(
"Starting Python interpreter session, please wait ...\n")
# setup the sub-process
wx.BeginBusyCursor()
self._process = wx.Process(self)
self._process.Redirect()
# get the path to the interpreter
interpPath = '"' + sys.executable + '"'
# start the sub-process
self._pid = wx.Execute(
r' '.join([interpPath, r'-i']),
wx.EXEC_ASYNC,
self._process)
# bind the event called when the process ends
self._process.Bind(wx.EVT_END_PROCESS, self.onTerminate)
# clear all text in the widget and display the welcome message
self.txtTerm.Clear()
self.txtTerm.write(
"Python shell in PsychoPy (pid:{}) - type some commands!\n".format(
self._pid)) # show the subprocess PID for reference
self._lastTextPos = self.txtTerm.GetLastPosition()
self.toolbar.update()
wx.EndBusyCursor()
def interrupt(self, evt=None):
"""Send a keyboard interrupt signal to the interpreter.
"""
if self.isStarted:
os.kill(self._pid, wx.SIGINT)
self.toolbar.update()
def close(self, evt=None):
"""Close an open interpreter.
"""
if self.isStarted:
os.kill(self._pid, wx.SIGTERM)
def restart(self, evt=None):
"""Close the running interpreter (if running) and spawn a new one.
"""
self.close()
self.start()
def clear(self, evt=None):
"""Clear the contents of the console.
"""
self.txtTerm.Clear()
self._lastTextPos = self.txtTerm.GetLastPosition()
self.push('')
def onMaxLength(self, event):
"""What to do if we exceed the buffer size limit for the control.
"""
event.Skip()
def __del__(self):
pass
def clearAndReplaceTyped(self, replaceWith=''):
"""Clear any text that has been typed.
"""
self.txtTerm.Remove(self._lastTextPos, self.txtTerm.GetLastPosition())
if replaceWith:
self.txtTerm.write(replaceWith)
self.txtTerm.SetInsertionPoint(self.txtTerm.GetLastPosition())
def getTyped(self):
"""Get the text that was typed or is editable (`str`).
"""
return self.txtTerm.GetRange(
self._lastTextPos,
self.txtTerm.GetLastPosition())
def onChar(self, event):
"""Called when the shell gets a keypress event.
"""
self.resetCaret()
if not self.isStarted:
if event.GetKeyCode() == wx.WXK_RETURN:
self.start()
event.Skip()
return
# if self._isBusy: # dont capture events when busy
# return
if event.GetKeyCode() == wx.WXK_RETURN:
self.txtTerm.SetInsertionPointEnd()
entry = self.getTyped()
if entry:
self._history.insert(0, entry)
self.push(entry)
self._historyIdx = -1
elif event.GetKeyCode() == wx.WXK_BACK or event.GetKeyCode() == wx.WXK_LEFT:
# prevent the cursor from leaving the editable region
if self.txtTerm.GetInsertionPoint() <= self._lastTextPos:
self.txtTerm.SetInsertionPoint(self._lastTextPos)
return
elif event.GetKeyCode() == wx.WXK_UP:
# get previous (last entered) item in history
if self._history:
self._historyIdx = min(
max(0, self._historyIdx + 1),
len(self._history) - 1)
self.clearAndReplaceTyped(self._history[self._historyIdx])
return
elif event.GetKeyCode() == wx.WXK_DOWN:
# get next item in history
if self._history:
self._historyIdx = max(self._historyIdx - 1, -1)
if self._historyIdx >= 0:
self.clearAndReplaceTyped(self._history[self._historyIdx])
else:
self.clearAndReplaceTyped()
return
elif event.GetKeyCode() == wx.WXK_F8: # interrupt a misbehaving terminal
self.interrupt()
elif event.GetKeyCode() == wx.WXK_F4: # clear the screen
self.clear()
else:
if self._history:
self._historyIdx = -1
event.Skip()
def _applyAppTheme(self):
# Set background
self.SetBackgroundColour(fonts.coderTheme.base.backColor)
self.Refresh()
self.Update()
# Match line
self.sep.SetBackgroundColour(fonts.coderTheme.margin.backColor)
self.Refresh()
self.Update()
if __name__ == "__main__":
pass
| 16,546
|
Python
|
.py
| 405
| 30.402469
| 93
| 0.591104
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,802
|
fileBrowser.py
|
psychopy_psychopy/psychopy/app/coder/fileBrowser.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Classes and functions for the coder file browser pane."""
# Part of the PsychoPy library
# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd.
# Distributed under the terms of the GNU General Public License (GPL).
import wx
from wx.lib.mixins.listctrl import ListCtrlAutoWidthMixin
try:
from wx import aui
except Exception:
import wx.lib.agw.aui as aui # some versions of phoenix
import os
import sys
import subprocess
import mimetypes
from ..themes import icons, colors, handlers
from psychopy.localization import _translate
# enums for file types
FOLDER_TYPE_NORMAL = 0
FOLDER_TYPE_NAV = 1
FOLDER_TYPE_NO_ACCESS = 2
# IDs for menu events
ID_GOTO_BROWSE = wx.NewIdRef(count=1)
ID_GOTO_CWD = wx.NewIdRef(count=1)
ID_GOTO_FILE = wx.NewIdRef(count=1)
def convertBytes(nbytes):
"""Convert a size in bytes to a string."""
if nbytes >= 1e9:
return '{:.1f} GB'.format(nbytes / 1e9)
elif nbytes >= 1e6:
return '{:.1f} MB'.format(nbytes / 1e6)
elif nbytes >= 1e3:
return '{:.1f} KB'.format(nbytes / 1e3)
else:
return '{:.1f} B'.format(nbytes)
class FolderItemData:
"""Class representing a folder item in the file browser."""
__slots__ = ['name', 'abspath', 'basename']
def __init__(self, name, abspath, basename):
self.name = name
self.abspath = abspath
self.basename = basename
class FileItemData:
"""Class representing a file item in the file browser."""
__slots__ = ['name', 'abspath', 'basename', 'fsize', 'mod']
def __init__(self, name, abspath, basename, fsize, mod):
self.name = name
self.abspath = abspath
self.basename = basename
self.fsize = fsize
self.mod = mod
class FileBrowserListCtrl(ListCtrlAutoWidthMixin, wx.ListCtrl, handlers.ThemeMixin):
"""Custom list control for the file browser."""
def __init__(self, parent, id, pos, size, style):
wx.ListCtrl.__init__(self,
parent,
id,
pos,
size,
style=style)
self.parent = parent
ListCtrlAutoWidthMixin.__init__(self)
self.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, self.OnRightClick)
def OnRightClick(self, evt=None):
# create menu
menu = wx.Menu()
# create new menu
newMenu = wx.Menu()
btn = newMenu.Append(
wx.ID_NEW,
item=_translate("Folder"),
helpString=_translate("Create a new folder here.")
)
newMenu.Bind(wx.EVT_MENU, self.parent.OnNewFolderTool, source=btn)
menu.AppendSubMenu(newMenu, _translate("New..."))
# rename btn
btn = menu.Append(
wx.ID_ANY,
item=_translate("Rename"),
helpString=_translate("Rename the file"))
menu.Bind(wx.EVT_MENU, self.parent.OnRenameTool, source=btn)
# delete btn
btn = menu.Append(
wx.ID_DELETE,
item=_translate("Delete"),
helpString=_translate("Delete the file"))
menu.Bind(wx.EVT_MENU, self.parent.OnDeleteTool, source=btn)
# show menu
self.PopupMenu(menu, pos=evt.GetPoint())
def _applyAppTheme(self, target=None):
self.SetBackgroundColour(colors.app['tab_bg'])
self.SetForegroundColour(colors.app['text'])
class FileBrowserPanel(wx.Panel, handlers.ThemeMixin):
"""Panel for a file browser.
"""
fileImgExt = {
"..": 'dirup16',
"\\": 'folder16',
".?": 'fileunknown16',
".csv": 'filecsv16',
".xlsx": 'filecsv16',
".xls": 'filecsv16',
".tsv": 'filecsv16',
".png": 'fileimage16',
".jpeg": 'fileimage16',
".jpg": 'fileimage16',
".bmp": 'fileimage16',
".tiff": 'fileimage16',
".tif": 'fileimage16',
".ppm": 'fileimage16',
".gif": 'fileimage16',
".py": 'coderpython',
".js": 'coderjs'
}
def __init__(self, parent, frame):
wx.Panel.__init__(self, parent, -1, style=wx.BORDER_NONE)
self.parent = parent
self.coder = frame
self.app = frame.app
self.tabIcon = "folder"
self.currentPath = None
self.selectedItem = None
self.isSubDir = False
self.fileImgList = None # will be a wx ImageList to store icons
self.pathData = {}
# setup sizer
szr = wx.BoxSizer(wx.VERTICAL)
self.SetSizer(szr)
# create a navigation toolbar
self.lblDir = wx.StaticText(self, label=_translate("Directory:"))
szr.Add(self.lblDir, border=5, flag=wx.TOP | wx.LEFT | wx.RIGHT | wx.EXPAND)
self.navBar = wx.BoxSizer(wx.HORIZONTAL)
szr.Add(self.navBar, border=3, flag=wx.ALL | wx.EXPAND)
# file path ctrl
self.txtAddr = wx.TextCtrl(self, style=wx.TE_PROCESS_ENTER)
self.Bind(wx.EVT_TEXT_ENTER, self.OnAddrEnter, self.txtAddr)
self.navBar.Add(self.txtAddr, proportion=1, border=5, flag=wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.EXPAND)
# browse button
self.browseBtn = wx.Button(self, size=(16, 16), style=wx.BORDER_NONE)
self.browseBtn.Bind(wx.EVT_BUTTON, self.OnBrowse)
self.navBar.Add(self.browseBtn, border=3, flag=wx.ALL | wx.EXPAND)
self.browseBtn.SetToolTip(_translate(
"Browse for a folder to open."
))
# library root button
self.libRootBtn = wx.Button(self, size=(16, 16), style=wx.BORDER_NONE)
self.libRootBtn.SetToolTip(_translate(
"Navigate to PsychoPy library root."
))
self.libRootBtn.Bind(wx.EVT_BUTTON, self.OnGotoCWD)
self.navBar.Add(self.libRootBtn, border=3, flag=wx.ALL | wx.EXPAND)
# current file button
self.currentFileBtn = wx.Button(self, size=(16, 16), style=wx.BORDER_NONE)
self.currentFileBtn.SetToolTip(_translate(
"Navigate to current open file."
))
self.currentFileBtn.Bind(wx.EVT_BUTTON, self.OnGotoFileLocation)
self.navBar.Add(self.currentFileBtn, border=3, flag=wx.ALL | wx.EXPAND)
# create the source tree control
self.flId = wx.NewIdRef()
self.fileList = FileBrowserListCtrl(
self,
self.flId,
pos=(0, 0),
size=wx.Size(300, 300),
style=wx.LC_REPORT | wx.LC_SINGLE_SEL | wx.BORDER_NONE |
wx.LC_NO_HEADER)
# bind events for list control
self.Bind(
wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelected, self.fileList)
self.Bind(
wx.EVT_LIST_ITEM_ACTIVATED, self.OnItemActivated, self.fileList)
szr.Add(self.fileList, 1, flag=wx.EXPAND)
self.makeFileImgIcons()
# add columns
self.fileList.InsertColumn(0, "Name")
#self.fileList.InsertColumn(1, "Size", wx.LIST_FORMAT_LEFT)
#self.fileList.InsertColumn(2, "Modified")
self.fileList.SetColumnWidth(0, 280)
#self.fileList.SetColumnWidth(1, 80)
#self.fileList.SetColumnWidth(2, 100)
self.gotoDir(os.getcwd())
def _applyAppTheme(self, target=None):
# Set background
self.SetBackgroundColour(colors.app['tab_bg'])
self.SetForegroundColour(colors.app['text'])
# Style nav bar
btns = {
self.currentFileBtn: icons.ButtonIcon(stem="currentFile", size=16).bitmap,
self.libRootBtn: icons.ButtonIcon(stem="libroot", size=16).bitmap,
self.browseBtn: icons.ButtonIcon(stem="fileopen", size=16).bitmap
}
for btn, bmp in btns.items():
btn.SetBackgroundColour(colors.app['tab_bg'])
btn.SetBitmap(bmp)
btn.SetBitmapFocus(bmp)
btn.SetBitmapDisabled(bmp)
btn.SetBitmapPressed(bmp)
btn.SetBitmapCurrent(bmp)
# Make sure directory label is correct color
self.lblDir.SetForegroundColour(colors.app['text'])
# Remake icons
self.makeFileImgIcons()
# Refresh
self.Refresh()
def makeFileImgIcons(self):
# handles for icon graphics in the image list
self.fileImgInds = {}
if self.fileImgList:
self.fileImgList.RemoveAll()
else:
self.fileImgList = wx.ImageList(16, 16)
for key in self.fileImgExt:
self.fileImgInds[key] = self.fileImgList.Add(
icons.ButtonIcon(self.fileImgExt[key], size=(16, 16)).bitmap
)
self.fileList.SetImageList(self.fileImgList, wx.IMAGE_LIST_SMALL)
self.Update()
def OnGotoFileLocation(self, evt):
"""Goto the currently opened file location."""
filename = self.coder.currentDoc.filename
filedir = os.path.split(filename)[0]
if os.path.isabs(filedir):
self.gotoDir(filedir)
# select the file in the browser
for idx, item in enumerate(self.dirData):
if item.abspath == filename:
self.fileList.Select(idx, True)
self.fileList.EnsureVisible(idx)
self.selectedItem = self.dirData[idx]
self.fileList.SetFocus()
break
else:
dlg = wx.MessageDialog(
self,
_translate(
"Cannot change working directory to location of file `{}`. It"
" needs to be saved first.").format(filename),
style=wx.ICON_ERROR | wx.OK)
dlg.ShowModal()
dlg.Destroy()
evt.Skip()
def OnGotoMenu(self, event):
mnuGoto = wx.Menu()
mnuGoto.Append(
ID_GOTO_BROWSE,
_translate("Browse ..."),
_translate("Browse the file system for a directory to open"))
mnuGoto.AppendSeparator()
mnuGoto.Append(
ID_GOTO_CWD,
_translate("Current working directory"),
_translate("Open the current working directory"))
mnuGoto.Append(
ID_GOTO_FILE,
_translate("Editor file location"),
_translate("Open the directory the current editor file is located"))
self.PopupMenu(mnuGoto)
mnuGoto.Destroy()
#event.Skip()
def OnBrowse(self, event=None):
dlg = wx.DirDialog(self, _translate("Choose directory ..."), "",
wx.DD_DEFAULT_STYLE | wx.DD_DIR_MUST_EXIST)
if dlg.ShowModal() == wx.ID_OK:
self.gotoDir(dlg.GetPath())
dlg.Destroy()
def OnNewFolderTool(self, event):
"""When the new folder tool is clicked."""
# ask for the name of the folder
dlg = wx.TextEntryDialog(self, _translate('Enter folder name:'),
_translate('New folder'), '')
if dlg.ShowModal() == wx.ID_CANCEL:
dlg.Destroy()
event.Skip()
return
folderName = dlg.GetValue()
if folderName == '':
dlg = wx.MessageDialog(
self,
_translate("Folder name cannot be empty.").format(folderName),
style=wx.ICON_ERROR | wx.OK)
dlg.ShowModal()
dlg.Destroy()
event.Skip()
return
abspath = os.path.join(self.currentPath, folderName)
if os.path.isdir(abspath): # folder exists, warn and exit
dlg = wx.MessageDialog(
self,
_translate("Cannot create folder `{}`, already exists.").format(folderName),
style=wx.ICON_ERROR | wx.OK)
dlg.ShowModal()
dlg.Destroy()
event.Skip()
return
# try to create the folder
try:
os.mkdir(abspath)
except OSError:
dlg = wx.MessageDialog(
self,
_translate("Cannot create folder `{}`, permission denied.").format(folderName),
style=wx.ICON_ERROR | wx.OK)
dlg.ShowModal()
dlg.Destroy()
event.Skip()
return
# open the folder we just created
self.gotoDir(abspath)
def OnDeleteTool(self, event=None):
"""Activated when the delete tool is pressed."""
if self.selectedItem is not None:
if isinstance(self.selectedItem, FolderItemData):
if self.selectedItem.name == '..':
return # is a sub directory marker
self.delete()
def OnRenameTool(self, event):
"""Activated when the rename tool is pressed."""
if self.selectedItem is not None:
if isinstance(self.selectedItem, FolderItemData):
if self.selectedItem.name == '..':
return # is a sub directory marker
self.rename()
def OnGotoCWD(self, event):
"""Activated when the goto CWD menu item is clicked."""
cwdpath = os.getcwd()
if os.getcwd() != '':
self.gotoDir(cwdpath)
#
# def OnCopyTool(self, event=None):
# """Activated when the copy tool is pressed."""
# pass # mdc - will add this in a later version
def rename(self):
"""Rename a file or directory."""
if os.path.isdir(self.selectedItem.abspath): # rename a directory
dlg = wx.TextEntryDialog(
self,
_translate('Rename folder `{}` to:').format(self.selectedItem.name),
_translate('Rename Folder'), self.selectedItem.name)
if dlg.ShowModal() == wx.ID_OK:
newName = dlg.GetValue()
try:
os.rename(self.selectedItem.abspath,
os.path.join(self.selectedItem.basename, newName))
except OSError:
dlg2 = wx.MessageDialog(
self,
_translate("Cannot rename `{}` to `{}`.").format(
self.selectedItem.name, newName),
style=wx.ICON_ERROR | wx.OK)
dlg2.ShowModal()
dlg2.Destroy()
dlg.Destroy()
return
self.gotoDir(self.currentPath) # refresh
for idx, item in enumerate(self.dirData):
abspath = os.path.join(self.currentPath, newName)
if item.abspath == abspath:
self.fileList.Select(idx, True)
self.fileList.EnsureVisible(idx)
self.selectedItem = self.dirData[idx]
self.fileList.SetFocus()
break
dlg.Destroy()
elif os.path.isfile(self.selectedItem.abspath): # rename a directory
dlg = wx.TextEntryDialog(
self,
_translate('Rename file `{}` to:').format(self.selectedItem.name),
_translate('Rename file'), self.selectedItem.name)
if dlg.ShowModal() == wx.ID_OK:
newName = dlg.GetValue()
try:
newPath = os.path.join(self.selectedItem.basename, newName)
os.rename(self.selectedItem.abspath,
newPath)
except OSError:
dlgError = wx.MessageDialog(
self,
_translate("Cannot rename `{}` to `{}`.").format(
self.selectedItem.name, newName),
style=wx.ICON_ERROR | wx.OK)
dlgError.ShowModal()
dlgError.Destroy()
dlg.Destroy()
return
self.gotoDir(self.currentPath) # refresh
for idx, item in enumerate(self.dirData):
if newPath == item.abspath:
self.fileList.Select(idx, True)
self.fileList.EnsureVisible(idx)
self.selectedItem = self.dirData[idx]
self.fileList.SetFocus()
break
dlg.Destroy()
def delete(self):
"""Delete a file or directory."""
if os.path.isdir(self.selectedItem.abspath): # delete a directory
dlg = wx.MessageDialog(
self,
_translate("Are you sure you want to PERMANENTLY delete folder "
"`{}`?").format(self.selectedItem.name),
'Confirm delete', style=wx.YES_NO | wx.NO_DEFAULT |
wx.ICON_WARNING)
if dlg.ShowModal() == wx.ID_YES:
try:
os.rmdir(self.selectedItem.abspath)
except FileNotFoundError: # file was removed
dlgError = wx.MessageDialog(
self, _translate("Cannot delete folder `{}`, directory does not "
"exist.").format(self.selectedItem.name),
'Error', style=wx.OK | wx.ICON_ERROR)
dlgError.ShowModal()
dlgError.Destroy()
except OSError: # permission or directory not empty error
dlgError = wx.MessageDialog(
self, _translate("Cannot delete folder `{}`, directory is not "
"empty or permission denied.").format(
self.selectedItem.name),
'Error', style=wx.OK | wx.ICON_ERROR)
dlgError.ShowModal()
dlgError.Destroy()
self.gotoDir(self.currentPath)
dlg.Destroy()
elif os.path.isfile(self.selectedItem.abspath): # delete a file
dlg = wx.MessageDialog(
self, _translate("Are you sure you want to PERMANENTLY delete file "
"`{}`?").format(self.selectedItem.name),
'Confirm delete', style=wx.YES_NO | wx.NO_DEFAULT |
wx.ICON_WARNING)
if dlg.ShowModal() == wx.ID_YES:
try:
os.remove(self.selectedItem.abspath)
except FileNotFoundError:
dlgError = wx.MessageDialog(
self, _translate("Cannot delete folder `{}`, file does not "
"exist.").format(self.selectedItem.name),
'Error', style=wx.OK | wx.ICON_ERROR)
dlgError.ShowModal()
dlgError.Destroy()
except OSError:
dlgError = wx.MessageDialog(
self, _translate("Cannot delete file `{}`, permission "
"denied.").format(self.selectedItem.name),
'Error', style=wx.OK | wx.ICON_ERROR)
dlgError.ShowModal()
dlgError.Destroy()
self.gotoDir(self.currentPath)
dlg.Destroy()
def OnAddrEnter(self, evt=None):
"""When enter is pressed."""
path = self.txtAddr.GetValue()
if path == self.currentPath:
return
if os.path.isdir(path):
self.gotoDir(path)
else:
dlg = wx.MessageDialog(
self,
_translate("Specified path `{}` is not a directory.").format(path),
style=wx.ICON_ERROR | wx.OK)
dlg.ShowModal()
dlg.Destroy()
self.txtAddr.SetValue(self.currentPath)
def OnItemActivated(self, evt):
"""Even for when an item is double-clicked or activated."""
if self.selectedItem is not None:
if isinstance(self.selectedItem, FolderItemData):
self.gotoDir(self.selectedItem.abspath)
elif isinstance(self.selectedItem, FileItemData):
# add some mimetypes which aren't recognised by default
mimetypes.add_type("text/xml", ".psyexp")
mimetypes.add_type("text/json", ".psyrun")
mimetypes.add_type("text/markdown", ".md")
mimetypes.add_type("text/config", ".cfg")
mimetypes.add_type("text/plain", ".log")
mimetypes.add_type("text/plain", ".yaml")
# try to guess data type
dataType = mimetypes.guess_type(self.selectedItem.abspath)[0]
if dataType and "text" in dataType:
# open text files in editor
self.coder.fileOpen(None, self.selectedItem.abspath)
else:
# open other files in system default
if sys.platform == 'win32':
cmd = 'explorer'
elif sys.platform == 'darwin':
cmd = 'open'
elif sys.platform == 'linux':
cmd = 'xdg-open'
else:
return # not supported
subprocess.run(
[cmd, self.selectedItem.abspath], shell=True)
def OnItemSelected(self, evt=None):
"""Event for when an item is selected."""
itemIdx = self.fileList.GetFirstSelected()
if itemIdx >= 0:
self.selectedItem = self.dirData[itemIdx]
def scanDir(self, path):
"""Scan a directory and update file and folder items."""
self.dirData = []
# are we in a sub directory?
upPath = os.path.abspath(os.path.join(path, '..'))
if upPath != path: # add special item that goes up a directory
self.dirData.append(FolderItemData('..', upPath, None))
# scan the directory and create item objects
try:
contents = os.listdir(path)
for f in contents:
absPath = os.path.join(path, f)
if os.path.isdir(absPath):
self.dirData.append(FolderItemData(f, absPath, path))
for f in contents:
absPath = os.path.join(path, f)
if os.path.isfile(absPath):
fsize = convertBytes(os.stat(absPath).st_size)
self.dirData.append(
FileItemData(f, absPath, path, fsize, None))
except OSError:
dlg = wx.MessageDialog(
self,
_translate("Cannot access directory `{}`, permission denied.").format(path),
style=wx.ICON_ERROR | wx.OK)
dlg.ShowModal()
dlg.Destroy()
return False
return True
def updateFileBrowser(self):
"""Update the contents of the file browser.
"""
# start off with adding folders to the list
self.fileList.DeleteAllItems()
for obj in self.dirData:
if isinstance(obj, FolderItemData):
if obj.name == '..':
img = self.fileImgInds['..']
else:
img = self.fileImgInds['\\']
self.fileList.InsertItem(
self.fileList.GetItemCount(), obj.name, img)
elif isinstance(obj, FileItemData):
ext = os.path.splitext(obj.name)[1]
if ext in self.fileImgInds:
img = self.fileImgInds[ext]
else:
img = self.fileImgInds['.?']
self.fileList.InsertItem(
self.fileList.GetItemCount(),
obj.name,
img)
#self.fileList.SetItem(index, 1, obj.fsize)
#self.fileList.SetItem(index, 2, obj.mod)
# Enable/disable "go to current file" button based on current file
self.currentFileBtn.Enable(self.GetTopLevelParent().filename is not None)
def addItem(self, name, absPath):
"""Add an item to the directory browser."""
pass
def gotoDir(self, path):
"""Set the file browser to a directory."""
# check if a directory
if not os.path.isdir(path):
dlg = wx.MessageDialog(
self,
_translate("Cannot access directory `{}`, not a directory.").format(path),
style=wx.ICON_ERROR | wx.OK)
dlg.ShowModal()
dlg.Destroy()
return
# check if we have access
# if not os.access(path, os.R_OK):
# dlg = wx.MessageDialog(
# self,
# "Cannot access directory `{}`, permission denied.".format(path),
# style=wx.ICON_ERROR | wx.OK)
# dlg.ShowModal()
# return
# update files and folders
if not self.scanDir(path): # if failed, return the current directory
self.gotoDir(self.currentPath)
return
# change the current path
self.currentPath = path
self.txtAddr.SetValue(self.currentPath)
self.updateFileBrowser()
| 25,352
|
Python
|
.py
| 585
| 30.164103
| 110
| 0.545495
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,803
|
colors.py
|
psychopy_psychopy/psychopy/app/themes/colors.py
|
import numpy
import wx
from . import theme
class BaseColor(wx.Colour):
"""
Essentially a wx.Colour with some extra features for convenience
"""
def __add__(self, other):
# Get own RGB value
rgb = numpy.array([self.Red(), self.Green(), self.Blue()])
# Get adjustment
adj = self._getAdj(other)
# Do addition
result = numpy.clip(rgb + adj, 0, 255)
# Create new wx.Colour object from result
return wx.Colour(result[0], result[1], result[2], self.Alpha())
def __sub__(self, other):
# Get own RGB value
rgb = numpy.array([self.Red(), self.Green(), self.Blue()])
# Get adjustment
adj = self._getAdj(other)
# Do subtraction
result = numpy.clip(rgb - adj, 0, 255)
# Create new wx.Colour object from result
return wx.Colour(result[0], result[1], result[2], self.Alpha())
def __mul__(self, other):
assert isinstance(other, (int, float)), (
"BaseColor can only be multiplied by a float (0-1) or int (0-255), as this sets its alpha."
)
# If given as a float, convert to 255
if isinstance(other, float):
other = round(other * 255)
# Set alpha
return wx.Colour(self.Red(), self.Green(), self.Blue(), alpha=other)
@staticmethod
def _getAdj(other):
"""
Get the adjustment indicated by another object given to this as an operator for __add__ or __sub__
"""
# If other is also a wx.Colour, adjustment is its RGBA value
if isinstance(other, wx.Colour):
adj = numpy.array([other.Red(), other.Green(), other.Blue()])
# If other is an int, adjustment is itself*15
elif isinstance(other, int):
adj = other * 15
# Otherwise, just treat it as an RGBA array
else:
adj = numpy.array(other)
return adj
# PsychoPy brand colours
scheme = {
'none': BaseColor(0, 0, 0, 0),
'white': BaseColor(255, 255, 255, 255),
'offwhite': BaseColor(242, 242, 242, 255),
'grey': BaseColor(102, 102, 110, 255),
'lightgrey': BaseColor(172, 172, 176, 255),
'black': BaseColor(0, 0, 0, 255),
'red': BaseColor(242, 84, 91, 255),
'purple': BaseColor(195, 190, 247, 255),
'blue': BaseColor(2, 169, 234, 255),
'green': BaseColor(108, 204, 116, 255),
'yellow': BaseColor(241, 211, 2, 255),
'orange': BaseColor(236, 151, 3, 255),
}
class AppColors(dict):
light = {
"text": scheme['black'],
"frame_bg": scheme['offwhite'] - 1,
"docker_bg": scheme['offwhite'] - 2,
"docker_fg": scheme['black'],
"panel_bg": scheme['offwhite'],
"tab_bg": scheme['white'],
"bmpbutton_bg_hover": scheme['offwhite'] - 1,
"bmpbutton_fg_hover": scheme['black'],
"txtbutton_bg_hover": scheme['red'],
"txtbutton_fg_hover": scheme['offwhite'],
"rt_timegrid": scheme['grey'],
"rt_comp": scheme['blue'],
"rt_comp_force": scheme['orange'],
"rt_comp_disabled": scheme['offwhite'] - 2,
"rt_static": scheme['red'] * 75,
"rt_static_disabled": scheme['grey'] * 75,
"fl_routine_fg": scheme['offwhite'] + 1,
"fl_routine_bg_slip": scheme['blue'],
"fl_routine_bg_nonslip": scheme['green'],
"fl_flowline_bg": scheme['grey'],
"fl_flowline_fg": scheme['white'] + 1,
}
dark = {
"text": scheme['offwhite'],
"frame_bg": scheme['grey'] - 1,
"docker_bg": scheme['grey'] - 2,
"docker_fg": scheme['offwhite'],
"panel_bg": scheme['grey'],
"tab_bg": scheme['grey'] + 1,
"bmpbutton_bg_hover": scheme['grey'] + 1,
"bmpbutton_fg_hover": scheme['offwhite'],
"txtbutton_bg_hover": scheme['red'],
"txtbutton_fg_hover": scheme['offwhite'],
"rt_timegrid": scheme['grey'] + 2,
"rt_comp": scheme['blue'],
"rt_comp_force": scheme['orange'],
"rt_comp_disabled": scheme['grey'],
"rt_static": scheme['red'] * 75,
"rt_static_disabled": scheme['white'] * 75,
"fl_routine_fg": scheme['white'],
"fl_routine_bg_slip": scheme['blue'],
"fl_routine_bg_nonslip": scheme['green'],
"fl_flowline_bg": scheme['offwhite'] - 1,
"fl_flowline_fg": scheme['black'],
}
contrast_white = {
"text": scheme['black'],
"frame_bg": scheme['offwhite'] + 1,
"docker_bg": scheme['yellow'],
"docker_fg": scheme['black'],
"panel_bg": scheme['offwhite'],
"tab_bg": scheme['offwhite'] + 1,
"bmpbutton_bg_hover": scheme['red'],
"bmpbutton_fg_hover": scheme['offwhite'],
"txtbutton_bg_hover": scheme['red'],
"txtbutton_fg_hover": scheme['offwhite'],
"rt_timegrid": scheme['black'],
"rt_comp": scheme['blue'],
"rt_comp_force": scheme['orange'],
"rt_comp_disabled": scheme['grey'],
"rt_static": scheme['red'] * 75,
"rt_static_disabled": scheme['grey'] * 75,
"fl_routine_fg": scheme['offwhite'] + 1,
"fl_routine_bg_slip": scheme['blue'],
"fl_routine_bg_nonslip": scheme['green'],
"fl_flowline_bg": scheme['black'],
"fl_flowline_fg": scheme['offwhite'] + 1,
}
contrast_black = {
"text": scheme['offwhite'],
"frame_bg": scheme['black'],
"docker_bg": "#800080",
"docker_fg": scheme['offwhite'],
"panel_bg": scheme['black'] + 1,
"tab_bg": scheme['black'] + 1,
"bmpbutton_bg_hover": scheme['red'],
"bmpbutton_fg_hover": scheme['offwhite'],
"txtbutton_bg_hover": scheme['red'],
"txtbutton_fg_hover": scheme['offwhite'],
"rt_timegrid": scheme['offwhite'],
"rt_comp": scheme['blue'],
"rt_comp_force": scheme['orange'],
"rt_comp_disabled": scheme['grey'],
"rt_static": scheme['red'] * 75,
"rt_static_disabled": scheme['grey'] * 75,
"fl_routine_fg": scheme['white'],
"fl_routine_bg_slip": scheme['blue'],
"fl_routine_bg_nonslip": scheme['green'],
"fl_flowline_bg": scheme['offwhite'],
"fl_flowline_fg": scheme['black'],
}
pink = {
"text": scheme['red'] - 10,
"frame_bg": scheme['red'] + 8,
"docker_bg": scheme['red'] + 7,
"docker_fg": scheme['red'] - 10,
"panel_bg": scheme['red'] + 9,
"tab_bg": scheme['red'] + 10,
"bmpbutton_bg_hover": scheme['red'] + 7,
"bmpbutton_fg_hover": scheme['red'] - 10,
"txtbutton_bg_hover": scheme['red'] + 7,
"txtbutton_fg_hover": scheme['red'] - 10,
"rt_timegrid": scheme['red'] + 4,
"rt_comp": scheme['blue'] + 12,
"rt_comp_force": scheme['orange'] + 12,
"rt_comp_disabled": scheme['red'] + 6,
"rt_static": scheme['white'] * 170,
"rt_static_disabled": scheme['red'] * 21,
"fl_routine_fg": scheme['red'] - 10,
"fl_routine_bg_slip": scheme['blue'] + 12,
"fl_routine_bg_nonslip": scheme['green'] + 8,
"fl_flowline_bg": scheme['red'] + 4,
"fl_flowline_fg": scheme['red'] - 10,
}
def __getitem__(self, item):
# When getting an attribute of this object, return the key from the theme-appropriate dict
return getattr(self, theme.app)[item]
app = AppColors()
| 7,425
|
Python
|
.py
| 184
| 32.217391
| 106
| 0.556202
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,804
|
ui.py
|
psychopy_psychopy/psychopy/app/themes/ui.py
|
import subprocess
import sys
from copy import copy
import wx
from pathlib import Path
from . import theme, Theme
from psychopy.localization import _translate
from psychopy.tools import filetools as ft
from ... import prefs
menuCache = []
class ThemeSwitcher(wx.Menu):
"""Class to make a submenu for switching theme, meaning that the menu will
always be the same across frames."""
order = ["PsychopyDark", "PsychopyLight", "ClassicDark", "Classic"]
def __init__(self, app):
self.app = app
# Get list of themes
themeFolder = Path(prefs.paths['themes'])
themeList = []
for file in themeFolder.glob("*.json"):
themeList.append(Theme(file.stem))
# Reorder so that priority items are at the start
self.themes = []
order = copy(self.order)
order.reverse()
for name in order:
for i, obj in enumerate(themeList):
if obj.code == name:
self.themes.append(themeList.pop())
self.themes.extend(themeList)
# Make menu
wx.Menu.__init__(self)
# Make buttons
for obj in self.themes:
item = self.AppendRadioItem(id=wx.ID_ANY, item=obj.code, help=obj.info)
item.Check(obj == theme)
self.Bind(wx.EVT_MENU, self.onThemeChange, item)
self.AppendSeparator()
# Add Theme Folder button
item = self.Append(wx.ID_ANY, _translate("&Open theme folder"))
self.Bind(wx.EVT_MENU, self.openThemeFolder, item)
# Cache self
menuCache.append(self)
def onThemeChange(self, evt):
"""Handles a theme change event"""
# Set theme at app level
newTheme = self.FindItemById(evt.GetId()).ItemLabel
self.app.theme = newTheme
# Update other theme menus with new value
global menuCache
for menu in menuCache.copy():
# Skip deleted menus
try:
menu.GetRefData()
except RuntimeError:
menuCache.remove(menu)
continue
for item in menu.GetMenuItems():
# Skip non-checkable buttons (aka the Theme Folder button)
if not item.IsCheckable():
continue
# Check or uncheck item to match current theme
item.Check(menu.GetLabelText(item.GetId()) == newTheme)
def openThemeFolder(self, event=None):
ft.openInExplorer(prefs.paths['themes'])
| 2,517
|
Python
|
.py
| 65
| 29.4
| 83
| 0.612362
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,805
|
handlers.py
|
psychopy_psychopy/psychopy/app/themes/handlers.py
|
from copy import deepcopy
from . import colors, icons, theme
from ...preferences.preferences import prefs
# --- Functions to handle specific subclasses of wx.Window ---
import wx
import wx.lib.agw.aui as aui
import wx.stc as stc
import wx.richtext
from wx.html import HtmlWindow
def styleFrame(target):
# Set background color
target.SetBackgroundColour(colors.app['frame_bg'])
# Set foreground color
target.SetForegroundColour(colors.app['text'])
# Set aui art provider
if hasattr(target, 'getAuiManager'):
target.getAuiManager().SetArtProvider(PsychopyDockArt())
target.getAuiManager().Update()
def stylePanel(target):
# Set background color
target.SetBackgroundColour(colors.app['panel_bg'])
# Set text color
target.SetForegroundColour(colors.app['text'])
target.Refresh()
def styleToolbar(target):
# Set background color
target.SetBackgroundColour(colors.app['frame_bg'])
# Recreate tools
target.makeTools()
target.Realize()
def styleNotebook(target):
# Set art provider to style tabs
target.SetArtProvider(PsychopyTabArt())
# Set dock art provider to get rid of outline
target.GetAuiManager().SetArtProvider(PsychopyDockArt())
# Iterate through each page
for index in range(target.GetPageCount()):
page = target.GetPage(index)
# Set page background
page.SetBackgroundColour(colors.app['panel_bg'])
# If page points to an icon for the tab, set it
if hasattr(page, "tabIcon"):
btn = icons.ButtonIcon(page.tabIcon, size=(16, 16))
target.SetPageBitmap(index, btn.bitmap)
target.Refresh()
target.GetAuiManager().Update()
def styleCodeEditor(target):
from . import fonts
fonts.coderTheme.load(theme.code)
target.SetBackgroundColour(colors.app['tab_bg'])
# Set margin
margin = fonts.coderTheme.margin
target.SetFoldMarginColour(True, margin.backColor)
target.SetFoldMarginHiColour(True, margin.backColor)
# style folding interface
for marknum, mark in [
(wx.stc.STC_MARKNUM_FOLDEREND, wx.stc.STC_MARK_BOXPLUSCONNECTED),
(wx.stc.STC_MARKNUM_FOLDEROPENMID, wx.stc.STC_MARK_BOXMINUSCONNECTED),
(wx.stc.STC_MARKNUM_FOLDEROPEN, wx.stc.STC_MARK_BOXMINUS),
(wx.stc.STC_MARKNUM_FOLDER, wx.stc.STC_MARK_BOXPLUS),
(wx.stc.STC_MARKNUM_FOLDERSUB, wx.stc.STC_MARK_VLINE),
(wx.stc.STC_MARKNUM_FOLDERTAIL, wx.stc.STC_MARK_LCORNER),
(wx.stc.STC_MARKNUM_FOLDERMIDTAIL, wx.stc.STC_MARK_TCORNER),
]:
target.MarkerDefine(
marknum, mark,
fonts.coderTheme.margin.backColor, fonts.coderTheme.margin.foreColor
)
# Set caret colour
caret = fonts.coderTheme.caret
target.SetCaretForeground(caret.foreColor)
target.SetCaretLineBackground(caret.backColor)
target.SetCaretWidth(1 + (caret.bold))
# Set selection colour
select = fonts.coderTheme.select
target.SetSelForeground(True, select.foreColor)
target.SetSelBackground(True, select.backColor)
# Set wrap point
target.edgeGuideColumn = prefs.coder['edgeGuideColumn']
target.edgeGuideVisible = target.edgeGuideColumn > 0
# Set line spacing
spacing = min(int(prefs.coder['lineSpacing'] / 2), 64) # Max out at 64
target.SetExtraAscent(spacing)
target.SetExtraDescent(spacing)
# Set styles
for tag, font in fonts.coderTheme.items():
if tag is None:
# Skip tags for e.g. margin, caret
continue
if isinstance(font, dict) and tag == target.GetLexer():
# If tag is the current lexer, then get styles from sub-dict
for subtag, subfont in font.items():
target.StyleSetSize(subtag, subfont.pointSize)
target.StyleSetFaceName(subtag, subfont.obj.GetFaceName())
target.StyleSetBold(subtag, subfont.bold)
target.StyleSetItalic(subtag, subfont.italic)
target.StyleSetForeground(subtag, subfont.foreColor)
target.StyleSetBackground(subtag, subfont.backColor)
elif isinstance(font, dict):
# If tag is another lexer, skip
continue
else:
# If tag is a direct style tag, apply
target.StyleSetSize(tag, font.pointSize)
target.StyleSetFaceName(tag, font.obj.GetFaceName())
target.StyleSetBold(tag, font.bold)
target.StyleSetItalic(tag, font.italic)
target.StyleSetForeground(tag, font.foreColor)
target.StyleSetBackground(tag, font.backColor)
# Update lexer keywords
lexer = target.GetLexer()
filename = ""
if hasattr(target, "filename"):
filename = target.filename
keywords = fonts.getLexerKeywords(lexer, filename)
for level, val in keywords.items():
target.SetKeyWords(level, " ".join(val))
def styleTextCtrl(target):
from . import fonts
fonts.coderTheme.load(theme.code)
font = fonts.coderTheme.base
# Set background
target.SetBackgroundColour(font.backColor)
target.SetForegroundColour(font.foreColor)
# Construct style
style = wx.TextAttr(
colText=font.foreColor,
colBack=font.backColor,
font=font.obj,
)
if isinstance(target, wx.richtext.RichTextCtrl):
style = wx.richtext.RichTextAttr(style)
# Set base style
target.SetDefaultStyle(style)
# Update
target.Refresh()
target.Update()
def styleListCtrl(target):
target.SetBackgroundColour(colors.app['tab_bg'])
target.SetTextColour(colors.app['text'])
target.Refresh()
def styleHTMLCtrl(target):
target.SetBackgroundColour(colors.app['tab_bg'])
# Define dict linking object types to style functions
methods = {
wx.Frame: styleFrame,
wx.Panel: stylePanel,
aui.AuiNotebook: styleNotebook,
stc.StyledTextCtrl: styleCodeEditor,
wx.TextCtrl: styleTextCtrl,
wx.richtext.RichTextCtrl: styleTextCtrl,
wx.ToolBar: styleToolbar,
wx.ListCtrl: styleListCtrl,
HtmlWindow: styleHTMLCtrl
}
class ThemeMixin:
"""
Mixin class for wx.Window objects, which adds a getter/setter `theme` which will identify children and style them
according to theme.
"""
@property
def theme(self):
if hasattr(self, "_theme"):
return self._theme
@theme.setter
def theme(self, value):
# Skip method if theme value is unchanged
if value == self.theme:
return
# Store value
self._theme = deepcopy(value)
# Do own styling
self._applyAppTheme()
# Get children
children = []
if hasattr(self, 'GetChildren'):
for child in self.GetChildren():
if child not in children:
children.append(child)
if isinstance(self, aui.AuiNotebook):
for index in range(self.GetPageCount()):
page = self.GetPage(index)
if page not in children:
children.append(page.window)
if hasattr(self, 'GetSizer') and self.GetSizer():
for child in self.GetSizer().GetChildren():
if child not in children:
children.append(child.Window)
if hasattr(self, 'MenuItems'):
for child in self.MenuItems:
if child not in children:
children.append(child)
if hasattr(self, "GetToolBar"):
tb = self.GetToolBar()
if tb not in children:
children.append(tb)
# For each child, do styling
for child in children:
if isinstance(child, ThemeMixin):
# If child is a ThemeMixin subclass, we can just set theme
child.theme = self.theme
elif hasattr(child, "_applyAppTheme"):
# If it's manually been given an _applyAppTheme function, use it
child._applyAppTheme()
else:
# Otherwise, look for appropriate method in methods array
for cls, fcn in methods.items():
if isinstance(child, cls):
# If child extends this class, call the appropriate method on it
fcn(child)
def _applyAppTheme(self):
"""
Method for applying app theme to self. By default is the same method as for applying to panels, buttons, etc.
but can be overloaded when subclassing from ThemeMixin to control behaviour on specific objects.
"""
for cls, fcn in methods.items():
if isinstance(self, cls):
# If child extends this class, call the appropriate method on it
fcn(self)
class PsychopyDockArt(aui.AuiDefaultDockArt):
def __init__(self):
aui.AuiDefaultDockArt.__init__(self)
# Gradient
self._gradient_type = aui.AUI_GRADIENT_NONE
# Background
self._background_colour = colors.app['frame_bg']
self._background_gradient_colour = colors.app['frame_bg']
self._background_brush = wx.Brush(self._background_colour)
# Border
self._border_size = 0
self._border_pen = wx.Pen(colors.app['frame_bg'])
# Sash
self._draw_sash = True
self._sash_size = 5
self._sash_brush = wx.Brush(colors.app['frame_bg'])
# Gripper
self._gripper_brush = wx.Brush(colors.app['frame_bg'])
self._gripper_pen1 = wx.Pen(colors.app['frame_bg'])
self._gripper_pen2 = wx.Pen(colors.app['frame_bg'])
self._gripper_pen3 = wx.Pen(colors.app['frame_bg'])
self._gripper_size = 0
# Hint
self._hint_background_colour = colors.app['frame_bg']
# Caption bar
self._inactive_caption_colour = colors.app['docker_bg']
self._inactive_caption_gradient_colour = colors.app['docker_bg']
self._inactive_caption_text_colour = colors.app['docker_fg']
self._active_caption_colour = colors.app['docker_bg']
self._active_caption_gradient_colour = colors.app['docker_bg']
self._active_caption_text_colour = colors.app['docker_fg']
# self._caption_font
self._caption_size = 25
self._button_size = 20
class PsychopyTabArt(aui.AuiDefaultTabArt):
def __init__(self):
aui.AuiDefaultTabArt.__init__(self)
self.SetDefaultColours()
self.SetAGWFlags(aui.AUI_NB_NO_TAB_FOCUS)
self.SetBaseColour(colors.app['tab_bg'])
self._background_top_colour = colors.app['panel_bg']
self._background_bottom_colour = colors.app['panel_bg']
self._tab_text_colour = lambda page: colors.app['text']
self._tab_top_colour = colors.app['tab_bg']
self._tab_bottom_colour = colors.app['tab_bg']
self._tab_gradient_highlight_colour = colors.app['tab_bg']
self._border_colour = colors.app['tab_bg']
self._border_pen = wx.Pen(self._border_colour)
self._tab_disabled_text_colour = colors.app['text']
self._tab_inactive_top_colour = colors.app['panel_bg']
self._tab_inactive_bottom_colour = colors.app['panel_bg']
def DrawTab(self, dc, wnd, page, in_rect, close_button_state, paint_control=False):
"""
Overloads AuiDefaultTabArt.DrawTab to add a transparent border to inactive tabs
"""
if page.active:
self._border_pen = wx.Pen(self._border_colour)
else:
self._border_pen = wx.TRANSPARENT_PEN
return aui.AuiDefaultTabArt.DrawTab(self, dc, wnd, page, in_rect, close_button_state, paint_control)
| 11,688
|
Python
|
.py
| 279
| 33.458781
| 117
| 0.652767
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,806
|
__init__.py
|
psychopy_psychopy/psychopy/app/themes/__init__.py
|
import json
from pathlib import Path
from ... import logging, prefs
_cache = {}
class Theme:
# Tag pointing to code colors
code = "PsychopyLight"
# Tag pointing to app colors
app = "light"
# Tag pointing to app icons
icons = "light"
# Tooltip for theme menu
info = ""
def __init__(self, name):
self.set(name)
def set(self, name):
# Get spec file from name
specFile = Path(prefs.paths['themes']) / (name.replace(" ", "") + ".json")
# Ensure spec file exists
if not specFile.is_file():
# If no file, use PsychopyLight
logging.warn(f"Theme file for '{name}' not found, reverting to PsychopyLight")
name = "PsychopyLight"
specFile = Path(__file__).parent / "spec" / "PsychopyLight.json"
# Load file
spec = loadSpec(specFile)
# Ensure code spec is present
if "code" not in spec:
# If no code spec, use PsychopyLight
logging.warn(f"Code color spec for '{name}' not found, reverting to PsychopyLight")
default = loadSpec(Path(__file__).parent / "spec" / "PsychopyLight.json")
spec['code'] = default
# Store theme name as code colors
self.code = name
# If spec file points to a set of app colors, update this object
if "app" in spec:
self.app = spec['app']
# If spec file points to a set of app icons, update this object
if "icons" in spec:
self.icons = spec['icons']
# If spec file contains tooltip, store it
if "info" in spec:
self.info = spec['info']
def __repr__(self):
return f"<{self.code}: app={self.app}, icons={self.icons}>"
def __eq__(self, other):
# If other is also a Theme, check that all its values are the same
if isinstance(other, Theme):
app = self.app == other.app
icons = self.icons == other.icons
code = self.code.replace(" ", "").lower() == other.code.replace(" ", "").lower()
return app and icons and code
def __deepcopy__(self, memo=None):
return Theme(self.code)
def loadSpec(file):
# Convert to path
if isinstance(file, str):
file = Path(file)
# If filename is not already cached, load and cache the file
if file.stem not in _cache:
with open(file) as f:
_cache[file] = json.load(f)
# Return cached values
return _cache[file]
theme = Theme("PsychopyLight")
| 2,539
|
Python
|
.py
| 65
| 30.907692
| 95
| 0.591223
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,807
|
fonts.py
|
psychopy_psychopy/psychopy/app/themes/fonts.py
|
import builtins
import keyword
import sys
from pathlib import Path
import wx
import wx.stc as stc
import re
from ... import prefs
from . import colors, theme, loadSpec
# STC tags corresponding to words in theme spec
tags = {
"base": stc.STC_STYLE_DEFAULT,
"margin": stc.STC_STYLE_LINENUMBER,
"caret": None,
"select": None,
"indent": stc.STC_STYLE_INDENTGUIDE,
"brace": stc.STC_STYLE_BRACELIGHT,
"controlchar": stc.STC_STYLE_CONTROLCHAR,
# Python
"python": {
"operator": stc.STC_P_OPERATOR,
"keyword": stc.STC_P_WORD,
"keyword2": stc.STC_P_WORD2,
"id": stc.STC_P_IDENTIFIER,
"num": stc.STC_P_NUMBER,
"char": stc.STC_P_CHARACTER,
"str": stc.STC_P_STRING,
"openstr": stc.STC_P_STRINGEOL,
"decorator": stc.STC_P_DECORATOR,
"def": stc.STC_P_DEFNAME,
"class": stc.STC_P_CLASSNAME,
"comment": stc.STC_P_COMMENTLINE,
"commentblock": stc.STC_P_COMMENTBLOCK,
"documentation": stc.STC_P_TRIPLE,
"documentation2": stc.STC_P_TRIPLEDOUBLE,
"whitespace": stc.STC_P_DEFAULT
},
# R
"r": {
"operator": stc.STC_R_OPERATOR,
"keyword": stc.STC_R_BASEKWORD,
"keyword2": stc.STC_R_KWORD,
"id": stc.STC_R_IDENTIFIER,
"num": stc.STC_R_NUMBER,
"char": stc.STC_R_STRING2,
"str": stc.STC_R_STRING,
"infix": stc.STC_R_INFIX,
"openinfix": stc.STC_R_INFIXEOL,
"comment": stc.STC_R_COMMENT,
"whitespace": stc.STC_R_DEFAULT
},
# C++
"c++": {
"operator": stc.STC_C_OPERATOR,
"keyword": stc.STC_C_WORD,
"keyword2": stc.STC_C_WORD2,
"id": stc.STC_C_IDENTIFIER,
"num": stc.STC_C_NUMBER,
"char": stc.STC_C_CHARACTER,
"str": stc.STC_C_STRING,
"openstr": stc.STC_C_STRINGEOL,
"class": stc.STC_C_GLOBALCLASS,
"comment": stc.STC_C_COMMENT,
"commentblock": stc.STC_C_COMMENTLINE,
"commentkw": stc.STC_C_COMMENTDOCKEYWORD,
"commenterror": stc.STC_C_COMMENTDOCKEYWORDERROR,
"documentation": stc.STC_C_COMMENTLINEDOC,
"documentation2": stc.STC_C_COMMENTDOC,
"whitespace": stc.STC_C_DEFAULT,
"preprocessor": stc.STC_C_PREPROCESSOR,
"preprocessorcomment": stc.STC_C_PREPROCESSORCOMMENT
},
# JSON
"json": {
"operator": stc.STC_JSON_OPERATOR,
"keyword": stc.STC_JSON_KEYWORD,
"uri": stc.STC_JSON_URI,
"compactiri": stc.STC_JSON_COMPACTIRI,
"error": stc.STC_JSON_ERROR,
"espacesequence": stc.STC_JSON_ESCAPESEQUENCE,
"propertyname": stc.STC_JSON_PROPERTYNAME,
"ldkeyword": stc.STC_JSON_LDKEYWORD,
"num": stc.STC_JSON_NUMBER,
"str": stc.STC_JSON_STRING,
"openstr": stc.STC_JSON_STRINGEOL,
"comment": stc.STC_JSON_LINECOMMENT,
"commentblock": stc.STC_JSON_BLOCKCOMMENT,
"whitespace": stc.STC_JSON_DEFAULT
},
# Markdown
"markdown": {
"base": stc.STC_MARKDOWN_DEFAULT,
"whitespace": stc.STC_MARKDOWN_LINE_BEGIN,
"str": stc.STC_MARKDOWN_BLOCKQUOTE,
"code": stc.STC_MARKDOWN_CODE,
"codeblock": stc.STC_MARKDOWN_CODE2,
"italic": stc.STC_MARKDOWN_EM1,
"italic2": stc.STC_MARKDOWN_EM2,
"bold": stc.STC_MARKDOWN_STRONG1,
"bold2": stc.STC_MARKDOWN_STRONG2,
"h1": stc.STC_MARKDOWN_HEADER1,
"h2": stc.STC_MARKDOWN_HEADER2,
"h3": stc.STC_MARKDOWN_HEADER3,
"h4": stc.STC_MARKDOWN_HEADER4,
"h5": stc.STC_MARKDOWN_HEADER5,
"h6": stc.STC_MARKDOWN_HEADER6,
"hr": stc.STC_MARKDOWN_HRULE,
"link": stc.STC_MARKDOWN_LINK,
"num": stc.STC_MARKDOWN_OLIST_ITEM,
"prechar": stc.STC_MARKDOWN_PRECHAR,
"li": stc.STC_MARKDOWN_ULIST_ITEM,
}
}
lexerNames = {
"python": stc.STC_LEX_PYTHON,
"c++": stc.STC_LEX_CPP,
"r": stc.STC_LEX_R,
"json": stc.STC_LEX_JSON,
"markdown": stc.STC_LEX_MARKDOWN,
}
def getLexerKeywords(lexer, filename=""):
"""
Get the keywords to look for with a given lexer.
"""
# Keywords common to all C-based languages
baseC = {
0: ['typedef', 'if', 'else', 'return', 'struct', 'for', 'while', 'do',
'using', 'namespace', 'union', 'break', 'enum', 'new', 'case',
'switch', 'continue', 'volatile', 'finally', 'throw', 'try',
'delete', 'typeof', 'sizeof', 'class', 'volatile', 'int',
'float', 'double', 'char', 'short', 'byte', 'void', 'const',
'unsigned', 'signed', 'NULL', 'true', 'false', 'bool', 'size_t',
'long', 'long long'],
1: []
}
if lexer == stc.STC_LEX_PYTHON:
# Python
keywords = {
0: keyword.kwlist + ['cdef', 'ctypedef', 'extern', 'cimport', 'cpdef', 'include'],
1: dir(builtins) + ['self']
}
elif lexer == stc.STC_LEX_R:
# R
keywords = {
1: ['function', 'for', 'repeat', 'while', 'if', 'else',
'break', 'local', 'global'],
0: ['NA']
}
elif lexer == stc.STC_LEX_CPP:
# C/C++
keywords = baseC.copy()
if filename.endswith('.js'):
# JavaScript
keywords = {
0: ['var', 'const', 'let', 'import', 'function', 'if',
'else', 'return', 'struct', 'for', 'while', 'do',
'finally', 'throw', 'try', 'switch', 'case',
'break', 'await'],
1: ['null', 'false', 'true']
}
elif any([filename.lower().endswith(ext) for ext in (
'.glsl', '.vert', '.frag')]):
# keywords
keywords[0] += [
'invariant', 'precision', 'highp', 'mediump', 'lowp',
'coherent', 'sampler', 'sampler2D', 'layout', 'out',
'in', 'varying', 'uniform', 'attribute']
# types
keywords[0] += [
'vec2', 'vec3', 'vec4', 'mat2', 'mat3', 'mat4',
'ivec2', 'ivec3', 'ivec4', 'imat2', 'imat3', 'imat4',
'bvec2', 'bvec3', 'bvec4', 'bmat2', 'bmat3', 'bmat4',
'dvec2', 'dvec3', 'dvec4', 'dmat2', 'dmat3', 'dmat4']
# reserved
keywords[1] += [
'gl_Position', 'gl_LightSourceParameters',
'gl_MaterialParameters', 'gl_LightModelProducts',
'gl_FrontLightProduct', 'gl_BackLightProduct',
'gl_FrontMaterial', 'gl_BackMaterial', 'gl_FragColor',
'gl_ModelViewMatrix', 'gl_ModelViewProjectionMatrix',
'gl_Vertex', 'gl_NormalMatrix', 'gl_Normal',
'gl_ProjectionMatrix', 'gl_LightSource']
# elif lexer stc.STC_LEX_ARDUINO:
# # Arduino
# keywords = {
# 0: baseC[0],
# 1: baseC[1] + [
# 'BIN', 'HEX', 'OCT', 'DEC', 'INPUT', 'OUTPUT', 'HIGH', 'LOW',
# 'INPUT_PULLUP', 'LED_BUILTIN', 'string', 'array']
# }
# elif lexer == stc.STC_LEX_GLSL:
# # GLSL
# glslTypes = []
# baseType = ['', 'i', 'b', 'd']
# dim = ['2', '3', '4']
# name = ['vec', 'mat']
# for i in baseType:
# for j in name:
# for k in dim:
# glslTypes.append(i + j + k)
# keywords = {
# 0: baseC[0] + ['invariant', 'precision', 'highp', 'mediump', 'lowp', 'coherent',
# 'sampler', 'sampler2D'],
# 1: baseC[1]
# }
else:
keywords = {
0: [],
1: []
}
return keywords
class CodeTheme(dict):
def __init__(self):
dict.__init__(self)
# Create base attributes
self._base = {}
self._caret = {}
self._margin = {}
self._select = {}
# Load theme
self.load(theme.code)
def __getitem__(self, item):
# If theme isn't cached yet, load & cache it
self.load(theme.code)
# Return value from theme cache
return dict.__getitem__(self, theme.code)[item]
def __getattr__(self, attr):
# If theme isn't cached yet, load & cache it
self.load(theme.code)
# Return value
return getattr(self, attr)
def items(self):
# If theme isn't cached yet, load & cache it
self.load(theme.code)
return dict.__getitem__(self, theme.code).items()
def values(self):
# If theme isn't cached yet, load & cache it
self.load(theme.code)
return dict.__getitem__(self, theme.code).values()
def keys(self):
# If theme isn't cached yet, load & cache it
self.load(theme.code)
return dict.__getitem__(self, theme.code).keys()
def __iter__(self):
# If theme isn't cached yet, load & cache it
self.load(theme.code)
return dict.__getitem__(self, theme.code).__iter__()
@property
def base(self):
if theme.code not in self._base:
self.load(theme.code)
return self._base[theme.code]
@base.setter
def base(self, value):
self._base[theme.code] = value
@property
def caret(self):
if theme.code not in self._caret:
self.load(theme.code)
return self._caret[theme.code]
@caret.setter
def caret(self, value):
self._caret[theme.code] = value
@property
def margin(self):
if theme.code not in self._margin:
self.load(theme.code)
return self._margin[theme.code]
@margin.setter
def margin(self, value):
self._margin[theme.code] = value
@property
def select(self):
if theme.code not in self._select:
self.load(theme.code)
return self._select[theme.code]
@select.setter
def select(self, value):
self._select[theme.code] = value
def load(self, name):
# If already loaded, just set base attributes, don't load again
if theme.code in self:
CodeFont.pointSize = self.base.pointSize
CodeFont.foreColor = self.base.foreColor
CodeFont.backColor = self.base.backColor
CodeFont.faceNames = self.base.faceNames
CodeFont.bold = self.base.bold
CodeFont.italic = self.base.italic
return
cache = {}
# Load theme from file
filename = Path(prefs.paths['themes']) / (theme.code + ".json")
spec = loadSpec(filename)
# Set base attributes
self.base = CodeFont(*extractAll(spec['code']['base']))
CodeFont.pointSize = self.base.pointSize
CodeFont.foreColor = self.base.foreColor
CodeFont.backColor = self.base.backColor
CodeFont.faceNames = self.base.faceNames
CodeFont.bold = self.base.bold
CodeFont.italic = self.base.italic
# Store other non-tag spec
for attr in ('caret', 'margin', 'select'):
if attr in spec['code']:
val = CodeFont(*extractAll(spec['code'][attr]))
else:
val = CodeFont()
setattr(self, attr, val)
# Find style associated with each tag
for key, tag in tags.items():
# Skip None
if tag is None:
continue
elif key.lower() in lexerNames:
# If tag is a lexer, store in a sub-dict
lex = lexerNames[key]
cache[lex] = {}
# If lexer isn't described in spec, skip
if key not in spec['code']:
continue
for subkey, subtag in tag.items():
# For each subtag, extract font
if subkey in spec['code'][key]:
# If font is directly specified, use it
cache[lex][subtag] = CodeFont(*extractAll(spec['code'][key][subkey]))
elif subkey in spec['code']:
# If font is not directly specified, use universal equivalent
cache[lex][subtag] = CodeFont(*extractAll(spec['code'][subkey]))
elif key in spec['code']:
# If tag is a tag, extract font
cache[tag] = CodeFont(*extractAll(spec['code'][key]))
else:
cache[tag] = CodeFont()
# Store cache
dict.__setitem__(self, name, cache)
class CodeFont:
# Defaults are defined at class level, so they can change with theme
pointSize = 12
foreColor = "#000000"
backColor = "#FFFFFF"
faceNames = ["JetBrains Mono", "Monaco", "Consolas"]
bold = False
italic = False
def __init__(self, pointSize=None, foreColor=None, backColor=None, faceNames=None, bold=None, italic=None):
# Set point size
if pointSize in (None, ""):
pointSize = CodeFont.pointSize
self.pointSize = pointSize
# Set foreground color
if foreColor in (None, ""):
foreColor = CodeFont.foreColor
self.foreColor = foreColor
# Set background color
if backColor in (None, ""):
backColor = CodeFont.backColor
self.backColor = backColor
# Set font face
if faceNames in (None, ""):
faceNames = CodeFont.faceNames
self.faceNames = faceNames
# Set bold
if bold in (None, ""):
bold = CodeFont.bold
self.bold = bold
# Set italic
if italic in (None, ""):
italic = CodeFont.italic
self.italic = italic
@property
def obj(self):
# If wx.Font object not created, create one
if not hasattr(self, "_obj"):
# Make wx.FontInfo object
info = wx.FontInfo(self.pointSize).Bold(self.bold).Italic(self.italic)
# Make wx.Font object
self._obj = wx.Font(info)
# Try faces sequentially until one works
success = False
for name in self.faceNames:
success = self._obj.SetFaceName(name)
if success:
break
# If nothing worked, use the default monospace
if not success:
self._obj = wx.SystemSettings.GetFont(wx.SYS_ANSI_FIXED_FONT)
return self._obj
@obj.setter
def obj(self, value):
self._obj = value
def __repr__(self):
return (
f"<{type(self).__name__}: "
f"pointSize={self.pointSize}, "
f"foreColor={self.foreColor}, backColor={self.backColor}, "
f"faceName={self.obj.GetFaceName()}, bold={self.bold}, italic={self.italic}"
f">"
)
class AppTheme(dict):
def __getitem__(self, item):
# If theme isn't cached yet, load & cache it
self.load(theme.app)
# Return value from theme cache
return dict.__getitem__(self, theme.app)[item]
def __getattr__(self, attr):
# If theme isn't cached yet, load & cache it
self.load(theme.app)
# Return value
return getattr(self, attr)
def items(self):
# If theme isn't cached yet, load & cache it
self.load(theme.app)
return dict.__getitem__(self, theme.app).items()
def values(self):
# If theme isn't cached yet, load & cache it
self.load(theme.app)
return dict.__getitem__(self, theme.app).values()
def keys(self):
# If theme isn't cached yet, load & cache it
self.load(theme.app)
return dict.__getitem__(self, theme.app).keys()
def __iter__(self):
# If theme isn't cached yet, load & cache it
self.load(theme.app)
return dict.__getitem__(self, theme.app).__iter__()
def load(self, name):
# Make sure default color is up to date
AppFont.foreColor = colors.app['text']
# If theme is unchanged, do nothing
if name in self:
return
# If we have a new theme, do setup
rem = AppFont.pointSize
cache = {
'base': AppFont(),
'h1': AppFont(pointSize=int(rem*1.6)),
'h2': AppFont(pointSize=int(rem*1.5)),
'h3': AppFont(pointSize=int(rem*1.4)),
'h4': AppFont(pointSize=int(rem*1.3)),
'h5': AppFont(pointSize=int(rem*1.2)),
'h6': AppFont(pointSize=int(rem*1.1)),
'code': CodeFont()
}
dict.__setitem__(self, name, cache)
class AppFont:
# Defaults are defined at class level, so they can change with theme
pointSize = 12
foreColor = "#000000"
backColor = wx.TRANSPARENT
bold = False
italic = False
def __init__(self, pointSize=None, foreColor=None, backColor=None, bold=None, italic=None):
# Set point size
if pointSize in (None, ""):
pointSize = AppFont.pointSize
self.pointSize = pointSize
# Set foreground color
if foreColor in (None, ""):
foreColor = AppFont.foreColor
self.foreColor = foreColor
# Set background color
if backColor in (None, ""):
backColor = AppFont.backColor
self.backColor = backColor
# Set bold
if bold in (None, ""):
bold = AppFont.bold
self.bold = bold
# Set italic
if italic in (None, ""):
italic = AppFont.italic
self.italic = italic
@property
def faceName(self):
if not hasattr(self, "_faceName"):
if sys.platform == 'win32':
self._faceName = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT).GetFaceName()
else:
self._faceName = wx.SystemSettings.GetFont(wx.SYS_ANSI_FIXED_FONT).GetFaceName()
return self._faceName
@faceName.setter
def faceName(self, value):
self._faceName = value
@property
def obj(self):
# If wx.Font object not created, create one
if not hasattr(self, "_obj"):
style = wx.FONTSTYLE_ITALIC if self.italic else wx.FONTSTYLE_NORMAL
weight = wx.FONTWEIGHT_BOLD if self.bold else wx.FONTWEIGHT_NORMAL
self._obj = wx.Font(
pointSize=self.pointSize,
family=wx.FONTFAMILY_SWISS,
style=style,
weight=weight,
faceName=self.faceName,
)
return self._obj
@obj.setter
def obj(self, value):
self._obj = value
def extractAll(val):
pointSize = int(prefs.coder['codeFontSize'])
foreColor = extractColor(val['fg'])
backColor = extractColor(val['bg'])
faceNames = extractFaceNames(val['font'])
bold, italic = extractFontStyle(val['font'])
return pointSize, foreColor, backColor, faceNames, bold, italic
def extractFaceNames(val):
# Make sure val is a list
if isinstance(val, str):
# Get rid of any perentheses
val = re.sub(r"[\(\)\[\]]", "", val)
# Split by comma
val = val.split(",")
# Clear style markers
val = [p for p in val if val not in ("bold", "italic")]
# Add fallback font
val += CodeFont.faceNames
return val
def extractFontStyle(val):
bold = "bold" in val
italic = "italic" in val
return bold, italic
def extractColor(val):
val = str(val)
# If val is blank, return None so further down the line we know to sub in defaults
if val in ("None", ""):
return None
# Split value according to operators, commas and spaces
val = val.replace("+", " + ").replace("-", " - ").replace("\\", " \\ ")
parts = re.split(r"[\\\s,\(\)\[\]]", val)
parts = [p for p in parts if p]
# Set assumed values
color = colors.scheme['black']
modifier = +0
alpha = 255
for i, part in enumerate(parts):
# If value is a named psychopy color, get it
if part in colors.scheme:
color = colors.scheme[part]
# If assigned an operation, store it for application
if part == "+" and i < len(parts) and parts[i+1].isnumeric():
modifier = int(parts[i+1])
if part == "-" and i < len(parts) and parts[i+1].isnumeric():
modifier = -int(parts[i+1])
if part == "*" and i < len(parts) and parts[i + 1].isnumeric():
alpha = int(parts[i + 1])
# If given a hex value, make a color from it
if re.fullmatch(r"#[\dabcdefABCDEF]{6}", part):
part = part.replace("#", "")
vals = [int(part[i:i+2], 16) for i in range(0, len(part), 2)] + [255]
color = colors.BaseColor(*vals)
# Apply modifier
color = color + modifier
# Apply alpha
color = wx.Colour(color.Red(), color.Green(), color.Blue(), alpha=alpha)
return color
coderTheme = CodeTheme()
appTheme = AppTheme()
| 20,976
|
Python
|
.py
| 558
| 28.435484
| 111
| 0.55561
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,808
|
icons.py
|
psychopy_psychopy/psychopy/app/themes/icons.py
|
import re
from abc import ABC
import numpy
import wx
from pathlib import Path
from psychopy import prefs, logging
from . import theme as appTheme
retStr = ""
resources = Path(prefs.paths['resources'])
iconCache = {}
pluginIconFiles = []
class BaseIcon:
def __init__(self, stem, size=None, theme=None):
# Initialise bitmaps array
self.bitmaps = {}
self._bitmap = None
self.size = size
self.stem = stem
if theme in (appTheme.icons, None) and stem in iconCache:
# Duplicate relevant attributes if relevant (depends on subclass)
self.bitmaps = iconCache[stem].bitmaps
else:
# Use subclass-specific populate call to create bitmaps
self._populate(stem, theme=theme)
# Set size
self.size = size
# Store ref to self in iconCache if using app theme
if theme in (appTheme.icons, None):
iconCache[stem] = self
def reload(self, theme=None):
"""
Get all images associated with this icon again. This is useful when changeing theme to one
with different icons.
Parameters
----------
theme : str, optional
Theme to get icons from, by default will use the current theme
"""
self._populate(stem=self.stem, theme=theme)
def _populate(self, stem, theme=None):
raise NotImplementedError(
"BaseIcon should not be instanced directly; it serves only as a base class for ButtonIcon and ComponentIcon"
)
@property
def size(self):
return self._size
@size.setter
def size(self, value):
# Sanitize size value
if isinstance(value, (tuple, list)):
# If given an iterable, use first value as width
width = value[0]
height = value[1]
else:
# Otherwise, assume square
width = value
height = value
if width is not None and not isinstance(width, int):
# If width is not an integer, try to make it one
width = int(width)
if height is not None and not isinstance(height, int):
# If height is not an integer, try to make it one
height = int(height)
# Store value
self._size = (width, height)
# Clear bitmap cache
self._bitmap = None
@property
def bitmap(self):
if self._bitmap is None:
# Get list of sizes cached
cachedSizes = list(self.bitmaps)
# If we don't have any cached sizes, return a blank bitmap
if not len(cachedSizes):
return wx.Bitmap()
if self.size in cachedSizes:
# If requested size is cached, return it
self._bitmap = self.bitmaps[self.size]
elif self.size[1] is None and self.size[0] is not None:
# If height is None, check for correct width
widths = [w for w, h in cachedSizes]
if self.size[0] in widths:
i = widths.index(self.size[0])
self._bitmap = self.bitmaps[cachedSizes[i]]
elif self.size[0] is None and self.size[1] is not None:
# If width is None, check for correct height
heights = [h for w, h in cachedSizes]
if self.size[1] in heights:
i = heights.index(self.size[1])
self._bitmap = self.bitmaps[cachedSizes[i]]
elif self.size[0] is None and self.size[1] is None:
# If both size values are None, use biggest bitmap
areas = [w * h for w, h in cachedSizes]
i = areas.index(max(areas))
self._bitmap = self.bitmaps[cachedSizes[i]]
else:
# Otherwise, resize the closest bitmap in size
areas = [w * h for w, h in cachedSizes]
area = self.size[0] * self.size[1]
deltas = [abs(area - a) for a in areas]
i = deltas.index(min(deltas))
bmp = self.bitmaps[cachedSizes[i]]
self._bitmap = self.resizeBitmap(bmp, self.size)
self.bitmaps[self._bitmap.GetWidth(), self._bitmap.GetHeight()] = self._bitmap
return self._bitmap
@staticmethod
def resizeBitmap(bmp, size=None):
assert isinstance(bmp, wx.Bitmap), (
"Bitmap supplied to `resizeBitmap()` must be a `wx.Bitmap` object."
)
# If size is None, return bitmap as is
if size in (None, (None, None)):
return bmp
# Split up size value
width, height = size
# If size is unchanged, return bitmap as is
if width == bmp.GetWidth() and height == bmp.GetHeight():
return bmp
# Convert to an image
img = bmp.ConvertToImage()
# Resize image
img.Rescale(width, height, quality=wx.IMAGE_QUALITY_HIGH)
# Return as bitmap
return wx.Bitmap(img)
class ButtonIcon(BaseIcon):
def _populate(self, stem, theme=None):
# Use current theme if none requested
if theme is None:
theme = appTheme.icons
# Get all files in the resource folder containing the given stem
matches = [f for f in resources.glob(f"**/{stem}*.png")] + pluginIconFiles
# Create blank arrays to store retina and non-retina files
ret = {}
nret = {}
# Validate matches
for match in matches:
# Reject match if in unused theme folder
if match.parent.stem not in (theme, "Resources"):
continue
# Get appendix (any chars in file stem besides requested stem and retina string)
appendix = match.stem.replace(stem, "").replace(retStr, "") or None
# Reject non-numeric appendices (may be a longer word, e.g. requested "folder", got "folder-open")
if appendix is not None and not appendix.isnumeric():
continue
elif appendix is not None:
appendix = int(appendix)
# If valid, append to array according to retina
if "@2x" in match.stem:
if appendix in ret and match.parent.stem != theme:
# Prioritise theme-specific if match is already present
continue
ret[appendix] = match
else:
if appendix in nret and match.parent.stem != theme:
# Prioritise theme-specific if match is already present
continue
nret[appendix] = match
# Compare keys in retina and non-retina matches
retOnly = set(ret) - set(nret)
nretOnly = set(nret) - set(ret)
both = set(ret) & set(nret)
# Compare keys from both match dicts
retKeys = list(retOnly)
nretKeys = list(nretOnly)
if retStr:
# If using retina, prioritise retina matches
retKeys += list(both)
else:
# Otherwise, prioritise non-retina matches
nretKeys += list(both)
# Merge match dicts
files = {}
for key in retKeys:
files[key] = ret[key]
for key in nretKeys:
files[key] = nret[key]
# Create bitmap array for files
self.bitmaps = {}
for file in files.values():
bmp = wx.Bitmap(str(file), wx.BITMAP_TYPE_PNG)
self.bitmaps[(bmp.GetWidth(), bmp.GetHeight())] = bmp
class ComponentIcon(BaseIcon):
def _populate(self, cls, theme=None):
# Throw error if class doesn't have associated icon file
if not hasattr(cls, "iconFile"):
raise AttributeError(
f"Could not retrieve icon for {cls} as the class does not have an `iconFile` attribute."
)
# Use current theme if none requested
if theme is None:
theme = appTheme.icons
# Get file from class
filePath = Path(cls.iconFile)
# Get icon file stem and root folder from iconFile value
stem = filePath.stem
folder = filePath.parent
# Look in appropriate theme folder for files
matches = {}
for match in (folder / theme).glob(f"{stem}*.png"):
appendix = match.stem.replace(stem, "")
matches[appendix] = match
# Choose / resize file according to retina
if retStr in matches:
file = matches[retStr]
else:
file = list(matches.values())[0]
img = wx.Image(str(file))
# Use appropriate sized bitmap
bmp = wx.Bitmap(img)
self.bitmaps[(bmp.GetWidth(), bmp.GetHeight())] = bmp
@property
def beta(self):
if not hasattr(self, "_beta"):
# Get appropriately sized beta sticker
betaImg = ButtonIcon("beta", size=self.size).bitmap.ConvertToImage()
# Get bitmap as image
baseImg = self.bitmap.ConvertToImage()
# Get color data and alphas
betaData = numpy.array(betaImg.GetData())
betaAlpha = numpy.array(betaImg.GetAlpha(), dtype=int)
baseData = numpy.array(baseImg.GetData())
baseAlpha = numpy.array(baseImg.GetAlpha(), dtype=int)
# Overlay colors
combinedData = baseData
r = numpy.where(betaAlpha > 0)[0] * 3
g = numpy.where(betaAlpha > 0)[0] * 3 + 1
b = numpy.where(betaAlpha > 0)[0] * 3 + 2
combinedData[r] = betaData[r]
combinedData[g] = betaData[g]
combinedData[b] = betaData[b]
# Combine alphas
combinedAlpha = numpy.add(baseAlpha, betaAlpha)
combinedAlpha[combinedAlpha > 255] = 255
combinedAlpha = numpy.uint8(combinedAlpha)
# Set these back to the base image
combined = betaImg
combined.SetData(combinedData)
combined.SetAlpha(combinedAlpha)
self._beta = wx.Bitmap(combined)
return self._beta
| 10,160
|
Python
|
.py
| 240
| 31.129167
| 120
| 0.577133
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,809
|
PsychopyLight.json
|
psychopy_psychopy/psychopy/app/themes/spec/PsychopyLight.json
|
{
"app": "light",
"icons": "light",
"info": "Psychopy's default look",
"code": {
"base": {
"fg": "#000000",
"bg": "#FFFFFF",
"font": "JetBrains Mono"
},
"margin": {
"fg": "#75757D",
"bg": "#F2F2F2",
"font": ""
},
"caret": {
"fg": "#F46E75",
"bg": "#F2F2F2",
"font": "bold"
},
"select": {
"fg": "#FFFFFF",
"bg": "#75757D",
"font": ""
},
"indent": {
"fg": "#D4D4D4",
"bg": "#D4D4D4",
"font": ""
},
"brace": {
"fg": "",
"bg": "#F2F2F2",
"font": ""
},
"operator": {
"fg": "",
"bg": "",
"font": ""
},
"keyword": {
"fg": "#F2545B",
"bg": "",
"font": ""
},
"keyword2": {
"fg": "#02A9EA",
"bg": "",
"font": "italic,bold"
},
"controlchar": {
"fg": "",
"bg": "",
"font": ""
},
"id": {
"fg": "",
"bg": "",
"font": ""
},
"num": {
"fg": "#028EC5",
"bg": "",
"font": ""
},
"char": {
"fg": "#75757D",
"bg": "",
"font": ""
},
"str": {
"fg": "#75757D",
"bg": "",
"font": ""
},
"openstr": {
"fg": "#75757D",
"bg": "#f2f2f2",
"font": ""
},
"infix": {
"fg": "#f2545b",
"bg": "",
"font": ""
},
"openinfix": {
"fg": "#f2545b",
"bg": "#f2f2f2",
"font": ""
},
"decorator": {
"fg": "#EC9703",
"bg": "",
"font": ""
},
"class": {
"fg": "",
"bg": "",
"font": ""
},
"def": {
"fg": "",
"bg": "",
"font": ""
},
"comment": {
"fg": "#39A141",
"bg": "",
"font": ""
},
"commentblock": {
"fg": "#39A141",
"bg": "#f2f2f2",
"font": ""
},
"commentkw": {
"fg": "#39A141",
"bg": "",
"font": ""
},
"commenterror": {
"fg": "#39A141",
"bg": "",
"font": ""
},
"documentation": {
"fg": "#75757D",
"bg": "",
"font": "italic"
},
"documentation2": {
"fg": "#75757D",
"bg": "",
"font": "italic"
},
"whitespace": {
"fg": "#D4D4D4",
"bg": "",
"font": "bold"
},
"python": {
},
"c++": {
},
"r": {
},
"json": {
},
"markdown": {
"italic": {
"fg": "orange",
"bg": "",
"font": "italic"
},
"italic2": {
"fg": "orange",
"bg": "",
"font": "italic"
},
"bold": {
"fg": "orange",
"bg": "",
"font": "bold"
},
"bold2": {
"fg": "orange",
"bg": "",
"font": "bold"
},
"link": {
"fg": "blue",
"bg": "",
"font": "italic"
},
"hr": {
"fg": "blue",
"bg": "",
"font": "bold"
},
"h1": {
"fg": "red",
"bg": "",
"font": "bold"
},
"h2": {
"fg": "red",
"bg": "",
"font": "bold"
},
"h3": {
"fg": "red",
"bg": "",
"font": "bold"
},
"h4": {
"fg": "red",
"bg": "",
"font": "bold"
},
"h5": {
"fg": "red",
"bg": "",
"font": "bold"
},
"h6": {
"fg": "red",
"bg": "",
"font": "bold"
},
"code": {
"fg": "green",
"bg": "",
"font": ""
},
"codeblock": {
"fg": "green",
"bg": "",
"font": ""
},
"li": {
"fg": "blue",
"bg": "",
"font": "bold"
},
"prechar": {
"fg": "#B8B8BB",
"bg": "",
"font": "bold"
}
}
}
}
| 3,845
|
Python
|
.py
| 232
| 9.831897
| 36
| 0.282627
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,810
|
PsychopyDark.json
|
psychopy_psychopy/psychopy/app/themes/spec/PsychopyDark.json
|
{
"app": "dark",
"icons": "dark",
"info": "A darker version of Psychopy's default look",
"code": {
"base": {
"fg": "#f2f2f2",
"bg": "#66666E",
"font": "JetBrains Mono"
},
"margin": {
"fg": "#B6B6B6",
"bg": "#75757D",
"font": ""
},
"caret": {
"fg": "#F46E75",
"bg": "#000000",
"font": "bold"
},
"select": {
"fg": "",
"bg": "#7C7C86",
"font": ""
},
"indent": {
"fg": "#75757D",
"bg": "#75757D",
"font": ""
},
"brace": {
"fg": "",
"bg": "#75757D",
"font": ""
},
"operator": {
"fg": "",
"bg": "",
"font": ""
},
"keyword": {
"fg": "#F46E75",
"bg": "",
"font": ""
},
"keyword2": {
"fg": "#C3BEF7",
"bg": "",
"font": ["italic","bold"]
},
"controlchar": {
"fg": "",
"bg": "",
"font": ""
},
"id": {
"fg": "",
"bg": "",
"font": ""
},
"num": {
"fg": "#C3BEF7",
"bg": "",
"font": ""
},
"char": {
"fg": "#B6B6B6",
"bg": "",
"font": ""
},
"str": {
"fg": "#B6B6B6",
"bg": "",
"font": ""
},
"openstr": {
"fg": "#B6B6B6",
"bg": "#75757D",
"font": ""
},
"infix": {
"fg": "#f2545b",
"bg": "",
"font": ""
},
"openinfix": {
"fg": "#f2545b",
"bg": "#75757D",
"font": ""
},
"decorator": {
"fg": "#C3BEF7",
"bg": "",
"font": ""
},
"class": {
"fg": "",
"bg": "",
"font": ""
},
"def": {
"fg": "",
"bg": "",
"font": ""
},
"comment": {
"fg": "#EC9703",
"bg": "",
"font": ""
},
"commentblock": {
"fg": "#EC9703",
"bg": "#75757D",
"font": ""
},
"commentkw": {
"fg": "#F46E75",
"bg": "",
"font": ""
},
"commenterror": {
"fg": "#F2545B",
"bg": "",
"font": ""
},
"documentation": {
"fg": "#B6B6B6",
"bg": "",
"font": "italic"
},
"documentation2": {
"fg": "#B6B6B6",
"bg": "",
"font": "italic"
},
"whitespace": {
"fg": "#B8B8BB",
"bg": "",
"font": "bold"
},
"python": {
},
"c++": {
},
"json": {
},
"markdown": {
"italic": {
"fg": "orange",
"bg": "",
"font": "italic"
},
"italic2": {
"fg": "orange",
"bg": "",
"font": "italic"
},
"bold": {
"fg": "orange",
"bg": "",
"font": "bold"
},
"bold2": {
"fg": "orange",
"bg": "",
"font": "bold"
},
"link": {
"fg": "purple",
"bg": "",
"font": "italic"
},
"hr": {
"fg": "blue",
"bg": "",
"font": "bold"
},
"h1": {
"fg": "red",
"bg": "",
"font": "bold"
},
"h2": {
"fg": "red",
"bg": "",
"font": "bold"
},
"h3": {
"fg": "red",
"bg": "",
"font": "bold"
},
"h4": {
"fg": "red",
"bg": "",
"font": "bold"
},
"h5": {
"fg": "red",
"bg": "",
"font": "bold"
},
"h6": {
"fg": "red",
"bg": "",
"font": "bold"
},
"code": {
"fg": "purple",
"bg": "",
"font": ""
},
"codeblock": {
"fg": "purple",
"bg": "",
"font": ""
},
"li": {
"fg": "purple",
"bg": "",
"font": "bold"
},
"prechar": {
"fg": "#B8B8BB",
"bg": "",
"font": "bold"
}
}
}
}
| 3,845
|
Python
|
.py
| 230
| 9.973913
| 56
| 0.285833
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,811
|
stdOutRich.py
|
psychopy_psychopy/psychopy/app/stdout/stdOutRich.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import webbrowser
import wx
import re
import wx.richtext
import locale
from psychopy import prefs, alerts
from psychopy.localization import _translate
from psychopy.app.utils import sanitize
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Classes and functions for the script output."""
# Part of the PsychoPy library
# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd.
# Distributed under the terms of the GNU General Public License (GPL).
import re
import locale
import wx
import wx.richtext
import webbrowser
from psychopy.localization import _translate
from psychopy.app.themes import handlers, icons, colors, fonts
_prefEncoding = locale.getpreferredencoding()
from psychopy.alerts._alerts import AlertEntry
from psychopy.alerts._errorHandler import _BaseErrorHandler
class StdOutRich(wx.richtext.RichTextCtrl, _BaseErrorHandler, handlers.ThemeMixin):
"""
A rich text ctrl for handling stdout/stderr
"""
def __init__(self, parent, style, size=None, font=None, fontSize=None, app=None):
kwargs = {'parent': parent, 'style': style}
if size is not None:
kwargs['size'] = size
_BaseErrorHandler.__init__(self)
wx.richtext.RichTextCtrl.__init__(self, **kwargs)
self.prefs = prefs
self.paths = prefs.paths
if font and fontSize:
currFont = self.GetFont()
currFont.SetFaceName(font)
currFont.SetPointSize(fontSize)
self.BeginFont(currFont)
self.parent = parent
self.app = app
self.Bind(wx.EVT_TEXT_URL, self.onURL)
self._applyAppTheme()
def _applyAppTheme(self):
# do usual theme stuff
handlers.ThemeMixin._applyAppTheme(self)
# get base font
font = fonts.coderTheme.base
# dict of styles
self._styles = {
'base': wx.richtext.RichTextAttr(wx.TextAttr(
colText=font.foreColor,
colBack=font.backColor,
font=font.obj,
)),
'error': wx.richtext.RichTextAttr(wx.TextAttr(
colText=colors.scheme['red'],
colBack=font.backColor,
font=font.obj,
)),
'warning': wx.richtext.RichTextAttr(wx.TextAttr(
colText=colors.scheme['orange'],
colBack=font.backColor,
font=font.obj,
)),
'info': wx.richtext.RichTextAttr(wx.TextAttr(
colText=colors.scheme['lightgrey'],
colBack=font.backColor,
font=font.obj,
)),
'link': wx.richtext.RichTextAttr(wx.TextAttr(
colText=colors.scheme['blue'],
colBack=font.backColor,
font=font.obj,
)),
}
# connect logging levels to styles
from psychopy import logging
self.logLevelStyles = {
logging.NOTSET: self._styles['base'],
logging.DEBUG: self._styles['info'],
logging.INFO: self._styles['info'],
logging.EXP: self._styles['info'],
logging.DATA: self._styles['info'],
logging.WARNING: self._styles['warning'],
logging.ERROR: self._styles['error'],
logging.CRITICAL: self._styles['error'],
}
def onURL(self, evt=None):
wx.BeginBusyCursor()
try:
if evt.String.startswith("http"):
webbrowser.open(evt.String)
else:
# decompose the URL of a file and line number"""
# "C:\Program Files\wxPython...\samples\hangman\hangman.py"
filename = evt.GetString().split('"')[1]
lineNumber = int(evt.GetString().split(',')[1][5:])
self.app.showCoder()
self.app.coder.gotoLine(filename, lineNumber)
except Exception as e:
print("##### Could not open URL: {} #####\n".format(evt.String))
print(e)
wx.EndBusyCursor()
def write(self, inStr, evt=None):
self.MoveEnd() # always 'append' text rather than 'writing' it
"""tracebacks have the form:
Traceback (most recent call last):
File "C:\\Program Files\\wxPython2.8 Docs and Demos\\samples\\hangman\\hangman.py", line 21, in <module>
class WordFetcher:
File "C:\\Program Files\\wxPython2.8 Docs and Demos\\samples\\hangman\\hangman.py", line 23, in WordFetcher
"""
from psychopy import logging
if type(inStr) == AlertEntry:
alert = inStr
# sanitize message
alert.msg = sanitize(alert.msg)
# Write Code
self.BeginStyle(self._styles['link'])
self.BeginURL(alert.url)
self.WriteText("Alert {}:".format(alert.code))
self.EndURL()
# Write Message
self.BeginStyle(self._styles['base'])
self.WriteText("\n\t" + alert.msg)
# Write URL
self.BeginStyle(self._styles['base'])
self.WriteText("\n\t"+_translate("For further info see "))
self.BeginStyle(self._styles['link'])
self.BeginURL(alert.url)
self.WriteText("{:<15}".format(alert.url))
self.EndURL()
self.Newline()
self.ShowPosition(self.GetLastPosition())
else:
# if it comes form a stdout in Py3 then convert to unicode
if type(inStr) == bytes:
try:
inStr = inStr.decode('utf-8')
except UnicodeDecodeError:
inStr = inStr.decode(_prefEncoding)
# sanitize message
inStr = sanitize(inStr)
for thisLine in inStr.splitlines(True):
try:
thisLine = thisLine.replace("\t", " ")
except Exception as e:
self.WriteText(str(e))
if len(re.findall('".*", line.*', thisLine)) > 0:
# this line contains a file/line location so write as URL
self.BeginStyle(self._styles['link'])
self.BeginURL(thisLine)
self.WriteText(thisLine)
self.EndURL()
elif re.match('https?://.*', thisLine):
# this line contains an actual URL
self.BeginStyle(self._styles['link'])
self.BeginURL(thisLine)
self.WriteText(thisLine)
self.EndURL()
elif re.findall(logging._levelNamesRe, thisLine):
# this line contains a logging message
lvl = logging.NOTSET
# for each styled level...
for thisLvl, style in self.logLevelStyles.items():
# get its name
name = logging._levelNames[thisLvl]
# look for name in the current line
if len(re.findall(name, thisLine)) > 0:
# if found, set level and stop looking
lvl = thisLvl
break
# if level allowed by prefs, set style and write
self.BeginStyle(self.logLevelStyles[lvl])
self.WriteText(thisLine)
else:
# anything else
self.BeginStyle(self._styles['base'])
self.WriteText(thisLine)
# cap number of lines
text = self.GetValue()
maxLength = 100000
if len(text) > maxLength:
self.Remove(0, 1000)
# go to end of stdout so user can see updated text
self.MoveEnd()
self.ShowPosition(self.GetLastPosition())
if evt is not None:
evt.Skip()
def flush(self):
for alert in self.alerts:
self.write(alert)
for err in self.errors:
print(err)
self.errors = []
self.alerts = []
def getText(self):
"""Get and return the text of the current buffer."""
return self.GetValue()
def setStatus(self, status):
self.SetValue(status)
self.Refresh()
self.Layout()
wx.Yield()
def statusAppend(self, newText):
text = self.GetValue() + newText
self.setStatus(text)
class ScriptOutputPanel(wx.Panel, handlers.ThemeMixin):
"""Class for the script output window in Coder.
Parameters
----------
parent : :class:`wx.Window`
Window this object belongs to.
style : int
Symbolic constants for style flags.
size : ArrayLike or None
Size of the control in pixels `(w, h)`. Use `None` for default.
font : str or None
Font to use for output, fixed-width is preferred. If `None`, the theme
defaults will be used.
fontSize : int or None
Point size of the font. If `None`, the theme defaults will be used.
"""
class OutputToolbar(wx.Panel, handlers.ThemeMixin):
def __init__(self, parent):
wx.Panel.__init__(self, parent, size=(30, 90))
self.parent = parent
# Setup sizer
self.borderBox = wx.BoxSizer(wx.VERTICAL)
self.SetSizer(self.borderBox)
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.borderBox.Add(self.sizer, border=6, flag=wx.ALL)
# Clear button
self.clrBtn = wx.Button(self, size=(16, 16), style=wx.BORDER_NONE)
self.clrBtn.SetToolTip(_translate(
"Clear all previous output."
))
self.clrBtn.SetBitmap(
icons.ButtonIcon(stem="clear", size=16).bitmap
)
self.sizer.Add(self.clrBtn, border=6, flag=wx.BOTTOM)
self.clrBtn.Bind(wx.EVT_BUTTON, self.parent.ctrl.clear)
self.Layout()
def _applyAppTheme(self):
# Set background
self.SetBackgroundColour(fonts.coderTheme.base.backColor)
# Style buttons
for btn in (self.clrBtn,):
btn.SetBackgroundColour(fonts.coderTheme.base.backColor)
self.Refresh()
self.Update()
def __init__(self,
parent,
style=wx.TE_READONLY | wx.TE_MULTILINE | wx.BORDER_NONE,
font=None,
fontSize=None):
# Init superclass
wx.Panel.__init__(self, parent, size=(480, 480), style=style)
self.tabIcon = "stdout"
# Setup sizer
self.sizer = wx.BoxSizer(wx.HORIZONTAL)
self.SetSizer(self.sizer)
# Text control
self.ctrl = ScriptOutputCtrl(self,
style=style,
font=font,
fontSize=fontSize)
self.sizer.Add(self.ctrl, proportion=1, border=6, flag=wx.ALL | wx.EXPAND)
# Sep
self.sep = wx.Window(self, size=(1, -1))
self.sizer.Prepend(self.sep, border=12, flag=wx.EXPAND | wx.TOP | wx.BOTTOM)
# Toolbar
self.toolbar = self.OutputToolbar(self)
self.sizer.Prepend(self.toolbar, border=6, flag=wx.EXPAND | wx.TOP | wx.BOTTOM)
def _applyAppTheme(self):
self.ctrl._applyAppTheme()
# Set background
self.SetBackgroundColour(fonts.coderTheme.base.backColor)
self.Refresh()
self.Update()
# Match line
self.sep.SetBackgroundColour(fonts.coderTheme.margin.backColor)
self.Refresh()
self.Update()
class ScriptOutputCtrl(StdOutRich, handlers.ThemeMixin):
def __init__(self, parent,
style=wx.TE_READONLY | wx.TE_MULTILINE | wx.BORDER_NONE,
size=None,
font=None,
fontSize=None):
StdOutRich.__init__(
self,
parent,
size=wx.DefaultSize if size is None else size,
style=style)
self.parent = parent
self.tabIcon = "stdout"
self._font = font
self._fontSize = fontSize
self.Bind(wx.EVT_TEXT_URL, self.onURL)
def onURL(self, evt):
"""Open link in default browser."""
wx.BeginBusyCursor()
try:
if evt.String.startswith("http"):
webbrowser.open(evt.String)
else:
# decompose the URL of a file and line number"""
# "C:\Program Files\wxPython...\samples\hangman\hangman.py"
filename = evt.GetString().split('"')[1]
lineNumber = int(evt.GetString().split(',')[1][5:])
# get handle to app
app = self.GetTopLevelParent().app
# make sure we have a Coder window
app.showCoder()
# open in coder
app.coder.gotoLine(filename, lineNumber)
except Exception as e:
print("##### Could not open URL: {} #####\n".format(evt.String))
print(e)
wx.EndBusyCursor()
def clear(self, evt=None):
self.Clear()
def flush(self):
for alert in self.alerts:
self.write(alert)
for err in self.errors:
print(err)
self.errors = []
self.alerts = []
def __del__(self):
"""
If setup as an alert handler, remove self on deletion.
"""
if alerts.isAlertHandler(self):
alerts.removeAlertHandler(self)
if __name__ == "__main__":
pass
| 13,715
|
Python
|
.py
| 342
| 28.201754
| 115
| 0.557184
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,812
|
ui.py
|
psychopy_psychopy/psychopy/app/colorpicker/ui.py
|
# -*- coding: utf-8 -*-
import wx
import wx.xrc
from psychopy.localization import _translate
###########################################################################
## Class ColorPickerDialog
###########################################################################
class ColorPickerDialog ( wx.Dialog ):
def __init__( self, parent ):
wx.Dialog.__init__ ( self, parent, id = wx.ID_ANY, title = "Color Picker", pos = wx.DefaultPosition, size = wx.Size( 640,480 ), style = wx.DEFAULT_DIALOG_STYLE )
self.SetSizeHints( wx.Size( -1,-1 ), wx.DefaultSize )
szrMain = wx.BoxSizer( wx.VERTICAL )
self.pnlColorSelector = wx.Panel( self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL )
szrColorSelector = wx.BoxSizer( wx.HORIZONTAL )
self.pnlColorPreview = wx.Panel( self.pnlColorSelector, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL )
self.pnlColorPreview.SetBackgroundColour( wx.SystemSettings.GetColour( wx.SYS_COLOUR_HIGHLIGHT ) )
self.pnlColorPreview.SetMaxSize( wx.Size( 120,-1 ) )
szrColorSelector.Add( self.pnlColorPreview, 1, wx.EXPAND|wx.LEFT|wx.RIGHT|wx.TOP, 5 )
self.nbColorSelector = wx.Notebook( self.pnlColorSelector, wx.ID_ANY, wx.DefaultPosition, wx.Size( -1,-1 ), 0 )
self.pnlRGBPage = wx.Panel( self.nbColorSelector, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL )
szrRGBPage = wx.BoxSizer( wx.VERTICAL )
fraRGBChannels = wx.StaticBoxSizer( wx.StaticBox( self.pnlRGBPage, wx.ID_ANY, _translate(" RGB Channels ") ), wx.VERTICAL )
szrRGBChannels = wx.FlexGridSizer( 3, 3, 5, 10 )
szrRGBChannels.AddGrowableCol( 1 )
szrRGBChannels.SetFlexibleDirection( wx.BOTH )
szrRGBChannels.SetNonFlexibleGrowMode( wx.FLEX_GROWMODE_SPECIFIED )
self.lblRedChannel = wx.StaticText( fraRGBChannels.GetStaticBox(), wx.ID_ANY, u"R:", wx.DefaultPosition, wx.DefaultSize, 0 )
self.lblRedChannel.Wrap( -1 )
szrRGBChannels.Add( self.lblRedChannel, 0, wx.ALL|wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL, 0 )
self.sldRedChannel = wx.Slider( fraRGBChannels.GetStaticBox(), wx.ID_ANY, 50, 0, 100, wx.DefaultPosition, wx.DefaultSize, wx.SL_HORIZONTAL )
szrRGBChannels.Add( self.sldRedChannel, 0, wx.ALL|wx.EXPAND|wx.ALIGN_CENTER_VERTICAL, 0 )
self.spnRedChannel = wx.SpinCtrlDouble( fraRGBChannels.GetStaticBox(), wx.ID_ANY, u"0.0", wx.DefaultPosition, wx.DefaultSize, wx.SP_ARROW_KEYS, -1, 1, 0.000000, 0.01 )
self.spnRedChannel.SetDigits( 4 )
szrRGBChannels.Add( self.spnRedChannel, 0, wx.ALL|wx.EXPAND, 0 )
self.lblGreenChannel = wx.StaticText( fraRGBChannels.GetStaticBox(), wx.ID_ANY, u"G:", wx.DefaultPosition, wx.DefaultSize, 0 )
self.lblGreenChannel.Wrap( -1 )
szrRGBChannels.Add( self.lblGreenChannel, 0, wx.ALL|wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL, 0 )
self.sldGreenChannel = wx.Slider( fraRGBChannels.GetStaticBox(), wx.ID_ANY, 50, 0, 100, wx.DefaultPosition, wx.DefaultSize, wx.SL_HORIZONTAL )
szrRGBChannels.Add( self.sldGreenChannel, 0, wx.ALL|wx.EXPAND|wx.ALIGN_CENTER_VERTICAL, 0 )
self.spnGreenChannel = wx.SpinCtrlDouble( fraRGBChannels.GetStaticBox(), wx.ID_ANY, u"0.0", wx.DefaultPosition, wx.DefaultSize, wx.SP_ARROW_KEYS, -1, 1, 0.000000, 0.01 )
self.spnGreenChannel.SetDigits( 4 )
szrRGBChannels.Add( self.spnGreenChannel, 0, wx.ALL|wx.EXPAND, 0 )
self.lblBlueChannel = wx.StaticText( fraRGBChannels.GetStaticBox(), wx.ID_ANY, u"B:", wx.DefaultPosition, wx.DefaultSize, 0 )
self.lblBlueChannel.Wrap( -1 )
szrRGBChannels.Add( self.lblBlueChannel, 0, wx.ALL|wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL, 0 )
self.sldBlueChannel = wx.Slider( fraRGBChannels.GetStaticBox(), wx.ID_ANY, 50, 0, 100, wx.DefaultPosition, wx.DefaultSize, wx.SL_HORIZONTAL )
szrRGBChannels.Add( self.sldBlueChannel, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, 0 )
self.spnBlueChannel = wx.SpinCtrlDouble( fraRGBChannels.GetStaticBox(), wx.ID_ANY, u"0.0", wx.DefaultPosition, wx.DefaultSize, wx.SP_ARROW_KEYS, -1, 1, 0, 0.01 )
self.spnBlueChannel.SetDigits( 4 )
szrRGBChannels.Add( self.spnBlueChannel, 0, wx.ALL|wx.EXPAND, 0 )
fraRGBChannels.Add( szrRGBChannels, 1, wx.EXPAND, 5 )
szrRGBPage.Add( fraRGBChannels, 0, wx.ALL|wx.EXPAND, 5 )
szrLowerRGBPage = wx.BoxSizer( wx.HORIZONTAL )
fraHexRGB = wx.StaticBoxSizer( wx.StaticBox( self.pnlRGBPage, wx.ID_ANY, _translate("Hex/HTML") ), wx.VERTICAL )
self.txtHexRGB = wx.TextCtrl( fraHexRGB.GetStaticBox(), wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0 )
fraHexRGB.Add( self.txtHexRGB, 0, wx.ALL|wx.EXPAND, 5 )
szrLowerRGBPage.Add( fraHexRGB, 1, wx.ALL, 5 )
fraRGBFormat = wx.StaticBoxSizer( wx.StaticBox( self.pnlRGBPage, wx.ID_ANY, _translate("RGB Format") ), wx.VERTICAL )
self.rdoRGBModePsychoPy = wx.RadioButton( fraRGBFormat.GetStaticBox(), wx.ID_ANY, u"PsychoPy RGB [-1:1]", wx.DefaultPosition, wx.DefaultSize, 0 )
self.rdoRGBModePsychoPy.SetValue( True )
fraRGBFormat.Add( self.rdoRGBModePsychoPy, 0, wx.ALL, 2 )
self.rdoRGBModeNormalized = wx.RadioButton( fraRGBFormat.GetStaticBox(), wx.ID_ANY, u"Normalized RGB [0:1]", wx.DefaultPosition, wx.DefaultSize, 0 )
fraRGBFormat.Add( self.rdoRGBModeNormalized, 0, wx.ALL, 2 )
self.rdoRGBMode255 = wx.RadioButton( fraRGBFormat.GetStaticBox(), wx.ID_ANY, u"8-Bit RGB [0:255]", wx.DefaultPosition, wx.DefaultSize, 0 )
fraRGBFormat.Add( self.rdoRGBMode255, 0, wx.ALL, 2 )
szrLowerRGBPage.Add( fraRGBFormat, 1, wx.BOTTOM|wx.RIGHT|wx.TOP, 5 )
szrRGBPage.Add( szrLowerRGBPage, 1, wx.EXPAND, 5 )
self.pnlRGBPage.SetSizer( szrRGBPage )
self.pnlRGBPage.Layout()
szrRGBPage.Fit( self.pnlRGBPage )
self.nbColorSelector.AddPage( self.pnlRGBPage, u"RGB", True )
self.pnlHSVPage = wx.Panel( self.nbColorSelector, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL )
szrHSVPage = wx.BoxSizer( wx.VERTICAL )
fraHSVChannels = wx.StaticBoxSizer( wx.StaticBox( self.pnlHSVPage, wx.ID_ANY, _translate(" HSV Channels ") ), wx.VERTICAL )
szrHSVChannels = wx.FlexGridSizer( 3, 3, 5, 10 )
szrHSVChannels.AddGrowableCol( 1 )
szrHSVChannels.SetFlexibleDirection( wx.BOTH )
szrHSVChannels.SetNonFlexibleGrowMode( wx.FLEX_GROWMODE_SPECIFIED )
self.lblHueChannel = wx.StaticText( fraHSVChannels.GetStaticBox(), wx.ID_ANY, u"H:", wx.DefaultPosition, wx.DefaultSize, 0 )
self.lblHueChannel.Wrap( -1 )
szrHSVChannels.Add( self.lblHueChannel, 0, wx.ALL|wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL, 0 )
self.sldHueChannel = wx.Slider( fraHSVChannels.GetStaticBox(), wx.ID_ANY, 50, 0, 100, wx.DefaultPosition, wx.DefaultSize, wx.SL_HORIZONTAL )
szrHSVChannels.Add( self.sldHueChannel, 0, wx.ALL|wx.EXPAND|wx.ALIGN_CENTER_VERTICAL, 0 )
self.spnHueChannel = wx.SpinCtrlDouble( fraHSVChannels.GetStaticBox(), wx.ID_ANY, u"0.0", wx.DefaultPosition, wx.DefaultSize, wx.SP_ARROW_KEYS, 0, 360, 0, 1 )
self.spnHueChannel.SetDigits( 0 )
szrHSVChannels.Add( self.spnHueChannel, 0, wx.ALL|wx.EXPAND, 0 )
self.lblSaturationChannel = wx.StaticText( fraHSVChannels.GetStaticBox(), wx.ID_ANY, u"S:", wx.DefaultPosition, wx.DefaultSize, 0 )
self.lblSaturationChannel.Wrap( -1 )
szrHSVChannels.Add( self.lblSaturationChannel, 0, wx.ALL|wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL, 0 )
self.sldStaturationChannel = wx.Slider( fraHSVChannels.GetStaticBox(), wx.ID_ANY, 50, 0, 100, wx.DefaultPosition, wx.DefaultSize, wx.SL_HORIZONTAL )
szrHSVChannels.Add( self.sldStaturationChannel, 0, wx.ALL|wx.EXPAND|wx.ALIGN_CENTER_VERTICAL, 0 )
self.spnSaturationChannel = wx.SpinCtrlDouble( fraHSVChannels.GetStaticBox(), wx.ID_ANY, u"0.0", wx.DefaultPosition, wx.DefaultSize, wx.SP_ARROW_KEYS, -1, 1, 0.000000, 0.01 )
self.spnSaturationChannel.SetDigits( 4 )
szrHSVChannels.Add( self.spnSaturationChannel, 0, wx.ALL|wx.EXPAND, 0 )
self.lblValueChannel = wx.StaticText( fraHSVChannels.GetStaticBox(), wx.ID_ANY, u"V:", wx.DefaultPosition, wx.DefaultSize, 0 )
self.lblValueChannel.Wrap( -1 )
szrHSVChannels.Add( self.lblValueChannel, 0, wx.ALL|wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL, 0 )
self.sldValueChannel = wx.Slider( fraHSVChannels.GetStaticBox(), wx.ID_ANY, 50, 0, 100, wx.DefaultPosition, wx.DefaultSize, wx.SL_HORIZONTAL )
szrHSVChannels.Add( self.sldValueChannel, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, 0 )
self.spnValueChannel = wx.SpinCtrlDouble( fraHSVChannels.GetStaticBox(), wx.ID_ANY, u"0.0", wx.DefaultPosition, wx.DefaultSize, wx.SP_ARROW_KEYS, -1, 1, 0.000000, 0.001 )
self.spnValueChannel.SetDigits( 4 )
szrHSVChannels.Add( self.spnValueChannel, 0, wx.ALL|wx.EXPAND, 0 )
fraHSVChannels.Add( szrHSVChannels, 0, wx.EXPAND, 5 )
szrHSVPage.Add( fraHSVChannels, 0, wx.ALL|wx.EXPAND, 5 )
self.pnlHSVPage.SetSizer( szrHSVPage )
self.pnlHSVPage.Layout()
szrHSVPage.Fit( self.pnlHSVPage )
self.nbColorSelector.AddPage( self.pnlHSVPage, u"HSV", False )
szrColorSelector.Add( self.nbColorSelector, 1, wx.EXPAND|wx.TOP, 5 )
lstColorPresetsChoices = []
self.lstColorPresets = wx.ListBox( self.pnlColorSelector, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, lstColorPresetsChoices, 0|wx.ALWAYS_SHOW_SB )
self.lstColorPresets.SetMinSize( wx.Size( 140,-1 ) )
szrColorSelector.Add( self.lstColorPresets, 1, wx.EXPAND|wx.LEFT|wx.RIGHT|wx.TOP, 5 )
self.pnlColorSelector.SetSizer( szrColorSelector )
self.pnlColorSelector.Layout()
szrColorSelector.Fit( self.pnlColorSelector )
szrMain.Add( self.pnlColorSelector, 1, wx.EXPAND, 0 )
# Output space chooser
self.pnlOutputSelector = wx.Panel(self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL )
szrOutputSelector = wx.BoxSizer(wx.HORIZONTAL)
szrOutputSelector.AddStretchSpacer(1)
self.lblOutputSpace = wx.StaticText( self.pnlOutputSelector, wx.ID_ANY, _translate("Output Space:"), wx.DefaultPosition, wx.DefaultSize, 0 )
self.lblOutputSpace.Wrap( -1 )
szrOutputSelector.Add( self.lblOutputSpace, 0, wx.ALIGN_CENTER_VERTICAL|wx.BOTTOM|wx.LEFT|wx.TOP, 0 )
cboOutputSpaceChoices = [u"PsychoPy RGB (rgb)"]
self.cboOutputSpace = wx.Choice(self.pnlOutputSelector, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize,
cboOutputSpaceChoices, 0)
self.cboOutputSpace.SetSelection(0)
szrOutputSelector.Add(self.cboOutputSpace, 0, wx.ALL | wx.EXPAND, 5)
self.cmdCopy = wx.Button( self.pnlOutputSelector, wx.ID_ANY, _translate("Copy"), wx.DefaultPosition, wx.DefaultSize, 0 )
szrOutputSelector.Add( self.cmdCopy, 0, wx.BOTTOM|wx.LEFT|wx.TOP, 5 )
self.cmdInsert = wx.Button( self.pnlOutputSelector, wx.ID_ANY, _translate("Insert"), wx.DefaultPosition, wx.DefaultSize, 0 )
szrOutputSelector.Add( self.cmdInsert, 0, wx.ALL, 5 )
self.pnlOutputSelector.SetSizer(szrOutputSelector)
szrMain.Add(self.pnlOutputSelector, 0, wx.ALL | wx.EXPAND, 5)
# Dialog buttons
szrDlgButtons = self.CreateStdDialogButtonSizer(flags=wx.CANCEL)
#self.cmdCancel = szrDlgButtons.AddButton(wx.ID_CANCEL)
szrMain.Add( szrDlgButtons, 0, wx.ALL|wx.EXPAND, 5 )
# Layout
self.SetSizer( szrMain )
self.Layout()
self.Centre( wx.BOTH )
# Connect Events
self.Bind( wx.EVT_CLOSE, self.OnClose )
self.sldRedChannel.Bind( wx.EVT_SCROLL, self.OnRedScroll )
self.spnRedChannel.Bind( wx.EVT_SPINCTRLDOUBLE, self.OnRedSpin )
self.spnRedChannel.Bind( wx.EVT_TEXT_ENTER, self.OnRedTextEnter )
self.sldGreenChannel.Bind( wx.EVT_SCROLL, self.OnGreenScroll )
self.spnGreenChannel.Bind( wx.EVT_SPINCTRLDOUBLE, self.OnGreenSpin )
self.spnGreenChannel.Bind( wx.EVT_TEXT_ENTER, self.OnGreenTextEnter )
self.sldBlueChannel.Bind( wx.EVT_SCROLL, self.OnBlueScroll )
self.spnBlueChannel.Bind( wx.EVT_SPINCTRLDOUBLE, self.OnBlueSpin )
self.spnBlueChannel.Bind( wx.EVT_TEXT_ENTER, self.OnBlueTextEnter )
self.txtHexRGB.Bind( wx.EVT_KEY_DOWN, self.OnHexRGBKeyDown )
self.rdoRGBModePsychoPy.Bind( wx.EVT_RADIOBUTTON, self.OnRGBModePsychoPy )
self.rdoRGBModeNormalized.Bind( wx.EVT_RADIOBUTTON, self.OnRGBModeNormalized )
self.rdoRGBMode255.Bind( wx.EVT_RADIOBUTTON, self.OnRGBMode255 )
self.sldHueChannel.Bind( wx.EVT_SCROLL, self.OnHueScroll )
self.spnHueChannel.Bind( wx.EVT_SPINCTRLDOUBLE, self.OnHueSpin )
self.spnHueChannel.Bind( wx.EVT_TEXT_ENTER, self.OnHueTextEnter )
self.sldStaturationChannel.Bind( wx.EVT_SCROLL, self.OnSaturationScroll )
self.spnSaturationChannel.Bind( wx.EVT_SPINCTRLDOUBLE, self.OnSaturationSpin )
self.spnSaturationChannel.Bind( wx.EVT_TEXT_ENTER, self.OnSaturationTextEnter )
self.sldValueChannel.Bind( wx.EVT_SCROLL, self.OnValueScroll )
self.spnValueChannel.Bind( wx.EVT_SPINCTRLDOUBLE, self.OnValueSpin )
self.spnValueChannel.Bind( wx.EVT_TEXT_ENTER, self.OnValueTextEnter )
self.lstColorPresets.Bind( wx.EVT_LISTBOX, self.OnPresetSelect )
self.cmdCopy.Bind( wx.EVT_BUTTON, self.OnCopy )
self.cmdInsert.Bind( wx.EVT_BUTTON, self.OnInsert )
def __del__( self ):
pass
# Virtual event handlers, override them in your derived class
def OnClose( self, event ):
event.Skip()
def OnRedScroll( self, event ):
event.Skip()
def OnRedSpin( self, event ):
event.Skip()
def OnRedTextEnter( self, event ):
event.Skip()
def OnGreenScroll( self, event ):
event.Skip()
def OnGreenSpin( self, event ):
event.Skip()
def OnGreenTextEnter( self, event ):
event.Skip()
def OnBlueScroll( self, event ):
event.Skip()
def OnBlueSpin( self, event ):
event.Skip()
def OnBlueTextEnter( self, event ):
event.Skip()
def OnHexRGBKeyDown( self, event ):
event.Skip()
def OnRGBModePsychoPy( self, event ):
event.Skip()
def OnRGBModeNormalized( self, event ):
event.Skip()
def OnRGBMode255( self, event ):
event.Skip()
def OnHueScroll( self, event ):
event.Skip()
def OnHueSpin( self, event ):
event.Skip()
def OnHueTextEnter( self, event ):
event.Skip()
def OnSaturationScroll( self, event ):
event.Skip()
def OnSaturationSpin( self, event ):
event.Skip()
def OnSaturationTextEnter( self, event ):
event.Skip()
def OnValueScroll( self, event ):
event.Skip()
def OnValueSpin( self, event ):
event.Skip()
def OnValueTextEnter( self, event ):
event.Skip()
def OnPresetSelect( self, event ):
event.Skip()
def OnCancel( self, event ):
event.Skip()
def OnCopy( self, event ):
event.Skip()
def OnInsert( self, event ):
event.Skip()
| 14,238
|
Python
|
.py
| 227
| 59.409692
| 176
| 0.750539
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,813
|
__init__.py
|
psychopy_psychopy/psychopy/app/colorpicker/__init__.py
|
# -*- coding: utf-8 -*-
"""Classes for the color picker."""
# Part of the PsychoPy library
# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019 Open Science Tools Ltd.
# Distributed under the terms of the GNU General Public License (GPL).
import sys
import wx
import wx.stc as stc
from .ui import ColorPickerDialog
from psychopy.colors import Color, colorNames
# from psychopy.localization import _translate
SLIDER_RES = 255 # resolution of the slider for color channels, leave alone!
class ColorPickerState:
"""Class representing the state of the color picker. This is used to
provide persistence between multiple invocations of the dialog within a
single session.
Parameters
----------
color : Color
Last color selected by the user.
space : int
Last RGB colorspace specified.
rgbInputMode : int
RGB input mode selected by the user.
"""
def __init__(self, color, space, rgbInputMode):
self.color = color
self.space = space
self.rgbInputMode = rgbInputMode
# Store the state of the color picker here for persistance. Here we define the
# defaults for when the colorpicker is first invoked.
COLORPICKER_STATE = ColorPickerState(
color=Color((0, 0, 0, 1), space='rgba'),
space=0,
rgbInputMode=0 # PsychopPy RGB
)
class PsychoColorPicker(ColorPickerDialog):
"""Class for the color picker dialog.
This dialog is used to standardize color selection across platforms. It also
supports PsychoPy's RGB representation directly.
This is a subclass of the auto-generated `ColorPickerDialog` class.
Parameters
----------
parent : object
Reference to a :class:`~wx.Frame` which owns this dialog.
"""
# NB: This is a *really* complicated dialog box as controls can update each
# other and colors have many different formats that can be used to set
# values. If you're not careful, one control updating the values of another
# can trigger events which in-turn set the original control. This can lead
# to deadlocks that may either stop the control from being updated or cause
# an application error. There are probably better ways of doing things here
# but beware of these potential pitfalls when making changes to this class.
# -- mdc
#
def __init__(self, parent, context=None, allowInsert=True, allowCopy=True):
ColorPickerDialog.__init__(self, parent)
self.parent = parent
self.allowInsert = allowInsert
if not self.allowInsert:
self.cmdInsert.Disable()
self.cmdInsert.Hide()
self.allowCopy = allowCopy
if not self.allowCopy:
self.cmdCopy.Disable()
self.cmdCopy.Hide()
self.SetSizeHints(wx.DefaultSize, wx.DefaultSize)
self.SetSize(wx.Size(640, 480))
self.SetMinSize(wx.Size(640, 480))
# store context
self.context = context
# output spaces mapped to the `cboOutputSpace` object
self._spaces = {
0: 'rgb',
1: 'rgb1',
2: 'rgb255',
3: 'hex',
4: 'hsv'
}
# what to show in the output selection, maps to the spaces above
self._outputChoices = [
u'PsychoPy RGB (rgb)',
u'Normalized RGB (rgb1)',
u'8-bit RGB (rgb255)',
u'Hex/HTML (hex)',
u'Hue-Saturation-Value (hsv)'
]
# set preset color names, all except None
self.lstColorPresets.SetItems(
[col for col in colorNames.keys() if col is not None])
# Functions to convert slider units to an RGB format to display in the
# double-spin controls beside them.
self._posToValFunc = {
0: lambda v: 2 * (v / SLIDER_RES) - 1, # [-1:1]
1: lambda v: v / SLIDER_RES, # [0:1]
2: lambda v: v} # [0:255]
# inverse of the above functions, converts values to positions
self._valToPosFunc = {
0: lambda p: int(SLIDER_RES * (p + 1) / 2.), # [-1:1]
1: lambda p: int(p * SLIDER_RES), # [0:1]
2: lambda p: int(p)} # [0:255]
# initialize the window controls
midpoint = int(SLIDER_RES / 2.)
self.sldRedChannel.SetValue(midpoint)
self.sldGreenChannel.SetValue(midpoint)
self.sldBlueChannel.SetValue(midpoint)
self.sldRedChannel.SetMax(SLIDER_RES)
self.sldGreenChannel.SetMax(SLIDER_RES)
self.sldBlueChannel.SetMax(SLIDER_RES)
self.sldHueChannel.SetRange(0, 360)
self.sldStaturationChannel.SetRange(0, SLIDER_RES)
self.sldValueChannel.SetRange(0, SLIDER_RES)
# current output color, should be displayed in the preview
global COLORPICKER_STATE
self._color = None
self.color = COLORPICKER_STATE.color.copy()
self.rgbInputMode = COLORPICKER_STATE.rgbInputMode
# set the available output spaces
self.cboOutputSpace.SetItems(self._outputChoices)
self.cboOutputSpace.SetSelection(COLORPICKER_STATE.space)
@property
def color(self):
"""Current color the user has specified. Should be reflected in the
preview area. Value has type :class:`psychopy.colors.Color`.
This is the primary setter for the dialog's color value. It will
automatically update all color space pages to reflect this color value.
Pages should absolutely not attempt to set other page's values directly
or risk blowing up the call stack.
"""
return self._color
@color.setter
def color(self, value):
if value is None:
value = Color((0., 0., 0., 1.), space='rgba')
self._color = value
self.updateRGBPage()
self.updateHSVPage()
self.updateDialog()
@property
def rgbInputMode(self):
"""The RGB input mode (`int`). This will update how RGB channels are
formatted when set.
"""
# replaces the older radio box which returned indices
if self.rdoRGBModePsychoPy.GetValue():
return 0
elif self.rdoRGBModeNormalized.GetValue():
return 1
elif self.rdoRGBMode255.GetValue():
return 2
else:
return -1
@rgbInputMode.setter
def rgbInputMode(self, value):
value = int(value)
if value == 0:
self.rdoRGBModePsychoPy.SetValue(1)
elif value == 1:
self.rdoRGBModeNormalized.SetValue(1)
elif value == 2:
self.rdoRGBMode255.SetValue(1)
else:
raise IndexError('Invalid index for `rgbInputMode`.')
self.updateRGBChannels()
self.updateDialog()
# --------------------------------------------------------------------------
# Dialog controls update methods
#
def updateDialog(self):
"""Update the color specified by the dialog. Call this whenever the
color controls are updated by the user.
"""
spinVals = [
self.spnRedChannel.GetValue(),
self.spnGreenChannel.GetValue(),
self.spnBlueChannel.GetValue()]
if self.rgbInputMode == 0:
self.color.rgb = spinVals
elif self.rgbInputMode == 1:
self.color.rgb1 = spinVals
elif self.rgbInputMode == 2:
self.color.rgb255 = spinVals
else:
raise ValueError('Color channel format not supported.')
# update the HSV page
previewRGB = [int(gun) for gun in self.color.rgb255]
r, g, b = previewRGB
self.pnlColorPreview.SetBackgroundColour(
wx.Colour(r, g, b, alpha=wx.ALPHA_OPAQUE))
self.pnlColorPreview.Refresh()
self.txtHexRGB.SetValue(self.color.hex)
def updateHSVPage(self):
"""Update values on the HSV page. This is called when some other page is
used to pick the color and the HSV page needs to reflect that.
"""
# get colors and convert to format wxPython controls can accept
hsvColor = self.color.hsv
self.sldHueChannel.SetValue(int(hsvColor[0]))
self.sldStaturationChannel.SetValue(int(hsvColor[1] * SLIDER_RES))
self.sldValueChannel.SetValue(int(hsvColor[2] * SLIDER_RES))
# set the value in the new range
self.spnHueChannel.SetValue(hsvColor[0])
self.spnSaturationChannel.SetValue(hsvColor[1])
self.spnValueChannel.SetValue(hsvColor[2])
def updateRGBPage(self):
"""Update values on the RGB page. This is called when some other page is
used to pick the color and the RGB page needs to reflect that.
"""
rgb255 = [int(i) for i in self.color.rgb255]
self.sldRedChannel.SetValue(rgb255[0])
self.sldGreenChannel.SetValue(rgb255[1])
self.sldBlueChannel.SetValue(rgb255[2])
# self.sldAlpha.SetValue(
# rgbaColor.alpha * SLIDER_RES) # arrrg! should be 255!!!
# set the value in the new range
if self.rgbInputMode == 0:
spnColVals = self.color.rgb
elif self.rgbInputMode == 1:
spnColVals = self.color.rgb1
elif self.rgbInputMode == 2:
spnColVals = self.color.rgb255
else:
raise ValueError(
"Unknown RGB channel format specified. Did you add a new mode?")
self.spnRedChannel.SetValue(spnColVals[0])
self.spnGreenChannel.SetValue(spnColVals[1])
self.spnBlueChannel.SetValue(spnColVals[2])
def updateRGBChannels(self):
"""Update the values of the indicated RGB channels to reflect the
selected color input mode.
The RGB page has modes which changes the format of the input values.
Calling this updates the controls to reflect the format.
"""
# get colors and convert to format wxPython controls can accept
channelMode = self.rgbInputMode
convFunc = self._posToValFunc[channelMode]
# update spinner values/ranges for each channel
for spn in (self.spnRedChannel, self.spnGreenChannel, self.spnBlueChannel):
spn.SetDigits(
0 if channelMode == 2 else 4)
spn.SetIncrement(
1 if channelMode == 2 else 0.05)
spn.SetMin(convFunc(0))
spn.SetMax(convFunc(SLIDER_RES))
self.updateRGBPage()
# --------------------------------------------------------------------------
# Events for RGB controls
#
def OnRedScroll(self, event):
"""Called when the red (RGB) channel slider is moved.
"""
self.spnRedChannel.SetValue(
self._posToValFunc[self.rgbInputMode](
event.Position))
self.updateHSVPage()
self.updateDialog()
def OnGreenScroll(self, event):
"""Called when the green (RGB) channel slider is moved.
"""
self.spnGreenChannel.SetValue(
self._posToValFunc[self.rgbInputMode](
event.Position))
self.updateHSVPage()
self.updateDialog()
def OnBlueScroll(self, event):
"""Called when the blue (RGB) channel slider is moved.
"""
self.spnBlueChannel.SetValue(
self._posToValFunc[self.rgbInputMode](
event.Position))
self.updateHSVPage()
self.updateDialog()
def OnRedSpin(self, event):
"""Called when the red (RGB) spin control is changed.
"""
self.sldRedChannel.SetValue(
self._valToPosFunc[self.rgbInputMode](event.Value))
self.updateHSVPage()
self.updateDialog()
def OnGreenSpin(self, event):
"""Called when the green (RGB) spin control is changed.
"""
self.sldGreenChannel.SetValue(
self._valToPosFunc[self.rgbInputMode](event.Value))
self.updateHSVPage()
self.updateDialog()
def OnBlueSpin(self, event):
"""Called when the blue (RGB) spin control is changed.
"""
self.sldBlueChannel.SetValue(
self._valToPosFunc[self.rgbInputMode](event.Value))
self.updateHSVPage()
self.updateDialog()
def OnRGBModePsychoPy(self, event):
"""Called when the user selects 'PsychoPy RGB' mode as the RGB input
format.
"""
self.updateRGBChannels()
def OnRGBModeNormalized(self, event):
"""Called when the user selects 'Normalized RGB' mode as the RGB input
format.
"""
self.updateRGBChannels()
def OnRGBMode255(self, event):
"""Called when the user selects '8-Bit RGB' mode as the RGB input
format.
"""
self.updateRGBChannels()
# --------------------------------------------------------------------------
# Events for HSV controls
#
def OnHueSpin(self, event):
"""Called when the hue (HSV) spin control is changed.
"""
self.sldHueChannel.SetValue(event.GetValue())
self.color.hsv = (
self.spnHueChannel.GetValue(),
self.spnSaturationChannel.GetValue(),
self.spnValueChannel.GetValue())
self.updateRGBPage()
self.updateDialog()
def OnHueScroll(self, event):
"""Called when the hue (HSV) channel slider is moved.
"""
self.spnHueChannel.SetValue(event.Position)
self.color.hsv = (
self.spnHueChannel.GetValue(),
self.spnSaturationChannel.GetValue(),
self.spnValueChannel.GetValue())
self.updateRGBPage()
self.updateDialog()
def OnSaturationSpin(self, event):
"""Called when the saturation (HSV) spin control is changed.
"""
self.sldStaturationChannel.SetValue(event.GetValue() * SLIDER_RES)
self.color.hsv = (
self.spnHueChannel.GetValue(),
self.spnSaturationChannel.GetValue(),
self.spnValueChannel.GetValue())
self.updateRGBPage()
self.updateDialog()
def OnSaturationScroll(self, event):
"""Called when the saturation (HSV) channel slider is moved.
"""
self.spnSaturationChannel.SetValue(event.Position / SLIDER_RES)
self.color.hsv = (
self.spnHueChannel.GetValue(),
self.spnSaturationChannel.GetValue(),
self.spnValueChannel.GetValue())
self.updateRGBPage()
self.updateDialog()
def OnValueSpin(self, event):
"""Called when the value (HSV) spin control is changed.
"""
self.sldValueChannel.SetValue(event.GetValue() * SLIDER_RES)
self.color.hsv = (
self.spnHueChannel.GetValue(),
self.spnSaturationChannel.GetValue(),
self.spnValueChannel.GetValue())
self.updateRGBPage()
self.updateDialog()
def OnValueScroll(self, event):
"""Called when the value (HSV) channel slider is moved.
"""
self.spnValueChannel.SetValue(event.Position / SLIDER_RES)
self.color.hsv = (
self.spnHueChannel.GetValue(),
self.spnSaturationChannel.GetValue(),
self.spnValueChannel.GetValue())
self.updateRGBPage()
self.updateDialog()
# --------------------------------------------------------------------------
# Hex RGB input methods
#
def OnHexRGBKeyDown(self, event):
"""Called when the user manually enters a hex value into the field.
If the color value is valid, the new value will appear and the channels
will update. If not, the box will revert back to the last valid value.
"""
# keydown need to be processed like this on MacOS
if event.GetKeyCode() == wx.WXK_RETURN:
oldHexColor = self.color.hex
try:
self.color.rgba = Color(
self.txtHexRGB.GetValue(), space='hex').rgba
self.updateRGBPage()
self.updateHSVPage()
self.updateDialog()
except ValueError:
self.txtHexRGB.SetValue(oldHexColor)
else:
event.Skip()
def updateHex(self):
"""Update the hex/HTML value using the color specified by the dialog.
"""
self.txtHexRGB.SetValue(self.color.hex)
# --------------------------------------------------------------------------
# Color preset list methods
#
def OnPresetSelect(self, event):
"""Called when the user selects a preset from the list.
"""
idxSelection = self.lstColorPresets.GetSelection()
if idxSelection == -1: # event occurred with no valid selection
event.Skip()
presetColorKey = self.lstColorPresets.GetString(idxSelection)
presetColor = Color(colorNames[presetColorKey], space='rgb')
self.color = presetColor
# --------------------------------------------------------------------------
# Output methods
#
def getOutputValue(self):
"""Get the string value using the specified output format.
Returns
-------
str
Color value using the current output format.
"""
outputSpace = self.cboOutputSpace.GetSelection()
dlgCol = self.GetTopLevelParent().color
if outputSpace == 0: # RGB
colorOut = '{:.4f}, {:.4f}, {:.4f}'.format(*dlgCol.rgb)
elif outputSpace == 1: # RGB1
colorOut = '{:.4f}, {:.4f}, {:.4f}'.format(*dlgCol.rgb1)
elif outputSpace == 2: # RGB255
colorOut = '{:d}, {:d}, {:d}'.format(
*[int(i) for i in dlgCol.rgb255])
elif outputSpace == 3: # Hex
colorOut = "'{}'".format(dlgCol.hex)
elif outputSpace == 4: # HSV
colorOut = '{:.4f}, {:.4f}, {:.4f}'.format(*dlgCol.hsv)
else:
raise ValueError(
"Invalid output color space selection. Have you added any "
"choices to `cboOutputSpace`?")
return colorOut
def _copyToClipboard(self, text):
"""Copy text to the clipboard.
Shows an error dialog if the clipboard cannot be opened to inform the
user the values have not been copied.
Parameters
----------
text : str
Text to copy to the clipboard.
"""
# copy the value to the clipboard
if wx.TheClipboard.Open():
wx.TheClipboard.SetData(wx.TextDataObject(str(text)))
wx.TheClipboard.Close()
else:
# Raised if the clipboard fails to open, warns the user the value
# wasn't copied.
errDlg = wx.MessageDialog(
self,
'Failed to open the clipboard, output value not copied.',
'Clipboard Error',
wx.OK | wx.ICON_ERROR)
errDlg.ShowModal()
errDlg.Destroy()
def _saveState(self):
"""Call this to make dialog value persistent across invocations.
"""
global COLORPICKER_STATE
COLORPICKER_STATE.color = self.color.copy()
COLORPICKER_STATE.space = self.cboOutputSpace.GetSelection()
COLORPICKER_STATE.rgbInputMode = self.rgbInputMode
def OnInsert(self, event):
"""Event to copy the color to the clipboard as a an object.
"""
if not self.allowInsert:
event.Skip()
if isinstance(self.context, wx.TextCtrl):
self.context.SetValue(self.getOutputValue())
elif isinstance(self.context, stc.StyledTextCtrl):
self.context.InsertText(
self.context.GetCurrentPos(), "(" + self.getOutputValue() + ")")
self._saveState() # retain state
self.Close()
def OnCopy(self, event):
"""Event to copy the color to the clipboard as a value.
"""
if not self.allowCopy:
event.Skip()
self._copyToClipboard(self.getOutputValue()) # copy out to clipboard
self._saveState()
self.Close()
def OnCancel(self, event):
"""Called when the cancel button is clicked.
"""
self.Close()
# def OnClose(self, event):
# """Called when the 'x' is clicked on the title bar."""
# self._saveState()
# self.Close()
if __name__ == "__main__":
pass
| 20,423
|
Python
|
.py
| 496
| 31.919355
| 83
| 0.607242
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,814
|
__init__.py
|
psychopy_psychopy/psychopy/app/ui/__init__.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Classes for graphical user interface elements for the main application.
"""
# Part of the PsychoPy library
# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd.
# Distributed under the terms of the GNU General Public License (GPL).
import wx
import wx.lib.agw.aui as aui
# default values
DEFAULT_FRAME_SIZE = wx.Size(800, 600)
DEFAULT_FRAME_TITLE = u"PsychoPy"
DEFAULT_AUI_STYLE_FLAGS = ( # flags for AUI
aui.AUI_MGR_DEFAULT | aui.AUI_MGR_RECTANGLE_HINT)
class BaseAuiFrame(wx.Frame):
"""Base class for AUI managed frames.
Takes the same arguments as `wx.Frame`. This frame is AUI managed which
allows for sub-windows to be attached to it. No application logic should be
implemented in this class, only its sub-classes.
Parameter
---------
parent : wx.Window or None
Parent window.
id : int
Unique ID for this window, default is `wx.ID_ANY`.
title : str
Window title to use. Can be set later.
pos : ArrayLike or `wx.Position`
Initial position of the window on the desktop. Default is
`wx.DefaultPosition`.
size : ArrayLike or `wx.Size`
Initial sie of the window in desktop units.
style : int
Style flags for the window. Default is the combination of
`wx.DEFAULT_FRAME_STYLE` and `wx.TAB_TRAVERSAL`.
"""
def __init__(self,
parent,
id=wx.ID_ANY,
title=DEFAULT_FRAME_TITLE,
pos=wx.DefaultPosition,
size=DEFAULT_FRAME_SIZE,
style=wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL):
# subclass `wx.Frame`
wx.Frame.__init__(self, parent, id=id, title=title, pos=pos, size=size,
style=style)
# defaults for window
self.SetSizeHints(wx.DefaultSize, wx.DefaultSize)
# create the AUI manager and attach it to this window
self.m_mgr = aui.AuiManager(self, agwFlags=DEFAULT_AUI_STYLE_FLAGS)
self.m_mgr.Update()
self.Centre(wx.BOTH)
# events associated with this window
self.Bind(aui.EVT_AUI_PANE_ACTIVATED, self.onAuiPaneActivate)
self.Bind(aui.EVT_AUI_PANE_BUTTON, self.onAuiPaneButton)
self.Bind(aui.EVT_AUI_PANE_CLOSE, self.onAuiPaneClose)
self.Bind(aui.EVT_AUI_PANE_MAXIMIZE, self.onAuiPaneMaximize)
self.Bind(aui.EVT_AUI_PANE_RESTORE, self.onAuiPaneRestore)
self.Bind(wx.EVT_CLOSE, self.onClose)
self.Bind(wx.EVT_IDLE, self.onIdle)
def __del__(self):
# called when tearing down the window
self.m_mgr.UnInit()
# --------------------------------------------------------------------------
# Class properties and methods
#
@property
def manager(self):
"""Handle of the AUI manager for this frame (`wx.aui.AuiManager`).
"""
return self.getAuiManager()
def getAuiManager(self):
"""Get the AUI manager instance for this window.
Returns
-------
wx.aui.AuiManager
Handle for the AUI manager instance associated with this window.
"""
return self.m_mgr
def setTitle(self, title=DEFAULT_FRAME_TITLE, document=None):
"""Set the window title.
Use this method to set window titles to ensure that PsychoPy windows use
similar formatting for them.
Parameters
----------
title : str
Window title to set. Default is `DEFAULT_FRAME_TITLE`.
document : str or None
Optional document file name or path. Will be appended to the title
bar with a `' - '` separator.
Examples
--------
Set the window title for the new document::
someFrame.setTitle(document='mycode.py')
# title set to: "mycode.py - PsychoPy"
"""
if document is not None:
self.SetTitle(" - ".join([document, title]))
else:
self.SetTitle(title)
def getTitle(self):
"""Get the window frame title.
Returns
-------
str
Current window frame title.
"""
return self.GetTitle()
# --------------------------------------------------------------------------
# Events for the AUI frame
#
# AUI events can be used to monitor changes to the pane layout. These can
# then be used to update the appropriate menu item.
#
def onAuiPaneActivate(self, event):
"""Called when the pane gets focused or is activated.
"""
event.Skip()
def onAuiPaneButton(self, event):
"""Called when an AUI pane button is clicked.
"""
event.Skip()
def onAuiPaneClose(self, event):
"""Called when an AUI pane is closed.
"""
event.Skip()
def onAuiPaneMaximize(self, event):
"""Called when an AUI pane is maximized.
"""
event.Skip()
def onAuiPaneRestore(self, event):
"""Called when a AUI pane is restored.
"""
event.Skip()
def onClose(self, event):
"""Event handler for `EVT_CLOSE` events. This is usually called when the
user clicks the close button on the frame's title bar.
"""
event.Skip()
def onIdle(self, event):
"""Event handler for `EVT_IDLE` events. Called periodically when the
user is not interacting with the UI.
"""
event.Skip()
if __name__ == "__main__":
pass
| 5,578
|
Python
|
.py
| 146
| 30.041096
| 80
| 0.602151
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,815
|
ui.py
|
psychopy_psychopy/psychopy/app/linuxconfig/ui.py
|
# -*- coding: utf-8 -*-
###########################################################################
## Python code generated with wxFormBuilder (version 3.10.1-0-g8feb16b)
## http://www.wxformbuilder.org/
##
## PLEASE DO *NOT* EDIT THIS FILE!
###########################################################################
import wx
import wx.xrc
###########################################################################
## Class BaseLinuxConfigDialog
###########################################################################
class BaseLinuxConfigDialog ( wx.Dialog ):
def __init__( self, parent ):
wx.Dialog.__init__ ( self, parent, id = wx.ID_ANY, title = u"Additional configuration needed ...", pos = wx.DefaultPosition, size = wx.Size( 640,420 ), style = wx.DEFAULT_DIALOG_STYLE )
self.SetSizeHints( wx.DefaultSize, wx.DefaultSize )
szrMain = wx.BoxSizer( wx.VERTICAL )
self.lblIntro = wx.StaticText( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( -1,-1 ), 0 )
self.lblIntro.Wrap( 640 )
szrMain.Add( self.lblIntro, 0, wx.ALL|wx.EXPAND, 5 )
szrCommands = wx.FlexGridSizer( 3, 2, 5, 5 )
szrCommands.AddGrowableCol( 0 )
szrCommands.AddGrowableRow( 0 )
szrCommands.SetFlexibleDirection( wx.BOTH )
szrCommands.SetNonFlexibleGrowMode( wx.FLEX_GROWMODE_SPECIFIED )
self.txtCmdList = wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, wx.HSCROLL|wx.TE_DONTWRAP|wx.TE_MULTILINE|wx.TE_READONLY )
szrCommands.Add( self.txtCmdList, 1, wx.EXPAND, 5 )
self.cmdCopyLine = wx.Button( self, wx.ID_ANY, u"Copy", wx.DefaultPosition, wx.DefaultSize, 0 )
szrCommands.Add( self.cmdCopyLine, 0, 0, 5 )
szrMain.Add( szrCommands, 1, wx.ALL|wx.EXPAND, 10 )
szrButtons = wx.FlexGridSizer( 0, 4, 0, 0 )
szrButtons.AddGrowableCol( 1 )
szrButtons.SetFlexibleDirection( wx.BOTH )
szrButtons.SetNonFlexibleGrowMode( wx.FLEX_GROWMODE_SPECIFIED )
self.cmdOpenTerminal = wx.Button( self, wx.ID_ANY, u"Open Terminal ...", wx.DefaultPosition, wx.DefaultSize, 0 )
szrButtons.Add( self.cmdOpenTerminal, 0, 0, 0 )
szrButtons.Add( ( 0, 0), 1, wx.EXPAND, 5 )
self.cmdDone = wx.Button( self, wx.ID_ANY, u"Done", wx.DefaultPosition, wx.DefaultSize, 0 )
szrButtons.Add( self.cmdDone, 0, 0, 0 )
szrMain.Add( szrButtons, 0, wx.ALL|wx.EXPAND, 10 )
self.SetSizer( szrMain )
self.Layout()
self.Centre( wx.BOTH )
# Connect Events
self.cmdCopyLine.Bind( wx.EVT_BUTTON, self.OnCopy )
self.cmdOpenTerminal.Bind( wx.EVT_BUTTON, self.OnOpenTerminal )
self.cmdDone.Bind( wx.EVT_BUTTON, self.OnDone )
def __del__( self ):
pass
# Virtual event handlers, override them in your derived class
def OnCopy( self, event ):
event.Skip()
def OnOpenTerminal( self, event ):
event.Skip()
def OnDone( self, event ):
event.Skip()
| 3,061
|
Python
|
.py
| 56
| 47.375
| 193
| 0.593676
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,816
|
__init__.py
|
psychopy_psychopy/psychopy/app/linuxconfig/__init__.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Part of the PsychoPy library
# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd.
# Distributed under the terms of the GNU General Public License (GPL).
"""Dialog prompting the user to configure their system for Linux specific
optimizations.
"""
__all__ = [
'LinuxConfigDialog',
'linuxConfigFileExists'
]
import os.path
import sys
import wx
from .ui import BaseLinuxConfigDialog
from ...core import rush
# Text that appears at the top of the dialog with provides instructions to the
# user.
_introStr = (
u"For optimal performance on Linux, Psychtoolbox requires additional "
u"configuration changes to be made to this system by entering the "
u"following commands into your terminal:"
)
# config file path
_confPath = u"/etc/security/limits.d/99-psychopylimits.conf"
# these are the commands we want the user to run in their terminal
_cmdStr = (
u"sudo groupadd --force psychopy\n\n"
u"sudo usermod -a -G psychopy $USER\n\n"
u"sudo gedit {fpath}\n"
u"@psychopy - nice -20\n"
u"@psychopy - rtprio 50\n"
u"@psychopy - memlock unlimited")
_cmdStr = _cmdStr.format(fpath=_confPath)
class LinuxConfigDialog(BaseLinuxConfigDialog):
"""Class for the Linux one-time setup dialog.
This dialog appears to users running PsychoPy on Linux for the first time.
It prompts the user to open a terminal and enter the indicated commands that
configure the environment to run Psychtoolbox with optimal settings.
This dialog will appear at startup until the user completes the
configuration steps. We determine if configuration is complete by testing if
the expected file is present at the required location.
Parameters
----------
parent : wx.Window or None
Dialog parent.
timeout : int or None
Milliseconds to keep the dialog open. Setting to `None` keeps the dialog
open. Specify a time if we're running in a test environment to prevent
the UI from locking up the test suite.
"""
def __init__(self, parent, timeout=None):
BaseLinuxConfigDialog.__init__(self, parent)
# intro text which provides instructions for the user
self.lblIntro.SetLabel(_introStr)
self.lblIntro.Wrap(640)
# make the text box show the commands for the user to enter into their
# terminal
self.txtCmdList.SetValue(_cmdStr)
self.txtCmdList.SetMinSize((320, 240))
# redo the layout
self.DoLayoutAdaptation()
self.timeout = timeout
if self.timeout is not None:
timeout = wx.CallLater(self.timeout, self.Close)
timeout.Start()
def OnOpenTerminal(self, event):
event.Skip()
def OnCopy(self, event):
"""Called when the copy button is clicked.
"""
# check if we have a selection
start, end = self.txtCmdList.GetSelection()
if start != end:
txt = self.txtCmdList.GetStringSelection()
else:
txt = self.txtCmdList.GetValue()
if wx.TheClipboard.Open():
wx.TheClipboard.SetData(wx.TextDataObject(txt))
wx.TheClipboard.Close()
event.Skip()
def OnDone(self, event):
"""Called when the 'Done' button is clicked.
"""
if not linuxConfigFileExists():
msgText = (
u"Setup does not appear to be complete, would you like to "
u"continue anyways?\nNote that PTB audio timing performance "
u"may not be optimal this session until this configuration "
u"step is completed."
)
# show dialog
dlg = wx.MessageDialog(
self,
msgText,
style=wx.YES_NO | wx.YES_DEFAULT
)
result = dlg.ShowModal()
if result == wx.ID_YES:
self.Close()
else:
event.Skip()
dlg.Destroy()
def linuxConfigFileExists():
"""Check if the required configuration file has been written.
Returns
-------
bool
`True` if the file exists or not on Linux.
"""
# if not on linux, just pass it
if sys.platform != 'linux':
return True
return os.path.isfile(_confPath)
def linuxRushAllowed():
if sys.platform != 'linux':
return True
success = rush(1)
rush(0)
return success
| 4,494
|
Python
|
.py
| 121
| 29.859504
| 80
| 0.651693
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,817
|
project.py
|
psychopy_psychopy/psychopy/app/pavlovia_ui/project.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Part of the PsychoPy library
# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd.
# Distributed under the terms of the GNU General Public License (GPL).
import io
import sys
import tempfile
import time
import os
import traceback
from pathlib import Path
import gitlab
import requests
from .functions import (setLocalPath, showCommitDialog, logInPavlovia,
noGitWarning)
from psychopy.localization import _translate
from psychopy.projects import pavlovia
from psychopy import logging
from psychopy.app.pavlovia_ui import sync, functions
import wx
from wx.lib import scrolledpanel as scrlpanel
from .. import utils
from ..themes import icons
from ...projects.pavlovia import PavloviaProject
try:
import wx.lib.agw.hyperlink as wxhl # 4.0+
except ImportError:
import wx.lib.hyperlink as wxhl # <3.0.2
_starred = u"\u2605"
_unstarred = u"\u2606"
class ProjectEditor(wx.Dialog):
def __init__(self, parent=None, id=wx.ID_ANY, project=None, localRoot="",
*args, **kwargs):
wx.Dialog.__init__(self, parent, id,
*args, **kwargs)
panel = wx.Panel(self, wx.ID_ANY, style=wx.TAB_TRAVERSAL)
# when a project is successfully created these will be populated
if hasattr(parent, 'filename'):
self.filename = parent.filename
else:
self.filename = None
self.project = project # type: pavlovia.PavloviaProject
self.projInfo = None
self.parent = parent
if project:
# edit existing project
self.isNew = False
if project.localRoot and not localRoot:
localRoot = project.localRoot
else:
self.isNew = True
# create the controls
nameLabel = wx.StaticText(panel, -1, _translate("Name:"))
self.nameBox = wx.TextCtrl(panel, -1, size=(400, -1))
# Path can contain only letters, digits, '_', '-' and '.'.
# Cannot start with '-', end in '.git' or end in '.atom']
pavSession = pavlovia.getCurrentSession()
try:
username = pavSession.user.username
except AttributeError as e:
raise pavlovia.NoUserError("{}: Tried to create project with no user logged in.".format(e))
gpChoices = [username]
gpChoices.extend(pavSession.listUserGroups())
groupLabel = wx.StaticText(panel, -1, _translate("Group/owner:"))
self.groupBox = wx.Choice(panel, -1, size=(400, -1),
choices=gpChoices)
descrLabel = wx.StaticText(panel, -1, _translate("Description:"))
self.descrBox = wx.TextCtrl(panel, -1, size=(400, 200),
style=wx.TE_MULTILINE | wx.SUNKEN_BORDER)
localLabel = wx.StaticText(panel, -1, _translate("Local folder:"))
self.localBox = wx.TextCtrl(panel, -1, size=(400, -1),
value=localRoot)
self.btnLocalBrowse = wx.Button(panel, wx.ID_ANY, _translate("Browse..."))
self.btnLocalBrowse.Bind(wx.EVT_BUTTON, self.onBrowseLocal)
localPathSizer = wx.BoxSizer(wx.HORIZONTAL)
localPathSizer.Add(self.localBox)
localPathSizer.Add(self.btnLocalBrowse)
tagsLabel = wx.StaticText(panel, -1,
_translate("Tags (comma separated):"))
self.tagsBox = wx.TextCtrl(panel, -1, size=(400, 100),
value="PsychoPy, Builder, Coder",
style=wx.TE_MULTILINE | wx.SUNKEN_BORDER)
publicLabel = wx.StaticText(panel, -1, _translate("Public:"))
self.publicBox = wx.CheckBox(panel, -1)
# buttons
if self.isNew:
buttonMsg = _translate("Create project on Pavlovia")
else:
buttonMsg = _translate("Submit changes to Pavlovia")
updateBtn = wx.Button(panel, -1, buttonMsg)
updateBtn.Bind(wx.EVT_BUTTON, self.submitChanges)
cancelBtn = wx.Button(panel, -1, _translate("Cancel"))
cancelBtn.Bind(wx.EVT_BUTTON, self.onCancel)
btnSizer = wx.BoxSizer(wx.HORIZONTAL)
if sys.platform == "win32":
btns = [updateBtn, cancelBtn]
else:
btns = [cancelBtn, updateBtn]
btnSizer.AddMany(btns)
# do layout
fieldsSizer = wx.FlexGridSizer(cols=2, rows=6, vgap=5, hgap=5)
fieldsSizer.AddMany([(nameLabel, 0, wx.ALIGN_RIGHT), self.nameBox,
(groupLabel, 0, wx.ALIGN_RIGHT), self.groupBox,
(localLabel, 0, wx.ALIGN_RIGHT), localPathSizer,
(descrLabel, 0, wx.ALIGN_RIGHT), self.descrBox,
(tagsLabel, 0, wx.ALIGN_RIGHT), self.tagsBox,
(publicLabel, 0, wx.ALIGN_RIGHT), self.publicBox])
border = wx.BoxSizer(wx.VERTICAL)
border.Add(fieldsSizer, 0, wx.ALL, 5)
border.Add(btnSizer, 0, wx.ALIGN_RIGHT | wx.ALL, 5)
panel.SetSizerAndFit(border)
self.Fit()
def onCancel(self, evt=None):
self.EndModal(wx.ID_CANCEL)
def submitChanges(self, evt=None):
session = pavlovia.getCurrentSession()
if not session.user:
user = logInPavlovia(parent=self.parent)
if not session.user:
return
# get current values
name = self.nameBox.GetValue()
namespace = self.groupBox.GetStringSelection()
descr = self.descrBox.GetValue()
visibility = self.publicBox.GetValue()
# tags need splitting and then
tagsList = self.tagsBox.GetValue().split(',')
tags = [thisTag.strip() for thisTag in tagsList]
localRoot = self.localBox.GetValue()
if not localRoot:
localRoot = setLocalPath(self.parent, project=None, path="")
# then create/update
if self.isNew:
project = session.createProject(name=name,
description=descr,
tags=tags,
visibility=visibility,
localRoot=localRoot,
namespace=namespace)
self.project = project
self.project._newRemote = True
else: # we're changing metadata of an existing project. Don't sync
self.project.pavlovia.name = name
self.project.pavlovia.description = descr
self.project.tags = tags
self.project.visibility = visibility
self.project.localRoot = localRoot
self.project.save() # pushes changed metadata to gitlab
self.project._newRemote = False
self.EndModal(wx.ID_OK)
pavlovia.knownProjects.save()
self.project.getRepo(forceRefresh=True)
self.parent.project = self.project
def onBrowseLocal(self, evt=None):
newPath = setLocalPath(self, path=self.filename)
if newPath:
self.localBox.SetLabel(newPath)
self.Layout()
if self.project:
self.project.localRoot = newPath
self.Raise()
class DetailsPanel(wx.Panel):
class StarBtn(wx.Button):
def __init__(self, parent, value=False):
wx.Button.__init__(self, parent, label=_translate("Star"))
# Setup icons
self.icons = {
True: icons.ButtonIcon(stem="starred", size=16, theme="light").bitmap,
False: icons.ButtonIcon(stem="unstarred", size=16, theme="light").bitmap,
}
self.SetBitmapDisabled(self.icons[False]) # Always appear empty when disabled
# Set start value
self.value = value
@property
def value(self):
return self._value
@value.setter
def value(self, value):
# Store value
self._value = bool(value)
# Change icon
self.SetBitmap(self.icons[self._value])
self.SetBitmapCurrent(self.icons[self._value])
self.SetBitmapFocus(self.icons[self._value])
def toggle(self):
self.value = (not self.value)
def __init__(self, parent, project=None,
size=(650, 650),
style=wx.NO_BORDER):
wx.Panel.__init__(self, parent, -1,
size=size,
style=style)
self.SetBackgroundColour("white")
self.parent = parent
self._updateQueue = []
# Setup sizer
self.contentBox = wx.BoxSizer()
self.SetSizer(self.contentBox)
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.contentBox.Add(self.sizer, proportion=1, border=12, flag=wx.ALL | wx.EXPAND)
# Head sizer
self.headSizer = wx.BoxSizer(wx.HORIZONTAL)
self.sizer.Add(self.headSizer, border=0, flag=wx.EXPAND)
# Icon
self.icon = utils.ImageCtrl(self, bitmap=wx.Bitmap(), size=(128, 128))
self.icon.SetBackgroundColour("#f2f2f2")
self.icon.Bind(wx.EVT_FILEPICKER_CHANGED, self.queueUpdate)
self.headSizer.Add(self.icon, border=6, flag=wx.ALL)
self.icon.SetToolTip(_translate(
"An image to represent this project, this helps it stand out when browsing on Pavlovia."
))
# Title sizer
self.titleSizer = wx.BoxSizer(wx.VERTICAL)
self.headSizer.Add(self.titleSizer, proportion=1, flag=wx.EXPAND)
# Title
self.title = wx.TextCtrl(self,
size=(-1, 30 if sys.platform == 'darwin' else -1),
value="")
self.title.Bind(wx.EVT_TEXT, self.queueUpdate)
self.title.SetFont(
wx.Font(24, wx.FONTFAMILY_SWISS, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD)
)
self.titleSizer.Add(self.title, border=6, flag=wx.ALL | wx.EXPAND)
self.title.SetToolTip(_translate(
"Title of the project. Unlike the project name, this isn't used as a filename anywhere; so you can "
"add spaces, apostrophes and emojis to your heart's content! 🦕✨"
))
# Author
self.author = wx.StaticText(self, size=(-1, -1), label="by ---")
self.titleSizer.Add(self.author, border=6, flag=wx.LEFT | wx.RIGHT)
# Pavlovia link
self.link = wxhl.HyperLinkCtrl(self, -1,
label="https://pavlovia.org/",
URL="https://pavlovia.org/",
)
self.link.SetBackgroundColour("white")
self.titleSizer.Add(self.link, border=6, flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM)
self.link.SetToolTip(_translate(
"Click to view the project in Pavlovia."
))
# Button sizer
self.btnSizer = wx.BoxSizer(wx.HORIZONTAL)
self.titleSizer.Add(self.btnSizer, flag=wx.EXPAND)
# Star button
self.starLbl = wx.StaticText(self, label="-")
self.btnSizer.Add(self.starLbl, border=6, flag=wx.LEFT | wx.TOP | wx.BOTTOM | wx.ALIGN_CENTER_VERTICAL)
self.starBtn = self.StarBtn(self)
self.starBtn.Bind(wx.EVT_BUTTON, self.star)
self.btnSizer.Add(self.starBtn, border=6, flag=wx.ALL | wx.EXPAND)
self.starBtn.SetToolTip(_translate(
"'Star' this project to get back to it easily. Projects you've starred will appear first in your searches "
"and projects with more stars in total will appear higher in everyone's searches."
))
# Fork button
self.forkLbl = wx.StaticText(self, label="-")
self.btnSizer.Add(self.forkLbl, border=6, flag=wx.LEFT | wx.TOP | wx.BOTTOM | wx.ALIGN_CENTER_VERTICAL)
self.forkBtn = wx.Button(self, label=_translate("Fork"))
self.forkBtn.SetBitmap(icons.ButtonIcon(stem="fork", size=16, theme="light").bitmap)
self.forkBtn.Bind(wx.EVT_BUTTON, self.fork)
self.btnSizer.Add(self.forkBtn, border=6, flag=wx.ALL | wx.EXPAND)
self.forkBtn.SetToolTip(_translate(
"Create a copy of this project on your own Pavlovia account so that you can make changes without affecting "
"the original project."
))
# Create button
self.createBtn = wx.Button(self, label=_translate("Create"))
self.createBtn.SetBitmap(icons.ButtonIcon(stem="plus", size=16, theme="light").bitmap)
self.createBtn.Bind(wx.EVT_BUTTON, self.create)
self.btnSizer.Add(self.createBtn, border=6, flag=wx.RIGHT | wx.TOP | wx.BOTTOM | wx.ALIGN_CENTER_VERTICAL)
self.createBtn.SetToolTip(_translate(
"Create a Pavlovia project for the current experiment."
))
# Sync button
self.syncBtn = wx.Button(self, label=_translate("Sync"))
self.syncBtn.SetBitmap(icons.ButtonIcon(stem="view-refresh", size=16, theme="light").bitmap)
self.syncBtn.Bind(wx.EVT_BUTTON, self.sync)
self.btnSizer.Add(self.syncBtn, border=6, flag=wx.ALL | wx.EXPAND)
self.syncBtn.SetToolTip(_translate(
"Synchronise this project's local files with their online counterparts. This will 'pull' changes from "
"Pavlovia and 'push' changes from your local files."
))
# Get button
self.downloadBtn = wx.Button(self, label=_translate("Download"))
self.downloadBtn.SetBitmap(icons.ButtonIcon(stem="download", size=16, theme="light").bitmap)
self.downloadBtn.Bind(wx.EVT_BUTTON, self.sync)
self.btnSizer.Add(self.downloadBtn, border=6, flag=wx.ALL | wx.EXPAND)
self.downloadBtn.SetToolTip(_translate(
"'Clone' this project, creating local copies of all its files and tracking any changes you make so that "
"they can be applied when you next 'sync' the project."
))
# Sync label
self.syncLbl = wx.StaticText(self, size=(-1, -1), label="---")
self.btnSizer.Add(self.syncLbl, border=6, flag=wx.RIGHT | wx.TOP | wx.BOTTOM | wx.ALIGN_CENTER_VERTICAL)
self.syncLbl.SetToolTip(_translate(
"Last synced at..."
))
self.btnSizer.AddStretchSpacer(1)
# Sep
self.sizer.Add(wx.StaticLine(self, -1), border=6, flag=wx.EXPAND | wx.ALL)
# Local root
self.rootSizer = wx.BoxSizer(wx.HORIZONTAL)
self.sizer.Add(self.rootSizer, flag=wx.EXPAND)
self.localRootLabel = wx.StaticText(self, label="Local root:")
self.rootSizer.Add(self.localRootLabel, border=6, flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL)
self.localRoot = utils.FileCtrl(self, dlgtype="dir")
self.localRoot.Bind(wx.EVT_FILEPICKER_CHANGED, self.queueUpdate)
self.rootSizer.Add(self.localRoot, proportion=1, border=6, flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM)
self.localRoot.SetToolTip(_translate(
"Folder in which local files are stored for this project. Changes to files in this folder will be tracked "
"and applied to the project when you 'sync', so make sure the only files in this folder are relevant!"
))
# Sep
self.sizer.Add(wx.StaticLine(self, -1), border=6, flag=wx.EXPAND | wx.ALL)
# Description
self.description = utils.MarkdownCtrl(self, size=(-1, -1), value="", file=None)
self.description.Bind(wx.EVT_TEXT, self.queueUpdate)
self.sizer.Add(self.description, proportion=1, border=6, flag=wx.ALL | wx.EXPAND)
self.description.SetToolTip(_translate(
"Description of the project to be shown on Pavlovia. Note: This is different than a README file!"
))
# Sep
self.sizer.Add(wx.StaticLine(self, -1), border=6, flag=wx.EXPAND | wx.ALL)
# Visibility
self.visSizer = wx.BoxSizer(wx.HORIZONTAL)
self.sizer.Add(self.visSizer, flag=wx.EXPAND)
self.visLbl = wx.StaticText(self, label=_translate("Visibility:"))
self.visSizer.Add(self.visLbl, border=6, flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL)
self.visibility = wx.Choice(self, choices=["Private", "Public"])
self.visibility.Bind(wx.EVT_CHOICE, self.queueUpdate)
self.visSizer.Add(self.visibility, proportion=1, border=6, flag=wx.EXPAND | wx.ALL)
self.visibility.SetToolTip(_translate(
"Visibility of the current project; whether its visible only to its creator (Private) or to any user "
"(Public)."
))
# Status
self.statusSizer = wx.BoxSizer(wx.HORIZONTAL)
self.sizer.Add(self.statusSizer, flag=wx.EXPAND)
self.statusLbl = wx.StaticText(self, label=_translate("Status:"))
self.statusSizer.Add(self.statusLbl, border=6, flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL)
self.status = wx.Choice(self, choices=["Running", "Piloting", "Inactive"])
self.status.Bind(wx.EVT_CHOICE, self.queueUpdate)
self.statusSizer.Add(self.status, proportion=1, border=6, flag=wx.EXPAND | wx.ALL)
self.status.SetToolTip(_translate(
"Project status; whether it can be run to collect data (Running), run by its creator without saving "
"data (Piloting) or cannot be run (Inactive)."
))
# Tags
self.tagSizer = wx.BoxSizer(wx.HORIZONTAL)
self.sizer.Add(self.tagSizer, flag=wx.EXPAND)
self.tagLbl = wx.StaticText(self, label=_translate("Keywords:"))
self.tagSizer.Add(self.tagLbl, border=6, flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL)
self.tags = utils.ButtonArray(self, orient=wx.HORIZONTAL, items=[], itemAlias=_translate("tag"))
self.tags.Bind(wx.EVT_LIST_INSERT_ITEM, self.queueUpdate)
self.tags.Bind(wx.EVT_LIST_DELETE_ITEM, self.queueUpdate)
self.tagSizer.Add(self.tags, proportion=1, border=6, flag=wx.EXPAND | wx.ALL)
self.tags.SetToolTip(_translate(
"Keywords associated with this project, helping others to find it. For example, if your experiment is "
"useful to psychophysicists, you may want to add the keyword 'psychophysics'."
))
# Update button
self.updateBtn = wx.Button(self, label=_translate("Save"), style=wx.BU_EXACTFIT)
self.updateBtn.SetBitmap(icons.ButtonIcon(stem="savebtn", size=16, theme="light").bitmap)
self.sizer.Add(self.updateBtn, flag=wx.ALIGN_RIGHT | wx.ALL)
self.updateBtn.Bind(wx.EVT_BUTTON, self.doUpdate)
self.updateBtn.Disable()
# Populate
if project is not None:
project.refresh()
self.project = project
# Bind close function
self.Bind(wx.EVT_WINDOW_DESTROY, self.close)
@property
def project(self):
return self._project
@project.setter
def project(self, project):
self._project = project
# Populate fields
if project is None:
# Icon
self.icon.setImage(wx.Bitmap())
self.icon.SetBackgroundColour("#f2f2f2")
self.icon.Disable()
# Title
self.title.SetValue("")
self.title.Disable()
# Author
self.author.SetLabel("by --- on ---")
self.author.Disable()
# Link
self.link.SetLabel("---/---")
self.link.SetURL("https://pavlovia.org/")
self.link.Disable()
# Star button
self.starBtn.Disable()
self.starBtn.value = False
# Star label
self.starLbl.SetLabel("-")
self.starLbl.Disable()
# Fork button
self.forkBtn.Disable()
# Fork label
self.forkLbl.SetLabel("-")
self.forkLbl.Disable()
# Create button
self.createBtn.Show()
self.createBtn.Enable(bool(self.session.user))
# Sync button
self.syncBtn.Hide()
# Get button
self.downloadBtn.Hide()
# Sync label
self.syncLbl.SetLabel("---")
self.syncLbl.Disable()
# Local root
self.localRootLabel.Disable()
wx.TextCtrl.SetValue(self.localRoot, "") # use base method to avoid callback
self.localRoot.Disable()
# Description
self.description.setValue("")
self.description.Disable()
# Visibility
self.visibility.SetSelection(wx.NOT_FOUND)
self.visibility.Disable()
# Status
self.status.SetSelection(wx.NOT_FOUND)
self.status.Disable()
# Tags
self.tags.clear()
self.tags.Disable()
elif project.project is None:
# If project has been deleted, prompt to unlink
dlg = wx.MessageDialog(
self,
message=_translate(
"Could not find GitLab project with id {}.\n"
"\n"
"Please check that the project exists on Pavlovia, that you are logged in as the correct user in "
"the PsychoPy app, and that your account has access to the project."
).format(project.id),
style=wx.ICON_ERROR
)
dlg.ShowModal()
self.project = None
else:
# Refresh project to make sure it has info
if not hasattr(project, "_info"):
project.refresh()
# Icon
if 'avatarUrl' in project.info:
try:
content = self.session.session.get(project['avatar_url']).content
icon = io.BytesIO(content)
except requests.exceptions.MissingSchema:
icon = wx.Bitmap()
else:
icon = wx.Bitmap()
self.icon.setImage(icon)
self.icon.SetBackgroundColour("#f2f2f2")
self.icon.Enable(project.editable)
# Title
self.title.SetValue(project['name'])
self.title.Enable(project.editable)
# Author
self.author.SetLabel(f"by {project['path_with_namespace'].split('/')[0]} on {project['created_at']:%d %B %Y}")
self.author.Enable()
# Link
self.link.SetLabel(project['path_with_namespace'])
self.link.SetURL("https://pavlovia.org/" + project['path_with_namespace'])
self.link.Enable()
# Star button
self.starBtn.value = project.starred
self.starBtn.Enable(bool(project.session.user))
# Star label
self.starLbl.SetLabel(str(project['star_count']))
self.starLbl.Enable()
# Fork button
self.forkBtn.Enable(bool(project.session.user) and not project.owned)
# Fork label
self.forkLbl.SetLabel(str(project['forks_count']))
self.forkLbl.Enable()
# Create button
self.createBtn.Hide()
# Sync button
self.syncBtn.Show(bool(project.localRoot) or (not project.editable))
self.syncBtn.Enable(project.editable)
# Get button
self.downloadBtn.Show(not bool(project.localRoot) and project.editable)
self.downloadBtn.Enable(project.editable)
# Sync label
self.syncLbl.SetLabel(f"{project['last_activity_at']:%d %B %Y, %I:%M%p}")
self.syncLbl.Show(bool(project.localRoot) or (not project.editable))
self.syncLbl.Enable(project.editable)
# Local root
wx.TextCtrl.SetValue(self.localRoot, project.localRoot or "") # use base method to avoid callback
self.localRootLabel.Enable(project.editable)
self.localRoot.Enable(project.editable)
# Description
self.description.setValue(project['description'])
self.description.Enable(project.editable)
# Visibility
self.visibility.SetStringSelection(project['visibility'])
self.visibility.Enable(project.editable)
# Status
self.status.SetStringSelection(str(project['status2']).title())
self.status.Enable(project.editable)
# Tags
self.tags.items = project['keywords']
self.tags.Enable(project.editable)
# Layout
self.Layout()
# Clear update queue as we've just set from online
self._updateQueue = []
self.updateBtn.Disable()
@property
def session(self):
# Cache session if not cached
if not hasattr(self, "_session"):
self._session = pavlovia.getCurrentSession()
# Return cached session
return self._session
def create(self, evt=None):
"""
Create a new project
"""
dlg = sync.CreateDlg(self, user=self.session.user)
dlg.ShowModal()
self.project = dlg.project
def sync(self, evt=None):
# If not synced locally, choose a folder
if not self.localRoot.GetValue():
self.localRoot.browse()
# If cancelled, return
if not self.localRoot.GetValue():
return
self.project.localRoot = self.localRoot.GetValue()
# Enable ctrl now that there is a local root
self.localRoot.Enable()
self.localRootLabel.Enable()
# Get filename if available
if hasattr(self.GetTopLevelParent(), "filename"):
file = self.parent.filename
else:
file = ""
# Do sync
syncProject(self, self.project, file=file)
# Update project
self.project.refresh()
# Update last sync date & show
self.syncLbl.SetLabel(f"{self.project['last_activity_at']:%d %B %Y, %I:%M%p}")
self.syncLbl.Show()
self.syncLbl.Enable()
# Switch buttons to show Sync rather than Download/Create
self.createBtn.Hide()
self.downloadBtn.Hide()
self.syncBtn.Show()
self.syncBtn.Enable()
def fork(self, evt=None):
# Do fork
try:
proj = self.project.fork()
except gitlab.GitlabCreateError as e:
# If project already exists, ask user if they want to view it rather than create again
dlg = wx.MessageDialog(self, f"{e.error_message}\n\nOpen forked project?", style=wx.YES_NO)
if dlg.ShowModal() == wx.ID_YES:
# If yes, show forked project
projData = requests.get(
f"https://pavlovia.org/api/v2/experiments/{self.project.session.user['username']}/{self.project.info['pathWithNamespace'].split('/')[1]}"
).json()
self.project = PavloviaProject(projData['experiment']['gitlabId'])
return
else:
# If no, return
return
# Switch to new project
self.project = proj
# Sync
dlg = wx.MessageDialog(self, "Fork created! Sync it to a local folder?", style=wx.YES_NO)
if dlg.ShowModal() == wx.ID_YES:
self.sync()
def star(self, evt=None):
# Toggle button
self.starBtn.toggle()
# Star/unstar project
self.queueUpdate(evt)
# todo: Refresh stars count
def queueUpdate(self, evt=None):
# Skip if no project
if self.project is None or evt is None:
return
# Get object
obj = evt.GetEventObject()
# Mark object as needing update
if obj not in self._updateQueue:
self._updateQueue.append(obj)
# Enable update button
self.updateBtn.Enable()
def doUpdate(self, evt=None):
# Update each object in queue
success = []
for obj in self._updateQueue:
success.append(self.updateProject(obj))
# Disable update button
self.updateBtn.Enable(not all(success))
def updateProject(self, obj):
success = False
# Update project attribute according to supplying object
if obj == self.title and self.project.editable:
self.project['name'] = self.title.Value
success = self.project.save()
if obj == self.icon:
# Create temporary image file
_, temp = tempfile.mkstemp(suffix=".png")
self.icon.BitmapFull.SaveFile(temp, wx.BITMAP_TYPE_PNG)
# Load and upload from temp file
self.project['avatar'] = open(temp, "rb")
success = self.project.save()
# Delete temp file
#os.remove(temp)
if obj == self.starBtn:
self.project.starred = self.starBtn.value
self.starLbl.SetLabel(str(self.project.info['nbStars']))
success = True
if obj == self.localRoot:
if Path(self.localRoot.Value).is_dir():
self.project.localRoot = self.localRoot.Value
else:
dlg = wx.MessageDialog(self,
message=_translate(
"Could not find folder {directory}, please select a different "
"local root.".format(directory=self.localRoot.Value)
),
caption="Directory not found",
style=wx.ICON_ERROR)
self.localRoot.SetValue("")
self.project.localRoot = ""
dlg.ShowModal()
# Set project again to trigger a refresh
self.project = self.project
success = True
if obj == self.description and self.project.editable:
self.project['description'] = self.description.getValue()
success = self.project.save()
if obj == self.visibility and self.project.editable:
self.project['visibility'] = self.visibility.GetStringSelection().lower()
success = self.project.save()
if obj == self.status and self.project.editable:
retval = self.session.session.put(
f"https://pavlovia.org/api/v2/experiments/{self.project.id}",
json={'status2': self.status.GetStringSelection().upper()}
)
success = True
if obj == self.tags and self.project.editable:
retval = self.session.session.put(
f"https://pavlovia.org/api/v2/experiments/{self.project.id}",
json={"keywords": self.tags.GetValue()}
)
success = True
# Clear from update queue
if obj in self._updateQueue:
self._updateQueue.remove(obj)
return success
def close(self, evt=None):
if len(self._updateQueue):
wx.MessageDialog(self, message=_translate(
"Project info has changed, update online before closing?"
), style=wx.YES_NO | wx.CANCEL)
class ProjectFrame(wx.Dialog):
def __init__(self, app, parent=None, style=None,
pos=wx.DefaultPosition, project=None):
if style is None:
style = (wx.DEFAULT_DIALOG_STYLE | wx.CENTER |
wx.TAB_TRAVERSAL | wx.RESIZE_BORDER)
if project:
title = project['name']
else:
title = _translate("Project info")
self.frameType = 'ProjectInfo'
wx.Dialog.__init__(self, parent, -1, title=title, style=style,
size=(700, 500), pos=pos)
self.app = app
self.project = project
self.parent = parent
self.detailsPanel = DetailsPanel(parent=self, project=self.project)
self.mainSizer = wx.BoxSizer(wx.VERTICAL)
self.mainSizer.Add(self.detailsPanel, proportion=1, border=12, flag=wx.EXPAND | wx.ALL)
self.SetSizerAndFit(self.mainSizer)
if self.parent:
self.CenterOnParent()
self.Layout()
def syncProject(parent, project, file="", closeFrameWhenDone=False):
"""A function to sync the current project (if there is one)
Returns
-----------
1 for success
0 for fail
-1 for cancel at some point in the process
"""
# Error catch logged out
session = pavlovia.getCurrentSession()
if not session or not session.user:
# If not logged in, prompt to login
dlg = wx.MessageDialog(None, message=_translate(
"You are not logged in to Pavlovia. Please log in to sync project."
), style=wx.ICON_AUTH_NEEDED | wx.OK | wx.CANCEL)
dlg.SetOKLabel(_translate("Login..."))
if dlg.ShowModal() == wx.ID_OK:
# If they click Login, open login screen
user = functions.logInPavlovia(None)
# If they cancelled out of login screen, cancel sync
if not user:
return
else:
# If they cancel out of login prompt, cancel sync
return
# If not in a project, make one
if project is None:
# Try to get project id from git files
projName = pavlovia.getNameWithNamespace(file)
if projName is not None:
# If successful, make PavloviaProject from local info
project = PavloviaProject(projName, localRoot=file)
if project is None or project.project is None:
# If project is still None
msgDlg = wx.MessageDialog(parent,
message=_translate("This file doesn't belong to any existing project."),
style=wx.OK | wx.CANCEL | wx.CENTER)
msgDlg.SetOKLabel(_translate("Create a project"))
if msgDlg.ShowModal() == wx.ID_OK:
# Get start path and name from builder/coder if possible
if file:
file = Path(file)
name = file.stem
path = file.parent
else:
name = path = ""
# Open dlg to create new project
createDlg = sync.CreateDlg(parent,
user=pavlovia.getCurrentSession().user,
name=name,
path=path)
if createDlg.ShowModal() == wx.ID_OK and createDlg.project is not None:
project = createDlg.project
else:
return
else:
return
# If no local root or dead local root, prompt to make one
if not project.localRoot or not Path(project.localRoot).is_dir():
defaultRoot = Path(file).parent
# Handle missing or invalid local root
if not project.localRoot or not Path(project.localRoot).is_dir():
if file and defaultRoot.is_dir():
# If we have a reference to the current folder, use it
project.localRoot = defaultRoot
else:
# Otherwise, ask user to choose a local root
if not project.localRoot:
# If there is no local root at all, prompt user to make one
msg = _translate("Project root folder is not yet specified, specify project root now?")
else:
# If there is a local root but the folder is gone, prompt user to change it
msg = _translate("Project root folder does not exist, change project root now?")
dlg = wx.MessageDialog(parent, message=msg, style=wx.OK | wx.CANCEL)
# Get response
if dlg.ShowModal() == wx.ID_OK:
dlg = wx.DirDialog(parent, message=_translate("Specify folder..."), defaultPath=str(defaultRoot))
if dlg.ShowModal() == wx.ID_OK:
project.localRoot = str(dlg.GetPath())
else:
# If cancelled, cancel sync
return
else:
# If they don't want to specify, cancel sync
return
# Assign project to parent frame
parent.project = project
# If there is (now) a project, do sync
if project is not None:
# Commit changes
committed = functions.showCommitDialog(parent, project, initMsg="")
# Cancel sync if commit cancelled
if committed == -1:
pavlovia.getInfoStream().write(_translate(
"\n"
"Sync cancelled by user."
))
return
# If there's no user yet, login
if project.session.user is None:
functions.logInPavlovia(parent)
# Do sync
project.sync()
class ForkDlg(wx.Dialog):
"""Simple dialog to help choose the location/name of a forked project"""
# this dialog is working fine, but the API call to fork to a specific
# namespace doesn't appear to work
def __init__(self, project, *args, **kwargs):
wx.Dialog.__init__(self, *args, **kwargs)
existingName = project.name
session = pavlovia.getCurrentSession()
groups = [session.user['username']]
groups.extend(session.listUserGroups())
msg = wx.StaticText(self, label="Where shall we fork to?")
groupLbl = wx.StaticText(self, label="Group:")
self.groupField = wx.Choice(self, choices=groups)
nameLbl = wx.StaticText(self, label="Project name:")
self.nameField = wx.TextCtrl(self, value=project.name)
fieldsSizer = wx.FlexGridSizer(cols=2, rows=2, vgap=5, hgap=5)
fieldsSizer.AddMany([groupLbl, self.groupField,
nameLbl, self.nameField])
buttonSizer = wx.BoxSizer(wx.HORIZONTAL)
buttonSizer.Add(wx.Button(self, id=wx.ID_OK, label="OK"))
buttonSizer.Add(wx.Button(self, id=wx.ID_CANCEL, label="Cancel"))
mainSizer = wx.BoxSizer(wx.VERTICAL)
mainSizer.Add(msg, 1, wx.ALL, 5)
mainSizer.Add(fieldsSizer, 1, wx.ALL, 5)
mainSizer.Add(buttonSizer, 1, wx.ALL | wx.ALIGN_RIGHT, 5)
self.SetSizerAndFit(mainSizer)
self.Layout()
class ProjectRecreator(wx.Dialog):
"""Use this Dlg to handle the case of a missing (deleted?) remote project
"""
def __init__(self, project, parent, *args, **kwargs):
wx.Dialog.__init__(self, parent, *args, **kwargs)
self.parent = parent
self.project = project
existingName = project.name
msgText = _translate("points to a remote that doesn't exist (deleted?).")
msgText += (" "+_translate("What shall we do?"))
msg = wx.StaticText(self, label="{} {}".format(existingName, msgText))
choices = [_translate("(Re)create a project"),
"{} ({})".format(_translate("Point to an different location"),
_translate("not yet supported")),
_translate("Forget the local git repository (deletes history keeps files)")]
self.radioCtrl = wx.RadioBox(self, label='RadioBox', choices=choices,
majorDimension=1)
self.radioCtrl.EnableItem(1, False)
self.radioCtrl.EnableItem(2, False)
mainSizer = wx.BoxSizer(wx.VERTICAL)
buttonSizer = wx.BoxSizer(wx.HORIZONTAL)
buttonSizer.Add(wx.Button(self, id=wx.ID_OK, label=_translate("OK")),
1, wx.ALL, 5)
buttonSizer.Add(wx.Button(self, id=wx.ID_CANCEL, label=_translate("Cancel")),
1, wx.ALL, 5)
mainSizer.Add(msg, 1, wx.ALL, 5)
mainSizer.Add(self.radioCtrl, 1, wx.ALL | wx.ALIGN_CENTER_HORIZONTAL, 5)
mainSizer.Add(buttonSizer, 1, wx.ALL | wx.ALIGN_RIGHT, 1)
self.SetSizer(mainSizer)
self.Layout()
def ShowModal(self):
if wx.Dialog.ShowModal(self) == wx.ID_OK:
choice = self.radioCtrl.GetSelection()
if choice == 0:
editor = ProjectEditor(parent=self.parent,
localRoot=self.project.localRoot)
if editor.ShowModal() == wx.ID_OK:
self.project = editor.project
return 1 # success!
else:
return -1 # user cancelled
elif choice == 1:
raise NotImplementedError("We don't yet support redirecting "
"your project to a new location.")
elif choice == 2:
raise NotImplementedError("Deleting the local git repo is not "
"yet implemented")
else:
return -1
| 40,868
|
Python
|
.py
| 870
| 34.942529
| 157
| 0.589756
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,818
|
sync.py
|
psychopy_psychopy/psychopy/app/pavlovia_ui/sync.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Part of the PsychoPy library
# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd.
# Distributed under the terms of the GNU General Public License (GPL).
import sys
import wx
from .. import utils
from . import functions
import re
from pathlib import Path
from psychopy.localization import _translate
from ...tools.stringtools import valid_proj_name
class InfoStream(wx.TextCtrl):
def __init__(self, parent, id, size,
value="Synchronising...",
style=wx.TE_READONLY | wx.TE_MULTILINE):
wx.TextCtrl.__init__(self, parent, id,
size=size, value=value, style=style)
def clear(self):
self.SetValue("")
def write(self, text):
if type(text) == bytes:
text = text.decode('utf-8')
# Sanitize text (remove sensitive info like oauth keys)
text = utils.sanitize(text)
# Show
self.SetValue(self.GetValue() + text)
wx.Yield()
class CreateDlg(wx.Dialog):
# List of folders which are invalid paths for a pavlovia project
invalidFolders = [Path.home() / 'Desktop',
Path.home() / 'My Documents',
Path.home() / 'Documents']
def __init__(self, parent, user, name="", path=""):
wx.Dialog.__init__(self, parent=parent,
title=_translate("New project..."),
size=(500, 200), style=wx.DEFAULT_DIALOG_STYLE | wx.CLOSE_BOX)
# If there's no user yet, login
if user is None:
user = functions.logInPavlovia(self)
self.user = user
self.session = parent.session
self.project = None
# Setup sizer
self.frame = wx.BoxSizer(wx.VERTICAL)
self.SetSizer(self.frame)
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.frame.Add(self.sizer, border=6, proportion=1, flag=wx.ALL | wx.EXPAND)
# Name label
self.nameLbl = wx.StaticText(self, label=_translate("Project name:"))
self.sizer.Add(self.nameLbl, border=3, flag=wx.ALL | wx.EXPAND)
# Name ctrls
self.nameSizer = wx.BoxSizer(wx.HORIZONTAL)
self.sizer.Add(self.nameSizer, border=3, flag=wx.ALL | wx.EXPAND)
# URL prefix
self.nameRootLbl = wx.StaticText(self, label="pavlovia.org /")
self.nameSizer.Add(self.nameRootLbl, border=3, flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL)
# Namespace ctrl
self.namespaceCtrl = wx.Choice(self, choices=[user['username']] + user.session.listUserGroups(namesOnly=True))
self.namespaceCtrl.SetStringSelection(user['username'])
self.nameSizer.Add(self.namespaceCtrl, border=3, flag=wx.ALL | wx.EXPAND)
# Slash
self.slashLbl = wx.StaticText(self, label="/")
self.nameSizer.Add(self.slashLbl, border=3, flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL)
# Name ctrl
self.nameCtrl = wx.TextCtrl(self, value=str(name))
self.nameCtrl.Bind(wx.EVT_TEXT, self.validate)
self.nameSizer.Add(self.nameCtrl, border=3, proportion=1, flag=wx.ALL | wx.EXPAND)
# Local root label
self.rootLbl = wx.StaticText(self, label=_translate("Project folder:"))
self.sizer.Add(self.rootLbl, border=3, flag=wx.ALL | wx.EXPAND)
# Local root ctrl
self.rootCtrl = utils.FileCtrl(self, value=str(path), dlgtype="dir")
self.rootCtrl.Bind(wx.EVT_FILEPICKER_CHANGED, self.validate)
self.sizer.Add(self.rootCtrl, border=3, flag=wx.ALL | wx.EXPAND)
# Add dlg buttons
self.sizer.AddStretchSpacer(1)
self.btnSizer = wx.BoxSizer(wx.HORIZONTAL)
self.sizer.Add(self.btnSizer, border=3, flag=wx.ALL | wx.EXPAND)
self.btnSizer.AddStretchSpacer(1)
# OK button
self.OKbtn = wx.Button(self, id=wx.ID_OK, label=_translate("OK"))
self.OKbtn.Bind(wx.EVT_BUTTON, self.submit)
# CANCEL button
self.CANCELbtn = wx.Button(self, id=wx.ID_CANCEL, label=_translate("Cancel"))
# Add dlg buttons in OS appropriate order
if sys.platform == "win32":
btns = [self.OKbtn, self.CANCELbtn]
else:
btns = [self.CANCELbtn, self.OKbtn]
self.btnSizer.Add(btns[0], border=3, flag=wx.ALL)
self.btnSizer.Add(btns[1], border=3, flag=wx.ALL)
self.Layout()
self.validate()
def validate(self, evt=None):
# Test name
name = self.nameCtrl.GetValue()
nameValid = bool(valid_proj_name.fullmatch(name))
# Test path
path = Path(self.rootCtrl.GetValue())
pathValid = path.is_dir() and path not in self.invalidFolders
# Combine
valid = nameValid and pathValid
# Enable/disable Okay button
self.OKbtn.Enable(valid)
return valid
def submit(self, evt=None):
self.project = self.session.createProject(**self.GetValue())
if self.project is not None:
self.project.refresh()
evt.Skip()
def GetValue(self):
return {
"name": self.nameCtrl.GetValue(),
"localRoot": self.rootCtrl.GetValue(),
"namespace": self.namespaceCtrl.GetStringSelection()
}
| 5,290
|
Python
|
.py
| 118
| 35.805085
| 118
| 0.626892
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,819
|
user.py
|
psychopy_psychopy/psychopy/app/pavlovia_ui/user.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Part of the PsychoPy library
# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd.
# Distributed under the terms of the GNU General Public License (GPL).
import tempfile
from . import PavloviaMiniBrowser
from .functions import logInPavlovia, logOutPavlovia
from psychopy.localization import _translate
from psychopy.projects import pavlovia
from psychopy.app import utils
import requests
import io
from psychopy import prefs
import os
import wx
import wx.lib.statbmp
from ..themes import icons
from ...projects.pavlovia import User
try:
import wx.lib.agw.hyperlink as wxhl # 4.0+
except ImportError:
import wx.lib.hyperlink as wxhl # <3.0.2
class UserFrame(wx.Dialog):
def __init__(self, parent,
style=wx.DEFAULT_DIALOG_STYLE | wx.CENTER | wx.TAB_TRAVERSAL | wx.RESIZE_BORDER,
size=(-1, -1)):
wx.Dialog.__init__(self, parent,
style=style,
size=size)
self.app = parent.app
self.sizer = wx.BoxSizer()
self.sizer.Add(UserPanel(self), proportion=1, border=12, flag=wx.ALL | wx.EXPAND)
self.SetSizerAndFit(self.sizer)
class UserPanel(wx.Panel):
def __init__(self, parent,
size=(600, 300),
style=wx.NO_BORDER):
wx.Panel.__init__(self, parent, -1,
size=size,
style=style)
self.parent = parent
self.SetBackgroundColour("white")
self.session = pavlovia.getCurrentSession()
# Setup sizer
self.contentBox = wx.BoxSizer()
self.SetSizer(self.contentBox)
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.contentBox.Add(self.sizer, proportion=1, border=12, flag=wx.ALL | wx.EXPAND)
# Head sizer
self.headSizer = wx.BoxSizer(wx.HORIZONTAL)
self.sizer.Add(self.headSizer, border=0, flag=wx.EXPAND)
# Icon
self.icon = wx.lib.statbmp.GenStaticBitmap(
self, ID=wx.ID_ANY,
bitmap=icons.ButtonIcon(stem="user_none", size=128, theme="light").bitmap,
size=(128, 128))
self.icon.SetBackgroundColour("#f2f2f2")
self.headSizer.Add(self.icon, border=6, flag=wx.ALL)
# Title sizer
self.titleSizer = wx.BoxSizer(wx.VERTICAL)
self.headSizer.Add(self.titleSizer, proportion=1, flag=wx.EXPAND)
# Full name
self.fullName = wx.StaticText(self, size=(-1, -1), label="---", style=wx.ST_ELLIPSIZE_END)
self.fullName.SetFont(
wx.Font(24, wx.FONTFAMILY_SWISS, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD)
)
self.fullName.Bind(wx.EVT_TEXT, self.updateUser)
self.titleSizer.Add(self.fullName, border=6, flag=wx.ALL | wx.EXPAND)
# Organisation
self.organisation = wx.StaticText(self, size=(-1, -1), label="---", style=wx.ST_ELLIPSIZE_END)
self.organisation.SetFont(
wx.Font(12, wx.FONTFAMILY_SWISS, wx.FONTSTYLE_ITALIC, wx.FONTWEIGHT_NORMAL)
)
self.titleSizer.Add(self.organisation, border=6, flag=wx.ALL | wx.EXPAND)
# Spacer
self.titleSizer.AddStretchSpacer(1)
# Button sizer
self.btnSizer = wx.BoxSizer(wx.HORIZONTAL)
self.titleSizer.Add(self.btnSizer, border=6, flag=wx.TOP | wx.BOTTOM | wx.EXPAND)
# Spacer
self.btnSizer.AddStretchSpacer(1)
# Pavlovia link
self.link = wxhl.HyperLinkCtrl(self, -1,
label="",
URL="https://gitlab.pavlovia.org/",
)
self.link.SetBackgroundColour(self.GetBackgroundColour())
self.btnSizer.Add(self.link, border=6, flag=wx.RIGHT | wx.ALIGN_CENTER_VERTICAL)
# Edit
self.edit = wx.Button(self, label=chr(int("270E", 16)), size=(24, -1))
self.edit.Bind(wx.EVT_BUTTON, self.onEdit)
self.btnSizer.Add(self.edit, border=3, flag=wx.LEFT | wx.RIGHT | wx.ALIGN_CENTER_VERTICAL)
# Switch user
self.switch = wx.Button(self, label=_translate("Switch User"))
self.switch.SetBitmap(icons.ButtonIcon(stem="view-refresh", size=16, theme="light").bitmap)
self.switch.Bind(wx.EVT_BUTTON, self.onSwitchUser)
self.btnSizer.Add(self.switch, border=3, flag=wx.LEFT | wx.RIGHT | wx.ALIGN_CENTER_VERTICAL)
# Login
self.login = wx.Button(self, label=_translate("Login"))
self.login.SetBitmap(icons.ButtonIcon(stem="person_off", size=16, theme="light").bitmap)
self.login.Bind(wx.EVT_BUTTON, self.onLogin)
self.btnSizer.Add(self.login, border=3, flag=wx.LEFT | wx.EXPAND)
# Logout
self.logout = wx.Button(self, label=_translate("Logout"))
self.logout.SetBitmap(icons.ButtonIcon(stem="person_off", size=16, theme="light").bitmap)
self.logout.Bind(wx.EVT_BUTTON, self.onLogout)
self.btnSizer.Add(self.logout, border=3, flag=wx.LEFT | wx.EXPAND)
# Sep
self.sizer.Add(wx.StaticLine(self, -1), border=6, flag=wx.EXPAND | wx.ALL)
# Bio
self.description = wx.StaticText(self, size=(-1, -1), label="", style=wx.TE_MULTILINE)
self.sizer.Add(self.description, proportion=1, border=6, flag=wx.ALL | wx.EXPAND)
# Populate
self.user = self.user
@property
def user(self):
if not hasattr(self, "_user"):
self._user = self.session.user
return self._user
@user.setter
def user(self, user):
self._user = user
if user is None:
# Icon
self.icon.SetBitmap(icons.ButtonIcon(stem="user_none", size=128, theme="light").bitmap)
self.icon.Disable()
# Full name
self.fullName.SetLabelText("---")
self.fullName.Disable()
# Organisation
self.organisation.SetLabelText("---")
self.organisation.Disable()
# Link
self.link.SetLabel("")
self.link.SetURL("https://pavlovia.org/")
self.link.Disable()
# Hide logout/switch and show login
self.logout.Hide()
self.switch.Hide()
self.login.Show()
# Disable edit
self.edit.Disable()
# Description
self.description.SetLabelText("")
self.description.Disable()
else:
try:
content = requests.get(user['avatar_url']).content
buffer = wx.Image(io.BytesIO(content))
buffer = buffer.Scale(*self.icon.Size, quality=wx.IMAGE_QUALITY_HIGH)
icon = wx.Bitmap(buffer)
except requests.exceptions.MissingSchema:
icon = wx.Bitmap()
self.icon.SetBitmap(icon)
self.icon.Enable()
# Full name
self.fullName.SetLabelText(user.user.attributes['name'] or "")
self.fullName.Enable()
# Organisation
self.organisation.SetLabelText(user['organization'] or "No organization")
self.organisation.Enable()
# Link
self.link.SetLabel(user['username'])
self.link.SetURL(user['web_url'] or "")
self.link.Enable()
# Hide login and show logout/switch
self.logout.Show()
self.switch.Show()
self.login.Hide()
# Enable edit
self.edit.Enable()
# Description
self.description.SetLabelText(user['bio'] or "")
self.description.Wrap(self.Size[0] - 36)
self.description.Enable()
self.Layout()
def onLogout(self, evt=None):
self.user = logOutPavlovia(self.parent)
def onLogin(self, evt=None):
self.user = logInPavlovia(parent=self.parent)
def onEdit(self, evt=None):
# Open edit window
dlg = PavloviaMiniBrowser(parent=self, loginOnly=False)
dlg.editUserPage()
dlg.ShowModal()
# Refresh user on close
self.user = User(self.user.id)
def onSwitchUser(self, evt):
def onSelectUser(evt):
# Get user from menu
id = evt.Id
menu = evt.EventObject
user = menu.users[id]
# Logout
pavlovia.logout()
# Log back in as new user
pavlovia.login(user['username'])
# Update view
self.user = pavlovia.getCurrentSession().user
# Update cache
prefs.appData['projects']['pavloviaUser'] = user['username']
self.Layout() # update the size of the button
self.Fit()
menu = wx.Menu()
menu.Bind(wx.EVT_MENU, onSelectUser)
menu.users = {}
for key, value in pavlovia.knownUsers.items():
item = menu.Append(id=wx.ID_ANY, item=key)
menu.users[item.GetId()] = value
# Get button position
btnPos = self.switch.GetRect()
menuPos = (btnPos[0], btnPos[1] + btnPos[3])
# Popup menu
self.PopupMenu(menu, menuPos)
def updateUser(self, evt=None):
"""
Disabled for now, as fields are not editable.
"""
# Skip if no user
if self.user is None or evt is None or self.session.user is None:
return
# Get object
obj = evt.GetEventObject()
# Update full name
if obj == self.fullName:
self.user.name = self.fullName.GetValue()
#self.user.save()
# Update organisation
if obj == self.organisation:
self.user.organization = self.organisation.GetValue()
#self.user.save()
# Update bio
if obj == self.description:
self.user.bio = self.description.GetValue()
#self.user.save()
# Update avatar
if obj == self.icon:
# Create temporary image file
_, temp = tempfile.mkstemp(suffix=".png")
self.icon.BitmapFull.SaveFile(temp, wx.BITMAP_TYPE_PNG)
# Load and upload from temp file
self.user.avatar = open(temp, "rb")
#self.user.save()
| 10,269
|
Python
|
.py
| 244
| 31.647541
| 102
| 0.594503
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,820
|
search.py
|
psychopy_psychopy/psychopy/app/pavlovia_ui/search.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Part of the PsychoPy library
# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd.
# Distributed under the terms of the GNU General Public License (GPL).
from .project import DetailsPanel
from .functions import logInPavlovia
from ._base import BaseFrame
from psychopy.localization import _translate
from psychopy.projects import pavlovia
import copy
import wx
from wx.lib import scrolledpanel as scrlpanel
import wx.lib.mixins.listctrl as listmixin
import requests
from .. import utils
from ..themes import icons
_starred = u"\u2605"
_unstarred = u"\u2606"
_fork = u"\u2442"
class ListCtrl(wx.ListCtrl, listmixin.ListCtrlAutoWidthMixin):
"""
A ListCtrl with ListCtrlAutoWidthMixin already mixed in, purely for convenience
"""
def __init__(self, *args, **kwargs):
wx.ListCtrl.__init__(self, *args, **kwargs)
listmixin.ListCtrlAutoWidthMixin.__init__(self)
class SearchFrame(wx.Dialog):
def __init__(self, app, parent=None, style=wx.RESIZE_BORDER | wx.DEFAULT_DIALOG_STYLE | wx.CENTER | wx.TAB_TRAVERSAL | wx.NO_BORDER,
pos=wx.DefaultPosition):
self.frameType = 'ProjectSearch'
wx.Dialog.__init__(self, parent, -1, title=_translate("Search for projects online"),
style=style,
size=(1080, 720), pos=pos)
self.app = app
self.SetMinSize((980, 520))
# Setup sizer
self.sizer = wx.BoxSizer(wx.HORIZONTAL)
self.SetSizer(self.sizer)
# Make panels
self.detailsPanel = DetailsPanel(self)
self.searchPanel = SearchPanel(self, viewer=self.detailsPanel)
# Add to sizers
self.sizer.Add(self.searchPanel, border=12, flag=wx.EXPAND | wx.ALL)
self.sizer.Add(self.detailsPanel, proportion=1, border=12, flag=wx.EXPAND | wx.ALL)
# Layout
self.Layout()
class SearchPanel(wx.Panel):
"""A scrollable panel showing a list of projects. To be used within the
Project Search dialog
"""
class FilterLabel(wx.StaticText):
"""
A label to show what filters and sorting are applied to the current search
"""
def update(self):
# Get parent object
parent = self.GetParent()
# Add me mode
mineLbl = ""
if parent._mine:
mineLbl += "Editable by me. "
# Add sort params
sortLbl = ""
if len(parent.sortOrder):
sortLbl += "Sort by: "
sortLbl += " then ".join([item.label.lower() for item in parent.sortOrder])
sortLbl += ". "
# Add filter params
filterLbl = ""
for key, values in parent.filterTerms.items():
if values:
if isinstance(values, str):
values = [values]
filterLbl += f"{key}: "
filterLbl += " or ".join(values)
filterLbl += ". "
# Construct full label
label = mineLbl + sortLbl + filterLbl
# Apply label
self.SetLabel(label)
# Show or hide self according to label
self.Show(bool(label))
parent.Layout()
def hoverOn(self, evt=None):
self.Wrap(self.GetParent().GetSize()[0] - 12)
self.GetParent().Layout()
def hoverOff(self, evt=None):
self.SetLabel(self.GetLabel().replace("\n", " "))
self.GetParent().Layout()
def __init__(self, parent, viewer,
size=(400, -1),
style=wx.NO_BORDER
):
# Init self
wx.Panel.__init__(self, parent, -1,
size=size,
style=style
)
self.session = pavlovia.getCurrentSession()
# Setup sizer
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.SetSizer(self.sizer)
# Add search ctrl
self.searchCtrl = wx.SearchCtrl(self)
self.searchCtrl.Bind(wx.EVT_SEARCH, self.search)
self.sizer.Add(self.searchCtrl, border=4, flag=wx.EXPAND | wx.ALL)
# Add button sizer
self.btnSizer = wx.BoxSizer(wx.HORIZONTAL)
self.sizer.Add(self.btnSizer, border=4, flag=wx.EXPAND | wx.ALL)
# Add "me mode" button
self.mineBtn = wx.ToggleButton(self, size=(64, -1), label=_translate("Me"))
self.mineBtn.SetBitmap(icons.ButtonIcon(stem="person_off", size=16, theme="light").bitmap)
self.mineBtn.SetBitmapFocus(icons.ButtonIcon(stem="person_on", size=16, theme="light").bitmap)
self.mineBtn.SetBitmapPressed(icons.ButtonIcon(stem="person_on", size=16, theme="light").bitmap)
self._mine = False
self.mineBtn.Bind(wx.EVT_TOGGLEBUTTON, self.onMineBtn)
self.mineBtn.Enable(self.session.userID is not None)
self.btnSizer.Add(self.mineBtn, border=6, flag=wx.EXPAND | wx.RIGHT | wx.TOP | wx.BOTTOM)
self.btnSizer.AddStretchSpacer(1)
# Add sort button
self.sortBtn = wx.Button(self, label=_translate("Sort..."))
self.sortOrder = []
self.sortBtn.Bind(wx.EVT_BUTTON, self.sort)
self.btnSizer.Add(self.sortBtn, border=6, flag=wx.LEFT | wx.RIGHT | wx.TOP | wx.BOTTOM)
# Add filter button
self.filterBtn = wx.Button(self, label=_translate("Filter..."))
self.filterTerms = {
"Status": [],
"Platform": [],
"Keywords": [],
}
self.filterOptions = {
"Author": None,
"Status": ["running", "piloting", "inactive"],
"Platform": ["psychojs", "jspsych", "labjs", "opensesame", "other"],
"Visibility": ["public", "private"],
"Keywords": None,
}
self.filterBtn.Bind(wx.EVT_BUTTON, self.filter)
self.btnSizer.Add(self.filterBtn, border=6, flag=wx.LEFT | wx.TOP | wx.BOTTOM)
# Add filter label
self.filterLbl = self.FilterLabel(self, style=wx.ST_ELLIPSIZE_END)
self.filterLbl.Bind(wx.EVT_ENTER_WINDOW, self.filterLbl.hoverOn)
self.filterLbl.Bind(wx.EVT_LEAVE_WINDOW, self.filterLbl.hoverOff)
self.sizer.Add(self.filterLbl, border=6, flag=wx.LEFT | wx.RIGHT)
self.filterLbl.update()
# Add project list
self.projectList = ListCtrl(self, size=(-1, -1), style=wx.LC_REPORT | wx.LC_SINGLE_SEL)
self.projectList.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.showProject)
self.sizer.Add(self.projectList, proportion=1, border=4, flag=wx.EXPAND | wx.ALL)
# Setup project list
self.projectList.InsertColumn(0, _starred, width=36, format=wx.LIST_FORMAT_CENTER) # Stars
#self.projectList.InsertColumn(1, _translate('Status'), width=wx.LIST_AUTOSIZE, format=wx.LIST_FORMAT_LEFT) # Status
self.projectList.InsertColumn(2, _translate('Author'), width=wx.LIST_AUTOSIZE, format=wx.LIST_FORMAT_LEFT) # Author
self.projectList.InsertColumn(3, _translate('Name'), width=wx.LIST_AUTOSIZE, format=wx.LIST_FORMAT_LEFT) # Name
# Setup projects dict
self.projects = None
# Link ProjectViewer
self.viewer = viewer
self.projectList.Bind(wx.EVT_LIST_ITEM_SELECTED, self.showProject)
# Layout
self.Layout()
# Initial search
self.search()
def search(self, evt=None):
# Get search term
if evt is None:
term = self.searchCtrl.GetValue()
elif isinstance(evt, str):
term = evt
else:
term = evt.GetString()
# Do search
self.projects = pavlovia.PavloviaSearch(term=term, filterBy=self.filterTerms, mine=self._mine)
# Sort values
if len(self.projects):
self.projects.sort_values(self.sortOrder)
# Refresh
self.refreshCtrl()
def refreshCtrl(self):
# Clear list and projects dict
self.projectList.DeleteAllItems()
# Skip if not searched yet
if self.projects is None:
return
# Skip if empty search
if len(self.projects) == 0:
return
# Populate list and projects dict
for i, _ in self.projects.iterrows():
i = self.projectList.Append([
self.projects['nbStars'][i],
#self.projects['status'][i],
self.projects['pathWithNamespace'][i].split('/')[0],
self.projects['name'][i],
])
def sort(self, evt=None):
# Create temporary arrays
items = copy.deepcopy(self.sortOrder)
selected = []
# Append missing items to copy
for item in pavlovia.PavloviaSearch.sortTerms:
if item in self.sortOrder:
selected.append(True)
else:
items.append(copy.deepcopy(item))
selected.append(False)
# Create dlg
_dlg = SortDlg(self, items=items, selected=selected)
if _dlg.ShowModal() != wx.ID_OK:
return
# Update sort order
self.sortOrder = _dlg.ctrls.GetValue()
# Sort
if self.projects is not None:
self.projects.sort_values(self.sortOrder)
# Refresh
self.refreshCtrl()
self.filterLbl.update()
def filter(self, evt=None):
# Open filter dlg
_dlg = FilterDlg(self,
terms=self.filterTerms,
options=self.filterOptions)
# Skip if cancelled
if _dlg.ShowModal() != wx.ID_OK:
return
# Update filters if Okayed
self.filterTerms = _dlg.GetValue()
# Update filter label
self.filterLbl.update()
# Re-search
self.search()
def showProject(self, evt=None):
"""
View current project in associated viewer
"""
if self.projects is not None:
proj = self.projects.iloc[self.projectList.GetFocusedItem()]
# Set project to None while waiting
self.viewer.project = None
# Set project
self.viewer.project = pavlovia.PavloviaProject(proj)
def onMineBtn(self, evt=None):
# If triggered manually with a bool, do setting
if isinstance(evt, bool):
self.mineBtn.Value = evt
# Apply "mine" filter
self._mine = self.mineBtn.Value
# Clear and disable filters & search todo: This is a stop gap, remove once the Pavlovia API can accept searches and filters WITHIN a designer
self.filterBtn.Enable(not self._mine)
self.searchCtrl.Enable(not self._mine)
if self._mine:
self.filterTerms = {key: [] for key in self.filterTerms}
self.searchCtrl.Value = ""
# Update
self.filterLbl.update()
self.search()
class SortDlg(wx.Dialog):
def __init__(self, parent, size=(200, 400),
items=pavlovia.PavloviaSearch.sortTerms,
selected=False):
wx.Dialog.__init__(self, parent, size=size, title="Sort by...", style=wx.DEFAULT_DIALOG_STYLE | wx.DIALOG_NO_PARENT)
# Setup sizer
self.contentBox = wx.BoxSizer(wx.VERTICAL)
self.SetSizer(self.contentBox)
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.contentBox.Add(self.sizer, proportion=1, border=0, flag=wx.EXPAND | wx.ALL)
# Create rearrange control
self.ctrls = utils.SortCtrl(self,
items=items,
showFlip=True,
showSelect=True, selected=selected)
self.sizer.Add(self.ctrls, border=6, flag=wx.EXPAND | wx.ALL)
# Add Okay button
self.sizer.AddStretchSpacer(1)
self.OkayBtn = wx.Button(self, id=wx.ID_OK, label="Okay")
self.contentBox.Add(self.OkayBtn, border=6, flag=wx.ALL | wx.ALIGN_RIGHT)
# Bind cancel
self.Bind(wx.EVT_CLOSE, self.onCancel)
def onCancel(self, evt=None):
self.EndModal(wx.ID_CANCEL)
class FilterDlg(wx.Dialog):
class KeyCtrl(wx.Window):
def __init__(self, parent,
key, value,
options=None,
selected=True):
# Init self
wx.Window.__init__(self, parent, size=(-1, -1))
self.SetBackgroundColour(parent.GetBackgroundColour())
# Create master sizer
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.SetSizer(self.sizer)
# Create title sizer
self.titleSizer = wx.BoxSizer(wx.HORIZONTAL)
self.sizer.Add(self.titleSizer, border=0, flag=wx.ALL | wx.EXPAND)
# Add tickbox
self.selectCtrl = wx.CheckBox(self)
self.selectCtrl.Bind(wx.EVT_CHECKBOX, self.onSelect)
self.selectCtrl.SetValue(selected)
self.titleSizer.Add(self.selectCtrl, border=6, flag=wx.ALL | wx.EXPAND)
# Add label
self.key = key
self.label = wx.StaticText(self, label=f"{key}:")
self.titleSizer.Add(self.label, proportion=1, border=6, flag=wx.ALL | wx.EXPAND | wx.TEXT_ALIGNMENT_LEFT)
# Add ctrl
if options is None:
self.ctrl = wx.TextCtrl(self, value=",".join(value))
else:
self.ctrl = wx.CheckListBox(self, choices=options)
self.ctrl.SetCheckedStrings(value)
self.sizer.Add(self.ctrl, border=6, flag=wx.LEFT | wx.RIGHT | wx.EXPAND)
# Layout
self.Layout()
# Enable
self.Enable(selected)
@property
def selected(self):
return self.selectCtrl.Value
@selected.setter
def selected(self, value):
self.selectCtrl.Value = value
def onSelect(self, evt=None):
self.Enable(self.selected)
def Enable(self, enable=True):
# Select button always enabled
self.selectCtrl.Enable(True)
# Enable/disable children
self.label.Enable(enable)
self.ctrl.Enable(enable)
if not enable and isinstance(self.ctrl, wx.CheckListBox):
# If disabled, every option should be checked and none selected
self.ctrl.SetCheckedStrings(self.ctrl.GetStrings())
self.ctrl.SetSelection(-1)
def Disable(self):
self.Enable(False)
def GetValue(self):
# If deselected, return blank
if not self.selected:
return []
# Otherwise, get ctrl value
if isinstance(self.ctrl, wx.CheckListBox):
# List of checked strings for check lists
return self.ctrl.GetCheckedStrings()
else:
# String split by commas for text ctrl
if self.ctrl.GetValue():
return self.ctrl.GetValue().split(",")
else:
# Substitute [''] for [] so it's booleanised to False
return []
def __init__(self, parent, size=(250, 400),
terms={},
options={}):
wx.Dialog.__init__(self, parent, size=size,
title="Filter by...", style=wx.DEFAULT_DIALOG_STYLE | wx.DIALOG_NO_PARENT)
# Setup sizer
self.contentBox = wx.BoxSizer(wx.VERTICAL)
self.SetSizer(self.contentBox)
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.contentBox.Add(self.sizer, proportion=1, border=0, flag=wx.EXPAND | wx.ALL)
# Add dict ctrl
self.ctrls = {}
for key in terms:
self.ctrls[key] = self.KeyCtrl(self, key,
terms[key], selected=bool(terms[key]),
options=options[key])
self.sizer.Add(self.ctrls[key], border=6, flag=wx.EXPAND | wx.ALL)
# Add Okay button
self.sizer.AddStretchSpacer(1)
self.OkayBtn = wx.Button(self, id=wx.ID_OK, label=_translate("OK"))
self.contentBox.Add(self.OkayBtn, border=6, flag=wx.ALL | wx.ALIGN_RIGHT)
# Bind cancel
self.Bind(wx.EVT_CLOSE, self.onCancel)
def onCancel(self, evt=None):
self.EndModal(wx.ID_CANCEL)
def GetValue(self):
# Create blank dict
value = {}
# Update dict keys with value from each ctrl
for key, ctrl in self.ctrls.items():
value[key] = ctrl.GetValue()
return value
def sortProjects(seq, name, reverse=False):
return sorted(seq, key=lambda k: k[name], reverse=reverse)
def getUniqueByID(seq):
"""Very fast function to remove duplicates from a list while preserving order
Based on sort f8() by Dave Kirby
benchmarked at https://www.peterbe.com/plog/uniqifiers-benchmark
Requires Python>=2.7 (requires set())
"""
# Order preserving
seen = set()
return [x for x in seq if x.id not in seen and not seen.add(x.id)]
| 17,177
|
Python
|
.py
| 396
| 32.381313
| 149
| 0.589613
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,821
|
__init__.py
|
psychopy_psychopy/psychopy/app/pavlovia_ui/__init__.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Part of the PsychoPy library
# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd.
# Distributed under the terms of the GNU General Public License (GPL).
# DONE: add+commit before push
# DONE: add .gitignore file. Added when opening a repo without one
# DONE: fork+sync doesn't yet fork the project first
# DONE: rather than clone into a folder with files we should init/add/push
#
# TODO: after clone, remember this folder for next file-open call
# TODO: user dlg could/should be local not a browser
# TODO: syncProject() doesn't handle case of a local git pushing to new gitlab
# TODO: if more than one remote then offer options
from psychopy.projects import pavlovia
from .functions import *
from .project import ProjectEditor, syncProject
from ._base import PavloviaMiniBrowser
from . import menu, project, search
| 896
|
Python
|
.py
| 19
| 46
| 79
| 0.778032
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,822
|
menu.py
|
psychopy_psychopy/psychopy/app/pavlovia_ui/menu.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Part of the PsychoPy library
# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd.
# Distributed under the terms of the GNU General Public License (GPL).
import io
import wx
import requests
from psychopy import logging
from .. import dialogs
from ..themes import icons
from .functions import logInPavlovia
from psychopy.app.pavlovia_ui.project import syncProject
from .search import SearchFrame
from .project import ProjectEditor
from psychopy.localization import _translate
from psychopy.projects import pavlovia
from psychopy.app.pavlovia_ui import sync
class PavloviaMenu(wx.Menu):
app = None
appData = None
currentUser = None
knownUsers = None
searchDlg = None
def __init__(self, parent):
wx.Menu.__init__(self)
self.parent = parent # is a BuilderFrame
PavloviaMenu.app = parent.app
keys = self.app.keys
# from prefs fetch info about prev usernames and projects
PavloviaMenu.appData = self.app.prefs.appData['projects']
# item = self.Append(wx.ID_ANY, _translate("Tell me more..."))
# parent.Bind(wx.EVT_MENU, self.onAbout, id=item.GetId())
# parent.Bind(wx.EVT_MENU, self.onAbout, id=item.GetId())
PavloviaMenu.knownUsers = pavlovia.knownUsers
# sub-menu for usernames and login
self.userMenu = wx.Menu()
# if a user was previously logged in then set them as current
lastPavUser = PavloviaMenu.appData['pavloviaUser']
if pavlovia.knownUsers and (lastPavUser not in pavlovia.knownUsers):
lastPavUser = None
# if lastPavUser and not PavloviaMenu.currentUser:
# self.setUser(PavloviaMenu.appData['pavloviaUser'])
if self.knownUsers is not None:
for name in self.knownUsers:
self.addToSubMenu(name, self.userMenu, self.onSetUser)
self.userMenu.AppendSeparator()
self.loginBtn = self.userMenu.Append(wx.ID_ANY,
_translate("Log in to Pavlovia...\t{}")
.format(keys['pavlovia_logIn']))
parent.Bind(wx.EVT_MENU, self.onLogInPavlovia, id=self.loginBtn.GetId())
self.AppendSubMenu(self.userMenu, _translate("User"))
# search
self.searchBtn = self.Append(wx.ID_ANY,
_translate("Search Pavlovia\t{}")
.format(keys['projectsFind']))
parent.Bind(wx.EVT_MENU, self.onSearch, id=self.searchBtn.GetId())
# new
self.newBtn = self.Append(wx.ID_ANY,
_translate("New...\t{}").format(keys['projectsNew']))
parent.Bind(wx.EVT_MENU, self.onNew, id=self.newBtn.GetId())
self.syncBtn = self.Append(wx.ID_ANY,
_translate("Sync\t{}").format(keys['projectsSync']))
parent.Bind(wx.EVT_MENU, self.onSync, id=self.syncBtn.GetId())
def addToSubMenu(self, name, menu, function):
item = menu.Append(wx.ID_ANY, name)
self.parent.Bind(wx.EVT_MENU, function, id=item.GetId())
def onAbout(self, event):
wx.GetApp().followLink(event)
def onSetUser(self, event):
user = self.userMenu.GetLabelText(event.GetId())
self.setUser(user)
def setUser(self, user=None):
if PavloviaMenu.appData:
if user is None and PavloviaMenu.appData['pavloviaUser']:
user = PavloviaMenu.appData['pavloviaUser']
if user in [PavloviaMenu.currentUser, None]:
return # nothing to do here. Move along please.
PavloviaMenu.currentUser = user
PavloviaMenu.appData['pavloviaUser'] = user
if user in pavlovia.knownUsers:
token = pavlovia.knownUsers[user]['token']
try:
pavlovia.login(token)
except requests.exceptions.ConnectionError:
logging.warning("Tried to log in to Pavlovia but no network "
"connection")
return
else:
if hasattr(self, 'onLogInPavlovia'):
self.onLogInPavlovia()
if PavloviaMenu.searchDlg:
PavloviaMenu.searchDlg.updateUserProjs()
def onSync(self, event):
syncProject(parent=self.parent, project=self.parent.project)
def onSearch(self, event):
PavloviaMenu.searchDlg = SearchFrame(app=self.parent.app)
PavloviaMenu.searchDlg.Show()
def onLogInPavlovia(self, event=None):
logInPavlovia(parent=self.parent)
def onNew(self, event):
"""Create a new project
"""
# Get session
session = pavlovia.getCurrentSession()
# If logged in, create project
if session.user:
dlg = sync.CreateDlg(self.parent, user=session.user)
dlg.ShowModal()
# Otherwise, prompt user to log in
else:
infoDlg = dialogs.MessageDialog(parent=None, type='Info',
message=_translate(
"You need to log in"
" to create a project"))
infoDlg.Show()
| 5,264
|
Python
|
.py
| 116
| 34.689655
| 80
| 0.619828
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,823
|
functions.py
|
psychopy_psychopy/psychopy/app/pavlovia_ui/functions.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Part of the PsychoPy library
# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd.
# Distributed under the terms of the GNU General Public License (GPL).
import os
import wx
from ._base import PavloviaMiniBrowser, PavloviaCommitDialog
from psychopy.projects import pavlovia # NB pavlovia will set gitpython path
from psychopy.localization import _translate
try:
import wx.adv as wxhl # in wx 4
except ImportError:
wxhl = wx # in wx 3.0.2
if pavlovia.haveGit:
import git
def setLocalPath(parent, project=None, path=""):
"""Open a DirDialog and set the project local folder to that specified
Returns
----------
None for no change and newPath if this has changed from previous
"""
if path:
origPath = path
elif project and 'localRoot' in project:
origPath = project.localRoot
else:
origPath = ""
# create the dialog
dlg = wx.DirDialog(
parent,
defaultPath=origPath,
message=_translate(
"Choose/create the root location for the synced project"))
if dlg.ShowModal() == wx.ID_OK:
newPath = dlg.GetPath()
if os.path.isfile(newPath):
newPath = os.path.split(newPath)[0]
if newPath != origPath:
if project:
project.localRoot = newPath
return newPath
def checkLogin(session=None):
"""
Check whether a given session, or the current session if left blank, is logged in to Pavlovia.
Returns:
status : bool
True if logged in after process is completed, False otherwise.
"""
if session is None:
# Substitute default session
session = pavlovia.getCurrentSession()
if session and session.user:
# If logged in, return positive
return True
else:
# If not logged in, prompt to login
dlg = wx.MessageDialog(None, message=_translate(
"You are not logged in to Pavlovia. Please log in to continue."
), style=wx.ICON_AUTH_NEEDED | wx.OK | wx.CANCEL)
dlg.SetOKLabel(_translate("Login..."))
if dlg.ShowModal() == wx.ID_OK:
# If they click Login, open login screen
user = logInPavlovia(None)
# Return positive or negative based on whether login succeeded
return bool(user)
else:
# If they cancel out of login prompt, return negative
return False
def logInPavlovia(parent, event=None):
"""Opens the built-in browser dialog to login to pavlovia
Returns
-------
None (user closed window without logging on) or a gitlab.User object
"""
# check known users list
dlg = PavloviaMiniBrowser(parent=parent, loginOnly=True)
dlg.ShowModal() # with loginOnly=True this will EndModal once logged in
if dlg.tokenInfo:
token = dlg.tokenInfo['token']
pavlovia.login(token, rememberMe=True) # log in to the current pavlovia session
return pavlovia.getCurrentSession().user
def logOutPavlovia(parent, event=None):
"""Opens the built-in browser dialog to login to pavlovia
Returns
-------
None (user closed window without logging on) or a gitlab.User object
"""
# also log out of gitlab session in python
pavlovia.logout()
# create minibrowser so we can logout of the session
dlg = PavloviaMiniBrowser(parent=parent, logoutOnly=True)
dlg.logout()
dlg.Destroy()
def showCommitDialog(parent, project, initMsg="", infoStream=None):
"""Brings up a commit dialog (if there is anything to commit
Returns
-------
0 nothing to commit
1 successful commit
-1 user cancelled
"""
changeDict, changeList = project.getChanges()
# if changeList is empty then nothing to do
if not changeList:
return 0
changeInfo = _translate("Changes to commit:\n")
for categ in ['untracked', 'changed', 'deleted', 'renamed']:
changes = changeDict[categ]
if categ == 'untracked':
categ = 'New'
if changes:
changeInfo += _translate("\t{}: {} files\n").format(categ.title(), len(changes))
dlg = PavloviaCommitDialog(parent, id=wx.ID_ANY, title=_translate("Committing changes"), changeInfo=changeInfo)
retVal = dlg.ShowCommitDlg()
commitMsg = dlg.getCommitMsg()
dlg.Destroy()
if retVal == wx.ID_CANCEL:
return -1
project.stageFiles(changeList) # NB not needed in dulwich
project.commit(commitMsg)
return 1
def noGitWarning(parent):
"""Raise a simpler warning dialog that the user needs to install git first"""
dlg = wx.Dialog(parent=parent, style=wx.ICON_ERROR | wx.OK | wx.STAY_ON_TOP)
errorBitmap = wx.ArtProvider.GetBitmap(wx.ART_ERROR, wx.ART_MESSAGE_BOX)
errorBitmapCtrl = wx.StaticBitmap(dlg, -1)
errorBitmapCtrl.SetBitmap(errorBitmap)
msg = wx.StaticText(dlg, label=_translate(
"You need to install git to use Pavlovia projects"))
link = wxhl.HyperlinkCtrl(dlg, url="https://git-scm.com/")
OK = wx.Button(dlg, wx.ID_OK, label="OK")
msgsSizer = wx.BoxSizer(wx.VERTICAL)
msgsSizer.Add(msg, 1, flag=wx.ALIGN_RIGHT | wx.ALL | wx.EXPAND, border=5)
msgsSizer.Add(link, 1, flag=wx.ALIGN_RIGHT | wx.ALL | wx.EXPAND, border=5)
msgsAndIcon = wx.BoxSizer(wx.HORIZONTAL)
msgsAndIcon.Add(errorBitmapCtrl, 0, flag=wx.ALIGN_RIGHT | wx.ALL, border=5)
msgsAndIcon.Add(msgsSizer, 1, flag=wx.ALIGN_RIGHT | wx.ALL | wx.EXPAND,
border=5)
mainSizer = wx.BoxSizer(wx.VERTICAL)
mainSizer.Add(msgsAndIcon, 0, flag=wx.ALIGN_RIGHT | wx.ALL, border=5)
mainSizer.Add(OK, 0, flag=wx.ALIGN_RIGHT | wx.ALL, border=5)
dlg.SetSizerAndFit(mainSizer)
dlg.Layout()
dlg.ShowModal()
| 5,865
|
Python
|
.py
| 145
| 33.827586
| 115
| 0.668953
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,824
|
_base.py
|
psychopy_psychopy/psychopy/app/pavlovia_ui/_base.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Part of the PsychoPy library
# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd.
# Distributed under the terms of the GNU General Public License (GPL).
import sys
import wx
import wx.html2
import requests
from psychopy.localization import _translate
from psychopy.projects import pavlovia
from psychopy import logging
class BaseFrame(wx.Frame):
def __init__(self, *args, **kwargs):
wx.Frame.__init__(self, *args, **kwargs)
self.Center()
# set up menu bar
self.menuBar = wx.MenuBar()
self.fileMenu = self.makeFileMenu()
self.menuBar.Append(self.fileMenu, _translate('&File'))
self.SetMenuBar(self.menuBar)
def makeFileMenu(self):
fileMenu = wx.Menu()
app = wx.GetApp()
keyCodes = app.keys
# add items to file menu
fileMenu.Append(wx.ID_CLOSE,
_translate("&Close View\t%s") % keyCodes['close'],
_translate("Close current window"))
self.Bind(wx.EVT_MENU, self.closeFrame, id=wx.ID_CLOSE)
# -------------quit
fileMenu.AppendSeparator()
fileMenu.Append(wx.ID_EXIT,
_translate("&Quit\t%s") % keyCodes['quit'],
_translate("Terminate the program"))
self.Bind(wx.EVT_MENU, app.quit, id=wx.ID_EXIT)
return fileMenu
def closeFrame(self, event=None, checkSave=True):
self.Destroy()
def checkSave(self):
"""If the app asks whether everything is safely saved
"""
return True # for OK
class PavloviaMiniBrowser(wx.Dialog):
"""This class is used by to open an internal browser for the user stuff
"""
style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER
def __init__(self, parent, user=None, loginOnly=False, logoutOnly=False,
style=style, *args, **kwargs):
# create the dialog
wx.Dialog.__init__(self, parent, style=style, *args, **kwargs)
# create browser window for authentication
self.browser = wx.html2.WebView.New(self)
self.loginOnly = loginOnly
self.logoutOnly = logoutOnly
self.tokenInfo = {}
# do layout
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.browser, 1, wx.EXPAND, 10)
self.SetSizer(sizer)
if loginOnly:
self.SetSize((600, 600))
else:
self.SetSize((700, 600))
self.CenterOnParent()
# check there is a user (or log them in)
if not user:
self.user = pavlovia.getCurrentSession().user
if not user:
self.login()
if not user:
return None
def logout(self):
self.browser.Bind(wx.html2.EVT_WEBVIEW_LOADED, self.checkForLogoutURL)
self.browser.LoadURL('https://gitlab.pavlovia.org/users/sign_out')
def login(self):
self._loggingIn = True
authURL, state = pavlovia.getAuthURL()
self.browser.Bind(wx.html2.EVT_WEBVIEW_ERROR, self.onConnectionErr)
self.browser.Bind(wx.html2.EVT_WEBVIEW_LOADED, self.getAccessTokenFromURL)
self.browser.LoadURL(authURL)
self.Close()
def setURL(self, url):
self.browser.LoadURL(url)
def gotoUserPage(self):
if self.user:
url = self.user.attributes['web_url']
self.browser.LoadURL(url)
def editUserPage(self):
url = "https://gitlab.pavlovia.org/profile"
self.browser.LoadURL(url)
self.SetSizeWH(1240, 840)
def gotoProjects(self):
self.browser.LoadURL("https://pavlovia.org/projects.html")
def onConnectionErr(self, event):
if 'INET_E_DOWNLOAD_FAILURE' in event.GetString():
self.EndModal(wx.ID_EXIT)
raise Exception("{}: No internet connection available.".format(event.GetString()))
def getAccessTokenFromURL(self, event):
"""
Parse the redirect url from a login request for the parameter `code`, this is
the "Auth code" which is used later to get an access token.
Parameters
----------
event : wx.html2.EVT_WEBVIEW_LOADED
Load event from the browser window.
"""
# get URL
url = event.GetURL()
# get auth code from URL
if "code=" in url:
# get state from redirect url
self.tokenInfo['state'] = self.getParamFromURL('state', url)
# if returned an auth code, use it to get a token
resp = requests.post(
"https://gitlab.pavlovia.org/oauth/token",
params={
'client_id': pavlovia.client_id,
'code': self.getParamFromURL("code", url),
'grant_type': "authorization_code",
'redirect_uri': pavlovia.redirect_url,
'code_verifier': pavlovia.code_verifier
}
).json()
# use the json response from that http request to get access remaining token info
self.tokenInfo['token'] = resp['access_token']
self.tokenInfo['tokenType'] = resp['token_type']
elif "access_token=" in url:
self.tokenInfo['token'] = self.getParamFromURL(
'access_token', url)
self.tokenInfo['tokenType'] = self.getParamFromURL(
'token_type', url)
self.tokenInfo['state'] = self.getParamFromURL(
'state', url)
self._loggingIn = False # we got a log in
self.browser.Unbind(wx.html2.EVT_WEBVIEW_LOADED)
pavlovia.login(self.tokenInfo['token'])
if self.loginOnly:
self.EndModal(wx.ID_OK)
elif url == 'https://gitlab.pavlovia.org/dashboard/projects':
# this is what happens if the user registered instead of logging in
# try now to do the log in (in the same session)
self.login()
else:
logging.info("OAuthBrowser.onNewURL: {}".format(url))
def checkForLogoutURL(self, event):
url = event.GetURL()
if url == 'https://gitlab.pavlovia.org/users/sign_in':
if self.logoutOnly and self.IsModal():
self.EndModal(wx.ID_OK)
def getParamFromURL(self, paramName, url=None):
"""Takes a url and returns the named param"""
if url is None:
url = self.browser.GetCurrentURL()
return url.split(paramName + '=')[1].split('&')[0]
class PavloviaCommitDialog(wx.Dialog):
"""This class will be used to brings up a commit dialog
(if there is anything to commit)"""
def __init__(self, *args, **kwargs):
# pop kwargs for Py2 compatibility
changeInfo = kwargs.pop('changeInfo', '')
initMsg = kwargs.pop('initMsg', '')
super(PavloviaCommitDialog, self).__init__(*args, **kwargs)
# Set Text widgets
wx.Dialog(None, id=wx.ID_ANY, title=_translate("Committing changes"))
self.updatesInfo = wx.StaticText(self, label=changeInfo)
self.commitTitleLbl = wx.StaticText(self, label=_translate('Summary of changes'))
self.commitTitleCtrl = wx.TextCtrl(self, size=(500, -1), value=initMsg)
self.commitDescrLbl = wx.StaticText(self, label=_translate('Details of changes\n (optional)'))
self.commitDescrCtrl = wx.TextCtrl(self, size=(500, 200), style=wx.TE_MULTILINE | wx.TE_AUTO_URL)
# Set buttons
self.btnOK = wx.Button(self, wx.ID_OK)
self.btnCancel = wx.Button(self, wx.ID_CANCEL)
# Format elements
self.setToolTips()
self.setDlgSizers()
def setToolTips(self):
"""Set the tooltips for the dialog widgets"""
self.commitTitleCtrl.SetToolTip(
wx.ToolTip(
_translate("Title summarizing the changes you're making in these files")))
self.commitDescrCtrl.SetToolTip(
wx.ToolTip(
_translate("Optional details about the changes you're making in these files")))
def setDlgSizers(self):
"""
Set the commit dialog sizers and layout.
"""
commitSizer = wx.FlexGridSizer(cols=2, rows=2, vgap=5, hgap=5)
commitSizer.AddMany([(self.commitTitleLbl, 0, wx.ALIGN_RIGHT),
self.commitTitleCtrl,
(self.commitDescrLbl, 0, wx.ALIGN_RIGHT),
self.commitDescrCtrl])
buttonSizer = wx.BoxSizer(wx.HORIZONTAL)
if sys.platform == "win32":
btns = [self.btnOK, self.btnCancel]
else:
btns = [self.btnCancel, self.btnOK]
buttonSizer.AddMany(btns)
# main sizer and layout
mainSizer = wx.BoxSizer(wx.VERTICAL)
mainSizer.Add(self.updatesInfo, 0, wx.ALL | wx.EXPAND, border=5)
mainSizer.Add(commitSizer, 1, wx.ALL | wx.EXPAND, border=5)
mainSizer.Add(buttonSizer, 0, wx.ALL | wx.ALIGN_RIGHT, border=5)
self.SetSizerAndFit(mainSizer)
self.Layout()
def ShowCommitDlg(self):
"""Show the commit application-modal dialog
Returns
-------
wx event
"""
return self.ShowModal()
def getCommitMsg(self):
"""
Gets the commit message for the git commit.
Returns
-------
string:
The commit message and description.
If somehow the commit message is blank, a default is given.
"""
if self.commitTitleCtrl.IsEmpty():
commitMsg = "_"
else:
commitMsg = self.commitTitleCtrl.GetValue()
if not self.commitDescrCtrl.IsEmpty():
commitMsg += "\n\n" + self.commitDescrCtrl.GetValue()
return commitMsg
| 9,847
|
Python
|
.py
| 229
| 32.834061
| 105
| 0.603279
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,825
|
runner.py
|
psychopy_psychopy/psychopy/app/runner/runner.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Part of the PsychoPy library
# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd.
# Distributed under the terms of the GNU General Public License (GPL).
import glob
import json
import errno
from .. import ribbon
from ..stdout.stdOutRich import ScriptOutputPanel
from ..themes import handlers, colors, icons
from ..themes.ui import ThemeSwitcher
import wx
import wx.lib.agw.aui as aui
import os
import sys
import time
import requests
import traceback
import webbrowser
from pathlib import Path
from subprocess import Popen, PIPE
from psychopy import experiment, logging, alerts
from psychopy.app.utils import FrameSwitcher, FileDropTarget
from psychopy.localization import _translate
from psychopy.projects.pavlovia import getProject
from psychopy.scripts.psyexpCompile import generateScript
from psychopy.app.runner.scriptProcess import ScriptProcess
import psychopy.tools.versionchooser as versions
folderColumn = 2
runModeColumn = 1
filenameColumn = 0
class RunnerFrame(wx.Frame, handlers.ThemeMixin):
"""Construct the Psychopy Runner Frame."""
def __init__(self, parent=None, id=wx.ID_ANY, title='', app=None):
super(RunnerFrame, self).__init__(parent=parent,
id=id,
title=title,
pos=wx.DefaultPosition,
size=wx.DefaultSize,
style=wx.DEFAULT_FRAME_STYLE,
name=title,
)
self.app = app
self.paths = self.app.prefs.paths
self.frameType = 'runner'
self.app.trackFrame(self)
self.panel = RunnerPanel(self, id, title, app)
self.panel.SetDoubleBuffered(True)
# detect retina displays (then don't use double-buffering)
self.isRetina = self.GetContentScaleFactor() != 1
self.SetDoubleBuffered(not self.isRetina)
self.SetMinSize(wx.Size(640, 480))
# double buffered better rendering except if retina
self.panel.SetDoubleBuffered(not self.isRetina)
# Create menu
self.runnerMenu = wx.MenuBar()
self.makeMenu()
self.SetMenuBar(self.runnerMenu)
# Link to file drop function
self.SetDropTarget(FileDropTarget(targetFrame=self))
# create icon
if sys.platform != 'darwin':
# doesn't work on darwin and not necessary: handled by app bundle
iconFile = os.path.join(self.paths['resources'], 'runner.ico')
if os.path.isfile(iconFile):
self.SetIcon(wx.Icon(iconFile, wx.BITMAP_TYPE_ICO))
self.mainSizer = wx.BoxSizer(wx.VERTICAL)
self.mainSizer.Add(self.panel, 1, wx.EXPAND | wx.ALL)
self.SetSizerAndFit(self.mainSizer)
self.appData = self.app.prefs.appData['runner']
# Load previous tasks
for filePath in self.appData['taskList']:
if os.path.exists(filePath):
self.addTask(fileName=filePath)
self.Bind(wx.EVT_CLOSE, self.onClose)
# hide alerts to begin with, more room for std while also making alerts more noticeable
self.Layout()
if self.isRetina:
self.SetSize(wx.Size(920, 640))
else:
self.SetSize(wx.Size(1080, 920))
self.theme = app.theme
@property
def filename(self):
"""Presently selected file name in Runner (`str` or `None`). If `None`,
not file is presently selected or the task list is empty.
"""
if not self.panel.currentSelection: # no selection or empty list
return
if self.panel.currentSelection >= 0: # has valid item selected
return self.panel.expCtrl.GetItem(self.panel.currentSelection).Text
def addTask(self, evt=None, fileName=None, runMode="run"):
self.panel.addTask(fileName=fileName, runMode=runMode)
def removeTask(self, evt=None):
self.panel.removeTask(evt)
def getOutputPanel(self, name):
"""
Get output panel which matches the given name.
Parameters
----------
name : str
Key by which the output panel was stored on creation
Returns
-------
ScriptOutputPanel
Handle of the output panel
"""
return self.panel.outputNotebook.panels[name]
@property
def stdOut(self):
return self.panel.stdoutPnl.ctrl
@property
def alerts(self):
return self.panel.alertsPnl.ctrl
def makeMenu(self):
"""Create Runner menubar."""
keys = self.app.prefs.keys
# Menus
fileMenu = wx.Menu()
viewMenu = wx.Menu()
runMenu = wx.Menu()
demosMenu = wx.Menu()
# Menu items
fileMenuItems = [
{'id': wx.ID_ADD, 'label': _translate('Add task'),
'status': _translate('Adding task'),
'func': self.addTask},
{'id': wx.ID_REMOVE, 'label': _translate('Remove task'),
'status': 'Removing task',
'func': self.removeTask},
{'id': wx.ID_CLEAR, 'label': _translate('Clear all'),
'status': _translate('Clearing tasks'),
'func': self.clearTasks},
{'id': wx.ID_SAVE,
'label': _translate('&Save list')+'\t%s'%keys['save'],
'status': _translate('Saving task'),
'func': self.saveTaskList},
{'id': wx.ID_OPEN, 'label': _translate('&Open list')+'\tCtrl-O',
'status': _translate('Loading task'),
'func': self.loadTaskList},
{'id': wx.ID_CLOSE_FRAME, 'label': _translate('Close')+'\tCtrl-W',
'status': _translate('Closing Runner'),
'func': self.onClose},
{'id': wx.ID_EXIT, 'label': _translate("&Quit\t%s") % keys['quit'],
'status': _translate('Quitting PsychoPy'),
'func': self.onQuit},
]
viewMenuItems = [
]
runMenuItems = [
{'id': wx.ID_ANY,
'label': _translate("&Run/pilot\t%s") % keys['runScript'],
'status': _translate('Running experiment'),
'func': self.panel.onRunShortcut},
{'id': wx.ID_ANY,
'label': _translate('Run &JS for local debug'),
'status': _translate('Launching local debug of online study'),
'func': self.panel.runOnlineDebug},
{'id': wx.ID_ANY,
'label': _translate('Run JS on &Pavlovia'),
'status': _translate('Launching online study at Pavlovia'),
'func': self.panel.runOnline},
]
demosMenuItems = [
{'id': wx.ID_ANY,
'label': _translate("&Builder Demos"),
'status': _translate("Loading builder demos"),
'func': self.loadBuilderDemos},
{'id': wx.ID_ANY,
'label': _translate("&Coder Demos"),
'status': _translate("Loading coder demos"),
'func': self.loadCoderDemos},
]
menus = [
{'menu': fileMenu, 'menuItems': fileMenuItems, 'separators': ['clear all', 'load list']},
{'menu': viewMenu, 'menuItems': viewMenuItems, 'separators': []},
{'menu': runMenu, 'menuItems': runMenuItems, 'separators': []},
{'menu': demosMenu, 'menuItems': demosMenuItems, 'separators': []},
]
# Add items to menus
for eachMenu in menus:
for item in eachMenu['menuItems']:
fileItem = eachMenu['menu'].Append(item['id'], item['label'], item['status'])
self.Bind(wx.EVT_MENU, item['func'], fileItem)
if item['label'].lower() in eachMenu['separators']:
eachMenu['menu'].AppendSeparator()
# Theme switcher
self.themesMenu = ThemeSwitcher(app=self.app)
viewMenu.AppendSubMenu(self.themesMenu, _translate("&Themes"))
# Frame switcher
FrameSwitcher.makeViewSwitcherButtons(viewMenu, frame=self, app=self.app)
# Create menus
self.runnerMenu.Append(fileMenu, _translate('&File'))
self.runnerMenu.Append(viewMenu, _translate('&View'))
self.runnerMenu.Append(runMenu, _translate('&Run'))
self.runnerMenu.Append(demosMenu, _translate('&Demos'))
# Add frame switcher
self.windowMenu = FrameSwitcher(self)
self.runnerMenu.Append(self.windowMenu, _translate('&Window'))
def saveTaskList(self, evt=None):
"""Save task list as psyrun file."""
if hasattr(self, 'listname'):
filename = self.listname
else:
filename = "untitled.psyrun"
initPath, filename = os.path.split(filename)
_w = "PsychoPy task lists (*.psyrun)|*.psyrun|Any file (*.*)|*"
if sys.platform != 'darwin':
_w += '.*'
wildcard = _translate(_w)
dlg = wx.FileDialog(
self, message=_translate("Save task list as ..."), defaultDir=initPath,
defaultFile=filename, style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT,
wildcard=wildcard)
if dlg.ShowModal() == wx.ID_OK:
newPath = dlg.GetPath()
# actually save
experiments = []
for i in range(self.panel.expCtrl.GetItemCount()):
experiments.append(
{
'path': self.panel.expCtrl.GetItem(i, folderColumn).Text,
'file': self.panel.expCtrl.GetItem(i, filenameColumn).Text,
'runMode': self.panel.expCtrl.GetItem(i, runModeColumn).Text,
},
)
with open(newPath, 'w') as file:
json.dump(experiments, file)
self.listname = newPath
dlg.Destroy()
def loadTaskList(self, evt=None):
"""Load saved task list from appData."""
if hasattr(self, 'listname'):
filename = self.listname
else:
filename = "untitled.psyrun"
initPath, filename = os.path.split(filename)
_w = "PsychoPy task lists (*.psyrun)|*.psyrun|Any file (*.*)|*"
if sys.platform != 'darwin':
_w += '.*'
wildcard = _translate(_w)
dlg = wx.FileDialog(
self, message=_translate("Open task list ..."), defaultDir=initPath,
defaultFile=filename, style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST,
wildcard=wildcard)
fileOk = True
newPath = None
if dlg.ShowModal() == wx.ID_OK: # file was selected
newPath = dlg.GetPath()
with open(newPath, 'r') as file:
try:
experiments = json.load(file)
except Exception: # broad catch, but lots of stuff can go wrong
fileOk = False
if fileOk:
self.panel.entries = {}
self.panel.expCtrl.DeleteAllItems()
for exp in experiments:
self.panel.addTask(
fileName=os.path.join(exp['path'], exp['file']),
runMode=exp.get('runMode', "run")
)
self.listname = newPath
dlg.Destroy() # close the file browser
if newPath is None: # user cancelled
if evt is not None:
evt.Skip()
return
if not fileOk: # file failed to load, show an error dialog
errMsg = (
u"Failed to open file '{}', check if the file has the "
u"correct UTF-8 encoding and is the correct format."
)
errMsg = errMsg.format(str(newPath))
errDlg = wx.MessageDialog(
None, errMsg, 'Error',
wx.OK | wx.ICON_ERROR)
errDlg.ShowModal()
errDlg.Destroy()
def clearTasks(self, evt=None):
"""Clear all items from the panels expCtrl ListCtrl."""
self.panel.expCtrl.DeleteAllItems()
self.panel.currentSelection = None
self.panel.currentProject = None
self.panel.currentFile = None
def onClose(self, event=None):
"""Define Frame closing behavior."""
self.app.runner = None
allFrames = self.app.getAllFrames()
lastFrame = len(allFrames) == 1
if lastFrame:
self.onQuit()
else:
self.Hide()
self.app.forgetFrame(self)
self.app.updateWindowMenu()
def onQuit(self, evt=None):
sys.stderr = sys.stdout = sys.__stdout__
self.panel.stopTask()
self.app.quit(evt)
def checkSave(self):
return True
def viewBuilder(self, evt):
if self.panel.currentFile is None:
self.app.showBuilder()
return
for frame in self.app.getAllFrames("builder"):
if frame.filename == 'untitled.psyexp' and frame.lastSavedCopy is None:
frame.fileOpen(filename=str(self.panel.currentFile))
return
self.app.showBuilder(fileList=[str(self.panel.currentFile)])
def viewCoder(self, evt):
if self.panel.currentFile is None:
self.app.showCoder()
return
self.app.showCoder() # ensures that a coder window exists
self.app.coder.setCurrentDoc(str(self.panel.currentFile))
self.app.coder.setFileModified(False)
def showRunner(self):
self.app.showRunner()
def loadBuilderDemos(self, event):
"""Load Builder demos"""
self.panel.expCtrl.DeleteAllItems()
unpacked = self.app.prefs.builder['unpackedDemosDir']
if not unpacked:
return
# list available demos
demoList = sorted(glob.glob(os.path.join(unpacked, '*')))
demos = {wx.NewIdRef(): demoList[n]
for n in range(len(demoList))}
for thisID in demos:
junk, shortname = os.path.split(demos[thisID])
if (shortname.startswith('_') or
shortname.lower().startswith('readme.')):
continue # ignore 'private' or README files
for file in os.listdir(demos[thisID]):
if file.endswith('.psyexp'):
self.addTask(fileName=os.path.join(demos[thisID], file))
def loadCoderDemos(self, event):
"""Load Coder demos"""
self.panel.expCtrl.DeleteAllItems()
_localized = {'basic': _translate('basic'),
'input': _translate('input'),
'stimuli': _translate('stimuli'),
'experiment control': _translate('exp control'),
'iohub': 'ioHub', # no translation
'hardware': _translate('hardware'),
'timing': _translate('timing'),
'misc': _translate('misc')}
folders = glob.glob(os.path.join(self.paths['demos'], 'coder', '*'))
for folder in folders:
# if it isn't a folder then skip it
if (not os.path.isdir(folder)):
continue
# otherwise create a submenu
folderDisplayName = os.path.split(folder)[-1]
if folderDisplayName.startswith('_'):
continue # don't include private folders
if folderDisplayName in _localized:
folderDisplayName = _localized[folderDisplayName]
# find the files in the folder (search two levels deep)
demoList = glob.glob(os.path.join(folder, '*.py'))
demoList += glob.glob(os.path.join(folder, '*', '*.py'))
demoList += glob.glob(os.path.join(folder, '*', '*', '*.py'))
demoList.sort()
for thisFile in demoList:
shortname = thisFile.split(os.path.sep)[-1]
if shortname == "run.py":
# file is just "run" so get shortname from directory name
# instead
shortname = thisFile.split(os.path.sep)[-2]
elif shortname.startswith('_'):
continue # remove any 'private' files
self.addTask(fileName=thisFile)
@property
def taskList(self):
"""
Retrieve item paths from expCtrl.
Returns
-------
taskList : list of filepaths
"""
temp = []
for idx in range(self.panel.expCtrl.GetItemCount()):
filename = self.panel.expCtrl.GetItem(idx, filenameColumn).Text
folder = self.panel.expCtrl.GetItem(idx, folderColumn).Text
temp.append(str(Path(folder) / filename))
return temp
class RunnerPanel(wx.Panel, ScriptProcess, handlers.ThemeMixin):
def __init__(self, parent=None, id=wx.ID_ANY, title='', app=None):
super(RunnerPanel, self).__init__(parent=parent,
id=id,
pos=wx.DefaultPosition,
size=[1080, 720],
style=wx.DEFAULT_FRAME_STYLE,
name=title,
)
ScriptProcess.__init__(self, app)
#self.Bind(wx.EVT_END_PROCESS, self.onProcessEnded)
# double buffered better rendering except if retina
self.SetDoubleBuffered(parent.IsDoubleBuffered())
self.SetMinSize(wx.Size(640, 480))
self.app = app
self.prefs = self.app.prefs.coder
self.paths = self.app.prefs.paths
self.parent = parent
# start values for server stuff
self.serverProcess = None
self.serverPort = None
# self.entries is dict of dicts: {filepath: {'index': listCtrlInd}} and may store more info later
self.entries = {}
self.currentFile = None
self.currentProject = None # access from self.currentProject property
self.currentSelection = None
self.currentExperiment = None
# setup sizer
self.mainSizer = wx.BoxSizer(wx.VERTICAL)
# setup ribbon
self.ribbon = RunnerRibbon(self)
self.ribbon.buttons['pyswitch'].setMode(0)
self.mainSizer.Add(self.ribbon, border=0, flag=wx.EXPAND | wx.ALL)
# Setup splitter
self.splitter = wx.SplitterWindow(self, style=wx.SP_NOBORDER)
self.mainSizer.Add(self.splitter, proportion=1, border=0, flag=wx.EXPAND | wx.ALL)
# Setup panel for top half (experiment control and toolbar)
self.topPanel = wx.Panel(self.splitter)
self.topPanel.border = wx.BoxSizer()
self.topPanel.SetSizer(self.topPanel.border)
self.topPanel.sizer = wx.BoxSizer(wx.HORIZONTAL)
self.topPanel.border.Add(self.topPanel.sizer, proportion=1, border=6, flag=wx.ALL | wx.EXPAND)
# ListCtrl for list of tasks
self.expCtrl = wx.ListCtrl(self.topPanel,
id=wx.ID_ANY,
style=wx.LC_REPORT | wx.BORDER_NONE | wx.LC_NO_HEADER | wx.LC_SINGLE_SEL)
self.expCtrl.Bind(wx.EVT_LIST_ITEM_SELECTED,
self.onItemSelected, self.expCtrl)
self.expCtrl.Bind(wx.EVT_LIST_ITEM_DESELECTED,
self.onItemDeselected, self.expCtrl)
self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.onDoubleClick, self.expCtrl)
self.expCtrl.InsertColumn(filenameColumn, _translate('File'))
self.expCtrl.InsertColumn(folderColumn, _translate('Path'))
self.expCtrl.InsertColumn(folderColumn, _translate('Run mode'))
self.topPanel.sizer.Add(self.expCtrl, proportion=1, border=6, flag=wx.ALL | wx.EXPAND)
# Setup panel for bottom half (alerts and stdout)
self.bottomPanel = wx.Panel(self.splitter, style=wx.BORDER_NONE)
self.bottomPanel.border = wx.BoxSizer()
self.bottomPanel.SetSizer(self.bottomPanel.border)
self.bottomPanel.sizer = wx.BoxSizer(wx.VERTICAL)
self.bottomPanel.border.Add(self.bottomPanel.sizer, proportion=1, border=6, flag=wx.ALL | wx.EXPAND)
# Setup notebook for output
self.outputNotebook = RunnerOutputNotebook(self.bottomPanel)
self.stdoutPnl = self.outputNotebook.stdoutPnl
self.stdoutCtrl = self.outputNotebook.stdoutPnl.ctrl
self.alertsPnl = self.outputNotebook.alertsPnl
self.alertsCtrl = self.outputNotebook.alertsPnl.ctrl
self.bottomPanel.sizer.Add(
self.outputNotebook, proportion=1, border=6, flag=wx.ALL | wx.EXPAND
)
# Assign to splitter
self.splitter.SplitVertically(
window1=self.topPanel,
window2=self.bottomPanel,
sashPosition=360
)
self.splitter.SetMinimumPaneSize(360)
self.SetSizerAndFit(self.mainSizer)
# Set starting states on buttons
self.ribbon.buttons['pystop'].Disable()
self.ribbon.buttons['remove'].Disable()
self.theme = parent.theme
def __del__(self):
if self.serverProcess is not None:
self.killServer()
def _applyAppTheme(self):
# Srt own background
self.SetBackgroundColour(colors.app['panel_bg'])
self.topPanel.SetBackgroundColour(colors.app['panel_bg'])
self.bottomPanel.SetBackgroundColour(colors.app['panel_bg'])
# Theme buttons
self.ribbon.theme = self.theme
# Theme notebook
self.outputNotebook.theme = self.theme
bmps = {
self.alertsPnl: icons.ButtonIcon("alerts", size=16).bitmap,
self.stdoutPnl: icons.ButtonIcon("stdout", size=16).bitmap,
self.outputNotebook.gitPnl: icons.ButtonIcon("pavlovia", size=16).bitmap,
}
for i in range(self.outputNotebook.GetPageCount()):
pg = self.outputNotebook.GetPage(i)
if pg in bmps:
self.outputNotebook.SetPageBitmap(i, bmps[pg])
# Apply app theme on objects in non-theme-mixin panels
for obj in (
self.expCtrl, self.ribbon
):
obj.theme = self.theme
if hasattr(obj, "_applyAppTheme"):
obj._applyAppTheme()
else:
handlers.ThemeMixin._applyAppTheme(obj)
self.Refresh()
def setAlertsVisible(self, new=True):
if new:
self.outputNotebook.SetSelectionToPage(
self.outputNotebook.GetPageIndex(self.alertsPnl)
)
def setStdoutVisible(self, new=True):
if new:
self.outputNotebook.SetSelectionToPage(
self.outputNotebook.GetPageIndex(self.stdoutPnl)
)
def stopTask(self, event=None):
"""Kill script processes currently running."""
# Stop subprocess script running local server
if self.serverProcess is not None:
self.serverProcess.kill()
self.serverProcess = None
# Stop local Runner processes
if self.scriptProcess is not None:
self.stopFile(event)
self.ribbon.buttons['pystop'].Disable()
if self.currentSelection:
self.ribbon.buttons['pyrun'].Enable()
self.ribbon.buttons['pypilot'].Enable()
def onRunShortcut(self, evt=None):
"""
Callback for when the run shortcut is pressed - will either run or pilot depending on run mode
"""
# do nothing if we have no experiment
if self.currentExperiment is None:
return
# run/pilot according to mode
if self.currentExperiment.runMode:
self.runLocal(evt)
else:
self.pilotLocal(evt)
def runLocal(self, evt=None, focusOnExit='runner', args=None):
"""Run experiment from new process using inherited ScriptProcess class methods."""
if self.currentSelection is None:
return
# substitute args
if args is None:
args = []
# start off looking at stdout (will switch to Alerts if there are any)
self.outputNotebook.SetSelectionToWindow(self.stdoutPnl)
currentFile = str(self.currentFile)
if self.currentFile.suffix == '.psyexp':
generateScript(
exp=self.loadExperiment(),
outfile=currentFile.replace('.psyexp', '_lastrun.py')
)
procStarted = self.runFile(
fileName=currentFile,
focusOnExit=focusOnExit,
args=args
)
# Enable/Disable btns
if procStarted:
self.ribbon.buttons['pyrun'].Disable()
self.ribbon.buttons['pypilot'].Disable()
self.ribbon.buttons['pystop'].Enable()
def pilotLocal(self, evt=None, focusOnExit='runner', args=None):
# run in pilot mode
self.runLocal(evt, args=["--pilot"], focusOnExit=focusOnExit)
def runOnline(self, evt=None):
"""Run PsychoJS task from https://pavlovia.org."""
if self.currentProject not in [None, "None", ''] and self.currentFile.suffix == '.psyexp':
webbrowser.open(
"https://pavlovia.org/run/{}/{}"
.format(self.currentProject,
self.outputPath))
def runOnlineDebug(self, evt, port=12002):
"""
Open PsychoJS task on local server running from localhost.
Local debugging is useful before pushing up to Pavlovia.
Parameters
----------
port: int
The port number used for the localhost server
"""
if self.currentSelection is None:
return
# get relevant paths
htmlPath = str(self.currentFile.parent / self.outputPath)
jsFile = self.currentFile.parent / (self.currentFile.stem + ".js")
# make sure JS file exists
if not os.path.exists(jsFile):
generateScript(outfile=str(jsFile),
exp=self.loadExperiment(),
target="PsychoJS")
# start server
self.startServer(htmlPath, port=port)
# open experiment
webbrowser.open("http://localhost:{}".format(port))
# log experiment open
print(
f"##### Running PsychoJS task from {htmlPath} on port {port} #####\n"
)
def startServer(self, htmlPath, port=12002):
# we only want one server process open
if self.serverProcess is not None:
self.killServer()
# get PsychoJS libs
self.getPsychoJS()
# construct command
command = [sys.executable, "-m", "http.server", str(port)]
# open server
self.serverPort = port
self.serverProcess = Popen(
command,
bufsize=1,
cwd=htmlPath,
stdout=PIPE,
stderr=PIPE,
shell=False,
universal_newlines=True,
)
time.sleep(.1)
# log server start
logging.info(f"Local server started on port {port} in directory {htmlPath}")
def killServer(self):
# we can only close if there is a process
if self.serverProcess is None:
return
# kill subprocess
self.serverProcess.terminate()
time.sleep(.1)
# log server stopped
logging.info(f"Local server on port {self.serverPort} stopped")
# reset references to server stuff
self.serverProcess = None
self.serverPort = None
def onURL(self, evt):
self.parent.onURL(evt)
def getPsychoJS(self, useVersion=''):
"""
Download and save the current version of the PsychoJS library.
Useful for debugging, amending scripts.
"""
libPath = self.currentFile.parent / self.outputPath / 'lib'
ver = versions.getPsychoJSVersionStr(self.app.version, useVersion)
libFileExtensions = ['css', 'iife.js', 'iife.js.map', 'js', 'js.LEGAL.txt', 'js.map']
try: # ask-for-forgiveness rather than query-then-make
os.makedirs(libPath)
except OSError as e:
if e.errno != errno.EEXIST: # we only want to ignore "exists", not others like permissions
raise # raises the error again
for ext in libFileExtensions:
finalPath = libPath / ("psychojs-{}.{}".format(ver, ext))
if finalPath.exists():
continue
url = "https://lib.pavlovia.org/psychojs-{}.{}".format(ver, ext)
req = requests.get(url)
with open(finalPath, 'wb') as f:
f.write(req.content)
print("##### PsychoJS libs downloaded to {} #####\n".format(libPath))
def addTask(self, evt=None, fileName=None, runMode="run"):
"""
Add task to the expList listctrl.
Only adds entry if current entry does not exist in list.
Can be passed a filename to add to the list.
Parameters
----------
evt: wx.Event
fileName: str
Filename of task to add to list
"""
if fileName: # Filename passed from outside runner
if Path(fileName).suffix not in ['.py', '.psyexp']:
print("##### You can only add Python files or psyexp files to the Runner. #####\n")
return
filePaths = [fileName]
else:
with wx.FileDialog(self, "Open task...", wildcard="Tasks (*.py;*.psyexp)|*.py;*.psyexp",
style=wx.FD_MULTIPLE | wx.FD_FILE_MUST_EXIST) as fileDialog:
if fileDialog.ShowModal() == wx.ID_CANCEL:
return # the user changed their mind
filePaths = fileDialog.GetPaths()
for thisFile in filePaths:
thisFile = Path(thisFile)
if thisFile.absolute() in self.entries:
thisIndex = self.entries[thisFile.absolute()]['index']
else:
# Set new item in listCtrl
thisIndex = self.expCtrl.InsertItem(self.expCtrl.GetItemCount(),
str(thisFile.name)) # implicitly filenameColumn
self.expCtrl.SetItem(thisIndex, folderColumn, str(thisFile.parent)) # add the folder name
# add the new item to our list of files
self.entries[thisFile.absolute()] = {'index': thisIndex}
# load psyexp
if thisFile.suffix == ".psyexp":
# get run mode from file
if experiment.Experiment.getRunModeFromFile(thisFile):
runMode = "run"
else:
runMode = "pilot"
# set run mode for item
self.expCtrl.SetItem(thisIndex, runModeColumn, runMode)
if filePaths: # set selection to the final item to be added
# Set item selection
# de-select previous
self.expCtrl.SetItemState(self.currentSelection or 0, 0, wx.LIST_STATE_SELECTED)
# select new
self.setSelection(thisIndex) # calls onSelectItem which updates other info
# Set column width
self.expCtrl.SetColumnWidth(filenameColumn, wx.LIST_AUTOSIZE)
self.expCtrl.SetColumnWidth(folderColumn, wx.LIST_AUTOSIZE)
self.expCtrl.SetColumnWidth(runModeColumn, wx.LIST_AUTOSIZE)
self.expCtrl.Refresh()
def removeTask(self, evt):
"""Remove experiment entry from the expList listctrl."""
if self.currentSelection is None:
self.currentProject = None
return
if self.expCtrl.GetItemCount() == 0:
self.currentSelection = None
self.currentFile = None
self.currentExperiment = None
self.currentProject = None
del self.entries[self.currentFile] # remove from our tracking dictionary
self.expCtrl.DeleteItem(self.currentSelection) # from wx control
self.app.updateWindowMenu()
def onRunModeToggle(self, evt):
"""
Function to execute when switching between pilot and run modes
"""
mode = evt.GetInt()
# update buttons
# show/hide run buttons
for key in ("pyrun", "jsrun"):
self.ribbon.buttons[key].Show(mode)
# hide/show pilot buttons
for key in ("pypilot", "jspilot"):
self.ribbon.buttons[key].Show(not mode)
# update experiment mode
if self.currentExperiment is not None:
# find any Builder windows with this experiment open
for frame in self.app.getAllFrames(frameType='builder'):
if frame.exp == self.currentExperiment:
frame.ribbon.buttons['pyswitch'].setMode(mode)
# update current selection
runMode = "pilot"
if mode:
runMode = "run"
self.expCtrl.SetItem(self.currentSelection, runModeColumn, runMode)
# update
self.ribbon.Update()
self.ribbon.Refresh()
self.ribbon.Layout()
def setSelection(self, index):
self.expCtrl.Select(index)
self.onItemSelected(index)
def onItemSelected(self, evt):
"""Set currentSelection to index of currently selected list item."""
if not isinstance(evt, int):
evt = evt.Index
self.currentSelection = evt
filename = self.expCtrl.GetItemText(self.currentSelection, filenameColumn)
folder = self.expCtrl.GetItemText(self.currentSelection, folderColumn)
runMode = self.expCtrl.GetItemText(self.currentSelection, runModeColumn)
self.currentFile = Path(folder, filename)
self.currentExperiment = self.loadExperiment()
self.currentProject = None # until it's needed (slow to update)
# thisItem = self.entries[self.currentFile]
self.ribbon.buttons['remove'].Enable()
# enable run/pilot ctrls
self.ribbon.buttons['pyswitch'].Enable()
self.ribbon.buttons['pyrun'].Enable()
self.ribbon.buttons['pypilot'].Enable()
# enable JS run
if self.currentFile.suffix == '.psyexp':
self.ribbon.buttons['jsrun'].Enable()
self.ribbon.buttons['jspilot'].Enable()
else:
self.ribbon.buttons['jsrun'].Disable()
self.ribbon.buttons['jspilot'].Disable()
# disable stop
self.ribbon.buttons['pystop'].Disable()
# switch mode
self.ribbon.buttons['pyswitch'].setMode(runMode == "run", silent=True)
# update
self.updateAlerts()
self.app.updateWindowMenu()
self.ribbon.Update()
self.ribbon.Refresh()
self.ribbon.Layout()
def onItemDeselected(self, evt):
"""Set currentSelection, currentFile, currentExperiment and currentProject to None."""
self.expCtrl.SetItemState(self.currentSelection, 0, wx.LIST_STATE_SELECTED)
self.currentSelection = None
self.currentFile = None
self.currentExperiment = None
self.currentProject = None
self.ribbon.buttons['pyswitch'].Disable()
self.ribbon.buttons['pyrun'].Disable()
self.ribbon.buttons['pypilot'].Disable()
self.ribbon.buttons['jsrun'].Disable()
self.ribbon.buttons['jspilot'].Disable()
self.ribbon.buttons['remove'].Disable()
self.app.updateWindowMenu()
def updateAlerts(self):
prev = sys.stdout
# check for alerts
sys.stdout = sys.stderr = self.alertsCtrl
self.alertsCtrl.Clear()
if hasattr(self.currentExperiment, 'integrityCheck'):
self.currentExperiment.integrityCheck()
nAlerts = len(self.alertsCtrl.alerts)
else:
nAlerts = 0
# update labels and text accordingly
sys.stdout.flush()
sys.stdout = sys.stderr = prev
if nAlerts == 0:
self.setAlertsVisible(False)
def onDoubleClick(self, evt):
self.currentSelection = evt.Index
filename = self.expCtrl.GetItem(self.currentSelection, filenameColumn).Text
folder = self.expCtrl.GetItem(self.currentSelection, folderColumn).Text
filepath = os.path.join(folder, filename)
if filename.endswith('psyexp'):
# do we have that file already in a frame?
builderFrames = self.app.getAllFrames("builder")
for frame in builderFrames:
if filepath == frame.filename:
frame.Show(True)
frame.Raise()
self.app.SetTopWindow(frame)
return # we're done
# that file isn't open so look for a blank frame to reuse
for frame in builderFrames:
if frame.filename == 'untitled.psyexp' and frame.lastSavedCopy is None:
frame.fileOpen(filename=filepath)
frame.Show(True)
frame.Raise()
self.app.SetTopWindow(frame)
# no reusable frame so make one
self.app.showBuilder(fileList=[filepath])
else:
self.app.showCoder() # ensures that a coder window exists
self.app.coder.setCurrentDoc(filepath)
def onHover(self, evt):
btn = evt.GetEventObject()
btn.SetBackgroundColour(colors.app['bmpbutton_bg_hover'])
btn.SetForegroundColour(colors.app['bmpbutton_fg_hover'])
def offHover(self, evt):
btn = evt.GetEventObject()
btn.SetBackgroundColour(colors.app['panel_bg'])
btn.SetForegroundColour(colors.app['text'])
@property
def outputPath(self):
"""
Access and return html output path saved in Experiment Settings from the current experiment.
Returns
-------
output path: str
The output path, relative to parent folder.
"""
return self.currentExperiment.settings.params['HTML path'].val
def loadExperiment(self):
"""
Load the experiment object for the current psyexp file.
Returns
-------
PsychoPy Experiment object
"""
fileName = str(self.currentFile)
if not os.path.exists(fileName):
raise FileNotFoundError("File not found: {}".format(fileName))
# If not a Builder file, return
if not fileName.endswith('.psyexp'):
return None
# Load experiment file
exp = experiment.Experiment(prefs=self.app.prefs)
try:
exp.loadFromXML(fileName)
except Exception:
print(u"Failed to load {}. Please send the following to"
u" the PsychoPy user list".format(fileName))
traceback.print_exc()
return exp
@property
def currentProject(self):
"""Returns the current project, updating from the git repo if no
project currently found"""
if not self._currentProject:
# Check for project
try:
project = getProject(str(self.currentFile))
if hasattr(project, 'id'):
self._currentProject = project.id
except NotADirectoryError as err:
self.stdoutCtrl.write(err)
return self._currentProject
@currentProject.setter
def currentProject(self, project):
self._currentProject = None
class RunnerOutputNotebook(aui.AuiNotebook, handlers.ThemeMixin):
def __init__(self, parent):
aui.AuiNotebook.__init__(self, parent, style=wx.BORDER_NONE)
# store pages by non-translated names for easy access (see RunnerFrame.getOutputPanel)
self.panels = {}
# Alerts
self.alertsPnl = ScriptOutputPanel(
parent=parent,
style=wx.TE_READONLY | wx.TE_MULTILINE | wx.BORDER_NONE
)
self.alertsPnl.ctrl.Bind(wx.EVT_TEXT, self.onWrite)
self.AddPage(
self.alertsPnl, caption=_translate("Alerts")
)
self.panels['alerts'] = self.alertsPnl
alerts.addAlertHandler(self.alertsPnl.ctrl)
# StdOut
self.stdoutPnl = ScriptOutputPanel(
parent=parent,
style=wx.TE_READONLY | wx.TE_MULTILINE | wx.BORDER_NONE
)
self.stdoutPnl.ctrl.Bind(wx.EVT_TEXT, self.onWrite)
self.AddPage(
self.stdoutPnl, caption=_translate("Stdout")
)
self.panels['stdout'] = self.stdoutPnl
# Git (Pavlovia) output
self.gitPnl = ScriptOutputPanel(
parent=parent,
style=wx.TE_READONLY | wx.TE_MULTILINE | wx.BORDER_NONE
)
self.gitPnl.ctrl.Bind(wx.EVT_TEXT, self.onWrite)
self.AddPage(
self.gitPnl, caption=_translate("Pavlovia")
)
self.panels['git'] = self.gitPnl
# bind function when page receives focus
self._readCache = {}
self.Bind(aui.EVT_AUINOTEBOOK_PAGE_CHANGED, self.onFocus)
# min size is 80 chars / 40 lines
self.SetMinSize(wx.Size(
self.stdoutPnl.GetCharWidth() * 80,
self.stdoutPnl.GetCharHeight() * 40,
))
def setRead(self, i, state):
"""
Mark a tab (by index) as read/unread (determines whether the page gets a little blue dot)
Parameters
----------
i : int
Index of the page to set
state : bool
True for read (i.e. no dot), False for unread (i.e. dot)
"""
# if state matches cached state, don't bother updating again
if self._readCache.get(i, None) == state:
return
# cache read value
self._readCache[i] = state
# get tab label without asterisk
label = self.GetPageText(i).replace(" *", "")
# add/remove asterisk
if state:
self.SetPageText(i, label)
else:
self.SetPageText(i, label + " *")
# update
self.Update()
self.Refresh()
def onWrite(self, evt):
# get ctrl
ctrl = evt.GetEventObject()
# iterate through pages
for i in range(self.GetPageCount()):
# get page window
page = self.GetPage(i)
# is the ctrl a child of that window, and is it deselected?
if page.IsDescendant(ctrl) and self.GetSelection() != i:
# mark unread
self.setRead(i, False)
# alerts and pavlovia get focus too when written to
if page in (self.panels['git'], self.panels['alerts']):
self.SetSelection(i)
def onFocus(self, evt):
# get index of new selection
i = evt.GetSelection()
# set read status
self.setRead(i, True)
class RunnerRibbon(ribbon.FrameRibbon):
def __init__(self, parent):
# initialize
ribbon.FrameRibbon.__init__(self, parent)
# --- File ---
self.addSection(
"list", label=_translate("Manage list"), icon="file"
)
# add experiment
self.addButton(
section="list", name="add", label=_translate("Add"), icon="addExp",
tooltip=_translate("Add experiment to list"),
callback=parent.addTask
)
# remove experiment
self.addButton(
section="list", name="remove", label=_translate("Remove"), icon="removeExp",
tooltip=_translate("Remove experiment from list"),
callback=parent.removeTask
)
# save
self.addButton(
section="list", name="save", label=_translate("Save"), icon="filesaveas",
tooltip=_translate("Save task list to a file"),
callback=parent.parent.saveTaskList
)
# load
self.addButton(
section="list", name="open", label=_translate("Open"), icon="fileopen",
tooltip=_translate("Load tasks from a file"),
callback=parent.parent.loadTaskList
)
self.addSeparator()
# --- Tools ---
self.addSection(
"experiment", label=_translate("Experiment"), icon="experiment"
)
# switch run/pilot
runPilotSwitch = self.addSwitchCtrl(
section="experiment", name="pyswitch",
labels=(_translate("Pilot"), _translate("Run")),
callback=parent.onRunModeToggle,
style=wx.HORIZONTAL
)
self.addSeparator()
# --- Python ---
self.addSection(
"py", label=_translate("Desktop"), icon="desktop"
)
# pilot Py
self.addButton(
section="py", name="pypilot", label=_translate("Pilot"), icon='pyPilot',
tooltip=_translate("Run the current script in Python with piloting features on"),
callback=parent.pilotLocal
).Disable()
# run Py
self.addButton(
section="py", name="pyrun", label=_translate("Run"), icon='pyRun',
tooltip=_translate("Run the current script in Python"),
callback=parent.runLocal
).Disable()
# stop
self.addButton(
section="py", name="pystop", label=_translate("Stop"), icon='stop',
tooltip=_translate("Stop the current (Python) script"),
callback=parent.stopTask
).Disable()
self.addSeparator()
# --- JS ---
self.addSection(
"browser", label=_translate("Browser"), icon="browser"
)
# pilot JS
self.addButton(
section="browser", name="jspilot", label=_translate("Pilot in browser"),
icon='jsPilot',
tooltip=_translate("Pilot experiment locally in your browser"),
callback=parent.runOnlineDebug
).Disable()
# run JS
self.addButton(
section="browser", name="jsrun", label=_translate("Run on Pavlovia"), icon='jsRun',
tooltip=_translate("Run experiment on Pavlovia"),
callback=parent.runOnline
).Disable()
self.addSeparator()
# --- Pavlovia ---
self.addSection(
name="pavlovia", label=_translate("Pavlovia"), icon="pavlovia"
)
# pavlovia user
self.addPavloviaUserCtrl(
section="pavlovia", name="pavuser", frame=parent
)
self.addSeparator()
# --- Plugin sections ---
self.addPluginSections("psychopy.app.builder")
# --- Views ---
self.addStretchSpacer()
self.addSeparator()
self.addSection(
"views", label=_translate("Views"), icon="windows"
)
# show Builder
self.addButton(
section="views", name="builder", label=_translate("Show Builder"), icon="showBuilder",
tooltip=_translate("Switch to Builder view"),
callback=parent.app.showBuilder
)
# show Coder
self.addButton(
section="views", name="coder", label=_translate("Show Coder"), icon="showCoder",
tooltip=_translate("Switch to Coder view"),
callback=parent.app.showCoder
)
# show Runner
self.addButton(
section="views", name="runner", label=_translate("Show Runner"), icon="showRunner",
tooltip=_translate("Switch to Runner view"),
callback=parent.app.showRunner
).Disable()
| 47,702
|
Python
|
.py
| 1,107
| 31.755194
| 108
| 0.587538
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,826
|
scriptProcess.py
|
psychopy_psychopy/psychopy/app/runner/scriptProcess.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Part of the PsychoPy library
# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd.
# Distributed under the terms of the GNU General Public License (GPL).
"""Utilities for running scripts from the PsychoPy application suite.
Usually these are Python scripts, either written by the user in Coder or
compiled from Builder.
"""
__all__ = ['ScriptProcess']
import os.path
import sys
import psychopy.app.jobs as jobs
from wx import BeginBusyCursor, EndBusyCursor, MessageDialog, ICON_ERROR, OK
from psychopy.app.console import StdStreamDispatcher
import psychopy.logging as logging
class ScriptProcess:
"""Class to run and manage user/compiled scripts from the PsychoPy UI.
Currently used as a "mixin" class, so don't create instances of this class
directly for now.
Parameters
----------
app : object
Handle for the application. Used to update UI elements to reflect the
current state of the script.
"""
def __init__(self, app):
self.app = app # reference to the app
self.scriptProcess = None # reference to the `Job` object
self._processEndTime = None # time the process ends
self._focusOnExit = 'runner'
@property
def focusOnExit(self):
"""Which output to focus on when the script exits (`str`)?
"""
return self._focusOnExit
@focusOnExit.setter
def focusOnExit(self, value):
if not isinstance(value, str):
raise TypeError('Property `focusOnExit` must be string.')
elif value not in ('runner', 'coder'):
raise ValueError(
'Property `focusOnExit` must have value either "runner" or '
'"coder"')
self._focusOnExit = value
@property
def running(self):
"""Is there a script running (`bool`)?
"""
# This is an alias for the old `runner` attribute.
if self.scriptProcess is None:
return False
return self.scriptProcess.isRunning
def runFile(self, event=None, fileName=None, focusOnExit='runner', args=None):
"""Begin new process to run experiment.
Parameters
----------
event : wx.Event or None
Parameter for event information if this function is bound as a
callback. Set as `None` if calling directly.
fileName : str
Path to the file to run.
focusOnExit : str
Which output window to focus on when the application exits. Can be
either 'coder' or 'runner'. Default is 'runner'.
Returns
-------
bool
True if the process has been started without error.
"""
# full path to the script
fullPath = fileName.replace('.psyexp', '_lastrun.py')
if not os.path.isfile(fullPath):
fileNotFoundDlg = MessageDialog(
None,
"Cannot run script '{}', file not found!".format(fullPath),
caption="File Not Found Error",
style=OK | ICON_ERROR
)
fileNotFoundDlg.ShowModal()
fileNotFoundDlg.Destroy()
if event is not None:
event.Skip()
return False
# provide a message that the script is running
# format the output message
runMsg = u"## Running: {} ##".format(fullPath)
runMsg = runMsg.center(80, "#") + "\n"
# if we have a runner frame, write to the output text box
if hasattr(self.app, 'runner'):
stdOut = StdStreamDispatcher.getInstance()
stdOut.lenLastRun = len(self.app.runner.stdOut.getText())
else:
# if not, just write to the standard output pipe
stdOut = sys.stdout
stdOut.write(runMsg)
stdOut.flush()
# interpreter path
pyExec = sys.executable
# optional flags for the subprocess
execFlags = jobs.EXEC_ASYNC # all use `EXEC_ASYNC`
if sys.platform == 'win32':
execFlags |= jobs.EXEC_HIDE_CONSOLE
else:
execFlags |= jobs.EXEC_MAKE_GROUP_LEADER
# build the shell command to run the script
# pyExec = '"' + pyExec + '"' # use quotes to prevent issues with spaces
# fullPath = '"' + fullPath + '"'
command = [pyExec, '-u', fullPath] # passed to the Job object
# append args to command
if args is None:
args = []
if isinstance(args, str):
args = [args]
if not isinstance(args, list):
args = list(args)
command += args
# create a new job with the user script
self.scriptProcess = jobs.Job(
self,
command=command,
# flags=execFlags,
inputCallback=self._onInputCallback, # both treated the same
errorCallback=self._onErrorCallback,
terminateCallback=self._onTerminateCallback
)
BeginBusyCursor() # visual feedback
# start the subprocess
workingDir, _ = os.path.split(fullPath)
workingDir = os.path.abspath(workingDir) # make absolute
# move set CWD to Job.__init__ later
pid = self.scriptProcess.start(cwd=workingDir)
if pid < 1: # error starting the process on zero or negative PID
errMsg = (
"Failed to run script '{}' in directory '{}'! Check whether "
"the file or its directory exists and is accessible.".format(
fullPath, workingDir)
)
fileNotFoundDlg = MessageDialog(
None,
errMsg,
caption="Run Task Error",
style=OK | ICON_ERROR
)
fileNotFoundDlg.ShowModal()
fileNotFoundDlg.Destroy()
# also log the error
logging.error(errMsg)
if event is not None:
event.Skip()
self.scriptProcess = None # reset
EndBusyCursor()
return False
self.focusOnExit = focusOnExit
return True
def stopFile(self, event=None):
"""Stop the script process.
Parameters
----------
event : wx.Event or None
Parameter for event information if this function is bound as a
callback. Set as `None` if calling directly.
"""
if hasattr(self.app, 'terminateHubProcess'):
self.app.terminateHubProcess()
if self.scriptProcess is not None:
self.scriptProcess.terminate()
# Used to call `_onTerminateCallback` here, but that is now called by
# the `Job` instance when it exits.
def _writeOutput(self, text, flush=True):
"""Write out bytes coming from the current subprocess.
By default, `text` is written to the Runner window output box. If not
available for some reason, text is written to `sys.stdout`.
Parameters
----------
text : str or bytes
Text to write.
flush : bool
Flush text so it shows up immediately on the pipe.
"""
# Make sure we have a string, data from pipes usually comes out as bytes
# so we make the conversion if needed.
if isinstance(text, bytes):
text = text.decode('utf-8')
# Where are we outputting to? Usually this is the Runner window, but if
# not available we just write to `sys.stdout`.
# if hasattr(self.app, 'runner'):
# # get any remaining data on the pipes
# stdOut = self.app.runner.stdOut
# else:
stdOut = StdStreamDispatcher.getInstance()
if stdOut is not None:
# write and flush if needed
stdOut.write(text)
if hasattr(stdOut, 'flush') and flush:
stdOut.flush()
# --------------------------------------------------------------------------
# Callbacks for subprocess events
#
def _onInputCallback(self, streamBytes):
"""Callback to process data from the input stream of the subprocess.
This is called when `~psychopy.app.jobs.Jobs.poll` is called and only if
there is data in the associated pipe.
The default behavior here is to convert the data to a UTF-8 string and
write it to the Runner output window.
Parameters
----------
streamBytes : bytes or str
Data from the 'stdin' streams connected to the subprocess.
"""
self._writeOutput(streamBytes)
def _onErrorCallback(self, streamBytes):
"""Callback to process data from the error stream of the subprocess.
This is called when `~psychopy.app.jobs.Jobs.poll` is called and only if
there is data in the associated pipe.
The default behavior is to call `_onInputCallback`, forwarding argument
`streamBytes` to it. Override this method if you want data from `stderr`
to be treated differently.
Parameters
----------
streamBytes : bytes or str
Data from the 'sdterr' streams connected to the subprocess.
"""
self._onInputCallback(streamBytes)
def _onTerminateCallback(self, pid, exitCode):
"""Callback invoked when the subprocess exits.
Default behavior is to push remaining data to the Runner output window
and show it by raising the Runner window. The 'Stop' button will be
disabled in Runner (if available) since the process has ended and no
longer can be stopped. Also restores the user's cursor to the default.
Parameters
----------
pid : int
Process ID number for the terminated subprocess.
exitCode : int
Program exit code.
"""
# write a close message, shows the exit code if there is one
if exitCode:
closeMsg = (
" Experiment ended with exit code {ec} [pid:{pid}] "
)
else:
closeMsg = (
" Experiment completed [pid:{pid}] "
)
closeMsg = closeMsg.format(ec=exitCode, pid=pid).center(64, '#') + '\n'
self._writeOutput(closeMsg)
self.scriptProcess = None # reset
# disable the stop button after exiting, no longer needed
if hasattr(self, 'toolbar'): # relies on this being a mixin class
self.toolbar.buttons['stopBtn'].Disable()
# reactivate the current selection after running
if hasattr(self, 'expCtrl') and hasattr(self, 'toolbar'):
itemIdx = self.expCtrl.GetFirstSelected()
if itemIdx >= 0:
self.expCtrl.Select(itemIdx)
self.toolbar.buttons['runBtn'].Disable()
def _focusOnOutput(win):
"""Subroutine to focus on a given output window."""
win.Show()
win.Raise()
win.Iconize(False)
# set focus to output window
if self.app is not None:
if self.focusOnExit == 'coder' and hasattr(self.app, 'coder'):
if self.app.coder is not None:
_focusOnOutput(self.app.coder)
self.app.coder.shelf.SetSelection(1) # page for the console output
self.app.coder.shell.SetFocus()
else: # coder is closed, open runner and show output instead
if hasattr(self.app, 'runner') and \
hasattr(self.app, 'showRunner'):
# show runner if available
if self.app.runner is None:
self.app.showRunner()
_focusOnOutput(self.app.runner)
self.app.runner.stdOut.SetFocus()
elif self.focusOnExit == 'runner' and hasattr(self.app, 'runner'):
if self.app.runner is not None:
_focusOnOutput(self.app.runner)
self.app.runner.stdOut.SetFocus()
self.app.runner.panel.ribbon.buttons['pyrun'].Enable()
self.app.runner.panel.ribbon.buttons['pypilot'].Enable()
self.app.runner.panel.ribbon.buttons['pystop'].Disable()
EndBusyCursor()
if __name__ == "__main__":
pass
| 12,448
|
Python
|
.py
| 288
| 32.465278
| 87
| 0.590653
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,827
|
psychopy.xml
|
psychopy_psychopy/psychopy/app/Resources/psychopy.xml
|
<?xml version="1.0" encoding="UTF-8"?>
<mime-info xmlns="http://www.freedesktop.org/standards/shared-mime-info">
<mime-type type="text/x-psyexp">
<comment>psychopy file</comment>
<icon name="psychopy"/>
<glob-deleteall/>
<glob pattern="*.psyexp"/>
</mime-type>
</mime-info>
| 314
|
Python
|
.py
| 9
| 29.444444
| 73
| 0.629508
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,828
|
psychopy.desktop
|
psychopy_psychopy/psychopy/app/Resources/psychopy.desktop
|
[Desktop Entry]
Version=1.90.dev2
Type=Application
Name=PsychoPy
GenericName=PsychoPy
Comment=Psychology software in Python
TryExec=psychopyApp.py
Exec=psychopyApp.py
Categories=Development;Education;Science;Biology;IDE
Icon=psychopy
Terminal=false
StartupNotify=true
MimeType=text/x-python;
| 292
|
Python
|
.py
| 13
| 21.461538
| 52
| 0.896057
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,829
|
moveComponentIcons.py
|
psychopy_psychopy/psychopy/app/Resources/moveComponentIcons.py
|
import os
from os.path import join, split, isdir
import shutil
cmpFolder = join("..", "..", "experiment", "components")
components = os.listdir(cmpFolder)
def shipOut(theme):
"""Move component icons from Resources folders to component folders, allowing themes to be customisable
without requiring component developers to have to deal with each app theme individually"""
# Get origin location & files
orig = join(os.getcwd(), theme, "components")
if isdir(orig):
files = os.listdir(orig)
else:
return
# For each file
for fname in files:
# Check whether it corresponds to a component
stripped = fname.replace("@2x.png", "").replace(".png", "")
if stripped in components:
# Move to corresponding component folder
dest = join(cmpFolder, stripped, theme)
shutil.move(
join(orig, fname),
join(dest, fname)
)
def shipIn(theme):
"""Return component icons from component folders to corresponding Resources folder"""
for comp in components:
# Set destination (Resources folder for this theme)
dest = join(os.getcwd(), theme, "components")
# Get origin location & files
orig = join(cmpFolder, comp, theme)
if isdir(orig) and isdir(dest):
files = os.listdir(orig)
for fname in files:
# Move back to resources folder
shutil.move(
join(orig, fname),
join(dest, fname)
)
# Get all themes
themes = os.listdir(os.getcwd())
# For each theme, if it is valid, perform shipOut
for theme in themes:
if isdir(theme):
shipOut(theme)
| 1,493
|
Python
|
.py
| 46
| 29.630435
| 104
| 0.727839
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,830
|
localizedStrings.py
|
psychopy_psychopy/psychopy/app/builder/localizedStrings.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Part of the PsychoPy library
# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd.
# Distributed under the terms of the GNU General Public License (GPL).
"""
Discover all _localized strings from all Builder components, etc.
Mainly used by validators.py -- need access to _translate()d field names.
"""
import copy
import os
import glob
from psychopy.localization import _localized as _localizedBase
from psychopy.localization import _translate
_localizedCategories = {
'Basic': _translate('Basic'),
'Color': _translate('Color'),
'Layout': _translate('Layout'),
'Data': _translate('Data'),
'Screen': _translate('Screen'),
'Input': _translate('Input'),
'Dots': _translate('Dots'),
'Grating': _translate('Grating'),
'Advanced': _translate('Advanced'),
'Favorites': _translate('Favorites'),
'Stimuli': _translate('Stimuli'),
'Responses': _translate('Responses'),
'I/O': _translate('I/O'),
'Custom': _translate('Custom'),
'Carrier': _translate('Carrier'),
'Envelope': _translate('Envelope'),
'Appearance': _translate('Appearance'),
'Save': _translate('Save'),
'Online':_translate('Online'),
'Testing':_translate('Testing'),
'Audio':_translate('Audio'),
'Format':_translate('Format'),
'Formatting':_translate('Formatting'),
'Eyetracking':_translate('Eyetracking'),
'Target':_translate('Target'),
'Animation':_translate('Animation'),
'Transcription':_translate('Transcription'),
'Timing':_translate('Timing'),
'Playback':_translate('Playback'),
'Window':_translate('Window')
}
_localizedDialogs = {
# strings for all allowedVals (from all components) go here:
# interpolation
'linear': _translate('linear'),
'nearest': _translate('nearest'),
# color spaces (except "named") should not be translated:
'named': _translate('named'),
'rgb': 'rgb', 'dkl': 'dkl', 'lms': 'lms', 'hsv': 'hsv',
'last key': _translate('last key'),
'first key': _translate('first key'),
'all keys': _translate('all keys'),
'nothing': _translate('nothing'),
'last button': _translate('last button'),
'first button': _translate('first button'),
'all buttons': _translate('all buttons'),
'final': _translate('final'),
'on click': _translate('on click'),
'every frame': _translate('every frame'),
'never': _translate('never'),
'from exp settings': _translate('from exp settings'),
'from prefs': _translate('from preferences'),
'circle': _translate('circle'),
'square': _translate('square'), # dots
# dots
'direction': _translate('direction'),
'position': _translate('position'),
'walk': _translate('walk'),
'same': _translate('same'),
'different': _translate('different'),
'experiment': _translate('Experiment'),
'repeat': _translate('repeat'),
'none': _translate('none'),
# startType & stopType:
'time (s)': _translate('time (s)'),
'frame N': _translate('frame N'),
'condition': _translate('condition'),
'duration (s)': _translate('duration (s)'),
'duration (frames)': _translate('duration (frames)'),
# units not translated:
'pix': 'pix', 'deg': 'deg', 'cm': 'cm',
'norm': 'norm', 'height': 'height',
'degFlat': 'degFlat', 'degFlatPos':'degFlatPos',
# background image:
'cover':_translate('cover'),
'contain':_translate('contain'),
'fill':_translate('fill'),
'scale-down':_translate('scale-down'),
# anchor
'center': _translate('center'),
'top-center': _translate('top-center'),
'bottom-center': _translate('bottom-center'),
'center-left': _translate('center-left'),
'center-right': _translate('center-right'),
'top-left': _translate('top-left'),
'top-right': _translate('top-right'),
'bottom-left': _translate('bottom-left'),
'bottom-right': _translate('bottom-right'),
# tex resolution:
'32': '32', '64': '64', '128': '128', '256': '256', '512': '512',
'routine': 'Routine',
# strings for allowedUpdates:
'constant': _translate('constant'),
'set every repeat': _translate('set every repeat'),
'set every frame': _translate('set every frame'),
# strings for allowedVals in settings:
'add': _translate('add'),
'average': _translate('average'),
'avg': _translate('avg'),
'average (no FBO)': _translate('average (no FBO)'), # blend mode
'use prefs': _translate('use prefs'),
'on Sync': _translate('on Sync'), # export HTML
'on Save': _translate('on Save'),
'manually': _translate('manually'),
# Data file delimiter
'auto': _translate('auto'),
'comma': _translate('comma'),
'semicolon': _translate('semicolon'),
'tab': _translate('tab'),
# logging level:
'debug': _translate('debug'),
'info': _translate('info'),
'exp': _translate('exp'),
'data': _translate('data'),
'warning': _translate('warning'),
'error': _translate('error'),
# Clock format:
'Experiment start':_translate('Experiment start'),
'Wall clock':_translate('Wall clock'),
# Experiment info dialog:
'Field': _translate('Field'),
'Default': _translate('Default'),
# Keyboard:
'press': _translate('press'),
'release': _translate('release'),
# Mouse:
'any click': _translate('any click'),
'valid click': _translate('valid click'),
'on valid click': _translate('on valid click'),
'correct click': _translate('correct click'),
'mouse onset':_translate('mouse onset'),
'Routine': _translate('Routine'),
# Joystick:
'joystick onset':_translate('joystick onset'),
# Button:
'every click': _translate('every click'),
'first click': _translate('first click'),
'last click': _translate('last click'),
'button onset': _translate('button onset'),
# Polygon:
'Line': _translate('Line'),
'Triangle': _translate('Triangle'),
'Rectangle': _translate('Rectangle'),
'Circle': _translate('Circle'),
'Cross': _translate('Cross'),
'Star': _translate('Star'),
'Arrow': _translate('Arrow'),
'Regular polygon...': _translate('Regular polygon...'),
'Custom polygon...': _translate('Custom polygon...'),
# Form
'rows': _translate('rows'),
'columns': _translate('columns'),
'custom...': _translate('custom...'),
# Variable component
'first': _translate('first'),
'last': _translate('last'),
'all': _translate('all'),
'average': _translate('average'),
# NameSpace
'one of your Components, Routines, or condition parameters':
_translate('one of your Components, Routines, or condition parameters'),
' Avoid `this`, `these`, `continue`, `Clock`, or `component` in name':
_translate(' Avoid `this`, `these`, `continue`, `Clock`, or `component` in name'),
'Builder variable': _translate('Builder variable'),
'Psychopy module': _translate('Psychopy module'),
'numpy function': _translate('numpy function'),
'python keyword': _translate('python keyword'),
# Eyetracker - ROI
'look at': _translate('look at'),
'look away': _translate('look away'),
'every look': _translate('every look'),
'first look': _translate('first look'),
'last look': _translate('last look'),
'roi onset': _translate('roi onset'),
# Eyetracker - Recording
'Start and Stop': _translate('Start and Stop'),
'Start Only': _translate('Start Only'),
'Stop Only': _translate('Stop Only'),
'None': _translate('None'),
# ResourceManager
'Start and Check': _translate('Start and Check'),
# 'Start Only': _translate('Start Only'), # defined in Eyetracker - Recording
'Check Only': _translate('Check Only'),
# Panorama
'Mouse': _translate('Mouse'),
'Drag': _translate('Drag'),
'Keyboard (Arrow Keys)': _translate('Keyboard (Arrow Keys)'),
'Keyboard (WASD)': _translate('Keyboard (WASD)'),
'Keyboard (Custom keys)': _translate('Keyboard (Custom keys)'),
'Mouse Wheel': _translate('Mouse Wheel'),
'Mouse Wheel (Inverted)': _translate('Mouse Wheel (Inverted)'),
'Keyboard (+-)': _translate('Keyboard (+-)'),
'Custom': _translate('Custom'),
# TextBox
'visible': _translate('visible'),
'scroll': _translate('scroll'),
'hidden': _translate('hidden'),
}
_localized = copy.copy(_localizedBase)
_localized.update(_localizedCategories)
_localized.update(_localizedDialogs)
thisDir = os.path.dirname(os.path.abspath(__file__))
modules = glob.glob(os.path.join(thisDir, 'components', '*.py'))
components = [os.path.basename(m).replace('.py', '') for m in modules
if not m.endswith('patch.py')]
for comp in components:
try:
exec('from psychopy.experiment.components.' + comp + ' import _localized as _loc')
_localized.update(_loc) # noqa: F821 # exists through exec import
except ImportError:
pass
if __name__ == '__main__':
for key, val in _localized.items():
print(key, val)
| 9,043
|
Python
|
.py
| 229
| 34.777293
| 90
| 0.632553
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,831
|
builder.py
|
psychopy_psychopy/psychopy/app/builder/builder.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Defines the behavior of Psychopy's Builder view window
Part of the PsychoPy library
Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd.
Distributed under the terms of the GNU General Public License (GPL).
"""
import collections
import os, sys
import subprocess
import webbrowser
from collections import OrderedDict
from pathlib import Path
import glob
import copy
import traceback
import codecs
from types import SimpleNamespace
import numpy
import requests
import io
from packaging.version import Version
import wx.stc
from wx.lib import scrolledpanel
from wx.lib import platebtn
from wx.html import HtmlWindow
import psychopy.app.plugin_manager.dialog
from .validators import WarningManager
from ..pavlovia_ui import sync, PavloviaMiniBrowser
from ..pavlovia_ui.project import ProjectFrame
from ..pavlovia_ui.search import SearchFrame
from ..pavlovia_ui.user import UserFrame
from ..pavlovia_ui.functions import logInPavlovia
from ...experiment import getAllElements, getAllCategories
from ...experiment.routines import Routine, BaseStandaloneRoutine
from psychopy.tools.versionchooser import parseVersionSafely, psychopyVersion
try:
import markdown_it as md
except ImportError:
md = None
import wx.lib.agw.aui as aui # some versions of phoenix
try:
from wx.adv import PseudoDC
except ImportError:
from wx import PseudoDC
if Version(wx.__version__) < Version('4.0.3'):
wx.NewIdRef = wx.NewId
from psychopy.localization import _translate
from ... import experiment, prefs
from .. import dialogs, utils, ribbon
from ..themes import icons, colors, handlers
from ..themes.ui import ThemeSwitcher
from ..ui import BaseAuiFrame
from psychopy import logging, data
from psychopy.tools.filetools import mergeFolder
from .dialogs import (DlgComponentProperties, DlgExperimentProperties,
DlgCodeComponentProperties, DlgLoopProperties,
ParamNotebook, DlgNewRoutine, BuilderFindDlg)
from ..utils import (BasePsychopyToolbar, HoverButton, ThemedPanel, WindowFrozen,
FileDropTarget, FrameSwitcher, updateDemosMenu,
ToggleButtonArray, HoverMixin)
from psychopy.experiment import getAllStandaloneRoutines
from psychopy.app import pavlovia_ui
from psychopy.projects import pavlovia
from psychopy.tools import stringtools as st
from psychopy.scripts.psyexpCompile import generateScript
# Components which are always hidden
alwaysHidden = [
'SettingsComponent', 'RoutineSettingsComponent', 'UnknownComponent', 'UnknownRoutine',
'UnknownStandaloneRoutine', 'UnknownPluginComponent', 'BaseComponent', 'BaseStandaloneRoutine',
'BaseValidatorRoutine'
]
class TemplateManager(dict):
mainFolder = Path(prefs.paths['resources']).absolute() / 'routine_templates'
userFolder = Path(prefs.paths['userPrefsDir']).absolute() / 'routine_templates'
experimentFiles = {}
def __init__(self):
dict.__init__(self)
self.updateTemplates()
def updateTemplates(self, ):
"""Search and import templates in the standard files"""
for folder in [TemplateManager.mainFolder, TemplateManager.userFolder]:
categs = folder.glob("*.psyexp")
for filePath in categs:
thisExp = experiment.Experiment()
thisExp.loadFromXML(filePath)
categName = filePath.stem
self[categName]={}
for routineName in thisExp.routines:
self[categName][routineName] = copy.copy(thisExp.routines[routineName])
class BuilderFrame(BaseAuiFrame, handlers.ThemeMixin):
"""Defines construction of the Psychopy Builder Frame"""
routineTemplates = TemplateManager()
def __init__(self, parent, id=-1, title='PsychoPy (Experiment Builder)',
pos=wx.DefaultPosition, fileName=None, frameData=None,
style=wx.DEFAULT_FRAME_STYLE, app=None):
if (fileName is not None) and (type(fileName) == bytes):
fileName = fileName.decode(sys.getfilesystemencoding())
self.app = app
self.dpi = self.app.dpi
# things the user doesn't set like winsize etc:
self.appData = self.app.prefs.appData['builder']
# things about the builder that the user can set:
self.prefs = self.app.prefs.builder
self.appPrefs = self.app.prefs.app
self.paths = self.app.prefs.paths
self.frameType = 'builder'
self.fileExists = False
self.filename = fileName
self.htmlPath = None
self.scriptProcess = None
self.stdoutBuffer = None
self.readmeFrame = None
self.generateScript = generateScript
# default window title
self.winTitle = 'PsychoPy Builder (v{})'.format(self.app.version)
if fileName in self.appData['frames']:
self.frameData = self.appData['frames'][fileName]
else: # work out a new frame size/location
dispW, dispH = self.app.getPrimaryDisplaySize()
default = self.appData['defaultFrame']
default['winW'] = int(dispW * 0.75)
default['winH'] = int(dispH * 0.75)
if default['winX'] + default['winW'] > dispW:
default['winX'] = 5
if default['winY'] + default['winH'] > dispH:
default['winY'] = 5
self.frameData = dict(self.appData['defaultFrame']) # copy
# increment default for next frame
default['winX'] += 10
default['winY'] += 10
# we didn't have the key or the win was minimized / invalid
if self.frameData['winH'] == 0 or self.frameData['winW'] == 0:
self.frameData['winX'], self.frameData['winY'] = (0, 0)
if self.frameData['winY'] < 20:
self.frameData['winY'] = 20
BaseAuiFrame.__init__(self, parent=parent, id=id, title=title,
pos=(int(self.frameData['winX']),
int(self.frameData['winY'])),
size=(int(self.frameData['winW']),
int(self.frameData['winH'])),
style=style)
# detect retina displays (then don't use double-buffering)
self.isRetina = \
self.GetContentScaleFactor() != 1 and wx.Platform == '__WXMAC__'
# create icon
if sys.platform != 'darwin':
# doesn't work on darwin and not necessary: handled by app bundle
iconFile = os.path.join(self.paths['resources'], 'builder.ico')
if os.path.isfile(iconFile):
self.SetIcon(wx.Icon(iconFile, wx.BITMAP_TYPE_ICO))
# create our panels
self.flowPanel = FlowPanel(frame=self)
self.flowCanvas = self.flowPanel.canvas
self.routinePanel = RoutinesNotebook(self)
self.componentButtons = ComponentsPanel(self)
self.ribbon = BuilderRibbon(self)
# menus and toolbars
self.menuIDs = SimpleNamespace()
self.makeMenus()
self.CreateStatusBar()
self.SetStatusText("")
# setup universal shortcuts
accelTable = self.app.makeAccelTable()
self.SetAcceleratorTable(accelTable)
# setup a default exp
if self.filename.is_file():
self.fileOpen(filename=fileName, closeCurrent=False)
else:
self.lastSavedCopy = None
# don't try to close before opening
self.fileNew(closeCurrent=False)
self.updateReadme() # check/create frame as needed
# control the panes using aui manager
self._mgr = self.getAuiManager()
#self._mgr.SetArtProvider(PsychopyDockArt())
#self._art = self._mgr.GetArtProvider()
# Create panels
self._mgr.AddPane(self.ribbon,
aui.AuiPaneInfo().
Name("Ribbon").
DockFixed(True).
CloseButton(False).MaximizeButton(True).PaneBorder(False).CaptionVisible(False).
Top()
)
self._mgr.AddPane(self.routinePanel,
aui.AuiPaneInfo().
Name("Routines").Caption("Routines").CaptionVisible(True).
Floatable(False).
Movable(False).
CloseButton(False).MaximizeButton(True).PaneBorder(False).
Center()) # 'center panes' expand
rtPane = self._mgr.GetPane('Routines')
self._mgr.AddPane(self.componentButtons,
aui.AuiPaneInfo().
Name("Components").Caption("Components").CaptionVisible(True).
Floatable(False).
RightDockable(True).LeftDockable(True).
CloseButton(False).PaneBorder(False))
compPane = self._mgr.GetPane('Components')
self._mgr.AddPane(self.flowPanel,
aui.AuiPaneInfo().
Name("Flow").Caption("Flow").CaptionVisible(True).
BestSize((8 * self.dpi, 2 * self.dpi)).
Floatable(False).
RightDockable(True).LeftDockable(True).
CloseButton(False).PaneBorder(False))
flowPane = self._mgr.GetPane('Flow')
self.layoutPanes()
rtPane.CaptionVisible(True)
# tell the manager to 'commit' all the changes just made
self._mgr.Update()
# self.SetSizer(self.mainSizer) # not necessary for aui type controls
if self.frameData['auiPerspective']:
self._mgr.LoadPerspective(self.frameData['auiPerspective'])
self.SetMinSize(wx.Size(600, 400)) # min size for the whole window
self.SetSize(
(int(self.frameData['winW']), int(self.frameData['winH'])))
self.SendSizeEvent()
self._mgr.GetPane("Ribbon").Show()
self._mgr.Update()
# self.SetAutoLayout(True)
self.Bind(wx.EVT_CLOSE, self.closeFrame)
self.Bind(wx.EVT_SIZE, self.onResize)
self.Bind(wx.EVT_SHOW, self.onShow)
self.app.trackFrame(self)
self.SetDropTarget(FileDropTarget(targetFrame=self))
self.theme = colors.theme
@property
def session(self):
"""
Current Pavlovia session
"""
return pavlovia.getCurrentSession()
# Synonymise Aui manager for use with theme mixin
def GetAuiManager(self):
return self._mgr
def makeMenus(self):
"""
Produces Menus for the Builder Frame
"""
# ---Menus---#000000#FFFFFF-------------------------------------------
menuBar = wx.MenuBar()
# ---_file---#000000#FFFFFF-------------------------------------------
self.fileMenu = wx.Menu()
menuBar.Append(self.fileMenu, _translate('&File'))
# create a file history submenu
self.fileHistoryMaxFiles = 10
self.fileHistory = wx.FileHistory(maxFiles=self.fileHistoryMaxFiles)
self.recentFilesMenu = wx.Menu()
self.fileHistory.UseMenu(self.recentFilesMenu)
for filename in self.appData['fileHistory']:
if os.path.exists(filename):
self.fileHistory.AddFileToHistory(filename)
self.Bind(wx.EVT_MENU_RANGE, self.OnFileHistory,
id=wx.ID_FILE1, id2=wx.ID_FILE9)
keys = self.app.keys
menu = self.fileMenu
menu.Append(
wx.ID_NEW,
_translate("&New\t%s") % keys['new'])
menu.Append(
wx.ID_OPEN,
_translate("&Open...\t%s") % keys['open'])
menu.AppendSubMenu(
self.recentFilesMenu,
_translate("Open &Recent"))
menu.Append(
wx.ID_SAVE,
_translate("&Save\t%s") % keys['save'],
_translate("Save current experiment file"))
menu.Append(
wx.ID_SAVEAS,
_translate("Save &as...\t%s") % keys['saveAs'],
_translate("Save current experiment file as..."))
# export html
self.menuIDs.ID_EXPORT_HTML = wx.NewIdRef(count=1)
menu.Append(
self.menuIDs.ID_EXPORT_HTML,
_translate("Export HTML...\t%s") % keys['exportHTML'],
_translate("Export experiment to html/javascript file")
)
self.Bind(wx.EVT_MENU, self.fileExport, id=self.menuIDs.ID_EXPORT_HTML)
# reveal folder
self.menuIDs.ID_REVEAL = wx.NewIdRef(count=1)
menu.Append(
self.menuIDs.ID_REVEAL,
_translate("Reveal in file explorer..."),
_translate("Open the folder containing this experiment in your system's file explorer")
)
self.Bind(wx.EVT_MENU, self.fileReveal, id=self.menuIDs.ID_REVEAL)
menu.Append(
wx.ID_CLOSE,
_translate("&Close file\t%s") % keys['close'],
_translate("Close current experiment"))
self.Bind(wx.EVT_MENU, self.app.newBuilderFrame, id=wx.ID_NEW)
self.Bind(wx.EVT_MENU, self.fileSave, id=wx.ID_SAVE)
menu.Enable(wx.ID_SAVE, False)
self.Bind(wx.EVT_MENU, self.fileSaveAs, id=wx.ID_SAVEAS)
self.Bind(wx.EVT_MENU, self.fileOpen, id=wx.ID_OPEN)
self.Bind(wx.EVT_MENU, self.commandCloseFrame, id=wx.ID_CLOSE)
self.fileMenu.AppendSeparator()
item = menu.Append(
wx.ID_PREFERENCES,
_translate("&Preferences\t%s") % keys['preferences'])
self.Bind(wx.EVT_MENU, self.app.showPrefs, item)
item = menu.Append(
wx.ID_ANY, _translate("Reset preferences...")
)
self.Bind(wx.EVT_MENU, self.resetPrefs, item)
# item = menu.Append(wx.NewIdRef(count=1), "Plug&ins")
# self.Bind(wx.EVT_MENU, self.pluginManager, item)
self.fileMenu.AppendSeparator()
self.fileMenu.Append(wx.ID_EXIT,
_translate("&Quit\t%s") % keys['quit'],
_translate("Terminate the program"))
self.Bind(wx.EVT_MENU, self.quit, id=wx.ID_EXIT)
# ------------- edit ------------------------------------
self.editMenu = wx.Menu()
menuBar.Append(self.editMenu, _translate('&Edit'))
menu = self.editMenu
self._undoLabel = menu.Append(wx.ID_UNDO,
_translate("Undo\t%s") % keys['undo'],
_translate("Undo last action"),
wx.ITEM_NORMAL)
self.Bind(wx.EVT_MENU, self.undo, id=wx.ID_UNDO)
self._redoLabel = menu.Append(wx.ID_REDO,
_translate("Redo\t%s") % keys['redo'],
_translate("Redo last action"),
wx.ITEM_NORMAL)
self.Bind(wx.EVT_MENU, self.redo, id=wx.ID_REDO)
menu.Append(wx.ID_PASTE, _translate("&Paste\t%s") % keys['paste'])
self.Bind(wx.EVT_MENU, self.paste, id=wx.ID_PASTE)
# ---_view---#000000#FFFFFF-------------------------------------------
self.viewMenu = wx.Menu()
menuBar.Append(self.viewMenu, _translate('&View'))
menu = self.viewMenu
# item = menu.Append(wx.ID_ANY,
# _translate("Open Coder view"),
# _translate("Open a new Coder view"))
# self.Bind(wx.EVT_MENU, self.app.showCoder, item)
#
# item = menu.Append(wx.ID_ANY,
# _translate("Open Runner view"),
# _translate("Open the Runner view"))
# self.Bind(wx.EVT_MENU, self.app.showRunner, item)
# menu.AppendSeparator()
item = menu.Append(wx.ID_ANY,
_translate("&Toggle readme\t%s") % self.app.keys[
'toggleReadme'],
_translate("Toggle Readme"))
self.Bind(wx.EVT_MENU, self.toggleReadme, item)
item = menu.Append(wx.ID_ANY,
_translate("&Flow Larger\t%s") % self.app.keys[
'largerFlow'],
_translate("Larger flow items"))
self.Bind(wx.EVT_MENU, self.flowPanel.canvas.increaseSize, item)
item = menu.Append(wx.ID_ANY,
_translate("&Flow Smaller\t%s") % self.app.keys[
'smallerFlow'],
_translate("Smaller flow items"))
self.Bind(wx.EVT_MENU, self.flowPanel.canvas.decreaseSize, item)
item = menu.Append(wx.ID_ANY,
_translate("&Routine Larger\t%s") % keys[
'largerRoutine'],
_translate("Larger routine items"))
self.Bind(wx.EVT_MENU, self.routinePanel.increaseSize, item)
item = menu.Append(wx.ID_ANY,
_translate("&Routine Smaller\t%s") % keys[
'smallerRoutine'],
_translate("Smaller routine items"))
self.Bind(wx.EVT_MENU, self.routinePanel.decreaseSize, item)
menu.AppendSeparator()
# Frame switcher
FrameSwitcher.makeViewSwitcherButtons(menu, frame=self, app=self.app)
# Theme switcher
self.themesMenu = ThemeSwitcher(app=self.app)
menu.AppendSubMenu(self.themesMenu, _translate("&Themes"))
# ---_tools ---#000000#FFFFFF-----------------------------------------
self.toolsMenu = wx.Menu()
menuBar.Append(self.toolsMenu, _translate('&Tools'))
menu = self.toolsMenu
item = menu.Append(wx.ID_ANY,
_translate("Monitor Center"),
_translate("To set information about your monitor"))
self.Bind(wx.EVT_MENU, self.app.openMonitorCenter, item)
item = menu.Append(wx.ID_ANY,
_translate("Compile\t%s") % keys['compileScript'],
_translate("Compile the exp to a script"))
self.Bind(wx.EVT_MENU, self.compileScript, item)
self.bldrRun = menu.Append(wx.ID_ANY,
_translate("Run/pilot\t%s") % keys['runScript'],
_translate("Run the current script"))
self.Bind(wx.EVT_MENU, self.onRunShortcut, self.bldrRun, id=self.bldrRun)
item = menu.Append(wx.ID_ANY,
_translate("Send to runner\t%s") % keys['runnerScript'],
_translate("Send current script to runner"))
self.Bind(wx.EVT_MENU, self.runFile, item)
menu.AppendSeparator()
item = menu.Append(wx.ID_ANY,
_translate("PsychoPy updates..."),
_translate("Update PsychoPy to the latest, or a "
"specific, version"))
self.Bind(wx.EVT_MENU, self.app.openUpdater, item)
item = menu.Append(wx.ID_ANY,
_translate("Plugin/packages manager..."),
_translate("Manage Python packages and optional plugins for PsychoPy"))
self.Bind(wx.EVT_MENU, self.openPluginManager, item)
if hasattr(self.app, 'benchmarkWizard'):
item = menu.Append(wx.ID_ANY,
_translate("Benchmark wizard"),
_translate("Check software & hardware, generate "
"report"))
self.Bind(wx.EVT_MENU, self.app.benchmarkWizard, item)
# ---_experiment---#000000#FFFFFF-------------------------------------
self.expMenu = wx.Menu()
menuBar.Append(self.expMenu, _translate('E&xperiment'))
menu = self.expMenu
item = menu.Append(wx.ID_ANY,
_translate("&New Routine\t%s") % keys['newRoutine'],
_translate("Create a new routine (e.g. the trial "
"definition)"))
self.Bind(wx.EVT_MENU, self.addRoutine, item)
item = menu.Append(wx.ID_ANY,
_translate("&Copy Routine\t%s") % keys[
'copyRoutine'],
_translate("Copy the current routine so it can be "
"used in another exp"),
wx.ITEM_NORMAL)
self.Bind(wx.EVT_MENU, self.onCopyRoutine, item)
item = menu.Append(wx.ID_ANY,
_translate("&Paste Routine\t%s") % keys[
'pasteRoutine'],
_translate("Paste the Routine into the current "
"experiment"),
wx.ITEM_NORMAL)
self.Bind(wx.EVT_MENU, self.onPasteRoutine, item)
item = menu.Append(wx.ID_ANY,
_translate("&Rename Routine\t%s") % keys[
'renameRoutine'],
_translate("Change the name of this routine"))
self.Bind(wx.EVT_MENU, self.renameRoutine, item)
item = menu.Append(wx.ID_ANY,
_translate("Paste Component\t%s") % keys[
'pasteCompon'],
_translate(
"Paste the Component at bottom of the current "
"Routine"),
wx.ITEM_NORMAL)
self.Bind(wx.EVT_MENU, self.onPasteCompon, item)
menu.AppendSeparator()
item = menu.Append(wx.ID_ANY,
_translate("Insert Routine in Flow"),
_translate(
"Select one of your routines to be inserted"
" into the experiment flow"))
self.Bind(wx.EVT_MENU, self.flowPanel.canvas.onInsertRoutine, item)
item = menu.Append(wx.ID_ANY,
_translate("Insert Loop in Flow"),
_translate("Create a new loop in your flow window"))
self.Bind(wx.EVT_MENU, self.flowPanel.canvas.insertLoop, item)
menu.AppendSeparator()
item = menu.Append(wx.ID_ANY,
_translate("&Find in experiment...\t%s") % keys['builderFind'],
_translate("Search the whole experiment for a specific term"))
self.Bind(wx.EVT_MENU, self.onFindInExperiment, item)
item = menu.Append(wx.ID_ANY,
_translate("README..."),
_translate("Add or edit the text shown when your experiment is opened"))
self.Bind(wx.EVT_MENU, self.editREADME, item)
# ---_demos---#000000#FFFFFF------------------------------------------
# for demos we need a dict where the event ID will correspond to a
# filename
self.demosMenu = wx.Menu()
# unpack demos option
menu = self.demosMenu
item = menu.Append(wx.ID_ANY,
_translate("&Unpack Demos..."),
_translate(
"Unpack demos to a writable location (so that"
" they can be run)"))
self.Bind(wx.EVT_MENU, self.demosUnpack, item)
item = menu.Append(wx.ID_ANY,
_translate("Browse on Pavlovia"),
_translate("Get more demos from the online demos "
"repository on Pavlovia")
)
self.Bind(wx.EVT_MENU, self.openPavloviaDemos, item)
item = menu.Append(wx.ID_ANY,
_translate("Open demos folder"),
_translate("Open the local folder where demos are stored")
)
self.Bind(wx.EVT_MENU, self.openLocalDemos, item)
menu.AppendSeparator()
# add any demos that are found in the prefs['demosUnpacked'] folder
updateDemosMenu(self, self.demosMenu, self.prefs['unpackedDemosDir'], ext=".psyexp")
menuBar.Append(self.demosMenu, _translate('&Demos'))
# ---_onlineStudies---#000000#FFFFFF-------------------------------------------
self.pavloviaMenu = pavlovia_ui.menu.PavloviaMenu(parent=self)
menuBar.Append(self.pavloviaMenu, _translate("&Pavlovia.org"))
# ---_window---#000000#FFFFFF-----------------------------------------
self.windowMenu = FrameSwitcher(self)
menuBar.Append(self.windowMenu, _translate("&Window"))
# ---_help---#000000#FFFFFF-------------------------------------------
self.helpMenu = wx.Menu()
menuBar.Append(self.helpMenu, _translate('&Help'))
menu = self.helpMenu
item = menu.Append(wx.ID_ANY,
_translate("&PsychoPy Homepage"),
_translate("Go to the PsychoPy homepage"))
self.Bind(wx.EVT_MENU, self.app.followLink, item)
self.app.urls[item.GetId()] = self.app.urls['psychopyHome']
item = menu.Append(wx.ID_ANY,
_translate("&PsychoPy Builder Help"),
_translate(
"Go to the online documentation for PsychoPy"
" Builder"))
self.Bind(wx.EVT_MENU, self.app.followLink, item)
self.app.urls[item.GetId()] = self.app.urls['builderHelp']
menu.AppendSeparator()
item = menu.Append(wx.ID_ANY,
_translate("&System Info..."),
_translate("Get system information."))
self.Bind(wx.EVT_MENU, self.app.showSystemInfo, id=item.GetId())
menu.AppendSeparator()
menu.Append(wx.ID_ABOUT, _translate(
"&About..."), _translate("About PsychoPy"))
self.Bind(wx.EVT_MENU, self.app.showAbout, id=wx.ID_ABOUT)
item = menu.Append(wx.ID_ANY,
_translate("&News..."),
_translate("News"))
self.Bind(wx.EVT_MENU, self.app.showNews, id=item.GetId())
self.SetMenuBar(menuBar)
def commandCloseFrame(self, event):
"""Defines Builder Frame Closing Event"""
self.Close()
def closeFrame(self, event=None, checkSave=True):
"""Defines Frame closing behavior, such as checking for file
saving"""
# close file first (check for save) but no need to update view
okToClose = self.fileClose(updateViews=False, checkSave=checkSave)
if not okToClose:
if hasattr(event, 'Veto'):
event.Veto()
return
else:
# as of wx3.0 the AUI manager needs to be uninitialised explicitly
self._mgr.UnInit()
# is it the last frame?
lastFrame = len(self.app.getAllFrames()) == 1
quitting = self.app.quitting
if lastFrame and sys.platform != 'darwin' and not quitting:
self.app.quit(event)
else:
self.app.forgetFrame(self)
self.Destroy() # required
# Show Runner if hidden
if self.app.runner is not None:
self.app.showRunner()
self.app.updateWindowMenu()
def quit(self, event=None):
"""quit the app
"""
self.app.quit(event)
def onResize(self, event):
"""Called when the frame is resized."""
self.componentButtons.Refresh()
self.flowPanel.canvas.Refresh()
event.Skip()
def onShow(self, event):
"""Called when the frame is shown"""
event.Skip()
# if README was updated when frame wasn't shown, it won't be show either - so update again
self.updateReadme()
@property
def filename(self):
"""Name of the currently open file"""
return self._filename
@filename.setter
def filename(self, value):
if value is None:
# mark nonexistant
self.fileExists = False
# keep placeholder name for labels and etc.
self._filename = Path("untitled.psyexp")
else:
# path-ise and set
self._filename = Path(value)
# mark existant
self.fileExists = Path(value).is_file()
# enable/disable reveal button
if hasattr(self, "menuIDs"):
self.fileMenu.Enable(self.menuIDs.ID_REVEAL, self.fileExists)
# skip if there's no ribbon
if not hasattr(self, "ribbon"):
return
# enable/disable compile buttons
for key in ('compile_py', 'compile_js'):
if key in self.ribbon.buttons:
self.ribbon.buttons[key].Enable(
self._filename.is_file()
)
def fileNew(self, event=None, closeCurrent=True):
"""Create a default experiment (maybe an empty one instead)
"""
# Note: this is NOT the method called by the File>New menu item.
# That calls app.newBuilderFrame() instead
if closeCurrent: # if no exp exists then don't try to close it
if not self.fileClose(updateViews=False):
# close the existing (and prompt for save if necess)
return False
self.filename = None
self.exp = experiment.Experiment(prefs=self.app.prefs)
defaultName = 'trial'
# create the trial routine as an example
self.exp.addRoutine(defaultName)
self.exp.flow.addRoutine(
self.exp.routines[defaultName], pos=1) # add it to flow
# add it to user's namespace
self.exp.namespace.add(defaultName, self.exp.namespace.user)
routine = self.exp.routines[defaultName]
## add an ISI component by default
# components = self.componentButtons.components
# Static = components['StaticComponent']
# ISI = Static(self.exp, parentName=defaultName, name='ISI',
# startType='time (s)', startVal=0.0,
# stopType='duration (s)', stopVal=0.5)
# routine.addComponent(ISI)
# set run mode silently and update icons
self.ribbon.buttons['pyswitch'].setMode(self.exp.runMode, silent=True)
self.updateRunModeIcons()
# update undo stack
self.resetUndoStack()
self.setIsModified(False)
self.updateAllViews()
self.app.updateWindowMenu()
def fileOpen(self, event=None, filename=None, closeCurrent=True):
"""Open a FileDialog, then load the file if possible.
"""
if filename is None:
# Set wildcard
if sys.platform != 'darwin':
wildcard = _translate("PsychoPy experiments (*.psyexp)|*.psyexp|Any file (*.*)|*.*")
else:
wildcard = _translate("PsychoPy experiments (*.psyexp)|*.psyexp|Any file (*.*)|*")
# get path of current file (or home dir to avoid temp)
initPath = str(self.filename.parent)
if self.fileExists:
dlg = wx.FileDialog(self, message=_translate("Open file ..."),
defaultDir=initPath,
style=wx.FD_OPEN,
wildcard=wildcard)
else:
dlg = wx.FileDialog(self, message=_translate("Open file ..."),
style=wx.FD_OPEN,
wildcard=wildcard)
if dlg.ShowModal() != wx.ID_OK:
return 0
filename = dlg.GetPath()
filename = str(filename)
# did user try to open a script in Builder?
if filename.endswith('.py'):
self.app.showCoder() # ensures that a coder window exists
self.app.coder.setCurrentDoc(filename)
self.app.coder.setFileModified(False)
return
with WindowFrozen(ctrl=self):
# try to pause rendering until all panels updated
if closeCurrent:
if not self.fileClose(updateViews=False):
# close the existing (and prompt for save if necess)
return False
self.exp = experiment.Experiment(prefs=self.app.prefs)
try:
self.exp.loadFromXML(filename)
# set run mode silently and update buttons accordingly
self.ribbon.buttons['pyswitch'].setMode(self.exp.runMode, silent=True)
self.updateRunModeIcons()
except Exception:
print(u"Failed to load {}. Please send the following to"
u" the PsychoPy user list".format(filename))
traceback.print_exc()
logging.flush()
self.resetUndoStack()
self.setIsModified(False)
self.filename = filename
# routinePanel.addRoutinePage() is done in
# routinePanel.redrawRoutines(), called by self.updateAllViews()
# update the views
self.updateAllViews() # if frozen effect will be visible on thaw
# Show README
if self.prefs['alwaysShowReadme']:
# If prefs are to always show README, show if populated
self.updateReadme()
else:
# Otherwise update so we have the object, but don't show until asked
self.updateReadme(show=False)
self.fileHistory.AddFileToHistory(filename)
self.htmlPath = None # so we won't accidentally save to other html exp
if self.app.runner:
self.app.runner.addTask(fileName=self.filename) # Add to Runner
self.project = pavlovia.getProject(filename)
self.app.updateWindowMenu()
def fileReveal(self, evt=None):
"""
Reveal the current file in the system file explorer.
"""
# get current dir
if self.fileExists:
folder = Path(self.filename).parent
else:
folder = Path().home()
# choose a command according to OS
if sys.platform in ['win32']:
comm = "explorer"
elif sys.platform in ['darwin']:
comm = "open"
elif sys.platform in ['linux', 'linux2']:
comm = "dolphin"
# use command to open folder
subprocess.call(f"{comm} {folder}", shell=True)
def fileSave(self, event=None, filename=None):
"""Save file, revert to SaveAs if the file hasn't yet been saved
"""
if filename is None:
filename = self.filename
else:
filename = Path(filename)
if not self.fileExists:
if not self.fileSaveAs(filename):
return False # the user cancelled during saveAs
else:
filename = self.exp.saveToXML(filename)
self.fileHistory.AddFileToHistory(filename)
self.setIsModified(False)
# if export on save then we should have an html file to update
if self._getExportPref('on save') and os.path.split(filename)[0]:
self.filename = filename
self.fileExport(htmlPath=self.htmlPath)
return True
def fileSaveAs(self, event=None, filename=None):
"""Defines Save File as Behavior
"""
shortFilename = self.getShortFilename()
expName = self.exp.getExpName()
if (not expName) or (shortFilename == expName):
usingDefaultName = True
else:
usingDefaultName = False
# force filename to Path
if filename is None:
filename = self.filename
else:
filename = Path(filename)
# get parent and filename
initPath = filename.parent
filename = filename.name
# substitute temp dir for home
if not self.fileExists:
initPath = Path.home()
if sys.platform != 'darwin':
wildcard = _translate("PsychoPy experiments (*.psyexp)|*.psyexp|Any file (*.*)|*.*")
else:
wildcard = _translate("PsychoPy experiments (*.psyexp)|*.psyexp|Any file (*.*)|*")
returnVal = False
dlg = wx.FileDialog(
self, message=_translate("Save file as ..."), defaultDir=str(initPath),
defaultFile=filename, style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT,
wildcard=wildcard)
if dlg.ShowModal() == wx.ID_OK:
newPath = dlg.GetPath()
# update exp name
# if user has not manually renamed experiment
if usingDefaultName:
newShortName = os.path.splitext(
os.path.split(newPath)[1])[0]
self.exp.setExpName(newShortName)
# actually save
self.filename = newPath
self.fileExists = True
self.fileSave(event=None, filename=newPath)
# enable/disable reveal button
if hasattr(self, "menuIDs"):
self.fileMenu.Enable(self.menuIDs.ID_REVEAL, True)
# update pavlovia project
self.project = pavlovia.getProject(filename)
returnVal = 1
dlg.Destroy()
self.updateWindowTitle()
# update README in case the file path has changed
if self.prefs['alwaysShowReadme']:
# if prefs are to always show README, show if populated
self.updateReadme()
else:
# otherwise update so we have the object, but don't show until asked
self.updateReadme(show=False)
return returnVal
def fileExport(self, event=None, htmlPath=None):
"""Exports the script as an HTML file (PsychoJS library)
"""
# get path if not given one
if htmlPath is None:
htmlPath = self._getHtmlPath(self.filename)
if not htmlPath:
return
exportPath = os.path.join(htmlPath, self.exp.name + '.js')
exportPath = self.generateScript(
outfile=exportPath,
exp=self.exp,
target="PsychoJS"
)
# Open exported files
self.app.showCoder(fileList=[exportPath])
self.app.coder.fileReload(event=None, filename=exportPath)
def editREADME(self, event):
if self.filename is None:
dlg = wx.MessageDialog(
self,
_translate("Please save experiment before editing the README file"),
_translate("No readme file"),
wx.OK | wx.ICON_WARNING | wx.CENTRE)
dlg.ShowModal()
else:
self.updateReadme(show=True)
def getShortFilename(self, withExt=False):
"""
Returns the filename without path
Parameters
----------
withExt : bool
Should the returned filename include the file extension? False by default.
"""
# get file stem
shortName = self.filename.stem
ext = self.filename.suffix
# append extension if requested
if withExt:
shortName += ext
return shortName
# def pluginManager(self, evt=None, value=True):
# """Show the plugin manager frame."""
# PluginManagerFrame(self).ShowModal()
def onFindInExperiment(self, evt=None):
dlg = BuilderFindDlg(frame=self, exp=self.exp)
dlg.Show()
def updateReadme(self, show=None):
"""Check whether there is a readme file in this folder and try to show
Parameters
==========
show : bool or None
If True, always show Readme frame.
If False, never show Readme frame.
If None, show only when there is content.
"""
# Make sure we have a file
dirname = self.filename.parent
possibles = list(dirname.glob('readme*'))
if len(possibles) == 0:
possibles = list(dirname.glob('Readme*'))
possibles.extend(dirname.glob('README*'))
# still haven't found a file so use default name
if len(possibles) == 0:
self.readmeFilename = str(dirname / 'readme.md') # use this as our default
else:
self.readmeFilename = str(possibles[0]) # take the first one found
# Make sure we have a frame
if self.readmeFrame is None:
self.readmeFrame = ReadmeFrame(
parent=self, filename=self.readmeFilename
)
# Set file
if self.fileExists:
self.readmeFrame.setFile(self.readmeFilename)
else:
self.readmeFrame.setFile(None)
show = False
self.readmeFrame.ctrl.load()
# Show/hide frame as appropriate
if show is None:
show = len(self.readmeFrame.ctrl.getValue()) > 0
show = show and self.IsShown()
self.readmeFrame.show(show)
def showReadme(self, evt=None, value=True):
"""Shows Readme file
"""
if not self.readmeFrame.IsShown():
self.readmeFrame.show(value)
def toggleReadme(self, evt=None):
"""Toggles visibility of Readme file
"""
if self.readmeFrame is None:
self.showReadme()
else:
self.readmeFrame.toggleVisible()
def OnFileHistory(self, evt=None):
"""get the file based on the menu ID
"""
fileNum = evt.GetId() - wx.ID_FILE1
path = self.fileHistory.GetHistoryFile(fileNum)
self.fileOpen(filename=path)
# add it back to the history so it will be moved up the list
self.fileHistory.AddFileToHistory(path)
def checkSave(self):
"""Check whether we need to save before quitting
"""
if hasattr(self, 'isModified') and self.isModified and not self.app.testMode:
self.Show(True)
self.Raise()
self.app.SetTopWindow(self)
msg = _translate('Experiment %s has changed. Save before '
'quitting?') % self.filename
dlg = dialogs.MessageDialog(self, msg, type='Warning')
resp = dlg.ShowModal()
if resp == wx.ID_CANCEL:
return False # return, don't quit
elif resp == wx.ID_YES:
if not self.fileSave():
return False # user might cancel during save
elif resp == wx.ID_NO:
pass # don't save just quit
return True
def fileClose(self, event=None, checkSave=True, updateViews=True):
"""This is typically only called when the user x
"""
if checkSave:
ok = self.checkSave()
if not ok:
return False # user cancelled
if self.filename is None:
frameData = self.appData['defaultFrame']
else:
frameData = dict(self.appData['defaultFrame'])
self.appData['prevFiles'].append(self.filename)
# get size and window layout info
if self.IsIconized():
self.Iconize(False) # will return to normal mode to get size info
frameData['state'] = 'normal'
elif self.IsMaximized():
# will briefly return to normal mode to get size info
self.Maximize(False)
frameData['state'] = 'maxim'
else:
frameData['state'] = 'normal'
frameData['auiPerspective'] = self._mgr.SavePerspective()
frameData['winW'], frameData['winH'] = self.GetSize()
frameData['winX'], frameData['winY'] = self.GetPosition()
# truncate history to the recent-most last N unique files, where
# N = self.fileHistoryMaxFiles, as defined in makeMenus()
for ii in range(self.fileHistory.GetCount()):
self.appData['fileHistory'].append(
self.fileHistory.GetHistoryFile(ii))
# fileClose gets calls multiple times, so remove redundancy
# while preserving order; end of the list is recent-most:
tmp = []
fhMax = self.fileHistoryMaxFiles
for f in self.appData['fileHistory'][-3 * fhMax:]:
if f not in tmp:
tmp.append(f)
self.appData['fileHistory'] = copy.copy(tmp[-fhMax:])
# assign the data to this filename
self.appData['frames'][str(self.filename)] = frameData
# save the display data only for those frames in the history:
tmp2 = {}
for f in self.appData['frames']:
if f in self.appData['fileHistory']:
tmp2[f] = self.appData['frames'][f]
self.appData['frames'] = copy.copy(tmp2)
# close self
self.routinePanel.removePages()
self.filename = None
# add the current exp as the start point for undo:
self.resetUndoStack()
if updateViews:
self.updateAllViews()
return 1
def updateAllViews(self):
"""Updates Flow Panel, Routine Panel, and Window Title simultaneously
"""
self.flowPanel.canvas.draw()
self.routinePanel.redrawRoutines()
self.componentButtons.Refresh()
self.updateWindowTitle()
def layoutPanes(self):
# Get panes
flowPane = self._mgr.GetPane('Flow')
compPane = self._mgr.GetPane('Components')
rtPane = self._mgr.GetPane('Routines')
# Arrange panes according to prefs
if 'FlowBottom' in self.prefs['builderLayout']:
flowPane.Bottom()
elif 'FlowTop' in self.prefs['builderLayout']:
flowPane.Top()
if 'CompRight' in self.prefs['builderLayout']:
compPane.Right()
if 'CompLeft' in self.prefs['builderLayout']:
compPane.Left()
rtPane.Center()
# Commit
self._mgr.Update()
def resetPrefs(self, event):
"""Reset preferences to default"""
# Present "are you sure" dialog
dlg = wx.MessageDialog(
self, _translate(
"Are you sure you want to reset your preferences? This cannot "
"be undone."),
caption="Reset Preferences...",
style=wx.ICON_WARNING | wx.CANCEL)
dlg.SetOKCancelLabels(
_translate("I'm sure"),
_translate("Wait, go back!")
)
if dlg.ShowModal() == wx.ID_OK:
# If okay is pressed, remove prefs file (meaning a new one will be
# created on next restart)
os.remove(prefs.paths['userPrefsFile'])
# Show confirmation
dlg = wx.MessageDialog(
self, _translate(
"Done! Your preferences have been reset. Changes will be "
"applied when you next open PsychoPy."))
dlg.ShowModal()
else:
pass
def updateWindowTitle(self, newTitle=None):
"""Defines behavior to update window Title
"""
if newTitle is None:
newTitle = self.getShortFilename(withExt=True)
self.setTitle(title=self.winTitle, document=newTitle)
def setIsModified(self, newVal=None):
"""Sets current modified status and updates save icon accordingly.
This method is called by the methods fileSave, undo, redo,
addToUndoStack and it is usually preferably to call those
than to call this directly.
Call with ``newVal=None``, to only update the save icon(s)
"""
if newVal is None:
newVal = self.getIsModified()
else:
self.isModified = newVal
# get ribbon buttons
if 'save' in self.ribbon.buttons:
self.ribbon.buttons['save'].Enable(newVal)
self.fileMenu.Enable(wx.ID_SAVE, newVal)
def getIsModified(self):
"""Checks if changes were made"""
return self.isModified
def resetUndoStack(self):
"""Reset the undo stack. do *immediately after* creating a new exp.
Implicitly calls addToUndoStack() using the current exp as the state
"""
self.currentUndoLevel = 1 # 1 is current, 2 is back one setp...
self.currentUndoStack = []
self.addToUndoStack()
self.updateUndoRedo()
self.setIsModified(newVal=False) # update save icon if needed
def addToUndoStack(self, action="", state=None):
"""Add the given ``action`` to the currentUndoStack, associated
with the @state@. ``state`` should be a copy of the exp
from *immediately after* the action was taken.
If no ``state`` is given the current state of the experiment is used.
If we are at end of stack already then simply append the action. If
not (user has done an undo) then remove orphan actions and append.
"""
if state is None:
state = copy.deepcopy(self.exp)
# remove actions from after the current level
if self.currentUndoLevel > 1:
self.currentUndoStack = self.currentUndoStack[
:-(self.currentUndoLevel - 1)]
self.currentUndoLevel = 1
# append this action
self.currentUndoStack.append({'action': action, 'state': state})
self.setIsModified(newVal=True) # update save icon if needed
self.updateUndoRedo()
def undo(self, event=None):
"""Step the exp back one level in the @currentUndoStack@ if possible,
and update the windows.
Returns the final undo level (1=current, >1 for further in past)
or -1 if redo failed (probably can't undo)
"""
if self.currentUndoLevel >= len(self.currentUndoStack):
return -1 # can't undo
self.currentUndoLevel += 1
state = self.currentUndoStack[-self.currentUndoLevel]['state']
self.exp = copy.deepcopy(state)
self.updateAllViews()
self.setIsModified(newVal=True) # update save icon if needed
self.updateUndoRedo()
return self.currentUndoLevel
def redo(self, event=None):
"""Step the exp up one level in the @currentUndoStack@ if possible,
and update the windows.
Returns the final undo level (0=current, >0 for further in past)
or -1 if redo failed (probably can't redo)
"""
if self.currentUndoLevel <= 1:
return -1 # can't redo, we're already at latest state
self.currentUndoLevel -= 1
self.exp = copy.deepcopy(
self.currentUndoStack[-self.currentUndoLevel]['state'])
self.updateUndoRedo()
self.updateAllViews()
self.setIsModified(newVal=True) # update save icon if needed
return self.currentUndoLevel
def paste(self, event=None):
"""This receives paste commands for all child dialog boxes as well
"""
foc = self.FindFocus()
if hasattr(foc, 'Paste'):
foc.Paste()
def updateUndoRedo(self):
"""Defines Undo and Redo commands for the window
"""
undoLevel = self.currentUndoLevel
# check undo
if undoLevel >= len(self.currentUndoStack):
# can't undo if we're at top of undo stack
label = _translate("Undo\t%s") % self.app.keys['undo']
enable = False
else:
action = self.currentUndoStack[-undoLevel]['action']
txt = _translate("Undo %(action)s\t%(key)s")
fmt = {'action': action, 'key': self.app.keys['undo']}
label = txt % fmt
enable = True
self._undoLabel.SetItemLabel(label)
if 'undo' in self.ribbon.buttons:
self.ribbon.buttons['undo'].Enable(enable)
self.editMenu.Enable(wx.ID_UNDO, enable)
# check redo
if undoLevel == 1:
label = _translate("Redo\t%s") % self.app.keys['redo']
enable = False
else:
action = self.currentUndoStack[-undoLevel + 1]['action']
txt = _translate("Redo %(action)s\t%(key)s")
fmt = {'action': action, 'key': self.app.keys['redo']}
label = txt % fmt
enable = True
self._redoLabel.SetItemLabel(label)
if 'redo' in self.ribbon.buttons:
self.ribbon.buttons['redo'].Enable(enable)
self.editMenu.Enable(wx.ID_REDO, enable)
def demosUnpack(self, event=None):
"""Get a folder location from the user and unpack demos into it."""
# choose a dir to unpack in
dlg = wx.DirDialog(parent=self, message=_translate(
"Location to unpack demos"))
if dlg.ShowModal() == wx.ID_OK:
unpackFolder = dlg.GetPath()
else:
return -1 # user cancelled
# ensure it's an empty dir:
if os.listdir(unpackFolder) != []:
unpackFolder = os.path.join(unpackFolder, 'PsychoPy3 Demos')
if not os.path.isdir(unpackFolder):
os.mkdir(unpackFolder)
mergeFolder(os.path.join(self.paths['demos'], 'builder'),
unpackFolder)
self.prefs['unpackedDemosDir'] = unpackFolder
self.app.prefs.saveUserPrefs()
updateDemosMenu(self, self.demosMenu, self.prefs['unpackedDemosDir'],
ext=".psyexp")
def demoLoad(self, event=None):
"""Defines Demo Loading Event."""
fileDir = self.demos[event.GetId()]
files = glob.glob(os.path.join(fileDir, '*.psyexp'))
if len(files) == 0:
print("Found no psyexp files in %s" % fileDir)
else:
self.fileOpen(event=None, filename=files[0], closeCurrent=True)
def openLocalDemos(self, event=None):
# Choose a command according to OS
if sys.platform in ['win32']:
comm = "explorer"
elif sys.platform in ['darwin']:
comm = "open"
elif sys.platform in ['linux', 'linux2']:
comm = "dolphin"
# Use command to open themes folder
subprocess.call(f"{comm} {prefs.builder['unpackedDemosDir']}", shell=True)
def openPavloviaDemos(self, event=None):
webbrowser.open("https://pavlovia.org/explore")
def sendToRunner(self, evt=None):
"""
Send the current file to the Runner.
"""
# Check whether file is truly untitled (not just saved as untitled)
if not self.fileExists:
ok = self.fileSave(self.filename)
if not ok:
return False # save file before compiling script
if self.getIsModified():
ok = self.fileSave(self.filename)
if not ok:
return False # save file before compiling script
self.app.showRunner()
self.app.runner.addTask(fileName=self.filename)
self.app.runner.Raise()
self.app.showRunner()
return True
def updateRunModeIcons(self, evt=None):
"""
Function to update run/pilot icons according to run mode
"""
mode = self.ribbon.buttons['pyswitch'].mode
# show/hide run buttons
for key in ("pyrun", "jsrun", "sendRunner"):
self.ribbon.buttons[key].Show(mode)
# hide/show pilot buttons
for key in ("pypilot", "jspilot", "pilotRunner"):
self.ribbon.buttons[key].Show(not mode)
# update
self.ribbon.Layout()
def onRunModeToggle(self, evt):
"""
Function to execute when switching between pilot and run modes
"""
mode = evt.GetInt()
# update icons
self.updateRunModeIcons()
# update experiment mode
if self.exp is not None and self.exp.runMode != mode:
self.exp.runMode = mode
# mark as modified
self.setIsModified(True)
# update
self.ribbon.Update()
self.ribbon.Refresh()
self.ribbon.Layout()
def onRunShortcut(self, evt=None):
"""
Callback for when the run shortcut is pressed - will either run or pilot depending on run mode
"""
# do nothing if we have no experiment
if self.exp is None:
return
# run/pilot according to mode
if self.exp.runMode:
self.runFile(evt)
else:
self.pilotFile(evt)
def runFile(self, event=None):
"""
Send the current file to the Runner and run it.
"""
if self.sendToRunner(event):
self.app.runner.panel.runLocal(event)
def pilotFile(self, event=None):
"""
Send the current file to the Runner and run it in pilot mode.
"""
if self.sendToRunner(event):
self.app.runner.panel.pilotLocal(event)
def onCopyRoutine(self, event=None):
"""copy the current routine from self.routinePanel
to self.app.copiedRoutine.
"""
r = self.routinePanel.getCurrentRoutine().copy()
if r is not None:
self.app.copiedRoutine = r
def onPasteRoutine(self, event=None):
"""Paste the current routine from self.app.copiedRoutine to a new page
in self.routinePanel after prompting for a new name.
"""
if self.app.copiedRoutine is None:
return -1
origName = self.app.copiedRoutine.name
defaultName = self.exp.namespace.makeValid(origName)
msg = _translate('New name for copy of "%(copied)s"? [%(default)s]')
vals = {'copied': origName, 'default': defaultName}
message = msg % vals
dlg = wx.TextEntryDialog(self, message=message,
caption=_translate('Paste Routine'))
if dlg.ShowModal() == wx.ID_OK:
routineName = dlg.GetValue()
if not routineName:
routineName = defaultName
newRoutine = self.app.copiedRoutine.copy()
self.pasteRoutine(newRoutine, routineName)
dlg.Destroy()
def pasteRoutine(self, newRoutine, routineName):
"""
Paste a copied Routine into the current Experiment. Returns a copy of that Routine
"""
newRoutine.name = self.exp.namespace.makeValid(routineName, prefix="routine")
newRoutine.exp = self.exp
# add to the experiment
self.exp.addRoutine(newRoutine.name, newRoutine)
for newComp in newRoutine: # routine == list of components
newName = self.exp.namespace.makeValid(newComp.params['name'])
self.exp.namespace.add(newName)
newComp.params['name'].val = newName
newComp.exp = self.exp
# could do redrawRoutines but would be slower?
self.routinePanel.addRoutinePage(newRoutine.name, newRoutine)
self.routinePanel.setCurrentRoutine(newRoutine)
return newRoutine
def onPasteCompon(self, event=None):
"""
Paste the copied Component (if there is one) into the current
Routine
"""
routinePage = self.routinePanel.getCurrentPage()
routinePage.pasteCompon()
def onURL(self, evt):
"""decompose the URL of a file and line number"""
# "C:\Program Files\wxPython...\samples\hangman\hangman.py"
filename = evt.GetString().split('"')[1]
lineNumber = int(evt.GetString().split(',')[1][5:])
self.app.showCoder()
self.app.coder.gotoLine(filename, lineNumber)
def setExperimentSettings(self, event=None, timeout=None):
"""Defines ability to save experiment settings
"""
component = self.exp.settings
# does this component have a help page?
if hasattr(component, 'url'):
helpUrl = component.url
else:
helpUrl = None
title = '%s Properties' % self.exp.getExpName()
dlg = DlgExperimentProperties(
frame=self, element=component, experiment=self.exp, timeout=timeout)
if dlg.OK:
# add to undo stack
self.addToUndoStack("EDIT experiment settings")
# update run mode
self.ribbon.buttons['pyswitch'].setMode(self.exp.runMode)
# mark modified
self.setIsModified(True)
def addRoutine(self, event=None):
"""Defines ability to add routine in the routine panel
"""
self.routinePanel.createNewRoutine()
def renameRoutine(self, name, event=None):
"""Defines ability to rename routine in the routine panel
"""
# get notebook details
routine = self.routinePanel.GetPage(
self.routinePanel.GetSelection()).routine
oldName = routine.name
msg = _translate("What is the new name for the Routine?")
dlg = wx.TextEntryDialog(self, message=msg, value=oldName,
caption=_translate('Rename'))
if dlg.ShowModal() == wx.ID_OK:
name = dlg.GetValue()
self._doRenameRoutine(oldName=oldName, newName=name)
dlg.Destroy()
def _doRenameRoutine(self, oldName, newName):
# silently auto-adjust the name to be valid, and register in the
# namespace:
name = self.exp.namespace.makeValid(newName, prefix='routine')
if oldName in self.exp.routines:
# Swap old with new names
self.exp.routines[oldName].name = name
self.exp.routines[name] = self.exp.routines.pop(oldName)
self.exp.namespace.rename(oldName, name)
currentRoutine = self.routinePanel.getCurrentPage()
currentRoutineIndex = self.routinePanel.GetPageIndex(currentRoutine)
self.routinePanel.renameRoutinePage(currentRoutineIndex, name)
self.addToUndoStack("`RENAME Routine `%s`" % oldName)
self.flowPanel.canvas.draw()
def compileScript(self, event=None):
"""Defines compile script button behavior"""
# save so we have a file to work off
saved = self.fileSave()
# if save cancelled, return now
if not saved:
return
# construct filename for py file
fullPath = self.filename.parent / (self.exp.name + '.py')
# write script
fullPath = self.generateScript(
outfile=str(fullPath),
exp=self.exp
)
# show it in Coder
self.app.showCoder(fileList=[fullPath]) # make sure coder is visible
self.app.coder.fileReload(event=None, filename=fullPath)
@property
def stdoutFrame(self):
"""
Gets Experiment Runner stdout.
"""
if not self.app.runner:
self.app.runner = self.app.showRunner()
return self.app.runner
def _getHtmlPath(self, filename):
expPath = os.path.split(filename)[0]
if not os.path.isdir(expPath):
retVal = self.fileSave()
if retVal:
return self._getHtmlPath(self.filename)
else:
return False
htmlPath = os.path.join(expPath, self.exp.htmlFolder)
return htmlPath
def _getExportPref(self, pref):
"""Returns True if pref matches exportHTML preference"""
if pref.lower() not in [prefs.lower() for prefs in self.exp.settings.params['exportHTML'].allowedVals]:
raise ValueError("'{}' is not an allowed value for {}".format(pref, 'exportHTML'))
exportHtml = str(self.exp.settings.params['exportHTML'].val).lower()
if exportHtml == pref.lower():
return True
def openPluginManager(self, evt=None):
dlg = psychopy.app.plugin_manager.dialog.EnvironmentManagerDlg(self)
dlg.Show()
# Do post-close checks
dlg.onClose()
def onPavloviaCreate(self, evt=None):
if Path(self.filename).is_file():
# Save file
self.fileSave(self.filename)
# If allowed by prefs, export html and js files
if self._getExportPref('on sync'):
htmlPath = self._getHtmlPath(self.filename)
if htmlPath:
self.fileExport(htmlPath=htmlPath)
else:
return
# Get start path and name from builder/coder if possible
if self.filename:
file = Path(self.filename)
name = file.stem
path = file.parent
else:
name = path = ""
# Open dlg to create new project
createDlg = sync.CreateDlg(self,
user=pavlovia.getCurrentSession().user,
name=name,
path=path)
if createDlg.ShowModal() == wx.ID_OK and createDlg.project is not None:
self.project = createDlg.project
else:
return
# Do first sync
self.onPavloviaSync()
def onPavloviaSync(self, evt=None):
if Path(self.filename).is_file():
# Save file
self.fileSave(self.filename)
# If allowed by prefs, export html and js files
if self._getExportPref('on sync'):
htmlPath = self._getHtmlPath(self.filename)
if htmlPath:
self.fileExport(htmlPath=htmlPath)
else:
return
# Sync
pavlovia_ui.syncProject(parent=self, file=self.filename, project=self.project)
def onPavloviaRun(self, evt=None):
# Sync project
self.onPavloviaSync()
if self.project is not None:
# Update project status
self.project.pavloviaStatus = 'ACTIVATED'
# Run
url = "https://pavlovia.org/run/{}".format(self.project['path_with_namespace'])
wx.LaunchDefaultBrowser(url)
def onPavloviaDebug(self, evt=None):
# Open runner
self.app.showRunner()
runner = self.app.runner
# Make sure we have a current file
if self.getIsModified() or not Path(self.filename).is_file():
saved = self.fileSave()
if not saved:
return
# Send current file to runner
runner.addTask(fileName=self.filename)
# Run debug function from runner
self.app.runner.panel.runOnlineDebug(evt=evt)
@property
def project(self):
"""A PavloviaProject object if one is known for this experiment
"""
if hasattr(self, "_project"):
return self._project
elif self.fileExists:
return pavlovia.getProject(self.filename)
else:
return None
@project.setter
def project(self, project):
self._project = project
self.ribbon.buttons['pavproject'].updateInfo()
class RoutinesNotebook(aui.AuiNotebook, handlers.ThemeMixin):
"""A notebook that stores one or more routines
"""
def __init__(self, frame, id=-1):
self.frame = frame
self.app = frame.app
self.routineMaxSize = 2
self.appData = self.app.prefs.appData
aui.AuiNotebook.__init__(self, frame, id,
agwStyle=aui.AUI_NB_TAB_MOVE | aui.AUI_NB_CLOSE_ON_ACTIVE_TAB | aui.AUI_NB_WINDOWLIST_BUTTON)
self.Bind(aui.EVT_AUINOTEBOOK_PAGE_CLOSE, self.onClosePane)
self.Bind(aui.EVT_AUINOTEBOOK_END_DRAG, self.onMoveTab)
# double buffered better rendering except if retina
self.SetDoubleBuffered(not self.frame.isRetina)
# This needs to be done on init, otherwise it gets an outline
self.GetAuiManager().SetArtProvider(handlers.PsychopyDockArt())
if not hasattr(self.frame, 'exp'):
return # we haven't yet added an exp
def getCurrentRoutine(self):
routinePage = self.getCurrentPage()
if routinePage:
return routinePage.routine # no routine page
return None
def setCurrentRoutine(self, routine):
for ii in range(self.GetPageCount()):
if routine is self.GetPage(ii).routine:
self.SetSelection(ii)
self.frame.flowPanel.canvas.draw()
def SetSelection(self, index, force=False):
aui.AuiNotebook.SetSelection(self, index, force=force)
self.frame.componentButtons.enableComponents(
not isinstance(self.GetPage(index).routine, BaseStandaloneRoutine)
)
def getCurrentPage(self):
if self.GetSelection() >= 0:
return self.GetPage(self.GetSelection())
return None
def addRoutinePage(self, routineName, routine):
# Make page
routinePage = None
if isinstance(routine, Routine):
routinePage = RoutineCanvas(notebook=self, routine=routine)
elif isinstance(routine, BaseStandaloneRoutine):
routinePage = StandaloneRoutineCanvas(parent=self, routine=routine)
# Add page
if routinePage:
self.AddPage(routinePage, routineName)
def renameRoutinePage(self, index, newName, ):
self.SetPageText(index, newName)
def removePages(self):
for ii in range(self.GetPageCount()):
currId = self.GetSelection()
self.DeletePage(currId)
def createNewRoutine(self, template=None):
msg = _translate("What is the name for the new Routine? "
"(e.g. instr, trial, feedback)")
dlg = DlgNewRoutine(self)
routineName = None
if dlg.ShowModal() == wx.ID_OK:
routineName = dlg.nameCtrl.GetValue()
routineName = self.frame.exp.namespace.makeValid(routineName, prefix="routine")
template = copy.deepcopy(dlg.selectedTemplate)
self.frame.pasteRoutine(template, routineName)
self.frame.addToUndoStack("NEW Routine `%s`" % routineName)
dlg.Destroy()
return routineName
def onClosePane(self, event=None):
"""Close the pane and remove the routine from the exp.
"""
currentPage = self.GetPage(event.GetSelection())
routine = currentPage.routine
name = routine.name
# name is not valid for some reason
if name not in self.frame.exp.routines:
event.Skip()
return
# check if the user wants a prompt
showDlg = self.app.prefs.builder.get('confirmRoutineClose', False)
if showDlg:
# message to display
msg = _translate(
"Do you want to remove routine '{}' from the experiment?")
# dialog asking if the user wants to remove the routine
dlg = wx.MessageDialog(
self,
_translate(msg).format(name),
_translate('Remove routine?'),
wx.YES_NO | wx.NO_DEFAULT | wx.CENTRE | wx.STAY_ON_TOP)
# show the dialog and get the response
dlgResult = dlg.ShowModal()
dlg.Destroy()
if dlgResult == wx.ID_NO: # if NO, stop the tab from closing
event.Veto()
return
# remove names of the routine and its components from namespace
_nsp = self.frame.exp.namespace
for c in self.frame.exp.routines[name]:
_nsp.remove(c.params['name'].val)
_nsp.remove(self.frame.exp.routines[name].name)
del self.frame.exp.routines[name]
if routine in self.frame.exp.flow:
self.frame.exp.flow.removeComponent(routine)
self.frame.flowPanel.canvas.draw()
self.frame.addToUndoStack("REMOVE Routine `%s`" % (name))
def onMoveTab(self, evt=None):
"""
After moving tabs around, sorts Routines in the Experiment accordingly
and marks experiment as changed.
Parameters
----------
evt : wx.aui.AUI_NB_TAB_MOVE
Event generated by moving the tab (not used)
"""
# Get tab names in order
names = []
for i in range(self.GetPageCount()):
names.append(self.GetPageText(i))
# Reorder routines in experiment to match tab order
routines = collections.OrderedDict()
for name in names:
routines[name] = self.frame.exp.routines[name]
self.frame.exp.routines = routines
# Set modified
self.frame.setIsModified(True)
def increaseSize(self, event=None):
self.appData['routineSize'] = min(
self.routineMaxSize, self.appData['routineSize'] + 1)
with WindowFrozen(self):
self.redrawRoutines()
def decreaseSize(self, event=None):
self.appData['routineSize'] = max(0, self.appData['routineSize'] - 1)
with WindowFrozen(self):
self.redrawRoutines()
def redrawRoutines(self):
"""Removes all the routines, adds them back (alphabetical order),
sets current back to orig
"""
currPage = self.GetSelection()
self.removePages()
for routineName in self.frame.exp.routines:
if isinstance(self.frame.exp.routines[routineName], (Routine, BaseStandaloneRoutine)):
self.addRoutinePage(
routineName, self.frame.exp.routines[routineName])
if currPage > -1:
self.SetSelection(currPage)
class RoutineCanvas(wx.ScrolledWindow, handlers.ThemeMixin):
"""Represents a single routine (used as page in RoutinesNotebook)"""
def __init__(self, notebook, id=wx.ID_ANY, routine=None):
"""This window is based heavily on the PseudoDC demo of wxPython
"""
wx.ScrolledWindow.__init__(
self, notebook, id, (0, 0), style=wx.BORDER_NONE | wx.VSCROLL)
self.frame = notebook.frame
self.app = self.frame.app
self.dpi = self.app.dpi
self.lines = []
self.maxWidth = self.GetSize().GetWidth()
self.maxHeight = 15 * self.dpi
self.x = self.y = 0
self.curLine = []
self.drawing = False
self.drawSize = self.app.prefs.appData['routineSize']
# dict in which to store rectangles to aid layout (populated in updateLayoutRects)
self.rects = {}
# auto-rescale based on number of components and window size is jumpy
# when switch between routines of diff drawing sizes
self.iconSize = (24, 24, 48)[self.drawSize] # only 24, 48 so far
self.fontBaseSize = (1100, 1200, 1300)[self.drawSize] # depends on OS?
#self.scroller = PsychopyScrollbar(self, wx.VERTICAL)
self.SetVirtualSize((self.maxWidth, self.maxHeight))
self.SetScrollRate(self.dpi // 16, self.dpi // 16)
self.routine = routine
self.yPositions = None
self.yPosTop = (25, 40, 60)[self.drawSize]
# the step in Y between each component
self.componentStep = (25, 32, 50)[self.drawSize]
self.timeXposStart = (150, 150, 200)[self.drawSize]
# the left hand edge of the icons:
_scale = (1.3, 1.5, 1.5)[self.drawSize]
self.iconXpos = self.timeXposStart - self.iconSize * _scale
self.timeXposEnd = self.timeXposStart + 400 # onResize() overrides
# create a PseudoDC to record our drawing
self.pdc = PseudoDC()
self.pen_cache = {}
self.brush_cache = {}
# vars for handling mouse clicks
self.dragid = -1
self.lastpos = (0, 0)
# use the ID of the drawn icon to retrieve component name:
self.componentFromID = {}
# define context menu items and labels
self.contextMenuLabels = {
'copy': _translate("Copy"),
'paste above': _translate("Paste above"),
'paste below': _translate("Paste below"),
'edit': _translate("Edit"),
'remove': _translate("Remove"),
'move to top': _translate("Move to top"),
'move up': _translate("Move up"),
'move down': _translate("Move down"),
'move to bottom': _translate("Move to bottom"),
}
self.contextMenuItems = list(self.contextMenuLabels)
self.contextItemFromID = {}
self.contextIDFromItem = {}
for item in self.contextMenuItems:
id = wx.NewIdRef()
self.contextItemFromID[id] = item
self.contextIDFromItem[item] = id
self.Bind(wx.EVT_PAINT, self.OnPaint)
self.Bind(wx.EVT_ERASE_BACKGROUND, lambda x: None)
self.Bind(wx.EVT_MOUSE_EVENTS, self.OnMouse)
self.Bind(wx.EVT_MOUSEWHEEL, self.OnScroll)
self.Bind(wx.EVT_SIZE, self.onResize)
# crashes if drop on OSX:
# self.SetDropTarget(FileDropTarget(builder = self.frame))
def _applyAppTheme(self, target=None):
"""Synonymise app theme method with redraw method"""
return self.redrawRoutine()
def onResize(self, event):
self.sizePix = event.GetSize()
self.timeXposStart = (150, 150, 200)[self.drawSize]
self.timeXposEnd = self.sizePix[0] - (60, 80, 100)[self.drawSize]
self.redrawRoutine() # then redraw visible
def ConvertEventCoords(self, event):
xView, yView = self.GetViewStart()
xDelta, yDelta = self.GetScrollPixelsPerUnit()
return (event.GetX() + (xView * xDelta),
event.GetY() + (yView * yDelta))
def OffsetRect(self, r):
"""Offset the rectangle, r, to appear in the given pos in the window
"""
xView, yView = self.GetViewStart()
xDelta, yDelta = self.GetScrollPixelsPerUnit()
r.OffsetXY(-(xView * xDelta), -(yView * yDelta))
def OnMouse(self, event):
if event.LeftDown():
x, y = self.ConvertEventCoords(event)
icons = self.pdc.FindObjectsByBBox(x, y)
if len(icons):
self.editComponentProperties(
component=self.componentFromID[icons[0]])
elif event.RightDown():
x, y = self.ConvertEventCoords(event)
icons = self.pdc.FindObjectsByBBox(x, y)
menuPos = event.GetPosition()
if 'flowTop' in self.app.prefs.builder['builderLayout']:
# width of components panel
menuPos[0] += self.frame.componentButtons.GetSize()[0]
# height of flow panel
menuPos[1] += self.frame.flowPanel.canvas.GetSize()[1]
if len(icons):
self._menuComponent = self.componentFromID[icons[0]]
self.showContextMenu(self._menuComponent, xy=menuPos)
else: # no context
self.showContextMenu(None, xy=menuPos)
elif event.Dragging() or event.LeftUp():
if self.dragid != -1:
pass
if event.LeftUp():
pass
elif event.Moving():
try:
x, y = self.ConvertEventCoords(event)
id = self.pdc.FindObjectsByBBox(x, y)[0]
component = self.componentFromID[id]
# Indicate hover target in the bottom bar
if component == self.routine.settings:
self.frame.SetStatusText("Routine settings: " + component.params['name'].val)
else:
self.frame.SetStatusText("Component: "+component.params['name'].val)
except IndexError:
self.frame.SetStatusText("")
def OnScroll(self, event):
xy = self.GetViewStart()
delta = int(event.WheelRotation * self.dpi / 1600)
self.Scroll(xy[0], xy[1]-delta)
def showContextMenu(self, component, xy):
"""Show a context menu in the routine view.
"""
menu = wx.Menu()
if component not in (None, self.routine.settings):
for item in self.contextMenuItems:
id = self.contextIDFromItem[item]
# don't show paste option unless something is copied
if item.startswith('paste'):
if not self.app.copiedCompon: # skip paste options
continue
itemLabel = " ".join(
(self.contextMenuLabels[item],
"({})".format(
self.app.copiedCompon.params['name'].val)))
elif any([item.startswith(op) for op in ('copy', 'remove', 'edit')]):
itemLabel = " ".join(
(self.contextMenuLabels[item],
"({})".format(component.params['name'].val)))
else:
itemLabel = self.contextMenuLabels[item]
menu.Append(id, itemLabel)
menu.Bind(wx.EVT_MENU, self.onContextSelect, id=id)
self.frame.PopupMenu(menu, xy)
menu.Destroy() # destroy to avoid mem leak
else:
# anywhere but a hotspot is clicked, show this menu
if self.app.copiedCompon:
itemLabel = " ".join(
(_translate('paste'),
"({})".format(
self.app.copiedCompon.params['name'].val)))
menu.Append(wx.ID_ANY, itemLabel)
menu.Bind(wx.EVT_MENU, self.pasteCompon, id=wx.ID_ANY)
self.frame.PopupMenu(menu, xy)
menu.Destroy()
def onContextSelect(self, event):
"""Perform a given action on the component chosen
"""
op = self.contextItemFromID[event.GetId()]
component = self._menuComponent
r = self.routine
if op == 'edit':
self.editComponentProperties(component=component)
elif op == 'copy':
self.copyCompon(component=component)
elif op == 'paste above':
self.pasteCompon(index=r.index(component))
elif op == 'paste below':
self.pasteCompon(index=r.index(component) + 1)
elif op == 'remove':
r.removeComponent(component)
self.frame.addToUndoStack(
"REMOVE `%s` from Routine" % component.params['name'].val)
self.frame.exp.namespace.remove(component.params['name'].val)
elif op.startswith('move'):
lastLoc = r.index(component)
r.remove(component)
if op == 'move to top':
r.insert(0, component)
if op == 'move up':
r.insert(lastLoc - 1, component)
if op == 'move down':
r.insert(lastLoc + 1, component)
if op == 'move to bottom':
r.append(component)
self.frame.addToUndoStack("MOVED `%s`" %
component.params['name'].val)
self.redrawRoutine()
self._menuComponent = None
def OnPaint(self, event):
# Create a buffered paint DC. It will create the real
# wx.PaintDC and then blit the bitmap to it when dc is
# deleted.
dc = wx.GCDC(wx.BufferedPaintDC(self))
# we need to clear the dc BEFORE calling PrepareDC
bg = wx.Brush(self.GetBackgroundColour())
dc.SetBackground(bg)
dc.Clear()
# use PrepareDC to set position correctly
self.PrepareDC(dc)
# create a clipping rect from our position and size
# and the Update Region
xv, yv = self.GetViewStart()
dx, dy = self.GetScrollPixelsPerUnit()
x, y = (xv * dx, yv * dy)
rgn = self.GetUpdateRegion()
rgn.Offset(x, y)
r = rgn.GetBox()
# draw to the dc using the calculated clipping rect
self.pdc.DrawToDCClipped(dc, r)
def redrawRoutine(self):
# clear everything
self.pdc.Clear()
self.pdc.RemoveAll()
# set font size
self.setFontSize(self.fontBaseSize // self.dpi, self.pdc)
# update rects with which to layout
self.updateLayoutRects()
# # if debugging, draw all the rects
# self.pdc.SetPen(wx.Pen("Red"))
# for rect in self.rects.values():
# self.pdc.DrawRectangle(rect)
self.SetBackgroundColour(colors.app['tab_bg'])
# separate components according to whether they are drawn in separate
# row
rowComponents = []
staticCompons = []
for n, component in enumerate(self.routine):
if component.type == 'Static':
staticCompons.append(component)
elif component == self.routine.settings:
pass
else:
rowComponents.append(component)
# draw settings button
settingsBtnExtent = self.drawSettingsBtn(self.pdc, self.routine.settings)
# draw static, time grid, normal (row) comp:
yPos = self.rects['grid'].Top
yPosBottom = self.rects['grid'].Bottom
# draw any Static Components first (below the grid)
for component in staticCompons:
bottom = max(yPosBottom, self.GetSize()[1])
self.drawStatic(self.pdc, component, yPos, bottom)
self.drawTimeGrid(self.pdc, yPos, yPosBottom)
# normal components, one per row
for component in rowComponents:
self.drawComponent(self.pdc, component, yPos)
yPos += self.componentStep
# draw end line (if there is one)
self.drawForceEndLine(self.pdc, yPosBottom)
# the 50 allows space for labels below the time axis
self.SetVirtualSize((int(self.maxWidth), yPos + 50))
self.Refresh() # refresh the visible window after drawing (OnPaint)
#self.scroller.Resize()
def updateLayoutRects(self):
"""
Recalculate the positions and sizes of the wx.Rect objects which determine
how the canvas is laid out.
"""
self.rects = {}
self.setFontSize(self.fontBaseSize // self.dpi, self.pdc)
# --- Whole area ---
canvas = self.rects['canvas'] = wx.Rect(
x=15,
y=15,
width=self.sizePix[0] - 30,
height=self.sizePix[1] - 30
)
# --- Time grid ---
# filter Components for just those included in the time grid
trueComponents = []
for comp in self.routine:
if type(comp).__name__ in ("StaticComponent", "RoutineSettingsComponent"):
continue
else:
trueComponents.append(comp)
# note: will be modified as things are added around it
grid = self.rects['grid'] = wx.Rect(
x=canvas.Left,
y=canvas.Top,
width=canvas.Width,
height=self.componentStep * len(trueComponents)
)
# --- Top bar ---
# this is where the Settings button lives
topBar = self.rects['topBar'] = wx.Rect(
x=canvas.Left,
y=canvas.Top,
width=canvas.Width,
height=int(self.iconSize/3) + 24
)
# shift grid down
grid.Top += topBar.Height
# --- Time labels ---
# note: will be modified as things are added around it
timeLbls = self.rects['timeLbls'] = wx.Rect(
x=grid.Left,
y=topBar.Bottom,
width=grid.Width,
height=int(self.componentStep/2)
)
# shift grid down
grid.Top += timeLbls.Height
# --- Component names ---
# get width of component names column
compNameWidths = [120]
if not prefs.builder['abbreviateLongCompNames']:
# get width of longest name if we're not elipsizing
for comp in self.routine:
w = self.GetFullTextExtent(comp.name)[0] + 12
compNameWidths.append(w)
componentLabelWidth = max(compNameWidths)
# create rect
compLbls = self.rects['compLbls'] = wx.Rect(
x=canvas.Left,
y=grid.Top,
width=componentLabelWidth,
height=grid.Height
)
# shift grid and time labels right (and cut to size)
grid.Left += compLbls.Width
grid.Width -= compLbls.Width
timeLbls.Left += compLbls.Width
timeLbls.Width -= compLbls.Width
# --- Component icons ---
icons = self.rects['icons'] = wx.Rect(
x=compLbls.Right,
y=grid.Top,
width=self.iconSize + 12,
height=grid.Height
)
# shift grid and time labels right (and cut to size)
grid.Left += icons.Width + 12
grid.Width -= icons.Width + 12
timeLbls.Left += icons.Width + 12
timeLbls.Width -= icons.Width + 12
# --- Time units label ---
timeUnitsLbl = self.rects['timeUnitsLbl'] = wx.Rect(
x=grid.Right,
y=grid.Top,
width=self.GetFullTextExtent("t (sec)")[0] + 12,
height=int(self.componentStep/2)
)
# align self by right edge
timeUnitsLbl.Left -= timeUnitsLbl.Width
# shift grid and time labels left (and cut to size)
grid.Width -= timeUnitsLbl.Width
timeLbls.Width -= timeUnitsLbl.Width
# update references from rects
self.timeXposStart = grid.Left
self.timeXposEnd = grid.Right
self.iconXpos = self.rects['icons'].Left
def getMaxTime(self):
"""Return the max time to be drawn in the window
"""
maxTime, nonSlip = self.routine.getMaxTime()
if self.routine.hasOnlyStaticComp():
maxTime = int(maxTime) + 1.0
# if max came from routine settings, mark as hard stop
rtMax, rtMaxIsNum = self.routine.settings.getDuration()
hardStop = rtMaxIsNum and rtMax == maxTime
# handle no max
if maxTime is None:
maxTime = 10
return maxTime, hardStop
def drawTimeGrid(self, dc, yPosTop, yPosBottom, labelAbove=True):
"""Draws the grid of lines and labels the time axes
"""
yPosTop = int(yPosTop) # explicit type conversion to `int`
yPosBottom = int(yPosBottom)
tMax, hardStop = self.getMaxTime()
tMax *= 1.1
xScale = self.getSecsPerPixel()
xSt = self.timeXposStart
xEnd = self.timeXposEnd
# dc.SetId(wx.NewIdRef())
dc.SetPen(wx.Pen(colors.app['rt_timegrid']))
dc.SetTextForeground(wx.Colour(colors.app['rt_timegrid']))
self.setFontSize(self.fontBaseSize // self.dpi, dc)
id = wx.NewIdRef()
dc.SetId(id)
# draw horizontal lines on top and bottom
dc.DrawLine(
x1=int(xSt),
y1=yPosTop,
x2=int(xEnd),
y2=yPosTop)
dc.DrawLine(
x1=int(xSt),
y1=yPosBottom,
x2=int(xEnd),
y2=yPosBottom)
# draw vertical time points
# gives roughly 1/10 the width, but in rounded to base 10 of
# 0.1,1,10...
unitSize = 10 ** numpy.ceil(numpy.log10(tMax * 0.8)) / 10.0
if tMax / unitSize < 3:
# gives units of 2 (0.2,2,20)
unitSize = 10 ** numpy.ceil(numpy.log10(tMax * 0.8)) / 50.0
elif tMax / unitSize < 6:
# gives units of 5 (0.5,5,50)
unitSize = 10 ** numpy.ceil(numpy.log10(tMax * 0.8)) / 20.0
for lineN in range(int(numpy.floor((tMax / unitSize)))):
# vertical line:
dc.DrawLine(int(xSt + lineN * unitSize / xScale),
yPosTop - 4,
int(xSt + lineN * unitSize / xScale),
yPosBottom + 4)
# label above:
dc.DrawText('%.2g' % (lineN * unitSize),
int(xSt + lineN * unitSize / xScale - 4),
yPosTop - 30)
if yPosBottom > 300:
# if bottom of grid is far away then draw labels here too
dc.DrawText('%.2g' % (lineN * unitSize),
int(xSt + lineN * unitSize / xScale - 4),
yPosBottom + 10)
# add a label
self.setFontSize(self.fontBaseSize // self.dpi, dc)
# y is y-half height of text
dc.DrawText('t (sec)',
self.rects['timeUnitsLbl'].Left + 6,
self.rects['timeUnitsLbl'].Top)
# or draw bottom labels only if scrolling is turned on, virtual size >
# available size?
if yPosBottom > 300:
# if bottom of grid is far away then draw labels there too
# y is y-half height of text
dc.DrawText('t (sec)',
int(xEnd + 5),
yPosBottom - self.GetFullTextExtent('t')[1] // 2)
dc.SetTextForeground(colors.app['text'])
def drawForceEndLine(self, dc, yPosBottom):
id = wx.NewIdRef()
dc.SetId(id)
# get max time & check if we have a hard stop
tMax, hardStop = self.getMaxTime()
# if routine has an estimated stop, it's not a hard stop but we shold draw the line anyway
if self.routine.settings.params.get("durationEstim", False):
hardStop = True
if hardStop:
# if hard stop, draw orange final line
dc.SetPen(
wx.Pen(colors.app['rt_comp_force'], width=4)
)
dc.SetTextForeground(
wx.Colour(colors.app['rt_comp_force'])
)
# vertical line:
dc.DrawLine(self.timeXposEnd,
self.rects['grid'].Top - 4,
self.timeXposEnd,
yPosBottom + 4)
# label above:
dc.DrawText('%.2g' % tMax,
int(self.timeXposEnd - 4),
self.rects['grid'].Top - 30)
def setFontSize(self, size, dc):
font = self.GetFont()
font.SetPointSize(size)
dc.SetFont(font)
self.SetFont(font)
def drawStatic(self, dc, component, yPosTop, yPosBottom):
"""draw a static (ISI) component box"""
# type conversion to `int`
yPosTop = int(yPosTop)
yPosBottom = int(yPosBottom)
# set an id for the region of this component (so it can
# act as a button). see if we created this already.
id = None
for key in self.componentFromID:
if self.componentFromID[key] == component:
id = key
if not id: # then create one and add to the dict
id = wx.NewIdRef()
self.componentFromID[id] = component
dc.SetId(id)
# deduce start and stop times if possible
startTime, duration, nonSlipSafe = component.getStartAndDuration()
# ensure static comps are clickable (even if $code start or duration)
unknownTiming = False
if startTime is None:
startTime = 0
unknownTiming = True
if duration is None:
duration = 0 # minimal extent ensured below
unknownTiming = True
# calculate rectangle for component
xScale = self.getSecsPerPixel()
if component.params['disabled'].val:
dc.SetBrush(wx.Brush(colors.app['rt_static_disabled']))
dc.SetPen(wx.Pen(colors.app['rt_static_disabled']))
else:
dc.SetBrush(wx.Brush(colors.app['rt_static']))
dc.SetPen(wx.Pen(colors.app['rt_static']))
xSt = self.timeXposStart + startTime // xScale
w = duration // xScale + 1 # +1 b/c border alpha=0 in dc.SetPen
w = max(min(w, 10000), 2) # ensure 2..10000 pixels
h = yPosBottom - yPosTop
# name label, position:
name = component.params['name'].val # "ISI"
if unknownTiming:
# flag it as not literally represented in time, e.g., $code
# duration
name += ' ???'
nameW, nameH = self.GetFullTextExtent(name)[0:2]
x = xSt + w // 2
staticLabelTop = (0, 50, 60)[self.drawSize]
y = staticLabelTop - nameH * 3
fullRect = wx.Rect(int(x - 20), int(y), int(nameW), int(nameH))
# draw the rectangle, draw text on top:
dc.DrawRectangle(
int(xSt), int(yPosTop - nameH * 4), int(w), int(h + nameH * 5))
dc.DrawText(name, int(x - nameW // 2), y)
# update bounds to include time bar
fullRect.Union(wx.Rect(int(xSt), int(yPosTop), int(w), int(h)))
dc.SetIdBounds(id, fullRect)
def drawComponent(self, dc, component, yPos):
"""Draw the timing of one component on the timeline"""
# set an id for the region of this component (so it
# can act as a button). see if we created this already
yPos = int(yPos) # explicit type conversion
id = None
for key in self.componentFromID:
if self.componentFromID[key] == component:
id = key
if not id: # then create one and add to the dict
id = wx.NewIdRef()
self.componentFromID[id] = component
dc.SetId(id)
iconYOffset = (6, 6, 0)[self.drawSize]
# get default icon and bar color
thisIcon = icons.ComponentIcon(component, size=self.iconSize).bitmap
thisColor = colors.app['rt_comp']
thisStyle = wx.BRUSHSTYLE_SOLID
# check True/False on ForceEndRoutine
if 'forceEndRoutine' in component.params:
if component.params['forceEndRoutine'].val:
thisColor = colors.app['rt_comp_force']
# check True/False on ForceEndRoutineOnPress
if 'forceEndRoutineOnPress' in component.params:
if component.params['forceEndRoutineOnPress'].val in ['any click', 'correct click', 'valid click']:
thisColor = colors.app['rt_comp_force']
# check True aliases on EndRoutineOn
if 'endRoutineOn' in component.params:
if component.params['endRoutineOn'].val in ['look at', 'look away']:
thisColor = colors.app['rt_comp_force']
# grey bar if comp is disabled
if component.params['disabled'].val:
thisIcon = thisIcon.ConvertToDisabled()
thisColor = colors.app['rt_comp_disabled']
dc.DrawBitmap(thisIcon, int(self.iconXpos) + 6, int(yPos + iconYOffset), True)
fullRect = wx.Rect(
int(self.iconXpos),
yPos,
thisIcon.GetWidth(),
thisIcon.GetHeight())
self.setFontSize(self.fontBaseSize // self.dpi, dc)
name = component.params['name'].val
# elipsize name if it's too long
if self.GetFullTextExtent(name)[0] > self.rects['compLbls'].Width:
name = name[:6] + "..." + name[-6:]
# get size based on text
w = self.rects['compLbls'].Width
h = self.GetFullTextExtent(name)[1]
# draw text
# + x position of icon (left side)
# - half width of icon (including whitespace around it)
# - FULL width of text
# + slight adjustment for whitespace
x = self.rects['compLbls'].Right - 6 - self.GetFullTextExtent(name)[0]
_adjust = (5, 5, -2)[self.drawSize]
y = yPos + thisIcon.GetHeight() // 2 - h // 2 + _adjust
dc.DrawText(name, int(x), y)
fullRect.Union(
wx.Rect(int(x - 20), int(y), int(w), int(h)))
# deduce start and stop times if possible
startTime, duration, nonSlipSafe = component.getStartAndDuration()
# draw entries on timeline (if they have some time definition)
if duration is not None:
yOffset = (3.5, 3.5, 0.5)[self.drawSize]
h = self.componentStep // (4, 3.25, 2.5)[self.drawSize]
xScale = self.getSecsPerPixel()
# then we can draw a sensible time bar!
thisPen = wx.Pen(thisColor, style=wx.TRANSPARENT)
thisBrush = wx.Brush(thisColor, style=thisStyle)
dc.SetPen(thisPen)
dc.SetBrush(thisBrush)
# cap duration if routine has a max
maxDur, useMax = self.routine.settings.getDuration()
overspill = 0
if useMax:
overspill = max(duration - maxDur, 0)
duration = min(maxDur, duration)
# If there's a fixed end time and no start time, start 20px before 0
if ('stopType' in component.params) and ('startType' in component.params) and (
component.params['stopType'].val in ('time (s)', 'duration (s)')
and component.params['startType'].val in ('time (s)')
and startTime is None
):
startTime = -20 * self.getSecsPerPixel()
duration += 20 * self.getSecsPerPixel()
# thisBrush.SetStyle(wx.BRUSHSTYLE_BDIAGONAL_HATCH)
# dc.SetBrush(thisBrush)
if startTime is not None:
xSt = self.timeXposStart + startTime // xScale
w = duration // xScale + 1
if w > 10000:
w = 10000 # limit width to 10000 pixels!
if w < 2:
w = 2 # make sure at least one pixel shows
dc.DrawRectangle(int(xSt), int(y + yOffset), int(w), int(h))
# update bounds to include time bar
fullRect.Union(wx.Rect(int(xSt), int(y + yOffset), int(w), int(h)))
# draw greyed out bar for any overspill (if routine has a max dur)
if useMax and overspill > 0:
# use disabled color
dc.SetBrush(
wx.Brush(colors.app['rt_comp_disabled'], style=thisStyle)
)
dc.SetPen(
wx.Pen(colors.app['rt_comp_disabled'], style=wx.TRANSPARENT)
)
# draw rest of bar
w = overspill // xScale + 1
if w > 10000:
w = 10000 # limit width to 10000 pixels!
if w < 2:
w = 2 # make sure at least one pixel shows
dc.DrawRectangle(self.timeXposEnd, int(y + yOffset), int(w), int(h))
dc.SetIdBounds(id, fullRect)
def drawSettingsBtn(self, dc, component):
# Setup ID
id = None
for key in self.componentFromID:
if self.componentFromID[key] == component:
id = key
if not id: # then create one and add to the dict
id = wx.NewIdRef()
self.componentFromID[id] = component
dc.SetId(id)
# Get settings icon
sz = int(self.iconSize/3)
thisIcon = icons.ComponentIcon(component, size=sz).bitmap
# Some parameters
lbl = _translate("Routine settings")
padding = 12
# Set font
fontSize = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT).GetPointSize()
self.setFontSize(fontSize, dc)
# Calculate extent
extent = wx.Rect(
x=self.rects['topBar'].Left,
y=self.rects['topBar'].Top,
width=padding + sz + 6 + self.GetTextExtent(lbl)[0] + padding,
height=padding + sz + padding
)
extent = extent.CenterIn(self.rects['topBar'], dir=wx.VERTICAL)
# Get content rect
rect = wx.Rect(extent.TopLeft, extent.BottomRight)
rect.Deflate(padding)
# Draw rect
dc.SetPen(wx.Pen(colors.app['panel_bg']))
dc.SetBrush(wx.Brush(colors.app['tab_bg']))
dc.DrawRoundedRectangle(extent, 6)
# Draw button
dc.SetTextForeground(
wx.Colour(colors.app['text'])
)
dc.DrawLabel(
lbl,
image=thisIcon,
rect=rect,
alignment=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL
)
# Bind to ID bounds
dc.SetIdBounds(id, extent)
return extent
def copyCompon(self, event=None, component=None):
"""This is easy - just take a copy of the component into memory
"""
self.app.copiedCompon = component.copy()
def pasteCompon(self, event=None, component=None, index=None):
# Alias None for component stored in app
if component is None and self.app.copiedCompon:
component = self.app.copiedCompon
# Fail if nothing copied
if component is None:
return -1
exp = self.frame.exp
origName = component.params['name'].val
defaultName = exp.namespace.makeValid(origName)
msg = _translate('New name for copy of "%(copied)s"? [%(default)s]')
vals = {'copied': origName, 'default': defaultName}
message = msg % vals
dlg = wx.TextEntryDialog(self, message=message,
caption=_translate('Paste Component'))
if dlg.ShowModal() == wx.ID_OK:
# Get new name
newName = dlg.GetValue()
if not newName:
newName = defaultName
newName = exp.namespace.makeValid(newName)
# Create copy of component with new references
newCompon = component.copy(
exp=exp,
parentName=self.routine.name,
name=newName
)
# Add to routine
if index is None:
self.routine.addComponent(newCompon)
else:
self.routine.insertComponent(index, newCompon)
self.frame.exp.namespace.user.append(newName)
# could do redrawRoutines but would be slower?
self.redrawRoutine()
self.frame.addToUndoStack("PASTE Component `%s`" % newName)
dlg.Destroy()
def editComponentProperties(self, event=None, component=None, openToPage=None):
# we got here from a wx.button press (rather than our own drawn icons)
if event:
componentName = event.EventObject.GetName()
component = self.routine.getComponentFromName(componentName)
# does this component have a help page?
if hasattr(component, 'url'):
helpUrl = component.url
else:
helpUrl = None
old_name = component.params['name'].val
old_disabled = component.params['disabled'].val
# check current timing settings of component (if it changes we
# need to update views)
initialTimings = component.getStartAndDuration()
if 'forceEndRoutine' in component.params \
or 'forceEndRoutineOnPress' in component.params:
# If component can force end routine, check if it did before
initialForce = [component.params[key].val
for key in ['forceEndRoutine', 'forceEndRoutineOnPress']
if key in component.params]
else:
initialForce = False
# create the dialog
if hasattr(component, 'type') and component.type.lower() == 'code':
_Dlg = DlgCodeComponentProperties
else:
_Dlg = DlgComponentProperties
dlg = _Dlg(frame=self.frame,
element=component,
experiment=self.frame.exp, editing=True,
openToPage=openToPage)
if dlg.OK:
# Redraw if force end routine has changed
if any(key in component.params for key in ['forceEndRoutine', 'forceEndRoutineOnPress', 'endRoutineOn']):
newForce = [component.params[key].val
for key in ['forceEndRoutine', 'forceEndRoutineOnPress', 'endRoutineOn']
if key in component.params]
if initialForce != newForce:
self.redrawRoutine() # need to refresh timings section
self.Refresh() # then redraw visible
self.frame.flowPanel.canvas.draw()
# Redraw if timings have changed (or always, if comp was RoutineSettings)
if (
component.getStartAndDuration() != initialTimings
or component.type == "RoutineSettingsComponent"
):
self.redrawRoutine() # need to refresh timings section
self.Refresh() # then redraw visible
self.frame.flowPanel.canvas.draw()
# self.frame.flowPanel.Refresh()
elif component.name != old_name:
if component == self.routine.settings:
self.frame.flowPanel.canvas.draw()
self.frame._doRenameRoutine(oldName=old_name, newName=component.name)
self.redrawRoutine() # need to refresh name
elif component.params['disabled'].val != old_disabled:
self.redrawRoutine() # need to refresh color
self.frame.exp.namespace.remove(old_name)
self.frame.exp.namespace.add(component.params['name'].val)
self.frame.addToUndoStack("EDIT `%s`" %
component.params['name'].val)
def getSecsPerPixel(self):
pixels = float(self.timeXposEnd - self.timeXposStart)
return self.getMaxTime()[0] / pixels
class StandaloneRoutineCanvas(scrolledpanel.ScrolledPanel):
def __init__(self, parent, routine=None):
# Init super
scrolledpanel.ScrolledPanel.__init__(
self, parent,
style=wx.BORDER_NONE)
# Store basics
self.frame = parent.frame
self.app = self.frame.app
self.dpi = self.app.dpi
self.routine = routine
self.helpUrl = self.routine.url
self.params = routine.params
# Setup sizer
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.SetSizer(self.sizer)
# Setup categ notebook
self.ctrls = ParamNotebook(self, experiment=self.frame.exp, element=routine)
self.paramCtrls = self.ctrls.paramCtrls
self.sizer.Add(self.ctrls, border=12, proportion=1, flag=wx.ALIGN_CENTER | wx.TOP)
# Make buttons
self.btnsSizer = wx.BoxSizer(wx.HORIZONTAL)
self.helpBtn = utils.HoverButton(self, id=wx.ID_HELP, label=_translate("Help"))
self.helpBtn.Bind(wx.EVT_BUTTON, self.onHelp)
self.btnsSizer.Add(self.helpBtn, border=6, flag=wx.ALL | wx.EXPAND)
self.btnsSizer.AddStretchSpacer(1)
# Add validator stuff
self.warnings = WarningManager(self)
self.sizer.Add(self.warnings.output, border=3, flag=wx.EXPAND | wx.ALL)
# Add buttons to sizer
self.sizer.Add(self.btnsSizer, border=3, proportion=0, flag=wx.EXPAND | wx.ALL)
# Style
self.SetupScrolling(scroll_y=True)
def _applyAppTheme(self):
self.SetBackgroundColour(colors.app['tab_bg'])
self.helpBtn._applyAppTheme()
self.Refresh()
self.Update()
def updateExperiment(self, evt=None):
"""Update this routine's saved parameters to what is currently entered"""
# Get params in correct formats
self.routine.params = self.ctrls.getParams()
# Duplicate routine list and iterate through to find this one
routines = self.frame.exp.routines.copy()
for name, routine in routines.items():
if routine == self.routine:
# Update the routine dict keys to use the current name for this routine
self.frame.exp.routines[self.routine.params['name'].val] = self.frame.exp.routines.pop(name)
# Redraw the flow panel
self.frame.flowPanel.canvas.draw()
# Rename this page
page = self.frame.routinePanel.GetPageIndex(self)
self.frame.routinePanel.SetPageText(page, self.routine.params['name'].val)
# Update save button
self.frame.setIsModified(True)
def onHelp(self, event=None):
"""Uses self.app.followLink() to self.helpUrl
"""
self.app.followLink(url=self.helpUrl)
def Validate(self, *args, **kwargs):
return self.ctrls.Validate()
class ComponentsPanel(scrolledpanel.ScrolledPanel, handlers.ThemeMixin):
"""Panel containing buttons for each component, sorted by category"""
class CategoryButton(wx.ToggleButton, handlers.ThemeMixin, HoverMixin):
"""Button to show/hide a category of components"""
def __init__(self, parent, name, cat):
if sys.platform == 'darwin':
label = name # on macOS the wx.BU_LEFT flag has no effect
else:
label = " "+name
# Initialise button
wx.ToggleButton.__init__(self, parent,
label=label, size=(-1, 24),
style= wx.BORDER_NONE | wx.BU_LEFT)
self.parent = parent
# Link to category of buttons
self.menu = self.parent.catSizers[cat]
# # Set own sizer
# self.sizer = wx.GridSizer(wx.HORIZONTAL)
# self.SetSizer(self.sizer)
# # Add icon
# self.icon = wx.StaticText(parent=self, label="DOWN")
# self.sizer.Add(self.icon, border=5, flag=wx.ALL | wx.ALIGN_RIGHT)
# Default states to false
self.state = False
self.hover = False
# Bind toggle function
self.Bind(wx.EVT_TOGGLEBUTTON, self.ToggleMenu)
# Bind hover functions
self.SetupHover()
def ToggleMenu(self, event):
# If triggered manually with a bool, treat that as a substitute for event selection
if isinstance(event, bool):
state = event
else:
state = event.GetSelection()
# Set state
self.SetValue(state)
# Refresh view (which will show/hide according to this button's state)
self.parent.refreshView()
# Restyle
self.OnHover()
def _applyAppTheme(self):
"""Apply app theme to this button"""
self.OnHover()
class ComponentButton(wx.Button, handlers.ThemeMixin):
"""Button to open component parameters dialog"""
def __init__(self, parent, name, comp, cat):
self.parent = parent
self.component = comp
self.category = cat
# construct label
label = name
# remove "Component" from the end
for redundant in ['component', 'Component']:
label = label.replace(redundant, "")
# convert to title case
label = st.CaseSwitcher.pascal2title(label)
# wrap
label = st.wrap(label, 10)
# Make button
wx.Button.__init__(self, parent, wx.ID_ANY,
label=label, name=name,
size=(68, 68+12*label.count("\n")),
style=wx.NO_BORDER)
self.SetToolTip(wx.ToolTip(comp.tooltip or name))
# Style
self._applyAppTheme()
# Bind to functions
self.Bind(wx.EVT_BUTTON, self.onClick)
self.Bind(wx.EVT_RIGHT_DOWN, self.onRightClick)
@property
def element(self):
return self.component
def onClick(self, evt=None, timeout=None):
"""Called when a component button is clicked on.
"""
routine = self.parent.frame.routinePanel.getCurrentRoutine()
if routine is None:
if timeout is not None: # just return, we're testing the UI
return
# Show a message telling the user there is no routine in the
# experiment, making adding a component pointless until they do
# so.
dlg = wx.MessageDialog(
self,
_translate(
"Cannot add component, experiment has no routines."),
_translate("Error"),
wx.OK | wx.ICON_ERROR | wx.CENTRE)
dlg.ShowModal()
dlg.Destroy()
return
page = self.parent.frame.routinePanel.getCurrentPage()
comp = self.component(
parentName=routine.name,
exp=self.parent.frame.exp)
# does this component have a help page?
if hasattr(comp, 'url'):
helpUrl = comp.url
else:
helpUrl = None
# create component template
if comp.type == 'Code':
_Dlg = DlgCodeComponentProperties
else:
_Dlg = DlgComponentProperties
dlg = _Dlg(frame=self.parent.frame,
element=comp,
experiment=self.parent.frame.exp,
timeout=timeout)
if dlg.OK:
# Add to the actual routine
routine.addComponent(comp)
namespace = self.parent.frame.exp.namespace
desiredName = comp.params['name'].val
name = comp.params['name'].val = namespace.makeValid(desiredName)
namespace.add(name)
# update the routine's view with the new component too
page.redrawRoutine()
self.parent.frame.addToUndoStack(
"ADD `%s` to `%s`" % (name, routine.name))
return True
def onRightClick(self, evt):
"""
Defines rightclick behavior within builder view's
components panel
"""
# Get fave levels
faveLevels = prefs.appDataCfg['builder']['favComponents']
# Make menu
menu = wx.Menu()
if faveLevels[self.component.__name__] > ComponentsPanel.faveThreshold:
# If is in favs
msg = _translate("Remove from favorites")
fun = self.removeFromFavorites
else:
# If is not in favs
msg = _translate("Add to favorites")
fun = self.addToFavorites
btn = menu.Append(wx.ID_ANY, msg)
menu.Bind(wx.EVT_MENU, fun, btn)
# Show as popup
self.PopupMenu(menu, evt.GetPosition())
# Destroy to avoid mem leak
menu.Destroy()
def addToFavorites(self, evt):
self.parent.addToFavorites(self.component)
def removeFromFavorites(self, evt):
self.parent.removeFromFavorites(self)
def _applyAppTheme(self):
# Set colors
self.SetForegroundColour(colors.app['text'])
self.SetBackgroundColour(colors.app['panel_bg'])
# Set bitmap
icon = icons.ComponentIcon(self.component, size=48)
if hasattr(self.component, "beta") and self.component.beta:
icon = icon.beta
else:
icon = icon.bitmap
self.SetBitmap(icon)
self.SetBitmapCurrent(icon)
self.SetBitmapPressed(icon)
self.SetBitmapFocus(icon)
self.SetBitmapPosition(wx.TOP)
# Refresh
self.Refresh()
class RoutineButton(wx.Button, handlers.ThemeMixin):
"""Button to open component parameters dialog"""
def __init__(self, parent, name, rt, cat):
self.parent = parent
self.routine = rt
self.category = cat
# construct label
label = name
# remove "Routine" from the end
for redundant in ['routine', 'Routine', "ButtonBox"]:
label = label.replace(redundant, "")
# convert to title case
label = st.CaseSwitcher.pascal2title(label)
# wrap
label = st.wrap(label, 10)
# Make button
wx.Button.__init__(self, parent, wx.ID_ANY,
label=label, name=name,
size=(68, 68+12*label.count("\n")),
style=wx.NO_BORDER)
self.SetToolTip(wx.ToolTip(rt.tooltip or name))
# Style
self._applyAppTheme()
# Bind to functions
self.Bind(wx.EVT_BUTTON, self.onClick)
self.Bind(wx.EVT_RIGHT_DOWN, self.onRightClick)
@property
def element(self):
return self.routine
def onClick(self, evt=None, timeout=None):
# Make a routine instance
comp = self.routine(exp=self.parent.frame.exp)
# Add to the actual routine
exp = self.parent.frame.exp
namespace = exp.namespace
name = comp.params['name'].val = namespace.makeValid(
comp.params['name'].val)
namespace.add(name)
exp.addStandaloneRoutine(name, comp)
# update the routine's view with the new routine too
self.parent.frame.addToUndoStack(
"ADD `%s` to `%s`" % (name, exp.name))
# Add a routine page
notebook = self.parent.frame.routinePanel
notebook.addRoutinePage(name, comp)
notebook.setCurrentRoutine(comp)
def onRightClick(self, evt):
"""
Defines rightclick behavior within builder view's
routines panel
"""
return
def addToFavorites(self, evt):
self.parent.addToFavorites(self.routine)
def removeFromFavorites(self, evt):
self.parent.removeFromFavorites(self)
def _applyAppTheme(self):
# Set colors
self.SetForegroundColour(colors.app['text'])
self.SetBackgroundColour(colors.app['panel_bg'])
# Set bitmap
icon = icons.ComponentIcon(self.routine, size=48)
if hasattr(self.routine, "beta") and self.routine.beta:
icon = icon.beta
else:
icon = icon.bitmap
self.SetBitmap(icon)
self.SetBitmapCurrent(icon)
self.SetBitmapPressed(icon)
self.SetBitmapFocus(icon)
self.SetBitmapPosition(wx.TOP)
# Refresh
self.Refresh()
class FilterDialog(wx.Dialog, handlers.ThemeMixin):
def __init__(self, parent, size=(200, 300)):
wx.Dialog.__init__(self, parent, size=size)
self.parent = parent
# Setup sizer
self.border = wx.BoxSizer(wx.VERTICAL)
self.SetSizer(self.border)
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.border.Add(self.sizer, border=6, proportion=1, flag=wx.ALL | wx.EXPAND)
# Label
self.label = wx.StaticText(self, label="Show components which \nwork with...")
self.sizer.Add(self.label, border=6, flag=wx.ALL | wx.EXPAND)
# Control
self.viewCtrl = ToggleButtonArray(self,
labels=("PsychoPy (local)", "PsychoJS (online)", "Both", "Any"),
values=("PsychoPy", "PsychoJS", "Both", "Any"),
multi=False, ori=wx.VERTICAL)
self.viewCtrl.Bind(wx.EVT_CHOICE, self.onChange)
self.sizer.Add(self.viewCtrl, border=6, flag=wx.ALL | wx.EXPAND)
self.viewCtrl.SetValue(prefs.builder['componentFilter'])
# OK
self.OKbtn = wx.Button(self, id=wx.ID_OK, label=_translate("OK"))
self.SetAffirmativeId(wx.ID_OK)
self.border.Add(self.OKbtn, border=6, flag=wx.ALL | wx.ALIGN_RIGHT)
self.Layout()
self._applyAppTheme()
def _applyAppTheme(self):
self.SetBackgroundColour(colors.app['panel_bg'])
self.label.SetForegroundColour(colors.app['text'])
def GetValue(self):
return self.viewCtrl.GetValue()
def onChange(self, evt=None):
self.parent.filter = prefs.builder['componentFilter'] = self.GetValue()
prefs.saveUserPrefs()
self.parent.refreshView()
faveThreshold = 20
def __init__(self, frame, id=-1):
"""A panel that displays available components.
"""
self.frame = frame
self.app = frame.app
self.dpi = self.app.dpi
self.prefs = self.app.prefs
panelWidth = 3 * (68 + 12) + 12 + 12
scrolledpanel.ScrolledPanel.__init__(self,
frame,
id,
size=(panelWidth, 10 * self.dpi),
style=wx.BORDER_NONE)
# Get filter from prefs
self.filter = prefs.builder['componentFilter']
# Setup sizer
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.SetSizer(self.sizer)
# Top bar
self.topBarSizer = wx.BoxSizer(wx.HORIZONTAL)
self.sizer.Add(self.topBarSizer, border=0, flag=wx.ALL | wx.EXPAND)
# Add plugins button
self.pluginBtn = wx.Button(self, label=_translate("Get more..."), style=wx.BU_EXACTFIT | wx.BORDER_NONE)
self.pluginBtn.SetToolTip(_translate("Add new components and features via plugins."))
self.topBarSizer.Add(self.pluginBtn, border=3, flag=wx.ALL)
self.pluginBtn.Bind(wx.EVT_BUTTON, self.onPluginBtn)
# Add filter button
self.topBarSizer.AddStretchSpacer(1)
self.filterBtn = wx.Button(self, style=wx.BU_EXACTFIT | wx.BORDER_NONE)
self.filterBtn.SetToolTip(_translate("Filter components by whether they work with PsychoJS, PsychoPy or both."))
self.topBarSizer.Add(self.filterBtn, border=3, flag=wx.ALL)
self.filterBtn.Bind(wx.EVT_BUTTON, self.onFilterBtn)
# Attributes to store handles in
self.catLabels = {}
self.catSizers = {}
self.compButtons = []
self.rtButtons = []
self.objectHandles = {}
# Create buttons
self.populate()
# Apply filter
self.refreshView()
# Do sizing
self.Fit()
# double buffered better rendering except if retina
self.SetDoubleBuffered(not self.frame.isRetina)
def getSortedElements(self):
allElements = getAllElements()
if "SettingsComponent" in allElements:
del allElements['SettingsComponent']
# Create array to store elements in
elements = OrderedDict()
# Specify which categories are fixed to start/end
firstCats = ['Favorites', 'Stimuli', 'Responses', 'Custom']
lastCats = ['I/O', 'Other']
# Add categories which are fixed to start
for cat in firstCats:
elements[cat] = {}
# Add unfixed categories
for cat in getAllCategories():
if cat not in lastCats + firstCats:
elements[cat] = {}
# Add categories which are fixed to end
for cat in lastCats:
elements[cat] = {}
# Get elements and sort by category
for name, emt in allElements.items():
for cat in emt.categories:
if cat in elements:
elements[cat][name] = emt
# Assign favorites
self.faveLevels = prefs.appDataCfg['builder']['favComponents']
for name, emt in allElements.items():
# Make sure element has a level
if name not in self.faveLevels:
self.faveLevels[name] = 0
# If it exceeds the threshold, add to favorites
if self.faveLevels[name] > self.faveThreshold:
elements['Favorites'][name] = emt
# Fill in gaps in favorites with defaults
faveDefaults = [
('ImageComponent', allElements['ImageComponent']),
('KeyboardComponent', allElements['KeyboardComponent']),
('SoundComponent', allElements['SoundComponent']),
('TextComponent', allElements['TextComponent']),
('MouseComponent', allElements['MouseComponent']),
('SliderComponent', allElements['SliderComponent']),
]
while len(elements['Favorites']) < 6:
name, emt = faveDefaults.pop(0)
if name not in elements['Favorites']:
elements['Favorites'][name] = emt
self.faveLevels[name] = self.faveThreshold + 1
return elements
def populate(self):
"""
Find all component/standalone routine classes and create buttons for each, sorted by category.
This *can* be called multiple times - already existing buttons are simply detached from their sizer and
reattached in the correct place given any changes since last called.
"""
elements = self.getSortedElements()
# Detach any extant category labels and sizers from main sizer
for cat in self.objectHandles:
self.sizer.Detach(self.catLabels[cat])
self.sizer.Detach(self.catSizers[cat])
# Add each category
for cat, emts in elements.items():
if cat not in self.objectHandles:
# Make category sizer
self.catSizers[cat] = wx.WrapSizer(orient=wx.HORIZONTAL)
# Make category button
self.catLabels[cat] = self.CategoryButton(self, name=_translate(cat), cat=cat)
# Store category reference
self.objectHandles[cat] = {}
# Add to sizer
self.sizer.Add(self.catLabels[cat], border=3, flag=wx.BOTTOM | wx.EXPAND)
self.sizer.Add(self.catSizers[cat], border=6, flag=wx.ALL | wx.ALIGN_CENTER)
# Detach any extant buttons from sizer
for btn in self.objectHandles[cat].values():
self.catSizers[cat].Detach(btn)
# Add each element
for name, emt in emts.items():
if name not in self.objectHandles[cat]:
# Make appropriate button
if issubclass(emt, BaseStandaloneRoutine):
emtBtn = self.RoutineButton(self, name=name, rt=emt, cat=cat)
self.rtButtons.append(emtBtn)
else:
emtBtn = self.ComponentButton(self, name=name, comp=emt, cat=cat)
self.compButtons.append(emtBtn)
# If we're in standalone routine view, disable new component button
rtPage = self.frame.routinePanel.getCurrentPage()
if rtPage:
emtBtn.Enable(
not isinstance(rtPage.routine, BaseStandaloneRoutine)
)
# Store reference by category
self.objectHandles[cat][name] = emtBtn
# Add to category sizer
self.catSizers[cat].Add(self.objectHandles[cat][name], border=3, flag=wx.ALL)
# Show favourites on startup
self.catLabels['Favorites'].ToggleMenu(True)
def refreshView(self):
# Get view value(s)
if prefs.builder['componentFilter'] == "Both":
view = ["PsychoPy", "PsychoJS"]
elif prefs.builder['componentFilter'] == "Any":
view = []
else:
view = [prefs.builder['componentFilter']]
# Iterate through categories and buttons
for cat in self.objectHandles:
anyShown = False
for name, btn in self.objectHandles[cat].items():
shown = True
# Get element button refers to
if isinstance(btn, self.ComponentButton):
emt = btn.component
elif isinstance(btn, self.RoutineButton):
emt = btn.routine
else:
emt = None
# Check whether button is hidden by filter
for v in view:
if v not in btn.element.targets:
shown = False
# Check whether button is hidden by prefs
if name in prefs.builder['hiddenComponents'] + alwaysHidden:
shown = False
# Check whether button refers to a future comp/rt
if hasattr(emt, "version"):
ver = parseVersionSafely(emt.version)
if ver > psychopyVersion:
shown = False
# Show/hide button
btn.Show(shown)
# Count state towards category
anyShown = anyShown or shown
# Only show category button if there are some buttons
self.catLabels[cat].Show(anyShown)
# If comp button is set to hide, hide all regardless
if not self.catLabels[cat].GetValue():
self.catSizers[cat].ShowItems(False)
# Do sizing
self.Layout()
self.SetupScrolling(scrollToTop=False)
def _applyAppTheme(self, target=None):
# Style component panel
self.SetForegroundColour(colors.app['text'])
self.SetBackgroundColour(colors.app['panel_bg'])
# Style category labels
for lbl in self.catLabels:
self.catLabels[lbl].SetForegroundColour(colors.app['text'])
# Style filter button
self.filterBtn.SetBackgroundColour(colors.app['panel_bg'])
icon = icons.ButtonIcon("filter", size=16).bitmap
self.filterBtn.SetBitmap(icon)
self.filterBtn.SetBitmapCurrent(icon)
self.filterBtn.SetBitmapPressed(icon)
self.filterBtn.SetBitmapFocus(icon)
# Style plugin button
self.pluginBtn.SetBackgroundColour(colors.app['panel_bg'])
self.pluginBtn.SetForegroundColour(colors.app['text'])
icon = icons.ButtonIcon("plus", size=16).bitmap
self.pluginBtn.SetBitmap(icon)
self.pluginBtn.SetBitmapCurrent(icon)
self.pluginBtn.SetBitmapPressed(icon)
self.pluginBtn.SetBitmapFocus(icon)
self.Refresh()
def addToFavorites(self, comp):
name = comp.__name__
# Mark component as a favorite
self.faveLevels[name] = self.faveThreshold + 1
# Repopulate
self.populate()
# Do sizing
self.Layout()
def removeFromFavorites(self, button):
comp = button.component
name = comp.__name__
# Unmark component as favorite
self.faveLevels[name] = 0
# Remove button from favorites menu
button.Destroy()
del self.objectHandles["Favorites"][name]
# Do sizing
self.Layout()
def enableComponents(self, enable=True):
for button in self.compButtons:
button.Enable(enable)
self.Update()
def onFilterBtn(self, evt=None):
dlg = self.FilterDialog(self)
dlg.ShowModal()
def onPluginBtn(self, evt=None):
dlg = psychopy.app.plugin_manager.dialog.EnvironmentManagerDlg(self)
dlg.Show()
# Do post-close checks
dlg.onClose()
class ReadmeFrame(wx.Frame, handlers.ThemeMixin):
"""Defines construction of the Readme Frame"""
def __init__(self, parent, filename=None):
"""
A frame for presenting/loading/saving readme files
"""
self.parent = parent
try:
title = "%s readme" % (parent.exp.name)
except AttributeError:
title = "readme"
self._fileLastModTime = None
pos = wx.Point(parent.Position[0] + 80, parent.Position[1] + 80)
_style = wx.DEFAULT_FRAME_STYLE | wx.FRAME_FLOAT_ON_PARENT
wx.Frame.__init__(self, parent, title=title,
size=(600, 500), pos=pos, style=_style)
# Setup sizer
self.sizer = wx.BoxSizer()
self.SetSizer(self.sizer)
self.Bind(wx.EVT_CLOSE, self.onClose)
self.Hide()
# create icon
if sys.platform == 'darwin':
pass # doesn't work and not necessary - handled by app bundle
else:
iconFile = os.path.join(parent.paths['resources'], 'coder.ico')
if os.path.isfile(iconFile):
self.SetIcon(wx.Icon(iconFile, wx.BITMAP_TYPE_ICO))
self.ctrl = utils.MarkdownCtrl(self, file=filename, style=wx.BOTTOM)
self.sizer.Add(self.ctrl, border=6, proportion=1, flag=wx.ALL | wx.EXPAND)
def show(self, value=True):
self.Show(value)
if value:
self._applyAppTheme()
def _applyAppTheme(self):
from psychopy.app.themes import fonts
self.SetBackgroundColour(fonts.coderTheme.base.backColor)
self.ctrl.SetBackgroundColour(fonts.coderTheme.base.backColor)
self.Update()
self.Refresh()
def onClose(self, evt=None):
"""
Defines behavior on close of the Readme Frame
"""
self.parent.readmeFrame = None
self.Destroy()
def makeMenus(self):
"""Produces menus for the Readme Frame"""
# ---Menus---#000000#FFFFFF-------------------------------------------
menuBar = wx.MenuBar()
# ---_file---#000000#FFFFFF-------------------------------------------
self.fileMenu = wx.Menu()
menuBar.Append(self.fileMenu, _translate('&File'))
menu = self.fileMenu
keys = self.parent.app.keys
menu.Append(wx.ID_EDIT, _translate("Edit"))
self.Bind(wx.EVT_MENU, self.fileEdit, id=wx.ID_EDIT)
menu.Append(wx.ID_CLOSE,
_translate("&Close readme\t%s") % keys['close'])
item = self.Bind(wx.EVT_MENU, self.toggleVisible, id=wx.ID_CLOSE)
item = menu.Append(-1,
_translate("&Toggle readme\t%s") % keys[
'toggleReadme'],
_translate("Toggle Readme"))
self.Bind(wx.EVT_MENU, self.toggleVisible, item)
self.SetMenuBar(menuBar)
def setFile(self, filename):
"""Sets the readme file found with current builder experiment"""
self.filename = self.ctrl.file = filename
self.expName = self.parent.exp.getExpName()
if not self.expName:
self.expName = "untitled"
# check we can read
if filename is None: # check if we can write to the directory
return False
# Path-ise file
filename = Path(filename)
if not filename.is_file():
filename.write_text("")
self.filename = filename
return False
elif not os.access(filename, os.R_OK):
msg = "Found readme file (%s) no read permissions"
logging.warning(msg % filename)
return False
# attempt to open
try:
f = codecs.open(filename, 'r', 'utf-8-sig')
except IOError as err:
msg = ("Found readme file for %s and appear to have"
" permissions, but can't open")
logging.warning(msg % self.expName)
logging.warning(err)
return False
# attempt to read
try:
readmeText = f.read().replace("\r\n", "\n")
except Exception:
msg = ("Opened readme file for %s it but failed to read it "
"(not text/unicode?)")
logging.error(msg % self.expName)
return False
f.close()
self._fileLastModTime = os.path.getmtime(filename)
self.ctrl.setValue(readmeText)
self.SetTitle("readme (%s)" % self.expName)
def refresh(self, evt=None):
if hasattr(self, 'filename'):
self.setFile(self.filename)
def fileEdit(self, evt=None):
self.parent.app.showCoder()
coder = self.parent.app.coder
if not self.filename:
self.parent.updateReadme()
coder.fileOpen(filename=self.filename)
# Close README window
self.Close()
def fileSave(self, evt=None):
"""Defines save behavior for readme frame"""
mtime = os.path.getmtime(self.filename)
if self._fileLastModTime and mtime > self._fileLastModTime:
logging.warning(
'readme file has been changed by another program?')
txt = self.rawText
with codecs.open(self.filename, 'w', 'utf-8-sig') as f:
f.write(txt)
def toggleVisible(self, evt=None):
"""Defines visibility toggle for readme frame"""
if self.IsShown():
self.Hide()
else:
self.Show()
class FlowPanel(wx.Panel, handlers.ThemeMixin):
def __init__(self, frame, id=-1):
wx.Panel.__init__(self, parent=frame)
# setup sizer
self.sizer = wx.BoxSizer(wx.HORIZONTAL)
self.SetSizer(self.sizer)
# buttons panel
self.btnPanel = ThemedPanel(self)
self.btnPanel.sizer = wx.BoxSizer(wx.VERTICAL)
self.btnPanel.SetSizer(self.btnPanel.sizer)
self.sizer.Add(self.btnPanel, border=6, flag=wx.EXPAND | wx.ALL)
# canvas
self.canvas = FlowCanvas(parent=self, frame=frame)
self.sizer.Add(self.canvas, border=0, proportion=1, flag=wx.EXPAND | wx.ALL)
# add routine button
self.btnInsertRoutine = self.canvas.btnInsertRoutine = HoverButton(
self.btnPanel, -1, _translate('Insert Routine'), size=(120, 50),
style=wx.BORDER_NONE
)
self.btnInsertRoutine.Bind(wx.EVT_BUTTON, self.canvas.onInsertRoutine)
self.btnPanel.sizer.Add(self.btnInsertRoutine, border=6, flag=wx.EXPAND | wx.ALL)
# add loop button
self.btnInsertLoop = self.canvas.btnInsertLoop = HoverButton(
self.btnPanel, -1, _translate('Insert Loop'), size=(120, 50),
style=wx.BORDER_NONE
)
self.btnInsertLoop.Bind(wx.EVT_BUTTON, self.canvas.setLoopPoint1)
self.btnPanel.sizer.Add(self.btnInsertLoop, border=6, flag=wx.EXPAND | wx.ALL)
# align buttons to top
self.btnPanel.sizer.AddStretchSpacer(1)
self.Layout()
def _applyAppTheme(self):
self.SetBackgroundColour(colors.app['panel_bg'])
self.btnPanel.SetBackgroundColour(colors.app['panel_bg'])
self.Refresh()
class FlowCanvas(wx.ScrolledWindow, handlers.ThemeMixin):
def __init__(self, parent, frame, id=-1):
"""A panel that shows how the routines will fit together
"""
self.frame = frame
self.parent = parent
self.app = frame.app
self.dpi = self.app.dpi
wx.ScrolledWindow.__init__(self, parent, id,
style=wx.HSCROLL | wx.VSCROLL | wx.BORDER_NONE)
self.needUpdate = True
self.maxWidth = 50 * self.dpi
self.maxHeight = 2 * self.dpi
self.mousePos = None
# if we're adding a loop or routine then add spots to timeline
# self.drawNearestRoutinePoint = True
# self.drawNearestLoopPoint = False
# lists the x-vals of points to draw, eg loop locations:
self.pointsToDraw = []
# for flowSize, showLoopInfoInFlow:
self.appData = self.app.prefs.appData
# self.SetAutoLayout(True)
self.SetScrollRate(self.dpi // 16, self.dpi // 16)
# create a PseudoDC to record our drawing
self.pdc = PseudoDC()
if Version(wx.__version__) < Version('4.0.0a1'):
self.pdc.DrawRoundedRectangle = self.pdc.DrawRoundedRectangleRect
self.pen_cache = {}
self.brush_cache = {}
# vars for handling mouse clicks
self.hitradius = 5
self.dragid = -1
self.entryPointPosList = []
self.entryPointIDlist = []
self.gapsExcluded = []
# mode can also be 'loopPoint1','loopPoint2','routinePoint'
self.mode = 'normal'
self.insertingRoutine = ""
# for the context menu use the ID of the drawn icon to retrieve
# the component (loop or routine)
self.componentFromID = {}
self.contextMenuLabels = {
'remove': _translate('remove'),
'rename': _translate('rename')}
self.contextMenuItems = ['remove', 'rename']
self.contextItemFromID = {}
self.contextIDFromItem = {}
for item in self.contextMenuItems:
id = wx.NewIdRef()
self.contextItemFromID[id] = item
self.contextIDFromItem[item] = id
# self.btnInsertRoutine = wx.Button(self,-1,
# 'Insert Routine', pos=(10,10))
# self.btnInsertLoop = wx.Button(self,-1,'Insert Loop', pos=(10,30))
# use self.appData['flowSize'] to index a tuple to get a specific
# value, eg: (4,6,8)[self.appData['flowSize']]
self.flowMaxSize = 2 # upper limit on increaseSize
# bind events
self.Bind(wx.EVT_MOUSE_EVENTS, self.OnMouse)
self.Bind(wx.EVT_MOUSEWHEEL, self.OnScroll)
self.Bind(wx.EVT_PAINT, self.OnPaint)
idClear = wx.NewIdRef()
self.Bind(wx.EVT_MENU, self.clearMode, id=idClear)
aTable = wx.AcceleratorTable([
(wx.ACCEL_NORMAL, wx.WXK_ESCAPE, idClear)
])
self.SetAcceleratorTable(aTable)
# double buffered better rendering except if retina
self.SetDoubleBuffered(not self.frame.isRetina)
def _applyAppTheme(self, target=None):
"""Apply any changes which have been made to the theme since panel was last loaded"""
# Set background
self.SetBackgroundColour(colors.app['panel_bg'])
self.draw()
def clearMode(self, event=None):
"""If we were in middle of doing something (like inserting routine)
then end it, allowing user to cancel
"""
self.mode = 'normal'
self.insertingRoutine = None
for id in self.entryPointIDlist:
self.pdc.RemoveId(id)
self.entryPointPosList = []
self.entryPointIDlist = []
self.gapsExcluded = []
self.draw()
self.frame.SetStatusText("")
self.btnInsertRoutine.SetLabel(_translate('Insert Routine'))
self.btnInsertRoutine.Update()
self.btnInsertLoop.SetLabel(_translate('Insert Loop'))
self.btnInsertRoutine.Update()
def ConvertEventCoords(self, event):
xView, yView = self.GetViewStart()
xDelta, yDelta = self.GetScrollPixelsPerUnit()
return (event.GetX() + (xView * xDelta),
event.GetY() + (yView * yDelta))
def OffsetRect(self, r):
"""Offset the rectangle, r, to appear in the given position
in the window
"""
xView, yView = self.GetViewStart()
xDelta, yDelta = self.GetScrollPixelsPerUnit()
r.Offset((-(xView * xDelta), -(yView * yDelta)))
def onInsertRoutine(self, evt):
"""For when the insert Routine button is pressed - bring up
dialog and present insertion point on flow line.
see self.insertRoutine() for further info
"""
if self.mode.startswith('loopPoint'):
self.clearMode()
elif self.mode == 'routine':
# clicked again with label now being "Cancel..."
self.clearMode()
return
self.frame.SetStatusText(_translate(
"Select a Routine to insert (Esc to exit)"))
menu = wx.Menu()
self.routinesFromID = {}
id = wx.NewIdRef()
menu.Append(id, '(new)')
self.routinesFromID[id] = '(new)'
menu.Bind(wx.EVT_MENU, self.insertNewRoutine, id=id)
flow = self.frame.exp.flow
for name, routine in self.frame.exp.routines.items():
id = wx.NewIdRef()
item = menu.Append(id, name)
# Enable / disable each routine's button according to limits
if hasattr(routine, "limit"):
limitProgress = 0
for rt in flow:
limitProgress += int(isinstance(rt, type(routine)))
item.Enable(limitProgress < routine.limit or routine in flow)
self.routinesFromID[id] = name
menu.Bind(wx.EVT_MENU, self.onInsertRoutineSelect, id=id)
self.PopupMenu(menu)
menu.Bind(wx.EVT_MENU_CLOSE, self.clearMode)
menu.Destroy() # destroy to avoid mem leak
def insertNewRoutine(self, event):
"""selecting (new) is a short-cut for:
make new routine, insert it into the flow
"""
newRoutine = self.frame.routinePanel.createNewRoutine()
if newRoutine:
self.routinesFromID[event.GetId()] = newRoutine
self.onInsertRoutineSelect(event)
else:
self.clearMode()
def onInsertRoutineSelect(self, event):
"""User has selected a routine to be entered so bring up the
entrypoint marker and await mouse button press.
see self.insertRoutine() for further info
"""
self.mode = 'routine'
self.btnInsertRoutine.SetLabel(_translate('CANCEL Insert'))
self.frame.SetStatusText(_translate(
'Click where you want to insert the Routine, or CANCEL insert.'))
self.insertingRoutine = self.routinesFromID[event.GetId()]
x = self.getNearestGapPoint(0)
self.drawEntryPoints([x])
def insertRoutine(self, ii):
"""Insert a routine into the Flow knowing its name and location
onInsertRoutine() the button has been pressed so present menu
onInsertRoutineSelect() user selected the name so present entry points
OnMouse() user has selected a point on the timeline to insert entry
"""
rtn = self.frame.exp.routines[self.insertingRoutine]
self.frame.exp.flow.addRoutine(rtn, ii)
self.frame.addToUndoStack("ADD Routine `%s`" % rtn.name)
# reset flow drawing (remove entry point)
self.clearMode()
# enable/disable add loop button
self.btnInsertLoop.Enable(bool(len(self.frame.exp.flow)))
def setLoopPoint1(self, evt=None):
"""Someone pushed the insert loop button.
Fetch the dialog
"""
if self.mode == 'routine':
self.clearMode()
# clicked again, label is "Cancel..."
elif self.mode.startswith('loopPoint'):
self.clearMode()
return
self.btnInsertLoop.SetLabel(_translate('CANCEL insert'))
self.mode = 'loopPoint1'
self.frame.SetStatusText(_translate(
'Click where you want the loop to start/end, or CANCEL insert.'))
x = self.getNearestGapPoint(0)
self.drawEntryPoints([x])
def setLoopPoint2(self, evt=None):
"""We have the location of the first point, waiting to get the second
"""
self.mode = 'loopPoint2'
self.frame.SetStatusText(_translate(
'Click the other end for the loop'))
thisPos = self.entryPointPosList[0]
self.gapsExcluded = [thisPos]
self.gapsExcluded.extend(self.getGapPointsCrossingStreams(thisPos))
# is there more than one available point
diff = wx.GetMousePosition()[0] - self.GetScreenPosition()[0]
x = self.getNearestGapPoint(diff, exclude=self.gapsExcluded)
self.drawEntryPoints([self.entryPointPosList[0], x])
nAvailableGaps = len(self.gapMidPoints) - len(self.gapsExcluded)
if nAvailableGaps == 1:
self.insertLoop() # there's only one place - use it
def insertLoop(self, evt=None):
# bring up listbox to choose the routine to add, and / or a new one
loopDlg = DlgLoopProperties(frame=self.frame,
helpUrl=self.app.urls['builder.loops'])
startII = self.gapMidPoints.index(min(self.entryPointPosList))
endII = self.gapMidPoints.index(max(self.entryPointPosList))
if loopDlg.OK:
handler = loopDlg.currentHandler
self.frame.exp.flow.addLoop(handler,
startPos=startII, endPos=endII)
action = "ADD Loop `%s` to Flow" % handler.params['name'].val
self.frame.addToUndoStack(action)
self.clearMode()
self.draw()
def increaseSize(self, event=None):
if self.appData['flowSize'] == self.flowMaxSize:
self.appData['showLoopInfoInFlow'] = True
self.appData['flowSize'] = min(
self.flowMaxSize, self.appData['flowSize'] + 1)
self.clearMode() # redraws
def decreaseSize(self, event=None):
if self.appData['flowSize'] == 0:
self.appData['showLoopInfoInFlow'] = False
self.appData['flowSize'] = max(0, self.appData['flowSize'] - 1)
self.clearMode() # redraws
def editLoopProperties(self, event=None, loop=None):
# add routine points to the timeline
self.setDrawPoints('loops')
self.draw()
if 'conditions' in loop.params:
condOrig = loop.params['conditions'].val
condFileOrig = loop.params['conditionsFile'].val
title = loop.params['name'].val + ' Properties'
loopDlg = DlgLoopProperties(frame=self.frame,
helpUrl=self.app.urls['builder.loops'],
title=title, loop=loop)
if loopDlg.OK:
prevLoop = loop
if loopDlg.params['loopType'].val == 'staircase':
loop = loopDlg.stairHandler
elif loopDlg.params['loopType'].val == 'interleaved staircases':
loop = loopDlg.multiStairHandler
else:
# ['random','sequential', 'fullRandom', ]
loop = loopDlg.trialHandler
# if the loop is a whole new class then we can't just update the
# params
if loop.getType() != prevLoop.getType():
# get indices for start and stop points of prev loop
flow = self.frame.exp.flow
# find the index of the initiator
startII = flow.index(prevLoop.initiator)
# minus one because initiator will have been deleted
endII = flow.index(prevLoop.terminator) - 1
# remove old loop completely
flow.removeComponent(prevLoop)
# finally insert the new loop
flow.addLoop(loop, startII, endII)
self.frame.addToUndoStack("EDIT Loop `%s`" %
(loop.params['name'].val))
elif 'conditions' in loop.params:
loop.params['conditions'].val = condOrig
loop.params['conditionsFile'].val = condFileOrig
# remove the points from the timeline
self.setDrawPoints(None)
self.draw()
def OnMouse(self, event):
x, y = self.ConvertEventCoords(event)
handlerTypes = ('StairHandler', 'TrialHandler', 'MultiStairHandler')
if self.mode == 'normal':
if event.LeftDown():
icons = self.pdc.FindObjectsByBBox(x, y)
for thisIcon in icons:
# might intersect several and only one has a callback
if thisIcon in self.componentFromID:
comp = self.componentFromID[thisIcon]
if comp.getType() in handlerTypes:
self.editLoopProperties(loop=comp)
if comp.getType() in ['Routine'] + list(getAllStandaloneRoutines()):
self.frame.routinePanel.setCurrentRoutine(
routine=comp)
elif event.RightDown():
icons = self.pdc.FindObjectsByBBox(x, y)
# todo: clean-up remove `comp`, its unused
comp = None
for thisIcon in icons:
# might intersect several and only one has a callback
if thisIcon in self.componentFromID:
# loop through comps looking for Routine, or a Loop if
# no routine
thisComp = self.componentFromID[thisIcon]
if thisComp.getType() in handlerTypes:
comp = thisComp # unused
icon = thisIcon
if thisComp.getType() in ['Routine'] + list(getAllStandaloneRoutines()):
comp = thisComp
icon = thisIcon
break # we've found a Routine so stop looking
self.frame.routinePanel.setCurrentRoutine(comp)
try:
self._menuComponentID = icon
xy = wx.Point(event.X + self.parent.GetPosition()[0],
event.Y + self.parent.GetPosition()[1])
self.showContextMenu(self._menuComponentID, xy=xy)
except UnboundLocalError:
# right click but not on an icon
# might as well do something
self.Refresh()
elif event.Moving():
icons = self.pdc.FindObjectsByBBox(x, y)
if not icons:
self.frame.SetStatusText("")
for thisIcon in icons:
# might intersect several and only one has a callback
if thisIcon in self.componentFromID:
comp = self.componentFromID[thisIcon]
# indicate hover target in bottom bar
if comp.getType() in handlerTypes:
self.frame.SetStatusText(f"Loop ({comp.getType()}): {comp.name}")
else:
self.frame.SetStatusText(f"{comp.getType()}: {comp.name}")
elif self.mode == 'routine':
if event.LeftDown():
pt = self.entryPointPosList[0]
self.insertRoutine(ii=self.gapMidPoints.index(pt))
else: # move spot if needed
point = self.getNearestGapPoint(mouseX=x)
self.drawEntryPoints([point])
elif self.mode == 'loopPoint1':
if event.LeftDown():
self.setLoopPoint2()
else: # move spot if needed
point = self.getNearestGapPoint(mouseX=x)
self.drawEntryPoints([point])
elif self.mode == 'loopPoint2':
if event.LeftDown():
self.insertLoop()
else: # move spot if needed
point = self.getNearestGapPoint(mouseX=x,
exclude=self.gapsExcluded)
self.drawEntryPoints([self.entryPointPosList[0], point])
def OnScroll(self, evt):
xy = self.GetViewStart()
delta = int(evt.WheelRotation * self.dpi / 1600)
if evt.GetWheelAxis() == wx.MOUSE_WHEEL_VERTICAL:
# scroll vertically
self.Scroll(xy[0], xy[1] - delta)
if evt.GetWheelAxis() == wx.MOUSE_WHEEL_HORIZONTAL:
# scroll horizontally
self.Scroll(xy[0] + delta, xy[1])
def getNearestGapPoint(self, mouseX, exclude=()):
"""Get gap that is nearest to a particular mouse location
"""
d = 1000000000
nearest = None
for point in self.gapMidPoints:
if point in exclude:
continue
if (point - mouseX) ** 2 < d:
d = (point - mouseX) ** 2
nearest = point
return nearest
def getGapPointsCrossingStreams(self, gapPoint):
"""For a given gap point, identify the gap points that are
excluded by crossing a loop line
"""
gapArray = numpy.array(self.gapMidPoints)
nestLevels = numpy.array(self.gapNestLevels)
thisLevel = nestLevels[gapArray == gapPoint]
invalidGaps = (gapArray[nestLevels != thisLevel]).tolist()
return invalidGaps
def showContextMenu(self, component, xy):
menu = wx.Menu()
# get ID
# the ID is also the index to the element in the flow list
compID = self._menuComponentID
flow = self.frame.exp.flow
component = flow[compID]
compType = component.getType()
if compType == 'Routine':
for item in self.contextMenuItems:
id = self.contextIDFromItem[item]
menu.Append(id, self.contextMenuLabels[item])
menu.Bind(wx.EVT_MENU, self.onContextSelect, id=id)
self.frame.PopupMenu(menu, xy)
# destroy to avoid mem leak:
menu.Destroy()
else:
for item in self.contextMenuItems:
if item == 'rename':
continue
id = self.contextIDFromItem[item]
menu.Append(id, self.contextMenuLabels[item])
menu.Bind(wx.EVT_MENU, self.onContextSelect, id=id)
self.frame.PopupMenu(menu, xy)
# destroy to avoid mem leak:
menu.Destroy()
def onContextSelect(self, event):
"""Perform a given action on the component chosen
"""
# get ID
op = self.contextItemFromID[event.GetId()]
# the ID is also the index to the element in the flow list
compID = self._menuComponentID
flow = self.frame.exp.flow
component = flow[compID]
# if we have a Loop Initiator, remove the whole loop
if component.getType() == 'LoopInitiator':
component = component.loop
if op == 'remove':
self.removeComponent(component, compID)
self.frame.addToUndoStack(
"REMOVE `%s` from Flow" % component.params['name'])
if op == 'rename':
self.frame.renameRoutine(component)
def removeComponent(self, component, compID):
"""Remove either a Routine or a Loop from the Flow
"""
flow = self.frame.exp.flow
if component.getType() in ['Routine'] + list(getAllStandaloneRoutines()):
# check whether this will cause a collapsed loop
# prev and next elements on flow are a loop init/end
prevIsLoop = nextIsLoop = False
if compID > 0: # there is at least one preceding
prevIsLoop = (flow[compID - 1]).getType() == 'LoopInitiator'
if len(flow) > (compID + 1): # there is at least one more compon
nextIsLoop = (flow[compID + 1]).getType() == 'LoopTerminator'
if prevIsLoop and nextIsLoop:
# because flow[compID+1] is a terminator
loop = flow[compID + 1].loop
msg = _translate('The "%s" Loop is about to be deleted as '
'well (by collapsing). OK to proceed?')
title = _translate('Impending Loop collapse')
warnDlg = dialogs.MessageDialog(
parent=self.frame, message=msg % loop.params['name'],
type='Warning', title=title)
resp = warnDlg.ShowModal()
if resp in [wx.ID_CANCEL, wx.ID_NO]:
return # abort
elif resp == wx.ID_YES:
# make recursive calls to this same method until success
# remove the loop first
self.removeComponent(loop, compID)
# because the loop has been removed ID is now one less
self.removeComponent(component, compID - 1)
return # have done the removal in final successful call
# remove name from namespace only if it's a loop;
# loops exist only in the flow
elif 'conditionsFile' in component.params:
conditionsFile = component.params['conditionsFile'].val
if conditionsFile and conditionsFile not in ['None', '']:
try:
trialList, fieldNames = data.importConditions(
conditionsFile, returnFieldNames=True)
for fname in fieldNames:
self.frame.exp.namespace.remove(fname)
except Exception:
msg = ("Conditions file %s couldn't be found so names not"
" removed from namespace")
logging.debug(msg % conditionsFile)
self.frame.exp.namespace.remove(component.params['name'].val)
# perform the actual removal
flow.removeComponent(component, id=compID)
self.draw()
# enable/disable add loop button
self.btnInsertLoop.Enable(bool(len(flow)))
def OnPaint(self, event):
# Create a buffered paint DC. It will create the real
# wx.PaintDC and then blit the bitmap to it when dc is
# deleted.
dc = wx.GCDC(wx.BufferedPaintDC(self))
# use PrepareDC to set position correctly
self.PrepareDC(dc)
# we need to clear the dc BEFORE calling PrepareDC
bg = wx.Brush(self.GetBackgroundColour())
dc.SetBackground(bg)
dc.Clear()
# create a clipping rect from our position and size
# and the Update Region
xv, yv = self.GetViewStart()
dx, dy = self.GetScrollPixelsPerUnit()
x, y = (xv * dx, yv * dy)
rgn = self.GetUpdateRegion()
rgn.Offset(x, y)
r = rgn.GetBox()
# draw to the dc using the calculated clipping rect
self.pdc.DrawToDCClipped(dc, r)
def draw(self, evt=None):
"""This is the main function for drawing the Flow panel.
It should be called whenever something changes in the exp.
This then makes calls to other drawing functions,
like drawEntryPoints...
"""
if not hasattr(self.frame, 'exp'):
# we haven't yet added an exp
return
# retrieve the current flow from the experiment
expFlow = self.frame.exp.flow
pdc = self.pdc
# use the ID of the drawn icon to retrieve component (loop or routine)
self.componentFromID = {}
pdc.Clear() # clear the screen
pdc.RemoveAll() # clear all objects (icon buttons)
font = self.GetFont()
# draw the main time line
self.linePos = (1 * self.dpi, 0.5 * self.dpi) # x,y of start
gap = self.dpi // (6, 4, 2)[self.appData['flowSize']]
dLoopToBaseLine = (15, 25, 43)[self.appData['flowSize']]
dBetweenLoops = (20, 24, 30)[self.appData['flowSize']]
# guess virtual size; nRoutines wide by nLoops high
# make bigger than needed and shrink later
nRoutines = len(expFlow)
nLoops = 0
for entry in expFlow:
if entry.getType() == 'LoopInitiator':
nLoops += 1
sizeX = nRoutines * self.dpi * 2
sizeY = nLoops * dBetweenLoops + dLoopToBaseLine * 3
self.SetVirtualSize(size=(int(sizeX), int(sizeY)))
# this has type `float` for values, needs to be `int`
linePosX, linePosY = [int(x) for x in self.linePos]
# step through components in flow, get spacing from text size, etc
currX = self.linePos[0] # float
lineId = wx.NewIdRef()
pdc.SetPen(wx.Pen(colour=colors.app['fl_flowline_bg']))
pdc.DrawLine(
x1=linePosX - gap,
y1=linePosY,
x2=linePosX,
y2=linePosY)
# NB the loop is itself the key, value is further info about it
self.loops = {}
nestLevel = 0
maxNestLevel = 0
self.gapMidPoints = [currX - gap // 2]
self.gapNestLevels = [0]
for ii, entry in enumerate(expFlow):
if entry.getType() == 'LoopInitiator':
# NB the loop is itself the dict key!?
self.loops[entry.loop] = {
'init': currX, 'nest': nestLevel, 'id': ii}
nestLevel += 1 # start of loop so increment level of nesting
maxNestLevel = max(nestLevel, maxNestLevel)
elif entry.getType() == 'LoopTerminator':
# NB the loop is itself the dict key!
self.loops[entry.loop]['term'] = currX
nestLevel -= 1 # end of loop so decrement level of nesting
elif entry.getType() == 'Routine' or entry.getType() in getAllStandaloneRoutines():
# just get currX based on text size, don't draw anything yet:
currX = self.drawFlowRoutine(pdc, entry, id=ii,
pos=[currX, linePosY - 10],
draw=False)
self.gapMidPoints.append(currX + gap // 2)
self.gapNestLevels.append(nestLevel)
pdc.SetId(lineId)
pdc.SetPen(wx.Pen(colour=colors.app['fl_flowline_bg']))
pdc.DrawLine(
x1=int(currX),
y1=linePosY,
x2=int(currX + gap),
y2=linePosY)
currX += gap
lineRect = wx.Rect(
linePosX - 2,
linePosY - 2,
int(currX) - linePosX + 2,
4)
pdc.SetIdBounds(lineId, lineRect)
# draw the loops first:
maxHeight = 0
for thisLoop in self.loops:
thisInit = self.loops[thisLoop]['init']
thisTerm = self.loops[thisLoop]['term']
thisNest = maxNestLevel - self.loops[thisLoop]['nest'] - 1
thisId = self.loops[thisLoop]['id']
height = (linePosY + dLoopToBaseLine +
thisNest * dBetweenLoops)
self.drawLoop(pdc, thisLoop, id=thisId,
startX=thisInit, endX=thisTerm,
base=linePosY, height=height)
self.drawLoopStart(pdc, pos=[thisInit, linePosY])
self.drawLoopEnd(pdc, pos=[thisTerm, linePosY])
if height > maxHeight:
maxHeight = height
# draw routines second (over loop lines):
currX = int(self.linePos[0])
for ii, entry in enumerate(expFlow):
if entry.getType() == 'Routine' or entry.getType() in getAllStandaloneRoutines():
currX = self.drawFlowRoutine(
pdc, entry, id=ii, pos=[currX, linePosY - 10])
pdc.SetPen(wx.Pen(wx.Pen(colour=colors.app['fl_flowline_bg'])))
pdc.DrawLine(
x1=int(currX),
y1=linePosY,
x2=int(currX + gap),
y2=linePosY)
currX += gap
self.SetVirtualSize(size=(currX + 100, maxHeight + 50))
self.drawLineStart(pdc, (linePosX - gap, linePosY))
self.drawLineEnd(pdc, (currX, linePosY))
# refresh the visible window after drawing (using OnPaint)
self.Refresh()
def drawEntryPoints(self, posList):
ptSize = (3, 4, 5)[self.appData['flowSize']]
for n, pos in enumerate(posList):
pos = int(pos)
if n >= len(self.entryPointPosList):
# draw for first time
id = wx.NewIdRef()
self.entryPointIDlist.append(id)
self.pdc.SetId(id)
self.pdc.SetBrush(wx.Brush(colors.app['fl_flowline_bg']))
self.pdc.DrawCircle(pos, int(self.linePos[1]), ptSize)
r = self.pdc.GetIdBounds(id)
self.OffsetRect(r)
self.RefreshRect(r, False)
elif pos == self.entryPointPosList[n]:
pass # nothing to see here, move along please :-)
else:
# move to new position
dx = pos - self.entryPointPosList[n]
dy = 0
r = self.pdc.GetIdBounds(self.entryPointIDlist[n])
self.pdc.TranslateId(self.entryPointIDlist[n], int(dx), int(dy))
r2 = self.pdc.GetIdBounds(self.entryPointIDlist[n])
# combine old and new locations to get redraw area
rectToRedraw = r.Union(r2)
rectToRedraw.Inflate(4, 4)
self.OffsetRect(rectToRedraw)
self.RefreshRect(rectToRedraw, False)
self.entryPointPosList = posList
# refresh the visible window after drawing (using OnPaint)
self.Refresh()
def setDrawPoints(self, ptType, startPoint=None):
"""Set the points of 'routines', 'loops', or None
"""
if ptType == 'routines':
self.pointsToDraw = self.gapMidPoints
elif ptType == 'loops':
self.pointsToDraw = self.gapMidPoints
else:
self.pointsToDraw = []
def drawLineStart(self, dc, pos):
# draw bar at start of timeline; circle looked bad, offset vertically
tmpId = wx.NewIdRef(count=1)
dc.SetId(tmpId)
ptSize = (9, 9, 12)[self.appData['flowSize']]
thic = (1, 1, 2)[self.appData['flowSize']]
dc.SetBrush(wx.Brush(colors.app['fl_flowline_bg']))
dc.SetPen(wx.Pen(colors.app['fl_flowline_bg']))
posX, posY = pos
dc.DrawPolygon(
[[0, -ptSize], [thic, -ptSize], [thic, ptSize], [0, ptSize]],
int(posX), int(posY))
def drawLineEnd(self, dc, pos):
# draws arrow at end of timeline
tmpId = wx.NewIdRef(count=1)
dc.SetId(tmpId)
dc.SetBrush(wx.Brush(colors.app['fl_flowline_bg']))
dc.SetPen(wx.Pen(colors.app['fl_flowline_bg']))
posX, posY = pos
dc.DrawPolygon([[0, -3], [5, 0], [0, 3]], int(posX), int(posY))
# dc.SetIdBounds(tmpId,wx.Rect(pos[0],pos[1]+3,5,6))
def drawLoopEnd(self, dc, pos, downwards=True):
# define the right side of a loop but draw nothing
# idea: might want an ID for grabbing and relocating the loop endpoint
tmpId = wx.NewIdRef()
dc.SetId(tmpId)
# dc.SetBrush(wx.Brush(wx.Colour(0,0,0, 250)))
# dc.SetPen(wx.Pen(wx.Colour(0,0,0, 255)))
size = (3, 4, 5)[self.appData['flowSize']]
# if downwards:
# dc.DrawPolygon([[size, 0], [0, size], [-size, 0]],
# pos[0], pos[1] + 2 * size) # points down
# else:
# dc.DrawPolygon([[size, size], [0, 0], [-size, size]],
# pos[0], pos[1]-3*size) # points up
posX, posY = pos
doubleSize = int(2 * size)
dc.SetIdBounds(tmpId, wx.Rect(
int(posX) - size, int(posY) - size,
doubleSize,
doubleSize))
return
def drawLoopStart(self, dc, pos, downwards=True):
# draws direction arrow on left side of a loop
tmpId = wx.NewIdRef()
dc.SetId(tmpId)
dc.SetBrush(wx.Brush(colors.app['fl_flowline_bg']))
dc.SetPen(wx.Pen(colors.app['fl_flowline_bg']))
size = (3, 4, 5)[self.appData['flowSize']]
offset = (3, 2, 0)[self.appData['flowSize']]
posX, posY = [int(x) for x in pos]
if downwards:
dc.DrawPolygon(
[[size, size], [0, 0], [-size, size]],
posX, posY + 3 * size - offset) # points up
else:
dc.DrawPolygon(
[[size, 0], [0, size], [-size, 0]],
posX,
posY - 4 * size) # points down
doubleSize = int(2 * size)
dc.SetIdBounds(tmpId, wx.Rect(
posX - size,
posY - size,
doubleSize,
doubleSize))
def drawFlowRoutine(self, dc, routine, id, pos=(0, 0), draw=True):
"""Draw a box to show a routine on the timeline
draw=False is for a dry-run, esp to compute and return size
without drawing or setting a pdc ID
"""
name = routine.name
if self.appData['flowSize'] == 0 and len(name) > 5:
name = ' ' + name[:4] + '..'
else:
name = ' ' + name + ' '
if draw:
dc.SetId(id)
font = self.GetFont()
if sys.platform == 'darwin':
fontSizeDelta = (9, 6, 0)[self.appData['flowSize']]
font.SetPointSize(1400 // self.dpi - fontSizeDelta)
elif sys.platform.startswith('linux'):
fontSizeDelta = (6, 4, 0)[self.appData['flowSize']]
font.SetPointSize(1400 // self.dpi - fontSizeDelta)
else:
fontSizeDelta = (8, 4, 0)[self.appData['flowSize']]
font.SetPointSize(1000 // self.dpi - fontSizeDelta)
# if selected, bold text
if routine == self.frame.routinePanel.getCurrentRoutine():
font.SetWeight(wx.FONTWEIGHT_BOLD)
else:
font.SetWeight(wx.FONTWEIGHT_NORMAL)
maxTime, nonSlip = routine.getMaxTime()
if hasattr(routine, "disabled") and routine.disabled:
rtFill = colors.app['rt_comp_disabled']
rtEdge = colors.app['rt_comp_disabled']
rtText = colors.app['fl_routine_fg']
elif nonSlip:
rtFill = colors.app['fl_routine_bg_nonslip']
rtEdge = colors.app['fl_routine_bg_nonslip']
rtText = colors.app['fl_routine_fg']
else:
rtFill = colors.app['fl_routine_bg_slip']
rtEdge = colors.app['fl_routine_bg_slip']
rtText = colors.app['fl_routine_fg']
# get size based on text
self.SetFont(font)
if draw:
dc.SetFont(font)
w, h = self.GetFullTextExtent(name)[0:2]
pos = [int(x) for x in pos] # explicit type conversion for position
pad = (5, 10, 20)[self.appData['flowSize']]
# draw box
rect = wx.Rect(pos[0], pos[1] + 2 - self.appData['flowSize'],
w + pad, h + pad)
endX = pos[0] + w + pad
# the edge should match the text, unless selected
if draw:
dc.SetPen(wx.Pen(wx.Colour(rtEdge[0], rtEdge[1],
rtEdge[2], wx.ALPHA_OPAQUE)))
dc.SetBrush(wx.Brush(rtFill))
dc.DrawRoundedRectangle(
rect, (4, 6, 8)[self.appData['flowSize']])
# draw text
dc.SetTextForeground(rtText)
dc.DrawLabel(name, rect, alignment=wx.ALIGN_CENTRE)
if nonSlip and self.appData['flowSize'] != 0:
font.SetPointSize(int(font.GetPointSize() * 0.6))
dc.SetFont(font)
_align = wx.ALIGN_CENTRE | wx.ALIGN_BOTTOM
timeRect = wx.Rect(rect.Left, rect.Top, rect.Width, rect.Height-2)
dc.DrawLabel("(%.2fs)" % maxTime, timeRect, alignment=_align)
self.componentFromID[id] = routine
# set the area for this component
dc.SetIdBounds(id, rect)
return endX
def drawLoop(self, dc, loop, id, startX, endX, base, height,
downwards=True):
if downwards:
up = -1
else:
up = +1
# draw loop itself, as transparent rect with curved corners
tmpId = wx.NewIdRef()
dc.SetId(tmpId)
# extra distance, in both h and w for curve
curve = (6, 11, 15)[self.appData['flowSize']]
# convert args types to `int`
startX, endX, base, height = [
int(x) for x in (startX, endX, base, height)]
yy = [base, height + curve * up, height +
curve * up // 2, height] # for area
dc.SetPen(wx.Pen(colors.app['fl_flowline_bg']))
vertOffset = 0 # 1 is interesting too
area = wx.Rect(startX, base + vertOffset,
endX - startX, max(yy) - min(yy))
dc.SetBrush(wx.Brush(wx.Colour(0, 0, 0, 0), style=wx.TRANSPARENT))
# draws outline:
dc.DrawRoundedRectangle(area, curve)
dc.SetIdBounds(tmpId, area)
flowsize = self.appData['flowSize'] # 0, 1, or 2
# add a name label, loop info, except at smallest size
name = loop.params['name'].val
_show = self.appData['showLoopInfoInFlow']
if _show and flowsize:
_cond = 'conditions' in list(loop.params)
if _cond and loop.params['conditions'].val:
xnumTrials = 'x' + str(len(loop.params['conditions'].val))
else:
xnumTrials = ''
name += ' (' + str(loop.params['nReps'].val) + xnumTrials
abbrev = ['', # for flowsize == 0
{'random': 'rand.',
'sequential': 'sequ.',
'fullRandom': 'f-ran.',
'staircase': 'stair.',
'interleaved staircases': "int-str."},
{'random': 'random',
'sequential': 'sequential',
'fullRandom': 'fullRandom',
'staircase': 'staircase',
'interleaved staircases': "interl'vd stairs"}]
name += ' ' + abbrev[flowsize][loop.params['loopType'].val] + ')'
if flowsize == 0:
if len(name) > 9:
name = ' ' + name[:8] + '..'
else:
name = ' ' + name[:9]
else:
name = ' ' + name + ' '
dc.SetId(id)
font = self.GetFont()
font.SetWeight(wx.FONTWEIGHT_NORMAL)
if sys.platform == 'darwin':
basePtSize = (650, 750, 900)[flowsize]
elif sys.platform.startswith('linux'):
basePtSize = (750, 850, 1000)[flowsize]
else:
basePtSize = (700, 750, 800)[flowsize]
font.SetPointSize(basePtSize // self.dpi)
self.SetFont(font)
dc.SetFont(font)
# get size based on text
pad = (5, 8, 10)[self.appData['flowSize']]
w, h = self.GetFullTextExtent(name)[0:2]
x = startX + (endX - startX) // 2 - w // 2 - pad // 2
y = (height - h // 2)
# draw box
rect = wx.Rect(int(x), int(y), int(w + pad), int(h + pad))
# the edge should match the text
dc.SetPen(wx.Pen(colors.app['fl_flowline_bg']))
# try to make the loop fill brighter than the background canvas:
dc.SetBrush(wx.Brush(colors.app['fl_flowline_bg']))
dc.DrawRoundedRectangle(rect, (4, 6, 8)[flowsize])
# draw text
dc.SetTextForeground(colors.app['fl_flowline_fg'])
dc.DrawText(name, x + pad // 2, y + pad // 2)
self.componentFromID[id] = loop
# set the area for this component
dc.SetIdBounds(id, rect)
class BuilderRibbon(ribbon.FrameRibbon):
def __init__(self, parent):
# initialize
ribbon.FrameRibbon.__init__(self, parent)
# --- File ---
self.addSection(
"file", label=_translate("File"), icon="file"
)
# file new
self.addButton(
section="file", name="new", label=_translate("New"), icon="filenew",
tooltip=_translate("Create new experiment file"),
callback=parent.app.newBuilderFrame
)
# file open
self.addButton(
section="file", name="open", label=_translate("Open"), icon="fileopen",
tooltip=_translate("Open an existing experiment file"),
callback=parent.fileOpen
)
# file save
self.addButton(
section="file", name="save", label=_translate("Save"), icon="filesave",
tooltip=_translate("Save current experiment file"),
callback=parent.fileSave
)
# file save as
self.addButton(
section="file", name="saveas", label=_translate("Save as..."), icon="filesaveas",
tooltip=_translate("Save current experiment file as..."),
callback=parent.fileSaveAs
)
self.addSeparator()
# --- Edit ---
self.addSection(
"edit", label=_translate("Edit"), icon="edit"
)
# undo
self.addButton(
section="edit", name="undo", label=_translate("Undo"), icon="undo",
tooltip=_translate("Undo last action"),
callback=parent.undo
)
# redo
self.addButton(
section="edit", name="redo", label=_translate("Redo"), icon="redo",
tooltip=_translate("Redo last action"),
callback=parent.redo
)
self.addSeparator()
# --- Tools ---
self.addSection(
"experiment", label=_translate("Experiment"), icon="experiment"
)
# monitor center
self.addButton(
section="experiment", name='monitor', label=_translate('Monitor center'),
icon="monitors",
tooltip=_translate("Monitor settings and calibration"),
callback=parent.app.openMonitorCenter
)
# settings
self.addButton(
section="experiment", name='expsettings', label=_translate('Experiment settings'), icon="expsettings",
tooltip=_translate("Edit experiment settings"),
callback=parent.setExperimentSettings
)
# switch run/pilot
self.addSwitchCtrl(
section="experiment", name="pyswitch",
labels=(_translate("Pilot"), _translate("Run")),
startMode=0, callback=parent.onRunModeToggle,
style=wx.HORIZONTAL
)
# send to runner
self.addButton(
section="experiment", name='sendRunner', label=_translate('Runner'), icon="runner",
tooltip=_translate("Send experiment to Runner"),
callback=parent.sendToRunner
)
# send to runner (pilot icon)
self.addButton(
section="experiment", name='pilotRunner', label=_translate('Runner'),
icon="runnerPilot",
tooltip=_translate("Send experiment to Runner"),
callback=parent.sendToRunner
)
self.addSeparator()
# --- Python ---
self.addSection(
"py", label=_translate("Desktop"), icon="desktop"
)
# compile python
self.addButton(
section="py", name="pycompile", label=_translate('Write Python'), icon='compile_py',
tooltip=_translate("Write experiment as a Python script"),
callback=parent.compileScript
)
# pilot Py
self.addButton(
section="py", name="pypilot", label=_translate("Pilot"), icon='pyPilot',
tooltip=_translate("Run the current script in Python with piloting features on"),
callback=parent.pilotFile
)
# run Py
self.addButton(
section="py", name="pyrun", label=_translate("Run"), icon='pyRun',
tooltip=_translate("Run the current script in Python"),
callback=parent.runFile
)
self.addSeparator()
# --- JS ---
self.addSection(
"browser", label=_translate("Browser"), icon="browser"
)
# compile JS
self.addButton(
section="browser", name="jscompile", label=_translate('Write JS'), icon='compile_js',
tooltip=_translate("Write experiment as a JavaScript (JS) script"),
callback=parent.fileExport
)
# pilot JS
self.addButton(
section="browser", name="jspilot", label=_translate("Pilot in browser"),
icon='jsPilot',
tooltip=_translate("Pilot experiment locally in your browser"),
callback=parent.onPavloviaDebug
)
# run JS
self.addButton(
section="browser", name="jsrun", label=_translate("Run on Pavlovia"), icon='jsRun',
tooltip=_translate("Run experiment on Pavlovia"),
callback=parent.onPavloviaRun
)
# sync project
self.addButton(
section="browser", name="pavsync", label=_translate("Sync"), icon='pavsync',
tooltip=_translate("Sync project with Pavlovia"),
callback=parent.onPavloviaSync
)
self.addSeparator()
# --- JS ---
self.addSection(
"pavlovia", label=_translate("Pavlovia"), icon="pavlovia"
)
# pavlovia user
self.addPavloviaUserCtrl(
section="pavlovia", name="pavuser", frame=parent
)
# pavlovia project
self.addPavloviaProjectCtrl(
section="pavlovia", name="pavproject", frame=parent
)
self.addSeparator()
# --- Plugin sections ---
self.addPluginSections("psychopy.app.builder")
# --- Views ---
self.addStretchSpacer()
self.addSeparator()
self.addSection(
"views", label=_translate("Views"), icon="windows"
)
# show Builder
self.addButton(
section="views", name="builder", label=_translate("Show Builder"), icon="showBuilder",
tooltip=_translate("Switch to Builder view"),
callback=parent.app.showBuilder
).Disable()
# show Coder
self.addButton(
section="views", name="coder", label=_translate("Show Coder"), icon="showCoder",
tooltip=_translate("Switch to Coder view"),
callback=parent.app.showCoder
)
# show Runner
self.addButton(
section="views", name="runner", label=_translate("Show Runner"), icon="showRunner",
tooltip=_translate("Switch to Runner view"),
callback=parent.app.showRunner
)
def extractText(stream):
"""Take a byte stream (or any file object of type b?) and return
:param stream: stream from wx.Process or any byte stream from a file
:return: text converted to unicode ready for appending to wx text view
"""
return stream.read().decode('utf-8')
| 189,927
|
Python
|
.py
| 4,228
| 32.906575
| 120
| 0.575946
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,832
|
__init__.py
|
psychopy_psychopy/psychopy/app/builder/__init__.py
|
"""
Builder is the main GUI experiment building frame
"""
from ... import experiment
from .builder import BuilderFrame
| 119
|
Python
|
.py
| 5
| 22.8
| 49
| 0.798246
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,833
|
validators.py
|
psychopy_psychopy/psychopy/app/builder/validators.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Part of the PsychoPy library
# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd.
# Distributed under the terms of the GNU General Public License (GPL).
"""Module containing validators for various parameters.
"""
import re
import wx
import psychopy.experiment.utils
from psychopy.tools import stringtools
from psychopy.localization import _translate
from . import experiment
from packaging.version import Version
from psychopy.tools.fontmanager import FontManager
fontMGR = FontManager()
if Version(wx.__version__) < Version('4.0.0a1'):
_ValidatorBase = wx.PyValidator
else:
_ValidatorBase = wx.Validator
# Symbolic constants representing the 'kind' of warning for instances of
# `ValidatorWarning`.
VALIDATOR_WARNING_NONE = 0
VALIDATOR_WARNING_NAME = 1
VALIDATOR_WARNING_SYNTAX = 2
VALIDATOR_WARNING_FONT_MISSING = 3
VALIDATOR_WARNING_COUNT = 4 # increment when adding more
class ValidatorWarning:
"""Class for validator warnings.
These are used internally by the `WarningManager`, do not create instances
of this class unless you know what you're doing with them.
Parameters
----------
parent : wx.Window or wx.Panel
Dialog associate with this warning.
control : wx.Window or wx.Panel
Control associated with the validator which threw this warning.
msg : str
Message text associated with the warning to be displayed.
kind : int
Symbolic constant representing the type of warning. Values can be one of
`VALIDATOR_WARNING_NONE`, `VALIDATOR_WARNING_NAME`,
`VALIDATOR_WARNING_SYNTAX` or `VALIDATOR_WARNING_FONT_MISSING`.
"""
__slots__ = [
'_parent',
'_control',
'_msg',
'_kind']
def __init__(self, parent, control, msg="", kind=VALIDATOR_WARNING_NONE):
self.parent = parent
self.control = control
self.msg = msg
self.kind = kind
@property
def parent(self):
"""Dialog associate with this warning (`wx.Window` or similar)."""
return self._parent
@parent.setter
def parent(self, value):
self._parent = value
@property
def control(self):
"""Control associated with the validator which threw this warning
(`wx.Window` or similar).
"""
return self._control
@control.setter
def control(self, value):
self._control = value
@property
def msg(self):
"""Message text associated with the warning to be displayed (`str`).
"""
return self._msg
@msg.setter
def msg(self, value):
self._msg = str(value)
@property
def kind(self):
"""Symbolic constant representing the type of warning (`int`). Values
can be one of `VALIDATOR_WARNING_NONE`, `VALIDATOR_WARNING_NAME`,
`VALIDATOR_WARNING_SYNTAX` or `VALIDATOR_WARNING_FONT_MISSING`.
"""
return self._kind
@kind.setter
def kind(self, value):
value = int(value)
assert VALIDATOR_WARNING_NONE <= value < VALIDATOR_WARNING_COUNT
self._kind = value
@property
def isSyntaxWarning(self):
"""`True` if this is a syntax warning (`bool`)."""
return self._kind == VALIDATOR_WARNING_SYNTAX
@property
def isNameWarning(self):
"""`True` if this is a namespace warning (`bool`)."""
return self._kind == VALIDATOR_WARNING_NAME
@property
def allowed(self):
"""`True` if this is a non-critical message which doesn't disable the OK button"""
return self.kind in [VALIDATOR_WARNING_FONT_MISSING]
class WarningManager:
"""Manager for warnings produced by validators associated with controls
within the component properties dialog. Assumes that the `parent` dialog
uses a standardized convention for attribute names for all components.
Each control can only have a single warning at a time in the current
implementation of this class.
Warnings
--------
Do not make strong references to instances of this class outside of the
`parent` dialog. This class must be destroyed along with the `parent` object
when the `parent` is deleted. This also goes for any `ValidatorWarning`
objects referenced by this class.
Parameters
----------
parent : wx.Window
Component properties dialog or panel.
"""
def __init__(self, parent):
self._parent = parent
# Dictionary for storing warnings, keys are IDs for the controls that
# produced them. In the future we should use wx object names to
# reference these objects instead of IDs.
self._warnings = {}
# create an output label box for the parent
self.output = wx.StaticText(
self._parent, label="", style=wx.ALIGN_CENTRE_HORIZONTAL)
self.output.SetForegroundColour(wx.RED)
@property
def OK(self):
"""`True` if there are no warnings (`bool`)."""
if len(self._warnings) == 0:
return True
else:
return all(warning.allowed for warning in self._warnings.values())
@property
def parent(self):
"""Parent dialog (`wx.Panel` or `wx.Window`). This attribute is
read-only."""
return self._parent
@property
def warnings(self):
"""Raw dictionary of warning objects (`dict`). Keys are IDs for the
objects representing controls as integers, values are the
`ValidatorWarning` instances associated with them."""
return self._parent
@property
def messages(self):
"""List of warning messages (`list`). Messages are displayed in the
order they have been added.
"""
if not self._warnings: # no warnings, return empty string
return []
warnings = self._warnings.values() # warning objects
return [warning.msg for warning in warnings]
def getControlsWithWarnings(self):
"""Get a list of controls which have active warnings (`list`). You can
use this to process controls which still have warnings registered to
them.
"""
if not self._warnings: # no active warnings
return []
_, warnings = self._warnings.items()
return [warning.control for warning in warnings]
def setWarning(self, control, msg='', kind=VALIDATOR_WARNING_NONE):
"""Set a warning for a control. A control can only have one active
warning associate with it at any given time.
Parameters
----------
control : wx.Window or wx.Panel
Control to set an active warning for.
msg : str
Warning message text (e.g., "Syntax error").
kind : int
Symbolic constant representing the type of warning (e.g.,
`VALIDATOR_WARN_SYNTAX`).
"""
self._warnings[id(control)] = ValidatorWarning(
self.parent, control, msg, kind)
def getWarning(self, control):
"""Get an active warning associated with the control.
Parameters
----------
control : wx.Window or wx.Panel
Control to check if there is a warning active against it.
Returns
-------
ValidatorWarning or None
Warning validator if there is warning, else None.
"""
try:
return self._warnings[id(control)]
except KeyError:
return None
def clearWarning(self, control):
"""Clear the warning associated with a given control.
Parameters
----------
control : wx.Window or wx.Panel
Control to clear any warnings against it.
Returns
-------
bool
`True` if the warning was cleared. `False` if there was no warning
associated with the `control` provided.
"""
wasCleared = True
try:
del self._warnings[id(control)]
except KeyError:
wasCleared = False
return wasCleared
def validate(self, control=None):
"""Validate one or many controls.
Calling this will re-run validation on all controls which have active
warnings presently registered to them. If the specified control(s) no
longer generate warnings, it will be removed from the manager.
This can be called make sure that all warnings have been addressed.
"""
pass
def _lockout(self, enable=True):
"""Lockout the dialog, preventing user changes from being applied.
Parameters
----------
enable : bool
Lockout the dialog if `True`. `False` will re-enable the OK button.
Assumes the parent dialog has an `ok` attribute which points to a
`wx.Button` object or similar.
"""
if hasattr(self.parent, 'ok'):
okButton = self.parent.ok
elif hasattr(self.parent, 'OKbtn'): # another option ...
okButton = self.parent.OKbtn
else:
# raise AttributeError("Parent object does not have an OK button.")
return # nop better here?
if isinstance(okButton, wx.Button):
okButton.Enable(enable)
def showWarning(self):
"""Show the active warnings. Disables the OK button if present.
"""
self._lockout(self.OK) # enable / disable ok button
# If there's any errors to show, show them
messages = self.messages
if messages:
self.output.SetLabel("\n".join(messages))
else:
self.output.SetLabel("")
# Update sizer
sizer = self.output.GetContainingSizer()
if sizer:
sizer.Layout()
class BaseValidator(_ValidatorBase):
"""Component name validator for _BaseParamsDlg class. It depends on access
to an experiment namespace.
Validate calls check, which needs to be implemented per class.
Messages are passed to user as text in nameOklabel.
See Also
--------
_BaseParamsDlg
"""
def __init__(self):
super(BaseValidator, self).__init__()
def Clone(self):
return self.__class__()
def Validate(self, parent):
# we need to find the dialog to which the Validate event belongs
# (the event might be fired by a sub-panel and won't have builder exp)
while not hasattr(parent, 'warnings'):
try:
parent = parent.GetParent()
except Exception:
raise AttributeError("Could not find warnings manager")
self.check(parent)
return True
def TransferFromWindow(self):
return True
def TransferToWindow(self):
return True
def check(self, parent):
raise NotImplementedError
class NameValidator(BaseValidator):
"""Validation checks if the value in Name field is a valid Python
identifier and if it does not clash with existing names.
"""
def __init__(self):
super(NameValidator, self).__init__()
def check(self, parent):
"""Checks namespace.
Parameters
----------
parent : object
Component properties dialog or similar.
"""
control = self.GetWindow()
newName = control.GetValue()
msg, OK = '', True # until we find otherwise
if newName == '':
msg = _translate("Missing name")
OK = False
else:
namespace = parent.frame.exp.namespace
used = namespace.exists(newName)
sameAsOldName = bool(newName == parent.params['name'].val)
if used and not sameAsOldName:
# NOTE: formatted string literal doesn't work with _translate().
# So, we have to call format() after _translate() is applied.
msg = _translate(
"That name is in use (by {used}). Try another name."
).format(used=_translate(used))
OK = False
elif not namespace.isValid(newName): # valid as a var name
msg = _translate("Name can only contain letters, numbers and underscores (_), no spaces or other symbols")
OK = False
# warn but allow, chances are good that its actually ok
elif namespace.isPossiblyDerivable(newName):
msg = _translate(namespace.isPossiblyDerivable(newName))
OK = True
if not OK:
parent.warnings.setWarning(
control, msg=msg, kind=VALIDATOR_WARNING_NAME)
else:
parent.warnings.clearWarning(control)
parent.warnings.showWarning()
class CodeSnippetValidator(BaseValidator):
"""Validation checks if field value is intended to be Python code.
If so, check that it is valid Python, and if valid, check whether
it contains bad identifiers (currently only self-reference).
@see: _BaseParamsDlg
"""
def __init__(self, fieldName, displayName=None):
super(CodeSnippetValidator, self).__init__()
self.fieldName = fieldName
if displayName is None:
displayName = fieldName
self.displayName = displayName
def Clone(self):
return self.__class__(self.fieldName, self.displayName)
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.
Parameters
----------
parent : object
Component properties dialog or similar.
"""
# 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 # mdc - why return anything here?
val = control.GetValue() # same as parent.params[self.fieldName].val
if not isinstance(val, str):
return '', True
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]
# Check if it is a Google font
if self.fieldName == 'font' and not val.startswith('$'):
fontInfo = fontMGR.getFontNamesSimilar(val)
if not fontInfo:
msg = _translate(
"Font `{val}` not found locally, will attempt to retrieve "
"from Google Fonts when this experiment next runs"
).format(val=val)
parent.warnings.setWarning(
control, msg=msg, kind=VALIDATOR_WARNING_FONT_MISSING)
else:
parent.warnings.clearWarning(control)
# Validate as code
if codeWanted or isCodeField:
# get var names from val, check against namespace:
code = experiment.getCodeFromParamStr(val, target="PsychoPy")
try:
names = list(stringtools.getVariables(code))
parent.warnings.clearWarning(control)
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)
parent.warnings.setWarning(
control, msg=msg, kind=VALIDATOR_WARNING_SYNTAX)
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) # security risk here?
except NameError as e:
_highlightParamVal(parent, True)
# NOTE: formatted string literal doesn't work with _translate().
# So, we have to call format() after _translate() is applied.
msg = _translate(
"Looks like your variable '{code}' in "
"'{displayName}' should be set to update."
).format(code=code, displayName=self.displayName)
parent.warnings.setWarning(
control, msg=msg, kind=VALIDATOR_WARNING_NAME)
except SyntaxError as e:
parent.warnings.setWarning(
control, msg=msg, kind=VALIDATOR_WARNING_SYNTAX)
# 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)
parent.warnings.setWarning(
control, msg=msg, kind=VALIDATOR_WARNING_NAME)
else:
parent.warnings.clearWarning(control)
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+r"(?!\(\))", 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:
# NOTE: formatted string literal doesn't work with _translate().
# So, we have to call format() after _translate() is applied.
msg = _translate(
"Variable name ${newName} is in use (by "
"{used}). Try another name."
).format(newName=newName, used=_translate(used))
parent.warnings.setWarning(
control, msg=msg, kind=VALIDATOR_WARNING_NAME)
else:
parent.warnings.clearWarning(control)
else:
parent.warnings.clearWarning(control)
parent.warnings.showWarning() # show most recent warnings
if __name__ == "__main__":
pass
| 21,328
|
Python
|
.py
| 480
| 33
| 122
| 0.59464
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,834
|
dlgsCode.py
|
psychopy_psychopy/psychopy/app/builder/dialogs/dlgsCode.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Part of the PsychoPy library
# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd.
# Distributed under the terms of the GNU General Public License (GPL).
"""Dialog classes for the Builder Code component
"""
import sys
import keyword
import wx
# import wx.lib.agw.aui as aui
from collections import OrderedDict
from psychopy.experiment.components.code import CodeComponent
from ..validators import WarningManager
from ...themes import handlers
from importlib.util import find_spec as loader
hasMetapensiero = loader("metapensiero") is not None
from .. import validators
from psychopy.localization import _translate
from psychopy.app.coder.codeEditorBase import BaseCodeEditor
from psychopy.experiment.py2js_transpiler import translatePythonToJavaScript
class DlgCodeComponentProperties(wx.Dialog):
_style = (wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER
| wx.DIALOG_NO_PARENT)
def __init__(self, frame, element, experiment,
helpUrl=None, suppressTitles=True, size=(1000,600),
style=_style, editing=False, depends=[],
timeout=None, type="Code",
openToPage=None):
# translate title
if "name" in element.params:
title = element.params['name'].val + _translate(' Properties')
elif "expName" in element.params:
title = element.params['expName'].val + _translate(' Properties')
else:
title = "Properties"
# get help url
if hasattr(element, 'url'):
helpUrl = element.url
else:
helpUrl = None
wx.Dialog.__init__(self, None, -1, title,
size=size, style=style)
self.SetTitle(title) # use localized title
# self.panel = wx.Panel(self)
self.frame = frame
self.app = frame.app
self.helpUrl = helpUrl
self.component = element
self.params = element.params # dict
self.order = element.order
self.title = title
self.timeout = timeout
self.codeBoxes = {}
self.tabs = OrderedDict()
if not editing and 'name' in self.params:
# then we're adding a new component so ensure a valid name:
makeValid = self.frame.exp.namespace.makeValid
self.params['name'].val = makeValid(self.params['name'].val)
self.codeNotebook = wx.Notebook(self)
# in AUI notebook the labels are blurry on retina mac
# and the close-tab buttons are hard to kill
# self.codeNotebook = aui.AuiNotebook(self)
# in FlatNoteBook the tab controls (left,right,close) are ugly on mac
# and also can't be killed
for paramN, paramName in enumerate(self.order):
param = self.params.get(paramName)
if paramName == 'name':
self.nameLabel = wx.StaticText(self, wx.ID_ANY,
_translate(param.label))
_style = wx.TE_PROCESS_ENTER | wx.TE_PROCESS_TAB
self.componentName = wx.TextCtrl(self, wx.ID_ANY,
str(param.val),
style=_style)
self.componentName.SetToolTip(wx.ToolTip(
_translate(param.hint)))
self.componentName.SetValidator(validators.NameValidator())
self.nameOKlabel = wx.StaticText(self, -1, '',
style=wx.ALIGN_RIGHT)
self.nameOKlabel.SetForegroundColour(wx.RED)
elif paramName == 'Code Type':
# Create code type choice menu
_codeTypes = self.params['Code Type'].allowedVals
_selectedCodeType = self.params['Code Type'].val
_selectedCodeTypeIndex = _codeTypes.index(_selectedCodeType)
self.codeTypeMenu = wx.Choice(self, choices=_codeTypes)
# If user does not have metapensiero but codetype is auto-js, revert to (Py?)
if not hasMetapensiero and _selectedCodeType.lower() == 'auto->js':
_selectedCodeTypeIndex -= 1
# Set selection to value stored in self params
self.codeTypeMenu.SetSelection(_selectedCodeTypeIndex)
self.codeTypeMenu.Bind(wx.EVT_CHOICE, self.onCodeChoice)
self.codeTypeName = wx.StaticText(self, wx.ID_ANY,
_translate(param.label))
elif paramName == 'disabled':
# Create bool control to disable/enable component
self.disableCtrl = wx.CheckBox(self, wx.ID_ANY, label=_translate('Disabled'))
self.disableCtrl.SetValue(bool(param.val))
else:
codeType = ["Py", "JS"]["JS" in paramName] # Give CodeBox a code type
tabName = paramName.replace("JS ", "")
if tabName in self.tabs:
_panel = self.tabs[tabName]
else:
_panel = wx.Panel(self.codeNotebook, wx.ID_ANY)
_panel.tabN = len(self.tabs)
_panel.app = self.app
self.tabs[tabName] = _panel
# if openToPage refers to this page by name, convert to index
if openToPage == paramName:
openToPage = _panel.tabN
self.codeBoxes[paramName] = CodeBox(_panel, wx.ID_ANY,
pos=wx.DefaultPosition,
style=0,
prefs=self.app.prefs,
params=self.params,
codeType=codeType)
self.codeBoxes[paramName].AddText(param.val)
self.codeBoxes[paramName].Bind(wx.EVT_KEY_UP, self.onKeyUp) # For real time translation
if len(param.val.strip()) and hasattr(_panel, "tabN") and not isinstance(openToPage, str):
if openToPage is None or openToPage > _panel.tabN:
# index of first non-blank page
openToPage = _panel.tabN
if self.helpUrl is not None:
self.helpButton = wx.Button(self, wx.ID_HELP,
_translate(" Help "))
tip = _translate("Go to online help about this component")
self.helpButton.SetToolTip(wx.ToolTip(tip))
self.okButton = wx.Button(self, wx.ID_OK, _translate(" OK "))
self.okButton.SetDefault()
self.cancelButton = wx.Button(self, wx.ID_CANCEL,
_translate(" Cancel "))
self.warnings = WarningManager(self) # to store warnings for all fields
self.__do_layout()
if openToPage is None:
openToPage = 1
self.codeNotebook.SetSelection(openToPage)
self.Update()
self.Bind(wx.EVT_BUTTON, self.helpButtonHandler, self.helpButton)
if self.timeout:
timeout = wx.CallLater(self.timeout, self.onEnter)
timeout.Start()
# do show and process return
ret = self.ShowModal()
if ret == wx.ID_OK:
self.checkName()
self.OK = True
self.params = self.getParams() # get new vals from dlg
self.Validate()
else:
self.OK = False
def readOnlyCodeBox(self, val=False):
"""
Sets ReadOnly for JS code boxes.
Parameters
----------
val : bool
True/False for ReadOnly/ReadWrite
"""
for box in self.codeBoxes:
if 'JS' in box:
self.codeBoxes[box].SetReadOnly(val)
def onKeyUp(self, event):
"""
Translates Python to JS on EVT_KEY_UP event, if Code Type is Auto->JS.
"""
if self.codeChoice[1].val.lower() != 'auto->js':
return
pythonCodeBox = event.GetEventObject()
keys = list(self.codeBoxes.keys())
vals = list(self.codeBoxes.values())
codeBox = keys[vals.index(pythonCodeBox)]
if 'JS' not in codeBox:
self.runTranslation(codeBox)
if event:
event.Skip()
@property
def codeChoice(self):
"""
Set code to Python, JS, Both, or Auto->JS for translation.
Returns
-------
tuple :
(previousCodeType, code type param)
"""
param = self.params['Code Type'] # Update param with menu selection
prevCodeType = param.val
param.val = param.allowedVals[self.codeTypeMenu.GetSelection()]
return prevCodeType, param
def undoCodeTypeChoice(self, prevCodeType):
"""
Return code type to previous selection.
Parameters
----------
prevCodeType: str
Code Type
"""
prevCodeTypeIndex = self.params['Code Type'].allowedVals.index(prevCodeType)
self.codeTypeMenu.SetSelection(prevCodeTypeIndex)
self.params['Code Type'].val = prevCodeType
def onCodeChoice(self, event):
"""
Set code to Python, JS, Both, or Auto->JS for translation.
Calls translation and updates to visible windows
"""
prevCodeType, param = self.codeChoice
# If user doesn't have metapensiero and current choice is auto-js...
if not hasMetapensiero and param.val.lower() == "auto->js" :
# Throw up error dlg instructing to get metapensiero
msg = _translate("\nPy to JS auto-translation requires the metapensiero library.\n"
"Available for Python 3.5+.\n")
dlg = CodeOverwriteDialog(self, -1, _translate("Warning: requires the metapensiero library"), msg)
dlg.ShowModal()
# Revert to previous choice
self.undoCodeTypeChoice(prevCodeType)
return
# Translate from previous language to new, make sure correct box is visible
self.translateCode(event, prevCodeType, param.val)
self.updateVisibleCode(event)
if event:
event.Skip()
def translateCode(self, event, prevCodeType='', newCodeType=''):
"""
For each code box, calls runTranslate to translate Python code to JavaScript.
Overwrite warning given when previous code type (prevCodeType) is Py, JS, or Both,
and when codeChangeDetected determines whether JS code has new additions
Parameters
----------
event : wx.Event
prevCodeType : str
Previous code type selected
newCodeType : str
New code type selected
"""
# If new codetype is not auto-js, terminate function
if not newCodeType.lower() == "auto->js":
return
# If code type has changed and previous code type isn't auto-js...
if prevCodeType.lower() != 'auto->js' and self.codeChangeDetected():
# Throw up a warning dlg to alert user of overwriting
msg = _translate("\nAuto-JS translation will overwrite your existing JavaScript code.\n"
"Press OK to continue, or Cancel.\n")
dlg = CodeOverwriteDialog(self, -1, _translate("Warning: Python to JavaScript Translation"), msg)
retVal = dlg.ShowModal()
# When window closes, if OK was not clicked revert to previous codetype
if not retVal == wx.ID_OK:
self.undoCodeTypeChoice(prevCodeType)
return
# For each codebox...
for boxName in self.codeBoxes:
# If it is not JS...
if 'JS' not in boxName:
# Translate to JS
self.runTranslation(boxName)
if event:
event.Skip()
def runTranslation(self, codeBox, codeChangeTest=False):
"""
Runs Python to JS translation for single code box.
Only receives Python code boxes.
Parameters
----------
codeBox : Str
The name of the code box e.g., Begin Experiment
codeChangeTest: bool
Whether the translation is part of the overwrite test:
i.e., is it safe to overwrite users new JS code
Returns
-------
Return values only given if codeChangeTest is True.
Returns translated JS code as str, or False if translation fails
"""
jsCode = ''
jsBox = codeBox.replace(' ', ' JS ')
pythonCode = self.codeBoxes[codeBox].GetValue()
self.readOnlyCodeBox(False)
try:
if pythonCode:
jsCode = translatePythonToJavaScript(pythonCode, namespace=None)
if codeChangeTest:
return jsCode
self.codeBoxes[jsBox].SetValue(jsCode)
except Exception: # Errors can be caught using alerts syntax checks
if codeChangeTest:
return False
self.codeBoxes[jsBox].SetValue("/* Syntax Error: Fix Python code */")
finally:
self.readOnlyCodeBox(self.codeChoice[1].val.lower() == 'auto->js')
def codeChangeDetected(self):
"""
Compares current JS code with newly translated code for each tab.
Returns
-------
bool
True if current code differs from translated code, else False
"""
for boxName in self.codeBoxes:
if 'JS' not in boxName:
newJS = self.runTranslation(boxName, True)
currentJS = self.codeBoxes[boxName.replace(' ', ' JS ')].GetValue()
if newJS == False or currentJS != newJS:
return True
return False
def updateVisibleCode(self, event=None):
"""
Receives keyboard events and code menu choice events.
On choice events, the code is stored for python or JS parameters,
and written to panel depending on choice of code. The duplicate panel
is shown/hidden depending on code choice. When duplicate is shown, Python and JS
code are shown in codeBox(left panel) and codeBoxDup (right panel), respectively.
"""
codeType = self.codeChoice[1].val
for boxName in self.codeBoxes:
self.readOnlyCodeBox(codeType.lower() == 'auto->js')
# If type is both or autojs, show split codebox
if codeType.lower() in ['both', 'auto->js']:
self.codeBoxes[boxName].Show()
# If type is JS, hide the non-JS box
elif codeType == 'JS':
if 'JS' in boxName:
self.codeBoxes[boxName].Show()
else:
self.codeBoxes[boxName].Hide()
# If type is Py, hide the JS box
else:
# user only wants Py code visible
if 'JS' in boxName:
self.codeBoxes[boxName].Hide()
else:
self.codeBoxes[boxName].Show()
# Name codebox tabs
for thisTabname in self.tabs:
self.tabs[thisTabname].Layout()
if event:
event.Skip()
def onEnter(self, evt=None, retval=wx.ID_OK):
self.EndModal(retval)
def checkName(self, event=None):
"""
Issue a form validation on name change.
"""
self.Validate()
def __do_layout(self, show=False):
self.updateVisibleCode()
for tabName in self.tabs:
pyName = tabName
jsName = pyName.replace(" ", " JS ")
panel = self.tabs[tabName]
sizer = wx.BoxSizer(wx.HORIZONTAL)
pyBox = self.codeBoxes[pyName]
jsBox = self.codeBoxes[jsName]
sizer.Add(pyBox, 1, wx.EXPAND, 2)
sizer.Add(jsBox, 1, wx.EXPAND, 2)
panel.SetSizer(sizer)
tabLabel = self.params.get(pyName).label
# Add a visual indicator when tab contains code
emptyCodeComp = CodeComponent('', '') # Spawn empty code component
# If code tab is not empty and not the same as in empty code component, add an asterisk to tab name
hasContents = self.params.get(pyName).val or self.params.get(jsName).val
pyEmpty = self.params.get(pyName).val == emptyCodeComp.params.get(pyName).val
jsEmpty = self.params.get(jsName).val == emptyCodeComp.params.get(jsName).val
if hasContents and not (pyEmpty and jsEmpty):
tabLabel += ' *'
self.codeNotebook.AddPage(panel, tabLabel)
nameSizer = wx.BoxSizer(wx.HORIZONTAL)
nameSizer.Add(self.nameLabel, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 10)
nameSizer.Add(self.componentName,
flag=wx.EXPAND | wx.ALL,
border=10, proportion=1)
nameSizer.Add(self.nameOKlabel, 0, wx.ALL, 10)
nameSizer.Add(self.codeTypeName,
flag=wx.TOP | wx.RIGHT, border=13, proportion=0)
nameSizer.Add(self.codeTypeMenu, 0, wx.ALIGN_CENTER_VERTICAL, 0)
nameSizer.Add(self.disableCtrl, flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL, border=13)
mainSizer = wx.BoxSizer(wx.VERTICAL)
buttonSizer = wx.BoxSizer(wx.HORIZONTAL)
mainSizer.Add(nameSizer)
mainSizer.Add(self.codeNotebook, 1, wx.EXPAND | wx.ALL, 10)
buttonSizer.Add(self.helpButton, 0,
wx.ALL | wx.RIGHT | wx.ALIGN_CENTER_VERTICAL, 10)
buttonSizer.AddStretchSpacer()
# Add Okay and Cancel buttons
if sys.platform == "win32":
btns = [self.okButton, self.cancelButton]
else:
btns = [self.cancelButton, self.okButton]
buttonSizer.Add(btns[0], 0,
wx.ALL | wx.RIGHT | wx.ALIGN_CENTER_VERTICAL,
border=3)
buttonSizer.Add(btns[1], 0,
wx.ALL | wx.RIGHT | wx.ALIGN_CENTER_VERTICAL,
border=3)
mainSizer.Add(buttonSizer, 0, wx.ALL | wx.RIGHT | wx.EXPAND, 5)
self.SetSizer(mainSizer)
self.Layout()
self.Center()
def getParams(self):
"""retrieves data from any fields in self.codeGuiElements
(populated during the __init__ function)
The new data from the dlg get inserted back into the original params
used in __init__ and are also returned from this method.
"""
# get data from input fields
for fieldName in self.params:
param = self.params[fieldName]
if fieldName == 'name':
param.val = self.componentName.GetValue()
elif fieldName == 'Code Type':
param.val = self.codeTypeMenu.GetStringSelection()
elif fieldName == 'disabled':
param.val = self.disableCtrl.GetValue()
else:
codeBox = self.codeBoxes[fieldName]
param.val = codeBox.GetText()
return self.params
def helpButtonHandler(self, event):
"""Uses self.app.followLink() to self.helpUrl
"""
self.app.followLink(url=self.helpUrl)
class CodeBox(BaseCodeEditor, handlers.ThemeMixin):
# this comes mostly from the wxPython demo styledTextCtrl 2
def __init__(self, parent, ID, prefs,
# set the viewer to be small, then it will increase with
# wx.aui control
pos=wx.DefaultPosition, size=wx.Size(100, 160),
style=0,
params=None,
codeType='Py'):
BaseCodeEditor.__init__(self, parent, ID, pos, size, style)
self.parent = parent
self.app = parent.app
self.prefs = prefs.coder
self.appData = prefs.appData
self.paths = prefs.paths
self.params = params
self.codeType = codeType
lexers = {
'Py': wx.stc.STC_LEX_PYTHON,
'JS': wx.stc.STC_LEX_CPP,
'txt': wx.stc.STC_LEX_CONTAINER
}
self.SetLexer(lexers[codeType])
self.SetProperty("fold", "1")
# 4 means 'tabs are bad'; 1 means 'flag inconsistency'
self.SetProperty("tab.timmy.whinge.level", "4")
self.SetViewWhiteSpace(self.appData['coder']['showWhitespace'])
self.SetViewEOL(self.appData['coder']['showEOLs'])
self.Bind(wx.stc.EVT_STC_MARGINCLICK, self.OnMarginClick)
self.SetIndentationGuides(False)
self.Bind(wx.EVT_KEY_DOWN, self.OnKeyPressed)
# apply the theme to the lexer
self._applyAppTheme()
def OnKeyPressed(self, event):
keyCode = event.GetKeyCode()
_mods = event.GetModifiers()
# Check combination keys
if keyCode == ord('/') and wx.MOD_CONTROL == _mods:
if self.params is not None:
self.toggleCommentLines()
elif keyCode == ord('V') and wx.MOD_CONTROL == _mods:
self.Paste()
return # so that we don't reach the skip line at end
if keyCode == wx.WXK_RETURN and not self.AutoCompActive():
# process end of line and then do smart indentation
event.Skip(False)
self.CmdKeyExecute(wx.stc.STC_CMD_NEWLINE)
if self.params is not None:
self.smartIdentThisLine()
return # so that we don't reach the skip line at end
event.Skip()
def setStatus(self, status):
if status == 'error':
color = (255, 210, 210, 255)
elif status == 'changed':
color = (220, 220, 220, 255)
else:
color = (255, 255, 255, 255)
self.StyleSetBackground(wx.stc.STC_STYLE_DEFAULT, color)
self._applyAppTheme()
def OnMarginClick(self, evt):
# fold and unfold as needed
if evt.GetMargin() == 2:
lineClicked = self.LineFromPosition(evt.GetPosition())
_flag = wx.stc.STC_FOLDLEVELHEADERFLAG
if self.GetFoldLevel(lineClicked) & _flag:
if evt.GetShift():
self.SetFoldExpanded(lineClicked, True)
self.Expand(lineClicked, True, True, 1)
elif evt.GetControl():
if self.GetFoldExpanded(lineClicked):
self.SetFoldExpanded(lineClicked, False)
self.Expand(lineClicked, False, True, 0)
else:
self.SetFoldExpanded(lineClicked, True)
self.Expand(lineClicked, True, True, 100)
else:
self.ToggleFold(lineClicked)
class CodeOverwriteDialog(wx.Dialog):
def __init__(self, parent, ID, title,
msg='',
size=wx.DefaultSize,
pos=wx.DefaultPosition,
style=wx.DEFAULT_DIALOG_STYLE):
wx.Dialog.__init__(self, parent, ID, title,
size=size, pos=pos, style=style)
sizer = wx.BoxSizer(wx.VERTICAL)
# Set warning Message
msg = _translate(msg)
warning = wx.StaticText(self, wx.ID_ANY, msg)
warning.SetForegroundColour((200, 0, 0))
sizer.Add(warning, 0, wx.ALIGN_CENTRE | wx.ALL, 5)
# Set divider
line = wx.StaticLine(self, wx.ID_ANY, size=(20, -1), style=wx.LI_HORIZONTAL)
sizer.Add(line, 0, wx.GROW | wx.RIGHT | wx.TOP, 5)
# Set buttons
btnsizer = wx.StdDialogButtonSizer()
btn = wx.Button(self, wx.ID_OK)
btn.SetHelpText("The OK button completes the dialog")
btn.SetDefault()
btnsizer.AddButton(btn)
btn = wx.Button(self, wx.ID_CANCEL)
btn.SetHelpText("The Cancel button cancels the dialog. (Crazy, huh?)")
btnsizer.AddButton(btn)
btnsizer.Realize()
sizer.Add(btnsizer, 0, wx.ALIGN_RIGHT | wx.ALL, 5)
# Center and size
self.CenterOnScreen()
self.SetSizerAndFit(sizer)
| 24,236
|
Python
|
.py
| 528
| 33.390152
| 111
| 0.579319
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,835
|
findDlg.py
|
psychopy_psychopy/psychopy/app/builder/dialogs/findDlg.py
|
import wx
from psychopy import experiment
from psychopy.app import utils
from psychopy.app.themes import icons
from psychopy.localization import _translate
class BuilderFindDlg(wx.Dialog):
def __init__(self, frame, exp):
self.frame = frame
self.exp = exp
self.results = []
wx.Dialog.__init__(
self,
parent=frame,
title=_translate("Find in experiment..."),
size=(512, 512),
style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER
)
# setup sizer
self.border = wx.BoxSizer(wx.VERTICAL)
self.SetSizer(self.border)
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.border.Add(self.sizer, border=12, proportion=1, flag=wx.EXPAND | wx.ALL)
# create search box
self.termCtrl = wx.SearchCtrl(self)
self.termCtrl.Bind(wx.EVT_SEARCH, self.onSearch)
self.sizer.Add(self.termCtrl, border=6, flag=wx.EXPAND | wx.ALL)
# create results box
self.resultsCtrl = utils.ListCtrl(self, style=wx.LC_REPORT | wx.LC_SINGLE_SEL)
self.resetListCtrl()
self.resultsCtrl.Bind(wx.EVT_LIST_ITEM_SELECTED, self.onSelectResult)
self.resultsCtrl.Bind(wx.EVT_LIST_ITEM_DESELECTED, self.onSelectResult)
self.resultsCtrl.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.onViewResult)
self.sizer.Add(self.resultsCtrl, border=6, proportion=1, flag=wx.EXPAND | wx.ALL)
# setup component icons
self.imageList = wx.ImageList(16, 16)
self.imageMap = {}
for cls in experiment.getAllElements().values():
i = self.imageList.Add(
icons.ComponentIcon(cls, theme="light", size=16).bitmap
)
self.imageMap[cls] = i
self.resultsCtrl.SetImageList(self.imageList, wx.IMAGE_LIST_SMALL)
# add buttons
btnSzr = self.CreateButtonSizer(wx.OK | wx.CANCEL)
self.border.Add(btnSzr, border=12, flag=wx.EXPAND | wx.ALL)
# relabel OK to Go
for child in btnSzr.GetChildren():
if child.Window and child.Window.GetId() == wx.ID_OK:
self.okBtn = child.Window
self.okBtn.SetLabel(_translate("Go"))
self.okBtn.Disable()
# rebind OK to view method
self.okBtn.Bind(wx.EVT_BUTTON, self.onViewResult)
self.Layout()
self.termCtrl.SetFocus()
def resetListCtrl(self):
self.resultsCtrl.ClearAll()
self.resultsCtrl.AppendColumn(_translate("Component"), width=120)
self.resultsCtrl.AppendColumn(_translate("Parameter"), width=120)
self.resultsCtrl.AppendColumn(_translate("Value"), width=-1)
self.resultsCtrl.resizeLastColumn(minWidth=120)
self.selectedResult = None
def onSearch(self, evt):
# get term to search
term = evt.GetString()
if term:
# get locations of term in experiment
self.results = getParamLocations(self.exp, term=term)
else:
# return nothing for blank string
self.results = []
# clear old output
self.resetListCtrl()
# show new output
for result in self.results:
# unpack result
rt, comp, paramName, param = result
# sanitize val for display
val = str(param.val)
if "\n" in val:
# if multiline, show first line with match
for line in val.split("\n"):
if self.termCtrl.GetValue() in line:
val = line
break
# construct entry
entry = [comp.name, param.label, val]
# add entry
self.resultsCtrl.Append(entry)
# set image for comp
self.resultsCtrl.SetItemImage(
item=self.resultsCtrl.GetItemCount()-1,
image=self.imageMap[type(comp)]
)
# size
self.resultsCtrl.Layout()
# disable Go button until item selected
self.okBtn.Disable()
def onSelectResult(self, evt):
if evt.GetEventType() == wx.EVT_LIST_ITEM_SELECTED.typeId:
# if item is selected, store its info
self.selectedResult = self.results[evt.GetIndex()]
# enable Go button
self.okBtn.Enable()
else:
# if no item selected, clear its info
self.selectedResult = None
# disable Go button
self.okBtn.Disable()
evt.Skip()
def onViewResult(self, evt):
# there should be a selected result if this button was enabled, but just in case...
if self.selectedResult is None:
return
# do usual OK button stuff
self.Close()
# unpack
rt, comp, paramName, param = self.selectedResult
# navigate to routine
self.frame.routinePanel.setCurrentRoutine(rt)
# navigate to component & category
page = self.frame.routinePanel.getCurrentPage()
if isinstance(comp, experiment.components.BaseComponent):
# if we have a component, open its dialog and navigate to categ page
if hasattr(comp, 'type') and comp.type.lower() == 'code':
openToPage = paramName
else:
openToPage = param.categ
page.editComponentProperties(component=comp, openToPage=openToPage)
else:
# if we're in a standalone routine, just navigate to categ page
i = page.ctrls.getCategoryIndex(param.categ)
page.ctrls.ChangeSelection(i)
def getParamLocations(exp, term):
"""
Get locations of params containing the given term.
Parameters
----------
term : str
Term to search for
Returns
-------
list
List of tuples, with each tuple functioning as a path to the found
param
"""
# array to store results in
found = []
# go through all routines
for rt in exp.routines.values():
if isinstance(rt, experiment.routines.BaseStandaloneRoutine):
# find in standalone routine
for paramName, param in rt.params.items():
if term in str(param.val):
# append path (routine -> param)
found.append(
(rt, rt, paramName, param)
)
if isinstance(rt, experiment.routines.Routine):
# find in regular routine
for comp in rt:
for paramName, param in comp.params.items():
if term in str(param.val):
# append path (routine -> component -> param)
found.append(
(rt, comp, paramName, param)
)
return found
| 6,839
|
Python
|
.py
| 168
| 29.77381
| 91
| 0.59203
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,836
|
dlgsConditions.py
|
psychopy_psychopy/psychopy/app/builder/dialogs/dlgsConditions.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Part of the PsychoPy library
# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd.
# Distributed under the terms of the GNU General Public License (GPL).
"""Conditions-file preview and mini-editor for the Builder
"""
import os
import sys
import pickle
import wx
from wx.lib.expando import ExpandoTextCtrl, EVT_ETC_LAYOUT_NEEDED
from packaging.version import Version
from psychopy import gui
from psychopy.experiment.utils import valid_var_re
from psychopy.data.utils import _nonalphanumeric_re
from psychopy.localization import _translate
darkblue = wx.Colour(30, 30, 150, 255)
darkgrey = wx.Colour(65, 65, 65, 255)
white = wx.Colour(255, 255, 255, 255)
class DlgConditions(wx.Dialog):
"""Given a file or conditions, present values in a grid; view, edit, save.
Accepts file name, list of lists, or list-of-dict
Designed around a conditionsFile, but potentially more general.
Example usage: from builder.DlgLoopProperties.viewConditions()
edit new empty .pkl file:
gridGUI = builder.DlgConditions(parent=self) # create and present Dlg
edit existing .pkl file, loading from file (also for .csv or .xlsx):
gridGUI = builder.DlgConditions(fileName=self.conditionsFile,
parent=self, title=fileName)
preview existing .csv or .xlsx file that has been loaded -> conditions:
gridGUI = builder.DlgConditions(conditions, parent=self,
title=fileName, fixed=True)
To add columns, an instance of this class will instantiate a new instance
having one more column. Doing so makes the return value from the first
instance's showModal() meaningless. In order to update things like
fileName and conditions, values are set in the parent, and should not be
set based on showModal retVal.
Author: Jeremy Gray, 2011
adjusted for wx 3.x: Dec 2015
"""
def __init__(self, grid=None, fileName=False, parent=None, title='',
trim=True, fixed=False, hasHeader=True, gui=True,
extraRows=0, extraCols=0,
clean=True, pos=wx.DefaultPosition, preview=True,
_restore=None, size=wx.DefaultSize,
style=wx.DEFAULT_DIALOG_STYLE | wx.DIALOG_NO_PARENT):
self.parent = parent # gets the conditionsFile info
if parent:
self.helpUrl = self.parent.app.urls['builder.loops']
# read data from file, if any:
self.defaultFileName = 'conditions.pkl'
self.newFile = True
if _restore:
self.newFile = _restore[0]
self.fileName = _restore[1]
if fileName:
grid = self.load(fileName)
if grid:
self.fileName = fileName
self.newFile = False
if not title:
f = os.path.abspath(fileName)
f = f.rsplit(os.path.sep, 2)[1:]
f = os.path.join(*f) # eg, BART/trialTypes.xlsx
title = f
elif not grid:
title = _translate('New (no file)')
elif _restore:
if not title:
f = os.path.abspath(_restore[1])
f = f.rsplit(os.path.sep, 2)[1:]
f = os.path.join(*f) # eg, BART/trialTypes.xlsx
title = f
elif not title:
title = _translate('Conditions data (no file)')
# if got here via addColumn:
# convert from conditions dict format:
if grid and type(grid) == list and type(grid[0]) == dict:
conditions = grid[:]
numCond, numParam = len(conditions), len(conditions[0])
grid = [list(conditions[0].keys())]
for i in range(numCond):
row = list(conditions[i].values())
grid.append(row)
hasHeader = True # keys of a dict are the header
# ensure a sensible grid, or provide a basic default:
if not grid or not len(grid) or not len(grid[0]):
grid = [[self.colName(0)], [u'']]
hasHeader = True
extraRows += 5
extraCols += 3
self.grid = grid # grid is list of lists
self.fixed = bool(fixed)
if self.fixed:
extraRows = extraCols = 0
trim = clean = confirm = False
else:
style = style | wx.RESIZE_BORDER
self.pos = pos
self.title = title
try:
self.madeApp = False
wx.Dialog.__init__(self, None, -1, title, pos, size, style)
except wx._core.PyNoAppError: # only needed during development?
self.madeApp = True
global app
if Version(wx.__version__) < Version('2.9'):
app = wx.PySimpleApp()
else:
app = wx.App(False)
wx.Dialog.__init__(self, None, -1, title, pos, size, style)
self.trim = trim
self.warning = '' # updated to warn about eg, trailing whitespace
if hasHeader and not len(grid) > 1 and not self.fixed:
self.grid.append([])
self.clean = bool(clean)
self.typeChoices = ['None', 'str', 'utf-8', 'int', 'long', 'float',
'bool', 'list', 'tuple', 'array']
# make all rows have same # cols, extending as needed or requested:
longest = max([len(r) for r in self.grid]) + extraCols
for row in self.grid:
for i in range(len(row), longest):
row.append(u'') # None
# self.header <== row of input param name fields
self.hasHeader = bool(hasHeader)
self.rows = min(len(self.grid), 30) # max 30 rows displayed
self.cols = len(self.grid[0])
if wx.version()[0] == '2':
# extra row for explicit type drop-down
extraRow = int(not self.fixed)
self.sizer = wx.FlexGridSizer(self.rows + extraRow,
self.cols + 1, # +1 for labels
vgap=0, hgap=0)
else:
self.sizer = wx.FlexGridSizer(cols=self.cols + 1, vgap=0, hgap=0)
# set length of input box as the longest in the column (bounded):
self.colSizes = []
for x in range(self.cols):
_size = [len(str(self.grid[y][x])) for y in range(self.rows)]
self.colSizes.append(max([4] + _size))
self.colSizes = [min(20, max(10, x + 1)) * 8 + 30 for x in self.colSizes]
self.inputTypes = [] # explicit, as selected by user
self.inputFields = [] # values in fields
self.data = []
# make header label, if any:
if self.hasHeader:
rowLabel = wx.StaticText(self, -1, label=_translate('Params:'),
size=(6 * 9, 20))
rowLabel.SetForegroundColour(darkblue)
self.addRow(0, rowLabel=rowLabel)
# make type-selector drop-down:
if not self.fixed:
if sys.platform == 'darwin':
self.SetWindowVariant(variant=wx.WINDOW_VARIANT_SMALL)
labelBox = wx.BoxSizer(wx.VERTICAL)
tx = wx.StaticText(self, -1, label=_translate('type:'),
size=(5 * 9, 20))
tx.SetForegroundColour(darkgrey)
labelBox.Add(tx, 1, flag=wx.ALIGN_RIGHT)
labelBox.AddSpacer(5) # vertical
self.sizer.Add(labelBox, 1, flag=wx.ALIGN_RIGHT)
row = int(self.hasHeader) # row to use for type inference
for col in range(self.cols):
# make each selector:
typeOpt = wx.Choice(self, choices=self.typeChoices)
# set it to best guess about the column's type:
firstType = str(type(self.grid[row][col])).split("'", 2)[1]
if firstType == 'numpy.ndarray':
firstType = 'array'
if firstType == 'unicode':
firstType = 'utf-8'
typeOpt.SetStringSelection(str(firstType))
self.inputTypes.append(typeOpt)
self.sizer.Add(typeOpt, 1)
if sys.platform == 'darwin':
self.SetWindowVariant(variant=wx.WINDOW_VARIANT_NORMAL)
# stash implicit types for setType:
self.types = [] # implicit types
row = int(self.hasHeader) # which row to use for type inference
for col in range(self.cols):
firstType = str(type(self.grid[row][col])).split("'")[1]
self.types.append(firstType)
# add normal row:
for row in range(int(self.hasHeader), self.rows):
self.addRow(row)
for r in range(extraRows):
self.grid.append([u'' for i in range(self.cols)])
self.rows = len(self.grid)
self.addRow(self.rows - 1)
# show the GUI:
if gui:
self.show()
self.Destroy()
if self.madeApp:
del(self, app)
def colName(self, c, prefix='param_'):
# generates 702 excel-style column names, A ... ZZ, with prefix
abc = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' # for A, ..., Z
aabb = [''] + [ch for ch in abc] # for Ax, ..., Zx
return prefix + aabb[c // 26] + abc[c % 26]
def addRow(self, row, rowLabel=None):
"""Add one row of info, either header (col names) or normal data
Adds items sequentially; FlexGridSizer moves to next row automatically
"""
labelBox = wx.BoxSizer(wx.HORIZONTAL)
if not rowLabel:
if sys.platform == 'darwin':
self.SetWindowVariant(variant=wx.WINDOW_VARIANT_SMALL)
label = _translate('cond %s:') % str(
row + 1 - int(self.hasHeader)).zfill(2)
rowLabel = wx.StaticText(self, -1, label=label)
rowLabel.SetForegroundColour(darkgrey)
if sys.platform == 'darwin':
self.SetWindowVariant(variant=wx.WINDOW_VARIANT_NORMAL)
labelBox.Add(rowLabel, 1, flag=wx.ALIGN_BOTTOM)
self.sizer.Add(labelBox, 1, flag=wx.ALIGN_CENTER)
lastRow = []
for col in range(self.cols):
# get the item, as unicode for display purposes:
if len(str(self.grid[row][col])): # want 0, for example
item = str(self.grid[row][col])
else:
item = u''
# make a textbox:
field = ExpandoTextCtrl(
self, -1, item, size=(self.colSizes[col], 20))
field.Bind(EVT_ETC_LAYOUT_NEEDED, self.onNeedsResize)
field.SetMaxHeight(100) # ~ 5 lines
if self.hasHeader and row == 0:
# add a default column name (header) if none provided
header = self.grid[0]
if item.strip() == '':
c = col
while self.colName(c) in header:
c += 1
field.SetValue(self.colName(c))
field.SetForegroundColour(darkblue) # dark blue
# or (self.parent and
if not valid_var_re.match(field.GetValue()):
# self.parent.exp.namespace.exists(field.GetValue()) ):
# was always red when preview .xlsx file -- in
# namespace already is fine
if self.fixed:
field.SetForegroundColour("Red")
field.SetToolTip(wx.ToolTip(_translate(
'Should be legal as a variable name (alphanumeric)')))
field.Bind(wx.EVT_TEXT, self.checkName)
elif self.fixed:
field.SetForegroundColour(darkgrey)
field.SetBackgroundColour(white)
# warn about whitespace unless will be auto-removed. invisible,
# probably spurious:
if (self.fixed or not self.clean) and item != item.strip():
field.SetForegroundColour('Red')
# also used in show():
self.warning = _translate('extra white-space')
field.SetToolTip(wx.ToolTip(self.warning))
if self.fixed:
field.Disable()
lastRow.append(field)
self.sizer.Add(field, 1)
self.inputFields.append(lastRow)
if self.hasHeader and row == 0:
self.header = lastRow
def checkName(self, event=None, name=None):
"""check param name (missing, namespace conflict, legal var name)
disable save, save-as if bad name
"""
if self.parent:
if event:
msg, enable = self.parent._checkName(event=event)
else:
msg, enable = self.parent._checkName(name=name)
else:
if (name and not valid_var_re.match(name)
or not valid_var_re.match(event.GetString())):
msg, enable = _translate(
"Name must be alphanumeric or _, no spaces"), False
else:
msg, enable = "", True
self.tmpMsg.SetLabel(msg)
if enable:
self.OKbtn.Enable()
self.SAVEAS.Enable()
else:
self.OKbtn.Disable()
self.SAVEAS.Disable()
def userAddRow(self, event=None):
"""handle user request to add another row: add to the FlexGridSizer
"""
self.grid.append([u''] * self.cols)
self.rows = len(self.grid)
self.addRow(self.rows - 1)
self.tmpMsg.SetLabel('')
self.onNeedsResize()
def userAddCol(self, event=None):
"""adds a column by recreating the Dlg with size +1 one column wider.
relaunching loses the retVal from OK, so use parent.fileName instead
"""
self.relaunch(extraCols=1, title=self.title)
def relaunch(self, **kwargs):
self.trim = False # dont remove blank rows / cols that user added
self.getData(True)
currentData = self.data[:]
# launch new Dlg, but only after bail out of current one:
if hasattr(self, 'fileName'):
fname = self.fileName
else:
fname = None
wx.CallAfter(DlgConditions, currentData,
_restore=(self.newFile, fname),
parent=self.parent, **kwargs)
# bail from current Dlg:
# retVal here, first one goes to Builder, ignore
self.EndModal(wx.ID_OK)
# self.Destroy() # -> PyDeadObjectError, so already handled hopefully
def getData(self, typeSelected=False):
"""gets data from inputFields (unicode), converts to desired type
"""
if self.fixed:
self.data = self.grid
return
elif typeSelected: # get user-selected explicit types of the columns
self.types = []
for col in range(self.cols):
selected = self.inputTypes[col].GetCurrentSelection()
self.types.append(self.typeChoices[selected])
# mark empty columns for later removal:
if self.trim:
start = int(self.hasHeader) # name is not empty, so ignore
for col in range(self.cols):
if not ''.join([self.inputFields[row][col].GetValue()
for row in range(start, self.rows)]):
self.types[col] = 'None' # col will be removed below
# get the data:
self.data = []
for row in range(self.rows):
lastRow = []
# remove empty rows
fieldVals = [self.inputFields[row][col].GetValue()
for col in range(self.cols)]
if self.trim and not ''.join(fieldVals):
continue
for col in range(self.cols):
thisType = self.types[col]
# trim 'None' columns, including header name:
if self.trim and thisType in ['None']:
continue
thisVal = self.inputFields[row][col].GetValue()
if self.clean:
thisVal = thisVal.lstrip().strip()
if thisVal: # and thisType in ['list', 'tuple', 'array']:
while len(thisVal) and thisVal[-1] in "]), ":
thisVal = thisVal[:-1]
while len(thisVal) and thisVal[0] in "[(, ":
thisVal = thisVal[1:]
if thisType not in ['str', 'utf-8']:
thisVal = thisVal.replace('\n', '')
else:
thisVal = repr(thisVal) # handles quoting ', ", ''' etc
# convert to requested type:
try:
if self.hasHeader and row == 0:
# header always str
val = self.inputFields[row][col].GetValue()
lastRow.append(str(val))
elif thisType in ['float', 'int', 'long']:
eval("lastRow.append(" + thisType +
'(' + thisVal + "))")
elif thisType in ['list']:
thisVal = thisVal.lstrip('[').strip(']')
eval("lastRow.append(" + thisType +
'([' + thisVal + "]))")
elif thisType in ['tuple']:
thisVal = thisVal.lstrip('(').strip(')')
if thisVal:
eval("lastRow.append((" +
thisVal.strip(',') + ",))")
else:
lastRow.append(tuple(()))
elif thisType in ['array']:
thisVal = thisVal.lstrip('[').strip(']')
eval("lastRow.append(numpy.array" +
'("[' + thisVal + ']"))')
elif thisType in ['utf-8', 'bool']:
if thisType == 'utf-8':
thisType = 'unicode'
eval("lastRow.append(" + thisType +
'(' + thisVal + '))')
elif thisType in ['str']:
eval("lastRow.append(str(" + thisVal + "))")
elif thisType in ['file']:
eval("lastRow.append(repr(" + thisVal + "))")
else:
eval("lastRow.append(" + str(thisVal) + ')')
except ValueError as msg:
print('ValueError:', msg, '; using unicode')
eval("lastRow.append(" + str(thisVal) + ')')
except NameError as msg:
print('NameError:', msg, '; using unicode')
eval("lastRow.append(" + repr(thisVal) + ')')
self.data.append(lastRow)
if self.trim:
# the corresponding data have already been removed
while 'None' in self.types:
self.types.remove('None')
return self.data[:]
def preview(self, event=None):
self.getData(typeSelected=True)
# in theory, self.data is also ok, because fixed
previewData = self.data[:]
# is supposed to never change anything, but bugs would be very subtle
DlgConditions(previewData, parent=self.parent,
title=_translate('PREVIEW'), fixed=True)
def onNeedsResize(self, event=None):
self.SetSizerAndFit(self.border) # do outer-most sizer
if self.pos is None:
self.Center()
def show(self):
"""called internally; to display, pass gui=True to init
"""
# put things inside a border:
if wx.version()[0] == '2':
# data matrix on top, buttons below
self.border = wx.FlexGridSizer(2, 1)
elif wx.version()[0] == '3':
self.border = wx.FlexGridSizer(4)
else:
self.border = wx.FlexGridSizer(4, 1, wx.Size(0,0))
self.border.Add(self.sizer, proportion=1,
flag=wx.ALL | wx.EXPAND, border=8)
# add a message area, buttons:
buttons = wx.BoxSizer(wx.HORIZONTAL)
if sys.platform == 'darwin':
self.SetWindowVariant(variant=wx.WINDOW_VARIANT_SMALL)
if not self.fixed:
# placeholder for possible messages / warnings:
self.tmpMsg = wx.StaticText(
self, -1, label='', size=(350, 15), style=wx.ALIGN_RIGHT)
self.tmpMsg.SetForegroundColour('Red')
if self.warning:
self.tmpMsg.SetLabel(self.warning)
buttons.Add(self.tmpMsg, flag=wx.ALIGN_CENTER)
buttons.AddSpacer(8)
self.border.Add(buttons, 1, flag=wx.BOTTOM |
wx.ALIGN_CENTER, border=8)
buttons = wx.BoxSizer(wx.HORIZONTAL)
ADDROW = wx.Button(self, -1, _translate("+cond."))
tip = _translate('Add a condition (row); to delete a condition,'
' delete all of its values.')
ADDROW.SetToolTip(wx.ToolTip(tip))
ADDROW.Bind(wx.EVT_BUTTON, self.userAddRow)
buttons.Add(ADDROW)
buttons.AddSpacer(4)
ADDCOL = wx.Button(self, -1, _translate("+param"))
tip = _translate('Add a parameter (column); to delete a param, '
'set its type to None, or delete all of its values.')
ADDCOL.SetToolTip(wx.ToolTip(tip))
ADDCOL.Bind(wx.EVT_BUTTON, self.userAddCol)
buttons.Add(ADDCOL)
buttons.AddSpacer(4)
PREVIEW = wx.Button(self, -1, _translate("Preview"))
tip = _translate("Show all values as they would appear after "
"saving to a file, without actually saving anything.")
PREVIEW.SetToolTip(wx.ToolTip(tip))
PREVIEW.Bind(wx.EVT_BUTTON, self.preview)
buttons.Add(PREVIEW)
buttons.AddSpacer(4)
self.SAVEAS = wx.Button(self, wx.FD_SAVE, _translate("Save as"))
self.SAVEAS.Bind(wx.EVT_BUTTON, self.saveAs)
buttons.Add(self.SAVEAS)
buttons.AddSpacer(8)
self.border.Add(buttons, 1, flag=wx.BOTTOM |
wx.ALIGN_RIGHT, border=8)
if sys.platform == 'darwin':
self.SetWindowVariant(variant=wx.WINDOW_VARIANT_NORMAL)
buttons = wx.StdDialogButtonSizer()
# help button if we know the url
if self.helpUrl and not self.fixed:
helpBtn = wx.Button(self, wx.ID_HELP, _translate(" Help "))
helpBtn.SetToolTip(wx.ToolTip(_translate("Go to online help")))
helpBtn.Bind(wx.EVT_BUTTON, self.onHelp)
buttons.Add(helpBtn, wx.ALIGN_CENTER | wx.ALL)
buttons.AddSpacer(12)
# Add Okay and Cancel buttons
self.OKbtn = wx.Button(self, wx.ID_OK, _translate(" OK "))
if not self.fixed:
self.OKbtn.SetToolTip(wx.ToolTip(_translate('Save and exit')))
self.OKbtn.Bind(wx.EVT_BUTTON, self.onOK)
self.OKbtn.SetDefault()
if not self.fixed:
buttons.AddSpacer(4)
CANCEL = wx.Button(self, wx.ID_CANCEL, _translate(" Cancel "))
CANCEL.SetToolTip(wx.ToolTip(
_translate('Exit, discard any edits')))
buttons.Add(CANCEL)
else:
CANCEL = None
if sys.platform == "win32":
btns = [self.OKbtn, CANCEL]
else:
btns = [CANCEL, self.OKbtn]
if not self.fixed:
btns.remove(btns.index(CANCEL))
buttons.AddMany(btns)
buttons.AddSpacer(8)
buttons.Realize()
self.border.Add(buttons, 1, flag=wx.BOTTOM | wx.ALIGN_RIGHT, border=8)
# finally, its show time:
self.SetSizerAndFit(self.border)
if self.pos is None:
self.Center()
if self.ShowModal() == wx.ID_OK:
# set self.data and self.types, from fields
self.getData(typeSelected=True)
self.OK = True
else:
self.data = self.types = None
self.OK = False
self.Destroy()
def onOK(self, event=None):
if not self.fixed:
if not self.save():
return # disallow OK if bad param names
event.Skip() # handle the OK button event
def saveAs(self, event=None):
"""save, but allow user to give a new name
"""
self.newFile = True # trigger query for fileName
self.save()
self.relaunch() # to update fileName in title
def save(self, event=None):
"""save header + row x col data to a pickle file
"""
self.getData(True) # update self.data
adjustedNames = False
for i, paramName in enumerate(self.data[0]):
newName = paramName
# ensure its legal as a var name, including namespace check:
if self.parent:
msg, enable = self.parent._checkName(name=paramName)
if msg: # msg not empty means a namespace issue
newName = self.parent.exp.namespace.makeValid(
paramName, prefix='param')
adjustedNames = True
elif not valid_var_re.match(paramName):
msg, enable = _translate(
"Name must be alphanumeric or _, no spaces"), False
newName = _nonalphanumeric_re.sub('_', newName)
adjustedNames = True
else:
msg, enable = "", True
# try to ensure its unique:
while newName in self.data[0][:i]:
adjustedNames = True
newName += 'x' # might create a namespace conflict?
self.data[0][i] = newName
self.header[i].SetValue(newName) # displayed value
if adjustedNames:
self.tmpMsg.SetLabel(_translate(
'Param name(s) adjusted to be legal. Look ok?'))
return False
if hasattr(self, 'fileName') and self.fileName:
fname = self.fileName
else:
self.newFile = True
fname = self.defaultFileName
if self.newFile or not os.path.isfile(fname):
fullPath = gui.fileSaveDlg(initFilePath=os.path.split(fname)[0],
initFileName=os.path.basename(fname),
allowed="Pickle files (*.pkl)|*.pkl")
else:
fullPath = fname
if fullPath: # None if user canceled
if not fullPath.endswith('.pkl'):
fullPath += '.pkl'
f = open(fullPath, 'w')
pickle.dump(self.data, f)
f.close()
self.fileName = fullPath
self.newFile = False
# ack, sometimes might want relative path
if self.parent:
self.parent.conditionsFile = fullPath
return True
def load(self, fileName=''):
"""read and return header + row x col data from a pickle file
"""
if not fileName:
fileName = self.defaultFileName
if not os.path.isfile(fileName):
_base = os.path.basename(fileName)
fullPathList = gui.fileOpenDlg(tryFileName=_base,
allowed="All files (*.*)|*.*")
if fullPathList:
fileName = fullPathList[0] # wx.MULTIPLE -> list
if os.path.isfile(fileName) and fileName.endswith('.pkl'):
f = open(fileName, 'rb')
# Converting newline characters.
# 'b' is necessary in Python3 because byte object is
# returned when file is opened in binary mode.
buffer = f.read().replace(b'\r\n',b'\n').replace(b'\r',b'\n')
contents = pickle.loads(buffer)
f.close()
if self.parent:
self.parent.conditionsFile = fileName
return contents
elif not os.path.isfile(fileName):
print('file %s not found' % fileName)
else:
print('only .pkl supported at the moment')
def asConditions(self):
"""converts self.data into self.conditions for TrialHandler.
returns conditions
"""
if not self.data or not self.hasHeader:
if hasattr(self, 'conditions') and self.conditions:
return self.conditions
return
self.conditions = []
keyList = self.data[0] # header = keys of dict
for row in self.data[1:]:
condition = {}
for col, key in enumerate(keyList):
condition[key] = row[col]
self.conditions.append(condition)
return self.conditions
def onHelp(self, event=None):
"""similar to self.app.followLink() to self.helpUrl, but only use url
"""
wx.LaunchDefaultBrowser(self.helpUrl)
| 29,134
|
Python
|
.py
| 632
| 32.781646
| 83
| 0.544809
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,837
|
__init__.py
|
psychopy_psychopy/psychopy/app/builder/dialogs/__init__.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Part of the PsychoPy library
# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd.
# Distributed under the terms of the GNU General Public License (GPL).
"""Dialog classes for the Builder, including ParamCtrls
"""
import sys
import os
import copy
import time
from collections import OrderedDict
import numpy
import re
import wx
import psychopy.experiment.utils
from psychopy.experiment import Param
from ... import dialogs
from .. import experiment
from .. validators import NameValidator, CodeSnippetValidator, WarningManager
from .dlgsConditions import DlgConditions
from .dlgsCode import DlgCodeComponentProperties, CodeBox
from .findDlg import BuilderFindDlg
from . import paramCtrls
from psychopy import data, logging, exceptions
from psychopy.localization import _translate
from psychopy.tools import versionchooser as vc
from psychopy.alerts import alert
from ...colorpicker import PsychoColorPicker
from pathlib import Path
from ...themes import handlers, icons
white = wx.Colour(255, 255, 255, 255)
codeSyntaxOkay = wx.Colour(220, 250, 220, 255) # light green
class ParamCtrls():
def __init__(self, dlg, label, param, parent, fieldName,
browse=False, noCtrls=False, advanced=False, appPrefs=None):
"""Create a set of ctrls for a particular Component Parameter, to be
used in Component Properties dialogs. These need to be positioned
by the calling dlg.
e.g.::
param = experiment.Param(val='boo', valType='str')
ctrls = ParamCtrls(dlg=self, label=fieldName,param=param)
self.paramCtrls[fieldName] = ctrls # keep track in the dlg
sizer.Add(ctrls.nameCtrl, (currRow,0), (1,1),wx.ALIGN_RIGHT )
sizer.Add(ctrls.valueCtrl, (currRow,1) )
# these are optional (the parameter might be None)
if ctrls.typeCtrl:
sizer.Add(ctrls.typeCtrl, (currRow,2) )
if ctrls.updateCtrl:
sizer.Add(ctrls.updateCtrl, (currRow,3))
If browse is True then a browseCtrl will be added (you need to
bind events yourself). If noCtrls is True then no actual wx widgets
are made, but attribute names are created
`fieldName`'s value is always in en_US, and never for display,
whereas `label` is only for display and can be translated or
tweaked (e.g., add '$'). Component._localized.keys() are
`fieldName`s, and .values() are `label`s.
"""
super(ParamCtrls, self).__init__()
self.param = param
self.dlg = dlg
self.dpi = self.dlg.dpi
self.valueWidth = self.dpi * 3.5
# try to find the experiment
self.exp = None
tryForExp = self.dlg
while self.exp is None:
if hasattr(tryForExp, 'frame'):
self.exp = tryForExp.frame.exp
else:
try:
tryForExp = tryForExp.parent # try going up a level
except Exception:
tryForExp.parent
# param has the fields:
# val, valType, allowedVals=[],allowedTypes=[],
# hint="", updates=None, allowedUpdates=None
# we need the following:
self.nameCtrl = self.valueCtrl = self.typeCtrl = None
self.updateCtrl = self.browseCtrl = None
if noCtrls:
return # we don't need to do any more
if type(param.val) == numpy.ndarray:
initial = param.val.tolist() # convert numpy arrays to lists
label = _translate(label)
self.nameCtrl = wx.StaticText(parent, -1, label, size=wx.DefaultSize)
if fieldName == 'Use version':
# _localVersionsCache is the default (faster) when creating
# settings. If remote info has become available in the meantime,
# now populate with that as well
if vc._remoteVersionsCache:
options = vc._versionFilter(
vc.versionOptions(local=False), wx.__version__)
versions = vc._versionFilter(
vc.availableVersions(local=False), wx.__version__)
param.allowedVals = (options + [''] + versions)
if param.inputType == "single":
# Create single line string control
self.valueCtrl = paramCtrls.SingleLineCtrl(
parent,
val=str(param.val),
valType=param.valType,
fieldName=fieldName,
size=wx.Size(int(self.valueWidth), 24))
elif param.inputType == 'multi':
if param.valType == "extendedCode":
# Create multiline code control
self.valueCtrl = paramCtrls.CodeCtrl(
parent,
val=str(param.val),
valType=param.valType,
fieldName=fieldName,
size=wx.Size(int(self.valueWidth), 144))
else:
# Create multiline string control
self.valueCtrl = paramCtrls.MultiLineCtrl(
parent,
val=str(param.val),
valType=param.valType,
fieldName=fieldName,
size=wx.Size(int(self.valueWidth), 144))
# Set focus if field is text of a Textbox or Text component
if fieldName == 'text':
self.valueCtrl.SetFocus()
elif param.inputType == 'spin':
# Create single line string control
self.valueCtrl = paramCtrls.SingleLineCtrl(
parent,
val=str(param.val),
valType=param.valType,
fieldName=fieldName,
size=wx.Size(int(self.valueWidth), 24))
# Will have to disable spinCtrl until we have a dropdown for inputType, sadly
# self.valueCtrl = paramCtrls.IntCtrl(parent,
# val=param.val, valType=param.valType,
# fieldName=fieldName,size=wx.Size(self.valueWidth, 24),
# limits=param.allowedVals)
elif param.inputType == 'choice':
self.valueCtrl = paramCtrls.ChoiceCtrl(
parent,
val=str(param.val),
valType=param.valType,
choices=param.allowedVals,
labels=param.allowedLabels,
fieldName=fieldName)
elif param.inputType == 'multiChoice':
self.valueCtrl = paramCtrls.MultiChoiceCtrl(
parent,
valType=param.valType,
vals=param.val,
choices=param.allowedVals,
fieldName=fieldName,
size=wx.Size(int(self.valueWidth), -1))
elif param.inputType == 'richChoice':
self.valueCtrl = paramCtrls.RichChoiceCtrl(
parent,
valType=param.valType,
vals=param.val,
choices=param.allowedVals,
labels=param.allowedLabels,
fieldName=fieldName,
size=wx.Size(int(self.valueWidth), -1))
elif param.inputType == 'bool':
self.valueCtrl = paramCtrls.BoolCtrl(
parent,
name=fieldName,
size=wx.Size(int(self.valueWidth), 24))
self.valueCtrl.SetValue(bool(param))
elif param.inputType == 'file' or browse:
self.valueCtrl = paramCtrls.FileCtrl(
parent,
val=str(param.val),
valType=param.valType,
fieldName=fieldName,
size=wx.Size(int(self.valueWidth), 24))
self.valueCtrl.allowedVals = param.allowedVals
elif param.inputType == 'survey':
self.valueCtrl = paramCtrls.SurveyCtrl(
parent,
val=str(param.val),
valType=param.valType,
fieldName=fieldName,
size=wx.Size(int(self.valueWidth), 24))
self.valueCtrl.allowedVals = param.allowedVals
elif param.inputType == 'fileList':
self.valueCtrl = paramCtrls.FileListCtrl(
parent,
choices=param.val,
valType=param.valType,
size=wx.Size(int(self.valueWidth), 100),
pathtype="rel")
elif param.inputType == 'table':
self.valueCtrl = paramCtrls.TableCtrl(
parent,
param=param,
fieldName=fieldName,
size=wx.Size(int(self.valueWidth), 24))
elif param.inputType == 'color':
self.valueCtrl = paramCtrls.ColorCtrl(
parent,
val=param.val,
valType=param.valType,
fieldName=fieldName,
size=wx.Size(int(self.valueWidth), 24))
elif param.inputType == 'dict':
self.valueCtrl = paramCtrls.DictCtrl(
parent,
val=param.val,
labels=param.allowedLabels,
valType=param.valType,
fieldName=fieldName)
elif param.inputType == 'inv':
self.valueCtrl = paramCtrls.InvalidCtrl(
parent,
val=str(param.val),
valType=param.valType,
fieldName=fieldName,
size=wx.Size(int(self.valueWidth), 24))
else:
self.valueCtrl = paramCtrls.SingleLineCtrl(
parent,
val=str(param.val),
valType=param.valType,
fieldName=fieldName,
size=wx.Size(int(self.valueWidth), 24))
logging.warn(
f"Parameter {fieldName} has unrecognised inputType \"{param.inputType}\"")
# if fieldName == 'Experiment info':
# # for expInfo convert from a string to the list-of-dicts
# val = self.expInfoToListWidget(param.val)
# self.valueCtrl = dialogs.ListWidget(
# parent, val, order=['Field', 'Default'])
if hasattr(self.valueCtrl, 'SetToolTip'):
self.valueCtrl.SetToolTip(wx.ToolTip(_translate(param.hint)))
if not callable(param.allowedVals) and len(param.allowedVals) == 1 or param.readOnly:
self.valueCtrl.Disable() # visible but can't be changed
# add a Validator to the valueCtrl
if fieldName == "name":
self.valueCtrl.SetValidator(NameValidator())
elif param.inputType in ("single", "multi"):
# only want anything that is valType code, or can be with $
self.valueCtrl.SetValidator(CodeSnippetValidator(fieldName, param.label))
# create the type control
if len(param.allowedTypes):
# are there any components with non-empty allowedTypes?
self.typeCtrl = wx.Choice(parent, choices=param.allowedTypes)
self.typeCtrl._choices = copy.copy(param.allowedTypes)
index = param.allowedTypes.index(param.valType)
self.typeCtrl.SetSelection(index)
if len(param.allowedTypes) == 1:
self.typeCtrl.Disable() # visible but can't be changed
# create update control
_localizedUpdateLbls = {
'constant': _translate('constant'),
'set every repeat': _translate('set every repeat'),
'set every frame': _translate('set every frame'),
}
if param.allowedUpdates is not None and len(param.allowedUpdates):
# updates = display-only version of allowed updates
updateLabels = [_localizedUpdateLbls.get(upd, upd) for upd in param.allowedUpdates]
# allowedUpdates = extend version of allowed updates that includes
# "set during:static period"
allowedUpdates = copy.copy(param.allowedUpdates)
for routineName, routine in list(self.exp.routines.items()):
for static in routine.getStatics():
# Note: replacing following line with
# "localizedMsg = _translate(msg)",
# poedit would not able to find this message.
msg = "set during: "
localizedMsg = _translate("set during: ")
fullName = "{}.{}".format(
routineName, static.params['name'])
allowedUpdates.append(msg + fullName)
updateLabels.append(localizedMsg + fullName)
self.updateCtrl = wx.Choice(parent, choices=updateLabels)
# stash non-localized choices to allow retrieval by index:
self.updateCtrl._choices = copy.copy(allowedUpdates)
# If parameter isn't in list, default to the first choice
if param.updates not in allowedUpdates:
param.updates = allowedUpdates[0]
# get index of the currently set update value, set display:
index = allowedUpdates.index(param.updates)
# set by integer index, not string value
self.updateCtrl.SetSelection(index)
if self.updateCtrl is not None and len(self.updateCtrl.GetItems()) == 1:
self.updateCtrl.Disable() # visible but can't be changed
def _getCtrlValue(self, ctrl):
"""Retrieve the current value form the control (whatever type of ctrl
it is, e.g. checkbox.GetValue, choice.GetSelection)
Different types of control have different methods for retrieving
value. This function checks them all and returns the value or None.
.. note::
Don't use GetStringSelection() here to avoid that translated value
is returned. Instead, use GetSelection() to get index of selection
and get untranslated value from _choices attribute.
"""
if ctrl is None:
return None
elif hasattr(ctrl, 'getValue'):
return ctrl.getValue()
elif ctrl == self.updateCtrl:
return ctrl.GetStringSelection()
elif hasattr(ctrl, 'GetText'):
return ctrl.GetText()
elif hasattr(ctrl, 'GetValue'): # e.g. TextCtrl
val = ctrl.GetValue()
if isinstance(self.valueCtrl, dialogs.ListWidget):
val = self.expInfoFromListWidget(val)
return val
elif hasattr(ctrl, 'GetCheckedStrings'):
return ctrl.GetCheckedStrings()
elif hasattr(ctrl, 'GetLabel'): # for wx.StaticText
return ctrl.GetLabel()
else:
print("failed to retrieve the value for %s" % ctrl)
return None
def _setCtrlValue(self, ctrl, newVal):
"""Set the current value of the control (whatever type of ctrl it
is, e.g. checkbox.SetValue, choice.SetSelection)
Different types of control have different methods for retrieving
value. This function checks them all and returns the value or None.
.. note::
Don't use SetStringSelection() here to avoid using translated
value. Instead, get index of the value using _choices attribute
and use SetSelection() to set the value.
"""
if ctrl is None:
return None
elif hasattr(ctrl, "setValue"):
ctrl.setValue(newVal)
elif hasattr(ctrl, 'SetValue'): # e.g. TextCtrl
ctrl.SetValue(newVal)
elif hasattr(ctrl, 'SetSelection'): # for wx.Choice
# _choices = list of non-localized strings, set during __init__
# NOTE: add untranslated value to _choices if
# _choices.index(newVal) fails.
index = ctrl._choices.index(newVal)
# set the display to the localized version of the string:
ctrl.SetSelection(index)
elif hasattr(ctrl, 'SetLabel'): # for wx.StaticText
ctrl.SetLabel(newVal)
else:
print("failed to retrieve the value for %s" % (ctrl))
def getValue(self):
"""Get the current value of the value ctrl
"""
return self._getCtrlValue(self.valueCtrl)
def setValue(self, newVal):
"""Get the current value of the value ctrl
"""
return self._setCtrlValue(self.valueCtrl, newVal)
def getType(self):
"""Get the current value of the type ctrl
"""
if self.typeCtrl:
return self._getCtrlValue(self.typeCtrl)
def getUpdates(self):
"""Get the current value of the updates ctrl
"""
if self.updateCtrl:
return self._getCtrlValue(self.updateCtrl)
def setVisible(self, newVal=True):
self._visible = newVal
if hasattr(self.valueCtrl, "ShowAll"):
self.valueCtrl.ShowAll(newVal)
else:
self.valueCtrl.Show(newVal)
self.nameCtrl.Show(newVal)
if self.updateCtrl:
self.updateCtrl.Show(newVal)
if self.typeCtrl:
self.typeCtrl.Show(newVal)
def getVisible(self):
if hasattr(self, "_visible"):
return self._visible
else:
return self.valueCtrl.IsShown()
def expInfoToListWidget(self, expInfoStr):
"""Takes a string describing a dictionary and turns it into a format
that the ListWidget can receive.
returns: list of dicts of {Field:'', Default:''}
"""
expInfo = self.exp.settings.getInfo()
listOfDicts = []
for field, default in list(expInfo.items()):
listOfDicts.append({'Field': field, 'Default': default})
return listOfDicts
def expInfoFromListWidget(self, listOfDicts):
"""Creates a string representation of a dict from a list of
field / default values.
"""
expInfo = {}
for field in listOfDicts:
expInfo[field['Field']] = field['Default']
expInfoStr = repr(expInfo)
return expInfoStr
def setChangesCallback(self, callbackFunction):
"""Set a callback to detect any changes in this value (whether it's
a checkbox event or a text event etc
:param callbackFunction: the function to be called when the valueCtrl
changes value
:return:
"""
if isinstance(self.valueCtrl, wx.TextCtrl):
self.valueCtrl.Bind(wx.EVT_KEY_UP, callbackFunction)
elif isinstance(self.valueCtrl, CodeBox):
self.valueCtrl.Bind(wx.stc.EVT_STC_CHANGE, callbackFunction)
elif isinstance(self.valueCtrl, wx.ComboBox):
self.valueCtrl.Bind(wx.EVT_COMBOBOX, callbackFunction)
elif isinstance(self.valueCtrl, (wx.Choice, paramCtrls.RichChoiceCtrl)):
self.valueCtrl.Bind(wx.EVT_CHOICE, callbackFunction)
elif isinstance(self.valueCtrl, wx.CheckListBox):
self.valueCtrl.Bind(wx.EVT_CHECKLISTBOX, callbackFunction)
elif isinstance(self.valueCtrl, wx.CheckBox):
self.valueCtrl.Bind(wx.EVT_CHECKBOX, callbackFunction)
elif isinstance(self.valueCtrl, paramCtrls.CodeCtrl):
self.valueCtrl.Bind(wx.EVT_KEY_UP, callbackFunction)
elif isinstance(self.valueCtrl, (paramCtrls.DictCtrl, paramCtrls.FileListCtrl)):
pass
else:
print("setChangesCallback doesn't know how to handle ctrl {}"
.format(type(self.valueCtrl)))
class StartStopCtrls(wx.GridBagSizer):
def __init__(self, parent, params):
wx.GridBagSizer.__init__(self, 0, 0)
# Make ctrls
self.ctrls = {}
self.parent = parent
empty = True
for name, param in params.items():
if name in ['startVal', 'stopVal']:
# Add dollar sign
self.dollar = wx.StaticText(parent, label="$")
self.Add(self.dollar, (0, 0), border=6, flag=wx.ALIGN_CENTER_VERTICAL | wx.TOP | wx.RIGHT)
# Add ctrl
self.ctrls[name] = wx.TextCtrl(parent,
value=str(param.val), size=wx.Size(-1, 24))
self.ctrls[name].SetToolTip(param.hint)
self.ctrls[name].Bind(wx.EVT_TEXT, self.updateCodeFont)
self.updateCodeFont(self.ctrls[name])
self.label = wx.StaticText(parent, label=param.label)
self.Add(self.ctrls[name], (0, 2), border=6, flag=wx.EXPAND | wx.TOP)
# There is now content
empty = False
if name in ['startType', 'stopType']:
localizedChoices = list(map(_translate, param.allowedVals or [param.val]))
self.ctrls[name] = wx.Choice(parent,
choices=localizedChoices,
size=wx.Size(96, -1))
self.ctrls[name]._choices = copy.copy(param.allowedVals)
self.ctrls[name].SetSelection(param.allowedVals.index(str(param.val)))
self.Add(self.ctrls[name], (0, 1), border=6, flag=wx.EXPAND | wx.TOP)
# There is now content
empty = False
if name in ['startEstim', 'durationEstim']:
self.ctrls[name] = wx.TextCtrl(parent,
value=str(param.val), size=wx.Size(-1, 24))
self.ctrls[name].Bind(wx.EVT_TEXT, self.updateCodeFont)
self.updateCodeFont(self.ctrls[name])
self.estimLabel = wx.StaticText(parent,
label=param.label, size=wx.Size(-1, 24))
self.estimLabel.SetForegroundColour("grey")
self.Add(self.estimLabel, (1, 1), border=6, flag=wx.EXPAND | wx.ALL)
self.Add(self.ctrls[name], (1, 2), border=6, flag=wx.EXPAND | wx.TOP | wx.BOTTOM)
# There is now content
empty = False
if not empty:
self.AddGrowableCol(2)
def getVisible(self):
return all(ctrl.IsShown() for ctrl in self.ctrls.values())
def setVisible(self, visible=True):
# Show/hide controls
for ctrl in self.ctrls.values():
ctrl.Show(visible)
# Show/hide labels
if hasattr(self, "estimLabel"):
self.estimLabel.Show(visible)
if hasattr(self, "label"):
self.label.Show(visible)
# show/hide dollars
if hasattr(self, "dollar"):
self.dollar.Show(visible)
# Set value to None if hidden (specific to start/stop)
if not visible:
if "startVal" in self.ctrls:
self.ctrls["startVal"].Value = ""
if "stopVal" in self.ctrls:
self.ctrls["stopVal"].Value = ""
# Layout
self.parent.Layout()
def updateCodeFont(self, evt=None):
"""Style input box according to code wanted"""
if isinstance(evt, wx.TextCtrl):
obj = evt
else:
obj = evt.EventObject
if psychopy.experiment.utils.unescapedDollarSign_re.match(obj.GetLineText(0)):
# Set font if code
obj.SetFont(self.parent.GetTopLevelParent().app._codeFont.Bold())
else:
# Set font if not
obj.SetFont(self.parent.GetTopLevelParent().app._mainFont)
class ParamNotebook(wx.Notebook, handlers.ThemeMixin):
class CategoryPage(wx.Panel, handlers.ThemeMixin):
def __init__(self, parent, dlg, params, categ=None):
wx.Panel.__init__(self, parent, size=(600, -1))
self.parent = parent
self.parent = parent
self.dlg = dlg
self.app = self.dlg.app
self.categ = categ
# Setup sizer
self.border = wx.BoxSizer()
self.SetSizer(self.border)
self.sizer = wx.GridBagSizer(0, 0)
self.border.Add(self.sizer, border=12, proportion=1, flag=wx.ALL | wx.EXPAND)
# Add controls
self.ctrls = {}
self.row = 0
# Sort params
sortedParams = OrderedDict(params)
for name in reversed(self.parent.element.order):
if name in sortedParams:
sortedParams.move_to_end(name, last=False)
# Make name ctrl
if "name" in sortedParams:
param = sortedParams.pop("name")
self.addParam("name", param)
# Make start controls
startParams = OrderedDict()
for name in ['startVal', 'startType', 'startEstim']:
if name in sortedParams:
startParams[name] = sortedParams.pop(name)
if startParams:
self.startCtrl = self.addStartStopCtrl(startParams)
# Make stop controls
stopParams = OrderedDict()
for name in ['stopVal', 'stopType', 'durationEstim']:
if name in sortedParams:
stopParams[name] = sortedParams.pop(name)
if stopParams:
self.stopCtrl = self.addStartStopCtrl(stopParams)
# Make controls
for name, param in sortedParams.items():
self.addParam(name, param)
# Add growable
self.sizer.AddGrowableCol(1, 1)
# Check depends
self.checkDepends()
def addParam(self, name, param):
# Make ctrl
self.ctrls[name] = ParamCtrls(self.dlg, param.label, param, self, name)
# Add value ctrl
_flag = wx.EXPAND | wx.ALL
if hasattr(self.ctrls[name].valueCtrl, '_szr'):
self.sizer.Add(self.ctrls[name].valueCtrl._szr, (self.row, 1), border=6, flag=_flag)
else:
self.sizer.Add(self.ctrls[name].valueCtrl, (self.row, 1), border=6, flag=_flag)
# Add other ctrl stuff
_flag = wx.LEFT | wx.RIGHT | wx.ALIGN_CENTER_VERTICAL
self.sizer.Add(self.ctrls[name].nameCtrl, (self.row, 0), (1, 1), border=5, flag=_flag)
if self.ctrls[name].typeCtrl:
self.sizer.Add(self.ctrls[name].typeCtrl, (self.row, 2), border=5, flag=_flag)
if self.ctrls[name].updateCtrl:
self.sizer.Add(self.ctrls[name].updateCtrl, (self.row, 3), border=5, flag=_flag)
# Link to depends callback
self.ctrls[name].setChangesCallback(self.doValidate)
if name == 'name':
self.ctrls[name].valueCtrl.SetFocus()
# Some param ctrls need to grow with page
if param.inputType in ('multi', 'fileList'):
self.sizer.AddGrowableRow(self.row, proportion=1)
# Iterate row
self.row += 1
def addStartStopCtrl(self, params):
# Make controls
panel = StartStopCtrls(self, params)
# Add to dict of ctrls
self.ctrls.update(panel.ctrls)
# Add label
_flag = wx.LEFT | wx.RIGHT | wx.ALIGN_CENTER_VERTICAL
self.sizer.Add(panel.label, (self.row, 0), (1, 1), border=5, flag=_flag)
# Add ctrls
_flag = wx.EXPAND | wx.ALL
self.sizer.Add(panel, (self.row, 1), border=6, flag=_flag)
# Iterate row
self.row += 1
return panel
def checkDepends(self, event=None):
"""Checks the relationships between params that depend on each other
Dependencies are a list of dicts like this (as in BaseComponent):
{"dependsOn": "shape",
"condition": "=='n vertices",
"param": "n vertices",
"true": "Enable", # what to do with param if condition is True
"false": "Disable", # permitted: hide, show, enable, disable
}"""
isChanged = False
for thisDep in self.parent.element.depends:
if not (
thisDep['param'] in list(self.ctrls) + ['start', 'stop']
and thisDep['dependsOn'] in self.ctrls):
# If params are on another page, skip
continue
# Get associated ctrl
if thisDep['param'] == 'start':
dependentCtrls = self.startCtrl
elif thisDep['param'] == 'stop':
dependentCtrls = self.stopCtrl
else:
dependentCtrls = self.ctrls[thisDep['param']]
dependencyCtrls = self.ctrls[thisDep['dependsOn']]
condString = "dependencyCtrls.getValue() {}".format(thisDep['condition'])
if eval(condString):
action = thisDep['true']
else:
action = thisDep['false']
if action == "hide":
# Track change if changed
if dependentCtrls.getVisible():
isChanged = True
# Apply visibiliy
dependentCtrls.setVisible(False)
elif action == "show":
# Track change if changed
if not dependentCtrls.getVisible():
isChanged = True
dependentCtrls.setVisible(True)
elif action == "populate":
# only repopulate if dependency ctrl has changed
dependencyParam = self.parent.element.params[thisDep['dependsOn']]
if dependencyParam.val != dependencyCtrls.getValue():
dependencyParam.val = dependencyCtrls.getValue()
if hasattr(dependentCtrls.valueCtrl, "populate"):
dependentCtrls.valueCtrl.populate()
else:
# if action is "enable" then do ctrl.Enable() etc
for ctrlName in ['valueCtrl', 'nameCtrl', 'updatesCtrl']:
# disable/enable all parts of the control
if hasattr(dependentCtrls, ctrlName):
evalStr = ("dependentCtrls.{}.{}()"
.format(ctrlName, action.title()))
eval(evalStr)
# Update sizer
if isChanged:
self.sizer.SetEmptyCellSize((0, 0))
self.sizer.Layout()
if isinstance(self.dlg, wx.Dialog):
self.dlg.Fit()
self.Refresh()
def doValidate(self, event=None):
self.Validate()
self.checkDepends(event=event)
if hasattr(self.dlg, "updateExperiment"):
self.dlg.updateExperiment()
def _applyAppTheme(self, target=None):
self.SetBackgroundColour("white")
def __init__(self, parent, element, experiment):
wx.Notebook.__init__(self, parent)
self.parent = parent
self.exp = experiment
self.element = element
self.params = element.params
# Setup sizer
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.SetSizer(self.sizer)
# Get arrays of params
paramsByCateg = OrderedDict()
for name, param in self.params.items():
# Add categ if not present
if param.categ not in paramsByCateg:
paramsByCateg[param.categ] = OrderedDict()
# Append param to categ
paramsByCateg[param.categ][name] = param
# Move high priority categs to the front
for categ in reversed(['Basic', 'Layout', 'Appearance', 'Formatting', 'Texture']):
if categ in paramsByCateg:
paramsByCateg.move_to_end(categ, last=False)
# Move low priority categs to the end
for categ in ['Data', 'Custom', 'Hardware', 'Testing']:
if categ in paramsByCateg:
paramsByCateg.move_to_end(categ, last=True)
# Setup pages
self.paramCtrls = {}
for categ, params in paramsByCateg.items():
page = self.CategoryPage(self, self.parent, params, categ=categ)
self.paramCtrls.update(page.ctrls)
# Add page to notebook
self.AddPage(page, _translate(categ))
def checkDepends(self, event=None):
"""
When check depends is called on the whole notebook, check each page
"""
for i in range(self.GetPageCount()):
self.GetPage(i).checkDepends(event)
def getParams(self):
"""retrieves data from any fields in self.paramCtrls
(populated during the __init__ function)
The new data from the dlg get inserted back into the original params
used in __init__ and are also returned from this method.
.. note::
Don't use GetStringSelection() here to avoid that translated value
is returned. Instead, use GetSelection() to get index of selection
and get untranslated value from _choices attribute.
"""
# Create empty list to store fieldnames of params for deletion
killList = []
# get data from input fields
for fieldName in self.params:
param = self.params[fieldName]
# Get control
ctrl = self.paramCtrls[fieldName]
# Get value
if hasattr(ctrl, "getValue"):
param.val = ctrl.getValue()
elif hasattr(ctrl, "GetValue"):
param.val = ctrl.GetValue()
elif isinstance(ctrl, wx.Choice):
if hasattr(ctrl, "_choices"):
param.val = ctrl._choices[ctrl.GetSelection()]
else:
# use GetStringSelection()
# only if this control doesn't has _choices
param.val = ctrl.GetStringSelection()
# Get type
if hasattr(ctrl, "typeCtrl"):
if ctrl.typeCtrl:
param.valType = ctrl.typeCtrl._choices[ctrl.typeCtrl.GetSelection()]
# Get update type
if hasattr(ctrl, "updateCtrl"):
if ctrl.updateCtrl:
updates = ctrl.updateCtrl._choices[ctrl.updateCtrl.GetSelection()]
# may also need to update a static
if param.updates != updates:
self._updateStaticUpdates(fieldName,
param.updates, updates)
param.updates = updates
# If requested, mark param for deletion
if hasattr(ctrl, "valueCtrl") and isinstance(ctrl.valueCtrl, paramCtrls.InvalidCtrl) and ctrl.valueCtrl.forDeletion:
killList.append(fieldName)
# Delete params on kill list
for fieldName in killList:
del self.params[fieldName]
return self.params
def getCategoryIndex(self, categ):
"""
Get page index for a given category
"""
# iterate through pages by index
for i in range(self.GetPageCount()):
# if this page is the correct category, return current index
if self.GetPage(i).categ == categ:
return i
def _updateStaticUpdates(self, fieldName, updates, newUpdates):
"""If the old/new updates ctrl is using a Static component then we
need to remove/add the component name to the appropriate static
"""
exp = self.exp
compName = self.params['name'].val
if hasattr(updates, 'startswith') and "during:" in updates:
# remove the part that says 'during'
updates = updates.split(': ')[1]
origRoutine, origStatic = updates.split('.')
_comp = exp.routines[origRoutine].getComponentFromName(origStatic)
if _comp is not None:
_comp.remComponentUpdate(origRoutine, compName, fieldName)
if hasattr(newUpdates, 'startswith') and "during:" in newUpdates:
# remove the part that says 'during'
newUpdates = newUpdates.split(': ')[1]
newRoutine, newStatic = newUpdates.split('.')
_comp = exp.routines[newRoutine].getComponentFromName(newStatic)
_comp.addComponentUpdate(newRoutine, compName, fieldName)
class _BaseParamsDlg(wx.Dialog):
_style = wx.DEFAULT_DIALOG_STYLE | wx.DIALOG_NO_PARENT | wx.TAB_TRAVERSAL
def __init__(self, frame, element, experiment,
suppressTitles=True,
showAdvanced=False,
size=wx.DefaultSize,
style=_style, editing=False,
timeout=None, openToPage=None):
# translate title
if "name" in element.params:
title = element.params['name'].val + _translate(' Properties')
elif "expName" in element.params:
title = element.params['expName'].val + _translate(' Properties')
else:
title = "Properties"
# get help url
if hasattr(element, 'url'):
helpUrl = element.url
else:
helpUrl = None
# use translated title for display
wx.Dialog.__init__(self, parent=None, id=-1, title=title,
size=size, style=style)
self.frame = frame
self.app = frame.app
self.dpi = self.app.dpi
self.helpUrl = helpUrl
self.params = params = element.params # dict
self.title = title
self.timeout = timeout
if (not editing and
title != 'Experiment Settings' and
'name' in self.params):
# then we're adding a new component, so provide known-valid name:
makeValid = self.frame.exp.namespace.makeValid
self.params['name'].val = makeValid(params['name'].val)
self.paramCtrls = {}
CodeSnippetValidator.clsWarnings = {}
self.suppressTitles = suppressTitles
self.showAdvanced = showAdvanced
self.order = element.order
self.depends = element.depends
self.data = []
# max( len(str(self.params[x])) for x in keys )
self.maxFieldLength = 10
self.timeParams = ['startType', 'startVal', 'stopType', 'stopVal']
self.codeFieldNameFromID = {}
self.codeIDFromFieldName = {}
# a list of all panels in the ctrl to be traversed by validator
self.panels = []
# need font size for STCs:
if wx.Platform == '__WXMSW__':
self.faceSize = 10
elif wx.Platform == '__WXMAC__':
self.faceSize = 14
else:
self.faceSize = 12
# create main sizer
self.mainSizer = wx.BoxSizer(wx.VERTICAL)
self.ctrls = ParamNotebook(self, element, experiment)
self.paramCtrls = self.ctrls.paramCtrls
# open to page
if openToPage is not None:
i = self.ctrls.getCategoryIndex(openToPage)
self.ctrls.ChangeSelection(i)
self.mainSizer.Add(self.ctrls, # ctrls is the notebook of params
proportion=1, flag=wx.EXPAND | wx.ALL, border=5)
self.SetSizerAndFit(self.mainSizer)
def getParams(self):
return self.ctrls.getParams()
def openMonitorCenter(self, event):
self.app.openMonitorCenter(event)
self.paramCtrls['Monitor'].valueCtrl.SetFocus()
# need to delay until the user closes the monitor center
# self.paramCtrls['Monitor'].valueCtrl.Clear()
# if wx.TheClipboard.Open():
# dataObject = wx.TextDataObject()
# if wx.TheClipboard.GetData(dataObject):
# self.paramCtrls['Monitor'].valueCtrl.
# WriteText(dataObject.GetText())
# wx.TheClipboard.Close()
def launchColorPicker(self, event):
# bring up a colorPicker
dlg = PsychoColorPicker(self.frame)
dlg.ShowModal()
dlg.Destroy()
@staticmethod
def showScreenNumbers(evt=None, dur=5):
"""
Spawn some PsychoPy windows to display each monitor's number.
"""
from psychopy.hardware import DeviceManager
DeviceManager.showScreenNumbers(dur=5)
def onNewTextSize(self, event):
self.Fit() # for ExpandoTextCtrl this is needed
def show(self, testing=False):
"""Adds an OK and cancel button, shows dialogue.
This method returns wx.ID_OK (as from ShowModal), but also
sets self.OK to be True or False
"""
# add buttons for OK and Cancel
buttons = wx.BoxSizer(wx.HORIZONTAL)
# help button if we know the url
if self.helpUrl != None:
helpBtn = wx.Button(self, wx.ID_HELP, _translate(" Help "))
_tip = _translate("Go to online help about this component")
helpBtn.SetToolTip(wx.ToolTip(_tip))
helpBtn.Bind(wx.EVT_BUTTON, self.onHelp)
buttons.Add(helpBtn, 0,
flag=wx.LEFT | wx.ALL | wx.ALIGN_CENTER_VERTICAL,
border=3)
self.OKbtn = wx.Button(self, wx.ID_OK, _translate(" OK "))
# intercept OK button if a loop dialog, in case file name was edited:
if type(self) == DlgLoopProperties:
self.OKbtn.Bind(wx.EVT_BUTTON, self.onOK)
self.OKbtn.SetDefault()
CANCEL = wx.Button(self, wx.ID_CANCEL, _translate(" Cancel "))
# Add validator stuff
self.warnings = WarningManager(self)
self.mainSizer.Add(self.warnings.output, border=3, flag=wx.EXPAND | wx.ALL)
self.Validate() # disables OKbtn if bad name, syntax error, etc
buttons.AddStretchSpacer()
# Add Okay and Cancel buttons
if sys.platform == "win32":
btns = [self.OKbtn, CANCEL]
else:
btns = [CANCEL, self.OKbtn]
buttons.Add(btns[0], 0,
wx.ALL | wx.RIGHT | wx.ALIGN_CENTER_VERTICAL,
border=3)
buttons.Add(btns[1], 0,
wx.ALL | wx.RIGHT | wx.ALIGN_CENTER_VERTICAL,
border=3)
# buttons.Realize()
# add to sizer
self.mainSizer.Add(buttons, flag=wx.ALL | wx.EXPAND, border=3)
self.SetSizerAndFit(self.mainSizer)
self.mainSizer.Layout()
# move the position to be v near the top of screen and
# to the right of the left-most edge of builder
builderPos = self.frame.GetPosition()
self.SetPosition((builderPos[0] + 200, 20))
# self.paramCtrls['name'].valueCtrl.SetFocus()
# do show and process return
if self.timeout is not None:
timeout = wx.CallLater(self.timeout, self.autoTerminate)
timeout.Start()
if testing:
self.Show()
else:
retVal = self.ShowModal()
self.OK = bool(retVal == wx.ID_OK)
return wx.ID_OK
def autoTerminate(self, event=None, retval=1):
"""Terminates the dialog early, for use with a timeout
:param event: an optional wx.EVT
:param retval: an optional int to pass to EndModal()
:return:
"""
self.EndModal(retval)
def Validate(self, *args, **kwargs):
"""Validate form data and disable OK button if validation fails.
"""
return self.ctrls.Validate()
def onOK(self, event=None):
"""Handler for OK button which should validate dialog contents.
"""
valid = self.Validate()
if not valid:
return
event.Skip()
def onTextEventCode(self, event=None):
"""process text events for code components: change color to grey
"""
codeBox = event.GetEventObject()
textBeforeThisKey = codeBox.GetText()
keyCode = event.GetKeyCode()
pos = event.GetPosition()
# ord(10)='\n', ord(13)='\l'
if keyCode < 256 and keyCode not in [10, 13]:
# new line is trigger to check syntax
codeBox.setStatus('changed')
elif (keyCode in (10, 13) and
len(textBeforeThisKey) and
textBeforeThisKey[-1] != ':'):
# ... but skip the check if end of line is colon ord(58)=':'
self._setNameColor(self._testCompile(codeBox))
event.Skip()
def _testCompile(self, ctrl, mode='exec'):
"""checks whether code.val is legal python syntax,
returns error status
mode = 'exec' (statement or expr) or 'eval' (expr only)
"""
if hasattr(ctrl, 'GetText'):
val = ctrl.GetText()
elif hasattr(ctrl, 'GetValue'):
# e.g. TextCtrl
val = ctrl.GetValue()
else:
msg = 'Unknown type of ctrl in _testCompile: %s'
raise ValueError(msg % (type(ctrl)))
try:
compile(val, '', mode)
syntaxOk = True
ctrl.setStatus('OK')
except SyntaxError:
ctrl.setStatus('error')
syntaxOk = False
return syntaxOk
def checkCodeSyntax(self, event=None):
"""Checks syntax for whole code component by code box,
sets box bg-color.
"""
if hasattr(event, 'GetEventObject'):
codeBox = event.GetEventObject()
elif hasattr(event, 'GetText'):
# we were given the control itself, not an event
codeBox = event
else:
msg = ('checkCodeSyntax received unexpected event object (%s). '
'Should be a wx.Event or a CodeBox')
raise ValueError(msg % type(event))
text = codeBox.GetText()
if not text.strip():
# if basically empty
codeBox.SetBackgroundColour(white)
return
# test syntax:
goodSyntax = self._testCompile(codeBox)
# not quite every dialog has a name (e.g. settings)
# but if so then set its color
if 'name' in self.paramCtrls:
self._setNameColor(goodSyntax)
def _setNameColor(self, goodSyntax):
if goodSyntax:
_nValCtrl = self.paramCtrls['name'].valueCtrl
_nValCtrl.SetBackgroundColour(codeSyntaxOkay)
self.nameOKlabel.SetLabel('')
else:
self.paramCtrls['name'].valueCtrl.SetBackgroundColour(white)
self.nameOKlabel.SetLabel('syntax error')
def checkCodeWanted(self, event=None):
"""check whether a $ is present (if so, set the display font)
"""
if hasattr(event, 'GetEventObject'):
strBox = event.GetEventObject()
elif hasattr(event, 'GetValue'):
# we were given the control itself, not an event
strBox = event
else:
raise ValueError('checkCodeWanted received unexpected event'
' object (%s).')
try:
val = strBox.GetValue()
stc = False
except Exception:
if not hasattr(strBox, 'GetText'):
# eg, wx.Choice control
if hasattr(event, 'Skip'):
event.Skip()
return
val = strBox.GetText()
# might be StyledTextCtrl
stc = True
if hasattr(event, 'Skip'):
event.Skip()
def _checkName(self, event=None, name=None):
"""checks namespace, return error-msg (str), enable (bool)
"""
if event:
newName = event.GetString()
elif name:
newName = name
elif hasattr(self, 'paramCtrls'):
newName = self.paramCtrls['name'].getValue()
elif hasattr(self, 'globalCtrls'):
newName = self.globalCtrls['name'].getValue()
if newName == '':
return _translate("Missing name"), False
else:
namespace = self.frame.exp.namespace
used = namespace.exists(newName)
sameOldName = bool(newName == self.params['name'].val)
if used and not sameOldName:
msg = _translate(
"That name is in use (it's a %s). Try another name.")
return msg % _translate(used), False
elif not namespace.isValid(newName): # valid as a var name
msg = _translate("Name must be alphanumeric or _, no spaces")
return msg, False
# warn but allow, chances are good that its actually ok
elif namespace.isPossiblyDerivable(newName):
msg = namespace.isPossiblyDerivable(newName)
return msg, True
else:
return "", True
def onHelp(self, event=None):
"""Uses self.app.followLink() to self.helpUrl
"""
self.app.followLink(url=self.helpUrl)
class DlgLoopProperties(_BaseParamsDlg):
_style = wx.DEFAULT_DIALOG_STYLE | wx.DIALOG_NO_PARENT | wx.RESIZE_BORDER
def __init__(self, frame, title="Loop Properties", loop=None,
helpUrl=None, pos=wx.DefaultPosition, size=wx.DefaultSize,
style=_style, depends=[], timeout=None):
# translate title
localizedTitle = title.replace(' Properties',
_translate(' Properties'))
wx.Dialog.__init__(self, None, wx.ID_ANY, localizedTitle,
pos, size, style)
self.helpUrl = helpUrl
self.frame = frame
self.expPath = Path(self.frame.filename).parent
self.exp = frame.exp
self.app = frame.app
self.dpi = self.app.dpi
self.params = {}
self.timeout = timeout
self.panel = wx.Panel(self, -1)
self.globalCtrls = {}
self.constantsCtrls = {}
self.staircaseCtrls = {}
self.multiStairCtrls = {}
self.currentCtrls = {}
self.data = []
self.mainSizer = wx.BoxSizer(wx.VERTICAL)
self.conditions = None
self.conditionsFile = None
self.condNamesInFile = []
# create a valid new name; save old name in case we need to revert
namespace = frame.exp.namespace
defaultName = namespace.makeValid('trials')
oldLoopName = defaultName
if loop:
oldLoopName = loop.params['name'].val
# create default instances of the diff loop types
# for 'random','sequential', 'fullRandom'
self.trialHandler = experiment.loops.TrialHandler(
exp=self.exp, name=oldLoopName, loopType='random',
nReps=5, conditions=[])
# for staircases:
self.stairHandler = experiment.loops.StairHandler(
exp=self.exp, name=oldLoopName, nReps=50, nReversals='',
stepSizes='[0.8,0.8,0.4,0.4,0.2]', stepType='log', startVal=0.5)
self.multiStairHandler = experiment.loops.MultiStairHandler(
exp=self.exp, name=oldLoopName, nReps=50, stairType='simple',
switchStairs='random', conditions=[], conditionsFile='')
# replace defaults with the loop we were given
if loop is None:
self.currentType = 'random'
self.currentHandler = self.trialHandler
elif loop.type == 'TrialHandler':
self.conditions = loop.params['conditions'].val
self.conditionsFile = loop.params['conditionsFile'].val
self.trialHandler = self.currentHandler = loop
# could be 'random', 'sequential', 'fullRandom'
self.currentType = loop.params['loopType'].val
elif loop.type == 'StairHandler':
self.stairHandler = self.currentHandler = loop
self.currentType = 'staircase'
elif loop.type == 'MultiStairHandler':
self.conditions = loop.params['conditions'].val
self.conditionsFile = loop.params['conditionsFile'].val
self.multiStairHandler = self.currentHandler = loop
self.currentType = 'interleaved staircases'
elif loop.type == 'QuestHandler':
pass # what to do for quest?
# Store conditions file
self.conditionsOrig = self.conditions
self.params['name'] = self.currentHandler.params['name']
self.globalPanel = self.makeGlobalCtrls()
self.stairPanel = self.makeStaircaseCtrls()
# the controls for Method of Constants
self.constantsPanel = self.makeConstantsCtrls()
self.multiStairPanel = self.makeMultiStairCtrls()
self.mainSizer.Add(self.globalPanel, border=12,
flag=wx.ALL | wx.EXPAND)
self.mainSizer.Add(wx.StaticLine(self), border=6,
flag=wx.ALL | wx.EXPAND)
self.mainSizer.Add(self.stairPanel, border=12,
flag=wx.ALL | wx.EXPAND)
self.mainSizer.Add(self.constantsPanel, border=12,
flag=wx.ALL | wx.EXPAND)
self.mainSizer.Add(self.multiStairPanel, border=12,
flag=wx.ALL | wx.EXPAND)
self.setCtrls(self.currentType)
# create a list of panels in the dialog, for the validator to step
# through
self.panels = [self.globalPanel, self.stairPanel,
self.constantsPanel, self.multiStairPanel]
self.params = {}
self.params.update(self.trialHandler.params)
self.params.update(self.stairHandler.params)
self.params.update(self.multiStairHandler.params)
self.paramCtrls = {}
self.paramCtrls.update(self.globalCtrls)
self.paramCtrls.update(self.constantsCtrls)
self.paramCtrls.update(self.staircaseCtrls)
self.paramCtrls.update(self.multiStairCtrls)
if "conditionsFile" in self.globalCtrls:
self.updateSummary()
# show dialog and get most of the data
self.show()
if self.OK:
self.params = self.getParams()
# convert endPoints from str to list
_endP = self.params['endPoints'].val
self.params['endPoints'].val = eval("%s" % _endP)
# then sort the list so the endpoints are in correct order
self.params['endPoints'].val.sort()
if loop:
# editing an existing loop
namespace.remove(oldLoopName)
namespace.add(self.params['name'].val)
# don't always have a conditionsFile
if hasattr(self, 'condNamesInFile'):
namespace.add(self.condNamesInFile)
if hasattr(self, 'duplCondNames'):
namespace.remove(self.duplCondNames)
else:
if loop is not None:
# if we had a loop during init then revert to its old name
loop.params['name'].val = oldLoopName
# make sure we set this back regardless of whether OK
# otherwise it will be left as a summary string, not a conditions
if 'conditionsFile' in self.currentHandler.params:
self.currentHandler.params['conditions'].val = self.conditions
def Validate(self, *args, **kwargs):
for ctrl in self.globalCtrls.values():
checker = ctrl.valueCtrl.GetValidator()
if checker:
checker.Validate(self)
return self.warnings.OK
@property
def conditionsFile(self):
"""
Location of the conditions file, in whatever format it is best available in. Ideally
relative to the experiment path, but if this is not possible, then absolute.
"""
if not hasattr(self, "_conditionsFile") or self._conditionsFile is None:
# If no file, return None
return None
elif "$" in str(self._conditionsFile):
# If a variabel, return as string
return str(self._conditionsFile)
else:
# Otherwise return as unix string
return str(self._conditionsFile).replace("\\", "/")
@conditionsFile.setter
def conditionsFile(self, value):
# Store last value
self.conditionsFileOrig = self.conditionsFileAbs
if value in (None, ""):
# Store None as is
self._conditionsFile = None
elif "$" in str(value):
# Store variable as is
self._conditionsFile = str(value)
else:
# Otherwise convert to Path
value = Path(value)
try:
# Relativise if possible
self._conditionsFile = value.relative_to(self.expPath)
except ValueError:
# Otherwise as is
self._conditionsFile = value
@property
def conditionsFileAbs(self):
"""
Absolute path to the conditions file
"""
if not hasattr(self, "_conditionsFile") or self._conditionsFile is None:
# If no file, return None
return None
elif "$" in str(self._conditionsFile):
# If variable. return as is
return str(self._conditionsFile)
elif self._conditionsFile.is_absolute():
# Return as is if absolute
return str(self._conditionsFile)
else:
# Append to experiment path if relative
return str(self.expPath / self._conditionsFile)
def makeGlobalCtrls(self):
panel = wx.Panel(parent=self)
panelSizer = wx.GridBagSizer(0, 0)
panel.SetSizer(panelSizer)
row = 0
for fieldName in ('name', 'loopType', 'isTrials'):
try:
label = self.currentHandler.params[fieldName].label
except Exception:
label = fieldName
self.globalCtrls[fieldName] = ctrls = ParamCtrls(
dlg=self, parent=panel, label=label, fieldName=fieldName,
param=self.currentHandler.params[fieldName])
panelSizer.Add(ctrls.nameCtrl, [row, 0], border=3,
flag=wx.LEFT | wx.RIGHT | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
if hasattr(ctrls.valueCtrl, '_szr'):
panelSizer.Add(ctrls.valueCtrl._szr, [row, 1], border=3,
flag=wx.EXPAND | wx.ALL)
else:
panelSizer.Add(ctrls.valueCtrl, [row, 1], border=3,
flag=wx.EXPAND | wx.ALL)
row += 1
panelSizer.AddGrowableCol(1, 1)
self.globalCtrls['name'].valueCtrl.Bind(wx.EVT_TEXT, self.Validate)
self.Bind(wx.EVT_CHOICE, self.onTypeChanged,
self.globalCtrls['loopType'].valueCtrl)
return panel
def makeConstantsCtrls(self):
# a list of controls for the random/sequential versions
# that can be hidden or shown
handler = self.trialHandler
# loop through the params
keys = list(handler.params.keys())
panel = wx.Panel(parent=self)
panel.app=self.app
panelSizer = wx.GridBagSizer(0, 0)
panel.SetSizer(panelSizer)
row = 0
# add conditions stuff to the *end*
if 'conditionsFile' in keys:
keys.remove('conditionsFile')
keys.append('conditionsFile')
if 'conditions' in keys:
keys.remove('conditions')
keys.append('conditions')
_flag = wx.LEFT | wx.RIGHT | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND
# then step through them
for fieldName in keys:
# try and get alternative "label" for the parameter
try:
label = self.currentHandler.params[fieldName].label
if not label:
# it might exist but be empty
label = fieldName
except Exception:
label = fieldName
# handle special cases
if fieldName == 'endPoints':
continue # this was deprecated in v1.62.00
if fieldName in self.globalCtrls:
# these have already been made and inserted into sizer
ctrls = self.globalCtrls[fieldName]
elif fieldName == 'conditions':
if 'conditions' in handler.params:
_cond = handler.params['conditions'].val
text, OK = self.getTrialsSummary(_cond)
else:
text = _translate("No parameters set")
# we'll create our own widgets
ctrls = ParamCtrls(dlg=self, parent=panel, label=label,
fieldName=fieldName,
param=text, noCtrls=True)
ctrls.valueCtrl = wx.StaticText(
panel, label=text, style=wx.ALIGN_RIGHT)
ctrls.valueCtrl._szr = wx.BoxSizer(wx.HORIZONTAL)
ctrls.valueCtrl._szr.Add(ctrls.valueCtrl)
panelSizer.Add(ctrls.valueCtrl._szr, (row, 1),
flag=wx.ALIGN_RIGHT)
# create refresh button
ctrls.refreshBtn = wx.Button(panel, style=wx.BU_EXACTFIT | wx.BORDER_NONE)
ctrls.refreshBtn.SetBitmap(
icons.ButtonIcon("view-refresh", size=16).bitmap
)
ctrls.refreshBtn.Bind(wx.EVT_BUTTON, self.updateSummary)
ctrls.valueCtrl._szr.Prepend(ctrls.refreshBtn, border=12, flag=wx.LEFT | wx.RIGHT | wx.ALIGN_TOP)
row += 1
else: # normal text entry field
ctrls = ParamCtrls(dlg=self, parent=panel, label=label,
fieldName=fieldName,
param=handler.params[fieldName])
panelSizer.Add(ctrls.nameCtrl, [row, 0], border=3, flag=wx.LEFT | wx.RIGHT | wx.ALIGN_CENTER_VERTICAL)
if hasattr(ctrls.valueCtrl, "_szr"):
panelSizer.Add(ctrls.valueCtrl._szr, [row, 1], border=3, flag=wx.EXPAND | wx.ALL)
else:
panelSizer.Add(ctrls.valueCtrl, [row, 1], border=3, flag=wx.EXPAND | wx.ALL)
row += 1
# Link conditions file browse button to its own special method
if fieldName == 'conditionsFile':
ctrls.valueCtrl.findBtn.Bind(wx.EVT_BUTTON, self.onBrowseTrialsFile)
ctrls.setChangesCallback(self.setNeedUpdate)
# store info about the field
self.constantsCtrls[fieldName] = ctrls
panelSizer.AddGrowableCol(1, 1)
return panel
def makeMultiStairCtrls(self):
# a list of controls for the random/sequential versions
panel = wx.Panel(parent=self)
panel.app = self.app
panelSizer = wx.GridBagSizer(0, 0)
panel.SetSizer(panelSizer)
row = 0
# that can be hidden or shown
handler = self.multiStairHandler
# loop through the params
keys = list(handler.params.keys())
# add conditions stuff to the *end*
# add conditions stuff to the *end*
if 'conditionsFile' in keys:
keys.remove('conditionsFile')
keys.append('conditionsFile')
if 'conditions' in keys:
keys.remove('conditions')
keys.append('conditions')
# then step through them
for fieldName in keys:
# try and get alternative "label" for the parameter
try:
label = handler.params[fieldName].label
if not label: # it might exist but be empty
label = fieldName
except Exception:
label = fieldName
# handle special cases
if fieldName == 'endPoints':
continue # this was deprecated in v1.62.00
if fieldName in self.globalCtrls:
# these have already been made and inserted into sizer
ctrls = self.globalCtrls[fieldName]
elif fieldName == 'conditions':
if 'conditions' in handler.params:
text, OK = self.getTrialsSummary(
handler.params['conditions'].val)
else:
text = _translate(
"No parameters set (select a file above)")
OK = False
# we'll create our own widgets
ctrls = ParamCtrls(dlg=self, parent=panel, label=label,
fieldName=fieldName,
param=text, noCtrls=True)
ctrls.valueCtrl = wx.StaticText(panel, label=text,
style=wx.ALIGN_CENTER)
if OK:
ctrls.valueCtrl.SetForegroundColour("Black")
else:
ctrls.valueCtrl.SetForegroundColour("Red")
if hasattr(ctrls.valueCtrl, "_szr"):
panelSizer.Add(ctrls.valueCtrl._szr, (row, 0),
span=(1, 3), flag=wx.ALIGN_CENTER)
else:
panelSizer.Add(ctrls.valueCtrl, (row, 0),
span=(1, 3), flag=wx.ALIGN_CENTER)
row += 1
else:
# normal text entry field
ctrls = ParamCtrls(dlg=self, parent=panel, label=label,
fieldName=fieldName,
param=handler.params[fieldName])
panelSizer.Add(ctrls.nameCtrl, [row, 0], border=3, flag=wx.LEFT | wx.RIGHT | wx.ALIGN_CENTER_VERTICAL)
if hasattr(ctrls.valueCtrl, "_szr"):
panelSizer.Add(ctrls.valueCtrl._szr, [row, 1], border=3, flag=wx.EXPAND | wx.ALL)
else:
panelSizer.Add(ctrls.valueCtrl, [row, 1], border=3, flag=wx.EXPAND | wx.ALL)
row += 1
# Bind file button with its own special method
if fieldName == 'conditionsFile':
ctrls.valueCtrl.findBtn.Bind(wx.EVT_BUTTON, self.onBrowseTrialsFile)
# store info about the field
self.multiStairCtrls[fieldName] = ctrls
panelSizer.AddGrowableCol(1, 1)
return panel
def makeStaircaseCtrls(self):
"""Setup the controls for a StairHandler
"""
panel = wx.Panel(parent=self)
panelSizer = wx.GridBagSizer(0, 0)
panel.SetSizer(panelSizer)
row = 0
handler = self.stairHandler
# loop through the params
for fieldName in handler.params:
# try and get alternative "label" for the parameter
try:
label = handler.params[fieldName].label
if not label:
# it might exist but be empty
label = fieldName
except Exception:
label = fieldName
# handle special cases
if fieldName == 'endPoints':
continue # this was deprecated in v1.62.00
if fieldName in self.globalCtrls:
# these have already been made and inserted into sizer
ctrls = self.globalCtrls[fieldName]
else: # normal text entry field
ctrls = ParamCtrls(dlg=self, parent=panel, label=label,
fieldName=fieldName,
param=handler.params[fieldName])
panelSizer.Add(ctrls.nameCtrl, [row, 0], border=3, flag=wx.LEFT | wx.RIGHT | wx.ALIGN_CENTER_VERTICAL)
if hasattr(ctrls.valueCtrl, "_szr"):
panelSizer.Add(ctrls.valueCtrl._szr, [row, 1], border=3, flag=wx.EXPAND | wx.ALL)
else:
panelSizer.Add(ctrls.valueCtrl, [row, 1], border=3, flag=wx.EXPAND | wx.ALL)
row += 1
# store info about the field
self.staircaseCtrls[fieldName] = ctrls
panelSizer.AddGrowableCol(1, 1)
return panel
def getTrialsSummary(self, conditions):
if type(conditions) == list and len(conditions) > 0:
# get attr names (conditions[0].keys() inserts u'name' and u' is
# annoying for novice)
paramStr = "["
for param in conditions[0]:
# check for namespace clashes
clashes = self.exp.namespace.getCategories(param)
if clashes:
alert(4705, strFields={
'param': param,
'category': ", ".join(clashes)
})
paramStr += (str(param) + ', ')
# check for derivables
derivable = self.exp.namespace.isPossiblyDerivable(param)
if derivable:
alert(4710, strFields={
'param': param,
'msg': derivable
})
paramStr = paramStr[:-2] + "]" # remove final comma and add ]
# generate summary info
msg = _translate('%(nCondition)i conditions, with %(nParam)i '
'parameters\n%(paramStr)s')
vals = {'nCondition': len(conditions),
'nParam': len(conditions[0]),
'paramStr': paramStr}
return msg % vals, True
else:
if (self.conditionsFile and
not os.path.isfile(self.conditionsFile)):
return _translate("No parameters set (conditionsFile not found)"), False
# No condition file is not an error
return _translate("No parameters set"), True
def setCtrls(self, ctrlType):
# choose the ctrls to show/hide
if ctrlType == 'staircase':
self.currentHandler = self.stairHandler
self.stairPanel.Show()
self.constantsPanel.Hide()
self.multiStairPanel.Hide()
self.currentCtrls = self.staircaseCtrls
elif ctrlType == 'interleaved staircases':
self.currentHandler = self.multiStairHandler
self.stairPanel.Hide()
self.constantsPanel.Hide()
self.multiStairPanel.Show()
self.currentCtrls = self.multiStairCtrls
else:
self.currentHandler = self.trialHandler
self.stairPanel.Hide()
self.constantsPanel.Show()
self.multiStairPanel.Hide()
self.currentCtrls = self.constantsCtrls
self.currentType = ctrlType
# redo layout
self.mainSizer.Layout()
self.Fit()
self.Refresh()
@property
def type(self):
"""What type of loop is represented by this dlg"""
if self.currentHandler.type == "MultiStairHandler":
return "MultiStairHandler:" + self.currentHandler.params['stairType'].val
else:
return self.currentHandler.type
@type.setter
def type(self, value):
self.setCtrls(value)
def onTypeChanged(self, evt=None):
newType = evt.GetString()
if newType == self.currentType:
return
self.setCtrls(newType)
def onBrowseTrialsFile(self, event):
self.conditionsFileOrig = self.conditionsFile
self.conditionsOrig = self.conditions
dlg = wx.FileDialog(self, message=_translate("Open file ..."),
style=wx.FD_OPEN, defaultDir=str(self.expPath))
if dlg.ShowModal() == wx.ID_OK:
self.conditionsFile = dlg.GetPath()
self.currentCtrls['conditionsFile'].valueCtrl.SetValue(
self.conditionsFile
)
self.updateSummary()
def setNeedUpdate(self, evt=None):
"""
Mark that conditions need an update, i.e. enable the refresh button
"""
self.constantsCtrls['conditions'].refreshBtn.Enable()
def updateSummary(self, evt=None):
"""
Figure out what conditions we can get from the file and display them, or an error
or message, as appropriate. Upon completion this will disable the update button as
we are now up to date.
"""
self.conditionsFile = self.currentCtrls['conditionsFile'].valueCtrl.GetValue()
# Check whether the file and path are the same as previously
isSameFilePathAndName = self.conditionsFileAbs == self.conditionsFileOrig
# Start off with no message and assumed valid
msg = ""
valid = True
if self.conditionsFile in (None, ""):
# If no conditions file, no message
msg = ""
valid = True
elif "$" in str(self.conditionsFile):
# If set from a variable, message but no error
msg = _translate("Conditions file set from variable.")
valid = True
else:
duplCondNames = []
try:
_c, _n = data.importConditions(self.conditionsFileAbs.strip(),
returnFieldNames=True)
self.conditions, self.condNamesInFile = _c, _n
msg, valid = self.getTrialsSummary(self.conditions)
except exceptions.ConditionsImportError as err:
# If import conditions errors, then value is not valid
valid = False
errMsg = str(err)
mo = re.search(r'".+\.[0-9]+"$', errMsg)
if "Could not open" in errMsg:
msg = _translate('Could not read conditions from: %s\n') % self.conditionsFile
logging.error('Could not open as a conditions file: %s' % self.conditionsFileAbs)
elif "Bad name:" in errMsg and "punctuation" in errMsg and mo:
# column name is something like "stim.1", which may
# be in conditionsFile or generated by pandas when
# duplicated column names are found.
msg = _translate(
'Bad name in %s: Parameters (column headers) cannot contain dots or be duplicated.'
) % self.conditionsFile
logging.error(
('Bad name in %s: Parameters (column headers) cannot contain dots or be '
'duplicated.') % self.conditionsFileAbs
)
else:
msg = err.translated
logging.error(msg)
# check for Builder variables
builderVariables = []
for condName in self.condNamesInFile:
if condName in self.exp.namespace.builder:
builderVariables.append(condName)
if builderVariables:
msg = _translate('Builder variable(s) ({}) in file:{}').format(
','.join(builderVariables), self.conditionsFile)
logging.error(msg)
valid = False
msg = 'Rejected Builder variable(s) ({}) in file:{}'.format(
','.join(builderVariables), self.conditionsFile)
logging.error(msg)
if len(self.condNamesInFile):
for condName in self.condNamesInFile:
if self.exp.namespace.exists(condName):
duplCondNames.append(condName)
# abbrev long strings to better fit in the dialog:
duplCondNamesStr = ' '.join(duplCondNames)[:42]
if len(duplCondNamesStr) == 42:
duplCondNamesStr = duplCondNamesStr[:39] + '...'
if len(duplCondNames):
if isSameFilePathAndName:
logging.info(
'Assuming reloading file: same filename and '
'duplicate condition names in file: %s' % self.conditionsFile)
else:
self.currentCtrls['conditionsFile'].setValue(self.conditionsFile or "")
logging.warning(
'Warning: Condition names conflict with existing'
':\n[' + duplCondNamesStr + ']\nProceed'
' anyway? (= safe if these are in old file)'
)
valid = False
msg = _translate(
'Duplicate condition names, different '
'conditions file: %s'
) % duplCondNamesStr
# stash condition names but don't add to namespace yet, user can
# still cancel
# add after self.show() in __init__:
self.duplCondNames = duplCondNames
# Update ctrl value in case it's been abbreviated by conditionsFile setter
self.currentCtrls['conditionsFile'].setValue(self.conditionsFile or "")
# Do actual value setting
self.currentCtrls['conditions'].setValue(msg)
if valid:
self.currentCtrls['conditions'].valueCtrl.SetForegroundColour("Black")
else:
self.currentCtrls['conditions'].valueCtrl.SetForegroundColour("Red")
self.Layout()
self.Fit()
# Disable update button now that we're up to date
self.constantsCtrls['conditions'].refreshBtn.Disable()
def getParams(self):
"""Retrieves data and re-inserts it into the handler and returns
those handler params
"""
# get data from input fields
for fieldName in self.currentHandler.params:
if fieldName == 'endPoints':
continue # this was deprecated in v1.62.00
param = self.currentHandler.params[fieldName]
if fieldName in ['conditionsFile']:
param.val = self.conditionsFile or ""
# not the value from ctrl - that was abbreviated
# see onOK() for partial handling = check for '...'
else: # most other fields
# the various dlg ctrls for this param
ctrls = self.currentCtrls[fieldName]
param.val = ctrls.getValue()
# from _baseParamsDlg (handles diff control types)
if ctrls.typeCtrl:
param.valType = ctrls.getType()
if ctrls.updateCtrl:
param.updates = ctrls.getUpdates()
return self.currentHandler.params
def onOK(self, event=None):
# intercept OK in case user deletes or edits the filename manually
if 'conditionsFile' in self.currentCtrls:
self.updateSummary()
event.Skip() # do the OK button press
class DlgComponentProperties(_BaseParamsDlg):
def __init__(self, frame, element, experiment,
suppressTitles=True, size=wx.DefaultSize,
style=wx.DEFAULT_DIALOG_STYLE | wx.DIALOG_NO_PARENT,
editing=False,
timeout=None, testing=False, type=None,
openToPage=None):
style = style | wx.RESIZE_BORDER
self.type = type or element.type
_BaseParamsDlg.__init__(self, frame=frame, element=element, experiment=experiment,
size=size,
style=style, editing=editing,
timeout=timeout, openToPage=openToPage)
self.frame = frame
self.app = frame.app
self.dpi = self.app.dpi
# for all components
self.show(testing)
if not testing:
if self.OK:
self.params = self.getParams() # get new vals from dlg
self.Destroy()
class DlgExperimentProperties(_BaseParamsDlg):
def __init__(self, frame, element, experiment,
suppressTitles=False, size=wx.DefaultSize,
style=wx.DEFAULT_DIALOG_STYLE | wx.DIALOG_NO_PARENT,
timeout=None):
style = style | wx.RESIZE_BORDER
_BaseParamsDlg.__init__(self, frame=frame, element=element, experiment=experiment,
size=size,
style=style,
timeout=timeout)
self.frame = frame
self.app = frame.app
self.dpi = self.app.dpi
# for input devices:
# do this just to set the initial values to be
self.paramCtrls['Full-screen window'].setChangesCallback(self.onFullScrChange)
self.onFullScrChange(event=None)
self.Bind(wx.EVT_CHECKBOX, self.onFullScrChange,
self.paramCtrls['Full-screen window'].valueCtrl)
# Add button to show screen numbers
scrNumCtrl = self.paramCtrls['Screen'].valueCtrl
self.screenNsBtn = wx.Button(scrNumCtrl.GetParent(), label=_translate("Show screen numbers"))
scrNumCtrl._szr.Add(self.screenNsBtn, border=5, flag=wx.ALIGN_CENTER_VERTICAL | wx.RIGHT | wx.LEFT)
scrNumCtrl.Layout()
self.screenNsBtn.Bind(wx.EVT_BUTTON, self.showScreenNumbers)
if timeout is not None:
wx.FutureCall(timeout, self.Destroy)
# for all components
self.show()
if self.OK:
self.params = self.getParams() # get new vals from dlg
self.Destroy()
def onFullScrChange(self, event=None):
"""full-screen has been checked / unchecked.
Show or hide the window size field accordingly
"""
if self.paramCtrls['Full-screen window'].valueCtrl.GetValue():
# get screen size for requested display
numDisplays = wx.Display.GetCount()
try:
screenValue = int(
self.paramCtrls['Screen'].valueCtrl.GetValue())
except ValueError:
# param control currently contains no integer value
screenValue = 1
if screenValue < 1 or screenValue > numDisplays:
logging.error("User requested non-existent screen")
screenN = 0
else:
screenN = screenValue - 1
size = list(wx.Display(screenN).GetGeometry()[2:])
# set vals and disable changes
field = 'Window size (pixels)'
self.paramCtrls[field].valueCtrl.SetValue(str(size))
self.paramCtrls[field].param.val = size
self.paramCtrls[field].valueCtrl.Disable()
self.paramCtrls[field].nameCtrl.Disable()
# enable show/hide mouse
self.paramCtrls['Show mouse'].valueCtrl.Enable()
self.paramCtrls['Show mouse'].nameCtrl.Enable()
else:
self.paramCtrls['Window size (pixels)'].valueCtrl.Enable()
self.paramCtrls['Window size (pixels)'].nameCtrl.Enable()
# set show mouse to visible and disable control
self.paramCtrls['Show mouse'].valueCtrl.Disable()
self.paramCtrls['Show mouse'].nameCtrl.Disable()
self.mainSizer.Layout()
self.Fit()
self.Refresh()
class DlgNewRoutine(wx.Dialog):
def __init__(self, parent, pos=wx.DefaultPosition, size=(512, -1),
style=wx.DEFAULT_DIALOG_STYLE | wx.DIALOG_NO_PARENT):
self.parent = parent # parent is probably the RoutinesNotebook (not the BuilderFrame)
self.app = parent.app
if hasattr(parent, 'frame'):
self.frame = parent.frame
else:
self.frame = parent
# Initialise dlg
wx.Dialog.__init__(self, parent, title=_translate("New Routine"), name=_translate("New Routine"),
size=size, pos=pos, style=style)
# Setup sizer
self.border = wx.BoxSizer(wx.VERTICAL)
self.SetSizer(self.border)
self.sizer = wx.FlexGridSizer(cols=2, vgap=0, hgap=6)
self.border.Add(self.sizer, border=12, proportion=1, flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP)
# Get templates
self.templates = self.frame.routineTemplates
self.templatesByID = {}
self.selectedTemplate = self.templates['Basic']['blank'] # until we know otherwise
# New name ctrl
self.nameLbl = wx.StaticText(self, -1, _translate("New Routine name:"))
self.sizer.Add(self.nameLbl, border=6, flag=wx.ALL | wx.ALIGN_RIGHT)
self.nameCtrl = wx.TextCtrl(self, -1, "", size=(200, -1))
self.nameCtrl.SetToolTip(_translate(
"What is the name for the new Routine? (e.g. instr, trial, feedback)"
))
self.sizer.Add(self.nameCtrl, border=6, flag=wx.ALL | wx.ALIGN_TOP | wx.EXPAND)
# Template picker
self.templateLbl = wx.StaticText(self, -1, _translate("Routine Template:"))
self.sizer.Add(self.templateLbl, border=6, flag=wx.ALL | wx.ALIGN_RIGHT)
self.templateCtrl = wx.Button(self, -1, "Basic:blank", size=(200, -1))
self.templateCtrl.SetToolTip(_translate(
"Select a template to base your new Routine on"
))
self.templateCtrl.Bind(wx.EVT_BUTTON, self.showTemplatesContextMenu)
self.sizer.Add(self.templateCtrl, border=6, flag=wx.ALL | wx.ALIGN_TOP | wx.EXPAND)
# Buttons
self.btnSizer = wx.StdDialogButtonSizer()
self.CANCEL = wx.Button(self, wx.ID_CANCEL, "Cancel")
self.btnSizer.AddButton(self.CANCEL)
self.OK = wx.Button(self, wx.ID_OK, "OK")
self.btnSizer.AddButton(self.OK)
self.btnSizer.Realize()
self.border.Add(self.btnSizer, border=12, flag=wx.ALL | wx.ALIGN_RIGHT)
self.Fit()
self.Center()
def showTemplatesContextMenu(self, evt):
self.templateMenu = wx.Menu()
self.templateMenu.Bind(wx.EVT_MENU, self.onSelectTemplate)
self.templatesByID = {}
for categName, categDict in self.templates.items():
submenu = wx.Menu()
self.templateMenu.Append(wx.ID_ANY, categName, submenu)
for templateName, routine in categDict.items():
id = wx.NewIdRef()
self.templatesByID[id] = {
'routine': routine,
'name': templateName,
'categ': categName,
}
item = submenu.Append(id, templateName)
btnPos = self.templateCtrl.GetRect()
menuPos = (btnPos[0], btnPos[1] + btnPos[3])
self.PopupMenu(self.templateMenu, menuPos)
def onSelectTemplate(self, evt):
id = evt.Id
categ = self.templatesByID[id]['categ']
templateName = self.templatesByID[id]['name']
self.templateCtrl.SetLabelText(f"{categ}: {templateName}")
self.selectedTemplate = self.templates[categ][templateName]
self.Layout() # update the size of the button
self.Fit()
# self.templateMenu.Destroy() # destroy to avoid mem leak
| 86,940
|
Python
|
.py
| 1,863
| 33.633924
| 128
| 0.57512
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,838
|
paramCtrls.py
|
psychopy_psychopy/psychopy/app/builder/dialogs/paramCtrls.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Part of the PsychoPy library
# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd.
# Distributed under the terms of the GNU General Public License (GPL).
import ast
import os
import subprocess
import sys
import webbrowser
import wx
import wx.stc
from psychopy.app.colorpicker import PsychoColorPicker
from psychopy.app.dialogs import ListWidget
from psychopy.colors import Color
from psychopy.localization import _translate
from psychopy import data, prefs, experiment
import re
from pathlib import Path
from . import CodeBox
from ...coder import BaseCodeEditor
from ...themes import icons, handlers
from ... import utils
from ...themes import icons
class _FrameMixin:
@property
def frame(self):
"""
Top level frame associated with this ctrl
"""
topParent = self.GetTopLevelParent()
if hasattr(topParent, "frame"):
return topParent.frame
else:
return topParent
class _ValidatorMixin:
def validate(self, evt=None):
"""Redirect validate calls to global validate method, assigning
appropriate `valType`.
"""
validate(self, self.valType)
if evt is not None:
evt.Skip()
def showValid(self, valid):
"""Style input box according to valid"""
if not hasattr(self, "SetForegroundColour"):
return
if valid:
self.SetForegroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_BTNTEXT))
else:
self.SetForegroundColour(wx.Colour(1, 0, 0))
def updateCodeFont(self, valType):
"""Style input box according to code wanted"""
if not hasattr(self, "SetStyle"):
# Skip if font not applicable to object type
return
if self.GetName() == "name":
# Name is never code
valType = "str"
# get font
if valType == "code" or hasattr(self, "dollarLbl"):
font = self.GetTopLevelParent().app._codeFont.Bold()
else:
font = self.GetTopLevelParent().app._mainFont
# set font
if sys.platform == "linux":
# have to go via SetStyle on Linux
style = wx.TextAttr(self.GetForegroundColour(), font=font)
self.SetStyle(0, len(self.GetValue()), style)
else:
# otherwise SetFont is fine
self.SetFont(font)
class _FileMixin(_FrameMixin):
@property
def rootDir(self):
if not hasattr(self, "_rootDir"):
# Store location of root directory if not defined
self._rootDir = Path(self.frame.exp.filename)
if self._rootDir.is_file():
# Move up a dir if root is a file
self._rootDir = self._rootDir.parent
# Return stored rootDir
return self._rootDir
@rootDir.setter
def rootDir(self, value):
self._rootDir = value
def getFile(self, msg="Specify file ...", wildcard="All Files (*.*)|*.*"):
dlg = wx.FileDialog(self, message=_translate(msg), defaultDir=str(self.rootDir),
style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST,
wildcard=_translate(wildcard))
if dlg.ShowModal() != wx.ID_OK:
return
file = dlg.GetPath()
try:
filename = Path(file).relative_to(self.rootDir)
except ValueError:
filename = Path(file).absolute()
return str(filename).replace("\\", "/")
def getFiles(self, msg="Specify file or files...", wildcard="All Files (*.*)|*.*"):
dlg = wx.FileDialog(self, message=_translate(msg), defaultDir=str(self.rootDir),
style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST | wx.FD_MULTIPLE,
wildcard=_translate(wildcard))
if dlg.ShowModal() != wx.ID_OK:
return
inList = dlg.GetPaths()
outList = []
for file in inList:
try:
filename = Path(file).relative_to(self.rootDir)
except ValueError:
filename = Path(file).absolute()
outList.append(str(filename).replace("\\", "/"))
return outList
class _HideMixin:
def ShowAll(self, visible):
# Get sizer, if present
if hasattr(self, "_szr"):
sizer = self._szr
elif isinstance(self, DictCtrl):
sizer = self
else:
sizer = self.GetSizer()
# If there is a sizer, recursively hide children
if sizer is not None:
self.tunnelShow(sizer, visible)
else:
self.Show(visible)
def HideAll(self):
self.Show(False)
def tunnelShow(self, sizer, visible):
if sizer is not None:
# Show/hide everything in the sizer
for child in sizer.Children:
if child.Window is not None:
child.Window.Show(visible)
if child.Sizer is not None:
# If child is a sizer, recur
self.tunnelShow(child.Sizer, visible)
class SingleLineCtrl(wx.TextCtrl, _ValidatorMixin, _HideMixin):
def __init__(self, parent, valType,
val="", fieldName="",
size=wx.Size(-1, 24), style=wx.TE_LEFT):
# Create self
wx.TextCtrl.__init__(self)
self.Create(parent, -1, val, name=fieldName, size=size, style=style)
self.valType = valType
# On MacOS, we need to disable smart quotes
if sys.platform == 'darwin':
self.OSXDisableAllSmartSubstitutions()
# Add sizer
self._szr = wx.BoxSizer(wx.HORIZONTAL)
if not valType == "str" and not fieldName == "name":
# Add $ for anything to be interpreted verbatim
self.dollarLbl = wx.StaticText(parent, -1, "$", size=wx.Size(-1, -1), style=wx.ALIGN_RIGHT)
self.dollarLbl.SetToolTip(_translate("This parameter will be treated as code - we have already put in the $, so you don't have to."))
self._szr.Add(self.dollarLbl, border=5, flag=wx.ALIGN_CENTER_VERTICAL | wx.RIGHT | wx.LEFT)
# Add self to sizer
self._szr.Add(self, proportion=1, border=5, flag=wx.EXPAND)
# Bind to validation
self.Bind(wx.EVT_TEXT, self.validate)
self.validate()
def Show(self, value=True):
wx.TextCtrl.Show(self, value)
if hasattr(self, "dollarLbl"):
self.dollarLbl.Show(value)
if hasattr(self, "deleteBtn"):
self.deleteBtn.Show(value)
class MultiLineCtrl(SingleLineCtrl, _ValidatorMixin, _HideMixin):
def __init__(self, parent, valType,
val="", fieldName="",
size=wx.Size(-1, 144)):
SingleLineCtrl.__init__(self, parent, valType,
val=val, fieldName=fieldName,
size=size, style=wx.TE_MULTILINE)
class CodeCtrl(BaseCodeEditor, handlers.ThemeMixin, _ValidatorMixin):
def __init__(self, parent, valType,
val="", fieldName="",
size=wx.Size(-1, 144)):
BaseCodeEditor.__init__(self, parent,
ID=wx.ID_ANY, pos=wx.DefaultPosition, size=size,
style=0)
self.valType = valType
self.SetValue(val)
self.fieldName = fieldName
self.params = fieldName
# Setup lexer to style text
self.SetLexer(wx.stc.STC_LEX_PYTHON)
self._applyAppTheme()
# Hide margin
self.SetMarginWidth(0, 0)
# Setup auto indent behaviour as in Code component
self.Bind(wx.EVT_KEY_DOWN, self.onKey)
def getValue(self, evt=None):
return self.GetValue()
def setValue(self, value):
self.SetValue(value)
@property
def val(self):
"""
Alias for Set/GetValue, as .val is used elsewhere
"""
return self.getValue()
@val.setter
def val(self, value):
self.setValue(value)
def onKey(self, evt=None):
CodeBox.OnKeyPressed(self, evt)
class InvalidCtrl(SingleLineCtrl, _ValidatorMixin, _HideMixin):
def __init__(self, parent, valType,
val="", fieldName="",
size=wx.Size(-1, 24), style=wx.DEFAULT):
SingleLineCtrl.__init__(self, parent, valType,
val=val, fieldName=fieldName,
size=size, style=style)
self.Disable()
# Add delete button
self.deleteBtn = wx.Button(parent, label="×", size=(24, 24))
self.deleteBtn.SetForegroundColour("red")
self.deleteBtn.Bind(wx.EVT_BUTTON, self.deleteParam)
self.deleteBtn.SetToolTip(_translate(
"This parameter has come from an older version of PsychoPy. "
"In the latest version of PsychoPy, it is not used. Click this "
"button to delete it. WARNING: This may affect how this experiment "
"works in older versions!"))
self._szr.Add(self.deleteBtn, border=6, flag=wx.LEFT | wx.RIGHT)
# Add deleted label
self.deleteLbl = wx.StaticText(parent, label=_translate("DELETED"))
self.deleteLbl.SetForegroundColour("red")
self.deleteLbl.Hide()
self._szr.Add(self.deleteLbl, border=6, proportion=1, flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL)
# Add undo delete button
self.undoBtn = wx.Button(parent, label="⟲", size=(24, 24))
self.undoBtn.SetToolTip(_translate(
"This parameter will not be deleted until you click Okay. "
"Click this button to revert the deletion and keep the parameter."))
self.undoBtn.Hide()
self.undoBtn.Bind(wx.EVT_BUTTON, self.undoDelete)
self._szr.Add(self.undoBtn, border=6, flag=wx.LEFT | wx.RIGHT)
# Set deletion flag
self.forDeletion = False
def deleteParam(self, evt=None):
"""
When the remove button is pressed, mark this param as for deletion
"""
# Mark for deletion
self.forDeletion = True
# Hide value ctrl and delete button
self.Hide()
self.deleteBtn.Hide()
# Show delete label and
self.undoBtn.Show()
self.deleteLbl.Show()
self._szr.Layout()
def undoDelete(self, evt=None):
# Mark not for deletion
self.forDeletion = False
# Show value ctrl and delete button
self.Show()
self.deleteBtn.Show()
# Hide delete label and
self.undoBtn.Hide()
self.deleteLbl.Hide()
self._szr.Layout()
class IntCtrl(wx.SpinCtrl, _ValidatorMixin, _HideMixin):
def __init__(self, parent, valType,
val="", fieldName="",
size=wx.Size(-1, 24), limits=None):
wx.SpinCtrl.__init__(self)
limits = limits or (-100,100)
self.Create(parent, -1, str(val), name=fieldName, size=size, min=min(limits), max=max(limits))
self.valType = valType
self.Bind(wx.EVT_SPINCTRL, self.spin)
def spin(self, evt):
"""Redirect validate calls to global validate method, assigning appropriate valType"""
if evt.EventType == wx.EVT_SPIN_UP.evtType[0]:
self.SetValue(str(int(self.GetValue())+1))
elif evt.EventType == wx.EVT_SPIN_DOWN.evtType[0]:
self.SetValue(str(int(self.GetValue()) - 1))
validate(self, "int")
BoolCtrl = wx.CheckBox
class ChoiceCtrl(wx.Choice, _ValidatorMixin, _HideMixin):
def __init__(self, parent, valType,
val="", choices=[], labels=[], fieldName="",
size=wx.Size(-1, -1)):
self._choices = choices
self._labels = labels
# Create choice ctrl from labels
wx.Choice.__init__(self)
self.Create(parent, -1, name=fieldName)
self.populate()
self.valType = valType
self.SetStringSelection(val)
def populate(self):
if callable(self._choices):
# if choices are given as a partial, execute it now to get values
choices = self._choices()
else:
# otherwise, treat it as a list
choices = list(self._choices)
if callable(self._labels):
# if labels are given as a partial, execute it now to get values
labels = self._labels()
elif self._labels:
# otherwise, treat it as a list
labels = list(self._labels)
else:
# if not given any labels, alias values
labels = choices
# Map labels to values
_labels = {}
for i, value in enumerate(choices):
if i < len(labels):
_labels[value] = _translate(labels[i]) if labels[i] != '' else ''
else:
_labels[value] = _translate(value) if value != '' else ''
labels = _labels
# store labels and choices
self.labels = labels
self.choices = choices
# apply to ctrl
self.SetItems([str(self.labels[c]) for c in self.choices])
def SetStringSelection(self, string):
strChoices = [str(choice) for choice in self.choices]
if string not in self.choices:
if string in strChoices:
# If string is a stringified version of a value in choices, stringify the value in choices
i = strChoices.index(string)
self.labels[string] = self.labels.pop(self.choices[i])
self.choices[i] = string
else:
# Otherwise it is a genuinely new value, so add it to options
self.choices.append(string)
self.labels[string] = string
# Refresh items
self.SetItems(
[str(self.labels[c]) for c in self.choices]
)
# Don't use wx.Choice.SetStringSelection here because label string is localized.
wx.Choice.SetSelection(self, self.choices.index(string))
def getValue(self):
# Don't use wx.Choice.GetStringSelection here because label string is localized.
return self.choices[self.GetSelection()]
class MultiChoiceCtrl(wx.CheckListBox, _ValidatorMixin, _HideMixin):
def __init__(self, parent, valType,
vals="", choices=[], fieldName="",
size=wx.Size(-1, -1)):
wx.CheckListBox.__init__(self)
self.Create(parent, id=wx.ID_ANY, size=size, choices=choices, name=fieldName, style=wx.LB_MULTIPLE)
self.valType = valType
self._choices = choices
# Make initial selection
if isinstance(vals, str):
# Convert to list if needed
vals = data.utils.listFromString(vals, excludeEmpties=True)
self.SetCheckedStrings(vals)
self.validate()
def SetCheckedStrings(self, strings):
if not isinstance(strings, (list, tuple)):
strings = [strings]
for s in strings:
if s not in self._choices:
self._choices.append(s)
self.SetItems(self._choices)
wx.CheckListBox.SetCheckedStrings(self, strings)
def GetValue(self, evt=None):
return self.GetCheckedStrings()
class RichChoiceCtrl(wx.Panel, _ValidatorMixin, _HideMixin):
class RichChoiceItem(wx.Panel):
def __init__(self, parent, value, label, body="", linkText="", link="", startShown="always", viewToggle=True):
# Initialise
wx.Panel.__init__(self, parent, style=wx.BORDER_THEME)
self.parent = parent
self.value = value
self.startShown = startShown
# Setup sizer
self.border = wx.BoxSizer()
self.SetSizer(self.border)
self.sizer = wx.FlexGridSizer(cols=3)
self.sizer.AddGrowableCol(idx=1, proportion=1)
self.border.Add(self.sizer, proportion=1, border=6, flag=wx.ALL | wx.EXPAND)
# Check
self.check = wx.CheckBox(self, label=" ")
self.check.Bind(wx.EVT_CHECKBOX, self.onCheck)
self.check.Bind(wx.EVT_KEY_UP, self.onToggle)
self.sizer.Add(self.check, border=3, flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL)
# Title
self.title = wx.StaticText(self, label=label)
self.title.SetFont(self.title.GetFont().Bold())
self.sizer.Add(self.title, border=3, flag=wx.ALL | wx.EXPAND)
# Toggle
self.toggleView = wx.ToggleButton(self, style=wx.BU_EXACTFIT)
self.toggleView.Bind(wx.EVT_TOGGLEBUTTON, self.onToggleView)
self.toggleView.Show(viewToggle)
self.sizer.Add(self.toggleView, border=3, flag=wx.ALL | wx.EXPAND)
# Body
self.body = utils.WrappedStaticText(self, label=body)
self.sizer.AddStretchSpacer(1)
self.sizer.Add(self.body, border=3, proportion=1, flag=wx.ALL | wx.EXPAND)
self.sizer.AddStretchSpacer(1)
# Link
self.link = utils.HyperLinkCtrl(self, label=linkText, URL=link)
self.link.SetBackgroundColour(self.GetBackgroundColour())
self.sizer.AddStretchSpacer(1)
self.sizer.Add(self.link, border=3, flag=wx.ALL | wx.ALIGN_LEFT)
self.sizer.AddStretchSpacer(1)
# Style
self.SetBackgroundColour("white")
self.body.SetBackgroundColour("white")
self.link.SetBackgroundColour("white")
self.Layout()
def getChecked(self):
return self.check.GetValue()
def setChecked(self, state):
if self.parent.multi:
# If multi select is allowed, leave other values unchanged
values = self.parent.getValue()
if not isinstance(values, (list, tuple)):
values = [values]
if state:
# Add this item to list if checked
values.append(self.value)
else:
# Remove this item from list if unchecked
if self.value in values:
values.remove(self.value)
self.parent.setValue(values)
elif state:
# If single only, set at parent level so others are unchecked
self.parent.setValue(self.value)
def onCheck(self, evt):
self.setChecked(evt.IsChecked())
def onToggle(self, evt):
if evt.GetUnicodeKey() in (wx.WXK_SPACE, wx.WXK_NUMPAD_SPACE):
self.setChecked(not self.check.IsChecked())
def onToggleView(self, evt):
# If called with a boolean, use it directly, otherwise get bool from event
if isinstance(evt, bool):
val = evt
else:
val = evt.IsChecked()
# Update toggle ctrl label
if val:
lbl = "⯆"
else:
lbl = "⯇"
self.toggleView.SetLabel(lbl)
# Show/hide body based on value
self.body.Show(val)
self.link.Show(val)
# Layout
self.Layout()
self.parent.parent.Layout() # layout params notebook page
def __init__(self, parent, valType,
vals="", fieldName="",
choices=[], labels=[],
size=wx.Size(-1, -1),
viewToggle=True):
# Initialise
wx.Panel.__init__(self, parent, size=size)
self.parent = parent
self.valType = valType
self.fieldName = fieldName
self.multi = False
self.viewToggle = viewToggle
# Setup sizer
self.border = wx.BoxSizer()
self.SetSizer(self.border)
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.border.Add(self.sizer, proportion=1, border=6, flag=wx.ALL | wx.EXPAND)
self.SetSizer(self.border)
# Store values
self.choices = {}
for i, val in enumerate(choices):
self.choices[val] = labels[i]
# Populate
self.populate()
# Set value
self.setValue(vals)
# Start off showing according to param
for obj in self.items:
# Work out if we should start out shown
if self.viewToggle:
if obj.startShown == "never":
startShown = False
elif obj.startShown == "checked":
startShown = obj.check.IsChecked()
elif obj.startShown == "unchecked":
startShown = not obj.check.IsChecked()
else:
startShown = True
else:
startShown = True
# Apply starting view
obj.toggleView.SetValue(startShown)
obj.onToggleView(startShown)
self.Layout()
def populate(self):
self.items = []
for val, label in self.choices.items():
if not isinstance(label, dict):
# Make sure label is dict
label = {"label": label}
# Add item control
self.addItem(val, label=label)
self.Layout()
def addItem(self, value, label={}):
# Create item object
item = self.RichChoiceItem(self, value=value, viewToggle=self.viewToggle, **label)
self.items.append(item)
# Add to sizer
self.sizer.Add(item, border=3, flag=wx.ALL | wx.EXPAND)
def getValue(self):
# Get corresponding value for each checked item
values = []
for item in self.items:
if item.getChecked():
# If checked, append value
values.append(item.value)
# Strip list if not multi
if not self.multi:
if len(values):
values = values[0]
else:
values = ""
return values
def setValue(self, value):
# Make sure value is iterable
if not isinstance(value, (list, tuple)):
value = [value]
# Check/uncheck corresponding items
for item in self.items:
state = item.value in value
item.check.SetValue(state)
# Post event
evt = wx.ListEvent(commandType=wx.EVT_CHOICE.typeId, id=-1)
evt.SetEventObject(self)
wx.PostEvent(self, evt)
self.Layout()
class FileCtrl(wx.TextCtrl, _ValidatorMixin, _HideMixin, _FileMixin):
def __init__(self, parent, valType,
val="", fieldName="",
size=wx.Size(-1, 24)):
# Create self
wx.TextCtrl.__init__(self)
self.Create(parent, -1, val, name=fieldName, size=size)
self.valType = valType
# Add sizer
self._szr = wx.BoxSizer(wx.HORIZONTAL)
self._szr.Add(self, border=5, proportion=1, flag=wx.EXPAND | wx.RIGHT)
# Add button to browse for file
fldr = icons.ButtonIcon(stem="folder", size=16, theme="light").bitmap
self.findBtn = wx.BitmapButton(parent, -1, bitmap=fldr, style=wx.BU_EXACTFIT)
self.findBtn.SetToolTip(_translate("Specify file ..."))
self.findBtn.Bind(wx.EVT_BUTTON, self.findFile)
self._szr.Add(self.findBtn)
# Configure validation
self.Bind(wx.EVT_TEXT, self.validate)
self.validate()
def findFile(self, evt):
file = self.getFile()
if file:
self.setFile(file)
self.validate(evt)
def setFile(self, file):
# Set text value
wx.TextCtrl.SetValue(self, file)
# Post event
evt = wx.FileDirPickerEvent(wx.EVT_FILEPICKER_CHANGED.typeId, self, -1, file)
evt.SetEventObject(self)
wx.PostEvent(self, evt)
# Post keypress event to trigger onchange
evt = wx.FileDirPickerEvent(wx.EVT_KEY_UP.typeId, self, -1, file)
evt.SetEventObject(self)
wx.PostEvent(self, evt)
class FileListCtrl(wx.ListBox, _ValidatorMixin, _HideMixin, _FileMixin):
def __init__(self, parent, valType,
choices=[], size=None, pathtype="rel"):
wx.ListBox.__init__(self)
self.valType = valType
parent.Bind(wx.EVT_DROP_FILES, self.addItem)
self.app = parent.app
if type(choices) == str:
choices = data.utils.listFromString(choices)
self.Create(id=wx.ID_ANY, parent=parent, choices=choices, size=size, style=wx.LB_EXTENDED | wx.LB_HSCROLL)
self.addCustomBtn = wx.Button(parent, -1, size=(24,24), style=wx.BU_EXACTFIT, label="...")
self.addCustomBtn.Bind(wx.EVT_BUTTON, self.addCustomItem)
self.addBtn = wx.Button(parent, -1, size=(24,24), style=wx.BU_EXACTFIT, label="+")
self.addBtn.Bind(wx.EVT_BUTTON, self.addItem)
self.subBtn = wx.Button(parent, -1, size=(24,24), style=wx.BU_EXACTFIT, label="-")
self.subBtn.Bind(wx.EVT_BUTTON, self.removeItem)
self._szr = wx.BoxSizer(wx.HORIZONTAL)
self.btns = wx.BoxSizer(wx.VERTICAL)
self.btns.AddMany((self.addCustomBtn, self.addBtn, self.subBtn))
self._szr.Add(self, proportion=1, flag=wx.EXPAND)
self._szr.Add(self.btns)
def addItem(self, event):
# Get files
if event.GetEventObject() == self.addBtn:
fileList = self.getFiles()
else:
fileList = event.GetFiles()
for i, filename in enumerate(fileList):
try:
fileList[i] = Path(filename).relative_to(self.rootDir)
except ValueError:
fileList[i] = Path(filename).absolute()
# Add files to list
if fileList:
self.InsertItems(fileList, 0)
def removeItem(self, event):
i = self.GetSelections()
if isinstance(i, int):
i = [i]
items = [item for index, item in enumerate(self.Items)
if index not in i]
self.SetItems(items)
def addCustomItem(self, event):
# Create string dialog
dlg = wx.TextEntryDialog(parent=self, message=_translate("Add custom item"))
# Show dialog
if dlg.ShowModal() != wx.ID_OK:
return
# Get string
stringEntry = dlg.GetValue()
# Add to list
if stringEntry:
self.InsertItems([stringEntry], 0)
def GetValue(self):
return self.Items
class SurveyCtrl(wx.TextCtrl, _ValidatorMixin, _HideMixin):
class SurveyFinderDlg(wx.Dialog, utils.ButtonSizerMixin):
def __init__(self, parent, session):
wx.Dialog.__init__(self, parent=parent, size=(-1, 496), style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER)
self.session = session
# Setup sizer
self.border = wx.BoxSizer(wx.VERTICAL)
self.SetSizer(self.border)
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.border.Add(self.sizer, border=12, proportion=1, flag=wx.ALL | wx.EXPAND)
# Add instructions
self.instr = utils.WrappedStaticText(self, label=_translate(
"Below are all of the surveys linked to your Pavlovia account - select the one you want and "
"press OK to add its ID."
))
self.sizer.Add(self.instr, border=6, flag=wx.ALL | wx.EXPAND)
# Add ctrl
self.ctrl = wx.ListCtrl(self, size=(-1, 248), style=wx.LC_REPORT)
self.sizer.Add(self.ctrl, border=6, proportion=1, flag=wx.ALL | wx.EXPAND)
# Add placeholder for when there are no surveys
self.placeholder = wx.TextCtrl(self, size=(-1, 248), value=_translate(
"There are no surveys linked to your Pavlovia account."
), style=wx.TE_READONLY | wx.TE_MULTILINE)
self.sizer.Add(self.placeholder, border=6, proportion=1, flag=wx.ALL | wx.EXPAND)
self.placeholder.Hide()
# Sizer for extra ctrls
self.extraCtrls = wx.Panel(self)
self.extraCtrls.sizer = wx.BoxSizer(wx.HORIZONTAL)
self.extraCtrls.SetSizer(self.extraCtrls.sizer)
self.sizer.Add(self.extraCtrls, border=6, flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND)
# Link to Pavlovia
self.pavLink = utils.HyperLinkCtrl(self.extraCtrls, label=_translate(
"Click here to manage surveys on Pavlovia."
), URL="https://pavlovia.org/dashboard?tab=4")
self.extraCtrls.sizer.Add(self.pavLink, flag=wx.ALL | wx.ALIGN_LEFT)
# Update button
self.updateBtn = wx.Button(self.extraCtrls, size=(24, 24))
self.updateBtn.SetBitmap(icons.ButtonIcon(stem="view-refresh", size=16).bitmap)
self.updateBtn.SetToolTip(_translate(
"Refresh survey list"
))
self.updateBtn.Bind(wx.EVT_BUTTON, self.populate)
self.extraCtrls.sizer.AddStretchSpacer(prop=1)
self.extraCtrls.sizer.Add(self.updateBtn, flag=wx.ALL | wx.EXPAND)
# Setup dialog buttons
self.btnSizer = self.CreatePsychoPyDialogButtonSizer(flags=wx.OK | wx.CANCEL | wx.HELP)
self.sizer.AddSpacer(12)
self.border.Add(self.btnSizer, border=6, flag=wx.ALL | wx.EXPAND)
# Populate
self.populate()
self.Layout()
def populate(self, evt=None):
# Clear ctrl
self.ctrl.ClearAll()
self.ctrl.InsertColumn(0, "Name")
self.ctrl.InsertColumn(1, "ID")
# Ask Pavlovia for list of surveys
resp = self.session.session.get(
"https://pavlovia.org/api/v2/surveys",
timeout=10
).json()
# Get surveys from returned json
surveys = resp['surveys']
# If there are no surveys, hide the ctrl and present link to survey designer
if len(surveys):
self.ctrl.Show()
self.placeholder.Hide()
else:
self.ctrl.Hide()
self.placeholder.Show()
# Populate control
for survey in surveys:
self.ctrl.Append([
survey['surveyName'],
survey['surveyId']
])
# Resize columns
self.ctrl.SetColumnWidth(0, wx.LIST_AUTOSIZE)
self.ctrl.SetColumnWidth(1, wx.LIST_AUTOSIZE)
def getValue(self):
i = self.ctrl.GetFirstSelected()
if i > -1:
return self.ctrl.GetItem(i, col=1).Text
else:
return ""
def __init__(self, parent, valType,
val="", fieldName="",
size=wx.Size(-1, 24)):
# Create self
wx.TextCtrl.__init__(self)
self.Create(parent, -1, val, name=fieldName, size=size)
self.valType = valType
# Add CTRL + click behaviour
self.Bind(wx.EVT_RIGHT_DOWN, self.onRightClick)
# Add placeholder
self.SetHint("e.g. e89cd6eb-296e-4960-af14-103026a59c14")
# Add sizer
self._szr = wx.BoxSizer(wx.HORIZONTAL)
self._szr.Add(self, border=5, proportion=1, flag=wx.EXPAND | wx.RIGHT)
# Add button to browse for survey
self.findBtn = wx.Button(
parent, -1,
label=_translate("Find online..."),
size=wx.Size(-1, 24)
)
self.findBtn.SetBitmap(
icons.ButtonIcon(stem="search", size=16).bitmap
)
self.findBtn.SetToolTip(_translate(
"Get survey ID from a list of your surveys on Pavlovia"
))
self.findBtn.Bind(wx.EVT_BUTTON, self.findSurvey)
self._szr.Add(self.findBtn)
# Configure validation
self.Bind(wx.EVT_TEXT, self.validate)
self.validate()
def onRightClick(self, evt=None):
menu = wx.Menu()
thisId = menu.Append(wx.ID_ANY, item=f"https://pavlovia.org/surveys/{self.getValue()}")
menu.Bind(wx.EVT_MENU, self.openSurvey, source=thisId)
self.PopupMenu(menu)
def openSurvey(self, evt=None):
"""
Open current survey in web browser
"""
webbrowser.open(f"https://pavlovia.org/surveys/{self.getValue()}")
def findSurvey(self, evt=None):
# Import Pavlovia modules locally to avoid Pavlovia bugs affecting other param ctrls
from psychopy.projects.pavlovia import getCurrentSession
from ...pavlovia_ui import checkLogin
# Get session
session = getCurrentSession()
# Check Pavlovia login
if checkLogin(session):
# Get session again incase login process changed it
session = getCurrentSession()
# Show survey finder dialog
dlg = self.SurveyFinderDlg(self, session)
if dlg.ShowModal() == wx.ID_OK:
# If OK, get value
self.SetValue(dlg.getValue())
# Validate
self.validate()
# Raise event
evt = wx.ListEvent(wx.EVT_KEY_UP.typeId)
evt.SetEventObject(self)
wx.PostEvent(self, evt)
def getValue(self, evt=None):
"""
Get the value of the text control, but sanitize such that if the user pastes a full survey URL
we only take the survey ID
"""
# Get value by usual wx method
value = self.GetValue()
# Strip pavlovia run url
if "run.pavlovia.org/pavlovia/survey/?surveyId=" in value:
# Keep only the values after the URL
value = value.split("run.pavlovia.org/pavlovia/survey/?surveyId=")[-1]
if "&" in value:
# If there are multiple URL parameters, only keep the Id
value = value.split("&")[0]
# Strip regular pavlovia url
elif "pavlovia.org/surveys/" in value:
# Keep only the values after the URL
value = value.split(".pavlovia.org/pavlovia/survey/")[-1]
if "&" in value:
# If there are URL parameters, only keep the Id
value = value.split("?")[0]
return value
class TableCtrl(wx.TextCtrl, _ValidatorMixin, _HideMixin, _FileMixin):
def __init__(self, parent, param, fieldName="",
size=wx.Size(-1, 24)):
# get val and val type
val = param.val
valType = param.valType
# store param
self.param = param
# Create self
wx.TextCtrl.__init__(self)
self.Create(parent, -1, val, name=fieldName, size=size)
self.valType = valType
# Add sizer
self._szr = wx.BoxSizer(wx.HORIZONTAL)
self._szr.Add(self, proportion=1, border=5, flag=wx.EXPAND | wx.RIGHT)
# Add button to browse for file
fldr = icons.ButtonIcon(stem="folder", size=16, theme="light").bitmap
self.findBtn = wx.BitmapButton(parent, -1, bitmap=fldr, style=wx.BU_EXACTFIT)
self.findBtn.SetToolTip(_translate("Specify file ..."))
self.findBtn.Bind(wx.EVT_BUTTON, self.findFile)
self._szr.Add(self.findBtn)
# Add button to open in Excel
xl = icons.ButtonIcon(stem="filecsv", size=16, theme="light").bitmap
self.xlBtn = wx.BitmapButton(parent, -1, bitmap=xl, style=wx.BU_EXACTFIT)
self.xlBtn.SetToolTip(_translate("Open/create in your default table editor"))
self.xlBtn.Bind(wx.EVT_BUTTON, self.openExcel)
self._szr.Add(self.xlBtn)
# Specify valid extensions
self.validExt = [".csv",".tsv",".txt",
".xl",".xlsx",".xlsm",".xlsb",".xlam",".xltx",".xltm",".xls",".xlt",
".htm",".html",".mht",".mhtml",
".xml",".xla",".xlm",
".odc",".ods",
".udl",".dsn",".mdb",".mde",".accdb",".accde",".dbc",".dbf",
".iqy",".dqy",".rqy",".oqy",
".cub",".atom",".atomsvc",
".prn",".slk",".dif"]
# Configure validation
self.Bind(wx.EVT_TEXT, self.validate)
self.validate()
def validate(self, evt=None):
"""Redirect validate calls to global validate method, assigning appropriate valType"""
validate(self, "file")
# if field is blank, enable/diable according to whether there's a template
if not self.GetValue().strip():
self.xlBtn.Enable("template" in self.param.ctrlParams)
# otherwise, enable/disable according to validity
else:
self.xlBtn.Enable(self.valid)
# if value isn't known until runtime, always disable Excel button
if "$" in self.GetValue():
self.xlBtn.Disable()
def openExcel(self, event):
"""Either open the specified excel sheet, or make a new one from a template"""
file = self.rootDir / self.GetValue()
if not (file.is_file() and file.suffix in self.validExt): # If not a valid file
dlg = wx.MessageDialog(self, _translate(
"Once you have created and saved your table,"
"please remember to add it to {name}").format(name=_translate(self.Name)),
caption=_translate("Reminder"))
dlg.ShowModal()
# get template
if "template" in self.param.ctrlParams:
file = self.param.ctrlParams['template']
# if template is specified as a method, call it now to get the value live
if callable(file):
file = file()
# convert to Path
file = Path(file)
else:
# use blank template if none given
file = Path(experiment.__file__).parent / 'blankTemplate.xltx',
# Open whatever file is used
try:
os.startfile(file)
except AttributeError:
opener = "open" if sys.platform == "darwin" else "xdg-open"
subprocess.call([opener, file])
def findFile(self, event):
_wld = f"All Table Files({'*'+';*'.join(self.validExt)})|{'*'+';*'.join(self.validExt)}|All Files (*.*)|*.*"
file = self.getFile(msg="Specify table file ...", wildcard=_wld)
if file:
self.SetValue(file)
self.validate(event)
class ColorCtrl(wx.TextCtrl, _ValidatorMixin, _HideMixin):
def __init__(self, parent, valType,
val="", fieldName="",
size=wx.Size(-1, 24)):
# Create self
wx.TextCtrl.__init__(self)
self.Create(parent, -1, val, name=fieldName, size=size)
self.valType = valType
# Add sizer
self._szr = wx.BoxSizer(wx.HORIZONTAL)
if valType == "code":
# Add $ for anything to be interpreted verbatim
self.dollarLbl = wx.StaticText(parent, -1, "$", size=wx.Size(-1, -1), style=wx.ALIGN_RIGHT)
self.dollarLbl.SetToolTip(_translate("This parameter will be treated as code - we have already put in the $, so you don't have to."))
self._szr.Add(self.dollarLbl, border=5, flag=wx.ALIGN_CENTER_VERTICAL | wx.RIGHT | wx.LEFT)
# Add ctrl to sizer
self._szr.Add(self, proportion=1, border=5, flag=wx.EXPAND | wx.RIGHT)
# Add button to activate color picker
fldr = icons.ButtonIcon(stem="color", size=16, theme="light").bitmap
self.pickerBtn = wx.BitmapButton(parent, -1, bitmap=fldr, style=wx.BU_EXACTFIT)
self.pickerBtn.SetToolTip(_translate("Specify color ..."))
self.pickerBtn.Bind(wx.EVT_BUTTON, self.colorPicker)
self._szr.Add(self.pickerBtn)
# Bind to validation
self.Bind(wx.EVT_CHAR, self.validate)
self.validate()
def colorPicker(self, evt):
dlg = PsychoColorPicker(self, context=self, allowCopy=False) # open a color picker
dlg.ShowModal()
dlg.Destroy()
def validate(obj, valType):
val = str(obj.GetValue())
valid = True
if val.startswith("$"):
# If indicated as code, treat as code
valType = "code"
# Validate string
if valType == "str":
if re.findall(r"(?<!\\)\"", val):
# If there are unescaped "
valid = False
if re.findall(r"(?<!\\)\'", val):
# If there are unescaped '
valid = False
# Validate code
if valType == "code":
# Replace unescaped curly quotes
if re.findall(r"(?<!\\)[\u201c\u201d]", val):
pt = obj.GetInsertionPoint()
obj.SetValue(re.sub(r"(?<!\\)[\u201c\u201d]", "\"", val))
obj.SetInsertionPoint(pt)
# For now, ignore
pass
# Validate num
if valType in ["num", "int"]:
try:
# Try to convert value to a float
float(val)
except ValueError:
# If conversion fails, value is invalid
valid = False
# Validate bool
if valType == "bool":
if val not in ["True", "False"]:
# If value is not True or False, it is invalid
valid = False
# Validate list
if valType == "list":
empty = not bool(val) # Is value empty?
fullList = re.fullmatch(r"[\(\[].*[\]\)]", val) # Is value full list with parentheses?
partList = "," in val and not re.match(r"[\(\[].*[\]\)]", val) # Is value list without parentheses?
singleVal = not " " in val or re.match(r"[\"\'].*[\"\']", val) # Is value a single value?
if not any([empty, fullList, partList, singleVal]):
# If value is not any of valid types, it is invalid
valid = False
# Validate color
if valType == "color":
# Strip function calls
if re.fullmatch(r"\$?(Advanced)?Color\(.*\)", val):
val = re.sub(r"\$?(Advanced)?Color\(", "", val[:-1])
try:
# Try to create a Color object from value
obj.color = Color(val, False)
if not obj.color:
# If invalid object is created, input is invalid
valid = False
except:
# If object creation fails, input is invalid
valid = False
if valType == "file":
val = Path(str(val))
if not val.is_absolute():
frame = obj.GetTopLevelParent()
if hasattr(frame, "frame"):
frame = frame.frame
# If not an absolute path, append to current directory
val = Path(frame.filename).parent / val
if not val.is_file():
# Is value a valid filepath?
valid = False
if hasattr(obj, "validExt"):
# If control has specified list of ext, does value end in correct ext?
if val.suffix not in obj.validExt:
valid = False
# If additional allowed values are defined, override validation
if hasattr(obj, "allowedVals"):
if val in obj.allowedVals:
valid = True
# Apply valid status to object
obj.valid = valid
if hasattr(obj, "showValid"):
obj.showValid(valid)
# Update code font
obj.updateCodeFont(valType)
class DictCtrl(ListWidget, _ValidatorMixin, _HideMixin):
def __init__(self, parent,
val={}, labels=(_translate("Field"), _translate("Default")), valType='dict',
fieldName=""):
# try to convert to a dict if given a string
if isinstance(val, str):
try:
val = ast.literal_eval(val)
except:
raise ValueError(_translate("Could not interpret parameter value as a dict:\n{}").format(val))
# raise error if still not a dict
if not isinstance(val, (dict, list)):
raise ValueError("DictCtrl must be supplied with either a dict or a list of 1-long dicts, value supplied was {}: {}".format(type(val), val))
# Get labels
keyLbl, valLbl = labels
# If supplied with a dict, convert it to a list of dicts
if isinstance(val, dict):
newVal = []
for key, v in val.items():
if hasattr(v, "val"):
v = v.val
newVal.append({keyLbl: key, valLbl: v})
val = newVal
# Make sure we have at least 1 value
if not len(val):
val = [{keyLbl: "", valLbl: ""}]
# If any items within the list are not dicts or are dicts longer than 1, throw error
if not all(isinstance(v, dict) and len(v) == 2 for v in val):
raise ValueError("DictCtrl must be supplied with either a dict or a list of 1-long dicts, value supplied was {}".format(val))
# Create ListWidget
ListWidget.__init__(self, parent, val, order=labels)
def SetForegroundColour(self, color):
for child in self.Children:
if hasattr(child, "SetForegroundColour"):
child.SetForegroundColour(color)
def Enable(self, enable=True):
"""
Enable or disable all items in the dict ctrl
"""
# Iterate through all children
for cell in self.Children:
# Get the actual child rather than the sizer item
child = cell.Window
# If it can be enabled/disabled, enable/disable it
if hasattr(child, "Enable"):
child.Enable(enable)
def Disable(self):
"""
Disable all items in the dict ctrl
"""
self.Enable(False)
def Show(self, show=True):
"""
Show or hide all items in the dict ctrl
"""
# Iterate through all children
for cell in self.Children:
# Get the actual child rather than the sizer item
child = cell.Window
# If it can be shown/hidden, show/hide it
if hasattr(child, "Show"):
child.Show(show)
def Hide(self):
"""
Hide all items in the dict ctrl
"""
self.Show(False)
| 46,179
|
Python
|
.py
| 1,063
| 32.361242
| 152
| 0.580707
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,839
|
dialog.py
|
psychopy_psychopy/psychopy/app/plugin_manager/dialog.py
|
import subprocess
from pathlib import Path
import wx
from psychopy import prefs
from psychopy.app import getAppInstance
from psychopy.app.plugin_manager import PluginManagerPanel, PackageManagerPanel, InstallStdoutPanel
from psychopy.experiment import getAllElements
from psychopy.localization import _translate
import psychopy.logging as logging
import psychopy.tools.pkgtools as pkgtools
import psychopy.app.jobs as jobs
import sys
import os
import subprocess as sp
import psychopy.plugins as plugins
pkgtools.refreshPackages() # build initial package cache
# flag to indicate if PsychoPy needs to be restarted after installing a package
NEEDS_RESTART = False
class EnvironmentManagerDlg(wx.Dialog):
def __init__(self, parent):
wx.Dialog.__init__(
self, parent=parent,
title=_translate("Plugins & Packages"),
size=(1080, 720),
style=wx.RESIZE_BORDER | wx.DEFAULT_DIALOG_STYLE | wx.CENTER | wx.TAB_TRAVERSAL | wx.NO_BORDER
)
self.SetMinSize((980, 520))
self.app = getAppInstance()
# Setup sizer
self.border = wx.BoxSizer(wx.VERTICAL)
self.SetSizer(self.border)
self.sizer = wx.BoxSizer(wx.HORIZONTAL)
self.border.Add(self.sizer, proportion=1, border=6, flag=wx.EXPAND | wx.ALL)
# Create notebook
self.notebook = wx.Notebook(self)
self.sizer.Add(self.notebook, border=6, proportion=1, flag=wx.EXPAND | wx.ALL)
# Output panel
self.output = InstallStdoutPanel(self.notebook)
self.notebook.AddPage(self.output, text=_translate("Output"))
# Plugin manager
self.pluginMgr = PluginManagerPanel(self.notebook, dlg=self)
self.notebook.InsertPage(0, self.pluginMgr, text=_translate("Plugins"))
# Package manager
self.packageMgr = PackageManagerPanel(self.notebook, dlg=self)
self.notebook.InsertPage(1, self.packageMgr, text=_translate("Packages"))
# Buttons
self.btns = self.CreateStdDialogButtonSizer(flags=wx.HELP | wx.CLOSE)
self.Bind(wx.EVT_CLOSE, self.onClose)
self.border.Add(self.btns, border=12, flag=wx.EXPAND | wx.ALL)
# store button handles
self.closeBtn = self.helpBtn = None
for btn in self.btns.Children:
if not btn.Window:
continue
if btn.Window.GetId() == wx.ID_CLOSE:
self.closeBtn = btn.Window
if btn.Window.GetId() == wx.ID_HELP:
self.helpBtn = btn.Window
self.pipProcess = None # handle to the current Job
self.notebook.ChangeSelection(0)
@staticmethod
def getPackageVersionInfo(packageName):
"""Query packages for available versions.
This function invokes the `pip index versions` ins a subprocess and
parses the results.
Parameters
----------
packageName : str
Name of the package to get available versions of.
Returns
-------
dict
Mapping of versions information. Keys are `'All'` (`list`),
`'Current'` (`str`), and `'Latest'` (`str`).
"""
cmd = [sys.executable, "-m", "pip", "index", "versions", packageName,
'--no-input', '--no-color']
env = os.environ.copy()
# run command in subprocess
output = sp.Popen(
cmd,
stdout=sp.PIPE,
stderr=sp.PIPE,
shell=False,
env=env,
universal_newlines=True)
stdout, stderr = output.communicate() # blocks until process exits
nullVersion = {'All': [], 'Installed': '', 'Latest': ''}
# if stderr: # error pipe has something, give nothing
# return nullVersion
# parse versions
if stdout:
allVersions = installedVersion = latestVersion = None
for line in stdout.splitlines(keepends=False):
line = line.strip() # remove whitespace
if line.startswith("Available versions:"):
allVersions = (line.split(': ')[1]).split(', ')
elif line.startswith("LATEST:"):
latestVersion = line.split(': ')[1].strip()
elif line.startswith("INSTALLED:"):
installedVersion = line.split(': ')[1].strip()
if installedVersion is None: # not present, use first entry
installedVersion = allVersions[0]
if latestVersion is None: # ditto
latestVersion = allVersions[0]
toReturn = {
'All': allVersions,
'Installed': installedVersion,
'Latest': latestVersion}
return toReturn
return nullVersion
@property
def isBusy(self):
"""`True` if there is currently a `pip` subprocess running.
"""
return self.pipProcess is not None
def uninstallPackage(self, packageName):
"""Uninstall a package.
This deletes any bundles in the user's package directory, or uninstalls
packages from `site-packages`.
Parameters
----------
packageName : str
Name of the package to install. Should be the project name but other
formats may work.
"""
# alert if busy
if self.isBusy:
msg = wx.MessageDialog(
self,
("Cannot remove package. Wait for the installation already in "
"progress to complete first."),
"Uninstallation Failed", wx.OK | wx.ICON_WARNING
)
msg.ShowModal()
return
# tab to output
self.output.open()
if pkgtools._isUserPackage(packageName):
msg = 'Uninstalling package bundle for `{}` ...'.format(
packageName)
self.output.writeStdOut(msg)
success = pkgtools._uninstallUserPackage(packageName)
if success:
msg = 'Successfully removed package `{}`.'.format(
packageName)
else:
msg = ('Failed to remove package `{}`, check log for '
'details.').format(packageName)
self.output.writeStdOut(msg)
return
# interpreter path
pyExec = sys.executable
env = os.environ.copy()
# build the shell command to run the script
command = [pyExec, '-m', 'pip', 'uninstall', packageName, '--yes']
# write command to output panel
self.output.writeCmd(" ".join(command))
# create a new job with the user script
self.pipProcess = jobs.Job(
self,
command=command,
# flags=execFlags,
inputCallback=self.output.writeStdOut, # both treated the same
errorCallback=self.output.writeStdErr,
terminateCallback=self.onUninstallExit
)
self.pipProcess.start(env=env)
global NEEDS_RESTART # flag as needing a restart
NEEDS_RESTART = True
def installPackage(self, packageName, version=None, extra=None, forceReinstall=None):
"""Install a package.
Calling this will invoke a `pip` command which will install the
specified package. Packages are installed to bundles and added to the
system path when done.
During an installation, the UI will make the console tab visible. It
will display any messages coming from the subprocess. No way to cancel
and installation midway at this point.
Parameters
----------
packageName : str
Name of the package to install. Should be the project name but other
formats may work.
version : str or None
Version of the package to install. If `None`, the latest version
will be installed.
extra : dict or None
Dict of extra variables to be accessed by callback functions, use None
for a blank dict.
"""
# add version if given
if version is not None:
packageName += f"=={version}"
# if forceReinstall is None, work out from version
if forceReinstall is None:
forceReinstall = version is not None
# use package tools to install
self.pipProcess = pkgtools.installPackage(
packageName,
upgrade=version is None,
forceReinstall=forceReinstall,
awaited=False,
outputCallback=self.output.writeStdOut,
terminateCallback=self.onInstallExit,
extra=extra,
)
def installPlugin(self, pluginInfo, version=None, forceReinstall=None):
"""Install a package.
Calling this will invoke a `pip` command which will install the
specified package. Packages are installed to bundles and added to the
system path when done.
During an installation, the UI will make the console tab visible. It
will display any messages coming from the subprocess. No way to cancel
and installation midway at this point.
Parameters
----------
pluginInfo : psychopy.app.plugin_manager.plugins.PluginInfo
Info object of the plugin to install.
version : str or None
Version of the package to install. If `None`, the latest version
will be installed.
"""
# do install
self.installPackage(
packageName=pluginInfo.pipname,
version=version,
extra={
'pluginInfo': pluginInfo
},
forceReinstall=forceReinstall
)
def uninstallPlugin(self, pluginInfo):
"""Uninstall a plugin.
This deletes any bundles in the user's package directory, or uninstalls
packages from `site-packages`.
Parameters
----------
pluginInfo : psychopy.app.plugin_manager.plugins.PluginInfo
Info object of the plugin to uninstall.
"""
# do uninstall
self.uninstallPackage(pluginInfo.pipname)
def onInstallExit(self, pid, exitCode):
"""
Callback function to handle a pip process exiting. Prints a termination statement
to the output panel then, if installing a plugin, provides helpful info about that
plugin.
"""
if self.pipProcess is None:
# if pip process is None, this has been called by mistake, do nothing
return
# write installation termination statement
msg = "Installation complete"
if 'pipname' in self.pipProcess.extra:
msg = "Finished installing %(pipname)s" % self.pipProcess.extra
self.output.writeTerminus(msg)
# if we have a plugin, write additional plugin information post-install
if 'pluginInfo' in self.pipProcess.extra:
# get plugin info object
pluginInfo = self.pipProcess.extra['pluginInfo']
# scan plugins
plugins.scanPlugins()
# enable plugin
try:
pluginInfo.activate()
# plugins.loadPlugin(pluginInfo.pipname)
except RuntimeError:
prefs.general['startUpPlugins'].append(pluginInfo.pipname)
self.output.writeStdErr(_translate(
"[Warning] Could not activate plugin. PsychoPy may need to restart for plugin to take effect."
))
global NEEDS_RESTART # flag as needing a restart
NEEDS_RESTART = True
showNeedsRestartDialog()
# show list of components/routines now available
emts = []
for name, emt in getAllElements().items():
if hasattr(emt, "plugin") and emt.plugin == pluginInfo.pipname:
cats = ", ".join(emt.categories)
emts.append(f"{name} ({cats})")
if len(emts):
msg = _translate(
"The following components/routines should now be visible in the Components panel (a restart may be "
"required in some cases):\n"
)
for emt in emts:
msg += (
f" - {emt}\n"
)
self.output.write(msg)
# show info link
if pluginInfo.docs:
msg = _translate(
"For more information about the %s plugin, read the documentation at:"
) % pluginInfo.name
self.output.writeStdOut(msg)
self.output.writeLink(pluginInfo.docs, link=pluginInfo.docs)
# clear pip process
self.pipProcess = None
# refresh view
pkgtools.refreshPackages()
self.pluginMgr.updateInfo()
def onUninstallExit(self, pid, exitCode):
# write installation termination statement
msg = "Uninstall complete"
if 'pipname' in self.pipProcess.extra:
msg = "Finished uninstalling %(pipname)s" % self.pipProcess.extra
self.output.writeTerminus(msg)
# clear pip process
self.pipProcess = None
def onClose(self, evt=None):
if self.isBusy:
# if closing during an install, prompt user to reconsider
dlg = wx.MessageDialog(
self,
_translate(
"There is currently an installation/uninstallation in progress, are you sure "
"you want to close?"
),
style=wx.YES | wx.NO
)
# if they change their mind, cancel closing
if dlg.ShowModal() == wx.ID_NO:
return
if evt is not None:
evt.Skip()
def showNeedsRestartDialog():
"""Show a dialog asking the user if they would like to restart PsychoPy.
"""
msg = _translate("Please restart PsychoPy to apply changes.")
# show a simple dialog that asks the user to restart PsychoPy
dlg = wx.MessageDialog(
None, msg, "Restart Required",
style=wx.ICON_INFORMATION | wx.OK
)
dlg.ShowModal()
| 14,283
|
Python
|
.py
| 336
| 31.410714
| 120
| 0.600187
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,840
|
plugins.py
|
psychopy_psychopy/psychopy/app/plugin_manager/plugins.py
|
from pathlib import Path
from packaging.version import Version
import shutil
import wx
from wx.lib import scrolledpanel
import webbrowser
from PIL import Image as pil
from psychopy.tools import pkgtools
from psychopy.app.themes import theme, handlers, colors, icons
from psychopy.tools import stringtools as st
from psychopy.tools.versionchooser import VersionRange
from psychopy.app import utils
from psychopy.localization import _translate
from psychopy import plugins, __version__
from psychopy.preferences import prefs
import requests
import os.path
import errno
import sys
import json
import glob
class AuthorInfo:
"""Plugin author information.
Parameters
----------
name : str
Author name.
email : str
Author email URL.
github : str
GitHub repo URL (optional).
avatar : str
Avatar image file or URL.
"""
def __init__(self,
name="",
email="",
github="",
avatar=None,
**kwargs):
self.name = name
self.email = email
self.github = github
self.avatar = avatar
def __eq__(self, other):
if other == "ost":
# If author is us, check against our github
return self.github == "psychopy"
else:
# Otherwise check against string attributes
return other in (self.name, self.email, self.github)
@property
def avatar(self):
if hasattr(self, "_avatar"):
return self._avatar
@avatar.setter
def avatar(self, value):
self._requestedAvatar = value
self._avatar = utils.ImageData(value)
def __repr__(self):
return (f"<psychopy.app.plugins.AuthorInfo: "
f"{self.name} (@{self.github}, {self.email})>")
class PluginInfo:
"""Minimal class to store info about a plugin.
Parameters
----------
pipname : str
Name of plugin on pip, e.g. "psychopy-legacy".
name : str
Plugin name for display, e.g. "Psychopy Legacy".
icon : wx.Bitmap, path or None
Icon for the plugin, if any (if None, will use blank bitmap).
description : str
Description of the plugin.
installed : bool or None
Whether or not the plugin in installed on this system.
active : bool
Whether or not the plug is enabled on this system (if not installed,
will always be False).
"""
def __init__(self,
pipname, name="",
author=None, homepage="", docs="", repo="",
keywords=None, version=(None, None),
icon=None, description="", **kwargs):
self.pipname = pipname
self.name = name
self.author = author
self.homepage = homepage
self.docs = docs
self.repo = repo
self.icon = icon
self.description = description
self.keywords = keywords or []
self.version = VersionRange(*version)
self.parent = None # set after
# icon graphic
self._icon = None
def __repr__(self):
return (f"<psychopy.plugins.PluginInfo: {self.name} "
f"[{self.pipname}] by {self.author}>")
def __eq__(self, other):
if isinstance(other, PluginInfo):
return self.pipname == other.pipname
else:
return self.pipname == str(other)
def setParent(self, parent):
"""Set the parent window or panel.
Need a parent to invoke methods on the top-level window. Might not
be set.
Parameters
----------
parent : wx.Window or wx.Panel
Parent window or panel.
"""
self.parent = parent
@property
def icon(self):
# check if the directory for the plugin cache exists, create it otherwise
appPluginCacheDir = os.path.join(
prefs.paths['userCacheDir'], 'appCache', 'plugins')
try:
os.makedirs(appPluginCacheDir, exist_ok=True)
except OSError as err:
if err.errno != errno.EEXIST:
raise
if isinstance(self._requestedIcon, str):
if st.is_url(self._requestedIcon):
# get the file name from the URL in the JSON
fname = str(self._requestedIcon).split("/")
if len(fname) > 1:
fname = fname[-1]
else:
pass # not a valid URL, use broken image icon
# check if the icon is already in the cache, use it if so
if fname in os.listdir(appPluginCacheDir):
self._icon = utils.ImageData(os.path.join(
appPluginCacheDir, fname))
return self._icon
# if not, download it
if st.is_url(self._requestedIcon):
# download to cache directory
ext = "." + str(self._requestedIcon).split(".")[-1]
if ext in pil.registered_extensions():
content = requests.get(self._requestedIcon).content
writeOut = os.path.join(appPluginCacheDir, fname)
with open(writeOut, 'wb') as f:
f.write(content)
self._icon = utils.ImageData(os.path.join(
appPluginCacheDir, fname))
elif st.is_file(self._requestedIcon):
self._icon = utils.ImageData(self._requestedIcon)
else:
raise ValueError("Invalid icon URL or file path.")
return self._icon
# icon already loaded into memory, just return that
if hasattr(self, "_icon"):
return self._icon
@icon.setter
def icon(self, value):
self._requestedIcon = value
@property
def active(self):
"""
Is this plugin active? If so, it is loaded when the app starts.
Otherwise, it remains installed but is not loaded.
"""
return plugins.isStartUpPlugin(self.pipname)
def activate(self, evt=None):
# If active, add to list of startup plugins
plugins.startUpPlugins(self.pipname, add=True, verify=False)
def deactivate(self, evt=None):
# Remove from list of startup plugins
current = plugins.listPlugins(which='startup')
if self.pipname in current:
current.remove(self.pipname)
plugins.startUpPlugins(current, add=False, verify=False)
def install(self, forceReinstall=False):
if self.parent is None:
return
wx.CallAfter(
self.parent.GetTopLevelParent().installPlugin, self, forceReinstall=forceReinstall)
def uninstall(self):
if self.parent is None:
return
wx.CallAfter(
self.parent.GetTopLevelParent().uninstallPlugin, self)
@property
def installed(self):
return pkgtools.isInstalled(self.pipname)
@property
def installedVersion(self):
"""
Returns
-------
Version or None
The version of this plugin which is installed, or None if it is not installed.
"""
if self.installed:
try:
ver = plugins.pluginMetadata(self.pipname)["Version"]
return Version(ver)
except:
return None
else:
return None
@property
def author(self):
if hasattr(self, "_author"):
return self._author
@author.setter
def author(self, value):
if isinstance(value, AuthorInfo):
# If given an AuthorInfo, use it directly
self._author = value
elif isinstance(value, dict):
# If given a dict, make an AuthorInfo from it
self._author = AuthorInfo(**value)
else:
# Otherwise, assume no author
self._author = AuthorInfo()
def getReleases(self):
"""
Get known versions of this plugin.
Returns
-------
list[str]
List of version strings
"""
# get package info
info = pkgtools.getPypiInfo(self.pipname, silence=True)
# convert all release numbers to Version objects
releases = []
for release in info.get('releases', []):
try:
ver = Version(release)
releases.append(ver)
except:
continue
return releases
class PluginManagerPanel(wx.Panel, handlers.ThemeMixin):
def __init__(self, parent, dlg):
wx.Panel.__init__(self, parent, style=wx.NO_BORDER)
self.dlg = dlg
# Setup sizer
self.border = wx.BoxSizer(wx.VERTICAL)
self.SetSizer(self.border)
self.sizer = wx.BoxSizer(wx.HORIZONTAL)
self.border.Add(self.sizer, proportion=1, border=6, flag=wx.ALL | wx.EXPAND)
# Make splitter
self.splitter = wx.SplitterWindow(self, style=wx.NO_BORDER)
self.sizer.Add(self.splitter, proportion=1, border=0, flag=wx.EXPAND | wx.ALL)
# Make list
self.pluginList = PluginBrowserList(self.splitter, stream=dlg.output)
# Make viewer
self.pluginViewer = PluginDetailsPanel(self.splitter, stream=self.dlg.output)
# Cross-reference viewer & list
self.pluginViewer.list = self.pluginList
self.pluginList.viewer = self.pluginViewer
# Assign to splitter
self.splitter.SplitVertically(
window1=self.pluginList,
window2=self.pluginViewer,
sashPosition=0
)
self.splitter.SetMinimumPaneSize(450)
# Start of with nothing selected
self.pluginList.onDeselect()
self.Layout()
self.splitter.SetSashPosition(1, True)
self.theme = theme.app
def updateInfo(self):
# refresh all list items
self.pluginList.updateInfo()
# set current plugin again to refresh view
self.pluginViewer.info = self.pluginViewer.info
def _applyAppTheme(self):
# Set colors
self.SetBackgroundColour("white")
# Manually style children as Splitter interfered with inheritance
self.pluginList.theme = self.theme
self.pluginViewer.theme = self.theme
class PluginBrowserList(scrolledpanel.ScrolledPanel, handlers.ThemeMixin):
class PluginListItem(wx.Window, handlers.ThemeMixin):
"""
Individual item pointing to a plugin
"""
def __init__(self, parent, info):
wx.Window.__init__(self, parent=parent, style=wx.SIMPLE_BORDER)
self.SetMaxSize((400, -1))
self.parent = parent
# Link info object
self.info = info
# Setup sizer
self.border = wx.BoxSizer(wx.VERTICAL)
self.SetSizer(self.border)
self.sizer = wx.BoxSizer(wx.HORIZONTAL)
self.border.Add(self.sizer, proportion=1, border=6, flag=wx.ALL | wx.EXPAND)
# Add label
self.label = wx.BoxSizer(wx.VERTICAL)
self.nameLbl = wx.StaticText(self, label=info.name)
self.label.Add(self.nameLbl, flag=wx.ALIGN_LEFT)
self.pipNameLbl = wx.StaticText(self, label=info.pipname)
self.label.Add(self.pipNameLbl, flag=wx.ALIGN_LEFT)
self.sizer.Add(self.label, proportion=1, border=3, flag=wx.ALL | wx.EXPAND)
# Button sizer
self.btnSizer = wx.BoxSizer(wx.VERTICAL)
self.sizer.Add(self.btnSizer, border=3, flag=wx.ALL | wx.ALIGN_BOTTOM)
self.btnSizer.AddStretchSpacer(1)
# # Add active button
# self.activeBtn = wx.Button(self)
# self.activeBtn.Bind(wx.EVT_BUTTON, self.onToggleActivate)
# self.btnSizer.Add(self.activeBtn, border=3, flag=wx.ALL | wx.ALIGN_RIGHT)
# Add install button
self.installBtn = wx.Button(self, label=_translate("Install"))
self.installBtn.SetBitmap(
icons.ButtonIcon("download", 16).bitmap
)
self.installBtn.SetBitmapMargins(6, 3)
self.installBtn.Bind(wx.EVT_BUTTON, self.onInstall)
self.btnSizer.Add(self.installBtn, border=3, flag=wx.ALL | wx.ALIGN_RIGHT)
# # add uninstall button
# self.uninstallBtn = wx.Button(self, label=_translate("Uninstall"))
# self.uninstallBtn.SetBitmap(
# icons.ButtonIcon("delete", 16).bitmap
# )
# self.uninstallBtn.SetBitmapMargins(6, 3)
# self.uninstallBtn.Bind(wx.EVT_BUTTON, self.onUninstall)
# self.btnSizer.Add(self.uninstallBtn, border=3, flag=wx.ALL | wx.EXPAND)
# Map to onclick function
self.Bind(wx.EVT_LEFT_DOWN, self.onSelect)
self.nameLbl.Bind(wx.EVT_LEFT_DOWN, self.onSelect)
self.pipNameLbl.Bind(wx.EVT_LEFT_DOWN, self.onSelect)
# Bind navigation
self.Bind(wx.EVT_NAVIGATION_KEY, self.onNavigation)
self._applyAppTheme()
self.markInstalled(self.info.installed)
@property
def viewer(self):
"""
Return parent's linked viewer when asked for viewer
"""
return self.parent.viewer
def updateInfo(self):
# update install state
self.markInstalled(self.info.installed)
def _applyAppTheme(self):
# Set label fonts
from psychopy.app.themes import fonts
self.nameLbl.SetFont(fonts.appTheme['h6'].obj)
self.pipNameLbl.SetFont(fonts.coderTheme.base.obj)
# Mark installed/active
self.markInstalled(self.info.installed)
#self.markActive(self.info.active)
def onNavigation(self, evt=None):
"""
Use the tab key to progress to the next panel, or the arrow keys to
change selection in this panel.
This is the same functionality as in a wx.ListCtrl
"""
# Some shorthands for prev, next and whether each have focus
prev = self.GetPrevSibling()
prevFocus = False
if hasattr(prev, "HasFocus"):
prevFocus = prev.HasFocus()
next = self.GetNextSibling()
nextFocus = False
if hasattr(next, "HasFocus"):
nextFocus = next.HasFocus()
if evt.GetDirection() and prevFocus:
# If moving forwards from previous sibling, target is self
target = self
elif evt.GetDirection() and self.HasFocus():
# If moving forwards from self, target is next sibling
target = next
elif evt.GetDirection():
# If we're moving forwards from anything else, this event shouldn't have happened. Just deselect.
target = None
elif not evt.GetDirection() and nextFocus:
# If moving backwards from next sibling, target is self
target = self
elif not evt.GetDirection() and self.HasFocus():
# If moving backwards from self, target is prev sibling
target = prev
else:
# If we're moving backwards from anything else, this event shouldn't have happened. Just deselect.
target = None
# If target is self or another PluginListItem, select it
if target in self.parent.items:
self.parent.setSelection(target)
target.SetFocus()
else:
self.parent.setSelection(None)
# Do usual behaviour
evt.Skip()
def onSelect(self, evt=None):
self.parent.setSelection(self)
def markInstalled(self, installed=True):
"""
Shorthand to call markInstalled with self and corresponding item
Parameters
----------
installed : bool or None
True if installed, False if not installed, None if pending/unclear
"""
markInstalled(
pluginItem=self,
pluginPanel=self.parent.viewer,
installed=installed
)
def markActive(self, active=True):
"""
Shorthand to call markActive with self and corresponding item
Parameters
----------
active : bool or None
True if active, False if not active, None if pending/unclear
"""
markActive(
pluginItem=self,
pluginPanel=self.parent.viewer,
active=active
)
def _doInstall(self):
"""Routine to run the installation of a package after the `onInstall`
event is processed.
"""
# mark as pending
self.markInstalled(None)
# install
self.info.install()
# mark according to install success
self.markInstalled(self.info.installed)
def _doUninstall(self):
# mark as pending
self.markInstalled(None)
# uninstall
self.info.uninstall()
# mark according to uninstall success
self.markInstalled(self.info.installed)
def onInstall(self, evt=None):
"""Event called when the install button is clicked.
"""
wx.CallAfter(self._doInstall) # call after processing button events
if evt is not None and hasattr(evt, 'Skip'):
evt.Skip()
def onUninstall(self, evt=None):
"""
Event called when the uninstall button is clicked.
"""
wx.CallAfter(self._doUninstall) # call after processing button events
if evt is not None and hasattr(evt, 'Skip'):
evt.Skip()
def onToggleActivate(self, evt=None):
if self.info.active:
self.onDeactivate(evt=evt)
else:
self.onActivate(evt=evt)
def onActivate(self, evt=None):
# Mark as pending
self.markActive(None)
# Do activation
self.info.activate()
# Mark according to success
self.markActive(self.info.active)
def onDeactivate(self, evt=None):
# Mark as pending
self.markActive(None)
# Do deactivation
self.info.deactivate()
# Mark according to success
self.markActive(self.info.active)
def __init__(self, parent, stream, viewer=None):
scrolledpanel.ScrolledPanel.__init__(self, parent=parent, style=wx.VSCROLL)
self.parent = parent
self.viewer = viewer
self.stream = stream
# Setup sizer
self.border = wx.BoxSizer(wx.VERTICAL)
self.SetSizer(self.border)
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.border.Add(self.sizer, proportion=1, border=6, flag=wx.ALL | wx.EXPAND)
# Add search box
self.searchCtrl = wx.SearchCtrl(self)
self.sizer.Add(self.searchCtrl, border=9, flag=wx.ALL | wx.EXPAND)
self.searchCtrl.Bind(wx.EVT_SEARCH, self.search)
# Setup items sizers & labels
self.itemSizer = wx.BoxSizer(wx.VERTICAL)
self.sizer.Add(self.itemSizer, proportion=1, border=3, flag=wx.ALL | wx.EXPAND)
self.badItemLbl = wx.StaticText(self, label=_translate("Not for PsychoPy {}:").format(__version__))
self.sizer.Add(self.badItemLbl, border=9, flag=wx.ALL | wx.EXPAND)
self.badItemSizer = wx.BoxSizer(wx.VERTICAL)
self.sizer.Add(self.badItemSizer, border=3, flag=wx.ALL | wx.EXPAND)
# ctrl to display when plugins can't be retrieved
self.errorCtrl = utils.MarkdownCtrl(
self, value=_translate(
"Could not retrieve plugins. Try restarting the PsychoPy app and make sure you "
"are connected to the internet."
),
style=wx.TE_READONLY
)
self.sizer.Add(self.errorCtrl, proportion=1, border=3, flag=wx.ALL | wx.EXPAND)
self.errorCtrl.Hide()
# add button to uninstall all
self.uninstallAllBtn = wx.Button(self, label=_translate("Uninstall all plugins"))
self.uninstallAllBtn.SetBitmap(
icons.ButtonIcon("delete", 16).bitmap
)
self.uninstallAllBtn.SetBitmapMargins(6, 3)
self.uninstallAllBtn.Bind(wx.EVT_BUTTON, self.onUninstallAll)
self.sizer.Add(self.uninstallAllBtn, border=12, flag=wx.ALL | wx.CENTER)
# Bind deselect
self.Bind(wx.EVT_LEFT_DOWN, self.onDeselect)
# Setup items
self.items = []
self.populate()
# Store state of plugins on init so we can detect changes later
self.initState = {}
for item in self.items:
self.initState[item.info.pipname] = {"installed": item.info.installed, "active": item.info.active}
def populate(self):
# get all plugin details
items = getAllPluginDetails()
# start off assuming no headings
self.badItemLbl.Hide()
# put installed packages at top of list
items.sort(key=lambda obj: obj.installed, reverse=True)
for item in items:
item.setParent(self)
self.appendItem(item)
# if we got no items, display error message
if not len(items):
self.errorCtrl.Show()
# layout
self.Layout()
self.SetupScrolling()
def updateInfo(self):
for item in self.items:
item.updateInfo()
def search(self, evt=None):
searchTerm = self.searchCtrl.GetValue().strip()
for item in self.items:
# Otherwise show/hide according to search
match = any((
searchTerm == "", # If search is blank, show all
searchTerm.lower() in item.info.name.lower(),
searchTerm.lower() in item.info.pipname.lower(),
searchTerm.lower() in [val.lower() for val in item.info.keywords],
searchTerm.lower() in item.info.author.name.lower(),
))
item.Show(match)
self.Layout()
def getChanges(self):
"""
Check what plugins have changed state (installed, active) since this dialog was opened
"""
changes = {}
for item in self.items:
info = item.info
# Skip if its init state wasn't stored
if info.pipname not in self.initState:
continue
# Get inits
inits = self.initState[info.pipname]
itemChanges = []
# Has it been activated?
if info.active and not inits['active']:
itemChanges.append("activated")
# Has it been deactivated?
if inits['active'] and not info.active:
itemChanges.append("deactivated")
# Has it been installed?
if info.installed and not inits['installed']:
itemChanges.append("installed")
# Has it been uninstalled?
if inits['installed'] and not info.installed:
itemChanges.append("uninstalled")
# Add changes if there are any
if itemChanges:
changes[info.pipname] = itemChanges
return changes
def onClick(self, evt=None):
self.SetFocusIgnoringChildren()
self.viewer.info = None
def onUninstallAll(self, evt=None):
"""
Called when the "Uninstall all" button is clicked
"""
# warn user that they'll delete the packages folder
dlg = wx.MessageDialog(
self,
message=_translate("This will uninstall all plugins an additional packages you have installed, are you sure you want to continue?"),
style=wx.ICON_WARNING | wx.YES | wx.NO
)
if dlg.ShowModal() != wx.ID_YES:
# cancel if they didn't explicitly say yes
return
# delete the packages folder
shutil.rmtree(prefs.paths['packages'])
# print success
dlg = wx.MessageDialog(
self,
message=_translate("All plugins and additional packages have been uninstalled. You will need to restart PsychoPy for this to take effect."),
style=wx.ICON_INFORMATION | wx.OK
)
dlg.ShowModal()
# close dialog
self.GetTopLevelParent().Close()
def setSelection(self, item):
"""
Set the current selection as either None or the handle of a PluginListItem
"""
if item is None:
# If None, set to no selection
self.selected = None
self.viewer.info = None
elif isinstance(item, self.PluginListItem):
# If given a valid item, select it
self.selected = item
self.viewer.info = item.info
# Style all items
for obj in self.items:
if obj == self.selected:
# Selected colors
bg = colors.app.light['panel_bg']
else:
# Deselected colors
bg = colors.app.light['tab_bg']
# Set color
obj.SetBackgroundColour(bg)
# Restyle item
obj._applyAppTheme()
# Refresh
obj.Update()
obj.Refresh()
# Post CHOICE event
evt = wx.CommandEvent(wx.EVT_CHOICE.typeId)
evt.SetEventObject(self)
evt.SetClientData(item)
wx.PostEvent(self, evt)
def onDeselect(self, evt=None):
"""
If panel itself (not any children) are clicked on, set selection to None
"""
self.setSelection(None)
def _applyAppTheme(self):
# Set colors
self.SetBackgroundColour("white")
# Style heading(s)
from psychopy.app.themes import fonts
self.badItemLbl.SetFont(fonts.appTheme['h6'].obj)
def appendItem(self, info):
item = self.PluginListItem(self, info)
self.items.append(item)
if __version__ in item.info.version:
self.itemSizer.Add(item, border=6, flag=wx.ALL | wx.EXPAND)
else:
self.badItemSizer.Add(item, border=6, flag=wx.ALL | wx.EXPAND)
self.badItemLbl.Show()
def getItem(self, info):
"""
Get the PluginListItem object associated with a PluginInfo object
"""
for item in self.items:
if item.info == info:
return item
class PluginDetailsPanel(wx.Panel, handlers.ThemeMixin):
iconSize = (128, 128)
def __init__(self, parent, stream, info=None, list=None):
wx.Panel.__init__(self, parent)
self.SetMinSize((480, 620))
self.parent = parent
self.list = list
self.stream = stream
# Setup sizers
self.border = wx.BoxSizer(wx.VERTICAL)
self.SetSizer(self.border)
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.border.Add(self.sizer, proportion=1, border=6, flag=wx.ALL | wx.EXPAND)
self.headSizer = wx.BoxSizer(wx.HORIZONTAL)
self.sizer.Add(self.headSizer, flag=wx.EXPAND)
# Icon ctrl
self.icon = wx.StaticBitmap(self, bitmap=wx.Bitmap(), size=self.iconSize, style=wx.SIMPLE_BORDER)
self.headSizer.Add(self.icon, border=6, flag=wx.ALL | wx.EXPAND)
# Title
self.titleSizer = wx.BoxSizer(wx.VERTICAL)
self.headSizer.Add(self.titleSizer, proportion=1, border=6, flag=wx.ALL | wx.EXPAND)
self.title = wx.StaticText(self, label="...")
self.titleSizer.Add(self.title, flag=wx.EXPAND)
# Pip name
self.pipName = wx.StaticText(self, label="psychopy-...")
self.titleSizer.Add(self.pipName, flag=wx.EXPAND)
# Space
self.titleSizer.AddStretchSpacer()
# Versions
self.versionCtrl = wx.StaticText(self, label=_translate("Version:"))
self.titleSizer.Add(self.versionCtrl, border=6, flag=wx.TOP | wx.LEFT | wx.RIGHT | wx.EXPAND)
# Buttons
self.buttonSizer = wx.BoxSizer(wx.HORIZONTAL)
self.titleSizer.Add(self.buttonSizer, flag=wx.EXPAND)
# install btn
self.installBtn = wx.Button(self, label=_translate("Install"))
self.installBtn.SetBitmap(
icons.ButtonIcon("download", 16).bitmap
)
self.installBtn.SetBitmapMargins(6, 3)
self.installBtn.Bind(wx.EVT_BUTTON, self.onInstall)
self.buttonSizer.Add(self.installBtn, border=3, flag=wx.ALL | wx.EXPAND)
# update btn
self.updateBtn = wx.Button(self, label=_translate("Update"))
self.updateBtn.SetBitmap(
icons.ButtonIcon("plus", 16).bitmap
)
self.updateBtn.Bind(wx.EVT_BUTTON, self.onUpdate)
self.buttonSizer.Add(self.updateBtn, border=3, flag=wx.ALL | wx.EXPAND)
# uninstall btn
self.uninstallBtn = wx.Button(self, label=_translate("Uninstall"))
self.uninstallBtn.SetBitmap(
icons.ButtonIcon("delete", 16).bitmap
)
self.uninstallBtn.SetBitmapMargins(6, 3)
self.uninstallBtn.Bind(wx.EVT_BUTTON, self.onUninstall)
self.buttonSizer.Add(self.uninstallBtn, border=3, flag=wx.ALL | wx.EXPAND)
# Homepage btn
self.homepageBtn = wx.Button(self, label=_translate("Homepage"))
self.homepageBtn.Bind(wx.EVT_BUTTON, self.onHomepage)
self.buttonSizer.Add(self.homepageBtn, border=3, flag=wx.ALL | wx.EXPAND)
# Description
self.description = utils.MarkdownCtrl(
self, value="",
style=wx.TE_READONLY | wx.TE_MULTILINE | wx.BORDER_NONE | wx.TE_NO_VSCROLL
)
self.sizer.Add(self.description, border=0, proportion=1, flag=wx.ALL | wx.EXPAND)
# Keywords
self.keywordsLbl = wx.StaticText(self, label=_translate("Keywords:"))
self.sizer.Add(self.keywordsLbl, border=12, flag=wx.TOP | wx.LEFT | wx.RIGHT | wx.EXPAND)
self.keywordsCtrl = utils.ButtonArray(
self,
orient=wx.HORIZONTAL,
itemAlias=_translate("keyword"),
readonly=True
)
self.keywordsCtrl.Bind(wx.EVT_BUTTON, self.onKeyword)
self.sizer.Add(self.keywordsCtrl, border=6, flag=wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.EXPAND)
self.sizer.Add(wx.StaticLine(self), border=6, flag=wx.EXPAND | wx.ALL)
# Add author panel
self.author = AuthorDetailsPanel(self, info=None)
self.sizer.Add(self.author, border=6, flag=wx.EXPAND | wx.ALL)
# Add placeholder for when there's no plugin selected
self.placeholder = utils.MarkdownCtrl(
self, value=_translate("Select a plugin to view details."),
style=wx.TE_READONLY
)
self.border.Add(
self.placeholder,
proportion=1,
border=12,
flag=wx.ALL | wx.EXPAND)
# Set info and installed status
self.info = info
self.markInstalled(self.info.installed)
#self.markActive(self.info.active)
# Style
self.Layout()
self._applyAppTheme()
def _applyAppTheme(self):
# Set background
self.SetBackgroundColour("white")
self.keywordsCtrl.SetBackgroundColour("white")
self.versionCtrl.SetForegroundColour("grey")
# Set fonts
from psychopy.app.themes import fonts
self.title.SetFont(fonts.appTheme['h1'].obj)
self.pipName.SetFont(fonts.coderTheme.base.obj)
def markInstalled(self, installed=True):
"""
Shorthand to call markInstalled with self and corresponding item
Parameters
----------
installed : bool or None
True if installed, False if not installed, None if pending/unclear
"""
if self.list:
item = self.list.getItem(self.info)
else:
item = None
markInstalled(
pluginItem=item,
pluginPanel=self,
installed=installed
)
def markActive(self, active=True):
"""
Shorthand to call markActive with self and corresponding item
Parameters
----------
active : bool or None
True if active, False if not active, None if pending/unclear
"""
if self.list:
item = self.list.getItem(self.info)
else:
item = None
markActive(
pluginItem=item,
pluginPanel=self,
active=active
)
def _doInstall(self, forceReinstall=None):
"""Routine to run the installation of a package after the `onInstall`
event is processed.
"""
# mark as pending
self.markInstalled(None)
# install
self.info.install(forceReinstall=forceReinstall)
# mark according to install success
self.markInstalled(self.info.installed)
def _doUninstall(self):
# mark as pending
self.markInstalled(None)
# uninstall
self.info.uninstall()
# mark according to uninstall success
self.markInstalled(self.info.installed)
def onInstall(self, evt=None):
"""Event called when the install button is clicked.
"""
wx.CallAfter(self._doInstall) # call after processing button events
if evt is not None and hasattr(evt, 'Skip'):
evt.Skip()
def onUpdate(self, evt=None):
wx.CallAfter(self._doInstall, forceReinstall=True) # call after processing button events
if evt is not None and hasattr(evt, 'Skip'):
evt.Skip()
def onUninstall(self, evt=None):
"""
Event called when the uninstall button is clicked.
"""
wx.CallAfter(self._doUninstall) # call after processing button events
if evt is not None and hasattr(evt, 'Skip'):
evt.Skip()
def _doActivate(self, state=True):
"""Activate a plugin or package after the `onActivate` event.
Parameters
----------
state : bool
Active state to set, True for active or False for inactive. Default
is `True`.
"""
# Mark as pending
self.markActive(None)
if state: # handle activation
self.info.activate()
else:
self.info.deactivate()
# Mark according to success
self.markActive(self.info.active)
def onToggleActivate(self, evt=None):
if self.info.active:
self.onDeactivate(evt=evt)
else:
self.onActivate(evt=evt)
def onActivate(self, evt=None):
wx.CallAfter(self._doActivate, True) # call after processing button events
if evt is not None and hasattr(evt, 'Skip'):
evt.Skip()
def onDeactivate(self, evt=None):
wx.CallAfter(self._doActivate, False)
if evt is not None and hasattr(evt, 'Skip'):
evt.Skip()
def onKeyword(self, evt=None):
kw = evt.GetString()
if kw:
# If we have a keyword, use it in a search
self.list.searchCtrl.SetValue(kw)
self.list.search()
def onHomepage(self, evt=None):
if self.info.homepage:
webbrowser.open(self.info.homepage)
@property
def info(self):
"""
Information about this plugin
"""
return self._info
@info.setter
def info(self, value):
# Hide/show everything according to None
self.sizer.ShowItems(value is not None)
# Show/hide placeholder according to None
self.placeholder.Show(value is None)
# Handle None
if value is None:
value = PluginInfo(
"psychopy-...",
name="..."
)
self._info = value
# Set icon
icon = value.icon
if icon is None:
icon = wx.Bitmap()
if isinstance(icon, pil.Image):
# Resize to fit ctrl
icon = icon.resize(size=self.iconSize)
# Supply an alpha channel
alpha = icon.tobytes("raw", "A")
icon = wx.Bitmap.FromBufferAndAlpha(
width=icon.size[0],
height=icon.size[1],
data=icon.tobytes("raw", "RGB"),
alpha=alpha
)
if not isinstance(icon, wx.Bitmap):
icon = wx.Bitmap(icon)
self.icon.SetBitmap(icon)
# Set names
self.title.SetLabelText(value.name)
self.pipName.SetLabelText(value.pipname)
# Set installed
self.markInstalled(value.installed)
# show/hide update button
releases = self.info.getReleases()
if releases:
self.updateBtn.Show(
self.info.installed and self.info.installedVersion < max(releases)
)
# Enable/disable homepage
self.homepageBtn.Enable(bool(self.info.homepage))
# Set activated
# self.markActive(value.active)
# Set description
self.description.setValue(value.description)
# Set version text
self.versionCtrl.SetLabelText(_translate(
"Works with versions {}."
).format(value.version))
self.versionCtrl.Show(
value.version.first is not None or value.version.last is not None
)
# Set keywords
self.keywordsCtrl.items = value.keywords
# Set author info
self.author.info = value.author
# Handle version mismatch
self.installBtn.Enable(__version__ in self.info.version)
self.Layout()
class AuthorDetailsPanel(wx.Panel, handlers.ThemeMixin):
avatarSize = (64, 64)
def __init__(self, parent, info):
wx.Panel.__init__(self, parent)
# Setup sizers
self.border = wx.BoxSizer(wx.VERTICAL)
self.SetSizer(self.border)
self.sizer = wx.BoxSizer(wx.HORIZONTAL)
self.border.Add(self.sizer, proportion=1, border=6, flag=wx.ALL | wx.EXPAND)
# Details sizer
self.detailsSizer = wx.BoxSizer(wx.VERTICAL)
self.sizer.Add(self.detailsSizer, proportion=1, border=6, flag=wx.LEFT | wx.EXPAND)
# Name
self.name = wx.StaticText(self)
self.detailsSizer.Add(self.name, border=6, flag=wx.ALIGN_RIGHT | wx.ALL)
# Button sizer
self.buttonSizer = wx.BoxSizer(wx.HORIZONTAL)
self.detailsSizer.Add(self.buttonSizer, border=3, flag=wx.ALIGN_RIGHT | wx.ALL)
# # Email button
# self.emailBtn = wx.Button(self, style=wx.BU_EXACTFIT)
# self.emailBtn.SetToolTip(_translate("Email author"))
# self.emailBtn.Bind(wx.EVT_BUTTON, self.onEmailBtn)
# self.buttonSizer.Add(self.emailBtn, border=3, flag=wx.EXPAND | wx.ALL)
# GitHub button
self.githubBtn = wx.Button(self, style=wx.BU_EXACTFIT)
self.githubBtn.SetToolTip(_translate("Author's GitHub"))
self.githubBtn.Bind(wx.EVT_BUTTON, self.onGithubBtn)
self.buttonSizer.Add(self.githubBtn, border=3, flag=wx.EXPAND | wx.ALL)
# Avatar
self.avatar = wx.StaticBitmap(self, bitmap=wx.Bitmap(), size=self.avatarSize, style=wx.BORDER_NONE)
self.sizer.Add(self.avatar, border=6, flag=wx.ALL | wx.EXPAND)
# Set initial info
if info is not None:
self.info = info
self.Layout()
self._applyAppTheme()
def _applyAppTheme(self):
# Name font
from psychopy.app.themes import fonts
self.name.SetFont(fonts.appTheme['h4'].obj)
# # Email button bitmap
# self.emailBtn.SetBitmap(icons.ButtonIcon("email", 16).bitmap)
# self.emailBtn.SetBitmapDisabled(icons.ButtonIcon("email", 16).bitmap)
# Github button bitmap
self.githubBtn.SetBitmap(icons.ButtonIcon("github", 16).bitmap)
self.githubBtn.SetBitmapDisabled(icons.ButtonIcon("github", 16).bitmap)
@property
def info(self):
if hasattr(self, "_info"):
return self._info
@info.setter
def info(self, value):
# Alias None
if value is None:
value = AuthorInfo(
name="..."
)
# Store value
self._info = value
# Update avatar
icon = value.avatar
if icon is None:
icon = wx.Bitmap()
if isinstance(icon, pil.Image):
# Resize to fit ctrl
icon = icon.resize(size=self.avatarSize)
# Supply an alpha channel
alpha = icon.tobytes("raw", "A")
icon = wx.Bitmap.FromBufferAndAlpha(
width=icon.size[0],
height=icon.size[1],
data=icon.tobytes("raw", "RGB"),
alpha=alpha
)
if not isinstance(icon, wx.Bitmap):
icon = wx.Bitmap(icon)
self.avatar.SetBitmap(icon)
# Update name
self.name.SetLabelText(value.name)
# Add tooltip for OST
if value == "ost":
self.name.SetToolTip(_translate(
"That's us! We make PsychoPy and Pavlovia!"
))
else:
self.name.SetToolTip("")
# Show/hide buttons
# self.emailBtn.Show(bool(value.email))
self.githubBtn.Show(bool(value.github))
def onEmailBtn(self, evt=None):
webbrowser.open(f"mailto:{self.info.email}")
def onGithubBtn(self, evt=None):
webbrowser.open(f"github.com/{self.info.github}")
def markInstalled(pluginItem, pluginPanel, installed=True):
"""
Setup installed button according to install state
Parameters
----------
pluginItem : PluginBrowserList.PluginListItem
Plugin list item associated with this plugin
pluginPanel : PluginDetailsPanel
Plugin viewer panel to update
installed : bool or None
True if installed, False if not installed, None if pending/unclear
"""
# update plugin item
if pluginItem:
if installed is None:
# if pending, hide both buttons
pluginItem.installBtn.Hide()
elif installed:
# if installed, hide install button
pluginItem.installBtn.Hide()
else:
# if not installed, show "Install" and download icon
pluginItem.installBtn.Show()
# refresh buttons
pluginItem.Update()
pluginItem.Layout()
# update panel (if applicable)
if pluginPanel and pluginItem and pluginPanel.info == pluginItem.info:
if installed is None:
# if pending, show elipsis and refresh icon
pluginPanel.installBtn.Hide()
pluginPanel.uninstallBtn.Hide()
elif installed:
# if installed, show as installed with tick
pluginPanel.installBtn.Hide()
pluginPanel.uninstallBtn.Show()
else:
# if not installed, show "Install" and download icon
pluginPanel.installBtn.Show()
pluginPanel.uninstallBtn.Hide()
# refresh buttons
pluginPanel.Update()
pluginPanel.Layout()
def markActive(pluginItem, pluginPanel, active=True):
"""
Setup installed button according to install state
Parameters
----------
pluginItem : PluginBrowserList.PluginListItem
Plugin list item associated with this plugin
pluginPanel : PluginDetailsPanel
Plugin viewer panel to update
active : bool or None
True if active, False if not active, None if pending/unclear
"""
def _setAllBitmaps(btn, bmp):
"""
Set all bitmaps (enabled, disabled, focus, unfocus, etc.) for a button
"""
btn.SetBitmap(bmp)
btn.SetBitmapDisabled(bmp)
btn.SetBitmapPressed(bmp)
btn.SetBitmapCurrent(bmp)
btn.SetBitmapFocus(bmp)
btn.SetBitmapMargins(6, 3)
# Update plugin item
if pluginItem:
if active is None:
# If pending, show elipsis and refresh icon
pluginItem.activeBtn.SetLabel("...")
_setAllBitmaps(pluginItem.activeBtn, icons.ButtonIcon("orangedot", 16).bitmap)
elif active:
# If active, show Enabled and green dot
pluginItem.activeBtn.SetLabel(_translate("Enabled"))
_setAllBitmaps(pluginItem.activeBtn, icons.ButtonIcon("greendot", 16).bitmap)
else:
# If not active, show Disabled and grey dot
pluginItem.activeBtn.SetLabel(_translate("Disabled"))
_setAllBitmaps(pluginItem.activeBtn, icons.ButtonIcon("greydot", 16).bitmap)
# Refresh
pluginItem.Update()
pluginItem.Layout()
# Update panel (if applicable)
if pluginPanel and pluginItem and pluginPanel.info == pluginItem.info:
if active is None:
# If pending, show elipsis and refresh icon
pluginPanel.activeBtn.SetLabel("...")
_setAllBitmaps(pluginPanel.activeBtn, icons.ButtonIcon("orangedot", 16).bitmap)
elif active:
# If active, show Enabled and green dot
pluginPanel.activeBtn.SetLabel(_translate("Enabled"))
_setAllBitmaps(pluginPanel.activeBtn, icons.ButtonIcon("greendot", 16).bitmap)
else:
# If not active, show Disabled and grey dot
pluginPanel.activeBtn.SetLabel(_translate("Disabled"))
_setAllBitmaps(pluginPanel.activeBtn, icons.ButtonIcon("greydot", 16).bitmap)
# Refresh
pluginPanel.Update()
# store plugin objects for later use
_pluginObjects = None
# persistent variable to keep track of whether we need to update plugins
redownloadPlugins = True
def getAllPluginDetails():
"""Get all plugin details from the server and return as a list of
`PluginInfo` objects.
This function will download the plugin database from the server and
return a list of `PluginInfo` objects, one for each plugin in the
database. The database is cached locally and will only be replaced when
the server version is newer than the local version. This allows the user
to use the plugin manager offline or when the server is down.
Returns
-------
list of PluginInfo
List of plugin details.
"""
# check if the local `plugins.json` file exists and is up to date
appPluginCacheDir = os.path.join(
prefs.paths['userCacheDir'], 'appCache', 'plugins')
# create the cache directory if it doesn't exist
if not os.path.exists(appPluginCacheDir):
try:
os.makedirs(appPluginCacheDir)
except OSError:
pass
# where the database is expected to be
pluginDatabaseFile = Path(appPluginCacheDir) / "plugins.json"
def downloadPluginDatabase(srcURL="https://psychopy.org/plugins.json"):
"""Downloads the plugin database from the server and returns the text
as a string. If the download fails, returns None.
Parameters
----------
srcURL : str
The URL to download the plugin database from.
Returns
-------
list or None
The plugin database as a list, or None if the download failed.
"""
global redownloadPlugins
# if plugins already up to date, skip
if not redownloadPlugins:
return None
# download database from website
try:
resp = requests.get(srcURL)
except requests.exceptions.ConnectionError:
# if connection to website fails, return nothing
return None
# if download failed, return nothing
if resp.status_code == 404:
return None
# otherwise get as a string
value = resp.text
if value is None or value == "":
return None
# make sure we are using UTF-8 encoding
value = value.encode('utf-8', 'ignore').decode('utf-8')
# attempt to parse JSON
try:
database = json.loads(value)
except json.decoder.JSONDecodeError:
# if JSON parse fails, return nothing
return None
# if we made it this far, mark plugins as not needing update
redownloadPlugins = False
return database
def readLocalPluginDatabase(srcFile):
"""Read the local plugin database file (if it exists) and return the
text as a string. If the file doesn't exist, returns None.
Parameters
----------
srcFile : pathlib.Path
The expected path to the plugin database file.
Returns
-------
list or None
The plugin database as a list, or None if the file doesn't exist.
"""
# if source file doesn't exist, return nothing
if not srcFile.is_file():
return None
# attempt to parse JSON
try:
with srcFile.open("r", encoding="utf-8", errors="ignore") as f:
return json.load(f)
except json.decoder.JSONDecodeError:
# if JSON parse fails, return nothing
return None
def deletePluginDlgCache():
"""Delete the local plugin database file and cached files related to
the Plugin dialog.
"""
if os.path.exists(appPluginCacheDir):
files = glob.glob(os.path.join(appPluginCacheDir, '*'))
for f in files:
os.remove(f)
# get a copy of the plugin database from the server, check if it's newer
# than the local copy, and if so, replace the local copy
# get remote database
serverPluginDatabase = downloadPluginDatabase()
# get local database
localPluginDatabase = readLocalPluginDatabase(pluginDatabaseFile)
if serverPluginDatabase is not None:
# if we have a database from the remote, use it
pluginDatabase = serverPluginDatabase
# if the file contents has changed, delete cached icons and etc.
if str(pluginDatabase) != str(localPluginDatabase):
deletePluginDlgCache()
# write new contents to file
with pluginDatabaseFile.open("w", encoding='utf-8') as f:
json.dump(pluginDatabase, f, indent=True)
elif localPluginDatabase is not None:
# otherwise use cached
pluginDatabase = localPluginDatabase
else:
# if we have neither, treat as blank list
pluginDatabase = []
# check if we need to update plugin objects, if not return the cached data
global _pluginObjects
requiresRefresh = _pluginObjects is None
if not requiresRefresh:
return _pluginObjects
# Create PluginInfo objects from info list
objs = []
for info in pluginDatabase:
objs.append(PluginInfo(**info))
# Add info objects for local plugins which aren't found online
localPlugins = plugins.listPlugins(which='all')
for name in localPlugins:
# Check whether plugin is accounted for
if name not in objs:
# If not, get its metadata
data = plugins.pluginMetadata(name)
# Create best representation we can from metadata
author = AuthorInfo(
name=data.get('Author', ''),
email=data.get('Author-email', ''),
)
info = PluginInfo(
pipname=name, name=name,
author=author,
homepage=data.get('Home-page', ''),
keywords=data.get('Keywords', ''),
description=data.get('Summary', ''),
)
# Add to list
objs.append(info)
_pluginObjects = objs # cache for later
return _pluginObjects
if __name__ == "__main__":
pass
| 52,274
|
Python
|
.py
| 1,292
| 29.979102
| 152
| 0.603195
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,841
|
output.py
|
psychopy_psychopy/psychopy/app/plugin_manager/output.py
|
import webbrowser
import wx
import wx.richtext
from psychopy.app.themes import handlers, colors
class InstallStdoutPanel(wx.Panel, handlers.ThemeMixin):
def __init__(self, parent):
wx.Panel.__init__(
self, parent
)
# Setup sizer
self.sizer = wx.BoxSizer(wx.HORIZONTAL)
self.SetSizer(self.sizer)
# Output
self.output = wx.richtext.RichTextCtrl(self, style=wx.BORDER_NONE | wx.richtext.RE_READONLY)
self.output.Bind(wx.EVT_TEXT_URL, self.onLink)
self.sizer.Add(self.output, proportion=1, border=6, flag=wx.ALL | wx.EXPAND)
# Start off hidden
self.Hide()
self.Layout()
def open(self):
notebook = self.GetParent()
# Skip if parent isn't a notebook
if not isinstance(notebook, wx.Notebook):
return
# Navigate to own page
i = notebook.FindPage(self)
notebook.ChangeSelection(i)
def write(self, content, color="black", style=""):
"""Write out bytes coming from the current subprocess.
Parameters
----------
content : str or bytes
Text to write.
color : bool
Color to show the text as
style : str
Whether to show the text as bold and/or italic.
* "" = Regular
* "b" = Bold
* "i" = Italic
* "bi" / "ib" = Bold Italic
"""
# Decode content if needed
if isinstance(content, bytes):
content = content.decode('utf-8')
# Move cursor to end
self.output.SetInsertionPointEnd()
# Set font
from psychopy.app.themes import fonts
self.output.BeginFont(fonts.CodeFont().obj)
# Set style
self.output.BeginTextColour(color)
if "b" in style:
self.output.BeginBold()
if "i" in style:
self.output.BeginItalic()
# Write content
self.output.WriteText(f"\n{content}")
# End style
self.output.EndTextColour()
self.output.EndBold()
self.output.EndItalic()
# Scroll to end
self.output.ShowPosition(self.output.GetLastPosition())
# Make sure we're shown
self.open()
# Update
self.Update()
self.Refresh()
def writeLink(self, content, link=""):
# Begin style
self.output.BeginURL(link)
# Write content
self.write(content, color=colors.scheme["blue"], style="i")
# End style
self.output.EndURL()
def writeCmd(self, cmd=""):
"""
Write input (black, bold, italic, prefaced by >>) text to the output panel.
Parameters
----------
cmd : bytes or str
Command which was supplied to the subprocess
"""
self.write(f">> {cmd}", style="bi")
def writeStdOut(self, lines=""):
"""
Write output (black) text to the output panel.
Parameters
----------
lines : bytes or str
String to print, can also be bytes (as is the case when retrieved directly from the subprocess).
"""
self.write(lines)
def writeStdErr(self, lines=""):
"""
Write error (red) text to the output panel.
Parameters
----------
lines : bytes or str
String to print, can also be bytes (as is the case when retrieved directly from the subprocess).
"""
self.write(lines, color=colors.scheme["red"])
def writeTerminus(self, msg="Process completed"):
"""
Write output when the subprocess exits.
Parameters
----------
msg : str
Message to be printed flanked by `#` characters.
"""
# Construct a close message, shows the exit code
closeMsg = f" {msg} ".center(80, '#')
# Write close message
self.write(closeMsg, color=colors.scheme["green"])
def onLink(self, evt=None):
webbrowser.open(evt.String)
| 4,045
|
Python
|
.py
| 117
| 25.547009
| 108
| 0.576284
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,842
|
utils.py
|
psychopy_psychopy/psychopy/app/plugin_manager/utils.py
|
import wx
import wx.richtext
from psychopy.app.themes import handlers, icons
from psychopy.localization import _translate
from psychopy.tools import pkgtools
class InstallErrorDlg(wx.Dialog, handlers.ThemeMixin):
"""
Dialog to display when something fails to install, contains info on what
command was tried and what output was received.
"""
def __init__(self, label, caption=_translate("PIP error"), cmd="", stdout="", stderr=""):
from psychopy.app.themes import fonts
# Initialise
wx.Dialog.__init__(
self, None,
size=(480, 620),
title=caption,
style=wx.RESIZE_BORDER | wx.CLOSE_BOX | wx.CAPTION
)
# Setup sizer
self.border = wx.BoxSizer(wx.VERTICAL)
self.SetSizer(self.border)
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.border.Add(self.sizer, proportion=1, border=6, flag=wx.ALL | wx.EXPAND)
# Create title sizer
self.title = wx.BoxSizer(wx.HORIZONTAL)
self.sizer.Add(self.title, border=6, flag=wx.ALL | wx.EXPAND)
# Create icon
self.icon = wx.StaticBitmap(
self, size=(32, 32),
bitmap=icons.ButtonIcon(stem="stop", size=32).bitmap
)
self.title.Add(self.icon, border=6, flag=wx.ALL | wx.EXPAND)
# Create title
self.titleLbl = wx.StaticText(self, label=label)
self.titleLbl.SetFont(fonts.appTheme['h3'].obj)
self.title.Add(self.titleLbl, proportion=1, border=6, flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL)
# Show what we tried
self.inLbl = wx.StaticText(self, label=_translate("We tried:"))
self.sizer.Add(self.inLbl, border=6, flag=wx.ALL | wx.EXPAND)
self.inCtrl = wx.TextCtrl(self, value=cmd, style=wx.TE_READONLY)
self.inCtrl.SetBackgroundColour("white")
self.inCtrl.SetFont(fonts.appTheme['code'].obj)
self.sizer.Add(self.inCtrl, border=6, flag=wx.ALL | wx.EXPAND)
# Show what we got
self.outLbl = wx.StaticText(self, label=_translate("We got:"))
self.sizer.Add(self.outLbl, border=6, flag=wx.ALL | wx.EXPAND)
self.outCtrl = wx.TextCtrl(self, value=f"{stdout}\n{stderr}",
size=(-1, 620), style=wx.TE_READONLY | wx.TE_MULTILINE)
self.outCtrl.SetFont(fonts.appTheme['code'].obj)
self.sizer.Add(self.outCtrl, proportion=1, border=6, flag=wx.ALL | wx.EXPAND)
# Make buttons
self.btns = self.CreateStdDialogButtonSizer(flags=wx.OK)
self.border.Add(self.btns, border=6, flag=wx.ALIGN_RIGHT | wx.ALL)
self.Layout()
self._applyAppTheme()
def ShowModal(self):
# Make error noise
wx.Bell()
# Show as normal
wx.Dialog.ShowModal(self)
def uninstallPackage(package):
"""
Call `pkgtools.uninstallPackage` and handle any errors cleanly.
"""
retcode, info = pkgtools.uninstallPackage(package)
# Handle errors
if retcode != 0:
# Display output if error
cmd = "\n>> " + " ".join(info['cmd']) + "\n"
dlg = InstallErrorDlg(
cmd=cmd,
stdout=info['stdout'],
stderr=info['stderr'],
label=_translate("Package {} could not be uninstalled.").format(package)
)
else:
# Display success message if success
dlg = wx.MessageDialog(
parent=None,
caption=_translate("Package installed"),
message=_translate("Package {} successfully uninstalled!").format(package),
style=wx.ICON_INFORMATION
)
dlg.ShowModal()
def installPackage(package, stream):
"""
Call `pkgtools.installPackage` and handle any errors cleanly.
"""
# Show output
stream.open()
# Install package
retcode, info = pkgtools.installPackage(package)
# Write command
stream.writeCmd(" ".join(info['cmd']))
# Write output
stream.writeStdOut(info['stdout'])
stream.writeStdErr(info['stderr'])
# Report success
if retcode:
stream.writeStdOut(_translate("Installation complete. See above for info.\n"))
else:
stream.writeStdErr(_translate("Installation failed. See above for info.\n"))
return stream
| 4,267
|
Python
|
.py
| 104
| 32.894231
| 101
| 0.634393
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,843
|
__init__.py
|
psychopy_psychopy/psychopy/app/plugin_manager/__init__.py
|
"""Plugin manager for PsychoPy GUI apps (Builder and Coder)."""
from .plugins import PluginManagerPanel
from .packages import PackageManagerPanel
from .output import InstallStdoutPanel
| 186
|
Python
|
.py
| 4
| 45.25
| 63
| 0.839779
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,844
|
packages.py
|
psychopy_psychopy/psychopy/app/plugin_manager/packages.py
|
import webbrowser
import wx
import os
import sys
import subprocess as sp
from pypi_search import search as pypi
from psychopy.app import utils
from psychopy.app.themes import handlers, icons
from psychopy.localization import _translate
from psychopy.tools.pkgtools import (
getInstalledPackages, getPackageMetadata, getPypiInfo, isInstalled,
_isUserPackage, getInstallState
)
from psychopy.tools.versionchooser import parseVersionSafely
class PackageManagerPanel(wx.Panel):
def __init__(self, parent, dlg):
wx.Panel.__init__(self, parent)
self.dlg = dlg
# Setup sizer
self.border = wx.BoxSizer(wx.VERTICAL)
self.SetSizer(self.border)
self.sizer = wx.BoxSizer(wx.HORIZONTAL)
self.border.Add(self.sizer, proportion=1, border=6, flag=wx.ALL | wx.EXPAND)
# Add package list
self.packageList = PackageListCtrl(self, dlg=self.dlg)
self.packageList.Bind(wx.EVT_LIST_ITEM_SELECTED, self.onSelectItem)
self.sizer.Add(self.packageList, flag=wx.EXPAND | wx.ALL)
# Seperator
self.sizer.Add(wx.StaticLine(self, style=wx.LI_VERTICAL), border=6, flag=wx.EXPAND | wx.ALL)
# Add details panel
self.detailsPanel = PackageDetailsPanel(self, dlg=self.dlg)
self.sizer.Add(self.detailsPanel, proportion=1, flag=wx.EXPAND | wx.ALL)
def onSelectItem(self, evt=None):
# Get package name
pipname = evt.GetText()
# Set pip details from name
self.detailsPanel.package = pipname
class PIPTerminalPanel(wx.Panel):
"""
Interface for interacting with PIP within the standalone PsychoPy environment.
"""
def __init__(self, parent):
wx.Panel.__init__(self, parent)
# Setup sizers
self.border = wx.BoxSizer()
self.SetSizer(self.border)
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.border.Add(self.sizer, proportion=1, border=12, flag=wx.ALL | wx.EXPAND)
# Sanitize system executable
executable = sys.executable
if not (
executable[0] in ("'", '"') and executable[-1] in ("'", '"')
):
executable = f'"{executable}"'
# Construct preface
self.preface = " ".join([executable, "-m"])
# Add output
self.output = wx.richtext.RichTextCtrl(
self,
value=_translate(
"Type a PIP command below and press Enter to execute it in the installed PsychoPy environment, any "
"returned text will appear below.\n"
"\n"
"All commands will be automatically prefaced with:\n"
"{}\n"
"\n"
).format(self.preface),
size=(480, -1),
style=wx.TE_READONLY)
self.sizer.Add(self.output, proportion=1, border=6, flag=wx.ALL | wx.EXPAND)
# Add text control
self.consoleSzr = wx.BoxSizer(wx.HORIZONTAL)
self.consoleLbl = wx.StaticText(self, label=">>")
self.consoleSzr.Add(self.consoleLbl, border=6, flag=wx.RIGHT | wx.ALIGN_CENTER_VERTICAL)
self.console = wx.TextCtrl(self, size=(-1, -1), style=wx.TE_PROCESS_ENTER)
self.console.Bind(wx.EVT_TEXT_ENTER, self.onEnter)
self.consoleSzr.Add(self.console, proportion=1)
self.sizer.Add(self.consoleSzr, border=6, flag=wx.ALL | wx.EXPAND)
self._applyAppTheme()
self.Center()
def onEnter(self, evt=None):
# Get current command
cmd = self.console.GetValue()
# Clear text entry
self.console.Clear()
# Run command
self.runCommand(cmd)
def runCommand(self, cmd):
"""Run the command."""
env = os.environ.copy()
emts = [self.preface, cmd]
output = sp.Popen(' '.join(emts),
stdout=sp.PIPE,
stderr=sp.PIPE,
shell=True,
env=env,
universal_newlines=True)
stdout, stderr = output.communicate()
sys.stdout.write(stdout)
sys.stderr.write(stderr)
# Display input
self.output.AppendText("\n>> " + cmd + "\n")
# Display output if error
if output.returncode != 0:
self.output.AppendText(stderr)
self.output.AppendText(stdout)
# Update output ctrl to style new text
handlers.ThemeMixin._applyAppTheme(self.output)
# Scroll to bottom
self.output.ShowPosition(self.output.GetLastPosition())
def _applyAppTheme(self):
# Style output ctrl
handlers.ThemeMixin._applyAppTheme(self.output)
# Apply code font to text ctrl
from psychopy.app.themes import fonts
self.console.SetFont(fonts.coderTheme.base.obj)
class PackageListCtrl(wx.Panel):
def __init__(self, parent, dlg):
wx.Panel.__init__(self, parent, size=(300, -1))
self.dlg = dlg
# Setup sizers
self.border = wx.BoxSizer()
self.SetSizer(self.border)
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.border.Add(self.sizer, proportion=1, border=12, flag=wx.ALL | wx.EXPAND)
# Search bar
self.searchCtrl = wx.SearchCtrl(self)
self.searchCtrl.Bind(wx.EVT_SEARCH, self.refresh)
self.sizer.Add(self.searchCtrl, border=6, flag=wx.ALL | wx.EXPAND)
# Create list ctrl
self.ctrl = utils.ListCtrl(self, style=wx.LC_REPORT | wx.LC_SINGLE_SEL)
self.ctrl.setResizeColumn(0)
self.ctrl.Bind(wx.EVT_LIST_ITEM_SELECTED, self.onItemSelected)
self.ctrl.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, self.onRightClick)
self.sizer.Add(self.ctrl, proportion=1, border=6, flag=wx.LEFT | wx.RIGHT | wx.EXPAND)
# "Or..." label
self.orLbl = wx.StaticText(self, label=_translate("or..."))
self.sizer.Add(self.orLbl, border=3, flag=wx.ALL | wx.ALIGN_CENTER)
# Add by file...
self.addFileBtn = wx.Button(self, label=_translate("Install from file"))
self.addFileBtn.SetToolTip(_translate(
"Install a package from a local file, such as a .egg or .whl. You can also point to a "
"pyproject.toml file to add an 'editable install' of an in-development package."
))
self.addFileBtn.Bind(wx.EVT_BUTTON, self.onAddFromFile)
self.sizer.Add(self.addFileBtn, border=6, flag=wx.ALL | wx.ALIGN_CENTER)
# Add button to open pip
self.terminalBtn = wx.Button(self, label=_translate("Open PIP terminal"))
self.terminalBtn.SetToolTip(_translate("Open PIP terminal to manage packages manually"))
self.sizer.Add(self.terminalBtn, border=3, flag=wx.ALL | wx.ALIGN_CENTER)
self.terminalBtn.Bind(wx.EVT_BUTTON, self.onOpenPipTerminal)
# Initial data
self.refresh()
self.Layout()
def onOpenPipTerminal(self, evt=None):
# Make dialog
dlg = wx.Dialog(self, title="PIP Terminal", size=(480, 480), style=wx.RESIZE_BORDER | wx.CAPTION | wx.CLOSE_BOX)
# Setup sizer
dlg.sizer = wx.BoxSizer(wx.VERTICAL)
dlg.SetSizer(dlg.sizer)
# Add panel
panel = PIPTerminalPanel(dlg)
dlg.sizer.Add(panel, proportion=1, border=6, flag=wx.ALL | wx.EXPAND)
# Layout
dlg.Layout()
# Show
dlg.Show()
def onItemSelected(self, evt=None):
# Post event so it can be caught by parent
evt.SetEventObject(self)
wx.PostEvent(self, evt)
def onRightClick(self, evt=None):
# Get package name
package = evt.GetText()
# Create menu
menu = wx.Menu()
# Map menu functions
menu.functions = {}
if isInstalled(package) and _isUserPackage(package):
# Add uninstall if installed to user
uninstallOpt = menu.Append(wx.ID_ANY, item=_translate("Uninstall"))
menu.functions[uninstallOpt.GetId()] = self.onUninstall
elif isInstalled(package):
# Add nothing if installed to protected system folder
pass
else:
# Add install if not installed
uninstallOpt = menu.Append(wx.ID_ANY, item=_translate("Install"))
menu.functions[uninstallOpt.GetId()] = self.onInstall
# Bind choice event
menu.Bind(wx.EVT_MENU, self.onRightClickMenuChoice)
# Store pip name as attribute of menu
menu.pipname = evt.GetText()
# Show menu
self.PopupMenu(menu)
def onRightClickMenuChoice(self, evt=None):
# Work out what was chosen
menu = evt.GetEventObject()
choice = evt.GetId()
if choice not in menu.functions:
return
# Perform associated method
menu.functions[choice](evt)
def onUninstall(self, evt=None):
# Get rightclick menu
menu = evt.GetEventObject()
pipname = menu.pipname
msg = wx.MessageDialog(
self,
"Are you sure you want to uninstall package `{}`?".format(pipname),
caption="Uninstall Package?",
style=wx.YES_NO | wx.NO_DEFAULT)
# if user selects NO, exit the routine
if msg.ShowModal() == wx.ID_YES:
self.GetTopLevelParent().uninstallPackage(pipname)
self.refresh()
def onInstall(self, evt=None):
# Get rightclick menu
menu = evt.GetEventObject()
pipname = menu.pipname
# Install package
self.GetTopLevelParent().installPackage(pipname)
self.refresh()
def refresh(self, evt=None):
# Get search term
searchTerm = self.searchCtrl.GetValue()
# Clear
self.ctrl.ClearAll()
self.ctrl.AppendColumn(_translate("Package"))
self.ctrl.AppendColumn(_translate("Installed"))
# Get installed packages
installedPackages = dict(getInstalledPackages())
# If there's no search term, show all installed and return
if searchTerm in (None, ""):
for pkg, version in installedPackages.items():
item = self.ctrl.Append((pkg, version))
self.ctrl.SetItemFont(item, font=wx.Font().Bold())
return
# Add column for latest version if we're actually searching
self.ctrl.AppendColumn(_translate("Latest"))
# Get packages from search
foundPackages = pypi.find_packages(self.searchCtrl.GetValue())
# Populate
for pkg in foundPackages:
font = wx.Font()
if pkg['name'] in installedPackages:
# If installed, add row with value for installed version
item = self.ctrl.Append((pkg['name'], installedPackages[pkg['name']], pkg['version']))
font = font.Bold()
else:
# Otherwise, add row with installed version blank
item = self.ctrl.Append((pkg['name'], "-", pkg['version']))
# Style new row according to install status
self.ctrl.SetItemFont(item, font)
def onAddFromFile(self, evt=None):
# Create dialog to get package file location
dlg = wx.FileDialog(
self,
wildcard="Wheel files (*.whl)|*.whl|"
"Source distribution files (*.sdist)|*.sdist|"
"Python project (pyproject.toml)|pyproject.toml|"
"All files (*.*)|*.*",
style=wx.FD_OPEN | wx.FD_SHOW_HIDDEN)
if dlg.ShowModal() == wx.ID_OK:
# Install
self.GetTopLevelParent().installPackage(dlg.GetPath())
# Reload packages
self.refresh()
class PackageDetailsPanel(wx.Panel):
def __init__(self, parent, dlg):
wx.Panel.__init__(self, parent)
self.dlg = dlg
# Setup sizers
self.border = wx.BoxSizer(wx.VERTICAL)
self.SetSizer(self.border)
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.border.Add(self.sizer, proportion=1, border=12, flag=wx.ALL | wx.EXPAND)
# Name sizer
self.nameSzr = wx.BoxSizer(wx.HORIZONTAL)
self.sizer.Add(self.nameSzr)
# Name
self.nameCtrl = wx.StaticText(self)
self.nameSzr.Add(self.nameCtrl, border=6, flag=wx.TOP | wx.LEFT | wx.RIGHT | wx.EXPAND)
# Author
self.authorSzr = wx.BoxSizer(wx.HORIZONTAL)
self.sizer.Add(self.authorSzr, border=6, flag=wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.EXPAND)
self.authorPre = wx.StaticText(self, label=_translate("by "))
self.authorSzr.Add(self.authorPre, border=0, flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL)
self.authorCtrl = wx.StaticText(self)
self.authorSzr.Add(self.authorCtrl, border=0, flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL)
self.licenseCtrl = wx.StaticText(self)
self.authorSzr.Add(self.licenseCtrl, border=0, flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL)
# Header buttons sizer
self.headBtnSzr = wx.BoxSizer(wx.HORIZONTAL)
self.sizer.Add(self.headBtnSzr, border=3, flag=wx.ALL | wx.EXPAND)
# Homepage button
self.homeBtn = wx.Button(self, label=_translate("Homepage"))
self.headBtnSzr.Add(self.homeBtn, border=3, flag=wx.ALL | wx.EXPAND)
self.homeBtn.Bind(wx.EVT_BUTTON, self.onHomepage)
# Install button
self.installBtn = wx.Button(self, label=_translate("Install"))
self.headBtnSzr.Add(wx.StaticLine(self, style=wx.LI_VERTICAL), border=6, flag=wx.LEFT | wx.RIGHT | wx.EXPAND)
self.headBtnSzr.Add(self.installBtn, border=3, flag=wx.ALL | wx.EXPAND)
self.installBtn.Bind(wx.EVT_BUTTON, self.onInstall)
# Version chooser
self.versionCtrl = wx.Choice(self)
self.headBtnSzr.Add(self.versionCtrl, border=3, flag=wx.RIGHT | wx.TOP | wx.BOTTOM | wx.ALIGN_CENTER)
self.versionCtrl.Bind(wx.EVT_CHOICE, self.onVersion)
# Uninstall button
self.uninstallBtn = wx.Button(self, label=_translate("Uninstall"))
self.headBtnSzr.AddStretchSpacer(1)
self.headBtnSzr.Add(self.uninstallBtn, border=3, flag=wx.ALL | wx.EXPAND)
self.uninstallBtn.Bind(wx.EVT_BUTTON, self.onUninstall)
# Description
self.descCtrl = utils.MarkdownCtrl(self, style=wx.TE_READONLY | wx.TE_MULTILINE | wx.BORDER_NONE | wx.TE_NO_VSCROLL)
self.sizer.Add(self.descCtrl, proportion=1, border=6, flag=wx.ALL | wx.EXPAND)
# todo: Required by...
self.package = None
@property
def package(self):
if hasattr(self, "_package"):
return self._package
@package.setter
def package(self, pipname):
self._package = pipname
if self._package is None:
# Show placeholder text
self.params = {
"name": "...",
"author": "...",
"authorEmail": "",
"license": "",
"summary": "",
"desc": "",
'version': None,
'releases': []
}
else:
# Get data from pypi
pypiData = getPypiInfo(self._package)
# Get package metadata (if installed)
if self._package in dict(getInstalledPackages()):
metadata = getPackageMetadata(self._package)
else:
metadata = {}
# Get best data available, prioritising local metadata
self.params = {
'name': metadata.get('Name', pypiData.get('Name', pipname)),
'author': metadata.get('Author', pypiData.get('author', 'Unknown')),
'authorEmail': metadata.get('Author-email', pypiData.get('author_email', 'Unknown')),
'license': metadata.get('License', pypiData.get('license', 'Unknown')),
'summary': metadata.get('Summary', pypiData.get('summary', '')),
'desc': metadata.get('Description', pypiData.get('description', '')),
'version': metadata.get('Version', None),
'releases': pypiData.get('Releases', pypiData.get('releases', []))
}
# Sort versions in descending order
self.params['releases'] = sorted(
self.params['releases'],
key=lambda v: parseVersionSafely(v),
reverse=True
)
# Set values from params
self.nameCtrl.SetLabel(self.params['name'] or "")
self.authorCtrl.SetLabel(self.params['author'] or "")
self.authorCtrl.SetToolTip(self.params['authorEmail'])
self.licenseCtrl.SetLabel(" (License: %(license)s)" % self.params)
self.descCtrl.setValue("%(summary)s\n\n%(desc)s" % self.params)
# Set current and possible versions
self.versionCtrl.Clear()
self.versionCtrl.AppendItems(self.params['releases'])
if self.params['version'] is None:
self.versionCtrl.SetSelection(0)
else:
if self.params['version'] not in self.versionCtrl.GetStrings():
self.versionCtrl.Append(self.params['version'])
self.versionCtrl.SetStringSelection(self.params['version'])
self.refresh()
self.Layout()
self._applyAppTheme()
def refresh(self, evt=None):
state, version = getInstallState(self.package)
if state == "u":
# If installed to the user space, can be uninstalled or changed
self.uninstallBtn.Enable()
self.versionCtrl.Enable()
self.installBtn.Enable(
self.versionCtrl.GetStringSelection() != version
)
elif state == "s":
# If installed to the system, can't be uninstalled or changed
self.uninstallBtn.Disable()
self.versionCtrl.Disable()
self.installBtn.Disable()
elif state == "n":
# If uninstalled, can only be installed
self.uninstallBtn.Disable()
self.versionCtrl.Enable()
self.installBtn.Enable()
else:
# If None, disable everything
self.uninstallBtn.Disable()
self.versionCtrl.Disable()
self.installBtn.Disable()
# Disable all controls if we have None
self.homeBtn.Enable(state is not None)
self.nameCtrl.Enable(state is not None)
self.authorPre.Enable(state is not None)
self.authorCtrl.Enable(state is not None)
self.licenseCtrl.Enable(state is not None)
self.descCtrl.Enable(state is not None)
def onHomepage(self, evt=None):
# Open homepage in browser
webbrowser.open(self.params.get('Home-page', ""))
def onInstall(self, evt=None):
name = self.package
version = self.versionCtrl.GetStringSelection()
# Append version if given
if version is not None:
name += f"=={version}"
# Install package then disable the button to indicate it's installed
win = self.GetTopLevelParent()
wx.CallAfter(win.installPackage, name)
# Refresh view
self.refresh()
def onUninstall(self, evt=None):
# Get rightclick menu
msg = wx.MessageDialog(
self,
"Are you sure you want to uninstall package `{}`?".format(self.package),
caption="Uninstall Package?",
style=wx.YES_NO | wx.NO_DEFAULT)
# if user selects NO, exit the routine
if msg.ShowModal() == wx.ID_YES:
win = self.GetTopLevelParent()
wx.CallAfter(win.uninstallPackage, self.package)
# Refresh view
self.refresh()
def onVersion(self, evt=None):
# Refresh view
self.refresh()
def _applyAppTheme(self):
from psychopy.app.themes import fonts
self.nameCtrl.SetFont(fonts.appTheme['h1'].obj)
self.installBtn.SetBitmap(icons.ButtonIcon(stem="download", size=16).bitmap)
self.uninstallBtn.SetBitmap(icons.ButtonIcon(stem="delete", size=16).bitmap)
self.authorCtrl.SetBackgroundColour("white")
if __name__ == "__main__":
pass
| 20,151
|
Python
|
.py
| 449
| 34.679287
| 124
| 0.614081
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,845
|
__init__.py
|
psychopy_psychopy/psychopy/app/connections/__init__.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Part of the PsychoPy library
# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd.
# Distributed under the terms of the GNU General Public License (GPL).
from .updates import * # pylint: disable=W0401
from .news import getNewsItems, showNews
from .sendusage import sendUsageStats
| 357
|
Python
|
.py
| 8
| 43.375
| 79
| 0.766571
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,846
|
sendusage.py
|
psychopy_psychopy/psychopy/app/connections/sendusage.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Part of the PsychoPy library
# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd.
# Distributed under the terms of the GNU General Public License (GPL).
import time
import sys
import platform
import psychopy
from psychopy import web, logging
try:
import certifi
except ImportError:
certifi = None
def sendUsageStats(app=None):
"""Sends anonymous, very basic usage stats to psychopy server:
the version of PsychoPy
the system used (platform and version)
the date
"""
v = psychopy.__version__
dateNow = time.strftime("%Y-%m-%d_%H:%M")
try:
miscInfo = platform.machine()
except AttributeError:
miscInfo=''
# get platform-specific info
if sys.platform == 'darwin':
OSXver, junk, architecture = platform.mac_ver()
systemInfo = "OSX_%s" % (OSXver)
elif sys.platform.startswith('linux'):
import distro
systemInfo = '%s_%s_%s' % (
'Linux',
':'.join([x for x in [distro.name(), distro.version(), distro.codename()] if x != '']),
platform.release())
if len(systemInfo) > 30: # if it's too long PHP/SQL fails to store!?
systemInfo = systemInfo[0:30]
elif sys.platform == 'win32':
systemInfo = "win32_v" + platform.version()
else:
systemInfo = platform.system() + platform.release()
u = "https://usage.psychopy.org/submit.php?date=%s&sys=%s&version=%s&misc=%s"
URL = u % (dateNow, systemInfo, v, miscInfo)
try:
req = web.urllib.request.Request(URL)
if certifi:
page = web.urllib.request.urlopen(req, cafile=certifi.where())
else:
page = web.urllib.request.urlopen(req)
except Exception:
logging.warning("Couldn't connect to psychopy.org\n"
"Check internet settings (and proxy "
"setting in PsychoPy Preferences.")
| 1,995
|
Python
|
.py
| 54
| 30.074074
| 99
| 0.628749
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,847
|
updates.py
|
psychopy_psychopy/psychopy/app/connections/updates.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Part of the PsychoPy library
# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd.
# Distributed under the terms of the GNU General Public License (GPL).
import sys
import re
import glob
import time
import zipfile
import platform
import os
from packaging.version import Version
import wx
import wx.lib.filebrowsebutton
try:
import wx.lib.agw.hyperlink as wxhl # 4.0+
except ImportError:
import wx.lib.hyperlink as wxhl # <3.0.2
import psychopy
from .. import dialogs
from psychopy.localization import _translate
from psychopy import logging
from psychopy import web
import io
urllib = web.urllib
versionURL = "https://www.psychopy.org/version.txt"
"""The Updater class checks for updates and suggests that an update is carried
out if a new version is found. The actual updating is handled by
InstallUpdateDialog (via Updater.doUpdate() ).
"""
def getLatestVersionInfo(app=None):
"""
Fetch info about the latest available version.
Returns -1 if fails to make a connection
"""
try:
page = urllib.request.urlopen(versionURL)
except urllib.error.URLError:
return -1
# parse update file as a dictionary
latest = {}
for line in page.readlines():
# in some odd circumstances (wifi hotspots) you can fetch a
# page that is not the correct URL but a redirect
line = line.decode() # convert from a byte to a str
if line.find(':') == -1:
return -1
# this will succeed if every line has a key
key, keyInfo = line.split(':')
latest[key] = keyInfo.replace('\n', '').replace('\r', '')
if app:
app._latestAvailableVersion = latest
return latest
class Updater():
def __init__(self, app=None, runningVersion=None):
"""The updater will check for updates and download/install as needed.
Several dialogs may be created as needed during the process.
Usage::
if app.prefs['AutoUpdate']:
app.updates = Updater(app)
app.updater.checkForUpdates()
# if updates are found further dialogs will prompt
"""
super(Updater, self).__init__()
self.app = app
if runningVersion is None:
self.runningVersion = psychopy.__version__
else:
self.runningVersion = runningVersion
# self.headers = {'User-Agent': psychopy.constants.PSYCHOPY_USERAGENT}
self.latest = getLatestVersionInfo()
if web.proxies is None:
web.setupProxy()
def getLatestInfo(self, warnMsg=False):
# open page
latest = getLatestVersionInfo()
if latest == -1:
m1 = _translate("Couldn't connect to psychopy.org to check for "
"updates. \n")
m2 = _translate("Check internet settings (and proxy setting in "
"PsychoPy Preferences).")
confirmDlg = dialogs.MessageDialog(
parent=None, message=m1 + m2, type='Info',
title=_translate('PsychoPy updates'))
confirmDlg.ShowModal()
return latest
def suggestUpdate(self, confirmationDlg=False):
"""Query user about whether to update (if it's possible to update)
"""
if self.latest is None: # we haven't checked for updates yet
self.latest = self.getLatestInfo()
if self.latest == -1:
return -1 # failed to find out about updates
# have found 'latest'. Is it newer than running version?
try:
newer = self.latest['version'] > self.runningVersion
except KeyError as err:
print(self.latest)
raise(err)
skip = self.app.prefs.appData['skipVersion'] == self.latest['version']
if newer and not skip:
if (Version(self.latest['lastUpdatable'])
<= Version(self.runningVersion)):
# go to the updating window
confirmDlg = SuggestUpdateDialog(
self.latest, self.runningVersion)
resp = confirmDlg.ShowModal()
confirmDlg.Destroy()
# what did the user ask us to do?
if resp == wx.ID_CANCEL:
return 0 # do nothing
if resp == wx.ID_NO:
self.app.prefs.appData[
'skipVersion'] = self.latest['version']
self.app.prefs.saveAppData()
return 0 # do nothing
if resp == wx.ID_YES:
self.doUpdate()
else:
# the latest version needs a full install, not autoupdate
msg = _translate("PsychoPy v%(latest)s is available (you are"
" running %(running)s).\n\n")
msg = msg % {'latest': self.latest['version'],
'running': self.runningVersion}
msg += _translate("This version is too big an update to be "
"handled automatically.\n")
msg += _translate("Please fetch the latest version from "
"www.psychopy.org and install manually.")
confirmDlg = dialogs.MessageDialog(
parent=None, message=msg, type='Warning',
title=_translate('PsychoPy updates'))
confirmDlg.cancelBtn.SetLabel(_translate('Go to downloads'))
confirmDlg.cancelBtn.SetDefault()
confirmDlg.noBtn.SetLabel(_translate('Go to changelog'))
confirmDlg.yesBtn.SetLabel(_translate('Later'))
resp = confirmDlg.ShowModal()
confirmDlg.Destroy()
if resp == wx.ID_CANCEL:
self.app.followLink(url=self.app.urls['downloads'])
if resp == wx.ID_NO:
self.app.followLink(url=self.app.urls['changelog'])
elif not confirmationDlg: # do nothing
return 0
else:
txt = _translate(
"You are running the latest version of PsychoPy (%s). ")
msg = txt % self.runningVersion
confirmDlg = dialogs.MessageDialog(
parent=None, message=msg, type='Info',
title=_translate('PsychoPy updates'))
confirmDlg.ShowModal()
return -1
def doUpdate(self):
"""Should be called from suggestUpdate
(separate dialog to ask user whether they want to)
"""
# app contains a reciprocal pointer to this Updater object
dlg = InstallUpdateDialog(None, -1, app=self.app)
class SuggestUpdateDialog(wx.Dialog):
"""A dialog explaining that a new version is available
with a link to the changelog
"""
def __init__(self, latest, runningVersion):
wx.Dialog.__init__(self, None, -1, title='PsychoPy3 Updates')
sizer = wx.BoxSizer(wx.VERTICAL)
# info about current version
txt = _translate("PsychoPy v%(latest)s is available (you are running "
"%(running)s).\n\n"
"(To disable this check, see Preferences > "
"connections > checkForUpdates)")
label = txt % {'latest': latest['version'], 'running': runningVersion}
msg1 = wx.StaticText(self, -1, style=wx.ALIGN_CENTRE, label=label)
if latest['lastCompatible'] > runningVersion:
label = _translate("This version MAY require you to modify your\n"
"scripts/exps slightly. Read the changelog "
"carefully.")
msg2 = wx.StaticText(self, -1, style=wx.ALIGN_CENTRE, label=label)
msg2.SetForegroundColour([200, 0, 0])
else:
label = _translate("There are no known compatibility\nissues "
"with your current version.")
msg2 = wx.StaticText(self, -1, style=wx.ALIGN_CENTRE, label=label)
changelog = wxhl.HyperLinkCtrl(self, wx.ID_ANY,
_translate("View complete Changelog"),
URL="https://www.psychopy.org/changelog.html")
if sys.platform.startswith('linux'):
msg = _translate("You can update PsychoPy with your package "
"manager")
msg3 = wx.StaticText(self, -1, msg)
else:
msg = _translate("Should PsychoPy update itself?")
msg3 = wx.StaticText(self, -1, msg)
sizer.Add(msg1, flag=wx.ALL | wx.CENTER, border=15)
sizer.Add(msg2, flag=wx.RIGHT | wx.LEFT | wx.CENTER, border=15)
sizer.Add(changelog, flag=wx.RIGHT | wx.LEFT | wx.CENTER, border=5)
sizer.Add(msg3, flag=wx.ALL | wx.CENTER, border=15)
# add buttons
btnSizer = wx.BoxSizer(wx.HORIZONTAL)
# for linux there should be no 'update' option
if sys.platform.startswith('linux'):
self.cancelBtn = wx.Button(
self, wx.ID_CANCEL, _translate('Keep warning me'))
self.cancelBtn.SetDefault()
self.noBtn = wx.Button(
self, wx.ID_NO, _translate('Stop warning me'))
else:
self.yesBtn = wx.Button(self, wx.ID_YES, _translate('Yes'))
self.Bind(wx.EVT_BUTTON, self.onButton, id=wx.ID_YES)
self.cancelBtn = wx.Button(
self, wx.ID_CANCEL, _translate('Not now'))
self.noBtn = wx.Button(
self, wx.ID_NO, _translate('Skip this version'))
self.Bind(wx.EVT_BUTTON, self.onButton, id=wx.ID_CANCEL)
self.Bind(wx.EVT_BUTTON, self.onButton, id=wx.ID_NO)
btnSizer.Add(self.noBtn, wx.ALIGN_LEFT)
btnSizer.Add((60, 20), 0, wx.EXPAND)
btnSizer.Add(self.cancelBtn)
if not sys.platform.startswith('linux'):
self.yesBtn.SetDefault()
btnSizer.Add((5, 20), 0)
btnSizer.Add(self.yesBtn)
# configure sizers and fit
sizer.Add(btnSizer, flag= wx.ALL, border=5)
self.Center()
self.SetSizerAndFit(sizer)
def onButton(self, event):
self.EndModal(event.GetId())
class InstallUpdateDialog(wx.Dialog):
def __init__(self, parent, ID, app):
"""Latest is optional extra. If not given it will be fetched.
"""
self.app = app
# get latest version info if poss
if app.updater in [False, None]:
# user has turned off check for updates in prefs so check now
app.updater = updater = Updater(app=self.app)
# don't need a warning - we'll provide one ourselves
self.latest = updater.getLatestInfo(warnMsg=False)
else:
self.latest = app.updater.latest
self.runningVersion = app.updater.runningVersion
wx.Dialog.__init__(self, parent, ID,
title=_translate('PsychoPy Updates'))
borderSizer = wx.BoxSizer(wx.VERTICAL)
mainSizer = wx.BoxSizer(wx.VERTICAL)
self.SetSizer(borderSizer)
borderSizer.Add(mainSizer, border=12, proportion=1, flag=wx.ALL | wx.EXPAND)
# set the actual content of status msg later in self.updateStatus()
self.statusMessage = wx.StaticText(
self, -1, "msg", style=wx.ALIGN_CENTER)
mainSizer.Add(self.statusMessage, flag=wx.EXPAND | wx.ALL, border=5)
# ctrls for auto-update from web
msg = _translate(" Auto-update (will fetch latest version)")
self.useLatestBtn = wx.RadioButton(self, -1, msg,
style=wx.RB_GROUP)
self.Bind(wx.EVT_RADIOBUTTON, self.onRadioSelect, self.useLatestBtn)
self.progressBar = wx.Gauge(self, -1, 100, size=(250, 36))
mainSizer.Add(self.useLatestBtn,
flag=wx.ALIGN_LEFT | wx.ALL, border=5)
mainSizer.Add(self.progressBar, flag=wx.EXPAND | wx.ALL, border=5)
# ctrls for updating from specific zip file
msg = _translate(" Use zip file below (download a PsychoPy release "
"file ending .zip)")
self.useZipBtn = wx.RadioButton(self, -1, msg)
self.Bind(wx.EVT_RADIOBUTTON, self.onRadioSelect, self.useZipBtn)
self.fileBrowseCtrl = wx.lib.filebrowsebutton.FileBrowseButton(
self, -1, size=(450, 48), changeCallback=self.onFileBrowse,
fileMask='*.zip')
mainSizer.Add(self.useZipBtn, flag=wx.ALIGN_LEFT | wx.ALL, border=5)
mainSizer.Add(self.fileBrowseCtrl, flag=wx.ALIGN_LEFT | wx.ALL, border=5)
# ctrls for buttons (install/cancel)
self.installBtn = wx.Button(self, -1, _translate('Install'))
self.Bind(wx.EVT_BUTTON, self.onInstall, self.installBtn)
self.installBtn.SetDefault()
self.cancelBtn = wx.Button(self, -1, _translate('Close'))
self.Bind(wx.EVT_BUTTON, self.onCancel, self.cancelBtn)
btnSizer = wx.BoxSizer(wx.HORIZONTAL)
btnSizer.AddStretchSpacer()
if sys.platform == "win32":
btns = [self.installBtn, self.cancelBtn]
else:
btns = [self.cancelBtn, self.installBtn]
btnSizer.Add(btns[0], 0, flag=wx.LEFT, border=5)
btnSizer.Add(btns[1], 0, flag=wx.LEFT, border=5)
mainSizer.AddStretchSpacer()
mainSizer.Add(btnSizer, flag=wx.ALL | wx.EXPAND, border=5)
self.Layout()
self.Fit()
# positioning and sizing
self.updateStatus()
self.Center()
self.ShowModal()
def updateStatus(self):
"""Check the current version and most recent version and update ctrls
"""
if self.latest == -1:
# Set message and display, and return early if version could not be found
msg = _translate(
"You are running PsychoPy v%s.\n ") % self.runningVersion
msg += _translate("PsychoPy could not connect to the \n internet"
" to check for more recent versions.\n")
msg += _translate("Check proxy settings in preferences.")
self.statusMessage.SetLabel(msg)
return
elif (Version(self.latest['version'])
< Version(self.runningVersion)):
msg = _translate(
"You are running PsychoPy (%(running)s), which is ahead of "
"the latest official version (%(latest)s)") % {
'running':self.runningVersion, 'latest':self.latest['version']}
elif self.latest['version'] == self.runningVersion:
msg = _translate(
"You are running the latest version of PsychoPy (%s)\n ") % self.runningVersion
msg += _translate("You can revert to a previous version by "
"selecting a specific .zip source installation file")
else:
txt = _translate(
"PsychoPy v%(latest)s is available\nYou are running v%(running)s")
msg = txt % {'latest': self.latest['version'],
'running': self.runningVersion}
if (Version(self.latest['lastUpdatable'])
<= Version(self.runningVersion)):
msg += _translate("\nYou can update to the latest version automatically")
else:
msg += _translate("\nYou cannot update to the latest version "
"automatically.\nPlease fetch the latest "
"Standalone package from www.psychopy.org")
self.statusMessage.SetLabel(msg)
areRunningLatest = self.latest['version'] == self.runningVersion
notUpdateable = self.latest['lastUpdatable'] > self.runningVersion
if self.latest == -1 or areRunningLatest or notUpdateable:
# can't auto-update
self.currentSelection = self.useZipBtn
self.useZipBtn.SetValue(True)
self.useLatestBtn.Disable()
else:
self.currentSelection = self.useLatestBtn
self.useLatestBtn.SetValue(True)
self.Layout()
self.Fit()
# this will enable/disable additional controls for the above:
self.onRadioSelect()
def onRadioSelect(self, event=None):
"""Set the controls of the appropriate selection to disabled/enabled
"""
# if receive no event then just set everything to previous state
if event != None:
self.currentSelection = event.GetEventObject()
else:
pass
if self.currentSelection == self.useLatestBtn:
self.fileBrowseCtrl.Disable()
self.progressBar.Enable()
elif self.currentSelection == self.useZipBtn:
self.fileBrowseCtrl.Enable()
self.progressBar.Disable()
# if this has been disabled by the fact that we couldn't connect
self.installBtn.Enable()
def onCancel(self, event):
self.app.updater = None
self.Close()
def onFileBrowse(self, event):
self.filename = event.GetString()
def onInstall(self, event):
if self.currentSelection == self.useLatestBtn:
info = self.doAutoInstall()
else:
info = self.installZipFile(self.filename)
self.statusMessage.SetLabel(str(info))
self.Fit()
def fetchPsychoPy(self, v='latest'):
msg = _translate("Attempting to fetch PsychoPy %s...")
self.statusMessage.SetLabel(msg % self.latest['version'])
info = ""
if v == 'latest':
v = self.latest['version']
# open page
URL = "http://github.com/psychopy/psychopy/releases/download/%s/PsychoPy-%s.zip"
page = urllib.request.urlopen(URL % v)
# download in chunks so that we can monitor progress and abort mid-way
chunk = 4096
read = 0
fileSize = int(page.info()['Content-Length'])
buffer = io.StringIO()
self.progressBar.SetRange(fileSize)
while read < fileSize:
ch = page.read(chunk)
buffer.write(ch)
read += chunk
self.progressBar.SetValue(read)
txt = _translate(
"Fetched %(done)i of %(total)i kb of PsychoPy-%(version)s.zip")
msg = txt % {'done': read // 1000,
'total': fileSize // 1000, 'version': v}
self.statusMessage.SetLabel(msg)
self.Update()
info += _translate('Successfully downloaded PsychoPy-%s.zip') % v
page.close()
zfile = zipfile.ZipFile(buffer)
# buffer.close()
return zfile, info
def installZipFile(self, zfile, v=None):
"""If v is provided this will be used as new version number;
otherwise try and retrieve a version number from zip file name
"""
info = "" # return this at the end
zfileIsName = type(zfile) == str
if os.path.isfile(zfile) and zfileIsName:
# zfile is filename not an actual file
if v is None: # try and deduce it
zFilename = os.path.split(zfile)[-1]
searchName = re.search(r'[0-9]*\.[0-9]*\.[0-9]*.', zFilename)
if searchName != None:
v = searchName.group(0)[:-1]
else:
msg = "Couldn't deduce version from zip file: %s"
logging.warning(msg % zFilename)
f = open(zfile, 'rb')
zfile = zipfile.ZipFile(f)
else: # assume here that zfile is a ZipFile
pass # todo: error checking - is it a zipfile?
currPath = self.app.prefs.paths['psychopy']
currVer = psychopy.__version__
# any commands that are successfully executed may need to be undone if
# a later one fails
undoStr = ""
# depending on install method, needs diff handling
# if path ends with 'psychopy' then move it to 'psychopy-version' and
# create a new 'psychopy' folder for new version
# does the path contain any version number?
versionLabelsInPath = re.findall('PsychoPy-.*/', currPath)
# e.g. the mac standalone app, no need to refer to new version number
onWin32 = bool(sys.platform == 'win32' and
int(sys.getwindowsversion()[1]) > 5)
if len(versionLabelsInPath) == 0:
unzipTarget = currPath
try: # to move existing PsychoPy
os.rename(currPath, "%s-%s" % (currPath, currVer))
undoStr += 'os.rename("%s-%s" %(currPath, currVer),currPath)\n'
except Exception:
if onWin32:
msg = _translate("To upgrade you need to restart the app"
" as admin (Right-click the app and "
"'Run as admin')")
else:
msg = _translate("Could not move existing PsychoPy "
"installation (permissions error?)")
return msg
else: # setuptools-style installation
# generate new target path
unzipTarget = currPath
for thisVersionLabel in versionLabelsInPath:
# remove final slash from the re.findall
pathVersion = thisVersionLabel[:-1]
unzipTarget = unzipTarget.replace(pathVersion,
"PsychoPy-%s" % v)
# find the .pth file that specifies the python dir
# create the new installation directory BEFORE changing pth
# file
nUpdates, newInfo = self.updatePthFile(pathVersion,
"PsychoPy-%s" % v)
if nUpdates == -1: # there was an error (likely permissions)
undoStr += 'self.updatePthFile(unzipTarget, currPath)\n'
exec(undoStr) # undo previous changes
return newInfo
try:
# create the new installation dir AFTER renaming existing dir
os.makedirs(unzipTarget)
undoStr += 'os.remove(%s)\n' % unzipTarget
except Exception: # revert path rename and inform user
exec(undoStr) # undo previous changes
if onWin32:
msg = _translate(
"Right-click the app and 'Run as admin'):\n%s")
else:
msg = _translate("Failed to create directory for new version"
" (permissions error?):\n%s")
return msg % unzipTarget
# do the actual extraction
for name in zfile.namelist(): # for each file within the zip
# check that this file is part of psychopy (not metadata or docs)
if name.count('/psychopy/') < 1:
continue
try:
targetFile = os.path.join(unzipTarget,
name.split('/psychopy/')[1])
targetContainer = os.path.split(targetFile)[0]
if not os.path.isdir(targetContainer):
os.makedirs(targetContainer) # make the containing folder
if targetFile.endswith('/'):
os.makedirs(targetFile) # it's a folder
else:
outfile = open(targetFile, 'wb')
outfile.write(zfile.read(name))
outfile.close()
except Exception:
exec(undoStr) # undo previous changes
logging.error('failed to unzip file: ' + name)
logging.error(sys.exc_info()[0])
info += _translate('Success. \nChanges to PsychoPy will be completed'
' when the application is next run')
self.cancelBtn.SetDefault()
self.installBtn.Disable()
return info
def doAutoInstall(self, v='latest'):
if v == 'latest':
v = self.latest['version']
msg = _translate("Downloading PsychoPy v%s") % v
self.statusMessage.SetLabel(msg)
try:
zipFile, info = self.fetchPsychoPy(v)
except Exception:
msg = _translate('Failed to fetch PsychoPy release.\n'
'Check proxy setting in preferences')
self.statusMessage.SetLabel(msg)
return -1
self.statusMessage.SetLabel(info)
self.Fit()
# got a download - try to install it
info = self.installZipFile(zipFile, v)
return info
def updatePthFile(self, oldName, newName):
"""Searches site-packages for .pth files and replaces any instance of
`oldName` with `newName`, expect names like PsychoPy-1.60.04
"""
from distutils.sysconfig import get_python_lib
siteDir = get_python_lib()
pthFiles = glob.glob(os.path.join(siteDir, '*.pth'))
# sometimes the site-packages dir isn't where the pth files are kept?
enclosingSiteDir = os.path.split(siteDir)[0]
pthFiles.extend(glob.glob(os.path.join(enclosingSiteDir, '*.pth')))
nUpdates = 0 # no paths updated
info = ""
for filename in pthFiles:
lines = open(filename, 'r').readlines()
needSave = False
for lineN, line in enumerate(lines):
if oldName in line:
lines[lineN] = line.replace(oldName, newName)
needSave = True
if needSave:
try:
f = open(filename, 'w')
f.writelines(lines)
f.close()
nUpdates += 1
logging.info('Updated PsychoPy path in %s' % filename)
except Exception:
info += 'Failed to update PsychoPy path in %s' % filename
return -1, info
return nUpdates, info
def sendUsageStats():
"""Sends anonymous, very basic usage stats to psychopy server:
the version of PsychoPy
the system used (platform and version)
the date
"""
v = psychopy.__version__
dateNow = time.strftime("%Y-%m-%d_%H:%M")
miscInfo = ''
# urllib.install_opener(opener)
# check for proxies
if web.proxies is None:
web.setupProxy()
# get platform-specific info
if sys.platform == 'darwin':
OSXver, junk, architecture = platform.mac_ver()
systemInfo = "OSX_%s_%s" % (OSXver, architecture)
elif sys.platform.startswith('linux'):
import distro
systemInfo = '%s_%s_%s' % (
'Linux',
':'.join([x for x in [distro.name(), distro.version(), distro.codename()] if x != '']),
platform.release())
if len(systemInfo) > 30: # if it's too long PHP/SQL fails to store!?
systemInfo = systemInfo[0:30]
elif sys.platform == 'win32':
systemInfo = "win32_v" + platform.version()
else:
systemInfo = platform.system() + platform.release()
u = "https://usage.psychopy.org/submit.php?date=%s&sys=%s&version=%s&misc=%s"
URL = u % (dateNow, systemInfo, v, miscInfo)
try:
req = urllib.request.Request(URL)
page = urllib.request.urlopen(req) # proxies
except Exception:
logging.warning("Couldn't connect to psychopy.org\n"
"Check internet settings (and proxy "
"setting in PsychoPy Preferences.")
| 27,751
|
Python
|
.py
| 590
| 34.632203
| 99
| 0.576893
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,848
|
news.py
|
psychopy_psychopy/psychopy/app/connections/news.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Part of the PsychoPy library
# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd.
# Distributed under the terms of the GNU General Public License (GPL).
import requests
from psychopy import logging, prefs
import wx
from datetime import datetime
newsURL = "https://news.psychopy.org/"
CRITICAL = 40
ANNOUNCE = 30
TIP = 20
JOKE = 10
def getNewsItems(app=None):
url = newsURL + "news_items.json"
try:
resp = requests.get(url, timeout=0.5)
except (requests.ConnectionError, requests.exceptions.ReadTimeout):
return None
if resp.status_code == 200:
try:
items = resp.json()
except Exception as e:
logging.warning("Found, but failed to parse '{}'".format(url))
print(str(e))
else:
logging.debug("failed to connect to '{}'".format(url))
if app:
app.news = items["news"]
return items["news"]
def showNews(app=None, checkPrev=True):
"""Brings up an internal html viewer and show the latest psychopy news
:Returns:
itemShown : bool
"""
if checkPrev:
if app.news:
toShow = None
if 'lastNewsDate' in prefs.appData:
lastNewsDate = prefs.appData['lastNewsDate']
else:
lastNewsDate = ""
for item in app.news:
if item['importance'] >= ANNOUNCE and item['date'] > lastNewsDate:
toShow = item
break
# update prefs lastNewsDate to match JavaScript Date().toISOString()
now = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z'
prefs.appData['lastNewsDate'] = now
prefs.saveAppData()
if not toShow:
return 0
else:
return 0
dlg = wx.Dialog(None, style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER,
size=(800, 400))
browser = wx.html2.WebView.New(dlg)
# do layout
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(browser, 1, wx.EXPAND, 10)
dlg.SetSizer(sizer)
logging.debug(f"loading news page at: {newsURL}")
browser.LoadURL(newsURL)
# browser.Reload()
dlg.Show()
return 1
#
# class NewsFrame(wx.Dialog):
# """This class is used by to open an internal browser for the user stuff
# """
# style =
#
# def __init__(self, parent, style=style, *args, **kwargs):
# # create the dialog
# wx.Dialog.__init__(self, parent, style=style, *args, **kwargs)
# # create browser window for authentication
# self.browser = wx.html2.WebView.New(self)
#
# # do layout
# sizer = wx.BoxSizer(wx.VERTICAL)
# sizer.Add(self.browser, 1, wx.EXPAND, 10)
# self.SetSizer(sizer)
#
# self.browser.LoadURL(newsURL)
# self.Show()
| 2,909
|
Python
|
.py
| 86
| 27.5
| 82
| 0.603209
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,849
|
_localization.py
|
psychopy_psychopy/psychopy/localization/_localization.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Language localization for PsychoPy.
Sets the locale value as a wx languageID (int) and initializes gettext
translation _translate():
from psychopy.app import localization
"""
# Part of the PsychoPy library
# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd.
# Distributed under the terms of the GNU General Public License (GPL).
# Author: Jeremy Gray, July 2014
import gettext
import os
import glob
import io
from psychopy import logging, prefs, constants
import wx
import locale as locale_pkg
def setLocaleWX():
"""Sets up the locale for the wx application. Only call this after the app
has been created and initialised (it is called by PsychoPyApp.OnInit())
:return: wx.Locale object
"""
# set locale for wx app (before splash screen):
encod = locale_pkg.getpreferredencoding(do_setlocale=False)
if locale.IsAvailable(languageID):
wxlocale = wx.Locale(languageID)
else:
wxlocale = wx.Locale(wx.LANGUAGE_DEFAULT)
# Check language layout, and reset to default if RTL
if wxlocale.GetCanonicalName()[:2] in ['ar', 'dv', 'fa', 'ha', 'he', 'ps', 'ur', 'yi']:
wxlocale = wx.Locale(wx.LANGUAGE_DEFAULT)
# wx.Locale on Py2.7/wx3.0 seems to delete the preferred encoding (utf-8)
# Check if that happened and reinstate if needed.
if locale_pkg.getpreferredencoding(do_setlocale=False) == '':
locale_pkg.setlocale(locale_pkg.LC_ALL,
"{}.{}".format(codeFromWxId[languageID], encod))
return wxlocale
# Get a dict of locale aliases from wx.Locale() -- same cross-platform
# (Win 7, Mac 10.9)
# this DOESN'T need the app to be instantiated
locale = wx.Locale()
aliases = {u'English (U.S.)': 'en_US'}
# set defaults because locale.GetLanguageInfo(0) can return None on some
# systems:
wxIdFromCode = {'en_US': wx.LANGUAGE_DEFAULT} # int: 0 default, 2-229
# used in directory names e.g. ja_JP; never JPN ala Windows
codeFromWxId = {wx.LANGUAGE_DEFAULT: 'en_US'}
for i in range(230):
info = locale.GetLanguageInfo(i)
if info:
# mix of forms: ja or ja_JP
aliases[info.Description] = info.CanonicalName
wxIdFromCode[info.CanonicalName] = i
codeFromWxId[i] = info.CanonicalName
# read all known mappings cross-platform from a file:
# get windows 3-letter code (=val) from canonical form (=key); use only
# for setting locale (non-wx)
winmap = {'en_US': 'ENU'}
# descriptive name, if available; 5-letter code if not
locname = {'en_US': u'English (U.S.)'}
reverseMap = {u'English (U.S.)': 'en_US'}
mappings = os.path.join(os.path.dirname(__file__), 'mappings.txt')
with io.open(mappings, 'r', encoding='utf-8-sig') as f:
for line in f.readlines():
try:
# canonical, windows, name-with-spaces
can, win, name = line.strip().split(' ', 2)
except ValueError:
can, win = line.strip().split(' ', 1)
name = can
winmap[can] = win
locname[can] = name
reverseMap[name] = can
# what are the available translations? available languages on the OS?
expr = os.path.join(os.path.dirname(__file__), '..', 'app', 'locale', '*')
available = sorted(map(os.path.basename, glob.glob(expr)))
sysAvail = [str(l) for l in codeFromWxId.values() # installed language packs
if l and locale.IsAvailable(wxIdFromCode[l])]
def getID(lang=None):
"""Get wx ID of language to use for translations:
`lang`, pref, or system default.
`lang` is a 5 char `language_REGION`, eg ja_JP
"""
if lang:
val = lang
else:
try:
val = prefs.app['locale']
except KeyError:
val = locale.GetLocale() # wx.Locale, no encoding
if not val:
val = codeFromWxId[wx.LANGUAGE_DEFAULT]
try:
# todo: try to set wx.Locale here to language
language = wxIdFromCode[val]
except KeyError:
logging.error('locale %s not known to wx.Locale, using default' % val)
language = wx.LANGUAGE_DEFAULT
return language, val
languageID, lang = getID()
# use lang like this:
# import locale -- the non-wx version of locale
#
# if sys.platform.startswith('win'):
# v = winmap[val]
# else: v=val
# locale.setlocale(locale.LC_ALL, (v, 'UTF-8'))
# ideally rewrite the following using wxlocale only:
path = os.path.join(os.path.dirname(__file__), '..', 'app',
'locale', lang, 'LC_MESSAGE') + os.sep
mofile = os.path.join(path, 'messages.mo')
try:
logging.debug("Opening message catalog %s for locale %s" % (mofile, lang))
trans = gettext.GNUTranslations(open(mofile, "rb"))
except IOError:
logging.debug("Locale for '%s' not found. Using default." % lang)
trans = gettext.NullTranslations()
trans.install()
# PsychoPy app uses a nonstandard name _translate (instead of _)
# A dependency overwrites _ somewhere, clobbering use of _ as global:
# __builtins__['_translate'] = _
# del(__builtins__['_']) # idea: force psychopy code to use _translate
# Feb 2016: require modules to explicitly import _translate from localization:
_translate = _ # noqa: F821
# Note that _ is created by gettext, in builtins namespace
del(__builtins__['_'])
# __builtins__['_'] = wx.GetTranslation
# this seems to have no effect, needs more investigation:
# path = os.path.join(os.path.dirname(__file__), '..', 'locale',
# lang, 'LC_MESSAGE') + os.sep
# wxlocale.AddCatalogLookupPathPrefix(path)
| 5,538
|
Python
|
.py
| 132
| 37.439394
| 91
| 0.672673
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,850
|
__init__.py
|
psychopy_psychopy/psychopy/localization/__init__.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Language localization for PsychoPy.
Sets the locale value as a wx languageID (int) and initializes gettext
translation _translate():
from psychopy.app import localization
"""
# Part of the PsychoPy library
# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd.
# Distributed under the terms of the GNU General Public License (GPL).
try:
from ._localization import (
_translate, setLocaleWX, locname, available)
except ModuleNotFoundError:
# if wx doesn't exist we can't translate but most other parts
# of the _localization lib will not be relevant
def _translate(val):
return val
| 694
|
Python
|
.py
| 18
| 35.388889
| 79
| 0.741456
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,851
|
generateTranslationTemplate.py
|
psychopy_psychopy/psychopy/localization/generateTranslationTemplate.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Generate template of translation file (.po) from source tree.
# preferences/generateHints.py is automatically invoked to update
# localization of popup hints on the Preference Dialog.
#
#
import os
import sys
import subprocess
import codecs
import shutil
import git
import babel.messages.frontend
import babel.messages.pofile
import argparse
from psychopy import __version__ as psychopy_version
#
# commandline argument
#
parser = argparse.ArgumentParser(description='usage: generateTranslationTemplate.py [-h] [-c]')
parser.add_argument('-c', '--commit', action='store_true', help='Commit messages.pot if updated.', required=False)
command_args = parser.parse_args()
#
# hints.py must be updated to find new hints and alarts
#
print('Generate hints.py... ', end='')
subprocess.call(['python', 'generateHints.py'], cwd='../preferences')
print('Done.\nGenerate alartmsg.py... ', end='')
subprocess.call(['python', 'generateAlertmsg.py'], cwd='../alerts/alertsCatalogue')
print('Done.')
#
# Extracting messages and generating new template file
#
print('Generating new template file... ', end='')
new_pot_filename = 'messages_new.pot'
current_pot_filename = 'messages.pot'
argv = ['pybabel', '-q', 'extract',
'--input-dirs=..',
'--project=PsychoPy',
'--version='+psychopy_version,
'-k', '_translate',
'-o', new_pot_filename]
babel_frontend = babel.messages.frontend.CommandLineInterface()
babel_frontend.run(argv)
print('Done.')
#
# Comparing new and current pot file.
#
print('Maing a list of message IDs in the new template... ', end='')
new_pot_message_ids = []
current_pot_id = []
untranslated_new = []
with codecs.open(new_pot_filename, 'r', 'utf-8') as fp:
for message in babel.messages.pofile.read_po(fp):
if message.id:
new_pot_message_ids.append(message.id)
if not os.path.exists(current_pot_filename):
# if current pot file doesn't exist, copy it from new pot file.
shutil.copy(new_pot_filename, current_pot_filename)
with codecs.open(current_pot_filename, 'r', 'utf-8') as fp:
for message in babel.messages.pofile.read_po(fp):
if message.id:
current_pot_id.append(message.id)
for id in new_pot_message_ids:
if id not in current_pot_id:
untranslated_new.append(id)
print('Done.')
#
# Output summary
#
print('Checking current PO files...')
n_untranslated_locale = []
for root, dirs, files in os.walk('../app/locale/'):
for file in files:
if file=='messages.po':
po_message_ids = []
n_untranslated = 0
locale_identifier = os.path.basename(os.path.dirname(root))
print('{}: '.format(locale_identifier), end='')
try:
with codecs.open(os.path.join(root, file), 'r', 'utf-8') as fp:
catalog = babel.messages.pofile.read_po(fp)
for message in catalog:
if message.id:
po_message_ids.append(message.id)
# found in the new POT, but not translated
if message.id in new_pot_message_ids and message.string == '':
n_untranslated += 1
for id in new_pot_message_ids:
# not found in the current PO (it must be untranslated)
if id not in po_message_ids:
n_untranslated += 1
n_untranslated_locale.append((locale_identifier, n_untranslated))
except ValueError:
# If date strings in PO file is wrong (e.g. empty string),
# read_po() raises ValueError.
print('Skip.')
else:
print('Ok.')
n_messages = len(new_pot_message_ids)
summary_message = '\nNumber of messages in *.py files: {}\n'.format(n_messages)
summary_message += 'New message(s): {}\n\n'.format(len(untranslated_new))
summary_message += 'Untranslated message(s)\n'
for locale_identifier, n in n_untranslated_locale:
summary_message += ' {}:{:>8} ({:>5.1f}%)\n'.format(locale_identifier, n, 100*n/n_messages)
# output to stdout
sys.stdout.write(summary_message)
#
# Update current pot file only if new strings were found.
#
if len(untranslated_new) > 0:
# replace current pot file with new one.
os.remove(current_pot_filename)
os.rename(new_pot_filename, current_pot_filename)
# add and commit template file if --commit is given
if command_args.commit:
sys.stdout.write('\nCommit messages.pot...\n')
repo = git.Repo('../../')
pot_file_path = 'psychopy/localization/' + current_pot_filename
print(pot_file_path)
print([item.a_path for item in repo.index.diff(None)])
if pot_file_path in repo.untracked_files or pot_file_path in [item.a_path for item in repo.index.diff(None)]:
repo.index.add([pot_file_path])
repo.index.commit('ENH: Translation template is updated')
else:
# keep current pot file and remove new one.
os.remove(new_pot_filename)
| 5,157
|
Python
|
.py
| 128
| 33.671875
| 117
| 0.64791
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,852
|
win32.py
|
psychopy_psychopy/psychopy/platform_specific/win32.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Part of the PsychoPy library
# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd.
# Distributed under the terms of the GNU General Public License (GPL).
# These are correct for win32, not sure about 64bit versions
# DEFINE NORMAL_PRIORITY_CLASS 32
# DEFINE IDLE_PRIORITY_CLASS 64
# DEFINE HIGH_PRIORITY_CLASS 128
# DEFINE REALTIME_PRIORITY_CLASS 1600
# define THREAD_PRIORITY_IDLE -15
# define THREAD_PRIORITY_LOWEST -2
# define THREAD_PRIORITY_BELOW_NORMAL -1
# define THREAD_PRIORITY_NORMAL 0
# define THREAD_PRIORITY_ABOVE_NORMAL 1
# define THREAD_PRIORITY_HIGHEST 2
# define THREAD_PRIORITY_TIME_CRITICAL 15
try:
from ctypes import windll
from ctypes.wintypes import HANDLE, DWORD, BOOL, INT, UINT
windll = windll.kernel32
importWindllFailed = False
except Exception:
importWindllFailed = True
from .. import logging
logging.debug("rush() not available because import windll "
"failed in psychopy/platform_specific/win32.py")
FALSE = 0
PROCESS_SET_INFORMATION = 0x0200
PROCESS_QUERY_INFORMATION = 0x0400
NORMAL_PRIORITY_CLASS = 32
HIGH_PRIORITY_CLASS = 128
REALTIME_PRIORITY_CLASS = 256
THREAD_PRIORITY_NORMAL = 0
THREAD_PRIORITY_HIGHEST = 2
THREAD_PRIORITY_TIME_CRITICAL = 15
# sleep signals
ES_CONTINUOUS = 0x80000000
ES_DISPLAY_REQUIRED = 0x00000002
ES_SYSTEM_REQUIRED = 0x00000001
GetCurrentProcessId = windll.GetCurrentProcessId
GetCurrentProcessId.restype = HANDLE
OpenProcess = windll.OpenProcess
OpenProcess.restype = HANDLE
OpenProcess.argtypes = (DWORD, BOOL, DWORD)
GetCurrentThread = windll.GetCurrentThread
GetCurrentThread.restype = HANDLE
SetPriorityClass = windll.SetPriorityClass
SetPriorityClass.restype = BOOL
SetPriorityClass.argtypes = (HANDLE, DWORD)
SetThreadPriority = windll.SetThreadPriority
SetThreadPriority.restype = BOOL
SetThreadPriority.argtypes = (HANDLE, INT)
SetThreadExecutionState = windll.SetThreadExecutionState
SetThreadExecutionState.restype = UINT
SetThreadExecutionState.argtypes = (UINT,)
def rush(enable=True, realtime=False):
"""Raise the priority of the current thread/process.
Set with rush(True) or rush(False)
Beware and don't take priority until after debugging your code
and ensuring you have a way out (e.g. an escape sequence of
keys within the display loop). Otherwise you could end up locked
out and having to reboot!
"""
if importWindllFailed:
return False
pr_rights = PROCESS_QUERY_INFORMATION | PROCESS_SET_INFORMATION
pr = windll.OpenProcess(pr_rights, FALSE, GetCurrentProcessId())
thr = windll.GetCurrentThread()
# In this context, non-zero is success and zero is error
out = 1
if enable:
if not realtime:
out = SetPriorityClass(pr, HIGH_PRIORITY_CLASS) != 0
out &= SetThreadPriority(thr, THREAD_PRIORITY_HIGHEST) != 0
else:
out = SetPriorityClass(pr, REALTIME_PRIORITY_CLASS) != 0
out &= SetThreadPriority(thr, THREAD_PRIORITY_TIME_CRITICAL) != 0
else:
out = SetPriorityClass(pr, NORMAL_PRIORITY_CLASS) != 0
out &= SetThreadPriority(thr, THREAD_PRIORITY_NORMAL) != 0
return out != 0
def waitForVBL():
"""Not implemented on win32 yet.
"""
pass
def sendStayAwake():
"""Sends a signal to your system to indicate that the computer is
in use and should not sleep. This should be sent periodically, but
PsychoPy will send the signal by default on each screen refresh.
Added: v1.79.00
Currently supported on: windows, macOS.
"""
code = ES_SYSTEM_REQUIRED | ES_DISPLAY_REQUIRED
success = SetThreadExecutionState(code)
return success
| 3,786
|
Python
|
.py
| 96
| 35.583333
| 79
| 0.745767
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,853
|
linux.py
|
psychopy_psychopy/psychopy/platform_specific/linux.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Part of the PsychoPy library
# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd.
# Distributed under the terms of the GNU General Public License (GPL).
"""Placeholder for adding c (or ctypes) extensions to PsychoPy on linux.
"""
from psychopy import logging
import sys
try:
import ctypes
import ctypes.util
c = ctypes.cdll.LoadLibrary(ctypes.util.find_library('c'))
importCtypesFailed = False
except Exception:
importCtypesFailed = True
logging.debug("rush() not available because import ctypes, ctypes.util "
"failed in psychopy/platform_specific/linux.py")
# FIFO and RR(round-robin) allow highest priority for realtime
SCHED_NORMAL = 0
SCHED_FIFO = 1
SCHED_RR = 2
SCHED_BATCH = 3
if not importCtypesFailed:
class _SchedParams(ctypes.Structure):
_fields_ = [('sched_priority', ctypes.c_int)]
# Text that appears at the top of the dialog with provides instructions to the
# user.
_introStr = (
u"Could not set the thread priority with sched_setscheduler.\n"
u"For optimal performance on Linux, Psychtoolbox requires additional\n"
u"configuration changes to be made to this system by entering the\n"
u"following commands into your terminal:\n\n{cmdstr}"
)
# config file path
_confPath = u"/etc/security/limits.d/99-psychopylimits.conf"
# these are the commands we want the user to run in their terminal
_cmdStr = (
u"sudo groupadd --force psychopy\n\n"
u"sudo usermod -a -G psychopy $USER\n\n"
u"sudo gedit {fpath}\n"
u"@psychopy - nice -20\n"
u"@psychopy - rtprio 50\n"
u"@psychopy - memlock unlimited")
warnMax = _introStr.format(cmdstr=_cmdStr.format(fpath=_confPath))
def rush(value=True, realtime=False):
"""Raise the priority of the current thread/process using
- sched_setscheduler
realtime arg is not used in Linux implementation.
NB for rush() to work on Linux requires that the script is run by
a user with sufficient permissions to raise the priority of a process.
In PsychoPy, we suggest adding the user to a group with these permissions.
If this function returns `False`, see the log for instructions on how
to set up such a group.
"""
if importCtypesFailed:
return False
schedParams = _SchedParams()
sched = SCHED_RR if value else SCHED_NORMAL
schedParams.sched_priority = c.sched_get_priority_min(sched)
err = c.sched_setscheduler(0, sched, ctypes.byref(schedParams))
if err == -1:
logging.warning(warnMax)
return not err
| 2,604
|
Python
|
.py
| 64
| 36.703125
| 79
| 0.728532
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,854
|
__init__.py
|
psychopy_psychopy/psychopy/platform_specific/__init__.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Platform specific extensions (using ctypes)"""
# Part of the PsychoPy library
# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd.
# Distributed under the terms of the GNU General Public License (GPL).
import sys
import platform
# dummy methods should be overridden by imports below if they exist
def rush(value=False, realtime=False):
"""
"""
# dummy method.
return False
def waitForVBL():
"""DEPRECATED: waiting for a VBL is handled by the screen flip
"""
return False
def sendStayAwake():
"""Sends a signal to your system to indicate that the computer is
in use and should not sleep. This should be sent periodically,
but PsychoPy will send the signal by default on each screen refresh.
Added: v1.79.00.
Currently supported on: windows, macOS
"""
return False
# NB includes vista and 7 (but not sure about vista64)
if sys.platform == 'win32':
from .win32 import * # pylint: disable=W0401
elif sys.platform == 'darwin':
from .darwin import * # pylint: disable=W0401
elif sys.platform.startswith('linux'): # normally 'linux2'
from .linux import * # pylint: disable=W0401
| 1,233
|
Python
|
.py
| 33
| 33.909091
| 79
| 0.719461
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,855
|
darwin.py
|
psychopy_psychopy/psychopy/platform_specific/darwin.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Part of the PsychoPy library
# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd.
# Distributed under the terms of the GNU General Public License (GPL).
from psychopy import logging
try:
import ctypes
import ctypes.util
importCtypesFailed = False
except Exception:
importCtypesFailed = True
logging.debug("rush() not available because import ctypes "
"failed in contrib/darwin.py")
# constants
KERN_SUCCESS = 0
kCGLCPSwapInterval = ctypes.c_int(222)
# these defined in thread_policy.h from apple (googleable)
THREAD_STANDARD_POLICY = ctypes.c_int(1)
THREAD_STANDARD_POLICY_COUNT = ctypes.c_int(0)
THREAD_EXTENDED_POLICY = ctypes.c_int(1)
THREAD_EXTENDED_POLICY_COUNT = ctypes.c_int(1)
THREAD_TIME_CONSTRAINT_POLICY = ctypes.c_int(2)
THREAD_TIME_CONSTRAINT_POLICY_COUNT = ctypes.c_int(4)
# these were found in pyglet/window/carbon/constants thanks to Alex Holkner
kCFStringEncodingASCII = 0x0600
kCFStringEncodingUnicode = 0x0100
kCFStringEncodingUTF8 = 0x08000100
kCFNumberLongType = 10
# some data types these can be found in various *.defs
CGDirectDisplayID = ctypes.c_void_p
CGDisplayCount = ctypes.c_uint32
CGTableCount = ctypes.c_uint32
CGDisplayCoord = ctypes.c_int32
CGByteValue = ctypes.c_ubyte
CGOpenGLDisplayMask = ctypes.c_uint32
CGRefreshRate = ctypes.c_double
CGCaptureOptions = ctypes.c_uint32
integer_t = ctypes.c_int32
natural_t = ctypes.c_uint32
thread_flavor_t = ctypes.c_int32 # in mach_types.defs
thread_info_t = integer_t * 12 # in mach_types.defs
thread_policy_flavor_t = natural_t # in mach_types.defs
thread_policy_t = integer_t * 16 # in mach_types.defs
# for use with sysctl()
CTL_HW = ctypes.c_int(6) # /* generic cpu/io */
HW_BUS_FREQ = ctypes.c_int(14)
# could use carbon instead?
cocoa = ctypes.cdll.LoadLibrary(ctypes.util.find_library("Cocoa"))
# not needed - all the functions seem to be in cocoa:
# mach = ctypes.cdll.LoadLibrary(ctypes.util.find_library("libm"))
# ogl = ctypes.cdll.LoadLibrary(ctypes.util.find_library("OpenGL"))
def _create_cfstring(text):
# some string parameters need to be converted to SFStrings
if importCtypesFailed:
return False
return cocoa.CFStringCreateWithCString(ctypes.c_void_p(),
text.encode('utf8'),
kCFStringEncodingUTF8)
if importCtypesFailed == False:
class _timeConstraintThreadPolicy(ctypes.Structure):
_fields_ = [('period', ctypes.c_uint), # HZ/160
('computation', ctypes.c_uint), # HZ/3300
('constrain', ctypes.c_uint), # HZ/2200
('preemptible', ctypes.c_int)]
def syncSwapBuffers(n):
"""syncSwapBuffers(n)
if n==1 then buffers will sync, otherwise sync will be turned off.
"""
try:
# set v to 1 to enable vsync, 0 to disable vsync
v = ctypes.c_int(n)
# this is the parameter index?!
cocoa.CGLSetParameter(cocoa.CGLGetCurrentContext(),
kCGLCPSwapInterval, ctypes.pointer(v))
except Exception:
logging.warning("Unable to set vsync mode. Using driver defaults")
def getBusFreq():
"""Get the frequency of the system bus (HZ).
"""
if importCtypesFailed:
return False
mib = (ctypes.c_int * 2)(CTL_HW, HW_BUS_FREQ)
val = ctypes.c_int()
intSize = ctypes.c_int(ctypes.sizeof(val))
cocoa.sysctl(ctypes.byref(mib), 2, ctypes.byref(
val), ctypes.byref(intSize), 0, 0)
return val.value
def rush(value=True, realtime=False):
"""Raise the priority of the current thread / process.
Set with rush(True) or rush(False).
realtime arg is not used by osx implementation.
Beware and don't take priority until after debugging your code
and ensuring you have a way out (e.g. an escape sequence of
keys within the display loop). Otherwise you could end up locked
out and having to reboot!
"""
if importCtypesFailed:
return False
if value:
bus = getBusFreq()
extendedPolicy = _timeConstraintThreadPolicy()
# number of cycles in hz (make higher than frame rate)
extendedPolicy.period = bus // 160
extendedPolicy.computation = bus // 320 # half of that period
# max period that they should be carried out in
extendedPolicy.constrain = bus // 640
extendedPolicy.preemptible = 1
extendedPolicy = getThreadPolicy(getDefault=True,
flavour=THREAD_TIME_CONSTRAINT_POLICY)
err = cocoa.thread_policy_set(cocoa.mach_thread_self(),
THREAD_TIME_CONSTRAINT_POLICY,
# send the address of the struct
ctypes.byref(extendedPolicy),
THREAD_TIME_CONSTRAINT_POLICY_COUNT)
if err != KERN_SUCCESS:
logging.error(
'Failed to set darwin thread policy, with thread_policy_set')
else:
logging.info('Successfully set darwin thread to realtime')
else:
# revert to default policy
extendedPolicy = getThreadPolicy(getDefault=True,
flavour=THREAD_STANDARD_POLICY)
err = cocoa.thread_policy_set(cocoa.mach_thread_self(),
THREAD_STANDARD_POLICY,
# send the address of the struct
ctypes.byref(extendedPolicy),
THREAD_STANDARD_POLICY_COUNT)
return err == KERN_SUCCESS
def getThreadPolicy(getDefault, flavour):
"""Retrieve the current (or default) thread policy.
`getDefault` should be True or False.
`flavour` should be 1 (standard) or 2 (realtime). Not implemented.
Returns a ctypes struct with fields:
.period
.computation
.constrain
.preemptible
See https://docs.huihoo.com/darwin/kernel-programming-guide/scheduler/chapter_8_section_4.html
"""
if importCtypesFailed:
return False
extendedPolicy = _timeConstraintThreadPolicy() # to store the infos
# we want to retrieve actual policy or the default
getDefault = ctypes.c_int(getDefault)
err = cocoa.thread_policy_get(cocoa.mach_thread_self(),
THREAD_TIME_CONSTRAINT_POLICY,
# send the address of the policy struct
ctypes.byref(extendedPolicy),
ctypes.byref(
THREAD_TIME_CONSTRAINT_POLICY_COUNT),
ctypes.byref(getDefault))
return extendedPolicy
def getRush():
"""Determine whether or not we are in rush mode. Returns True/False.
"""
if importCtypesFailed:
return None
policy = getThreadPolicy(getDefault=False,
flavour=THREAD_TIME_CONSTRAINT_POLICY)
default = getThreadPolicy(getDefault=True,
flavour=THREAD_TIME_CONSTRAINT_POLICY)
# by default this is zero, so not zero means we've changed it
return policy.period != default.period
def getScreens():
"""Get a list of display IDs from cocoa.
"""
if importCtypesFailed:
return False
count = CGDisplayCount()
cocoa.CGGetActiveDisplayList(0, None, ctypes.byref(count))
displays = (CGDirectDisplayID * count.value)()
cocoa.CGGetActiveDisplayList(count.value, displays, ctypes.byref(count))
return [id for id in displays] # python list
def getScreen(screen):
"""Select `screen` from getScreens(), or raise if bad value.
"""
screens = getScreens()
if screen > len(screens) - 1:
msg = "Requested refresh rate of screen %i, but only have %i screens."
raise IndexError(msg % (screen, len(screens)))
return getScreens()[screen]
def getRefreshRate(screen=0):
"""Return the refresh rate of the given screen (typically screen = 0 or 1)
NB. If two screens are connected with different refresh rates then the
rate at which we draw may not reflect the refresh rate of the monitor.
"""
if importCtypesFailed:
return False
scrID = getScreen(screen)
mode = cocoa.CGDisplayCurrentMode(scrID)
refreshCF = cocoa.CFDictionaryGetValue(mode,
_create_cfstring('RefreshRate'))
refresh = ctypes.c_long()
cocoa.CFNumberGetValue(refreshCF, kCFNumberLongType,
ctypes.byref(refresh))
if refresh.value == 0:
return 60 # probably an LCD
else:
return refresh.value
def getScreenSizePix(screen=0):
"""Return the height and width (in pixels) of the given screen.
(typically screen is 0 or 1) If no screen is given then screen 0 is used.
h,w = getScreenSizePix()
"""
if importCtypesFailed:
return False
scrID = getScreen(screen)
h = cocoa.CGDisplayPixelsHigh(scrID)
w = cocoa.CGDisplayPixelsWide(scrID)
return [h, w]
def waitForVBL(screen=0, nFrames=1):
"""DEPRECATED: the code for doing this is now smaller and cross-platform
so is included in visual.Window.flip()
This version is based on detecting the display beam position. It may give
unpredictable results for an LCD.
"""
if importCtypesFailed:
return False
scrID = getScreen(screen)
framePeriod = 1.0 / getRefreshRate(screen)
if screen > 0: # got multiple screens, check if they have same rate
mainFramePeriod = 1.0 / getRefreshRate(0)
if mainFramePeriod != framePeriod:
# CGDisplayBeamPosition is unpredictable in this case - usually
# synced to the first monitor, but maybe better if 2 gfx cards?
msg = ("You are trying to wait for blanking on a secondary "
"monitor that has a different refresh rate to your "
"primary monitor. This is not recommended (likely to "
"reduce your frame rate to the primary monitor).")
logging.warning(msg)
# when we're in a VBL the current beam position is greater than
# the screen height (for up to ~30 lines)
top = getScreenSizePix(screen)[0]
if cocoa.CGDisplayBeamPosition(scrID) > top:
nFrames += 1 # we're in a VBL already, wait for one more
while nFrames > 0:
beamPos = cocoa.CGDisplayBeamPosition(scrID) # get current pos
# choose how long to wait
# we have at least 5ms to go so can wait for 1ms
while framePeriod * (top - beamPos) / top > 0.005:
# time.sleep(0.0001)#actually it seems that time.sleep() waits too
# long on macOS
beamPos = cocoa.CGDisplayBeamPosition(scrID) # get current pos
# now near top so poll continuously
while beamPos < top:
beamPos = cocoa.CGDisplayBeamPosition(scrID) # get current pos
# if this was not the last frame, then wait until start of next
# frame before continuing so that we don't detect the VBL again.
# If this was the last frame then get back to script asap
if nFrames > 1:
while beamPos >= top:
beamPos = cocoa.CGDisplayBeamPosition(scrID)
nFrames -= 1
def sendStayAwake():
"""Sends a signal to your system to indicate that the computer is in
use and should not sleep. This should be sent periodically, but
PsychoPy will send the signal by default on each screen refresh.
Added: v1.79.00
Currently supported on: windows, macOS
"""
cocoa.UpdateSystemActivity(0)
#beamPos = cocoa.CGDisplayBeamPosition(1)
# while beamPos<=1000:
# beamPos = cocoa.CGDisplayBeamPosition(1)
# print(beamPos)
# first=last=time.time()
# print(getRefreshRate(1))
# for nFrames in range(20):
# waitForVBL(1, nFrames=1)
# time.sleep(0.005)
# this=time.time()
# print(this-first, this-last, 1/(this-last))
# last=this
# rush()
| 12,201
|
Python
|
.py
| 276
| 35.757246
| 98
| 0.652632
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,856
|
util.py
|
psychopy_psychopy/psychopy/plugins/util.py
|
import importlib.metadata
def getEntryPoints(module, submodules=True, flatten=True):
"""
Get entry points which target a particular module.
Parameters
----------
module : str
Import string for the target module (e.g.
`"psychopy.iohub.devices"`)
submodules : bool, optional
If True, will also get entry points which target a
submodule of the given module. By default True.
flatten : bool, optional
If True, will return a flat list of entry points. If
False, will return a dict arranged by target group. By
default True.
"""
# start off with a blank list/dict
entryPointsList = []
entryPointsDict = {}
# iterate through groups
for group, points in importlib.metadata.entry_points().items():
# does this group correspond to the requested module?
if submodules:
targeted = group.startswith(module)
else:
targeted = group == module
# if group is targeted, add entry points
if targeted:
entryPointsList += points
entryPointsDict[group] = points
# return list or dict according to flatten arg
if flatten:
return entryPointsList
else:
return entryPointsDict
| 1,277
|
Python
|
.py
| 36
| 28.166667
| 67
| 0.653473
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,857
|
__init__.py
|
psychopy_psychopy/psychopy/plugins/__init__.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Part of the PsychoPy library
# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd.
# Distributed under the terms of the GNU General Public License (GPL).
"""Utilities for extending PsychoPy with plugins."""
__all__ = [
'loadPlugin',
'listPlugins',
'installPlugin',
'computeChecksum',
'startUpPlugins',
'pluginMetadata',
'pluginEntryPoints',
'scanPlugins',
'requirePlugin',
'isPluginLoaded',
'isStartUpPlugin',
'activatePlugins',
'discoverModuleClasses',
'getBundleInstallTarget',
'refreshBundlePaths'
]
import os
from pathlib import Path
import sys
import inspect
import collections
import hashlib
import importlib, importlib.metadata
from psychopy import logging
from psychopy.preferences import prefs
# Configure the environment to use our custom site-packages location for
# user-installed packages (i.e. plugins).
USER_PACKAGES_PATH = str(prefs.paths['userPackages'])
# check if we're in a virtual environment or not
inVenv = hasattr(sys, 'real_prefix') or sys.prefix != sys.base_prefix
# add the plugins folder to the path
if not inVenv and USER_PACKAGES_PATH not in sys.path:
sys.path.insert(0, USER_PACKAGES_PATH) # add to path
# Keep track of plugins that have been loaded. Keys are plugin names and values
# are their entry point mappings.
_loaded_plugins_ = collections.OrderedDict() # use OrderedDict for Py2 compatibility
# Entry points for all plugins installed on the system, this is populated by
# calling `scanPlugins`. We are caching entry points to avoid having to rescan
# packages for them.
_installed_plugins_ = collections.OrderedDict()
# Keep track of plugins that failed to load here
_failed_plugins_ = []
# ------------------------------------------------------------------------------
# Functions
#
def getEntryPointGroup(group, subgroups=False):
"""
Get all entry points which target a specific group.
Parameters
----------
group : str
Group to look for (e.g. "psychopy.experiment.components" for plugin Components)
subgroups : bool
If True, then will also look for subgroups (e.g. "psychopy.experiment" will also return
entry points for "psychopy.experiment.components")
Returns
-------
list[importlib.metadata.Entrypoint]
List of EntryPoint objects for the given group
"""
# start off with no entry points or sections
entryPoints = []
if subgroups:
# if searching subgroups, iterate through entry point groups
for thisGroup, eps in importlib.metadata.entry_points().items():
# get entry points within matching group
if thisGroup.startswith(group):
# add to list of all entry points
entryPoints += eps
else:
# otherwise, just get the requested group
entryPoints += importlib.metadata.entry_points().get(group, [])
return entryPoints
def resolveObjectFromName(name, basename=None, resolve=True, error=True):
"""Get an object within a module's namespace using a fully-qualified or
relative dotted name.
This function is mainly used to get objects associated with entry point
groups, so entry points can be assigned to them. It traverses through
objects along `name` until it reaches the end, then returns a reference to
that object.
You can also use this function to dynamically import modules and fully
realize target names without needing to call ``import`` on intermediate
modules. For instance, by calling the following::
Window = resolveObjectFromName('psychopy.visual.Window')
The function will first import `psychopy.visual` then get a reference to the
unbound `Window` class within it and assign it to `Window`.
Parameters
----------
name : str
Fully-qualified or relative name to the object (eg.
`psychopy.visual.Window` or `.Window`). If name is relative, `basename`
must be specified.
basename : str, ModuleType or None
If `name` is relative (starts with '.'), `basename` should be the
`__name__` of the module or reference to the module itself `name` is
relative to. Leave `None` if `name` is already fully qualified.
resolve : bool
If `resolve=True`, any name encountered along the way that isn't present
will be assumed to be a module and imported. This guarantees the target
object is fully-realized and reachable if the target is valid. If
`False`, this function will fail if the `name` is not reachable and
raise an error or return `None` if `error=False`.
error : bool
Raise an error if an object is not reachable. If `False`, this function
will return `None` instead and suppress the error. This may be useful in
cases where having access to the target object is a "soft" requirement
and the program can still operate without it.
Returns
-------
object
Object referred to by the name. Returns `None` if the object is not
reachable and `error=False`.
Raises
------
ModuleNotFoundError
The base module the FQN is referring to has not been imported.
NameError
The provided name does not point to a valid object.
ValueError
A relative name was given to `name` but `basename` was not specified.
Examples
--------
Get a reference to the `psychopy.visual.Window` class (will import `visual`
in doing so)::
Window = resolveObjectFromName('psychopy.visual.Window')
Get the `Window` class if `name` is relative to `basename`::
import psychopy.visual as visual
Window = resolveObjectFromName('.Window', visual)
Check if an object exists::
Window = resolveObjectFromName(
'psychopy.visual.Window',
resolve=False, # False since we don't want to import anything
error=False) # suppress error, makes function return None
if Window is None:
print('Window has not been imported yet!')
"""
# make sure a basename is given if relative
if name.startswith('.') and basename is None:
raise ValueError('`name` specifies a relative name but `basename` is '
'not specified.')
# if basename is a module object
if inspect.ismodule(basename):
basename = basename.__name__
# get fqn and split
fqn = (basename + name if basename is not None else name).split(".")
# get the object the fqn refers to
try:
objref = sys.modules[fqn[0]] # base name
except KeyError:
raise ModuleNotFoundError(
'Base module cannot be found, has it been imported yet?')
# walk through the FQN to get the object it refers to
path = fqn[0]
for attr in fqn[1:]:
path += '.' + attr
if not hasattr(objref, attr):
# try importing the module
if resolve:
try:
importlib.import_module(path)
except ImportError:
if not error: # return if suppressing error
return None
raise NameError(
"Specified `name` does not reference a valid object or "
"is unreachable.")
else:
if not error: # return None if we want to suppress errors
return None
raise NameError(
"Specified `name` does not reference a valid object or is "
"unreachable.")
objref = getattr(objref, attr)
return objref
def computeChecksum(fpath, method='sha256', writeOut=None):
"""Compute the checksum hash/key for a given package.
Authors of PsychoPy plugins can use this function to compute a checksum
hash and users can use it to check the integrity of their packages.
Parameters
----------
fpath : str
Path to the plugin package or file.
method : str
Hashing method to use, values are 'md5' or 'sha256'. Default is
'sha256'.
writeOut : str
Path to a text file to write checksum data to. If the file exists, the
data will be written as a line at the end of the file.
Returns
-------
str
Checksum hash digested to hexadecimal format.
Examples
--------
Compute a checksum for a package and write it to a file::
with open('checksum.txt', 'w') as f:
f.write(computeChecksum(
'/path/to/plugin/psychopy_plugin-1.0-py3.6.egg'))
"""
methodObj = {'md5': hashlib.md5,
'sha256': hashlib.sha256}
hashobj = methodObj[method]()
with open(fpath, "rb") as f:
chunk = f.read(4096)
while chunk != b"":
chunk = f.read(4096)
hashobj.update(chunk)
checksumStr = hashobj.hexdigest()
if writeOut is not None:
with open(writeOut, 'a') as f:
f.write('\n' + checksumStr)
return checksumStr
def getBundleInstallTarget(projectName):
"""Get the path to a bundle given a package name.
This returns the installation path for a bundle with the specified project
name. This is used to either generate installation target directories.
Parameters
----------
projectName : str
Project name for the main package within the bundle.
Returns
-------
str
Path to the bundle with a given project name. Project name is converted
to a 'safe name'.
"""
return os.path.join(
prefs.paths['packages'], projectName)
def refreshBundlePaths():
"""Find package bundles within the PsychoPy user plugin directory.
This finds subdirectories inside the PsychoPy user package directory
containing distributions, then add them to the search path for packages.
These are referred to as 'bundles' since each subdirectory contains the
plugin package code and all extra dependencies related to it. This allows
plugins to be uninstalled cleanly along with all their supporting libraries.
A directory is considered a bundle if it contains a package at the top-level
whose project name matches the name of the directory. If not, the directory
will not be appended to `sys.path`.
This is called implicitly when :func:`scanPlugins()` is called.
Returns
-------
list
List of bundle names found in the plugin directory which have been
added to `sys.path`.
"""
pluginBaseDir = prefs.paths['packages'] # directory packages are in
foundBundles = []
pluginTopLevelDirs = os.listdir(pluginBaseDir)
for pluginDir in pluginTopLevelDirs:
fullPath = os.path.join(pluginBaseDir, pluginDir)
allDists = importlib.metadata.distributions(path=pluginDir)
if not allDists: # no packages found, move on
continue
# does the sud-directory contain an appropriately named distribution?
validDist = False
for dist in allDists:
if sys.version.startswith("3.8"):
distName = dist.metadata['name']
else:
distName = dist.name
validDist = validDist or distName == pluginDir
if not validDist:
continue
# add to path if the subdir has a valid distribution in it
if fullPath not in sys.path:
sys.path.append(fullPath) # add to path
foundBundles.append(pluginDir)
# refresh package index since the working set is now stale
scanPlugins()
return foundBundles
def getPluginConfigPath(plugin):
"""Get the path to the configuration file for a plugin.
This function returns the path to folder alloted to a plugin for storing
configuration files. This is useful for plugins that require user settings
to be stored in a file.
Parameters
----------
plugin : str
Name of the plugin package to get the configuration file for.
Returns
-------
str
Path to the configuration file for the plugin.
"""
# check if the plugin is installed first
if plugin not in _installed_plugins_:
raise ValueError("Plugin `{}` is not installed.".format(plugin))
# get the config directory
import pathlib
configDir = pathlib.Path(prefs.paths['configs']) / 'plugins' / plugin
configDir.mkdir(parents=True, exist_ok=True)
return configDir
def installPlugin(package, local=True, upgrade=False, forceReinstall=False,
noDeps=False):
"""Install a plugin package.
Parameters
----------
package : str
Name or path to distribution of the plugin package to install.
local : bool
If `True`, install the package locally to the PsychoPy user plugin
directory.
upgrade : bool
Upgrade the specified package to the newest available version.
forceReinstall : bool
If `True`, the package and all it's dependencies will be reinstalled if
they are present in the current distribution.
noDeps : bool
Don't install dependencies if `True`.
"""
# determine where to install the package
installWhere = USER_PACKAGES_PATH if local else None
import psychopy.tools.pkgtools as pkgtools
pkgtools.installPackage(
package,
target=installWhere,
upgrade=upgrade,
forceReinstall=forceReinstall,
noDeps=noDeps)
def scanPlugins():
"""Scan the system for installed plugins.
This function scans installed packages for the current Python environment
and looks for ones that specify PsychoPy entry points in their metadata.
Afterwards, you can call :func:`listPlugins()` to list them and
`loadPlugin()` to load them into the current session. This function is
called automatically when PsychoPy starts, so you do not need to call this
unless packages have been added since the session began.
Returns
-------
int
Number of plugins found during the scan. Calling `listPlugins()` will
return the names of the found plugins.
"""
global _installed_plugins_
_installed_plugins_ = {} # clear the cache
# iterate through installed packages
for dist in importlib.metadata.distributions(path=sys.path + [USER_PACKAGES_PATH]):
# map all entry points
for ep in dist.entry_points:
# skip entry points which don't target PsychoPy
if not ep.group.startswith("psychopy"):
continue
# make sure we have an entry for this distribution
if sys.version.startswith("3.8"):
distName = dist.metadata['name']
else:
distName = dist.name
if distName not in _installed_plugins_:
_installed_plugins_[distName] = {}
# make sure we have an entry for this group
if ep.group not in _installed_plugins_[distName]:
_installed_plugins_[distName][ep.group] = {}
# map entry point
_installed_plugins_[distName][ep.group][ep.name] = ep
return len(_installed_plugins_)
def listPlugins(which='all'):
"""Get a list of installed or loaded PsychoPy plugins.
This function lists either all potential plugin packages installed on the
system, those registered to be loaded automatically when PsychoPy starts, or
those that have been previously loaded successfully this session.
Parameters
----------
which : str
Category to list plugins. If 'all', all plugins installed on the system
will be listed, whether they have been loaded or not. If 'loaded', only
plugins that have been previously loaded successfully this session will
be listed. If 'startup', plugins registered to be loaded when a PsychoPy
session starts will be listed, whether or not they have been loaded this
session. If 'unloaded', plugins that have not been loaded but are
installed will be listed. If 'failed', returns a list of plugin names
that attempted to load this session but failed for some reason.
Returns
-------
list
Names of PsychoPy related plugins as strings. You can load all installed
plugins by passing list elements to `loadPlugin`.
See Also
--------
loadPlugin : Load a plugin into the current session.
Examples
--------
Load all plugins installed on the system into the current session (assumes
all plugins don't require any additional arguments passed to them)::
for plugin in plugins.listPlugins():
plugins.loadPlugin(plugin)
If certain plugins take arguments, you can do this give specific arguments
when loading all plugins::
pluginArgs = {'some-plugin': (('someArg',), {'setup': True, 'spam': 10})}
for plugin in plugins.listPlugins():
try:
args, kwargs = pluginArgs[plugin]
plugins.loadPlugin(plugin, *args, **kwargs)
except KeyError:
plugins.loadPlugin(plugin)
Check if a plugin package named `plugin-test` is installed on the system and
has entry points into PsychoPy::
if 'plugin-test' in plugins.listPlugins():
print("Plugin installed!")
Check if all plugins registered to be loaded on startup are currently
active::
if not all([p in listPlugins('loaded') for p in listPlugins('startup')]):
print('Please restart your PsychoPy session for plugins to take effect.')
"""
if which not in ('all', 'startup', 'loaded', 'unloaded', 'failed'):
raise ValueError("Invalid value specified to argument `which`.")
if which == 'loaded': # only list plugins we have already loaded
return list(_loaded_plugins_.keys())
elif which == 'startup':
return list(prefs.general['startUpPlugins']) # copy this
elif which == 'unloaded':
return [p for p in listPlugins('all') if p in listPlugins('loaded')]
elif which == 'failed':
return list(_failed_plugins_) # copy
else:
return list(_installed_plugins_.keys())
def isPluginLoaded(plugin):
"""Check if a plugin has been previously loaded successfully by a
:func:`loadPlugin` call.
Parameters
----------
plugin : str
Name of the plugin package to check if loaded. This usually refers to
the package or project name.
Returns
-------
bool
`True` if a plugin was successfully loaded and active, else `False`.
See Also
--------
loadPlugin : Load a plugin into the current session.
"""
return plugin in listPlugins(which='loaded')
def isStartUpPlugin(plugin):
"""Check if a plugin is registered to be loaded when PsychoPy starts.
Parameters
----------
plugin : str
Name of the plugin package to check. This usually refers to the package
or project name.
Returns
-------
bool
`True` if a plugin is registered to be loaded when a PsychoPy session
starts, else `False`.
Examples
--------
Check if a plugin was loaded successfully at startup::
pluginName = 'psychopy-plugin'
if isStartUpPlugin(pluginName) and isPluginLoaded(pluginName):
print('Plugin successfully loaded at startup.')
"""
return plugin in listPlugins(which='startup')
def loadPlugin(plugin):
"""Load a plugin to extend PsychoPy.
Plugins are packages which extend upon PsychoPy's existing functionality by
dynamically importing code at runtime, without modifying the existing
installation files. Plugins create or redefine objects in the namespaces
of modules (eg. `psychopy.visual`) and unbound classes, allowing them to be
used as if they were part of PsychoPy. In some cases, objects exported by
plugins will be registered for a particular function if they define entry
points into specific modules.
Plugins are simply Python packages,`loadPlugin` will search for them in
directories specified in `sys.path`. Only packages which define entry points
in their metadata which pertain to PsychoPy can be loaded with this
function. This function also permits passing optional arguments to a
callable object in the plugin module to run any initialization routines
prior to loading entry points.
This function is robust, simply returning `True` or `False` whether a
plugin has been fully loaded or not. If a plugin fails to load, the reason
for it will be written to the log as a warning or error, and the application
will continue running. This may be undesirable in some cases, since features
the plugin provides may be needed at some point and would lead to undefined
behavior if not present. If you want to halt the application if a plugin
fails to load, consider using :func:`requirePlugin` to assert that a plugin
is loaded before continuing.
It is advised that you use this function only when using PsychoPy as a
library. If using the Builder or Coder GUI, it is recommended that you use
the plugin dialog to enable plugins for PsychoPy sessions spawned by the
experiment runner. However, you can still use this function if you want to
load additional plugins for a given experiment, having their effects
isolated from the main application and other experiments.
Parameters
----------
plugin : str
Name of the plugin package to load. This usually refers to the package
or project name.
Returns
-------
bool
`True` if the plugin has valid entry points and was loaded successfully.
Also returns `True` if the plugin was already loaded by a previous
`loadPlugin` call this session, this function will have no effect in
this case. `False` is returned if the plugin defines no entry points
specific to PsychoPy or crashed (an error is logged).
Warnings
--------
Make sure that plugins installed on your system are from reputable sources,
as they may contain malware! PsychoPy is not responsible for undefined
behaviour or bugs associated with the use of 3rd party plugins.
See Also
--------
listPlugins : Search for and list installed or loaded plugins.
requirePlugin : Require a plugin be previously loaded.
Examples
--------
Load a plugin by specifying its package/project name::
loadPlugin('psychopy-hardware-box')
You can give arguments to this function which are passed on to the plugin::
loadPlugin('psychopy-hardware-box', switchOn=True, baudrate=9600)
You can use the value returned from `loadPlugin` to determine if the plugin
is installed and supported by the platform::
hasPlugin = loadPlugin('psychopy-hardware-box')
if hasPlugin:
# initialize objects which require the plugin here ...
"""
global _loaded_plugins_, _failed_plugins_
if isPluginLoaded(plugin):
logging.info('Plugin `{}` already loaded. Skipping.'.format(plugin))
return True # already loaded, return True
try:
entryMap = _installed_plugins_[plugin]
except KeyError:
logging.warning(
'Package `{}` does not appear to be a valid plugin. '
'Skipping.'.format(plugin))
if plugin not in _failed_plugins_:
_failed_plugins_.append(plugin)
return False
if not any([i.startswith('psychopy') for i in entryMap.keys()]):
logging.warning(
'Specified package `{}` defines no entry points for PsychoPy. '
'Skipping.'.format(plugin))
if plugin not in _failed_plugins_:
_failed_plugins_.append(plugin)
return False # can't do anything more here, so return
# go over entry points, looking for objects explicitly for psychopy
validEntryPoints = collections.OrderedDict() # entry points to assign
for fqn, attrs in entryMap.items():
if not fqn.startswith('psychopy'):
continue
# forbid plugins from modifying this module
if fqn.startswith('psychopy.plugins') or \
(fqn == 'psychopy' and 'plugins' in attrs):
logging.error(
"Plugin `{}` declares entry points into the `psychopy.plugins` "
"module which is forbidden. Skipping.".format(plugin))
if plugin not in _failed_plugins_:
_failed_plugins_.append(plugin)
return False
# Get the object the fully-qualified name points to the group which the
# plugin wants to modify.
targObj = resolveObjectFromName(fqn, error=False)
if targObj is None:
logging.error(
"Plugin `{}` specified entry point group `{}` that does not "
"exist or is unreachable.".format(plugin, fqn))
if plugin not in _failed_plugins_:
_failed_plugins_.append(plugin)
return False
validEntryPoints[fqn] = []
# Import modules assigned to entry points and load those entry points.
# We don't assign anything to PsychoPy's namespace until we are sure
# that the entry points are valid. This prevents plugins from being
# partially loaded which can cause all sorts of undefined behaviour.
for attr, ep in attrs.items():
try:
# parse the module name from the entry point value
if ':' in ep.value:
module_name, _ = ep.value.split(':', 1)
else:
module_name = ep.value
module_name = module_name.split(".")[0]
except ValueError:
logging.error(
"Plugin `{}` entry point `{}` is not formatted correctly. "
"Skipping.".format(plugin, ep))
if plugin not in _failed_plugins_:
_failed_plugins_.append(plugin)
return False
# Load the module the entry point belongs to, this happens
# anyways when .load() is called, but we get to access it before
# we start binding. If the module has already been loaded, don't
# do this again.
if module_name not in sys.modules:
# Do stuff before loading entry points here, any executable code
# in the module will run to configure it.
try:
imp = importlib.import_module(module_name)
except (ModuleNotFoundError, ImportError):
importSuccess = False
logging.error(
"Plugin `{}` entry point requires module `{}`, but it "
"cannot be imported.".format(plugin, module_name))
except:
importSuccess = False
logging.error(
"Plugin `{}` entry point requires module `{}`, but an "
"error occurred while loading it.".format(
plugin, module_name))
else:
importSuccess = True
if not importSuccess: # if we failed to import
if plugin not in _failed_plugins_:
_failed_plugins_.append(plugin)
return False
# Ensure that we are not wholesale replacing an existing module.
# We want plugins to be explicit about what they are changing.
# This makes sure plugins play nice with each other, only
# making changes to existing code where needed. However, plugins
# are allowed to add new modules to the namespaces of existing
# ones.
if hasattr(targObj, attr):
# handle what to do if an attribute exists already here ...
if inspect.ismodule(getattr(targObj, attr)):
logging.warning(
"Plugin `{}` attempted to override module `{}`.".format(
plugin, fqn + '.' + attr))
# if plugin not in _failed_plugins_:
# _failed_plugins_.append(plugin)
#
# return False
try:
ep = ep.load() # load the entry point
# Raise a warning if the plugin is being loaded from a zip file.
if '.zip' in inspect.getfile(ep):
logging.warning(
"Plugin `{}` is being loaded from a zip file. This may "
"cause issues with the plugin's functionality.".format(plugin))
except ImportError as e:
logging.error(
"Failed to load entry point `{}` of plugin `{}`. "
"(`{}: {}`) "
"Skipping.".format(str(ep), plugin, e.name, e.msg))
if plugin not in _failed_plugins_:
_failed_plugins_.append(plugin)
return False
except Exception: # catch everything else
logging.error(
"Failed to load entry point `{}` of plugin `{}` for unknown"
" reasons. Skipping.".format(str(ep), plugin))
if plugin not in _failed_plugins_:
_failed_plugins_.append(plugin)
return False
# If we get here, the entry point is valid and we can safely add it
# to PsychoPy's namespace.
validEntryPoints[fqn].append((targObj, attr, ep))
# Assign entry points that have been successfully loaded. We defer
# assignment until all entry points are deemed valid to prevent plugins
# from being partially loaded.
for fqn, vals in validEntryPoints.items():
for targObj, attr, ep in vals:
# add the object to the module or unbound class
setattr(targObj, attr, ep)
logging.debug(
"Assigning the entry point `{}` to `{}`.".format(
ep.__name__, fqn + '.' + attr))
# --- handle special cases ---
# Note - We're going to handle special cases here for now, but
# this will eventually be handled by special functions in the
# target modules (e.g. `getAllPhotometers()` in
# `psychopy.hardware.photometer`) which can detect the loaded
# attribute inside the module and add it to a collection.
if fqn == 'psychopy.visual.backends': # if window backend
_registerWindowBackend(attr, ep)
elif fqn == 'psychopy.experiment.components': # if component
_registerBuilderComponent(ep)
elif fqn == 'psychopy.experiment.routine': # if component
_registerBuilderStandaloneRoutine(ep)
elif fqn == 'psychopy.hardware.photometer': # photometer
_registerPhotometer(ep)
elif fqn == "psychopy.app.themes.icons":
# get module folder
folder = Path(ep.__file__).parent
# add all matching .png files from that folder
for file in folder.glob(f"**/*.png"):
targObj.pluginIconFiles.append(file)
# Retain information about the plugin's entry points, we will use this for
# conflict resolution.
_loaded_plugins_[plugin] = entryMap
# If we made it here on a previously failed plugin, it was likely fixed and
# can be removed from the list.
if plugin not in _failed_plugins_:
try:
_failed_plugins_.remove(plugin)
except ValueError:
pass
return True
def requirePlugin(plugin):
"""Require a plugin to be already loaded.
This function can be used to ensure if a plugin has already been loaded and
is ready for use, raising an exception and ending the session if not.
This function compliments :func:`loadPlugin`, which does not halt the
application if plugin fails to load. This allows PsychoPy to continue
working, giving the user a chance to deal with the problem (either by
disabling or fixing the plugins). However, :func:`requirePlugin` can be used
to guard against undefined behavior caused by a failed or partially loaded
plugin by raising an exception before any code that uses the plugin's
features is executed.
Parameters
----------
plugin : str
Name of the plugin package to require. This usually refers to the package
or project name.
Raises
------
RuntimeError
Plugin has not been previously loaded this session.
See Also
--------
loadPlugin : Load a plugin into the current session.
Examples
--------
Ensure plugin `psychopy-plugin` is loaded at this point in the session::
requirePlugin('psychopy-plugin') # error if not loaded
You can catch the error and try to handle the situation by::
try:
requirePlugin('psychopy-plugin')
except RuntimeError:
# do something about it ...
"""
if not isPluginLoaded(plugin):
raise RuntimeError('Required plugin `{}` has not been loaded.'.format(
plugin))
def startUpPlugins(plugins, add=True, verify=True):
"""Specify which plugins should be loaded automatically when a PsychoPy
session starts.
This function edits ``psychopy.preferences.prefs.general['startUpPlugins']``
and provides a means to verify if entries are valid. The PsychoPy session
must be restarted for the plugins specified to take effect.
If using PsychoPy as a library, this function serves as a convenience to
avoid needing to explicitly call :func:`loadPlugin` every time to use your
favorite plugins.
Parameters
----------
plugins : `str`, `list` or `None`
Name(s) of plugins to have load on startup.
add : bool
If `True` names of plugins will be appended to `startUpPlugins` unless a
name is already present. If `False`, `startUpPlugins` will be set to
`plugins`, overwriting the previous value. If `add=False` and
`plugins=[]` or `plugins=None`, no plugins will be loaded in the next
session.
verify : bool
Check if `plugins` are installed and have valid entry points to
PsychoPy. Raises an error if any are not. This prevents undefined
behavior arsing from invalid plugins being loaded in the next session.
If `False`, plugin names will be added regardless if they are installed
or not.
Raises
------
RuntimeError
If `verify=True`, any of `plugins` is not installed or does not have
entry points to PsychoPy. This is raised to prevent issues in future
sessions where invalid plugins are written to the config file and are
automatically loaded.
Warnings
--------
Do not use this function within the builder or coder GUI! Use the plugin
dialog to specify which plugins to load on startup. Only use this function
when using PsychoPy as a library!
Examples
--------
Adding plugins to load on startup::
startUpPlugins(['plugin1', 'plugin2'])
Clearing the startup plugins list, no plugins will be loaded automatically
at the start of the next session::
plugins.startUpPlugins([], add=False)
# or ..
plugins.startUpPlugins(None, add=False)
If passing `None` or an empty list with `add=True`, the present value of
`prefs.general['startUpPlugins']` will remain as-is.
"""
# check if there is a config entry
if 'startUpPlugins' not in prefs.general.keys():
logging.warning(
'Config file does not define `startUpPlugins`. Skipping.')
return
# if a string is specified
if isinstance(plugins, str):
plugins = [plugins]
# if the list is empty or None, just clear
if not plugins or plugins is None:
if not add: # adding nothing gives the original
prefs.general['startUpPlugins'] = []
prefs.saveUserPrefs()
return
# check if the plugins are installed before adding to `startUpPlugins`
scanPlugins()
installedPlugins = listPlugins()
if verify:
notInstalled = [plugin not in installedPlugins for plugin in plugins]
if any(notInstalled):
missingIdx = [i for i, x in enumerate(notInstalled) if x]
errStr = '' # build up an error string
for i, idx in enumerate(missingIdx):
if i < len(missingIdx) - 1:
errStr += '`{}`, '.format(plugins[idx])
else:
errStr += '`{}`;'.format(plugins[idx])
raise RuntimeError(
"Cannot add startup plugin(s): {} either not installed or has "
"no PsychoPy entry points.".format(errStr))
if add: # adding plugin names to existing list
for plugin in plugins:
if plugin not in prefs.general['startUpPlugins']:
prefs.general['startUpPlugins'].append(plugin)
else:
prefs.general['startUpPlugins'] = plugins # overwrite
prefs.saveUserPrefs() # save after loading
def pluginMetadata(plugin):
"""Get metadata from a plugin package.
Reads the package's PKG_INFO and gets fields as a dictionary. Only packages
that have valid entry points to PsychoPy can be queried.
Parameters
----------
plugin : str
Name of the plugin package to retrieve metadata from.
Returns
-------
dict
Metadata fields.
"""
installedPlugins = listPlugins()
if plugin not in installedPlugins:
raise ModuleNotFoundError(
"Plugin `{}` is not installed or does not have entry points for "
"PsychoPy.".format(plugin))
pkg = importlib.metadata.distribution(plugin)
metadict = dict(pkg.metadata)
return metadict
def pluginEntryPoints(plugin, parse=False):
"""Get the entry point mapping for a specified plugin.
You must call `scanPlugins` before calling this function to get the entry
points for a given plugin.
Note this function is intended for internal use by the PsychoPy plugin
system only.
Parameters
----------
plugin : str
Name of the plugin package to get advertised entry points.
parse : bool
Parse the entry point specifiers and convert them to fully-qualified
names.
Returns
-------
dict
Dictionary of target groups/attributes and entry points objects.
"""
global _installed_plugins_
if plugin in _installed_plugins_.keys():
if not parse:
return _installed_plugins_[plugin]
else:
toReturn = {}
for group, val in _installed_plugins_[plugin].items():
if group not in toReturn.keys():
toReturn[group] = {} # create a new group entry
for attr, ep in val.items():
# parse the entry point specifier
ex = '.'.join(str(ep).split(' = ')[1].split(':')) # make fqn
toReturn[group].update({attr: ex})
return toReturn
logging.error("Cannot retrieve entry points for plugin `{}`, either not "
" installed or reachable.")
return None
def activatePlugins(which='all'):
"""Activate plugins.
Calling this routine will load all startup plugins into the current process.
Warnings
--------
This should only be called outside of PsychoPy sub-packages as plugins may
import them, causing a circular import condition.
"""
if not scanPlugins():
logging.info(
'Calling `psychopy.plugins.activatePlugins()`, but no plugins have '
'been found in active distributions.')
return # nop if no plugins
# load each plugin and apply any changes to Builder
for plugin in listPlugins(which):
loadPlugin(plugin)
# Keep track of currently installed window backends. When a window is loaded,
# its `winType` is looked up here and the matching backend is loaded. Plugins
# which define entry points into this module will update `winTypes` if they
# define subclasses of `BaseBackend` that have valid names.
_winTypes = {
'pyglet': '.pygletbackend.PygletBackend',
'glfw': '.glfwbackend.GLFWBackend', # moved to plugin
'pygame': '.pygamebackend.PygameBackend'
}
def getWindowBackends():
# Return winTypes array from backend object
return _winTypes
def discoverModuleClasses(nameSpace, classType, includeUnbound=True):
"""Discover classes and sub-classes matching a specific type within a
namespace.
This function is used to scan a namespace for references to specific classes
and sub-classes. Classes may be either bound or unbound. This is useful for
scanning namespaces for plugins which have loaded their entry points into
them at runtime.
Parameters
----------
nameSpace : str or ModuleType
Fully-qualified path to the namespace, or the reference itself. If the
specified module hasn't been loaded, it will be after calling this.
classType : Any
Which type of classes to get. Any value that `isinstance` or
`issubclass` expects as its second argument is valid.
includeUnbound : bool
Include unbound classes in the search. If `False` only bound objects are
returned. The default is `True`.
Returns
-------
dict
Mapping of names and associated classes.
Examples
--------
Get references to all visual stimuli classes. Since they all are derived
from `psychopy.visual.basevisual.BaseVisualStim`, we can specify that as
the type to search for::
import psychopy.plugins as plugins
import psychopy.visual as visual
foundClasses = plugins.discoverModuleClasses(
visual, # base module to search
visual.basevisual.BaseVisualStim, # type to search for
includeUnbound=True # get unbound classes too
)
The resulting dictionary referenced by `foundClasses` will look like::
foundClasses = {
'BaseShapeStim': <class 'psychopy.visual.shape.BaseShapeStim'>,
'BaseVisualStim': <class 'psychopy.visual.basevisual.BaseVisualStim'>
# ~~~ snip ~~~
'TextStim': <class 'psychopy.visual.text.TextStim'>,
'VlcMovieStim': <class 'psychopy.visual.vlcmoviestim.VlcMovieStim'>
}
To search for classes more broadly, pass `object` as the type to search
for::
foundClasses = plugins.discoverModuleClasses(visual, object)
"""
if isinstance(nameSpace, str):
module = resolveObjectFromName(
nameSpace,
resolve=(nameSpace not in sys.modules),
error=False) # catch error below
elif inspect.ismodule(nameSpace):
module = nameSpace
else:
raise TypeError(
'Invalid type for parameter `nameSpace`. Must be `str` or '
'`ModuleType`')
if module is None:
raise ImportError("Cannot resolve namespace `{}`".format(nameSpace))
foundClasses = {}
if includeUnbound: # get unbound classes in a module
for name, attr in inspect.getmembers(module):
if inspect.isclass(attr) and issubclass(attr, classType):
foundClasses[name] = attr
# now get bound objects, overwrites unbound names if they show up
for name in dir(module):
attr = getattr(module, name)
if inspect.isclass(attr) and issubclass(attr, classType):
foundClasses[name] = attr
return foundClasses
# ------------------------------------------------------------------------------
# Registration functions
#
# These functions are called to perform additional operations when a plugin is
# loaded. Most plugins that specify an entry point elsewhere will not need to
# use these functions to appear in the application.
#
def _registerWindowBackend(attr, ep):
"""Make an entry point discoverable as a window backend.
This allows it the given entry point to be used as a window backend by
specifying `winType`. All window backends must be subclasses of `BaseBackend`
and define a `winTypeName` attribute. The value of `winTypeName` will be
used for selecting `winType`.
This function is called by :func:`loadPlugin`, it should not be used for any
other purpose.
Parameters
----------
attr : str
Attribute name the backend is being assigned in
'psychopy.visual.backends'.
ep : ModuleType or ClassType
Entry point which defines an object with window backends. Can be a class
or module. If a module, the module will be scanned for subclasses of
`BaseBackend` and they will be added as backends.
"""
# get reference to the backend class
fqn = 'psychopy.visual.backends'
backend = resolveObjectFromName(
fqn, resolve=(fqn not in sys.modules), error=False)
if backend is None:
logging.error("Failed to resolve name `{}`.".format(fqn))
return # something weird happened, just exit
# if a module, scan it for valid backends
foundBackends = {}
if inspect.ismodule(ep): # if the backend is a module
for attrName in dir(ep):
_attr = getattr(ep, attrName)
if not inspect.isclass(_attr): # skip if not class
continue
if not issubclass(_attr, backend.BaseBackend): # not backend
continue
# check if the class defines a name for `winType`
if not hasattr(_attr, 'winTypeName'): # has no backend name
continue
# found something that can be a backend
foundBackends[_attr.winTypeName] = '.' + attr + '.' + attrName
logging.debug(
"Registered window backend class `{}` for `winType={}`.".format(
foundBackends[_attr.winTypeName], _attr.winTypeName))
elif inspect.isclass(ep): # backend passed as a class
if not issubclass(ep, backend.BaseBackend):
return
if not hasattr(ep, 'winTypeName'):
return
foundBackends[ep.winTypeName] = '.' + attr
logging.debug(
"Registered window backend class `{}` for `winType={}`.".format(
foundBackends[ep.winTypeName], ep.winTypeName))
backend.winTypes.update(foundBackends) # update installed backends
def _registerBuilderComponent(ep):
"""Register a PsychoPy builder component module.
This function is called by :func:`loadPlugin` when encountering an entry
point group for :mod:`psychopy.experiment.components`. It searches the
module at the entry point for sub-classes of `BaseComponent` and registers
it as a builder component. It will also search the module for any resources
associated with the component (eg. icons and tooltip text) and register them
for use.
Builder component modules in plugins should follow the conventions and
structure of a normal, stand-alone components. Any plugins that adds
components to PsychoPy must be registered to load on startup.
This function is called by :func:`loadPlugin`, it should not be used for any
other purpose.
Parameters
----------
ep : ClassType
Class defining the component.
"""
# get reference to the backend class
fqn = 'psychopy.experiment.components'
compPkg = resolveObjectFromName(
fqn, resolve=(fqn not in sys.modules), error=False)
if compPkg is None:
logging.error("Failed to resolve name `{}`.".format(fqn))
return
if hasattr(compPkg, 'addComponent'):
compPkg.addComponent(ep)
else:
raise AttributeError(
"Cannot find function `addComponent()` in namespace "
"`{}`".format(fqn))
def _registerBuilderStandaloneRoutine(ep):
"""Register a PsychoPy builder standalone routine module.
This function is called by :func:`loadPlugin` when encountering an entry
point group for :mod:`psychopy.experiment.routine`.
This function is called by :func:`loadPlugin`, it should not be used for any
other purpose.
Parameters
----------
ep : ClassType
Class defining the standalone routine.
"""
# get reference to the backend class
fqn = 'psychopy.experiment.routines'
routinePkg = resolveObjectFromName(
fqn, resolve=(fqn not in sys.modules), error=False)
if routinePkg is None:
logging.error("Failed to resolve name `{}`.".format(fqn))
return
if hasattr(routinePkg, 'addStandaloneRoutine'):
routinePkg.addStandaloneRoutine(ep)
else:
raise AttributeError(
"Cannot find function `addStandaloneRoutine()` in namespace "
"`{}`".format(fqn))
def _registerPhotometer(ep):
"""Register a photometer class.
This is called when the plugin specifies an entry point into
:class:`~psychopy.hardware.photometers`.
Parameters
----------
ep : ModuleType or ClassType
Entry point which defines an object serving as the interface for the
photometer.
"""
# get reference to the backend class
fqn = 'psychopy.hardware.photometer'
photPkg = resolveObjectFromName(
fqn, resolve=(fqn not in sys.modules), error=False)
if photPkg is None:
logging.error("Failed to resolve name `{}`.".format(fqn))
return
if hasattr(photPkg, 'addPhotometer'):
photPkg.addPhotometer(ep)
else:
raise AttributeError(
"Cannot find function `addPhotometer()` in namespace "
"`{}`".format(fqn))
if __name__ == "__main__":
pass
| 50,248
|
Python
|
.py
| 1,109
| 36.754734
| 95
| 0.652302
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,858
|
psyexpCompile.py
|
psychopy_psychopy/psychopy/scripts/psyexpCompile.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Part of the PsychoPy library
# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd.
# Distributed under the terms of the GNU General Public License (GPL).
import io
import sys
import os
import argparse
from subprocess import PIPE, Popen
from pathlib import Path
from psychopy import __version__
# DO NOT IMPORT ANY OTHER PSYCHOPY SUB-PACKAGES OR THEY WON'T SWITCH VERSIONS
parser = argparse.ArgumentParser(description='Compile your python file from here')
parser.add_argument('infile', help='The input (psyexp) file to be compiled')
parser.add_argument('--version', '-v', help='The PsychoPy version to use for compiling the script. e.g. 1.84.1')
parser.add_argument('--outfile', '-o', help='The output (py) file to be generated (defaults to the ')
class LegacyScriptError(ChildProcessError):
pass
def generateScript(exp, outfile, target="PsychoPy"):
"""
Generate python script from the current builder experiment.
Parameters
----------
exp: experiment.Experiment object
The current PsychoPy experiment object generated using Builder
outfile : str or Path
File to write to
target: str
PsychoPy or PsychoJS - determines whether Python or JS script is generated.
Returns
-------
"""
import logging # import here not at top of script (or useVersion fails)
print("Generating {} script...\n".format(target))
# get name of executable
if sys.platform == 'win32':
pythonExec = sys.executable
else:
pythonExec = sys.executable.replace(' ', r'\ ')
# compile script from command line using version
compiler = 'psychopy.scripts.psyexpCompile'
# if version is not specified then don't touch useVersion at all
version = exp.settings.params['Use version'].val
# if useVersion is different to installed version...
if version not in [None, 'None', '', __version__]:
# make sure we have a legacy save file
if not Path(exp.legacyFilename).is_file():
exp.saveToXML(filename=exp.filename)
# generate command to run compile from requested version
cmd = [
pythonExec, '-m', compiler, str(exp.legacyFilename), '-o', outfile
]
# run command
cmd.extend(['-v', version])
logging.info(' '.join(cmd))
output = Popen(cmd,
stdout=PIPE,
stderr=PIPE,
universal_newlines=True)
stdout, stderr = output.communicate()
sys.stdout.write(stdout)
sys.stderr.write(stderr)
# we got a non-zero error code, raise an error
if output.returncode != 0:
raise LegacyScriptError(
'Error: Script compile exited with code {}. Traceback:\n'
'{}'.format(output.returncode, stderr))
else:
compileScript(infile=exp, version=None, outfile=outfile)
return outfile
def compileScript(infile=None, version=None, outfile=None):
"""
Compile either Python or JS PsychoPy script from .psyexp file.
Parameters
----------
infile: string, experiment.Experiment object
The input (psyexp) file to be compiled
version: str
The PsychoPy version to use for compiling the script. e.g. 1.84.1.
Warning: Cannot set version if module imported. Set version from
command line interface only.
outfile: string
The output file to be generated (defaults to Python script).
"""
def _setVersion(version):
"""
Sets the version to be used for compiling using the useVersion function
Parameters
----------
version: string
The version requested
"""
# Set version
if version:
from psychopy import useVersion
useVersion(version)
# import logging here not at top of script (or useVersion fails)
global logging
from psychopy import logging
if __name__ != '__main__' and version not in [None, 'None', 'none', '']:
version = None
msg = "You cannot set version by calling compileScript() manually. Setting 'version' to None."
logging.warning(msg)
return version
def _getExperiment(infile, version):
"""
Get experiment if infile is not type experiment.Experiment.
Parameters
----------
infile: string, experiment.Experiment object
The input (psyexp) file to be compiled
version: string
The version requested
Returns
-------
experiment.Experiment
The experiment object used for generating the experiment script
"""
# import PsychoPy experiment and write script with useVersion active
from psychopy.app.builder import experiment
# Check infile type
if isinstance(infile, experiment.Experiment):
thisExp = infile
else:
thisExp = experiment.Experiment()
thisExp.loadFromXML(infile)
thisExp.psychopyVersion = version
return thisExp
def _setTarget(outfile):
"""
Set target for compiling i.e., Python or JavaScript.
Parameters
----------
outfile : string
The output file to be generated (defaults to Python script).
Returns
-------
string
The Python or JavaScript target type
"""
# Set output type, either JS or Python
if outfile.endswith(".js"):
targetOutput = "PsychoJS"
else:
targetOutput = "PsychoPy"
return targetOutput
def _makeTarget(thisExp, outfile, targetOutput):
"""
Generate the actual scripts for Python and/or JS.
Parameters
----------
thisExp : experiment.Experiment object
The current experiment created under requested version
outfile : string
The output file to be generated (defaults to Python script).
targetOutput : string
The Python or JavaScript target type
"""
# Write script
if targetOutput == "PsychoJS":
# Write module JS code
script = thisExp.writeScript(outfile, target=targetOutput, modular=True)
# Write no module JS code
outfileNoModule = outfile.replace('.js', '-legacy-browsers.js') # For no JS module script
scriptNoModule = thisExp.writeScript(outfileNoModule, target=targetOutput, modular=False)
# Store scripts in list
scriptDict = [(outfile, script), (outfileNoModule, scriptNoModule)]
else:
script = thisExp.writeScript(outfile, target=targetOutput)
scriptDict = [(outfile, script)]
# Output script to file
for outfile, script in scriptDict:
if not type(script) in (str, type(u'')):
# We have a stringBuffer not plain string/text
scriptText = script.getvalue()
else:
# We already have the text
scriptText = script
with io.open(outfile, 'w', encoding='utf-8-sig') as f:
f.write(scriptText)
return 1
###### Write script #####
version = _setVersion(version)
thisExp = _getExperiment(infile, version)
targetOutput = _setTarget(outfile)
_makeTarget(thisExp, outfile, targetOutput)
if __name__ == "__main__":
# define args
args = parser.parse_args()
if args.outfile is None:
args.outfile = args.infile.replace(".psyexp", ".py")
compileScript(args.infile, args.version, args.outfile)
| 7,762
|
Python
|
.py
| 193
| 31.57513
| 112
| 0.630559
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,859
|
audiodevice.py
|
psychopy_psychopy/psychopy/sound/audiodevice.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Classes and functions for managing audio devices.
"""
# Part of the PsychoPy library
# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd.
# Distributed under the terms of the GNU General Public License (GPL).
__all__ = [
'AudioDeviceInfo',
'AudioDeviceStatus',
'NULL_AUDIO_DEVICE',
'NULL_AUDIO_DEVICE_STATUS',
'sampleRateQualityLevels',
'latencyClassLevels',
'runModeLevels',
'SAMPLE_RATE_8kHz',
'SAMPLE_RATE_TELCOM_QUALITY',
'SAMPLE_RATE_16kHz',
'SAMPLE_RATE_VOIP_QUALITY',
'SAMPLE_RATE_VOICE_QUALITY',
'SAMPLE_RATE_44p1kHz',
'SAMPLE_RATE_CD_QUALITY',
'SAMPLE_RATE_48kHz',
'SAMPLE_RATE_DVD_QUALITY',
'SAMPLE_RATE_96kHz',
'SAMPLE_RATE_192kHz',
'AUDIO_PTB_LATENCY_CLASS0',
'AUDIO_PTB_LATENCY_CLASS1',
'AUDIO_PTB_LATENCY_CLASS2',
'AUDIO_PTB_LATENCY_CLASS3',
'AUDIO_PTB_LATENCY_CLASS4',
'AUDIO_PTB_LATENCY_CLASS_DONT_CARE',
'AUDIO_PTB_LATENCY_CLASS_SHARE',
'AUDIO_PTB_LATENCY_CLASS_EXCLUSIVE',
'AUDIO_PTB_LATENCY_CLASS_AGGRESSIVE',
'AUDIO_PTB_LATENCY_CLASS_CRITICAL',
'AUDIO_PTB_RUN_MODE0',
'AUDIO_PTB_RUN_MODE1',
'AUDIO_PTB_RUN_MODE_STANDBY',
'AUDIO_PTB_RUN_MODE_KEEP_HOT',
'AUDIO_LIBRARY_PTB'
]
from psychopy.tools.audiotools import *
# audio library identifiers
AUDIO_LIBRARY_PTB = 'ptb' # PsychPortAudio from Psychtoolbox
# Latency classes for the PsychPortAudio backend. These are used to set how
# aggressive PsychPortAudio should be at minimizing sound latency and getting
# precise timing. Exclusive mode `AUDIO_PTB_LATENCY_CLASS2` is usually used
# for the best timing and maximum compatibility.
#
AUDIO_PTB_LATENCY_CLASS0 = AUDIO_PTB_LATENCY_CLASS_DONT_CARE = 0
AUDIO_PTB_LATENCY_CLASS1 = AUDIO_PTB_LATENCY_CLASS_SHARE = 1
AUDIO_PTB_LATENCY_CLASS2 = AUDIO_PTB_LATENCY_CLASS_EXCLUSIVE = 2
AUDIO_PTB_LATENCY_CLASS3 = AUDIO_PTB_LATENCY_CLASS_AGGRESSIVE = 3
AUDIO_PTB_LATENCY_CLASS4 = AUDIO_PTB_LATENCY_CLASS_CRITICAL = 4
# used for GUI dropdowns
latencyClassLevels = {
0: (AUDIO_PTB_LATENCY_CLASS0, 'Latency not important'),
1: (AUDIO_PTB_LATENCY_CLASS1, 'Share low-latency driver'),
2: (AUDIO_PTB_LATENCY_CLASS2, 'Exclusive low-latency'), # <<< default
3: (AUDIO_PTB_LATENCY_CLASS3, 'Aggressive low-latency'),
4: (AUDIO_PTB_LATENCY_CLASS4, 'Latency critical'),
}
# Run modes for the PsychPortAudio backend.
AUDIO_PTB_RUN_MODE0 = AUDIO_PTB_RUN_MODE_STANDBY = 0
AUDIO_PTB_RUN_MODE1 = AUDIO_PTB_RUN_MODE_KEEP_HOT = 1
runModeLevels = {
0: (AUDIO_PTB_RUN_MODE0, 'Standby (low resource use, higher latency)'),
1: (AUDIO_PTB_RUN_MODE1, 'Keep hot (higher resource use, low latency)')
}
class AudioDeviceInfo:
"""Descriptor for an audio device (playback or recording) on this system.
Properties associated with this class provide information about a specific
audio playback or recording device. An object can be then passed to
:class:`~psychopy.sound._microphone.Microphone` to open a stream using the
device described by the object.
This class is usually instanced only by calling
:meth:`~psychopy.sound._microphone.Microphone.getDevices()`. Users should
avoid creating instances of this class themselves unless they have good
reason to.
Parameters
----------
deviceIndex : int
Enumerated index of the audio device. This number is specific to the
engine used for audio.
deviceName : str
Human-readable name of the device.
hostAPIName : str
Human-readable name of the host API used for audio.
outputChannels : int
Number of output channels.
outputLatency : tuple
Low (`float`) and high (`float`) output latency in milliseconds.
inputChannels : int
Number of input channels.
inputLatency : tuple
Low (`float`) and high (`float`) input latency in milliseconds.
defaultSampleRate : int
Default sample rate for the device in Hertz (Hz).
audioLib : str
Audio library that queried device information used to populate the
properties of this descriptor (e.g., ``'ptb'`` for Psychtoolbox).
Examples
--------
Get a list of available devices::
import psychopy.sound as sound
recordingDevicesList = sound.Microphone.getDevices()
Get the low and high input latency of the first recording device::
recordingDevice = recordingDevicesList[0] # assume not empty
inputLatencyLow, inputLatencyHigh = recordingDevice.inputLatency
Get the device name as it may appear in the system control panel or sound
settings::
deviceName = recordingDevice.deviceName
Specifying the device to use for capturing audio from a microphone::
# get the first suitable capture device found by the sound engine
recordingDevicesList = sound.Microphone.getDevices()
recordingDevice = recordingDevicesList[0]
# pass the descriptor to microphone to configure it
mic = sound.Microphone(device=recordingDevice)
mic.start() # start recording sound
"""
__slots__ = [
'_deviceIndex',
'_deviceName',
'_hostAPIName',
'_outputChannels',
'_inputChannels',
'_lowInputLatency',
'_highInputLatency',
'_lowOutputLatency',
'_highOutputLatency',
'_defaultSampleRate',
'_audioLib'
]
def __init__(self,
deviceIndex=-1,
deviceName=u'Null Device',
hostAPIName=u'Null Audio Driver',
outputChannels=0,
outputLatency=(0., 0.),
inputChannels=0,
inputLatency=(0., 0.),
defaultSampleRate=SAMPLE_RATE_48kHz,
audioLib=u''):
# values based off Psychtoolbox audio device descriptors
self.deviceIndex = deviceIndex
self.deviceName = deviceName
self.hostAPIName = hostAPIName
self.outputChannels = outputChannels
self.inputChannels = inputChannels
self.inputLatency = inputLatency
self.outputLatency = outputLatency
self.defaultSampleRate = defaultSampleRate
self.audioLib = audioLib
def __repr__(self):
return (f"AudioDeviceInfo(deviceIndex={self.deviceIndex}, "
f"deviceName={repr(self.deviceName)}, "
f"hostAPIName={repr(self.hostAPIName)}, "
f"outputChannels={self.outputChannels}, "
f"outputLatency={repr(self.outputLatency)}, "
f"inputChannels={self.inputChannels}, "
f"inputLatency={repr(self.inputLatency)}, "
f"defaultSampleRate={self.defaultSampleRate}, "
f"audioLib={repr(self.audioLib)})")
@staticmethod
def createFromPTBDesc(desc):
"""Create an `AudioDevice` instance with values populated using a
descriptor (`dict`) returned from the PTB `audio.get_devices` API call.
Parameters
----------
desc : dict
Audio device descriptor returned from Psychtoolbox's `get_devices`
function.
Returns
-------
AudioDeviceInfo
Audio device descriptor with properties set using `desc`.
"""
assert isinstance(desc, dict)
# required fields, sanity check to see if something changed in PTB land
reqFields = [
'DeviceIndex', 'DeviceName', 'HostAudioAPIName', 'NrOutputChannels',
'NrInputChannels', 'LowOutputLatency', 'HighOutputLatency',
'LowInputLatency', 'HighInputLatency', 'DefaultSampleRate'
]
assert all([field in desc.keys() for field in reqFields])
audioDevDesc = AudioDeviceInfo(
deviceIndex=desc['DeviceIndex'],
deviceName=desc['DeviceName'],
hostAPIName=desc['HostAudioAPIName'],
outputChannels=desc['NrOutputChannels'],
outputLatency=(desc['LowOutputLatency'], desc['HighOutputLatency']),
inputChannels=desc['NrInputChannels'],
inputLatency=(desc['LowInputLatency'], desc['HighInputLatency']),
defaultSampleRate=desc['DefaultSampleRate'],
audioLib=AUDIO_LIBRARY_PTB) # queried with psychtoolbox
return audioDevDesc
@property
def audioLib(self):
"""Audio library used to query device information (`str`)."""
return self._audioLib
@audioLib.setter
def audioLib(self, value):
self._audioLib = str(value)
@property
def inputChannels(self):
"""Number of input channels (`int`). If >0, this is likely a audio
capture device.
"""
return self._inputChannels
@inputChannels.setter
def inputChannels(self, value):
self._inputChannels = int(value)
@property
def outputChannels(self):
"""Number of output channels (`int`). If >0, this is likely a audio
playback device.
"""
return self._outputChannels
@outputChannels.setter
def outputChannels(self, value):
self._outputChannels = int(value)
@property
def deviceIndex(self):
"""Enumerated index (`int`) of the audio device."""
return self._deviceIndex
@deviceIndex.setter
def deviceIndex(self, value):
self._deviceIndex = int(value)
@property
def deviceName(self):
"""Human-readable name (`str`) for the audio device reported by the
driver.
"""
return self._deviceName
@deviceName.setter
def deviceName(self, value):
self._deviceName = str(value)
@property
def hostAPIName(self):
"""Human-readable name (`str`) for the host API."""
return self._hostAPIName
@hostAPIName.setter
def hostAPIName(self, value):
self._hostAPIName = str(value)
@property
def outputLatency(self):
"""Low and high output latency in milliseconds `(low, high)`."""
return self._lowOutputLatency, self._highOutputLatency
@outputLatency.setter
def outputLatency(self, value):
assert len(value) == 2
self._lowOutputLatency = float(value[0])
self._highOutputLatency = float(value[1])
@property
def inputLatency(self):
"""Low and high input latency in milliseconds `(low, high)`."""
return self._lowInputLatency, self._highInputLatency
@inputLatency.setter
def inputLatency(self, value):
assert len(value) == 2
self._lowInputLatency = float(value[0])
self._highInputLatency = float(value[1])
@property
def defaultSampleRate(self):
"""Default sample rate in Hertz (Hz) for this device (`int`)."""
return self._defaultSampleRate
@defaultSampleRate.setter
def defaultSampleRate(self, value):
self._defaultSampleRate = int(value)
@property
def isPlayback(self):
"""`True` if this device is suitable for playback (`bool`)."""
return self._outputChannels > 0
@property
def isCapture(self):
"""`True` if this device is suitable for capture (`bool`)."""
return self._inputChannels > 0
@property
def isDuplex(self):
"""`True` if this device is suitable for capture and playback (`bool`).
"""
return self.isPlayback and self.isCapture
class AudioDeviceStatus:
"""Descriptor for audio device status information.
Properties of this class are standardized on the status information returned
by Psychtoolbox. Other audio backends should try to populate these fields as
best they can with their equivalent status values.
Users should never instance this class themselves unless they have good
reason to.
Parameters
----------
active : bool
`True` if playback or recording has started, else `False`.
state : int
State of the device, either `1` for playback, `2` for recording or `3`
for duplex (recording and playback).
requestedStartTime : float
Requested start time of the audio stream after the start of playback or
recording.
startTime : float
The actual (real) start time of audio playback or recording.
captureStartTime : float
Estimate of the start time of audio capture. Only valid if audio capture
is active. Usually, this time corresponds to the time when the first
sound was captured.
requestedStopTime : float
Stop time requested when starting the stream.
estimatedStopTime : float
Estimated stop time given `requestedStopTime`.
currentStreamTime : float
Estimate of the time it will take for the most recently submitted sample
to reach the speaker. Value is in absolute system time and reported for
playback only.
elapsedOutSamples : int
Total number of samples submitted since the start of playback.
positionSecs : float
Current stream playback position in seconds this loop. Does not account
for hardware of driver latency.
recordedSecs : float
Total amount of recorded sound data (in seconds) since start of capture.
readSecs : float
Total amount of sound data in seconds that has been fetched from the
internal buffer.
schedulePosition : float
Current position in a running schedule in seconds.
xRuns : int
Number of dropouts due to buffer over- and under-runs. Such conditions
can result is glitches during playback/recording. Even if the number
remains zero, that does not mean that glitches did not occur.
totalCalls : int
**Debug** - Used for debugging the audio engine.
timeFailed : float
**Debug** - Used for debugging the audio engine.
bufferSize : int
**Debug** - Size of the buffer allocated to contain stream samples. Used
for debugging the audio engine.
cpuLoad : float
Amount of load on the CPU imparted by the sound engine. Ranges between
0.0 and 1.0 where 1.0 indicates maximum load on the core running the
sound engine process.
predictedLatency : float
Latency for the given hardware and driver. This indicates how far ahead
you need to start the device to ensure is starts at a scheduled time.
latencyBias : float
Additional latency bias added by the user.
sampleRate : int
Sample rate in Hertz (Hz) the playback recording is using.
outDeviceIndex : int
Enumerated index of the output device.
inDeviceIndex : int
Enumerated index of the input device.
audioLib : str
Identifier for the audio library which created this status.
"""
__slots__ = [
'_active',
'_state',
'_requestedStartTime',
'_startTime',
'_captureStartTime',
'_requestedStopTime',
'_estimatedStopTime',
'_currentStreamTime',
'_elapsedOutSamples',
'_positionSecs',
'_recordedSecs',
'_readSecs',
'_schedulePosition',
'_xRuns',
'_totalCalls',
'_timeFailed',
'_bufferSize',
'_cpuLoad',
'_predictedLatency',
'_latencyBias',
'_sampleRate',
'_outDeviceIndex',
'_inDeviceIndex',
'_audioLib'
]
def __init__(self,
active=0,
state=0,
requestedStartTime=0.0,
startTime=0.0,
captureStartTime=0.0,
requestedStopTime=0.0,
estimatedStopTime=0.0,
currentStreamTime=0.0,
elapsedOutSamples=0,
positionSecs=0.0,
recordedSecs=0.0,
readSecs=0.0,
schedulePosition=0.0,
xRuns=0,
totalCalls=0,
timeFailed=0,
bufferSize=0,
cpuLoad=0.0,
predictedLatency=0.0,
latencyBias=0.0,
sampleRate=SAMPLE_RATE_44p1kHz,
outDeviceIndex=0,
inDeviceIndex=0,
audioLib=u'Null Audio Library'):
self.active = active
self.state = state
self.requestedStartTime = requestedStartTime
self.startTime = startTime
self.captureStartTime = captureStartTime
self.requestedStopTime = requestedStopTime
self.estimatedStopTime = estimatedStopTime
self.currentStreamTime = currentStreamTime
self.elapsedOutSamples = elapsedOutSamples
self.positionSecs = positionSecs
self.recordedSecs = recordedSecs
self.readSecs = readSecs
self.schedulePosition = schedulePosition
self.xRuns = xRuns
self.totalCalls = totalCalls
self.timeFailed = timeFailed
self.bufferSize = bufferSize
self.cpuLoad = cpuLoad
self.predictedLatency = predictedLatency
self.latencyBias = latencyBias
self.sampleRate = sampleRate
self.outDeviceIndex = outDeviceIndex
self.inDeviceIndex = inDeviceIndex
self.audioLib = audioLib
def __repr__(self):
return (f"AudioDeviceStatus(active={self.active}, "
f"state={self.state}, "
f"requestedStartTime={self.requestedStartTime}, "
f"startTime={self.startTime}, "
f"captureStartTime={self.captureStartTime}, "
f"requestedStopTime={self.requestedStopTime}, "
f"estimatedStopTime={self.estimatedStopTime}, "
f"currentStreamTime={self.currentStreamTime}, "
f"elapsedOutSamples={self.elapsedOutSamples}, "
f"positionSecs={self.positionSecs}, "
f"recordedSecs={self.recordedSecs}, "
f"readSecs={self.readSecs}, "
f"schedulePosition={self.schedulePosition}, "
f"xRuns={self.xRuns}, "
f"totalCalls={self.totalCalls}, "
f"timeFailed={self.timeFailed}, "
f"bufferSize={self.bufferSize}, "
f"cpuLoad={self.cpuLoad}, "
f"predictedLatency={self.predictedLatency}, "
f"latencyBias={self.latencyBias}, "
f"sampleRate={self.sampleRate}, "
f"outDeviceIndex={self.outDeviceIndex}, "
f"inDeviceIndex={self.inDeviceIndex}, "
f"audioLib={repr(self.audioLib)})")
@staticmethod
def createFromPTBDesc(desc):
"""Create an `AudioDeviceStatus` instance using a status descriptor
returned by Psychtoolbox.
Parameters
----------
desc : dict
Audio device status descriptor.
Returns
-------
AudioDeviceStatus
Audio device descriptor with properties set using `desc`.
"""
audioStatusDesc = AudioDeviceStatus(
active=desc['Active'],
state=desc['State'],
requestedStartTime=desc['RequestedStartTime'],
startTime=desc['StartTime'],
captureStartTime=desc['CaptureStartTime'],
requestedStopTime=desc['RequestedStopTime'],
estimatedStopTime=desc['EstimatedStopTime'],
currentStreamTime=desc['CurrentStreamTime'],
elapsedOutSamples=desc['ElapsedOutSamples'],
positionSecs=desc['PositionSecs'],
recordedSecs=desc['RecordedSecs'],
readSecs=desc['ReadSecs'],
schedulePosition=desc['SchedulePosition'],
xRuns=desc['XRuns'],
totalCalls=desc['TotalCalls'],
timeFailed=desc['TimeFailed'],
bufferSize=desc['BufferSize'],
cpuLoad=desc['CPULoad'],
predictedLatency=desc['PredictedLatency'],
latencyBias=desc['LatencyBias'],
sampleRate=desc['SampleRate'],
outDeviceIndex=desc['OutDeviceIndex'],
inDeviceIndex=desc['InDeviceIndex'],
audioLib='ptb')
return audioStatusDesc
@property
def audioLib(self):
"""Identifier for the audio library which created this status (`str`).
"""
return self._audioLib
@audioLib.setter
def audioLib(self, value):
self._audioLib = str(value)
@property
def active(self):
"""`True` if playback or recording has started (`bool`).
"""
return self._active
@active.setter
def active(self, value):
self._active = bool(value)
@property
def state(self):
"""State of the device (`int`). Either `1` for playback, `2` for
recording or `3` for duplex (recording and playback).
"""
return self._state
@state.setter
def state(self, value):
self._state = int(value)
@property
def isPlayback(self):
"""`True` if this device is operating in playback mode (`bool`)."""
return self._state == 1 or self._state == 3
@property
def isCapture(self):
"""`True` if this device is operating in capture mode (`bool`)."""
return self._state == 2 or self._state == 3
@property
def isDuplex(self):
"""`True` if this device is operating capture and recording mode
(`bool`).
"""
return self._state == 3
@property
def requestedStartTime(self):
"""Requested start time of the audio stream after the start of playback
or recording (`float`).
"""
return self._requestedStartTime
@requestedStartTime.setter
def requestedStartTime(self, value):
self._requestedStartTime = float(value)
@property
def startTime(self):
"""The actual (real) start time of audio playback or recording
(`float`).
"""
return self._startTime
@startTime.setter
def startTime(self, value):
self._startTime = float(value)
@property
def captureStartTime(self):
"""Estimate of the start time of audio capture (`float`). Only valid if
audio capture is active. Usually, this time corresponds to the time when
the first sound was captured.
"""
return self._startTime
@captureStartTime.setter
def captureStartTime(self, value):
self._captureStartTime = float(value)
@property
def requestedStopTime(self):
"""Stop time requested when starting the stream (`float`)."""
return self._requestedStopTime
@requestedStopTime.setter
def requestedStopTime(self, value):
self._requestedStopTime = float(value)
@property
def estimatedStopTime(self):
"""Estimated stop time given `requestedStopTime` (`float`)."""
return self._requestedStopTime
@estimatedStopTime.setter
def estimatedStopTime(self, value):
self._estimatedStopTime = float(value)
@property
def currentStreamTime(self):
"""Estimate of the time it will take for the most recently submitted
sample to reach the speaker (`float`). Value is in absolute system time
and reported for playback mode only.
"""
return self._currentStreamTime
@currentStreamTime.setter
def currentStreamTime(self, value):
self._currentStreamTime = float(value)
@property
def elapsedOutSamples(self):
"""Total number of samples submitted since the start of playback
(`int`).
"""
return self._elapsedOutSamples
@elapsedOutSamples.setter
def elapsedOutSamples(self, value):
self._elapsedOutSamples = int(value)
@property
def positionSecs(self):
"""Current stream playback position in seconds this loop (`float`). Does
not account for hardware of driver latency.
"""
return self._positionSecs
@positionSecs.setter
def positionSecs(self, value):
self._positionSecs = float(value)
@property
def recordedSecs(self):
"""Total amount of recorded sound data (in seconds) since start of
capture (`float`).
"""
return self._recordedSecs
@recordedSecs.setter
def recordedSecs(self, value):
self._recordedSecs = float(value)
@property
def readSecs(self):
"""Total amount of sound data in seconds that has been fetched from the
internal buffer (`float`).
"""
return self._readSecs
@readSecs.setter
def readSecs(self, value):
self._readSecs = float(value)
@property
def schedulePosition(self):
"""Current position in a running schedule in seconds (`float`)."""
return self._schedulePosition
@schedulePosition.setter
def schedulePosition(self, value):
self._schedulePosition = float(value)
@property
def xRuns(self):
"""Number of dropouts due to buffer over- and under-runs (`int`). Such
conditions can result is glitches during playback/recording. Even if the
number remains zero, that does not mean that glitches did not occur.
"""
return self._xRuns
@xRuns.setter
def xRuns(self, value):
self._xRuns = int(value)
@property
def totalCalls(self):
"""**Debug** - Used for debugging the audio engine (`int`)."""
return self._xRuns
@totalCalls.setter
def totalCalls(self, value):
self._xRuns = int(value)
@property
def timeFailed(self):
"""**Debug** - Used for debugging the audio engine (`float`)."""
return self._timeFailed
@timeFailed.setter
def timeFailed(self, value):
self._timeFailed = float(value)
@property
def bufferSize(self):
"""**Debug** - Size of the buffer allocated to contain stream samples.
Used for debugging the audio engine.
"""
return self._bufferSize
@bufferSize.setter
def bufferSize(self, value):
self._bufferSize = int(value)
@property
def cpuLoad(self):
"""Amount of load on the CPU imparted by the sound engine (`float`).
Ranges between 0.0 and 1.0 where 1.0 indicates maximum load on the core
running the sound engine process.
"""
return self._cpuLoad
@cpuLoad.setter
def cpuLoad(self, value):
self._cpuLoad = float(value)
@property
def predictedLatency(self):
"""Latency for the given hardware and driver (`float`). This indicates
how far ahead you need to start the device to ensure is starts at a
scheduled time.
"""
return self._predictedLatency
@predictedLatency.setter
def predictedLatency(self, value):
self._predictedLatency = float(value)
@property
def latencyBias(self):
"""Additional latency bias added by the user (`float`)."""
return self._latencyBias
@latencyBias.setter
def latencyBias(self, value):
self._latencyBias = float(value)
@property
def sampleRate(self):
"""Sample rate in Hertz (Hz) the playback recording is using (`int`)."""
return self._sampleRate
@sampleRate.setter
def sampleRate(self, value):
self._sampleRate = int(value)
@property
def outDeviceIndex(self):
"""Enumerated index of the output device (`int`)."""
return self._outDeviceIndex
@outDeviceIndex.setter
def outDeviceIndex(self, value):
self._outDeviceIndex = int(value)
@property
def inDeviceIndex(self):
"""Enumerated index of the input device (`int`)."""
return self._inDeviceIndex
@inDeviceIndex.setter
def inDeviceIndex(self, value):
self._inDeviceIndex = int(value)
# These are used as sentinels or for testing. Instancing these here behaves as
# a self-test, providing coverage to most of the setter methods when this module
# is imported.
#
NULL_AUDIO_DEVICE = AudioDeviceInfo()
NULL_AUDIO_DEVICE_STATUS = AudioDeviceStatus()
if __name__ == "__main__":
pass
| 28,180
|
Python
|
.py
| 717
| 30.993026
| 80
| 0.64755
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,860
|
microphone.py
|
psychopy_psychopy/psychopy/sound/microphone.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Audio recording using a microphone.
"""
# Part of the PsychoPy library
# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd.
# Distributed under the terms of the GNU General Public License (GPL).
__all__ = ['Microphone']
from pathlib import Path
from psychopy import logging
from psychopy.constants import NOT_STARTED
from psychopy.hardware import DeviceManager
from psychopy.tools.attributetools import logAttrib
class Microphone:
def __init__(
self,
device=None,
sampleRateHz=None,
channels=None,
streamBufferSecs=2.0,
maxRecordingSize=24000,
policyWhenFull='warn',
audioLatencyMode=None,
audioRunMode=0,
name="mic",
recordingFolder=Path.home(),
recordingExt="wav",
):
# store name
self.name = name
# store folder
self.recordingFolder = Path(recordingFolder)
# store ext (without dot)
while recordingExt.startswith("."):
recordingExt = recordingExt[1:]
self.recordingExt = recordingExt
# look for device if initialised
self.device = DeviceManager.getDevice(device)
# if no matching name, try matching index
if self.device is None:
self.device = DeviceManager.getDeviceBy("index", device)
# if still no match, make a new device
if self.device is None:
self.device = DeviceManager.addDevice(
deviceClass="psychopy.hardware.microphone.MicrophoneDevice", deviceName=device,
index=device,
sampleRateHz=sampleRateHz,
channels=channels,
streamBufferSecs=streamBufferSecs,
maxRecordingSize=maxRecordingSize,
policyWhenFull=policyWhenFull,
audioLatencyMode=audioLatencyMode,
audioRunMode=audioRunMode
)
# set policy when full (in case device already existed)
self.device.policyWhenFull = policyWhenFull
# setup clips and transcripts dicts
self.clips = {}
self.lastClip = None
self.scripts = {}
self.lastScript = None
# set initial status
self.status = NOT_STARTED
def __del__(self):
self.saveClips()
@property
def maxRecordingSize(self):
"""
Until a file is saved, the audio data from a Microphone needs to be stored in RAM. To avoid
a memory leak, we limit the amount which can be stored by a single Microphone object. The
`maxRecordingSize` parameter defines what this limit is.
Parameters
----------
value : int
How much data (in kb) to allow, default is 24mb (so 24,000kb)
"""
return self.device.maxRecordingSize
@maxRecordingSize.setter
def maxRecordingSize(self, value):
# set size
self.device.maxRecordingSize = value
def setMaxRecordingSize(self, value):
self.maxRecordingSize = value
# log
logAttrib(
obj=self, log=True, attrib="maxRecordingSize", value=value
)
setMaxRecordingSize.__doc__ == maxRecordingSize.__doc__
# the Builder param has a different name
setMaxSize = setMaxRecordingSize
@property
def policyWhenFull(self):
"""
Until a file is saved, the audio data from a Microphone needs to be stored in RAM. To avoid
a memory leak, we limit the amount which can be stored by a single Microphone object. The
`policyWhenFull` parameter tells the Microphone what to do when it's reached that limit.
Parameters
----------
value : str
One of:
- "ignore": When full, just don't record any new samples
- "warn": Same as ignore, but will log a warning
- "error": When full, will raise an error
- "rolling": When full, clears the start of the buffer to make room for new samples
"""
return self.device.policyWhenFull
@policyWhenFull.setter
def policyWhenFull(self, value):
return self.device.policyWhenFull
def setPolicyWhenFull(self, value):
self.policyWhenFull = value
# log
logAttrib(
obj=self, log=True, attrib="policyWhenFull", value=value
)
setPolicyWhenFull.__doc__ = policyWhenFull.__doc__
@property
def recording(self):
return self.device.recording
@property
def recBufferSecs(self):
return self.device.recBufferSecs
@property
def maxRecordingSize(self):
return self.device.maxRecordingSize
@maxRecordingSize.setter
def maxRecordingSize(self, value):
self.device.maxRecordingSize = value
@property
def latencyBias(self):
return self.device.latencyBias
@latencyBias.setter
def latencyBias(self, value):
self.device.latency_bias = value
@property
def audioLatencyMode(self):
return self.device.audioLatencyMode
@property
def streamBufferSecs(self):
return self.device.streamBufferSecs
@property
def streamStatus(self):
return self.device.streamStatus
@property
def isRecBufferFull(self):
return self.device.isRecBufferFull
@property
def isStarted(self):
return self.device.isStarted
@property
def isRecording(self):
return self.device.isRecording
def start(self, when=None, waitForStart=0, stopTime=None):
return self.device.start(
when=when, waitForStart=waitForStart, stopTime=stopTime
)
def record(self, when=None, waitForStart=0, stopTime=None):
return self.start(
when=when, waitForStart=waitForStart, stopTime=stopTime
)
def stop(self, blockUntilStopped=True, stopTime=None):
return self.device.stop(
blockUntilStopped=blockUntilStopped, stopTime=stopTime
)
def pause(self, blockUntilStopped=True, stopTime=None):
return self.stop(
blockUntilStopped=blockUntilStopped, stopTime=stopTime
)
def close(self):
return self.device.close()
def reopen(self):
return self.device.reopen()
def poll(self):
return self.device.poll()
def saveClips(self, clear=True):
"""
Save all stored clips to audio files.
Parameters
----------
clear : bool
If True, clips will be removed from this object once saved to files.
"""
# iterate through all clips
for tag in self.clips:
logging.info(f"Saving {len(self.clips[tag])} audio clips with tag {tag}")
for i, clip in enumerate(self.clips[tag]):
# construct filename
filename = self.getClipFilename(tag, i)
# save clip
clip.save(self.recordingFolder / filename)
# clear
if clear:
del self.clips[tag][i]
def getClipFilename(self, tag, i=0):
"""
Get the filename for a particular clip.
Parameters
----------
tag : str
Tag assigned to the clip when `bank` was called
i : int
Index of clip within this tag (default is -1, i.e. the last clip)
Returns
-------
str
Constructed filename for this clip
"""
# if there's more than 1 clip with this tag, append a counter
counter = ""
if i > 0:
counter += f"_{i}"
# construct filename
filename = f"recording_{self.name}_{tag}{counter}.{self.recordingExt}"
return filename
def bank(self, tag=None, transcribe=False, **kwargs):
"""Store current buffer as a clip within the microphone object.
This method is used internally by the Microphone component in Builder,
don't use it for other applications. Either `stop()` or `pause()` must
be called before calling this method.
Parameters
----------
tag : str or None
Label for the clip.
transcribe : bool or str
Set to the name of a transcription engine (e.g. "GOOGLE") to
transcribe using that engine, or set as `False` to not transcribe.
kwargs : dict
Additional keyword arguments to pass to
:class:`~psychopy.sound.AudioClip.transcribe()`.
"""
# make sure the tag exists in both clips and transcripts dicts
if tag not in self.clips:
self.clips[tag] = []
if tag not in self.scripts:
self.scripts[tag] = []
# append current recording to clip list according to tag
self.lastClip = self.getRecording()
self.clips[tag].append(self.lastClip)
# synonymise null values
nullVals = (
'undefined', 'NONE', 'None', 'none', 'False', 'false', 'FALSE')
if transcribe in nullVals:
transcribe = False
# append current clip's transcription according to tag
if transcribe:
if transcribe in ('Built-in', True, 'BUILT_IN', 'BUILT-IN',
'Built-In', 'built-in'):
engine = "sphinx"
elif type(transcribe) == str:
engine = transcribe
else:
raise ValueError(
"Invalid transcription engine {} specified.".format(
transcribe))
self.lastScript = self.lastClip.transcribe(
engine=engine, **kwargs)
else:
self.lastScript = "Transcription disabled."
self.scripts[tag].append(self.lastScript)
# clear recording buffer
self.device._recording.clear()
# return banked items
if transcribe:
return self.lastClip, self.lastScript
else:
return self.lastClip
def clear(self):
"""Wipe all clips. Deletes previously banked audio clips.
"""
# clear clips
self.clips = {}
# clear recording
self._recording.clear()
def flush(self):
"""Get a copy of all banked clips, then clear the clips from storage."""
# get copy of clips dict
clips = self.clips.copy()
self.clear()
return clips
def getRecording(self):
return self.device.getRecording()
if __name__ == "__main__":
pass
| 10,650
|
Python
|
.py
| 283
| 28.04947
| 100
| 0.613283
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,861
|
backend_pygame.py
|
psychopy_psychopy/psychopy/sound/backend_pygame.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from pathlib import Path
import numpy
from os import path
from psychopy import logging, prefs
from psychopy.constants import (STARTED, PLAYING, PAUSED, FINISHED, STOPPED,
NOT_STARTED, FOREVER)
from psychopy.tools import filetools as ft
from ._base import _SoundBase
from .exceptions import DependencyError
try:
import pygame
from pygame import mixer, sndarray
except ImportError as err:
# convert this import error to our own, pygame probably not installed
raise DependencyError(repr(err))
def getDevices(kind=None):
"""Get audio playback and recording devices via the backend's audio API.
Queries the system for available audio playback and recording devices,
returning names and capabilities.
Parameters
----------
kind : str or None
Audio device types to query from the system. Values can be 'input' or
'output' for recording and playback, respectively. If `None`, only
playback devices are returned.
Returns
-------
dict
A `dict` of `dict` of installed playback/capture devices and their
properties. Keys are device names and values are properties stored in a
`dict`. Properties are guaranteed to contain the following keys and
values:
* `name` - Human readable name of the device i.e. "High Definition
Audio". This is the same as the value's key used to access the
property.
* `id` - Enumerated device ID.
"""
# Just some values to keep the prefs dialog from crashing
if kind.startswith('out') or None:
return {'Default Playback Device':
{'name': 'Default Playback Device', 'id': 0}}
elif kind.startswith('in'):
return {'Default Recording Device':
{'name': 'Default Recording Device', 'id': 0}}
else:
raise ValueError("Invalid value for argument `kind`.")
# # This code here will be usable when we update to Pygame 2.x, for now we
# # just return some values indicating the default audio device is being
# # used.
#
# # 0 = playback, 1 = recording
# if kind.startswith('out') or None:
# devType = 0
# elif kind.startswith('in'):
# devType = 1
# else:
# raise ValueError('Invalid value for `kind`.')
#
# # query the number of devices of `kind` from SDL
# devCount = sdl2.get_num_audio_devices(devType)
#
# # DEBUG: make sure we have an integer
# assert isinstance(devCount, (int,))
#
# # build the dictionary of audio devices
# devs = dict()
# for devIdx in range(devCount):
# # create new entry in output dict
# devName = str(sdl2.get_audio_device_name(devIdx, 0), encoding="utf-8")
# devs[devName] = dict()
# devs['name'] = devName # redundant?
# devs['id'] = devIdx
#
# # query additional information from SDL2 about device
def init(rate=22050, bits=16, stereo=True, buffer=1024):
"""If you need a specific format for sounds you need to run this init
function. Run this *before creating your visual.Window*.
The format cannot be changed once initialised or once a Window has been
created.
If a Sound object is created before this function is run it will be
executed with default format (signed 16bit stereo at 22KHz).
For more details see pygame help page for the mixer.
"""
global Sound, audioDriver
Sound = SoundPygame
audioDriver = 'n/a'
if stereo == True:
stereoChans = 2
else:
stereoChans = 0
if bits == 16:
# for pygame bits are signed for 16bit, signified by the minus
bits = -16
# defaults: 22050Hz, 16bit, stereo,
mixer.init(rate, bits, stereoChans, buffer)
sndarray.use_arraytype("numpy")
setRate, setBits, setStereo = mixer.get_init()
if setRate != rate:
logging.warn('Requested sound sample rate was not poossible')
if setBits != bits:
logging.warn('Requested sound depth (bits) was not possible')
if setStereo != 2 and stereo == True:
logging.warn('Requested stereo setting was not possible')
class SoundPygame(_SoundBase):
"""Create a sound object, from one of many ways.
Parameters
----------
value: int, float, str or ndarray
* If it's a number between 37 and 32767 then a tone will be generated at
that frequency in Hz.
* It could be a string for a note ('A', 'Bfl', 'B', 'C', 'Csh', ...).
Then you may want to specify which octave as well.
* Or a string could represent a filename in the current location, or
mediaLocation, or a full path combo.
* Or by giving an Nx2 numpy array of floats (-1:1) you can specify the
sound yourself as a waveform.
secs: float
Duration in seconds (only relevant if the value is a note name or a
frequency value.)
octave:
Middle octave of a piano is 4. Most computers won't output sounds in the
bottom octave (1) and the top octave (8) is generally painful. Is only
relevant if the value is a note name.
sampleRate: int
Audio sample rate, default is 44100 Hz.
bits: int
Bit depth. Pygame uses the same bit depth for all sounds once
initialised. Default is 16.
"""
def __init__(self, value="C", secs=0.5, octave=4, sampleRate=44100,
bits=16, name='', autoLog=True, loops=0, stereo=True,
hamming=False, speaker=None):
self.name = name # only needed for autoLogging
self.autoLog = autoLog
self.speaker = self._parseSpeaker(speaker)
if stereo == True:
stereoChans = 2
else:
stereoChans = 0
if bits == 16:
# for pygame bits are signed for 16bit, signified by the minus
bits = -16
# check initialisation
if not mixer.get_init():
pygame.mixer.init(sampleRate, bits, stereoChans, 3072)
inits = mixer.get_init()
if inits is None:
init()
inits = mixer.get_init()
self.sampleRate, self.format, self.isStereo = inits
if hamming:
logging.warning("Hamming was requested using the 'pygame' sound "
"library but hamming is not supported there.")
self.hamming = False
# try to create sound
self._snd = None
# distinguish the loops requested from loops actual because of
# infinite tones (which have many loops but none requested)
# -1 for infinite or a number of loops
self.requestedLoops = self.loops = int(loops)
self.setSound(value=value, secs=secs, octave=octave, hamming=False)
self._isPlaying = False
@property
def isPlaying(self):
"""`True` if the audio playback is ongoing."""
return self._isPlaying
def play(self, fromStart=True, log=True, loops=None, when=None):
"""Starts playing the sound on an available channel.
Parameters
----------
fromStart : bool
Not yet implemented.
log : bool
Whether to log the playback event.
loops : int
How many times to repeat the sound after it plays once. If
`loops` == -1, the sound will repeat indefinitely until
stopped.
when: not used but included for compatibility purposes
Notes
-----
If no sound channels are available, it will not play and return `None`.
This runs off a separate thread i.e. your code won't wait for the sound
to finish before continuing. You need to use a `psychopy.core.wait()`
command if you want things to pause. If you call `play()` whiles
something is already playing the sounds will be played over each other.
"""
if self.isPlaying:
return
if loops is None:
loops = self.loops
self._snd.play(loops=loops)
self._isPlaying = True
if log and self.autoLog:
logging.exp("Sound %s started" % self.name, obj=self)
return self
def stop(self, log=True):
"""Stops the sound immediately
"""
if not self.isPlaying:
return
self._snd.stop()
self._isPlaying = False
if log and self.autoLog:
logging.exp("Sound %s stopped" % (self.name), obj=self)
def fadeOut(self, mSecs):
"""fades out the sound (when playing) over mSecs.
Don't know why you would do this in psychophysics but it's easy
and fun to include as a possibility :)
"""
self._snd.fadeout(mSecs)
self.status = STOPPED
def getDuration(self):
"""Gets the duration of the current sound in secs
"""
return self._snd.get_length()
def getVolume(self):
"""Returns the current volume of the sound (0.0:1.0)
"""
return self._snd.get_volume()
def setVolume(self, newVol, log=True):
"""Sets the current volume of the sound (0.0:1.0)
"""
self._snd.set_volume(newVol)
if log and self.autoLog:
msg = "Set Sound %s volume=%.3f"
logging.exp(msg % (self.name, newVol), obj=self)
return self.getVolume()
def _setSndFromFile(self, fileName):
# alias default names (so it always points to default.png)
if fileName in ft.defaultStim:
fileName = Path(prefs.paths['assets']) / ft.defaultStim[fileName]
# load the file
if not path.isfile(fileName):
msg = "Sound file %s could not be found." % fileName
logging.error(msg)
raise ValueError(msg)
self.fileName = fileName
# in case a tone with inf loops had been used before
self.loops = self.requestedLoops
try:
self._snd = mixer.Sound(self.fileName)
except Exception:
msg = "Sound file %s could not be opened using pygame for sound."
logging.error(msg % fileName)
raise ValueError(msg % fileName)
def _setSndFromArray(self, thisArray):
# get a mixer.Sound object from an array of floats (-1:1)
# make stereo if mono
if (self.isStereo == 2 and
(len(thisArray.shape) == 1 or
thisArray.shape[1] < 2)):
tmp = numpy.ones((len(thisArray), 2))
tmp[:, 0] = thisArray
tmp[:, 1] = thisArray
thisArray = tmp
# get the format right
if self.format == -16:
thisArray = (thisArray * 2**15).astype(numpy.int16)
elif self.format == 16:
thisArray = ((thisArray + 1) * 2**15).astype(numpy.uint16)
elif self.format == -8:
thisArray = (thisArray * 2**7).astype(numpy.Int8)
elif self.format == 8:
thisArray = ((thisArray + 1) * 2**7).astype(numpy.uint8)
self._snd = sndarray.make_sound(thisArray)
| 11,135
|
Python
|
.py
| 268
| 33.115672
| 80
| 0.620266
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,862
|
backend_sounddevice.py
|
psychopy_psychopy/psychopy/sound/backend_sounddevice.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Audio playback backend using SoundDevice.
These are optional components that can be obtained by installing the
`psychopy-sounddevice` extension into the current environment.
"""
import psychopy.logging as logging
from .exceptions import DependencyError
try:
from psychopy_sounddevice import (
SoundDeviceSound,
init,
getDevices,
getStreamLabel
)
except (ModuleNotFoundError, ImportError):
logging.error(
"Support for the `sounddevice` audio backend is not available this "
"session. Please install `psychopy-sounddevice` and restart the "
"session to enable support.")
except (NameError, DependencyError):
logging.error(
"Error encountered while loading `psychopy-sounddevice`. Check logs "
"for more information.")
if __name__ == "__main__":
pass
| 895
|
Python
|
.py
| 26
| 29.653846
| 77
| 0.717265
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,863
|
backend_pysound.py
|
psychopy_psychopy/psychopy/sound/backend_pysound.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from pathlib import Path
from psychopy import logging, prefs
from .exceptions import DependencyError
from psychopy.constants import (STARTED, PLAYING, PAUSED, FINISHED, STOPPED,
NOT_STARTED, FOREVER)
from psychopy.tools import attributetools, filetools as ft
from ._base import _SoundBase
try:
import pysoundcard as soundcard
import soundfile as sndfile
except ImportError as err:
# convert this import error to our own, pysoundcard probably not installed
raise DependencyError(repr(err.msg))
import numpy
from os import path
import weakref
def init(rate=44100, stereo=True, buffer=128):
pass
# for compatibility with other backends but not needed
def getDevices(kind=None):
"""Returns a dict of dict of audio devices of specified `kind`
The dict keys are names and items are dicts of properties
"""
devs = {}
for ii, dev in enumerate(soundcard.device_info()):
if (dev['max_output_channels'] == 0 and kind == 'output' or
dev['max_input_channels'] == 0 and kind == 'input'):
continue
# newline characters must be removed
devName = dev['name'].replace('\r\n', '')
devs[devName] = dev
dev['id'] = ii
return devs
# these will be controlled by sound.__init__.py
defaultInput = None
defaultOutput = None
class _PySoundCallbackClass():
"""To use callbacks without creating circular references we need a
callback class.
Both the Stream and the sound object (SoundPySoundCard) point to this.
This receives data and current sample from SoundPySoundCard and is
stored by the c functions in the pysoundcard.Stream. We can't store
a reference here to the original sound instance that created it (or
we would create a circular ref again).
"""
def __init__(self, sndInstance):
self.status = NOT_STARTED
self._sampleIndex = 0
self.bufferSize = sndInstance.bufferSize
self.sndInstance = weakref.ref(sndInstance)
def fillBuffer(self, inData, outData, timeInfo, status):
# inData to record from a buffer(?)
# outData a buffer to write to (length of self.bufferSize)
# timeInfo is a dict
# status = 0 unless
# In tests on a macbook air this function takes around 7microsec
# to run so shouldn't impact on performance. Tested with this code:
# s1 = sound.SoundPySoundCard(secs=10, bufferSize=bSize)
# s1.play()
#
# inDat = numpy.zeros([bSize,2], dtype='f')
# outDat = numpy.zeros([bSize,2], dtype='f')
# t0 = time.time()
# for n in range(nRuns):
# s1._callbacks.fillBuffer(inDat, outDat,
# time_info=None, status=0)
# print("%fms per repeat" %((time.time()-t0)*1000/nRuns))
snd = self.sndInstance()
chansIn, chansOut = snd._stream.channels
nSamples = len(snd.sndArr)
if snd.status == STOPPED:
outData[:] = 0
return soundcard.abort_flag
if self._sampleIndex + self.bufferSize > nSamples:
outData[:] = 0 # set buffer to zero
# then insert the data
place = nSamples - self._sampleIndex
outData[0:place, :] = snd.sndArr[self._sampleIndex:, :]
self._sampleIndex = nSamples
snd._onEOS()
return soundcard.abort_flag
else:
place = self._sampleIndex + self.bufferSize
outData[:, :] = snd.sndArr[self._sampleIndex:place, :] * snd.volume
self._sampleIndex += self.bufferSize
return soundcard.continue_flag
def eos(self, log=True):
"""This is potentially given directly to the paStream but we don't use
it. Instead we're calling our own Sound.eos() from within the
fillBuffer callback
"""
self.sndInstance()._onEOS()
class SoundPySoundCard(_SoundBase):
def __init__(self, value="C", secs=0.5, octave=4, sampleRate=44100,
bits=None, name='', autoLog=True, loops=0, bufferSize=128,
volume=1, stereo=True, speaker=None):
"""Create a sound and get ready to play
:parameters:
value: can be a number, string or an array:
* If it's a number then a tone will be generated at that
frequency in Hz.
* It could be a string for a note ('A', 'Bfl', 'B', 'C',
'Csh', ...). Then you may want to specify which octave
* Or a string could represent a filename in the current
location, or mediaLocation, or a full path combo
* Or by giving an Nx2 numpy array of floats (-1:1) you can
specify the sound yourself as a waveform
secs: duration (only relevant if the value is a note name
or a frequency value)
octave: is only relevant if the value is a note name.
Middle octave of a piano is 4. Most computers won't
output sounds in the bottom octave (1) and the top
octave (8) is generally painful
sampleRate: int (default = 44100)
Will be ignored if a file is used for the sound and the
sampleRate can be determined from the file
name: string
Only used for logging purposes
autoLog: bool (default = true)
Determines whether changes to the object should be logged
by default
loops: int (default = 0)
number of times to loop (0 means play once, -1 means loop
forever)
bufferSize: int (default = 128)
How many samples should be loaded at a time to the sound
buffer. A larger number will reduce speed to play a sound.
If too small then audio artifacts will be heard where the
buffer ran empty
bits:
currently serves no purpose (exists for backwards
compatibility)
volume: 0-1.0
stereo:
currently serves no purpose (exists for backwards
compatibility)
"""
self.name = name # only needed for autoLogging
self.autoLog = autoLog
self.speaker = self._parseSpeaker(speaker)
self.sampleRate = sampleRate
self.bufferSize = bufferSize
self.volume = volume
# try to create sound
self._snd = None
# distinguish the loops requested from loops actual because of
# infinite tones (which have many loops but none requested)
# -1 for infinite or a number of loops
self.requestedLoops = self.loops = int(loops)
self.setSound(value=value, secs=secs, octave=octave)
self._isPlaying = False
@property
def isPlaying(self):
"""`True` if the audio playback is ongoing."""
return self._isPlaying
def play(self, fromStart=True, log=True, loops=None, when=None):
"""Starts playing the sound on an available channel.
:Parameters:
fromStart : bool
Not yet implemented.
log : bool
Whether or not to log the playback event.
loops : int
How many times to repeat the sound after it plays once. If
`loops` == -1, the sound will repeat indefinitely until
stopped.
when: not used
Included for compatibility purposes
:Notes:
If no sound channels are available, it will not play and return
None. This runs off a separate thread, i.e. your code won't
wait for the sound to finish before continuing. You need to
use a psychopy.core.wait() command if you want things to pause.
If you call play() whiles something is already playing the sounds
will be played over each other.
"""
if self.isPlaying:
return
if loops is not None:
self.loops = loops
self._stream.start()
self._isPlaying = True
if log and self.autoLog:
logging.exp("Sound %s started" % (self.name), obj=self)
return self
def stop(self, log=True):
"""Stops the sound immediately"""
if not self.isPlaying: # already stopped
return
self._stream.abort() # _stream.stop() finishes current buffer
self._isPlaying = False
if log and self.autoLog:
logging.exp("Sound %s stopped" % (self.name), obj=self)
def fadeOut(self, mSecs):
"""fades out the sound (when playing) over mSecs.
Don't know why you would do this in psychophysics but it's easy
and fun to include as a possibility :)
"""
# todo
self._isPlaying = False
def getDuration(self):
"""Gets the duration of the current sound in secs
"""
pass # todo
@attributetools.attributeSetter
def volume(self, volume):
"""Returns the current volume of the sound (0.0:1.0)
"""
self.__dict__['volume'] = volume
def setVolume(self, value, operation="", log=None):
"""Sets the current volume of the sound (0.0:1.0)
"""
attributetools.setAttribute(self, 'volume', value, log, operation)
return value # this is returned for historical reasons
def _setSndFromFile(self, fileName):
# alias default names (so it always points to default.png)
if fileName in ft.defaultStim:
fileName = Path(prefs.paths['assets']) / ft.defaultStim[fileName]
# load the file
if not path.isfile(fileName):
msg = "Sound file %s could not be found." % fileName
logging.error(msg)
raise ValueError(msg)
self.fileName = fileName
# in case a tone with inf loops had been used before
self.loops = self.requestedLoops
try:
self.sndFile = sndfile.SoundFile(fileName)
sndArr = self.sndFile.read()
self.sndFile.close()
self._setSndFromArray(sndArr)
except Exception:
msg = "Sound file %s could not be opened using pysoundcard for sound."
logging.error(msg % fileName)
raise ValueError(msg % fileName)
def _setSndFromArray(self, thisArray):
"""For pysoundcard all sounds are ultimately played as an array so
other setSound methods are going to call this having created an arr
"""
self._callbacks = _PySoundCallbackClass(sndInstance=self)
if defaultOutput is not None and type(defaultOutput) != int:
devs = getDevices()
if defaultOutput not in devs:
raise ValueError("Attempted to set use device {!r} to "
"a device that is not available".format(defaultOutput))
else:
device = devs[defaultOutput]['id']
else:
device = defaultOutput
self._stream = soundcard.Stream(samplerate=self.sampleRate,
device=device,
blocksize=self.bufferSize,
channels=1,
callback=self._callbacks.fillBuffer)
self._snd = self._stream
chansIn, chansOut = self._stream.channels
if chansOut > 1 and thisArray.ndim == 1:
# make mono sound stereo
self.sndArr = numpy.resize(thisArray, [2, len(thisArray)]).T
else:
self.sndArr = numpy.asarray(thisArray)
self._nSamples = thisArray.shape[0]
# set to run from the start:
self.seek(0)
def seek(self, t):
self._sampleIndex = t * self.sampleRate
def _onEOS(self, log=True):
if log and self.autoLog:
logging.exp("Sound %s finished" % (self.name), obj=self)
self._isPlaying = False
def __del__(self):
self._stream.close()
| 12,249
|
Python
|
.py
| 274
| 33.985401
| 88
| 0.602417
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,864
|
backend_pyo.py
|
psychopy_psychopy/psychopy/sound/backend_pyo.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Audio playback backend using Pyo.
These are optional components that can be obtained by installing the
`psychopy-pyo` extension into the current environment.
"""
import psychopy.logging as logging
from .exceptions import DependencyError
try:
from psychopy_pyo import (
init,
get_devices_infos,
get_input_devices,
get_output_devices,
getDevices,
SoundPyo)
except (ModuleNotFoundError, ImportError):
logging.error(
"Support for the `pyo` audio backend is not available this session. "
"Please install `psychopy-pyo` and restart the session to enable "
"support.")
except (NameError, DependencyError):
logging.error(
"Error encountered while loading `psychopy-pyo`. Check logs for more "
"information.")
if __name__ == "__main__":
pass
| 892
|
Python
|
.py
| 27
| 27.962963
| 78
| 0.692666
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,865
|
audioclip.py
|
psychopy_psychopy/psychopy/sound/audioclip.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Classes and functions for working with audio data.
"""
# Part of the PsychoPy library
# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd.
# Distributed under the terms of the GNU General Public License (GPL).
__all__ = [
'AudioClip',
'load',
'save',
'AUDIO_SUPPORTED_CODECS',
'AUDIO_CHANNELS_MONO',
'AUDIO_CHANNELS_STEREO',
'AUDIO_CHANNEL_LEFT',
'AUDIO_EAR_LEFT',
'AUDIO_CHANNEL_RIGHT',
'AUDIO_EAR_RIGHT',
'AUDIO_CHANNEL_COUNT',
'AUDIO_EAR_COUNT'
]
from pathlib import Path
import shutil
import tempfile
import numpy as np
import soundfile as sf
from psychopy import prefs
from psychopy import logging
from psychopy.tools.audiotools import *
from psychopy.tools import filetools as ft
from .exceptions import *
# constants for specifying the number of channels
AUDIO_CHANNELS_MONO = 1
AUDIO_CHANNELS_STEREO = 2
# constants for indexing channels
AUDIO_CHANNEL_LEFT = AUDIO_EAR_LEFT = 0
AUDIO_CHANNEL_RIGHT = AUDIO_EAR_RIGHT = 1
AUDIO_CHANNEL_COUNT = AUDIO_EAR_COUNT = 2
class AudioClip:
"""Class for storing audio clip data.
This class is used to store and handle raw audio data, such as those
obtained from microphone recordings or loaded from files. PsychoPy stores
audio samples in contiguous arrays of 32-bit floating-point values ranging
between -1 and 1.
The `AudioClip` class provides basic audio editing capabilities too. You can
use operators on `AudioClip` instances to combine audio clips together. For
instance, the ``+`` operator will return a new `AudioClip` instance whose
samples are the concatenation of the two operands::
sndCombined = sndClip1 + sndClip2
Note that audio clips must have the same sample rates in order to be joined
using the addition operator. For online compatibility, use the `append()`
method instead.
There are also numerous static methods available to generate various tones
(e.g., sine-, saw-, and square-waves). Audio samples can also be loaded and
saved to files in various formats (e.g., WAV, FLAC, OGG, etc.)
You can play `AudioClip` by directly passing instances of this object to
the :class:`~psychopy.sound.Sound` class::
import psychopy.core as core
import psychopy.sound as sound
myTone = AudioClip.sine(duration=5.0) # generate a tone
mySound = sound.Sound(myTone)
mySound.play()
core.wait(5.0) # wait for sound to finish playing
core.quit()
Parameters
----------
samples : ArrayLike
Nx1 or Nx2 array of audio samples for mono and stereo, respectively.
Values in the array representing the amplitude of the sound waveform
should vary between -1 and 1. If not, they will be clipped.
sampleRateHz : int
Sampling rate used to obtain `samples` in Hertz (Hz). The sample rate or
frequency is related to the quality of the audio, where higher sample
rates usually result in better sounding audio (albeit a larger memory
footprint and file size). The value specified should match the frequency
the clip was recorded at. If not, the audio may sound distorted when
played back. Usually, a sample rate of 48kHz is acceptable for most
applications (DVD audio quality). For convenience, module level
constants with form ``SAMPLE_RATE_*`` are provided to specify many
common samples rates.
userData : dict or None
Optional user data to associated with the audio clip.
"""
def __init__(self, samples, sampleRateHz=SAMPLE_RATE_48kHz, userData=None):
# samples should be a 2D array where columns represent channels
self._samples = np.atleast_2d(
np.asarray(samples, dtype=np.float32, order='C'))
self._samples.clip(-1, 1) # force values to be clipped
# set the sample rate of the clip
self._sampleRateHz = int(sampleRateHz)
# the duration of the audio clip
self._duration = len(self.samples) / float(self.sampleRateHz)
# user data
self._userData = userData if userData is not None else {}
assert isinstance(self._userData, dict)
# --------------------------------------------------------------------------
# Loading and saving
#
# These static methods are related to loading and saving audio clips from
# files. The file types supported are those that `libsoundfile` supports.
#
# Additional codecs such as `mp3` require the pydub package which is
# optional.
#
@staticmethod
def _checkCodecSupported(codec, raiseError=False):
"""Check if the audio format string corresponds to a supported codec.
Used internally to check if the user specified a valid codec identifier.
Parameters
----------
codec: str
Codec identifier (e.g., 'wav', 'mp3', etc.)
raiseError : bool
Raise an error (``) instead of returning a value. Default is
`False`.
Returns
-------
bool
`True` if the format is supported.
"""
if not isinstance(codec, str):
raise ValueError('Codec identifier must be a string.')
hasCodec = codec.lower() in AUDIO_SUPPORTED_CODECS
if raiseError and not hasCodec:
fmtList = ["'{}'".format(s) for s in AUDIO_SUPPORTED_CODECS]
raise AudioUnsupportedCodecError(
"Unsupported audio codec specified, must be either: " +
", ".join(fmtList))
return hasCodec
@staticmethod
def load(filename, codec=None):
"""Load audio samples from a file. Note that this is a static method!
Parameters
----------
filename : str
File name to load.
codec : str or None
Codec to use. If `None`, the format will be implied from the file
name.
Returns
-------
AudioClip
Audio clip containing samples loaded from the file.
"""
if codec is not None:
AudioClip._checkCodecSupported(codec, raiseError=True)
samples, sampleRateHz = sf.read(
filename,
dtype='float32',
always_2d=True,
format=codec)
return AudioClip(
samples=samples,
sampleRateHz=sampleRateHz)
def save(self, filename, codec=None):
"""Save an audio clip to file.
Parameters
----------
filename : str
File name to write audio clip to.
codec : str or None
Format to save audio clip data as. If `None`, the format will be
implied from the extension at the end of `filename`.
"""
if codec is not None:
AudioClip._checkCodecSupported(codec, raiseError=True)
# write file
sf.write(
filename,
data=self._samples,
samplerate=self._sampleRateHz,
format=codec)
# log
logging.info(
f"Saved audio data to {filename}"
)
# --------------------------------------------------------------------------
# Tone and noise generation methods
#
# These static methods are used to generate audio samples, such as random
# colored noise (e.g., white) and tones (e.g., sine, square, etc.)
#
# All of these methods return `AudioClip` objects containing the generated
# samples.
#
@staticmethod
def whiteNoise(duration=1.0, sampleRateHz=SAMPLE_RATE_48kHz, channels=2):
"""Generate gaussian white noise.
**New feature, use with caution.**
Parameters
----------
duration : float or int
Length of the sound in seconds.
sampleRateHz : int
Samples rate of the audio for playback.
channels : int
Number of channels for the output.
Returns
-------
AudioClip
"""
samples = whiteNoise(duration, sampleRateHz)
if channels > 1:
samples = np.tile(samples, (1, channels)).astype(np.float32)
return AudioClip(samples, sampleRateHz=sampleRateHz)
@staticmethod
def silence(duration=1.0, sampleRateHz=SAMPLE_RATE_48kHz, channels=2):
"""Generate audio samples for a silent period.
This is used to create silent periods of a very specific duration
between other audio clips.
Parameters
----------
duration : float or int
Length of the sound in seconds.
sampleRateHz : int
Samples rate of the audio for playback.
channels : int
Number of channels for the output.
Returns
-------
AudioClip
Examples
--------
Generate 10 seconds of silence to enjoy::
import psychopy.sound as sound
silence = sound.AudioClip.silence(10.)
Use the silence as a break between two audio clips when concatenating
them::
fullClip = clip1 + sound.AudioClip.silence(10.) + clip2
"""
samples = np.zeros(
(int(duration * sampleRateHz), channels), dtype=np.float32)
return AudioClip(samples, sampleRateHz=sampleRateHz)
@staticmethod
def sine(duration=1.0, freqHz=440, gain=0.8, sampleRateHz=SAMPLE_RATE_48kHz,
channels=2):
"""Generate audio samples for a tone with a sine waveform.
Parameters
----------
duration : float or int
Length of the sound in seconds.
freqHz : float or int
Frequency of the tone in Hertz (Hz). Note that this differs from the
`sampleRateHz`.
gain : float
Gain factor ranging between 0.0 and 1.0. Default is 0.8.
sampleRateHz : int
Samples rate of the audio for playback.
channels : int
Number of channels for the output.
Returns
-------
AudioClip
Examples
--------
Generate an audio clip of a tone 10 seconds long with a frequency of
400Hz::
import psychopy.sound as sound
tone400Hz = sound.AudioClip.sine(10., 400.)
Create a marker/cue tone and append it to pre-recorded instructions::
import psychopy.sound as sound
voiceInstr = sound.AudioClip.load('/path/to/instructions.wav')
markerTone = sound.AudioClip.sine(
1.0, 440., # duration and freq
sampleRateHz=voiceInstr.sampleRateHz) # must be the same!
fullInstr = voiceInstr + markerTone # create instructions with cue
fullInstr.save('/path/to/instructions_with_tone.wav') # save it
"""
samples = sinetone(duration, freqHz, gain, sampleRateHz)
if channels > 1:
samples = np.tile(samples, (1, channels)).astype(np.float32)
return AudioClip(samples, sampleRateHz=sampleRateHz)
@staticmethod
def square(duration=1.0, freqHz=440, dutyCycle=0.5, gain=0.8,
sampleRateHz=SAMPLE_RATE_48kHz, channels=2):
"""Generate audio samples for a tone with a square waveform.
Parameters
----------
duration : float or int
Length of the sound in seconds.
freqHz : float or int
Frequency of the tone in Hertz (Hz). Note that this differs from the
`sampleRateHz`.
dutyCycle : float
Duty cycle between 0.0 and 1.0.
gain : float
Gain factor ranging between 0.0 and 1.0. Default is 0.8.
sampleRateHz : int
Samples rate of the audio for playback.
channels : int
Number of channels for the output.
Returns
-------
AudioClip
"""
samples = squaretone(duration, freqHz, dutyCycle, gain, sampleRateHz)
if channels > 1:
samples = np.tile(samples, (1, channels)).astype(np.float32)
return AudioClip(samples, sampleRateHz=sampleRateHz)
@staticmethod
def sawtooth(duration=1.0, freqHz=440, peak=1.0, gain=0.8,
sampleRateHz=SAMPLE_RATE_48kHz, channels=2):
"""Generate audio samples for a tone with a sawtooth waveform.
Parameters
----------
duration : float or int
Length of the sound in seconds.
freqHz : float or int
Frequency of the tone in Hertz (Hz). Note that this differs from the
`sampleRateHz`.
peak : float
Location of the peak between 0.0 and 1.0. If the peak is at 0.5, the
resulting wave will be triangular. A value of 1.0 will cause the
peak to be located at the very end of a cycle.
gain : float
Gain factor ranging between 0.0 and 1.0. Default is 0.8.
sampleRateHz : int
Samples rate of the audio for playback.
channels : int
Number of channels for the output.
Returns
-------
AudioClip
"""
samples = sawtone(duration, freqHz, peak, gain, sampleRateHz)
if channels > 1:
samples = np.tile(samples, (1, channels)).astype(np.float32)
return AudioClip(samples, sampleRateHz=sampleRateHz)
# --------------------------------------------------------------------------
# Speech synthesis methods
#
# These static methods are used to generate audio samples from text using
# text-to-speech (TTS) engines.
#
@staticmethod
def synthesizeSpeech(text, engine='gtts', synthConfig=None, outFile=None):
"""Synthesize speech from text using a text-to-speech (TTS) engine.
This method is used to generate audio samples from text using a
text-to-speech (TTS) engine. The synthesized speech can be used for
various purposes, such as generating audio cues for experiments or
creating audio instructions for participants.
This method returns an `AudioClip` object containing the synthesized
speech. The quality and format of the retured audio may vary depending
on the TTS engine used.
Please note that online TTS engines may require an active internet
connection to work. This also may send the text to a remote server for
processing, so be mindful of privacy concerns.
Parameters
----------
text : str
Text to synthesize into speech.
engine : str
TTS engine to use for speech synthesis. Default is 'gtts'.
synthConfig : dict or None
Additional configuration options for the specified engine. These
are specified using a dictionary (ex.
`synthConfig={'slow': False}`). These paramters vary depending on
the engine in use. Default is `None` which uses the default
configuration for the engine.
outFile : str or None
File name to save the synthesized speech to. This can be used to
save the audio to a file for later use. If `None`, the audio clip
will be returned in memory. If you plan on using the same audio
clip multiple times, it is recommended to save it to a file and load
it later.
Returns
-------
AudioClip
Audio clip containing the synthesized speech.
Examples
--------
Synthesize speech using the default gTTS engine::
import psychopy.sound as sound
voiceClip = sound.AudioClip.synthesizeSpeech(
'How are you doing today?')
Save the synthesized speech to a file for later use::
voiceClip = sound.AudioClip.synthesizeSpeech(
'How are you doing today?', outFile='/path/to/speech.mp3')
Synthesize speech using the gTTS engine with a specific language,
timeout, and top-level domain::
voiceClip = sound.AudioClip.synthesizeSpeech(
'How are you doing today?',
engine='gtts',
synthConfig={'lang': 'en', 'timeout': 10, 'tld': 'us'})
"""
if engine not in ['gtts']:
raise ValueError('Unsupported TTS engine specified.')
synthConfig = {} if synthConfig is None else synthConfig
if engine == 'gtts': # google's text-to-speech engine
logging.info('Using Google Text-to-Speech (gTTS) engine.')
try:
import gtts
except ImportError:
raise ImportError(
'The gTTS package is required for speech synthesis.')
# set defaults for parameters if not specified
if 'timeout' not in synthConfig:
synthConfig['timeout'] = None
logging.warning(
'The gTTS speech-to-text engine has been configured with '
'an infinite timeout. The application may stall if the '
'server is unresponsive. To set a timeout, specify the '
'`timeout` key in `synthConfig`.')
if 'lang' not in synthConfig: # language
synthConfig['lang'] = 'en'
logging.info(
"Language not specified, defaulting to '{}' for speech "
"synthesis engine.".format(synthConfig['lang']))
else:
# check if the value is a valid language code
if synthConfig['lang'] not in gtts.lang.tts_langs():
raise ValueError('Unsupported language code specified.')
if 'tld' not in synthConfig: # top-level domain
synthConfig['tld'] = 'us'
logging.info(
"Top-level domain (TLD) not specified, defaulting to '{}' "
"for synthesis engine.".format(synthConfig['tld']))
if 'slow' not in synthConfig: # slow mode
synthConfig['slow'] = False
logging.info(
"Slow mode not specified, defaulting to '{}' for synthesis "
"engine.".format(synthConfig['slow']))
try:
handle = gtts.gTTS(
text=text,
**synthConfig)
except gtts.gTTSError as e:
raise AudioSynthesisError(
'Error occurred during speech synthesis: {}'.format(e))
# this is online and needs a download, so we'll save it to a file
with tempfile.TemporaryDirectory() as tmpdir:
# always returns an MP3 file
tmpfile = str(Path(tmpdir) / 'psychopy_tts_output.mp3')
handle.save(tmpfile)
# load audio clip samples to memory
toReturn = AudioClip.load(tmpfile)
# copy the file if we want to save it
import shutil
if outFile is not None:
shutil.copy(tmpfile, outFile)
return toReturn
# --------------------------------------------------------------------------
# Audio editing methods
#
# Methods related to basic editing of audio samples (operations such as
# splicing clips and signal gain).
#
def __add__(self, other):
"""Concatenate two audio clips."""
assert other.sampleRateHz == self._sampleRateHz
assert other.channels == self.channels
newSamples = np.ascontiguousarray(
np.vstack((self._samples, other.samples)),
dtype=np.float32)
toReturn = AudioClip(
samples=newSamples,
sampleRateHz=self._sampleRateHz)
return toReturn
def __iadd__(self, other):
"""Concatenate two audio clips inplace."""
assert other.sampleRateHz == self._sampleRateHz
assert other.channels == self.channels
self._samples = np.ascontiguousarray(
np.vstack((self._samples, other.samples)),
dtype=np.float32)
return self
def append(self, clip):
"""Append samples from another sound clip to the end of this one.
The `AudioClip` object must have the same sample rate and channels as
this object.
Parameters
----------
clip : AudioClip
Audio clip to append.
Returns
-------
AudioClip
This object with samples from `clip` appended.
Examples
--------
Join two sound clips together::
snd1.append(snd2)
"""
# if either clip is empty, just replace it
if len(self.samples) == 0:
return clip
if len(clip.samples) == 0:
return self
assert self.channels == clip.channels
assert self._sampleRateHz == clip.sampleRateHz
self._samples = np.ascontiguousarray(
np.vstack((self._samples, clip.samples)),
dtype=np.float32)
# recompute the duration of the new clip
self._duration = len(self.samples) / float(self.sampleRateHz)
return self
def copy(self):
"""Create an independent copy of this `AudioClip`.
Returns
-------
AudioClip
"""
return AudioClip(
samples=self._samples.copy(),
sampleRateHz=self._sampleRateHz)
def gain(self, factor, channel=None):
"""Apply gain the audio samples.
This will modify the internal store of samples inplace. Clipping is
automatically applied to samples after applying gain.
Parameters
----------
factor : float or int
Gain factor to multiply audio samples.
channel : int or None
Channel to apply gain to. If `None`, gain will be applied to all
channels.
"""
try:
arrview = self._samples[:, :] \
if channel is None else self._samples[:, channel]
except IndexError:
raise ValueError('Invalid value for `channel`.')
# multiply and clip range
arrview *= float(factor)
arrview.clip(-1, 1)
def resample(self, targetSampleRateHz, resampleType='default',
equalEnergy=False, copy=False):
"""Resample audio to another sample rate.
This method will resample the audio clip to a new sample rate. The
method used for resampling can be specified using the `method` parameter.
Parameters
----------
targetSampleRateHz : int
New sample rate.
resampleType : str
Fitler (or method) to use for resampling. The methods available
depend on the packages installed. The 'default' method uses
`scipy.signal.resample` to resample the audio. Other methods require
the user to install `librosa` or `resampy`. Default is 'default'.
equalEnergy : bool
Make the output have similar energy to the input. Option not
available for the 'default' method. Default is `False`.
copy : bool
Return a copy of the resampled audio clip at the new sample rate.
If `False`, the audio clip will be resampled inplace. Default is
`False`.
Returns
-------
AudioClip
Resampled audio clip.
Notes
-----
* Resampling audio clip may result in distortion which is exacerbated by
successive resampling.
* When using `librosa` for resampling, the `fix` parameter is set to
`False`.
* The resampling types 'linear', 'zero_order_hold', 'sinc_best',
'sinc_medium' and 'sinc_fastest' require the `samplerate` package to
be installed in addition to `librosa`.
* Specifying either the 'fft' or 'scipy' method will use the same
resampling method as the 'default' method, howwever it will allow for
the `equalEnergy` option to be used.
Examples
--------
Resample an audio clip to 44.1kHz::
snd.resample(44100)
Use the 'soxr_vhq' method for resampling::
snd.resample(44100, resampleType='soxr_vhq')
Create a copy of the audio clip resampled to 44.1kHz::
sndResampled = snd.resample(44100, copy=True)
Resample the audio clip to be playable on a certain device::
import psychopy.sound as sound
from psychopy.sound.audioclip import AudioClip
audioClip = sound.AudioClip.load('/path/to/audio.wav')
deviceSampleRateHz = sound.Sound().sampleRate
audioClip.resample(deviceSampleRateHz)
"""
targetSampleRateHz = int(targetSampleRateHz) # ensure it's an integer
# sample rate is the same, return self
if targetSampleRateHz == self._sampleRateHz:
if copy:
return AudioClip(
self._samples.copy(),
sampleRateHz=self._sampleRateHz)
logging.info('No resampling needed, sample rate is the same.')
return self # no need to resample
if resampleType == 'default': # scipy
import scipy.signal # hard dep, so we'll import here
# the simplest method to resample audio using the libraries we have
# already
nSamp = round(
len(self._samples) * float(targetSampleRateHz) /
self.sampleRateHz)
newSamples = scipy.signal.resample(
self._samples, nSamp, axis=0)
if equalEnergy:
logging.warning(
'The `equalEnergy` option is not available for the '
'default resampling method.')
elif resampleType in ('kaiser_best', 'kaiser_fast'): # resampy
try:
import resampy
except ImportError:
raise ImportError(
'The `resampy` package is required for this resampling '
'method ({}).'.format(resampleType))
newSamples = resampy.resample(
self._samples,
self._sampleRateHz,
targetSampleRateHz,
filter=resampleType,
scale=equalEnergy,
axis=0)
elif resampleType in ('soxr_vhq', 'soxr_hq', 'soxr_mq', 'soxr_lq',
'soxr_qq', 'polyphase', 'linear', 'zero_order_hold', 'fft',
'scipy', 'sinc_best', 'sinc_medium', 'sinc_fastest'): # librosa
try:
import librosa
except ImportError:
raise ImportError(
'The `librosa` package is required for this resampling '
'method ({}).'.format(resampleType))
newSamples = librosa.resample(
self._samples,
orig_sr=self._sampleRateHz,
target_sr=targetSampleRateHz,
res_type=resampleType,
scale=equalEnergy,
fix=False,
axis=0)
else:
raise ValueError('Unsupported resampling method specified.')
logging.info(
"Resampled audio from {}Hz to {}Hz using method '{}'.".format(
self._sampleRateHz, targetSampleRateHz, resampleType))
if copy: # return a new object
return AudioClip(newSamples, sampleRateHz=targetSampleRateHz)
# inplace resampling, need to clear the old array since the shape may
# have changed
self._samples = newSamples
self._sampleRateHz = targetSampleRateHz
return self
# --------------------------------------------------------------------------
# Audio analysis methods
#
# Methods related to basic analysis of audio samples, nothing too advanced
# but still useful.
#
def rms(self, channel=None):
"""Compute the root mean square (RMS) of the samples to determine the
average signal level.
Parameters
----------
channel : int or None
Channel to compute RMS (zero-indexed). If `None`, the RMS of all
channels will be computed.
Returns
-------
ndarray or float
An array of RMS values for each channel if ``channel=None`` (even if
there is one channel an array is returned). If `channel` *was*
specified, a `float` will be returned indicating the RMS of that
single channel.
"""
if channel is not None:
assert 0 < channel < self.channels
# get samples
arr = self._samples if channel is None else self._samples[:, channel]
# calculate rms
rms = np.nan_to_num(np.sqrt(np.nanmean(np.square(arr), axis=0)), nan=0)
return rms if len(rms) > 1 else rms[0]
# --------------------------------------------------------------------------
# Properties
#
@property
def samples(self):
"""Nx1 or Nx2 array of audio samples (`~numpy.ndarray`).
Values must range from -1 to 1. Values outside that range will be
clipped, possibly resulting in distortion.
"""
return self._samples
@samples.setter
def samples(self, value):
self._samples = np.asarray(value, dtype=float) # convert to array
self._samples.clip(-1., 1.) # do clipping to keep samples in range
# recompute duration after updating samples
self._duration = len(self._samples) / float(self._sampleRateHz)
@property
def sampleRateHz(self):
"""Sample rate of the audio clip in Hz (`int`). Should be the same
value as the rate `samples` was captured at.
"""
return self._sampleRateHz
@sampleRateHz.setter
def sampleRateHz(self, value):
self._sampleRateHz = int(value)
# recompute duration after updating sample rate
self._duration = len(self._samples) / float(self._sampleRateHz)
@property
def duration(self):
"""The duration of the audio in seconds (`float`).
This value is computed using the specified sampling frequency and number
of samples.
"""
return self._duration
@property
def channels(self):
"""Number of audio channels in the clip (`int`).
If `channels` > 1, the audio clip is in stereo.
"""
return self._samples.shape[1]
@property
def isStereo(self):
"""`True` if there are two channels of audio samples.
Usually one for each ear. The first channel is usually the left ear, and
the second the right.
"""
return not self.isMono # are we moving in stereo? ;)
@property
def isMono(self):
"""`True` if there is only one channel of audio data.
"""
return self._samples.shape[1] == 1
@property
def userData(self):
"""User data associated with this clip (`dict`). Can be used for storing
additional data related to the clip. Note that `userData` is not saved
with audio files!
Example
-------
Adding fields to `userData`. For instance, we want to associated the
start time the clip was recorded at with it::
myClip.userData['date_recorded'] = t_start
We can access that field later by::
thisRecordingStartTime = myClip.userData['date_recorded']
"""
return self._userData
@userData.setter
def userData(self, value):
assert isinstance(value, dict)
self._userData = value
def convertToWAV(self):
"""Get a copy of stored audio samples in WAV PCM format.
Returns
-------
ndarray
Array with the same shapes as `.samples` but in 16-bit WAV PCM
format.
"""
return np.asarray(
self._samples * ((1 << 15) - 1), dtype=np.int16).tobytes()
def asMono(self, copy=True):
"""Convert the audio clip to mono (single channel audio).
Parameters
----------
copy : bool
If `True` an :class:`~psychopy.sound.AudioClip` containing a copy
of the samples will be returned. If `False`, channels will be
mixed inplace resulting in the same object being returned. User data
is not copied.
Returns
-------
:class:`~psychopy.sound.AudioClip`
Mono version of this object.
"""
samples = np.atleast_2d(self._samples) # enforce 2D
if samples.shape[1] > 1:
samplesMixed = np.atleast_2d(
np.sum(samples, axis=1, dtype=np.float32) / np.float32(2.)).T
else:
samplesMixed = samples.copy()
if copy:
return AudioClip(samplesMixed, self.sampleRateHz)
self._samples = samplesMixed # overwrite
return self
def asStereo(self, copy=True):
"""Convert the audio clip to stereo (two channel audio).
Parameters
----------
copy : bool
If `True` an :class:`~psychopy.sound.AudioClip` containing a copy
of the samples will be returned. If `False`, channels will be
mixed inplace resulting in the same object being returned. User data
is not copied.
Returns
-------
:class:`~psychopy.sound.AudioClip`
Stereo version of this object.
"""
if self.channels == 2:
return self
samples = np.atleast_2d(self._samples) # enforce 2D
samples = np.hstack((samples, samples))
if copy:
return AudioClip(samples, self.sampleRateHz)
self._samples = samples # overwrite
return self
def transcribe(self, engine='whisper', language='en-US', expectedWords=None,
config=None):
"""Convert speech in audio to text.
This function accepts an audio clip and returns a transcription of the
speech in the clip. The efficacy of the transcription depends on the
engine selected, audio quality, and language support.
Speech-to-text conversion blocks the main application thread when used
on Python. Don't transcribe audio during time-sensitive parts of your
experiment! Instead, initialize the transcriber before the experiment
begins by calling this function with `audioClip=None`.
Parameters
----------
engine : str
Speech-to-text engine to use.
language : str
BCP-47 language code (eg., 'en-US'). Note that supported languages
vary between transcription engines.
expectedWords : list or tuple
List of strings representing expected words or phrases. This will
constrain the possible output words to the ones specified which
constrains the model for better accuracy. Note not all engines
support this feature (only Sphinx and Google Cloud do at this time).
A warning will be logged if the engine selected does not support this
feature. CMU PocketSphinx has an additional feature where the
sensitivity can be specified for each expected word. You can
indicate the sensitivity level to use by putting a ``:`` after each
word in the list (see the Example below). Sensitivity levels range
between 0 and 100. A higher number results in the engine being more
conservative, resulting in a higher likelihood of false rejections.
The default sensitivity is 80% for words/phrases without one
specified.
config : dict or None
Additional configuration options for the specified engine. These
are specified using a dictionary (ex. `config={'pfilter': 1}` will
enable the profanity filter when using the `'google'` engine).
Returns
-------
:class:`~psychopy.sound.transcribe.TranscriptionResult`
Transcription result.
Notes
-----
* The recommended transcriber is OpenAI Whisper which can be used locally
without an internet connection once a model is downloaded to cache. It
can be selected by passing `engine='whisper'` to this function.
* Online transcription services (eg., Google) provide robust and accurate
speech recognition capabilities with broader language support than
offline solutions. However, these services may require a paid
subscription to use, reliable broadband internet connections, and may
not respect the privacy of your participants as their responses are
being sent to a third-party. Also consider that a track of audio data
being sent over the network can be large, users on metered connections
may incur additional costs to run your experiment. Offline
transcription services (eg., CMU PocketSphinx and OpenAI Whisper) do not
require an internet connection after the model has been downloaded and
installed.
* If the audio clip has multiple channels, they will be combined prior to
being passed to the transcription service if needed.
"""
# avoid circular import
from psychopy.sound.transcribe import (
getActiveTranscriber,
setupTranscriber)
# get the active transcriber
transcriber = getActiveTranscriber()
if transcriber is None:
logging.warning(
'No active transcriber, creating one now! If this happens in '
'a time sensitive part of your experiment, consider creating '
'the transcriber before the experiment begins by calling '
'`psychopy.sound.transcribe.setupTranscriber()` function.'
)
setupTranscriber(engine=engine, config=config)
transcriber = getActiveTranscriber() # get again
return transcriber.transcribe(
self,
language=language,
expectedWords=expectedWords,
config=config)
def load(filename, codec=None):
"""Load an audio clip from file.
Parameters
----------
filename : str
File name to load.
codec : str or None
Codec to use. If `None`, the format will be implied from the file name.
Returns
-------
AudioClip
Audio clip containing samples loaded from the file.
"""
# alias default names (so it always points to default.png)
if filename in ft.defaultStim:
filename = Path(prefs.paths['assets']) / ft.defaultStim[filename]
return AudioClip.load(filename, codec)
def save(filename, clip, codec=None):
"""Save an audio clip to file.
Parameters
----------
filename : str
File name to write audio clip to.
clip : AudioClip
The clip with audio samples to write.
codec : str or None
Format to save audio clip data as. If `None`, the format will be
implied from the extension at the end of `filename`.
"""
clip.save(filename, codec)
if __name__ == "__main__":
pass
| 39,658
|
Python
|
.py
| 907
| 33.351709
| 83
| 0.606126
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,866
|
backend_ptb.py
|
psychopy_psychopy/psychopy/sound/backend_ptb.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
New backend for the Psychtoolbox portaudio engine
"""
import sys
import os
import time
import re
import weakref
from pathlib import Path
from psychopy import prefs, logging, exceptions
from psychopy.constants import (STARTED, PAUSED, FINISHED, STOPPING,
NOT_STARTED)
from psychopy.tools import systemtools
from psychopy.tools import filetools as ft
from .exceptions import SoundFormatError, DependencyError
from ._base import _SoundBase, HammingWindow
from ..hardware import DeviceManager
try:
from psychtoolbox import audio
import psychtoolbox as ptb
except Exception:
raise DependencyError("psychtoolbox audio failed to import")
try:
import soundfile as sf
except Exception:
raise DependencyError("soundfile not working")
import numpy as np
try:
defaultLatencyClass = int(prefs.hardware['audioLatencyMode'][0])
except (TypeError, IndexError): # maybe we were given a number instead
defaultLatencyClass = prefs.hardware['audioLatencyMode']
"""vals in prefs.hardware['audioLatencyMode'] are:
{0:_translate('Latency not important'),
1:_translate('Share low-latency driver'),
2:_translate('Exclusive low-latency'),
3:_translate('Aggressive low-latency'),
4:_translate('Latency critical')}
Based on help at http://psychtoolbox.org/docs/PsychPortAudio-Open
"""
# suggestedLatency = 0.005 ## Not currently used. Keep < 1 scr refresh
if prefs.hardware['audioDriver']=='auto':
audioDriver = None
else:
audioDriver = prefs.hardware['audioDriver']
if prefs.hardware['audioDevice']=='auto':
audioDevice = None
else:
audioDevice = prefs.hardware['audioDevice']
# check if we should only use WAS host API (default is True on Windows)
audioWASAPIOnly = False
if sys.platform == 'win32' and prefs.hardware['audioWASAPIOnly']:
audioWASAPIOnly = True
# these will be used by sound.__init__.py
defaultInput = None
defaultOutput = audioDevice
logging.info("Loaded psychtoolbox audio version {}"
.format(audio.get_version_info()['version']))
# ask PTB to align verbosity with our current logging level at console
_verbosities = ((logging.DEBUG, 5),
(logging.INFO, 4),
(logging.EXP, 3),
(logging.WARNING, 2),
(logging.ERROR, 1))
for _logLevel, _verbos in _verbosities:
if logging.console.level <= _logLevel:
audio.verbosity(_verbos)
break
def init(rate=48000, stereo=True, buffer=128):
pass # for compatibility with other backends
def getDevices(kind=None):
"""Returns a dict of dict of audio devices of specified `kind`
kind can be None, 'input' or 'output'
The dict keys are names, and items are dicts of properties
"""
if audioWASAPIOnly:
deviceTypes = 13 # only WASAPI drivers need apply!
else:
deviceTypes = None
devs = {}
if systemtools.isVM_CI(): # GitHub actions VM does not have a sound device
return devs
else:
allDevs = audio.get_devices(device_type=deviceTypes)
# annoyingly query_devices is a DeviceList or a dict depending on number
if isinstance(allDevs, dict):
allDevs = [allDevs]
for ii, dev in enumerate(allDevs):
if kind and kind.startswith('in'):
if dev['NrInputChannels'] < 1:
continue
elif kind and kind.startswith('out'):
if dev['NrOutputChannels'] < 1:
continue
# we have a valid device so get its name
# newline characters must be removed
devName = dev['DeviceName'].replace('\r\n', '')
devs[devName] = dev
dev['id'] = ii
return devs
def getStreamLabel(sampleRate, channels, blockSize):
"""Returns the string repr of the stream label
"""
return "{}_{}_{}".format(sampleRate, channels, blockSize)
class _StreamsDict(dict):
"""Keeps track of what streams have been created. On macOS we can have
multiple streams under portaudio but under windows we can only have one.
use the instance `streams` rather than creating a new instance of this
"""
def __init__(self, index):
# store device index
self.index = index
def getStream(self, sampleRate, channels, blockSize):
"""Gets a stream of exact match or returns a new one
(if possible for the current operating system)
"""
# if the query looks flexible then try getSimilar
if channels == -1 or blockSize == -1:
return self._getSimilar(sampleRate,
channels=channels,
blockSize=blockSize)
else:
return self._getStream(sampleRate,
channels=channels,
blockSize=blockSize)
def _getSimilar(self, sampleRate, channels=-1, blockSize=-1):
"""Do we already have a compatible stream?
Many sounds can allow channels and blocksize to change but samplerate
is generally fixed. Any values set to -1 above will be flexible. Any
values set to an alternative number will be fixed
usage:
label, stream = streams._getSimilar(sampleRate=44100, # must match
channels=-1, # any
blockSize=-1) # wildcard
"""
label = getStreamLabel(sampleRate, channels, blockSize)
# replace -1 with any regex integer
simil = re.compile(label.replace("-1", r"[-+]?(\d+)")) # I hate REGEX!
for thisFormat in self:
if simil.match(thisFormat): # we found a close-enough match
return thisFormat, self[thisFormat]
# if we've been given values in each place then create stream
if (sampleRate not in [None, -1, 0] and
channels not in [None, -1] and
blockSize not in [None, -1]):
return self._getStream(sampleRate, channels, blockSize)
def _getStream(self, sampleRate, channels, blockSize):
"""Strict check for this format or create new
"""
label = getStreamLabel(sampleRate, channels, blockSize)
# try to retrieve existing stream of that name
if label in self:
pass
# todo: check if this is still needed on win32
# on some systems more than one stream isn't supported so check
elif sys.platform == 'win32' and len(self):
raise SoundFormatError(
"Tried to create audio stream {} but {} already exists "
"and {} doesn't support multiple portaudio streams"
.format(label, list(self.keys())[0], sys.platform)
)
else:
# create new stream
self[label] = _MasterStream(sampleRate, channels, blockSize,
device=self.index)
return label, self[label]
devices = {}
class _MasterStream(audio.Stream):
def __init__(self, sampleRate, channels, blockSize,
device=None, duplex=False, mode=1,
audioLatencyClass=None):
# initialise thread
if audioLatencyClass is None:
audioLatencyClass = defaultLatencyClass
self.streamLabel = None
self.streams = []
self.list = []
# sound stream info
self.sampleRate = sampleRate
self.channels = channels
self.duplex = duplex
self.blockSize = blockSize
self.label = getStreamLabel(sampleRate, channels, blockSize)
if isinstance(device, list) and len(device):
device = device[0]
if isinstance(device, str): # we need to convert name to an ID or make None
devs = getDevices('output')
if device in devs:
deviceID = devs[device]['DeviceIndex']
else:
deviceID = None
else:
deviceID = device
self.sounds = [] # list of dicts for sounds currently playing
self.takeTimeStamp = False
self.frameN = 1
# self.frameTimes = range(5) # DEBUGGING: store the last 5 callbacks
if not systemtools.isVM_CI(): # Github Actions VM does not have a sound device
try:
audio.Stream.__init__(self, device_id=deviceID, mode=mode+8,
latency_class=audioLatencyClass,
freq=sampleRate,
channels=channels,
) # suggested_latency=suggestedLatency
except OSError as e: # noqa: F841
audio.Stream.__init__(self, device_id=deviceID, mode=mode+8,
latency_class=audioLatencyClass,
# freq=sampleRate,
channels=channels,
)
self.sampleRate = self.status['SampleRate']
print("Failed to start PTB.audio with requested rate of "
"{} but succeeded with a default rate ({}). "
"This is depends on the selected latency class and device."
.format(sampleRate, self.sampleRate))
except TypeError as e:
print("device={}, mode={}, latency_class={}, freq={}, channels={}"
.format(device, mode+8, audioLatencyClass, sampleRate, channels))
raise e
except Exception as e:
if deviceID == -1:
# if default device doesn't setup from ptb, pick first device
for device in audio.get_devices(device_type=13):
logging.error(
f"System default audio device failed to connect, so using first found "
f"device: {device['DeviceName']}"
)
audio.Stream.__init__(
self,mode=mode+8,
device_id=device['DeviceIndex'],
freq=device['DefaultSampleRate'],
channels=device['NrOutputChannels']
)
break
else:
# any other problem, try with no device ID
audio.Stream.__init__(
self, mode=mode+8,
latency_class=audioLatencyClass,
freq=sampleRate,
channels=channels,
)
if "there isn't any audio output device" in str(e):
print("Failed to load audio device:\n"
" '{}'\n"
"so fetching default audio device instead: \n"
" '{}'"
.format(device, 'test'))
self.start(0, 0, 1)
# self.device = self._sdStream.device
# self.latency = self._sdStream.latency
# self.cpu_load = self._sdStream.cpu_load
self._tSoundRequestPlay = 0
class SoundPTB(_SoundBase):
"""Play a variety of sounds using the new PsychPortAudio library
"""
def __init__(self, value="C", secs=0.5, octave=4, stereo=-1,
volume=1.0, loops=0,
sampleRate=None, blockSize=128,
preBuffer=-1,
hamming=True,
startTime=0, stopTime=-1,
name='', autoLog=True,
syncToWin=None, speaker=None):
"""
:param value: note name ("C","Bfl"), filename or frequency (Hz)
:param secs: duration (for synthesised tones)
:param octave: which octave to use for note names (4 is middle)
:param stereo: -1 (auto), True or False
to force sounds to stereo or mono
:param volume: float 0-1
:param loops: number of loops to play (-1=forever, 0=single repeat)
:param sampleRate: sample rate for synthesized tones
:param blockSize: the size of the buffer on the sound card
(small for low latency, large for stability)
:param preBuffer: integer to control streaming/buffering
- -1 means store all
- 0 (no buffer) means stream from disk
- potentially we could buffer a few secs(!?)
:param hamming: boolean (default True) to indicate if the sound should
be apodized (i.e., the onset and offset smoothly ramped up from
down to zero). The function apodize uses a Hanning window, but
arguments named 'hamming' are preserved so that existing code
is not broken by the change from Hamming to Hanning internally.
Not applied to sounds from files.
:param startTime: for sound files this controls the start of snippet
:param stopTime: for sound files this controls the end of snippet
:param name: string for logging purposes
:param autoLog: whether to automatically log every change
:param syncToWin: if you want start/stop to sync with win flips add this
"""
self.speaker = self._parseSpeaker(speaker)
self.sound = value
self.name = name
self.secs = secs # for any synthesised sounds (notesand freqs)
self.octave = octave # for note name sounds
self.loops = self._loopsRequested = loops
self._loopsFinished = 0
self.volume = volume
self.startTime = startTime # for files
self.stopTime = stopTime # for files specify thesection to be played
self.blockSize = blockSize # can be per-sound unlike other backends
self.preBuffer = preBuffer
self.frameN = 0
self._tSoundRequestPlay = 0
self.sampleRate = sampleRate
self.channels = None # let this be set by stereo
self.stereo = stereo
self.duplex = None
self.autoLog = autoLog
self.streamLabel = ""
self.sourceType = 'unknown' # set to be file, array or freq
self.sndFile = None
self.sndArr = None
self.hamming = hamming
self._hammingWindow = None # will be created during setSound
self.win = syncToWin
# setSound (determines sound type)
self.setSound(value, secs=self.secs, octave=self.octave,
hamming=self.hamming)
self._isPlaying = False # set `True` after `play()` is called
self._isFinished = False
self.status = NOT_STARTED
@property
def isPlaying(self):
"""`True` if the audio playback is ongoing."""
# This will update _isPlaying if sound has stopped by _EOS()
_ = self._checkPlaybackFinished()
return self._isPlaying
@property
def isFinished(self):
"""`True` if the audio playback has completed."""
return self._checkPlaybackFinished()
def _getDefaultSampleRate(self):
"""Check what streams are open and use one of these"""
if len(devices.get(self.speaker.index, [])):
return list(devices[self.speaker.index].values())[0].sampleRate
else:
return 48000 # seems most widely supported
@property
def statusDetailed(self):
if not self.track:
return None
return self.track.status
@property
def volume(self):
return self.__dict__['volume']
@volume.setter
def volume(self, newVolume):
self.__dict__['volume'] = newVolume
if 'track' in self.__dict__:
# Update volume of an existing track, if it exists.
# (BUGFIX, otherwise only the member variable is updated, but the sound
# volume does not change while playing - Suddha Sourav, 14.10.2020)
self.__dict__['track']().volume = newVolume
else:
return None
@property
def stereo(self):
return self.__dict__['stereo']
@stereo.setter
def stereo(self, val):
# if auto, get from speaker
if val == -1:
val = self.speaker.channels > 1
# store value
self.__dict__['stereo'] = val
# convert to n channels
if val is True:
self.__dict__['channels'] = 2
elif val is False:
self.__dict__['channels'] = 1
elif val == -1:
self.__dict__['channels'] = -1
def setSound(self, value, secs=0.5, octave=4, hamming=None, log=True):
"""Set the sound to be played.
Often this is not needed by the user - it is called implicitly during
initialisation.
:parameters:
value: can be a number, string or an array:
* If it's a number between 37 and 32767 then a tone will
be generated at that frequency in Hz.
* It could be a string for a note ('A', 'Bfl', 'B', 'C',
'Csh'. ...). Then you may want to specify which octave.
* Or a string could represent a filename in the current
location, or mediaLocation, or a full path combo
* Or by giving an Nx2 numpy array of floats (-1:1) you can
specify the sound yourself as a waveform
secs: duration (only relevant if the value is a note name or
a frequency value)
octave: is only relevant if the value is a note name.
Middle octave of a piano is 4. Most computers won't
output sounds in the bottom octave (1) and the top
octave (8) is generally painful
"""
# reset self.loops to what was requested (in case altered for infinite play of tones)
self.loops = self._loopsRequested
# start with the base class method
_SoundBase.setSound(self, value, secs, octave, hamming, log)
def _setSndFromFile(self, filename):
# alias default names (so it always points to default.png)
if filename in ft.defaultStim:
filename = Path(prefs.paths['assets']) / ft.defaultStim[filename]
self.sndFile = f = sf.SoundFile(filename)
self.sourceType = 'file'
self.sampleRate = f.samplerate
if self.channels == -1: # if channels was auto then set to file val
self.channels = f.channels
fileDuration = float(len(f)) / f.samplerate # needed for duration?
# process start time
if self.startTime and self.startTime > 0:
startFrame = self.startTime * self.sampleRate
self.sndFile.seek(int(startFrame))
self.t = self.startTime
else:
self.t = 0
# process stop time
if self.stopTime and self.stopTime > 0:
requestedDur = self.stopTime - self.t
self.duration = min(requestedDur, fileDuration)
else:
self.duration = fileDuration - self.t
# can now calculate duration in frames
self.durationFrames = int(round(self.duration * self.sampleRate))
# are we preloading or streaming?
if self.preBuffer == 0:
# no buffer - stream from disk on each call to nextBlock
pass
elif self.preBuffer == -1:
# full pre-buffer. Load requested duration to memory
sndArr = self.sndFile.read(
frames=int(self.sampleRate * self.duration))
self.sndFile.close()
self._setSndFromArray(sndArr)
self._channelCheck(
self.sndArr) # Check for fewer channels in stream vs data array
def _setSndFromArray(self, thisArray):
self.sndArr = np.asarray(thisArray).astype('float32')
if thisArray.ndim == 1:
self.sndArr.shape = [len(thisArray), 1] # make 2D for broadcasting
if self.channels == 2 and self.sndArr.shape[1] == 1: # mono -> stereo
self.sndArr = self.sndArr.repeat(2, axis=1)
elif self.sndArr.shape[1] == 1: # if channels in [-1,1] then pass
pass
else:
try:
self.sndArr.shape = [len(thisArray), 2]
except ValueError:
raise ValueError("Failed to format sound with shape {} "
"into sound with channels={}"
.format(self.sndArr.shape, self.channels))
# is this stereo?
if self.stereo == -1: # auto stereo. Try to detect
if self.sndArr.shape[1] == 1:
self.stereo = 0
elif self.sndArr.shape[1] == 2:
self.stereo = 1
else:
raise IOError("Couldn't determine whether array is "
"stereo. Shape={}".format(self.sndArr.shape))
self._nSamples = thisArray.shape[0]
if self.stopTime == -1:
self.duration = self._nSamples / float(self.sampleRate)
# set to run from the start:
self.seek(0)
self.sourceType = "array"
# catch when array is empty
if not len(self.sndArr):
logging.warning(
"Received a blank array for sound, playing nothing instead."
)
self.sndArr = np.zeros(shape=(self.blockSize, self.channels))
if not self.track: # do we have one already?
self.track = audio.Slave(self.stream.handle, data=self.sndArr,
volume=self.volume)
else:
self.track.stop()
self.track.fill_buffer(self.sndArr)
def _channelCheck(self, array):
"""Checks whether stream has fewer channels than data. If True, ValueError"""
if self.channels < array.shape[1]:
msg = (
"The sound stream is set up incorrectly. You have fewer channels in the buffer "
"than in data file ({} vs {}).\n**Ensure you have selected 'Force stereo' in "
"experiment settings**".format(self.channels, array.shape[1]))
logging.error(msg)
raise ValueError(msg)
def _checkPlaybackFinished(self):
"""Checks whether playback has finished by looking up the status.
"""
# get detailed status from backend
pa_status = self.statusDetailed
# was the sound already finished?
wasFinished = self._isFinished
# is it finished now?
isFinished = self._isFinished = not pa_status['Active'] and pa_status['State'] == 0
# if it wasn't finished but now is, do end of stream behaviour
if isFinished and not wasFinished:
self._EOS()
return self._isFinished
def play(self, loops=None, when=None, log=True):
"""Start the sound playing.
Calling this after the sound has finished playing will restart the
sound.
"""
if self._checkPlaybackFinished():
self.stop(reset=True)
if loops is not None and self.loops != loops:
self.setLoops(loops)
self._tSoundRequestPlay = time.time()
if hasattr(when, 'getFutureFlipTime'):
logTime = when.getFutureFlipTime(clock=None)
when = when.getFutureFlipTime(clock='ptb')
elif when is None and hasattr(self.win, 'getFutureFlipTime'):
logTime = self.win.getFutureFlipTime(clock=None)
when = self.win.getFutureFlipTime(clock='ptb')
else:
logTime = None
self.track.start(repetitions=loops, when=when)
self._isPlaying = True
self._isFinished = False
# time.sleep(0.)
if log and self.autoLog:
logging.exp(u"Playing sound %s on speaker %s" % (self.name, self.speaker.deviceName), obj=self, t=logTime)
def pause(self, log=True):
"""Stops the sound without reset, so that play will continue from here if needed
"""
if self._isPlaying:
self.stop(reset=False, log=False)
if log and self.autoLog:
logging.exp(u"Sound %s paused" % (self.name), obj=self)
def stop(self, reset=True, log=True):
"""Stop the sound and return to beginning
"""
# this uses FINISHED for some reason, all others use STOPPED
if not self._isPlaying:
return
self.track.stop()
self._isPlaying = False
if reset:
self.seek(0)
if log and self.autoLog:
logging.exp(u"Sound %s stopped" % (self.name), obj=self)
def seek(self, t):
self.t = t
self.frameN = int(round(t * self.sampleRate))
if self.sndFile and not self.sndFile.closed:
self.sndFile.seek(self.frameN)
self._isFinished = t >= self.duration
def _EOS(self, reset=True, log=True):
"""Function called on End Of Stream
"""
self._loopsFinished += 1
if self._loopsFinished >= self._loopsRequested:
# if we have finished all requested loops
self.stop(reset=reset, log=False)
else:
# reset _isFinished back to False
self._isFinished = False
if log and self.autoLog:
logging.exp(u"Sound %s reached end of file" % self.name, obj=self)
@property
def stream(self):
"""Read-only property returns the stream on which the sound
will be played
"""
# if no stream yet, make one
if not self.streamLabel:
# if no streams for current device yet, make a StreamsDict for it
if self.speaker.index not in devices:
devices[self.speaker.index] = _StreamsDict(index=self.speaker.index)
# make stream
try:
label, s = devices[self.speaker.index].getStream(
sampleRate=self.sampleRate,
channels=self.channels,
blockSize=self.blockSize
)
except SoundFormatError as err:
# try to use something similar (e.g. mono->stereo)
# then check we have an appropriate stream open
altern = devices[self.speaker.index]._getSimilar(
sampleRate=self.sampleRate,
channels=-1,
blockSize=-1
)
if altern is None:
raise SoundFormatError(err)
else: # safe to extract data
label, s = altern
# update self in case it changed to fit the stream
self.sampleRate = s.sampleRate
self.channels = s.channels
self.blockSize = s.blockSize
self.streamLabel = label
return devices[self.speaker.index][self.streamLabel]
def __del__(self):
if self.track:
self.track.close()
self.track = None
@property
def track(self):
"""The track on the master stream to which we belong"""
# the track is actually a weak reference to avoid circularity
if 'track' in self.__dict__:
return self.__dict__['track']()
else:
return None
@track.setter
def track(self, track):
if track is None:
self.__dict__['track'] = None
else:
self.__dict__['track'] = weakref.ref(track)
| 27,624
|
Python
|
.py
| 615
| 33.165854
| 118
| 0.58398
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,867
|
__init__.py
|
psychopy_psychopy/psychopy/sound/__init__.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Load and play sounds
We have used a number of different Python libraries ("backends") for generating
sounds in PsychoPy. We started with `Pygame`, then tried `pyo` and `sounddevice`
but we now strongly recommend you use the PTB setting. That uses the
`PsychPortAudio`_ engine, written by Mario Kleiner for `Psychophysics Toolbox`_.
With the PTB backend you get some options about how aggressively you want to try
for low latency, and there is also an option to pre-schedule a sound to play at
a given time in the future.
By default PsychoPy will try to use the following Libs, in this order, for
sound reproduction but you can alter the order in
preferences > hardware > audioLib:
['sounddevice', 'pyo', 'pygame']
For portaudio-based backends (all except for pygame) there is also a
choice of the underlying sound driver (e.g. ASIO, CoreAudio etc).
After importing sound, the sound lib and driver being used will be stored as::
`psychopy.sound.audioLib`
`psychopy.sound.audioDriver`
.. PTB
.. _PsychPortAudio: http://psychtoolbox.org/docs/PsychPortAudio-Open
.. _Psychophysics Toolbox: http://psychtoolbox.org
"""
# Part of the PsychoPy library
# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd.
# Distributed under the terms of the GNU General Public License (GPL).
import sys
import os
import traceback
from psychopy import logging, prefs, constants
from psychopy.tools import systemtools
from .exceptions import DependencyError, SoundFormatError
from .audiodevice import *
from .audioclip import * # import objects related to AudioClip
from . import microphone
__all__ = ["microphone"]
# # import transcription if possible
# try:
# from .transcribe import * # import transcription engine stuff
# except ImportError as err:
# formatted_tb = ''.join(
# traceback.format_exception(type(err), err, err.__traceback__))
# logging.error(
# "Failed to import psychopy.sound.transcribe. Transcription will not be"
# "possible on this machine. For details see stack trace below:\n"
# f"{formatted_tb}")
# used to check if we are on 64-bit Python
bits32 = sys.maxsize == 2 ** 32
# Globals for the sound library. We can only load one audio library at a time,
# so once these values are populated they cannot be changed without restarting
# Python.
pyoSndServer = None
Sound = None
audioLib = None
audioDriver = None
backend = None
# These are the names that can be used in the prefs to specifiy audio libraries.
# The available libraries are hard-coded at this point until we can overhaul
# the sound library to be more modular.
_audioLibs = ['PTB', 'sounddevice', 'pyo', 'pysoundcard', 'pygame']
failed = [] # keep track of audio libs that failed to load
# check if this is being imported on Travis/Github (has no audio card)
if systemtools.isVM_CI():
# for sounddevice we built in some VM protection but not in pyo
prefs.hardware['audioLib'] = ['ptb', 'sounddevice']
# ensure that the value for `audioLib` is a list
if isinstance(prefs.hardware['audioLib'], str):
prefs.hardware['audioLib'] = [prefs.hardware['audioLib']]
thisLibName = None # name of the library we are trying to load
# selection and fallback mechanism for audio libraries
for thisLibName in prefs.hardware['audioLib']:
# Tell the user we are trying to load the specifeid audio library
logging.info(f"Trying to load audio library: {thisLibName}")
# Iterate over the list of audioLibs and try to load the first one that
# is supported. If none are supported, load PTB as a fallback. If PTB isn't
# installed, raise an error.
thisLibName = thisLibName.lower()
# lowercased list of valid audio libraries for safe comparisons
validLibs = [libName.lower() for libName in _audioLibs]
# check if `thisLibName` is a valid audio library
if thisLibName not in validLibs:
failed.append(thisLibName)
logging.warning(f"Invalid audioLib pref: {thisLibName}. "
f"Valid options are: {_audioLibs}")
continue
# select the backend and set the Sound class
if thisLibName == 'ptb':
# The Psychtoolbox backend is preferred, provides the best performance
# and is the only one that supports low-latency scheduling. If no other
# audio backend can be loaded, we will use PTB.
if not bits32:
try:
from . import backend_ptb as backend
Sound = backend.SoundPTB
audioDriver = backend.audioDriver
except Exception:
failed.append(thisLibName)
continue
else:
break
else:
logging.warning("PTB backend is not supported on 32-bit Python. "
"Trying another backend...")
continue
elif thisLibName == 'pyo':
# pyo is a wrapper around PortAudio, which is a cross-platform audio
# library. It is the recommended backend for Windows and Linux.
try:
# Caution: even import failed inside, we still get a module object.
# This is not the case for other backends and may not be desired.
from . import backend_pyo as backend
Sound = backend.SoundPyo
pyoSndServer = backend.pyoSndServer
audioDriver = backend.audioDriver
except Exception:
failed.append(thisLibName)
continue
else:
break
elif thisLibName == 'sounddevice':
# sounddevice is a wrapper around PortAudio, which is a cross-platform
# audio library. It is the recommended backend for Windows and Linux.
try:
# Caution: even import failed inside, we still get a module object.
# This is not the case for other backends and may not be desired.
from . import backend_sounddevice as backend
Sound = backend.SoundDeviceSound
except Exception:
failed.append(thisLibName)
continue
else:
break
elif thisLibName == 'pygame':
# pygame is a cross-platform audio library. It is no longer supported by
# PsychoPy, but we keep it here for backwards compatibility until
# something breaks.
try:
from . import backend_pygame as backend
Sound = backend.SoundPygame
except Exception:
failed.append(thisLibName)
continue
else:
break
elif thisLibName == 'pysoundcard':
# pysoundcard is a wrapper around PortAudio, which is a cross-platform
# audio library.
try:
from . import backend_pysound as backend
Sound = backend.SoundPySoundCard
except Exception:
failed.append(thisLibName)
continue
else:
break
else:
# Catch-all for invalid audioLib prefs.
msg = ("audioLib pref should be one of {!r}, not {!r}"
.format(_audioLibs, thisLibName))
raise ValueError(msg)
else:
# if we get here, there is no audioLib that is supported, try for PTB
msg = ("Failed to load any of the audioLibs: {!r}. Falling back to "
"PsychToolbox ('ptb') backend for sound. Be sure to add 'ptb' to "
"preferences to avoid seeing this message again.".format(failed))
logging.error(msg)
try:
from . import backend_ptb as backend
Sound = backend.SoundPTB
audioDriver = backend.audioDriver
except Exception:
failed.append(thisLibName)
# we successfully loaded a backend if `Sound` is not None
if Sound is not None:
audioLib = thisLibName
init = backend.init
if hasattr(backend, 'getDevices'):
getDevices = backend.getDevices
logging.info('sound is using audioLib: %s' % audioLib)
else:
# if we get here, there is no audioLib that is supported
logging.error(
"No audioLib could be loaded. Tried: {}\n Check whether the necessary "
"audioLibs are installed.".format(prefs.hardware['audioLib']))
# warn the user
if audioLib is not None:
if audioLib.lower() != 'ptb':
# Could be running PTB, just aren't?
logging.warning("We strongly recommend you activate the PTB sound "
"engine in PsychoPy prefs as the preferred audio "
"engine. Its timing is vastly superior. Your prefs "
"are currently set to use {} (in that order)."
.format(prefs.hardware['audioLib']))
# function to set the device (if current lib allows it)
def setDevice(dev, kind=None):
"""Sets the device to be used for new streams being created.
Parameters
----------
dev: str or dict
Name of the device to be used (name, index or sounddevice.device)
kind: str
One of [None, 'output', 'input']
"""
if dev is None:
# if given None, do nothing
return
global backend # pull from module namespace
if not hasattr(backend, 'defaultOutput'):
raise IOError("Attempting to SetDevice (audio) but not supported by "
"the current audio library ({!r})".format(audioLib))
if hasattr(dev, 'name'):
dev = dev['name']
if kind is None:
backend.defaultInput = backend.defaultOutput = dev
elif kind == 'input':
backend.defaultInput = dev
elif kind == 'output':
backend.defaultOutput = dev
else:
if systemtools.isVM_CI(): # no audio device on CI, ignore
return
else:
raise TypeError("`kind` should be one of [None, 'output', 'input'] "
"not {!r}".format(kind))
# Set the device according to user prefs (if current lib allows it)
deviceNames = []
if backend is None:
raise ImportError("None of the audio library backends could be imported. "
"Tried: {}\n Check whether the necessary audioLibs are "
"installed and can be imported successfully."
.format(prefs.hardware['audioLib']))
elif hasattr(backend, 'defaultOutput'):
pref = prefs.hardware['audioDevice']
# is it a list or a simple string?
if isinstance(pref, list):
# multiple options so use zeroth
dev = pref[0]
else:
# a single option
dev = pref
# is it simply "default" (do nothing)
if dev == 'default' or systemtools.isVM_CI():
pass # do nothing
elif dev not in backend.getDevices(kind='output'):
deviceNames = sorted(backend.getDevices(kind='output').keys())
logging.warn(
u"Requested audio device '{}' that is not available on "
"this hardware. The 'audioDevice' preference should be one of "
"{}".format(dev, deviceNames))
else:
setDevice(dev, kind='output')
if __name__ == "__main__":
pass
| 11,021
|
Python
|
.py
| 253
| 36.312253
| 81
| 0.662691
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,868
|
exceptions.py
|
psychopy_psychopy/psychopy/sound/exceptions.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Errors and warnings associated with audio recording and playback.
"""
from ..exceptions import SoundFormatError, DependencyError
# Part of the PsychoPy library
# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd.
# Distributed under the terms of the GNU General Public License (GPL).
__all__ = [
'AudioStreamError',
'AudioFrequencyRangeError',
'AudioUnsupportedSampleRateError',
'AudioInvalidDeviceError',
'AudioUnsupportedCodecError',
'AudioInvalidCaptureDeviceError',
'AudioInvalidPlaybackDeviceError',
'AudioRecordingBufferFullError',
'RecognizerAPICredentialsError',
'RecognizerLanguageNotSupportedError',
'RecognizerEngineNotFoundError',
'SoundFormatError',
'DependencyError'
]
# ------------------------------------------------------------------------------
# Audio hardware and software exceptions
#
class AudioUnsupportedCodecError(Exception):
"""Error raise when trying to save or load and unsupported audio
codec/format.
"""
pass
class AudioStreamError(Exception):
"""Error raised when there is a problem during audio recording/streaming."""
pass
class AudioFrequencyRangeError(Exception): # might transform to a warning
"""Error raised when generating a tone with a frequency outside the audible
range for humans (20Hz to 20kHz).
"""
pass
class AudioUnsupportedSampleRateError(Exception):
"""Error raised when the sampling rate is not supported by the hardware.
"""
pass
class AudioInvalidDeviceError(Exception):
"""Error raised when the audio device configuration does not match any
supported configuration.
"""
pass
class AudioInvalidCaptureDeviceError(AudioInvalidDeviceError):
"""Error raised when the audio device cannot be used for capture (i.e. not
a microphone).
"""
pass
class AudioInvalidPlaybackDeviceError(AudioInvalidDeviceError):
"""Error raised when the audio device is not suitable for playback.
"""
pass
class AudioRecordingBufferFullError(Exception):
"""Error raised when the recording buffer is full."""
pass
# ------------------------------------------------------------------------------
# Transcriber exceptions
#
class RecognizerAPICredentialsError(ValueError):
"""Raised when a given speech recognition is being given improper
credentials (i.e. API key is invalid or not found).
"""
class RecognizerLanguageNotSupportedError(ValueError):
"""Raised when the specified language is not supported by the engine. If you
get this, you need to install the appropriate language support or select
another language.
"""
class RecognizerEngineNotFoundError(ModuleNotFoundError):
"""Raised when the specified recognizer cannot be found. Usually get this
error if the required packages are not installed for a recognizer that is
invoked.
"""
if __name__ == "__main__":
pass
| 3,013
|
Python
|
.py
| 79
| 34.101266
| 80
| 0.719462
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,869
|
transcribe.py
|
psychopy_psychopy/psychopy/sound/transcribe.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Classes and functions for transcribing speech in audio data to text.
"""
# Part of the PsychoPy library
# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd.
# Distributed under the terms of the GNU General Public License (GPL).
__all__ = [
'TranscriptionResult',
'transcribe',
'TRANSCR_LANG_DEFAULT',
'BaseTranscriber',
'recognizerEngineValues',
'recognizeSphinx',
'recognizeGoogle',
'getAllTranscriberInterfaces',
'getTranscriberInterface',
'setupTranscriber',
'getActiveTranscriber',
'getActiveTranscriberEngine',
'submit'
]
import importlib
import json
import sys
import os
import psychopy.logging as logging
from psychopy.alerts import alert
from pathlib import Path
from psychopy.preferences import prefs
from .audioclip import *
from .exceptions import *
import numpy as np
# ------------------------------------------------------------------------------
# Initialize the speech recognition system
#
# _hasSpeechRecognition = True
# try:
# import speech_recognition as sr
# except (ImportError, ModuleNotFoundError):
# logging.warning(
# "Speech-to-text recognition module for PocketSphinx is not available "
# "(use command `pip install SpeechRecognition` to get it). "
# "Transcription will be unavailable using that service this session.")
# _hasSpeechRecognition = False
# Google Cloud API
# _hasGoogleCloud = True
# _googleCloudClient = None # client for Google Cloud, instanced on first use
# try:
# import google.cloud.speech
# import google.auth.exceptions
# except (ImportError, ModuleNotFoundError):
# logging.warning(
# "Speech-to-text recognition using Google online services is not "
# "available (use command `pip install google-api-core google-auth "
# "google-cloud google-cloud-speech googleapis-common-protos` to get "
# "it). Transcription will be unavailable using that service this "
# "session.")
# _hasGoogleCloud = False
# try:
# import pocketsphinx
# sphinxLangs = [folder.stem for folder
# in Path(pocketsphinx.get_model_path()).glob('??-??')]
# haveSphinx = True
# except (ImportError, ModuleNotFoundError):
# haveSphinx = False
# sphinxLangs = None
# Constants related to the transcription system.
TRANSCR_LANG_DEFAULT = 'en-US'
# Values for specifying recognizer engines. This dictionary is used by Builder
# to populate the component property dropdown.
recognizerEngineValues = {
0: ('sphinx', "CMU Pocket Sphinx", "Offline"),
1: ('google', "Google Cloud Speech API", "Online, Key Required"),
2: ('whisper', "OpenAI Whisper", "Offline, Built-in")
}
# the active transcriber interface
_activeTranscriber = None
# ------------------------------------------------------------------------------
# Exceptions for the speech recognition interface
#
class TranscriberError(Exception):
"""Base class for transcriber exceptions.
"""
pass
class TranscriberNotSetupError(TranscriberError):
"""Exception raised when a transcriber interface has not been setup.
"""
pass
# ------------------------------------------------------------------------------
# Classes and functions for speech-to-text transcription
#
class TranscriptionResult:
"""Descriptor for returned transcription data.
Fields within this class can be used to access transcribed words and other
information related to the transcription request.
This is returned by functions and methods which perform speech-to-text
transcription from audio data within PsychoPy. The user usually does not
create instances of this class themselves.
Parameters
----------
words : list of str
Words extracted from the audio clip.
unknownValue : bool
`True` if the transcription API failed make sense of the audio and did
not complete the transcription.
requestFailed : bool
`True` if there was an error with the transcriber itself. For instance,
network error or improper formatting of the audio data.
engine : str
Name of engine used to perform this transcription.
language : str
Identifier for the language used to perform the transcription.
"""
__slots__ = [
'_words',
'_wordData', # additional word data
'_text', # unused for now, will be used in future
'_confidence', # unused on Python for now
'_response',
'_engine',
'_language',
'_expectedWords',
'_requestFailed',
'_unknownValue']
def __init__(self, words, unknownValue, requestFailed, engine, language):
self.words = words
self.unknownValue = unknownValue
self.requestFailed = requestFailed
self.engine = engine
self.language = language
# initialize other fields
self._wordData = None
self._text = ""
self._confidence = 0.0
self._response = None
self._expectedWords = None
self._requestFailed = True
self._unknownValue = True
def __repr__(self):
return (f"TranscriptionResult(words={self._words}, "
f"unknownValue={self._unknownValue}, ",
f"requestFailed={self._requestFailed}, ",
f"engine={self._engine}, ",
f"language={self._language})")
def __str__(self):
return " ".join(self._words)
def __json__(self):
return str(self)
@property
def wordCount(self):
"""Number of words found (`int`)."""
return len(self._words)
@property
def words(self):
"""Words extracted from the audio clip (`list` of `str`)."""
return self._words
@property
def text(self):
"""Text transcribed for the audio data (`str`).
"""
return self._text
@words.setter
def words(self, value):
self._words = list(value)
@property
def response(self):
"""Raw API response from the transcription engine (`str`).
"""
return self._response
@response.setter
def response(self, val):
self._response = val
@property
def responseData(self):
"""
Values from self.response, parsed into a `dict`.
"""
return json.loads(self.response)
@responseData.setter
def responseData(self, val):
self._response = str(val)
@property
def wordData(self):
"""Additional data about each word (`list`).
Not all engines provide this data in the same format or at all.
"""
return self._wordData
@wordData.setter
def wordData(self, val):
self._wordData = val
def getSpeechInterval(self):
"""Get the start and stop times for the interval of speech in the audio
clip.
This feature is only supported by the Whisper transcriber. The start and
end times of the speech interval are returned in seconds.
Returns
-------
tuple
Start and end times of the speech interval in seconds. If the engine
does not support this feature, or if the data is missing,
`(None, None)` is returned. In cases where either the start or end
time is missing, the value will be `None` for that field.
"""
nullData = (None, None) # default return value if no data
if self._engine in ('sphinx', 'google'):
logging.warning(
"Method `getSpeechInterval` is not supported for the "
"transcription engine `{}`.".format(self._engine))
return nullData
elif self._engine == 'whisper':
if self.responseData is None:
return nullData
# this value is in the response data which is in JSON format
segmentData = self.responseData.get('segments', None)
if segmentData is None:
return nullData
# integers for keys
segmentKeys = list(segmentData.keys())
if len(segmentKeys) == 0:
return nullData
# sort segment keys to ensure monotonic ordering
segmentKeys.sort()
# get first and last segment
firstSegment = segmentData.get(segmentKeys[0], None)
lastSegment = segmentData.get(segmentKeys[-1], None)
# get speech onset/offset times
speechOnset = firstSegment.get('start', None)
speechOffset = lastSegment.get('end', None)
# return start and end times
return speechOnset, speechOffset
@property
def success(self):
"""`True` if the transcriber returned a result successfully (`bool`)."""
return not (self._unknownValue or self._requestFailed)
@property
def error(self):
"""`True` if there was an error during transcription (`bool`). Value is
always the compliment of `.success`."""
return not self.success
@property
def unknownValue(self):
"""`True` if the transcription API failed make sense of the audio and
did not complete the transcription (`bool`).
"""
return self._unknownValue
@unknownValue.setter
def unknownValue(self, value):
self._unknownValue = bool(value)
@property
def requestFailed(self):
"""`True` if there was an error with the transcriber itself (`bool`).
For instance, network error or improper formatting of the audio data,
invalid key, or if there was network connection error.
"""
return self._requestFailed
@requestFailed.setter
def requestFailed(self, value):
self._requestFailed = bool(value)
@property
def engine(self):
"""Name of engine used to perform this transcription (`str`).
"""
return self._engine
@engine.setter
def engine(self, value):
if value == 'sphinx':
if not haveSphinx:
raise ModuleNotFoundError(
"To perform built-in (local) transcription you need to "
"have pocketsphinx installed (pip install pocketsphinx)")
self._engine = str(value)
@property
def language(self):
"""Identifier for the language used to perform the transcription
(`str`).
"""
return self._language
@language.setter
def language(self, value):
self._language = str(value)
# empty result returned when a transcriber is given no data
NULL_TRANSCRIPTION_RESULT = TranscriptionResult(
words=[''],
unknownValue=False,
requestFailed=False,
engine='null',
language=TRANSCR_LANG_DEFAULT
)
# ------------------------------------------------------------------------------
# Transcription interfaces
#
class BaseTranscriber:
"""Base class for text-to-speech transcribers.
This class defines the API for transcription, which is an interface to a
speech-to-text engine. All transcribers must be sub-classes of this class
and implement all members of this class.
Parameters
----------
initConfig : dict or None
Options to configure the speech-to-text engine during initialization.
"""
_isLocal = True
_engine = u'Null'
_longName = u"Null"
_lastResult = None
def __init__(self, initConfig=None):
self._initConf = initConfig
@property
def longName(self):
"""Human-readable name of the transcriber (`str`).
"""
return self._longName
@property
def engine(self):
"""Identifier for the transcription engine which this object interfaces
with (`str`).
"""
return self._engine
@property
def isLocal(self):
"""`True` if the transcription engine works locally without sending data
to a remote server.
"""
return self._isLocal
@property
def isComplete(self):
"""`True` if the transcriber has completed its transcription. The result
can be accessed through `.lastResult`.
"""
return True
@property
def lastResult(self):
"""Result of the last transcription.
"""
return self._lastResult
@lastResult.setter
def lastResult(self, val):
self._lastResult = val
def transcribe(self, audioClip, modelConfig=None, decoderConfig=None):
"""Perform speech-to-text conversion on the provided audio samples.
Parameters
----------
audioClip : :class:`~psychopy.sound.AudioClip`
Audio clip containing speech to transcribe (e.g., recorded from a
microphone).
modelConfig : dict or None
Additional configuration options for the model used by the engine.
decoderConfig : dict or None
Additional configuration options for the decoder used by the engine.
Returns
-------
TranscriptionResult
Transcription result object.
"""
self._lastResult = NULL_TRANSCRIPTION_RESULT # dummy value
return self._lastResult
def unload(self):
"""Unload the transcriber interface.
This method is called when the transcriber interface is no longer
needed. This is useful for freeing up resources used by the transcriber
interface.
This might not be available on all transcriber interfaces.
"""
pass
class PocketSphinxTranscriber(BaseTranscriber):
"""Class to perform speech-to-text conversion on the provided audio samples
using CMU Pocket Sphinx.
Parameters
----------
initConfig : dict or None
Options to configure the speech-to-text engine during initialization.
"""
_isLocal = True
_engine = u'sphinx'
_longName = u"CMU PocketSphinx"
def __init__(self, initConfig=None):
super(PocketSphinxTranscriber, self).__init__(initConfig)
# import the library and get language models
import speech_recognition as sr
# create a recognizer interface
self._recognizer = sr.Recognizer()
@staticmethod
def getAllModels():
"""Get available language models for the PocketSphinx transcriber
(`list`).
Returns
-------
list
List of available models.
"""
import pocketsphinx
modelPath = pocketsphinx.get_model_path()
toReturn = [folder.stem for folder in Path(modelPath).glob('??-??')]
return toReturn
def transcribe(self, audioClip, modelConfig=None, decoderConfig=None):
"""Perform speech-to-text conversion on the provided audio samples using
CMU Pocket Sphinx.
Parameters
----------
audioClip : :class:`~psychopy.sound.AudioClip`
Audio clip containing speech to transcribe (e.g., recorded from a
microphone).
modelConfig : dict or None
Additional configuration options for the model used by the engine.
decoderConfig : dict or None
Additional configuration options for the decoder used by the engine.
Presently unused by this transcriber.
Returns
-------
TranscriptionResult
Transcription result object.
"""
import speech_recognition as sr
try:
import pocketsphinx
except (ImportError, ModuleNotFoundError):
raise RecognizerEngineNotFoundError()
# warmup the engine, not used here but needed for compatibility
if audioClip is None:
return NULL_TRANSCRIPTION_RESULT
if isinstance(audioClip, AudioClip):
pass
elif isinstance(audioClip, (tuple, list,)):
waveform, sampleRate = audioClip
audioClip = AudioClip(waveform, sampleRateHz=sampleRate)
else:
raise TypeError(
"Expected type for parameter `audioClip` to be either "
"`AudioClip`, `list` or `tuple`")
# engine configuration
modelConfig = {} if modelConfig is None else modelConfig
if not isinstance(modelConfig, dict):
raise TypeError(
"Invalid type for parameter `config` specified, must be `dict` "
"or `None`.")
language = modelConfig.get('language', TRANSCR_LANG_DEFAULT)
if not isinstance(language, str):
raise TypeError(
"Invalid type for parameter `language`, must be type `str`.")
language = language.lower()
if language not in sphinxLangs: # missing a language pack error
url = "https://sourceforge.net/projects/cmusphinx/files/" \
"Acoustic%20and%20Language%20Models/"
msg = (f"Language `{language}` is not installed for "
f"`pocketsphinx`. You can download languages here: {url}. "
f"Install them here: {pocketsphinx.get_model_path()}")
raise RecognizerLanguageNotSupportedError(msg)
# configure the recognizer
modelConfig['language'] = language # sphinx users en-us not en-US
modelConfig['show_all'] = False
expectedWords = modelConfig.get('keyword_entries', None)
if expectedWords is not None:
words, sens = _parseExpectedWords(expectedWords)
modelConfig['keyword_entries'] = tuple(zip(words, sens))
# convert audio to format for transcription
sampleWidth = 2 # two bytes per sample for WAV
audioData = sr.AudioData(
audioClip.asMono().convertToWAV(),
sample_rate=audioClip.sampleRateHz,
sample_width=sampleWidth)
# submit audio samples to the API
respAPI = ''
unknownValueError = requestError = False
try:
respAPI = self._recognizer.recognize_sphinx(
audioData, **modelConfig)
except sr.UnknownValueError:
unknownValueError = True
except sr.RequestError:
requestError = True
# remove empty words
result = [word for word in respAPI.split(' ') if word != '']
# object to return containing transcription data
self.lastResult = toReturn = TranscriptionResult(
words=result,
unknownValue=unknownValueError,
requestFailed=requestError,
engine='sphinx',
language=language)
# split only if the user does not want the raw API data
return toReturn
class GoogleCloudTranscriber(BaseTranscriber):
"""Class for speech-to-text transcription using Google Cloud API services.
Parameters
----------
initConfig : dict or None
Options to configure the speech-to-text engine during initialization.
"""
_isLocal = False
_engine = u'googleCloud'
_longName = u'Google Cloud'
def __init__(self, initConfig=None):
super(GoogleCloudTranscriber, self).__init__(initConfig)
try:
import google.cloud.speech
import google.auth.exceptions
except (ImportError, ModuleNotFoundError):
pass
if "GOOGLE_APPLICATION_CREDENTIALS" not in os.environ:
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = \
prefs.general['appKeyGoogleCloud']
# empty string indicates no key has been specified, raise error
if not os.environ["GOOGLE_APPLICATION_CREDENTIALS"]:
raise RecognizerAPICredentialsError(
'No application key specified for Google Cloud Services, '
'specify the path to the key file with either the system '
'environment variable `GOOGLE_APPLICATION_CREDENTIALS` or in '
'preferences (General -> appKeyGoogleCloud).')
# open new client, takes a while the first go
try:
client = google.cloud.speech.SpeechClient()
except google.auth.exceptions.DefaultCredentialsError:
raise RecognizerAPICredentialsError(
'Invalid key specified for Google Cloud Services, check if the '
'key file is valid and readable.')
self._googleCloudClient = client
def transcribe(self, audioClip, modelConfig=None, decoderConfig=None):
"""Transcribe text using Google Cloud.
Parameters
----------
audioClip : AudioClip, list or tuple
Audio clip containing speech to transcribe (e.g., recorded from a
microphone). Can be either an :class:`~psychopy.sound.AudioClip`
object or tuple where the first value is as a Nx1 or Nx2 array of
audio samples (`ndarray`) and the second the sample rate (`int`) in
Hertz (e.g., ``(samples, 48000)``).
Returns
-------
TranscriptionResult
Result of the transcription.
"""
# if None, return a null transcription result and just open a client
if audioClip is None:
return NULL_TRANSCRIPTION_RESULT
if isinstance(audioClip, (list, tuple,)):
waveform, sr = audioClip
audioClip = AudioClip(waveform, sampleRateHz=sr)
# check if we have a valid audio clip
if not isinstance(audioClip, AudioClip):
raise TypeError(
"Expected parameter `audioClip` to have type "
"`psychopy.sound.AudioClip`.")
# import here the first time
import google.cloud.speech as speech
import google.auth.exceptions
# defaults
languageCode = modelConfig.get('language', 'language_code')
model = modelConfig.get('model', 'command_and_search')
expectedWords = modelConfig.get('expectedWords', None)
# configure the recognizer
params = {
'encoding': speech.RecognitionConfig.AudioEncoding.LINEAR16,
'sample_rate_hertz': audioClip.sampleRateHz,
'language_code': languageCode,
'model': model,
'audio_channel_count': audioClip.channels,
'max_alternatives': 1}
if isinstance(modelConfig, dict): # overwrites defaults!
params.update(modelConfig)
# speech context (i.e. expected phrases)
if expectedWords is not None:
expectedWords, _ = _parseExpectedWords(expectedWords)
params['speech_contexts'] = \
[google.cloud.speech.SpeechContext(phrases=expectedWords)]
# Detects speech in the audio file
response = self._googleCloudClient.recognize(
config=google.cloud.speech.RecognitionConfig(**params),
audio=google.cloud.speech.RecognitionAudio(
content=audioClip.convertToWAV()))
# package up response
result = [
result.alternatives[0].transcript for result in response.results]
toReturn = TranscriptionResult(
words=result,
unknownValue=False, # not handled yet
requestFailed=False, # not handled yet
engine='google',
language=languageCode)
toReturn.response = response
self._lastResult = toReturn
return toReturn
# ------------------------------------------------------------------------------
# Functions
#
def getAllTranscriberInterfaces(engineKeys=False):
"""Get all available transcriber interfaces.
Transcriber interface can be implemented in plugins. When loaded, this
function will return them.
It is not recommended to work with transcriber interfaces directly. Instead,
setup a transcriber interface using `setupTranscriber()` and use
`submit()` to perform transcriptions.
Parameters
----------
engineKeys : bool
Have the returned mapping use engine names for keys instead of class
names.
Returns
-------
dict
Mapping of transcriber class or engine names (`str`) and references to
classes (subclasses of `BaseTranscriber`.)
Examples
--------
Getting a transcriber interface, initializing it, and doing a
transcription::
whisperInterface = sound.getAllTranscribers()['WhisperTranscriber']
# create the instance which initialize the transcriber service
transcriber = whisperInterface({'device': 'cuda'})
# you can now begin transcribing audio
micRecording = mic.getRecording()
result = transcriber.transcribe(micRecording)
"""
from psychopy.plugins import discoverModuleClasses
# build a dictionary with names
here = sys.modules[__name__]
foundTranscribers = discoverModuleClasses(here, BaseTranscriber)
del foundTranscribers['BaseTranscriber'] # remove base, not needed
if not engineKeys:
return foundTranscribers
# remap using engine names, more useful for builder
toReturn = {}
for className, interface in foundTranscribers.items():
if hasattr(interface, '_engine'): # has interface
toReturn[interface._engine] = interface
return toReturn
def getTranscriberInterface(engine):
"""Get a transcriber interface by name.
It is not recommended to work with transcriber interfaces directly. Instead,
setup a transcriber interface using `setupTranscriber()` and use
`submit()` to perform transcriptions.
Parameters
----------
engine : str
Name of the transcriber interface to get.
Returns
-------
Subclass of `BaseTranscriber`
Transcriber interface.
Examples
--------
Get a transcriber interface and initalize it::
whisperInterface = getTranscriberInterface('whisper')
# initialize it
transcriber = whisperInterface({'device': 'cuda'})
"""
transcribers = getAllTranscriberInterfaces(engineKeys=True)
try:
transcriber = transcribers[engine]
except KeyError:
raise ValueError(
f"Transcriber with engine name `{engine}` not found.")
return transcriber
def setupTranscriber(engine, config=None):
"""Setup a transcriber interface.
Calling this function will instantiate a transcriber interface and perform
any necessary setup steps. This function is useful for performing the
initialization step without blocking the main thread during a time-sensitive
part of the experiment.
You can only instantiate a single transcriber interface at a time. Calling
this function will replace the existing transcriber interface if one is
already setup.
Parameters
----------
engine : str
Name of the transcriber interface to setup, or a path to the backend class (e.g.
`psychopy_whisper.transcribe:WhisperTranscriber`).
config : dict or None
Options to configure the speech-to-text engine during initialization.
"""
global _activeTranscriber
if _activeTranscriber is not None:
oldInterface = _activeTranscriber.engine
logging.warning(
"Transcriber interface already setup, replacing existing "
"interface `{}` with `{}`".format(oldInterface, engine))
# unload the model if the interface supports it
if hasattr(_activeTranscriber, 'unload'):
_activeTranscriber.unload()
_activeTranscriber = None
# get all named transcribers
allTranscribers = getAllTranscriberInterfaces(engineKeys=True)
if engine in allTranscribers:
# if engine is included by name, get it
transcriber = allTranscribers[engine]
elif engine.lower() in allTranscribers:
# try lowercase
transcriber = allTranscribers[engine.lower()]
else:
# try to import it
try:
if ":" in engine:
group, name = engine.split(":")
else:
group, name = str.rsplit(".")
mod = importlib.import_module(group)
transcriber = getattr(mod, name)
except ModuleNotFoundError:
raise KeyError(
f"Could not find transcriber engine from '{engine}'"
)
logging.debug(f"Setting up transcriber `{engine}` with options `{config}`.")
_activeTranscriber = transcriber(config) # init the transcriber
def getActiveTranscriber():
"""Get the currently active transcriber interface instance.
Should return a subclass of `BaseTranscriber` upon a successful call to
`setupTranscriber()`, otherwise `None` is returned.
Returns
-------
Subclass of `BaseTranscriber` or None
Active transcriber interface instance, or `None` if none is active.
"""
global _activeTranscriber
return _activeTranscriber
def getActiveTranscriberEngine():
"""Get the name currently active transcriber interface.
Should return a string upon a successful call to `setupTranscriber()`,
otherwise `None` is returned.
Returns
-------
str or None
Name of the active transcriber interface, or `None` if none is active.
"""
activeTranscriber = getActiveTranscriber()
if activeTranscriber is None:
return None
return activeTranscriber.engine
def submit(audioClip, config=None):
"""Submit an audio clip for transcription.
This will begin the transcription process using the currently loaded
transcriber and return when completed. Unlike `transcribe`, not calling
`setupTranscriber` before calling this function will raise an exception.
Parameters
----------
audioClip : :class:`~psychopy.sound.AudioClip` or tuple
Audio clip containing speech to transcribe (e.g., recorded from a
microphone). Can be either an :class:`~psychopy.sound.AudioClip` object
or tuple where the first value is as a Nx1 or Nx2 array of audio
samples (`ndarray`) and the second the sample rate (`int`) in Hertz
(e.g., `(samples, 48000)`).
config : dict or None
Additional configuration options for the specified engine. These
are specified using a dictionary (ex. `config={'pfilter': 1}` will
enable the profanity filter when using the `'google'` engine).
Returns
-------
TranscriptionResult
Result of the transcription.
"""
global _activeTranscriber
if getActiveTranscriberEngine() is None:
raise TranscriberNotSetupError(
"No transcriber interface has been setup, call `setupTranscriber` "
"before calling `submit`.")
return _activeTranscriber.transcribe(audioClip, config=config)
def transcribe(audioClip, engine='whisper', language='en-US', expectedWords=None,
config=None):
"""Convert speech in audio to text.
This function accepts an audio clip and returns a transcription of the
speech in the clip. The efficacy of the transcription depends on the engine
selected, audio quality, and language support.
Speech-to-text conversion blocks the main application thread when used on
Python. Don't transcribe audio during time-sensitive parts of your
experiment! Instead, initialize the transcriber before the experiment
begins by calling this function with `audioClip=None`.
Parameters
----------
audioClip : :class:`~psychopy.sound.AudioClip` or tuple
Audio clip containing speech to transcribe (e.g., recorded from a
microphone). Can be either an :class:`~psychopy.sound.AudioClip` object
or tuple where the first value is as a Nx1 or Nx2 array of audio
samples (`ndarray`) and the second the sample rate (`int`) in Hertz
(e.g., `(samples, 48000)`). Passing `None` will initialize the
the transcriber without performing a transcription. This is useful for
performing the initialization step without blocking the main thread
during a time-sensitive part of the experiment.
engine : str
Speech-to-text engine to use.
language : str
BCP-47 language code (eg., 'en-US'). Note that supported languages
vary between transcription engines.
expectedWords : list or tuple
List of strings representing expected words or phrases. This will
constrain the possible output words to the ones specified which
constrains the model for better accuracy. Note not all engines support
this feature (only Sphinx and Google Cloud do at this time). A warning
will be logged if the engine selected does not support this feature. CMU
PocketSphinx has an additional feature where the sensitivity can be
specified for each expected word. You can indicate the sensitivity level
to use by putting a ``:`` after each word in the list (see the Example
below). Sensitivity levels range between 0 and 100. A higher number
results in the engine being more conservative, resulting in a higher
likelihood of false rejections. The default sensitivity is 80% for
words/phrases without one specified.
config : dict or None
Additional configuration options for the specified engine. These
are specified using a dictionary (ex. `config={'pfilter': 1}` will
enable the profanity filter when using the `'google'` engine).
Returns
-------
:class:`~psychopy.sound.transcribe.TranscriptionResult`
Transcription result.
Notes
-----
* The recommended transcriber is OpenAI Whisper which can be used locally
without an internet connection once a model is downloaded to cache. It can
be selected by passing `engine='whisper'` to this function.
* Online transcription services (eg., Google) provide robust and accurate
speech recognition capabilities with broader language support than offline
solutions. However, these services may require a paid subscription to use,
reliable broadband internet connections, and may not respect the privacy
of your participants as their responses are being sent to a third-party.
Also consider that a track of audio data being sent over the network can
be large, users on metered connections may incur additional costs to run
your experiment. Offline transcription services (eg., CMU PocketSphinx and
OpenAI Whisper) do not require an internet connection after the model has
been downloaded and installed.
* If the audio clip has multiple channels, they will be combined prior to
being passed to the transcription service if needed.
Examples
--------
Use a voice command as a response to a task::
# after doing microphone recording
resp = mic.getRecording()
transcribeResults = transcribe(resp)
if transcribeResults.success: # successful transcription
words = transcribeResults.words
if 'hello' in words:
print('You said hello.')
Initialize the transcriber without performing a transcription::
# initialize the transcriber
transcribe(None, config={
'model_name': 'tiny.en',
'device': 'auto'}
)
Specifying expected words with sensitivity levels when using CMU Pocket
Sphinx:
# expected words 90% sensitivity on the first two, default for the rest
expectedWords = ['right:90', 'left:90', 'up', 'down']
transcribeResults = transcribe(
resp.samples,
resp.sampleRateHz,
expectedWords=expectedWords)
if transcribeResults.success: # successful transcription
# process results ...
Specifying the API key to use Google's Cloud service for speech-to-text::
# set the environment variable
import os
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = \
"C:\\path\\to\\my\\key.json"
# you can now call the transcriber ...
results = transcribe(
myRecording,
engine='google',
expectedWords=['left', 'right'])
if results.success:
print("You said: {}".format(results.words[0]))
"""
# check if the engine parameter is valid
engine = engine.lower() # make lower case
if config is None:
config = {}
global _activeTranscriber
if _activeTranscriber is None:
logging.warning(
"Called `transcribe` before calling `setupTranscriber`. The "
"transcriber interface will be initialized now. If this is a "
"time sensitive part of your experiment, consider calling "
"`setupTranscriber` before any experiment routine begins.")
setupTranscriber(engine, config=config)
return NULL_TRANSCRIPTION_RESULT
# check if we have necessary keys
if engine in ('google',):
alert(4615, strFields={'engine': engine})
# if we got a tuple, convert to audio clip object
if isinstance(audioClip, (tuple, list,)):
samples, sampleRateHz = audioClip
audioClip = AudioClip(samples, sampleRateHz)
# bit of a hack for the wisper transcriber
if engine == 'whisper':
# trim the language specifier, this should be close enough for now
langSplit = language.split('-')
if len(langSplit) > 1:
language = langSplit[0]
else:
language = language
else:
config['expectedWords'] = expectedWords
config['language'] = language
# do the actual transcription
return _activeTranscriber.transcribe(
audioClip,
language=language,
expectedWords=expectedWords,
config=config)
def _parseExpectedWords(wordList, defaultSensitivity=80):
"""Parse expected words list.
This function is used internally by other functions and classes within the
`transcribe` module.
Expected words or phrases are usually specified as a list of strings. CMU
Pocket Sphinx allows for additional 'sensitivity' values for each phrase
ranging from *0* to *100*. This function will generate to lists, first with
just words and another with specified sensitivity values. This allows the
user to specify sensitivity levels which can be ignored if the recognizer
engine does not support it.
Parameters
----------
wordList : list of str
List of words of phrases. Sensitivity levels for each can be specified
by putting a value at the end of each string separated with a colon `:`.
For example, ``'hello:80'`` for 80% sensitivity on 'hello'. Values are
normalized between *0.0* and *1.0* when returned.
defaultSensitivity : int or float
Default sensitivity to use if a word does not have one specified between
0 and 100%.
Returns
-------
tuple
Returns list of expected words and list of normalized sensitivities for
each.
Examples
--------
Specifying expected words to CMU Pocket Sphinx::
words = [('hello:95', 'bye:50')]
expectedWords = zip(_parseExpectedWords(words))
"""
defaultSensitivity = defaultSensitivity / 100. # normalized
sensitivities = []
if wordList is not None:
# sensitivity specified as `word:80`
wordListTemp = []
for word in wordList:
wordAndSense = word.split(':')
if len(wordAndSense) == 2: # specified as `word:80`
word, sensitivity = wordAndSense
sensitivity = int(sensitivity) / 100.
else:
word = wordAndSense[0]
sensitivity = defaultSensitivity # default is 80% confidence
wordListTemp.append(word)
sensitivities.append(sensitivity)
wordList = wordListTemp
return wordList, sensitivities
# ------------------------------------------------------------------------------
# Recognizers
#
# These functions are used to send off audio and configuration data to the
# indicated speech-to-text engine. Most of these functions are synchronous,
# meaning they block the application until they return. Don't run these in any
# time critical parts of your program.
#
_pocketSphinxTranscriber = None
def recognizeSphinx(audioClip=None, language='en-US', expectedWords=None,
config=None):
"""Perform speech-to-text conversion on the provided audio samples using
CMU Pocket Sphinx.
Parameters
----------
audioClip : :class:`~psychopy.sound.AudioClip` or None
Audio clip containing speech to transcribe (e.g., recorded from a
microphone). Specify `None` to open a client without performing a
transcription, this will reduce latency when the transcriber is invoked
in successive calls.
language : str
BCP-47 language code (eg., 'en-US'). Should match the language which the
speaker is using. Pocket Sphinx requires language packs to be installed
locally.
expectedWords : list or None
List of strings representing expected words or phrases. This will
attempt bias the possible output words to the ones specified if the
engine is uncertain. Sensitivity can be specified for each expected
word. You can indicate the sensitivity level to use by putting a ``:``
after each word in the list (see the Example below). Sensitivity levels
range between 0 and 100. A higher number results in the engine being
more conservative, resulting in a higher likelihood of false rejections.
The default sensitivity is 80% for words/phrases without one specified.
config : dict or None
Additional configuration options for the specified engine.
Returns
-------
TranscriptionResult
Transcription result object.
"""
if config is None:
config = {} # empty dict if `None`
onlyInitialize = audioClip is None
global _pocketSphinxTranscriber
if _pocketSphinxTranscriber is None:
allTranscribers = getAllTranscribers(engineKeys=True)
try:
interface = allTranscribers['sphinx']
except KeyError:
raise RecognizerEngineNotFoundError(
"Cannot load transcriber interface for 'sphinx'.")
_pocketSphinxTranscriber = interface() # create instance
if onlyInitialize:
return NULL_TRANSCRIPTION_RESULT
# extract parameters which we used to support
config['expectedWords'] = expectedWords
config['language'] = language
# do transcription and return result
return _pocketSphinxTranscriber.transcribe(audioClip, modelConfig=config)
_googleCloudTranscriber = None # keep instance for legacy functions
def recognizeGoogle(audioClip=None, language='en-US', expectedWords=None,
config=None):
"""Perform speech-to-text conversion on the provided audio clip using
the Google Cloud API.
This is an online based speech-to-text engine provided by Google as a
subscription service, providing exceptional accuracy compared to `built-in`.
Requires an API key to use which you must generate and specify prior to
calling this function.
Parameters
----------
audioClip : :class:`~psychopy.sound.AudioClip` or None
Audio clip containing speech to transcribe (e.g., recorded from a
microphone). Specify `None` to open a client without performing a
transcription, this will reduce latency when the transcriber is invoked
in successive calls.
language : str
BCP-47 language code (eg., 'en-US'). Should match the language which the
speaker is using.
expectedWords : list or None
List of strings representing expected words or phrases. These are passed
as speech context metadata which will make the recognizer prefer a
particular word in cases where there is ambiguity or uncertainty.
config : dict or None
Additional configuration options for the recognizer as a dictionary.
Notes
-----
* The first invocation of this function will take considerably longer to run
that successive calls as the client has not been started yet. Only one
instance of a recognizer client can be created per-session.
Examples
--------
Specifying the API key to use Google's Cloud service for speech-to-text::
import os
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = \
"C:\\path\\to\\my\\key.json"
# you can now call the transcriber
results = recognizeGoogle(myRecording, expectedWords=['left', 'right'])
if results.success:
print("You said: {}".format(results.words[0])) # first word
"""
if config is None:
config = {} # empty dict if `None`
onlyInitialize = audioClip is None
global _googleCloudTranscriber
if _googleCloudTranscriber is None:
allTranscribers = getAllTranscribers(engineKeys=True)
try:
interface = allTranscribers['googleCloud']
except KeyError:
raise RecognizerEngineNotFoundError(
"Cannot load transcriber interface for 'googleCloud'.")
_googleCloudTranscriber = interface() # create instance
if onlyInitialize:
return NULL_TRANSCRIPTION_RESULT
# set parameters which we used to support
config['expectedWords'] = expectedWords
config['language'] = language
# do transcription and return result
return _googleCloudTranscriber.transcribe(audioClip, modelConfig=config)
if __name__ == "__main__":
pass
| 45,865
|
Python
|
.py
| 1,064
| 35.009398
| 89
| 0.65921
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,870
|
_base.py
|
psychopy_psychopy/psychopy/sound/_base.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Part of the PsychoPy library
# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd.
# Distributed under the terms of the GNU General Public License (GPL).
import numpy
import copy
from os import path
from psychopy import logging
from psychopy.constants import (STARTED, PLAYING, PAUSED, FINISHED, STOPPED,
NOT_STARTED, FOREVER)
from psychopy.tools.filetools import pathToString, defaultStim, defaultStimRoot
from psychopy.tools.audiotools import knownNoteNames, stepsFromA
from psychopy.tools.attributetools import AttributeGetSetMixin
from sys import platform
from .audioclip import AudioClip
from ..hardware import DeviceManager
from ..preferences.preferences import prefs
if platform == 'win32':
mediaLocation = "C:\\Windows\\Media"
elif platform == 'darwin':
mediaLocation = "/System/Library/Sounds/"
elif platform.startswith("linux"):
mediaLocation = "/usr/share/sounds"
def apodize(soundArray, sampleRate):
"""Apply a Hanning window (5ms) to reduce a sound's 'click' onset / offset
"""
hwSize = int(min(sampleRate // 200, len(soundArray) // 15))
hanningWindow = numpy.hanning(2 * hwSize + 1)
soundArray = copy.copy(soundArray)
soundArray[:hwSize] *= hanningWindow[:hwSize]
soundArray[-hwSize:] *= hanningWindow[hwSize + 1:]
return soundArray
class HammingWindow():
def __init__(self, winSecs, soundSecs, sampleRate):
"""
:param winSecs:
:param soundSecs:
:param sampleRate:
"""
self.sampleRate = sampleRate
self.winSecs = winSecs
self.winSamples = int(round(sampleRate*winSecs))
self.soundSecs = soundSecs
self.soundSamples = int(round(sampleRate*soundSecs))
self.startWindow = numpy.hanning(self.winSamples*2)[0:self.winSamples]
self.endWindow = numpy.hanning(self.winSamples*2)[self.winSamples:]
self.finalWinStart = self.soundSamples-self.winSamples
def nextBlock(self, t, blockSize):
"""Returns a block to be multiplied with the current sound block or 1.0
:param t: current position in time (secs)
:param blockSize: block size for the sound needing the hanning window
:return: numpy array of length blockSize
"""
startSample = int(t*self.sampleRate)
if startSample < self.winSamples:
# we're in beginning hanning window (start of sound)
# 2 options:
# - block is fully within window
# - block starts in window but ends after window
block = numpy.ones(blockSize)
winEndII = min(self.winSamples, # if block goes beyond hann win
startSample+blockSize) # if block shorter
blockEndII = min(self.winSamples-startSample, # if block beyond
blockSize) # if block shorter
block[0:blockEndII] = self.startWindow[startSample:winEndII]
elif startSample >= self.soundSamples:
block = None # the sound has finished (shouldn't have got here!)
elif startSample >= self.finalWinStart-blockSize:
# we're in final hanning window (end of sound)
# More complicated, with 3 options:
# - block starts before win
# - start/end during win
# - start during but end after win
block = numpy.ones(blockSize) # the initial flat part
blockStartII = max(self.finalWinStart-startSample,
0) # if block start inside window
blockEndII = min(blockSize, # if block ends in hann win
self.soundSamples-startSample) # ends after snd
winStartII = max(0, # current block ends in win but starts before
startSample-self.finalWinStart)
winEndII = min(self.winSamples,
startSample+blockSize-self.finalWinStart)
block[blockStartII:blockEndII] = \
self.endWindow[winStartII:winEndII]
else:
block = None # we're in the middle of sound so no need for window
if block is not None:
block.shape = [len(block), 1]
return block
class _SoundBase(AttributeGetSetMixin):
"""Base class for sound object, from one of many ways.
"""
# Must be provided by class SoundPygame or SoundPyo:
# def __init__()
# def play(self, fromStart=True, **kwargs):
# def stop(self, log=True):
# def getDuration(self):
# def getVolume(self):
# def setVolume(self, newVol, log=True):
# def _setSndFromFile(self, fileName):
# def _setSndFromArray(self, thisArray):
def _parseSpeaker(self, speaker):
from psychopy.hardware.speaker import SpeakerDevice
# if already a SpeakerDevice, great!
if isinstance(speaker, SpeakerDevice):
return speaker
# if no device, populate from prefs
if speaker is None:
pref = prefs.hardware['audioDevice']
if isinstance(pref, (list, tuple)):
pref = pref[0]
speaker = pref
# if first pref is defualt, use first device
if speaker in ("default", "", None):
for profile in DeviceManager.getAvailableDevices("psychopy.hardware.speaker.SpeakerDevice"):
# log
logging.debug("Using speaker %(deviceName)s as defaultSpeaker" % profile)
# initialise as defaultSpeaker
profile['deviceName'] = "defaultSpeaker"
device = DeviceManager.addDevice(**profile)
return device
# look for device if initialised
device = DeviceManager.getDevice(speaker)
# if no matching name, try matching index
if device is None:
device = DeviceManager.getDeviceBy("index", speaker)
# if still no match, make a new device
if device is None:
device = DeviceManager.addDevice(
deviceClass="psychopy.hardware.speaker.SpeakerDevice",
deviceName=speaker,
index=speaker,
)
return device
def setSound(self, value, secs=0.5, octave=4, hamming=True, log=True):
"""Set the sound to be played.
Often this is not needed by the user - it is called implicitly during
initialisation.
Parameters
----------
value : ArrayLike, AudioClip, int or str
If it's a number between 37 and 32767 then a tone will be generated
at that frequency in Hz. It could be a string for a note ('A',
'Bfl', 'B', 'C', 'Csh'. ...). Then you may want to specify which
octave.O r a string could represent a filename in the current
location, or media location, or a full path combo. Or by giving an
Nx2 numpy array of floats (-1:1) or
:class:`~psychopy.sound.AudioClip` instance.
secs : float
Duration of a tone if a note name is to `value`.
octave : int
Is only relevant if the value is a note name. Middle octave of a
piano is 4. Most computers won't output sounds in the bottom octave
(1) and the top octave (8) is generally painful.
hamming : bool
To indicate if the sound should be apodized (i.e., the onset and
offset smoothly ramped up from down to zero). The function apodize
uses a Hanning window, but arguments named 'hamming' are preserved
so that existing code is not broken by the change from Hamming to
Hanning internally. Not applied to sounds from files.
"""
# Re-init sound to ensure bad values will raise error during setting:
self._snd = None
# make references to default stim into absolute paths
if isinstance(value, str) and value in defaultStim:
value = defaultStimRoot / defaultStim[value]
# if directly given a Microphone, get its last recording
if hasattr(value, "lastClip"):
value = value.lastClip
# Coerces pathlib obj to string, else returns inputted value
value = pathToString(value)
try:
# could be '440' meaning 440
value = float(value)
except (ValueError, TypeError):
# this is a string that can't be a number, eg, a file or note
pass
else:
# we've been asked for a particular Hz
if value < 37 or value > 20000:
msg = 'Sound: bad requested frequency %.0f'
raise ValueError(msg % value)
self._setSndFromFreq(value, secs, hamming=hamming)
if isinstance(value, str):
if value.capitalize() in knownNoteNames:
self._setSndFromNote(value.capitalize(), secs, octave,
hamming=hamming)
else:
# try finding a file
self.fileName = None
for filePath in ['', mediaLocation]:
p = path.join(filePath, value)
if path.isfile(p):
self.fileName = p
break
elif path.isfile(p + '.wav'):
self.fileName = p = p + '.wav'
break
if self.fileName is None:
msg = "setSound: could not find a sound file named "
raise ValueError(msg + value)
else:
self._setSndFromFile(p)
elif isinstance(value, (list, numpy.ndarray,)):
# create a sound from the input array/list
self._setSndFromArray(numpy.array(value))
elif isinstance(value, AudioClip): # from an audio clip object
# check if we should resample the audio clip to match the device
if self.sampleRate is None:
logging.warning(
"Sound output sample rate not set. The provided AudioClip "
"requires a sample rate of {} Hz for playback which may "
"not match the device settings.".format(value.sampleRateHz))
self.sampleRate = value.sampleRateHz
if self.sampleRate != value.sampleRateHz:
logging.warning(
"Resampling to match sound device sample rate (from {} "
"to {} Hz), distortion may occur.".format(
value.sampleRateHz, self.sampleRate))
# resample with the new sample rate using the AudioClip method
value = value.resample(self.sampleRate, copy=True)
self._setSndFromArray(value.samples)
# did we succeed?
if self._snd is None:
pass # raise ValueError, "Could not make a "+value+" sound"
else:
if log and self.autoLog:
logging.exp("Set %s sound=%s" % (self.name, value), obj=self)
self.status = NOT_STARTED
def _setSndFromNote(self, thisNote, secs, octave, hamming=True):
# note name -> freq -> sound
freqA = 440.0
thisOctave = octave - 4
mult = 2.0**(stepsFromA[thisNote] / 12.)
thisFreq = freqA * mult * 2.0 ** thisOctave
self._setSndFromFreq(thisFreq, secs, hamming=hamming)
def _setSndFromFreq(self, thisFreq, secs, hamming=True):
# note freq -> array -> sound
if secs < 0:
# want infinite duration - create 1 sec sound and loop it
secs = 10.0
self.loops = -1
if not self.sampleRate:
self.sampleRate = self._getDefaultSampleRate()
nSamples = int(secs * self.sampleRate)
outArr = numpy.arange(0.0, 1.0, 1.0 / nSamples)
outArr *= 2 * numpy.pi * thisFreq * secs
outArr = numpy.sin(outArr)
if hamming and nSamples > 30:
outArr = apodize(outArr, self.sampleRate)
self._setSndFromArray(outArr)
def _getDefaultSampleRate(self):
"""For backends this might depend on what streams are open"""
return 44100
def getDuration(self):
"""Return the duration of the sound"""
return self.duration
def getVolume(self):
"""Returns the current volume of the sound (0.0 to 1.0, inclusive)
"""
return self.volume
def getLoops(self):
"""Returns the current requested loops value for the sound (int)
"""
return self.loops
def setVolume(self, newVol, log=True):
"""Sets the current volume of the sound (0.0 to 1.0, inclusive)
"""
self.volume = min(1.0, max(0.0, newVol))
self.needsUpdate = True
if log and self.autoLog:
logging.exp("Sound %s set volume %.3f" %
(self.name, self.volume), obj=self)
def setLoops(self, newLoops, log=True):
"""Sets the current requested extra loops (int)"""
self.loops = int(newLoops)
self.needsUpdate = True
if log and self.autoLog:
logging.exp("Sound %s set loops %s" %
(self.name, self.loops), obj=self)
| 13,324
|
Python
|
.py
| 281
| 36.145907
| 104
| 0.606096
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,871
|
test_demo_migration.py
|
psychopy_psychopy/psychopy/demos/test_demo_migration.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Migration helper script for Coder demos: test the conversion
For all demos (there are ~70 or so total):
compare updated style script against existing script
ignore things that we intend to change, including:
initial comment about the demo
whitespace, upper/lower case, use of underscore (in var names, but doesn't check that specifically)
myWin -> win
PatchStim -> GratingStim
win.close() present / absent
core.quit() present / absent
leading comment
shebang, encoding
"""
import glob, os
import io
def get_contents(f1, f2):
with io.open(f1, 'r', encoding='utf-8-sig') as f:
f1r = f.read()
with io.open(f2, 'r', encoding='utf-8-sig') as f:
f2r = f.read()
return f1r, f2r
def remove_shbang(f1, f2):
if f1.startswith('#!'):
f1 = f1.split('\n', 1)[1]
if f2.startswith('#!'):
f2 = f2.split('\n', 1)[1]
return f1, f2
def remove_encoding(f1, f2):
if f1.startswith('# -*- coding:'):
f1 = f1.split('\n', 1)[1]
if f2.startswith('# -*- coding:'):
f2 = f2.split('\n', 1)[1]
return f1, f2
def remove_licence_future(f1, f2):
license = '# The contents of this file are in the public domain.'
future = 'from __future__ import division'
return f1.replace(license, '').replace(future, ''), f2.replace(license, '').replace(future, '')
def remove_first_comment(f1, f2):
# call after remove_shbang
# ignore blank lines
# remove lines starting with #
# ignore multi-line """ or ''' comments
f1s = [line for line in f1.splitlines() if line.strip() and not line.strip().startswith('#')]
f2s = [line for line in f2.splitlines() if line.strip() and not line.strip().startswith('#')]
if not f1s or not f2s:
return f1, f2
for delim in ['"""', "'''"]:
for f in (f1s, f2s):
if delim in f[0]:
if len(f[0].split(delim)) == 2:
f.pop(0)
while not delim in f[0]:
f.pop(0)
f.pop(0)
return '\n'.join(f1s), '\n'.join(f2s)
def remove_semicolon(f1, f2):
lines = f1.splitlines()
for i, line in enumerate(lines):
if line.strip().startswith('#'):
continue
if line.strip().endswith(';'):
lines[i] = line.strip('; ')
f1 = '\n'.join(lines)
lines = f2.splitlines()
for i, line in enumerate(lines):
if line.strip().startswith('#'):
continue
if line.strip().endswith(';'):
lines[i] = line.strip('; ')
f2 = '\n'.join(lines)
return f1, f2
def replace_PatchStim(f1, f2):
return f1.replace('PatchStim', 'GratingStim'), f2.replace('PatchStim', 'GratingStim')
def replace_myWin_win(f1, f2):
f1, f2 = f1.replace('myWin', 'win'), f2.replace('myWin', 'win')
if 'iohub' in f1:
f1 = f1.replace('window', 'win')
if 'iohub' in f2:
f2 = f2.replace('window', 'win')
return f1.replace('win.update()', 'win.flip'), f2.replace('win.update()', 'win.flip')
def remove_core_quit(f1, f2):
return f1.replace('core.quit()', ''), f2.replace('core.quit()', '')
def remove_win_close(f1, f2):
return f1.replace('win.close()', ''), f2.replace('win.close()', '')
def flatten_content(f1, f2):
f1r = f1.replace(' ', '').replace('\n', '').replace('_', '')
f2r = f2.replace(' ', '').replace('\n', '').replace('_', '')
return f1r.lower().strip(), f2r.lower().strip()
def replace_xrange(f1, f2):
return f1.replace('xrange', 'range'), f2.replace('xrange', 'range')
def process_files(f1, f2):
"""Compare contents, ignoring differences in eoln, whitespace,underline, caps
and various code conventions (win, myWin)
"""
f = get_contents(f1, f2)
if not len(f[0].strip()) and not len(f[1].strip()):
return True, True
f = remove_shbang(*f)
f = remove_encoding(*f)
f = remove_licence_future(*f)
f = remove_first_comment(*f) # do after license_future
f = replace_PatchStim(*f)
f = replace_xrange(*f)
f = replace_myWin_win(*f)
f = remove_semicolon(*f)
f = remove_win_close(*f)
f = remove_core_quit(*f)
f = flatten_content(*f)
return f
if __name__ == '__main__':
dirs = [d for d in glob.glob('coder/*') if os.path.isdir(d)]
print('all pass unless noted')
for d in dirs:
p = glob.glob(d+'/*.py')
for f1 in p:
if '__init__.py' in f1:
continue
f2 = f1.replace('coder/', 'coder_updated/')
t1, t2 = process_files(f1, f2)
if not t1 == t2:
print('FAILED', f1)
t = t1[0]
i = 0
while t2.startswith(t):
i += 1
t += t1[i]
print(' ' + t[:-1] + ' |---')
#print t1, '\n', t2
| 4,973
|
Python
|
.py
| 130
| 30.676923
| 105
| 0.563259
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,872
|
demo_migration.py
|
psychopy_psychopy/psychopy/demos/demo_migration.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""This is a helper to keep demos in a reasonably consistent style
For all demos/coder/subdir/*.py (there are ~70 or so total), write out a new file: coder_updated/subdir/*
"""
import sys
import glob
import os
import re
import io
valid_var_re = re.compile(r"^[a-zA-Z_][\w]*$")
coding = '# -*- coding: utf-8 -*-\n'
demo_license = '\n# The contents of this file are in the public domain.\n'
def get_contents(f1):
with io.open(f1, 'r', encoding='utf-8-sig') as f:
return f.read()
def add_shebang_encoding_future(f1):
if not f1.startswith('#!'):
f1 = '#!/usr/bin/env python\n' + f1
if '# -*- coding:' not in f1:
f = f1.split('\n', 1)
f1 = f[0] + '\n' + coding + f[1]
return f1
def remove_doublesharp_trailing_whitespace(f1):
f1 = f1.replace('##', '#')
f1 = f1.replace('\n#\n', '\n\n')
return '\n'.join([line.rstrip() for line in f1.splitlines()]) + '\n'
def replace_PatchStim(f1):
return f1.replace('PatchStim', 'GratingStim')
def replace_xrange(f1):
return f1.replace('xrange', 'range')
def replace_myWin_win(f1):
f1 = f1.replace('myWin', 'win')
if 'iohub' in f1:
f1 = f1.replace('window', 'win')
return f1.replace('win.update()', 'win.flip')
def add_win_close_quit_demo_license(f1):
# remove first, then add back consistently
lines = f1.strip().splitlines()
# need to avoid removing if they are indented:
if lines[-2].startswith('win.close()') or lines[-2].startswith('core.quit()'):
lines[-2] = ''
if lines[-1].startswith('win.close()') or lines[-1].startswith('core.quit()'):
lines[-1] = ''
f1 = '\n'.join(lines)
f1 += '\n'
if 'Window(' in f1: # a visual.Window() is defined somewhere
f1 += '\nwin.close()\n'
if [line for line in lines if 'psychopy' in line and 'core' in line and 'import' in line]:
f1 += 'core.quit()\n'
if not demo_license in f1:
f1 = f1 + demo_license
return f1
def convert_inline_comments(f1):
lines = f1.splitlines()
for i, line in enumerate(lines):
lines[i] = line.replace('#', '# ').replace('# ', '# ')
if '#' in line and not line.strip().startswith('#'):
lines[i] = lines[i].replace('#', ' #').replace(' #', ' #').replace(' #', ' #')
return '\n'.join(lines)
def replace_commas_etc(f1):
# do after shebang, encoding
f1 = f1.replace(',', ', ').replace(', ', ', ')
f1 = f1.replace('=visual', ' = visual')
f1 = f1.replace('=data', ' = data').replace('=numpy', ' = numpy')
for op in ['+', '*', '>', '<', '==']: # too tricky, don't do: % = / -
f1 = f1.replace(op, ' ' + op + ' ')
f1 = f1.replace(' ' + op, ' ' + op).replace(op + ' ', op + ' ')
f1 = f1.replace('> =', '>= ').replace(' < =', ' <= ')
f1 = f1.replace('> >', '>> ').replace('< <', '<< ')
f1 = f1.replace('* *', '**').replace('# !', '#!').replace('- * -', '-*-')
f1 = f1.replace('+ =', '+= ').replace('+= ', '+= ').replace('- =', '-= ').replace('* =', '*= ')
f1 = f1.replace(' + + ', '++') # bits++, mono++ etc
lines = f1.splitlines()
for i, line in enumerate(lines):
if line.strip().startswith('#'):
continue
if line.strip().endswith(';'):
lines[i] = line.strip('; ')
if ':' in line and not ('"' in line or "'" in line):
lines[i] = line.replace(':', ': ').replace(': \n', ':\n').replace(': ', ': ')
f1 = '\n'.join(lines)
f1 = f1.replace('\n\n\n', '\n\n')
f1 = f1.replace('\n\n"""', '\n"""').replace('\n"""','\n\n"""', 1)
f1 = f1.replace('\n"""', '\n"""\n').replace('\n"""\n\n', '\n"""\n')
return f1
def is_var_name(name):
return all([valid_var_re.match(n) for n in name.split('.')])
def replace_equals(f1):
lines = f1.splitlines()
for i, line in enumerate(lines):
if line.strip().startswith('#'):
continue
if '=' in line:
left, right = line.split('=', 1)
if is_var_name(left):
lines[i] = ' = '.join([left, right])
lines[i] = lines[i].replace('= ', '=')
return '\n'.join(lines)
def uk_to_us_spelling(f1):
f1 = f1.replace('centre', 'center').replace('centerd', 'centered')
f1 = f1.replace('nitialise', 'nitialize')
f1 = f1.replace('colour', 'color')
f1 = f1.replace('analyse', 'analyze')
return f1
def split_multiline(f1):
lines = f1.splitlines()
for i, line in enumerate(lines):
if line.strip().startswith('#'):
continue
if 'if' in line and ':' in line and not ('"' in line or "'" in line) and not line.strip().endswith(':'):
pre, post = line.split(':', 1)
if post and not (post.strip().startswith('#') or ']' in line):
pre_indent = ' '
count = 0
while pre.startswith(pre_indent):
count += 1
pre_indent = ' ' * count
lines[i] = pre + ':\n' + pre_indent + post.strip()
return '\n'.join(lines)
def demo_update_one(filename):
"""convert file contents to updated style etc
"""
f = get_contents(filename)
if not len(f.strip()):
return '' # eg __init__.py
f = remove_doublesharp_trailing_whitespace(f)
f = add_shebang_encoding_future(f)
f = add_win_close_quit_demo_license(f)
f = convert_inline_comments(f)
f = replace_xrange(f)
f = replace_commas_etc(f) # do after shebang, encoding
f = replace_PatchStim(f)
f = replace_myWin_win(f)
f = replace_equals(f)
f = uk_to_us_spelling(f)
f = split_multiline(f)
return f
def demo_update_two(filename):
f = get_contents(filename)
if not len(f.strip()):
return '' # eg __init__.py
f = f + '\n'
return f
if __name__ == '__main__':
# run from within psychopy/demos/
dirs = [d for d in glob.glob('coder/*') if os.path.isdir(d)]
if not dirs:
sys.exit('in wrong directory')
if not os.path.isdir('coder_updated'):
os.mkdir('coder_updated')
for d in dirs:
if not os.path.isdir(d.replace('coder', 'coder_updated')):
os.mkdir(d.replace('coder', 'coder_updated'))
py = glob.glob(d + '/*.py')
for f1 in py:
if '__init__.py' in f1:
continue
new = demo_update_two(f1)
#"""
out = f1.replace('coder', 'coder_updated')
with io.open(out, 'wb') as fh:
fh.write(new)
print(new)
try:
compile(new, '', 'exec')
except Exception:
print(out)
raise
| 6,790
|
Python
|
.py
| 169
| 32.792899
| 112
| 0.532609
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,873
|
modernizeDemos.py
|
psychopy_psychopy/psychopy/demos/modernizeDemos.py
|
"""
Helper script to quickly update all Builder demos to be saved in the current version.
"""
from pathlib import Path
from psychopy.experiment import Experiment
# get root demos folder
root = Path(__file__).parent
# iterate through all psyexp files
for file in root.glob("**/*.psyexp"):
# load experiment
exp = Experiment.fromFile(file)
# save experiment
exp.saveToXML(file, makeLegacy=False)
| 413
|
Python
|
.py
| 13
| 29.307692
| 85
| 0.755668
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,874
|
sysInfo.py
|
psychopy_psychopy/psychopy/demos/coder/sysInfo.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from pyglet.gl import gl_info, GLint, glGetIntegerv, GL_MAX_ELEMENTS_VERTICES
from psychopy import visual, preferences
import sys, platform
print("Paths to files on the system:")
for key in ['userPrefsFile', 'appDataFile', 'demos', 'appFile']:
print(" %s: %s" % (key, preferences.prefs.paths[key]))
print("\nSystem info:")
print(platform.platform())
if sys.platform == 'darwin':
OSXver, junk, architecture = platform.mac_ver()
print("macOS %s running on %s" % (OSXver, architecture))
print("\nPython info")
print(sys.executable)
print(sys.version)
import numpy
print("numpy", numpy.__version__)
import scipy
print("scipy", scipy.__version__)
import matplotlib
print("matplotlib", matplotlib.__version__)
import pyglet
print("pyglet", pyglet.version)
# pyo is a new dependency, for sound:
try:
import pyo
print("pyo", '%i.%i.%i' % pyo.getVersion())
except Exception:
print('pyo [not installed]')
from psychopy import __version__
print("\nPsychoPy", __version__)
win = visual.Window([100, 100]) # some drivers want a window open first
print("have shaders:", win._haveShaders)
print("\nOpenGL info:")
# get info about the graphics card and drivers
print("vendor:", gl_info.get_vendor())
print("rendering engine:", gl_info.get_renderer())
print("OpenGL version:", gl_info.get_version())
print("(Selected) Extensions:")
extensionsOfInterest = ['GL_ARB_multitexture',
'GL_EXT_framebuffer_object', 'GL_ARB_fragment_program',
'GL_ARB_shader_objects', 'GL_ARB_vertex_shader',
'GL_ARB_texture_non_power_of_two', 'GL_ARB_texture_float', 'GL_STEREO']
for ext in extensionsOfInterest:
print("\t", bool(gl_info.have_extension(ext)), ext)
# also determine nVertices that can be used in vertex arrays
maxVerts = GLint()
glGetIntegerv(GL_MAX_ELEMENTS_VERTICES, maxVerts)
print('\tmax vertices in vertex array:', maxVerts.value)
| 1,967
|
Python
|
.py
| 50
| 36.22
| 95
| 0.705913
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,875
|
csvFromPsydat.py
|
psychopy_psychopy/psychopy/demos/coder/csvFromPsydat.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""utility for creating a .csv file from a .psydat file
edit the file name, then run the script
"""
import os
from psychopy.tools.filetools import fromFile
# EDIT THE NEXT LINE to be your .psydat file, with the correct path:
name = 'fileName.psydat'
file_psydat = os.path.abspath(name)
print("psydat: {0}".format(file_psydat))
# read in the experiment session from the psydat file:
exp = fromFile(file_psydat)
# write out the data in .csv format (comma-separated tabular text):
if file_psydat.endswith('.psydat'):
file_csv = file_psydat[:-7]
else:
file_csv = file_psydat
file_csv += '.csv'
exp.saveAsWideText(file_csv)
print('-> csv: {0}'.format(os.path.abspath(file_csv)))
| 736
|
Python
|
.py
| 21
| 33.285714
| 68
| 0.732673
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,876
|
colors.py
|
psychopy_psychopy/psychopy/demos/coder/understanding psychopy/colors.py
|
"""
This demo shows off the Color class (`psychopy.colors.Color`), allowing object
colors to be set and accessed in a variety of different color spaces! Just choose
a color space from the slider at the top and type a value into the textbox
"""
from psychopy import visual, colors
# Create window
win = visual.Window(size=(1080, 720), units='height')
# Button to end script
endBtn = visual.ButtonStim(win, "End",
pos=(0, -0.45), anchor='bottom-center',
size=(0.2, 0.1), letterHeight=0.05)
# Color space chooser
spaces = ['named', 'hex', 'rgb', 'rgb1', 'rgb255', 'hsv', 'lms']
spaceCtrl = visual.Slider(win, style="radio",
ticks=list(range(len(spaces))), granularity=1,
labels=spaces,
pos=(0, 0.4), size=(1.2, 0.05), labelHeight=0.02)
spaceCtrl.value = spaces.index('rgb')
# TextBox to type in values to try out
valueCtrl = visual.TextBox2(win, text="#ffffff", font="Courier Prime",
pos=(-0.3, 0.1), size=(0.5, 0.2), letterHeight=0.05,
color='white', fillColor='black',
editable=True)
win.currentEditable = valueCtrl
# Rect to show current colour
colorBox = visual.TextBox2(win, text="", font="Open Sans",
pos=(-0.3, -0.2), size=(0.5, 0.2), padding=0.05, letterHeight=0.05,
color='white', borderColor='white', fillColor=None)
# Instructions
instr = (
"This demo shows how to define colors in PsychoPy - type a value into the "
"textbox to the left, choose a color space and the box below will appear in "
"the color and space you have chosen. For more info on the different spaces, "
"check out the documentation: \n"
"psychopy.org/general/colours.html"
)
instrBox = visual.TextBox2(win, text=instr, font="Open Sans",
pos=(0.3, 0), size=(0.5, 0.5), padding=0.05, letterHeight=0.03,
color='white', borderColor=None, fillColor=None)
while not endBtn.isClicked:
# Try to make a fillColor, make it False if failed
try:
val = valueCtrl.text
# If input looks like a number, convert it
if val.isnumeric():
val = float(val)
# If input looks like an array, un-stringify it
if "," in val:
val = eval(val)
# Get color space from radio slider
space = spaces[int(spaceCtrl.markerPos)]
col = colors.Color(val, space)
except:
col = False
# Set the color box's fill color, show text "invalid" if color is invalid
if col:
colorBox.text = ""
colorBox.fillColor = col
else:
colorBox.text = "invalid color"
colorBox.fillColor = None
# Draw stim and flip
for stim in (valueCtrl, endBtn, colorBox, spaceCtrl, instrBox):
stim.draw()
win.flip()
| 2,668
|
Python
|
.py
| 66
| 35.651515
| 82
| 0.669488
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,877
|
fontLayout.py
|
psychopy_psychopy/psychopy/demos/coder/understanding psychopy/fontLayout.py
|
"""
This demo produces a handy diagram showing how the metrics of a PsychoPy GLFont object affect the layout of rows in a textbox. A textbox is drawn such that the baseline of the first line is at the vertical coordinate 0, meaning that all other lines and shapes can be laid out relative to this line.
"""
from psychopy import visual, event
from psychopy.tools.fontmanager import FontManager
# Create window
win = visual.Window(size=(500, 200), units="pix", color="white")
# Create a list to store objects for easy drawing
drawList = []
# Get a font with consistent proportions that are easy to spot
allFonts = FontManager()
font = allFonts.getFont("Outfit", size=50, lineSpacing=1.3)
# Create a textbox using this font, whose vertical position is such that the baseline of the first line of text is at 0
text = visual.TextBox2(
win=win, text="My text has an È!\nMy text has an È!", font=font,
pos=(-50, font.ascender), size=(400, font.height), padding=0,
color="black", anchor="top center", alignment="top left"
)
drawList += [text]
# Draw the baseline
baseline = visual.Line(win, start=(-250, 0), end=(250, 0), lineColor="green")
baselineLbl = visual.TextBox2(win, "baseline (0)", "Outfit", color="green", letterHeight=12, pos=(160, 8), size=(50, 10), padding=0)
drawList += [baseline, baselineLbl]
# Draw the descent line
descender = visual.Line(win, start=(-250, font.descender), end=(250, font.descender), lineColor="blue")
descenderLbl = visual.TextBox2(win, ".descender", "Outfit", color="blue", letterHeight=12, pos=(160, font.descender + 8), size=(50, 10), padding=0)
drawList += [descender, descenderLbl]
# Draw the ascent line
ascender = visual.Line(win, start=(-250, font.ascender), end=(250, font.ascender), lineColor="orange")
ascenderLbl = visual.TextBox2(win, ".ascender", "Outfit", color="orange", letterHeight=12, pos=(160, font.ascender + 8), size=(50, 10), padding=0)
drawList += [ascender, ascenderLbl]
# Draw the cap height line
capheight = visual.Line(win, start=(-250, font.capheight), end=(250, font.capheight), lineColor="red")
capheightLbl = visual.TextBox2(win, ".capheight", "Outfit", color="red", letterHeight=12, pos=(160, font.capheight + 8), size=(50, 10), padding=0)
drawList += [capheight, capheightLbl]
# Draw the leading line
leading = visual.Line(win, start=(-250, font.leading), end=(250, font.leading), lineColor="purple")
leadingLbl = visual.TextBox2(win, ".leading", "Outfit", color="purple", letterHeight=12, pos=(160, font.leading - 4), size=(50, 10), padding=0)
drawList += [leading, leadingLbl]
# Draw the height box
height = visual.Rect(win, fillColor="orange", pos=(215, (font.ascender + font.leading)/2), size=(20, font.height))
heightLbl = visual.TextStim(win, ".height", "Outfit", color="white", bold=True, pos=(215, (font.ascender + font.leading)/2), height=12, ori=90)
drawList += [height, heightLbl]
# Draw the size box
size = visual.Rect(win, fillColor="red", pos=(240, (font.capheight + font.descender)/2), size=(20, font.size))
sizeLbl = visual.TextStim(win, ".size", "Outfit", color="white", bold=True, pos=(240, (font.capheight + font.descender)/2), height=12, ori=90)
drawList += [size, sizeLbl]
# Draw linegap box
linegap = visual.TextBox2(win, ".linegap", "Outfit", fillColor="purple", color="white", letterHeight=12, pos=(160, (font.descender + font.leading)/2), size=(45, font.linegap), padding=0)
drawList += [linegap]
# Rearrange order
drawList += [drawList.pop(drawList.index(descender))]
drawList += [drawList.pop(drawList.index(height))]
drawList += [drawList.pop(drawList.index(heightLbl))]
drawList += [drawList.pop(drawList.index(leading))]
while not event.getKeys("escape"):
for obj in drawList:
obj.draw()
win.flip()
| 3,732
|
Python
|
.py
| 59
| 61.576271
| 298
| 0.726577
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,878
|
timeByFramesEx.py
|
psychopy_psychopy/psychopy/demos/coder/timing/timeByFramesEx.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This is an extended version of the base timeByFrames demo, adding
the ability to set the psychopy experiment runtime process priority
and disable python garbage collection to see if either influences
the precision of your frame flips.
"""
import gc, numpy
from psychopy import visual, logging, core, event
nIntervals = 500
visual.useFBO = True # if available (try without for comparison)
disable_gc = False
process_priority = 'normal' # 'high' or 'realtime'
if process_priority == 'normal':
pass
elif process_priority == 'high':
core.rush(True)
elif process_priority == 'realtime':
# Only makes a diff compared to 'high' on Windows.
core.rush(True, realtime=True)
else:
print('Invalid process priority:', process_priority, "Process running at normal.")
process_priority = 'normal'
if disable_gc:
gc.disable()
import matplotlib
matplotlib.use('QtAgg') # change this to control the plotting 'back end'
import pylab
win = visual.Window([1280, 1024], fullscr=True, allowGUI=False, waitBlanking=True)
progBar = visual.GratingStim(win, tex=None, mask=None,
size=[0, 0.05], color='red', pos=[0, -0.9], autoLog=False)
myStim = visual.GratingStim(win, tex='sin', mask='gauss',
size=300, sf=0.05, units='pix', autoLog=False)
# logging.console.setLevel(logging.INFO) # uncomment to print log every frame
fliptimes = numpy.zeros(nIntervals + 1)
win.recordFrameIntervals = True
for frameN in range(nIntervals + 1):
progBar.setSize([2.0 * frameN / nIntervals, 0.05])
progBar.draw()
myStim.setPhase(0.1, '+')
myStim.setOri(1, '+')
myStim.draw()
if event.getKeys():
print('stopped early')
break
win.logOnFlip(msg='frame=%i' % frameN, level=logging.EXP)
fliptimes[frameN] = win.flip()
if disable_gc:
gc.enable()
core.rush(False)
win.close()
# calculate some values
intervalsMS = pylab.array(win.frameIntervals) * 1000
m = pylab.mean(intervalsMS)
sd = pylab.std(intervalsMS)
# se=sd/pylab.sqrt(len(intervalsMS)) # for CI of the mean
nTotal = len(intervalsMS)
nDropped = sum(intervalsMS > (1.5 * m))
ifis =(fliptimes[1: ]-fliptimes[: -1]) * 1000
# plot the frameintervals
pylab.figure(figsize=[12, 8], )
pylab.subplot2grid((2, 2), (0, 0), colspan=2)
pylab.plot(intervalsMS, '-')
pylab.ylabel('t (ms)')
pylab.xlabel('frame N')
msg = "Dropped/Frames = %i/%i = %.3f%%. Process Priority: %s, GC Disabled: %s"
pylab.title(msg % (nDropped, nTotal, 100 * nDropped/float(nTotal),
process_priority, str(disable_gc)), fontsize=12)
pylab.subplot2grid((2, 2), (1, 0))
pylab.hist(intervalsMS, 50, histtype='stepfilled')
pylab.xlabel('t (ms)')
pylab.ylabel('n frames')
msg = "win.frameIntervals\nMean=%.2fms, s.d.=%.2f, 99%%CI(frame)=%.2f-%.2f"
pylab.title(msg % (m, sd, m-2.58 * sd, m + 2.58 * sd), fontsize=12)
pylab.subplot2grid((2, 2), (1, 1))
pylab.hist(ifis, 50, histtype='stepfilled')
pylab.xlabel('t (ms)')
pylab.ylabel('n frames')
msg = "Inter Flip Intervals\nMean=%.2fms, s.d.=%.2f, range=%.2f-%.2f ms"
pylab.title(msg % (ifis.mean(), ifis.std(), ifis.min(), ifis.max()), fontsize=12)
pylab.tight_layout()
pylab.show()
win.close()
core.quit()
# The contents of this file are in the public domain.
| 3,256
|
Python
|
.py
| 86
| 35.372093
| 86
| 0.706256
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,879
|
millikeyKeyboardTimingTest.py
|
psychopy_psychopy/psychopy/demos/coder/timing/millikeyKeyboardTimingTest.py
|
# -*- coding: utf-8 -*-
"""
Tests timestamp accuracy and event delay of the keyboard event handling
backend specified by KB_BACKEND using a MilliKey device.
* This test / demo requires that a MilliKey device is connected to the computer being tested.
KB_BACKEND must be one of:
- 'psychopy.event': Use PsychoPy's original pyglet based event handling backend.
- 'psychopy.keyboard': Use keyboard.Keyboard class running PsychHID based backend.
- 'psychopy.keyboard.iohub': Use keyboard.Keyboard class running iohub based backend.
- 'psychopy.iohub': Use the psychopy.iohub event framewok directly.
- 'psychhid': Use an alternative implementation using PsychHID, only for testing.
"""
import os
import string
from psychopy import core, visual, event
import serial
import numpy
import json
import time
# KB_BACKEND = 'psychopy.event'
KB_BACKEND = 'psychopy.keyboard'
# KB_BACKEND = 'psychopy.keyboard.iohub'
# KB_BACKEND = 'psychopy.iohub'
# KB_BACKEND = 'psychhid'
# Used by 'psychopy.keyboard' and 'psychopy.keyboard.iohub' backends
psychopy_keyboard_waitRelease = False
# Number of keyboard events to generate.
kgen_count = 10
# min, max msec duration for generated keypresses.
min_dur, max_dur = 50, 300
# Update the display each loop
# while waiting for event ...
update_display_while_waiting = True
# Sleep sleep_while_wait each loop
# while waiting for event.
# 0 == no call to sleep
sleep_while_wait = 0
#
# Helper functions
#
def getSerialPorts():
available = []
if os.name == 'nt': # Windows
for i in range(1, 256):
try:
sport = 'COM' + str(i)
s = serial.Serial(sport, baudrate=128000)
available.append(sport)
s.close()
except (serial.SerialException, ValueError):
pass
else: # Mac / Linux
from serial.tools import list_ports
available = [port[0] for port in list_ports.comports()]
return available
def getMilliKeyDevices():
devices = []
available = getSerialPorts()
for p in available:
try:
mkey_sport = serial.Serial(p, baudrate=128000, timeout=1.0)
while mkey_sport.readline():
pass
mkey_sport.write(b"GET CONFIG\n")
rx_data = mkey_sport.readline()
if rx_data:
rx_data = rx_data[:-1].strip()
try:
mkconf = json.loads(rx_data)
mkconf['port'] = p
devices.append(mkconf)
except:
raise RuntimeError("ERROR: {}".format(rx_data))
mkey_sport.close()
except:
pass
return devices
#
# Run Test
#
if __name__ == "__main__":
millikeys = getMilliKeyDevices()
if len(millikeys) == 0:
print("No Millikey device detected. Exiting test...")
core.quit()
mk_serial_port = millikeys[0]['port']
# min, max msec MilliKey will wait before issuing the requested key press event.
min_delay, max_delay = 1, 3
possible_kgen_chars = string.ascii_lowercase + string.digits
io = None
ptb_kb = None
getKeys = None
# psychhid event timestamps are in psychtoolbox.GetSecs
# so make test use that timebase.
getTime = core.getTime
if KB_BACKEND in ['psychhid', 'psychopy.keyboard']:
from psychtoolbox import GetSecs
getTime = GetSecs
# psychopy.event is used as a secondary backend in case the primary backend
# being tested (KB_BACKEND) fails to detect a keypress event.
# Only used if KB_BACKEND != psychopy.event
backup_getKeys = None
if KB_BACKEND != 'psychopy.event':
def backup_getKeys():
return event.getKeys(timeStamped=True)
# Create getKeys function to test desired keyboard backend
if KB_BACKEND == 'psychopy.event':
def getKeys():
return event.getKeys(timeStamped=True)
elif KB_BACKEND == 'psychopy.keyboard':
from psychopy.hardware.keyboard import Keyboard as ptbKeyboard
ptb_kb = ptbKeyboard()
def getKeys():
keys = ptb_kb.getKeys(waitRelease=psychopy_keyboard_waitRelease)
return [(k.name, k.tDown) for k in keys]
elif KB_BACKEND == 'psychopy.iohub':
from psychopy.iohub import launchHubServer
io = launchHubServer()
def getKeys():
keys = io.devices.keyboard.getPresses()
return [(k.key, k.time) for k in keys]
elif KB_BACKEND == 'psychopy.keyboard.iohub':
from psychopy.iohub import launchHubServer
io = launchHubServer()
from psychopy.hardware.keyboard import Keyboard as ptbKeyboard
ptb_kb = ptbKeyboard()
def getKeys():
keys = ptb_kb.getKeys(waitRelease=psychopy_keyboard_waitRelease)
return [(k.name, k.tDown) for k in keys]
elif KB_BACKEND == 'psychhid':
from psychtoolbox import PsychHID
ptb_keys = [1] * 256
PsychHID('KbQueueCreate', [], ptb_keys)
PsychHID('KbQueueStart')
def getKeys():
keys = []
while PsychHID('KbQueueFlush'):
evt = PsychHID('KbQueueGetEvent')[0]
if evt['Pressed']:
K = chr(int(evt['CookedKey'])).lower()
keys.append((K, evt['Time']))
return keys
def close_backend():
if KB_BACKEND == 'psychhid':
PsychHID('KbQueueStop')
elif io:
io.quit()
win = visual.Window([800, 400]) #, fullscr=True, allowGUI=False)
r = win.getMsPerFrame(60)
print()
print("Test Settings: ")
print("\tEvent backend: ", KB_BACKEND)
if KB_BACKEND.find('psychopy.keyboard') >= 0:
print("\tpsychopy_keyboard_waitRelease: ", psychopy_keyboard_waitRelease)
print("\tupdate_display_while_waiting: ", update_display_while_waiting)
print("\tsleep_while_wait (sec): ", sleep_while_wait)
print("\tmin_delay, max_delay (msec): ", (min_delay, max_delay))
print("\tmin_dur, max_dur (msec): ", (min_dur, max_dur))
print("\twin.getMsPerFrame(): ", r)
print()
ts_errors = numpy.zeros(kgen_count, dtype=numpy.float64)
evt_delays = numpy.zeros(kgen_count, dtype=numpy.float64)
mk_sconn = serial.Serial(mk_serial_port, baudrate=128000, timeout=0.01)
txt1 = "Testing %s backend.\nMilliKey Generating Key Press:\n Key: [%s], Duration: %d msec.\n%d of %d events."
msg = visual.TextStim(win, text=txt1)
dotPatch = visual.DotStim(win, color=(0.0, 1.0, 0.0), dir=270,
nDots=223, fieldShape='sqr',
fieldPos=(0.0, 0.0), fieldSize=1.5,
dotLife=50, signalDots='same',
noiseDots='direction', speed=0.01,
coherence=0.9)
def drawAndFlip(txt=None):
if txt:
msg.text = txt
dotPatch.draw()
msg.draw()
return win.flip()
drawAndFlip()
print()
count = 0
no_event_count = 0
while count < kgen_count:
kchar = possible_kgen_chars[count % (len(possible_kgen_chars))]
press_duration = int(numpy.random.randint(min_dur, max_dur))
delay_evt_usec = int(numpy.random.randint(min_delay, max_delay))*1000
evt_delay_sec = delay_evt_usec/1000.0/1000.0
drawAndFlip(txt1 % (KB_BACKEND, kchar, press_duration, count+1, kgen_count))
if ptb_kb:
ptb_kb.clock.reset()
# Instruct MilliKey device to:
# - generate a key press delay_evt_usec after receiving the KGEN command
# - generate key release event press_duration after press event is sent.
kgen_cmd = "KGEN {} {} {}\n".format(kchar, press_duration, delay_evt_usec).encode()
mk_sconn.write(kgen_cmd)
mk_sconn.flush()
# stime is the time the KGEN command was sent to the MilliKey device.
# plus the event offset the device is using.
stime = getTime()+evt_delay_sec
# Keep checking for key press events until one is received
kb_presses = getKeys()
last_check_time = ctime = getTime()
while not kb_presses:
if getTime() - ctime > 2.0:
# Report missed event.
print("*WARNING: {} did not detect key press '{}' of duration {}.".format(KB_BACKEND, kchar, press_duration))
if backup_getKeys:
presses = backup_getKeys()
if presses:
print("\tHowever, event.getKeys() received: ", presses)
no_event_count += 1
break
if update_display_while_waiting:
drawAndFlip()
if sleep_while_wait > 0:
time.sleep(sleep_while_wait)
kb_presses = getKeys()
last_check_time = getTime()
# to clear backup getKeys()
if backup_getKeys:
_ = backup_getKeys()
if kb_presses:
if len(kb_presses) > 1:
txt = "Error: {} keypress events detected at once: {}\n"
txt += "Was a keyboard key or MilliKey button pressed during the test?"
print(txt.format(len(kb_presses), kb_presses))
close_backend()
core.quit()
# Get the key name and timestamp of event
kpress, ktime = kb_presses[0]
# Ensure we got the key we were expecting.....
if kchar == kpress:
ts_errors[count] = ktime - stime
evt_delays[count] = last_check_time-stime
count += 1
else:
txt = "Error: Keyboard Key != Key Press Issued ([{}] vs [{}]).\n"
txt += "Was a keyboard key or MilliKey button pressed during the test?"
print(txt.format(kchar, kpress))
close_backend()
core.quit()
# Wait until after MilliKey has issued associated key release event.
ctime = getTime()
while getTime() - ctime < (press_duration/1000.0)*1.25:
if update_display_while_waiting:
drawAndFlip()
if sleep_while_wait > 0:
time.sleep(sleep_while_wait)
getKeys()
# Done test, close backend if needed
close_backend()
mk_sconn.close()
win.close()
# Print Results
if no_event_count > 0:
print()
print("** WARNING: '%s' missed %d keypress events (%.6f percent)." % (KB_BACKEND, no_event_count,
(no_event_count/count)*100))
print()
# Convert times to msec.
evt_results = ts_errors[:count] * 1000.0
print("%s Timestamp Accuracy Stats" % KB_BACKEND)
print("\tCount: {}".format(evt_results.shape))
print("\tAverage: {:.3f} msec".format(evt_results.mean()))
print("\tMedian: {:.3f} msec".format(numpy.median(evt_results)))
print("\tMin: {:.3f} msec".format(evt_results.min()))
print("\tMax: {:.3f} msec".format(evt_results.max()))
print("\tStdev: {:.3f} msec".format(evt_results.std()))
print()
# Convert times to msec.
evt_results = evt_delays[:count] * 1000.0
print("%s Keypress Event Delays" % KB_BACKEND)
print("\tCount: {}".format(evt_results.shape))
print("\tAverage: {:.3f} msec".format(evt_results.mean()))
print("\tMedian: {:.3f} msec".format(numpy.median(evt_results)))
print("\tMin: {:.3f} msec".format(evt_results.min()))
print("\tMax: {:.3f} msec".format(evt_results.max()))
print("\tStdev: {:.3f} msec".format(evt_results.std()))
core.quit()
| 11,835
|
Python
|
.py
| 278
| 32.902878
| 125
| 0.598776
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,880
|
timeByFrames.py
|
psychopy_psychopy/psychopy/demos/coder/timing/timeByFrames.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
The most accurate way to time your stimulus presentation is to
present for a certain number of frames. For that to work you need
your window flips to synchronize to the monitor and not to drop
any frames. This script examines the precision of your frame flips.
Shut down as many applications as possible, especially those that
might try to update
"""
from psychopy import visual, logging, core, event
visual.useFBO = True # if available (try without for comparison)
import matplotlib
import pylab
import sys
if sys.platform == "darwin":
# on Mac...
matplotlib.use('QtAgg')
else:
# on any other OS...
matplotlib.use('Qt4Agg')
nIntervals = 500
win = visual.Window([1280, 1024], fullscr=True, allowGUI=False, waitBlanking=True)
progBar = visual.GratingStim(win, tex=None, mask=None,
size=[0, 0.05], color='red', pos=[0, -0.9], autoLog=False)
myStim = visual.GratingStim(win, tex='sin', mask='gauss',
size=300, sf=0.05, units='pix', autoLog=False)
# logging.console.setLevel(logging.INFO)# uncomment to log every frame
win.recordFrameIntervals = True
for frameN in range(nIntervals + 1):
progBar.setSize([2.0 * frameN/nIntervals, 0.05])
progBar.draw()
myStim.setPhase(0.1, '+')
myStim.draw()
if event.getKeys():
print('stopped early')
break
win.logOnFlip(msg='frame=%i' %frameN, level=logging.EXP)
win.flip()
win.fullscr = False
win.close()
# calculate some values
intervalsMS = pylab.array(win.frameIntervals) * 1000
m = pylab.mean(intervalsMS)
sd = pylab.std(intervalsMS)
# se=sd/pylab.sqrt(len(intervalsMS)) # for CI of the mean
msg = "Mean=%.1fms, s.d.=%.2f, 99%%CI(frame)=%.2f-%.2f"
distString = msg % (m, sd, m - 2.58 * sd, m + 2.58 * sd)
nTotal = len(intervalsMS)
nDropped = sum(intervalsMS > (1.5 * m))
msg = "Dropped/Frames = %i/%i = %.3f%%"
droppedString = msg % (nDropped, nTotal, 100 * nDropped / float(nTotal))
# plot the frameintervals
pylab.figure(figsize=[12, 8])
pylab.subplot(1, 2, 1)
pylab.plot(intervalsMS, '-')
pylab.ylabel('t (ms)')
pylab.xlabel('frame N')
pylab.title(droppedString)
pylab.subplot(1, 2, 2)
pylab.hist(intervalsMS, 50, histtype='stepfilled')
pylab.xlabel('t (ms)')
pylab.ylabel('n frames')
pylab.title(distString)
pylab.show()
win.close()
core.quit()
# The contents of this file are in the public domain.
| 2,370
|
Python
|
.py
| 68
| 32.676471
| 82
| 0.719214
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,881
|
callOnFlip.py
|
psychopy_psychopy/psychopy/demos/coder/timing/callOnFlip.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This demo shows you how to schedule a call to an arbitrary function immediately
using win.callOnFlip()
This is especially useful in scheduling a call to a trigger (eg. parallel port) when
your frame flip occurs. Avoid do anything time-consuming in these function calls.
The first argument to callOnFlip() is the function you want to call, the other
arguments are the arguments exactly as you would normally use them
(and can used ordered arguments or named, keyword args as usual).
"""
from psychopy import visual, core
import numpy
win = visual.Window([400, 400])
# insert a pause to allow the window and python (avoid initial frame drops)
core.wait(2)
clock = core.Clock() # a clock to check times from
# a function to be called on selected frames
def printFrame(frameN, tReceived):
tPrinted = clock.getTime()
print(frameN, tReceived, tPrinted)
for frame in range(100):
core.wait(numpy.random.random()/200) # wait 0-5ms
if frame in [2, 4, 6, 20, 30, 40]:
win.callOnFlip(printFrame, frame, tReceived=clock.getTime())
core.wait(numpy.random.random() / 200) # wait 0-5ms
win.flip()
win.close()
core.quit()
# The contents of this file are in the public domain.
| 1,253
|
Python
|
.py
| 30
| 39.4
| 84
| 0.747941
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,882
|
clocksAndTimers.py
|
psychopy_psychopy/psychopy/demos/coder/timing/clocksAndTimers.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Demo for clocks and count-down timers
"""
from psychopy import core
core.wait(0.5) # give the system time to settle
# create a clock
clock = core.Clock()
clock.reset() # whenever you like
# to create a timer you can 'add' time to the zero point
# and wait to get back to zero
timer = core.Clock()
timer.add(3)
# there's also a countdown timer (just a flip of the clock)
countDown = core.CountdownTimer()
countDown.add(3)
another = core.Clock()
print("down up clock")
while countDown.getTime() > 0:
msg = "%.4f %.4f %.4f"
print(msg % (countDown.getTime(), timer.getTime(), clock.getTime()))
core.wait(0.2) # this combined + print will allow a gradual timing 'slip'
# use the timer, rather than wait(), to prevent the slip
print("\ndown clock")
timer.reset()
timer.add(0.2)
countDown.add(3)
while countDown.getTime() > 0:
print("%.4f %.4f" %(countDown.getTime(), clock.getTime()))
while timer.getTime() < 0: # includes the time taken to print
pass
timer.add(0.2)
print("The last run should have been precise sub-millisecond")
core.quit()
# The contents of this file are in the public domain.
| 1,216
|
Python
|
.py
| 36
| 31.611111
| 78
| 0.688034
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,883
|
hello_world.py
|
psychopy_psychopy/psychopy/demos/coder/basic/hello_world.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Demo: show a very basic program: hello world
"""
# Import key parts of the PsychoPy library:
from psychopy import visual, core
# Create a visual window:
win = visual.Window(units="height")
# Create (but not yet display) some text:
msg1 = visual.TextBox2(win,
text=u"Hello world!",
font="Open Sans", letterHeight=0.1,
pos=(0, 0.2))
msg2 = visual.TextBox2(win,
text=u"\u00A1Hola mundo!",
font="Open Sans", letterHeight=0.1,
pos=(0, -0.2))
# Draw the text to the hidden visual buffer:
msg1.draw()
msg2.draw()
# Show the hidden buffer--everything that has been drawn since the last win.flip():
win.flip()
# Wait 3 seconds so people can see the message, then exit gracefully:
core.wait(3)
win.close()
core.quit()
# The contents of this file are in the public domain.
| 851
|
Python
|
.py
| 28
| 28
| 83
| 0.710074
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,884
|
makeMovie.py
|
psychopy_psychopy/psychopy/demos/coder/misc/makeMovie.py
|
from psychopy import visual, core, prefs
from pathlib import Path
from math import sin, pi, cos
win = visual.Window(size=(128,128), units='pix')
resourcesFolder = Path(prefs.paths['resources'])
psychopyIcon = resourcesFolder / "psychopy.png"
img = visual.ImageStim(win, psychopyIcon)
img.autoDraw = True
# grow and spin
for frameN in range(200):
if frameN < 50:
h = frameN*2
img.size = (cos(frameN/50*pi)*h, h)
win.flip()
win.getMovieFrame()
# fade to grey
for frameN in range(5):
img.contrast -= 0.2
win.flip()
win.getMovieFrame()
win.saveMovieFrames('myMov.mp4', fps=30, codec='libx264', clearFrames=False)
#win.saveMovieFrames('myMov.png')
#win.saveMovieFrames('myMov.gif')
| 721
|
Python
|
.py
| 23
| 28.434783
| 76
| 0.724638
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,885
|
encrypt_data.py
|
psychopy_psychopy/psychopy/demos/coder/misc/encrypt_data.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Demo to illustrate encryption and decryption of a data file using pyFileSec
"""
from pyfilesec import SecFile, GenRSA
import os
# Logging is available, optional:
# from psychopy import logging
# logging.console.setLevel(logging.INFO)
# pfs.logging = logging
# We need a data file to encrypt, e.g., containing "sensitive" info:
datafile = 'data.txt'
with open(datafile, 'wb') as file:
file.write("confidential data, e.g., participant's drug-use history")
# To set up for encryption, give it to a SecFile:
sf = SecFile(datafile)
msg = 'make a file:\n file name: "%s"\n contents: "%s"'
print(msg % (sf.file, sf.snippet))
print(' is encrypted: %s' % sf.is_encrypted)
# These particular RSA keys are ONLY for testing
# see pyfilesec.genrsa() to make your own keys)
# paths to new tmp files that hold the keys
pubkey, privkey, passphrase = GenRSA().demo_rsa_keys()
# To encrypt the file, use the RSA public key:
sf.encrypt(pubkey)
msg = 'ENCRYPT it:\n file name: "%s"\n contents (base64): "%s . . ."'
print(msg % (sf.file, sf.snippet))
print(' is encrypted: %s' % sf.is_encrypted)
# To decrypt the file, use the matching RSA private key (and its passphrase):
sf.decrypt(privkey, passphrase)
msg = 'DECRYPT it:\n file name: "%s"\n contents: "%s"'
print(msg % (sf.file, sf.snippet))
print(' is encrypted: %s' % sf.is_encrypted)
# clean-up the tmp files:
for file in [sf.file, pubkey, privkey, passphrase]:
os.unlink(file)
# The contents of this file are in the public domain.
| 1,545
|
Python
|
.py
| 38
| 39.184211
| 77
| 0.718103
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,886
|
rigidBodyTransform.py
|
psychopy_psychopy/psychopy/demos/coder/misc/rigidBodyTransform.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Demo for the class psychopy.visual.RigidBodyPose class.
This demonstrates how to use rigid body transforms to control the poses of 3D
objects in a scene.
"""
from psychopy import core, event
import psychopy.visual as visual
from psychopy.visual import SphereStim, LightSource, RigidBodyPose
win = visual.Window((600, 600), allowGUI=False, monitor='testMonitor')
# create a rigid body defining the pivot point of objects in the scene
pivotPose = RigidBodyPose((0, 0, -5))
# text to display
instr = visual.TextStim(win, text="Any key to quit", pos=(0, -.7))
# create scene light at the pivot point
win.lights = [
LightSource(win, pos=pivotPose.pos, lightType='point',
diffuseColor=(0, 0, 0), specularColor=(1, 1, 1))
]
# Create poses for objects in the scene, these need to remain unchanged so we
# define them here and then set the poses of the 3D stimuli. Pose positions
# are relative to the pivot point.
spherePose1 = RigidBodyPose((0.1, -0.1, 0.1))
spherePose2 = RigidBodyPose((-0.1, 0.1, 0.1))
spherePose3 = RigidBodyPose((0.1, -0.1 , -0.1))
# create some sphere stim objects
lightSphere = SphereStim(win, radius=0.05, color='white')
sphere1 = SphereStim(win, radius=0.05, color='red')
sphere2 = SphereStim(win, radius=0.1, color='green')
sphere3 = SphereStim(win, radius=0.075, color='blue')
angle = 0.0
while not event.getKeys():
# rotate the pivot pose
pivotPose.setOriAxisAngle((0, 1, 0), angle)
# setup drawing
win.setPerspectiveView()
# sphere for the light source, note this does not actually emit light
lightSphere.thePose = pivotPose
lightSphere.draw()
# call after drawing `lightSphere` since we don't want it being shaded
win.useLights = True
# multiplying pose puts the first object in the reference frame of the
# second
sphere1.thePose = spherePose1 * pivotPose
sphere2.thePose = spherePose2 * pivotPose
sphere3.thePose = spherePose3 * pivotPose
sphere1.draw()
sphere2.draw()
sphere3.draw()
# reset transform to draw text correctly
win.resetEyeTransform()
instr.draw()
win.flip()
angle += 0.5
win.close()
core.quit()
| 2,211
|
Python
|
.py
| 56
| 36.214286
| 77
| 0.727996
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,887
|
piloting.py
|
psychopy_psychopy/psychopy/demos/coder/experiment control/piloting.py
|
"""
This demo shows off the piloting mode setting. Using a function in the `core`
module, you can figure out whether the script was run with the "--pilot" flag,
which is supplied if you click the Run button while the pilot/run toggle is set
to pilot (the run button will be orange).
See below for some examples of behaviour you may wish to change according to
piloting mode.
"""
from psychopy import core, visual, logging
from psychopy.hardware import keyboard
# work out from system args whether we are running in pilot mode
PILOTING = core.setPilotModeFromArgs()
# set some variables according to whether or not we're piloting
fullScr = True
pilotingIndicator = False
logLvl = logging.WARNING
modeMsg = "RUNNING"
tryMsg = "PILOTING"
if PILOTING:
# it's a good idea to force fullScr False when piloting, to stop yourself
# from getting stuck in a full screen experiment if there's an error in
# your code
fullScr = False
# the piloting indicator is pretty obnoxious, making it super clear when
# you're piloting (so you don't accidentally gather data in piloting mode!)
pilotingIndicator = True
# there will be a lot of EXPERIMENT level logging messages, which can get
# annoying - but when you're piloting, you're more likely to want this
# level of detail for debugging!
logLvl = logging.INFO
# in this demo, we're showing some text which varies according to piloting
# mode - these variables is what varies it
modeMsg = "PILOTING"
tryMsg = "RUNNING"
# set logging level
logging.console.setLevel(logLvl)
# make window
win = visual.Window(fullscr=fullScr)
# set piloting indicator
if pilotingIndicator:
win.showPilotingIndicator()
# make a textbox with a differing message according to mode
txtbox = visual.TextBox2(
win, text=(
f"If you're reading this, you're in {modeMsg} mode! Toggle the "
f"pilot/run switch and run again to try {tryMsg}"
),
alignment="center"
)
# make a Keyboard
kb = keyboard.Keyboard()
# start a frame loop until user presses esc
while not kb.getKeys("escape"):
txtbox.draw()
win.flip()
| 2,137
|
Python
|
.py
| 55
| 35.618182
| 80
| 0.749154
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,888
|
JND_staircase_analysis.py
|
psychopy_psychopy/psychopy/demos/coder/experiment control/JND_staircase_analysis.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This analysis script takes one or more staircase datafiles as input from a GUI
It then plots the staircases on top of each other on the left
and a combined psychometric function from the same data
on the right.
The combined plot uses every unique X value form the staircase, and alters the
size of the points according to how many trials were run at that level
"""
from psychopy import data, gui, core
from psychopy.tools.filetools import fromFile
import pylab
import os
# set to 0.5 for Yes/No (or PSE). Set to 0.8 for a 2AFC threshold
threshVal = 0.5
# set to zero for Yes/No (or PSE). Set to 0.5 for 2AFC
expectedMin = 0.0
files = gui.fileOpenDlg('.')
if not files:
core.quit()
# get the data from all the files
allIntensities, allResponses = [], []
for thisFileName in files:
thisDat = fromFile(thisFileName)
assert isinstance(thisDat, data.StairHandler)
allIntensities.append(thisDat.intensities)
allResponses.append(thisDat.data)
dataFolder = os.path.split(thisFileName)[0] # just the path, not file name
# plot each staircase in left hand panel
pylab.subplot(121)
colors = 'brgkcmbrgkcm'
lines, names = [], []
for fileN, thisStair in enumerate(allIntensities):
# lines.extend(pylab.plot(thisStair)) # uncomment for a legend for files
# names = files[fileN]
pylab.plot(thisStair, label=files[fileN])
# pylab.legend()
# get combined data
i, r, n = data.functionFromStaircase(allIntensities, allResponses, bins='unique')
combinedInten, combinedResp, combinedN = i, r, n
combinedN = pylab.array(combinedN) # convert to array so we can do maths
# fit curve
fit = data.FitWeibull(combinedInten, combinedResp, expectedMin=expectedMin,
sems=1.0 / combinedN)
smoothInt = pylab.arange(min(combinedInten), max(combinedInten), 0.001)
smoothResp = fit.eval(smoothInt)
thresh = fit.inverse(threshVal)
print(thresh)
# plot curve
pylab.subplot(122)
pylab.plot(smoothInt, smoothResp, 'k-')
pylab.plot([thresh, thresh], [0, threshVal], 'k--') # vertical dashed line
pylab.plot([0, thresh], [threshVal, threshVal], 'k--') # horizontal dashed line
pylab.title('threshold (%.2f) = %0.3f' %(threshVal, thresh))
# plot points
pointSizes = pylab.array(combinedN) * 5 # 5 pixels per trial at each point
points = pylab.scatter(combinedInten, combinedResp, s=pointSizes,
edgecolors=(0, 0, 0), facecolor=(1, 1, 1), linewidths=1,
zorder=10, # make sure the points plot on top of the line
)
pylab.ylim([0, 1])
pylab.xlim([0, None])
# save a vector-graphics format for future
outputFile = os.path.join(dataFolder, 'last.pdf')
pylab.savefig(outputFile)
print('saved figure to: ' + outputFile)
pylab.show()
core.quit()
# The contents of this file are in the public domain.
| 2,767
|
Python
|
.py
| 70
| 37.628571
| 81
| 0.752051
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,889
|
gammaMotionAnalysis.py
|
psychopy_psychopy/psychopy/demos/coder/experiment control/gammaMotionAnalysis.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Use this script to analyze data from the gammaMotionNull.py
script.
Instructions: From the dialogue box select multiple staircases (Cmd-click
or shift-click) to plot the results
"""
import matplotlib
matplotlib.use('TKAgg')
from psychopy import data, gui, core
from psychopy.tools.filetools import fromFile
import pylab
import numpy as num
files = gui.fileOpenDlg('.')
if not files:
core.quit()
# get the data from all the files
allIntensities, allResponses = [], []
for thisFileName in files:
thisDat = fromFile(thisFileName)
assert isinstance(thisDat, data.StairHandler)
allIntensities.append( thisDat.intensities )
allResponses.append( thisDat.data )
# plot each staircase
pylab.subplot(121)
lines, names = [], []
for fileN, thisStair in enumerate(allIntensities):
# lines.extend(pylab.plot(thisStair))
# names = files[fileN]
pylab.plot(thisStair, label=files[fileN])
# pylab.legend()
# get combined data
i, r, n = data.functionFromStaircase(allIntensities, allResponses, 'unique')
combinedInten, combinedResp, combinedN = i, r, n
# fit curve
guess =[num.average(combinedInten), num.average(combinedInten)/5]
fit = data.FitWeibull(combinedInten, combinedResp, guess=guess, expectedMin=0.0)
smoothInt = num.arange(min(combinedInten), max(combinedInten), 0.001)
smoothResp = fit.eval(smoothInt)
thresh = fit.inverse(0.5)
print(thresh)
# plot curve
pylab.subplot(122)
pylab.plot(smoothInt, smoothResp, '-')
pylab.plot([thresh, thresh], [0, 0.5], '--')
pylab.plot([0, thresh], [0.5, 0.5], '--')
pylab.title('threshold = %0.3f' %(thresh))
# plot points
pylab.plot(combinedInten, combinedResp, 'o')
pylab.ylim([0, 1])
pylab.show()
core.quit()
# The contents of this file are in the public domain.
| 1,790
|
Python
|
.py
| 54
| 31.296296
| 80
| 0.754936
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,890
|
logFiles.py
|
psychopy_psychopy/psychopy/demos/coder/experiment control/logFiles.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
PsychoPy's log module is mostly a simple wrapper of the python logging module.
It allows messages to be sent from any location (any library or your script) and
written to files according to the importance level of the message and the minimum level
that the log file (or console) is set to receive. You can have multiple log files each receiving
different levels of input.
The importance levels are
40: ERROR
35: DATA
30: WARNING
25: DATA
22: EXP
20: INFO
10: DEBUG
So setting to DEBUG level will include all possible messages, setting to ERROR will include only the absolutely essential messages.
"""
from psychopy import logging, core, visual
globalClock = core.Clock() # if this isn't provided the log times will reflect secs since python started
logging.setDefaultClock(globalClock)
logging.console.setLevel(logging.DEBUG) # receive nearly all messages
logDat = logging.LogFile('logLastRun.log',
filemode='w', # if you set this to 'a' it will append instead of overwriting
level=logging.WARNING) # errors, data and warnings will be sent to this logfile
# the following will go to any files with the appropriate minimum level set
logging.info('Something fairly unimportant')
logging.data('Something about our data. Data is likely very important!')
logging.warning('Handy while building your experiment - highlights possible flaws in code/design')
logging.error("You might have done something that PsychoPy can't handle! But hopefully this gives you some idea what.")
# some things should be logged timestamped on the next video frame
# For instance the time of a stimulus appearing is related to the flip:
win = visual.Window([400, 400])
for n in range(5):
win.logOnFlip('frame %i occured' %n, level=logging.EXP)
if n in [2, 4]:
win.logOnFlip('an even frame occured', level=logging.EXP)
win.flip()
# LogFiles can also simply receive direct input from the write() method
# messages using write() will be sent immediately, and are often not
# in correct chronological order with logged messages
logDat.write("Testing\n\n")
win.close()
core.quit()
# The contents of this file are in the public domain.
| 2,221
|
Python
|
.py
| 45
| 46.888889
| 131
| 0.770083
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,891
|
fMRI_launchScan.py
|
psychopy_psychopy/psychopy/demos/coder/experiment control/fMRI_launchScan.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This demo illustrates using hardware.emulator.launchScan() to either start a
real scan, or emulate sync pulses. Emulation is to allow debugging script timing
offline, without requiring a scanner (or a hardware sync pulse generator).
"""
# Author: Jeremy R. Gray
from psychopy import visual, event, core, gui
from psychopy.hardware.emulator import launchScan
# settings for launchScan:
MR_settings = {
'TR': 2.000, # duration (sec) per whole-brain volume
'volumes': 5, # number of whole-brain 3D volumes per scanning run
'sync': 'slash', # character to use as the sync timing event; assumed to come at start of a volume
'skip': 0, # number of volumes lacking a sync pulse at start of scan (for T1 stabilization)
'sound': True # in test mode: play a tone as a reminder of scanner noise
}
infoDlg = gui.DlgFromDict(MR_settings, title='fMRI parameters', order=['TR', 'volumes'])
if not infoDlg.OK:
core.quit()
win = visual.Window(fullscr=False)
globalClock = core.Clock()
# summary of run timing, for each key press:
output = u'vol onset key\n'
for i in range(-1 * MR_settings['skip'], 0):
output += u'%d prescan skip (no sync)\n' % i
counter = visual.TextStim(win, height=.05, pos=(0, 0), color=win.rgb + 0.5)
output += u" 0 0.000 sync [Start of scanning run, vol 0]\n"
# launch: operator selects Scan or Test (emulate); see API documentation
vol = launchScan(win, MR_settings, globalClock=globalClock)
counter.setText(u"%d volumes\n%.3f seconds" % (0, 0.0))
counter.draw()
win.flip()
duration = MR_settings['volumes'] * MR_settings['TR']
# note: globalClock has been reset to 0.0 by launchScan()
while globalClock.getTime() < duration:
allKeys = event.getKeys()
for key in allKeys:
if key == MR_settings['sync']:
onset = globalClock.getTime()
# do your experiment code at this point if you want it sync'd to the TR
# for demo just display a counter & time, updated at the start of each TR
counter.setText(u"%d volumes\n%.3f seconds" % (vol, onset))
output += u"%3d %7.3f sync\n" % (vol, onset)
counter.draw()
win.flip()
vol += 1
else:
# handle keys (many fiber-optic buttons become key-board key-presses)
output += u"%3d %7.3f %s\n" % (vol-1, globalClock.getTime(), str(key))
if key == 'escape':
output += u'user cancel, '
break
t = globalClock.getTime()
win.flip()
output += u"End of scan (vol 0..%d = %d of %s). Total duration = %7.3f sec" % (vol - 1, vol, MR_settings['volumes'], t)
print(output)
win.close()
core.quit()
# The contents of this file are in the public domain.
| 2,785
|
Python
|
.py
| 61
| 40.836066
| 119
| 0.659904
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,892
|
gammaMotionNull.py
|
psychopy_psychopy/psychopy/demos/coder/experiment control/gammaMotionNull.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Determine screen gamma using motion-nulling method
of Ledgeway and Smith, 1994, Vision Research, 34, 2727-2740
A similar system had been used early for chromatic isoluminance:
Anstis SM, Cavanagh P. A minimum motion technique for judging equiluminance.
In: Sharpe MJD & LT Colour vision: Psychophysics and physiology. London: Academic Press; 1983. pp. 66-77.
Instructions: on each trial press the up/down cursor keys depending on
the apparent direction of motion of the bars.
"""
from psychopy import visual, core, event, gui, data
from psychopy.tools.filetools import fromFile, toFile
from psychopy.visual import filters
import numpy as num
import time
try:
# try to load previous info
info = fromFile('info_gamma.pickle')
print(info)
except Exception:
# if no file use some defaults
info = {}
info['lumModNoise'] = 0.5
info['lumModLum'] = 0.1
info['contrastModNoise'] = 1.0
info['observer'] = ''
info['highGamma'] = 3.0
info['lowGamma'] = 0.8
info['nTrials'] = 50
dlg = gui.DlgFromDict(info)
# save to a file for future use (ie storing as defaults)
if dlg.OK:
toFile('info_gamma.pickle', info)
else:
core.quit() # user cancelled. quit
print(info)
info['timeStr']=time.strftime("%b_%d_%H%M", time.localtime())
nFrames = 3
cyclesTime = 2
cyclesSpace = 2
pixels = 128
win = visual.Window((1024, 768), units='pix', allowGUI=True, bitsMode=None)
visual.TextStim(win, text='building stimuli').draw()
win.flip()
globalClock = core.Clock()
# for luminance modulated noise
noiseMatrix = num.random.randint(0, 2, [pixels, pixels]) # * noiseContrast
noiseMatrix = noiseMatrix * 2.0-1 # into range -1: 1
stimFrames = []; lumGratings=[]
# create the 4 frames of the sequence (luminance and contrast modulated noise in quadrature)
lumGratings.append(filters.makeGrating(pixels, 0, cyclesSpace, phase=0))
stimFrames.append(visual.GratingStim(win, texRes=pixels, mask='circle',
size=pixels * 2, sf=1.0 / pixels, ori=90,
tex= (noiseMatrix * info['lumModNoise'] + lumGratings[0] * info['lumModLum'])
))
lumGratings.append(filters.makeGrating(pixels, 0, cyclesSpace, phase=90) / 2.0 + 0.5)
stimFrames.append(visual.GratingStim(win, texRes=pixels, mask='circle',
size=pixels * 2, sf=1.0/pixels, ori=90,
tex= (noiseMatrix * info['contrastModNoise'] * lumGratings[1])
))
lumGratings.append(filters.makeGrating(pixels, 0, cyclesSpace, phase=180))
stimFrames.append(visual.GratingStim(win, texRes=pixels, mask='circle',
size=pixels * 2, sf=1.0/pixels, ori=90,
tex= (noiseMatrix * info['lumModNoise'] + lumGratings[2] * info['lumModLum'])
))
lumGratings.append(filters.makeGrating(pixels, 0, cyclesSpace, phase=270) / 2.0 + 0.5)
stimFrames.append(visual.GratingStim(win, texRes=pixels, mask='circle',
size=pixels * 2, sf=1.0/pixels, ori=90,
tex= (noiseMatrix * info['contrastModNoise'] * lumGratings[3])
))
stairCases = []
# two staircases - one from the top, one from below - to average
stairCases.append(data.StairHandler(startVal=info['highGamma'], nTrials=info['nTrials'],
stepSizes=[0.5, 0.5, 0.1, 0.1, 0.1, 0.1, 0.05, 0.05], stepType='lin',
nUp=1, nDown=1))
stairCases.append(data.StairHandler(startVal=info['lowGamma'], nTrials=info['nTrials'],
stepSizes=[0.5, 0.5, 0.1, 0.1, 0.1, 0.1, 0.05, 0.05], stepType='lin',
nUp=1, nDown=1))
def getResponse(direction):
"""if subject said up when direction was up ( + 1) then increase gamma
Otherwise, decrease gamma"""
event.clearEvents() # clear the event buffer to start with
while 1: # forever until we return
for key in event.getKeys():
# quit
if key in ['escape', 'q']:
win.close()
# win.bits.reset()
core.quit()
# valid response - check to see if correct
elif key in ['down', 'up']:
if ((key in ['down'] and direction == -1) or
(key in ['up'] and direction == +1)):
return 0
else:
return 1
else:
print("hit DOWN or UP (or Esc) (You hit %s)" %key)
def presentStimulus(direction):
"""Present stimulus drifting in a given direction (for low gamma)
where:
direction = + 1(up) or -1(down)
"""
win.fps()
startPhase = num.random.random()
if direction == 1:
frameIndices = num.arange(0, 4)
else:
frameIndices = num.arange(3, -1, -1)
for cycles in range(cyclesTime):
# cycle through the 4 frames
for ii in frameIndices:
thisStim = stimFrames[ii]
thisStim.setPhase(startPhase)
for n in range(nFrames):
# present for several constant frames (TF)
thisStim.draw()
win.flip()
# then blank the screen
win.flip()
# run the staircase
for trialN in range(info['nTrials']):
for stairCase in stairCases:
thisGamma = next(stairCase)
t = globalClock.getTime()
win.gamma = [thisGamma, thisGamma, thisGamma]
direction = num.random.randint(0, 2) * 2-1 # a random number -1 or 1
presentStimulus(direction)
ans = getResponse(direction)
stairCase.addData(ans)
win.flip()
core.wait(0.5)
win.close()
# save data
fileName = gui.fileSaveDlg('.', '%s_%s' %(info['observer'], info['timeStr']))
stairCases[1].saveAsPickle(fileName + 'hi')
stairCases[1].saveAsText(fileName + 'hi')
stairCases[0].saveAsPickle(fileName + 'lo')
stairCases[0].saveAsText(fileName + 'lo')
print('That took %.1fmins' % (globalClock.getTime() / 60.0))
core.quit()
# The contents of this file are in the public domain.
| 5,824
|
Python
|
.py
| 143
| 34.986014
| 105
| 0.657825
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,893
|
TrialHandler.py
|
psychopy_psychopy/psychopy/demos/coder/experiment control/TrialHandler.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Demo of TrialHandler
The contents of this file are in the public domain.
"""
from random import random
from psychopy import data
# create your list of stimuli
# NB as of version 1.62 you could simply import an excel spreadsheet with this
# using data.importConditions('someFile.xlsx')
stimList = []
for ori in range(90, 180, 30):
for sf in [0.5, 1.0, 2.0]:
# append a python 'dictionary' to the list
stimList.append({'sf': sf, 'ori': ori})
# organize them with the trial handler
trials = data.TrialHandler(stimList, 10,
extraInfo={'participant': "Nobody", 'session':'001'})
# run the experiment
nDone = 0
for thisTrial in trials: # handler can act like a for loop
# simulate some data
thisReactionTime = random() + float(thisTrial['sf']) / 2.0
thisChoice = round(random())
trials.data.add('RT', thisReactionTime) # add the data to our set
trials.data.add('choice', thisChoice)
nDone += 1 # just for a quick reference
msg = 'trial %i had position %s in the list (sf=%.1f)'
print(msg % (nDone, trials.thisIndex, thisTrial['sf']))
# After the experiment, print a new line
print('\n')
# Write summary data to screen
trials.printAsText(stimOut=['sf', 'ori'],
dataOut=['RT_mean', 'RT_std', 'choice_raw'])
# Write summary data to a text file ...
trials.saveAsText(fileName='testData',
stimOut=['sf', 'ori'],
dataOut=['RT_mean', 'RT_std', 'choice_raw'])
# ... or an xlsx file (which supports sheets)
trials.saveAsExcel(fileName='testData',
sheetName='rawData',
stimOut=['sf', 'ori'],
dataOut=['RT_mean', 'RT_std', 'choice_raw'])
# Save a copy of the whole TrialHandler object, which can be reloaded later to
# re-create the experiment.
trials.saveAsPickle(fileName='testData')
# Wide format is useful for analysis with R or SPSS.
df = trials.saveAsWideText('testDataWide.txt')
| 2,028
|
Python
|
.py
| 49
| 36.183673
| 80
| 0.660387
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,894
|
JND_staircase_exp.py
|
psychopy_psychopy/psychopy/demos/coder/experiment control/JND_staircase_exp.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Measure your JND in orientation using a staircase method
"""
from psychopy import core, visual, gui, data, event
from psychopy.tools.filetools import fromFile, toFile
import time, numpy
try: # try to get a previous parameters file
expInfo = fromFile('lastParams.pickle')
except: # if not there then use a default set
expInfo = {'observer':'jwp', 'refOrientation':0}
dateStr = time.strftime("%b_%d_%H%M", time.localtime()) # add the current time
# present a dialogue to change params
dlg = gui.DlgFromDict(expInfo, title='simple JND Exp', fixed=['date'])
if dlg.OK:
toFile('lastParams.pickle', expInfo) # save params to file for next time
else:
core.quit() # the user hit cancel so exit
# make a text file to save data
fileName = expInfo['observer'] + dateStr
dataFile = open(fileName + '.txt', 'w')
dataFile.write('targetSide oriIncrement correct\n')
# create window and stimuli
globalClock = core.Clock() # to keep track of time
trialClock = core.Clock() # to keep track of time
win = visual.Window([800, 600], allowGUI=False, monitor='testMonitor', units='deg')
foil = visual.GratingStim(win, sf=1, size=4, mask='gauss', ori=expInfo['refOrientation'])
target = visual.GratingStim(win, sf=1, size=4, mask='gauss', ori=expInfo['refOrientation'])
fixation = visual.GratingStim(win, color='black', tex=None, mask='circle', size=0.2)
message1 = visual.TextStim(win, pos=[0, + 3],
text='Hit a key when ready.')
message2 = visual.TextStim(win, pos=[0, -3],
text="Then press left or right to identify the %.1fdegree probe." % expInfo['refOrientation'])
# create the staircase handler
staircase = data.StairHandler(startVal=20.0,
stepType='lin',
stepSizes=[8, 4, 4, 2, 2, 1, 1], # reduce step size every two reversals
minVal=0, maxVal=90,
nUp=1, nDown=3, # will home in on the 80% threshold
nTrials=50)
# display instructions and wait
message1.draw()
message2.draw()
fixation.draw()
win.flip()
# check for a keypress
event.waitKeys()
for thisIncrement in staircase: # will step through the staircase
# set location of stimuli
targetSide = round(numpy.random.random()) * 2 - 1 # +1 = right, -1 = left
foil.setPos([-5 * targetSide, 0])
target.setPos([5 * targetSide, 0]) # in other location
# set orientation of probe
foil.setOri(expInfo['refOrientation'] + thisIncrement)
# draw all stimuli
foil.draw()
target.draw()
fixation.draw()
win.flip()
core.wait(0.5) # wait 500ms (use a loop of x frames for more accurate timing)
# blank screen
fixation.draw()
win.flip()
# get response
thisResp = None
while thisResp is None:
allKeys = event.waitKeys()
for thisKey in allKeys:
if ((thisKey == 'left' and targetSide == -1) or
(thisKey == 'right' and targetSide == 1)):
thisResp = 1 # correct
elif ((thisKey == 'right' and targetSide == -1) or
(thisKey == 'left' and targetSide == 1)):
thisResp = 0 # incorrect
elif thisKey in ['q', 'escape']:
core.quit() # abort experiment
event.clearEvents('mouse') # only really needed for pygame windows
# add the data to the staircase so it can calculate the next level
staircase.addResponse(thisResp)
dataFile.write('%i %.3f %i\n' % (targetSide, thisIncrement, thisResp))
# staircase has ended
dataFile.close()
staircase.saveAsPickle(fileName) # special python data file to save all the info
# give some output to user
print('reversals:')
print(staircase.reversalIntensities)
print('mean of final 6 reversals = %.3f' % numpy.average(staircase.reversalIntensities[-6:]))
win.close()
core.quit()
# The contents of this file are in the public domain.
| 3,827
|
Python
|
.py
| 91
| 37.901099
| 98
| 0.68792
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,895
|
autoDraw_autoLog.py
|
psychopy_psychopy/psychopy/demos/coder/experiment control/autoDraw_autoLog.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
One easy way to handle stimuli that are drawn repeatedly is to
setAutoDraw(True) for that stimulus. It will continue to be drawn until
stim.setAutoDraw(False) is called. By default a logging message of
level EXP will be created when the setAutoDraw is called.
This can be turned off for each call with stim.setAutoDraw(True, autoLog=False)
"""
from psychopy import visual, core
win = visual.Window([800, 800])
# a stim's name is used in log entries
stim1 = visual.GratingStim(win, pos=[-0.5, -0.5], name='stim1')
stim2 = visual.TextStim(win, pos=[0.5, 0.5], text='stim2', name='textStim')
# no need to log the fixation point info, use autoLog=False
fixation = visual.GratingStim(win, mask='gauss', tex=None, size=0.02,
name='fixation', autoLog=False)
fixation.setAutoDraw(True)
stim1.setAutoDraw(True)
stim2.setAutoDraw(True)
# both on
for frameN in range(20): # run 20 frames like this
win.flip()
stim2.setAutoDraw(False)
# will draw only stim1 (and fixation)
for frameN in range(20): # run 20 frames like this
win.flip()
stim1.setAutoDraw(False)
stim2.setAutoDraw(True)
# will draw only stim2 (and fixation)
for frameN in range(20): # run 20 frames like this
win.flip()
for stim in [stim1, stim2, fixation]:
stim.setAutoDraw(False)
win.flip() # will cause the 'off' log messages to be sent
win.close()
core.quit()
# The contents of this file are in the public domain.
| 1,456
|
Python
|
.py
| 38
| 36.473684
| 79
| 0.748222
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,896
|
runtimeInfo.py
|
psychopy_psychopy/psychopy/demos/coder/experiment control/runtimeInfo.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Demo of some ways to use class psychopy.info.RunTimeInfo()
to obtain current system and other data at run-time.
"""
from psychopy import visual, logging, core
import psychopy.info
# author and version are used in the demo, in the way you might in your experiment.
# They are expected to be at the top of the script that calls RunTimeInfo()),
# with a string literal assigned to them (no variables).
# double-quotes will be silently removed, single quotes will be left, eg, O'Connor
__author__ = """Jeremy "R." Gray"""
__version__ = "v1.0.a"
# When creating an experiment, first define your window (& monitor):
win = visual.Window(fullscr=False, size=[200, 200], monitor='testMonitor')
win.recordFrameIntervals = True
logging.console.setLevel(logging.DEBUG)
# Then gather run-time info. All parameters are optional:
runInfo = psychopy.info.RunTimeInfo(
# if you specify author and version here, it overrides the automatic detection of __author__ and __version__ in your script
# author=' < your name goes here, plus whatever you like, e.g., your lab or contact info > ',
# version=" < your experiment version info > ",
win=win, # # a psychopy.visual.Window() instance; None = default temp window used; False = no win, no win.flips()
refreshTest='grating', # # None, True, or 'grating' (eye-candy to avoid a blank screen)
verbose=True, # # True means report on everything
userProcsDetailed=True, # # if verbose and userProcsDetailed, return (command, process-ID) of the user's processes
)
win.close()
print("""
System and other run-time details are now saved in "runInfo", a dict-like object. You have to decide
what to do with it.
"print(runInfo)" will give you the same as "print(str(runInfo))". This format is intended to be useful
for writing to a data file in a human readable form:""")
print(runInfo)
print("If that's more detail than you want, try: runInfo = info.RunTimeInfo(..., verbose=False, ...).")
# To get the same info in python syntax, use "print(repr(info))".
# You could write this format into a data file, and it's fairly readable.
# And because its python syntax you could later simply
# import your data file into python to reconstruct the dict.
print("\nYou can extract single items from info, using keys, e.g.:")
print(" psychopyVersion = %s" % runInfo['psychopyVersion'])
if "windowRefreshTimeAvg_ms" in runInfo:
print("or from the test of the screen refresh rate:")
print(" %.2f ms = average refresh time" % runInfo["windowRefreshTimeAvg_ms"])
print(" %.3f ms = standard deviation" % runInfo["windowRefreshTimeSD_ms"])
# Once you have run-time info, you can fine-tune things with the values, prior to running your experiment.
refreshSDwarningLevel_ms = 0.20 # ms
if runInfo["windowRefreshTimeSD_ms"] > refreshSDwarningLevel_ms:
print("\nThe variability of the refresh rate is sort of high (SD > %.2f ms)." % (refreshSDwarningLevel_ms))
# and here you could prompt the user with suggestions, possibly based on other info:
if runInfo["windowIsFullScr"]:
print("Your window is full-screen, which is good for timing.")
print('Possible issues: internet / wireless? bluetooth? recent startup (not finished)?')
if len(runInfo['systemUserProcFlagged']):
print('other programs running? (command, process-ID):' + str(runInfo['systemUserProcFlagged']))
else:
print("""Try defining the window as full-screen (it's not currently), i.e. at the top of the demo change to:
win = visual.Window((800, 600), fullscr=True, ...
and re-run the demo.""")
print("""
(NB: The visual is not the demo! Scroll up to see the text output.)""")
win.close()
core.quit()
# The contents of this file are in the public domain.
| 3,881
|
Python
|
.py
| 65
| 55.6
| 131
| 0.708574
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,897
|
experimentHandler.py
|
psychopy_psychopy/psychopy/demos/coder/experiment control/experimentHandler.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Demo of class data.ExperimentHandler
"""
from psychopy import data, logging
from numpy import random
logging.console.setLevel(logging.DEBUG)
exp = data.ExperimentHandler(name='testExp',
version='0.1',
extraInfo={'participant':'jwp', 'ori':45},
runtimeInfo=None,
originPath=None,
savePickle=True,
saveWideText=True,
dataFileName='testExp')
# a first loop (like training?)
conds = data.createFactorialTrialList(
{'faceExpression':['happy', 'sad'], 'presTime':[0.2, 0.3]})
training = data.TrialHandler(trialList=conds, nReps=3, name='train',
method='random',
seed=100) # this will set the global seed - for the whole exp
exp.addLoop(training)
# run those trials
for trial in training:
training.addData('training.rt', random.random() * 0.5 + 0.5)
if random.random() > 0.5:
training.addData('training.key', 'left')
else:
training.addData('training.key', 'right')
exp.nextEntry()
# then run 3 repeats of a staircase
outerLoop = data.TrialHandler(trialList=[], nReps=3, name='stairBlock',
method='random')
exp.addLoop(outerLoop)
for thisRep in outerLoop: # the outer loop doesn't save any data
staircase = data.StairHandler(startVal=10, name='staircase', nTrials=5)
exp.addLoop(staircase)
for thisTrial in staircase:
id=random.random()
if random.random() > 0.5:
staircase.addData(1)
else:
staircase.addData(0)
exp.addData('id', id)
exp.nextEntry()
for e in exp.entries:
print(e)
print("Done. 'exp' experimentHandler will now (end of script) save data to testExp.csv")
print(" and also to testExp.psydat, which is a pickled version of `exp`")
# The contents of this file are in the public domain.
| 1,926
|
Python
|
.py
| 51
| 31.176471
| 88
| 0.648475
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,898
|
TrialHandler2.py
|
psychopy_psychopy/psychopy/demos/coder/experiment control/TrialHandler2.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Demo of TrialHandler
"""
from random import random
from psychopy import data
# create your list of stimuli
# NB as of version 1.62 you could simply import an excel spreadsheet with this
# using data.importConditions('someFile.xlsx')
stimList = []
for ori in range(90, 180, 30):
for sf in [0.5, 1.0, 2.0]:
# append a python 'dictionary' to the list
stimList.append({'sf':sf, 'ori':ori})
# organize them with the trial handler
trials = data.TrialHandler2(stimList, 10,
extraInfo= {'participant':"Nobody", 'session':'001'})
# run the experiment
nDone = 0
for thisTrial in trials: # handler can act like a for loop
# simulate some data
thisReactionTime = random() + float(thisTrial['sf']) / 2.0
thisChoice = round(random())
trials.addData('RT', thisReactionTime) # add the data to our set
trials.addData('choice', thisChoice)
nDone += 1 # just for a quick reference
msg = 'trial %i had position %s in the list (sf=%.1f)'
print(msg % (nDone, trials.thisIndex, thisTrial['sf']))
# after the experiment
print('\n')
trials.saveAsPickle(fileName = 'testData') # this saves a copy of the whole object
df = trials.saveAsWideText("testDataWide.csv") # wide is useful for analysis with R or SPSS. Also returns dataframe df
# The contents of this file are in the public domain.
| 1,407
|
Python
|
.py
| 34
| 37.794118
| 119
| 0.696703
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,899
|
keyNameFinder.py
|
psychopy_psychopy/psychopy/demos/coder/input/keyNameFinder.py
|
from psychopy import visual
from psychopy.hardware import keyboard
# Make window
win = visual.Window(units="height")
# Make instructions textbox
instr = visual.TextBox2(win,
text="Press any key...",
font="Open Sans", letterHeight=0.1,
pos=(0, 0.2))
# Make key name textbox
output = visual.TextBox2(win,
text="No key pressed yet",
font="Open Sans", letterHeight=0.1,
pos=(0, -0.2))
# Make keyboard object. Optionally add backend kwarg, using 'iohub', 'ptb', 'event', or ''.
# If using '', best available backend will be selected.
#kb = keyboard.Keyboard(backend='iohub')
kb = keyboard.Keyboard()
print("KB backend: ", kb.getBackend())
# Listen for keypresses until escape is pressed
keys = kb.getKeys()
while 'escape' not in keys:
# Draw stimuli
instr.draw()
output.draw()
win.flip()
# Check keypresses
keys = kb.getKeys()
if keys:
# If a key was pressed, display it
output.text = f"That key was `{keys[-1].name}`. Press another key."
for k in keys:
print(k.name, k.code, k.tDown, k.rt, k.duration)
# End the demo
win.close()
| 1,117
|
Python
|
.py
| 35
| 28.285714
| 91
| 0.67718
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|