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,700
parser.py
psychopy_psychopy/psychopy/iohub/devices/eyetracker/filters/parser.py
# Part of the psychopy.iohub library. # Copyright (C) 2012-2016 iSolver Software Solutions # Distributed under the terms of the GNU General Public License (GPL). """ ioHub Eye Tracker Online Sample Event Parser WORK IN PROGRESS - VERY EXPERIMENTAL Copyright (C) 2012-2014 iSolver Software Solutions Distributed under the terms of the GNU General Public License (GPL version 3 or any later version). .. moduleauthor:: Sol Simpson <sol@isolver-software.com> .. fileauthor:: Sol Simpson <sol@isolver-software.com> NOTES: * The parser is designed to work with monocular and binocular eye data, but only binocular input samples have been tested so far. * If binocular input samples are being used, they are converted to monocular samples for parsing. If both left and right eye position data is available for a sample, the positions are averaged together. If only one of the two eyes has valid data, then that eye data is used for the sample. So the only case where a sample will be tagged as missing data is when both eyes do not have valid eye position / pupil size data. POSITION_FILTER and VELOCITY_FILTER can be set to one of the following event field filter types. Example values for any input arguments are given. The filter is selected by giving the filter class name followed by a dictionary of values to use for the filter. Valid filter options depend on the filter selected. eventfilters.MovingWindowFilter -------------------------------- This is a standard averaging filter. Any samples within the window buffer are simply averaged together to give the filtered value for a given sample. Parameters: * length: The size of the moving window in samples. Minimum of 2 required. * knot_pos: The index within the moving window that should be used to extract a sample from and apply the current window filtered value. Example: POSITION_FILTER = eventfilters.MovingWindowFilter, {length: 3, knot_pos:'center'} Applies the MovingWindowFilter to x and y gaze data fields of eye samples. The window size is three, and each sample position is filtered using data from the previous and next samples as well as itself. eventfilters.PassThroughFilter --------------------------------- A NULL filter. In other words, the filter does not do any filtering. Parameters: None Example: VELOCITY_FILTER = eventfilters.PassThroughFilter, {} Velocity data is calculated from (filtered) sample positions, but is not filtered itself. eventfilters.MedianFilter ----------------------------- MedianFilter applies the median value of the filter window to the knot_pos window sample. Parameters: * length: The size of the moving window in samples. Minimum of 3 is required and the length must be odd. * knot_pos: The index within the moving window that should be used to extract a sample from and apply the current window filtered value. Example: POSITION_FILTER = eventfilters.MedianFilter, {length: 3, knot_pos: 0} Sample position fields are filtered by the median value of three samples, those being the current sample and the two following samples (so the current sample is at index 0. eventfilters.WeightedAverageFilter ----------------------------------- WeightedAverageFilter is similar to the standard MovingWindowFilter field filter, however each element in the window is assigned a weighting factor that is used during averaging. Parameters: * weights: A list of weights to be applied to the window values. The window length is == len(weights). The weight values are all normalized to sum to 1 before use in the filter. For example, a weight list of (25,50,25) will be converted to (0.25,0.50,0.25) for use in the filter, with window value index i being multiplied by weith list index i. * knot_pos: The index within the moving window that should be used to extract a sample from and apply the current window filtered value. Example: VELOCITY_FILTER = eventfilters.WeightedAverageFilter, {weights: (25,50,25), knot_pos: 1} A weighted average window filter will be applied to x and y velocity fields. The length of the window is 3 samples, and the filtered sample index retrieved is 1, the same as using 'center' in this case. The filtered sample index will count toward 1/2 the weighted average, with the previous and next samples contributing 1/4 of the weighted average each. eventfilters.StampFilter -------------------------- A variant of the filter proposed by Dr. David Stampe (1993 ???). A window of length 3 is used, with the knot_pos centered, or at index 1. If the current 3 values in the window list are monotonic, then the sample is not filtered. If the values are non-monotonic, then v[1] = (v[0]+v[2])/2.0 Parameters: * levels: The number of iterations (recursive) that should be applied to the windowed data. Minimum value is 1. The number of levels equals the number of samples the filtered sample will be delayed compared to the non filtered sample time. Example: POSITION_FILTER = eventfilters.StampFilter, {level: 1} Data is filtered once, similar to what a 'normal' filter level would be in the eyelink<tm> system. Level = 2 would be similar to the 'extra' filter level setting of eyelink<tm>. """ import numpy as np from ....constants import EventConstants from ....errors import print2err from ... import DeviceEvent, eventfilters from collections import OrderedDict from ....util.visualangle import VisualAngleCalc MONOCULAR_EYE_SAMPLE = EventConstants.MONOCULAR_EYE_SAMPLE BINOCULAR_EYE_SAMPLE = EventConstants.BINOCULAR_EYE_SAMPLE FIXATION_START = EventConstants.FIXATION_START FIXATION_END = EventConstants.FIXATION_END SACCADE_START = EventConstants.SACCADE_START SACCADE_END = EventConstants.SACCADE_END BLINK_START = EventConstants.BLINK_START BLINK_END = EventConstants.BLINK_END NO_EYE = 0 LEFT_EYE = 1 RIGHT_EYE = 2 BOTH_EYE = 3 class EyeTrackerEventParser(eventfilters.DeviceEventFilter): def __init__(self, **kwargs): eventfilters.DeviceEventFilter.__init__(self, **kwargs) self.sample_type = None self.io_sample_class = None self.io_event_ix = None self.last_valid_sample = None self.last_sample = None self.invalid_samples_run = [] self._last_parser_sample = None self.open_parser_events = OrderedDict() self.convertEvent = None self.isValidSample = None self.vel_thresh_history_dur = kwargs.get( 'adaptive_vel_thresh_history', 3.0) position_filter = kwargs.get('position_filter') velocity_filter = kwargs.get('velocity_filter') display_device = kwargs.get('display_device') sampling_rate = kwargs.get('sampling_rate') if position_filter: pos_filter_class_name = position_filter.get( 'name', 'PassThroughFilter') pos_filter_class = getattr(eventfilters, pos_filter_class_name) del position_filter['name'] pos_filter_kwargs = position_filter else: pos_filter_class, pos_filter_kwargs = eventfilters.PassThroughFilter, {} if velocity_filter: vel_filter_class_name = position_filter.get( 'name', 'PassThroughFilter') vel_filter_class = getattr(eventfilters, vel_filter_class_name) del velocity_filter['name'] vel_filter_kwargs = velocity_filter else: vel_filter_class, vel_filter_kwargs = eventfilters.PassThroughFilter, {} self.adaptive_x_vthresh_buffer = np.zeros( self.vel_thresh_history_dur * sampling_rate) self.x_vthresh_buffer_index = 0 self.adaptive_y_vthresh_buffer = np.zeros( self.vel_thresh_history_dur * sampling_rate) self.y_vthresh_buffer_index = 0 pos_filter_kwargs['event_type'] = MONOCULAR_EYE_SAMPLE pos_filter_kwargs['inplace'] = True pos_filter_kwargs['event_field_name'] = 'angle_x' self.x_position_filter = pos_filter_class(**pos_filter_kwargs) pos_filter_kwargs['event_field_name'] = 'angle_y' self.y_position_filter = pos_filter_class(**pos_filter_kwargs) vel_filter_kwargs['event_type'] = MONOCULAR_EYE_SAMPLE vel_filter_kwargs['inplace'] = True vel_filter_kwargs['event_field_name'] = 'velocity_x' self.x_velocity_filter = vel_filter_class(**vel_filter_kwargs) vel_filter_kwargs['event_field_name'] = 'velocity_y' self.y_velocity_filter = vel_filter_class(**vel_filter_kwargs) vel_filter_kwargs['event_field_name'] = 'velocity_xy' self.xy_velocity_filter = vel_filter_class(**vel_filter_kwargs) ### mm_size = display_device.get('mm_size') if mm_size: mm_size = mm_size['width'], mm_size['height'], pixel_res = display_device.get('pixel_res') eye_distance = display_device.get('eye_distance') self.visual_angle_calc = VisualAngleCalc(mm_size, pixel_res, eye_distance) self.pix2deg = self.visual_angle_calc.pix2deg @property def filter_id(self): return 23 @property def input_event_types(self): event_type_and_filter_ids = dict() event_type_and_filter_ids[BINOCULAR_EYE_SAMPLE] = [0, ] event_type_and_filter_ids[MONOCULAR_EYE_SAMPLE] = [0, ] return event_type_and_filter_ids def process(self): """""" samples_for_processing = [] for in_evt in self.getInputEvents(): if self.sample_type is None: self.initializeForSampleType(in_evt) # If event is binocular, convert to monocular. # Regardless of type, convert pix to angle positions and calculate # unfiltered velocity data. current_mono_evt = self.convertEvent(self.last_sample, in_evt) is_valid = self.isValidSample(current_mono_evt) if is_valid: # If sample is valid (no missing pos data), first # check for a previous missing data run and handle. if self.invalid_samples_run: if self.last_valid_sample: samples_for_processing.extend( self.interpolateMissingData(current_mono_evt)) self._addVelocity( samples_for_processing[-1], current_mono_evt) # Discard all invalid samples that occurred prior # to the first valid sample. del self.invalid_samples_run[:] # Then add current event to field filters. If a filtered event # is returned, add it to the to be processed sample list. filtered_event = self.addToFieldFilters(current_mono_evt) if filtered_event: filtered_event, _junk = filtered_event x_vel_thresh, y_vel_thresh = self.addVelocityToAdaptiveThreshold( filtered_event) filtered_event[self.io_event_ix('raw_x')] = x_vel_thresh filtered_event[self.io_event_ix('raw_y')] = y_vel_thresh samples_for_processing.append(filtered_event) self.last_valid_sample = current_mono_evt else: self.invalid_samples_run.append(current_mono_evt) self.addOutputEvent(current_mono_evt) self.last_sample = current_mono_evt # Add any new filtered samples to be output. # Also create parsed events with no heuristics being used # at this point. for s in samples_for_processing: self.parseEvent(s) if self.isValidSample(s): self.addOutputEvent(s) self.clearInputEvents() def parseEvent(self, sample): if self._last_parser_sample: last_sec = self.getSampleEventCategory(self._last_parser_sample) current_sec = self.getSampleEventCategory(sample) if last_sec and last_sec != current_sec: start_event, end_event = self.createEyeEvents( last_sec, current_sec, self._last_parser_sample, sample) if start_event: self.addOutputEvent(start_event) if end_event: self.addOutputEvent(end_event) else: self.open_parser_events.setdefault( current_sec + '_SAMPLES', []).append(sample) self._last_parser_sample = sample def getSampleEventCategory(self, sample): if self.isValidSample(sample): x_velocity_threshold = sample[self.io_event_ix('raw_x')] y_velocity_threshold = sample[self.io_event_ix('raw_y')] if x_velocity_threshold == np.NaN: return None sample_vx = sample[self.io_event_ix('velocity_x')] sample_vy = sample[self.io_event_ix('velocity_y')] if sample_vx >= x_velocity_threshold or sample_vy >= y_velocity_threshold: return 'SAC' return 'FIX' return 'MIS' def createEyeEvents( self, last_sample_category, current_sample_category, last_sample, current_sample): start_event = None end_event = None if last_sample_category == 'MIS': # Create end blink event existing_start_event = self.open_parser_events.get('MIS') evt_samples = self.open_parser_events.get('MIS_SAMPLES') if evt_samples: del self.open_parser_events['MIS_SAMPLES'] if existing_start_event: end_event = self.createBlinkEndEventArray( last_sample, existing_start_event, evt_samples) del self.open_parser_events['MIS'] else: # print2err("PARSER Warning: Blink Start Event not found; Blink End event being dropped: ", end_event) pass elif last_sample_category == 'FIX': # Create end fix event existing_start_event = self.open_parser_events.get('FIX') evt_samples = self.open_parser_events.get('FIX_SAMPLES') if evt_samples: del self.open_parser_events['FIX_SAMPLES'] if existing_start_event: end_event = self.createFixationEndEventArray( last_sample, existing_start_event, evt_samples) del self.open_parser_events['FIX'] else: # print2err("PARSER Warning: Fixation Start Event not found; Fixation End event being dropped: ", end_event) pass elif last_sample_category == 'SAC': # Create end sac event existing_start_event = self.open_parser_events.get('SAC') evt_samples = self.open_parser_events.get('SAC_SAMPLES') if evt_samples: del self.open_parser_events['SAC_SAMPLES'] if existing_start_event: end_event = self.createSaccadeEndEventArray( last_sample, existing_start_event, evt_samples) del self.open_parser_events['SAC'] else: # print2err("PARSER Warning: Saccade Start Event not found; Saccade End event being dropped: ", end_event) pass if current_sample_category == 'MIS': # Create start blink event start_event = self.createBlinkStartEventArray(current_sample) self.open_parser_events['MIS_SAMPLES'] = [current_sample, ] existing_start_event = self.open_parser_events.get('MIS') if existing_start_event: print2err( 'PARSER ERROR: Blink Start Event already Open and is being dropped: ', existing_start_event) self.open_parser_events['MIS'] = current_sample elif current_sample_category == 'FIX': # Create start fix event start_event = self.createFixationStartEventArray(current_sample) self.open_parser_events['FIX_SAMPLES'] = [current_sample, ] existing_start_event = self.open_parser_events.get('FIX') if existing_start_event: print2err( 'PARSER ERROR: Fixation Start Event already Open and is being dropped: ', existing_start_event) self.open_parser_events['FIX'] = current_sample elif current_sample_category == 'SAC': # Create start sac event start_event = self.createSaccadeStartEventArray(current_sample) self.open_parser_events['SAC_SAMPLES'] = [current_sample, ] existing_start_event = self.open_parser_events.get('SAC') if existing_start_event: print2err( 'PARSER ERROR: Saccade Start Event already Open and is being dropped: ', existing_start_event) self.open_parser_events['SAC'] = current_sample return end_event, start_event def addVelocityToAdaptiveThreshold(self, sample): velocity_x = sample[self.io_event_ix('velocity_x')] velocity_y = sample[self.io_event_ix('velocity_y')] velocity_buffers = [ self.adaptive_x_vthresh_buffer, self.adaptive_y_vthresh_buffer] velocity_buffer_indexs = [ self.x_vthresh_buffer_index, self.y_vthresh_buffer_index] vthresh_values = [] for v, velocity in enumerate([velocity_x, velocity_y]): current_velocity_buffer = velocity_buffers[v] current_vbuffer_index = velocity_buffer_indexs[v] blen = len(current_velocity_buffer) if velocity > 0.0: i = current_vbuffer_index % blen current_velocity_buffer[i] = velocity full = current_vbuffer_index >= blen if v == 0: self.x_vthresh_buffer_index += 1 else: self.y_vthresh_buffer_index += 1 if full: PT = current_velocity_buffer.min() + current_velocity_buffer.std() * 3.0 velocity_below_thresh = current_velocity_buffer[ current_velocity_buffer < PT] PTd = 2.0 pt_list = [PT, ] while PTd >= 1.0: if len(pt_list) > 0: PT = velocity_below_thresh.mean() + 3.0 * velocity_below_thresh.std() velocity_below_thresh = current_velocity_buffer[ current_velocity_buffer < PT] PTd = np.abs(PT - pt_list[-1]) pt_list.append(PT) vthresh_values.append(PT) if len(vthresh_values) != v + 1: vthresh_values.append(np.NaN) return vthresh_values def reset(self): eventfilters.DeviceEventFilter.reset(self) self._last_parser_sample = None self.last_valid_sample = None self.last_sample = None self.invalid_samples_run = [] self.open_parser_events.clear() self.x_position_filter.clear() self.y_position_filter.clear() self.x_velocity_filter.clear() self.y_velocity_filter.clear() self.xy_velocity_filter.clear() self.x_vthresh_buffer_index = 0 self.y_vthresh_buffer_index = 0 def initializeForSampleType(self, in_evt): # in_evt[DeviceEvent.EVENT_TYPE_ID_INDEX] self.sample_type = MONOCULAR_EYE_SAMPLE #print2err("self.sample_type: ",self.sample_type,", ",EventConstants.getName(self.sample_type)) self.io_sample_class = EventConstants.getClass(self.sample_type) self.io_event_fields = self.io_sample_class.CLASS_ATTRIBUTE_NAMES #print2err("self.io_sample_class: ",self.io_sample_class,", ",len(self.io_event_fields),"\n>>",self.io_event_fields) self.io_event_ix = self.io_sample_class.CLASS_ATTRIBUTE_NAMES.index if in_evt[DeviceEvent.EVENT_TYPE_ID_INDEX] == BINOCULAR_EYE_SAMPLE: self.convertEvent = self._convertToMonoAveraged self.isValidSample = lambda x: x[self.io_event_ix('status')] != 22 else: self.convertEvent = self._convertMonoFields self.isValidSample = lambda x: x[self.io_event_ix('status')] == 0 def interpolateMissingData(self, current_sample): samples_for_processing = [] invalid_sample_count = len(self.invalid_samples_run) gx_ix = self.io_event_ix('angle_x') gy_ix = self.io_event_ix('angle_y') ps_ix = self.io_event_ix('pupil_measure1') starting_gx = self.last_valid_sample[gx_ix] starting_gy = self.last_valid_sample[gy_ix] starting_ps = self.last_valid_sample[ps_ix] ending_gx = current_sample[gx_ix] ending_gy = current_sample[gy_ix] ending_ps = current_sample[ps_ix] x_interp = np.linspace(starting_gx, ending_gx, num=invalid_sample_count + 2)[1:-1] y_interp = np.linspace(starting_gy, ending_gy, num=invalid_sample_count + 2)[1:-1] p_interp = np.linspace(starting_ps, ending_ps, num=invalid_sample_count + 2)[1:-1] # print2err('>>>>') # print2err('invalid_sample_count: ', invalid_sample_count) # print2err('starting_gx, ending_gx: ', starting_gx,', ',ending_gx) # print2err('x_interp: ', x_interp) # print2err('starting_gy, ending_gy: ', starting_gx,', ',ending_gx) # print2err('y_interp: ', y_interp) # print2err('<<<<') prev_samp = self.last_valid_sample # interpolate missing sample values, adding to pos and vel filters for ix, curr_samp in enumerate(self.invalid_samples_run): curr_samp[gx_ix] = x_interp[ix] curr_samp[gy_ix] = y_interp[ix] curr_samp[ps_ix] = p_interp[ix] self._addVelocity(prev_samp, curr_samp) filtered_event = self.addToFieldFilters(curr_samp) if filtered_event: filtered_event, _junk = filtered_event samples_for_processing.append(filtered_event) prev_samp = curr_samp return samples_for_processing def addToFieldFilters(self, sample): self.x_position_filter.add(sample) self.y_position_filter.add(sample) self.x_velocity_filter.add(sample) self.y_velocity_filter.add(sample) return self.xy_velocity_filter.add(sample) def _convertPosToAngles(self, mono_event): gx_ix = self.io_event_ix('gaze_x') gx_iy = self.io_event_ix('gaze_y') mono_event[ self.io_event_ix('angle_x')], mono_event[ self.io_event_ix('angle_y')] = self.pix2deg( mono_event[gx_ix], mono_event[gx_iy]) def _addVelocity(self, prev_event, current_event): io_ix = self.io_event_ix dx = np.abs( current_event[ io_ix('angle_x')] - prev_event[ io_ix('angle_x')]) dy = np.abs( current_event[ io_ix('angle_y')] - prev_event[ io_ix('angle_y')]) dt = current_event[io_ix('time')] - prev_event[io_ix('time')] current_event[io_ix('velocity_x')] = dx / dt current_event[io_ix('velocity_y')] = dy / dt current_event[io_ix('velocity_xy')] = np.hypot(dx / dt, dy / dt) def _convertMonoFields(self, prev_event, current_event): if self.isValidSample(current_event): self._convertPosToAngles(self, current_event) if prev_event: self._addVelocity(prev_event, current_event) def _convertToMonoAveraged(self, prev_event, current_event): mono_evt = [] binoc_field_names = EventConstants.getClass( EventConstants.BINOCULAR_EYE_SAMPLE).CLASS_ATTRIBUTE_NAMES #print2err("binoc_field_names: ",len(binoc_field_names),"\n",binoc_field_names) status = current_event[binoc_field_names.index('status')] for field in self.io_event_fields: if field in binoc_field_names: mono_evt.append(current_event[binoc_field_names.index(field)]) elif field == 'eye': mono_evt.append(LEFT_EYE) elif field.endswith('_type'): mono_evt.append( int(current_event[binoc_field_names.index('left_%s' % (field))])) else: #print2err("binoc status: ",status) if status == 0: lfv = float( current_event[ binoc_field_names.index( 'left_%s' % (field))]) rfv = float( current_event[ binoc_field_names.index( 'right_%s' % (field))]) mono_evt.append((lfv + rfv) / 2.0) elif status == 2: mono_evt.append( float( current_event[ binoc_field_names.index( 'left_%s' % (field))])) elif status == 20: mono_evt.append( float( current_event[ binoc_field_names.index( 'right_%s' % (field))])) elif status == 22: # both eyes have missing data, so use data from left eye # (does not really matter) mono_evt.append( float( current_event[ binoc_field_names.index( 'left_%s' % (field))])) else: ValueError('Unknown Sample Status: %d' % (status)) mono_evt[self.io_event_fields.index( 'type')] = EventConstants.MONOCULAR_EYE_SAMPLE if self.isValidSample(mono_evt): self._convertPosToAngles(mono_evt) if prev_event: self._addVelocity(prev_event, mono_evt) return mono_evt def _binocSampleValidEyeData(self, sample): evt_status = sample[self.io_event_ix('status')] if evt_status == 0: # both eyes are valid return BOTH_EYE elif evt_status == 20: # right eye data only return RIGHT_EYE elif evt_status == 2: # left eye data only return LEFT_EYE elif evt_status == 22: # both eye data missing return NO_EYE def createFixationStartEventArray(self, sample): return [sample[self.io_event_ix('experiment_id')], sample[self.io_event_ix('session_id')], sample[self.io_event_ix('device_id')], sample[self.io_event_ix('event_id')], EventConstants.FIXATION_START, sample[self.io_event_ix('device_time')], sample[self.io_event_ix('logged_time')], sample[self.io_event_ix('time')], 0.0, 0.0, 0, sample[self.io_event_ix('eye')], sample[self.io_event_ix('gaze_x')], sample[self.io_event_ix('gaze_y')], 0.0, sample[self.io_event_ix('angle_x')], sample[self.io_event_ix('angle_y')], # used to hold online x velocity threshold calculated for # sample sample[self.io_event_ix('raw_x')], # used to hold online y velocity threshold calculated for # sample sample[self.io_event_ix('raw_y')], sample[self.io_event_ix('pupil_measure1')], sample[self.io_event_ix('pupil_measure1_type')], 0.0, 0, 0.0, 0.0, sample[self.io_event_ix('velocity_x')], sample[self.io_event_ix('velocity_y')], sample[self.io_event_ix('velocity_xy')], sample[self.io_event_ix('status')] ] def createFixationEndEventArray( self, sample, existing_start_event, event_samples): evt_sample_array = np.asarray(event_samples) vx = self.io_event_ix('velocity_x') vy = self.io_event_ix('velocity_y') vxy = self.io_event_ix('velocity_xy') gx = self.io_event_ix('gaze_x') gy = self.io_event_ix('gaze_y') return [sample[self.io_event_ix('experiment_id')], sample[self.io_event_ix('session_id')], sample[self.io_event_ix('device_id')], sample[self.io_event_ix('event_id')], EventConstants.FIXATION_END, sample[self.io_event_ix('device_time')], sample[self.io_event_ix('logged_time')], sample[self.io_event_ix('time')], 0.0, 0.0, 0, sample[self.io_event_ix('eye')], sample[self.io_event_ix( 'time')] - existing_start_event[self.io_event_ix('time')], existing_start_event[gx], existing_start_event[gy], 0.0, existing_start_event[self.io_event_ix('angle_x')], existing_start_event[self.io_event_ix('angle_y')], # used to hold online x velocity threshold calculated for # sample existing_start_event[self.io_event_ix('raw_x')], # used to hold online y velocity threshold calculated for # sample existing_start_event[self.io_event_ix('raw_y')], existing_start_event[self.io_event_ix('pupil_measure1')], existing_start_event[self.io_event_ix('pupil_measure1_type')], 0.0, 0, 0.0, 0.0, existing_start_event[vx], existing_start_event[vy], existing_start_event[vxy], sample[gx], sample[gy], 0.0, sample[self.io_event_ix('angle_x')], sample[self.io_event_ix('angle_y')], # used to hold online x velocity threshold calculated for # sample sample[self.io_event_ix('raw_x')], # used to hold online y velocity threshold calculated for # sample sample[self.io_event_ix('raw_y')], sample[self.io_event_ix('pupil_measure1')], sample[self.io_event_ix('pupil_measure1_type')], 0.0, 0, 0.0, 0.0, sample[vx], sample[vy], sample[vxy], evt_sample_array[:, gx].mean(), # average_gaze_x, evt_sample_array[:, gy].mean(), # average_gaze_y, 0.0, 0.0, 0.0, 0.0, 0.0, evt_sample_array[ :, self.io_event_ix('pupil_measure1')].mean(), # average_pupil_measure1, # average_pupil_measure1_type, sample[self.io_event_ix('pupil_measure1_type')], 0.0, 0.0, 0.0, 0.0, evt_sample_array[:, vx].mean(), # average_velocity_x, evt_sample_array[:, vy].mean(), # average_velocity_y, evt_sample_array[:, vxy].mean(), # average_velocity_xy, evt_sample_array[:, vx].max(), # peak_velocity_x, evt_sample_array[:, vy].max(), # peak_velocity_y, evt_sample_array[:, vxy].max(), # peak_velocity_xy, sample[self.io_event_ix('status')] ] ################### Saccade Event Types ########################## def createSaccadeStartEventArray(self, sample): return [sample[self.io_event_ix('experiment_id')], sample[self.io_event_ix('session_id')], sample[self.io_event_ix('device_id')], sample[self.io_event_ix('event_id')], EventConstants.SACCADE_START, sample[self.io_event_ix('device_time')], sample[self.io_event_ix('logged_time')], sample[self.io_event_ix('time')], 0.0, 0.0, 0, sample[self.io_event_ix('eye')], sample[self.io_event_ix('gaze_x')], sample[self.io_event_ix('gaze_y')], 0.0, sample[self.io_event_ix('angle_x')], sample[self.io_event_ix('angle_y')], # used to hold online x velocity threshold calculated for # sample sample[self.io_event_ix('raw_x')], # used to hold online y velocity threshold calculated for # sample sample[self.io_event_ix('raw_y')], sample[self.io_event_ix('pupil_measure1')], sample[self.io_event_ix('pupil_measure1_type')], 0.0, 0, 0.0, 0.0, sample[self.io_event_ix('velocity_x')], sample[self.io_event_ix('velocity_y')], sample[self.io_event_ix('velocity_xy')], sample[self.io_event_ix('status')] ] def createSaccadeEndEventArray( self, sample, existing_start_event, event_samples): evt_sample_array = np.asarray(event_samples) gx = self.io_event_ix('gaze_x') gy = self.io_event_ix('gaze_y') x1 = existing_start_event[gx] y1 = existing_start_event[gy] x2 = sample[gx] y2 = sample[gy] xDiff = x2 - x1 yDiff = y2 - y1 vx = self.io_event_ix('velocity_x') vy = self.io_event_ix('velocity_y') vxy = self.io_event_ix('velocity_xy') return [sample[self.io_event_ix('experiment_id')], sample[self.io_event_ix('session_id')], sample[self.io_event_ix('device_id')], sample[self.io_event_ix('event_id')], EventConstants.SACCADE_END, sample[self.io_event_ix('device_time')], sample[self.io_event_ix('logged_time')], sample[self.io_event_ix('time')], 0.0, 0.0, 0, sample[self.io_event_ix('eye')], sample[self.io_event_ix( 'time')] - existing_start_event[self.io_event_ix('time')], xDiff, yDiff, np.rad2deg(np.arctan(yDiff, xDiff)), existing_start_event[gx], existing_start_event[gy], 0.0, existing_start_event[self.io_event_ix('angle_x')], existing_start_event[self.io_event_ix('angle_y')], # used to hold online x velocity threshold calculated for # sample existing_start_event[self.io_event_ix('raw_x')], # used to hold online y velocity threshold calculated for # sample existing_start_event[self.io_event_ix('raw_y')], existing_start_event[self.io_event_ix('pupil_measure1')], existing_start_event[self.io_event_ix('pupil_measure1_type')], 0.0, 0, 0.0, 0.0, existing_start_event[vx], existing_start_event[vy], existing_start_event[vxy], sample[gx], sample[gy], 0.0, sample[self.io_event_ix('angle_x')], sample[self.io_event_ix('angle_y')], # used to hold online x velocity threshold calculated for # sample sample[self.io_event_ix('raw_x')], # used to hold online y velocity threshold calculated for # sample sample[self.io_event_ix('raw_y')], sample[self.io_event_ix('pupil_measure1')], sample[self.io_event_ix('pupil_measure1_type')], 0.0, 0, 0.0, 0.0, sample[vx], sample[vy], sample[vxy], evt_sample_array[:, vx].mean(), # average_velocity_x, evt_sample_array[:, vy].mean(), # average_velocity_y, evt_sample_array[:, vxy].mean(), # average_velocity_xy, evt_sample_array[:, vx].max(), # peak_velocity_x, evt_sample_array[:, vy].max(), # peak_velocity_y, evt_sample_array[:, vxy].max(), # peak_velocity_xy, sample[self.io_event_ix('status')] ] ################### Blink Event Types ########################## def createBlinkStartEventArray(self, sample): return [sample[self.io_event_ix('experiment_id')], sample[self.io_event_ix('session_id')], sample[self.io_event_ix('device_id')], sample[self.io_event_ix('event_id')], EventConstants.BLINK_START, sample[self.io_event_ix('device_time')], sample[self.io_event_ix('logged_time')], sample[self.io_event_ix('time')], 0.0, 0.0, 0, sample[self.io_event_ix('eye')], sample[self.io_event_ix('status')] ] def createBlinkEndEventArray( self, sample, existing_start_event, event_samples): return [ sample[ self.io_event_ix('experiment_id')], sample[ self.io_event_ix('session_id')], sample[ self.io_event_ix('device_id')], sample[ self.io_event_ix('event_id')], EventConstants.BLINK_END, sample[ self.io_event_ix('device_time')], sample[ self.io_event_ix('logged_time')], sample[ self.io_event_ix('time')], 0.0, 0.0, 0, sample[ self.io_event_ix('eye')], sample[ self.io_event_ix('time')] - existing_start_event[ self.io_event_ix('time')], sample[ self.io_event_ix('status')]]
39,535
Python
.py
826
34.657385
124
0.563021
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,701
win32.py
psychopy_psychopy/psychopy/iohub/devices/mouse/win32.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). import ctypes from . import MouseDevice from ...constants import EventConstants, MouseConstants from .. import Computer, Device from ..keyboard import Keyboard from ...errors import print2err currentSec = Computer.getTime class Mouse(MouseDevice): """The Mouse class and related events represent a standard computer mouse device and the events a standard mouse can produce. Mouse position data is mapped to the coordinate space defined in the ioHub configuration file for the Display. Examples: A. Print all mouse events received for 5 seconds:: from psychopy.iohub import launchHubServer from psychopy.core import getTime # Start the ioHub process. 'io' can now be used during the # experiment to access iohub devices and read iohub device events. io = launchHubServer() mouse = io.devices.mouse # Check for and print any Mouse events received for 5 seconds. stime = getTime() while getTime()-stime < 5.0: for e in mouse.getEvents(): print(e) # Stop the ioHub Server io.quit() B. Print current mouse position for 5 seconds:: from psychopy.iohub import launchHubServer from psychopy.core import getTime # Start the ioHub process. 'io' can now be used during the # experiment to access iohub devices and read iohub device events. io = launchHubServer() mouse = io.devices.mouse # Check for and print any Mouse events received for 5 seconds. stime = getTime() while getTime()-stime < 5.0: print(mouse.getPosition()) # Stop the ioHub Server io.quit() """ WM_MOUSEFIRST = 0x0200 WM_MOUSEMOVE = 0x0200 WM_LBUTTONDOWN = 0x0201 WM_LBUTTONUP = 0x0202 WM_LBUTTONDBLCLK = 0x0203 WM_RBUTTONDOWN = 0x0204 WM_RBUTTONUP = 0x0205 WM_RBUTTONDBLCLK = 0x0206 WM_MBUTTONDOWN = 0x0207 WM_MBUTTONUP = 0x0208 WM_MBUTTONDBLCLK = 0x0209 WM_MOUSEWHEEL = 0x020A WM_MOUSELAST = 0x020A WH_MOUSE = 7 WH_MOUSE_LL = 14 WH_MAX = 15 _mouse_event_mapper = { WM_MOUSEMOVE: [ 0, EventConstants.MOUSE_MOVE, MouseConstants.MOUSE_BUTTON_NONE], WM_RBUTTONDOWN: [ MouseConstants.MOUSE_BUTTON_STATE_PRESSED, EventConstants.MOUSE_BUTTON_PRESS, MouseConstants.MOUSE_BUTTON_RIGHT], WM_MBUTTONDOWN: [ MouseConstants.MOUSE_BUTTON_STATE_PRESSED, EventConstants.MOUSE_BUTTON_PRESS, MouseConstants.MOUSE_BUTTON_MIDDLE], WM_LBUTTONDOWN: [ MouseConstants.MOUSE_BUTTON_STATE_PRESSED, EventConstants.MOUSE_BUTTON_PRESS, MouseConstants.MOUSE_BUTTON_LEFT], WM_RBUTTONUP: [ MouseConstants.MOUSE_BUTTON_STATE_RELEASED, EventConstants.MOUSE_BUTTON_RELEASE, MouseConstants.MOUSE_BUTTON_RIGHT], WM_MBUTTONUP: [ MouseConstants.MOUSE_BUTTON_STATE_RELEASED, EventConstants.MOUSE_BUTTON_RELEASE, MouseConstants.MOUSE_BUTTON_MIDDLE], WM_LBUTTONUP: [ MouseConstants.MOUSE_BUTTON_STATE_RELEASED, EventConstants.MOUSE_BUTTON_RELEASE, MouseConstants.MOUSE_BUTTON_LEFT], WM_RBUTTONDBLCLK: [ MouseConstants.MOUSE_BUTTON_STATE_MULTI_CLICK, EventConstants.MOUSE_MULTI_CLICK, MouseConstants.MOUSE_BUTTON_RIGHT], WM_MBUTTONDBLCLK: [ MouseConstants.MOUSE_BUTTON_STATE_MULTI_CLICK, EventConstants.MOUSE_MULTI_CLICK, MouseConstants.MOUSE_BUTTON_MIDDLE], WM_LBUTTONDBLCLK: [ MouseConstants.MOUSE_BUTTON_STATE_MULTI_CLICK, EventConstants.MOUSE_MULTI_CLICK, MouseConstants.MOUSE_BUTTON_LEFT], WM_MOUSEWHEEL: [ 0, EventConstants.MOUSE_SCROLL, MouseConstants.MOUSE_BUTTON_NONE]} slots = ['_user32', '_original_system_cursor_clipping_rect'] def __init__(self, *args, **kwargs): MouseDevice.__init__(self, *args, **kwargs['dconfig']) self._user32 = ctypes.windll.user32 self._original_system_cursor_clipping_rect = ctypes.wintypes.RECT() self._user32.GetClipCursor(ctypes.byref( self._original_system_cursor_clipping_rect)) def _initialMousePos(self): """If getPosition is called prior to any mouse events being received, this method gets the current system cursor pos. """ if self._position is None: p = 0.0, 0.0 mpos = ctypes.wintypes.POINT() if self._user32.GetCursorPos(ctypes.byref(mpos)): display_index = self.getDisplayIndexForMousePosition( (mpos.x,mpos.y)) if display_index == -1 and self._last_display_index is not None: display_index = self._last_display_index if display_index != self._display_device.getIndex(): # sys mouse is currently not in psychopy window # so keep pos to window center. display_index = -1 if display_index == -1: self._display_index = self._display_device.getIndex() self._last_display_index = self._display_index wm_pix = self._display_device._displayCoord2Pixel(p[0], p[1], self._display_index) self._nativeSetMousePos(*wm_pix) else: p = self._display_device._pixel2DisplayCoord( mpos.x, mpos.y, display_index) self._position = p self._lastPosition = self._position def _nativeSetMousePos(self, px, py): self._user32.SetCursorPos(int(px), int(py)) #print2err("_nativeSetMousePos {0}".format((int(px), int(py)))) def _nativeEventCallback(self, event): if self.isReportingEvents(): logged_time = currentSec() report_system_wide_events = self.getConfiguration().get('report_system_wide_events', True) pyglet_window_hnds = self._iohub_server._psychopy_windows.keys() if event.Window in pyglet_window_hnds: pass elif len(pyglet_window_hnds) > 0 and report_system_wide_events is False: return True self._scrollPositionY += event.Wheel event.WheelAbsolute = self._scrollPositionY event.DisplayIndex = display_index = 0 display_index = self.getDisplayIndexForMousePosition(event.Position) event.DisplayIndex = display_index if display_index == -1: if self._last_display_index is not None: display_index = self._last_display_index else: # Do not report event to iohub if it does not map to a display # ?? Can this ever actually happen ?? return True enable_multi_window = self.getConfiguration().get('enable_multi_window', False) if enable_multi_window is False: mx, my = event.Position p = self._display_device._pixel2DisplayCoord(mx, my, event.DisplayIndex) event.Position = p else: wid, wx, wy = self._desktopToWindowPos(event.Position) if wid: wx, wy = self._pix2windowUnits(wid, (wx, wy)) event.Position = wx, wy event.Window = wid else: event.Window = 0 self._lastPosition = self._position self._position = event.Position self._last_display_index = self._display_index self._display_index = display_index bstate, etype, bnum = self._mouse_event_mapper[event.Message] if bnum is not MouseConstants.MOUSE_BUTTON_NONE: self.activeButtons[bnum] = int(bstate == MouseConstants.MOUSE_BUTTON_STATE_PRESSED) abuttonSum = 0 for k, v in self.activeButtons.items(): abuttonSum += k * v event.ActiveButtons = abuttonSum self._addNativeEventToBuffer((logged_time, event)) self._last_callback_time = logged_time # pyHook require the callback to return True to inform the windows # low level hook functionality to pass the event on. return True def _getIOHubEventObject(self, native_event_data): logged_time, event = native_event_data p = event.Position px = p[0] py = p[1] bstate, etype, bnum = self._mouse_event_mapper[event.Message] if event.Message == self.WM_MOUSEMOVE and event.ActiveButtons > 0: etype = EventConstants.MOUSE_DRAG confidence_interval = 0.0 delay = 0.0 device_time = event.Time / 1000.0 # convert to sec hubTime = logged_time r = [0, 0, 0, # device id Device._getNextEventID(), etype, device_time, logged_time, hubTime, confidence_interval, delay, 0, event.DisplayIndex, bstate, bnum, event.ActiveButtons, px, py, 0, # scroll_dx not supported 0, # scroll_x not supported event.Wheel, event.WheelAbsolute, Keyboard._modifier_value, event.Window] return r def __del__(self): self._user32.ClipCursor( ctypes.byref( self._original_system_cursor_clipping_rect)) MouseDevice.__del__(self)
10,532
Python
.py
235
31.570213
102
0.586351
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,702
linux2.py
psychopy_psychopy/psychopy/iohub/devices/mouse/linux2.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). from ctypes import cdll from . import MouseDevice from .. import Computer, Device, xlib from ..keyboard import Keyboard from ...constants import MouseConstants from ...errors import print2err, printExceptionDetailsToStdErr currentSec = Computer.getTime class Mouse(MouseDevice): """The Mouse class and related events represent a standard computer mouse device and the events a standard mouse can produce. Mouse position data is mapped to the coordinate space defined in the ioHub configuration file for the Display. """ _xdll = None _xfixsdll = None _xdisplay = None _xscreen_count = None __slots__ = ['_cursorVisible'] def __init__(self, *args, **kwargs): MouseDevice.__init__(self, *args, **kwargs['dconfig']) self._cursorVisible = True if Mouse._xdll is None: try: Mouse._xdll = cdll.LoadLibrary('libX11.so') try: # should use linux cmd: # find /usr/lib -name libXfixes.so\* # to find full path to the lib (if it exists) # Mouse._xfixsdll = cdll.LoadLibrary('libXfixes.so') except Exception: try: Mouse._xfixsdll = cdll.LoadLibrary( 'libXfixes.so.3.1.0') except Exception: print2err( 'ERROR: Mouse._xfixsdll is None. libXfixes.so could not be found') except Exception: print2err( 'ERROR: Mouse._xdll is None. libX11.so could not be found') Mouse._xdisplay = xlib.XOpenDisplay(None) Mouse._xscreen_count = xlib.XScreenCount(Mouse._xdisplay) if Mouse._xfixsdll and self._xdll and self._display_device and self._display_device._xwindow is None: self._display_device._xwindow = self._xdll.XRootWindow( Mouse._xdisplay, self._display_device.getIndex()) def _initialMousePos(self): """If getPosition is called prior to any mouse events being received, this method gets the current system cursor pos. TODO: Implement Linux version """ if self._position is None: self._position = 0.0, 0.0 self._lastPosition = 0.0, 0.0 def _nativeSetMousePos(self, px, py): Mouse._xdll.XWarpPointer( Mouse._xdisplay, None, self._display_device._xwindow, 0, 0, 0, 0, int(px), int(py)) Mouse._xdll.XFlush(Mouse._xdisplay) def _nativeEventCallback(self, event): try: if self.isReportingEvents(): logged_time = currentSec() event_array = event[0] psychowins = self._iohub_server._psychopy_windows.keys() report_all = self.getConfiguration().get('report_system_wide_events', True) if report_all is False and psychowins and event_array[-1] not in psychowins: return True event_array[3] = Device._getNextEventID() display_index = self.getDisplayIndexForMousePosition((event_array[15], event_array[16])) if display_index == -1: if self._last_display_index is not None: display_index = self._last_display_index else: # Do not report event to iohub if it does not map to a display # ?? Can this ever actually happen ?? return True enable_multi_window = self.getConfiguration().get('enable_multi_window', False) if enable_multi_window is False: # convert mouse position to psychopy window coord space display_index = self._display_device.getIndex() x, y = self._display_device._pixel2DisplayCoord(event_array[15], event_array[16], display_index) event_array[15] = x event_array[16] = y else: wid, wx, wy = self._desktopToWindowPos((event_array[15], event_array[16])) if wid: wx, wy = self._pix2windowUnits(wid, (wx, wy)) event_array[15], event_array[16] = x, y = wx, wy event_array[-1] = wid else: event_array[-1] = 0 x = event_array[15] y = event_array[16] event_array[-2] = Keyboard._modifier_value self._lastPosition = self._position self._position = x, y event_array[11] = display_index self._last_display_index = self._display_index self._display_index = display_index bstate = event_array[-11] bnum = event_array[-10] if bnum is not MouseConstants.MOUSE_BUTTON_NONE: self.activeButtons[bnum] = int(bstate) self._scrollPositionY = event_array[-3] self._addNativeEventToBuffer(event_array) self._last_callback_time = logged_time except Exception: printExceptionDetailsToStdErr() return True def _getIOHubEventObject(self, native_event_data): return native_event_data def _close(self): if Mouse._xdll: #if Mouse._xfixsdll and self._nativeGetSystemCursorVisibility() is False: # Mouse._xfixsdll.XFixesShowCursor( # Mouse._xdisplay, self._display_device._xwindow) Mouse._xdll.XCloseDisplay(Mouse._xdisplay) Mouse._xdll = None Mouse._xfixsdll = None Mouse._xdisplay = None Mouse._xscreen_count = None try: self._display_device._xwindow = None except Exception: pass
6,331
Python
.py
136
32.492647
116
0.554438
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,703
__init__.py
psychopy_psychopy/psychopy/iohub/devices/mouse/__init__.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). from collections import namedtuple import numpy as np from .. import Device, Computer from ...constants import EventConstants, DeviceConstants from ...constants import MouseConstants, KeyboardConstants from ...errors import print2err, printExceptionDetailsToStdErr from psychopy.tools.monitorunittools import cm2pix, deg2pix, pix2cm, pix2deg RectangleBorder = namedtuple('RectangleBorderClass', 'left top right bottom') currentSec = Computer.getTime # OS 'independent' view of the Mouse Device class MouseDevice(Device): """ """ EVENT_CLASS_NAMES = [ 'MouseInputEvent', 'MouseButtonEvent', 'MouseScrollEvent', 'MouseMoveEvent', 'MouseDragEvent', 'MouseButtonPressEvent', 'MouseButtonReleaseEvent', 'MouseMultiClickEvent'] DEVICE_TYPE_ID = DeviceConstants.MOUSE DEVICE_TYPE_STRING = 'MOUSE' __slots__ = [ '_lock_mouse_to_display_id', '_scrollPositionY', '_position', '_clipRectsForDisplayID', '_lastPosition', '_display_index', '_last_display_index', '_isVisible', 'activeButtons'] def __init__(self, *args, **kwargs): Device.__init__(self, *args, **kwargs) self._clipRectsForDisplayID = {} self._lock_mouse_to_display_id = None self._scrollPositionY = 0 self._position = None self._lastPosition = None self._isVisible = 0 self._display_index = None self._last_display_index = None self.activeButtons = { MouseConstants.MOUSE_BUTTON_LEFT: 0, MouseConstants.MOUSE_BUTTON_RIGHT: 0, MouseConstants.MOUSE_BUTTON_MIDDLE: 0, } def getCurrentButtonStates(self): """Returns a list of three booleans, representing the current state of the MOUSE_BUTTON_LEFT, MOUSE_BUTTON_MIDDLE, MOUSE_BUTTON_RIGHT ioHub Mouse Device. Args: None Returns: (left_pressed, middle_pressed, right_pressed): Tuple of 3 bool values where True == Pressed. """ return (self.activeButtons[MouseConstants.MOUSE_BUTTON_LEFT] != 0, self.activeButtons[MouseConstants.MOUSE_BUTTON_MIDDLE] != 0, self.activeButtons[MouseConstants.MOUSE_BUTTON_RIGHT] != 0) def _initialMousePos(self): """If getPosition is called prior to any mouse events being received, this method gets the current system cursor pos using ctypes. """ if self._position is None: print2err('ERROR: _initialMousePos must be overwritten by ' 'OS dependent implementation') def getPosition(self, return_display_index=False): """Returns the current position of the ioHub Mouse Device. Mouse Position is in display coordinate units, with 0,0 being the center of the screen. Args: return_display_index: If True, the display index that is associated with the mouse position will also be returned. Returns: tuple: If return_display_index is false (default), return (x, y) position of mouse. If return_display_index is True return ( ( x,y), display_index). """ self._initialMousePos() if return_display_index is True: return (tuple(self._position), self._display_index) return tuple(self._position) def setPosition(self, pos, display_index=None): """Sets the current position of the ioHub Mouse Device. Mouse position ( pos ) should be specified in Display coordinate units, with 0,0 being the center of the screen. Args: pos ( (x,y) list or tuple ): The position, in Display coordinate space, to set the mouse position too. display_index (int): Optional argument giving the display index to set the mouse pos within. If None, the active ioHub Display device index is used. Returns: tuple: new (x,y) position of mouse in Display coordinate space. """ try: pos = pos[0], pos[1] except Exception: print2err('Warning: Mouse.setPosition: pos must be a list of ' 'two numbers, not: ', pos) return self._position display = self._display_device if display_index is None: display_index = display.getIndex() if 0 > display_index >= display.getDisplayCount(): print2err('Warning: Mouse.setPosition({},{}) failed. ' 'Display Index must be between ' '0 and {}.'.format(pos, display_index, display.getDisplayCount()-1)) return self._position px, py = display._displayCoord2Pixel(pos[0], pos[1], display_index) if not self._isPixPosWithinDisplay((px, py), display_index): print2err('Warning: Mouse.setPosition({},{}) failed because ' 'requested position ({} pix) does not fall within ' 'specified display pixel bounds.'.format(pos, display_index, (px, py))) return self._position mouse_display_index = self.getDisplayIndexForMousePosition((px, py)) if mouse_display_index != display_index: print2err( ' !!! requested display_index {0} != mouse_display_index ' '{1}'.format( display_index, mouse_display_index)) print2err(' mouse.setPos did not update mouse pos') else: self._lastPosition = self._position self._position = pos[0], pos[1] self._last_display_index = self._display_index self._display_index = mouse_display_index self._nativeSetMousePos(px, py) return self._position def _desktopToWindowPos(self, dpos): winfos = self._iohub_server._psychopy_windows for w in winfos.values(): mx, my = dpos wx, wy = w['pos'][0], w['pos'][1] ww, wh = w['size'][0], w['size'][1] if w['useRetina']: ww = ww / 2 wh = wh / 2 if wx <= mx <= wx+ww: if wy <= my <= wy + wh: return w['handle'], mx - wx - ww/2, -(my - wy - wh/2) return None, None, None def _pix2windowUnits(self, win_handle, pos): win = self._iohub_server._psychopy_windows.get(win_handle) win_units = win['units'] monitor = win['monitor'] pos = np.asarray(pos) if win_units == 'pix': return pos elif win_units == 'norm': return pos * 2.0 / win['size'] elif win_units == 'cm': if monitor: return pix2cm(pos, monitor['monitor']) else: # should raise exception? print2err("iohub Mouse error: Window is using units %s but has no Monitor definition." % win_units) elif win_units == 'deg': if monitor: return pix2deg(pos, monitor['monitor']) else: # should raise exception? print2err("iohub Mouse error: Window is using units %s but has no Monitor definition." % win_units) elif win_units == 'height': return pos / float(win['size'][1]) def _windowUnits2pix(self, win_handle, pos): win = self._iohub_server._psychopy_windows.get(win_handle) win_units = win['units'] monitor = win['monitor'] pos = np.asarray(pos) if win_units == 'pix': return pos elif win_units == 'norm': return pos * win['size'] / 2.0 elif win_units == 'cm': if monitor: return cm2pix(pos, monitor['monitor']) else: # should raise exception? print2err("iohub Mouse error: Window is using units %s but has no Monitor definition." % win_units) elif win_units == 'deg': if monitor: return deg2pix(pos, monitor['monitor']) else: # should raise exception print2err("iohub Mouse error: Window is using units %s but has no Monitor definition." % win_units) elif win_units == 'height': return pos * float(win['size'][1]) def getDisplayIndex(self): """ Returns the current display index of the ioHub Mouse Device. If the display index == the index of the display being used for stimulus presentation, then mouse position is in the display's coordinate units. If the display index != the index of the display being used for stimulus presentation, then mouse position is in OS system mouse coordinate space. Args: None Returns: (int): index of the Display the mouse is over. Display index's range from 0 to N-1, where N is the number of Display's active on the Computer. """ return self._display_index def getPositionAndDelta(self, return_display_index=False): """Returns a tuple of tuples, being the current position of the ioHub Mouse Device as an (x,y) tuple, and the amount the mouse position changed the last time it was updated (dx,dy). Mouse Position and Delta are in display coordinate units. Args: None Returns: tuple: ( (x,y), (dx,dy) ) position of mouse, change in mouse position, both in Display coordinate space. """ try: self._initialMousePos() cpos = self._position lpos = self._lastPosition if lpos is None: lpos = cpos[0], cpos[1] change_x = cpos[0] - lpos[0] change_y = cpos[1] - lpos[1] if return_display_index is True: return (cpos, (change_x, change_y), self._display_index) return cpos, (change_x, change_y) except Exception as e: print2err('>>ERROR getPositionAndDelta: ' + str(e)) printExceptionDetailsToStdErr() if return_display_index is True: return ((0.0, 0.0), (0.0, 0.0), self._display_index) return (0.0, 0.0), (0.0, 0.0) def getScroll(self): """ Returns the current vertical scroll value for the mouse. The vertical scroll value changes when the scroll wheel on a mouse is moved up or down. The vertical scroll value is in an arbitrary value space ranging for -32648 to +32648. Scroll position is initialize to 0 when the experiment starts. Args: None Returns: int: current vertical scroll value. """ return self._scrollPositionY def setScroll(self, s): """ Sets the current vertical scroll value for the mouse. The vertical scroll value changes when the scroll wheel on a mouse is moved up or down. The vertical scroll value is in an arbitrary value space ranging for -32648 to +32648. Scroll position is initialize to 0 when the experiment starts. This method allows you to change the scroll value to anywhere in the valid value range. Args (int): The scroll position you want to set the vertical scroll to. Should be a number between -32648 to +32648. Returns: int: current vertical scroll value. """ if isinstance(s, (int, float, complex)): self._scrollPositionY = s return self._scrollPositionY def getDisplayIndexForMousePosition(self, system_mouse_pos): return self._display_device._getDisplayIndexForNativePixelPosition( system_mouse_pos) def _getClippedMousePosForDisplay(self, pixel_pos, display_index): drti = self._display_device._getRuntimeInfoByIndex(display_index) left, top, right, bottom = drti['bounds'] mx, my = pixel_pos if mx < left: mx = left elif mx >= right: mx = right - 1 if my < top: my = top elif my >= bottom: my = bottom - 1 return mx, my def _validateMousePosForActiveDisplay(self, pixel_pos): left, top, right, bottom = self._display_device.getBounds() mx, my = pixel_pos mousePositionNeedsUpdate = False if mx < left: mx = left mousePositionNeedsUpdate = True elif mx >= right: mx = right - 1 mousePositionNeedsUpdate = True if my < top: my = top mousePositionNeedsUpdate = True elif my >= bottom: my = bottom - 1 mousePositionNeedsUpdate = True if mousePositionNeedsUpdate: return mx, my return True def _isPixPosWithinDisplay(self, pixel_pos, display_index): d = self._display_device._getDisplayIndexForNativePixelPosition(pixel_pos) return d == display_index def _nativeSetMousePos(self, px, py): print2err( 'ERROR: _nativeSetMousePos must be overwritten by OS ' 'dependent implementation') if Computer.platform == 'win32': from .win32 import Mouse elif Computer.platform.startswith('linux'): from .linux2 import Mouse elif Computer.platform == 'darwin': from .darwin import Mouse ############# OS Independent Mouse Event Classes #################### from .. import DeviceEvent class MouseInputEvent(DeviceEvent): """The MouseInputEvent is an abstract class that is the parent of all MouseInputEvent types that are supported in the ioHub. Mouse position is mapped to the coordinate space defined in the ioHub configuration file for the Display. """ PARENT_DEVICE = Mouse EVENT_TYPE_STRING = 'MOUSE_INPUT' EVENT_TYPE_ID = EventConstants.MOUSE_INPUT IOHUB_DATA_TABLE = EVENT_TYPE_STRING _newDataTypes = [ # gives the display index that the mouse was over for the event. ('display_id', np.uint8), # 1 if button is pressed, 0 if button is released ('button_state', np.uint8), # 1, 2,or 4, representing left, right, and middle buttons ('button_id', np.uint8), # sum of currently active button int values ('pressed_buttons', np.uint8), # x position of the position when the event occurred ('x_position', np.float64), # y position of the position when the event occurred ('y_position', np.float64), # horizontal scroll wheel position change when the event occurred (OS X # only) ('scroll_dx', np.int8), # horizontal scroll wheel abs. position when the event occurred (OS X # only) ('scroll_x', np.int16), # vertical scroll wheel position change when the event occurred ('scroll_dy', np.int8), # vertical scroll wheel abs. position when the event occurred ('scroll_y', np.int16), # indicates what modifier keys were active when the mouse event # occurred. ('modifiers', np.uint32), # window ID that the mouse was over when the event occurred ('window_id', np.uint64) # (window does not need to have focus) ] __slots__ = [e[0] for e in _newDataTypes] def __init__(self, *args, **kwargs): #: The id of the display that the mouse was over when the event #: occurred. #: Only supported on Windows at this time. Always 0 on other OS's. self.display_id = None #: 1 if button is pressed, 0 if button is released self.button_state = None #: MouseConstants.MOUSE_BUTTON_LEFT, MouseConstants.MOUSE_BUTTON_RIGHT #: and MouseConstants.MOUSE_BUTTON_MIDDLE are int constants #: representing left, right, and middle buttons of the mouse. self.button_id = None #: 'All' currently pressed button id's logically OR'ed together. self.pressed_buttons = None #: x position of the Mouse when the event occurred; in display #: coordinate space. self.x_position = None #: y position of the Mouse when the event occurred; in display #: coordinate space. self.y_position = None #: Horizontal scroll wheel position change when the event occurred. #: OS X Only. Always 0 on other OS's. self.scroll_dx = None #: Horizontal scroll wheel absolute position when the event occurred. #: OS X Only. Always 0 on other OS's. self.scroll_x = None #: Vertical scroll wheel position change when the event occurred. self.scroll_dy = None #: Vertical scroll wheel absolute position when the event occurred. self.scroll_y = None #: List of the modifiers that were active when the mouse event #: occurred, #: provided in online events as a list of the modifier constant labels #: specified in iohub.ModifierConstants #: list: Empty if no modifiers are pressed, otherwise each element is # the string name of a modifier constant. self.modifiers = 0 #: Window handle reference that the mouse was over when the event #: occurred #: (window does not need to have focus) self.window_id = None DeviceEvent.__init__(self, *args, **kwargs) @classmethod def _convertFields(cls, event_value_list): modifier_value_index = cls.CLASS_ATTRIBUTE_NAMES.index('modifiers') event_value_list[ modifier_value_index] = KeyboardConstants._modifierCodes2Labels( event_value_list[modifier_value_index]) @classmethod def createEventAsDict(cls, values): cls._convertFields(values) return dict(zip(cls.CLASS_ATTRIBUTE_NAMES, values)) # noinspection PyUnresolvedReferences @classmethod def createEventAsNamedTuple(cls, valueList): cls._convertFields(valueList) return cls.namedTupleClass(*valueList) class MouseMoveEvent(MouseInputEvent): """MouseMoveEvent's occur when the mouse position changes. Mouse position is mapped to the coordinate space defined in the ioHub configuration file for the Display. Event Type ID: EventConstants.MOUSE_MOVE Event Type String: 'MOUSE_MOVE' """ EVENT_TYPE_STRING = 'MOUSE_MOVE' EVENT_TYPE_ID = EventConstants.MOUSE_MOVE IOHUB_DATA_TABLE = MouseInputEvent.IOHUB_DATA_TABLE __slots__ = [] def __init__(self, *args, **kwargs): MouseInputEvent.__init__(self, *args, **kwargs) class MouseDragEvent(MouseMoveEvent): """MouseDragEvents occur when the mouse position changes and at least one mouse button is pressed. Mouse position is mapped to the coordinate space defined in the ioHub configuration file for the Display. Event Type ID: EventConstants.MOUSE_DRAG Event Type String: 'MOUSE_DRAG' """ EVENT_TYPE_STRING = 'MOUSE_DRAG' EVENT_TYPE_ID = EventConstants.MOUSE_DRAG IOHUB_DATA_TABLE = MouseMoveEvent.IOHUB_DATA_TABLE __slots__ = [] def __init__(self, *args, **kwargs): MouseMoveEvent.__init__(self, *args, **kwargs) class MouseScrollEvent(MouseInputEvent): """MouseScrollEvent's are generated when the scroll wheel on the Mouse Device (if it has one) is moved. Vertical scrolling is supported on all operating systems, horizontal scrolling is only supported on OS X. Each MouseScrollEvent provides the number of units the wheel was turned in each supported dimension, as well as the absolute scroll value for of each supported dimension. Event Type ID: EventConstants.MOUSE_SCROLL Event Type String: 'MOUSE_SCROLL' """ EVENT_TYPE_STRING = 'MOUSE_SCROLL' EVENT_TYPE_ID = EventConstants.MOUSE_SCROLL IOHUB_DATA_TABLE = MouseInputEvent.IOHUB_DATA_TABLE __slots__ = [] def __init__(self, *args, **kwargs): """ :rtype : MouseScrollEvent :param args: :param kwargs: """ MouseInputEvent.__init__(self, *args, **kwargs) class MouseButtonEvent(MouseInputEvent): EVENT_TYPE_STRING = 'MOUSE_BUTTON' EVENT_TYPE_ID = EventConstants.MOUSE_BUTTON IOHUB_DATA_TABLE = MouseInputEvent.IOHUB_DATA_TABLE __slots__ = [] def __init__(self, *args, **kwargs): """ :rtype : MouseButtonEvent :param args: :param kwargs: """ MouseInputEvent.__init__(self, *args, **kwargs) class MouseButtonPressEvent(MouseButtonEvent): """MouseButtonPressEvent's are created when a button on the mouse is pressed. The button_state of the event will equal MouseConstants.MOUSE_BUTTON_STATE_PRESSED, and the button that was pressed (button_id) will be MouseConstants.MOUSE_BUTTON_LEFT, MouseConstants.MOUSE_BUTTON_RIGHT, or MouseConstants.MOUSE_BUTTON_MIDDLE, assuming you have a 3 button mouse. To get the current state of all three buttons on the Mouse Device, the pressed_buttons attribute can be read, which tracks the state of all three mouse buttons as an int that is equal to the sum of any pressed button id's ( MouseConstants.MOUSE_BUTTON_LEFT, MouseConstants.MOUSE_BUTTON_RIGHT, or MouseConstants.MOUSE_BUTTON_MIDDLE ). To tell if a given mouse button was depressed when the event occurred, regardless of which button triggered the event, you can use the following:: isButtonPressed = event.pressed_buttons & MouseConstants.MOUSE_BUTTON_xxx == MouseConstants.MOUSE_BUTTON_xxx where xxx is LEFT, RIGHT, or MIDDLE. For example, if at the time of the event both the left and right mouse buttons were in a pressed state:: buttonToCheck=MouseConstants.MOUSE_BUTTON_RIGHT isButtonPressed = event.pressed_buttons & buttonToCheck == buttonToCheck print isButtonPressed >> True buttonToCheck=MouseConstants.MOUSE_BUTTON_LEFT isButtonPressed = event.pressed_buttons & buttonToCheck == buttonToCheck print isButtonPressed >> True buttonToCheck=MouseConstants.MOUSE_BUTTON_MIDDLE isButtonPressed = event.pressed_buttons & buttonToCheck == buttonToCheck print isButtonPressed >> False Event Type ID: EventConstants.MOUSE_BUTTON_PRESS Event Type String: 'MOUSE_BUTTON_PRESS' """ EVENT_TYPE_STRING = 'MOUSE_BUTTON_PRESS' EVENT_TYPE_ID = EventConstants.MOUSE_BUTTON_PRESS IOHUB_DATA_TABLE = MouseInputEvent.IOHUB_DATA_TABLE __slots__ = [] def __init__(self, *args, **kwargs): MouseButtonEvent.__init__(self, *args, **kwargs) class MouseButtonReleaseEvent(MouseButtonEvent): """MouseButtonUpEvent's are created when a button on the mouse is released. The button_state of the event will equal MouseConstants.MOUSE_BUTTON_STATE_RELEASED, and the button that was pressed (button_id) will be MouseConstants.MOUSE_BUTTON_LEFT, MouseConstants.MOUSE_BUTTON_RIGHT, or MouseConstants.MOUSE_BUTTON_MIDDLE, assuming you have a 3 button mouse. Event Type ID: EventConstants.MOUSE_BUTTON_RELEASE Event Type String: 'MOUSE_BUTTON_RELEASE' """ EVENT_TYPE_STRING = 'MOUSE_BUTTON_RELEASE' EVENT_TYPE_ID = EventConstants.MOUSE_BUTTON_RELEASE IOHUB_DATA_TABLE = MouseInputEvent.IOHUB_DATA_TABLE __slots__ = [] def __init__(self, *args, **kwargs): MouseButtonEvent.__init__(self, *args, **kwargs) class MouseMultiClickEvent(MouseButtonEvent): """MouseMultiClickEvent's are created when you rapidly press and release a mouse button two or more times. This event may never get triggered if your OS does not support it. The button that was multi clicked (button_id) will be MouseConstants.MOUSE_BUTTON_LEFT, MouseConstants.MOUSE_BUTTON_RIGHT, or MouseConstants.MOUSE_BUTTON_MIDDLE, assuming you have a 3 button mouse. Event Type ID: EventConstants.MOUSE_MULTI_CLICK Event Type String: 'MOUSE_MULTI_CLICK' """ EVENT_TYPE_STRING = 'MOUSE_MULTI_CLICK' EVENT_TYPE_ID = EventConstants.MOUSE_MULTI_CLICK IOHUB_DATA_TABLE = MouseInputEvent.IOHUB_DATA_TABLE __slots__ = [] def __init__(self, *args, **kwargs): MouseButtonEvent.__init__(self, *args, **kwargs)
25,017
Python
.py
562
35.161922
115
0.633577
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,704
darwin.py
psychopy_psychopy/psychopy/iohub/devices/mouse/darwin.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). from copy import copy import Quartz as Qz from AppKit import NSEvent from . import MouseDevice from ..keyboard import Keyboard from .. import Computer, Device from ...errors import print2err, printExceptionDetailsToStdErr from ...constants import EventConstants, MouseConstants currentSec = Computer.getTime pressID = [ None, Qz.kCGEventLeftMouseDown, Qz.kCGEventRightMouseDown, Qz.kCGEventOtherMouseDown] releaseID = [ None, Qz.kCGEventLeftMouseUp, Qz.kCGEventRightMouseUp, Qz.kCGEventOtherMouseUp] dragID = [ None, Qz.kCGEventLeftMouseDragged, Qz.kCGEventRightMouseDragged, Qz.kCGEventOtherMouseDragged] class Mouse(MouseDevice): """The Mouse class and related events represent a standard computer mouse device and the events a standard mouse can produce. Mouse position data is mapped to the coordinate space defined in the ioHub configuration file for the Display. Examples: A. Print all mouse events received for 5 seconds:: from psychopy.iohub import launchHubServer from psychopy.core import getTime # Start the ioHub process. 'io' can now be used during the # experiment to access iohub devices and read iohub device events. io = launchHubServer() mouse = io.devices.mouse # Check for and print any Mouse events received for 5 seconds. stime = getTime() while getTime()-stime < 5.0: for e in mouse.getEvents(): print(e) # Stop the ioHub Server io.quit() B. Print current mouse position for 5 seconds:: from psychopy.iohub import launchHubServer from psychopy.core import getTime # Start the ioHub process. 'io' can now be used during the # experiment to access iohub devices and read iohub device events. io = launchHubServer() mouse = io.devices.mouse # Check for and print any Mouse events received for 5 seconds. stime = getTime() while getTime()-stime < 5.0: print(mouse.getPosition()) # Stop the ioHub Server io.quit() """ __slots__ = ['_loop_source', '_tap', '_device_loop', '_CGEventTapEnable', '_loop_mode', '_scrollPositionX'] _IOHUB_BUTTON_ID_MAPPINGS = { Qz.kCGEventLeftMouseDown: MouseConstants.MOUSE_BUTTON_LEFT, Qz.kCGEventRightMouseDown: MouseConstants.MOUSE_BUTTON_RIGHT, Qz.kCGEventOtherMouseDown: MouseConstants.MOUSE_BUTTON_MIDDLE, Qz.kCGEventLeftMouseUp: MouseConstants.MOUSE_BUTTON_LEFT, Qz.kCGEventRightMouseUp: MouseConstants.MOUSE_BUTTON_RIGHT, Qz.kCGEventOtherMouseUp: MouseConstants.MOUSE_BUTTON_MIDDLE } DEVICE_TIME_TO_SECONDS = 0.000000001 _EVENT_TEMPLATE_LIST = [0, # experiment id 0, # session id 0, # device id 0, # Device._getNextEventID(), 0, # ioHub Event type 0.0, # event device time, 0.0, # event logged_time, 0.0, # event iohub Time, 0.0, # confidence_interval, 0.0, # delay, 0, # filtered by ID (always 0 right now) 0, # Display Index, 0, # ioHub Button State, 0, # ioHub Button ID, 0, # Active Buttons, 0.0, # x position of mouse in Display device coord's 0.0, # y position of mouse in Display device coord's 0, # Wheel dx 0, # Wheel Absolute x 0, # Wheel dy 0, # Wheel Absolute y 0, # modifiers 0] # event.Window] def __init__(self, *args, **kwargs): MouseDevice.__init__(self, *args, **kwargs['dconfig']) self._tap = Qz.CGEventTapCreate( Qz.kCGSessionEventTap, Qz.kCGHeadInsertEventTap, Qz.kCGEventTapOptionDefault, Qz.CGEventMaskBit(Qz.kCGEventMouseMoved) | Qz.CGEventMaskBit(Qz.kCGEventLeftMouseDown) | Qz.CGEventMaskBit(Qz.kCGEventLeftMouseUp) | Qz.CGEventMaskBit(Qz.kCGEventRightMouseDown) | Qz.CGEventMaskBit(Qz.kCGEventRightMouseUp) | Qz.CGEventMaskBit(Qz.kCGEventLeftMouseDragged) | Qz.CGEventMaskBit(Qz.kCGEventRightMouseDragged) | Qz.CGEventMaskBit(Qz.kCGEventOtherMouseDragged) | Qz.CGEventMaskBit(Qz.kCGEventOtherMouseDown) | Qz.CGEventMaskBit(Qz.kCGEventScrollWheel) | Qz.CGEventMaskBit(Qz.kCGEventOtherMouseUp), self._nativeEventCallback, None) self._scrollPositionX = 0 self._CGEventTapEnable = Qz.CGEventTapEnable self._loop_source = Qz.CFMachPortCreateRunLoopSource( None, self._tap, 0) self._device_loop = Qz.CFRunLoopGetCurrent() self._loop_mode = Qz.kCFRunLoopDefaultMode Qz.CFRunLoopAddSource( self._device_loop, self._loop_source, self._loop_mode) def _initialMousePos(self): """If getPosition is called prior to any mouse events being received, this method gets the current system cursor pos. TODO: Implement OS X version """ if self._position is None: self._position = 0.0, 0.0 self._lastPosition = 0.0, 0.0 def _nativeSetMousePos(self, px, py): result = Qz.CGWarpMouseCursorPosition( Qz.CGPointMake(float(px), float(py))) #print2err('_nativeSetMousePos result: ',result) #def _nativeGetSystemCursorVisibility(self): # return Qz.CGCursorIsVisible() # # def _nativeSetSystemCursorVisibility(self, v): # if v and not Qz.CGCursorIsVisible(): # Qz.CGDisplayShowCursor(Qz.CGMainDisplayID()) # elif not v and Qz.CGCursorIsVisible(): # Qz.CGDisplayHideCursor(Qz.CGMainDisplayID()) #def _nativeLimitCursorToBoundingRect(self, clip_rect): # print2err( # 'WARNING: Mouse._nativeLimitCursorToBoundingRect not implemented on OSX yet.') # native_clip_rect = None # return native_clip_rect def getScroll(self): """ TODO: Update docs for OSX Args: None Returns """ return self._scrollPositionX, self._scrollPositionY def setScroll(self, sp): """ TODO: Update docs for OSX """ self._scrollPositionX, self._scrollPositionY = sp return self._scrollPositionX, self._scrollPositionY def _poll(self): self._last_poll_time = currentSec() while Qz.CFRunLoopRunInMode(self._loop_mode, 0.0, True) == Qz.kCFRunLoopRunHandledSource: pass def _nativeEventCallback(self, *args): try: proxy, etype, event, refcon = args if self.isReportingEvents(): logged_time = currentSec() if etype == Qz.kCGEventTapDisabledByTimeout: print2err('** WARNING: Mouse Tap Disabled due to timeout. Re-enabling....: ', etype) Qz.CGEventTapEnable(self._tap, True) return event else: confidence_interval = 0.0 delay = 0.0 iohub_time = logged_time device_time = Qz.CGEventGetTimestamp(event) * self.DEVICE_TIME_TO_SECONDS ioe_type = EventConstants.UNDEFINED px, py = Qz.CGEventGetLocation(event) multi_click_count = Qz.CGEventGetIntegerValueField(event, Qz.kCGMouseEventClickState) mouse_event = NSEvent.eventWithCGEvent_(event) # TODO: window_handle seems to always be 0. window_handle = mouse_event.windowNumber() display_index = self.getDisplayIndexForMousePosition((px, py)) if display_index == -1: if self._last_display_index is not None: display_index = self._last_display_index else: # Do not report event to iohub if it does not map to a display # ?? Can this ever actually happen ?? return event enable_multi_window = self.getConfiguration().get('enable_multi_window', False) if enable_multi_window is False: px, py = self._display_device._pixel2DisplayCoord(px, py, display_index) else: wid, wx, wy = self._desktopToWindowPos((px, py)) if wid: px, py = self._pix2windowUnits(wid, (wx, wy)) window_handle = wid else: window_handle = 0 self._lastPosition = self._position self._position = px, py self._last_display_index = self._display_index self._display_index = display_index # TO DO: Supported reporting scroll x info for OSX. # This also suggests not having scroll up and down events and # just having the one scroll event type, regardless of # direction / dimension scroll_dx = 0 scroll_dy = 0 button_state = 0 if etype in pressID: button_state = MouseConstants.MOUSE_BUTTON_STATE_PRESSED if multi_click_count > 1: ioe_type = EventConstants.MOUSE_MULTI_CLICK else: ioe_type = EventConstants.MOUSE_BUTTON_PRESS elif etype in releaseID: button_state = MouseConstants.MOUSE_BUTTON_STATE_RELEASED ioe_type = EventConstants.MOUSE_BUTTON_RELEASE elif etype in dragID: ioe_type = EventConstants.MOUSE_DRAG elif etype == Qz.kCGEventMouseMoved: ioe_type = EventConstants.MOUSE_MOVE elif etype == Qz.kCGEventScrollWheel: ioe_type = EventConstants.MOUSE_SCROLL scroll_dy = Qz.CGEventGetIntegerValueField(event, Qz.kCGScrollWheelEventPointDeltaAxis1) scroll_dx = Qz.CGEventGetIntegerValueField(event, Qz.kCGScrollWheelEventPointDeltaAxis2) self._scrollPositionX += scroll_dx self._scrollPositionY += scroll_dy iohub_button_id = self._IOHUB_BUTTON_ID_MAPPINGS.get(etype, 0) if iohub_button_id in self.activeButtons: abuttons = int(button_state == MouseConstants.MOUSE_BUTTON_STATE_PRESSED) self.activeButtons[iohub_button_id] = abuttons pressed_buttons = 0 for k, v in self.activeButtons.items(): pressed_buttons += k * v # Create Event List # index 0 and 1 are session and exp. ID's # index 2 is (yet to be used) device_id ioe = self._EVENT_TEMPLATE_LIST ioe[3] = Device._getNextEventID() ioe[4] = ioe_type # event type code ioe[5] = device_time ioe[6] = logged_time ioe[7] = iohub_time ioe[8] = confidence_interval ioe[9] = delay # index 10 is filter id, not used at this time ioe[11] = display_index ioe[12] = button_state ioe[13] = iohub_button_id ioe[14] = pressed_buttons ioe[15] = px ioe[16] = py ioe[17] = int(scroll_dx) ioe[18] = int(self._scrollPositionX) ioe[19] = int(scroll_dy) ioe[20] = int(self._scrollPositionY) ioe[21] = Keyboard._modifier_value ioe[22] = window_handle self._addNativeEventToBuffer(copy(ioe)) self._last_callback_time = logged_time except Exception: printExceptionDetailsToStdErr() Qz.CGEventTapEnable(self._tap, False) # Must return original event or no mouse events will get to OSX! return event def _getIOHubEventObject(self, native_event_data): #ioHub.print2err('Event: ',native_event_data) return native_event_data def _close(self): #try: # self._nativeSetSystemCursorVisibility(True) #except Exception: # pass try: Qz.CGEventTapEnable(self._tap, False) except Exception: pass try: if Qz.CFRunLoopContainsSource( self._device_loop, self._loop_source, self._loop_mode) is True: Qz.CFRunLoopRemoveSource( self._device_loop, self._loop_source, self._loop_mode) finally: self._loop_source = None self._tap = None self._device_loop = None self._loop_mode = None MouseDevice._close(self) # END OF OSX MOUSE CLASS """ CGEventTapInformation Defines the structure used to report information about event taps. typedef struct CGEventTapInformation { uint32_t eventTapID; CGEventTapLocation tapPoint; CGEventTapOptions options; CGEventMask eventsOfInterest; pid_t tappingProcess; pid_t processBeingTapped; bool enabled; float minUsecLatency; float avgUsecLatency; float maxUsecLatency; } CGEventTapInformation; Fields eventTapID The unique identifier for the event tap. tapPoint The location of the event tap. See "Event Tap Locations." options The type of event tap (passive listener or active filter). eventsOfInterest The mask that identifies the set of events to be observed. tappingProcess The process ID of the application that created the event tap. processBeingTapped The process ID of the target application (non-zero only if the event tap was created using the function CGEventTapCreateForPSN. enabled TRUE if the event tap is currently enabled; otherwise FALSE. minUsecLatency Minimum latency in microseconds. In this data structure, latency is defined as the time in microseconds it takes for an event tap to process and respond to an event passed to it. avgUsecLatency Average latency in microseconds. This is a weighted average that gives greater weight to more recent events. maxUsecLatency Maximum latency in microseconds. Discussion To learn how to obtain information about event taps, see the function CGGetEventTapList. Availability Available in OS X v10.4 and later. Declared In CGEventTypes.h """
16,234
Python
.py
348
32.5
112
0.569678
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,705
__init__.py
psychopy_psychopy/psychopy/iohub/devices/display/__init__.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). import sys from .. import Device, Computer from ...constants import DeviceConstants from ...errors import print2err, printExceptionDetailsToStdErr import pyglet currentSec = Computer.getTime class Display(Device): """The ioHub Display Device represents a 2D visual stimulus presentation surface that is connected to the computer running ioHub and PsychoPy. The Display Device can be queries for several run-time properties that are read when the device is created, and is also used for transforming the physical Display surface area and pixel resolution into alternative coordinate system types that can be used during an experiment. """ _coord_type_mappings = dict(pix='pix', pixel='pix', pixels='pix', deg='deg', degree='deg', degrees='deg', cm='cm', norm='norm', normalize='norm', normalized='norm', height='height' ) _supported_origin_types = ['center', ] _enabled_display_instances = [] _computer_display_runtime_info_list = None EVENT_CLASS_NAMES = [] DEVICE_TYPE_ID = DeviceConstants.DISPLAY DEVICE_TYPE_STRING = 'DISPLAY' __slots__ = [ '_pixels_per_degree', '_pix2coord', '_coord2pix', '_xwindow', '_psychopy_monitor'] def __init__(self, *args, **kwargs): Device.__init__(self, *args, **kwargs['dconfig']) self._psychopy_monitor = None self._coord2pix = None self._pix2coord = None if sys.platform.startswith('linux'): self._xwindow = None if Display._computer_display_runtime_info_list is None: Display._computer_display_runtime_info_list = Display._createAllRuntimeInfoDicts() if self.getIndex() >= self.getDisplayCount(): # Requested Display index is invalid. Use Display / Screen index 0. print2err("WARNING: Requested display index does not exist. Using display index 0.") self.device_number = 0 self._addRuntimeInfoToDisplayConfig() def getDeviceNumber(self): """Same as Display.getIndex(). All ioHub devices have a device_number, so for the Display Device it makes sense to map device_number to the Display index. See Display.getIndex(). """ return self.device_number def getIndex(self): """ Returns the display index. In a single display configuration, this will always equal 0. In a multiple display configuration, valid index's range from 0 to N-1, where N equals the number of display's connected and active on the Computer being used. Args: None Returns: int: Current Display Index; between 0 and getDisplayCount()-1 """ return self.device_number @classmethod def getDisplayCount(cls): """Returns the number of monitors connected to the computer that are also active. For example, a Computer may have 3 Displays connected to it, but the video card may only support having two displays active at a time. Args: None Returns: int: Total number of displays active on the computer. """ return len(cls._computer_display_runtime_info_list) @classmethod def getAllDisplayBounds(cls): """ Returns pixel display bounds (l,t r,b) for each detected display. :return: list of (l,t r,b) tuples """ return [d.get('bounds') for d in cls._computer_display_runtime_info_list] def getRuntimeInfo(self, display_index = None): """ Returns a dictionary containing run-time determined settings for the Display Device, based on querying system settings regarding the Monitor. A Display's run-time properties consist of: * index: see getIndex(). * pixel_width: The horizontal pixel resolution of the Display. * pixel_height: The vertical pixel resolution of the Display. * pixel_resolution: ( pixel_width, pixel_height ) * bounds: See getBounds() * retrace_rate: The vertical retrace rate of the Display in Hz., as reported by the OS. * bits_per_pixel: Number if bits being used to represent all channels of a pixel by the OS. * primary: True if the current Monitor is also the primary monitor reported by the OS. Args: display_index (int): Optional screen index to return info about. Returns: dict: Run-time attributes of the Display specified by display_index. If display_index is None, use full screen window display_index. """ if display_index is None or display_index == self.getIndex(): return self.getConfiguration()['runtime_info'] return self._getRuntimeInfoByIndex(display_index) def getCoordinateType(self): """ Returns the coordinate, or reporting unit, being used by the Display. Supported types match the PsychoPy unit_types for Monitors, with the exception of the height option: * pix : Equivalent names for this type are *pixel* and *pixels*. * cm : There are no equivalent alternatives to this coordinate type name. * norm : Equivalent names for this type are *normalize* and *normalized*. * deg : Equivalent names for this type are *degree* and *degrees*. Please refer to the psychoPy documentation for a detailed description of coordinate type. Args: None Returns: str: The coordinate, or unit, type being used to define the Display stimulus area. """ return self.getConfiguration()['reporting_unit_type'] def getColorSpace(self): """ Returns the color space to use for PsychoPy Windows. Please refer to the psychoPy documentation for a detailed description of supported color spaces. Args: None Returns: str: Display color space """ return self.getConfiguration()['color_space'] def getPixelsPerDegree(self): """Returns the Display's horizontal and vertical pixels per degree This is currently calculated using the PsychoPy built in function. Therefore PPD x and PPD y will be the same value, as only the monitor width and participants viewing distance is currently used. The physical characteristics of the Display and the Participants viewing distance will either be based on the ioHub settings specified, or based on the information saved in the PsychoPy Monitor Configuration file that can be optionally given to the Display Device before it is instantiated. Args: None Returns: tuple: (ppd_x, ppd_y) """ try: return self.getConfiguration()['runtime_info']['pixels_per_degree'] except Exception: print2err('ERROR GETTING PPD !') printExceptionDetailsToStdErr() def getPixelResolution(self): """Get the Display's pixel resolution based on the current graphics mode. Args: None Returns: tuple: (width,height) of the monitor in pixels based. """ return self.getConfiguration()['runtime_info']['pixel_resolution'] def getRetraceInterval(self): """ Get the Display's *reported* retrace interval (1000.0/retrace_rate)*0.001 based on the current graphics mode. Args: None Returns: float: Current retrace interval of Monitor reported by the OS in sec.msec format. """ return (1000.0 / self.getConfiguration() ['runtime_info']['retrace_rate']) * 0.001 def getBounds(self): """Get the Display's pixel bounds; representing the left,top,right,and bottom edge of the display screen in native pixel units. .. note:: (left, top, right, bottom) bounds will 'not' always be (0, 0, pixel_width, pixel_height). If a multiple display setup is being used, (left, top, right, bottom) indicates the actual absolute pixel bounds assigned to that monitor by the OS. It can be assumed that right = left + display_pixel_width and bottom = top + display_pixel_height Args: None Returns: tuple: (left, top, right, bottom) Native pixel bounds for the Display. """ return self.getConfiguration()['runtime_info']['bounds'] def getCoordBounds(self): """Get the Display's left, top, right, and bottom border bounds, specified in the coordinate space returned by Display.getCoordinateType() Args: None Returns: tuple: (left, top, right, bottom) coordinate bounds for the Display represented in Display.getCoordinateType() units. """ return self.getConfiguration()['runtime_info']['coordinate_bounds'] def getDefaultEyeDistance(self): """Returns the default distance from the particpant's eye to the Display's physical screen surface, as specified in the ioHub Display device's configuration settings or the PsychoPy Monitor Configuration. Currently this is the distance from the participant's eye of interest ( or the average distance of both eyes when binocular data is being obtained ) to the center of the Display screen being used for stimulus presentation. Args: None Returns: int: Default distance in mm from the participant to the display screen surface. """ return self.getConfiguration()['default_eye_distance']\ ['surface_center'] def getPhysicalDimensions(self): """Returns the Display's physical screen area ( width, height ) as specified in the ioHub Display devices configuration settings or by a PsychoPy Monitor Configuration file. Args: None Returns: dict: A dict containing the screen 'width' and 'height' as keys, as well as the 'unit_type' the width and height are specified in. Currently only 'mm' is supported for unit_type. """ return self.getConfiguration()['physical_dimensions'] def getPsychopyMonitorName(self): """Returns the name of the PsychoPy Monitor Configuration file being used with the Display. Args: None Returns: str: Name of the PsychoPy Monitor Configuration being used with the Display. """ return self.getConfiguration().get('psychopy_monitor_name') # Private Methods ------> def _pixel2DisplayCoord(self, px, py, display_index=None): """ Converts the given pixel position (px, py), to the associated Display devices x, y position in the display's coordinate space. If display_index is None (the default), then it is assumed the px,py value is for the display index specified for the display configured with ioHub. If display_index is not None, then that display index is used in the computation. If the display_index matches the ioHub enable Display devices index, then the method converts from the px,py value to the DIsplay devices coordinate / unit space type (Currently also only pix is supported), factoring in the origin specified in the Display device configuration. If the display_index does not match the ioHub Display device that is being used, then px,py == the output x,y value. Args: display_index (int or None): the display index the px,py value should be relative to. None == use the currently enabled ioHub Display device's index. Returns: tuple: (x,y), the mapped position based on the 'logic' noted in the description of the method. """ if self._pix2coord: return self._pix2coord(self, px, py, display_index) return 0, 0 def _displayCoord2Pixel(self, cx, cy, display_index=None): """ Converts the given display position (dx, dy), to the associated pixel px, py position in the within the display's bounds. If display_index is None (the default), then it is assumed the dx,dy value is for the display index specified for the display configured with ioHub. If display_index is not None, then that display index is used in the computation. If the display_index matches the ioHub enable Display devices index, then the method converts from the dx,dy value (which would be in the Display's coordinate / unit space type) to the pixel position within the displays bounds, factoring in the origin specified in the Display device configuration. If the display_index does not match the ioHub Display device that is being used, then dx,dy == the output x,y value. Args: display_index (int or None): the display index the dx,dy value should be relative to. None == use the currently enabled ioHub Display device's index. Returns: tuple: (px,py), the mapped pixel position based on the 'logic' noted in the description of the method. """ if self._coord2pix: return self._coord2pix(self, cx, cy, display_index) return 0, 0 @classmethod def _getComputerDisplayRuntimeInfoList(cls): """ Returns a list of dictionaries containing run-time determined settings for each active computer display; based on querying the video card settings. The keys of each dict are: #. index: see getIndex(). #. pixel_width: the horizontal pixel resolution of the Display. #. pixel_height: the vertical pixel resolution of the Display. #. pixel_resolution: pixel_width,pixel_height #. bounds: see getBounds() #. retrace_rate: The vertical retrace rate of the Display in Hz., as reported by the OS. #. bits_per_pixel: Number if bits being used to represent all channels of a pixel by the OS. #. primary: True if the current Monitor is also the primary monitor reported by the OS. The length of the list will equal getDisplayCount(). Args: None Returns: list: Each element being a dict of run-time attributes for the associated display index; determined when the Display device was created. """ return cls._computer_display_runtime_info_list @classmethod def _getConfigurationByIndex(cls, display_index): """Returns full configuration dictionary for the Display device created with the specified display_index (called device_number in the device configuration settings). Args: display_index (int): display number to return the configuration dictionary for. Returns: dict: The configuration settings used to create the ioHub Display Device instance. """ if display_index is None or display_index < 0: return None for d in cls._getEnabledDisplays(): if d.getConfiguration()['device_number'] == display_index: return d return None @classmethod def _getRuntimeInfoByIndex(cls, display_index): """ Returns a dictionary containing run-time determined settings for the display that has the associated display_index. Run-time settings are based on querying the video card settings of the system. The keys of the dict are: #. index: see getIndex(). #. pixel_width: the horizontal pixel resolution of the Display. #. pixel_height: the vertical pixel resolution of the Display. #. pixel_resolution: pixel_width,pixel_height #. bounds: see getBounds() #. retrace_rate: The vertical retrace rate of the Display in Hz., as reported by the OS. #. bits_per_pixel: Number if bits being used to represent all channels of a pixel by the OS. #. primary: True if the current Monitor is also the primary monitor reported by the OS. Args: display_index (int): The index of the display to get run-time settings for. Valid display indexes are 0 - N-1, where N is the number of active physically connected displays of the computer in use. Returns: dict: run-time attributes of display that has index display_index. """ if (display_index is None or display_index < 0 or display_index >= cls.getDisplayCount()): return None for i in cls._computer_display_runtime_info_list: if i['index'] == display_index: return i return None @classmethod def _getDisplayIndexForNativePixelPosition(cls, pixel_pos): """Returns the index of the display that the native OS pixel position would fall within, based on the bounds information that ioHub has for each active computer display. Args: pixel_pos (tuple): the native x,y position to query the display index of. Returns: int: The index of the display that the pixel_pos falls within based on each display's bounds. """ px, py = pixel_pos for d in cls._getComputerDisplayRuntimeInfoList(): left, top, right, bottom = d['bounds'] if (px >= left and px < right) and (py >= top and py < bottom): return d['index'] return -1 @classmethod def _getEnabledDisplayCount(cls): """Returns the number of Display Device instances that the ioHub Server has been informed about. Currently, only one Display instance can be created, representing any of the computer's physical active displays. This display will be used to create the full screen window used for stimulus presentation. Args: None Returns: int: ioHub Display Device count. Currently limited to 1. """ return len(cls._enabled_display_instances) @classmethod def _getEnabledDisplays(cls): return cls._enabled_display_instances @classmethod def _createAllRuntimeInfoDicts(cls): runtime_info_list = [] try: default_screen = pyglet.canvas.get_display().get_default_screen() dx, dy = default_screen.x, default_screen.y dw, dh = default_screen.width, default_screen.height dbounds = (dx, dy, dx + dw, dy + dh) pyglet_screens = pyglet.canvas.get_display().get_screens() display_count = len(pyglet_screens) for i in range(display_count): d = pyglet_screens[i] mode = d.get_mode() x, y, w, h = d.x, d.y, d.width, d.height runtime_info = dict() runtime_info['index'] = i runtime_info['pixel_width'] = w runtime_info['pixel_height'] = h runtime_info['bounds'] = (x, y, x + w, y + h) runtime_info['primary'] = runtime_info['bounds'] == dbounds if mode: rate = mode.rate if rate == 0.0: rate = 60 runtime_info['retrace_rate'] = rate runtime_info['bits_per_pixel'] = mode.depth if mode and mode.width > 0 and mode.height > 0: runtime_info['pixel_resolution'] = mode.width, mode.height else: runtime_info['retrace_rate'] = 60 runtime_info['bits_per_pixel'] = 32 runtime_info['pixel_resolution'] = w, h runtime_info_list.append(runtime_info) return runtime_info_list except Exception: printExceptionDetailsToStdErr() def _addRuntimeInfoToDisplayConfig(self): if self not in Display._enabled_display_instances: Display._enabled_display_instances.append(self) display_config = self.getConfiguration() runtime_info = display_config.get('runtime_info', None) if runtime_info is None: runtime_info = self._getRuntimeInfoByIndex(self.device_number) display_config['runtime_info'] = runtime_info self._createPsychopyCalibrationFile() pixel_width = runtime_info['pixel_width'] pixel_height = runtime_info['pixel_height'] phys_width = display_config['physical_dimensions']['width'] phys_height = display_config['physical_dimensions']['height'] phys_unit_type = display_config['physical_dimensions']['unit_type'] # add pixels_per_degree to runtime info try: from psychopy import misc # math.tan(math.radians(0.5))*2.0*viewing_distance*pixel_width/phys_width ppd_x = misc.deg2pix(1.0, self._psychopy_monitor) # math.tan(math.radians(0.5))*2.0*viewing_distance*pixel_height/phys_height ppd_y = misc.deg2pix(1.0, self._psychopy_monitor) runtime_info['pixels_per_degree'] = ppd_x, ppd_y except ImportError as e: pass self. _calculateCoordMappingFunctions( pixel_width, pixel_height, phys_unit_type, phys_width, phys_height) left, top, right, bottom = runtime_info['bounds'] coord_left, coord_top = self._pixel2DisplayCoord( left, top, self.device_number) coord_right, coord_bottom = self._pixel2DisplayCoord( right, bottom, self.device_number) runtime_info[ 'coordinate_bounds'] = coord_left, coord_top, coord_right, coord_bottom def _calculateCoordMappingFunctions( self, pixel_width, pixel_height, phys_unit_type, phys_width, phys_height): ''' For the screen index the full screen psychopy window is created over, this function maps from psychopy coord space (pix, norm, deg, all with center = 0,0) to system pix position. For any other screen indices, mapping is not done, so x_in, y_in == x_out, y_out. ''' coord_type = self.getCoordinateType() if coord_type in Display._coord_type_mappings: coord_type = Display._coord_type_mappings[coord_type] elif coord_type is None: print2err(' *** iohub warning: Display / Monitor unit type has not been set.') return else: print2err(' *** iohub error: Unknown Display / Monitor coordinate type: {0}'.format(coord_type)) return self._pix2coord = None # For now, use psychopy unit conversions so that drawing positions match # device positions exactly l, t, r, b = self.getBounds() w = r - l h = b - t def display2psychopyPix(x, y): x = x - l y = y - t return (x - w / 2), -y + h / 2 def psychopy2displayPix(cx, cy): return l + (cx + w / 2), b - (cy + h / 2) if coord_type == 'pix': def pix2coord(self, x, y, display_index=None): if display_index == self.getIndex(): return display2psychopyPix(x, y) return x, y self._pix2coord = pix2coord def coord2pix(self, cx, cy, display_index=None): if display_index == self.getIndex(): return psychopy2displayPix(cx, cy) return cx, cy self._coord2pix = coord2pix elif coord_type == 'norm': def pix2ncoord(self, x, y, display_index=None): #print2err('Display {0} bounds: {1}'.format(display_index,self.getBounds())) if display_index == self.getIndex(): ppx, ppy = display2psychopyPix(x, y) return ppx / ((r - l) / 2.0), ppy / ((b - t) / 2.0) return x, y self._pix2coord = pix2ncoord def ncoord2pix(self, nx, ny, display_index=None): if display_index == self.getIndex(): return psychopy2displayPix( nx * ((r - l) / 2.0), ny * ((b - t) / 2.0)) return nx, ny self._coord2pix = ncoord2pix if self._pix2coord is None: try: from psychopy import misc if coord_type == 'cm': def pix2cmcoord(self, x, y, display_index=None): #print2err('Display {0} bounds: {1}'.format(display_index,self.getBounds())) if display_index == self.getIndex(): ppx, ppy = display2psychopyPix(x, y) return misc.pix2cm( ppx, self._psychopy_monitor), misc.pix2cm( ppy, self._psychopy_monitor) return x, y self._pix2coord = pix2cmcoord def cmcoord2pix(self, cx, cy, display_index=None): if display_index == self.getIndex(): return psychopy2displayPix( misc.cm2pix( cx, self._psychopy_monitor), misc.cm2pix( cy, self._psychopy_monitor)) return cx, cy self._coord2pix = cmcoord2pix elif coord_type == 'height': def pix2heightcoord(self, x, y, display_index=None): if display_index == self.getIndex(): ppx, ppy = display2psychopyPix(x, y) return ppx / h, ppy / h return x, y self._pix2coord = pix2heightcoord def height2pix(self, x, y, display_index=None): if display_index == self.getIndex(): if False: #TODO: Deal with win.useRetina when we don't have a win. x = x * h / 2.0 y = y * h / 2.0 else: x = x * h y = y * h return psychopy2displayPix(x, y) return x, y self._coord2pix = height2pix elif coord_type == 'deg': def pix2degcoord(self, x, y, display_index=None): if display_index == self.getIndex(): ppx, ppy = display2psychopyPix(x, y) return misc.pix2deg( ppx, self._psychopy_monitor), misc.pix2deg( ppy, self._psychopy_monitor) return x, y self._pix2coord = pix2degcoord def degcoord2pix(self, degx, degy, display_index=None): if display_index == self.getIndex(): return psychopy2displayPix( misc.deg2pix( degx, self._psychopy_monitor), misc.cm2pix( degy, self._psychopy_monitor)) return degx, degy self._coord2pix = degcoord2pix except: print2err('Error during _calculateCoordMappingFunctions') printExceptionDetailsToStdErr() def _createPsychopyCalibrationFile(self): display_config = self.getConfiguration() override_using_psycho_settings = display_config.get( 'override_using_psycho_settings', False) psychopy_monitor_name = display_config.get( 'psychopy_monitor_name', None) if psychopy_monitor_name is None or psychopy_monitor_name == 'None': return False from psychopy import monitors existing_monitors = monitors.getAllMonitors() psychoMonitor = None override = override_using_psycho_settings is True if override and psychopy_monitor_name in existing_monitors: psychoMonitor = monitors.Monitor(psychopy_monitor_name) px, py = self.getPixelResolution() mwidth = psychoMonitor.getWidth() * 10.0 aspect_ratio = px / float(py) mheight = mwidth / aspect_ratio display_config['physical_dimensions']['width'] = mwidth display_config['physical_dimensions']['height'] = mheight display_config['physical_dimensions']['unit_type'] = 'mm' display_config['default_eye_distance'][ 'surface_center'] = psychoMonitor.getDistance() * 10.0 display_config['default_eye_distance']['unit_type'] = 'mm' else: stim_area = display_config.get('physical_dimensions') dwidth = stim_area['width'] # switch from mm to cm if required dw_unit_type = stim_area['unit_type'] if dw_unit_type == 'mm': dwidth = dwidth / 10.0 ddist = self.getDefaultEyeDistance() unit_type = self.getConfiguration()['default_eye_distance']\ ['unit_type'] # switch from mm to cm if required if unit_type == 'mm': ddist = ddist / 10.0 psychoMonitor = monitors.Monitor( psychopy_monitor_name, width=dwidth, distance=ddist, gamma=1.0) psychoMonitor.setSizePix(list(self.getPixelResolution())) psychoMonitor.save() self._psychopy_monitor = psychoMonitor return True def _close(self): Device._close(self)
30,576
Python
.py
604
38.180464
355
0.604267
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,706
__init__.py
psychopy_psychopy/psychopy/iohub/devices/experiment/__init__.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). import numpy as N from .. import Device, DeviceEvent, Computer, Device from ...constants import DeviceConstants, EventConstants currentSec = Computer.getTime class Experiment(Device): """ The Experiment class represents a *virtual* device ( the Python run-time within the PsychoPy Process ), and is unique in that it is the *client* of the ioHub Event Monitoring Framework, but can also generate events itself that are registered with the ioHub process. The Experiment Device supports the creation of general purpose MessageEvent's, which can effectively hold any string up to 128 characters in length. Experiment Message events can be sent to the ioHub Server at any time, and are useful for creating stimulus onset or offset notifications, or other experiment events of interest that should be associated with events from other devices for post hoc analysis of the experiments event steam using the ioDataStore. The Experiment Device also support LogEvents, which result in the log text sent in the event being saved in both the PsychoPy logging module file(s) that have been defined, as well as in the ioHub DataStore. The ioHub Process itself actually uses the LogEvent type to log status and debugging related information to the DataStore and your log files if the log level accepts DEBUG messages. """ EVENT_CLASS_NAMES = ['MessageEvent', 'LogEvent'] DEVICE_TYPE_ID = DeviceConstants.EXPERIMENT DEVICE_TYPE_STRING = 'EXPERIMENT' __slots__ = [ 'critical', 'fatal', 'error', 'warning', 'warn', 'data', 'exp', 'info', 'debug'] def __init__(self, *args, **kwargs): Device.__init__(self, *args, **kwargs['dconfig']) self.critical = lambda text, ltime: self.log( text, LogEvent.CRITICAL, ltime) self.fatal = self.critical self.error = lambda text, ltime: self.log(text, LogEvent.ERROR, ltime) self.warning = lambda text, ltime: self.log( self, text, LogEvent.WARNING, ltime) self.warn = self.warning self.data = lambda text, ltime: self.log(text, LogEvent.DATA, ltime) self.exp = lambda text, ltime: self.log(text, LogEvent.EXP, ltime) self.info = lambda text, ltime: self.log(text, LogEvent.INFO, ltime) self.debug = lambda text, ltime: self.log(text, LogEvent.DEBUG, ltime) def _nativeEventCallback(self, native_event_data): if self.isReportingEvents(): notifiedTime = currentSec() if isinstance(native_event_data, tuple): native_event_data = list(native_event_data) native_event_data[ DeviceEvent.EVENT_ID_INDEX] = Device._getNextEventID() # set logged time of event native_event_data[ DeviceEvent.EVENT_LOGGED_TIME_INDEX] = notifiedTime native_event_data[DeviceEvent.EVENT_DELAY_INDEX] = native_event_data[ DeviceEvent.EVENT_LOGGED_TIME_INDEX] - native_event_data[DeviceEvent.EVENT_DEVICE_TIME_INDEX] native_event_data[ DeviceEvent.EVENT_HUB_TIME_INDEX] = native_event_data[ DeviceEvent.EVENT_DEVICE_TIME_INDEX] self._addNativeEventToBuffer(native_event_data) self._last_callback_time = notifiedTime def log(self, text, level=None, log_time=None): self._nativeEventCallback( LogEvent.create( text, level, log_time=log_time)) def _close(self): Device._close(self) ######### Experiment Events ########### class MessageEvent(DeviceEvent): """A MessageEvent can be created and sent to the ioHub to record important marker times during the experiment; for example, when key display changes occur, or when events related to devices not supported by the ioHub have happened, or simply information about the experiment you want to store in the ioDataStore along with all the other event data. Since the PsychoPy Process can access the same time base that is used by the ioHub Process, when you create a Message Event you can time stamp it at the time of MessageEvent creation, or with the result of a previous call to one of the ioHub time related methods. This makes experiment messages extremely accurate temporally when related to other events times saved to the ioDataSore. Event Type ID: EventConstants.MESSAGE Event Type String: 'MESSAGE' """ PARENT_DEVICE = Experiment EVENT_TYPE_ID = EventConstants.MESSAGE EVENT_TYPE_STRING = 'MESSAGE' IOHUB_DATA_TABLE = EVENT_TYPE_STRING _newDataTypes = [ ('msg_offset', N.float32), ('category','|S32'), ('text', '|S128') ] __slots__ = [e[0] for e in _newDataTypes] def __init__(self, *args, **kwargs): #: The text attribute is used to hold the actual 'content' of the message. #: The text attribute string can not be more than 128 characters in length. #: String type self.text = None #: The category attribute is a 0 - 32 long string used as a 'group' or 'category' #: code that can be assigned to messages. The category attribute may be useful #: for grouping messages into categories or types when retrieving them for analysis #: by assigning the same prix string to related Message Event types. #: String type. self.category = None #: The msg_offset attribute can be used in cases where the Experiment Message #: Evenet needs to be sent *before* or *after* the time the actual event occurred. #: msg offset should be in sec.msec format and in general can be calculated as: #: #: msg_offset=actual_event_iohub_time - iohub_message_time #: #: where actual_event_iohub_time is the time the event occurred that is being #: represented by the Message event; and iohub_message_time is either the #: time provided to the Experiment Message creation methods to be used as the #: Message time stamp, or is the time that the Message Event actually requested the #: current time if no message time was provided. #: Both times must be read from Computer.getTime() or one of it's method aliases. #: Float type. self.msg_offset = None DeviceEvent.__init__(self, *args, **kwargs) @staticmethod def _createAsList( text, category='', msg_offset=0.0, sec_time=None, set_event_id=None): csec = currentSec() if set_event_id is None: set_event_id = Computer.is_iohub_process if sec_time is not None: csec = sec_time event_num = 0 if set_event_id: event_num = Device._getNextEventID() return (0, 0, 0, event_num, MessageEvent.EVENT_TYPE_ID, csec, 0, 0, 0.0, 0.0, 0, msg_offset, category, text) class LogEvent(DeviceEvent): """A LogEvent creates an entry in the ioHub dataStore logging table. If psychopy is available, it also sends the LogEvent to the Experiment Process and it is entered into the psychopy.logging module. The LogEvent is unique in that instances can be created by the ioHub Server or the Experiment Process psychopy script. In either case, the log entry is entered in the psychopy.logging module and the DataStore log table (if the datastore is enabled). It is **critical** that log events created by the psychopy script use the core.getTime() method to provide a LogEvent with the time of the logged event, or do not specify a time, in which case the logging module uses the chared time base by default. Event Type ID: EventConstants.LOG Event Type String: 'LOG' """ _psychopyAvailable = False _levelNames = dict() try: from psychopy.logging import _levelNames _psychopyAvailable = True for lln, llv in _levelNames.items(): if isinstance(lln, str): _levelNames[lln] = llv _levelNames[llv] = lln except Exception: CRITICAL = 50 FATAL = CRITICAL ERROR = 40 WARNING = 30 WARN = WARNING DATA = 25 EXP = 22 INFO = 20 DEBUG = 10 NOTSET = 0 _levelNames = { CRITICAL: 'CRITICAL', ERROR: 'ERROR', DATA: 'DATA', EXP: 'EXP', WARNING: 'WARNING', INFO: 'INFO', DEBUG: 'DEBUG', NOTSET: 'NOTSET', 'CRITICAL': CRITICAL, 'ERROR': ERROR, 'DATA': DATA, 'EXP': EXP, 'WARN': WARNING, 'WARNING': WARNING, 'INFO': INFO, 'DEBUG': DEBUG, 'NOTSET': NOTSET } PARENT_DEVICE = Experiment EVENT_TYPE_ID = EventConstants.LOG EVENT_TYPE_STRING = 'LOG' IOHUB_DATA_TABLE = EVENT_TYPE_STRING _newDataTypes = [ ('log_level', N.uint8), ('text', '|S128') ] __slots__ = [e[0] for e in _newDataTypes] def __init__(self, *args, **kwargs): #: The text attribute is used to hold the actual 'content' of the message. #: The text attribute string can not be more than 128 characters in length. #: String type self.text = None #: The log level to set the log event at. If psychopy is available, #: valid log levels match the *predefined* logging levels. Otherwise #: the following log levels are available (which match the predefined #: psychopy 2.76 logging settings): #: #: * CRITICAL = 50 #: * FATAL = CRITICAL #: * ERROR = 40 #: * WARNING = 30 #: * WARN = WARNING #: * DATA = 25 #: * EXP = 22 #: * INFO = 20 #: * DEBUG = 10 #: * NOTSET = 0 #: #: The int defined value can be used, or a string version of the #: log level name, for example specifying "WARNING" is equal to #: specifying a log level of LogEvent.WARNING or 30. #: Default: NOTSET #: String or Int type. self.log_level = None DeviceEvent.__init__(self, *args, **kwargs) @classmethod def create(cls, msg, level=None, log_time=None): created_time = currentSec() if log_time is None: log_time = created_time if level is None or level not in cls._levelNames: level = cls.DEBUG elif isinstance(level, str): level = cls._levelNames[level] return cls._createAsList(msg, level, created_time, log_time) @staticmethod def _createAsList(text, log_level, created_time, log_time): return (0, 0, 0, 0, LogEvent.EVENT_TYPE_ID, created_time, 0, 0, 0.0, 0.0, 0, log_level, text) @classmethod def _convertFields(cls, event_value_list): log_level_value_index = cls.CLASS_ATTRIBUTE_NAMES.index('log_level') event_value_list[log_level_value_index] = cls._levelNames.get( event_value_list[log_level_value_index], 'UNKNOWN') @classmethod def createEventAsDict(cls, values): cls._convertFields(values) return dict(zip(cls.CLASS_ATTRIBUTE_NAMES, values)) @classmethod def createEventAsNamedTuple(cls, valueList): cls._convertFields(valueList) return cls.namedTupleClass(*valueList) if not hasattr(LogEvent, 'CRITICAL'): for lln, llv in LogEvent._levelNames.items(): if isinstance(lln, str): setattr(LogEvent, lln, llv)
12,020
Python
.py
267
36.543071
109
0.639518
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,707
__init__.py
psychopy_psychopy/psychopy/iohub/devices/serial/__init__.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). import serial import sys import numpy as N import struct from ... import EXP_SCRIPT_DIRECTORY from .. import Device, DeviceEvent, Computer from ...errors import print2err, printExceptionDetailsToStdErr from ...constants import DeviceConstants, EventConstants getTime = Computer.getTime class Serial(Device): """A general purpose serial input interface device. Configuration options are used to define how the serial input data should be parsed, and what conditions create a serial input event to be generated. """ _bytesizes = { 5: serial.FIVEBITS, 6: serial.SIXBITS, 7: serial.SEVENBITS, 8: serial.EIGHTBITS, } _parities = { 'NONE': serial.PARITY_NONE, 'EVEN': serial.PARITY_EVEN, 'ODD': serial.PARITY_ODD, 'MARK': serial.PARITY_MARK, 'SPACE': serial.PARITY_SPACE } _stopbits = { 'ONE': serial.STOPBITS_ONE, 'ONE_AND_HALF': serial.STOPBITS_ONE_POINT_FIVE, 'TWO': serial.STOPBITS_TWO } DEVICE_TIMEBASE_TO_SEC = 1.0 _newDataTypes = [('port', '|S32'), ('baud', '|S32'), ] EVENT_CLASS_NAMES = ['SerialInputEvent', 'SerialByteChangeEvent'] DEVICE_TYPE_ID = DeviceConstants.SERIAL DEVICE_TYPE_STRING = 'SERIAL' _serial_slots = [ 'port', 'baud', 'bytesize', 'parity', 'stopbits', '_serial', '_timeout', '_rx_buffer', '_parser_config', '_parser_state', '_event_count', '_byte_diff_mode', '_custom_parser', '_custom_parser_kwargs' ] __slots__ = [e for e in _serial_slots] def __init__(self, *args, **kwargs): Device.__init__(self, *args, **kwargs['dconfig']) self._serial = None self.port = self.getConfiguration().get('port') if self.port.lower() == 'auto': pports = self.findPorts() if pports: self.port = pports[0] if len(pports) > 1: print2err( 'Warning: Serial device port configuration set ' "to 'auto'.\nMultiple serial ports found:\n", pports, '\n** Using port ', self.port ) self.baud = self.getConfiguration().get('baud') self.bytesize = self._bytesizes[ self.getConfiguration().get('bytesize')] self.parity = self._parities[self.getConfiguration().get('parity')] self.stopbits = self._stopbits[self.getConfiguration().get('stopbits')] self._parser_config = self.getConfiguration().get('event_parser') self._byte_diff_mode = None self._custom_parser = None self._custom_parser_kwargs = {} custom_parser_func_str = self._parser_config.get('parser_function') if custom_parser_func_str: # print2err("CUSTOM SERIAL PARSER FUNC STR: ", custom_parser_func_str) # Function referenced by string must have the following signature: # # evt_list = someCustomParserName(read_time, rx_data, parser_state, **kwargs) # # where: # read_time: The time when the serial device read() returned # with the new rx_data. # rx_data: The new serial data received. Any buffering of data # across function calls must be done by the function # logic itself. parser_state could be used to hold # such a buffer if needed. # parser_state: A dict which can be used by the function to # store any values that need to be accessed # across multiple calls to the function. The dict # is initially empty. # kwargs: The parser_kwargs preference dict read from # the event_parser preferences; or an empty dict if # parser_kwargs was not found. # # The function must return a list like object, used to provide ioHub # with any new serial events that have been found. # Each element of the list must be a dict like object, representing # a single serial device event found by the parsing function. # A dict can contain the following key, value pairs: # data: The string containing the parsed event data. (REQUIRED) # time: The timestamp for the event (Optional). If not provided, # the return time of the latest serial.read() is used. # Each event returned by the function generates a SerialInputEvent # with the data field = the dict data value. import importlib import sys try: #print2err("EXP_SCRIPT_DIRECTORY: ",EXP_SCRIPT_DIRECTORY) if EXP_SCRIPT_DIRECTORY not in sys.path: sys.path.append(EXP_SCRIPT_DIRECTORY) mod_name, func_name = custom_parser_func_str.rsplit('.', 1) mod = importlib.import_module(mod_name) self._custom_parser = getattr(mod, func_name) except Exception: print2err( 'ioHub Serial Device Error: could not load ' 'custom_parser function: ', custom_parser_func_str) printExceptionDetailsToStdErr() if self._custom_parser: self._custom_parser_kwargs = self._parser_config.get( 'parser_kwargs', {}) else: self._byte_diff_mode = self._parser_config.get('byte_diff') if self._byte_diff_mode: self._rx_buffer = None else: self._resetParserState() self._rx_buffer = '' self._event_count = 0 self._timeout = None self._serial = None self.setConnectionState(True) @classmethod def findPorts(cls): """Finds serial ports that are available.""" import os available = [] if os.name == 'nt': # Windows for i in range(1, 256): try: sport = 'COM' + str(i) s = serial.Serial(sport) available.append(sport) s.close() except serial.SerialException: pass else: # Mac / Linux from serial.tools import list_ports available = [port[0] for port in list_ports.comports()] if len(available) < 1: print2err('Error: unable to find any serial ports on the computer.') return [] return available def _resetParserState(self): parser_config = self._parser_config if parser_config: if self._custom_parser: self._parser_state = dict() return self._parser_state = dict(parsed_event='') parser_state = self._parser_state fixed_length = parser_config.setdefault('fixed_length', None) if fixed_length: parser_state['bytes_needed'] = fixed_length else: parser_state['bytes_needed'] = 0 prefix = parser_config.setdefault('prefix', None) if prefix == r'\n': parser_config['prefix'] = '\n' elif prefix == r'\t': parser_config['prefix'] = '\t' elif prefix == r'\r': parser_config['prefix'] = '\r' elif prefix == r'\r\n': parser_config['prefix'] = '\r\n' if prefix: parser_state['prefix_found'] = False else: parser_state['prefix_found'] = True delimiter = parser_config.setdefault('delimiter', None) if delimiter == r'\n': parser_config['delimiter'] = '\n' elif delimiter == r'\t': parser_config['delimiter'] = '\t' elif delimiter == r'\r': parser_config['delimiter'] = '\r' elif delimiter == r'\r\n': parser_config['delimiter'] = '\r\n' if delimiter: parser_state['delimiter_found'] = False else: parser_state['delimiter_found'] = True def setConnectionState(self, enable): if enable is True: if self._serial is None: self._connectSerial() elif enable is False: if self._serial: self._serial.close() return self.isConnected() def isConnected(self): return self._serial is not None def getDeviceTime(self): return getTime() def getSecTime(self): """Returns current device time in sec.msec format. Relies on a functioning getDeviceTime() method. """ return self.getTime() def enableEventReporting(self, enabled=True): """ Specifies if the device should be reporting events to the ioHub Process (enabled=True) or whether the device should stop reporting events to the ioHub Process (enabled=False). Args: enabled (bool): True (default) == Start to report device events to the ioHub Process. False == Stop Reporting Events to the ioHub Process. Most Device types automatically start sending events to the ioHUb Process, however some devices like the EyeTracker and AnlogInput device's do not. The setting to control this behavior is 'auto_report_events' Returns: bool: The current reporting state. """ if enabled and not self.isReportingEvents(): if not self.isConnected(): self.setConnectionState(True) self.flushInput() if self._byte_diff_mode: self._rx_buffer = None else: self._rx_buffer = '' self._event_count = 0 return Device.enableEventReporting(self, enabled) def isReportingEvents(self): """Returns whether a Device is currently reporting events to the ioHub Process. Args: None Returns: (bool): Current reporting state. """ return Device.isReportingEvents(self) def _connectSerial(self): self._serial = serial.Serial( self.port, self.baud, timeout=self._timeout) if self._serial is None: raise ValueError( 'Error: Serial Port Connection Failed: %d' % (self.port)) self._serial.flushInput() inBytes = self._serial.inWaiting() if inBytes > 0: self._serial.read(inBytes) # empty buffer and discard if self._byte_diff_mode: self._rx_buffer = None else: self._rx_buffer = '' def flushInput(self): self._serial.flushInput() def flushOutput(self): self._serial.flush() def write(self, bytestring): if type(bytestring) != bytes: bytestring = bytestring.encode('utf-8') tx_count = self._serial.write(bytestring) self._serial.flush() return tx_count def read(self): returned = self._serial.read(self._serial.inWaiting()) returned = returned.decode('utf-8') return returned def closeSerial(self): if self._serial: self._serial.close() self._serial = None return True return False def close(self): try: self.flushInput() except Exception: pass try: self.closeSerial() except Exception: pass self._serial_port = None def _createSerialEvent(self, logged_time, read_time, event_data): self._event_count += 1 confidence_interval = read_time - self._last_poll_time elist = [0, 0, 0, Device._getNextEventID(), EventConstants.SERIAL_INPUT, read_time, logged_time, read_time, confidence_interval, 0.0, 0, self.port, event_data ] self._addNativeEventToBuffer(elist) self._resetParserState() def _createMultiByteSerialEvent(self, logged_time, read_time): self._event_count += 1 confidence_interval = read_time - self._last_poll_time elist = [0, 0, 0, Device._getNextEventID(), EventConstants.SERIAL_INPUT, read_time, logged_time, read_time, confidence_interval, 0.0, 0, self.port, self._parser_state['parsed_event'] ] self._addNativeEventToBuffer(elist) self._resetParserState() def _createByteChangeSerialEvent( self, logged_time, read_time, prev_byte, new_byte): self._event_count += 1 confidence_interval = read_time - self._last_poll_time elist = [0, 0, 0, Device._getNextEventID(), EventConstants.SERIAL_BYTE_CHANGE, read_time, logged_time, read_time, confidence_interval, 0.0, 0, self.port, ord(prev_byte), ord(new_byte) ] self._addNativeEventToBuffer(elist) def _poll(self): try: logged_time = getTime() if not self.isReportingEvents(): self._last_poll_time = logged_time return False if self.isConnected(): if self._custom_parser: parser_state = self._parser_state newrx = self.read() read_time = getTime() if newrx: try: serial_events = self._custom_parser( read_time, newrx, parser_state, **self._custom_parser_kwargs) for evt in serial_events: if isinstance(evt, dict): evt_time = evt.get('time', read_time) evt_data = evt.get( 'data', 'NO DATA FIELD IN EVENT DICT.') self._createSerialEvent( logged_time, evt_time, evt_data) else: print2err( "ioHub Serial Device Error: Events returned from custom parser must be dict's. Skipping: ", str(evt)) except Exception: print2err( 'ioHub Serial Device Error: Exception during parsing function call.') import traceback import sys traceback.print_exc(file=sys.stderr) print2err('---') elif self._byte_diff_mode: rx = self.read() read_time = getTime() for c in rx: if self._rx_buffer is not None and c != self._rx_buffer: self._createByteChangeSerialEvent(logged_time, read_time, self._rx_buffer, c) self._rx_buffer = c else: parser_state = self._parser_state rx_buffer = self._rx_buffer + self.read() read_time = getTime() prefix = self._parser_config['prefix'] delimiter = self._parser_config['delimiter'] if parser_state['prefix_found'] is False: if prefix and rx_buffer and len( rx_buffer) >= len(prefix): pindex = rx_buffer.find(prefix) if pindex >= 0: rx_buffer = rx_buffer[pindex + len(prefix):] parser_state['prefix_found'] = True if parser_state['delimiter_found'] is False: if delimiter and self._rx_buffer and len( rx_buffer) >= len(delimiter): dindex = rx_buffer.find(delimiter) if dindex >= 0: parser_state['delimiter_found'] = True sindex = dindex eindex = dindex + len(delimiter) parser_state[ 'parsed_event'] += rx_buffer[:sindex] if len(rx_buffer) > eindex: rx_buffer = rx_buffer[eindex:] else: rx_buffer = '' self._rx_buffer = rx_buffer self._createMultiByteSerialEvent( logged_time, read_time) return True if parser_state['bytes_needed'] > 0 and rx_buffer: rxlen = len(rx_buffer) #takebytes = rxlen - parser_state['bytes_needed'] if rxlen > parser_state['bytes_needed']: parser_state[ 'parsed_event'] += rx_buffer[:parser_state['bytes_needed']] parser_state['bytes_needed'] = 0 rx_buffer = rx_buffer[ parser_state['bytes_needed']:] else: parser_state['parsed_event'] += rx_buffer parser_state['bytes_needed'] -= rxlen rx_buffer = '' if parser_state['bytes_needed'] == 0: self._rx_buffer = rx_buffer self._createMultiByteSerialEvent( logged_time, read_time) return True self._rx_buffer = rx_buffer else: read_time = logged_time self._last_poll_time = read_time return True except Exception as e: print2err('--------------------------------') print2err('ERROR in Serial._poll: ', e) printExceptionDetailsToStdErr() print2err('---------------------') def _close(self): self.setConnectionState(False) Device._close(self) class Pstbox(Serial): """Provides convenient access to the PST Serial Response Box.""" EVENT_CLASS_NAMES = ['PstboxButtonEvent', ] DEVICE_TYPE_ID = DeviceConstants.PSTBOX DEVICE_TYPE_STRING = 'PSTBOX' # Only add new attributes for the subclass, the device metaclass # pulls them together. _serial_slots = [ '_nlamps', '_lamp_state', '_streaming_state', '_button_query_state', '_state', '_button_bytes', '_nbuttons' ] __slots__ = [e for e in _serial_slots] def __init__(self, *args, **kwargs): Serial.__init__(self, *args, **kwargs) self._nbuttons = 7 # Buttons 0--4, from left to right: # [1, 2, 4, 8, 16] self._button_bytes = 2**N.arange(self._nbuttons, dtype='uint8') self._nlamps = 5 self._lamp_state = N.repeat(False, self._nlamps) self._streaming_state = True self._button_query_state = True update_lamp_state = True self._state = N.r_[ self._lamp_state, self._button_query_state, update_lamp_state, self._streaming_state ] self._update_state() def _update_state(self): update_lamp_state = True # `state` is an array of bools. state = N.r_[ self._lamp_state, self._button_query_state, update_lamp_state, self._streaming_state ] # Convert the new state into a bitmask, collapse it into a # single byte and send it to the response box. state_bits = (2**N.arange(8))[state] self.write(struct.pack("B",(N.sum(state_bits)))) # Set the `update lamp` bit to LOW again. state[6] = False self._state = state def getState(self): """Return the current state of the response box. Returns ------- array An array of 8 boolean values will be returned, corresponding to the following properties: - state of lamp 0 (on/off) - state of lamp 1 (on/off) - state of lamp 2 (on/off) - state of lamp 3 (on/off) - state of lamp 4 (on/off) - button query state (on/off) - update lamp state (yes/no) - streaming state (on/off) See Also -------- setState """ return self._state def getLampState(self): """Return the current state of the lamps. Returns ------- array An array of 5 boolean values will be returned, corresponding to the following properties: - state of lamp 0 (on/off) - state of lamp 1 (on/off) - state of lamp 2 (on/off) - state of lamp 3 (on/off) - state of lamp 4 (on/off) See Also -------- setLampState """ return self._lamp_state def setLampState(self, state): """Change the state of the lamps (on/off). Parameters ---------- state : array_like The requested lamp states, from left to right. `0` or `False` means off, and `1` or `True` means on. This method expects an array of 5 boolean values, each corresponding to the following properties: - state of lamp 0 (on/off) - state of lamp 1 (on/off) - state of lamp 2 (on/off) - state of lamp 3 (on/off) - state of lamp 4 (on/off) See Also -------- getLampState """ if len(state) != self._nlamps: raise ValueError('Please specify a number of states that is ' 'equal to the number of lamps on the ' 'response box.') state = N.array(state).astype('bool') self._lamp_state = state self._update_state() def getStreamingState(self): """Get the current streaming state. Returns ------- bool `True` if the box is streaming data, and `False` otherwise. See Also -------- setStreamingState """ return self._streaming_state def setStreamingState(self, state): """Switch on or off streaming mode. If streaming mode is disabled, the box will not send anything to the computer. Parameters ---------- state : bool ``True`` will enable streaming, ``False`` will disable it. See Also -------- getStreamingState """ self._streaming_state = bool(state) self._update_state() def getButtonQueryState(self): """Get the current button query state. If the box is not querying buttons, no button presses will be reported. Returns ------- bool `True` if the box is streaming data, and `False` otherwise. See Also -------- getButtonQueryState """ return self._button_query_state def setButtonQueryState(self, state): """Switch on or off button querying. Parameters ---------- state : bool ``True`` will enable querying, ``False`` will disable it. See Also -------- getButtonQueryState """ self._button_query_state = bool(state) self._update_state() def _createByteChangeSerialEvent(self, logged_time, read_time, prev_byte, new_byte): self._event_count += 1 confidence_interval = read_time - self._last_poll_time prev_byte = ord(prev_byte) new_byte = ord(new_byte) try: if new_byte != 0: # Button was pressed button = N.where(self._button_bytes == new_byte)[0][0] button_event = 'press' else: # Button was released button = N.where(self._button_bytes == prev_byte)[0][0] button_event = 'release' except Exception: # Handles when data rx does not match either N.where within the try return events = [ 0, 0, 0, Device._getNextEventID(), EventConstants.PSTBOX_BUTTON, read_time, logged_time, read_time, confidence_interval, 0.0, 0, self.port, button, button_event ] self._addNativeEventToBuffer(events) class SerialInputEvent(DeviceEvent): _newDataTypes = [ ('port', '|S32'), ('data', '|S256') ] PARENT_DEVICE = Serial EVENT_TYPE_ID = EventConstants.SERIAL_INPUT EVENT_TYPE_STRING = 'SERIAL_INPUT' IOHUB_DATA_TABLE = EVENT_TYPE_STRING __slots__ = [e[0] for e in _newDataTypes] def __init__(self, *args, **kwargs): DeviceEvent.__init__(self, *args, **kwargs) class SerialByteChangeEvent(DeviceEvent): _newDataTypes = [ ('port', '|S32'), ('prev_byte', N.uint8), ('current_byte', N.uint8) ] PARENT_DEVICE = Serial EVENT_TYPE_ID = EventConstants.SERIAL_BYTE_CHANGE EVENT_TYPE_STRING = 'SERIAL_BYTE_CHANGE' IOHUB_DATA_TABLE = EVENT_TYPE_STRING __slots__ = [e[0] for e in _newDataTypes] def __init__(self, *args, **kwargs): DeviceEvent.__init__(self, *args, **kwargs) class PstboxButtonEvent(DeviceEvent): # Add new fields for PstboxButtonEvent _newDataTypes = [ ('port', '|S32'), # could be needed to identify events # from >1 connected button box; if that is # ever supported. ('button', N.uint8), ('button_event', '|S7') ] PARENT_DEVICE = Pstbox EVENT_TYPE_ID = EventConstants.PSTBOX_BUTTON EVENT_TYPE_STRING = 'PSTBOX_BUTTON' IOHUB_DATA_TABLE = EVENT_TYPE_STRING __slots__ = [e[0] for e in _newDataTypes] def __init__(self, *args, **kwargs): DeviceEvent.__init__(self, *args, **kwargs)
27,548
Python
.py
666
27.938438
360
0.5184
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,708
win32.py
psychopy_psychopy/psychopy/iohub/devices/keyboard/win32.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). try: import pyHook except ImportError: import pyWinhook as pyHook import win32api import ctypes from unicodedata import category as ucategory from . import ioHubKeyboardDevice, psychopy_key_mappings from ...constants import KeyboardConstants, EventConstants from .. import Computer, Device from ...errors import print2err, printExceptionDetailsToStdErr win32_vk = KeyboardConstants._virtualKeyCodes getTime = Computer.getTime jdumps = lambda x: str(x) try: import ujson jdumps = ujson.dumps except Exception: import json jdumps = json.dumps # Map key value when numlock is ON # to value when numlock is OFF. numpad_key_value_mappings = dict(Numpad0='insert', Numpad1='end', Numpad2='down', Numpad3='pagedown', Numpad4='left', Numpad5=' ', Numpad6='right', Numpad7='home', Numpad8='up', Numpad9='pageup', Decimal='delete' ) def updateToPsychopyKeymap(): global numpad_key_value_mappings numpad_key_value_mappings = dict(Numpad0='num_0', Numpad1='num_1', Numpad2='num_2', Numpad3='num_3', Numpad4='num_4', Numpad5='num_5', Numpad6='num_6', Numpad7='num_7', Numpad8='num_8', Numpad9='num_9', Decimal='num_decimal' ) class Keyboard(ioHubKeyboardDevice): _win32_modifier_mapping = { win32_vk.VK_LCONTROL: 'lctrl', win32_vk.VK_RCONTROL: 'rctrl', win32_vk.VK_LSHIFT: 'lshift', win32_vk.VK_RSHIFT: 'rshift', win32_vk.VK_LMENU: 'lalt', win32_vk.VK_RMENU: 'ralt', win32_vk.VK_LWIN: 'lcmd', win32_vk.VK_RWIN: 'rcmd', win32_vk.VK_CAPITAL: 'capslock', win32_vk.VK_NUM_LOCK: 'numlock', win32_vk.VK_SCROLL: 'scrolllock' } __slots__ = ['_user32', '_keyboard_state', '_unichar'] def __init__(self, *args, **kwargs): ioHubKeyboardDevice.__init__(self, *args, **kwargs['dconfig']) self._user32 = ctypes.windll.user32 self._keyboard_state = (ctypes.c_ubyte * 256)() self._unichar = (ctypes.c_wchar * 8)() if self.use_psychopy_keymap: updateToPsychopyKeymap() self.resetKeyAndModState() def resetKeyAndModState(self): for i in range(256): self._keyboard_state[i] = 0 ioHubKeyboardDevice._modifier_value = 0 for stateKeyID in [ win32_vk.VK_SCROLL, win32_vk.VK_NUM_LOCK, win32_vk.VK_CAPITAL]: state = pyHook.GetKeyState(stateKeyID) if state: self._keyboard_state[stateKeyID] = state modKeyName = Keyboard._win32_modifier_mapping.get( stateKeyID, None) mod_value = KeyboardConstants._modifierCodes.getID(modKeyName) ioHubKeyboardDevice._modifier_value += mod_value def _updateKeyMapState(self, event): keyID = event.KeyID is_press = event.Type == EventConstants.KEYBOARD_PRESS if is_press: self._keyboard_state[keyID] = 0x80 else: self._keyboard_state[keyID] = 0 if event.cap_state and ( self._keyboard_state[ win32_vk.VK_CAPITAL] & 1) == 0: self._keyboard_state[win32_vk.VK_CAPITAL] += 1 elif not event.cap_state and (self._keyboard_state[win32_vk.VK_CAPITAL] & 1) == 1: self._keyboard_state[win32_vk.VK_CAPITAL] -= 1 if event.scroll_state and ( self._keyboard_state[ win32_vk.VK_SCROLL] & 1) == 0: self._keyboard_state[win32_vk.VK_SCROLL] += 1 elif not event.scroll_state and (self._keyboard_state[win32_vk.VK_SCROLL] & 1) == 1: self._keyboard_state[win32_vk.VK_SCROLL] -= 1 if event.num_state and ( self._keyboard_state[ win32_vk.VK_NUM_LOCK] & 1) == 0: self._keyboard_state[win32_vk.VK_NUM_LOCK] += 1 elif not event.num_state and (self._keyboard_state[win32_vk.VK_NUM_LOCK] & 1) == 1: self._keyboard_state[win32_vk.VK_NUM_LOCK] -= 1 modKeyName = Keyboard._win32_modifier_mapping.get(keyID, None) if modKeyName: if is_press: if keyID in [win32_vk.VK_LSHIFT, win32_vk.VK_RSHIFT]: self._keyboard_state[win32_vk.VK_SHIFT] = 0x80 elif keyID in [win32_vk.VK_LCONTROL, win32_vk.VK_RCONTROL]: self._keyboard_state[win32_vk.VK_CONTROL] = 0x80 elif keyID in [win32_vk.VK_LMENU, win32_vk.VK_RMENU]: self._keyboard_state[win32_vk.VK_MENU] = 0x80 else: if keyID in [win32_vk.VK_LSHIFT, win32_vk.VK_RSHIFT]: self._keyboard_state[win32_vk.VK_SHIFT] = 0 elif keyID in [win32_vk.VK_LCONTROL, win32_vk.VK_RCONTROL]: self._keyboard_state[win32_vk.VK_CONTROL] = 0 elif keyID in [win32_vk.VK_LMENU, win32_vk.VK_RMENU]: self._keyboard_state[win32_vk.VK_MENU] = 0 return modKeyName def _updateModValue(self, keyID, is_press): modKeyName = Keyboard._win32_modifier_mapping.get(keyID, None) if modKeyName: mod_value = KeyboardConstants._modifierCodes.getID(modKeyName) mod_set = ioHubKeyboardDevice._modifier_value&mod_value == mod_value if keyID not in [win32_vk.VK_CAPITAL, win32_vk.VK_SCROLL, win32_vk.VK_NUM_LOCK]: if is_press and not mod_set: ioHubKeyboardDevice._modifier_value += mod_value elif not is_press and mod_set: ioHubKeyboardDevice._modifier_value -= mod_value else: if is_press: if mod_set: ioHubKeyboardDevice._modifier_value -= mod_value else: ioHubKeyboardDevice._modifier_value += mod_value return ioHubKeyboardDevice._modifier_value def _getKeyCharValue(self, event): key = None char = '' ucat = '' # Get char value # result = self._user32.ToUnicode(event.KeyID, event.ScanCode, ctypes.byref(self._keyboard_state), ctypes.byref(self._unichar), 8, 0) if result > 0: char = self._unichar[result - 1].encode('utf-8') ucat = ucategory(self._unichar[result - 1]) # Get .key value # if event.Key in numpad_key_value_mappings: key = numpad_key_value_mappings[event.Key] elif ucat.lower() != 'cc': prev_shift = self._keyboard_state[win32_vk.VK_SHIFT] prev_numlock = self._keyboard_state[win32_vk.VK_NUM_LOCK] prev_caps = self._keyboard_state[win32_vk.VK_CAPITAL] self._keyboard_state[win32_vk.VK_SHIFT] = 0 self._keyboard_state[win32_vk.VK_NUM_LOCK] = 0 result = self._user32.ToUnicode(event.KeyID, event.ScanCode, ctypes.byref(self._keyboard_state), ctypes.byref(self._unichar), 8, 0) self._keyboard_state[win32_vk.VK_SHIFT] = prev_shift self._keyboard_state[win32_vk.VK_NUM_LOCK] = prev_numlock self._keyboard_state[win32_vk.VK_CAPITAL] = prev_caps if result > 0: key = self._unichar[result - 1].encode('utf-8') if key is None: key = KeyboardConstants._getKeyName(event) if isinstance(key, bytes): key = str(key, 'utf-8') if isinstance(char, bytes): char = str(char, 'utf-8') key = key.lower() # misc. char value cleanup. if key == 'return': char = '\n'.encode('utf-8') elif key in ('escape', 'backspace'): char = '' if Keyboard.use_psychopy_keymap and key in psychopy_key_mappings.keys(): key = psychopy_key_mappings[key] # win32 specific handling of keypad / and - keys if event.Key == 'Subtract': key = 'num_subtract' elif event.Key == 'Divide': key = 'num_divide' return key, char def _evt2json(self, event): return jdumps(dict(Type=event.Type, Time=event.Time, KeyID=event.KeyID, ScanCode=event.ScanCode, Ascii=event.Ascii, flags=event.flags, Key=event.Key, scroll_state=event.scroll_state, num_state=event.num_state, cap_state=event.cap_state)) def _addEventToTestLog(self, event_data): if self._log_events_file is None: import datetime cdate = datetime.datetime.now().strftime('%Y_%m_%d_%H_%M') self._log_events_file = open( 'win32_events_{0}.log'.format(cdate), 'w') self._log_events_file.write(self._evt2json(event_data) + '\n') def _nativeEventCallback(self, event): if self.isReportingEvents(): notifiedTime = getTime() report_system_wide_events = self.getConfiguration().get( 'report_system_wide_events', True) if report_system_wide_events is False: pyglet_window_hnds = self._iohub_server._psychopy_windows.keys() if len( pyglet_window_hnds) > 0 and event.Window not in pyglet_window_hnds: return True event.Type = EventConstants.KEYBOARD_RELEASE if event.Message in [pyHook.HookConstants.WM_KEYDOWN, pyHook.HookConstants.WM_SYSKEYDOWN]: event.Type = EventConstants.KEYBOARD_PRESS self._last_callback_time = notifiedTime event.RepeatCount = 0 key_already_pressed = self._key_states.get(event.KeyID, None) if key_already_pressed and event.Type == EventConstants.KEYBOARD_PRESS: event.RepeatCount = key_already_pressed[1] + 1 if self._report_auto_repeats is False and event.RepeatCount > 0: return True event.Modifiers = 0 event.scroll_state = pyHook.GetKeyState(win32_vk.VK_SCROLL) event.num_state = pyHook.GetKeyState(win32_vk.VK_NUM_LOCK) event.cap_state = pyHook.GetKeyState(win32_vk.VK_CAPITAL) if self.getConfiguration().get('log_events_for_testing', False): self._addEventToTestLog(event) self._addNativeEventToBuffer((notifiedTime, event)) # pyHook require the callback to return True to inform the windows # low level hook functionality to pass the event on. return True def _getIOHubEventObject(self, native_event_data): try: notifiedTime, event = native_event_data is_press = event.Type == EventConstants.KEYBOARD_PRESS keyID = event.KeyID device_time = event.Time / 1000.0 # convert to sec time = notifiedTime # since this is a keyboard device using a callback method, # confidence_interval is not applicable confidence_interval = 0.0 # since this is a keyboard, we 'know' there is a delay, but until # we support setting a delay in the device properties based on # external testing for a given keyboard, we will leave at 0. delay = 0.0 modKeyName = self._updateKeyMapState(event) event.Modifiers = self._updateModValue(keyID, is_press) # Get key and char fields..... if modKeyName: key = modKeyName char = '' else: key, char = self._getKeyCharValue(event) kb_event = [0, 0, 0, # device id (not currently used) Device._getNextEventID(), event.Type, device_time, notifiedTime, time, confidence_interval, delay, 0, event.RepeatCount, event.ScanCode, event.KeyID, 0, key, event.Modifiers, event.Window, char, # .char 0.0, # duration 0 # press_event_id ] ioHubKeyboardDevice._updateKeyboardEventState(self, kb_event, is_press) return kb_event except Exception: printExceptionDetailsToStdErr() def _syncPressedKeyState(self): remove_keys = [] for kid in self._key_states.keys(): if win32api.GetAsyncKeyState(kid) == 0: # Key is no longer pressed, remove it from pressed key dict remove_keys.append(kid) for kid in remove_keys: del self._key_states[kid]
14,343
Python
.py
306
31.545752
92
0.531246
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,709
linux2.py
psychopy_psychopy/psychopy/iohub/devices/keyboard/linux2.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). from . import ioHubKeyboardDevice, psychopy_key_mappings from .. import Computer, Device from ...constants import EventConstants from ...errors import printExceptionDetailsToStdErr, print2err getTime = Computer.getTime NUMLOCK_MODIFIER = 8192 psychopy_numlock_key_mappings = dict() psychopy_numlock_key_mappings['num_end'] = 'num_1' psychopy_numlock_key_mappings['num_down'] = 'num_2' psychopy_numlock_key_mappings['num_page_down'] = 'num_3' psychopy_numlock_key_mappings['num_left'] = 'num_4' psychopy_numlock_key_mappings['num_begin'] = 'num_5' psychopy_numlock_key_mappings['num_right'] = 'num_6' psychopy_numlock_key_mappings['num_home'] = 'num_7' psychopy_numlock_key_mappings['num_up'] = 'num_8' psychopy_numlock_key_mappings['num_page_up'] = 'num_9' psychopy_numlock_key_mappings['num_insert'] = 'num_0' psychopy_numlock_key_mappings['num_delete'] = 'num_decimal' class Keyboard(ioHubKeyboardDevice): event_id_index = None def __init__(self, *args, **kwargs): ioHubKeyboardDevice.__init__(self, *args, **kwargs['dconfig']) if self.event_id_index is None: from . import KeyboardInputEvent Keyboard.auto_repeated_index = KeyboardInputEvent.CLASS_ATTRIBUTE_NAMES.index( 'auto_repeated') Keyboard.key_index = KeyboardInputEvent.CLASS_ATTRIBUTE_NAMES.index( 'key') Keyboard.key_id_index = KeyboardInputEvent.CLASS_ATTRIBUTE_NAMES.index( 'key_id') Keyboard.event_type_index = KeyboardInputEvent.EVENT_TYPE_ID_INDEX Keyboard.event_modifiers_index = KeyboardInputEvent.CLASS_ATTRIBUTE_NAMES.index( 'modifiers') Keyboard.win_id_index = KeyboardInputEvent.CLASS_ATTRIBUTE_NAMES.index( 'window_id') Keyboard.event_id_index = KeyboardInputEvent.EVENT_ID_INDEX def _nativeEventCallback(self, event): try: self._last_callback_time = getTime() if self.isReportingEvents(): event_array = event[0] key = event_array[Keyboard.key_index] if isinstance(key, bytes): event_array[Keyboard.key_index] = key = str(key, 'utf-8') if Keyboard.use_psychopy_keymap: if key in psychopy_key_mappings.keys(): key = event_array[Keyboard.key_index] = psychopy_key_mappings[key] elif key == 'num_next': key = event_array[Keyboard.key_index] = 'num_page_down' elif key == 'num_prior': key = event_array[Keyboard.key_index] = 'num_page_up' if (event_array[Keyboard.event_modifiers_index]&NUMLOCK_MODIFIER) > 0: if key in psychopy_numlock_key_mappings: key = event_array[Keyboard.key_index] = psychopy_numlock_key_mappings[key] # Check if key event window id is in list of psychopy # windows and what report_system_wide_events value is report_system_wide_events = self.getConfiguration().get( 'report_system_wide_events', True) if report_system_wide_events is False: pyglet_window_hnds = self._iohub_server._psychopy_windows.keys() if len(pyglet_window_hnds) > 0 and event_array[self.win_id_index] not in pyglet_window_hnds: return True is_pressed = event_array[ self.event_type_index] == EventConstants.KEYBOARD_PRESS if is_pressed and self._report_auto_repeats is False: # AUto repeat value provided by pyXHook code auto_repeat_count = event_array[self.auto_repeated_index] if auto_repeat_count > 0: return True # set event id for event since it has passed all filters event_array[self.event_id_index] = Device._getNextEventID() ioHubKeyboardDevice._modifier_value = event_array[ self.event_modifiers_index] self._updateKeyboardEventState(event_array, is_pressed) self._addNativeEventToBuffer(event_array) except Exception: printExceptionDetailsToStdErr() return 1 def _getIOHubEventObject(self, native_event_data): return native_event_data
4,768
Python
.py
84
43.333333
112
0.621146
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,710
darwinkey.py
psychopy_psychopy/psychopy/iohub/devices/keyboard/darwinkey.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). # /System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/ # HIToolbox.framework/Headers/Events.h QZ_ESCAPE = 0x35 QZ_F1 = 0x7A QZ_F2 = 0x78 QZ_F3 = 0x63 QZ_F4 = 0x76 QZ_F5 = 0x60 QZ_F6 = 0x61 QZ_F7 = 0x62 QZ_F8 = 0x64 QZ_F9 = 0x65 QZ_F10 = 0x6D QZ_F11 = 0x67 QZ_F12 = 0x6F QZ_F13 = 0x69 QZ_F14 = 0x6B QZ_F15 = 0x71 QZ_F16 = 0x6A QZ_F17 = 0x40 QZ_F18 = 0x4F QZ_F19 = 0x50 QZ_F20 = 0x5A QZ_BACKQUOTE = 0x32 QZ_MINUS = 0x1B QZ_EQUALS = 0x18 QZ_BACKSPACE = 0x33 QZ_INSERT = 0x72 QZ_HOME = 0x73 QZ_PAGEUP = 0x74 QZ_NUMLOCK = 0x47 QZ_KP_EQUALS = 0x51 QZ_KP_DIVIDE = 0x4B QZ_KP_MULTIPLY = 0x43 QZ_TAB = 0x30 QZ_LEFTBRACKET = 0x21 QZ_RIGHTBRACKET = 0x1E QZ_BACKSLASH = 0x2A QZ_DELETE = 0x75 QZ_END = 0x77 QZ_PAGEDOWN = 0x79 QZ_KP7 = 0x59 QZ_KP8 = 0x5B QZ_KP9 = 0x5C QZ_KP_MINUS = 0x4E QZ_CAPSLOCK = 0x39 QZ_SEMICOLON = 0x29 QZ_QUOTE = 0x27 QZ_RETURN = 0x24 QZ_KP4 = 0x56 QZ_KP5 = 0x57 QZ_KP6 = 0x58 QZ_KP_PLUS = 0x45 QZ_LSHIFT = 0x38 QZ_COMMA = 0x2B QZ_PERIOD = 0x2F QZ_SLASH = 0x2C QZ_RSHIFT = 0x3C QZ_UP = 0x7E QZ_KP1 = 0x53 QZ_KP2 = 0x54 QZ_KP3 = 0x55 QZ_NUM_ENTER = 0x4C QZ_LCTRL = 0x3B QZ_LALT = 0x3A QZ_LCMD = 0x37 QZ_SPACE = 0x31 QZ_RCMD = 0x36 QZ_RALT = 0x3D QZ_RCTRL = 0x3E QZ_FUNCTION = 0x3F QZ_LEFT = 0x7B QZ_DOWN = 0x7D QZ_RIGHT = 0x7C QZ_KP0 = 0x52 QZ_KP_PERIOD = 0x41 QZ_F1 = 145 # Keycode on Apple wireless kb QZ_F2 = 144 # Keycode on Apple wireless kb QZ_F3 = 160 # Keycode on Apple wireless kb QZ_F4 = 131 # Keycode on Apple wireless kb code2label = {} # need tp copy locals for py3 for k, v in locals().copy().items(): if k.startswith('QZ_'): klabel = u'' + k[3:].lower() code2label[klabel] = v code2label[v] = klabel
1,886
Python
.py
91
19.384615
85
0.717076
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,711
__init__.py
psychopy_psychopy/psychopy/iohub/devices/keyboard/__init__.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). global Keyboard Keyboard = None import numpy as N from ...errors import print2err, printExceptionDetailsToStdErr from ...constants import KeyboardConstants, DeviceConstants, EventConstants, ModifierKeyCodes from .. import Device, Computer getTime = Computer.getTime psychopy_key_mappings = {'`': 'quoteleft', '[': 'bracketleft', ']': 'bracketright', '\\': 'backslash', '/': 'slash', ';': 'semicolon', "'": 'apostrophe', ',': 'comma', '.': 'period', '-': 'minus', '=': 'equal', '+': 'num_add', '*': 'num_multiply', ' ': 'space' } class ioHubKeyboardDevice(Device): """The Keyboard device is used to receive events from a standard USB or PS2 keyboard connected to the experiment computer. Only one keyboard device is supported in an experiment at this time, if multiple keyboards are connected to the computer, any keyboard events will be combined from all keyboard devices, appearing to originate from a single keyboard device in the experiment. """ use_psychopy_keymap = True EVENT_CLASS_NAMES = [ 'KeyboardInputEvent', 'KeyboardPressEvent', 'KeyboardReleaseEvent'] DEVICE_TYPE_ID = DeviceConstants.KEYBOARD DEVICE_TYPE_STRING = 'KEYBOARD' _modifier_value = 0 __slots__ = [ '_key_states', '_modifier_states', '_report_auto_repeats', '_log_events_file'] def __init__(self, *args, **kwargs): self._key_states = dict() self._modifier_states = dict(zip(ModifierKeyCodes._mod_names, [ False] * len(ModifierKeyCodes._mod_names))) self._report_auto_repeats = kwargs.get( 'report_auto_repeat_press_events', False) self._log_events_file = None Device.__init__(self, *args, **kwargs) ioHubKeyboardDevice.use_psychopy_keymap = self.getConfiguration().get('use_keymap') == 'psychopy' @classmethod def getModifierState(cls): return cls._modifier_value def resetState(self): Device.clearEvents() self._key_states.clear() def _addEventToTestLog(self, event_data): print2err( 'Keyboard._addEventToTestLog must be implemented by platform specific Keyboard type.') def _updateKeyboardEventState(self, kb_event, is_press): key_id_index = KeyboardInputEvent.CLASS_ATTRIBUTE_NAMES.index('key_id') # print2err("==========") #print2err("ispress:",is_press," : ",kb_event) if is_press: key_state = self._key_states.setdefault( kb_event[key_id_index], [kb_event, -1]) key_state[1] += 1 else: key_press = self._key_states.get(kb_event[key_id_index], None) #print2err('update key release:', key_press) if key_press is None: return None else: duration_index = KeyboardInputEvent.CLASS_ATTRIBUTE_NAMES.index( 'duration') press_evt_id_index = KeyboardInputEvent.CLASS_ATTRIBUTE_NAMES.index( 'press_event_id') kb_event[duration_index] = kb_event[ DeviceEvent.EVENT_HUB_TIME_INDEX] - key_press[0][DeviceEvent.EVENT_HUB_TIME_INDEX] #print2err('Release times :',kb_event[DeviceEvent.EVENT_HUB_TIME_INDEX]," : ",key_press[0][DeviceEvent.EVENT_HUB_TIME_INDEX]) kb_event[press_evt_id_index] = key_press[ 0][DeviceEvent.EVENT_ID_INDEX] del self._key_states[kb_event[key_id_index]] def getCurrentDeviceState(self, clear_events=True): mods = self.getModifierState() presses = {str(k):v for k,v in list(self._key_states.items())} dstate = Device.getCurrentDeviceState(self, clear_events) dstate['modifiers'] = mods dstate['pressed_keys'] = presses return dstate def _close(self): if self._log_events_file: self._log_events_file.close() self._log_events_file = None Device._close(self) if Computer.platform == 'win32': from .win32 import Keyboard elif Computer.platform.startswith('linux'): from .linux2 import Keyboard elif Computer.platform == 'darwin': from .darwin import Keyboard ############# OS independent Keyboard Event classes #################### from .. import DeviceEvent class KeyboardInputEvent(DeviceEvent): """The KeyboardInputEvent class is an abstract class that is the parent of all Keyboard related event types.""" PARENT_DEVICE = Keyboard EVENT_TYPE_ID = EventConstants.KEYBOARD_INPUT EVENT_TYPE_STRING = 'KEYBOARD_INPUT' IOHUB_DATA_TABLE = EVENT_TYPE_STRING # TODO: Determine real maximum key name string and modifiers string # lengths and set appropriately. _newDataTypes = [('auto_repeated', N.uint16), # 0 if the original, first press event for the key. # > 0 = the number if times the key has repeated. # the scan code for the key that was pressed. ('scan_code', N.uint32), # Represents the physical key id on the keyboard layout # The scancode translated into a keyboard layout # independent, but still OS dependent, code representing # the key that was pressed ('key_id', N.uint32), # the translated key ID, should be keyboard layout and os # independent, ('ucode', N.uint32), # based on the keyboard local settings of the OS. # a string representation of what key was pressed. This # will be based on a mapping table ('key', '|S12'), # indicates what modifier keys were active when the key # was pressed. ('modifiers', N.uint32), # the id of the window that had focus when the key was # pressed. ('window_id', N.uint64), # Holds the unicode char value of the key, if available. # Only keys that also have a visible glyph will be set for # this field. ('char', '|S4'), # for keyboard release events, the duration from key press # event (if one was registered) ('duration', N.float32), # for keyboard release events, the duration from key press # event (if one was registered) # event_id of the associated key press event ('press_event_id', N.uint32) ] __slots__ = [e[0] for e in _newDataTypes] def __init__(self, *args, **kwargs): #: The auto repeat count for the keyboard event. 0 indicates the event #: was generated from an actual keyboard event. > 0 means the event #: was generated from the operating system's auto repeat settings for #: keyboard presses that are longer than an OS specified duration. #: This represents the physical key id on the keyboard layout. self.auto_repeated = 0 #: The scan code for the keyboard event. #: This represents the physical key id on the keyboard layout. #: The Linux and Windows ioHub interface provide's scan codes; the OS X implementation does not. #: int value self.scan_code = 0 #: The keyboard independent, but OS dependent, representation of the key pressed. #: int value. self.key_id = 0 #: The utf-8 coe point for the key present, if it has one and can be determined. 0 otherwise. #: This value is, in most cases, calculated by taking the event.key value, #: determining if it is a unicode utf-8 encoded char, and if so, calling the #: Python built in function unichr(event.key). #: int value between 0 and 2**16. self.ucode = '' #: A Psychopy constant used to represent the key pressed. Visible and latin-1 #: based non visible characters will , in general, have look up values. #: If a key constant can not be found for the event, the field will be empty. self.key = '' #: List of the modifiers that were active when the key was pressed, provide in #: online events as a list of the modifier constant labels specified in #: iohub.ModifierConstants #: list: Empty if no modifiers are pressed, otherwise each element is the string name of a modifier constant. self.modifiers = 0 #: The id or handle of the window that had focus when the key was pressed. #: long value. self.window_id = 0 #: the unicode char (u'') representation of what key was pressed. # For standard character ascii keys (a-z,A-Z,0-9, some punctuation values), and #: unicode utf-8 encoded characters that have been successfully detected, #: *char* will be the actual key value pressed as a unicode character. self.char = u'' #: The id or handle of the window that had focus when the key was pressed. #: long value. self.duration = 0 #: The id or handle of the window that had focus when the key was pressed. #: long value. self.press_event_id = 0 DeviceEvent.__init__(self, *args, **kwargs) @classmethod def _convertFields(cls, event_value_list): modifier_value_index = cls.CLASS_ATTRIBUTE_NAMES.index('modifiers') event_value_list[modifier_value_index] = KeyboardConstants._modifierCodes2Labels( event_value_list[modifier_value_index]) #char_value_index = cls.CLASS_ATTRIBUTE_NAMES.index('char') #event_value_list[char_value_index] = event_value_list[ # char_value_index].decode('utf-8') #key_value_index = cls.CLASS_ATTRIBUTE_NAMES.index('key') #event_value_list[key_value_index] = event_value_list[ # key_value_index].decode('utf-8') @classmethod def createEventAsDict(cls, values): cls._convertFields(values) return dict(zip(cls.CLASS_ATTRIBUTE_NAMES, values)) # noinspection PyUnresolvedReferences @classmethod def createEventAsNamedTuple(cls, valueList): cls._convertFields(valueList) return cls.namedTupleClass(*valueList) class KeyboardPressEvent(KeyboardInputEvent): """A KeyboardPressEvent is generated when a key is pressed down. The event is created prior to the keyboard key being released. If a key is held down for an extended period of time, multiple KeyboardPressEvent events may be generated depending on your OS and the OS's settings for key repeat event creation. If auto repeat key events are not desired at all, then the keyboard configuration setting 'report_auto_repeat_press_events' can be used to disable these events by having the ioHub Server filter the unwanted events out. By default this keyboard configuration parameter is set to True. Event Type ID: EventConstants.KEYBOARD_PRESS Event Type String: 'KEYBOARD_PRESS' """ EVENT_TYPE_ID = EventConstants.KEYBOARD_PRESS EVENT_TYPE_STRING = 'KEYBOARD_PRESS' IOHUB_DATA_TABLE = KeyboardInputEvent.IOHUB_DATA_TABLE __slots__ = [] def __init__(self, *args, **kwargs): KeyboardInputEvent.__init__(self, *args, **kwargs) class KeyboardReleaseEvent(KeyboardInputEvent): """A KeyboardReleaseEvent is generated when a key the keyboard is released. Event Type ID: EventConstants.KEYBOARD_RELEASE Event Type String: 'KEYBOARD_RELEASE' """ EVENT_TYPE_ID = EventConstants.KEYBOARD_RELEASE EVENT_TYPE_STRING = 'KEYBOARD_RELEASE' IOHUB_DATA_TABLE = KeyboardInputEvent.IOHUB_DATA_TABLE __slots__ = [] def __init__(self, *args, **kwargs): KeyboardInputEvent.__init__(self, *args, **kwargs)
12,637
Python
.py
248
40.044355
141
0.617862
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,712
darwin.py
psychopy_psychopy/psychopy/iohub/devices/keyboard/darwin.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). from copy import copy import Quartz as Qz from AppKit import NSEvent # NSKeyUp, NSSystemDefined, NSEvent from . import ioHubKeyboardDevice, psychopy_key_mappings from ...constants import KeyboardConstants, DeviceConstants, EventConstants from .. import Computer, Device #>>>>>>>>>>>>>>>>>>>>>>>> import ctypes import ctypes.util import CoreFoundation import objc from ...errors import print2err, printExceptionDetailsToStdErr try: unichr except NameError: unichr = chr import unicodedata from .darwinkey import code2label psychopy_numlock_key_mappings = dict() psychopy_numlock_key_mappings['1'] = 'num_1' psychopy_numlock_key_mappings['2'] = 'num_2' psychopy_numlock_key_mappings['3'] = 'num_3' psychopy_numlock_key_mappings['4'] = 'num_4' psychopy_numlock_key_mappings['5'] = 'num_5' psychopy_numlock_key_mappings['6'] = 'num_6' psychopy_numlock_key_mappings['7'] = 'num_7' psychopy_numlock_key_mappings['8'] = 'num_8' psychopy_numlock_key_mappings['9'] = 'num_9' psychopy_numlock_key_mappings['0'] = 'num_0' psychopy_numlock_key_mappings['/'] = 'num_divide' psychopy_numlock_key_mappings['*'] = 'num_multiple' psychopy_numlock_key_mappings['-'] = 'num_minus' psychopy_numlock_key_mappings['+'] = 'num_add' psychopy_numlock_key_mappings['='] = 'num_equal' psychopy_numlock_key_mappings['.'] = 'num_decimal' carbon_path = ctypes.util.find_library('Carbon') carbon = ctypes.cdll.LoadLibrary(carbon_path) _objc = ctypes.PyDLL(objc._objc.__file__) _objc.PyObjCObject_New.restype = ctypes.py_object _objc.PyObjCObject_New.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_int] def objcify(ptr): return _objc.PyObjCObject_New(ptr, 0, 1) kTISPropertyUnicodeKeyLayoutData_p = ctypes.c_void_p.in_dll( carbon, 'kTISPropertyUnicodeKeyLayoutData') kTISPropertyUnicodeKeyLayoutData = objcify(kTISPropertyUnicodeKeyLayoutData_p) carbon.TISCopyCurrentKeyboardInputSource.argtypes = [] carbon.TISCopyCurrentKeyboardInputSource.restype = ctypes.c_void_p carbon.TISGetInputSourceProperty.argtypes = [ctypes.c_void_p, ctypes.c_void_p] carbon.TISGetInputSourceProperty.restype = ctypes.c_void_p carbon.LMGetKbdType.argtypes = [] carbon.LMGetKbdType.restype = ctypes.c_uint32 OptionBits = ctypes.c_uint32 UniCharCount = ctypes.c_uint8 UniChar = ctypes.c_uint16 UniChar4 = UniChar * 4 carbon.UCKeyTranslate.argtypes = [ctypes.c_void_p, # keyLayoutPtr ctypes.c_uint16, # virtualKeyCode ctypes.c_uint16, # keyAction ctypes.c_uint32, # modifierKeyState ctypes.c_uint32, # keyboardType OptionBits, # keyTranslateOptions ctypes.POINTER( ctypes.c_uint32), # deadKeyState UniCharCount, # maxStringLength # actualStringLength ctypes.POINTER(UniCharCount), UniChar4] carbon.UCKeyTranslate.restype = ctypes.c_uint32 # OSStatus kUCKeyActionDisplay = 3 kUCKeyTranslateNoDeadKeysBit = 0 kTISPropertyUnicodeKeyLayoutData = ctypes.c_void_p.in_dll( carbon, 'kTISPropertyUnicodeKeyLayoutData') #<<<<<<<<<<<<<<<<<<<<<<<< from unicodedata import category as ucategory getTime = Computer.getTime eventHasModifiers = lambda v: Qz.kCGEventFlagMaskNonCoalesced - v != 0 keyFromNumpad = lambda v: Qz.kCGEventFlagMaskNumericPad & v == Qz.kCGEventFlagMaskNumericPad caplocksEnabled = lambda v: Qz.kCGEventFlagMaskAlphaShift & v == Qz.kCGEventFlagMaskAlphaShift shiftModifierActive = lambda v: Qz.kCGEventFlagMaskShift & v == Qz.kCGEventFlagMaskShift altModifierActive = lambda v: Qz.kCGEventFlagMaskAlternate & v == Qz.kCGEventFlagMaskAlternate controlModifierActive = lambda v: Qz.kCGEventFlagMaskControl & v == Qz.kCGEventFlagMaskControl fnModifierActive = lambda v: Qz.kCGEventFlagMaskSecondaryFn & v == Qz.kCGEventFlagMaskSecondaryFn modifier_name_mappings = dict( lctrl='lctrl', rctrl='rctrl', lshift='lshift', rshift='rshift', lalt='lalt', ralt='lalt', lcmd='lcmd', rcmd='lcmd', capslock='capslock', # MOD_SHIFT=512, # MOD_ALT=1024, # MOD_CTRL=2048, # MOD_CMD=4096, numlock='numlock', function='function', modhelp='modhelp') class Keyboard(ioHubKeyboardDevice): _last_mod_names = [] _OS_MODIFIERS = ([(0x00001, 'lctrl'), (0x02000, 'rctrl'), (0x00002, 'lshift'), (0x00004, 'rshift'), (0x00020, 'lalt'), (0x00040, 'ralt'), (0x000008, 'lcmd'), (0x000010, 'rcmd'), (Qz.kCGEventFlagMaskAlphaShift, 'capslock'), (Qz.kCGEventFlagMaskSecondaryFn, 'function'), (Qz.kCGEventFlagMaskHelp, 'modhelp')]) # 0x400000 DEVICE_TIME_TO_SECONDS = 0.000000001 _EVENT_TEMPLATE_LIST = [0, # experiment id 0, # session id 0, # device id (not currently used) 0, # Device._getNextEventID(), 0, # ioHub Event type 0.0, # event device time, 0.0, # event logged_time, 0.0, # event iohub Time, 0.0, # confidence_interval, 0.0, # delay, 0, # filtered by ID (always 0 right now) 0, # auto repeat count 0, # ScanCode 0, # KeyID 0, # ucode u'', # key None, # mods 0, # win num u'', # char 0.0, # duration 0] # press evt id __slots__ = [ '_loop_source', '_tap', '_device_loop', '_CGEventTapEnable', '_loop_mode', '_last_general_mod_states', '_codedict'] def __init__(self, *args, **kwargs): ioHubKeyboardDevice.__init__(self, *args, **kwargs['dconfig']) # TODO: This dict should be reset whenever monitoring is turned off for the device OR # whenever events are cleared for the device. # Do the same for the _active_modifiers bool lookup array self._last_general_mod_states = dict( shift_on=False, alt_on=False, cmd_on=False, ctrl_on=False) #self._codedict = {self._createStringForKey(code,0): code for code in range(128)} self._loop_source = None self._tap = None self._device_loop = None self._loop_mode = None self._tap = Qz.CGEventTapCreate( Qz.kCGSessionEventTap, Qz.kCGHeadInsertEventTap, Qz.kCGEventTapOptionDefault, Qz.CGEventMaskBit(Qz.kCGEventKeyDown) | Qz.CGEventMaskBit(Qz.kCGEventKeyUp) | Qz.CGEventMaskBit(Qz.kCGEventFlagsChanged), self._nativeEventCallback, None) self._CGEventTapEnable = Qz.CGEventTapEnable self._loop_source = Qz.CFMachPortCreateRunLoopSource( None, self._tap, 0) self._device_loop = Qz.CFRunLoopGetCurrent() self._loop_mode = Qz.kCFRunLoopDefaultMode Qz.CFRunLoopAddSource( self._device_loop, self._loop_source, self._loop_mode) def _createStringForKey(self, keycode, modifier_state): keyboard_p = carbon.TISCopyCurrentKeyboardInputSource() keyboard = objcify(keyboard_p) layout_p = carbon.TISGetInputSourceProperty( keyboard_p, kTISPropertyUnicodeKeyLayoutData) layout = objcify(layout_p) layoutbytes = layout.bytes() if hasattr(layoutbytes, 'tobytes'): layoutbytes_vp = layoutbytes.tobytes() else: layoutbytes_vp = memoryview(bytearray(layoutbytes)).tobytes() keysdown = ctypes.c_uint32() length = UniCharCount() chars = UniChar4() retval = carbon.UCKeyTranslate(layoutbytes_vp, keycode, kUCKeyActionDisplay, modifier_state, carbon.LMGetKbdType(), kUCKeyTranslateNoDeadKeysBit, ctypes.byref(keysdown), 4, ctypes.byref(length), chars) s = u''.join(unichr(chars[i]) for i in range(length.value)) CoreFoundation.CFRelease(keyboard) return s # def _keyCodeForChar(self, c): # return self._codedict[c] def _poll(self): self._last_poll_time = getTime() while Qz.CFRunLoopRunInMode( self._loop_mode, 0.0, True) == Qz.kCFRunLoopRunHandledSource: pass def _nativeEventCallback(self, *args): event = None try: proxy, etype, event, refcon = args if self.isReportingEvents(): logged_time = getTime() if etype == Qz.kCGEventTapDisabledByTimeout: print2err( '** WARNING: Keyboard Tap Disabled due to timeout. Re-enabling....: ', etype) Qz.CGEventTapEnable(self._tap, True) return event confidence_interval = logged_time - self._last_poll_time delay = 0.0 iohub_time = logged_time - delay char_value = None key_value = None ioe_type = None device_time = Qz.CGEventGetTimestamp( event) * self.DEVICE_TIME_TO_SECONDS key_code = Qz.CGEventGetIntegerValueField( event, Qz.kCGKeyboardEventKeycode) # Check Auto repeats if etype == Qz.kCGEventKeyDown and self._report_auto_repeats is False and self._key_states.get( key_code, None): return event nsEvent = NSEvent.eventWithCGEvent_(event) # should NSFunctionKeyMask, NSNumericPadKeyMask be used?? window_number = nsEvent.windowNumber() if etype in [ Qz.kCGEventKeyDown, Qz.kCGEventKeyUp, Qz.kCGEventFlagsChanged]: key_mods = Qz.CGEventGetFlags(event) ioHubKeyboardDevice._modifier_value, mod_names = self._checkForLeftRightModifiers( key_mods) if fnModifierActive(key_mods) and keyFromNumpad(key_mods): # At least on mac mini wireless kb, arrow keys have # fnModifierActive at all times, even when fn key is not pressed. # When fn key 'is' pressed, and arrow key is pressed, # then keyFromNumpad becomes false. mod_names.remove('function') ioHubKeyboardDevice._modifier_value -= KeyboardConstants._modifierCodes.getID( 'function') if etype != Qz.kCGEventFlagsChanged: char_value = nsEvent.characters() if etype == Qz.kCGEventKeyUp: ioe_type = EventConstants.KEYBOARD_RELEASE elif etype == Qz.kCGEventKeyDown: ioe_type = EventConstants.KEYBOARD_PRESS else: if len(mod_names) > len(self._last_mod_names): ioe_type = EventConstants.KEYBOARD_PRESS else: ioe_type = EventConstants.KEYBOARD_RELEASE Keyboard._last_mod_names = mod_names if char_value is None or fnModifierActive(key_mods): char_value = self._createStringForKey( key_code, key_mods) if len(char_value) != 1 or unicodedata.category( char_value).lower() == 'cc': char_value = '' key_value = self._createStringForKey(key_code, 0) if len(key_value) == 0 or unicodedata.category( key_value).lower() == 'cc': key_value = code2label.get(key_code, '') if key_value == 'tab': char_value = '\t' elif key_value == 'return': char_value = '\n' if Keyboard.use_psychopy_keymap: if keyFromNumpad(key_mods) and key_value in psychopy_numlock_key_mappings.keys(): key_value = psychopy_numlock_key_mappings[key_value] elif key_value in psychopy_key_mappings.keys(): key_value = psychopy_key_mappings[key_value] is_auto_repeat = Qz.CGEventGetIntegerValueField(event, Qz.kCGKeyboardEventAutorepeat) # TODO: CHeck WINDOW BOUNDS # report_system_wide_events=s elf.getConfiguration().get('report_system_wide_events',True) # Can not seem to figure out how to get window handle id from evt to match with pyget in darwin, so # Comparing event target process ID to the psychopy windows process ID, # yglet_window_hnds=self._iohub_server._pyglet_window_hnds #print2err("pyglet_window_hnds: ",window_number, " , ",pyglet_window_hnds) #targ_proc = Qz.CGEventGetIntegerValueField(event,Qz.kCGEventTargetUnixProcessID) #psych_proc = Computer.psychopy_process.pid # if targ_proc == psych_proc: # pass # elif report_system_wide_events is False: # For keyboard, when report_system_wide_events is false # do not record kb events that are not targeted for # a PsychoPy window, still allow them to pass to the desktop # apps. # return event if ioe_type: ioe = self._EVENT_TEMPLATE_LIST ioe[3] = Device._getNextEventID() ioe[4] = ioe_type ioe[5] = device_time ioe[6] = logged_time ioe[7] = iohub_time ioe[8] = confidence_interval ioe[9] = delay # index 10 is filter id, not used at this time ioe[11] = is_auto_repeat # Quartz does not give the scancode, so fill this with # keycode ioe[12] = key_code ioe[13] = key_code # key_code ioe[14] = 0 # unicode number field no longer used. ioe[15] = key_value ioe[16] = ioHubKeyboardDevice._modifier_value ioe[17] = window_number ioe[18] = char_value.encode('utf-8') ioe = copy(ioe) ioHubKeyboardDevice._updateKeyboardEventState( self, ioe, ioe_type == EventConstants.KEYBOARD_PRESS) self._addNativeEventToBuffer(ioe) else: print2err('\nWARNING: KEYBOARD RECEIVED A [ {0} ] KB EVENT, BUT COULD NOT GENERATE AN IOHUB EVENT FROM IT !!'.format( etype), ' [', key_value, '] ucode: ', char_value.encode('utf-8'), ' key_code: ', key_code) self._last_callback_time = logged_time return event except Exception: printExceptionDetailsToStdErr() Qz.CGEventTapEnable(self._tap, False) return event @classmethod def _checkForLeftRightModifiers(cls, mod_state): mod_value = 0 mod_strs = [] for k, v in cls._OS_MODIFIERS: if mod_state & k > 0: mod_value += KeyboardConstants._modifierCodes.getID(v) mod_strs.append( modifier_name_mappings.get( v, 'MISSING_MOD_NAME')) return mod_value, mod_strs def _getIOHubEventObject(self, native_event_data): return native_event_data def _close(self): try: Qz.CGEventTapEnable(self._tap, False) except Exception: pass try: if Qz.CFRunLoopContainsSource( self._device_loop, self._loop_source, self._loop_mode) is True: Qz.CFRunLoopRemoveSource( self._device_loop, self._loop_source, self._loop_mode) finally: self._loop_source = None self._tap = None self._device_loop = None self._loop_mode = None ioHubKeyboardDevice._close(self)
17,695
Python
.py
363
33.911846
137
0.553194
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,713
win32.py
psychopy_psychopy/psychopy/iohub/devices/wintab/win32.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). # Initial file based on pyglet.libs.win32 # Tablet related class definitions import pyglet from pyglet.event import EventDispatcher import ctypes from ...errors import print2err from ...constants import EventConstants lib = ctypes.windll.wintab32 LONG = ctypes.c_long BOOL = ctypes.c_int UINT = ctypes.c_uint WORD = ctypes.c_uint16 DWORD = ctypes.c_uint32 WCHAR = ctypes.c_wchar FIX32 = DWORD WTPKT = DWORD LCNAMELEN = 40 def print_struct(s, pretxt=''): print2err('{}{}:'.format(pretxt, s)) for field_name, field_type in s._fields_: print2err('\t{}:\t{}'.format(field_name, getattr(s, field_name))) print2err('<<<<<<<<') def struct2dict(s): csdict = {} for field_name, field_type in s._fields_: ufield_name = field_name if field_name.startswith('ax'): ufield_name = field_name[2:].lower() csdict[ufield_name] = getattr(s, field_name) return csdict class AXIS(ctypes.Structure): _fields_ = ( ('axMin', LONG), ('axMax', LONG), ('axUnits', UINT), ('axResolution', FIX32) ) def get_scale(self): return 1 / float(self.axMax - self.axMin) def get_bias(self): return -self.axMin class ORIENTATION(ctypes.Structure): _fields_ = ( ('orAzimuth', ctypes.c_int), ('orAltitude', ctypes.c_int), ('orTwist', ctypes.c_int) ) class ROTATION(ctypes.Structure): _fields_ = ( ('roPitch', ctypes.c_int), ('roRoll', ctypes.c_int), ('roYaw', ctypes.c_int), ) class LOGCONTEXT(ctypes.Structure): _fields_ = ( ('lcName', WCHAR * LCNAMELEN), ('lcOptions', UINT), ('lcStatus', UINT), ('lcLocks', UINT), ('lcMsgBase', UINT), ('lcDevice', UINT), ('lcPktRate', UINT), ('lcPktData', WTPKT), ('lcPktMode', WTPKT), ('lcMoveMask', WTPKT), ('lcBtnDnMask', DWORD), ('lcBtnUpMask', DWORD), ('lcInOrgX', LONG), ('lcInOrgY', LONG), ('lcInOrgZ', LONG), ('lcInExtX', LONG), ('lcInExtY', LONG), ('lcInExtZ', LONG), ('lcOutOrgX', LONG), ('lcOutOrgY', LONG), ('lcOutOrgZ', LONG), ('lcOutExtX', LONG), ('lcOutExtY', LONG), ('lcOutExtZ', LONG), ('lcSensX', FIX32), ('lcSensY', FIX32), ('lcSensZ', FIX32), ('lcSysMode', BOOL), ('lcSysOrgX', ctypes.c_int), ('lcSysOrgY', ctypes.c_int), ('lcSysExtX', ctypes.c_int), ('lcSysExtY', ctypes.c_int), ('lcSysSensX', FIX32), ('lcSysSensY', FIX32), ) PK_CONTEXT = 0x0001 # reporting context PK_STATUS = 0x0002 # status bits PK_TIME = 0x0004 # time stamp PK_CHANGED = 0x0008 # change bit vector PK_SERIAL_NUMBER = 0x0010 # packet serial number PK_CURSOR = 0x0020 # reporting cursor PK_BUTTONS = 0x0040 # button information PK_X = 0x0080 # x axis PK_Y = 0x0100 # y axis PK_Z = 0x0200 # z axis PK_NORMAL_PRESSURE = 0x0400 # normal or tip pressure PK_TANGENT_PRESSURE = 0x0800 # tangential or barrel pressure PK_ORIENTATION = 0x1000 # orientation info: tilts PK_ROTATION = 0x2000 # rotation info; 1.1 DEFAULT_PACKET_DATA_FIELDS = ( PK_STATUS | PK_TIME | PK_CHANGED | PK_SERIAL_NUMBER | PK_CURSOR | PK_BUTTONS | PK_X | PK_Y | PK_Z | PK_NORMAL_PRESSURE | PK_ORIENTATION) class PACKET(ctypes.Structure): _fields_ = ( ('pkStatus', UINT), ('pkTime', LONG), ('pkChanged', WTPKT), ('pkSerialNumber', UINT), ('pkCursor', UINT), ('pkButtons', DWORD), ('pkX', LONG), ('pkY', LONG), ('pkZ', LONG), ('pkNormalPressure', UINT), ('pkOrientation', ORIENTATION) ) TU_NONE = 0 TU_INCHES = 1 TU_CENTIMETERS = 2 TU_CIRCLE = 3 # messages WT_DEFBASE = 0x7ff0 WT_MAXOFFSET = 0xf WT_PACKET = 0 # remember to add base WT_CTXOPEN = 1 WT_CTXCLOSE = 2 WT_CTXUPDATE = 3 WT_CTXOVERLAP = 4 WT_PROXIMITY = 5 WT_INFOCHANGE = 6 WT_CSRCHANGE = 7 # system button assignment values SBN_NONE = 0x00 SBN_LCLICK = 0x01 SBN_LDBLCLICK = 0x02 SBN_LDRAG = 0x03 SBN_RCLICK = 0x04 SBN_RDBLCLICK = 0x05 SBN_RDRAG = 0x06 SBN_MCLICK = 0x07 SBN_MDBLCLICK = 0x08 SBN_MDRAG = 0x09 # for Pen Windows SBN_PTCLICK = 0x10 SBN_PTDBLCLICK = 0x20 SBN_PTDRAG = 0x30 SBN_PNCLICK = 0x40 SBN_PNDBLCLICK = 0x50 SBN_PNDRAG = 0x60 SBN_P1CLICK = 0x70 SBN_P1DBLCLICK = 0x80 SBN_P1DRAG = 0x90 SBN_P2CLICK = 0xA0 SBN_P2DBLCLICK = 0xB0 SBN_P2DRAG = 0xC0 SBN_P3CLICK = 0xD0 SBN_P3DBLCLICK = 0xE0 SBN_P3DRAG = 0xF0 HWC_INTEGRATED = 0x0001 HWC_TOUCH = 0x0002 HWC_HARDPROX = 0x0004 HWC_PHYSID_CURSORS = 0x0008 # 1.1 CRC_MULTIMODE = 0x0001 # 1.1 CRC_AGGREGATE = 0x0002 # 1.1 CRC_INVERT = 0x0004 # 1.1 WTI_INTERFACE = 1 IFC_WINTABID = 1 IFC_SPECVERSION = 2 IFC_IMPLVERSION = 3 IFC_NDEVICES = 4 IFC_NCURSORS = 5 IFC_NCONTEXTS = 6 IFC_CTXOPTIONS = 7 IFC_CTXSAVESIZE = 8 IFC_NEXTENSIONS = 9 IFC_NMANAGERS = 10 IFC_MAX = 10 WTI_STATUS = 2 STA_CONTEXTS = 1 STA_SYSCTXS = 2 STA_PKTRATE = 3 STA_PKTDATA = 4 STA_MANAGERS = 5 STA_SYSTEM = 6 STA_BUTTONUSE = 7 STA_SYSBTNUSE = 8 STA_MAX = 8 WTI_DEFCONTEXT = 3 WTI_DEFSYSCTX = 4 WTI_DDCTXS = 400 # 1.1 WTI_DSCTXS = 500 # 1.1 CTX_NAME = 1 CTX_OPTIONS = 2 CTX_STATUS = 3 CTX_LOCKS = 4 CTX_MSGBASE = 5 CTX_DEVICE = 6 CTX_PKTRATE = 7 CTX_PKTDATA = 8 CTX_PKTMODE = 9 CTX_MOVEMASK = 10 CTX_BTNDNMASK = 11 CTX_BTNUPMASK = 12 CTX_INORGX = 13 CTX_INORGY = 14 CTX_INORGZ = 15 CTX_INEXTX = 16 CTX_INEXTY = 17 CTX_INEXTZ = 18 CTX_OUTORGX = 19 CTX_OUTORGY = 20 CTX_OUTORGZ = 21 CTX_OUTEXTX = 22 CTX_OUTEXTY = 23 CTX_OUTEXTZ = 24 CTX_SENSX = 25 CTX_SENSY = 26 CTX_SENSZ = 27 CTX_SYSMODE = 28 CTX_SYSORGX = 29 CTX_SYSORGY = 30 CTX_SYSEXTX = 31 CTX_SYSEXTY = 32 CTX_SYSSENSX = 33 CTX_SYSSENSY = 34 CTX_MAX = 34 WTI_DEVICES = 100 DVC_NAME = 1 DVC_HARDWARE = 2 DVC_NCSRTYPES = 3 DVC_FIRSTCSR = 4 DVC_PKTRATE = 5 DVC_PKTDATA = 6 DVC_PKTMODE = 7 DVC_CSRDATA = 8 DVC_XMARGIN = 9 DVC_YMARGIN = 10 DVC_ZMARGIN = 11 DVC_X = 12 DVC_Y = 13 DVC_Z = 14 DVC_NPRESSURE = 15 DVC_TPRESSURE = 16 DVC_ORIENTATION = 17 DVC_ROTATION = 18 # 1.1 DVC_PNPID = 19 # 1.1 DVC_MAX = 19 WTI_CURSORS = 200 CSR_NAME = 1 CSR_ACTIVE = 2 CSR_PKTDATA = 3 CSR_BUTTONS = 4 CSR_BUTTONBITS = 5 CSR_BTNNAMES = 6 CSR_BUTTONMAP = 7 CSR_SYSBTNMAP = 8 CSR_NPBUTTON = 9 CSR_NPBTNMARKS = 10 CSR_NPRESPONSE = 11 CSR_TPBUTTON = 12 CSR_TPBTNMARKS = 13 CSR_TPRESPONSE = 14 CSR_PHYSID = 15 # 1.1 CSR_MODE = 16 # 1.1 CSR_MINPKTDATA = 17 # 1.1 CSR_MINBUTTONS = 18 # 1.1 CSR_CAPABILITIES = 19 # 1.1 CSR_TYPE = 20 # 1.2 CSR_MAX = 20 WTI_EXTENSIONS = 300 EXT_NAME = 1 EXT_TAG = 2 EXT_MASK = 3 EXT_SIZE = 4 EXT_AXES = 5 EXT_DEFAULT = 6 EXT_DEFCONTEXT = 7 EXT_DEFSYSCTX = 8 EXT_CURSORS = 9 EXT_MAX = 109 # Allow 100 cursors CXO_SYSTEM = 0x0001 CXO_PEN = 0x0002 CXO_MESSAGES = 0x0004 CXO_MARGIN = 0x8000 CXO_MGNINSIDE = 0x4000 CXO_CSRMESSAGES = 0x0008 # 1.1 # context status values CXS_DISABLED = 0x0001 CXS_OBSCURED = 0x0002 CXS_ONTOP = 0x0004 # context lock values CXL_INSIZE = 0x0001 CXL_INASPECT = 0x0002 CXL_SENSITIVITY = 0x0004 CXL_MARGIN = 0x0008 CXL_SYSOUT = 0x0010 # packet status values TPS_PROXIMITY = 0x0001 TPS_QUEUE_ERR = 0x0002 TPS_MARGIN = 0x0004 TPS_GRAB = 0x0008 TPS_INVERT = 0x0010 # 1.1 TBN_NONE = 0 TBN_UP = 1 TBN_DOWN = 2 PKEXT_ABSOLUTE = 1 PKEXT_RELATIVE = 2 # Extension tags. WTX_OBT = 0 # Out of bounds tracking WTX_FKEYS = 1 # Function keys WTX_TILT = 2 # Raw Cartesian tilt; 1.1 WTX_CSRMASK = 3 # select input by cursor type; 1.1 WTX_XBTNMASK = 4 # Extended button mask; 1.1 WTX_EXPKEYS = 5 # ExpressKeys; 1.3 def wtinfo(category, index, buffer): size = lib.WTInfoW(category, index, None) assert size <= ctypes.sizeof(buffer) lib.WTInfoW(category, index, ctypes.byref(buffer)) return buffer def wtinfo_string(category, index): size = lib.WTInfoW(category, index, None) buffer = ctypes.create_unicode_buffer(size) lib.WTInfoW(category, index, buffer) return buffer.value def wtinfo_uint(category, index): buffer = UINT() lib.WTInfoW(category, index, ctypes.byref(buffer)) return buffer.value def wtinfo_word(category, index): buffer = WORD() lib.WTInfoW(category, index, ctypes.byref(buffer)) return buffer.value def wtinfo_dword(category, index): buffer = DWORD() lib.WTInfoW(category, index, ctypes.byref(buffer)) return buffer.value def wtinfo_wtpkt(category, index): buffer = WTPKT() lib.WTInfoW(category, index, ctypes.byref(buffer)) return buffer.value def wtinfo_bool(category, index): buffer = BOOL() lib.WTInfoW(category, index, ctypes.byref(buffer)) return bool(buffer.value) class Win32Wintab: '''High-level interface to tablet devices. Unlike other devices, tablets must be opened for a specific window, and cannot be opened exclusively. The `open` method returns a `TabletCanvas` object, which supports the events provided by the tablet. Currently only one tablet device can be used, though it can be opened on multiple windows. If more than one tablet is connected, the behaviour is undefined. ''' def __init__(self, index): self._device = WTI_DEVICES + index self.name = wtinfo_string(self._device, DVC_NAME).strip() self.id = wtinfo_string(self._device, DVC_PNPID) self.hardware_type = wtinfo_uint(self._device, DVC_HARDWARE) self.hw_model_info = dict() self.hw_model_info['name'] = self.name self.hw_model_info['id'] = self.id self.hw_model_info['type'] = self.hardware_type self.hw_model_info['handle'] = self._device #phys_cursors = hardware & HWC_PHYSID_CURSORS n_cursors = wtinfo_uint(self._device, DVC_NCSRTYPES) first_cursor = wtinfo_uint(self._device, DVC_FIRSTCSR) self.hw_axis_info = dict() self._x_axis = wtinfo(self._device, DVC_X, AXIS()) self._y_axis = wtinfo(self._device, DVC_Y, AXIS()) self._z_axis = wtinfo(self._device, DVC_Z, AXIS()) self.tip_pressure_axis = wtinfo(self._device, DVC_NPRESSURE, AXIS()) # self.barrel_pressure_axis = wtinfo(self._device, DVC_TPRESSURE, # AXIS()) self.orient_axis = wtinfo(self._device, DVC_ORIENTATION, (AXIS * 3)()) # self.rotation_axis = wtinfo(self._device, DVC_ROTATION, # (AXIS*3)()) self.hw_axis_info['x'] = struct2dict(self._x_axis) self.hw_axis_info['y'] = struct2dict(self._y_axis) self.hw_axis_info['z'] = struct2dict(self._z_axis) # seems that z axis min value is being reported as -1023, # but it is never < 0 in PACKET field, so setting z min to 0 #print2err("z axis: ", self.hw_axis_info['z']) self.hw_axis_info['z']['min'] = 0 self.hw_axis_info['pressure'] = struct2dict(self.tip_pressure_axis) #self.hw_axis_info['barrel_pressure_axis'] = struct2dict(self.barrel_pressure_axis) self.hw_axis_info['orient_azimuth'] = struct2dict(self.orient_axis[0]) self.hw_axis_info['orient_altitude'] = struct2dict(self.orient_axis[1]) self.hw_axis_info['orient_twist'] = struct2dict(self.orient_axis[2]) #self.hw_axis_info['rotation_pitch_axis'] = struct2dict(self.rotation_axis[0]) #self.hw_axis_info['rotation_roll_axis'] = struct2dict(self.rotation_axis[1]) #self.hw_axis_info['rotation_yaw_axis'] = struct2dict(self.rotation_axis[2]) self.cursors = [] self._cursor_map = {} for i in range(n_cursors): cursor = Win32WintabCursor(self, i + first_cursor) if not cursor.bogus: self.cursors.append(cursor) self._cursor_map[i + first_cursor] = cursor def open(self, window, iohub_wt_device): """Open a tablet device for a window. :Parameters: `window` : `Window` The window on which the tablet will be used. :rtype: `Win32WintabCanvas` """ Win32WintabCanvas.iohub_wt_device = iohub_wt_device pc = Win32WintabCanvas(self, window) return pc class Win32WintabCanvas(EventDispatcher): """Event dispatcher for tablets. Use `Tablet.open` to obtain this object for a particular tablet device and window. Events may be generated even if the tablet stylus is outside of the window; this is operating-system dependent. The events each provide the `TabletCursor` that was used to generate the event; for example, to distinguish between a stylus and an eraser. Only one cursor can be used at a time, otherwise the results are undefined. :Ivariables: `window` : Window The window on which this tablet was opened. """ iohub_wt_device = None def __init__(self, device, window, msg_base=WT_DEFBASE): super(Win32WintabCanvas, self).__init__() self.window = window self.device = device self.msg_base = msg_base self._iohub_events = [] # TODO: Let user determine if raw or pixel coords should be used for # x,y pos fields. i.e. WTI_DEFCONTEXT == raw, # WTI_DEFSYSCTX == pix self.context_info = context_info = LOGCONTEXT() #wtinfo(WTI_DEFSYSCTX, 0, context_info) wtinfo(WTI_DEFCONTEXT, 0, context_info) context_info.lcMsgBase = msg_base context_info.lcOptions |= CXO_MESSAGES # If you change this, change definition of PACKET also. context_info.lcPktData = DEFAULT_PACKET_DATA_FIELDS context_info.lcPktMode = 0 # All absolute # set output scaling, right now, out == in # TODO: determine what coord space we want to output in. context_info.lcOutOrgX = context_info.lcOutOrgY = 0 # Set the entire tablet as active context_info.lcInOrgX = 0 context_info.lcInOrgY = 0 context_info.lcInOrgZ = 0 context_info.lcInExtX = self.device._x_axis.axMax context_info.lcInExtY = self.device._y_axis.axMax context_info.lcInExtZ = self.device._z_axis.axMax context_info.lcOutOrgX = context_info.lcInOrgX context_info.lcOutOrgY = context_info.lcInOrgY context_info.lcOutOrgZ = context_info.lcInOrgZ # INT(scale[0] * context_info.lcInExtX); context_info.lcOutExtX = context_info.lcInExtX # INT(scale[1] * context_info.lcInExtY); context_info.lcOutExtY = context_info.lcInExtY # INT(scale[1] * context_info.lcInExtY); context_info.lcOutExtZ = context_info.lcInExtZ self._context = lib.WTOpenW(window._hwnd, ctypes.byref(context_info), self.iohub_wt_device.getConfiguration(). get('auto_report_events', False)) if not self._context: print2err("Couldn't open tablet context.") window._event_handlers[msg_base + WT_PACKET] = self._event_wt_packet window._event_handlers[msg_base + WT_PROXIMITY] = self._event_wt_proximity self._current_cursor = None #self._pressure_scale = device.tip_pressure_axis.get_scale() #self._pressure_bias = device.tip_pressure_axis.get_bias() def getContextInfo(self): return struct2dict(self.context_info) def enable(self, enable=True): lib.WTEnable(self._context, enable) def close(self): lib.WTClose(self._context) self._context = None del self.window._event_handlers[self.msg_base + WT_PACKET] del self.window._event_handlers[self.msg_base + WT_PROXIMITY] def _set_current_cursor(self, cursor_type): self._current_cursor = self.device._cursor_map.get(cursor_type, None) if self._current_cursor: self.addHubEvent(None, EventConstants.WINTAB_ENTER_REGION) def addHubEvent( self, packet, evt_type=EventConstants.WINTAB_SAMPLE): # TODO: Display (screen) index #display_id = 0 #window_id = self.window._hwnd #ccursor = self._current_cursor #if ccursor is None: # ccursor = 0 #else: # ccursor = ccursor._cursor if packet is None or evt_type != EventConstants.WINTAB_SAMPLE: cevt = [evt_type, 0, 0, 0, 0, 0, # ('x',N.int32), 0, # ('y',N.int32), 0, # ('z',N.int32), 0, # ('pressure',N.uint32), 0, # ('orient_azimuth',N.int32), 0, # ('orient_altitude;',N.int32), 0, # ('orient_twist',N.int32), 0 # ('status', N.uint8) ] else: cevt = [evt_type, packet.pkTime / 1000.0, packet.pkStatus, packet.pkSerialNumber, packet.pkButtons, packet.pkX, # ('x',N.int32), packet.pkY, # ('y',N.int32), packet.pkZ, # ('z',N.int32), #(packet.pkNormalPressure + self._pressure_bias) * \ # self._pressure_scale, packet.pkNormalPressure, # ('pressure',N.uint32), # ('orient_azimuth',N.int32), packet.pkOrientation.orAzimuth, # ('orient_altitude;',N.int32), packet.pkOrientation.orAltitude, packet.pkOrientation.orTwist, # ('orient_twist',N.int32), 0 # ('status', N.uint8) ] self._iohub_events.append(cevt) @pyglet.window.win32.Win32EventHandler(0) def _event_wt_packet(self, msg, wParam, lParam): if lParam != self._context: return packet = PACKET() if lib.WTPacket(self._context, wParam, ctypes.byref(packet)) == 0: return if not packet.pkChanged: return if self._current_cursor is None: self._set_current_cursor(packet.pkCursor) self.addHubEvent(packet) @pyglet.window.win32.Win32EventHandler(0) def _event_wt_proximity(self, msg, wParam, lParam): if wParam != self._context: return if lParam & 0xffff: # Proximity Enter Event # If going in, proximity event will be generated by next event, which # can actually grab a cursor id, so evt is generated when # _set_current_cursor() is called with a non None cursor. pass else: # Proximity Leave Event self.addHubEvent(None, EventConstants.WINTAB_LEAVE_REGION) self._current_cursor = None class Win32WintabCursor: def __init__(self, device, index): self.device = device self._cursor = WTI_CURSORS + index self.name = wtinfo_string(self._cursor, CSR_NAME).strip() self.active = wtinfo_bool(self._cursor, CSR_ACTIVE) pktdata = wtinfo_wtpkt(self._cursor, CSR_PKTDATA) # A whole bunch of cursors are reported by the driver, but most of # them are hogwash. Make sure a cursor has at least X and Y data # before adding it to the device. self.bogus = not (pktdata & PK_X and pktdata & PK_Y) if self.bogus: return self.id = (wtinfo_dword(self._cursor, CSR_TYPE) << 32) | \ wtinfo_dword(self._cursor, CSR_PHYSID) def __repr__(self): return 'WintabCursor(%r)' % self.name def get_spec_version(): spec_version = wtinfo_word(WTI_INTERFACE, IFC_SPECVERSION) return spec_version def get_interface_name(): interface_name = wtinfo_string(WTI_INTERFACE, IFC_WINTABID) return interface_name def get_implementation_version(): impl_version = wtinfo_word(WTI_INTERFACE, IFC_IMPLVERSION) return impl_version def get_tablets(): # Require spec version 1.1 or greater if get_spec_version() < 0x101: return [] n_devices = wtinfo_uint(WTI_INTERFACE, IFC_NDEVICES) devices = [Win32Wintab(i) for i in range(n_devices)] return devices
20,599
Python
.py
601
28.004992
91
0.630477
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,714
__init__.py
psychopy_psychopy/psychopy/iohub/devices/wintab/__init__.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). _is_epydoc = False # Pen digitizers /tablets that support Wintab API from .. import Device, Computer from ...constants import EventConstants, DeviceConstants from ...errors import print2err, printExceptionDetailsToStdErr import numpy as N import copy from psychopy import platform_specific _sendStayAwake = platform_specific.sendStayAwake class SimulatedWinTabPacket: _next_pkt_id = 1 def __init__(self, time, x, y, press, buttons=0): self.pkTime=time*1000.0 self.pkStatus=0 self.pkSerialNumber=self.getNextID() self.pkButtons=buttons self.pkX = x self.pkY = y self.pkZ = 0 self.pkNormalPressure=press #('pressure',N.uint32), class Orientation: def __init__(self): self.orAzimuth=0 #('orient_azimuth',N.int32), self.orAltitude=0 #('orient_altitude;',N.int32), self.orTwist=0 #('orient_twist',N.int32), self.pkOrientation=Orientation() self.pkOrientation.orAzimuth=0 #('orient_azimuth',N.int32), self.pkOrientation.orAltitude=0 #('orient_altitude;',N.int32), self.pkOrientation.orTwist=0 #('orient_twist',N.int32), @classmethod def getNextID(cls): v = cls._next_pkt_id cls._next_pkt_id+=1 return v class Wintab(Device): """The Wintab class docstr TBC.""" EVENT_CLASS_NAMES = ['WintabSampleEvent', 'WintabEnterRegionEvent', 'WintabLeaveRegionEvent'] DEVICE_TYPE_ID = DeviceConstants.WINTAB DEVICE_TYPE_STRING = 'WINTAB' __slots__ = ['_wtablets', '_wtab_shadow_windows', '_wtab_canvases', '_last_sample', '_first_hw_and_hub_times', '_mouse_sim', '_ioMouse', '_simulated_wintab_events', '_last_simulated_evt', '_mouse_leave_region_timeout' ] def __init__(self, *args, **kwargs): Device.__init__(self, *args, **kwargs['dconfig']) self._wtablets = [] self._wtab_shadow_windows = [] self._wtab_canvases = [] self._ioMouse = self._last_simulated_evt = None self._mouse_sim = self.getConfiguration().get('mouse_simulation').get('enable') self._mouse_leave_region_timeout = self.getConfiguration().get('mouse_simulation').get('leave_region_timeout') self._simulated_wintab_events = [] if self._mouse_sim: self._registerMouseMonitor() self._setHardwareInterfaceStatus(True) else: self._init_wintab() # Following are used for sample status tracking self._last_sample = None self._first_hw_and_hub_times = None def _init_wintab(self): if Computer.platform == 'win32' and Computer.is_iohub_process: try: from .win32 import get_tablets except Exception: self._setHardwareInterfaceStatus( False, u"Error: ioHub Wintab Device " u"requires wintab32.dll to be " u"installed.") def get_tablets(): return [] else: def get_tablets(): print2err('Error: iohub.devices.wintab only supports ' 'Windows OS at this time.') return [] self._setHardwareInterfaceStatus(False, u"Error:ioHub Wintab Device " u"only supports Windows OS " u"at this time.") self._wtablets = get_tablets() index = self.getConfiguration().get('device_number', 0) if self._wtablets is None: return False if len(self._wtablets) == 0: self._setHardwareInterfaceStatus(False, u"Error: No WinTab Devices" u" Detected.") return False if index >= len(self._wtablets): self._setHardwareInterfaceStatus( False, u"Error: device_number {} " u"is out of range. Only {} " u"WinTab devices detected.". format( index, len( self._wtablets))) return False exp_screen_info = self._display_device.getRuntimeInfo() swidth, sheight = exp_screen_info.get('pixel_resolution', [None, None]) screen_index = exp_screen_info.get('index', 0) if swidth is None: self._setHardwareInterfaceStatus(False, u"Error: Wintab device is" u" unable to query experiment " u"screen pixel_resolution.") return False from pyglet.window import Window self._wtab_shadow_windows.append( Window( width=swidth, height=sheight, visible=False, fullscreen=True, vsync=False, screen=screen_index)) self._wtab_shadow_windows[0].switch_to() self._wtab_shadow_windows[0].set_mouse_visible(False) from pyglet import app app.windows.remove(self._wtab_shadow_windows[0]) try: self._wtab_canvases.append( self._wtablets[index].open(self._wtab_shadow_windows[0], self)) except Exception as e: self._setHardwareInterfaceStatus(False, u"Error: Unable to create" u"WintabCanvas for device." u"Exception: {}". format(e)) return False self._setHardwareInterfaceStatus(True) return True def getHardwareConfig(self, index=0): if self._ioMouse is None: hw_model_info = self._wtablets[index].hw_model_info return {'Context': self._wtab_canvases[index].getContextInfo(), 'Axis': self._wtablets[index].hw_axis_info, 'ModelInfo': hw_model_info } swidth, sheight = self._display_device.getRuntimeInfo().get('pixel_resolution',[None, None]) # running in mouse sim mode, so create hw config axis_info = {'orient_altitude': {'min': 0, 'max': 0, 'adjust': 0.0, 'factor': 0.0, 'units': 0, 'resolution': 0}, 'orient_azimuth': {'min': 0, 'max': 0, 'factor': 0.0, 'units': 0, 'resolution': 0}, 'pressure': {'min': 0, 'max': 1, 'units': 0, 'resolution': 0}, 'orient_twist': {'min': 0, 'max': 0, 'units': 0, 'resolution': 0}, 'y': {'min': 0, 'max': sheight, 'units': 0, 'resolution': 0}, 'x': {'min': 0, 'max': swidth, 'units': 0, 'resolution': 0}, 'z': {'min': 0, 'max': 0, 'units': 0, 'resolution': 0}} context = {'lcPktMode': 0, 'lcMoveMask': 0, 'lcLocks': 0, 'lcOptions': 0, 'lcInExtX': 0, 'lcSysOrgY': 0, 'lcSysOrgX': -0, 'lcPktRate': 0, 'lcBtnDnMask': 0, 'lcSysSensY': 0, 'lcSysSensX': 0, 'lcBtnUpMask': 0, 'lcSensY': 0, 'lcSensX': 0, 'lcSensZ': 0, 'lcInOrgX': 0, 'lcInOrgY': 0, 'lcInOrgZ': 0, 'lcOutExtX': 0, 'lcOutOrgX': 0, 'lcSysMode': 0, 'lcPktData': 0, 'lcOutOrgZ': 0, 'lcOutExtZ': 0, 'lcOutExtY': 0, 'lcOutOrgY': 0, 'lcInExtY': 0, 'lcStatus': 0, 'lcInExtZ': 0, 'lcName': '', 'lcDevice': 0, 'lcSysExtX': 0, 'lcMsgBase': 0, 'lcSysExtY': 0} model_info = {'type': 0, 'handle': 0, 'name': 'Mouse Simulation Mode', 'id': ''} return {"Context":context, "Axis":axis_info, "ModelInfo":model_info } def enableEventReporting(self, enabled=True): for wtc in self._wtab_canvases: wtc.enable(enabled) _sendStayAwake() if self.isReportingEvents() != enabled: self._simulated_wintab_events = [] self._last_sample = None self._first_hw_and_hub_times = None self._last_simulated_evt = None return Device.enableEventReporting(self, enabled) def _addSimulatedWintabEvent(self,packet): w, h = self._display_device.getRuntimeInfo().get('pixel_resolution') w = w/2 h=h/2 cevt = [EventConstants.WINTAB_SAMPLE, packet.pkTime/1000.0, packet.pkStatus, packet.pkSerialNumber, packet.pkButtons, packet.pkX+w, #('x',N.int32), packet.pkY+h, #('y',N.int32), packet.pkZ, #('z',N.int32), packet.pkNormalPressure, #('pressure',N.uint32), packet.pkOrientation.orAzimuth, #('orient_azimuth',N.int32), packet.pkOrientation.orAltitude, #('orient_altitude;',N.int32), packet.pkOrientation.orTwist, #('orient_twist',N.int32), 0 #('status', N.uint8) ] self._simulated_wintab_events.append(cevt) def _injectEventsIfNeeded(self, events): """ """ if len(events): if self._last_simulated_evt is None: events.insert(0, [EventConstants.WINTAB_ENTER_REGION, 0, 0, 0, 0, 0, #('x',N.int32), 0, #('y',N.int32), 0, #('z',N.int32), 0, #('pressure',N.uint32), 0, #('orient_azimuth',N.int32), 0, #('orient_altitude;',N.int32), 0, #('orient_twist',N.int32), 0]) self._last_simulated_evt = events[-1] elif self._last_simulated_evt: epress = self._last_simulated_evt[8] if not epress: ctime = Computer.getTime() etime = self._last_simulated_evt[1] if ctime-etime > self._mouse_leave_region_timeout: events.append([EventConstants.WINTAB_LEAVE_REGION, 0, 0, 0, 0, 0, #('x',N.int32), 0, #('y',N.int32), 0, #('z',N.int32), 0, #('pressure',N.uint32), 0, #('orient_azimuth',N.int32), 0, #('orient_altitude;',N.int32), 0, #('orient_twist',N.int32), 0]) self._last_simulated_evt = None return events def _poll(self): try: for swin in self._wtab_shadow_windows: swin.switch_to() swin.dispatch_events() logged_time = Computer.getTime() if not self.isReportingEvents(): self._last_poll_time = logged_time self._simulated_wintab_events = [] for wtc in self._wtab_canvases: del wtc._iohub_events[:] return False confidence_interval = logged_time - self._last_poll_time # Using 0 delay for now as it is unknown. delay = 0.0 wintab_events = [] if self._ioMouse: wintab_events = self._simulated_wintab_events wintab_events = self._injectEventsIfNeeded(wintab_events) self._simulated_wintab_events = [] else: for wtc in self._wtab_canvases: wintab_events.extend(copy.deepcopy(wtc._iohub_events)) del wtc._iohub_events[:] for wte in wintab_events: if wte and wte[0] != EventConstants.WINTAB_SAMPLE: # event is enter or leave region type, so clear # last sample as a flag that next sample should # be FIRST_ENTER self._last_sample = None else: if self._first_hw_and_hub_times is None: self._first_hw_and_hub_times = wte[1], logged_time status = 0 cur_press_state = wte[8] if self._last_sample is None: status += WintabSampleEvent.STATES[ 'FIRST_ENTER'] if cur_press_state > 0: status += WintabSampleEvent.STATES[ 'FIRST_PRESS'] status += WintabSampleEvent.STATES[ 'PRESSED'] else: status += WintabSampleEvent.STATES[ 'FIRST_HOVER'] status += WintabSampleEvent.STATES[ 'HOVERING'] else: prev_press_state = self._last_sample[8] if cur_press_state > 0: status += WintabSampleEvent.STATES[ 'PRESSED'] else: status += WintabSampleEvent.STATES[ 'HOVERING'] if cur_press_state > 0 and prev_press_state == 0: status += WintabSampleEvent.STATES[ 'FIRST_PRESS'] elif cur_press_state == 0 and prev_press_state > 0: status += WintabSampleEvent.STATES[ 'FIRST_HOVER'] # Fill in status field based on previous sample....... wte[-1] = status self._last_sample = wte self._addNativeEventToBuffer((logged_time, delay, confidence_interval, wte)) self._last_poll_time = logged_time return True except Exception as e: print2err('ERROR in WintabDevice._poll: ', e) printExceptionDetailsToStdErr() def _getIOHubEventObject(self, native_event_data): ''' :param native_event_data: :return: ''' logged_time, delay, confidence_interval, wt_event = native_event_data evt_type = wt_event[0] device_time = wt_event[1] #evt_status = wt_event[2] # TODO: Correct for polling interval / CI when calculating iohub_time iohub_time = logged_time if self._first_hw_and_hub_times: hwtime, iotime = self._first_hw_and_hub_times iohub_time = iotime + (wt_event[1] - hwtime) ioevt = [0, 0, 0, Device._getNextEventID(), evt_type, device_time, logged_time, iohub_time, confidence_interval, delay, 0 ] ioevt.extend(wt_event[3:]) return ioevt def _close(self): for wtc in self._wtab_canvases: wtc.close() for swin in self._wtab_shadow_windows: swin.close() if self._ioMouse: self._unregisterMouseMonitor() self._ioMouse=None self._last_simulated_evt=None Device._close(self) def _registerMouseMonitor(self): self._ioMouse=mouseDevice=None self._last_simulated_evt=None if self._iohub_server: for dev in self._iohub_server.devices: if dev.__class__.__name__ == 'Mouse': mouseDevice=dev if mouseDevice: eventIDs=[EventConstants.MOUSE_BUTTON_PRESS, EventConstants.MOUSE_BUTTON_RELEASE, EventConstants.MOUSE_MOVE, EventConstants.MOUSE_DRAG ] self._ioMouse=mouseDevice self._ioMouse._addEventListener(self,eventIDs) else: print2err("Warning: elCG could not connect to Mouse device for events.") def _unregisterMouseMonitor(self): if self._ioMouse: self._ioMouse._removeEventListener(self) def _handleEvent(self, event): """ """ event_type_index = DeviceEvent.EVENT_TYPE_ID_INDEX tix = DeviceEvent.EVENT_HUB_TIME_INDEX bix = 14 xix = 15 yix = 16 if event[event_type_index] == EventConstants.MOUSE_BUTTON_PRESS: if event[-10]==1: self._addSimulatedWintabEvent(SimulatedWinTabPacket(time=event[tix], x=event[xix], y=event[yix], press=1.0, buttons=event[bix])) elif event[event_type_index] == EventConstants.MOUSE_BUTTON_RELEASE: if event[-10]==1: self._addSimulatedWintabEvent(SimulatedWinTabPacket(time=event[tix], x=event[xix], y=event[yix], press=0.0, buttons=event[bix])) elif event[event_type_index] == EventConstants.MOUSE_MOVE: self._addSimulatedWintabEvent(SimulatedWinTabPacket(time=event[tix], x=event[xix], y=event[yix], press=0.0, buttons=event[bix])) elif event[event_type_index] == EventConstants.MOUSE_DRAG: if event[-10]==1 or event[bix]==1: self._addSimulatedWintabEvent(SimulatedWinTabPacket(time=event[tix], x=event[xix], y=event[yix], press=1.0, buttons=event[bix])) else: Device._handleEvent(self, event) ############# Wintab Event Classes #################### from .. import DeviceEvent class WintabInputEvent(DeviceEvent): """The WintabInputEvent is an abstract class that .......""" PARENT_DEVICE = Wintab _newDataTypes = [] __slots__ = [e[0] for e in _newDataTypes] def __init__(self, *args, **kwargs): DeviceEvent.__init__(self, *args, **kwargs) class WintabSampleEvent(WintabInputEvent): """WintabSampleEvent's occur when.....""" EVENT_TYPE_STRING = 'WINTAB_SAMPLE' EVENT_TYPE_ID = EventConstants.WINTAB_SAMPLE IOHUB_DATA_TABLE = EVENT_TYPE_STRING STATES = dict() # A sample that is the first sample following a time gap in the sample # stream STATES['FIRST_ENTER'] = 1 # A sample that is the first sample with pressure == 0 # following a sample with pressure > 0 STATES['FIRST_HOVER'] = 2 # A sample that has pressure == 0, and previous sample also had pressure # == 0 STATES['HOVERING'] = 4 # A sample that is the first sample with pressure > 0 # following a sample with pressure == 0 STATES['FIRST_PRESS'] = 8 # A sample that has pressure > 0 # following a sample with pressure > 0 STATES['PRESSED'] = 16 tstates = dict() for k, v in STATES.items(): tstates[v] = k for k, v in tstates.items(): STATES[k] = v _newDataTypes = [ ('serial_number', N.uint32), ('buttons', N.int32), ('x', N.int32), ('y', N.int32), ('z', N.int32), ('pressure', N.uint32), ('orient_azimuth', N.int32), ('orient_altitude', N.int32), ('orient_twist', N.int32), ('status', N.uint8) ] __slots__ = [e[0] for e in _newDataTypes] def __init__(self, *args, **kwargs): #: serial_number Hardware assigned PACKET serial number self.serial_number = None #: TODO: buttons self.buttons = None #: x Horizontal position of stylus on tablet surface. self.x = None #: y Vertical position of stylus on tablet surface. self.y = None #: z Distance of stylus tip from tablet surface #: Supported on Wacom Intuos4; other device support unknown. #: Value will between 0 and max_val, where max_val is usually 1024. #: A value of 0 = tip touching surface, while #: max_val = tip height above surface before events stop being reported. self.z = None #: pressure: Pressure of stylus tip on tablet surface. self.pressure = None #: orient_azimuth self.orient_azimuth = None #: orient_altitude self.orient_altitude = None #: orient_twist self.orient_twist = None WintabInputEvent.__init__(self, *args, **kwargs) class WintabEnterRegionEvent(WintabSampleEvent): """ TODO: WintabEnterRegionEvent doc str """ EVENT_TYPE_STRING = 'WINTAB_ENTER_REGION' EVENT_TYPE_ID = EventConstants.WINTAB_ENTER_REGION IOHUB_DATA_TABLE = WintabSampleEvent.EVENT_TYPE_STRING def __init__(self, *args, **kwargs): WintabSampleEvent.__init__(self, *args, **kwargs) class WintabLeaveRegionEvent(WintabSampleEvent): """ TODO: WintabLeaveRegionEvent doc str """ EVENT_TYPE_STRING = 'WINTAB_LEAVE_REGION' EVENT_TYPE_ID = EventConstants.WINTAB_LEAVE_REGION IOHUB_DATA_TABLE = WintabSampleEvent.EVENT_TYPE_STRING def __init__(self, *args, **kwargs): WintabSampleEvent.__init__(self, *args, **kwargs)
23,717
Python
.py
497
30.627767
148
0.483732
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,715
visualangle.py
psychopy_psychopy/psychopy/iohub/util/visualangle.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). """ Pixel to Visual Angle Calculation. Uses "symmetric angles" formula. Assumptions: 1) unit origin == position 0.0, 0.0 == screen center 2) Eye is orthogonal to origin of 2D plane """ import numpy as np arctan = np.arctan2 rad2deg = np.rad2deg hypot = np.hypot class VisualAngleCalc(): def __init__(self, display_size_mm, display_res_pix, eye_distance_mm=None): """Used to store calibrated surface information and eye to screen distance so that pixel positions can be converted to visual degree positions. Note: The information for display_size_mm,display_res_pix, and default eye_distance_mm could all be read automatically when opening a ioDataStore file. This automation should be implemented in a future release. """ self._display_width = display_size_mm[0] self._display_height = display_size_mm[1] self._display_x_resolution = display_res_pix[0] self._display_y_resolution = display_res_pix[1] self._eye_distance_mm = eye_distance_mm self.mmpp_x = self._display_width / self._display_x_resolution self.mmpp_y = self._display_height / self._display_y_resolution def pix2deg(self, pixel_x, pixel_y=None, eye_distance_mm=None): """ Stimulus positions (pixel_x,pixel_y) are defined in x and y pixel units, with the origin (0,0) being at the **center** of the display, as to match the PsychoPy pix unit coord type. The pix2deg method is vectorized, meaning that is will perform the pixel to angle calculations on all elements of the provided pixel position numpy arrays in one numpy call. The conversion process can use either a fixed eye to calibration plane distance, or a numpy array of eye distances passed as eye_distance_mm. In this case the eye distance array must be the same length as pixel_x, pixel_y arrays. """ eye_dist_mm = self._eye_distance_mm if eye_distance_mm is not None: eye_dist_mm = eye_distance_mm x_mm = self.mmpp_x * pixel_x y_mm = self.mmpp_y * pixel_y Ah = arctan(x_mm, hypot(eye_dist_mm, y_mm)) Av = arctan(y_mm, hypot(eye_dist_mm, x_mm)) return rad2deg(Ah), rad2deg(Av) ############################################################################### def generatedPointGrid(pixel_width, pixel_height, width_scalar=1.0, height_scalar=1.0, horiz_points=5, vert_points=5): """Generate a set of points in a NxM grid. Useful for creating calibration target positions, etc. """ swidth = pixel_width * width_scalar sheight = pixel_height * height_scalar # center 0 on screen center x, y = np.meshgrid(np.linspace(-swidth / 2.0, swidth / 2.0, horiz_points), np.linspace(-sheight / 2.0, sheight / 2.0, vert_points)) points = np.column_stack((x.flatten(), y.flatten())) return points # Test it if __name__ == '__main__': # physical size (w,h) of monitor in mm dsize = (600.0, 330.0) # pixel resolution of monitor dres = (1920.0, 1080.0) # eye distance to monitor in mm: edist = 550.0 # create converter class. Can be reused event if eye distance changes # from call to call. Also should support calc with vectorized inputs. vacalc = VisualAngleCalc(dsize, dres, edist) pix_20x20 = generatedPointGrid(pixel_width=1900, pixel_height=1060, horiz_points=15, vert_points=15) x_pos = pix_20x20[:, 0] y_pos = pix_20x20[:, 1] deg_20x20 = vacalc.pix2deg(x_pos, y_pos) # Plot the 2D target array in pixel and in deg corord units. from matplotlib import pyplot fig = pyplot.figure() fig.suptitle( 'Pixel to Visual Angle (Eye Dist: %.1f cm, %0.3fx%0.3f mm/pixel' % (edist / 10, vacalc.mmpp_x, vacalc.mmpp_y)) ax1 = fig.add_subplot(211) ax1.plot(x_pos, y_pos, '+g') ax1.grid(True) ax1.set_xlabel('Horizontal Pixel Pos') ax1.set_ylabel('Vertical Pixel Pos') ax2 = fig.add_subplot(212) ax2.plot(deg_20x20[0], deg_20x20[1], '+b') ax2.grid(True) ax2.set_xlabel('Horizontal Visual Angle') ax2.set_ylabel('Vertical Visual Angle') pyplot.show()
4,520
Python
.py
98
39.377551
85
0.650432
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,716
__init__.py
psychopy_psychopy/psychopy/iohub/util/__init__.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). import sys import os import copy import inspect import warnings import numpy import numbers # numbers.Integral is like (int, long) but supports Py3 import datetime from ..errors import print2err, printExceptionDetailsToStdErr import re import collections.abc import pathlib import psychopy.logging as logging import psychopy.plugins as plugins from psychopy.plugins.util import getEntryPoints from importlib.metadata import entry_points from pathlib import Path from psychopy.preferences import prefs ######################## # # .yaml read / write try: from yaml import load as yload from yaml import dump as ydump from yaml import CLoader as yLoader, CDumper as yDumper except ImportError: from yaml import Loader as yLoader, Dumper as yDumper try: from collections.abc import Iterable except ImportError: from collections import Iterable def saveConfig(config, dst_path): ''' Saves a config dict to dst_path in YAML format. ''' ydump(config, open(dst_path, 'w'), Dumper=yDumper) return os.path.exists(dst_path) def readConfig(scr_path): ''' Returns the config dict loaded from scr_path, which must be the path to a YAML file. ''' return yload(open(scr_path, 'r'), Loader=yLoader) def mergeConfigurationFiles(base_config_file_path, update_from_config_file_path, merged_save_to_path): """Merges two iohub configuration files into one and saves it to a file using the path/file name in merged_save_to_path.""" base_config = yload(open(base_config_file_path, 'r'), Loader=yLoader) update_from_config = yload( open( update_from_config_file_path, 'r'), Loader=yLoader) def merge(update, base): if isinstance(update, dict) and isinstance(base, dict): for k, v in base.items(): if k not in update: update[k] = v else: if isinstance(update[k], list): if isinstance(v, list): v.extend(update[k]) update[k] = v else: update[k].insert(0, v) else: update[k] = merge(update[k], v) return update merged = merge(copy.deepcopy(update_from_config), base_config) ydump(merged, open(merged_save_to_path, 'w'), Dumper=yDumper) return merged ######################## def normjoin(*path_parts): """ normjoin combines the following Python os.path functions in the following call order: * join * normcase * normpath Args: *path_parts (tuple): The tuple of path parts to pass to os.path.join. Returns: """ return os.path.normpath(os.path.normcase(os.path.join(*path_parts))) def addDirectoryToPythonPath(path_from_iohub_root, leaf_folder=''): from .. import IOHUB_DIRECTORY dir_path = os.path.join( IOHUB_DIRECTORY, path_from_iohub_root, sys.platform, 'python{0}{1}'.format( * sys.version_info[ 0:2]), leaf_folder) if os.path.isdir(dir_path) and dir_path not in sys.path: sys.path.append(dir_path) else: print2err('Could not add path: ', dir_path) dir_path = None return dir_path def module_path(local_function): """returns the module path without the use of __file__. Requires a function defined locally in the module. from http://stackoverflow.com/questions/729583/getting-file-path-of-imported-module """ return os.path.abspath(inspect.getsourcefile(local_function)) def module_directory(local_function): mp = module_path(local_function) moduleDirectory, mname = os.path.split(mp) return moduleDirectory def getSupportedConfigSettings(moduleName, deviceClassName=None): """Get the supported configuration settings for a device. These are usually stored as YAML files within the module directory that defines the device class. Parameters ---------- moduleName : str The name of the module to get the path for. Must be a package that defines `__init__.py`. deviceClassName : str, optional The name of the specific device class to get the path for. If not provided, the default configuration file will be searched for in the module directory. Returns ------- str The path to the supported configuration settings file in YAML format. """ yamlRoot = pathlib.Path(moduleName.__file__).parent if deviceClassName is not None: # file name for yaml file name convention for multiple files fileName = 'supported_config_settings_{0}.yaml'.format( deviceClassName.lower()) yamlFile = yamlRoot / pathlib.Path(moduleName.__file__).parent / fileName if not yamlFile.exists(): raise FileNotFoundError( "No config file found in module dir for: {0}".format( moduleName)) logging.debug( "Found ioHub device configuration file: {0}".format(yamlFile)) return str(yamlFile) # file name for yaml file name convention for single file yamlFile = yamlRoot / pathlib.Path('supported_config_settings.yaml') if not yamlFile.exists(): # nothing is found raise FileNotFoundError( "No config file found in module dir {0}".format(moduleName)) logging.debug( "Found ioHub device configuration file: {0}".format(yamlFile)) return str(yamlFile) def isIterable(o): return isinstance(o, Iterable) # Get available device module paths def getDevicePaths(device_name=""): """Get the paths to the iohub device modules that are available. Parameters ---------- device_name : str, optional The name of the device to get the paths for. If not provided, all available device paths are returned. Returns ------- list A list of tuples containing the path to the device module and the name of the device module. """ from psychopy.iohub.devices import import_device # mdc - Changes here were made to support loading device modules from # extensions. This allows support for devices that are not included in # the iohub package. def _getDevicePaths(iohub_device_path): """Look for device configuration files in the specified path. Parameters ---------- iohub_device_path : str The path to the iohub device module. Returns ------- list A list of tuples containing the path to the device module and the name of the device module. If empty, no device configuration files were found. """ yaml_paths = [] if '.zip' in iohub_device_path: # if the entry point is in a zip file, it is likely loading from a precompiled # library instead of a user installed plugin module. Raise warning. logging.error( f"Bad entry point loaded: {ep}\n" f"It is pointing into a zip file: {iohub_device_path}" ) else: # search the provided iohub_device_path for device config files for root, _, files in os.walk(iohub_device_path): # check each file in the route to see if it's a config yaml device_folder = None for file in files: if file == 'supported_config_settings.yaml': device_folder = root break if device_folder: for dfile in files: if dfile.startswith("default_") and dfile.endswith('.yaml'): # if file is a new config yaml, append it item = (device_folder, dfile) if item not in yaml_paths: yaml_paths.append(item) return yaml_paths scs_yaml_paths = [] # stores the paths to the device config files plugins.refreshBundlePaths() # make sure eyetracker external plugins are reachable # NOTE: The “selectable” entry points were introduced in importlib_metadata 3.6 and Python 3.10. # Prior to those changes, entry_points accepted no parameters and always returned a dictionary # of entry points, keyed by group. With importlib_metadata 5.0 and Python 3.12, entry_points # always returns an EntryPoints object. if 'eyetracker' in device_name.lower(): # Find entry points targeting psychopy.iohub.devices.eyetracker for ep in getEntryPoints('psychopy.iohub.devices.eyetracker', submodules=False, flatten=True): # load the target the entry point points to, it could be a class or a module try: ep_target = ep.load() except: # noqa: E722 logging.error(f"Failed to load entry point: {ep}") continue if hasattr(ep_target, "configFile"): # if entry point target binds to a yaml file, use it scs_yaml_paths.append( (ep_target.configFile.parent, ep_target.configFile.name) ) else: # otherwise, check the local folder of the target module or class deviceConfig = _getDevicePaths(os.path.dirname(inspect.getfile(ep_target))) scs_yaml_paths.extend(deviceConfig) # Use import_device() method for built-in devices iohub_device_path = module_directory(import_device) if device_name: iohub_device_path = os.path.join( iohub_device_path, device_name.replace('.', os.path.sep)) deviceConfigs = _getDevicePaths(iohub_device_path) scs_yaml_paths.extend(deviceConfigs) # Return a unique list of device config paths return list(set(scs_yaml_paths)) def getDeviceDefaultConfig(device_name, builder_hides=True): """ Return the default iohub config dictionary for the given device(s). The dictionary contains the (possibly nested) settings that should be displayed for the device (the dct item key) and the default value (the dict item value). Example: import pprint gp3_et_conf_defaults = getDeviceDefaultConfig('eyetracker.hw.gazepoint.gp3') pprint.pprint(gp3_et_conf_defaults) Output: {'calibration': {'target_delay': 0.5, 'target_duration': 1.25}, 'event_buffer_length': 1024, 'manufacturer_name': 'GazePoint', 'model_name': 'GP3', 'monitor_event_types': ['BinocularEyeSampleEvent', 'FixationStartEvent', 'FixationEndEvent'], 'network_settings': {'ip_address': '127.0.0.1', 'port': 4242}, 'runtime_settings': {'sampling_rate': 60}, 'save_events': True, 'stream_events': True} """ if device_name.endswith(".EyeTracker"): device_name = device_name[:-11] device_paths = getDevicePaths(device_name) device_configs = [] for dpath, dconf in device_paths: dname, dconf_dict = list(readConfig(os.path.join(dpath, dconf)).items())[0] if builder_hides: to_hide = dconf_dict.get('builder_hides', []) for param in to_hide: if param.find('.') >= 0: # it is a nested param param_tokens = param.split('.') cdict = dconf_dict for pt in param_tokens[:-1]: cdict = cdict.get(pt) try: del cdict[param_tokens[-1]] except KeyError: # key does not exist pass except TypeError: pass else: del dconf_dict[param] device_configs.append({dname: dconf_dict}) # if len(device_configs) == 1: # # simplify return value when only one device was requested # return list(device_configs[0].values())[0] return device_configs def getDeviceNames(device_name="eyetracker.hw", get_paths=True): """ Return a list of iohub eye tracker device names, as would be used as keys to launchHubServer. If get_paths is true, return both device manufacturer name (for display in builder) as well as iohub device name. Example: eyetrackers = getDeviceNames() print(eyetrackers) Output: [('GazePoint', 'eyetracker.gazepoint.EyeTracker'), ('MouseGaze', 'eyetracker.hw.mouse.EyeTracker'), ('SR Research Ltd', 'eyetracker.eyelink.EyeTracker'), ('Tobii Technology', 'eyetracker.tobii.EyeTracker')] """ names = [] dconfigs = getDeviceDefaultConfig(device_name) for dcfg in dconfigs: d_path = tuple(dcfg.keys())[0] d_config = tuple(dcfg.values())[0] if get_paths is False: names.append(d_path) else: names.append((d_config.get('manufacturer_name'), d_path)) return names def getDeviceFile(device_name, file_name): """ Returns the contents of file_name for the specified device. If file_name does not exist, None is returned. :param device_name: iohub device name :param: file_name: name of device yaml file to load :return: dict """ if device_name.endswith(".EyeTracker"): device_name = device_name[:-11] device_paths = getDevicePaths(device_name) device_sconfigs = [] for dpath, _ in device_paths: device_sconfigs.append(readConfig(os.path.join(dpath, file_name))) if len(device_sconfigs) == 1: # simplify return value when only one device was requested return list(device_sconfigs[0].values())[0] return device_sconfigs def getDeviceSupportedConfig(device_name): """ Returns the contents of the supported_config_settings.yaml for the specified device. :param device_name: iohub device name :return: dict """ return getDeviceFile(device_name, 'supported_config_settings.yaml') if sys.platform == 'win32': import pythoncom def win32MessagePump(): """Pumps the Windows Message Queue so that PsychoPy Window(s) lock up if psychopy has not called the windows 'dispatch_events()' method recently. If you are not flipping regularly (say because you do not need to and do not want to block frequently, you can call this, which will not block waiting for messages, but only pump out what is in the queue already. On an i7 desktop, this call method takes between 10 and 90 usec. """ if pythoncom.PumpWaitingMessages() == 1: raise KeyboardInterrupt() else: def win32MessagePump(): pass # PsychoPy Window Hide / Show functions. # Windows 10 and macOS have different code that needs to be called # to show a second full screen window on top of an existing one, like # is done by most eye tracker calibration routines. def hideWindow(win, force=False): """ If needed, hide / minimize the in. :param win: PsychoPy window instance :return: None """ if force or sys.platform == 'win32': if win._isFullScr: win.winHandle.minimize() # minimize the PsychoPy window win.winHandle.set_fullscreen(False) elif sys.platform == 'darwin': pass elif sys.platform == 'linux': # TODO: test on Linux, assuming same as macOS right now pass else: print("Warning: Unhandled sys.platform: ", sys.platform) def showWindow(win, force=False): """ If needed, hide / minimize the in. :param win: PsychoPy window instance :return: None """ if force or sys.platform == 'win32': if win._isFullScr: win.winHandle.set_fullscreen(True) win.winHandle.maximize() # maximize the PsychoPy window elif sys.platform == 'darwin': pass elif sys.platform == 'linux': # TODO: test on Linux, assuming same as macOS right now pass else: print("Warning: Unhandled sys.platform: ", sys.platform) def createCustomCalibrationStim(win, cal_settings): """ Create a custom calibration target using the CUSTOM eyetracker calibration settings. Returns an instance of target_attributes:custom:class_name class. If no custom target is defined, returns None. :param win: psychopy.visual.Window instance :param cal_settings: eye tracker calibration settings dictionary :return: visual stim instance """ try: import importlib custom_target_settings = cal_settings.get('target_attributes').get('custom') TargetClass = getattr(importlib.import_module(custom_target_settings.get('module_name')), custom_target_settings.get('class_name')) targ_kwargs = custom_target_settings.get('class_kwargs', {}) targ_kwargs['win'] = win path_kwargs = ['filename', 'image'] for pkwarg in path_kwargs: if pkwarg in targ_kwargs.keys(): if not os.path.isfile(targ_kwargs.get(pkwarg)): import psychopy abspath = os.path.join(psychopy.iohub.EXP_SCRIPT_DIRECTORY, targ_kwargs.get(pkwarg)) if os.path.isfile(abspath): targ_kwargs[pkwarg] = abspath # Instantiate the class (pass arguments to the constructor, if needed) return TargetClass(**targ_kwargs) except Exception: printExceptionDetailsToStdErr() print2err("Error creating custom iohub calibration graphics. Using default FixationTarget.") def getObjectModuleAndClassName(obj, split=True): """ Get the fully-qualified class name of a python object. """ cls = type(obj) module = cls.__module__ name = cls.__qualname__ if module in ("__builtin__", "__main__"): module = None if split: return module, name if module is not None: name = module + "." + name return name # Recursive updating of values from one dict into another if the key does not key exist. # Supported nested dicts and uses deep copy when setting values in the # target dict. def updateDict(add_to, add_from): for key, value in add_from.items(): if key not in add_to: add_to[key] = copy.deepcopy(value) elif isinstance(value, dict) and isinstance(add_to[key], dict): updateDict(add_to[key], value) def updateSettings(d, u): for k, v in u.items(): if isinstance(k, bytes): k = k.decode('UTF-8') if isinstance(v, collections.abc.Mapping): d[k] = updateSettings(d.get(k, {}), v) else: if isinstance(v, bytes): v = v.decode('UTF-8') d[k] = v return d # Convert Camel to Snake variable name format first_cap_re = re.compile('(.)([A-Z][a-z]+)') all_cap_re = re.compile('([a-z0-9])([A-Z])') def convertCamelToSnake(name, lower_snake=True): s1 = first_cap_re.sub(r'\1_\2', name) if lower_snake: return all_cap_re.sub(r'\1_\2', s1).lower() return all_cap_re.sub(r'\1_\2', s1).upper() # A couple date / time related utility functions getCurrentDateTime = datetime.datetime.now getCurrentDateTimeString = lambda: getCurrentDateTime().strftime("%Y-%m-%d %H:%M") # noqa: E731 # rgb255 color utils def hilo(a, b, c): if c < b: b, c = c, b if b < a: a, b = b, a if c < b: b, c = c, b return a + c def complement(r, g, b): if r == g == b: # handle mono color if r >= 128: return 0, 0, 0 return 255, 255, 255 k = hilo(r, g, b) return tuple(k - u for u in (r, g, b)) class NumPyRingBuffer(): """NumPyRingBuffer is a circular buffer implemented using a one dimensional numpy array on the backend. The algorithm used to implement the ring buffer behavior does not require any array copies to occur while the ring buffer is maintained, while at the same time allowing sequential element access into the numpy array using a subset of standard slice notation. When the circular buffer is created, a maximum size , or maximum number of elements, that the buffer can hold *must* be specified. When the buffer becomes full, each element added to the buffer removes the oldest element from the buffer so that max_size is never exceeded. Items are added to the ring buffer using the classes append method. The current number of elements in the buffer can be retrieved using the getLength() method of the class. The isFull() method can be used to determine if the ring buffer has reached its maximum size, at which point each new element added will disregard the oldest element in the array. The getElements() method is used to retrieve the actual numpy array containing the elements in the ring buffer. The element in index 0 is the oldest remaining element added to the buffer, and index n (which can be up to max_size-1) is the most recent element added to the buffer. Methods that can be called from a standard numpy array can also be called using the NumPyRingBuffer instance created. However Numpy module level functions will not accept a NumPyRingBuffer as a valid argument. To clear the ring buffer and start with no data in the buffer, without needing to create a new NumPyRingBuffer object, call the clear() method of the class. Example:: ring_buffer=NumPyRingBuffer(10) for i in range(25): ring_buffer.append(i) print('-------') print('Ring Buffer Stats:') print('\tWindow size: ',len(ring_buffer)) print('\tMin Value: ',ring_buffer.min()) print('\tMax Value: ',ring_buffer.max()) print('\tMean Value: ',ring_buffer.mean()) print('\tStandard Deviation: ',ring_buffer.std()) print('\tFirst 3 Elements: ',ring_buffer[:3]) print('\tLast 3 Elements: ',ring_buffer[-3:]) """ def __init__(self, max_size, dtype=numpy.float32): self._dtype = dtype self._npa = numpy.empty(max_size * 2, dtype=dtype) self.max_size = max_size self._index = 0 def append(self, element): """Add element e to the end of the RingBuffer. The element must match the numpy data type specified when the NumPyRingBuffer was created. By default, the RingBuffer uses float32 values. If the Ring Buffer is full, adding the element to the end of the array removes the currently oldest element from the start of the array. :param numpy.dtype element: An element to add to the RingBuffer. :returns None: """ i = self._index self._npa[i % self.max_size] = element self._npa[(i % self.max_size) + self.max_size] = element self._index += 1 def getElements(self): """Return the numpy array being used by the RingBuffer, the length of which will be equal to the number of elements added to the list, or the last max_size elements added to the list. Elements are in order of addition to the ring buffer. :param None: :returns numpy.array: The array of data elements that make up the Ring Buffer. """ return self._npa[ self._index % self.max_size:( self._index % self.max_size) + self.max_size] def isFull(self): """Indicates if the RingBuffer is at it's max_size yet. :param None: :returns bool: True if max_size or more elements have been added to the RingBuffer; False otherwise. """ return self._index >= self.max_size def clear(self): """Clears the RingBuffer. The next time an element is added to the buffer, it will have a size of one. :param None: :returns None: """ self._index = 0 def __setitem__(self, indexs, v): if isinstance(indexs, (list, tuple)): for i in indexs: if isinstance(i, numbers.Integral): i = i + self._index self._npa[i % self.max_size] = v self._npa[(i % self.max_size) + self.max_size] = v elif isinstance(i, slice): istart = indexs.start if istart is None: istart = 0 istop = indexs.stop if indexs.stop is None: istop = 0 start = istart + self._index stop = istop + self._index self._npa[ slice( start % self.max_size, stop % self.max_size, i.step)] = v self._npa[ slice( (start % self.max_size) + self.max_size, (stop % self.max_size) + self.max_size, i.step)] = v elif isinstance(indexs, numbers.Integral): i = indexs + self._index self._npa[i % self.max_size] = v self._npa[(i % self.max_size) + self.max_size] = v elif isinstance(indexs, slice): istart = indexs.start if istart is None: istart = 0 istop = indexs.stop if indexs.stop is None: istop = 0 start = istart + self._index stop = istop + self._index self._npa[ slice( start % self.max_size, stop % self.max_size, indexs.step)] = v self._npa[ slice( (start % self.max_size) + self.max_size, (stop % self.max_size) + self.max_size, indexs.step)] = v else: raise TypeError() def __getitem__(self, indexs): current_array = self.getElements() if isinstance(indexs, (list, tuple)): rarray = [] for i in indexs: if isinstance(i, int): rarray.append(current_array[i]) elif isinstance(i, slice): rarray.extend(current_array[i]) return numpy.asarray(rarray, dtype=self._dtype) elif isinstance(indexs, (int, slice)): return current_array[indexs] else: raise TypeError() def __getattr__(self, a): if self._index < self.max_size: return getattr(self._npa[:self._index], a) return getattr( self._npa[ self._index % self.max_size:( self._index % self.max_size) + self.max_size], a) def __len__(self): if self.isFull(): return self.max_size return self._index ############################################################################### # # Generate a set of points in a NxM grid. Useful for creating calibration target positions, # or grid spaced fixation point positions that can be used for validation / fixation accuracy. # def generatedPointGrid(pixel_width, pixel_height, width_scalar=1.0, height_scalar=1.0, horiz_points=5, vert_points=5): swidth = pixel_width * width_scalar sheight = pixel_height * height_scalar # center 0 on screen center x, y = numpy.meshgrid(numpy.linspace(-swidth / 2.0, swidth / 2.0, horiz_points), numpy.linspace(-sheight / 2.0, sheight / 2.0, vert_points)) points = numpy.column_stack((x.flatten(), y.flatten())) return points # Rotate a set of points in 2D # # Rotate a set of n 2D points in the form [[x1,x1],[x2,x2],...[xn,xn]] # around the 2D point origin (x0,y0), by ang radians. # Returns the rotated point list. # # FROM: # http://gis.stackexchange.com/questions/23587/how-do-i-rotate-the-polygon-about-an-anchor-point-using-python-script def rotate2D(pts, origin, ang=None): '''pts = {} Rotates points(nx2) about center cnt(2) by angle ang(1) in radian''' if ang is None: ang = numpy.pi / 4 return numpy.dot(pts - origin, numpy.array([[numpy.cos(ang), numpy.sin(ang)], [-numpy.sin(ang), numpy.cos(ang)]])) + origin
29,320
Python
.py
687
33.014556
119
0.608609
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,717
windowwarp.py
psychopy_psychopy/psychopy/visual/windowwarp.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Copyright (C) 2014 Allen Institute for Brain Science This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License Version 3 as published by the Free Software Foundation on 29 June 2007. This program is distributed WITHOUT WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE OR ANY OTHER WARRANTY, EXPRESSED OR IMPLIED. See the GNU General Public License Version 3 for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ """ import ctypes import numpy as np from psychopy import logging import pyglet GL = pyglet.gl class Warper: """Class to perform warps. Supports spherical, cylindrical, warpfile, or None (disabled) warps """ def __init__(self, win, warp=None, warpfile=None, warpGridsize=300, eyepoint=(0.5, 0.5), flipHorizontal=False, flipVertical=False): """Warping is a final operation which can be optionally performed on each frame just before transmission to the display. It is useful for perspective correction when the eye to monitor distance is small (say, under 50 cm), or when projecting to domes or other non-planar surfaces. These attributes define the projection and can be altered dynamically using the changeProjection() method. :Parameters: win : Handle to the window. warp : 'spherical', 'cylindrical, 'warpfile' or *None* This table gives the main properties of each projection +-----------+---------------+-----------+------------+--------------------+ | Warp | eyepoint | verticals | horizontals| perspective correct| | | modifies warp | parallel | parallel | | +===========+===============+===========+============+====================+ |spherical | y | n | n | y | +-----------+---------------+-----------+------------+--------------------+ |cylindrical| y | y | n | n | +-----------+---------------+-----------+------------+--------------------+ | warpfile | n | ? | ? | ? | +-----------+---------------+-----------+------------+--------------------+ | None | n | y | y | n | +-----------+---------------+-----------+------------+--------------------+ warpfile : *None* or filename containing Blender and Paul Bourke compatible warp definition. (see http://paulbourke.net/dome/warpingfisheye/) warpGridsize : 300 Defines the resolution of the warp in both X and Y when not using a warpfile. Typical values would be 64-300 trading off tolerance for jaggies for speed. eyepoint : [0.5, 0.5] center of the screen Position of the eye in X and Y as a fraction of the normalized screen width and height. [0,0] is the bottom left of the screen. [1,1] is the top right of the screen. flipHorizontal: True or *False* Flip the entire output horizontally. Useful for back projection scenarious. flipVertical: True or *False* Flip the entire output vertically. useful if projector is flipped upside down. :notes: 1) The eye distance from the screen is initialized from the monitor definition. 2) The eye distance can be altered dynamically by changing 'warper.dist_cm' and then calling changeProjection(). Example usage to create a spherical projection:: from psychopy.visual.windowwarp import Warper win = Window(monitor='testMonitor', screen=1, fullscr=True, useFBO = True) warper = Warper(win, warp='spherical', warpfile = "", warpGridsize = 128, eyepoint = [0.5, 0.5], flipHorizontal = False, flipVertical = False) """ super(Warper, self).__init__() self.win = win # monkey patch the warp method win._renderFBO = self.drawWarp self.warp = warp self.warpfile = warpfile self.warpGridsize = warpGridsize self.eyepoint = eyepoint self.flipHorizontal = flipHorizontal self.flipVertical = flipVertical self.initDefaultWarpSize() # get the eye distance from the monitor object, # but the pixel dimensions from the actual window object w, h = win.size self.aspect = w/h self.dist_cm = win.monitor.getDistance() if self.dist_cm is None: # create a fake monitor if one isn't defined self.dist_cm = 30.0 self.mon_width_cm = 50.0 logging.warning('Monitor is not calibrated') else: self.mon_width_cm = win.monitor.getWidth() self.mon_height_cm = self.mon_width_cm / self.aspect self.mon_width_pix = w self.mon_height_pix = h self.changeProjection(self.warp, self.warpfile, self.eyepoint) def drawWarp(self): """Warp the output, using the vertex, texture, and optionally an opacity array. """ GL.glUseProgram(0) GL.glColorMask(True, True, True, True) # point to color (opacity) if self.gl_color is not None: GL.glEnableClientState(GL.GL_COLOR_ARRAY) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self.gl_color) GL.glColorPointer(4, GL.GL_FLOAT, 0, None) GL.glEnable(GL.GL_BLEND) GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ZERO) # point to vertex data GL.glEnableClientState(GL.GL_VERTEX_ARRAY) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self.gl_vb) GL.glVertexPointer(2, GL.GL_FLOAT, 0, None) # point to texture GL.glEnableClientState(GL.GL_TEXTURE_COORD_ARRAY) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self.gl_tb) GL.glTexCoordPointer(2, GL.GL_FLOAT, 0, None) # draw quads GL.glDrawArrays(GL.GL_QUADS, 0, self.nverts) # cleanup GL.glBindBuffer(GL.GL_ARRAY_BUFFER, 0) GL.glDisableClientState(GL.GL_VERTEX_ARRAY) GL.glDisableClientState(GL.GL_TEXTURE_COORD_ARRAY) if self.gl_color is not None: GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA) GL.glDisableClientState(GL.GL_COLOR_ARRAY) def initDefaultWarpSize(self): self.xgrid = self.warpGridsize self.ygrid = self.warpGridsize def changeProjection(self, warp, warpfile=None, eyepoint=(0.5, 0.5), flipHorizontal=False, flipVertical=False): """Allows changing the warp method on the fly. Uses the same parameter definitions as constructor. """ self.warp = warp self.warpfile = warpfile self.eyepoint = list(eyepoint) self.flipHorizontal = flipHorizontal self.flipVertical = flipVertical # warpfile might have changed the size... self.initDefaultWarpSize() if self.warp is None: self.projectionNone() elif self.warp == 'spherical': self.projectionSphericalOrCylindrical(False) elif self.warp == 'cylindrical': self.projectionSphericalOrCylindrical(True) elif self.warp == 'warpfile': self.projectionWarpfile() else: raise ValueError('Unknown warp specification: %s' % self.warp) def projectionNone(self): """No warp, same projection as original PsychoPy """ # Vertex data v0 = (-1.0, -1.0) v1 = (-1.0, 1.0) v2 = (1.0, 1.0) v3 = (1.0, -1.0) # Texture coordinates t0 = (0.0, 0.0) t1 = (0.0, 1.0) t2 = (1.0, 1.0) t3 = (1.0, 0.0) vertices = np.array([v0, v1, v2, v3], 'float32') tcoords = np.array([t0, t1, t2, t3], 'float32') # draw four quads during rendering loop self.nverts = 4 self.createVertexAndTextureBuffers(vertices, tcoords) def projectionSphericalOrCylindrical(self, isCylindrical=False): """Correct perspective on flat screen using either a spherical or cylindrical projection. """ self.nverts = (self.xgrid - 1) * (self.ygrid - 1) * 4 # eye position in cm xEye = self.eyepoint[0] * self.mon_width_cm yEye = self.eyepoint[1] * self.mon_height_cm # create vertex grid array, and texture coords # times 4 for quads vertices = np.zeros( ((self.xgrid - 1) * (self.ygrid - 1) * 4, 2), dtype='float32') tcoords = np.zeros( ((self.xgrid - 1) * (self.ygrid - 1) * 4, 2), dtype='float32') equalDistanceX = np.linspace(0, self.mon_width_cm, self.xgrid) equalDistanceY = np.linspace(0, self.mon_height_cm, self.ygrid) # vertex coordinates x_c = np.linspace(-1.0, 1.0, self.xgrid) y_c = np.linspace(-1.0, 1.0, self.ygrid) x_coords, y_coords = np.meshgrid(x_c, y_c) x = np.zeros(((self.xgrid), (self.ygrid)), dtype='float32') y = np.zeros(((self.xgrid), (self.ygrid)), dtype='float32') x[:, :] = equalDistanceX - xEye y[:, :] = equalDistanceY - yEye y = np.transpose(y) r = np.sqrt(np.square(x) + np.square(y) + np.square(self.dist_cm)) azimuth = np.arctan(x / self.dist_cm) altitude = np.arcsin(y / r) # calculate the texture coordinates if isCylindrical: tx = self.dist_cm * np.sin(azimuth) ty = self.dist_cm * np.sin(altitude) else: tx = self.dist_cm * (1 + x/r) - self.dist_cm ty = self.dist_cm * (1 + y/r) - self.dist_cm # prevent div0 azimuth[azimuth == 0] = np.finfo(np.float32).eps altitude[altitude == 0] = np.finfo(np.float32).eps # the texture coordinates (which are now lying on the sphere) # need to be remapped back onto the plane of the display. # This effectively stretches the coordinates away from the eyepoint. if isCylindrical: tx = tx * azimuth / np.sin(azimuth) ty = ty * altitude / np.sin(altitude) else: centralAngle = np.arccos( np.cos(altitude) * np.cos(np.abs(azimuth))) # distance from eyepoint to texture vertex arcLength = centralAngle * self.dist_cm # remap the texture coordinate theta = np.arctan2(ty, tx) tx = arcLength * np.cos(theta) ty = arcLength * np.sin(theta) u_coords = tx / self.mon_width_cm + 0.5 v_coords = ty / self.mon_height_cm + 0.5 # loop to create quads vdex = 0 for y in range(0, self.ygrid - 1): for x in range(0, self.xgrid - 1): index = y * (self.xgrid) + x vertices[vdex + 0, 0] = x_coords[y, x] vertices[vdex + 0, 1] = y_coords[y, x] vertices[vdex + 1, 0] = x_coords[y, x + 1] vertices[vdex + 1, 1] = y_coords[y, x + 1] vertices[vdex + 2, 0] = x_coords[y + 1, x + 1] vertices[vdex + 2, 1] = y_coords[y + 1, x + 1] vertices[vdex + 3, 0] = x_coords[y + 1, x] vertices[vdex + 3, 1] = y_coords[y + 1, x] tcoords[vdex + 0, 0] = u_coords[y, x] tcoords[vdex + 0, 1] = v_coords[y, x] tcoords[vdex + 1, 0] = u_coords[y, x + 1] tcoords[vdex + 1, 1] = v_coords[y, x + 1] tcoords[vdex + 2, 0] = u_coords[y + 1, x + 1] tcoords[vdex + 2, 1] = v_coords[y + 1, x + 1] tcoords[vdex + 3, 0] = u_coords[y + 1, x] tcoords[vdex + 3, 1] = v_coords[y + 1, x] vdex += 4 self.createVertexAndTextureBuffers(vertices, tcoords) def projectionWarpfile(self): """Use a warp definition file to create the projection. See: http://paulbourke.net/dome/warpingfisheye/ """ try: fh = open(self.warpfile) lines = fh.readlines() fh.close() filetype = int(lines[0]) rc = list(map(int, lines[1].split())) cols, rows = rc[0], rc[1] warpdata = np.loadtxt(self.warpfile, skiprows=2) except Exception: error = 'Unable to read warpfile: ' + self.warpfile logging.warning(error) print(error) return if (cols * rows != warpdata.shape[0] or warpdata.shape[1] != 5 or filetype != 2): error = 'warpfile data incorrect: ' + self.warpfile logging.warning(error) print(error) return self.xgrid = cols self.ygrid = rows self.nverts = (self.xgrid - 1) * (self.ygrid - 1) * 4 # create vertex grid array, and texture coords times 4 for quads vertices = np.zeros( ((self.xgrid - 1) * (self.ygrid - 1) * 4, 2), dtype='float32') tcoords = np.zeros( ((self.xgrid - 1) * (self.ygrid - 1) * 4, 2), dtype='float32') # opacity is RGBA opacity = np.ones( ((self.xgrid - 1) * (self.ygrid - 1) * 4, 4), dtype='float32') # loop to create quads vdex = 0 for y in range(0, self.ygrid - 1): for x in range(0, self.xgrid - 1): index = y * (self.xgrid) + x vertices[vdex + 0, 0] = warpdata[index, 0] # x_coords[y,x] vertices[vdex + 0, 1] = warpdata[index, 1] # y_coords[y,x] # x_coords[y,x+1] vertices[vdex + 1, 0] = warpdata[index + 1, 0] # y_coords[y,x+1] vertices[vdex + 1, 1] = warpdata[index + 1, 1] # x_coords[y+1,x+1] vertices[vdex + 2, 0] = warpdata[index + cols + 1, 0] # y_coords[y+1,x+1] vertices[vdex + 2, 1] = warpdata[index + cols + 1, 1] # x_coords[y+1,x] vertices[vdex + 3, 0] = warpdata[index + cols, 0] # y_coords[y+1,x] vertices[vdex + 3, 1] = warpdata[index + cols, 1] # u_coords[y,x] tcoords[vdex + 0, 0] = warpdata[index, 2] # v_coords[y,x] tcoords[vdex + 0, 1] = warpdata[index, 3] # u_coords[y,x+1]: tcoords[vdex + 1, 0] = warpdata[index + 1, 2] # v_coords[y,x+1]: tcoords[vdex + 1, 1] = warpdata[index + 1, 3] # u_coords[y+1,x+1]: tcoords[vdex + 2, 0] = warpdata[index + cols + 1, 2] # v_coords[y+1,x+1]: tcoords[vdex + 2, 1] = warpdata[index + cols + 1, 3] # u_coords[y+1,x] tcoords[vdex + 3, 0] = warpdata[index + cols, 2] # v_coords[y+1,x]: tcoords[vdex + 3, 1] = warpdata[index + cols, 3] opacity[vdex, 3] = warpdata[index, 4] opacity[vdex + 1, 3] = warpdata[index + 1, 4] opacity[vdex + 2, 3] = warpdata[index + cols + 1, 4] opacity[vdex + 3, 3] = warpdata[index + cols, 4] vdex += 4 self.createVertexAndTextureBuffers(vertices, tcoords, opacity) def createVertexAndTextureBuffers(self, vertices, tcoords, opacity=None): """Allocate hardware buffers for vertices, texture coordinates, and optionally opacity. """ if self.flipHorizontal: vertices[:, 0] = -vertices[:, 0] if self.flipVertical: vertices[:, 1] = -vertices[:, 1] GL.glEnableClientState(GL.GL_VERTEX_ARRAY) # type and size for arrays arrType = ctypes.c_float ptrType = ctypes.POINTER(arrType) nbytes = ctypes.sizeof(arrType) # vertex buffer in hardware self.gl_vb = GL.GLuint() GL.glGenBuffers(1, self.gl_vb) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self.gl_vb) GL.glBufferData( GL.GL_ARRAY_BUFFER, vertices.size * nbytes, vertices.ctypes.data_as(ptrType), GL.GL_STATIC_DRAW) # vertex buffer texture data in hardware self.gl_tb = GL.GLuint() GL.glGenBuffers(1, self.gl_tb) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self.gl_tb) GL.glBufferData( GL.GL_ARRAY_BUFFER, tcoords.size * nbytes, tcoords.ctypes.data_as(ptrType), GL.GL_STATIC_DRAW) # opacity buffer in hardware (only for warp files) if opacity is not None: self.gl_color = GL.GLuint() GL.glGenBuffers(1, self.gl_color) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self.gl_color) # convert opacity to RGBA, one point for each corner of the quad GL.glBufferData( GL.GL_ARRAY_BUFFER, opacity.size * nbytes, opacity.ctypes.data_as(ptrType), GL.GL_STATIC_DRAW) else: self.gl_color = None GL.glBindBuffer(GL.GL_ARRAY_BUFFER, 0) GL.glDisableClientState(GL.GL_VERTEX_ARRAY)
18,099
Python
.py
388
34.744845
91
0.533896
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,718
filters.py
psychopy_psychopy/psychopy/visual/filters.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Various useful functions for creating filters and textures (e.g. for PatchStim) """ # 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 from numpy.fft import fft2, ifft2, fftshift, ifftshift def makeGrating(res, ori=0.0, # in degrees cycles=1.0, phase=0.0, # in degrees gratType="sin", contr=1.0): """Make an array containing a luminance grating of the specified params :Parameters: res: integer the size of the resulting matrix on both dimensions (e.g 256) ori: float or int (default=0.0) the orientation of the grating in degrees cycles:float or int (default=1.0) the number of grating cycles within the array phase: float or int (default=0.0) the phase of the grating in degrees (NB this differs to most PsychoPy phase arguments which use units of fraction of a cycle) gratType: 'sin', 'sqr', 'ramp' or 'sinXsin' (default="sin") the type of grating to be 'drawn' contr: float (default=1.0) contrast of the grating :Returns: a square numpy array of size resXres """ # to prevent the sinusoid ever being exactly at zero (for sqr wave): tiny = 0.0000000000001 ori *= -numpy.pi / 180. phase *= numpy.pi / 180. cyclesTwoPi = cycles * 2.0 * numpy.pi xrange, yrange = numpy.mgrid[ 0.0:cyclesTwoPi:(cyclesTwoPi / res), 0.0:cyclesTwoPi:(cyclesTwoPi / res)] sin, cos = numpy.sin, numpy.cos if gratType == "none": res = 2 intensity = numpy.ones((res, res), float) elif gratType == "sin": intensity = contr * sin(xrange * sin(ori) + yrange * cos(ori) + phase) elif gratType == "ramp": intensity = contr * (xrange * cos(ori) + yrange * sin(ori)) / (2 * numpy.pi) elif gratType == "sqr": # square wave (symmetric duty cycle) intensity = numpy.where(sin(xrange * sin(ori) + yrange * cos(ori) + phase + tiny) >= 0, 1, -1) elif gratType == "sinXsin": intensity = sin(xrange) * sin(yrange) else: # might be a filename of an image # try: # im = Image.open(gratType) # except Exception: # logging.error("couldn't find tex...", gratType) # return # # todo: opened it, now what? raise ValueError("Invalid value for parameter `gratType`.") return intensity def maskMatrix(matrix, shape='circle', radius=1.0, center=(0.0, 0.0)): """Make and apply a mask to an input matrix (e.g. a grating) :Parameters: matrix: a square numpy array array to which the mask should be applied shape: 'circle','gauss','ramp' (linear gradient from center) shape of the mask radius: float scale factor to be applied to the mask (circle with radius of [1,1] will extend just to the edge of the matrix). Radius can be asymmetric, e.g. [1.0,2.0] will be wider than it is tall. center: 2x1 tuple or list (default=[0.0,0.0]) the centre of the mask in the matrix ([1,1] is top-right corner, [-1,-1] is bottom-left) """ # NB makeMask now returns a value -1:1 alphaMask = makeMask(matrix.shape[0], shape, radius, center=(0.0, 0.0), range=[0, 1]) return matrix * alphaMask def makeMask(matrixSize, shape='circle', radius=1.0, center=(0.0, 0.0), range=(-1, 1), fringeWidth=0.2): """Returns a matrix to be used as an alpha mask (circle,gauss,ramp). :Parameters: matrixSize: integer the size of the resulting matrix on both dimensions (e.g 256) shape: 'circle','gauss','ramp' (linear gradient from center), 'raisedCosine' (the edges are blurred by a raised cosine) shape of the mask radius: float scale factor to be applied to the mask (circle with radius of [1,1] will extend just to the edge of the matrix). Radius can asymmetric, e.g. [1.0,2.0] will be wider than it is tall. center: 2x1 tuple or list (default=[0.0,0.0]) the centre of the mask in the matrix ([1,1] is top-right corner, [-1,-1] is bottom-left) fringeWidth: float (0-1) The proportion of the raisedCosine that is being blurred. range: 2x1 tuple or list (default=[-1,1]) The minimum and maximum value in the mask matrix """ rad = makeRadialMatrix(matrixSize, center, radius) if shape == 'ramp': outArray = 1 - rad elif shape == 'circle': # outArray=numpy.ones(matrixSize,'f') outArray = numpy.where(numpy.greater(rad, 1.0), 0.0, 1.0) elif shape == 'gauss': outArray = makeGauss(rad, mean=0.0, sd=0.33333) elif shape == 'raisedCosine': hammingLen = 1000 # This affects the 'granularity' of the raised cos fringeProportion = fringeWidth # This one affects the proportion of # the stimulus diameter that is devoted to the raised cosine. rad = makeRadialMatrix(matrixSize, center, radius) outArray = numpy.zeros_like(rad) outArray[numpy.where(rad < 1)] = 1 raisedCosIdx = numpy.where( [numpy.logical_and(rad <= 1, rad >= 1 - fringeProportion)])[1:] # Make a raised_cos (half a hamming window): raisedCos = numpy.hamming(hammingLen)[:hammingLen//2] raisedCos -= numpy.min(raisedCos) raisedCos /= numpy.max(raisedCos) # Measure the distance from the edge - this is your index into the # hamming window: dFromEdge = numpy.abs((1 - fringeProportion) - rad[raisedCosIdx]) dFromEdge /= numpy.max(dFromEdge) dFromEdge *= numpy.round(hammingLen/2) # This is the indices into the hamming (larger for small distances # from the edge!): portion_idx = (-1 * dFromEdge).astype(int) # Apply the raised cos to this portion: outArray[raisedCosIdx] = raisedCos[portion_idx] # Sometimes there are some remaining artifacts from this process, get # rid of them: artifact_idx = numpy.where( numpy.logical_and(outArray == 0, rad < 0.99)) outArray[artifact_idx] = 1 artifact_idx = numpy.where( numpy.logical_and(outArray == 1, rad > 0.99)) outArray[artifact_idx] = 0 else: raise ValueError('Unknown value for shape argument %s' % shape) mag = range[1] - range[0] offset = range[0] return outArray * mag + offset def makeRadialMatrix(matrixSize, center=(0.0, 0.0), radius=1.0): """Generate a square matrix where each element values is its distance from the centre of the matrix. Parameters ---------- matrixSize : int Matrix size. Corresponds to the number of elements along each dimension. Must be >0. radius: float scale factor to be applied to the mask (circle with radius of [1,1] will extend just to the edge of the matrix). Radius can be asymmetric, e.g. [1.0,2.0] will be wider than it is tall. center: 2x1 tuple or list (default=[0.0,0.0]) the centre of the mask in the matrix ([1,1] is top-right corner, [-1,-1] is bottom-left) Returns ------- ndarray Square matrix populated with distance values and `size == (matrixSize, matrixSize)`. """ if type(radius) in [int, float]: radius = [radius, radius] try: matrixSize = int(matrixSize) except ValueError: raise TypeError('parameter `matrixSize` must be a numeric type') if matrixSize <= 1: raise ValueError( 'parameter `matrixSize` must be positive and greater than 1, got: {}'.format( matrixSize)) # NB need to add one step length because yy, xx = numpy.mgrid[0:matrixSize, 0:matrixSize] xx = ((1.0 - 2.0 / matrixSize * xx) + center[0]) / radius[0] yy = ((1.0 - 2.0 / matrixSize * yy) + center[1]) / radius[1] rad = numpy.sqrt(numpy.power(xx, 2) + numpy.power(yy, 2)) return rad def makeGauss(x, mean=0.0, sd=1.0, gain=1.0, base=0.0): """ Return the gaussian distribution for a given set of x-vals :Parameters: mean: float the centre of the distribution sd: float the width of the distribution gain: float the height of the distribution base: float an offset added to the result """ simpleGauss = numpy.exp((-numpy.power(mean - x, 2) / (2 * sd**2))) return base + gain * simpleGauss def make2DGauss(x,y, mean=0.0, sd=1.0, gain=1.0, base=0.0): """ Return the gaussian distribution for a given set of x-vals Parameters ----------- x,y : should be x and y indexes as might be created by numpy.mgrid mean: float the centre of the distribution - may be a tuple sd: float the width of the distribution - may be a tuple gain: float the height of the distribution base: float an offset added to the result """ if numpy.size(sd)==1: sd = [sd, sd] if numpy.size(mean)==1: mean = [mean, mean] simpleGauss = numpy.exp((-numpy.power(x - mean[0], 2) / (2 * sd[0]**2))-(numpy.power(y - mean[1], 2) / (2 * sd[1]**2))) return base + gain * simpleGauss def getRMScontrast(matrix): """Returns the RMS contrast (the sample standard deviation) of a array """ RMScontrast = numpy.std(matrix) return RMScontrast def conv2d(smaller, larger): """Convolve a pair of 2d numpy matrices. Uses fourier transform method, so faster if larger matrix has dimensions of size 2**n Actually right now the matrices must be the same size (will sort out padding issues another day!) """ smallerFFT = fft2(smaller) largerFFT = fft2(larger) invFFT = ifft2(smallerFFT * largerFFT) return invFFT.real def imfft(X): """Perform 2D FFT on an image and center low frequencies """ return fftshift(fft2(X)) def imifft(X): """Inverse 2D FFT with decentering """ return numpy.abs(ifft2(ifftshift(X))) def butter2d_lp(size, cutoff, n=3): """Create lowpass 2D Butterworth filter. :Parameters: size : tuple size of the filter cutoff : float relative cutoff frequency of the filter (0 - 1.0) n : int, optional order of the filter, the higher n is the sharper the transition is. :Returns: numpy.ndarray filter kernel in 2D centered """ if not 0 < cutoff <= 1.0: raise ValueError('Cutoff frequency must be between 0 and 1.0') if not isinstance(n, int): raise ValueError('n must be an integer >= 1') rows, cols = size x = numpy.linspace(-0.5, 0.5, cols) y = numpy.linspace(-0.5, 0.5, rows) # An array with every pixel = radius relative to center radius = numpy.sqrt((x**2)[numpy.newaxis] + (y**2)[:, numpy.newaxis]) f = 1 / (1.0 + (radius/cutoff)**(2 * n)) # The filter return f def butter2d_bp(size, cutin, cutoff, n): """Bandpass Butterworth filter in two dimensions. :Parameters: size : tuple size of the filter cutin : float relative cutin frequency of the filter (0 - 1.0) cutoff : float relative cutoff frequency of the filter (0 - 1.0) n : int, optional order of the filter, the higher n is the sharper the transition is. :Returns: numpy.ndarray filter kernel in 2D centered """ return butter2d_lp(size, cutoff, n) - butter2d_lp(size, cutin, n) def butter2d_hp(size, cutoff, n=3): """Highpass Butterworth filter in two dimensions. :Parameters: size : tuple size of the filter cutoff : float relative cutoff frequency of the filter (0 - 1.0) n : int, optional order of the filter, the higher n is the sharper the transition is. :Returns: numpy.ndarray: filter kernel in 2D centered """ return 1.0 - butter2d_lp(size, cutoff, n) def butter2d_lp_elliptic(size, cutoff_x, cutoff_y, n=3, alpha=0, offset_x=0, offset_y=0): """Butterworth lowpass filter of any elliptical shape. :Parameters: size : tuple size of the filter cutoff_x, cutoff_y : float, float relative cutoff frequency of the filter (0 - 1.0) for x and y axes alpha : float, optional rotation angle (in radians) offset_x, offset_y : float offsets for the ellipsoid n : int, optional order of the filter, the higher n is the sharper the transition is. :Returns: numpy.ndarray: filter kernel in 2D centered """ if not (0 < cutoff_x <= 1.0): raise ValueError('cutoff_x frequency must be between 0 and 1') if not (0 < cutoff_y <= 1.0): raise ValueError('cutoff_y frequency must be between 0 and 1') rows, cols = size # this time we start up with 2D arrays for easy broadcasting x = (numpy.linspace(-0.5, 0.5, int(cols)) - offset_x)[numpy.newaxis] y = (numpy.linspace(-0.5, 0.5, int(rows)) - offset_y)[:, numpy.newaxis] x2 = (x * numpy.cos(alpha) - y * numpy.sin(-alpha)) y2 = (x * numpy.sin(-alpha) + y * numpy.cos(alpha)) f = 1 / (1+((x2/(cutoff_x))**2+(y2/(cutoff_y))**2)**n) return f
14,134
Python
.py
336
33.383929
123
0.603445
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,719
shaders.py
psychopy_psychopy/psychopy/visual/shaders.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). """shaders programs for either pyglet or pygame """ import pyglet.gl as GL import psychopy.tools.gltools as gltools from ctypes import c_int, c_char_p, c_char, cast, POINTER, byref class Shader: def __init__(self, vertexSource=None, fragmentSource=None): def compileShader(source, shaderType): """Compile shader source of given type (only needed by compileProgram) """ shader = GL.glCreateShaderObjectARB(shaderType) # if Py3 then we need to convert our (unicode) str into bytes for C if type(source) != bytes: source = source.encode() prog = c_char_p(source) length = c_int(-1) GL.glShaderSourceARB(shader, 1, cast(byref(prog), POINTER(POINTER(c_char))), byref(length)) GL.glCompileShaderARB(shader) # check for errors status = c_int() GL.glGetShaderiv(shader, GL.GL_COMPILE_STATUS, byref(status)) if not status.value: GL.glDeleteShader(shader) raise ValueError('Shader compilation failed') return shader self.handle = GL.glCreateProgramObjectARB() if vertexSource: vertexShader = compileShader( vertexSource, GL.GL_VERTEX_SHADER_ARB ) GL.glAttachObjectARB(self.handle, vertexShader) if fragmentSource: fragmentShader = compileShader( fragmentSource, GL.GL_FRAGMENT_SHADER_ARB ) GL.glAttachObjectARB(self.handle, fragmentShader) GL.glValidateProgramARB(self.handle) GL.glLinkProgramARB(self.handle) if vertexShader: GL.glDeleteObjectARB(vertexShader) if fragmentShader: GL.glDeleteObjectARB(fragmentShader) def bind(self): GL.glUseProgram(self.handle) def unbind(self): GL.glUseProgram(0) def setFloat(self, name, value): if type(name) is not bytes: name = bytes(name, 'utf-8') loc = GL.glGetUniformLocation(self.handle, name) if not hasattr(value, '__len__'): GL.glUniform1f(loc, value) elif len(value) in range(1, 5): # Select the correct function { 1 : GL.glUniform1f, 2 : GL.glUniform2f, 3 : GL.glUniform3f, 4 : GL.glUniform4f # Retrieve uniform location, and set it }[len(value)](loc, *value) else: raise ValueError("Shader.setInt '{}' should be length 1-4 not {}" .format(name, len(value))) def setInt(self, name, value): if type(name) is not bytes: name = bytes(name, 'utf-8') loc = GL.glGetUniformLocation(self.handle, name) if not hasattr(value, '__len__'): GL.glUniform1i(loc, value) elif len(value) in range(1, 5): # Select the correct function { 1 : GL.glUniform1i, 2 : GL.glUniform2i, 3 : GL.glUniform3i, 4 : GL.glUniform4i # Retrieve uniform location, and set it }[len(value)](loc, value) else: raise ValueError("Shader.setInt '{}' should be length 1-4 not {}" .format(name, len(value))) def compileProgram(vertexSource=None, fragmentSource=None): """Create and compile a vertex and fragment shader pair from their sources. Parameters ---------- vertexSource, fragmentSource : str or list of str Vertex and fragment shader GLSL sources. Returns ------- int Program object handle. """ program = gltools.createProgramObjectARB() vertexShader = fragmentShader = None if vertexSource: vertexShader = gltools.compileShaderObjectARB( vertexSource, GL.GL_VERTEX_SHADER_ARB) gltools.attachObjectARB(program, vertexShader) if fragmentSource: fragmentShader = gltools.compileShaderObjectARB( fragmentSource, GL.GL_FRAGMENT_SHADER_ARB) gltools.attachObjectARB(program, fragmentShader) gltools.linkProgramObjectARB(program) # gltools.validateProgramARB(program) if vertexShader: gltools.detachObjectARB(program, vertexShader) gltools.deleteObjectARB(vertexShader) if fragmentShader: gltools.detachObjectARB(program, fragmentShader) gltools.deleteObjectARB(fragmentShader) return program """NOTE about frag shaders using FBO. If a floating point texture is being used as a frame buffer (FBO object) then we should keep in the range -1:1 during frag shader. Otherwise we need to convert to 0:1. This means that some shaders differ for FBO use if they're performing any signed math. """ fragFBOtoFrame = ''' uniform sampler2D texture; float rand(vec2 seed){ return fract(sin(dot(seed.xy ,vec2(12.9898,78.233))) * 43758.5453); } void main() { vec4 textureFrag = texture2D(texture,gl_TexCoord[0].st); gl_FragColor.rgb = textureFrag.rgb; //! if too high then show red/black noise if ( gl_FragColor.r>1.0 || gl_FragColor.g>1.0 || gl_FragColor.b>1.0) { gl_FragColor.rgb = vec3 (rand(gl_TexCoord[0].st), 0, 0); } //! if too low then show red/black noise else if ( gl_FragColor.r<0.0 || gl_FragColor.g<0.0 || gl_FragColor.b<0.0) { gl_FragColor.rgb = vec3 (0, 0, rand(gl_TexCoord[0].st)); } } ''' # for stimuli with no texture (e.g. shapes) fragSignedColor = ''' void main() { gl_FragColor.rgb = ((gl_Color.rgb*2.0-1.0)+1.0)/2.0; gl_FragColor.a = gl_Color.a; } ''' fragSignedColor_adding = ''' void main() { gl_FragColor.rgb = (gl_Color.rgb*2.0-1.0)/2.0; gl_FragColor.a = gl_Color.a; } ''' # for stimuli with just a colored texture fragSignedColorTex = ''' uniform sampler2D texture; void main() { vec4 textureFrag = texture2D(texture,gl_TexCoord[0].st); gl_FragColor.rgb = (textureFrag.rgb* (gl_Color.rgb*2.0-1.0)+1.0)/2.0; gl_FragColor.a = gl_Color.a*textureFrag.a; } ''' fragSignedColorTex_adding = ''' uniform sampler2D texture; void main() { vec4 textureFrag = texture2D(texture,gl_TexCoord[0].st); gl_FragColor.rgb = textureFrag.rgb * (gl_Color.rgb*2.0-1.0)/2.0; gl_FragColor.a = gl_Color.a * textureFrag.a; } ''' # the shader for pyglet fonts doesn't use multitextures - just one texture fragSignedColorTexFont = ''' uniform sampler2D texture; uniform vec3 rgb; void main() { vec4 textureFrag = texture2D(texture,gl_TexCoord[0].st); gl_FragColor.rgb=rgb; gl_FragColor.a = gl_Color.a*textureFrag.a; } ''' # for stimuli with a colored texture and a mask (gratings, etc.) fragSignedColorTexMask = ''' uniform sampler2D texture, mask; void main() { vec4 textureFrag = texture2D(texture,gl_TexCoord[0].st); vec4 maskFrag = texture2D(mask,gl_TexCoord[1].st); gl_FragColor.a = gl_Color.a*maskFrag.a*textureFrag.a; gl_FragColor.rgb = (textureFrag.rgb* (gl_Color.rgb*2.0-1.0)+1.0)/2.0; } ''' fragSignedColorTexMask_adding = ''' uniform sampler2D texture, mask; void main() { vec4 textureFrag = texture2D(texture,gl_TexCoord[0].st); vec4 maskFrag = texture2D(mask,gl_TexCoord[1].st); gl_FragColor.a = gl_Color.a * maskFrag.a * textureFrag.a; gl_FragColor.rgb = textureFrag.rgb * (gl_Color.rgb*2.0-1.0)/2.0; } ''' # RadialStim uses a 1D mask with a 2D texture fragSignedColorTexMask1D = ''' uniform sampler2D texture; uniform sampler1D mask; void main() { vec4 textureFrag = texture2D(texture,gl_TexCoord[0].st); vec4 maskFrag = texture1D(mask,gl_TexCoord[1].s); gl_FragColor.a = gl_Color.a*maskFrag.a*textureFrag.a; gl_FragColor.rgb = (textureFrag.rgb* (gl_Color.rgb*2.0-1.0)+1.0)/2.0; } ''' fragSignedColorTexMask1D_adding = ''' uniform sampler2D texture; uniform sampler1D mask; void main() { vec4 textureFrag = texture2D(texture,gl_TexCoord[0].st); vec4 maskFrag = texture1D(mask,gl_TexCoord[1].s); gl_FragColor.a = gl_Color.a * maskFrag.a*textureFrag.a; gl_FragColor.rgb = textureFrag.rgb * (gl_Color.rgb*2.0-1.0)/2.0; } ''' # imageStim is providing its texture unsigned fragImageStim = ''' uniform sampler2D texture; uniform sampler2D mask; void main() { vec4 textureFrag = texture2D(texture,gl_TexCoord[0].st); vec4 maskFrag = texture2D(mask,gl_TexCoord[1].st); gl_FragColor.a = gl_Color.a*maskFrag.a*textureFrag.a; gl_FragColor.rgb = ((textureFrag.rgb*2.0-1.0)*(gl_Color.rgb*2.0-1.0)+1.0)/2.0; } ''' # imageStim is providing its texture unsigned fragImageStim_adding = ''' uniform sampler2D texture; uniform sampler2D mask; void main() { vec4 textureFrag = texture2D(texture,gl_TexCoord[0].st); vec4 maskFrag = texture2D(mask,gl_TexCoord[1].st); gl_FragColor.a = gl_Color.a*maskFrag.a*textureFrag.a; gl_FragColor.rgb = (textureFrag.rgb*2.0-1.0)*(gl_Color.rgb*2.0-1.0)/2.0; } ''' # in every case our vertex shader is simple (we don't transform coords) vertSimple = """ void main() { gl_FrontColor = gl_Color; gl_TexCoord[0] = gl_MultiTexCoord0; gl_TexCoord[1] = gl_MultiTexCoord1; gl_TexCoord[2] = gl_MultiTexCoord2; gl_Position = ftransform(); } """ vertPhongLighting = """ // Vertex shader for the Phong Shading Model // // This code is based of the tutorial here: // https://www.opengl.org/sdk/docs/tutorials/ClockworkCoders/lighting.php // // Only supports directional and point light sources for now. Spotlights will be // added later on. // #version 110 varying vec3 N; varying vec3 v; varying vec4 frontColor; void main(void) { v = vec3(gl_ModelViewMatrix * gl_Vertex); N = normalize(gl_NormalMatrix * gl_Normal); gl_TexCoord[0] = gl_MultiTexCoord0; gl_TexCoord[1] = gl_MultiTexCoord1; gl_Position = ftransform(); frontColor = gl_Color; } """ fragPhongLighting = """ // Fragment shader for the Phong Shading Model // // This code is based of the tutorial here: // https://www.opengl.org/sdk/docs/tutorials/ClockworkCoders/lighting.php // // Use `embedShaderSourceDefs` from gltools to enable the code path for diffuse // texture maps by setting DIFFUSE to 1. The number of lights can be specified // by setting MAX_LIGHTS, by default, the maximum should be 8. However, build // your shader for the exact number of lights required. // // Only supports directional and point light sources for now. Spotlights will be // added later on. // #version 110 varying vec3 N; varying vec3 v; varying vec4 frontColor; #ifdef DIFFUSE_TEXTURE uniform sampler2D diffTexture; #endif // Calculate lighting attenuation using the same formula OpenGL uses float calcAttenuation(float kConst, float kLinear, float kQuad, float dist) { return 1.0 / (kConst + kLinear * dist + kQuad * dist * dist); } void main (void) { #ifdef DIFFUSE_TEXTURE vec4 diffTexColor = texture2D(diffTexture, gl_TexCoord[0].st); #endif #if MAX_LIGHTS > 0 vec3 N = normalize(N); vec4 finalColor = vec4(0.0); // loop over available lights for (int i=0; i < MAX_LIGHTS; i++) { vec3 L; float attenuation = 1.0; // default factor, no attenuation // check if directional, compute attenuation if a point source if (gl_LightSource[i].position.w == 0.0) { // off at infinity, only use direction L = normalize(gl_LightSource[i].position.xyz); // attenuation is 1.0 (no attenuation for directional sources) } else { L = normalize(gl_LightSource[i].position.xyz - v); attenuation = calcAttenuation( gl_LightSource[i].constantAttenuation, gl_LightSource[i].linearAttenuation, gl_LightSource[i].quadraticAttenuation, length(gl_LightSource[i].position.xyz - v)); } vec3 E = normalize(-v); vec3 R = normalize(-reflect(L, N)); // combine scene ambient with object vec4 ambient = gl_FrontMaterial.diffuse * (gl_FrontLightProduct[i].ambient + gl_LightModel.ambient); // calculate diffuse component vec4 diffuse = gl_FrontLightProduct[i].diffuse * max(dot(N, L), 0.0); #ifdef DIFFUSE_TEXTURE // multiply in material texture colors if specified diffuse *= diffTexColor; ambient *= diffTexColor; // ambient should be modulated by diffuse color #endif vec3 halfwayVec = normalize(L + E); vec4 specular = gl_FrontLightProduct[i].specular * pow(max(dot(N, halfwayVec), 0.0), gl_FrontMaterial.shininess); // clamp color values for specular and diffuse ambient = clamp(ambient, 0.0, 1.0); diffuse = clamp(diffuse, 0.0, 1.0); specular = clamp(specular, 0.0, 1.0); // falloff with distance from eye? might be something to consider for // realism vec4 emission = clamp(gl_FrontMaterial.emission, 0.0, 1.0); finalColor += (ambient + emission) + attenuation * (diffuse + specular); } gl_FragColor = finalColor; // use texture alpha #else // no lights, only track ambient and emission component vec4 emission = clamp(gl_FrontMaterial.emission, 0.0, 1.0); vec4 ambient = gl_FrontLightProduct[0].ambient * gl_LightModel.ambient; ambient = clamp(ambient, 0.0, 1.0); #ifdef DIFFUSE_TEXTURE gl_FragColor = (ambient + emission) * texture2D(diffTexture, gl_TexCoord[0].st); #else gl_FragColor = ambient + emission; #endif #endif } """ vertSkyBox = """ varying vec3 texCoord; void main(void) { texCoord = gl_Vertex; gl_Position = ftransform().xyww; } """ fragSkyBox = """ varying vec3 texCoord; uniform samplerCube SkyTexture; void main (void) { gl_FragColor = texture(SkyTexture, texCoord); } """ fragTextBox2 = ''' uniform sampler2D texture; void main() { vec2 uv = gl_TexCoord[0].xy; vec4 current = texture2D(texture, uv); float r = current.r; float g = current.g; float b = current.b; float a = current.a; gl_FragColor = vec4( gl_Color.rgb, (r+g+b)/2.); } ''' fragTextBox2alpha = ''' uniform sampler2D texture; void main() { vec4 current = texture2D(texture,gl_TexCoord[0].st); gl_FragColor = vec4( gl_Color.rgb, current.a); } '''
15,221
Python
.py
403
30.503722
86
0.636951
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,720
form.py
psychopy_psychopy/psychopy/visual/form.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 copy import psychopy from .text import TextStim from .rect import Rect from psychopy.data.utils import importConditions, listFromString from psychopy.visual.basevisual import (BaseVisualStim, ContainerMixin, ColorMixin) from psychopy.tools import stimulustools as stt from psychopy import logging, layout from random import shuffle from pathlib import Path __author__ = 'Jon Peirce, David Bridges, Anthony Haffey' from ..colors import Color _REQUIRED = -12349872349873 # an unlikely int # a dict of known fields with their default vals _knownFields = { 'index': None, # optional field to index into the rows 'itemText': _REQUIRED, # (question used until 2020.2) 'itemColor': None, 'itemWidth': 1, # fraction of the form 'type': _REQUIRED, # type of response box (see below) 'options': ('Yes', 'No'), # for choice box 'ticks': None,#(1, 2, 3, 4, 5, 6, 7), 'tickLabels': None, 'font': None, # for rating/slider 'responseWidth': 1, # fraction of the form 'responseColor': None, 'markerColor': None, 'layout': 'horiz', # can be vert or horiz } _doNotSave = [ 'itemCtrl', 'responseCtrl', # these genuinely can't be save 'itemColor', 'itemWidth', 'options', 'ticks', 'tickLabels', # not useful? 'responseWidth', 'responseColor', 'layout', ] _knownRespTypes = { 'heading', 'description', # no responses 'rating', 'slider', # slider is continuous 'free text', 'choice', 'radio' # synonyms (radio was used until v2020.2) } _synonyms = { 'itemText': 'questionText', 'choice': 'radio', 'free text': 'textBox' } # Setting debug to True will set the sub-elements on Form to be outlined in red, making it easier to determine their position debug = False class Form(BaseVisualStim, ContainerMixin, ColorMixin): """A class to add Forms to a `psychopy.visual.Window` The Form allows Psychopy to be used as a questionnaire tool, where participants can be presented with a series of questions requiring responses. Form items, defined as questions and response pairs, are presented simultaneously onscreen with a scrollable viewing window. Example ------- survey = Form(win, items=[{}], size=(1.0, 0.7), pos=(0.0, 0.0)) Parameters ---------- win : psychopy.visual.Window The window object to present the form. items : List of dicts or csv or xlsx file a list of dicts or csv file should have the following key, value pairs / column headers: "index": The item index as a number "itemText": item question string, "itemWidth": fraction of the form width 0:1 "type": type of rating e.g., 'radio', 'rating', 'slider' "responseWidth": fraction of the form width 0:1, "options": list of tick labels for options, "layout": Response object layout e.g., 'horiz' or 'vert' textHeight : float Text height. size : tuple, list Size of form on screen. pos : tuple, list Position of form on screen. itemPadding : float Space or padding between form items. units : str units for stimuli - Currently, Form class only operates with 'height' units. randomize : bool Randomize order of Form elements """ knownStyles = stt.formStyles def __init__(self, win, name='default', colorSpace='rgb', fillColor=None, borderColor=None, itemColor='white', responseColor='white', markerColor='red', items=None, font=None, textHeight=.02, size=(.5, .5), pos=(0, 0), style=None, itemPadding=0.05, units='height', randomize=False, autoLog=True, depth=0, # legacy color=None, foreColor=None ): super(Form, self).__init__(win, units, autoLog=False) self.win = win self.autoLog = autoLog self.name = name self.randomize = randomize self.items = self.importItems(items) self.size = size self._pos = pos self.itemPadding = itemPadding self.scrollSpeed = self.setScrollSpeed(self.items, 4) self.units = units self.depth = depth # Appearance self.colorSpace = colorSpace self.fillColor = fillColor self.borderColor = borderColor self.itemColor = itemColor self.responseColor = responseColor self.markerColor = markerColor if color: self.foreColor = color if foreColor: self.foreColor = color self.font = font or "Open Sans" self.textHeight = textHeight self._baseYpositions = [] self.leftEdge = None self.rightEdge = None self.topEdge = None self._currentVirtualY = 0 # Y position in the virtual sheet self._vheight = 0 # Height of the virtual sheet self._decorations = [] self._externalDecorations = [] # Check units - only works with height units for now if self.win.units != 'height': logging.warning( "Form currently only formats correctly using height units. " "Please change the units in Experiment Settings to 'height'") self._complete = False # Create layout of form self._createItemCtrls() self.style = style if self.autoLog: logging.exp("Created {} = {}".format(self.name, repr(self))) def __repr__(self, complete=False): return self.__str__(complete=complete) # from MinimalStim def importItems(self, items): """Import items from csv or excel sheet and convert to list of dicts. Will also accept a list of dicts. Note, for csv and excel files, 'options' must contain comma separated values, e.g., one, two, three. No parenthesis, or quotation marks required. Parameters ---------- items : Excel or CSV file, list of dicts Items used to populate the Form Returns ------- List of dicts A list of dicts, where each list entry is a dict containing all fields for a single Form item """ def _checkSynonyms(items, fieldNames): """Checks for updated names for fields (i.e. synonyms)""" replacedFields = set() for field in _synonyms: synonym = _synonyms[field] for item in items: if synonym in item: # convert to new name item[field] = item[synonym] del item[synonym] replacedFields.add(field) for field in replacedFields: fieldNames.append(field) fieldNames.remove(_synonyms[field]) logging.warning("Form {} included field no longer used {}. " "Replacing with new name '{}'" .format(self.name, _synonyms[field], field)) def _checkRequiredFields(fieldNames): """Checks for required headings (do this after checking synonyms)""" for hdr in _knownFields: # is it required and/or present? if _knownFields[hdr] == _REQUIRED and hdr not in fieldNames: raise ValueError("Missing header ({}) in Form ({}). " "Headers found were: {}" .format(hdr, self.name, fieldNames)) def _checkTypes(types, itemText): """A nested function for testing the number of options given Raises ValueError if n Options not > 1 """ itemDiff = set([types]) - set(_knownRespTypes) for incorrItemType in itemDiff: if incorrItemType == _REQUIRED: if self._itemsFile: itemsFileStr = ("in items file '{}'" .format(self._itemsFile)) else: itemsFileStr = "" msg = ("Item {}{} is missing a required " "value for its response type. Permitted types are " "{}.".format(itemText, itemsFileStr, _knownRespTypes)) if self.autoLog: logging.error(msg) raise ValueError(msg) def _addDefaultItems(items): """ Adds default items when missing. Works in-place. Parameters ---------- items : List of dicts headers : List of column headers for each item """ def isPresent(d, field): # check if the field is there and not empty on this row return (field in d and d[field] not in [None, '']) missingHeaders = [] defaultValues = _knownFields for index, item in enumerate(items): defaultValues['index'] = index for header in defaultValues: # if header is missing of val is None or '' if not isPresent(item, header): oldHeader = header.replace('item', 'question') if isPresent(item, oldHeader): item[header] = item[oldHeader] logging.warning( "{} is a deprecated heading for Forms. " "Use {} instead" .format(oldHeader, header) ) continue # Default to colour scheme if specified if defaultValues[header] in ['fg', 'bg', 'em']: item[header] = self.color else: item[header] = defaultValues[header] missingHeaders.append(header) msg = "Using default values for the following headers: {}".format( missingHeaders) if self.autoLog: logging.info(msg) if self.autoLog: logging.info("Importing items...") if not isinstance(items, list): # items is a conditions file self._itemsFile = Path(items) items, fieldNames = importConditions(items, returnFieldNames=True) else: # we already have a list so lets find the fieldnames fieldNames = set() for item in items: fieldNames = fieldNames.union(item) fieldNames = list(fieldNames) # convert to list at the end self._itemsFile = None _checkSynonyms(items, fieldNames) _checkRequiredFields(fieldNames) # Add default values if entries missing _addDefaultItems(items) # Convert options to list of strings for idx, item in enumerate(items): if item['ticks']: item['ticks'] = listFromString(item['ticks']) if 'tickLabels' in item and item['tickLabels']: item['tickLabels'] = listFromString(item['tickLabels']) if 'options' in item and item['options']: item['options'] = listFromString(item['options']) # Check types [_checkTypes(item['type'], item['itemText']) for item in items] # Check N options > 1 # Randomise items if requested if self.randomize: shuffle(items) return items def setScrollSpeed(self, items, multiplier=2): """Set scroll speed of Form. Higher multiplier gives smoother, but slower scroll. Parameters ---------- items : list of dicts Items used to populate the form multiplier : int (default=2) Number used to calculate scroll speed Returns ------- int Scroll speed, calculated using N items by multiplier """ return len(items) * multiplier def _getItemRenderedWidth(self, size): """Returns text width for item text based on itemWidth and Form width. Parameters ---------- size : float, int The question width Returns ------- float Wrap width for question text """ return size * self.size[0] - (self.itemPadding * 2) def _setQuestion(self, item): """Creates TextStim object containing question Parameters ---------- item : dict The dict entry for a single item Returns ------- psychopy.visual.text.TextStim The textstim object with the question string questionHeight The height of the question bounding box as type float questionWidth The width of the question bounding box as type float """ if self.autoLog: logging.exp( u"Question text: {}".format(item['itemText'])) if item['type'] == 'heading': letterScale = 1.5 bold = True else: letterScale = 1.0 bold = False w = self._getItemRenderedWidth(item['itemWidth']) question = psychopy.visual.TextBox2( self.win, text=item['itemText'], units=self.units, letterHeight=self.textHeight * letterScale, anchor='top-left', alignment='center-left', pos=(self.leftEdge+self.itemPadding, 0), # y pos irrelevant size=[w, 0.1], # expand height with text autoLog=False, colorSpace=self.colorSpace, color=item['itemColor'] or self.itemColor, fillColor=None, padding=0, # handle this by padding between items borderWidth=1, borderColor='red' if debug else None, # add borderColor to help debug editable=False, bold=bold, font=item['font'] or self.font) # Resize textbox to be at least as tall as the text question._updateVertices() textHeight = getattr(question.boundingBox._size, question.units)[1] if textHeight > question.size[1]: question.size[1] = textHeight + question.padding[1] * 2 question._layout() questionHeight = question.size[1] questionWidth = question.size[0] # store virtual pos to combine with scroll bar for actual pos question._baseY = self._currentVirtualY # Add question objects to Form element dict item['itemCtrl'] = question return question, questionHeight, questionWidth def _setResponse(self, item): """Makes calls to methods which make Slider or TextBox response objects for Form Parameters ---------- item : dict The dict entry for a single item question : TextStim The question text object Returns ------- psychopy.visual.slider.Slider The Slider object for response psychopy.visual.TextBox The TextBox object for response respHeight The height of the response object as type float """ if self.autoLog: logging.info( "Adding response to Form type: {}, layout: {}, options: {}" .format(item['type'], item['layout'], item['options'])) if item['type'].lower() == 'free text': respCtrl, respHeight = self._makeTextBox(item) elif item['type'].lower() in ['heading', 'description']: respCtrl, respHeight = None, 0 elif item['type'].lower() in ['rating', 'slider', 'choice', 'radio']: respCtrl, respHeight = self._makeSlider(item) item['responseCtrl'] = respCtrl return respCtrl, float(respHeight) def _makeSlider(self, item): """Creates Slider object for Form class Parameters ---------- item : dict The dict entry for a single item pos : tuple position of response object Returns ------- psychopy.visual.slider.Slider The Slider object for response respHeight The height of the response object as type float """ # Slider dict kind = item['type'].lower() # what are the ticks for the scale/slider? if item['type'].lower() in ['radio', 'choice']: if item['ticks']: ticks = item['ticks'] else: ticks = None tickLabels = item['tickLabels'] or item['options'] or item['ticks'] granularity = 1 style = 'radio' else: if item['ticks']: ticks = item['ticks'] elif item['options']: ticks = range(0, len(item['options'])) else: raise ValueError("We don't appear to have either options or " "ticks for item '{}' of {}." .format(item['itemText'], self.name)) # how to label those ticks if item['tickLabels']: tickLabels = [str(i).strip() for i in item['tickLabels']] elif 'options' in item and item['options']: tickLabels = [str(i).strip() for i in item['options']] else: tickLabels = None # style/granularity if kind == 'slider' and 'granularity' in item: if item['granularity']: granularity = item['granularity'] else: granularity = 0 elif kind == 'slider' and 'granularity' not in item: granularity = 0 else: granularity = 1 style = kind # Make invisible guide rect to help with laying out slider w = (item['responseWidth'] - self.itemPadding * 2) * (self.size[0] - self.scrollbarWidth) * 0.8 if item['layout'] == 'horiz': h = self.textHeight * 2 + 0.03 elif item['layout'] == 'vert': h = self.textHeight * 1.1 * len(item['options']) x = self.rightEdge - self.itemPadding - self.scrollbarWidth - w * 0.1 guide = Rect( self.win, size=(w, h), pos=(x, 0), anchor="top-right", lineColor="red", fillColor=None, units=self.units, autoLog=False ) # Get slider pos and size if item['layout'] == 'horiz': x = guide.pos[0] - guide.size[0] / 2 w = guide.size[0] h = 0.03 wrap = None # Slider defaults are fine for horizontal elif item['layout'] == 'vert': # for vertical take into account the nOptions x = guide.pos[0] - guide.size[0] w = 0.03 h = guide.size[1] wrap = guide.size[0] / 2 - 0.03 item['options'].reverse() # Create Slider resp = psychopy.visual.Slider( self.win, pos=(x, 0), # NB y pos is irrelevant here - handled later size=(w, h), ticks=ticks, labels=tickLabels, units=self.units, labelHeight=self.textHeight, labelWrapWidth=wrap, granularity=granularity, flip=True, style=style, autoLog=False, font=item['font'] or self.font, color=item['responseColor'] or self.responseColor, fillColor=item['markerColor'] or self.markerColor, borderColor=item['responseColor'] or self.responseColor, colorSpace=self.colorSpace) resp.guide = guide # store virtual pos to combine with scroll bar for actual pos resp._baseY = self._currentVirtualY - guide.size[1] / 2 - self.itemPadding return resp, guide.size[1] def _getItemHeight(self, item, ctrl=None): """Returns the full height of the item to be inserted in the form""" if type(ctrl) == psychopy.visual.TextBox2: return ctrl.size[1] if type(ctrl) == psychopy.visual.Slider: # Set radio button layout if item['layout'] == 'horiz': return 0.03 + ctrl.labelHeight*3 elif item['layout'] == 'vert': # for vertical take into account the nOptions return ctrl.labelHeight*len(item['options']) def _makeTextBox(self, item): """Creates TextBox object for Form class NOTE: The TextBox 2 in work in progress, and has not been added to Form class yet. Parameters ---------- item : dict The dict entry for a single item pos : tuple position of response object Returns ------- psychopy.visual.TextBox The TextBox object for response respHeight The height of the response object as type float """ w = (item['responseWidth'] - self.itemPadding * 2) * (self.size[0] - self.scrollbarWidth) x = self.rightEdge - self.itemPadding - self.scrollbarWidth resp = psychopy.visual.TextBox2( self.win, text='', pos=(x, 0), # y pos irrelevant now (handled by scrollbar) size=(w, 0.1), letterHeight=self.textHeight, units=self.units, anchor='top-right', color=item['responseColor'] or self.responseColor, colorSpace=self.colorSpace, font=item['font'] or self.font, editable=True, borderColor=item['responseColor'] or self.responseColor, borderWidth=2, fillColor=None, onTextCallback=self._layoutY, ) if debug: resp.borderColor = "red" # Resize textbox to be at least as tall as the text resp._updateVertices() textHeight = getattr(resp.boundingBox._size, resp.units)[1] if textHeight > resp.size[1]: resp.size[1] = textHeight + resp.padding[1] * 2 resp._layout() respHeight = resp.size[1] # store virtual pos to combine with scroll bar for actual pos resp._baseY = self._currentVirtualY return resp, respHeight def _setScrollBar(self): """Creates Slider object for scrollbar Returns ------- psychopy.visual.slider.Slider The Slider object for scroll bar """ scroll = psychopy.visual.Slider(win=self.win, size=(self.scrollbarWidth, self.size[1] / 1.2), # Adjust size to account for scrollbar overflow ticks=[0, 1], style='scrollbar', borderColor=self.responseColor, fillColor=self.markerColor, pos=(self.rightEdge - self.scrollbarWidth / 2, self.pos[1]), autoLog=False) return scroll def _setBorder(self): """Creates border using Rect Returns ------- psychopy.visual.Rect The border for the survey """ return psychopy.visual.Rect(win=self.win, units=self.units, pos=self.pos, width=self.size[0], height=self.size[1], colorSpace=self.colorSpace, fillColor=self.fillColor, lineColor=self.borderColor, opacity=None, autoLog=False) def _setAperture(self): """Blocks text beyond border using Aperture Returns ------- psychopy.visual.Aperture The aperture setting viewable area for forms """ aperture = psychopy.visual.Aperture(win=self.win, name=f"{self.name}_aperture", units=self.units, shape='square', size=self.size, pos=self.pos, autoLog=False) aperture.disable() # Disable on creation. Only enable on draw. return aperture def _getScrollOffset(self): """Calculate offset position of items in relation to markerPos. Offset is a proportion of `vheight - height`, meaning the max offset (when scrollbar.markerPos is 1) is enough to take the bottom element to the bottom of the border. Returns ------- float Offset position of items proportionate to scroll bar """ offset = max(self._vheight - self.size[1], 0) * (1 - self.scrollbar.markerPos) * -1 return offset def _createItemCtrls(self): """Define layout of form""" # Define boundaries of form if self.autoLog: logging.info("Setting layout of Form: {}.".format(self.name)) self.leftEdge = self.pos[0] - self.size[0] / 2.0 self.rightEdge = self.pos[0] + self.size[0] / 2.0 # For each question, create textstim and rating scale for item in self.items: # set up the question object self._setQuestion(item) # set up the response object self._setResponse(item) # position a slider on right-hand edge self.scrollbar = self._setScrollBar() self.scrollbar.markerPos = 1 # Set scrollbar to start position self.border = self._setBorder() self.aperture = self._setAperture() # then layout the Y positions self._layoutY() if self.autoLog: logging.info("Layout set for Form: {}.".format(self.name)) def _layoutY(self): """This needs to be done when editable textboxes change their size because everything below them needs to move too""" self.topEdge = self.pos[1] + self.size[1] / 2.0 self._currentVirtualY = self.topEdge - self.itemPadding # For each question, create textstim and rating scale for item in self.items: question = item['itemCtrl'] response = item['responseCtrl'] # update item baseY question._baseY = self._currentVirtualY # and get height to update current Y questionHeight = self._getItemHeight(item=item, ctrl=question) # go on to next line if together they're too wide oneLine = (item['itemWidth']+item['responseWidth'] <= 1 or not response) if not oneLine: # response on next line self._currentVirtualY -= questionHeight + self.itemPadding / 4 # update response baseY if not response: self._currentVirtualY -= questionHeight + self.itemPadding continue # get height to update current Y respHeight = self._getItemHeight(item=item, ctrl=response) # update item baseY # slider needs to align by middle if type(response) == psychopy.visual.Slider: response._baseY = self._currentVirtualY - max(questionHeight, respHeight)/2 else: # hopefully we have an object that can anchor at top? response._baseY = self._currentVirtualY # go on to next line if together they're too wide if oneLine: # response on same line - work out which is bigger self._currentVirtualY -= ( max(questionHeight, respHeight) + self.itemPadding ) else: # response on next line self._currentVirtualY -= respHeight + self.itemPadding * 5/4 # Calculate virtual height as distance from top edge to bottom of last element self._vheight = abs(self.topEdge - self._currentVirtualY) self._setDecorations() # choose whether show/hide scroolbar def _setDecorations(self): """Sets Form decorations i.e., Border and scrollbar""" # add scrollbar if it's needed self._decorations = [self.border] if self._vheight > self.size[1]: self._decorations.append(self.scrollbar) def _inRange(self, item): """Check whether item position falls within border area Parameters ---------- item : TextStim, Slider object TextStim or Slider item from survey Returns ------- bool Returns True if item position falls within border area """ upperRange = self.size[1] lowerRange = -self.size[1] return (item.pos[1] < upperRange and item.pos[1] > lowerRange) def _drawDecorations(self): """Draw decorations on form.""" [decoration.draw() for decoration in self._decorations] def _drawExternalDecorations(self): """Draw decorations outside the aperture""" [decoration.draw() for decoration in self._externalDecorations] def _drawCtrls(self): """Draw elements on form within border range. Parameters ---------- items : List List of TextStim or Slider item from survey """ for idx, item in enumerate(self.items): for element in [item['itemCtrl'], item['responseCtrl']]: if element is None: # e.g. because this has no resp obj continue element.pos = (element.pos[0], element._baseY - self._getScrollOffset()) if self._inRange(element): element.draw() if debug and hasattr(element, "guide"): # If debugging, draw position guide too element.guide.pos = (element.guide.pos[0], element._baseY - self._getScrollOffset() + element.guide.size[1] / 2) element.guide.draw() def setAutoDraw(self, value, log=None): """Sets autoDraw for Form and any responseCtrl contained within """ for i in self.items: if i['responseCtrl']: i['responseCtrl'].__dict__['autoDraw'] = value self.win.addEditable(i['responseCtrl']) BaseVisualStim.setAutoDraw(self, value, log) def draw(self): """Draw all form elements""" # Check mouse wheel self.scrollbar.markerPos += self.scrollbar.mouse.getWheelRel()[ 1] / self.scrollSpeed # draw the box and scrollbar self._drawExternalDecorations() # enable aperture self.aperture._reset() # draw the box and scrollbar self._drawDecorations() # Draw question and response objects self._drawCtrls() # disable aperture self.aperture.disable() def getData(self): """Extracts form questions, response ratings and response times from Form items Returns ------- list A copy of the data as a list of dicts """ nIncomplete = 0 nIncompleteRequired = 0 for thisItem in self.items: if 'responseCtrl' not in thisItem or not thisItem['responseCtrl']: continue # maybe a heading or similar responseCtrl = thisItem['responseCtrl'] # get response if available if hasattr(responseCtrl, 'getRating'): thisItem['response'] = responseCtrl.getRating() else: thisItem['response'] = responseCtrl.text if thisItem['response'] in [None, '']: # todo : handle required items here (e.g. ending with * ?) nIncomplete += 1 # get RT if available if hasattr(responseCtrl, 'getRT'): thisItem['rt'] = responseCtrl.getRT() else: thisItem['rt'] = None self._complete = (nIncomplete == 0) return copy.copy(self.items) # don't want users changing orig def reset(self): """ Clear all responses and set all items to their initial values. """ # Iterate through all items for item in self.items: # If item doesn't have a response ctrl, skip it if "responseCtrl" not in item: continue # If response ctrl is a slider, set its rating to None if isinstance(item['responseCtrl'], psychopy.visual.Slider): item['responseCtrl'].rating = None # If response ctrl is a textbox, set its text to blank elif isinstance(item['responseCtrl'], psychopy.visual.TextBox2): item['responseCtrl'].text = "" # Set scrollbar to top self.scrollbar.rating = 1 def addDataToExp(self, exp, itemsAs='rows'): """Gets the current Form data and inserts into an :class:`~psychopy.experiment.ExperimentHandler` object either as rows or as columns Parameters ---------- exp : :class:`~psychopy.experiment.ExperimentHandler` itemsAs: 'rows','cols' (or 'columns') Returns ------- """ data = self.getData() # will be a copy of data (we can trash it) asCols = itemsAs.lower() in ['cols', 'columns'] # iterate over items and fields within each item # iterate all items and all fields before calling nextEntry for ii, thisItem in enumerate(data): # data is a list of dicts for fieldName in thisItem: if fieldName in _doNotSave: continue if asCols: # for columns format, we need index for item columnName = "{}[{}].{}".format(self.name, ii, fieldName) else: columnName = "{}.{}".format(self.name, fieldName) exp.addData(columnName, thisItem[fieldName]) # finished field if not asCols: # for rows format we add a newline each item exp.nextEntry() # finished item # finished form if asCols: # for cols format we add a newline each item exp.nextEntry() def formComplete(self): """Deprecated in version 2020.2. Please use the Form.complete property """ return self.complete @property def pos(self): if hasattr(self, '_pos'): return self._pos @pos.setter def pos(self, value): self._pos = value if hasattr(self, 'aperture'): self.aperture.pos = value if hasattr(self, 'border'): self.border.pos = value self.leftEdge = self.pos[0] - self.size[0] / 2.0 self.rightEdge = self.pos[0] + self.size[0] / 2.0 # Set horizontal position of elements for item in self.items: for element in [item['itemCtrl'], item['responseCtrl']]: if element is None: # e.g. because this has no resp obj continue element.pos = [value[0], element.pos[1]] element._baseY = value[1] if hasattr(element, 'anchor'): element.anchor = 'top-center' # Calculate new position for everything on the y axis self.scrollbar.pos = (self.rightEdge - .008, self.pos[1]) self._layoutY() @property def scrollbarWidth(self): """ Width of the scrollbar for this Form, in the spatial units of this Form. Can also be set as a `layout.Vector` object. """ if not hasattr(self, "_scrollbarWidth"): # Default to 15px self._scrollbarWidth = layout.Vector(15, 'pix', self.win) return getattr(self._scrollbarWidth, self.units)[0] @scrollbarWidth.setter def scrollbarWidth(self, value): self._scrollbarWidth = layout.Vector(value, self.units, self.win) self.scrollbar.width[0] = self.scrollbarWidth @property def opacity(self): return BaseVisualStim.opacity.fget(self) @opacity.setter def opacity(self, value): BaseVisualStim.opacity.fset(self, value) self.fillColor = self._fillColor self.borderColor = self._borderColor if hasattr(self, "_foreColor"): self._foreColor.alpha = value if hasattr(self, "_itemColor"): self._itemColor.alpha = value if hasattr(self, "_responseColor"): self._responseColor.alpha = value if hasattr(self, "_markerColor"): self._markerColor.alpha = value @property def complete(self): """A read-only property to determine if the current form is complete""" self.getData() return self._complete @property def foreColor(self): """ Sets both `itemColor` and `responseColor` to the same value """ return ColorMixin.foreColor.fget(self) @foreColor.setter def foreColor(self, value): ColorMixin.foreColor.fset(self, value) self.itemColor = value self.responseColor = value @property def fillColor(self): """ Color of the form's background """ return ColorMixin.fillColor.fget(self) @fillColor.setter def fillColor(self, value): ColorMixin.fillColor.fset(self, value) if hasattr(self, "border"): self.border.fillColor = value @property def borderColor(self): """ Color of the line around the form """ return ColorMixin.borderColor.fget(self) @borderColor.setter def borderColor(self, value): ColorMixin.borderColor.fset(self, value) if hasattr(self, "border"): self.border.borderColor = value @property def itemColor(self): """ Color of the text on form items """ return getattr(self._itemColor, self.colorSpace) @itemColor.setter def itemColor(self, value): self._itemColor = Color(value, self.colorSpace) # Set text color on each item for item in self.items: if 'itemCtrl' in item: if isinstance(item['itemCtrl'], psychopy.visual.TextBox2): item['itemCtrl'].foreColor = self._itemColor @property def responseColor(self): """ Color of the lines and text on form responses """ if hasattr(self, "_responseColor"): return getattr(self._responseColor, self.colorSpace) @responseColor.setter def responseColor(self, value): self._responseColor = Color(value, self.colorSpace) # Set line color on scrollbar if hasattr(self, "scrollbar"): self.scrollbar.borderColor = self._responseColor # Set line and label color on each item for item in self.items: if 'responseCtrl' in item: if isinstance(item['responseCtrl'], psychopy.visual.Slider) or isinstance(item['responseCtrl'], psychopy.visual.TextBox2): item['responseCtrl'].borderColor = self._responseColor item['responseCtrl'].foreColor = self._responseColor @property def markerColor(self): """ Color of the marker on any sliders in this form """ if hasattr(self, "_markerColor"): return getattr(self._markerColor, self.colorSpace) @markerColor.setter def markerColor(self, value): self._markerColor = Color(value, self.colorSpace) # Set marker color on scrollbar if hasattr(self, "scrollbar"): self.scrollbar.fillColor = self._markerColor # Set marker color on each item for item in self.items: if 'responseCtrl' in item: if isinstance(item['responseCtrl'], psychopy.visual.Slider): item['responseCtrl'].fillColor = self._markerColor @property def style(self): if hasattr(self, "_style"): return self._style @style.setter def style(self, style): """Sets some predefined styles or use these to create your own. If you fancy creating and including your own styles that would be great! Parameters ---------- style: string Known styles currently include: 'light': black text on a light background 'dark': white text on a dark background """ self._style = style # If style is custom, skip the rest if style in ['custom...', 'None', None]: return # If style is a string of a known style, use that if style in self.knownStyles: style = self.knownStyles[style] # By here, style should be a dict if not isinstance(style, dict): return # Apply each key in the style dict as an attr for key, val in style.items(): if hasattr(self, key): setattr(self, key, val) @property def values(self): # Iterate through each control and append its value to a dict out = {} for item in self.getData(): out.update( {item['index']: item['response']} ) return out @values.setter def values(self, values): for item in self.items: if item['index'] in values: ctrl = item['responseCtrl'] # set response if available if hasattr(ctrl, "rating"): ctrl.rating = values[item['index']] elif hasattr(ctrl, "value"): ctrl.value = values[item['index']] else: ctrl.text = values[item['index']]
43,469
Python
.py
1,033
29.725073
138
0.556078
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,721
window.py
psychopy_psychopy/psychopy/visual/window.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """A class representing a window for displaying one or more stimuli""" # 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 ctypes import os import sys import weakref import atexit from itertools import product from collections import deque from psychopy.contrib.lazy_import import lazy_import from psychopy import colors, event from psychopy.localization import _translate from psychopy.tools.systemtools import getCurrentPID, registerPID import math # from psychopy.clock import monotonicClock # try to find avbin (we'll overload pyglet's load_library tool and then # add some paths) from ..colors import Color, colorSpaces from .textbox2 import TextBox2 haveAvbin = False # on windows try to load avbin now (other libs can interfere) if sys.platform == 'win32': # make sure we also check in SysWOW64 if on 64-bit windows if 'C:\\Windows\\SysWOW64' not in os.environ['PATH']: os.environ['PATH'] += ';C:\\Windows\\SysWOW64' try: from pyglet.media import avbin haveAvbin = True except ImportError: haveAvbin = False # either avbin isn't installed or scipy.stats has been imported # (prevents avbin loading) except AttributeError: # avbin is not found, causing exception in pyglet 1.2?? # (running psychopy 1.81 standalone on windows 7): # # File "C:\Program Files (x86)\PsychoPy2\lib\site-packages\ # pyglet\media\avbin.py", line 158, in <module> # av.avbin_get_version.restype = ctypes.c_int # AttributeError: 'NoneType' object has no attribute # 'avbin_get_version' haveAvbin = False except Exception: # WindowsError on some systems # AttributeError if using avbin5 from pyglet 1.2? haveAvbin = False # for pyglet 1.3 if not haveAvbin: try: from pyglet.media.sources import avbin haveAvbin = True except ImportError: haveAvbin = False except AttributeError: haveAvbin = False except Exception: haveAvbin = False import psychopy # so we can get the __path__ from psychopy import core, platform_specific, logging, prefs, monitors import psychopy.event from . import backends, image # tools must only be imported *after* event or MovieStim breaks on win32 # (JWP has no idea why!) from psychopy.tools.attributetools import attributeSetter, setAttribute from psychopy.tools.arraytools import val2array from psychopy.tools.monitorunittools import convertToPix import psychopy.tools.viewtools as viewtools import psychopy.tools.gltools as gltools from .text import TextStim from .grating import GratingStim from .helpers import setColor from . import globalVars try: from PIL import Image except ImportError: import Image import numpy from psychopy.core import rush reportNDroppedFrames = 5 # stop raising warning after this # import pyglet.gl, pyglet.window, pyglet.image, pyglet.font, pyglet.event from . import shaders as _shaders try: from pyglet import media havePygletMedia = True except Exception: havePygletMedia = False # lazy_import puts pygame into the namespace but delays import until needed lazy_import(globals(), "import pygame") DEBUG = False IOHUB_ACTIVE = False retinaContext = None # only needed for retina-ready displays class OpenWinList(list): """Class to keep keep track of windows that have been opened. Uses a list of weak references so that we don't stop the window being deleted. """ def append(self, item): list.append(self, weakref.ref(item)) def remove(self, item): for ref in self: obj = ref() if obj is None or item == obj: list.remove(self, ref) openWindows = core.openWindows = OpenWinList() # core needs this for wait() class Window(): """Used to set up a context in which to draw objects, using either `pyglet <http://www.pyglet.org>`_, `pygame <http://www.pygame.org>`_, or `glfw <https://www.glfw.org>`_. The pyglet backend allows multiple windows to be created, allows the user to specify which screen to use (if more than one is available, duh!) and allows movies to be rendered. The GLFW backend is a new addition which provides most of the same features as pyglet, but provides greater flexibility for complex display configurations. Pygame may still work for you but it's officially deprecated in this project (we won't be fixing pygame-specific bugs). """ def __init__(self, size=(800, 600), pos=None, color=(0, 0, 0), colorSpace='rgb', backgroundImage=None, backgroundFit="cover", rgb=None, dkl=None, lms=None, fullscr=None, allowGUI=None, monitor=None, bitsMode=None, winType=None, units=None, gamma=None, blendMode='avg', screen=0, viewScale=None, viewPos=None, viewOri=0.0, waitBlanking=True, allowStencil=False, multiSample=False, numSamples=2, stereo=False, name='window1', title="PsychoPy", checkTiming=True, useFBO=False, useRetina=True, autoLog=True, gammaErrorPolicy='raise', bpc=(8, 8, 8), depthBits=8, stencilBits=8, backendConf=None, infoMsg=None): """ These attributes can only be set at initialization. See further down for a list of attributes which can be changed after initialization of the Window, e.g. color, colorSpace, gamma etc. Parameters ---------- size : array-like of int Size of the window in pixels [x, y]. pos : array-like of int Location of the top-left corner of the window on the screen [x, y]. color : array-like of float Color of background as [r, g, b] list or single value. Each gun can take values between -1.0 and 1.0. fullscr : bool or None Create a window in 'full-screen' mode. Better timing can be achieved in full-screen mode. allowGUI : bool or None If set to False, window will be drawn with no frame and no buttons to close etc., use `None` for value from preferences. winType : str or None Set the window type or back-end to use. If `None` then PsychoPy will revert to user/site preferences. monitor : :class:`~psychopy.monitors.Monitor` or None The monitor to be used during the experiment. If `None` a default monitor profile will be used. units : str or None Defines the default units of stimuli drawn in the window (can be overridden by each stimulus). Values can be *None*, 'height' (of the window), 'norm' (normalised), 'deg', 'cm', 'pix'. See :ref:`units` for explanation of options. screen : int Specifies the physical screen that stimuli will appear on ('pyglet' and 'glfw' `winType` only). Values can be >0 if more than one screen is present. viewScale : array-like of float or None Scaling factors [x, y] to apply custom scaling to the current units of the :class:`~psychopy.visual.Window` instance. viewPos : array-like of float or None If not `None`, redefines the origin within the window, in the units of the window. Values outside the borders will be clamped to lie on the border. viewOri : float A single value determining the orientation of the view in degrees. waitBlanking : bool or None After a call to :py:attr:`~Window.flip()` should we wait for the blank before the script continues. bitsMode : bool DEPRECATED in 1.80.02. Use BitsSharp class from pycrsltd instead. checkTiming : bool Whether to calculate frame duration on initialization. Estimated duration is saved in :py:attr:`~Window.monitorFramePeriod`. The message displayed on the screen can be set with the `infoMsg` argument. allowStencil : bool When set to `True`, this allows operations that use the OpenGL stencil buffer (notably, allowing the :class:`~psychopy.visual.Aperture` to be used). multiSample : bool If `True` and your graphics driver supports multisample buffers, multiple color samples will be taken per-pixel, providing an anti-aliased image through spatial filtering. This setting cannot be changed after opening a window. Only works with 'pyglet' and 'glfw' `winTypes`, and `useFBO` is `False`. numSamples : int A single value specifying the number of samples per pixel if multisample is enabled. The higher the number, the better the image quality, but can delay frame flipping. The largest number of samples is determined by ``GL_MAX_SAMPLES``, usually 16 or 32 on newer hardware, will crash if number is invalid. stereo : bool If `True` and your graphics card supports quad buffers then this will be enabled. You can switch between left and right-eye scenes for drawing operations using :py:attr:`~psychopy.visual.Window.setBuffer()`. title : str Name of the Window according to your Operating System. This is the text which appears on the title sash. useRetina : bool In PsychoPy >1.85.3 this should always be `True` as pyglet (or Apple) no longer allows us to create a non-retina display. NB when you use Retina display the initial win size request will be in the larger pixels but subsequent use of ``units='pix'`` should refer to the tiny Retina pixels. Window.size will give the actual size of the screen in Retina pixels. gammaErrorPolicy: str If `raise`, an error is raised if the gamma table is unable to be retrieved or set. If `warn`, a warning is raised instead. If `ignore`, neither an error nor a warning are raised. bpc : array_like or int Bits per color (BPC) for the back buffer as a tuple to specify bit depths for each color channel separately (red, green, blue), or a single value to set all of them to the same value. Valid values depend on the output color depth of the display (screen) the window is set to use and the system graphics configuration. By default, it is assumed the display has 8-bits per color (8, 8, 8). Behaviour may be undefined for non-fullscreen windows, or if multiple screens are attached with varying color output depths. depthBits : int Back buffer depth bits. Default is 8, but can be set higher (eg. 24) if drawing 3D stimuli to minimize artifacts such a 'Z-fighting'. stencilBits : int Back buffer stencil bits. Default is 8. backendConf : dict or None Additional options to pass to the backend specified by `winType`. Each backend may provide unique functionality which may not be available across all of them. This allows you to pass special configuration options to a specific backend to configure the feature. infoMsg : str or None Message to display during frame rate measurement (i.e., when ``checkTiming=True``). Default is None, which means that a default message is displayed. If you want to hide the message, pass an empty string. Notes ----- * Some parameters (e.g. units) can now be given default values in the user/site preferences and these will be used if `None` is given here. If you do specify a value here it will take precedence over preferences. Attributes ---------- size : array-like (float) Dimensions of the window's drawing area/buffer in pixels [w, h]. monitorFramePeriod : float Refresh rate of the display if ``checkTiming=True`` on window instantiation. """ # what local vars are defined (these are the init params) for use by # __repr__ self._initParams = dir() self._closed = False self.backend = None # this will be set later for unecess in ['self', 'checkTiming', 'rgb', 'dkl', ]: self._initParams.remove(unecess) # Check autoLog value if autoLog not in (True, False): raise ValueError( 'autoLog must be either True or False for visual.Window') self.autoLog = False # to suppress log msg during init self.name = name self.clientSize = numpy.array(size, int) # size of window, not buffer # size of the window when restored (not fullscreen) self._windowedSize = self.clientSize.copy() self.pos = pos # this will get overridden once the window is created self.winHandle = None self.useFBO = useFBO self.useRetina = useRetina and sys.platform == 'darwin' if gammaErrorPolicy not in ['raise', 'warn', 'ignore']: raise ValueError('Unexpected `gammaErrorPolicy`') self.gammaErrorPolicy = gammaErrorPolicy self._toLog = [] self._toCall = [] # settings for the monitor: local settings (if available) override # monitor # if we have a monitors.Monitor object (psychopy 0.54 onwards) # convert to a Monitor object if not monitor: self.monitor = monitors.Monitor('__blank__', autoLog=autoLog) elif isinstance(monitor, str): self.monitor = monitors.Monitor(monitor, autoLog=autoLog) elif hasattr(monitor, 'keys'): # convert into a monitor object self.monitor = monitors.Monitor('temp', currentCalib=monitor, verbose=False, autoLog=autoLog) else: self.monitor = monitor # otherwise monitor will just be a dict self.scrWidthCM = self.monitor.getWidth() self.scrDistCM = self.monitor.getDistance() scrSize = self.monitor.getSizePix() if scrSize is None: self.scrWidthPIX = None else: self.scrWidthPIX = scrSize[0] # if fullscreen not specified, get from prefs if fullscr is None: fullscr = prefs.general['fullscr'] self._isFullScr = fullscr self.units = units if allowGUI is None: allowGUI = prefs.general['allowGUI'] self.allowGUI = allowGUI self.screen = screen self.stereo = stereo # use quad buffer if requested (and if possible) # enable multisampling self.multiSample = multiSample self.numSamples = numSamples # load color conversion matrices self.dkl_rgb = self.monitor.getDKL_RGB() self.lms_rgb = self.monitor.getLMS_RGB() # Projection and view matrices, these can be lists if multiple views are # being used. # NB - attribute checks needed for Rift compatibility if not hasattr(self, '_viewMatrix'): self._viewMatrix = numpy.identity(4, dtype=numpy.float32) if not hasattr(self, '_projectionMatrix'): self._projectionMatrix = viewtools.orthoProjectionMatrix( -1, 1, -1, 1, -1, 1, dtype=numpy.float32) # set screen color self.__dict__['colorSpace'] = colorSpace if rgb is not None: logging.warning("Use of rgb arguments to stimuli are deprecated. " "Please use color and colorSpace args instead") color = rgb colorSpace = 'rgb' elif dkl is not None: logging.warning("Use of dkl arguments to stimuli are deprecated. " "Please use color and colorSpace args instead") color = dkl colorSpace = 'dkl' elif lms is not None: logging.warning("Use of lms arguments to stimuli are deprecated. " "Please use color and colorSpace args instead") color = lms colorSpace = 'lms' self.setColor(color, colorSpace=colorSpace, log=False) self.allowStencil = allowStencil # check whether FBOs are supported if blendMode == 'add' and not self.useFBO: logging.warning('User requested a blendmode of "add" but ' 'window requires useFBO=True') # resort to the simpler blending without float rendering self.__dict__['blendMode'] = 'avg' else: self.__dict__['blendMode'] = blendMode # then set up gl context and then call self.setBlendMode # setup context and openGL() if winType is None: # choose the default windowing winType = "pyglet" self.winType = winType # setup the context # backend specific options are passed as a dictionary backendConf = backendConf if backendConf is not None else {} # Here we make sure all the open windows use the same `winType` and have # context sharing enabled. The context to share is passed as an option # to `backendConf`. if openWindows: primaryWindow = openWindows[0]() # resolve ref if primaryWindow.winType != self.winType: raise ValueError( "Only one kind of `winType` can be used per session.") # Allow for context sharing, only used by the GLFW backend, Pyglet # uses `shadow_window` by default here so we don't need to worry # about it. backendConf['share'] = self if not isinstance(backendConf, dict): # type check on options raise TypeError( 'Object passed to `backendConf` must be type `dict`.') # augment settings with dedicated attributes backendConf['bpc'] = bpc backendConf['depthBits'] = depthBits backendConf['stencilBits'] = stencilBits # get the backend, pass the options to it self.backend = backends.getBackend(win=self, backendConf=backendConf) self.winHandle = self.backend.winHandle global GL GL = self.backend.GL # check whether shaders are supported # also will need to check for ARB_float extension, # but that should be done after context is created self._haveShaders = self.backend.shadersSupported self._setupGL() self.blendMode = self.blendMode # now that we have a window handle, set title self.title = title # parameters for transforming the overall view self.viewScale = val2array(viewScale) if viewPos is not None and self.units is None: raise ValueError('You must define the window units to use viewPos') self.viewPos = val2array(viewPos, withScalar=False) self.viewOri = float(viewOri) if self.viewOri != 0. and self.viewPos is not None: msg = "Window: viewPos & viewOri are currently incompatible" raise NotImplementedError(msg) # scaling factor for HiDPI displays, `None` until initialized self._contentScaleFactor = None # Code to allow iohub to know id of any psychopy windows created # so kb and mouse event filtering by window id can be supported. # # If an iohubConnection is active, give this window os handle to # to the ioHub server. If windows were already created before the # iohub was active, also send them to iohub. # if IOHUB_ACTIVE: from psychopy.iohub.client import ioHubConnection as ioconn if ioconn.ACTIVE_CONNECTION: from psychopy.iohub.client import windowInfoDict win_infos = [] win_handles = [] for w in openWindows: winfo = windowInfoDict(w()) win_infos.append(winfo) win_handles.append(w()._hw_handle) if self._hw_handle not in win_handles: winfo = windowInfoDict(self) win_infos.append(winfo) win_handles.append(self._hw_handle) ioconn.ACTIVE_CONNECTION.registerWindowHandles(*win_infos) self.backend.onMoveCallback = ioconn.ACTIVE_CONNECTION.updateWindowPos # near and far clipping planes self._nearClip = 0.1 self._farClip = 100.0 # 3D rendering related attributes self.frontFace = 'ccw' self.depthFunc = 'less' self.depthMask = False self.cullFace = False self.cullFaceMode = 'back' self.draw3d = False # gl viewport and scissor self._viewport = self._scissor = None # set later # scene light sources self._lights = [] self._useLights = False self._nLights = 0 self._ambientLight = numpy.array([0.0, 0.0, 0.0, 1.0], dtype=numpy.float32) # stereo rendering settings, set later by the user self._eyeOffset = 0.0 self._convergeOffset = 0.0 # gamma self.bits = None # this may change in a few lines time! self.__dict__['gamma'] = gamma self._setupGamma(gamma) # setup bits++ if needed. NB The new preferred method is for this # to be handled by the bits class instead. (we pass the Window to # bits not passing bits to the window) if bitsMode is not None: logging.warn("Use of Window(bitsMode=******) is deprecated. See " "the Coder>Demos>Hardware demo for new methods") self.bitsMode = bitsMode # could be [None, 'fast', 'slow'] logging.warn("calling Window(...,bitsMode='fast') is deprecated." " XXX provide further info") from psychopy.hardware.crs.bits import BitsPlusPlus self.bits = self.interface = BitsPlusPlus(self) self.haveBits = True if (hasattr(self.monitor, 'linearizeLums') or hasattr(self.monitor, 'lineariseLums')): # rather than a gamma value we could use bits++ and provide a # complete linearised lookup table using # monitor.linearizeLums(lumLevels) self.__dict__['gamma'] = None self.frameClock = core.Clock() # from psycho/core self.frames = 0 # frames since last fps calc self.movieFrames = [] # list of captured frames (Image objects) self.recordFrameIntervals = False # Be able to omit the long timegap that follows each time turn it off self.recordFrameIntervalsJustTurnedOn = False self.nDroppedFrames = 0 self.frameIntervals = [] self._frameTimes = deque(maxlen=1000) # 1000 keeps overhead low self._toDraw = [] self._heldDraw = [] self._toDrawDepths = [] self._eventDispatchers = [] # dict of stimulus:validator pairs self.validators = {} self.lastFrameT = core.getTime() self.waitBlanking = waitBlanking # set the swap interval if using GLFW if self.winType == 'glfw': self.backend.setSwapInterval(int(waitBlanking)) self.refreshThreshold = 1.0 # initial val needed by flip() # store editable stimuli self._editableChildren = [] self._currentEditableRef = None # store draggable stimuli self.currentDraggable = None # splash screen self._splashTextbox = None # created on first use self._showSplash = False self.resetViewport() # set viewport to full window size # piloting indicator self._pilotingIndicator = None self._showPilotingIndicator = False # over several frames with no drawing self._monitorFrameRate = None # for testing when to stop drawing a stim: self.monitorFramePeriod = 0.0 if checkTiming: self._monitorFrameRate = self.getActualFrameRate(infoMsg=infoMsg) if self._monitorFrameRate is not None: self.monitorFramePeriod = 1.0 / self._monitorFrameRate else: self.monitorFramePeriod = 1.0 / 60 # assume a flat panel? self.refreshThreshold = self.monitorFramePeriod * 1.2 openWindows.append(self) self.autoLog = autoLog if self.autoLog: logging.exp("Created %s = %s" % (self.name, str(self))) # Make sure this window's close method is called when exiting, even in # the event of an error we should be able to restore the original gamma # table. Note that a reference to this window object will live in this # function, preventing it from being garbage collected. def close_on_exit(): if self._closed is False: self.close() atexit.register(close_on_exit) self._mouse = event.Mouse(win=self) self.backgroundImage = backgroundImage self.backgroundFit = backgroundFit if hasattr(self.backgroundImage, "draw"): self.backgroundImage.draw() def __del__(self): if self._closed is False: self.close() def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): if not self._closed: self.close() def __str__(self): className = 'Window' paramStrings = [] for param in self._initParams: if hasattr(self, param): paramStrings.append("%s=%s" % (param, repr(getattr(self, param)))) else: paramStrings.append("%s=UNKNOWN" % (param)) # paramStrings = ["%s=%s" %(param, getattr(self, param)) # for param in self._initParams] params = ", ".join(paramStrings) s = "%s(%s)" % (className, params) return s @attributeSetter def title(self, value): self.__dict__['title'] = value if hasattr(self.winHandle, "set_caption"): # Pyglet backend self.winHandle.set_caption(value) elif hasattr(self.winHandle, "SetWindowTitle"): # GLFW backend self.winHandle.SetWindowTitle(value) else: # Unknown backend logging.warning(f"Cannot set Window title in backend {self.winType}") @attributeSetter def units(self, value): """*None*, 'height' (of the window), 'norm', 'deg', 'cm', 'pix' Defines the default units of stimuli initialized in the window. I.e. if you change units, already initialized stimuli won't change their units. Can be overridden by each stimulus, if units is specified on initialization. See :ref:`units` for explanation of options. """ if value is None: value = prefs.general['units'] self.__dict__['units'] = value def setUnits(self, value, log=True): setAttribute(self, 'units', value, log=log) @attributeSetter def viewPos(self, value): """The origin of the window onto which stimulus-objects are drawn. The value should be given in the units defined for the window. NB: Never change a single component (x or y) of the origin, instead replace the viewPos-attribute in one shot, e.g.:: win.viewPos = [new_xval, new_yval] # This is the way to do it win.viewPos[0] = new_xval # DO NOT DO THIS! Errors will result. """ self.__dict__['viewPos'] = value if value is not None: # let setter take care of normalisation setattr(self, '_viewPosNorm', value) @attributeSetter def _viewPosNorm(self, value): """Normalised value of viewPos, hidden from user view.""" # first convert to pixels, then normalise to window units viewPos_pix = convertToPix([0, 0], list(value), units=self.units, win=self)[:2] viewPos_norm = viewPos_pix / (self.size / 2.0) # Clip to +/- 1; should going out-of-window raise an exception? viewPos_norm = numpy.clip(viewPos_norm, a_min=-1., a_max=1.) self.__dict__['_viewPosNorm'] = viewPos_norm def setViewPos(self, value, log=True): setAttribute(self, 'viewPos', value, log=log) @property def fullscr(self): """Return whether the window is in fullscreen mode.""" return self._isFullScr @fullscr.setter def fullscr(self, value): """Set whether fullscreen mode is `True` or `False` (not all backends can toggle an open window). """ self.backend.setFullScr(value) self._isFullScr = value @attributeSetter def waitBlanking(self, value): """After a call to :py:attr:`~Window.flip()` should we wait for the blank before the script continues. """ self.__dict__['waitBlanking'] = value @attributeSetter def recordFrameIntervals(self, value): """Record time elapsed per frame. Provides accurate measures of frame intervals to determine whether frames are being dropped. The intervals are the times between calls to :py:attr:`~Window.flip()`. Set to `True` only during the time-critical parts of the script. Set this to `False` while the screen is not being updated, i.e., during any slow, non-frame-time-critical sections of your code, including inter-trial-intervals, ``event.waitkeys()``, ``core.wait()``, or ``image.setImage()``. Examples -------- Enable frame interval recording, successive frame intervals will be stored:: win.recordFrameIntervals = True Frame intervals can be saved by calling the :py:attr:`~Window.saveFrameIntervals` method:: win.saveFrameIntervals() """ # was off, and now turning it on self.recordFrameIntervalsJustTurnedOn = bool( not self.recordFrameIntervals and value) self.__dict__['recordFrameIntervals'] = value self.frameClock.reset() def setRecordFrameIntervals(self, value=True, log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message. """ setAttribute(self, 'recordFrameIntervals', value, log) def saveFrameIntervals(self, fileName=None, clear=True): """Save recorded screen frame intervals to disk, as comma-separated values. Parameters ---------- fileName : *None* or str *None* or the filename (including path if necessary) in which to store the data. If None then 'lastFrameIntervals.log' will be used. clear : bool Clear buffer frames intervals were stored after saving. Default is `True`. """ if not fileName: fileName = 'lastFrameIntervals.log' if len(self.frameIntervals): intervalStr = str(self.frameIntervals)[1:-1] f = open(fileName, 'w') f.write(intervalStr) f.close() if clear: self.frameIntervals = [] self.frameClock.reset() def _setCurrent(self): """Make this window's OpenGL context current. If called on a window whose context is current, the function will return immediately. This reduces the number of redundant calls if no context switch is required. If ``useFBO=True``, the framebuffer is bound after the context switch. """ # don't configure if we haven't changed context if not self.backend.setCurrent(): return # if we are using an FBO, bind it if hasattr(self, 'frameBuffer'): GL.glBindFramebufferEXT(GL.GL_FRAMEBUFFER_EXT, self.frameBuffer) GL.glReadBuffer(GL.GL_COLOR_ATTACHMENT0_EXT) GL.glDrawBuffer(GL.GL_COLOR_ATTACHMENT0_EXT) # NB - check if we need these GL.glActiveTexture(GL.GL_TEXTURE0) GL.glBindTexture(GL.GL_TEXTURE_2D, 0) # set these to match the current window or buffer's settings fbw, fbh = self.frameBufferSize self.viewport = self.scissor = [0, 0, fbw, fbh] self.scissorTest = True # apply the view transforms for this window #self.applyEyeTransform() def onResize(self, width, height): """A default resize event handler. This default handler updates the GL viewport to cover the entire window and sets the ``GL_PROJECTION`` matrix to be orthogonal in window space. The bottom-left corner is (0, 0) and the top-right corner is the width and height of the :class:`~psychopy.visual.Window` in pixels. Override this event handler with your own to create another projection, for example in perspective. """ # this has to be external so that pyglet can use it too without # circular referencing self.backend.onResize(width, height) def logOnFlip(self, msg, level, obj=None): """Send a log message that should be time-stamped at the next :py:attr:`~Window.flip()` command. Parameters ---------- msg : str The message to be logged. level : int The level of importance for the message. obj : object, optional The python object that might be associated with this message if desired. """ self._toLog.append({'msg': msg, 'level': level, 'obj': repr(obj)}) def callOnFlip(self, function, *args, **kwargs): """Call a function immediately after the next :py:attr:`~Window.flip()` command. The first argument should be the function to call, the following args should be used exactly as you would for your normal call to the function (can use ordered arguments or keyword arguments as normal). e.g. If you have a function that you would normally call like this:: pingMyDevice(portToPing, channel=2, level=0) then you could call :py:attr:`~Window.callOnFlip()` to have the function call synchronized with the frame flip like this:: win.callOnFlip(pingMyDevice, portToPing, channel=2, level=0) """ self._toCall.append({'function': function, 'args': args, 'kwargs': kwargs}) def timeOnFlip(self, obj, attrib, format=float): """Retrieves the time on the next flip and assigns it to the `attrib` for this `obj`. Parameters ---------- obj : dict or object A mutable object (usually a dict of class instance). attrib : str Key or attribute of `obj` to assign the flip time to. format : str, class or None Format in which to return time, see clock.Timestamp.resolve() for more info. Defaults to `float`. Examples -------- Assign time on flip to the ``tStartRefresh`` key of ``myTimingDict``:: win.getTimeOnFlip(myTimingDict, 'tStartRefresh') """ self.callOnFlip(self._assignFlipTime, obj, attrib, format) def getFutureFlipTime(self, targetTime=0, clock=None): """The expected time of the next screen refresh. This is currently calculated as win._lastFrameTime + refreshInterval Parameters ----------- targetTime: float The delay *from now* for which you want the flip time. 0 will give the because that the earliest we can achieve. 0.15 will give the schedule flip time that gets as close to 150 ms as possible clock : None, 'ptb', 'now' or any Clock object If True then the time returned is compatible with ptb.GetSecs() verbose: bool Set to True to view the calculations along the way """ baseClock = logging.defaultClock if not self.monitorFramePeriod: raise AttributeError("Cannot calculate nextFlipTime due to unknown " "monitorFramePeriod") lastFlip = self._frameTimes[-1] # unlike win.lastFrameTime this is always on timeNext = lastFlip + self.monitorFramePeriod now = baseClock.getTime() if (now + targetTime) > timeNext: # target is more than 1 frame in future extraFrames = math.ceil((now + targetTime - timeNext)/self.monitorFramePeriod) thisT = timeNext + extraFrames*self.monitorFramePeriod else: thisT = timeNext # convert back to target clock timebase if clock=='ptb': # add back the lastResetTime (that's the clock difference) output = thisT + baseClock.getLastResetTime() elif clock=='now': # time from now is easy! output = thisT - now elif clock: output = thisT + baseClock.getLastResetTime() - clock.getLastResetTime() else: output = thisT return output def _assignFlipTime(self, obj, attrib, format=float): """Helper function to assign the time of last flip to the obj.attrib Parameters ---------- obj : dict or object A mutable object (usually a dict of class instance). attrib : str Key or attribute of ``obj`` to assign the flip time to. format : str, class or None Format in which to return time, see clock.Timestamp.resolve() for more info. Defaults to `float`. """ frameTime = self._frameTime.resolve(format=format) if hasattr(obj, attrib): setattr(obj, attrib, frameTime) elif isinstance(obj, dict): obj[attrib] = frameTime else: raise TypeError("Window.getTimeOnFlip() should be called with an " "object and its attribute or a dict and its key. " "In this case it was called with obj={}" .format(repr(obj))) def _cleanEditables(self): """ Make sure there are no dead refs in the editables list """ for ref in self._editableChildren: obj = ref() if obj is None: self._editableChildren.remove(ref) @property def currentEditable(self): """The editable (Text?) object that currently has key focus""" if self._currentEditableRef: return self._currentEditableRef() @currentEditable.setter def currentEditable(self, editable): """Keeps the current editable stored as a weak ref""" # Ensure that item is added to editables list self.addEditable(editable) # Set the editable as the current editable stim in the window eRef = None for ref in weakref.getweakrefs(editable): if ref in self._editableChildren: eRef = ref break if eRef: self._currentEditableRef = eRef def addEditable(self, editable): """Adds an editable element to the screen (something to which characters can be sent with meaning from the keyboard). The current editable object receiving chars is Window.currentEditable :param editable: :return: """ # Ignore if object is not editable if not hasattr(editable, "editable"): return if not editable.editable: return # If editable is already present do nothing eRef = False for ref in weakref.getweakrefs(editable): if ref in self._editableChildren: eRef = ref break if eRef is False: eRef = weakref.ref(editable) # If editable is not already present, add it to the editables list self._editableChildren.append(eRef) # If this is the first editable obj then make it the current if len(self._editableChildren) == 1: self._currentEditableRef = eRef # Clean editables list self._cleanEditables() def removeEditable(self, editable): # If editable is present, remove it from editables list for ref in weakref.getweakrefs(editable): if ref in self._editableChildren: # If editable was current, move on to next current if self.currentEditable == editable: self.nextEditable() self._editableChildren.remove(ref) return True else: logging.warning(f"Request to remove editable object {editable} could not be completed as weakref " f"to this object could not be found in window.") # Clean editables list self._cleanEditables() return False def nextEditable(self): """Moves focus of the cursor to the next editable window""" # Clean editables list self._cleanEditables() # Progress if self.currentEditable is None: if len(self._editableChildren): self._currentEditableRef = self._editableChildren[0] else: for ref in weakref.getweakrefs(self.currentEditable): if ref in self._editableChildren: cei = self._editableChildren.index(ref) nei = cei+1 if nei >= len(self._editableChildren): nei=0 self._currentEditableRef = self._editableChildren[nei] return self.currentEditable @classmethod def dispatchAllWindowEvents(cls): """ Dispatches events for all pyglet windows. Used by iohub 2.0 psychopy kb event integration. """ Window.backend.dispatchEvents() def clearAutoDraw(self): """ Remove all autoDraw components, meaning they get autoDraw set to False and are not added to any list (as in .stashAutoDraw) """ for thisStim in self._toDraw.copy(): # set autoDraw to False thisStim.autoDraw = False def stashAutoDraw(self): """ Put autoDraw components on 'hold', meaning they get autoDraw set to False but are added to an internal list to be 'released' when .releaseAutoDraw is called. """ for thisStim in self._toDraw.copy(): # set autoDraw to False thisStim.autoDraw = False # add stim to held list self._heldDraw.append(thisStim) def retrieveAutoDraw(self): """ Add all stimuli which are on 'hold' back into the autoDraw list, and clear the hold list. """ for thisStim in self._heldDraw: # set autoDraw to True thisStim.autoDraw = True # clear list self._heldDraw = [] def flip(self, clearBuffer=True): """Flip the front and back buffers after drawing everything for your frame. (This replaces the :py:attr:`~Window.update()` method, better reflecting what is happening underneath). Parameters ---------- clearBuffer : bool, optional Clear the draw buffer after flipping. Default is `True`. Returns ------- float or None Wall-clock time in seconds the flip completed. Returns `None` if :py:attr:`~Window.waitBlanking` is `False`. Notes ----- * The time returned when :py:attr:`~Window.waitBlanking` is `True` corresponds to when the graphics driver releases the draw buffer to accept draw commands again. This time is usually close to the vertical sync signal of the display. Examples -------- Results in a clear screen after flipping:: win.flip(clearBuffer=True) The screen is not cleared (so represent the previous screen):: win.flip(clearBuffer=False) """ # draw message/splash if needed if self._showSplash: self._splashTextbox.draw() if self._toDraw: for thisStim in self._toDraw: # draw thisStim.draw() # draw validation rect if needed if thisStim in self.validators: self.validators[thisStim].draw() # handle dragging if getattr(thisStim, "draggable", False): thisStim.doDragging() else: self.backend.setCurrent() # set these to match the current window or buffer's settings self.viewport = self.scissor = \ (0, 0, self.frameBufferSize[0], self.frameBufferSize[1]) if not self.scissorTest: self.scissorTest = True # clear the projection and modelview matrix for FBO blit GL.glMatrixMode(GL.GL_PROJECTION) GL.glLoadIdentity() GL.glOrtho(-1, 1, -1, 1, -1, 1) GL.glMatrixMode(GL.GL_MODELVIEW) GL.glLoadIdentity() # disable lighting self.useLights = False # Check for mouse clicks on editables if hasattr(self, '_editableChildren'): # Make sure _editableChildren has actually been created editablesOnScreen = [] for thisObj in self._editableChildren: # Iterate through editables and decide which one should have focus if isinstance(thisObj, weakref.ref): # Solidify weakref if necessary thisObj = thisObj() if thisObj is None: continue if isinstance(thisObj.autoDraw, (bool, int, float)): # Store whether this editable is on screen editablesOnScreen.append(thisObj.autoDraw) else: editablesOnScreen.append(False) if self._mouse.isPressedIn(thisObj): # If editable was clicked on, give it focus self.currentEditable = thisObj # If there is only one editable on screen, make sure it starts off with focus if sum(editablesOnScreen) == 1: self.currentEditable = self._editableChildren[editablesOnScreen.index(True)]() flipThisFrame = self._startOfFlip() if self.useFBO and flipThisFrame: self.draw3d = False # disable 3d drawing self._prepareFBOrender() # need blit the framebuffer object to the actual back buffer # unbind the framebuffer as the render target GL.glBindFramebufferEXT(GL.GL_FRAMEBUFFER_EXT, 0) GL.glDisable(GL.GL_BLEND) stencilOn = self.stencilTest self.stencilTest = False if self.bits is not None: self.bits._prepareFBOrender() # before flipping need to copy the renderBuffer to the # frameBuffer GL.glActiveTexture(GL.GL_TEXTURE0) GL.glEnable(GL.GL_TEXTURE_2D) GL.glBindTexture(GL.GL_TEXTURE_2D, self.frameTexture) GL.glColor3f(1.0, 1.0, 1.0) # glColor multiplies with texture GL.glColorMask(True, True, True, True) self._renderFBO() GL.glEnable(GL.GL_BLEND) self._finishFBOrender() # call this before flip() whether FBO was used or not self._afterFBOrender() self.backend.swapBuffers(flipThisFrame) if self.useFBO and flipThisFrame: # set rendering back to the framebuffer object GL.glBindFramebufferEXT( GL.GL_FRAMEBUFFER_EXT, self.frameBuffer) GL.glReadBuffer(GL.GL_COLOR_ATTACHMENT0_EXT) GL.glDrawBuffer(GL.GL_COLOR_ATTACHMENT0_EXT) # set to no active rendering texture GL.glActiveTexture(GL.GL_TEXTURE0) GL.glBindTexture(GL.GL_TEXTURE_2D, 0) if stencilOn: self.stencilTest = True # rescale, reposition, & rotate GL.glMatrixMode(GL.GL_MODELVIEW) GL.glLoadIdentity() if self.viewScale is not None: GL.glScalef(self.viewScale[0], self.viewScale[1], 1) absScaleX = abs(self.viewScale[0]) absScaleY = abs(self.viewScale[1]) else: absScaleX, absScaleY = 1, 1 if self.viewPos is not None: # here we must use normalised units in _viewPosNorm, # see the corresponding attributeSetter above normRfPosX = self._viewPosNorm[0] / absScaleX normRfPosY = self._viewPosNorm[1] / absScaleY GL.glTranslatef(normRfPosX, normRfPosY, 0.0) if self.viewOri: # float # the logic below for flip is partially correct, but does not # handle a nonzero viewPos flip = 1 if self.viewScale is not None: _f = self.viewScale[0] * self.viewScale[1] if _f < 0: flip = -1 GL.glRotatef(flip * self.viewOri, 0.0, 0.0, -1.0) # reset returned buffer for next frame self._endOfFlip(clearBuffer) # waitBlanking if self.waitBlanking and flipThisFrame: GL.glBegin(GL.GL_POINTS) GL.glColor4f(0, 0, 0, 0) if sys.platform == 'win32' and self.glVendor.startswith('ati'): pass else: # this corrupts text rendering on win with some ATI cards :-( GL.glVertex2i(10, 10) GL.glEnd() GL.glFinish() # get timestamp self._frameTime = now = logging.defaultClock.getTime() self._frameTimes.append(self._frameTime) # run scheduled functions immediately after flip completes n_items = len(self._toCall) for i in range(n_items): self._toCall[i]['function'](*self._toCall[i]['args'], **self._toCall[i]['kwargs']) # leave newly scheduled functions for next flip del self._toCall[:n_items] # do bookkeeping if self.recordFrameIntervals: self.frames += 1 deltaT = now - self.lastFrameT self.lastFrameT = now if self.recordFrameIntervalsJustTurnedOn: # don't do anything self.recordFrameIntervalsJustTurnedOn = False else: # past the first frame since turned on self.frameIntervals.append(deltaT) if deltaT > self.refreshThreshold: self.nDroppedFrames += 1 if self.nDroppedFrames < reportNDroppedFrames: txt = 't of last frame was %.2fms (=1/%i)' msg = txt % (deltaT * 1000, 1 / deltaT) logging.warning(msg, t=now) elif self.nDroppedFrames == reportNDroppedFrames: logging.warning("Multiple dropped frames have " "occurred - I'll stop bothering you " "about them!") # log events for logEntry in self._toLog: # {'msg':msg, 'level':level, 'obj':copy.copy(obj)} logging.log(msg=logEntry['msg'], level=logEntry['level'], t=now, obj=logEntry['obj']) del self._toLog[:] # keep the system awake (prevent screen-saver or sleep) platform_specific.sendStayAwake() # draw background (if present) for next frame if hasattr(self.backgroundImage, "draw"): self.backgroundImage.draw() # draw piloting indicator (if piloting) for next frame if self._showPilotingIndicator: self._pilotingIndicator.draw() # If self.waitBlanking is True, then return the time that # GL.glFinish() returned, set as the 'now' variable. Otherwise # return None as before # if self.waitBlanking is True: return now def update(self): """Deprecated: use Window.flip() instead """ # clearBuffer was the original behaviour for win.update() self.flip(clearBuffer=True) def multiFlip(self, flips=1, clearBuffer=True): """Flip multiple times while maintaining the display constant. Use this method for precise timing. **WARNING:** This function should not be used. See the `Notes` section for details. Parameters ---------- flips : int, optional The number of monitor frames to flip. Floats will be rounded to integers, and a warning will be emitted. ``Window.multiFlip(flips=1)`` is equivalent to ``Window.flip()``. Defaults to `1`. clearBuffer : bool, optional Whether to clear the screen after the last flip. Defaults to `True`. Notes ----- - This function can behave unpredictably, and the PsychoPy authors recommend against using it. See https://github.com/psychopy/psychopy/issues/867 for more information. Examples -------- Example of using ``multiFlip``:: # Draws myStim1 to buffer myStim1.draw() # Show stimulus for 4 frames (90 ms at 60Hz) myWin.multiFlip(clearBuffer=False, flips=6) # Draw myStim2 "on top of" myStim1 # (because buffer was not cleared above) myStim2.draw() # Show this for 2 frames (30 ms at 60Hz) myWin.multiFlip(flips=2) # Show blank screen for 3 frames (buffer was cleared above) myWin.multiFlip(flips=3) """ if flips < 1: logging.error("flips argument for multiFlip should be " "a positive integer") if flips != int(flips): flips = int(round(flips)) logging.warning("Number of flips was not an integer; " "rounding to the next integer. Will flip " "%i times." % flips) if flips > 1 and not self.waitBlanking: logging.warning("Call to Window.multiFlip() with flips > 1 is " "unnecessary because Window.waitBlanking=False") # Do the flipping with last flip as special case for _ in range(flips - 1): self.flip(clearBuffer=False) self.flip(clearBuffer=clearBuffer) def setBuffer(self, buffer, clear=True): """Choose which buffer to draw to ('left' or 'right'). Requires the Window to be initialised with stereo=True and requires a graphics card that supports quad buffering (e,g nVidia Quadro series) PsychoPy always draws to the back buffers, so 'left' will use ``GL_BACK_LEFT`` This then needs to be flipped once both eye's buffers have been rendered. Parameters ---------- buffer : str Buffer to draw to. Can either be 'left' or 'right'. clear : bool, optional Clear the buffer before drawing. Default is ``True``. Examples -------- Stereoscopic rendering example using quad-buffers:: win = visual.Window(...., stereo=True) while True: # clear may not actually be needed win.setBuffer('left', clear=True) # do drawing for left eye win.setBuffer('right', clear=True) # do drawing for right eye win.flip() """ if buffer == 'left': GL.glDrawBuffer(GL.GL_BACK_LEFT) elif buffer == 'right': GL.glDrawBuffer(GL.GL_BACK_RIGHT) else: raise "Unknown buffer '%s' requested in Window.setBuffer" % buffer if clear: self.clearBuffer() def clearBuffer(self, color=True, depth=False, stencil=False): """Clear the present buffer (to which you are currently drawing) without flipping the window. Useful if you want to generate movie sequences from the back buffer without actually taking the time to flip the window. Set `color` prior to clearing to set the color to clear the color buffer to. By default, the depth buffer is cleared to a value of 1.0. Parameters ---------- color, depth, stencil : bool Buffers to clear. Examples -------- Clear the color buffer to a specified color:: win.color = (1, 0, 0) win.clearBuffer(color=True) Clear only the depth buffer, `depthMask` must be `True` or else this will have no effect. Depth mask is usually `True` by default, but may change:: win.depthMask = True win.clearBuffer(color=False, depth=True, stencil=False) """ clearBufferBits = GL.GL_NONE if color: clearBufferBits |= GL.GL_COLOR_BUFFER_BIT if depth: clearBufferBits |= GL.GL_DEPTH_BUFFER_BIT if stencil: clearBufferBits |= GL.GL_STENCIL_BUFFER_BIT # reset returned buffer for next frame GL.glClear(clearBufferBits) @property def size(self): """Size of the drawable area in pixels (w, h).""" # report clientSize until we get framebuffer size from # the backend, needs to be done properly in the future if self.backend is not None: return self.viewport[2:] else: return self.clientSize @property def frameBufferSize(self): """Size of the framebuffer in pixels (w, h).""" # Dimensions should match window size unless using a retina display return self.backend.frameBufferSize @property def windowedSize(self): """Size of the window to use when not fullscreen (w, h).""" return self._windowedSize @windowedSize.setter def windowedSize(self, value): """Size of the window to use when not fullscreen (w, h).""" self._windowedSize[:] = value def getContentScaleFactor(self): """Get the scaling factor required for scaling correctly on high-DPI displays. If the returned value is 1.0, no scaling needs to be applied to objects drawn on the backbuffer. A value >1.0 indicates that the backbuffer is larger than the reported client area, requiring points to be scaled to maintain constant size across similarly sized displays. In other words, the scaling required to convert framebuffer to client coordinates. Returns ------- float Scaling factor to be applied along both horizontal and vertical dimensions. Examples -------- Get the size of the client area:: clientSize = win.frameBufferSize / win.getContentScaleFactor() Get the framebuffer size from the client size:: frameBufferSize = win.clientSize * win.getContentScaleFactor() Convert client (window) to framebuffer pixel coordinates (eg., a mouse coordinate, vertices, etc.):: # `mousePosXY` is an array ... frameBufferXY = mousePosXY * win.getContentScaleFactor() # you can also use the attribute ... frameBufferXY = mousePosXY * win.contentScaleFactor Notes ----- * This value is only valid after the window has been fully realized. """ # this might be accessed at lots of points, probably shouldn't compute # this all the time if self._contentScaleFactor is not None: return self._contentScaleFactor sx = self.frameBufferSize[0] / float(self.clientSize[0]) sy = self.frameBufferSize[1] / float(self.clientSize[1]) if sx != sy: # messed up DPI settings return 1.0 and show warning self._contentScaleFactor = 1.0 else: self._contentScaleFactor = sx return self._contentScaleFactor @property def contentScaleFactor(self): """Scaling factor (`float`) to use when drawing to the backbuffer to convert framebuffer to client coordinates. See Also -------- getContentScaleFactor """ return self.getContentScaleFactor() @property def aspect(self): """Aspect ratio of the current viewport (width / height).""" return self._viewport[2] / float(self._viewport[3]) @property def ambientLight(self): """Ambient light color for the scene [r, g, b, a]. Values range from 0.0 to 1.0. Only applicable if `useLights` is `True`. Examples -------- Setting the ambient light color:: win.ambientLight = [0.5, 0.5, 0.5] # don't do this!!! win.ambientLight[0] = 0.5 win.ambientLight[1] = 0.5 win.ambientLight[2] = 0.5 """ # TODO - use signed color and colorspace instead return self._ambientLight[:3] @ambientLight.setter def ambientLight(self, value): self._ambientLight[:3] = value GL.glLightModelfv(GL.GL_LIGHT_MODEL_AMBIENT, numpy.ctypeslib.as_ctypes(self._ambientLight)) @property def lights(self): """Scene lights. This is specified as an array of `~psychopy.visual.LightSource` objects. If a single value is given, it will be converted to a `list` before setting. Set `useLights` to `True` before rendering to enable lighting/shading on subsequent objects. If `lights` is `None` or an empty `list`, no lights will be enabled if `useLights=True`, however, the scene ambient light set with `ambientLight` will be still be used. Examples -------- Create a directional light source and add it to scene lights:: dirLight = gltools.LightSource((0., 1., 0.), lightType='directional') win.lights = dirLight # `win.lights` will be a list when accessed! Multiple lights can be specified by passing values as a list:: myLights = [gltools.LightSource((0., 5., 0.)), gltools.LightSource((-2., -2., 0.)) win.lights = myLights """ return self._lights @lights.setter def lights(self, value): # if None or empty list, disable all lights if value is None or not value: for index in range(self._nLights): GL.glDisable(GL.GL_LIGHT0 + index) self._nLights = 0 # set number of lights to zero self._lights = value return # set the lights and make sure it's a list if a single value was passed self._lights = value if isinstance(value, (list, tuple,)) else [value] # disable excess lights if less lights were specified this time oldNumLights = self._nLights self._nLights = len(self._lights) # number of lights enabled if oldNumLights > self._nLights: for index in range(self._nLights, oldNumLights): GL.glDisable(GL.GL_LIGHT0 + index) # Setup legacy lights, new spec shader programs should access the # `lights` attribute directly to setup lighting uniforms. # The index of the lights is defined by the order it appears in # `self._lights`. for index, light in enumerate(self._lights): enumLight = GL.GL_LIGHT0 + index # convert data in light class to ctypes #pos = numpy.ctypeslib.as_ctypes(light.pos) diffuse = numpy.ctypeslib.as_ctypes(light._diffuseRGB) specular = numpy.ctypeslib.as_ctypes(light._specularRGB) ambient = numpy.ctypeslib.as_ctypes(light._ambientRGB) # pass values to OpenGL #GL.glLightfv(enumLight, GL.GL_POSITION, pos) GL.glLightfv(enumLight, GL.GL_DIFFUSE, diffuse) GL.glLightfv(enumLight, GL.GL_SPECULAR, specular) GL.glLightfv(enumLight, GL.GL_AMBIENT, ambient) constant, linear, quadratic = light._kAttenuation GL.glLightf(enumLight, GL.GL_CONSTANT_ATTENUATION, constant) GL.glLightf(enumLight, GL.GL_LINEAR_ATTENUATION, linear) GL.glLightf(enumLight, GL.GL_QUADRATIC_ATTENUATION, quadratic) # enable the light GL.glEnable(enumLight) @property def useLights(self): """Enable scene lighting. Lights will be enabled if using legacy OpenGL lighting. Stimuli using shaders for lighting should check if `useLights` is `True` since this will have no effect on them, and disable or use a no lighting shader instead. Lights will be transformed to the current view matrix upon setting to `True`. Lights are transformed by the present `GL_MODELVIEW` matrix. Setting `useLights` will result in their positions being transformed by it. If you want lights to appear at the specified positions in world space, make sure the current matrix defines the view/eye transformation when setting `useLights=True`. This flag is reset to `False` at the beginning of each frame. Should be `False` if rendering 2D stimuli or else the colors will be incorrect. """ return self._useLights @useLights.setter def useLights(self, value): self._useLights = value # Setup legacy lights, new spec shader programs should access the # `lights` attribute directly to setup lighting uniforms. if self._useLights and self._lights: GL.glEnable(GL.GL_LIGHTING) # make sure specular lights are computed relative to eye position, # this is more realistic than the default. Does not affect shaders. GL.glLightModeli(GL.GL_LIGHT_MODEL_LOCAL_VIEWER, GL.GL_TRUE) # update light positions for current model matrix for index, light in enumerate(self._lights): enumLight = GL.GL_LIGHT0 + index pos = numpy.ctypeslib.as_ctypes(light.pos) GL.glLightfv(enumLight, GL.GL_POSITION, pos) else: # disable lights GL.glDisable(GL.GL_LIGHTING) def updateLights(self, index=None): """Explicitly update scene lights if they were modified. This is required if modifications to objects referenced in `lights` have been changed since assignment. If you removed or added items of `lights` you must refresh all of them. Parameters ---------- index : int, optional Index of light source in `lights` to update. If `None`, all lights will be refreshed. Examples -------- Call `updateLights` if you modified lights directly like this:: win.lights[1].diffuseColor = [1., 0., 0.] win.updateLights(1) """ if self._lights is None: return # nop if there are no lights if index is None: self.lights = self._lights else: if index > len(self._lights) - 1: raise IndexError('Invalid index for `lights`.') enumLight = GL.GL_LIGHT0 + index # light object to modify light = self._lights[index] # convert data in light class to ctypes # pos = numpy.ctypeslib.as_ctypes(light.pos) diffuse = numpy.ctypeslib.as_ctypes(light.diffuse) specular = numpy.ctypeslib.as_ctypes(light.specular) ambient = numpy.ctypeslib.as_ctypes(light.ambient) # pass values to OpenGL # GL.glLightfv(enumLight, GL.GL_POSITION, pos) GL.glLightfv(enumLight, GL.GL_DIFFUSE, diffuse) GL.glLightfv(enumLight, GL.GL_SPECULAR, specular) GL.glLightfv(enumLight, GL.GL_AMBIENT, ambient) def resetViewport(self): """Reset the viewport to cover the whole framebuffer. Set the viewport to match the dimensions of the back buffer or framebuffer (if `useFBO=True`). The scissor rectangle is also set to match the dimensions of the viewport. """ # use the framebuffer size here, not the window size (hi-dpi compat) bufferWidth, bufferHeight = self.frameBufferSize self.scissor = self.viewport = [0, 0, bufferWidth, bufferHeight] @property def viewport(self): """Viewport rectangle (x, y, w, h) for the current draw buffer. Values `x` and `y` define the origin, and `w` and `h` the size of the rectangle in pixels. This is typically set to cover the whole buffer, however it can be changed for applications like multi-view rendering. Stimuli will draw according to the new shape of the viewport, for instance and stimulus with position (0, 0) will be drawn at the center of the viewport, not the window. Examples -------- Constrain drawing to the left and right halves of the screen, where stimuli will be drawn centered on the new rectangle. Note that you need to set both the `viewport` and the `scissor` rectangle:: x, y, w, h = win.frameBufferSize # size of the framebuffer win.viewport = win.scissor = [x, y, w / 2.0, h] # draw left stimuli ... win.viewport = win.scissor = [x + (w / 2.0), y, w / 2.0, h] # draw right stimuli ... # restore drawing to the whole screen win.viewport = win.scissor = [x, y, w, h] """ return self._viewport @viewport.setter def viewport(self, value): self._viewport = numpy.array(value, int) GL.glViewport(*self._viewport) @property def scissor(self): """Scissor rectangle (x, y, w, h) for the current draw buffer. Values `x` and `y` define the origin, and `w` and `h` the size of the rectangle in pixels. The scissor operation is only active if `scissorTest=True`. Usually, the scissor and viewport are set to the same rectangle to prevent drawing operations from `spilling` into other regions of the screen. For instance, calling `clearBuffer` will only clear within the scissor rectangle. Setting the scissor rectangle but not the viewport will restrict drawing within the defined region (like a rectangular aperture), not changing the positions of stimuli. """ return self._scissor @scissor.setter def scissor(self, value): self._scissor = numpy.array(value, int) GL.glScissor(*self._scissor) @property def scissorTest(self): """`True` if scissor testing is enabled.""" return self._scissorTest @scissorTest.setter def scissorTest(self, value): if value is True: GL.glEnable(GL.GL_SCISSOR_TEST) elif value is False: GL.glDisable(GL.GL_SCISSOR_TEST) else: raise TypeError("Value must be boolean.") self._scissorTest = value @property def stencilTest(self): """`True` if stencil testing is enabled.""" return self._stencilTest @stencilTest.setter def stencilTest(self, value): if value is True: GL.glEnable(GL.GL_STENCIL_TEST) elif value is False: GL.glDisable(GL.GL_STENCIL_TEST) else: raise TypeError("Value must be boolean.") self._stencilTest = value @property def nearClip(self): """Distance to the near clipping plane in meters.""" return self._nearClip @nearClip.setter def nearClip(self, value): self._nearClip = value @property def farClip(self): """Distance to the far clipping plane in meters.""" return self._farClip @farClip.setter def farClip(self, value): self._farClip = value @property def projectionMatrix(self): """Projection matrix defined as a 4x4 numpy array.""" return self._projectionMatrix @projectionMatrix.setter def projectionMatrix(self, value): self._projectionMatrix = numpy.asarray(value, numpy.float32) assert self._projectionMatrix.shape == (4, 4) @property def viewMatrix(self): """View matrix defined as a 4x4 numpy array.""" return self._viewMatrix @viewMatrix.setter def viewMatrix(self, value): self._viewMatrix = numpy.asarray(value, numpy.float32) assert self._viewMatrix.shape == (4, 4) @property def eyeOffset(self): """Eye offset in centimeters. This value is used by `setPerspectiveView` to apply a lateral offset to the view, therefore it must be set prior to calling it. Use a positive offset for the right eye, and a negative one for the left. Offsets should be the distance to from the middle of the face to the center of the eye, or half the inter-ocular distance. """ return self._eyeOffset * 100.0 @eyeOffset.setter def eyeOffset(self, value): self._eyeOffset = value / 100.0 @property def convergeOffset(self): """Convergence offset from monitor in centimeters. This is value corresponds to the offset from screen plane to set the convergence plane (or point for `toe-in` projections). Positive offsets move the plane farther away from the viewer, while negative offsets nearer. This value is used by `setPerspectiveView` and should be set before calling it to take effect. Notes ----- * This value is only applicable for `setToeIn` and `setOffAxisView`. """ return self._convergeOffset * 100.0 @convergeOffset.setter def convergeOffset(self, value): self._convergeOffset = value / 100.0 def setOffAxisView(self, applyTransform=True, clearDepth=True): """Set an off-axis projection. Create an off-axis projection for subsequent rendering calls. Sets the `viewMatrix` and `projectionMatrix` accordingly so the scene origin is on the screen plane. If `eyeOffset` is correct and the view distance and screen size is defined in the monitor configuration, the resulting view will approximate `ortho-stereo` viewing. The convergence plane can be adjusted by setting `convergeOffset`. By default, the convergence plane is set to the screen plane. Any points on the screen plane will have zero disparity. Parameters ---------- applyTransform : bool Apply transformations after computing them in immediate mode. Same as calling :py:attr:`~Window.applyEyeTransform()` afterwards. clearDepth : bool, optional Clear the depth buffer. """ scrDistM = 0.5 if self.scrDistCM is None else self.scrDistCM / 100.0 scrWidthM = 0.5 if self.scrWidthCM is None else self.scrWidthCM / 100.0 # Not in full screen mode? Need to compute the dimensions of the display # area to ensure disparities are correct even when in windowed-mode. aspect = self.size[0] / self.size[1] if not self._isFullScr: scrWidthM = (self.size[0] / self.scrWidthPIX) * scrWidthM frustum = viewtools.computeFrustum( scrWidthM, # width of screen aspect, # aspect ratio scrDistM, # distance to screen eyeOffset=self._eyeOffset, convergeOffset=self._convergeOffset, nearClip=self._nearClip, farClip=self._farClip) self._projectionMatrix = viewtools.perspectiveProjectionMatrix(*frustum) # translate away from screen self._viewMatrix = numpy.identity(4, dtype=numpy.float32) self._viewMatrix[0, 3] = -self._eyeOffset # apply eye offset self._viewMatrix[2, 3] = -scrDistM # displace scene away from viewer if applyTransform: self.applyEyeTransform(clearDepth=clearDepth) def setToeInView(self, applyTransform=True, clearDepth=True): """Set toe-in projection. Create a toe-in projection for subsequent rendering calls. Sets the `viewMatrix` and `projectionMatrix` accordingly so the scene origin is on the screen plane. The value of `convergeOffset` will define the convergence point of the view, which is offset perpendicular to the center of the screen plane. Points falling on a vertical line at the convergence point will have zero disparity. Parameters ---------- applyTransform : bool Apply transformations after computing them in immediate mode. Same as calling :py:attr:`~Window.applyEyeTransform()` afterwards. clearDepth : bool, optional Clear the depth buffer. Notes ----- * This projection mode is only 'correct' if the viewer's eyes are converged at the convergence point. Due to perspective, this projection introduces vertical disparities which increase in magnitude with eccentricity. Use `setOffAxisView` if you want to display something the viewer can look around the screen comfortably. """ scrDistM = 0.5 if self.scrDistCM is None else self.scrDistCM / 100.0 scrWidthM = 0.5 if self.scrWidthCM is None else self.scrWidthCM / 100.0 # Not in full screen mode? Need to compute the dimensions of the display # area to ensure disparities are correct even when in windowed-mode. aspect = self.size[0] / self.size[1] if not self._isFullScr: scrWidthM = (self.size[0] / self.scrWidthPIX) * scrWidthM frustum = viewtools.computeFrustum( scrWidthM, # width of screen aspect, # aspect ratio scrDistM, # distance to screen nearClip=self._nearClip, farClip=self._farClip) self._projectionMatrix = viewtools.perspectiveProjectionMatrix(*frustum) # translate away from screen eyePos = (self._eyeOffset, 0.0, scrDistM) convergePoint = (0.0, 0.0, self.convergeOffset) self._viewMatrix = viewtools.lookAt(eyePos, convergePoint) if applyTransform: self.applyEyeTransform(clearDepth=clearDepth) def setPerspectiveView(self, applyTransform=True, clearDepth=True): """Set the projection and view matrix to render with perspective. Matrices are computed using values specified in the monitor configuration with the scene origin on the screen plane. Calculations assume units are in meters. If `eyeOffset != 0`, the view will be transformed laterally, however the frustum shape will remain the same. Note that the values of :py:attr:`~Window.projectionMatrix` and :py:attr:`~Window.viewMatrix` will be replaced when calling this function. Parameters ---------- applyTransform : bool Apply transformations after computing them in immediate mode. Same as calling :py:attr:`~Window.applyEyeTransform()` afterwards if `False`. clearDepth : bool, optional Clear the depth buffer. """ # NB - we should eventually compute these matrices lazily since they may # not change over the course of an experiment under most circumstances. # scrDistM = 0.5 if self.scrDistCM is None else self.scrDistCM / 100.0 scrWidthM = 0.5 if self.scrWidthCM is None else self.scrWidthCM / 100.0 # Not in full screen mode? Need to compute the dimensions of the display # area to ensure disparities are correct even when in windowed-mode. aspect = self.size[0] / self.size[1] if not self._isFullScr: scrWidthM = (self.size[0] / self.scrWidthPIX) * scrWidthM frustum = viewtools.computeFrustum( scrWidthM, # width of screen aspect, # aspect ratio scrDistM, # distance to screen nearClip=self._nearClip, farClip=self._farClip) self._projectionMatrix = \ viewtools.perspectiveProjectionMatrix(*frustum, dtype=numpy.float32) # translate away from screen self._viewMatrix = numpy.identity(4, dtype=numpy.float32) self._viewMatrix[0, 3] = -self._eyeOffset # apply eye offset self._viewMatrix[2, 3] = -scrDistM # displace scene away from viewer if applyTransform: self.applyEyeTransform(clearDepth=clearDepth) def applyEyeTransform(self, clearDepth=True): """Apply the current view and projection matrices. Matrices specified by attributes :py:attr:`~Window.viewMatrix` and :py:attr:`~Window.projectionMatrix` are applied using 'immediate mode' OpenGL functions. Subsequent drawing operations will be affected until :py:attr:`~Window.flip()` is called. All transformations in ``GL_PROJECTION`` and ``GL_MODELVIEW`` matrix stacks will be cleared (set to identity) prior to applying. Parameters ---------- clearDepth : bool Clear the depth buffer. This may be required prior to rendering 3D objects. Examples -------- Using a custom view and projection matrix:: # Must be called every frame since these values are reset after # `flip()` is called! win.viewMatrix = viewtools.lookAt( ... ) win.projectionMatrix = viewtools.perspectiveProjectionMatrix( ... ) win.applyEyeTransform() # draw 3D objects here ... """ # apply the projection and view transformations if hasattr(self, '_projectionMatrix'): GL.glMatrixMode(GL.GL_PROJECTION) GL.glLoadIdentity() projMat = self._projectionMatrix.ctypes.data_as( ctypes.POINTER(ctypes.c_float)) GL.glMultTransposeMatrixf(projMat) if hasattr(self, '_viewMatrix'): GL.glMatrixMode(GL.GL_MODELVIEW) GL.glLoadIdentity() viewMat = self._viewMatrix.ctypes.data_as( ctypes.POINTER(ctypes.c_float)) GL.glMultTransposeMatrixf(viewMat) oldDepthMask = self.depthMask if clearDepth: GL.glDepthMask(GL.GL_TRUE) GL.glClear(GL.GL_DEPTH_BUFFER_BIT) if oldDepthMask is False: # return to old state if needed GL.glDepthMask(GL.GL_FALSE) def resetEyeTransform(self, clearDepth=True): """Restore the default projection and view settings to PsychoPy defaults. Call this prior to drawing 2D stimuli objects (i.e. GratingStim, ImageStim, Rect, etc.) if any eye transformations were applied for the stimuli to be drawn correctly. Parameters ---------- clearDepth : bool Clear the depth buffer upon reset. This ensures successive draw commands are not affected by previous data written to the depth buffer. Default is `True`. Notes ----- * Calling :py:attr:`~Window.flip()` automatically resets the view and projection to defaults. So you don't need to call this unless you are mixing 3D and 2D stimuli. Examples -------- Going between 3D and 2D stimuli:: # 2D stimuli can be drawn before setting a perspective projection win.setPerspectiveView() # draw 3D stimuli here ... win.resetEyeTransform() # 2D stimuli can be drawn here again ... win.flip() """ # should eventually have the same effect as calling _onResize(), so we # need to add the retina mode stuff eventually if hasattr(self, '_viewMatrix'): self._viewMatrix = numpy.identity(4, dtype=numpy.float32) if hasattr(self, '_projectionMatrix'): self._projectionMatrix = viewtools.orthoProjectionMatrix( -1, 1, -1, 1, -1, 1, dtype=numpy.float32) self.applyEyeTransform(clearDepth) def coordToRay(self, screenXY): """Convert a screen coordinate to a direction vector. Takes a screen/window coordinate and computes a vector which projects a ray from the viewpoint through it (line-of-sight). Any 3D point touching the ray will appear at the screen coordinate. Uses the current `viewport` and `projectionMatrix` to calculate the vector. The vector is in eye-space, where the origin of the scene is centered at the viewpoint and the forward direction aligned with the -Z axis. A ray of (0, 0, -1) results from a point at the very center of the screen assuming symmetric frustums. Note that if you are using a flipped/mirrored view, you must invert your supplied screen coordinates (`screenXY`) prior to passing them to this function. Parameters ---------- screenXY : array_like X, Y screen coordinate. Must be in units of the window. Returns ------- ndarray Normalized direction vector [x, y, z]. Examples -------- Getting the direction vector between the mouse cursor and the eye:: mx, my = mouse.getPos() dir = win.coordToRay((mx, my)) Set the position of a 3D stimulus object using the mouse, constrained to a plane. The object origin will always be at the screen coordinate of the mouse cursor:: # the eye position in the scene is defined by a rigid body pose win.viewMatrix = camera.getViewMatrix() win.applyEyeTransform() # get the mouse location and calculate the intercept mx, my = mouse.getPos() ray = win.coordToRay([mx, my]) result = intersectRayPlane( # from mathtools orig=camera.pos, dir=camera.transformNormal(ray), planeOrig=(0, 0, -10), planeNormal=(0, 1, 0)) # if result is `None`, there is no intercept if result is not None: pos, dist = result objModel.thePose.pos = pos else: objModel.thePose.pos = (0, 0, -10) # plane origin If you don't define the position of the viewer with a `RigidBodyPose`, you can obtain the appropriate eye position and rotate the ray by doing the following:: pos = numpy.linalg.inv(win.viewMatrix)[:3, 3] ray = win.coordToRay([mx, my]).dot(win.viewMatrix[:3, :3]) # then ... result = intersectRayPlane( orig=pos, dir=ray, planeOrig=(0, 0, -10), planeNormal=(0, 1, 0)) """ # put in units of pixels if self.units == 'pix': scrX, scrY = numpy.asarray(screenXY, numpy.float32) else: scrX, scrY = convertToPix(numpy.asarray([0, 0]), numpy.asarray(screenXY), units=self.units, win=self)[:2] # transform psychopy mouse coordinates to viewport coordinates scrX = scrX + (self.size[0] / 2.) scrY = scrY + (self.size[1] / 2.) # get the NDC coordinates of the projX = 2. * (scrX - self.viewport[0]) / self.viewport[2] - 1. projY = 2. * (scrY - self.viewport[1]) / self.viewport[3] - 1. vecNear = numpy.array((projX, projY, 0., 1.), dtype=numpy.float32) vecFar = numpy.array((projX, projY, 1., 1.), dtype=numpy.float32) # compute the inverse projection matrix invPM = numpy.linalg.inv(self.projectionMatrix) vecNear[:] = vecNear.dot(invPM.T) vecFar[:] = vecFar.dot(invPM.T) vecNear /= vecNear[3] vecFar /= vecFar[3] # direction vector, get rid of `w` dirVec = vecFar[:3] - vecNear[:3] return dirVec / numpy.linalg.norm(dirVec) def getMovieFrame(self, buffer='front'): """Capture the current Window as an image. Saves to stack for :py:attr:`~Window.saveMovieFrames()`. As of v1.81.00 this also returns the frame as a PIL image This can be done at any time (usually after a :py:attr:`~Window.flip()` command). Frames are stored in memory until a :py:attr:`~Window.saveMovieFrames()` command is issued. You can issue :py:attr:`~Window.getMovieFrame()` as often as you like and then save them all in one go when finished. The back buffer will return the frame that hasn't yet been 'flipped' to be visible on screen but has the advantage that the mouse and any other overlapping windows won't get in the way. The default front buffer is to be called immediately after a :py:attr:`~Window.flip()` and gives a complete copy of the screen at the window's coordinates. Parameters ---------- buffer : str, optional Buffer to capture. Returns ------- Image Buffer pixel contents as a PIL/Pillow image object. """ im = self._getFrame(buffer=buffer) self.movieFrames.append(im) return im def _getPixels(self, rect=None, buffer='front', includeAlpha=True, makeLum=False): """Return an array of pixel values from the current window buffer or sub-region. Parameters ---------- rect : tuple[int], optional The region of the window to capture in pixel coordinates (left, bottom, width, height). If `None`, the whole window is captured. buffer : str, optional Buffer to capture. includeAlpha : bool, optional Include the alpha channel in the returned array. Default is `True`. makeLum : bool, optional Convert the RGB values to luminance values. Values are rounded to the nearest integer. Default is `False`. Returns ------- ndarray Pixel values as a 3D array of shape (height, width, channels). If `includeAlpha` is `False`, the array will have shape (height, width, 3). If `makeLum` is `True`, the array will have shape (height, width). Examples -------- Get the pixel values of the whole window:: pix = win._getPixels() Get pixel values and convert to luminance and get average:: pix = win._getPixels(makeLum=True) average = pix.mean() """ # do the reading of the pixels if buffer == 'back' and self.useFBO: GL.glReadBuffer(GL.GL_COLOR_ATTACHMENT0_EXT) elif buffer == 'back': GL.glReadBuffer(GL.GL_BACK) elif buffer == 'front': if self.useFBO: GL.glBindFramebufferEXT(GL.GL_FRAMEBUFFER_EXT, 0) GL.glReadBuffer(GL.GL_FRONT) else: raise ValueError("Requested read from buffer '{}' but should be " "'front' or 'back'".format(buffer)) if rect: # box corners in pix left, bottom, w, h = rect else: left = bottom = 0 w, h = self.size # get pixel data bufferDat = (GL.GLubyte * (4 * w * h))() GL.glReadPixels( left, bottom, w, h, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, bufferDat) # convert to array toReturn = numpy.frombuffer(bufferDat, dtype=numpy.uint8) toReturn = toReturn.reshape((h, w, 4)) # rebind front buffer if needed if buffer == 'front' and self.useFBO: GL.glBindFramebufferEXT(GL.GL_FRAMEBUFFER_EXT, self.frameBuffer) # if we want the color data without an alpha channel, we need to # convert the data to a numpy array and remove the alpha channel if not includeAlpha: toReturn = toReturn[:, :, :3] # remove alpha channel # convert to luminance if requested if makeLum: coeffs = [0.2989, 0.5870, 0.1140] toReturn = numpy.rint(numpy.dot(toReturn[:, :, :3], coeffs)).astype( numpy.uint8) return toReturn def _getFrame(self, rect=None, buffer='front'): """Return the current Window as an image. """ # GL.glLoadIdentity() # do the reading of the pixels if buffer == 'back' and self.useFBO: GL.glReadBuffer(GL.GL_COLOR_ATTACHMENT0_EXT) elif buffer == 'back': GL.glReadBuffer(GL.GL_BACK) elif buffer == 'front': if self.useFBO: GL.glBindFramebufferEXT(GL.GL_FRAMEBUFFER_EXT, 0) GL.glReadBuffer(GL.GL_FRONT) else: raise ValueError("Requested read from buffer '{}' but should be " "'front' or 'back'".format(buffer)) if rect: x, y = self.size # of window, not image imType = 'RGBA' # not tested with anything else # box corners in pix left = int((rect[0] / 2. + 0.5) * x) bottom = int((rect[3] / 2. + 0.5) * y) w = int((rect[2] / 2. + 0.5) * x) - left h = int((rect[1] / 2. + 0.5) * y) - bottom else: left = bottom = 0 w, h = self.size # http://www.opengl.org/sdk/docs/man/xhtml/glGetTexImage.xml bufferDat = (GL.GLubyte * (4 * w * h))() GL.glReadPixels(left, bottom, w, h, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, bufferDat) try: im = Image.fromstring(mode='RGBA', size=(w, h), data=bufferDat) except Exception: im = Image.frombytes(mode='RGBA', size=(w, h), data=bufferDat) im = im.transpose(Image.FLIP_TOP_BOTTOM) im = im.convert('RGB') if self.useFBO and buffer == 'front': GL.glBindFramebufferEXT(GL.GL_FRAMEBUFFER_EXT, self.frameBuffer) return im @property def screenshot(self): return self._getFrame() def saveMovieFrames(self, fileName, codec='libx264', fps=30, clearFrames=True): """Writes any captured frames to disk. Will write any format that is understood by PIL (tif, jpg, png, ...) Parameters ---------- filename : str Name of file, including path. The extension at the end of the file determines the type of file(s) created. If an image type (e.g. .png) is given, then multiple static frames are created. If it is .gif then an animated GIF image is created (although you will get higher quality GIF by saving PNG files and then combining them in dedicated image manipulation software, such as GIMP). On Windows and Linux `.mpeg` files can be created if `pymedia` is installed. On macOS `.mov` files can be created if the pyobjc-frameworks-QTKit is installed. Unfortunately the libs used for movie generation can be flaky and poor quality. As for animated GIFs, better results can be achieved by saving as individual .png frames and then combining them into a movie using software like ffmpeg. codec : str, optional The codec to be used **by moviepy** for mp4/mpg/mov files. If `None` then the default will depend on file extension. Can be one of ``libx264``, ``mpeg4`` for mp4/mov files. Can be ``rawvideo``, ``png`` for avi files (not recommended). Can be ``libvorbis`` for ogv files. Default is ``libx264``. fps : int, optional The frame rate to be used throughout the movie. **Only for quicktime (.mov) movies.**. Default is `30`. clearFrames : bool, optional Set this to `False` if you want the frames to be kept for additional calls to ``saveMovieFrames``. Default is `True`. Examples -------- Writes a series of static frames as frame001.tif, frame002.tif etc.:: myWin.saveMovieFrames('frame.tif') As of PsychoPy 1.84.1 the following are written with moviepy:: myWin.saveMovieFrames('stimuli.mp4') # codec = 'libx264' or 'mpeg4' myWin.saveMovieFrames('stimuli.mov') myWin.saveMovieFrames('stimuli.gif') """ fileRoot, fileExt = os.path.splitext(fileName) fileExt = fileExt.lower() # easier than testing both later if len(self.movieFrames) == 0: logging.error('no frames to write - did you forget to update ' 'your window or call win.getMovieFrame()?') return else: logging.info('Writing %i frames to %s' % (len(self.movieFrames), fileName)) if fileExt in ['.gif', '.mpg', '.mpeg', '.mp4', '.mov']: # lazy loading of moviepy.editor (rarely needed) from moviepy.editor import ImageSequenceClip # save variety of movies with moviepy numpyFrames = [] for frame in self.movieFrames: numpyFrames.append(numpy.array(frame)) clip = ImageSequenceClip(numpyFrames, fps=fps) if fileExt == '.gif': clip.write_gif(fileName, fps=fps, fuzz=0, opt='nq') else: clip.write_videofile(fileName, codec=codec) elif len(self.movieFrames) == 1: # save an image using pillow self.movieFrames[0].save(fileName) else: frmc = numpy.ceil(numpy.log10(len(self.movieFrames) + 1)) frame_name_format = "%s%%0%dd%s" % (fileRoot, frmc, fileExt) for frameN, thisFrame in enumerate(self.movieFrames): thisFileName = frame_name_format % (frameN + 1,) thisFrame.save(thisFileName) if clearFrames: self.movieFrames = [] def _getRegionOfFrame(self, rect=(-1, 1, 1, -1), buffer='front', power2=False, squarePower2=False): """Deprecated function, here for historical reasons. You may now use `:py:attr:`~Window._getFrame()` and specify a rect to get a sub-region, just as used here. power2 can be useful with older OpenGL versions to avoid interpolation in :py:attr:`PatchStim`. If power2 or squarePower2, it will expand rect dimensions up to next power of two. squarePower2 uses the max dimensions. You need to check what your hardware & OpenGL supports, and call :py:attr:`~Window._getRegionOfFrame()` as appropriate. """ # Ideally: rewrite using GL frame buffer object; glReadPixels == slow region = self._getFrame(rect=rect, buffer=buffer) if power2 or squarePower2: # use to avoid interpolation in PatchStim if squarePower2: maxsize = max(region.size) xPowerOf2 = int(2**numpy.ceil(numpy.log2(maxsize))) yPowerOf2 = xPowerOf2 else: xPowerOf2 = int(2**numpy.ceil(numpy.log2(region.size[0]))) yPowerOf2 = int(2**numpy.ceil(numpy.log2(region.size[1]))) imP2 = Image.new('RGBA', (xPowerOf2, yPowerOf2)) # paste centered imP2.paste(region, (int(xPowerOf2 / 2. - region.size[0] / 2.), int(yPowerOf2 / 2.) - region.size[1] / 2)) region = imP2 return region def close(self): """Close the window (and reset the Bits++ if necess). """ self._closed = True # If iohub is running, inform it to stop using this win id # for mouse events try: if IOHUB_ACTIVE: from psychopy.iohub.client import ioHubConnection ioHubConnection.ACTIVE_CONNECTION.unregisterWindowHandles(self._hw_handle) except Exception: pass self.backend.close() # moved here, dereferencing the window prevents # backend specific actions to take place try: openWindows.remove(self) except Exception: pass try: self.mouseVisible = True except Exception: # can cause unimportant "'NoneType' object is not callable" pass try: if self.bits is not None: self.bits.reset() except Exception: pass try: logging.flush() except Exception: pass def fps(self): """Report the frames per second since the last call to this function (or since the window was created if this is first call)""" fps = self.frames / self.frameClock.getTime() self.frameClock.reset() self.frames = 0 return fps @property def depthTest(self): """`True` if depth testing is enabled.""" return self._depthTest @depthTest.setter def depthTest(self, value): if value is True: GL.glEnable(GL.GL_DEPTH_TEST) elif value is False: GL.glDisable(GL.GL_DEPTH_TEST) else: raise TypeError("Value must be boolean.") self._depthTest = value @property def depthFunc(self): """Depth test comparison function for rendering.""" return self._depthFunc @depthFunc.setter def depthFunc(self, value): depthFuncs = {'never': GL.GL_NEVER, 'less': GL.GL_LESS, 'equal': GL.GL_EQUAL, 'lequal': GL.GL_LEQUAL, 'greater': GL.GL_GREATER, 'notequal': GL.GL_NOTEQUAL, 'gequal': GL.GL_GEQUAL, 'always': GL.GL_ALWAYS} GL.glDepthFunc(depthFuncs[value]) self._depthFunc = value @property def depthMask(self): """`True` if depth masking is enabled. Writing to the depth buffer will be disabled. """ return self._depthMask @depthMask.setter def depthMask(self, value): if value is True: GL.glDepthMask(GL.GL_TRUE) elif value is False: GL.glDepthMask(GL.GL_FALSE) else: raise TypeError("Value must be boolean.") self._depthMask = value @property def cullFaceMode(self): """Face culling mode, either `back`, `front` or `both`.""" return self._cullFaceMode @cullFaceMode.setter def cullFaceMode(self, value): if value == 'back': GL.glCullFace(GL.GL_BACK) elif value == 'front': GL.glCullFace(GL.GL_FRONT) elif value == 'both': GL.glCullFace(GL.GL_FRONT_AND_BACK) else: raise ValueError('Invalid face cull mode.') self._cullFaceMode = value @property def cullFace(self): """`True` if face culling is enabled.`""" return self._cullFace @cullFace.setter def cullFace(self, value): if value is True: GL.glEnable(GL.GL_CULL_FACE) elif value is False: GL.glDisable(GL.GL_CULL_FACE) else: raise TypeError('Value must be type `bool`.') self._cullFace = value @property def frontFace(self): """Face winding order to define front, either `ccw` or `cw`.""" return self._frontFace @frontFace.setter def frontFace(self, value): if value == 'ccw': GL.glFrontFace(GL.GL_CCW) elif value == 'cw': GL.glFrontFace(GL.GL_CW) else: raise ValueError('Invalid value, must be `ccw` or `cw`.') self._frontFace = value @property def draw3d(self): """`True` if 3D drawing is enabled on this window.""" return self._draw3d @draw3d.setter def draw3d(self, value): if value is True: if self.depthMask is False: self.depthMask = True if self.depthTest is False: self.depthTest = True if self.cullFace is False: self.cullFace = True elif value is False: if self.depthMask is True: self.depthMask = False if self.depthTest is True: self.depthTest = False if self.cullFace is True: self.cullFace = False else: raise TypeError('Value must be type `bool`.') self._draw3d = value @attributeSetter def blendMode(self, blendMode): """Blend mode to use.""" self.__dict__['blendMode'] = blendMode if blendMode == 'avg': GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA) if hasattr(self, '_shaders'): self._progSignedFrag = self._shaders['signedColor'] self._progSignedTex = self._shaders['signedTex'] self._progSignedTexMask = self._shaders['signedTexMask'] self._progSignedTexMask1D = self._shaders['signedTexMask1D'] self._progImageStim = self._shaders['imageStim'] elif blendMode == 'add': GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE) if hasattr(self, '_shaders'): self._progSignedFrag = self._shaders['signedColor_adding'] self._progSignedTex = self._shaders['signedTex_adding'] self._progSignedTexMask = self._shaders['signedTexMask_adding'] tmp = self._shaders['signedTexMask1D_adding'] self._progSignedTexMask1D = tmp self._progImageStim = self._shaders['imageStim_adding'] else: raise ValueError("Window blendMode should be set to 'avg' or 'add'" " but we received the value {}" .format(repr(blendMode))) def setBlendMode(self, blendMode, log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message. """ setAttribute(self, 'blendMode', blendMode, log) @property def colorSpace(self): """The name of the color space currently being used Value should be: a string or None For strings and hex values this is not needed. If None the default colorSpace for the stimulus is used (defined during initialisation). Please note that changing colorSpace does not change stimulus parameters. Thus you usually want to specify colorSpace before setting the color. Example:: # A light green text stim = visual.TextStim(win, 'Color me!', color=(0, 1, 0), colorSpace='rgb') # An almost-black text stim.colorSpace = 'rgb255' # Make it light green again stim.color = (128, 255, 128) """ if hasattr(self, '_colorSpace'): return self._colorSpace else: return 'rgb' @colorSpace.setter def colorSpace(self, value): if value in colorSpaces: self._colorSpace = value else: logging.error(f"'{value}' is not a valid color space") @property def color(self): """Set the color of the window. This command sets the color that the blank screen will have on the next clear operation. As a result it effectively takes TWO :py:attr:`~Window.flip()` operations to become visible (the first uses the color to create the new screen, the second presents that screen to the viewer). For this reason, if you want to changed background color of the window "on the fly", it might be a better idea to draw a :py:attr:`Rect` that fills the whole window with the desired :py:attr:`Rect.fillColor` attribute. That'll show up on first flip. See other stimuli (e.g. :py:attr:`GratingStim.color`) for more info on the color attribute which essentially works the same on all PsychoPy stimuli. See :ref:`colorspaces` for further information about the ways to specify colors and their various implications. """ if hasattr(self, '_color'): return getattr(self._color, self.colorSpace) @color.setter def color(self, value): if isinstance(value, Color): # If supplied with a color object, set as that self._color = value else: # Otherwise, use it to make a color object self._color = Color(value, self.colorSpace) if not self._color: self._color = Color() logging.error(f"'{value}' is not a valid {self.colorSpace} color") # if it is None then this will be done during window setup if self.backend is not None: self.backend.setCurrent() # make sure this window is active GL.glClearColor(*self._color.render('rgba1')) def setColor(self, color, colorSpace=None, operation='', log=None): """Usually you can use ``stim.attribute = value`` syntax instead, but use this method if you want to set color and colorSpace simultaneously. See :py:attr:`~Window.color` for documentation on colors. """ self.colorSpace = colorSpace self.color = color def setRGB(self, newRGB): """Deprecated: As of v1.61.00 please use `setColor()` instead """ self.setColor(newRGB, colorSpace="rgb") @property def rgb(self): if hasattr(self, "_color"): return self._color.render("rgb") @rgb.setter def rgb(self, value): self.color = Color(value, 'rgb') @attributeSetter def backgroundImage(self, value): """ Background image for the window, can be either a visual.ImageStim object or anything which could be passed to visual.ImageStim.image to create one. Will be drawn each time `win.flip()` is called, meaning it is always below all other contents of the window. """ if value in (None, "None", "none", ""): # If given None, store so we know not to use a background image self._backgroundImage = None self.__dict__['backgroundImage'] = self._backgroundImage return elif hasattr(value, "draw") and hasattr(value, "win"): # If given a visual object, set its parent window to self and use it value.win = self self._backgroundImage = value else: # Otherwise, try to make an image from value (start off as if backgroundFit was None) self._backgroundImage = image.ImageStim(self, image=value, size=None, pos=(0, 0)) # Set background fit again now that we have an image if hasattr(self, "_backgroundFit"): self.backgroundFit = self._backgroundFit self.__dict__['backgroundImage'] = self._backgroundImage @attributeSetter def backgroundFit(self, value): """ How should the background image of this window fit? Options are: None, "None", "none" No scaling is applied, image is present at its pixel size unaltered. "cover" Image is scaled such that it covers the whole screen without changing its aspect ratio. In other words, both dimensions are evenly scaled such that its SHORTEST dimension matches the window's LONGEST dimension. "contain" Image is scaled such that it is contained within the screen without changing its aspect ratio. In other words, both dimensions are evenly scaled such that its LONGEST dimension matches the window's SHORTEST dimension. "scaleDown", "scale-down", "scaledown" If image is bigger than the window along any dimension, it will behave as if backgroundFit were "contain". Otherwise, it will behave as if backgroundFit were None. """ self._backgroundFit = value # Skip if no background image if (not hasattr(self, "_backgroundImage")) or (self._backgroundImage is None): self.__dict__['backgroundFit'] = self._backgroundFit return # If value is scaleDown or alias, set to None or "contain" based on relative size if value in ("scaleDown", "scale-down", "scaledown"): overflow = numpy.asarray(self._backgroundImage._origSize) > numpy.asarray(self.size) if overflow.any(): value = "contain" else: value = None if value in (None, "None", "none"): # If value is None, don't change the backgroundImage at all pass elif value == "fill": # If value is fill, make backgroundImage fill screen self._backgroundImage.units = "norm" self._backgroundImage.size = (2, 2) self._backgroundImage.pos = (0, 0) if value in ("contain", "cover"): # If value is contain or cover, set one dimension to fill screen and the other to maintain ratio ratios = numpy.asarray(self._backgroundImage._origSize) / numpy.asarray(self.size) if value == "cover": i = ratios.argmin() else: i = ratios.argmax() size = [None, None] size[i] = 2 self._backgroundImage.units = "norm" self._backgroundImage.size = size self._backgroundImage.pos = (0, 0) self.__dict__['backgroundFit'] = self._backgroundFit def _setupGamma(self, gammaVal): """A private method to work out how to handle gamma for this Window given that the user might have specified an explicit value, or maybe gave a Monitor. """ # determine which gamma value to use (or native ramp) if gammaVal is not None: self._checkGamma() self.useNativeGamma = False elif not self.monitor.gammaIsDefault(): if self.monitor.getGamma() is not None: self.__dict__['gamma'] = self.monitor.getGamma() self.useNativeGamma = False else: self.__dict__['gamma'] = None # gamma wasn't set anywhere self.useNativeGamma = True # then try setting it if self.useNativeGamma: if self.autoLog: logging.info('Using gamma table of operating system') else: if self.autoLog: logging.info('Using gamma: self.gamma' + str(self.gamma)) self.gamma = gammaVal # using either pygame or bits++ @attributeSetter def gamma(self, gamma): """Set the monitor gamma for linearization. Warnings -------- Don't use this if using a Bits++ or Bits#, as it overrides monitor settings. """ self._checkGamma(gamma) if self.bits is not None: msg = ("Do not use try to set the gamma of a window with " "Bits++/Bits# enabled. It was ambiguous what should " "happen. Use the setGamma() function of the bits box " "instead") raise DeprecationWarning(msg) self.backend.gamma = self.__dict__['gamma'] def setGamma(self, gamma, log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message. """ setAttribute(self, 'gamma', gamma, log) @attributeSetter def gammaRamp(self, newRamp): """Sets the hardware CLUT using a specified 3xN array of floats ranging between 0.0 and 1.0. Array must have a number of rows equal to 2 ^ max(bpc). """ self.backend.gammaRamp = newRamp def _checkGamma(self, gamma=None): if gamma is None: gamma = self.gamma if isinstance(gamma, (float, int)): self.__dict__['gamma'] = [gamma] * 3 elif hasattr(gamma, '__iter__'): self.__dict__['gamma'] = gamma else: raise ValueError('gamma must be a numeric scalar or iterable') def setScale(self, units, font='dummyFont', prevScale=(1.0, 1.0)): """DEPRECATED: this method used to be used to switch between units for stimulus drawing but this is now handled by the stimuli themselves and the window should always be left in units of 'pix' """ if self.useRetina: retinaScale = 2.0 else: retinaScale = 1.0 # then unit-specific changes if units == "norm": thisScale = numpy.array([1.0, 1.0]) elif units == "height": thisScale = numpy.array([2.0 * self.size[1] / self.size[0], 2.0]) elif units in ["pix", "pixels"]: thisScale = 2.0 / numpy.array(self.size) * retinaScale elif units == "cm": # windowPerCM = windowPerPIX / CMperPIX # = (window/winPIX) / (scrCm/scrPIX) if self.scrWidthCM in [0, None] or self.scrWidthPIX in [0, None]: logging.error('you did not give the width of the screen (pixels' ' and cm). Check settings in MonitorCentre.') core.wait(1.0) core.quit() thisScale = ((numpy.array([2.0, 2.0]) / self.size * retinaScale) / (self.scrWidthCM / self.scrWidthPIX)) elif units in ["deg", "degs"]: # windowPerDeg = winPerCM * CMperDEG # = winPerCM * tan(pi/180) * distance if ((self.scrWidthCM in [0, None]) or (self.scrWidthPIX in [0, None])): logging.error('you did not give the width of the screen (pixels' ' and cm). Check settings in MonitorCentre.') core.wait(1.0) core.quit() cmScale = ((numpy.array([2.0, 2.0]) / self.size) * retinaScale / (self.scrWidthCM / self.scrWidthPIX)) thisScale = cmScale * 0.017455 * self.scrDistCM elif units == "stroke_font": lw = 2 * font.letterWidth thisScale = numpy.array([lw, lw] / self.size * retinaScale / 38.0) # actually set the scale as appropriate # allows undoing of a previous scaling procedure thisScale = thisScale / numpy.asarray(prevScale) GL.glScalef(thisScale[0], thisScale[1], 1.0) return thisScale def _checkMatchingSizes(self, requested, actual): """Checks whether the requested and actual screen sizes differ. If not then a warning is output and the window size is set to actual """ if list(requested) != list(actual): logging.warning("User requested fullscreen with size %s, " "but screen is actually %s. Using actual size" % (requested, actual)) self.clientSize = numpy.array(actual) def _setupGL(self): """Setup OpenGL state for this window. """ # setup screen color self.color = self.color # call attributeSetter GL.glClearDepth(1.0) # viewport or drawable area of the framebuffer self.viewport = self.scissor = \ (0, 0, self.frameBufferSize[0], self.frameBufferSize[1]) self.scissorTest = True self.stencilTest = False GL.glMatrixMode(GL.GL_PROJECTION) # Reset the projection matrix GL.glLoadIdentity() GL.gluOrtho2D(-1, 1, -1, 1) GL.glMatrixMode(GL.GL_MODELVIEW) # Reset the modelview matrix GL.glLoadIdentity() self.depthTest = False # GL.glEnable(GL.GL_DEPTH_TEST) # Enables Depth Testing # GL.glDepthFunc(GL.GL_LESS) # The Type Of Depth Test To Do GL.glEnable(GL.GL_BLEND) GL.glShadeModel(GL.GL_SMOOTH) # Color Shading (FLAT or SMOOTH) GL.glEnable(GL.GL_POINT_SMOOTH) # check for GL_ARB_texture_float # (which is needed for shaders to be useful) # this needs to be done AFTER the context has been created if not GL.gl_info.have_extension('GL_ARB_texture_float'): self._haveShaders = False GL.glClear(GL.GL_COLOR_BUFFER_BIT) # identify gfx card vendor self.glVendor = GL.gl_info.get_vendor().lower() requestedFBO = self.useFBO if self._haveShaders: # do this after setting up FrameBufferObject self._setupShaders() else: self.useFBO = False if self.useFBO: success = self._setupFrameBuffer() if not success: self.useFBO = False if requestedFBO and not self.useFBO: logging.warning("Framebuffer object (FBO) not supported on " "this graphics card") if self.blendMode == 'add' and not self.useFBO: logging.warning("Framebuffer object (FBO) is required for " "blendMode='add'. Reverting to blendMode='avg'") self.blendMode = 'avg' def _setupShaders(self): self._progSignedTexFont = _shaders.compileProgram( _shaders.vertSimple, _shaders.fragSignedColorTexFont) self._progFBOtoFrame = _shaders.compileProgram( _shaders.vertSimple, _shaders.fragFBOtoFrame) self._shaders = {} self._shaders['signedColor'] = _shaders.compileProgram( _shaders.vertSimple, _shaders.fragSignedColor) self._shaders['signedColor_adding'] = _shaders.compileProgram( _shaders.vertSimple, _shaders.fragSignedColor_adding) self._shaders['signedTex'] = _shaders.compileProgram( _shaders.vertSimple, _shaders.fragSignedColorTex) self._shaders['signedTexMask'] = _shaders.compileProgram( _shaders.vertSimple, _shaders.fragSignedColorTexMask) self._shaders['signedTexMask1D'] = _shaders.compileProgram( _shaders.vertSimple, _shaders.fragSignedColorTexMask1D) self._shaders['signedTex_adding'] = _shaders.compileProgram( _shaders.vertSimple, _shaders.fragSignedColorTex_adding) self._shaders['signedTexMask_adding'] = _shaders.compileProgram( _shaders.vertSimple, _shaders.fragSignedColorTexMask_adding) self._shaders['signedTexMask1D_adding'] = _shaders.compileProgram( _shaders.vertSimple, _shaders.fragSignedColorTexMask1D_adding) self._shaders['imageStim'] = _shaders.compileProgram( _shaders.vertSimple, _shaders.fragImageStim) self._shaders['imageStim_adding'] = _shaders.compileProgram( _shaders.vertSimple, _shaders.fragImageStim_adding) self._shaders['stim3d_phong'] = {} # Create shader flags, these are used as keys to pick the appropriate # shader for the given material and lighting configuration. shaderFlags = [] for i in range(0, 8 + 1): for j in product((True, False), repeat=1): shaderFlags.append((i, j[0])) # Compile shaders based on generated flags. for flag in shaderFlags: # Define GLSL preprocessor values to enable code paths for specific # material properties. srcDefs = {'MAX_LIGHTS': flag[0]} if flag[1]: # has diffuse texture map srcDefs['DIFFUSE_TEXTURE'] = 1 # embed #DEFINE statements in GLSL source code vertSrc = gltools.embedShaderSourceDefs( _shaders.vertPhongLighting, srcDefs) fragSrc = gltools.embedShaderSourceDefs( _shaders.fragPhongLighting, srcDefs) # build a shader program prog = gltools.createProgramObjectARB() vertexShader = gltools.compileShaderObjectARB( vertSrc, GL.GL_VERTEX_SHADER_ARB) fragmentShader = gltools.compileShaderObjectARB( fragSrc, GL.GL_FRAGMENT_SHADER_ARB) gltools.attachObjectARB(prog, vertexShader) gltools.attachObjectARB(prog, fragmentShader) gltools.linkProgramObjectARB(prog) gltools.detachObjectARB(prog, vertexShader) gltools.detachObjectARB(prog, fragmentShader) gltools.deleteObjectARB(vertexShader) gltools.deleteObjectARB(fragmentShader) # set the flag self._shaders['stim3d_phong'][flag] = prog def _setupFrameBuffer(self): # Setup framebuffer self.frameBuffer = GL.GLuint() GL.glGenFramebuffersEXT(1, ctypes.byref(self.frameBuffer)) GL.glBindFramebufferEXT(GL.GL_FRAMEBUFFER_EXT, self.frameBuffer) # Create texture to render to self.frameTexture = GL.GLuint() GL.glGenTextures(1, ctypes.byref(self.frameTexture)) GL.glBindTexture(GL.GL_TEXTURE_2D, self.frameTexture) GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR) GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR) GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGBA32F_ARB, int(self.size[0]), int(self.size[1]), 0, GL.GL_RGBA, GL.GL_FLOAT, None) # attach texture to the frame buffer GL.glFramebufferTexture2DEXT(GL.GL_FRAMEBUFFER_EXT, GL.GL_COLOR_ATTACHMENT0_EXT, GL.GL_TEXTURE_2D, self.frameTexture, 0) # add a stencil buffer self._stencilTexture = GL.GLuint() GL.glGenRenderbuffersEXT(1, ctypes.byref( self._stencilTexture)) # like glGenTextures GL.glBindRenderbufferEXT(GL.GL_RENDERBUFFER_EXT, self._stencilTexture) GL.glRenderbufferStorageEXT(GL.GL_RENDERBUFFER_EXT, GL.GL_DEPTH24_STENCIL8_EXT, int(self.size[0]), int(self.size[1])) GL.glFramebufferRenderbufferEXT(GL.GL_FRAMEBUFFER_EXT, GL.GL_DEPTH_ATTACHMENT_EXT, GL.GL_RENDERBUFFER_EXT, self._stencilTexture) GL.glFramebufferRenderbufferEXT(GL.GL_FRAMEBUFFER_EXT, GL.GL_STENCIL_ATTACHMENT_EXT, GL.GL_RENDERBUFFER_EXT, self._stencilTexture) status = GL.glCheckFramebufferStatusEXT(GL.GL_FRAMEBUFFER_EXT) if status != GL.GL_FRAMEBUFFER_COMPLETE_EXT: logging.error("Error in framebuffer activation") # UNBIND THE FRAME BUFFER OBJECT THAT WE HAD CREATED GL.glBindFramebufferEXT(GL.GL_FRAMEBUFFER_EXT, 0) return False GL.glDisable(GL.GL_TEXTURE_2D) # clear the buffers (otherwise the texture memory can contain # junk from other app) GL.glClear(GL.GL_COLOR_BUFFER_BIT) GL.glClear(GL.GL_STENCIL_BUFFER_BIT) GL.glClear(GL.GL_DEPTH_BUFFER_BIT) return True @property def mouseVisible(self): """Returns the visibility of the mouse cursor.""" return self.backend.mouseVisible @mouseVisible.setter def mouseVisible(self, visibility): """Sets the visibility of the mouse cursor. If Window was initialized with ``allowGUI=False`` then the mouse is initially set to invisible, otherwise it will initially be visible. Usage:: win.mouseVisible = False win.mouseVisible = True """ self.backend.setMouseVisibility(visibility) def setMouseVisible(self, visibility, log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message.""" setAttribute(self, 'mouseVisible', visibility, log) def setMouseType(self, name='arrow'): """Change the appearance of the cursor for this window. Cursor types provide contextual hints about how to interact with on-screen objects. The graphics used 'standard cursors' provided by the operating system. They may vary in appearance and hot spot location across platforms. The following names are valid on most platforms: * ``arrow`` : Default pointer. * ``ibeam`` : Indicates text can be edited. * ``crosshair`` : Crosshair with hot-spot at center. * ``hand`` : A pointing hand. * ``hresize`` : Double arrows pointing horizontally. * ``vresize`` : Double arrows pointing vertically. Parameters ---------- name : str Type of standard cursor to use (see above). Default is ``arrow``. Notes ----- * On Windows the ``crosshair`` option is negated with the background color. It will not be visible when placed over 50% grey fields. """ if hasattr(self.backend, "setMouseType"): self.backend.setMouseType(name) def showPilotingIndicator(self): """ Show the visual indicator which shows we are in piloting mode. """ # if we haven't made the indicator yet, do that now if self._pilotingIndicator is None: self._pilotingIndicator = TextBox2( self, text=_translate("PILOTING: Switch to run mode before testing."), letterHeight=0.1, alignment="bottom left", units="norm", size=(2, 2), borderColor="#EC9703", color="#EC9703", fillColor="transparent", borderWidth=20, autoDraw=False ) # mark it as to be shown self._showPilotingIndicator = True def hidePilotingIndicator(self): """ Hide the visual indicator which shows we are in piloting mode. """ # mark indicator as to be hidden self._showPilotingIndicator = False def showMessage(self, msg): """Show a message in the window. This can be used to show information to the participant. This creates a TextBox2 object that is displayed in the window. The text can be updated by calling this method again with a new message. The updated text will appear the next time `draw()` is called. Parameters ---------- msg : str or None Message text to display. If None, then any existing message is removed. """ if msg is None: self.hideMessage() else: self._showSplash = True if self._splashTextbox is None: # create the textbox self._splashTextbox = TextBox2( self, text=msg, units="norm", size=(2, 2), alignment="center", # full screen and centred letterHeight=0.1, # font size relative to window autoDraw=False ) else: self._splashTextbox.text = str(msg) # update the text # set text color to contrast with background self._splashTextbox.color = self._color.getReadable(contrast=1) def hideMessage(self): """Remove any message that is currently being displayed.""" self._showSplash = False def getActualFrameRate(self, nIdentical=10, nMaxFrames=100, nWarmUpFrames=10, threshold=1, infoMsg=None): """Measures the actual frames-per-second (FPS) for the screen. This is done by waiting (for a max of `nMaxFrames`) until `nIdentical` frames in a row have identical frame times (std dev below `threshold` ms). Parameters ---------- nIdentical : int, optional The number of consecutive frames that will be evaluated. Higher --> greater precision. Lower --> faster. nMaxFrames : int, optional The maximum number of frames to wait for a matching set of nIdentical. nWarmUpFrames : int, optional The number of frames to display before starting the test (this is in place to allow the system to settle after opening the `Window` for the first time. threshold : int or float, optional The threshold for the std deviation (in ms) before the set are considered a match. Returns ------- float or None Frame rate (FPS) in seconds. If there is no such sequence of identical frames a warning is logged and `None` will be returned. """ if nIdentical > nMaxFrames: raise ValueError( 'Parameter `nIdentical` must be equal to or less than ' '`nMaxFrames`') screen = self.screen name = self.name if infoMsg is None: infoMsg = "Attempting to measure frame rate of screen, please wait ..." self.showMessage(infoMsg) # log that we're measuring the frame rate now if self.autoLog: msg = "{}: Attempting to measure frame rate of screen ({:d}) ..." logging.exp(msg.format(name, screen)) # Disable `recordFrameIntervals` prior to the warmup as we expect to see # some instability here. recordFrmIntsOrig = self.recordFrameIntervals self.recordFrameIntervals = False # warm-up, allow the system to settle a bit before measuring frames for frameN in range(nWarmUpFrames): self.flip() # run test frames self.recordFrameIntervals = True # record intervals for actual test threshSecs = threshold / 1000.0 # must be in seconds for frameN in range(nMaxFrames): self.flip() recentFrames = self.frameIntervals[-nIdentical:] nIntervals = len(self.frameIntervals) if len(recentFrames) < 3: continue # no need to check variance yet recentFramesStd = numpy.std(recentFrames) # compute variability if nIntervals >= nIdentical and recentFramesStd < threshSecs: # average duration of recent frames period = numpy.mean(recentFrames) # log this too? rate = 1.0 / period # compute frame rate in Hz if self.autoLog: scrStr = "" if screen is None else " (%i)" % screen msg = "Screen{} actual frame rate measured at {:.2f}Hz" logging.exp(msg.format(scrStr, rate)) self.recordFrameIntervals = recordFrmIntsOrig self.frameIntervals = [] self.hideMessage() # remove the message return rate self.hideMessage() # remove the message # if we get here we reached end of `maxFrames` with no consistent value msg = ("Couldn't measure a consistent frame rate!\n" " - Is your graphics card set to sync to vertical blank?\n" " - Are you running other processes on your computer?\n") logging.warning(msg) return None def getMsPerFrame(self, nFrames=60, showVisual=False, msg='', msDelay=0.): """Assesses the monitor refresh rate (average, median, SD) under current conditions, over at least 60 frames. Records time for each refresh (frame) for n frames (at least 60), while displaying an optional visual. The visual is just eye-candy to show that something is happening when assessing many frames. You can also give it text to display instead of a visual, e.g., ``msg='(testing refresh rate...)'``; setting msg implies ``showVisual == False``. To simulate refresh rate under cpu load, you can specify a time to wait within the loop prior to doing the :py:attr:`~Window.flip()`. If 0 < msDelay < 100, wait for that long in ms. Returns timing stats (in ms) of: - average time per frame, for all frames - standard deviation of all frames - median, as the average of 12 frame times around the median (~monitor refresh rate) :Author: - 2010 written by Jeremy Gray """ # lower bound of 60 samples--need enough to estimate the SD nFrames = max(60, nFrames) num2avg = 12 # how many to average from around the median if len(msg): showVisual = False showText = True myMsg = TextStim(self, text=msg, italic=True, color=(.7, .6, .5), colorSpace='rgb', height=0.1, autoLog=False) else: showText = False if showVisual: x, y = self.size myStim = GratingStim(self, tex='sin', mask='gauss', size=[.6 * y / float(x), .6], sf=3.0, opacity=.2, autoLog=False) clockt = [] # clock times # end of drawing time, in clock time units, # for testing how long myStim.draw() takes drawt = [] if msDelay > 0 and msDelay < 100: doWait = True delayTime = msDelay / 1000. # sec else: doWait = False winUnitsSaved = self.units # norm is required for the visual (or text) display, as coded below self.units = 'norm' # accumulate secs per frame (and time-to-draw) for a bunch of frames: rush(True) for i in range(5): # wake everybody up self.flip() for i in range(nFrames): # ... and go for real this time clockt.append(core.getTime()) if showVisual: myStim.setPhase(1.0 / nFrames, '+', log=False) myStim.setSF(3. / nFrames, '+', log=False) myStim.setOri(12. / nFrames, '+', log=False) myStim.setOpacity(.9 / nFrames, '+', log=False) myStim.draw() elif showText: myMsg.draw() if doWait: core.wait(delayTime) drawt.append(core.getTime()) self.flip() rush(False) self.units = winUnitsSaved # restore frameTimes = [(clockt[i] - clockt[i - 1]) for i in range(1, len(clockt))] drawTimes = [(drawt[i] - clockt[i]) for i in range(len(clockt))] # == drawing only freeTimes = [frameTimes[i] - drawTimes[i] for i in range(len(frameTimes))] # == unused time # cast to float so that the resulting type == type(0.123) # for median frameTimes.sort() # median-most slice msPFmed = 1000. * float(numpy.average( frameTimes[((nFrames - num2avg) // 2):((nFrames + num2avg) // 2)])) msPFavg = 1000. * float(numpy.average(frameTimes)) msPFstd = 1000. * float(numpy.std(frameTimes)) msdrawAvg = 1000. * float(numpy.average(drawTimes)) msdrawSD = 1000. * float(numpy.std(drawTimes)) msfree = 1000. * float(numpy.average(freeTimes)) return msPFavg, msPFstd, msPFmed # msdrawAvg, msdrawSD, msfree def _startOfFlip(self): """Custom hardware classes may want to prevent flipping from occurring and can override this method as needed. Return `True` to indicate hardware flip. """ return True def _renderFBO(self): """Perform a warp operation. (in this case a copy operation without any warping) """ GL.glBegin(GL.GL_QUADS) GL.glTexCoord2f(0.0, 0.0) GL.glVertex2f(-1.0, -1.0) GL.glTexCoord2f(0.0, 1.0) GL.glVertex2f(-1.0, 1.0) GL.glTexCoord2f(1.0, 1.0) GL.glVertex2f(1.0, 1.0) GL.glTexCoord2f(1.0, 0.0) GL.glVertex2f(1.0, -1.0) GL.glEnd() def _prepareFBOrender(self): GL.glUseProgram(self._progFBOtoFrame) def _finishFBOrender(self): GL.glUseProgram(0) def _afterFBOrender(self): pass def _endOfFlip(self, clearBuffer): """Override end of flip with custom color channel masking if required. """ if clearBuffer: GL.glClear(GL.GL_COLOR_BUFFER_BIT) def getMsPerFrame(myWin, nFrames=60, showVisual=False, msg='', msDelay=0.): """ Deprecated: please use the getMsPerFrame method in the `psychopy.visual.Window` class. Assesses the monitor refresh rate (average, median, SD) under current conditions, over at least 60 frames. Records time for each refresh (frame) for n frames (at least 60), while displaying an optional visual. The visual is just eye-candy to show that something is happening when assessing many frames. You can also give it text to display instead of a visual, e.g., msg='(testing refresh rate...)'; setting msg implies showVisual == False. To simulate refresh rate under cpu load, you can specify a time to wait within the loop prior to doing the win.flip(). If 0 < msDelay < 100, wait for that long in ms. Returns timing stats (in ms) of: - average time per frame, for all frames - standard deviation of all frames - median, as the average of 12 frame times around the median (~monitor refresh rate) :Author: - 2010 written by Jeremy Gray """ return myWin.getMsPerFrame(nFrames=60, showVisual=showVisual, msg=msg, msDelay=0.)
144,499
Python
.py
3,091
35.604012
118
0.607904
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,722
button.py
psychopy_psychopy/psychopy/visual/button.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Creates a button""" # 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 as np from psychopy import event, core, layout from psychopy.tools.attributetools import attributeSetter from psychopy.visual import TextBox2 from psychopy.visual.shape import ShapeStim from psychopy.constants import (NOT_STARTED, STARTED, PLAYING, PAUSED, STOPPED, FINISHED, PRESSED, RELEASED, FOREVER) __author__ = 'Anthony Haffey & Todd Parsons' class ButtonStim(TextBox2): """ A class for putting a button into your experiment. A button is essentially a TextBox with a Mouse component contained within it, making it easy to check whether it has been clicked on. """ def __init__(self, win, text, font='Arvo', pos=(0, 0), size=None, ori=0, padding=None, anchor='center', units=None, color='white', fillColor='darkgrey', borderColor=None, borderWidth=0, colorSpace='rgb', opacity=None, letterHeight=None, bold=True, italic=False, name="", depth=0, autoLog=None, ): # Initialise TextBox TextBox2.__init__(self, win, text, font, name=name, pos=pos, size=size, ori=ori, padding=padding, anchor=anchor, units=units, color=color, fillColor=fillColor, borderColor=borderColor, borderWidth=borderWidth, colorSpace=colorSpace, opacity=opacity, letterHeight=letterHeight, bold=bold, italic=italic, alignment='center', editable=False, depth=depth, autoLog=None) self.listener = event.Mouse(win=win) self.buttonClock = core.Clock() # Attribute to save whether button was previously clicked self.wasClicked = False # Arrays to store times of clicks on and off self.timesOn = [] self.timesOff = [] @property def numClicks(self): """How many times has this button been clicked on?""" return len(self.timesOn) @property def isClicked(self): """Is this button currently being clicked on?""" # Update vertices if self._needVertexUpdate: self._updateVertices() # Return True if pressed in return bool(self.listener.isPressedIn(self)) def reset(self): """ Clear previously stored times on / off and check current click state. In Builder, this is called at the start of each routine. """ # Update wasClicked (so continued clicks at routine start are considered) self.wasClicked = self.isClicked # Clear on/off times self.timesOn = [] self.timesOff = [] class CheckBoxStim(ShapeStim): def __init__(self, win, name="", startVal=False, shape="circle", pos=(0, 0), size=(0.1, 0.1), padding=(0.02, 0.02), anchor='center', units=None, color='white', fillColor=None, borderColor="white", borderWidth=4, colorSpace='rgb', opacity=None, autoLog=None): ShapeStim.__init__(self, win, name=name, vertices=shape, pos=pos, size=size, anchor=anchor, units=units, fillColor=fillColor, lineColor=borderColor, lineWidth=borderWidth, colorSpace=colorSpace, opacity=opacity, autoLog=autoLog) # Make marker self.marker = ShapeStim(win, name=name + "Marker", vertices=shape, anchor="center", units=units, fillColor=color, lineColor=None, colorSpace=colorSpace, autoLog=False) # Set size and padding to layout marker self.padding = padding self.size = size # Set value self.checked = startVal @attributeSetter def checked(self, value): # Store as bool value = bool(value) self.__dict__['checked'] = value # Show/hide marker according to check value if value: self.marker.opacity = self._borderColor.alpha else: self.marker.opacity = 0 def setChecked(self, value): self.checked = value @attributeSetter def value(self, value): self.checked = value def setValue(self, value): self.checked = value def toggle(self): self.checked = not self.checked @attributeSetter def padding(self, value): self.__dict__['padding'] = value # None = default = 1/5 of size if value is None: value = self._size / 5 # Create unit agnostic object self._padding = layout.Size(value, self.units, self.win) * 2 @property def pos(self): return ShapeStim.pos.fget(self) @pos.setter def pos(self, value): # Do base setting ShapeStim.pos.fset(self, value) if hasattr(self, "marker"): # Adjust marker pos so it is centered within self corners = getattr(self._vertices, self.units) midpoint = np.mean(corners, axis=0) # Set marker pos self.marker.pos = midpoint @property def size(self): return ShapeStim.size.fget(self) @size.setter def size(self, value): # Do base setting ShapeStim.size.fset(self, value) if hasattr(self, "marker"): # Adjust according to padding self.marker.size = self._size - self._padding # Set pos to refresh marker pos self.pos = self.pos @property def units(self): return ShapeStim.units.fget(self) @units.setter def units(self, value): ShapeStim.units.fset(self, value) if hasattr(self, "marker"): self.marker.units = value @property def foreColor(self): # Return marker color return self.marker.fillColor @foreColor.setter def foreColor(self, value): # Set marker color self.marker.fillColor = value @property def color(self): return self.foreColor @color.setter def color(self, value): self.foreColor = value def draw(self, win=None, keepMatrix=False): # Draw self ShapeStim.draw(self, win=win, keepMatrix=keepMatrix) # Draw marker self.marker.draw(win=win, keepMatrix=keepMatrix)
6,755
Python
.py
163
30.90184
156
0.598842
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,723
circle.py
psychopy_psychopy/psychopy/visual/circle.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Creates a Circle with a given radius as a special case of a :class:`~psychopy.visual.Polygon` """ # 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 psychopy # so we can get the __path__ from psychopy.visual.polygon import Polygon class Circle(Polygon): """Creates a Circle with a given radius as a special case of a :class:`~psychopy.visual.ShapeStim` Parameters ---------- win : :class:`~psychopy.visual.Window` Window this shape is being drawn to. The stimulus instance will allocate its required resources using that Windows context. In many cases, a stimulus instance cannot be drawn on different windows unless those windows share the same OpenGL context, which permits resources to be shared between them. edges : int Number of edges to use to define the outline of the circle. The greater the number of edges, the 'rounder' the circle will appear. radius : float Initial radius of the circle in `units`. units : str Units to use when drawing. This will affect how parameters and attributes `pos`, `size` and `radius` are interpreted. lineWidth : float Width of the circle's outline. lineColor, fillColor : array_like, str, :class:`~psychopy.colors.Color` or None Color of the circle's outline and fill. If `None`, a fully transparent color is used which makes the fill or outline invisible. lineColorSpace, fillColorSpace : str Colorspace to use for the outline and fill. These change how the values passed to `lineColor` and `fillColor` are interpreted. *Deprecated*. Please use `colorSpace` to set both outline and fill colorspace. These arguments may be removed in a future version. pos : array_like Initial position (`x`, `y`) of the circle on-screen relative to the origin located at the center of the window or buffer in `units` (unless changed by specifying `viewPos`). This can be updated after initialization by setting the `pos` property. The default value is `(0.0, 0.0)` which results in no translation. size : float or array_like Initial scale factor for adjusting the size of the circle. A single value (`float`) will apply uniform scaling, while an array (`sx`, `sy`) will result in anisotropic scaling in the horizontal (`sx`) and vertical (`sy`) direction. Providing negative values to `size` will cause the shape being mirrored. Scaling can be changed by setting the `size` property after initialization. The default value is `1.0` which results in no scaling. ori : float Initial orientation of the circle in degrees about its origin. Positive values will rotate the shape clockwise, while negative values will rotate counterclockwise. The default value for `ori` is 0.0 degrees. opacity : float Opacity of the shape. A value of 1.0 indicates fully opaque and 0.0 is fully transparent (therefore invisible). Values between 1.0 and 0.0 will result in colors being blended with objects in the background. This value affects the fill (`fillColor`) and outline (`lineColor`) colors of the shape. contrast : float Contrast level of the shape (0.0 to 1.0). This value is used to modulate the contrast of colors passed to `lineColor` and `fillColor`. depth : int Depth layer to draw the stimulus when `autoDraw` is enabled. interpolate : bool Enable smoothing (anti-aliasing) when drawing shape outlines. This produces a smoother (less-pixelated) outline of the shape. draggable : bool Can this stimulus be dragged by a mouse click? lineRGB, fillRGB: array_like, :class:`~psychopy.colors.Color` or None *Deprecated*. Please use `lineColor` and `fillColor`. These arguments may be removed in a future version. name : str Optional name of the stimuli for logging. autoLog : bool Enable auto-logging of events associated with this stimuli. Useful for debugging and to track timing when used in conjunction with `autoDraw`. autoDraw : bool Enable auto drawing. When `True`, the stimulus will be drawn every frame without the need to explicitly call the :py:meth:`~psychopy.visual.shape.ShapeStim.draw()` method. color : array_like, str, :class:`~psychopy.colors.Color` or `None` Sets both the initial `lineColor` and `fillColor` of the shape. colorSpace : str Sets the colorspace, changing how values passed to `lineColor` and `fillColor` are interpreted. Attributes ---------- radius : float or int Radius of the shape. Avoid using `size` for adjusting figure dimensions if radius != 0.5 which will result in undefined behavior. """ _defaultFillColor = "white" _defaultLineColor = None def __init__(self, win, radius=.5, edges="circle", units='', lineWidth=1.5, lineColor=False, fillColor=False, colorSpace='rgb', pos=(0, 0), size=1.0, anchor=None, ori=0.0, opacity=None, contrast=1.0, depth=0, interpolate=True, draggable=False, lineRGB=False, fillRGB=False, name=None, autoLog=None, autoDraw=False, # legacy color=False, fillColorSpace=None, lineColorSpace=None, ): # what local vars are defined (these are the init params) for use by # __repr__ self._initParams = dir() self._initParams.remove('self') # initialise parent class super(Circle, self).__init__( win, radius=radius, edges=edges, units=units, lineWidth=lineWidth, lineColor=lineColor, lineColorSpace=lineColorSpace, fillColor=fillColor, fillColorSpace=fillColorSpace, pos=pos, size=size, anchor=anchor, ori=ori, opacity=opacity, contrast=contrast, depth=depth, interpolate=interpolate, draggable=draggable, lineRGB=lineRGB, fillRGB=fillRGB, name=name, autoLog=autoLog, autoDraw=autoDraw, color=color, colorSpace=colorSpace)
7,013
Python
.py
160
33.95625
83
0.629678
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,724
stim3d.py
psychopy_psychopy/psychopy/visual/stim3d.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Classes for 3D stimuli.""" # 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 from psychopy.tools.attributetools import attributeSetter, setAttribute from psychopy.visual.basevisual import WindowMixin, ColorMixin from psychopy.visual.helpers import setColor from psychopy.colors import Color, colorSpaces import psychopy.tools.mathtools as mt import psychopy.tools.gltools as gt import psychopy.tools.arraytools as at import psychopy.tools.viewtools as vt import psychopy.visual.shaders as _shaders import os from io import StringIO from PIL import Image import numpy as np import pyglet.gl as GL class LightSource: """Class for representing a light source in a scene. This is a lazy-imported class, therefore import using full path `from psychopy.visual.stim3d import LightSource` when inheriting from it. Only point and directional lighting is supported by this object for now. The ambient color of the light source contributes to the scene ambient color defined by :py:attr:`~psychopy.visual.Window.ambientLight`. Warnings -------- This class is experimental and may result in undefined behavior. """ def __init__(self, win, pos=(0., 0., 0.), diffuseColor=(1., 1., 1.), specularColor=(1., 1., 1.), ambientColor=(0., 0., 0.), colorSpace='rgb', contrast=1.0, lightType='point', attenuation=(1, 0, 0)): """ Parameters ---------- win : `~psychopy.visual.Window` Window associated with this light source. pos : array_like Position of the light source (x, y, z, w). If `w=1.0` the light will be a point source and `x`, `y`, and `z` is the position in the scene. If `w=0.0`, the light source will be directional and `x`, `y`, and `z` will define the vector pointing to the direction the light source is coming from. For instance, a vector of (0, 1, 0, 0) will indicate that a light source is coming from above. diffuseColor : array_like Diffuse light color. specularColor : array_like Specular light color. ambientColor : array_like Ambient light color. colorSpace : str or None Colorspace for diffuse, specular, and ambient color components. contrast : float Contrast of the lighting color components. This acts as a 'gain' factor which scales color values. Must be between 0.0 and 1.0. attenuation : array_like Values for the constant, linear, and quadratic terms of the lighting attenuation formula. Default is (1, 0, 0) which results in no attenuation. """ self.win = win self._pos = np.zeros((4,), np.float32) self._diffuseColor = Color() self._specularColor = Color() self._ambientColor = Color() self._lightType = None # set later # internal RGB values post colorspace conversion self._diffuseRGB = np.array((0., 0., 0., 1.), np.float32) self._specularRGB = np.array((0., 0., 0., 1.), np.float32) self._ambientRGB = np.array((0., 0., 0., 1.), np.float32) self.contrast = contrast self.colorSpace = colorSpace # set the colors self.diffuseColor = diffuseColor self.specularColor = specularColor self.ambientColor = ambientColor self.lightType = lightType self.pos = pos # attenuation factors self._kAttenuation = np.asarray(attenuation, np.float32) # -------------------------------------------------------------------------- # Lighting # # Properties about the lighting position and type. This affects the shading # of the material. # @property def pos(self): """Position of the light source in the scene in scene units.""" return self._pos[:3] @pos.setter def pos(self, value): self._pos = np.zeros((4,), np.float32) self._pos[:3] = value if self._lightType == 'point': # if a point source then `w` == 1.0 self._pos[3] = 1.0 @property def lightType(self): """Type of light source, can be 'point' or 'directional'.""" return self._lightType @lightType.setter def lightType(self, value): self._lightType = value if self._lightType == 'point': self._pos[3] = 1.0 elif self._lightType == 'directional': self._pos[3] = 0.0 else: raise ValueError( "Unknown `lightType` specified, must be 'directional' or " "'point'.") @property def attenuation(self): """Values for the constant, linear, and quadratic terms of the lighting attenuation formula. """ return self._kAttenuation @attenuation.setter def attenuation(self, value): self._kAttenuation = np.asarray(value, np.float32) # -------------------------------------------------------------------------- # Lighting colors # @property def colorSpace(self): """The name of the color space currently being used (`str` or `None`). For strings and hex values this is not needed. If `None` the default `colorSpace` for the stimulus is used (defined during initialisation). Please note that changing `colorSpace` does not change stimulus parameters. Thus, you usually want to specify `colorSpace` before setting the color. """ if hasattr(self, '_colorSpace'): return self._colorSpace else: return 'rgba' @colorSpace.setter def colorSpace(self, value): if value in colorSpaces: self._colorSpace = value else: logging.error(f"'{value}' is not a valid color space") @property def contrast(self): """A value that is simply multiplied by the color (`float`). This may be used to adjust the gain of the light source. This is applied to all lighting color components. Examples -------- Basic usage:: stim.contrast = 1.0 # unchanged contrast stim.contrast = 0.5 # decrease contrast stim.contrast = 0.0 # uniform, no contrast stim.contrast = -0.5 # slightly inverted stim.contrast = -1.0 # totally inverted Setting contrast outside range -1 to 1 is permitted, but may produce strange results if color values exceeds the monitor limits.:: stim.contrast = 1.2 # increases contrast stim.contrast = -1.2 # inverts with increased contrast """ return self._diffuseColor.contrast @contrast.setter def contrast(self, value): self._diffuseColor.contrast = value self._specularColor.contrast = value self._ambientColor.contrast = value @property def diffuseColor(self): """Diffuse color for the light source (`psychopy.color.Color`, `ArrayLike` or None). """ return self._diffuseColor.render(self.colorSpace) @diffuseColor.setter def diffuseColor(self, value): if isinstance(value, Color): self._diffuseColor = value else: self._diffuseColor = Color( value, self.colorSpace, contrast=self.contrast) if not self._diffuseColor: # If given an invalid color, set as transparent and log error self._diffuseColor = Color() logging.error(f"'{value}' is not a valid {self.colorSpace} color") # set the RGB values self._diffuseRGB[:3] = self._diffuseColor.rgb1 self._diffuseRGB[3] = self._diffuseColor.opacity def setDiffuseColor(self, color, colorSpace=None, operation='', log=None): """Set the diffuse color for the light source. Use this function if you wish to supress logging or apply operations on the color component. Parameters ---------- color : ArrayLike or `~psychopy.colors.Color` Color to set as the diffuse component of the light source. colorSpace : str or None Colorspace to use. This is only used to set the color, the value of `diffuseColor` after setting uses the color space of the object. operation : str Operation string. log : bool or None Enable logging. """ setColor( obj=self, colorAttrib="diffuseColor", color=color, colorSpace=colorSpace or self.colorSpace, operation=operation, log=log) @property def specularColor(self): """Specular color of the light source (`psychopy.color.Color`, `ArrayLike` or None). """ return self._specularColor.render(self.colorSpace) @specularColor.setter def specularColor(self, value): if isinstance(value, Color): self._specularColor = value else: self._specularColor = Color( value, self.colorSpace, contrast=self.contrast) if not self._specularColor: # If given an invalid color, set as transparent and log error self._specularColor = Color() logging.error(f"'{value}' is not a valid {self.colorSpace} color") self._specularRGB[:3] = self._specularColor.rgb1 self._specularRGB[3] = self._specularColor.opacity def setSpecularColor(self, color, colorSpace=None, operation='', log=None): """Set the diffuse color for the light source. Use this function if you wish to supress logging or apply operations on the color component. Parameters ---------- color : ArrayLike or `~psychopy.colors.Color` Color to set as the specular component of the light source. colorSpace : str or None Colorspace to use. This is only used to set the color, the value of `diffuseColor` after setting uses the color space of the object. operation : str Operation string. log : bool or None Enable logging. """ setColor( obj=self, colorAttrib="specularColor", color=color, colorSpace=colorSpace or self.colorSpace, operation=operation, log=log) @property def ambientColor(self): """Ambient color of the light source (`psychopy.color.Color`, `ArrayLike` or None). The ambient color component is used to simulate indirect lighting caused by the light source. For instance, light bouncing off adjacent surfaces or atmospheric scattering if the light source is a sun. This is independent of the global ambient color. """ return self._ambientColor.render(self.colorSpace) @ambientColor.setter def ambientColor(self, value): if isinstance(value, Color): self._ambientColor = value else: self._ambientColor = Color( value, self.colorSpace, contrast=self.contrast) if not self._ambientColor: # If given an invalid color, set as transparent and log error self._ambientColor = Color() logging.error(f"'{value}' is not a valid {self.colorSpace} color") self._ambientRGB[:3] = self._ambientColor.rgb1 self._ambientRGB[3] = self._ambientColor.opacity def setAmbientColor(self, color, colorSpace=None, operation='', log=None): """Set the ambient color for the light source. Use this function if you wish to supress logging or apply operations on the color component. Parameters ---------- color : ArrayLike or `~psychopy.colors.Color` Color to set as the ambient component of the light source. colorSpace : str or None Colorspace to use. This is only used to set the color, the value of `ambientColor` after setting uses the color space of the object. operation : str Operation string. log : bool or None Enable logging. """ setColor( obj=self, colorAttrib="ambientColor", color=color, colorSpace=colorSpace or self.colorSpace, operation=operation, log=log) # -------------------------------------------------------------------------- # Lighting RGB colors # # These are the color values for the light which will be passed to the # shader. We protect these values since we don't want the user changing the # array type or size. # @property def diffuseRGB(self): """Diffuse RGB1 color of the material. This value is passed to OpenGL. """ return self._diffuseRGB @property def specularRGB(self): """Specular RGB1 color of the material. This value is passed to OpenGL. """ return self._specularRGB @property def ambientRGB(self): """Ambient RGB1 color of the material. This value is passed to OpenGL. """ return self._ambientRGB class SceneSkybox: """Class to render scene skyboxes. This is a lazy-imported class, therefore import using full path `from psychopy.visual.stim3d import SceneSkybox` when inheriting from it. A skybox provides background imagery to serve as a visual reference for the scene. Background images are projected onto faces of a cube centered about the viewpoint regardless of any viewpoint translations, giving the illusion that the background is very far away. Usually, only one skybox can be rendered per buffer each frame. Render targets must have a depth buffer associated with them. Background images are specified as a set of image paths passed to `faceTextures`:: sky = SceneSkybox( win, ('rt.jpg', 'lf.jpg', 'up.jpg', 'dn.jpg', 'bk.jpg', 'ft.jpg')) The skybox is rendered by calling `draw()` after drawing all other 3D stimuli. Skyboxes are not affected by lighting, however, their colors can be modulated by setting the window's `sceneAmbient` value. Skyboxes should be drawn after all other 3D stimuli, but before any successive call that clears the depth buffer (eg. `setPerspectiveView`, `resetEyeTransform`, etc.) """ def __init__(self, win, tex=(), ori=0.0, axis=(0, 1, 0)): """ Parameters ---------- win : `~psychopy.visual.Window` Window this skybox is associated with. tex : list or tuple or TexCubeMap List of files paths to images to use for each face. Images are assigned to faces depending on their index within the list ([+X, -X, +Y, -Y, +Z, -Z] or [right, left, top, bottom, back, front]). If `None` is specified, the cube map may be specified later by setting the `cubemap` attribute. Alternatively, you can specify a `TexCubeMap` object to set the cube map directly. ori : float Rotation of the skybox about `axis` in degrees. axis : array_like Axis [ax, ay, az] to rotate about, default is (0, 1, 0). """ self.win = win self._ori = ori self._axis = np.ascontiguousarray(axis, dtype=np.float32) if tex: if isinstance(tex, (list, tuple,)): if len(tex) == 6: imgFace = [] for img in tex: im = Image.open(img) im = im.convert("RGBA") pixelData = np.array(im).ctypes imgFace.append(pixelData) width = imgFace[0].shape[1] height = imgFace[0].shape[0] self._skyCubemap = gt.createCubeMap( width, height, internalFormat=GL.GL_RGBA, pixelFormat=GL.GL_RGBA, dataType=GL.GL_UNSIGNED_BYTE, data=imgFace, unpackAlignment=1, texParams={ GL.GL_TEXTURE_MAG_FILTER: GL.GL_LINEAR, GL.GL_TEXTURE_MIN_FILTER: GL.GL_LINEAR, GL.GL_TEXTURE_WRAP_S: GL.GL_CLAMP_TO_EDGE, GL.GL_TEXTURE_WRAP_T: GL.GL_CLAMP_TO_EDGE, GL.GL_TEXTURE_WRAP_R: GL.GL_CLAMP_TO_EDGE}) else: raise ValueError("Not enough textures specified, must be 6.") elif isinstance(tex, gt.TexCubeMap): self._skyCubemap = tex else: raise TypeError("Invalid type specified to `tex`.") else: self._skyCubemap = None # create cube vertices and faces, discard texcoords and normals vertices, _, _, faces = gt.createBox(1.0, True) # upload to buffers vertexVBO = gt.createVBO(vertices) # create an index buffer with faces indexBuffer = gt.createVBO( faces.flatten(), target=GL.GL_ELEMENT_ARRAY_BUFFER, dataType=GL.GL_UNSIGNED_SHORT) # create the VAO for drawing self._vao = gt.createVAO( {GL.GL_VERTEX_ARRAY: vertexVBO}, indexBuffer=indexBuffer, legacy=True) # shader for the skybox self._shaderProg = _shaders.compileProgram( _shaders.vertSkyBox, _shaders.fragSkyBox) # store the skybox transformation matrix, this is not to be updated # externally self._skyboxViewMatrix = np.identity(4, dtype=np.float32) self._prtSkyboxMatrix = at.array2pointer(self._skyboxViewMatrix) @property def skyCubeMap(self): """Cubemap for the sky.""" return self._skyCubemap @skyCubeMap.setter def skyCubeMap(self, value): self._skyCubemap = value def draw(self, win=None): """Draw the skybox. This should be called last after drawing other 3D stimuli for performance reasons. Parameters ---------- win : `~psychopy.visual.Window`, optional Window to draw the skybox to. If `None`, the window set when initializing this object will be used. The window must share a context with the window which this objects was initialized with. """ if self._skyCubemap is None: # nop if no cubemap is assigned return if win is None: win = self.win else: win._makeCurrent() # enable 3D drawing win.draw3d = True # do transformations GL.glPushMatrix() GL.glLoadIdentity() # rotate the skybox if needed if self._ori != 0.0: GL.glRotatef(self._ori, *self._axis) # get/set the rotation sub-matrix from the current view matrix self._skyboxViewMatrix[:3, :3] = win.viewMatrix[:3, :3] GL.glMultTransposeMatrixf(self._prtSkyboxMatrix) # use the shader program gt.useProgram(self._shaderProg) # enable texture sampler GL.glEnable(GL.GL_TEXTURE_2D) GL.glActiveTexture(GL.GL_TEXTURE0) GL.glBindTexture(GL.GL_TEXTURE_CUBE_MAP, self._skyCubemap.name) # draw the cube VAO oldDepthFunc = win.depthFunc win.depthFunc = 'lequal' # optimized for being drawn last gt.drawVAO(self._vao, GL.GL_TRIANGLES) win.depthFunc = oldDepthFunc gt.useProgram(0) # disable sampler GL.glBindTexture(GL.GL_TEXTURE_CUBE_MAP, 0) GL.glDisable(GL.GL_TEXTURE_2D) # return to previous transformation GL.glPopMatrix() # disable 3D drawing win.draw3d = False class BlinnPhongMaterial: """Class representing a material using the Blinn-Phong lighting model. This is a lazy-imported class, therefore import using full path `from psychopy.visual.stim3d import BlinnPhongMaterial` when inheriting from it. This class stores material information to modify the appearance of drawn primitives with respect to lighting, such as color (diffuse, specular, ambient, and emission), shininess, and textures. Simple materials are intended to work with features supported by the fixed-function OpenGL pipeline. However, one may use shaders that implement the Blinn-Phong shading model for per-pixel lighting. If shaders are enabled, the colors of objects will appear different than without. This is due to the lighting/material colors being computed on a per-pixel basis, and the formulation of the lighting model. The Phong shader determines the ambient color/intensity by adding up both the scene and light ambient colors, then multiplies them by the diffuse color of the material, as the ambient light's color should be a product of the surface reflectance (albedo) and the light color (the ambient light needs to reflect off something to be visible). Diffuse reflectance is Lambertian, where the cosine angle between the incident light ray and surface normal determines color. The size of specular highlights are related to the `shininess` factor which ranges from 1.0 to 128.0. The greater this number, the tighter the specular highlight making the surface appear smoother. If shaders are not being used, specular highlights will be computed using the Phong lighting model. The emission color is optional, it simply adds to the color of every pixel much like ambient lighting does. Usually, you would not really want this, but it can be used to add bias to the overall color of the shape. If there are no lights in the scene, the diffuse color is simply multiplied by the scene and material ambient color to give the final color. Lights are attenuated (fall-off with distance) using the formula:: attenuationFactor = 1.0 / (k0 + k1 * distance + k2 * pow(distance, 2)) The coefficients for attenuation can be specified by setting `attenuation` in the lighting object. Values `k0=1.0, k1=0.0, and k2=0.0` results in a light that does not fall-off with distance. Parameters ---------- win : `~psychopy.visual.Window` or `None` Window this material is associated with, required for shaders and some color space conversions. diffuseColor : array_like Diffuse material color (r, g, b) with values between -1.0 and 1.0. specularColor : array_like Specular material color (r, g, b) with values between -1.0 and 1.0. ambientColor : array_like Ambient material color (r, g, b) with values between -1.0 and 1.0. emissionColor : array_like Emission material color (r, g, b) with values between -1.0 and 1.0. shininess : float Material shininess, usually ranges from 0.0 to 128.0. colorSpace : str Color space for `diffuseColor`, `specularColor`, `ambientColor`, and `emissionColor`. This is no longer used. opacity : float Opacity of the material. Ranges from 0.0 to 1.0 where 1.0 is fully opaque. contrast : float Contrast of the material colors. diffuseTexture : TexImage2D Optional 2D texture to apply to the material. Color values from the texture are blended with the `diffuseColor` of the material. The target primitives must have texture coordinates to specify how texels are mapped to the surface. face : str Face to apply material to. Values are `front`, `back` or `both`. Warnings -------- This class is experimental and may result in undefined behavior. """ def __init__(self, win=None, diffuseColor=(-1., -1., -1.), specularColor=(-1., -1., -1.), ambientColor=(-1., -1., -1.), emissionColor=(-1., -1., -1.), shininess=10.0, colorSpace='rgb', diffuseTexture=None, opacity=1.0, contrast=1.0, face='front'): self.win = win self._diffuseColor = Color() self._specularColor = Color() self._ambientColor = Color() self._emissionColor = Color() self._shininess = float(shininess) self._face = None # set later # internal RGB values post colorspace conversion self._diffuseRGB = np.array((0., 0., 0., 1.), np.float32) self._specularRGB = np.array((0., 0., 0., 1.), np.float32) self._ambientRGB = np.array((0., 0., 0., 1.), np.float32) self._emissionRGB = np.array((0., 0., 0., 1.), np.float32) # internal pointers to arrays, initialized below self._ptrDiffuse = None self._ptrSpecular = None self._ptrAmbient = None self._ptrEmission = None self.diffuseColor = diffuseColor self.specularColor = specularColor self.ambientColor = ambientColor self.emissionColor = emissionColor self.colorSpace = colorSpace self.opacity = opacity self.contrast = contrast self.face = face self._diffuseTexture = diffuseTexture self._normalTexture = None self._useTextures = False # keeps track if textures are being used # -------------------------------------------------------------------------- # Material colors and other properties # # These properties are used to set the color components of various material # properties. # @property def colorSpace(self): """The name of the color space currently being used (`str` or `None`). For strings and hex values this is not needed. If `None` the default `colorSpace` for the stimulus is used (defined during initialisation). Please note that changing `colorSpace` does not change stimulus parameters. Thus, you usually want to specify `colorSpace` before setting the color. """ if hasattr(self, '_colorSpace'): return self._colorSpace else: return 'rgba' @colorSpace.setter def colorSpace(self, value): if value in colorSpaces: self._colorSpace = value else: logging.error(f"'{value}' is not a valid color space") @property def contrast(self): """A value that is simply multiplied by the color (`float`). This may be used to adjust the lightness of the material. This is applied to all material color components. Examples -------- Basic usage:: stim.contrast = 1.0 # unchanged contrast stim.contrast = 0.5 # decrease contrast stim.contrast = 0.0 # uniform, no contrast stim.contrast = -0.5 # slightly inverted stim.contrast = -1.0 # totally inverted Setting contrast outside range -1 to 1 is permitted, but may produce strange results if color values exceeds the monitor limits.:: stim.contrast = 1.2 # increases contrast stim.contrast = -1.2 # inverts with increased contrast """ return self._diffuseColor.contrast @contrast.setter def contrast(self, value): self._diffuseColor.contrast = value self._specularColor.contrast = value self._ambientColor.contrast = value self._emissionColor.contrast = value @property def shininess(self): """Material shininess coefficient (`float`). This is used to specify the 'tightness' of the specular highlights. Values usually range between 0 and 128, but the range depends on the specular highlight formula used by the shader. """ return self._shininess @shininess.setter def shininess(self, value): self._shininess = float(value) @property def face(self): """Face to apply the material to (`str`). Possible values are one of `'front'`, `'back'` or `'both'`. """ return self._face @face.setter def face(self, value): # which faces to apply the material if value == 'front': self._face = GL.GL_FRONT elif value == 'back': self._face = GL.GL_BACK elif value == 'both': self._face = GL.GL_FRONT_AND_BACK else: raise ValueError( "Invalid value for `face` specified, must be 'front', 'back' " "or 'both'.") @property def diffuseColor(self): """Diffuse color `(r, g, b)` for the material (`psychopy.color.Color`, `ArrayLike` or `None`). """ return self._diffuseColor.render(self.colorSpace) @diffuseColor.setter def diffuseColor(self, value): if isinstance(value, Color): self._diffuseColor = value else: self._diffuseColor = Color( value, self.colorSpace, contrast=self.contrast) if not self._diffuseColor: # If given an invalid color, set as transparent and log error self._diffuseColor = Color() logging.error(f"'{value}' is not a valid {self.colorSpace} color") # compute RGB values for the shader self._diffuseRGB[:3] = self._diffuseColor.rgb1 self._diffuseRGB[3] = self._diffuseColor.opacity # need to create a pointer for the shader self._ptrDiffuse = np.ctypeslib.as_ctypes(self._diffuseRGB) def setDiffuseColor(self, color, colorSpace=None, operation='', log=None): """Set the diffuse color for the material. Use this method if you wish to supress logging or apply operations on the color component. Parameters ---------- color : ArrayLike or `~psychopy.colors.Color` Color to set as the diffuse component of the material. colorSpace : str or None Colorspace to use. This is only used to set the color, the value of `diffuseColor` after setting uses the color space of the object. operation : str Operation string. log : bool or None Enable logging. """ setColor( obj=self, colorAttrib="diffuseColor", color=color, colorSpace=colorSpace or self.colorSpace, operation=operation, log=log) @property def specularColor(self): """Specular color `(r, g, b)` of the material (`psychopy.color.Color`, `ArrayLike` or `None`). """ return self._specularColor.render(self.colorSpace) @specularColor.setter def specularColor(self, value): if isinstance(value, Color): self._specularColor = value else: self._specularColor = Color( value, self.colorSpace, contrast=self.contrast) if not self._specularColor: # If given an invalid color, set as transparent and log error self._specularColor = Color() logging.error(f"'{value}' is not a valid {self.colorSpace} color") self._specularRGB[:3] = self._specularColor.rgb1 self._specularRGB[3] = self._specularColor.opacity self._ptrSpecular = np.ctypeslib.as_ctypes(self._specularRGB) def setSpecularColor(self, color, colorSpace=None, operation='', log=None): """Set the diffuse color for the material. Use this function if you wish to supress logging or apply operations on the color component. Parameters ---------- color : ArrayLike or `~psychopy.colors.Color` Color to set as the specular component of the light source. colorSpace : str or None Colorspace to use. This is only used to set the color, the value of `diffuseColor` after setting uses the color space of the object. operation : str Operation string. log : bool or None Enable logging. """ setColor( obj=self, colorAttrib="specularColor", color=color, colorSpace=colorSpace or self.colorSpace, operation=operation, log=log) @property def ambientColor(self): """Ambient color `(r, g, b)` of the material (`psychopy.color.Color`, `ArrayLike` or `None`). """ return self._ambientColor.render(self.colorSpace) @ambientColor.setter def ambientColor(self, value): if isinstance(value, Color): self._ambientColor = value else: self._ambientColor = Color( value, self.colorSpace, contrast=self.contrast) if not self._ambientColor: # If given an invalid color, set as transparent and log error self._ambientColor = Color() logging.error(f"'{value}' is not a valid {self.colorSpace} color") self._ambientRGB[:3] = self._ambientColor.rgb1 self._ambientRGB[3] = self._ambientColor.opacity self._ptrAmbient = np.ctypeslib.as_ctypes(self._ambientRGB) def setAmbientColor(self, color, colorSpace=None, operation='', log=None): """Set the ambient color for the material. Use this function if you wish to supress logging or apply operations on the color component. Parameters ---------- color : ArrayLike or `~psychopy.colors.Color` Color to set as the ambient component of the light source. colorSpace : str or None Colorspace to use. This is only used to set the color, the value of `ambientColor` after setting uses the color space of the object. operation : str Operation string. log : bool or None Enable logging. """ setColor( obj=self, colorAttrib="ambientColor", color=color, colorSpace=colorSpace or self.colorSpace, operation=operation, log=log) @property def emissionColor(self): """Emission color `(r, g, b)` of the material (`psychopy.color.Color`, `ArrayLike` or `None`). """ return self._emissionColor.render(self.colorSpace) @emissionColor.setter def emissionColor(self, value): if isinstance(value, Color): self._emissionColor = value else: self._emissionColor = Color( value, self.colorSpace, contrast=self.contrast) if not self._emissionColor: # If given an invalid color, set as transparent and log error self._emissionColor = Color() logging.error(f"'{value}' is not a valid {self.colorSpace} color") self._emissionRGB[:3] = self._emissionColor.rgb1 self._emissionRGB[3] = self._emissionColor.opacity self._ptrEmission = np.ctypeslib.as_ctypes(self._emissionRGB) def setEmissionColor(self, color, colorSpace=None, operation='', log=None): """Set the emission color for the material. Use this function if you wish to supress logging or apply operations on the color component. Parameters ---------- color : ArrayLike or `~psychopy.colors.Color` Color to set as the ambient component of the light source. colorSpace : str or None Colorspace to use. This is only used to set the color, the value of `ambientColor` after setting uses the color space of the object. operation : str Operation string. log : bool or None Enable logging. """ setColor( obj=self, colorAttrib="emissionColor", color=color, colorSpace=colorSpace or self.colorSpace, operation=operation, log=log) # -------------------------------------------------------------------------- # Material RGB colors # # These are the color values formatted for use in OpenGL. # @property def diffuseRGB(self): """RGB values of the diffuse color of the material (`numpy.ndarray`). """ return self._diffuseRGB[:3] @property def specularRGB(self): """RGB values of the specular color of the material (`numpy.ndarray`). """ return self._specularRGB[:3] @property def ambientRGB(self): """RGB values of the ambient color of the material (`numpy.ndarray`). """ return self._ambientRGB[:3] @property def emissionRGB(self): """RGB values of the emission color of the material (`numpy.ndarray`). """ return self._emissionRGB[:3] # Texture setter ----------------------------------------------------------- @property def diffuseTexture(self): """Diffuse texture of the material (`psychopy.tools.gltools.TexImage2D` or `None`). """ return self._diffuseTexture @diffuseTexture.setter def diffuseTexture(self, value): self._diffuseTexture = value # -------------------------------------------------------------------------- def begin(self, useTextures=True): """Use this material for successive rendering calls. Parameters ---------- useTextures : bool Enable textures. """ GL.glDisable(GL.GL_COLOR_MATERIAL) # disable color tracking face = self._face # check if lighting is enabled, otherwise don't render lights nLights = len(self.win.lights) if self.win.useLights else 0 useTextures = useTextures and self.diffuseTexture is not None shaderKey = (nLights, useTextures) gt.useProgram(self.win._shaders['stim3d_phong'][shaderKey]) # pass values to OpenGL GL.glMaterialfv(face, GL.GL_DIFFUSE, self._ptrDiffuse) GL.glMaterialfv(face, GL.GL_SPECULAR, self._ptrSpecular) GL.glMaterialfv(face, GL.GL_AMBIENT, self._ptrAmbient) GL.glMaterialfv(face, GL.GL_EMISSION, self._ptrEmission) GL.glMaterialf(face, GL.GL_SHININESS, self.shininess) # setup textures if useTextures and self.diffuseTexture is not None: self._useTextures = True GL.glEnable(GL.GL_TEXTURE_2D) gt.bindTexture(self.diffuseTexture, 0) def end(self, clear=True): """Stop using this material. Must be called after `begin` before using another material or else later drawing operations may have undefined behavior. Upon returning, `GL_COLOR_MATERIAL` is enabled so material colors will track the current `glColor`. Parameters ---------- clear : bool Overwrite material state settings with default values. This ensures material colors are set to OpenGL defaults. You can forgo clearing if successive materials are used which overwrite `glMaterialfv` values for `GL_DIFFUSE`, `GL_SPECULAR`, `GL_AMBIENT`, `GL_EMISSION`, and `GL_SHININESS`. This reduces a bit of overhead if there is no need to return to default values intermittently between successive material `begin` and `end` calls. Textures and shaders previously enabled will still be disabled. """ if clear: GL.glMaterialfv( self._face, GL.GL_DIFFUSE, (GL.GLfloat * 4)(0.8, 0.8, 0.8, 1.0)) GL.glMaterialfv( self._face, GL.GL_SPECULAR, (GL.GLfloat * 4)(0.0, 0.0, 0.0, 1.0)) GL.glMaterialfv( self._face, GL.GL_AMBIENT, (GL.GLfloat * 4)(0.2, 0.2, 0.2, 1.0)) GL.glMaterialfv( self._face, GL.GL_EMISSION, (GL.GLfloat * 4)(0.0, 0.0, 0.0, 1.0)) GL.glMaterialf(self._face, GL.GL_SHININESS, 0.0) if self._useTextures: self._useTextures = False gt.unbindTexture(self.diffuseTexture) GL.glDisable(GL.GL_TEXTURE_2D) gt.useProgram(0) GL.glEnable(GL.GL_COLOR_MATERIAL) class RigidBodyPose: """Class for representing rigid body poses. This is a lazy-imported class, therefore import using full path `from psychopy.visual.stim3d import RigidBodyPose` when inheriting from it. This class is an abstract representation of a rigid body pose, where the position of the body in a scene is represented by a vector/coordinate and the orientation with a quaternion. Pose can be manipulated and interacted with using class methods and attributes. Rigid body poses assume a right-handed coordinate system (-Z is forward and +Y is up). Poses can be converted to 4x4 transformation matrices with `getModelMatrix`. One can use these matrices when rendering to transform the vertices of a model associated with the pose by passing them to OpenGL. Matrices are cached internally to avoid recomputing them if `pos` and `ori` attributes have not been updated. Operators `*` and `~` can be used on `RigidBodyPose` objects to combine and invert poses. For instance, you can multiply (`*`) poses to get a new pose which is the combination of both orientations and translations by:: newPose = rb1 * rb2 Likewise, a pose can be inverted by using the `~` operator:: invPose = ~rb Multiplying a pose by its inverse will result in an identity pose with no translation and default orientation where `pos=[0, 0, 0]` and `ori=[0, 0, 0, 1]`:: identityPose = ~rb * rb Warnings -------- This class is experimental and may result in undefined behavior. """ def __init__(self, pos=(0., 0., 0.), ori=(0., 0., 0., 1.)): """ Parameters ---------- pos : array_like Position vector `[x, y, z]` for the origin of the rigid body. ori : array_like Orientation quaternion `[x, y, z, w]` where `x`, `y`, `z` are imaginary and `w` is real. """ self._pos = np.ascontiguousarray(pos, dtype=np.float32) self._ori = np.ascontiguousarray(ori, dtype=np.float32) self._modelMatrix = mt.posOriToMatrix( self._pos, self._ori, dtype=np.float32) # computed only if needed self._normalMatrix = np.zeros((4, 4), dtype=np.float32, order='C') self._invModelMatrix = np.zeros((4, 4), dtype=np.float32, order='C') # additional useful vectors self._at = np.zeros((3,), dtype=np.float32, order='C') self._up = np.zeros((3,), dtype=np.float32, order='C') # compute matrices only if `pos` and `ori` attributes have been updated self._matrixNeedsUpdate = False self._invMatrixNeedsUpdate = True self._normalMatrixNeedsUpdate = True self.pos = pos self.ori = ori self._bounds = None def __repr__(self): return 'RigidBodyPose({}, {}), %s)'.format(self.pos, self.ori) @property def bounds(self): """Bounding box associated with this pose.""" return self._bounds @bounds.setter def bounds(self, value): self._bounds = value @property def pos(self): """Position vector (X, Y, Z).""" return self._pos @pos.setter def pos(self, value): self._pos = np.ascontiguousarray(value, dtype=np.float32) self._normalMatrixNeedsUpdate = self._matrixNeedsUpdate = \ self._invMatrixNeedsUpdate = True @property def ori(self): """Orientation quaternion (X, Y, Z, W).""" return self._ori @ori.setter def ori(self, value): self._ori = np.ascontiguousarray(value, dtype=np.float32) self._normalMatrixNeedsUpdate = self._matrixNeedsUpdate = \ self._invMatrixNeedsUpdate = True @property def posOri(self): """The position (x, y, z) and orientation (x, y, z, w).""" return self._pos, self._ori @posOri.setter def posOri(self, value): self._pos = np.ascontiguousarray(value[0], dtype=np.float32) self._ori = np.ascontiguousarray(value[1], dtype=np.float32) self._matrixNeedsUpdate = self._invMatrixNeedsUpdate = \ self._normalMatrixNeedsUpdate = True @property def at(self): """Vector defining the forward direction (-Z) of this pose.""" if self._matrixNeedsUpdate: # matrix needs update, this need to be too atDir = [0., 0., -1.] self._at = mt.applyQuat(self.ori, atDir, out=self._at) return self._at @property def up(self): """Vector defining the up direction (+Y) of this pose.""" if self._matrixNeedsUpdate: # matrix needs update, this need to be too upDir = [0., 1., 0.] self._up = mt.applyQuat(self.ori, upDir, out=self._up) return self._up def __mul__(self, other): """Multiply two poses, combining them to get a new pose.""" newOri = mt.multQuat(self._ori, other.ori) return RigidBodyPose(mt.transform(other.pos, newOri, self._pos), newOri) def __imul__(self, other): """Inplace multiplication. Transforms this pose by another.""" self._ori = mt.multQuat(self._ori, other.ori) self._pos = mt.transform(other.pos, self._ori, self._pos) def copy(self): """Get a new `RigidBodyPose` object which copies the position and orientation of this one. Copies are independent and do not reference each others data. Returns ------- RigidBodyPose Copy of this pose. """ return RigidBodyPose(self._pos, self._ori) def isEqual(self, other): """Check if poses have similar orientation and position. Parameters ---------- other : `RigidBodyPose` Other pose to compare. Returns ------- bool Returns `True` is poses are effectively equal. """ return np.isclose(self._pos, other.pos) and \ np.isclose(self._ori, other.ori) def setIdentity(self): """Clear rigid body transformations. """ self._pos.fill(0.0) self._ori[:3] = 0.0 self._ori[3] = 1.0 self._matrixNeedsUpdate = self._normalMatrixNeedsUpdate = \ self._invMatrixNeedsUpdate = True def getOriAxisAngle(self, degrees=True): """Get the axis and angle of rotation for the rigid body. Converts the orientation defined by the `ori` quaternion to and axis-angle representation. Parameters ---------- degrees : bool, optional Specify ``True`` if `angle` is in degrees, or else it will be treated as radians. Default is ``True``. Returns ------- tuple Axis [rx, ry, rz] and angle. """ return mt.quatToAxisAngle(self._ori, degrees) def setOriAxisAngle(self, axis, angle, degrees=True): """Set the orientation of the rigid body using an `axis` and `angle`. This sets the quaternion at `ori`. Parameters ---------- axis : array_like Axis of rotation [rx, ry, rz]. angle : float Angle of rotation. degrees : bool, optional Specify ``True`` if `angle` is in degrees, or else it will be treated as radians. Default is ``True``. """ self.ori = mt.quatFromAxisAngle(axis, angle, degrees) def getYawPitchRoll(self, degrees=True): """Get the yaw, pitch and roll angles for this pose relative to the -Z world axis. Parameters ---------- degrees : bool, optional Specify ``True`` if `angle` is in degrees, or else it will be treated as radians. Default is ``True``. """ return mt.quatYawPitchRoll(self._ori, degrees) @property def modelMatrix(self): """Pose as a 4x4 model matrix (read-only).""" if not self._matrixNeedsUpdate: return self._modelMatrix else: return self.getModelMatrix() @property def inverseModelMatrix(self): """Inverse of the pose as a 4x4 model matrix (read-only).""" if not self._invMatrixNeedsUpdate: return self._invModelMatrix else: return self.getModelMatrix(inverse=True) @property def normalMatrix(self): """The normal transformation matrix.""" if not self._normalMatrixNeedsUpdate: return self._normalMatrix else: return self.getNormalMatrix() def getNormalMatrix(self, out=None): """Get the present normal matrix. Parameters ---------- out : ndarray or None Optional 4x4 array to write values to. Values written are computed using 32-bit float precision regardless of the data type of `out`. Returns ------- ndarray 4x4 normal transformation matrix. """ if not self._normalMatrixNeedsUpdate: return self._normalMatrix self._normalMatrix[:, :] = np.linalg.inv(self.modelMatrix).T if out is not None: out[:, :] = self._normalMatrix[:, :] self._normalMatrixNeedsUpdate = False return self._normalMatrix def getModelMatrix(self, inverse=False, out=None): """Get the present rigid body transformation as a 4x4 matrix. Matrices are computed only if the `pos` and `ori` attributes have been updated since the last call to `getModelMatrix`. The returned matrix is an `ndarray` and row-major. Parameters ---------- inverse : bool, optional Return the inverse of the model matrix. out : ndarray or None Optional 4x4 array to write values to. Values written are computed using 32-bit float precision regardless of the data type of `out`. Returns ------- ndarray 4x4 transformation matrix. Examples -------- Using a rigid body pose to transform something in OpenGL:: rb = RigidBodyPose((0, 0, -2)) # 2 meters away from origin # Use `array2pointer` from `psychopy.tools.arraytools` to convert # array to something OpenGL accepts. mv = array2pointer(rb.modelMatrix) # use the matrix to transform the scene glMatrixMode(GL_MODELVIEW) glPushMatrix() glLoadIdentity() glMultTransposeMatrixf(mv) # draw the thing here ... glPopMatrix() """ if self._matrixNeedsUpdate: self._modelMatrix = mt.posOriToMatrix( self._pos, self._ori, out=self._modelMatrix) self._matrixNeedsUpdate = False self._normalMatrixNeedsUpdate = self._invMatrixNeedsUpdate = True # only update and return the inverse matrix if requested if inverse: if self._invMatrixNeedsUpdate: self._invModelMatrix = mt.invertMatrix( self._modelMatrix, out=self._invModelMatrix) self._invMatrixNeedsUpdate = False if out is not None: out[:, :] = self._invModelMatrix[:, :] return self._invModelMatrix # return the inverse if out is not None: out[:, :] = self._modelMatrix[:, :] return self._modelMatrix def getViewMatrix(self, inverse=False): """Convert this pose into a view matrix. Creates a view matrix which transforms points into eye space using the current pose as the eye position in the scene. Furthermore, you can use view matrices for rendering shadows if light positions are defined as `RigidBodyPose` objects. Parameters ---------- inverse : bool Return the inverse of the view matrix. Default is `False`. Returns ------- ndarray 4x4 transformation matrix. """ axes = np.asarray([[0, 0, -1], [0, 1, 0]], dtype=np.float32) rotMatrix = mt.quatToMatrix(self._ori, dtype=np.float32) transformedAxes = mt.applyMatrix(rotMatrix, axes, dtype=np.float32) fwdVec = transformedAxes[0, :] + self._pos upVec = transformedAxes[1, :] viewMatrix = vt.lookAt(self._pos, fwdVec, upVec, dtype=np.float32) if inverse: viewMatrix = mt.invertMatrix(viewMatrix) return viewMatrix def transform(self, v, out=None): """Transform a vector using this pose. Parameters ---------- v : array_like Vector to transform [x, y, z]. out : ndarray or None, optional Optional array to write values to. Must have the same shape as `v`. Returns ------- ndarray Transformed points. """ return mt.transform(self._pos, self._ori, points=v, out=out) def transformNormal(self, n): """Rotate a normal vector with respect to this pose. Rotates a normal vector `n` using the orientation quaternion at `ori`. Parameters ---------- n : array_like Normal to rotate (1-D with length 3). Returns ------- ndarray Rotated normal `n`. """ pout = np.zeros((3,), dtype=np.float32) pout[:] = n t = np.cross(self._ori[:3], n[:3]) * 2.0 u = np.cross(self._ori[:3], t) t *= self._ori[3] pout[:3] += t pout[:3] += u return pout def __invert__(self): """Operator `~` to invert the pose. Returns a `RigidBodyPose` object.""" return RigidBodyPose( -self._pos, mt.invertQuat(self._ori, dtype=np.float32)) def invert(self): """Invert this pose. """ self._ori = mt.invertQuat(self._ori, dtype=np.float32) self._pos *= -1.0 def inverted(self): """Get a pose which is the inverse of this one. Returns ------- RigidBodyPose This pose inverted. """ return RigidBodyPose( -self._pos, mt.invertQuat(self._ori, dtype=np.float32)) def distanceTo(self, v): """Get the distance to a pose or point in scene units. Parameters ---------- v : RigidBodyPose or array_like Pose or point [x, y, z] to compute distance to. Returns ------- float Distance to `v` from this pose's origin. """ if hasattr(v, 'pos'): # v is pose-like object targetPos = v.pos else: targetPos = np.asarray(v[:3]) return np.sqrt(np.sum(np.square(targetPos - self.pos))) def interp(self, end, s): """Interpolate between poses. Linear interpolation is used on position (Lerp) while the orientation has spherical linear interpolation (Slerp) applied taking the shortest arc on the hypersphere. Parameters ---------- end : LibOVRPose End pose. s : float Interpolation factor between interval 0.0 and 1.0. Returns ------- RigidBodyPose Rigid body pose whose position and orientation is at `s` between this pose and `end`. """ if not (hasattr(end, 'pos') and hasattr(end, 'ori')): raise TypeError("Object for `end` does not have attributes " "`pos` and `ori`.") interpPos = mt.lerp(self._pos, end.pos, s) interpOri = mt.slerp(self._ori, end.ori, s) return RigidBodyPose(interpPos, interpOri) def alignTo(self, alignTo): """Align this pose to another point or pose. This sets the orientation of this pose to one which orients the forward axis towards `alignTo`. Parameters ---------- alignTo : array_like or LibOVRPose Position vector [x, y, z] or pose to align to. """ if hasattr(alignTo, 'pos'): # v is pose-like object targetPos = alignTo.pos else: targetPos = np.asarray(alignTo[:3]) fwd = np.asarray([0, 0, -1], dtype=np.float32) toTarget = targetPos - self._pos invPos = mt.applyQuat( mt.invertQuat(self._ori, dtype=np.float32), toTarget, dtype=np.float32) invPos = mt.normalize(invPos) self.ori = mt.multQuat( self._ori, mt.alignTo(fwd, invPos, dtype=np.float32)) class BoundingBox: """Class for representing object bounding boxes. This is a lazy-imported class, therefore import using full path `from psychopy.visual.stim3d import BoundingBox` when inheriting from it. A bounding box is a construct which represents a 3D rectangular volume about some pose, defined by its minimum and maximum extents in the reference frame of the pose. The axes of the bounding box are aligned to the axes of the world or the associated pose. Bounding boxes are primarily used for visibility testing; to determine if the extents of an object associated with a pose (eg. the vertices of a model) falls completely outside of the viewing frustum. If so, the model can be culled during rendering to avoid wasting CPU/GPU resources on objects not visible to the viewer. """ def __init__(self, extents=None): self._extents = np.zeros((2, 3), np.float32) self._posCorners = np.zeros((8, 4), np.float32) if extents is not None: self._extents[0, :] = extents[0] self._extents[1, :] = extents[1] else: self.clear() self._computeCorners() def _computeCorners(self): """Compute the corners of the bounding box. These values are cached to speed up computations if extents hasn't been updated. """ for i in range(8): self._posCorners[i, 0] = \ self._extents[1, 0] if (i & 1) else self._extents[0, 0] self._posCorners[i, 1] = \ self._extents[1, 1] if (i & 2) else self._extents[0, 1] self._posCorners[i, 2] = \ self._extents[1, 2] if (i & 4) else self._extents[0, 2] self._posCorners[i, 3] = 1.0 @property def isValid(self): """`True` if the bounding box is valid.""" return np.all(self._extents[0, :] <= self._extents[1, :]) @property def extents(self): return self._extents @extents.setter def extents(self, value): self._extents[0, :] = value[0] self._extents[1, :] = value[1] self._computeCorners() def fit(self, verts): """Fit the bounding box to vertices.""" np.amin(verts, axis=0, out=self._extents[0]) np.amax(verts, axis=0, out=self._extents[1]) self._computeCorners() def clear(self): """Clear a bounding box, invalidating it.""" self._extents[0, :] = np.finfo(np.float32).max self._extents[1, :] = np.finfo(np.float32).min self._computeCorners() class BaseRigidBodyStim(ColorMixin, WindowMixin): """Base class for rigid body 3D stimuli. This class handles the pose of a rigid body 3D stimulus. Poses are represented by a `RigidBodyClass` object accessed via `thePose` attribute. Any class the implements `pos` and `ori` attributes can be used in place of a `RigidBodyPose` instance for `thePose`. This common interface allows for custom classes which handle 3D transformations to be used for stimulus transformations (eg. `LibOVRPose` in PsychXR can be used instead of `RigidBodyPose` which supports more VR specific features). Warnings -------- This class is experimental and may result in undefined behavior. """ def __init__(self, win, pos=(0., 0., 0.), ori=(0., 0., 0., 1.), color=(0.0, 0.0, 0.0), colorSpace='rgb', contrast=1.0, opacity=1.0, name='', autoLog=True): """ Parameters ---------- win : `~psychopy.visual.Window` Window this stimulus is associated with. Stimuli cannot be shared across windows unless they share the same context. pos : array_like Position vector `[x, y, z]` for the origin of the rigid body. ori : array_like Orientation quaternion `[x, y, z, w]` where `x`, `y`, `z` are imaginary and `w` is real. """ self.name = name super(BaseRigidBodyStim, self).__init__() self.win = win self.autoLog = autoLog self.colorSpace = colorSpace self.contrast = contrast self.opacity = opacity self.color = color self._thePose = RigidBodyPose(pos, ori) self.material = None self._vao = None @property def thePose(self): """The pose of the rigid body. This is a class which has `pos` and `ori` attributes.""" return self._thePose @thePose.setter def thePose(self, value): if hasattr(value, 'pos') and hasattr(value, 'ori'): self._thePose = value else: raise AttributeError( 'Class set to `thePose` does not implement `pos` or `ori`.') @property def pos(self): """Position vector (X, Y, Z).""" return self.thePose.pos @pos.setter def pos(self, value): self.thePose.pos = value def getPos(self): return self.thePose.pos def setPos(self, pos): self.thePose.pos = pos @property def ori(self): """Orientation quaternion (X, Y, Z, W).""" return self.thePose.ori @ori.setter def ori(self, value): self.thePose.ori = value def getOri(self): return self.thePose.ori def setOri(self, ori): self.thePose.ori = ori def getOriAxisAngle(self, degrees=True): """Get the axis and angle of rotation for the 3D stimulus. Converts the orientation defined by the `ori` quaternion to and axis-angle representation. Parameters ---------- degrees : bool, optional Specify ``True`` if `angle` is in degrees, or else it will be treated as radians. Default is ``True``. Returns ------- tuple Axis `[rx, ry, rz]` and angle. """ return self.thePose.getOriAxisAngle(degrees) def setOriAxisAngle(self, axis, angle, degrees=True): """Set the orientation of the 3D stimulus using an `axis` and `angle`. This sets the quaternion at `ori`. Parameters ---------- axis : array_like Axis of rotation [rx, ry, rz]. angle : float Angle of rotation. degrees : bool, optional Specify ``True`` if `angle` is in degrees, or else it will be treated as radians. Default is ``True``. """ self.thePose.setOriAxisAngle(axis, angle, degrees) def _createVAO(self, vertices, textureCoords, normals, faces): """Create a vertex array object for handling vertex attribute data. """ self.thePose.bounds = BoundingBox() self.thePose.bounds.fit(vertices) # upload to buffers vertexVBO = gt.createVBO(vertices) texCoordVBO = gt.createVBO(textureCoords) normalsVBO = gt.createVBO(normals) # create an index buffer with faces indexBuffer = gt.createVBO( faces.flatten(), target=GL.GL_ELEMENT_ARRAY_BUFFER, dataType=GL.GL_UNSIGNED_INT) return gt.createVAO({GL.GL_VERTEX_ARRAY: vertexVBO, GL.GL_TEXTURE_COORD_ARRAY: texCoordVBO, GL.GL_NORMAL_ARRAY: normalsVBO}, indexBuffer=indexBuffer, legacy=True) def draw(self, win=None): """Draw the stimulus. This should work for stimuli using a single VAO and material. More complex stimuli with multiple materials should override this method to correctly handle that case. Parameters ---------- win : `~psychopy.visual.Window` Window this stimulus is associated with. Stimuli cannot be shared across windows unless they share the same context. """ if win is None: win = self.win else: self._selectWindow(win) # nop if there is no VAO to draw if self._vao is None: return win.draw3d = True # apply transformation to mesh GL.glPushMatrix() GL.glMultTransposeMatrixf(at.array2pointer(self.thePose.modelMatrix)) if self.material is not None: # has a material, use it useTexture = self.material.diffuseTexture is not None self.material.begin(useTexture) gt.drawVAO(self._vao, GL.GL_TRIANGLES) self.material.end() else: # doesn't have a material, use class colors r, g, b = self._foreColor.render('rgb') color = np.ctypeslib.as_ctypes( np.array((r, g, b, self.opacity), np.float32)) nLights = len(self.win.lights) shaderKey = (nLights, False) gt.useProgram(self.win._shaders['stim3d_phong'][shaderKey]) # pass values to OpenGL as material GL.glColor4f(r, g, b, self.opacity) GL.glMaterialfv(GL.GL_FRONT, GL.GL_DIFFUSE, color) GL.glMaterialfv(GL.GL_FRONT, GL.GL_AMBIENT, color) gt.drawVAO(self._vao, GL.GL_TRIANGLES) gt.useProgram(0) GL.glPopMatrix() win.draw3d = False @attributeSetter def units(self, value): """ None, 'norm', 'cm', 'deg', 'degFlat', 'degFlatPos', or 'pix' If None then the current units of the :class:`~psychopy.visual.Window` will be used. See :ref:`units` for explanation of other options. Note that when you change units, you don't change the stimulus parameters and it is likely to change appearance. Example:: # This stimulus is 20% wide and 50% tall with respect to window stim = visual.PatchStim(win, units='norm', size=(0.2, 0.5) # This stimulus is 0.2 degrees wide and 0.5 degrees tall. stim.units = 'deg' """ if value is not None and len(value): self.__dict__['units'] = value else: self.__dict__['units'] = self.win.units def _updateList(self): """The user shouldn't need this method since it gets called after every call to .set() Chooses between using and not using shaders each call. """ pass def isVisible(self): """Check if the object is visible to the observer. Test if a pose's bounding box or position falls outside of an eye's view frustum. Poses can be assigned bounding boxes which enclose any 3D models associated with them. A model is not visible if all the corners of the bounding box fall outside the viewing frustum. Therefore any primitives (i.e. triangles) associated with the pose can be culled during rendering to reduce CPU/GPU workload. Returns ------- bool `True` if the object's bounding box is visible. Examples -------- You can avoid running draw commands if the object is not visible by doing a visibility test first:: if myStim.isVisible(): myStim.draw() """ if self.thePose.bounds is None: return True if not self.thePose.bounds.isValid: return True # transformation matrix mvpMatrix = np.zeros((4, 4), dtype=np.float32) np.matmul(self.win.projectionMatrix, self.win.viewMatrix, out=mvpMatrix) np.matmul(mvpMatrix, self.thePose.modelMatrix, out=mvpMatrix) # compute bounding box corners in current view corners = self.thePose.bounds._posCorners.dot(mvpMatrix.T) # check if corners are completely off to one side of the frustum if not np.any(corners[:, 0] > -corners[:, 3]): return False if not np.any(corners[:, 0] < corners[:, 3]): return False if not np.any(corners[:, 1] > -corners[:, 3]): return False if not np.any(corners[:, 1] < corners[:, 3]): return False if not np.any(corners[:, 2] > -corners[:, 3]): return False if not np.any(corners[:, 2] < corners[:, 3]): return False return True def getRayIntersectBounds(self, rayOrig, rayDir): """Get the point which a ray intersects the bounding box of this mesh. Parameters ---------- rayOrig : array_like Origin of the ray in space [x, y, z]. rayDir : array_like Direction vector of the ray [x, y, z], should be normalized. Returns ------- tuple Coordinate in world space of the intersection and distance in scene units from `rayOrig`. Returns `None` if there is no intersection. """ if self.thePose.bounds is None: return None # nop return mt.intersectRayOBB(rayOrig, rayDir, self.thePose.modelMatrix, self.thePose.bounds.extents, dtype=np.float32) class SphereStim(BaseRigidBodyStim): """Class for drawing a UV sphere. This is a lazy-imported class, therefore import using full path `from psychopy.visual.stim3d import SphereStim` when inheriting from it. The resolution of the sphere mesh can be controlled by setting `sectors` and `stacks` which controls the number of latitudinal and longitudinal subdivisions, respectively. The radius of the sphere is defined by setting `radius` expressed in scene units (meters if using a perspective projection). Calling the `draw` method will render the sphere to the current buffer. The render target (FBO or back buffer) must have a depth buffer attached to it for the object to be rendered correctly. Shading is used if the current window has light sources defined and lighting is enabled (by setting `useLights=True` before drawing the stimulus). Warnings -------- This class is experimental and may result in undefined behavior. Examples -------- Creating a red sphere 1.5 meters away from the viewer with radius 0.25:: redSphere = SphereStim(win, pos=(0., 0., -1.5), radius=0.25, color=(1, 0, 0)) """ def __init__(self, win, radius=0.5, subdiv=(32, 32), flipFaces=False, pos=(0., 0., 0.), ori=(0., 0., 0., 1.), color=(0., 0., 0.), colorSpace='rgb', contrast=1.0, opacity=1.0, useMaterial=None, name='', autoLog=True): """ Parameters ---------- win : `~psychopy.visual.Window` Window this stimulus is associated with. Stimuli cannot be shared across windows unless they share the same context. radius : float Radius of the sphere in scene units. subdiv : array_like Number of latitudinal and longitudinal subdivisions `(lat, long)` for the sphere mesh. The greater the number, the smoother the sphere will appear. flipFaces : bool, optional If `True`, normals and face windings will be set to point inward towards the center of the sphere. Texture coordinates will remain the same. Default is `False`. pos : array_like Position vector `[x, y, z]` for the origin of the rigid body. ori : array_like Orientation quaternion `[x, y, z, w]` where `x`, `y`, `z` are imaginary and `w` is real. If you prefer specifying rotations in axis-angle format, call `setOriAxisAngle` after initialization. useMaterial : PhongMaterial, optional Material to use. The material can be configured by accessing the `material` attribute after initialization. If not material is specified, the diffuse and ambient color of the shape will be set by `color`. color : array_like Diffuse and ambient color of the stimulus if `useMaterial` is not specified. Values are with respect to `colorSpace`. colorSpace : str Colorspace of `color` to use. contrast : float Contrast of the stimulus, value modulates the `color`. opacity : float Opacity of the stimulus ranging from 0.0 to 1.0. Note that transparent objects look best when rendered from farthest to nearest. name : str Name of this object for logging purposes. autoLog : bool Enable automatic logging on attribute changes. """ super(SphereStim, self).__init__(win, pos=pos, ori=ori, color=color, colorSpace=colorSpace, contrast=contrast, opacity=opacity, name=name, autoLog=autoLog) # create a vertex array object for drawing vertices, textureCoords, normals, faces = gt.createUVSphere( sectors=subdiv[0], stacks=subdiv[1], radius=radius, flipFaces=flipFaces) self._vao = self._createVAO(vertices, textureCoords, normals, faces) self.material = useMaterial self._radius = radius # for raypicking self.extents = (vertices.min(axis=0), vertices.max(axis=0)) def getRayIntersectSphere(self, rayOrig, rayDir): """Get the point which a ray intersects the sphere. Parameters ---------- rayOrig : array_like Origin of the ray in space [x, y, z]. rayDir : array_like Direction vector of the ray [x, y, z], should be normalized. Returns ------- tuple Coordinate in world space of the intersection and distance in scene units from `rayOrig`. Returns `None` if there is no intersection. """ return mt.intersectRaySphere(rayOrig, rayDir, self.thePose.pos, self._radius, dtype=np.float32) class BoxStim(BaseRigidBodyStim): """Class for drawing 3D boxes. This is a lazy-imported class, therefore import using full path `from psychopy.visual.stim3d import BoxStim` when inheriting from it. Draws a rectangular box with dimensions specified by `size` (length, width, height) in scene units. Calling the `draw` method will render the box to the current buffer. The render target (FBO or back buffer) must have a depth buffer attached to it for the object to be rendered correctly. Shading is used if the current window has light sources defined and lighting is enabled (by setting `useLights=True` before drawing the stimulus). Warnings -------- This class is experimental and may result in undefined behavior. """ def __init__(self, win, size=(.5, .5, .5), flipFaces=False, pos=(0., 0., 0.), ori=(0., 0., 0., 1.), color=(0., 0., 0.), colorSpace='rgb', contrast=1.0, opacity=1.0, useMaterial=None, textureScale=None, name='', autoLog=True): """ Parameters ---------- win : `~psychopy.visual.Window` Window this stimulus is associated with. Stimuli cannot be shared across windows unless they share the same context. size : tuple or float Dimensions of the mesh. If a single value is specified, the box will be a cube. Provide a tuple of floats to specify the width, length, and height of the box (eg. `size=(0.2, 1.3, 2.1)`) in scene units. flipFaces : bool, optional If `True`, normals and face windings will be set to point inward towards the center of the box. Texture coordinates will remain the same. Default is `False`. pos : array_like Position vector `[x, y, z]` for the origin of the rigid body. ori : array_like Orientation quaternion `[x, y, z, w]` where `x`, `y`, `z` are imaginary and `w` is real. If you prefer specifying rotations in axis-angle format, call `setOriAxisAngle` after initialization. useMaterial : PhongMaterial, optional Material to use. The material can be configured by accessing the `material` attribute after initialization. If not material is specified, the diffuse and ambient color of the shape will track the current color specified by `glColor`. color : array_like Diffuse and ambient color of the stimulus if `useMaterial` is not specified. Values are with respect to `colorSpace`. colorSpace : str Colorspace of `color` to use. contrast : float Contrast of the stimulus, value modulates the `color`. opacity : float Opacity of the stimulus ranging from 0.0 to 1.0. Note that transparent objects look best when rendered from farthest to nearest. textureScale : array_like or float, optional Scaling factors for texture coordinates (sx, sy). By default, a factor of 1 will have the entire texture cover the surface of the mesh. If a single number is provided, the texture will be scaled uniformly. name : str Name of this object for logging purposes. autoLog : bool Enable automatic logging on attribute changes. """ super(BoxStim, self).__init__( win, pos=pos, ori=ori, color=color, colorSpace=colorSpace, contrast=contrast, opacity=opacity, name=name, autoLog=autoLog) # create a vertex array object for drawing vertices, texCoords, normals, faces = gt.createBox(size, flipFaces) # scale the texture if textureScale is not None: if isinstance(textureScale, (int, float)): texCoords *= textureScale else: texCoords *= np.asarray(textureScale, dtype=np.float32) self._vao = self._createVAO(vertices, texCoords, normals, faces) self.setColor(color, colorSpace=self.colorSpace, log=False) self.material = useMaterial self.extents = (vertices.min(axis=0), vertices.max(axis=0)) class PlaneStim(BaseRigidBodyStim): """Class for drawing planes. This is a lazy-imported class, therefore import using full path `from psychopy.visual.stim3d import PlaneStim` when inheriting from it. Draws a plane with dimensions specified by `size` (length, width) in scene units. Calling the `draw` method will render the plane to the current buffer. The render target (FBO or back buffer) must have a depth buffer attached to it for the object to be rendered correctly. Shading is used if the current window has light sources defined and lighting is enabled (by setting `useLights=True` before drawing the stimulus). Warnings -------- This class is experimental and may result in undefined behavior. """ def __init__(self, win, size=(.5, .5), pos=(0., 0., 0.), ori=(0., 0., 0., 1.), color=(0., 0., 0.), colorSpace='rgb', contrast=1.0, opacity=1.0, useMaterial=None, textureScale=None, name='', autoLog=True): """ Parameters ---------- win : `~psychopy.visual.Window` Window this stimulus is associated with. Stimuli cannot be shared across windows unless they share the same context. size : tuple or float Dimensions of the mesh. If a single value is specified, the plane will be a square. Provide a tuple of floats to specify the width and length of the plane (eg. `size=(0.2, 1.3)`). pos : array_like Position vector `[x, y, z]` for the origin of the rigid body. ori : array_like Orientation quaternion `[x, y, z, w]` where `x`, `y`, `z` are imaginary and `w` is real. If you prefer specifying rotations in axis-angle format, call `setOriAxisAngle` after initialization. By default, the plane is oriented with normal facing the +Z axis of the scene. useMaterial : PhongMaterial, optional Material to use. The material can be configured by accessing the `material` attribute after initialization. If not material is specified, the diffuse and ambient color of the shape will track the current color specified by `glColor`. colorSpace : str Colorspace of `color` to use. contrast : float Contrast of the stimulus, value modulates the `color`. opacity : float Opacity of the stimulus ranging from 0.0 to 1.0. Note that transparent objects look best when rendered from farthest to nearest. textureScale : array_like or float, optional Scaling factors for texture coordinates (sx, sy). By default, a factor of 1 will have the entire texture cover the surface of the mesh. If a single number is provided, the texture will be scaled uniformly. name : str Name of this object for logging purposes. autoLog : bool Enable automatic logging on attribute changes. """ super(PlaneStim, self).__init__( win, pos=pos, ori=ori, color=color, colorSpace=colorSpace, contrast=contrast, opacity=opacity, name=name, autoLog=autoLog) # create a vertex array object for drawing vertices, texCoords, normals, faces = gt.createPlane(size) # scale the texture if textureScale is not None: if isinstance(textureScale, (int, float)): texCoords *= textureScale else: texCoords *= np.asarray(textureScale, dtype=np.float32) self._vao = self._createVAO(vertices, texCoords, normals, faces) self.setColor(color, colorSpace=self.colorSpace, log=False) self.material = useMaterial self.extents = (vertices.min(axis=0), vertices.max(axis=0)) class ObjMeshStim(BaseRigidBodyStim): """Class for loading and presenting 3D stimuli in the Wavefront OBJ format. This is a lazy-imported class, therefore import using full path `from psychopy.visual.stim3d import ObjMeshStim` when inheriting from it. Calling the `draw` method will render the mesh to the current buffer. The render target (FBO or back buffer) must have a depth buffer attached to it for the object to be rendered correctly. Shading is used if the current window has light sources defined and lighting is enabled (by setting `useLights=True` before drawing the stimulus). Vertex positions, texture coordinates, and normals are loaded and packed into a single vertex buffer object (VBO). Vertex array objects (VAO) are created for each material with an index buffer referencing vertices assigned that material in the VBO. For maximum performance, keep the number of materials per object as low as possible, as switching between VAOs has some overhead. Material attributes are read from the material library file (*.MTL) associated with the *.OBJ file. This file will be automatically searched for and read during loading. Afterwards you can edit material properties by accessing the data structure of the `materials` attribute. Keep in mind that OBJ shapes are rigid bodies, the mesh itself cannot be deformed during runtime. However, meshes can be positioned and rotated as desired by manipulating the `RigidBodyPose` instance accessed through the `thePose` attribute. Warnings -------- Loading an *.OBJ file is a slow process, be sure to do this outside of any time-critical routines! This class is experimental and may result in undefined behavior. Examples -------- Loading an *.OBJ file from a disk location:: myObjStim = ObjMeshStim(win, '/path/to/file/model.obj') """ def __init__(self, win, objFile, pos=(0, 0, 0), ori=(0, 0, 0, 1), useMaterial=None, loadMtllib=True, color=(0.0, 0.0, 0.0), colorSpace='rgb', contrast=1.0, opacity=1.0, name='', autoLog=True): """ Parameters ---------- win : `~psychopy.visual.Window` Window this stimulus is associated with. Stimuli cannot be shared across windows unless they share the same context. size : tuple or float Dimensions of the mesh. If a single value is specified, the plane will be a square. Provide a tuple of floats to specify the width and length of the box (eg. `size=(0.2, 1.3)`). pos : array_like Position vector `[x, y, z]` for the origin of the rigid body. ori : array_like Orientation quaternion `[x, y, z, w]` where `x`, `y`, `z` are imaginary and `w` is real. If you prefer specifying rotations in axis-angle format, call `setOriAxisAngle` after initialization. By default, the plane is oriented with normal facing the +Z axis of the scene. useMaterial : PhongMaterial, optional Material to use for all sub-meshes. The material can be configured by accessing the `material` attribute after initialization. If no material is specified, `color` will modulate the diffuse and ambient colors for all meshes in the model. If `loadMtllib` is `True`, this value should be `None`. loadMtllib : bool Load materials from the MTL file associated with the mesh. This will override `useMaterial` if it is `None`. The value of `materials` after initialization will be a dictionary where keys are material names and values are materials. Any textures associated with the model will be loaded as per the material requirements. """ super(ObjMeshStim, self).__init__( win, pos=pos, ori=ori, color=color, colorSpace=colorSpace, contrast=contrast, opacity=opacity, name=name, autoLog=autoLog) # load the OBJ file objModel = gt.loadObjFile(objFile) # load materials from file if requested if loadMtllib and self.material is None: self.material = self._loadMtlLib(objModel.mtlFile) else: self.material = useMaterial # load vertex data into an interleaved VBO buffers = np.ascontiguousarray( np.hstack((objModel.vertexPos, objModel.texCoords, objModel.normals)), dtype=np.float32) # upload to buffer vertexAttr = gt.createVBO(buffers) # load vertex data into VAOs self._vao = {} # dictionary for VAOs # for each material create a VAO # keys are material names, values are index buffers for material, faces in objModel.faces.items(): # convert index buffer to VAO indexBuffer = \ gt.createVBO( faces.flatten(), # flatten face index for element array target=GL.GL_ELEMENT_ARRAY_BUFFER, dataType=GL.GL_UNSIGNED_INT) # see `setVertexAttribPointer` for more information about attribute # pointer indices self._vao[material] = gt.createVAO( {GL.GL_VERTEX_ARRAY: (vertexAttr, 3), GL.GL_TEXTURE_COORD_ARRAY: (vertexAttr, 2, 3), GL.GL_NORMAL_ARRAY: (vertexAttr, 3, 5, True)}, indexBuffer=indexBuffer, legacy=True) self.extents = objModel.extents self.thePose.bounds = BoundingBox() self.thePose.bounds.fit(objModel.vertexPos) def _loadMtlLib(self, mtlFile): """Load a material library associated with the OBJ file. This is usually called by the constructor for this class. Parameters ---------- mtlFile : str Path to MTL file. """ with open(mtlFile, 'r') as mtl: mtlBuffer = StringIO(mtl.read()) foundMaterials = {} foundTextures = {} thisMaterial = 0 for line in mtlBuffer.readlines(): line = line.strip() if line.startswith('newmtl '): # new material thisMaterial = line[7:] foundMaterials[thisMaterial] = BlinnPhongMaterial(self.win) elif line.startswith('Ns '): # specular exponent foundMaterials[thisMaterial].shininess = line[3:] elif line.startswith('Ks '): # specular color specularColor = np.asarray(list(map(float, line[3:].split(' ')))) specularColor = 2.0 * specularColor - 1 foundMaterials[thisMaterial].specularColor = specularColor elif line.startswith('Kd '): # diffuse color diffuseColor = np.asarray(list(map(float, line[3:].split(' ')))) diffuseColor = 2.0 * diffuseColor - 1 foundMaterials[thisMaterial].diffuseColor = diffuseColor elif line.startswith('Ka '): # ambient color ambientColor = np.asarray(list(map(float, line[3:].split(' ')))) ambientColor = 2.0 * ambientColor - 1 foundMaterials[thisMaterial].ambientColor = ambientColor elif line.startswith('map_Kd '): # diffuse color map # load a diffuse texture from file textureName = line[7:] if textureName not in foundTextures.keys(): im = Image.open( os.path.join(os.path.split(mtlFile)[0], textureName)) im = im.transpose(Image.FLIP_TOP_BOTTOM) im = im.convert("RGBA") pixelData = np.array(im).ctypes width = pixelData.shape[1] height = pixelData.shape[0] foundTextures[textureName] = gt.createTexImage2D( width, height, internalFormat=GL.GL_RGBA, pixelFormat=GL.GL_RGBA, dataType=GL.GL_UNSIGNED_BYTE, data=pixelData, unpackAlignment=1, texParams={GL.GL_TEXTURE_MAG_FILTER: GL.GL_LINEAR, GL.GL_TEXTURE_MIN_FILTER: GL.GL_LINEAR}) foundMaterials[thisMaterial].diffuseTexture = \ foundTextures[textureName] return foundMaterials def draw(self, win=None): """Draw the mesh. Parameters ---------- win : `~psychopy.visual.Window` Window this stimulus is associated with. Stimuli cannot be shared across windows unless they share the same context. """ if win is None: win = self.win else: self._selectWindow(win) win.draw3d = True GL.glPushMatrix() GL.glMultTransposeMatrixf(at.array2pointer(self.thePose.modelMatrix)) # iterate over materials, draw associated VAOs if self.material is not None: # if material is a dictionary if isinstance(self.material, dict): for materialName, materialDesc in self.material.items(): materialDesc.begin() gt.drawVAO(self._vao[materialName], GL.GL_TRIANGLES) materialDesc.end() else: # material is a single item self.material.begin() for materialName, _ in self._vao.items(): gt.drawVAO(self._vao[materialName], GL.GL_TRIANGLES) self.material.end() else: r, g, b = self._foreColor.render('rgb') color = np.ctypeslib.as_ctypes( np.array((r, g, b, self.opacity), np.float32)) nLights = len(self.win.lights) shaderKey = (nLights, False) gt.useProgram(self.win._shaders['stim3d_phong'][shaderKey]) # pass values to OpenGL as material GL.glColor4f(r, g, b, self.opacity) GL.glMaterialfv(GL.GL_FRONT, GL.GL_DIFFUSE, color) GL.glMaterialfv(GL.GL_FRONT, GL.GL_AMBIENT, color) for materialName, _ in self._vao.items(): gt.drawVAO(self._vao[materialName], GL.GL_TRIANGLES) gt.useProgram(0) GL.glPopMatrix() win.draw3d = False
96,408
Python
.py
2,213
32.989607
81
0.598457
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,725
slider.py
psychopy_psychopy/psychopy/visual/slider.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """A class for getting numeric or categorical ratings, e.g., a 1-to-7 scale.""" # Part of the PsychoPy library # Copyright (C) 2015 Jonathan Peirce # Distributed under the terms of the GNU General Public License (GPL). import copy import numpy as np from psychopy import core, logging, event, layout from psychopy.tools import arraytools, stimulustools as stt from .basevisual import MinimalStim, WindowMixin, ColorMixin, BaseVisualStim from .rect import Rect from .grating import GratingStim from .elementarray import ElementArrayStim from .circle import Circle from .shape import ShapeStim from . import TextBox2 from ..tools.attributetools import logAttrib, setAttribute, attributeSetter from ..constants import FINISHED, STARTED, NOT_STARTED # Set to True to make borders visible for debugging debug = False class Slider(MinimalStim, WindowMixin, ColorMixin): """A class for obtaining ratings, e.g., on a 1-to-7 or categorical scale. A simpler alternative to RatingScale, to be customised with code rather than with arguments. A Slider instance is a re-usable visual object having a ``draw()`` method, with customizable appearance and response options. ``draw()`` displays the rating scale, handles the subject's mouse or key responses, and updates the display. As soon as a rating is supplied, ``.rating`` will go from ``None`` to selected item You can call the ``getRating()`` method anytime to get a rating, ``getRT()`` to get the decision time, or ``getHistory()`` to obtain the entire set of (rating, RT) pairs. For other examples see Coder Demos -> stimuli -> ratingsNew.py. :Authors: - 2018: Jon Peirce """ def __init__(self, win, ticks=(1, 2, 3, 4, 5), labels=None, startValue=None, pos=(0, 0), size=None, units=None, flip=False, ori=0, style='rating', styleTweaks=[], granularity=0, readOnly=False, labelColor='White', markerColor='Red', lineColor='White', colorSpace='rgb', opacity=None, font='Helvetica Bold', depth=0, name=None, labelHeight=None, labelWrapWidth=None, autoDraw=False, autoLog=True, # Synonyms color=False, fillColor=False, borderColor=False): """ Parameters ---------- win : psychopy.visual.Window Into which the scale will be rendered ticks : list or tuple, optional A set of values for tick locations. If given a list of numbers then these determine the locations of the ticks (the first and last determine the endpoints and the rest are spaced according to their values between these endpoints. labels : a list or tuple, optional The text to go with each tick (or spaced evenly across the ticks). If you give 3 labels but 5 tick locations then the end and middle ticks will be given labels. If the labels can't be distributed across the ticks then an error will be raised. If you want an uneven distribution you should include a list matching the length of ticks but with some values set to None startValue : int or float, optional The initial position of the marker on the slider. If not specified, the marker will start at the mid-point of the scale. pos : tuple, list, or array, optional The (x, y) position of the slider on the screen. size : w,h pair (tuple, array or list) The size for the scale defines the area taken up by the line and the ticks. This also controls whether the scale is horizontal or vertical. units : str, optional The units to interpret the `pos` and `size` parameters. Can be any of the standard PsychoPy units (e.g., 'pix', 'cm', 'norm'). flip : bool, optional If `True`, the labels will be placed above (for horizontal sliders) or to the right (for vertical sliders) of the slider line. Default is `False`. ori : int or float, optional The orientation of the slider in degrees. A value of 0 means no rotation, positive values rotate the slider clockwise. style : str or list of str, optional The style of the slider, e.g., 'rating', 'slider', 'radio'. Multiple styles can be combined in a list. styleTweaks : list of str, optional Additional styling tweaks, e.g., 'triangleMarker', 'labels45'. granularity : int or float The smallest valid increments for the scale. 0 gives a continuous (e.g. "VAS") scale. 1 gives a traditional likert scale. Something like 0.1 gives a limited fine-grained scale. readOnly : bool, optional If `True`, the slider is displayed but does not accept input. labelColor : color, optional The color of the labels in the specified color space. markerColor : color, optional The color of the marker in the specified color space. lineColor : color, optional The color of the slider line and ticks in the specified color space. colorSpace : str, optional The color space for defining `labelColor`, `markerColor`, and `lineColor` (e.g., 'rgb', 'rgb255', 'hex'). opacity : float, optional The opacity of the slider, ranging from 0 (completely transparent) to 1 (completely opaque). font : str, optional The font used for the labels. depth : int, optional The depth layer for rendering. Layers with lower numbers are rendered first (behind). name : str, optional An optional name for the slider, useful for logging. labelHeight : float, optional The height of the label text. If `None`, a default value based on the slider size is used. labelWrapWidth : float, optional The maximum width for text labels before wrapping. If `None`, labels are not wrapped. autoDraw : bool, optional If `True`, the slider will be automatically drawn every frame. autoLog : bool, optional If `True`, a log message is automatically generated each time the slider is updated. This can be useful for debugging or analysis. color : color, optional Synonym for `labelColor`. fillColor : color, optional Synonym for `markerColor`. borderColor : color, optional Synonym for `lineColor`. """ # what local vars are defined (these are the init params) for use by # __repr__ self._initParams = dir() super(Slider, self).__init__(name=name, autoLog=False) self.win = win if ticks is None: self.ticks = None else: self.ticks = np.array(ticks) self.labels = labels # Set pos and size via base method as objects don't yet exist to layout self.units = units WindowMixin.pos.fset(self, pos) if size is None: size = layout.Size((1, 0.1), 'height', self.win) WindowMixin.size.fset(self, size) # Set multiplier and additions to each component's size self._markerSizeMultiplier = (1, 1) self._markerSizeAddition = (0, 0) self._lineSizeMultiplier = (1, 1) self._lineSizeAddition = (0, 0) self._tickSizeMultiplier = (1, 1) self._tickSizeAddition = (0, 0) # Allow styles to force alignment/anchor for labels self._forceLabelAnchor = None self.granularity = granularity self.colorSpace = colorSpace self.color = color if color is not False else labelColor self.fillColor = fillColor if fillColor is not False else markerColor self.borderColor = borderColor if borderColor is not False else lineColor self.opacity = opacity self.font = font self.autoDraw = autoDraw self.depth = depth self.name = name self.autoLog = autoLog self.readOnly = readOnly self.ori = ori self.flip = flip self.rt = None self.history = [] self.marker = None self.line = None self.tickLines = None self.labelWrapWidth = labelWrapWidth self.labelHeight = labelHeight or min(self.size) / 2 self._updateMarkerPos = True self._dragging = False self.mouse = event.Mouse(win=win) self._mouseStateClick = None # so we can rule out long click probs self._mouseStateXY = None # so we can rule out long click probs self.validArea = None # Create elements self._createElements() self.styleTweaks = [] self.style = style self.styleTweaks += styleTweaks self._layout() # some things must wait until elements created self.contrast = 1.0 self.startValue = self.markerPos = startValue # set autoLog (now that params have been initialised) self.autoLog = autoLog if autoLog: logging.exp("Created %s = %s" % (self.name, repr(self))) self.status = NOT_STARTED self.responseClock = core.Clock() def __repr__(self, complete=False): return self.__str__(complete=complete) # from MinimalStim @property def _tickL(self): """The length of the line (in the size units) """ return min(self.extent) @property def units(self): return WindowMixin.units.fget(self) @units.setter def units(self, value): WindowMixin.units.fset(self, value) if hasattr(self, "line"): self.line.units = value if hasattr(self, "marker"): self.marker.units = value if hasattr(self, "tickLines"): self.tickLines.units = value if hasattr(self, "labelObjs"): for label in self.labelObjs: label.units = value if hasattr(self, "validArea"): self.validArea.units = value @property def pos(self): return WindowMixin.pos.fget(self) @pos.setter def pos(self, value): WindowMixin.pos.fset(self, value) self._layout() def setPos(self, newPos, operation='', log=None): BaseVisualStim.setPos(self, newPos, operation=operation, log=log) def setOri(self, newOri, operation='', log=None): BaseVisualStim.setOri(self, newOri, operation=operation, log=log) @property def size(self): return WindowMixin.size.fget(self) @size.setter def size(self, value): WindowMixin.size.fset(self, value) self._layout() def setSize(self, newSize, operation='', units=None, log=None): BaseVisualStim.setSize(self, newSize, operation=operation, units=units, log=log) @property def horiz(self): """(readonly) determines from self.size whether the scale is horizontal""" return self.extent[0] > self.extent[1] @property def categorical(self): """(readonly) determines from labels and ticks whether the slider is categorical""" return self.ticks is None or self.style == "radio" @property def extent(self): """ The distance from the leftmost point on the slider to the rightmost point, and from the highest point to the lowest. """ # Get orientation (theta) and inverse orientation (atheta) in radans theta = np.radians(self.ori) atheta = np.radians(90-self.ori) # Calculate adjacent sides to get vertical extent A1 = abs(np.cos(theta) * self.size[1]) A2 = abs(np.cos(atheta) * self.size[0]) # Calculate opposite sides to get horizontal extent O1 = abs(np.sin(theta) * self.size[1]) O2 = abs(np.sin(atheta) * self.size[0]) # Return extent return O1 + O2, A1 + A2 @extent.setter def extent(self, value): self._extent = layout.Size(self.extent, self.units, self.win) @property def flip(self): if hasattr(self, "_flip"): return self._flip @flip.setter def flip(self, value): self._flip = value @property def opacity(self): BaseVisualStim.opacity.fget(self) @opacity.setter def opacity(self, value): BaseVisualStim.opacity.fset(self, value) self.fillColor = self._fillColor.copy() self.borderColor = self._borderColor.copy() self.foreColor = self._foreColor.copy() def setOpacity(self, newOpacity, operation='', log=None): BaseVisualStim.setOpacity(self, newOpacity, operation=operation, log=log) def updateOpacity(self): BaseVisualStim.updateOpacity(self) @property def labelHeight(self): if hasattr(self, "_labelHeight"): return getattr(self._labelHeight, self.units)[1] @labelHeight.setter def labelHeight(self, value): if isinstance(value, layout.Vector): # If given a Size, use it self._labelHeight = value else: # Otherwise, convert to a Size object self._labelHeight = layout.Size([None, value], units=self.units, win=self.win) @property def labelWrapWidth(self): if hasattr(self, "_labelWrapWidth"): return getattr(self._labelWrapWidth, self.units)[0] @labelWrapWidth.setter def labelWrapWidth(self, value): if value is None: pass elif isinstance(value, layout.Vector): # If given a Size, use it self._labelWrapWidth = value else: # Otherwise, convert to a Size object self._labelWrapWidth = layout.Size([value, None], units=self.units, win=self.win) @property def foreColor(self): ColorMixin.foreColor.fget(self) @foreColor.setter def foreColor(self, value): ColorMixin.foreColor.fset(self, value) # Set color of each label if hasattr(self, 'labelObjs'): for lbl in self.labelObjs: lbl.color = self._foreColor.copy() @property def labelColor(self): """ Synonym of Slider.foreColor """ return self.foreColor @labelColor.setter def labelColor(self, value): self.foreColor = value @property def fillColor(self): ColorMixin.fillColor.fget(self) @fillColor.setter def fillColor(self, value): ColorMixin.fillColor.fset(self, value) # Set color of marker if hasattr(self, 'marker'): self.marker.fillColor = self._fillColor.copy() @property def markerColor(self): """ Synonym of Slider.fillColor """ return self.fillColor @markerColor.setter def markerColor(self, value): self.fillColor = value @property def borderColor(self): ColorMixin.borderColor.fget(self) @borderColor.setter def borderColor(self, value): ColorMixin.borderColor.fset(self, value) # Set color of lines if hasattr(self, 'line'): if self.style not in ["scrollbar"]: # Scrollbar doesn't have an outline self.line.color = self._borderColor.copy() self.line.fillColor = self._borderColor.copy() if self.style in ["slider", "scrollbar"]: # Slider and scrollbar need translucent fills self.line._fillColor.alpha *= 0.2 if hasattr(self, 'tickLines'): self.tickLines.colors = self._borderColor.copy() self.tickLines.opacities = self._borderColor.alpha def reset(self): """Resets the slider to its starting state (so that it can be restarted on each trial with a new stimulus) """ self.rating = None # this is reset to None, whatever the startValue self.markerPos = self.startValue self.history = [] self.rt = None self.responseClock.reset() self.status = NOT_STARTED def _createElements(self): # Refresh extent self.extent = self.extent # Make line self._getLineParams() self.line = Rect( win=self.win, pos=self.lineParams['pos'], size=self.lineParams['size'], units=self.units, fillColor=self._borderColor.copy(), colorSpace=self.colorSpace, autoLog=False ) # Make ticks self._getTickParams() self.tickLines = ElementArrayStim( win=self.win, xys=self.tickParams['xys'], sizes=self.tickParams['sizes'], units=self.units, nElements=len(self.ticks), elementMask=None, sfs=0, colors=self._borderColor.copy(), opacities=self._borderColor.alpha, colorSpace=self.colorSpace, autoLog=False ) # Make labels self.labelObjs = [] if self.labels is not None: self._getLabelParams() for n, label in enumerate(self.labels): # Skip blank labels if label is None: continue # Create textbox for each label obj = TextBox2( self.win, label, font=self.font, pos=self.labelParams['pos'][n], size=self.labelParams['size'][n], padding=self.labelParams['padding'][n], units=self.units, anchor=self.labelParams['anchor'][n], alignment=self.labelParams['alignment'][n], color=self._foreColor.copy(), fillColor=None, colorSpace=self.colorSpace, borderColor="red" if debug else None, letterHeight=self.labelHeight, autoLog=False ) self.labelObjs.append(obj) # Make marker self._getMarkerParams() self.marker = ShapeStim( self.win, vertices="circle", pos=self.markerParams['pos'], size=self.markerParams['size'], units=self.units, fillColor=self._fillColor, lineColor=None, autoLog=False ) # create a rectangle to check for clicks self._getHitboxParams() self.validArea = Rect( self.win, pos=self.hitboxParams['pos'], size=self.hitboxParams['size'], units=self.units, fillColor=None, lineColor="red" if debug else None, autoLog=False ) def _layout(self): # Refresh style self.style = self.style # Refresh extent self.extent = self.extent # Get marker params self._getMarkerParams() # Apply marker params self.marker.units = self.units for param, value in self.markerParams.items(): setattr(self.marker, param, value) # Get line params self._getLineParams() # Apply line params self.line.units = self.units for param, value in self.lineParams.items(): setattr(self.line, param, value) # Get tick params self._getTickParams() # Apply tick params self.tickLines.units = self.units for param, value in self.tickParams.items(): setattr(self.tickLines, param, value) # Get label params self._getLabelParams() # Apply label params for n, obj in enumerate(self.labelObjs): obj.units = self.units for param, value in self.labelParams.items(): setattr(obj, param, value[n]) # Get hitbox params self._getHitboxParams() # Apply hitbox params self.validArea.units = self.units for param, value in self.hitboxParams.items(): setattr(self.validArea, param, value) def _ratingToPos(self, rating): # Get ticks or substitute if self.ticks is not None: ticks = self.ticks else: ticks = [0, len(self.labels)] # If rating is a label, convert to an index if isinstance(rating, str) and rating in self.labels: rating = self.labels.index(rating) # Reshape rating to handle multiple values rating = np.array(rating) rating = rating.reshape((-1, 1)) rating = np.hstack((rating, rating)) # Adjust to scale bottom magDelta = rating - ticks[0] # Adjust to scale magnitude delta = magDelta / (ticks[-1] - ticks[0]) # Adjust to scale size delta = self._extent.pix * (delta - 0.5) # Adjust to scale pos pos = delta + self._pos.pix # Replace irrelevant value according to orientation pos[:, int(self.horiz)] = self._pos.pix[int(self.horiz)] # Convert to native units return getattr(layout.Position(pos, units="pix", win=self.win), self.units) def _posToRating(self, pos): # Get ticks or substitute if self.ticks is not None: ticks = self.ticks else: ticks = [0, 1] # Get in pix pos = layout.Position(pos, units=self.win.units, win=self.win).pix # Get difference from scale pos delta = pos - self._pos.pix # Adjust to scale size delta = delta / self._extent.pix + 0.5 # Adjust to scale magnitude magDelta = delta * (ticks[-1] - ticks[0]) # Adjust to scale bottom rating = magDelta + ticks[0] # Return relevant value according to orientation return rating[1-int(self.horiz)] def _getLineParams(self): """ Calculates location and size of the line based on own location and size """ # Store line details self.lineParams = { 'units': self.units, 'pos': self.pos, 'size': self._extent * np.array(self._lineSizeMultiplier) + layout.Size(self._lineSizeAddition, self.units, self.win) } def _getMarkerParams(self): """ Calculates location and size of marker based on own location and size """ # Calculate pos pos = self._ratingToPos(self.rating or 0) # Get size (and correct for norm) size = layout.Size([min(self._size.pix)]*2, 'pix', self.win) # Store marker details self.markerParams = { 'units': self.units, 'pos': pos, 'size': size * np.array(self._markerSizeMultiplier) + layout.Size(self._markerSizeAddition, self.units, self.win), } def _getTickParams(self): """ Calculates the locations of the line, tickLines and labels from the rating info """ # If categorical, create tick values from labels if self.categorical: if self.labels is None: self.ticks = np.arange(5) else: self.ticks = np.arange(len(self.labels)) self.granularity = 1.0 # Calculate positions xys = self._ratingToPos(self.ticks) # Get size (and correct for norm) size = layout.Size([min(self._extent.pix)]*2, 'pix', self.win) # Store tick details self.tickParams = { 'units': self.units, 'xys': xys, 'sizes': np.tile( getattr(size, self.units) * np.array(self._tickSizeMultiplier) + np.array(self._tickSizeAddition), (len(self.ticks), 1)), } def _getLabelParams(self): if self.labels is None: return # Get number of labels now for convenience n = len(self.labels) # Get coords of slider edges top = self.pos[1] + self.extent[1] / 2 bottom = self.pos[1] - self.extent[1] / 2 left = self.pos[0] - self.extent[0] / 2 right = self.pos[0] + self.extent[0] / 2 # Work out where labels are relative to line w = self.labelWrapWidth if self.horiz: # horizontal # Always centered horizontally anchorHoriz = alignHoriz = 'center' # Width as fraction of size, height starts at double slider if w is None: w = self.extent[0] / len(self.ticks) h = self.extent[1] * 3 # Evenly spaced, constant y x = np.linspace(left, right, num=n) x = arraytools.snapto(x, points=self.tickParams['xys'][:, 0]) y = [self.pos[1]] * n # Padding applied on vertical paddingHoriz = 0 paddingVert = (self._tickL + self.labelHeight) / 2 # Vertical align/anchor depend on flip if not self.flip: # Labels below means anchor them from the top anchorVert = alignVert = 'top' else: # Labels on top means anchor them from below anchorVert = alignVert = 'bottom' # If style tells us to force label anchor, force it if self._forceLabelAnchor is not None: anchorVert = alignVert = self._forceLabelAnchor else: # vertical # Always centered vertically anchorVert = alignVert = 'center' # Height as fraction of size, width starts at double slider h = self.extent[1] / len(self.ticks) if w is None: w = self.extent[0] * 3 # Evenly spaced and clipped to ticks, constant x y = np.linspace(bottom, top, num=n) y = arraytools.snapto(y, points=self.tickParams['xys'][:, 1]) x = [self.pos[0]] * n # Padding applied on horizontal paddingHoriz = (self._tickL + self.labelHeight) / 2 paddingVert = 0 # Horizontal align/anchor depend on flip if not self.flip: # Labels left means anchor them from the right anchorHoriz = alignHoriz = 'right' else: # Labels right means anchor them from the left anchorHoriz = alignHoriz = 'left' # If style tells us to force label anchor, force it if self._forceLabelAnchor is not None: anchorHoriz = alignHoriz = self._forceLabelAnchor # Store label details self.labelParams = { 'units': (self.units,) * n, 'pos': np.vstack((x, y)).transpose(None), 'size': np.tile((w, h), (n, 1)), 'padding': np.tile((paddingHoriz, paddingVert), (n, 1)), 'anchor': np.tile((anchorHoriz, anchorVert), (n, 1)), 'alignment': np.tile((alignHoriz, alignVert), (n, 1)) } def _getHitboxParams(self): """ Calculates hitbox size and pos from own size and pos """ # Get pos pos = self.pos # Get size size = self._extent * 1.1 # Store hitbox details self.hitboxParams = { 'units': self.units, 'pos': pos, 'size': size, } def _granularRating(self, rating): """Handle granularity for the rating""" if rating is not None: if self.categorical: # If this is a categorical slider, snap to closest tick deltas = np.absolute(np.asarray(self.ticks) - rating) i = np.argmin(deltas) rating = self.ticks[i] elif self.granularity > 0: rating = round(rating / self.granularity) * self.granularity rating = round(rating, 8) # or gives 1.9000000000000001 rating = max(rating, self.ticks[0]) rating = min(rating, self.ticks[-1]) return rating @property def rating(self): if hasattr(self, "_rating"): return self._rating @rating.setter def rating(self, rating): """The most recent rating from the participant or None. Note that the position of the marker can be set using current without looking like a change in the marker position""" rating = self._granularRating(rating) self.markerPos = rating if self.categorical and (rating is not None): rating = self.labels[int(round(rating))] self._rating = rating @property def value(self): """Synonymous with .rating""" return self.rating @value.setter def value(self, val): self.rating = val @attributeSetter def ticks(self, value): if isinstance(value, (list, tuple, np.ndarray)): # make sure all values are numeric for i, subval in enumerate(value): if isinstance(subval, str): if subval in self.labels: # if it's a label name, get its index value[i] = self.labels.index(subval) elif subval.isnumeric(): # if it's a stringified number, make it a float value[i] = float(subval) else: # otherwise, use its index within the array value[i] = i self.__dict__['ticks'] = value @attributeSetter def markerPos(self, rating): """The position on the scale where the marker should be. Note that this does not alter the value of the reported rating, only its visible display. Also note that this position is in scale units, not in coordinates""" rating = self._granularRating(rating) if ('markerPos' not in self.__dict__ or not np.all( self.__dict__['markerPos'] == rating)): self.__dict__['markerPos'] = rating self._updateMarkerPos = True def recordRating(self, rating, rt=None, log=None): """Sets the current rating value """ rating = self._granularRating(rating) setAttribute(self, attrib='rating', value=rating, operation='', log=log) if rt is None: self.rt = self.responseClock.getTime() else: self.rt = rt self.history.append((rating, self.rt)) self._updateMarkerPos = True def getRating(self): """Get the current value of rating (or None if no response yet) """ return self.rating def getRT(self): """Get the RT for most recent rating (or None if no response yet) """ return self.rt def getMarkerPos(self): """Get the current marker position (or None if no response yet) """ return self.markerPos def setMarkerPos(self, rating): """Set the current marker position (or None if no response yet) Parameters ---------- rating : int or float The rating on the scale where we want to set the marker """ if self._updateMarkerPos: self.marker.pos = self._ratingToPos(rating) self.markerPos = rating self._updateMarkerPos = False def draw(self): """Draw the Slider, with all its constituent elements on this frame """ self.getMouseResponses() if debug: self.validArea.draw() self.line.draw() self.tickLines.draw() if self.markerPos is not None: if self._updateMarkerPos: self.marker.pos = self._ratingToPos(self.markerPos) self._updateMarkerPos = False self.marker.draw() for label in self.labelObjs: label.draw() # we started drawing to reset clock on flip if self.status == NOT_STARTED: self.win.callOnFlip(self.responseClock.reset) self.status = STARTED def getHistory(self): """Return a list of the subject's history as (rating, time) tuples. The history can be retrieved at any time, allowing for continuous ratings to be obtained in real-time. Both numerical and categorical choices are stored automatically in the history. """ return self.history def setReadOnly(self, value=True, log=None): """When the rating scale is read only no responses can be made and the scale contrast is reduced Parameters ---------- value : bool (True) The value to which we should set the readOnly flag log : bool or None Force the autologging to occur or leave as default """ setAttribute(self, 'readOnly', value, log) if value == True: self.contrast = 0.5 else: self.contrast = 1.0 @attributeSetter def contrast(self, contrast): """Set all elements of the Slider (labels, ticks, line) to a contrast Parameters ---------- contrast """ self.marker.contrast = contrast self.line.contrast = contrast self.tickLines.contrasts = contrast for label in self.labelObjs: label.contrast = contrast def getMouseResponses(self): """Instructs the rating scale to check for valid mouse responses. This is usually done during the draw() method but can be done by the user as well at any point in time. The rating will be returned but will ALSO automatically be set as the current rating response. While the mouse button is down we will alter self.markerPos but don't set a value for self.rating until button comes up Returns ---------- A rating value or None """ if self.readOnly: return click = bool(self.mouse.getPressed()[0]) xy = self.mouse.getPos() if click: # Update current but don't set Rating (mouse is still down) # Dragging has to start inside a "valid" area (i.e., on the # slider), but may continue even if the mouse moves away from # the slider, as long as the mouse button is not released. if (self.validArea.contains(self.mouse, units=self.units) or self._dragging): self.markerPos = self._posToRating(xy) # updates marker self._dragging = True self._updateMarkerPos = True else: # mouse is up - check if it *just* came up if self._dragging: self._dragging = False if self.markerPos is not None: self.recordRating(self.markerPos) return self.markerPos else: # is up and was already up - move along return None self._mouseStateXY = xy # Overload color setters so they set sub-components @property def foreColor(self): ColorMixin.foreColor.fget(self) @foreColor.setter def foreColor(self, value): ColorMixin.foreColor.fset(self, value) # Set color for all labels if hasattr(self, "labelObjs"): for obj in self.labelObjs: obj.color = self._foreColor.copy() @property def fillColor(self): ColorMixin.fillColor.fget(self) @fillColor.setter def fillColor(self, value): ColorMixin.fillColor.fset(self, value) # Set color for marker if hasattr(self, "marker"): self.marker.fillColor = self._fillColor.copy() @property def borderColor(self): ColorMixin.borderColor.fget(self) @borderColor.setter def borderColor(self, value): ColorMixin.borderColor.fset(self, value) # Set color for lines if hasattr(self, "line"): self.line.color = self._borderColor.copy() if hasattr(self, "tickLines"): self.tickLines.colors = self._borderColor.copy() knownStyles = stt.sliderStyles legacyStyles = [] knownStyleTweaks = stt.sliderStyleTweaks legacyStyleTweaks = ['whiteOnBlack'] @property def style(self): if hasattr(self, "_style"): return self._style @style.setter def style(self, style): """Sets some predefined styles or use these to create your own. If you fancy creating and including your own styles that would be great! Parameters ---------- style: string Known styles currently include: 'rating': the marker is a circle 'slider': looks more like an application slider control 'whiteOnBlack': a sort of color-inverse rating scale 'scrollbar': looks like a scrollbar for a window Styles cannot be combined in a list - they are discrete """ self._style = style # Legacy: If given a list (as was once the case), take the first style if isinstance(style, (list, tuple)): styles = style style = "rating" for val in styles: # If list contains a style, use it if val in self.knownStyles + self.legacyStyles: style = val # Apply any tweaks if val in self.knownStyleTweaks + self.legacyStyleTweaks: self.styleTweaks += val if style == 'rating' or style is None: # Narrow line self.line.opacity = 1 self._lineSizeAddition = (0, 0) if self.horiz: self._lineSizeMultiplier = (1, 0.1) else: self._lineSizeMultiplier = (0.1, 1) # 1:1 circular markers self.marker.vertices = "circle" self._markerSizeMultiplier = (1, 1) self._markerSizeAddition = (0, 0) # Narrow rectangular ticks self.tickLines.elementMask = None self._tickSizeAddition = (0, 0) if self.horiz: self._tickSizeMultiplier = (0.1, 1) else: self._tickSizeMultiplier = (1, 0.1) if style == 'slider': # Semi-transparent rectangle for a line self.line._fillColor.alpha = 0.2 self._lineSizeMultiplier = (1, 1) self._lineSizeAddition = (0, 0) # Rectangular marker self.marker.vertices = "rectangle" self._markerSizeAddition = (0, 0) if self.horiz: self._markerSizeMultiplier = (0.1, 0.8) else: self._markerSizeMultiplier = (0.8, 0.1) # Narrow rectangular ticks self.tickLines.elementMask = None self._tickSizeAddition = (0, 0) if self.horiz: self._tickSizeMultiplier = (0.1, 1) else: self._tickSizeMultiplier = (1, 0.1) if style == 'radio': # No line self._lineSizeMultiplier = (0, 0) self._lineSizeAddition = (0, 0) # 0.7 scale circular markers self.marker.vertices = "circle" self._markerSizeMultiplier = (0.7, 0.7) self._markerSizeAddition = (0, 0) # 1:1 circular ticks self.tickLines.elementMask = 'circle' self._tickSizeMultiplier = (1, 1) self._tickSizeAddition = (0, 0) if style == 'choice': if self.labels is None: nLabels = len(self.ticks) else: nLabels = len(self.labels) # No line if self.horiz: self._lineSizeMultiplier = (1 + 1 / nLabels, 1) else: self._lineSizeMultiplier = (1, 1 + 1 / nLabels) # Solid ticks self.tickLines.elementMask = None self._tickSizeAddition = (0, 0) self._tickSizeMultiplier = (0, 0) # Marker is box self.marker.vertices = "rectangle" if self.horiz: self._markerSizeMultiplier = (1, 1) else: self._markerSizeMultiplier = (1, 1 / nLabels) # Labels forced center self._forceLabelAnchor = "center" # Choice doesn't make sense with granularity 0 self.granularity = 1 if style == 'scrollbar': # Semi-transparent rectangle for a line (+ extra area for marker) self.line.opacity = 1 self.line._fillColor.alpha = 0.2 self._lineSizeAddition = (0, 0) if self.horiz: self._lineSizeMultiplier = (1.2, 1) else: self._lineSizeMultiplier = (1, 1.2) # Long rectangular marker self.marker.vertices = "rectangle" if self.horiz: self._markerSizeMultiplier = (0, 1) self._markerSizeAddition = (self.extent[0] / 5, 0) else: self._markerSizeMultiplier = (1, 0) self._markerSizeAddition = (0, self.extent[1] / 5) # No ticks self.tickLines.elementMask = None self._tickSizeAddition = (0, 0) self._tickSizeMultiplier = (0, 0) # Legacy: If given a tweak, apply it as a tweak rather than a style if style in self.knownStyleTweaks + self.legacyStyleTweaks: self.styleTweaks.append(style) # Refresh style tweaks (as these override some aspects of style) self.styleTweaks = self.styleTweaks return style @attributeSetter def styleTweaks(self, styleTweaks): """Sets some predefined style tweaks or use these to create your own. If you fancy creating and including your own style tweaks that would be great! Parameters ---------- styleTweaks: list of strings Known style tweaks currently include: 'triangleMarker': the marker is a triangle 'labels45': the text is rotated by 45 degrees Legacy style tweaks include: 'whiteOnBlack': a sort of color-inverse rating scale Legacy style tweaks will work if set in code, but are not exposed in Builder as they are redundant Style tweaks can be combined in a list e.g. `['labels45']` """ if not isinstance(styleTweaks, (list, tuple, np.ndarray)): styleTweaks = [styleTweaks] self.__dict__['styleTweaks'] = styleTweaks if 'triangleMarker' in styleTweaks: # Vertices for corners of a square tl = (-0.5, 0.5) tr = (0.5, 0.5) bl = (-0.5, -0.5) br = (0.5, -0.5) mid = (0, 0) # Create triangles from 2 corners + center if self.horiz: if self.flip: self.marker.vertices = [mid, bl, br] else: self.marker.vertices = [mid, tl, tr] else: if self.flip: self.marker.vertices = [mid, tl, bl] else: self.marker.vertices = [mid, tr, br] if 'labels45' in styleTweaks: for label in self.labelObjs: label.ori = -45 # Legacy if 'whiteOnBlack' in styleTweaks: self.line.color = 'black' self.tickLines.colors = 'black' self.marker.color = 'white' for label in self.labelObjs: label.color = 'white'
44,007
Python
.py
1,059
30.769594
143
0.587579
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,726
movie.py
psychopy_psychopy/psychopy/visual/movie.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """A stimulus class for playing movies (mpeg, avi, etc...) in PsychoPy. """ # 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.visual.movies import MovieStim
353
Python
.py
8
42.625
79
0.741935
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,727
basevisual.py
psychopy_psychopy/psychopy/visual/basevisual.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Provides class BaseVisualStim and mixins; subclass to get visual stimuli """ # 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 pathlib import Path from statistics import mean from psychopy.colors import Color, colorSpaces from psychopy.layout import Vector, Position, Size, Vertices, unitTypes # Ensure setting pyglet.options['debug_gl'] to False is done prior to any # other calls to pyglet or pyglet submodules, otherwise it may not get picked # up by the pyglet GL engine and have no effect. # Shaders will work but require OpenGL2.0 drivers AND PyOpenGL3.0+ import pyglet pyglet.options['debug_gl'] = False GL = pyglet.gl try: from PIL import Image except ImportError: from . import Image import copy import sys import os import ctypes from psychopy import logging # tools must only be imported *after* event or MovieStim breaks on win32 # (JWP has no idea why!) from psychopy.tools.arraytools import val2array from psychopy.tools.attributetools import (attributeSetter, logAttrib, setAttribute, AttributeGetSetMixin) from psychopy.tools.monitorunittools import (cm2pix, deg2pix, pix2cm, pix2deg, convertToPix) from psychopy.visual.helpers import (pointInPolygon, polygonsOverlap, setColor, findImageFile) from psychopy.tools.typetools import float_uint8 from psychopy.tools.arraytools import makeRadialMatrix, createLumPattern from psychopy.event import Mouse from psychopy.tools.colorspacetools import dkl2rgb, lms2rgb # pylint: disable=W0611 from . import globalVars import numpy from numpy import pi from psychopy.constants import NOT_STARTED, STARTED, STOPPED reportNImageResizes = 5 # permitted number of resizes """ There are several base and mix-in visual classes for multiple inheritance: - MinimalStim: non-visual house-keeping code common to all visual stim RatingScale inherits only from MinimalStim. - WindowMixin: attributes/methods about the stim relative to a visual.Window. - LegacyVisualMixin: deprecated visual methods (eg, setRGB) added to BaseVisualStim - ColorMixin: for Stim that need color methods (most, not Movie) color-related methods and attribs - ContainerMixin: for stim that need polygon .contains() methods. Most need this, but not Text. .contains(), .overlaps() - TextureMixin: for texture methods namely _createTexture (Grating, not Text) seems to work; caveat: There were issues in earlier (non-MI) versions of using _createTexture so it was pulled out of classes. Now it's inside classes again. Should be watched. - BaseVisualStim: = Minimal + Window + Legacy. Furthermore adds c ommon attributes like orientation, opacity, contrast etc. Typically subclass BaseVisualStim to create new visual stim classes, and add mixin(s) as needed to add functionality. """ class MinimalStim(AttributeGetSetMixin): """Non-visual methods and attributes for BaseVisualStim and RatingScale. Includes: name, autoDraw, autoLog, status, __str__ """ def __init__(self, name=None, autoLog=None): if name not in (None, ''): self.__dict__['name'] = name else: self.__dict__['name'] = 'unnamed %s' % self.__class__.__name__ self.status = NOT_STARTED self.autoLog = autoLog self.validator = None super(MinimalStim, self).__init__() if self.autoLog: msg = ("%s is calling MinimalStim.__init__() with autolog=True. " "Set autoLog to True only at the end of __init__())") logging.warning(msg % self.__class__.__name__) def __str__(self, complete=False): """ """ if hasattr(self, '_initParams'): className = self.__class__.__name__ paramStrings = [] for param in self._initParams: if hasattr(self, param): val = getattr(self, param) valStr = repr(getattr(self, param)) if len(repr(valStr)) > 50 and not complete: if val.__class__.__name__ == 'attributeSetter': _name = val.__getattribute__.__class__.__name__ else: _name = val.__class__.__name__ valStr = "%s(...)" % _name else: valStr = 'UNKNOWN' paramStrings.append("%s=%s" % (param, valStr)) # this could be used if all params are known to exist: # paramStrings = ["%s=%s" %(param, getattr(self, param)) # for param in self._initParams] params = ", ".join(paramStrings) s = "%s(%s)" % (className, params) else: s = object.__repr__(self) return s # Might seem simple at first, but this ensures that "name" attribute # appears in docs and that name setting and updating is logged. @attributeSetter def name(self, value): """The name (`str`) of the object to be using during logged messages about this stim. If you have multiple stimuli in your experiment this really helps to make sense of log files! If name = None your stimulus will be called "unnamed <type>", e.g. visual.TextStim(win) will be called "unnamed TextStim" in the logs. """ self.__dict__['name'] = value @attributeSetter def autoDraw(self, value): """Determines whether the stimulus should be automatically drawn on every frame flip. Value should be: `True` or `False`. You do NOT need to set this on every frame flip! """ self.__dict__['autoDraw'] = value toDraw = self.win._toDraw toDrawDepths = self.win._toDrawDepths beingDrawn = (self in toDraw) if value == beingDrawn: return # nothing to do elif value: # work out where to insert the object in the autodraw list depthArray = numpy.array(toDrawDepths) # all indices where true: iis = numpy.where(depthArray < self.depth)[0] if len(iis): # we featured somewhere before the end of the list toDraw.insert(iis[0], self) toDrawDepths.insert(iis[0], self.depth) else: toDraw.append(self) toDrawDepths.append(self.depth) # Add to editable list (if needed) self.win.addEditable(self) # Mark as started self.status = STARTED elif value == False: # remove from autodraw lists toDrawDepths.pop(toDraw.index(self)) # remove from depths toDraw.remove(self) # remove from draw list # Remove from editable list (if needed) self.win.removeEditable(self) # Mark as stopped self.status = STOPPED def setAutoDraw(self, value, log=None): """Sets autoDraw. Usually you can use 'stim.attribute = value' syntax instead, but use this method to suppress the log message. """ setAttribute(self, 'autoDraw', value, log) @attributeSetter def autoLog(self, value): """Whether every change in this stimulus should be auto logged. Value should be: `True` or `False`. Set to `False` if your stimulus is updating frequently (e.g. updating its position every frame) and you want to avoid swamping the log file with messages that aren't likely to be useful. """ self.__dict__['autoLog'] = value def setAutoLog(self, value=True, log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message. """ setAttribute(self, 'autoLog', value, log) class LegacyVisualMixin: """Class to hold deprecated visual methods and attributes. Intended only for use as a mixin class for BaseVisualStim, to maintain backwards compatibility while reducing clutter in class BaseVisualStim. """ # def __init__(self): # super(LegacyVisualMixin, self).__init__() def _calcSizeRendered(self): """DEPRECATED in 1.80.00. This functionality is now handled by _updateVertices() and verticesPix """ # raise DeprecationWarning, "_calcSizeRendered() was deprecated in # 1.80.00. This functionality is now handled by _updateVertices() # and verticesPix" if self.units in ['norm', 'pix', 'height']: self._sizeRendered = copy.copy(self.size) elif self.units in ['deg', 'degs']: self._sizeRendered = deg2pix(self.size, self.win.monitor) elif self.units == 'cm': self._sizeRendered = cm2pix(self.size, self.win.monitor) else: logging.error("Stimulus units should be 'height', 'norm', " "'deg', 'cm' or 'pix', not '%s'" % self.units) def _calcPosRendered(self): """DEPRECATED in 1.80.00. This functionality is now handled by _updateVertices() and verticesPix. """ # raise DeprecationWarning, "_calcSizeRendered() was deprecated # in 1.80.00. This functionality is now handled by # _updateVertices() and verticesPix" if self.units in ['norm', 'pix', 'height']: self._posRendered = copy.copy(self.pos) elif self.units in ['deg', 'degs']: self._posRendered = deg2pix(self.pos, self.win.monitor) elif self.units == 'cm': self._posRendered = cm2pix(self.pos, self.win.monitor) def _getPolyAsRendered(self): """DEPRECATED. Return a list of vertices as rendered. """ oriRadians = numpy.radians(self.ori) sinOri = numpy.sin(-oriRadians) cosOri = numpy.cos(-oriRadians) x = (self._verticesRendered[:, 0] * cosOri - self._verticesRendered[:, 1] * sinOri) y = (self._verticesRendered[:, 0] * sinOri + self._verticesRendered[:, 1] * cosOri) return numpy.column_stack((x, y)) + self._posRendered @attributeSetter def depth(self, value): """DEPRECATED, depth is now controlled simply by drawing order. """ self.__dict__['depth'] = value class LegacyForeColorMixin: """ Mixin class to give an object all of the legacy functions for setting foreground color """ def setDKL(self, color, operation=''): """DEPRECATED since v1.60.05: Please use the `color` attribute """ self.setForeColor(color, 'dkl', operation) def setLMS(self, color, operation=''): """DEPRECATED since v1.60.05: Please use the `color` attribute """ self.setForeColor(color, 'lms', operation) @property def foreRGB(self): """ DEPRECATED: Legacy property for setting the foreground color of a stimulus in RGB, instead use `obj._foreColor.rgb` """ return self._foreColor.rgb @foreRGB.setter def foreRGB(self, value): self.foreColor = Color(value, 'rgb') @property def RGB(self): """ DEPRECATED: Legacy property for setting the foreground color of a stimulus in RGB, instead use `obj._foreColor.rgb` """ return self.foreRGB @RGB.setter def RGB(self, value): self.foreRGB = value def setRGB(self, color, operation='', log=None): """ DEPRECATED: Legacy setter for foreground RGB, instead set `obj._foreColor.rgb` """ self.setForeColor(color, 'rgb', operation, log) def setForeRGB(self, color, operation='', log=None): """ DEPRECATED: Legacy setter for foreground RGB, instead set `obj._foreColor.rgb` """ self.setForeColor(color, 'rgb', operation, log) @property def foreColorSpace(self): """Deprecated, please use colorSpace to set color space for the entire object. """ return self.colorSpace @foreColorSpace.setter def foreColorSpace(self, value): logging.warning( "Setting color space by attribute rather than by object is deprecated. Value of foreColorSpace has been assigned to colorSpace.") self.colorSpace = value class LegacyFillColorMixin: """ Mixin class to give an object all of the legacy functions for setting fill color """ @property def fillRGB(self): """ DEPRECATED: Legacy property for setting the fill color of a stimulus in RGB, instead use `obj._fillColor.rgb` """ return self._fillColor.rgb @fillRGB.setter def fillRGB(self, value): self.fillColor = Color(value, 'rgb') @property def backRGB(self): """ DEPRECATED: Legacy property for setting the fill color of a stimulus in RGB, instead use `obj._fillColor.rgb` """ return self.fillRGB @backRGB.setter def backRGB(self, value): self.fillRGB = value def setFillRGB(self, color, operation='', log=None): """ DEPRECATED: Legacy setter for fill RGB, instead set `obj._fillColor.rgb` """ self.setFillColor(color, 'rgb', operation, log) def setBackRGB(self, color, operation='', log=None): """ DEPRECATED: Legacy setter for fill RGB, instead set `obj._fillColor.rgb` """ self.setFillColor(color, 'rgb', operation, log) @property def fillColorSpace(self): """Deprecated, please use colorSpace to set color space for the entire object. """ return self.colorSpace @fillColorSpace.setter def fillColorSpace(self, value): logging.warning("Setting color space by attribute rather than by object is deprecated. Value of fillColorSpace has been assigned to colorSpace.") self.colorSpace = value @property def backColorSpace(self): """Deprecated, please use colorSpace to set color space for the entire object. """ return self.colorSpace @backColorSpace.setter def backColorSpace(self, value): logging.warning( "Setting color space by attribute rather than by object is deprecated. Value of backColorSpace has been assigned to colorSpace.") self.colorSpace = value class LegacyBorderColorMixin: """ Mixin class to give an object all of the legacy functions for setting border color """ @property def borderRGB(self): """ DEPRECATED: Legacy property for setting the border color of a stimulus in RGB, instead use `obj._borderColor.rgb` """ return self._borderColor.rgb @borderRGB.setter def borderRGB(self, value): self.borderColor = Color(value, 'rgb') @property def lineRGB(self): """ DEPRECATED: Legacy property for setting the border color of a stimulus in RGB, instead use `obj._borderColor.rgb` """ return self.borderRGB @lineRGB.setter def lineRGB(self, value): self.borderRGB = value def setBorderRGB(self, color, operation='', log=None): """ DEPRECATED: Legacy setter for border RGB, instead set `obj._borderColor.rgb` """ self.setBorderColor(color, 'rgb', operation, log) def setLineRGB(self, color, operation='', log=None): """ DEPRECATED: Legacy setter for border RGB, instead set `obj._borderColor.rgb` """ self.setBorderColor(color, 'rgb', operation, log) @property def borderColorSpace(self): """Deprecated, please use colorSpace to set color space for the entire object """ return self.colorSpace @borderColorSpace.setter def borderColorSpace(self, value): logging.warning( "Setting color space by attribute rather than by object is deprecated. Value of borderColorSpace has been assigned to colorSpace.") self.colorSpace = value @property def lineColorSpace(self): """Deprecated, please use colorSpace to set color space for the entire object """ return self.colorSpace @lineColorSpace.setter def lineColorSpace(self, value): logging.warning( "Setting color space by attribute rather than by object is deprecated. Value of lineColorSpace has been assigned to colorSpace.") self.colorSpace = value class LegacyColorMixin(LegacyForeColorMixin, LegacyFillColorMixin, LegacyBorderColorMixin): """ Mixin class to give an object all of the legacy functions for setting all colors (fore, fill and border """ class BaseColorMixin: """ Mixin class giving base color methods (e.g. colorSpace) which are needed for any color stuff. """ @property def colorSpace(self): """The name of the color space currently being used Value should be: a string or None For strings and hex values this is not needed. If None the default colorSpace for the stimulus is used (defined during initialisation). Please note that changing colorSpace does not change stimulus parameters. Thus you usually want to specify colorSpace before setting the color. Example:: # A light green text stim = visual.TextStim(win, 'Color me!', color=(0, 1, 0), colorSpace='rgb') # An almost-black text stim.colorSpace = 'rgb255' # Make it light green again stim.color = (128, 255, 128) """ if hasattr(self, '_colorSpace'): return self._colorSpace else: return 'rgba' @colorSpace.setter def colorSpace(self, value): if value in colorSpaces: self._colorSpace = value else: logging.error(f"'{value}' is not a valid color space") @property def contrast(self): """A value that is simply multiplied by the color. Value should be: a float between -1 (negative) and 1 (unchanged). :ref:`Operations <attrib-operations>` supported. Set the contrast of the stimulus, i.e. scales how far the stimulus deviates from the middle grey. You can also use the stimulus `opacity` to control contrast, but that cannot be negative. Examples:: stim.contrast = 1.0 # unchanged contrast stim.contrast = 0.5 # decrease contrast stim.contrast = 0.0 # uniform, no contrast stim.contrast = -0.5 # slightly inverted stim.contrast = -1.0 # totally inverted Setting contrast outside range -1 to 1 is permitted, but may produce strange results if color values exceeds the monitor limits.:: stim.contrast = 1.2 # increases contrast stim.contrast = -1.2 # inverts with increased contrast """ if hasattr(self, '_foreColor'): return self._foreColor.contrast @contrast.setter def contrast(self, value): if hasattr(self, '_foreColor'): self._foreColor.contrast = value if hasattr(self, '_fillColor'): self._fillColor.contrast = value if hasattr(self, '_borderColor'): self._borderColor.contrast = value def setContrast(self, newContrast, operation='', log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message """ if newContrast is not None: self.contrast = newContrast if operation in ['', '=']: self.contrast = newContrast elif operation in ['+']: self.contrast += newContrast elif operation in ['-']: self.contrast -= newContrast else: logging.error(f"Operation '{operation}' not recognised.") def _getDesiredRGB(self, rgb, colorSpace, contrast): """ Convert color to RGB while adding contrast. Requires self.rgb, self.colorSpace and self.contrast """ col = Color(rgb, colorSpace) col.contrast *= contrast or 0 return col.render('rgb') def updateColors(self): """Placeholder method to update colours when set externally, for example updating the `pallette` attribute of a textbox""" return class ForeColorMixin(BaseColorMixin, LegacyForeColorMixin): """ Mixin class for visual stim that need fore color. """ @property def foreColor(self): """Foreground color of the stimulus Value should be one of: + string: to specify a :ref:`colorNames`. Any of the standard html/X11 `color names <http://www.w3schools.com/html/html_colornames.asp>` can be used. + :ref:`hexColors` + numerically: (scalar or triplet) for DKL, RGB or other :ref:`colorspaces`. For these, :ref:`operations <attrib-operations>` are supported. When color is specified using numbers, it is interpreted with respect to the stimulus' current colorSpace. If color is given as a single value (scalar) then this will be applied to all 3 channels. Examples -------- For whatever stim you have:: stim.color = 'white' stim.color = 'RoyalBlue' # (the case is actually ignored) stim.color = '#DDA0DD' # DDA0DD is hexadecimal for plum stim.color = [1.0, -1.0, -1.0] # if stim.colorSpace='rgb': # a red color in rgb space stim.color = [0.0, 45.0, 1.0] # if stim.colorSpace='dkl': # DKL space with elev=0, azimuth=45 stim.color = [0, 0, 255] # if stim.colorSpace='rgb255': # a blue stimulus using rgb255 space stim.color = 255 # interpreted as (255, 255, 255) # which is white in rgb255. :ref:`Operations <attrib-operations>` work as normal for all numeric colorSpaces (e.g. 'rgb', 'hsv' and 'rgb255') but not for strings, like named and hex. For example, assuming that colorSpace='rgb':: stim.color += [1, 1, 1] # increment all guns by 1 value stim.color *= -1 # multiply the color by -1 (which in this # space inverts the contrast) stim.color *= [0.5, 0, 1] # decrease red, remove green, keep blue You can use `setColor` if you want to set color and colorSpace in one line. These two are equivalent:: stim.setColor((0, 128, 255), 'rgb255') # ... is equivalent to stim.colorSpace = 'rgb255' stim.color = (0, 128, 255) """ if hasattr(self, '_foreColor'): return self._foreColor.render(self.colorSpace) @foreColor.setter def foreColor(self, value): if isinstance(value, Color): # If supplied with a Color object, set as that self._foreColor = value else: # Otherwise, make a new Color object self._foreColor = Color(value, self.colorSpace, contrast=self.contrast) if not self._foreColor: self._foreColor = Color() logging.error(f"'{value}' is not a valid {self.colorSpace} color") # Handle logging logAttrib(self, log=None, attrib="foreColor", value=value) @property def color(self): """Alternative way of setting `foreColor`.""" return self.foreColor @color.setter def color(self, value): self.foreColor = value @property def fontColor(self): """Alternative way of setting `foreColor`.""" return self.foreColor @fontColor.setter def fontColor(self, value): self.foreColor = value def setForeColor(self, color, colorSpace=None, operation='', log=None): """Hard setter for foreColor, allows suppression of the log message, simultaneous colorSpace setting and calls update methods. """ setColor(obj=self, colorAttrib="foreColor", color=color, colorSpace=colorSpace or self.colorSpace, operation=operation, log=log) # Trigger color update for components like Textbox which have different behaviours for a hard setter self.updateColors() def setColor(self, color, colorSpace=None, operation='', log=None): self.setForeColor(color, colorSpace=colorSpace, operation=operation, log=log) def setFontColor(self, color, colorSpace=None, operation='', log=None): self.setForeColor(color, colorSpace=colorSpace, operation=operation, log=log) class FillColorMixin(BaseColorMixin, LegacyFillColorMixin): """ Mixin class for visual stim that need fill color. """ @property def fillColor(self): """Set the fill color for the shape.""" if hasattr(self, '_fillColor'): return getattr(self._fillColor, self.colorSpace) # return self._fillColor.render(self.colorSpace) @fillColor.setter def fillColor(self, value): if isinstance(value, Color): # If supplied with a color object, set as that self._fillColor = value else: # Otherwise, make a new Color object self._fillColor = Color(value, self.colorSpace, contrast=self.contrast) if not self._fillColor: # If given an invalid color, set as transparent and log error self._fillColor = Color() logging.error(f"'{value}' is not a valid {self.colorSpace} color") # Handle logging logAttrib(self, log=None, attrib="fillColor", value=value) @property def backColor(self): """Alternative way of setting fillColor""" return self.fillColor @backColor.setter def backColor(self, value): self.fillColor = value @property def backgroundColor(self): """Alternative way of setting fillColor""" return self.fillColor @backgroundColor.setter def backgroundColor(self, value): self.fillColor = value def setFillColor(self, color, colorSpace=None, operation='', log=None): """Hard setter for fillColor, allows suppression of the log message, simultaneous colorSpace setting and calls update methods. """ setColor(obj=self, colorAttrib="fillColor", color=color, colorSpace=colorSpace or self.colorSpace, operation=operation, log=log) # Trigger color update for components like Textbox which have different behaviours for a hard setter self.updateColors() def setBackColor(self, color, colorSpace=None, operation='', log=None): self.setFillColor(color, colorSpace=colorSpace, operation=operation, log=log) def setBackgroundColor(self, color, colorSpace=None, operation='', log=None): self.setFillColor(color, colorSpace=colorSpace, operation=operation, log=log) class BorderColorMixin(BaseColorMixin, LegacyBorderColorMixin): @property def borderColor(self): if hasattr(self, '_borderColor'): return self._borderColor.render(self.colorSpace) @borderColor.setter def borderColor(self, value): if isinstance(value, Color): # If supplied with a color object, set as that self._borderColor = value else: # If supplied with a valid color, use it to make a color object self._borderColor = Color(value, self.colorSpace, contrast=self.contrast) if not self._borderColor: # If given an invalid color, set as transparent and log error self._borderColor = Color() logging.error(f"'{value}' is not a valid {self.colorSpace} color") # Handle logging logAttrib(self, log=None, attrib="borderColor", value=value) @property def lineColor(self): """Alternative way of setting `borderColor`.""" return self.borderColor @lineColor.setter def lineColor(self, value): self.borderColor = value def setBorderColor(self, color, colorSpace=None, operation='', log=None): """Hard setter for `fillColor`, allows suppression of the log message, simultaneous colorSpace setting and calls update methods. """ setColor(obj=self, colorAttrib="borderColor", color=color, colorSpace=colorSpace or self.colorSpace, operation=operation, log=log) # Trigger color update for components like Textbox which have different behaviours for a hard setter self.updateColors() def setLineColor(self, color, colorSpace=None, operation='', log=None): self.setBorderColor(color, colorSpace=None, operation='', log=None) @attributeSetter def borderWidth(self, value): self.__dict__['borderWidth'] = value return self.__dict__['borderWidth'] def setBorderWidth(self, newWidth, operation='', log=None): setAttribute(self, 'borderWidth', newWidth, log, operation) @attributeSetter def lineWidth(self, value): self.__dict__['borderWidth'] = value return self.__dict__['borderWidth'] def setLineWidth(self, newWidth, operation='', log=None): setAttribute(self, 'lineWidth', newWidth, log, operation) class ColorMixin(ForeColorMixin, FillColorMixin, BorderColorMixin): """ Mixin class for visual stim that need fill, fore and border color. """ class ContainerMixin: """Mixin class for visual stim that have verticesPix attrib and .contains() methods. """ def __init__(self): super(ContainerMixin, self).__init__() self._verticesBase = numpy.array( [[0.5, -0.5], [-0.5, -0.5], [-0.5, 0.5], [0.5, 0.5]]) # sqr self._borderBase = numpy.array( [[0.5, -0.5], [-0.5, -0.5], [-0.5, 0.5], [0.5, 0.5]]) # sqr self._rotationMatrix = [[1., 0.], [0., 1.]] # no rotation by default @property def verticesPix(self): """This determines the coordinates of the vertices for the current stimulus in pixels, accounting for size, ori, pos and units """ # because this is a property getter we can check /on-access/ if it # needs updating :-) if self._needVertexUpdate: self._updateVertices() return self.__dict__['verticesPix'] @property def _borderPix(self): """Allows for a dynamic border that differs from self.vertices, gets updated dynamically with identical transformations. """ if not hasattr(self, 'border'): msg = "%s._borderPix requested without .border" % self.name logging.error(msg) raise AttributeError(msg) if self._needVertexUpdate: self._updateVertices() return self.__dict__['_borderPix'] def _updateVertices(self): """Sets Stim.verticesPix and ._borderPix from pos, size, ori, flipVert, flipHoriz """ # Get vertices from available attribs if hasattr(self, '_tesselVertices'): # Shapes need to render from this verts = self._tesselVertices elif hasattr(self, "_vertices"): # Non-shapes should use base vertices object verts = self._vertices else: # We'll settle for base verts array verts = self.vertices # Convert to a vertices object if not already if not isinstance(verts, Vertices): verts = Vertices(verts, obj=self) # If needed, sub in missing values for flip and anchor if hasattr(self, "flip"): verts.flip = self.flip if hasattr(self, "anchor"): verts.anchor = self.anchor # Supply current object's pos and size objects verts._size = self._size verts._pos = self._pos # Apply rotation verts = (verts.pix - self._pos.pix).dot(self._rotationMatrix) + self._pos.pix if hasattr(self, "_vertices"): borderVerts = (self._vertices.pix - self._pos.pix).dot(self._rotationMatrix) + self._pos.pix else: borderVerts = verts # Set values self.__dict__['verticesPix'] = verts self.__dict__['_borderPix'] = borderVerts # Mark as updated self._needVertexUpdate = False self._needUpdate = True # but we presumably need to update the list def contains(self, x, y=None, units=None): """Returns True if a point x,y is inside the stimulus' border. Can accept variety of input options: + two separate args, x and y + one arg (list, tuple or array) containing two vals (x,y) + an object with a getPos() method that returns x,y, such as a :class:`~psychopy.event.Mouse`. Returns `True` if the point is within the area defined either by its `border` attribute (if one defined), or its `vertices` attribute if there is no .border. This method handles complex shapes, including concavities and self-crossings. Note that, if your stimulus uses a mask (such as a Gaussian) then this is not accounted for by the `contains` method; the extent of the stimulus is determined purely by the size, position (pos), and orientation (ori) settings (and by the vertices for shape stimuli). See Coder demos: shapeContains.py See Coder demos: shapeContains.py """ # get the object in pixels if hasattr(x, 'border'): xy = x._borderPix # access only once - this is a property units = 'pix' # we can forget about the units elif hasattr(x, 'verticesPix'): # access only once - this is a property (slower to access) xy = x.verticesPix units = 'pix' # we can forget about the units elif hasattr(x, 'getPos'): xy = x.getPos() units = x.units elif type(x) in [list, tuple, numpy.ndarray]: xy = numpy.array(x) else: xy = numpy.array((x, y)) # try to work out what units x,y has if units is None: if hasattr(xy, 'units'): units = xy.units else: units = self.units if units != 'pix': xy = convertToPix(xy, pos=(0, 0), units=units, win=self.win) # ourself in pixels if hasattr(self, 'border'): poly = self._borderPix # e.g., outline vertices elif hasattr(self, 'boundingBox'): if abs(self.ori) > 0.1: raise RuntimeError("TextStim.contains() doesn't currently " "support rotated text.") w, h = self.boundingBox # e.g., outline vertices x, y = self.posPix poly = numpy.array([[x+w/2, y-h/2], [x-w/2, y-h/2], [x-w/2, y+h/2], [x+w/2, y+h/2]]) else: poly = self.verticesPix # e.g., tessellated vertices return pointInPolygon(xy[0], xy[1], poly=poly) def overlaps(self, polygon): """Returns `True` if this stimulus intersects another one. If `polygon` is another stimulus instance, then the vertices and location of that stimulus will be used as the polygon. Overlap detection is typically very good, but it can fail with very pointy shapes in a crossed-swords configuration. Note that, if your stimulus uses a mask (such as a Gaussian blob) then this is not accounted for by the `overlaps` method; the extent of the stimulus is determined purely by the size, pos, and orientation settings (and by the vertices for shape stimuli). See coder demo, shapeContains.py """ return polygonsOverlap(self, polygon) class TextureMixin: """Mixin class for visual stim that have textures. Could move visual.helpers.setTexIfNoShaders() into here. """ def _createTexture(self, tex, id, pixFormat, stim, res=128, maskParams=None, forcePOW2=True, dataType=None, wrapping=True): """Create a new OpenGL 2D image texture. Parameters ---------- tex : Any Texture data. Value can be anything that resembles image data. id : int or :class:`~pyglet.gl.GLint` Texture ID. pixFormat : :class:`~pyglet.gl.GLenum` or int Pixel format to use, values can be `GL_ALPHA` or `GL_RGB`. stim : Any Stimulus object using the texture. res : int The resolution of the texture (unless a bitmap image is used). maskParams : dict or None Additional parameters to configure the mask used with this texture. forcePOW2 : bool Force the texture to be stored in a square memory area. For grating stimuli (anything that needs multiple cycles) `forcePOW2` should be set to be `True`. Otherwise the wrapping of the texture will not work. dataType : class:`~pyglet.gl.GLenum`, int or None None, `GL_UNSIGNED_BYTE`, `GL_FLOAT`. Only affects image files (numpy arrays will be float). wrapping : bool Enable wrapping of the texture. A texture will be set to repeat (or tile). """ # transform all variants of `None` to that, simplifies conditions below if isinstance(tex, str) and tex in ["none", "None", "color"]: tex = None # Create an intensity texture, ranging -1:1.0 notSqr = False # most of the options will be creating a sqr texture wasImage = False # change this if image loading works interpolate = stim.interpolate if dataType is None: if pixFormat == GL.GL_RGB: dataType = GL.GL_FLOAT else: dataType = GL.GL_UNSIGNED_BYTE # Fill out unspecified portions of maskParams with default values if maskParams is None: maskParams = {} # fringeWidth affects the proportion of the stimulus diameter that is # devoted to the raised cosine. allMaskParams = {'fringeWidth': 0.2, 'sd': 3} allMaskParams.update(maskParams) if type(tex) == numpy.ndarray: # handle a numpy array # for now this needs to be an NxN intensity array intensity = tex.astype(numpy.float32) if intensity.max() > 1 or intensity.min() < -1: logging.error('numpy arrays used as textures should be in ' 'the range -1(black):1(white)') if len(tex.shape) == 3: wasLum = False else: wasLum = True # is it 1D? if tex.shape[0] == 1: stim._tex1D = True res = tex.shape[1] elif len(tex.shape) == 1 or tex.shape[1] == 1: stim._tex1D = True res = tex.shape[0] else: stim._tex1D = False # check if it's a square power of two maxDim = max(tex.shape) powerOf2 = 2 ** numpy.ceil(numpy.log2(maxDim)) if (forcePOW2 and (tex.shape[0] != powerOf2 or tex.shape[1] != powerOf2)): logging.error("Requiring a square power of two (e.g. " "16 x 16, 256 x 256) texture but didn't " "receive one") res = tex.shape[0] dataType = GL.GL_FLOAT elif tex in ("sin", "sqr", "saw", "tri", "sinXsin", "sqrXsqr", "circle", "gauss", "cross", "radRamp", "raisedCos", None): if tex is None: res = 1 wrapping = True # override any wrapping setting for None # compute array of intensity value for desired pattern intensity = createLumPattern(tex, res, None, allMaskParams) wasLum = True else: if isinstance(tex, (str, Path)): # maybe tex is the name of a file: filename = findImageFile(tex, checkResources=True) if not filename: msg = "Couldn't find image %s; check path? (tried: %s)" logging.error(msg % (tex, os.path.abspath(tex))) logging.flush() raise IOError(msg % (tex, os.path.abspath(tex))) try: im = Image.open(filename) im = im.transpose(Image.FLIP_TOP_BOTTOM) except IOError: msg = "Found file '%s', failed to load as an image" logging.error(msg % (filename)) logging.flush() msg = "Found file '%s' [= %s], failed to load as an image" raise IOError(msg % (tex, os.path.abspath(tex))) elif hasattr(tex, 'getVideoFrame'): # camera or movie textures # get an image to configure the initial texture store if hasattr(tex, 'frameSize'): if tex.frameSize is None: raise RuntimeError( "`Camera.frameSize` is not yet specified, cannot " "initialize texture!") self._origSize = frameSize = tex.frameSize # empty texture for initialization blankTexture = numpy.zeros( (frameSize[0] * frameSize[1] * 3), dtype=numpy.uint8) im = Image.frombuffer( 'RGB', frameSize, blankTexture ).transpose(Image.FLIP_TOP_BOTTOM) else: msg = "Failed to initialize texture from camera stream." logging.error(msg) logging.flush() raise AttributeError(msg) else: # can't be a file; maybe its an image already in memory? try: im = tex.copy().transpose(Image.FLIP_TOP_BOTTOM) except AttributeError: # nope, not an image in memory msg = "Couldn't make sense of requested image." logging.error(msg) logging.flush() raise AttributeError(msg) # at this point we have a valid im stim._origSize = im.size wasImage = True # is it 1D? if im.size[0] == 1 or im.size[1] == 1: logging.error("Only 2D textures are supported at the moment") else: maxDim = max(im.size) powerOf2 = int(2**numpy.ceil(numpy.log2(maxDim))) if im.size[0] != powerOf2 or im.size[1] != powerOf2: if not forcePOW2: notSqr = True elif globalVars.nImageResizes < reportNImageResizes: msg = ("Image '%s' was not a square power-of-two ' " "'image. Linearly interpolating to be %ix%i") logging.warning(msg % (tex, powerOf2, powerOf2)) globalVars.nImageResizes += 1 im = im.resize([powerOf2, powerOf2], Image.BILINEAR) elif globalVars.nImageResizes == reportNImageResizes: logging.warning("Multiple images have needed resizing" " - I'll stop bothering you!") im = im.resize([powerOf2, powerOf2], Image.BILINEAR) # is it Luminance or RGB? if pixFormat == GL.GL_ALPHA and im.mode != 'L': # we have RGB and need Lum wasLum = True im = im.convert("L") # force to intensity (need if was rgb) elif im.mode == 'L': # we have lum and no need to change wasLum = True dataType = GL.GL_FLOAT elif pixFormat == GL.GL_RGB: # we want RGB and might need to convert from CMYK or Lm # texture = im.tostring("raw", "RGB", 0, -1) im = im.convert("RGBA") wasLum = False else: raise ValueError('cannot determine if image is luminance or RGB') if dataType == GL.GL_FLOAT: # convert from ubyte to float # much faster to avoid division 2/255 intensity = numpy.array(im).astype( numpy.float32) * 0.0078431372549019607 - 1.0 else: intensity = numpy.array(im) if pixFormat == GL.GL_RGB and wasLum and dataType == GL.GL_FLOAT: # grating stim on good machine # keep as float32 -1:1 if (sys.platform != 'darwin' and stim.win.glVendor.startswith('nvidia')): # nvidia under win/linux might not support 32bit float # could use GL_LUMINANCE32F_ARB here but check shader code? internalFormat = GL.GL_RGB16F_ARB else: # we've got a mac or an ATI card and can handle # 32bit float textures # could use GL_LUMINANCE32F_ARB here but check shader code? internalFormat = GL.GL_RGB32F_ARB # initialise data array as a float data = numpy.ones((intensity.shape[0], intensity.shape[1], 3), numpy.float32) data[:, :, 0] = intensity # R data[:, :, 1] = intensity # G data[:, :, 2] = intensity # B elif (pixFormat == GL.GL_RGB and wasLum and dataType != GL.GL_FLOAT): # was a lum image: stick with ubyte for speed internalFormat = GL.GL_RGB # initialise data array as a float data = numpy.ones((intensity.shape[0], intensity.shape[1], 3), numpy.ubyte) data[:, :, 0] = intensity # R data[:, :, 1] = intensity # G data[:, :, 2] = intensity # B elif pixFormat == GL.GL_RGB and dataType == GL.GL_FLOAT: # probably a custom rgb array or rgb image internalFormat = GL.GL_RGB32F_ARB data = intensity elif pixFormat == GL.GL_RGB: # not wasLum, not useShaders - an RGB bitmap with no shader # optionsintensity.min() internalFormat = GL.GL_RGB data = intensity # float_uint8(intensity) elif pixFormat == GL.GL_ALPHA: internalFormat = GL.GL_ALPHA dataType = GL.GL_UNSIGNED_BYTE if wasImage: data = intensity else: data = float_uint8(intensity) else: raise ValueError("invalid or unsupported `pixFormat`") # check for RGBA textures if len(data.shape) > 2 and data.shape[2] == 4: if pixFormat == GL.GL_RGB: pixFormat = GL.GL_RGBA if internalFormat == GL.GL_RGB: internalFormat = GL.GL_RGBA elif internalFormat == GL.GL_RGB32F_ARB: internalFormat = GL.GL_RGBA32F_ARB texture = data.ctypes # serialise # Create the pixel buffer object which will serve as the texture memory # store. First we compute the number of bytes used to store the texture. # We need to determine the data type in use by the texture to do this. if stim is not None and hasattr(stim, '_pixbuffID'): if dataType == GL.GL_UNSIGNED_BYTE: storageType = GL.GLubyte elif dataType == GL.GL_FLOAT: storageType = GL.GLfloat else: # raise waring or error? just default to `GLfloat` for now storageType = GL.GLfloat # compute buffer size bufferSize = data.size * ctypes.sizeof(storageType) # create the pixel buffer to access texture memory as an array GL.glBindBuffer(GL.GL_PIXEL_UNPACK_BUFFER, stim._pixbuffID) GL.glBufferData( GL.GL_PIXEL_UNPACK_BUFFER, bufferSize, None, GL.GL_STREAM_DRAW) # one-way app -> GL GL.glBindBuffer(GL.GL_PIXEL_UNPACK_BUFFER, 0) # bind the texture in openGL GL.glEnable(GL.GL_TEXTURE_2D) GL.glBindTexture(GL.GL_TEXTURE_2D, id) # bind that name to the target # makes the texture map wrap (this is actually default anyway) if wrapping: GL.glTexParameteri( GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, GL.GL_REPEAT) GL.glTexParameteri( GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_REPEAT) else: GL.glTexParameteri( GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, GL.GL_CLAMP) GL.glTexParameteri( GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_CLAMP) # data from PIL/numpy is packed, but default for GL is 4 bytes GL.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, 1) # important if using bits++ because GL_LINEAR # sometimes extrapolates to pixel vals outside range if interpolate: GL.glTexParameteri( GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR) # GL_GENERATE_MIPMAP was only available from OpenGL 1.4 GL.glTexParameteri( GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR) GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_GENERATE_MIPMAP, GL.GL_TRUE) GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, internalFormat, data.shape[1], data.shape[0], 0, pixFormat, dataType, texture) else: GL.glTexParameteri( GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST) GL.glTexParameteri( GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST) GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, internalFormat, data.shape[1], data.shape[0], 0, pixFormat, dataType, texture) GL.glTexEnvi(GL.GL_TEXTURE_ENV, GL.GL_TEXTURE_ENV_MODE, GL.GL_MODULATE) # ?? do we need this - think not! # unbind our texture so that it doesn't affect other rendering GL.glBindTexture(GL.GL_TEXTURE_2D, 0) return wasLum def clearTextures(self): """Clear all textures associated with the stimulus. As of v1.61.00 this is called automatically during garbage collection of your stimulus, so doesn't need calling explicitly by the user. """ if hasattr(self, '_texID'): GL.glDeleteTextures(1, self._texID) if hasattr(self, '_maskID'): GL.glDeleteTextures(1, self._maskID) if hasattr(self, '_pixBuffID'): GL.glDeleteBuffers(1, self._pixBuffID) @attributeSetter def mask(self, value): """The alpha mask (forming the shape of the image). This can be one of various options: * 'circle', 'gauss', 'raisedCos', 'cross' * **None** (resets to default) * the name of an image file (most formats supported) * a numpy array (1xN or NxN) ranging -1:1 """ self.__dict__['mask'] = value if self.__class__.__name__ == 'ImageStim': dataType = GL.GL_UNSIGNED_BYTE else: dataType = None self._createTexture( value, id=self._maskID, pixFormat=GL.GL_ALPHA, dataType=dataType, stim=self, res=self.texRes, maskParams=self.maskParams, wrapping=False) def setMask(self, value, log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message. """ setAttribute(self, 'mask', value, log) @attributeSetter def texRes(self, value): """Power-of-two int. Sets the resolution of the mask and texture. texRes is overridden if an array or image is provided as mask. :ref:`Operations <attrib-operations>` supported. """ self.__dict__['texRes'] = value # ... now rebuild textures (call attributeSetters without logging). if hasattr(self, 'tex'): setAttribute(self, 'tex', self.tex, log=False) if hasattr(self, 'mask'): setAttribute(self, 'mask', self.mask, log=False) @attributeSetter def maskParams(self, value): """Various types of input. Default to `None`. This is used to pass additional parameters to the mask if those are needed. - For 'gauss' mask, pass dict {'sd': 5} to control standard deviation. - For the 'raisedCos' mask, pass a dict: {'fringeWidth':0.2}, where 'fringeWidth' is a parameter (float, 0-1), determining the proportion of the patch that will be blurred by the raised cosine edge.""" self.__dict__['maskParams'] = value # call attributeSetter without log setAttribute(self, 'mask', self.mask, log=False) @attributeSetter def interpolate(self, value): """Whether to interpolate (linearly) the texture in the stimulus. If set to False then nearest neighbour will be used when needed, otherwise some form of interpolation will be used. """ self.__dict__['interpolate'] = value class WindowMixin: """Window-related attributes and methods. Used by BaseVisualStim, SimpleImageStim and ElementArrayStim. """ @property def win(self): """The :class:`~psychopy.visual.Window` object in which the stimulus will be rendered by default. (required) Example, drawing same stimulus in two different windows and display simultaneously. Assuming that you have two windows and a stimulus (win1, win2 and stim):: stim.win = win1 # stimulus will be drawn in win1 stim.draw() # stimulus is now drawn to win1 stim.win = win2 # stimulus will be drawn in win2 stim.draw() # it is now drawn in win2 win1.flip(waitBlanking=False) # do not wait for next # monitor update win2.flip() # wait for vertical blanking. Note that this just changes **default** window for stimulus. You could also specify window-to-draw-to when drawing:: stim.draw(win1) stim.draw(win2) """ return self.__dict__['win'] @win.setter def win(self, value): self.__dict__['win'] = value # Update window ref in size and pos objects if hasattr(self, "_size") and isinstance(self._size, Vector): self._size.win = value if hasattr(self, "_pos") and isinstance(self._pos, Vector): self._pos.win = value @property def pos(self): if hasattr(self, "_pos"): return getattr(self._pos, self.units) @pos.setter def pos(self, value): # If no autolog attribute, assume silent if hasattr(self, "autoLog"): log = self.autoLog else: log = False # Do attribute setting setAttribute(self, '_pos', Position(value, units=self.units, win=self.win), log) if hasattr(self, "_vertices"): self._vertices._pos = self._pos if hasattr(self, "_vertices"): self._vertices._pos = self._pos @property def size(self): if hasattr(self, "_size"): return getattr(self._size, self.units) @size.setter def size(self, value): # Convert None to a 2x1 tuple if value is None: value = (None, None) # If no autolog attribute, assume silent if hasattr(self, "autoLog"): log = self.autoLog else: log = False # Do attribute setting setAttribute(self, '_size', Size(value, units=self.units, win=self.win), log) if hasattr(self, "_vertices"): self._vertices._size = self._size if hasattr(self, "_vertices"): self._vertices._size = self._size @property def width(self): if len(self.size.shape) == 1: # Return first value if a 1d array return self.size[0] elif len(self.size.shape) == 2: # Return first column if a 2d array return self.size[:, 0] @width.setter def width(self, value): # Convert to a numpy array value = numpy.array(value) # Get original size size = self.size # Set size if len(self.size.shape) == 1: # Set first value if a 1d array size[0] = value elif len(self.size.shape) == 2: # Set first column if a 2d array size[:, 0] = value else: raise NotImplementedError( f"Cannot set height and width for {type(self).__name__} objects with more than 2 dimensions. " f"Please use .size instead." ) self.size = size @property def height(self): if len(self.size.shape) == 1: # Return first value if a 1d array return self.size[1] elif len(self.size.shape) == 2: # Return first column if a 2d array return self.size[:, 1] @height.setter def height(self, value): # Convert to a numpy array value = numpy.array(value) # Get original size size = self.size # Set size if len(self.size.shape) == 1: # Set second value if a 1d array size[1] = value elif len(self.size.shape) == 2: # Set second column if a 2d array size[:, 1] = value else: raise NotImplementedError( f"Cannot set height and width for {type(self).__name__} objects with more than 2 dimensions. " f"Please use .size instead." ) self.size = size @property def vertices(self): # Get or make Vertices object if hasattr(self, "_vertices"): verts = self._vertices else: # If not defined, assume vertices are just a square verts = self._vertices = Vertices(numpy.array([ [0.5, -0.5], [-0.5, -0.5], [-0.5, 0.5], [0.5, 0.5], ]), obj=self, flip=self.flip, anchor=self.anchor) return verts.base @vertices.setter def vertices(self, value): # If None, use defaut if value is None: value = [ [0.5, -0.5], [-0.5, -0.5], [-0.5, 0.5], [0.5, 0.5], ] # Create Vertices object self._vertices = Vertices(value, obj=self, flip=self.flip, anchor=self.anchor) self._needVertexUpdate = True @property def flip(self): """ 1x2 array for flipping vertices along each axis; set as True to flip or False to not flip. If set as a single value, will duplicate across both axes. Accessing the protected attribute (`._flip`) will give an array of 1s and -1s with which to multiply vertices. """ # Get base value if hasattr(self, "_flip"): flip = self._flip else: flip = numpy.array([[False, False]]) # Convert from boolean return flip == -1 @flip.setter def flip(self, value): if value is None: value = False # Convert to 1x2 numpy array value = numpy.array(value) value.resize((1, 2)) # Ensure values were bool assert value.dtype == bool, "Flip values must be either a boolean (True/False) or an array of booleans" # Set as multipliers rather than bool self._flip = numpy.array([[ -1 if value[0, 0] else 1, -1 if value[0, 1] else 1, ]]) self._flipHoriz, self._flipVert = self._flip[0] # Apply to vertices if not hasattr(self, "_vertices"): self.vertices = None self._vertices.flip = self.flip # Mark as needing vertex update self._needVertexUpdate = True @property def flipHoriz(self): return self.flip[0][0] @flipHoriz.setter def flipHoriz(self, value): self.flip = [value, self.flip[0, 1]] @property def flipVert(self): return self.flip[0][1] @flipVert.setter def flipVert(self, value): self.flip = [self.flip[0, 0], value] @property def anchor(self): if hasattr(self, "_vertices"): return self._vertices.anchor elif hasattr(self, "_anchor"): # Return a backup value if there's no vertices yet return self._anchor @anchor.setter def anchor(self, value): if hasattr(self, "_vertices"): self._vertices.anchor = value else: # Set a backup value if there's no vertices yet self._anchor = value def setAnchor(self, value, log=None): setAttribute(self, 'anchor', value, log) @property def units(self): if hasattr(self, "_units"): return self._units else: return self.win.units @units.setter def units(self, value): """ Units to use when drawing. Possible options are: None, 'norm', 'cm', 'deg', 'degFlat', 'degFlatPos', or 'pix'. If None then the current units of the :class:`~psychopy.visual.Window` will be used. See :ref:`units` for explanation of other options. Note that when you change units, you don't change the stimulus parameters and it is likely to change appearance. Example:: # This stimulus is 20% wide and 50% tall with respect to window stim = visual.PatchStim(win, units='norm', size=(0.2, 0.5) # This stimulus is 0.2 degrees wide and 0.5 degrees tall. stim.units = 'deg' """ if value in unitTypes: self._units = value or self.win.units self._needVertexUpdate = True else: raise ValueError(f"Invalid unit type '{value}', must be one of: {unitTypes}") def draw(self): raise NotImplementedError('Stimulus classes must override ' 'visual.BaseVisualStim.draw') def _selectWindow(self, win): """Switch drawing to the specified window. Calls the window's _setCurrent() method which handles the switch. """ win._setCurrent() def _updateList(self): """The user shouldn't need this method since it gets called after every call to .set() Chooses between using and not using shaders each call. """ self._updateListShaders() class DraggingMixin: """ Mixin to give an object innate dragging behaviour. Attributes ========== draggable : bool Can this object be dragged by a Mouse click? isDragging : bool Is this object currently being dragged? (read only) Methods ========== doDragging : Call this each frame to make sure dragging behaviour happens. If `autoDraw` and `draggable` are both True, then this will be called automatically by the Window object on flip. """ isDragging = False def doDragging(self): """ If this stimulus is draggable, do the necessary actions on a frame flip to drag it. """ # if not draggable, do nothing if not self.draggable: return # if something else is already dragging, do nothing if self.win.currentDraggable is not None and self.win.currentDraggable != self: return # if just clicked on, start dragging self.isDragging = self.isDragging or self.mouse.isPressedIn(self, buttons=[0]) # if click is released, stop dragging self.isDragging = self.isDragging and self.mouse.getPressed()[0] # get relative mouse pos rel = self.mouse.getRel() # if dragging, do necessary updates if self.isDragging: # set as current draggable self.win.currentDraggable = self # get own pos in win units pos = getattr(self._pos, self.win.units) # add mouse movement to pos setattr( self._pos, self.win.units, pos + rel ) # set pos self.pos = getattr(self._pos, self.units) else: # remove as current draggable self.win.currentDraggable = None @attributeSetter def draggable(self, value): """ Can this stimulus be dragged by a mouse click? """ # if we don't have reference to a mouse, make one if not isinstance(self.mouse, Mouse): self.mouse = Mouse(visible=self.win.mouseVisible, win=self.win) # make sure it has an initial pos for rel pos comparisons self.mouse.lastPos = self.mouse.getPos() # store value self.__dict__['draggable'] = value class BaseVisualStim(MinimalStim, WindowMixin, LegacyVisualMixin): """A template for a visual stimulus class. Actual visual stim like GratingStim, TextStim etc... are based on this. Not finished...? Methods defined here will override Minimal & Legacy, but best to avoid that for simplicity & clarity. """ def __init__(self, win, units=None, name='', autoLog=None): self.autoLog = False # just to start off during init, set at end self.win = win self.units = units self._rotationMatrix = [[1., 0.], [0., 1.]] # no rotation by default self.mouse = None # self.autoLog is set at end of MinimalStim.__init__ super(BaseVisualStim, self).__init__(name=name, autoLog=autoLog) if self.autoLog: msg = ("%s is calling BaseVisualStim.__init__() with autolog=True" ". Set autoLog to True only at the end of __init__())") logging.warning(msg % (self.__class__.__name__)) @property def opacity(self): """Determines how visible the stimulus is relative to background. The value should be a single float ranging 1.0 (opaque) to 0.0 (transparent). :ref:`Operations <attrib-operations>` are supported. Precisely how this is used depends on the :ref:`blendMode`. """ if not hasattr(self, "_opacity"): return 1 return self._opacity @opacity.setter def opacity(self, value): # Setting opacity as a single value makes all colours the same opacity if value is None: # If opacity is set to be None, this indicates that each color should handle its own opacity return self._opacity = value if hasattr(self, '_foreColor'): if self._foreColor != None: self._foreColor.alpha = value if hasattr(self, '_fillColor'): if self._fillColor != None: self._fillColor.alpha = value if hasattr(self, '_borderColor'): if self._borderColor != None: self._borderColor.alpha = value def updateOpacity(self): """Placeholder method to update colours when set externally, for example updating the `pallette` attribute of a textbox.""" return @attributeSetter def ori(self, value): """The orientation of the stimulus (in degrees). Should be a single value (:ref:`scalar <attrib-scalar>`). :ref:`Operations <attrib-operations>` are supported. Orientation convention is like a clock: 0 is vertical, and positive values rotate clockwise. Beyond 360 and below zero values wrap appropriately. """ self.__dict__['ori'] = float(value) radians = value * 0.017453292519943295 sin, cos = numpy.sin, numpy.cos self._rotationMatrix = numpy.array([[cos(radians), -sin(radians)], [sin(radians), cos(radians)]]) self._needVertexUpdate = True # need to update update vertices self._needUpdate = True @property def size(self): """The size (width, height) of the stimulus in the stimulus :ref:`units <units>` Value should be :ref:`x,y-pair <attrib-xy>`, :ref:`scalar <attrib-scalar>` (applies to both dimensions) or None (resets to default). :ref:`Operations <attrib-operations>` are supported. Sizes can be negative (causing a mirror-image reversal) and can extend beyond the window. Example:: stim.size = 0.8 # Set size to (xsize, ysize) = (0.8, 0.8) print(stim.size) # Outputs array([0.8, 0.8]) stim.size += (0.5, -0.5) # make wider and flatter: (1.3, 0.3) Tip: if you can see the actual pixel range this corresponds to by looking at `stim._sizeRendered` """ return WindowMixin.size.fget(self) @size.setter def size(self, value): # Supply default for None if value is None: value = Size((1, 1), units="height", win=self.win) # Duplicate single values if isinstance(value, (float, int)): value = (value, value) # Do setting WindowMixin.size.fset(self, value) # Mark any updates needed self._needVertexUpdate = True self._needUpdate = True if hasattr(self, '_calcCyclesPerStim'): self._calcCyclesPerStim() @property def pos(self): """ The position of the center of the stimulus in the stimulus :ref:`units <units>` `value` should be an :ref:`x,y-pair <attrib-xy>`. :ref:`Operations <attrib-operations>` are also supported. Example:: stim.pos = (0.5, 0) # Set slightly to the right of center stim.pos += (0.5, -1) # Increment pos rightwards and upwards. Is now (1.0, -1.0) stim.pos *= 0.2 # Move stim towards the center. Is now (0.2, -0.2) Tip: If you need the position of stim in pixels, you can obtain it like this:: from psychopy.tools.monitorunittools import posToPix posPix = posToPix(stim) """ return WindowMixin.pos.fget(self) @pos.setter def pos(self, value): # Supply defualt for None if value is None: value = Position((0, 0), units="height", win=self.win) # Do setting WindowMixin.pos.fset(self, value) # Mark any updates needed self._needVertexUpdate = True self._needUpdate = True def setPos(self, newPos, operation='', log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message. """ setAttribute(self, 'pos', val2array(newPos, False), log, operation) def setDepth(self, newDepth, operation='', log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message """ setAttribute(self, 'depth', newDepth, log, operation) def setSize(self, newSize, operation='', units=None, log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message """ if units is None: # need to change this to create several units from one units = self.units # If we have an original size (e.g. for an image or movie), then we CAN set size with None useNone = hasattr(self, "origSize") # Set attribute setAttribute(self, 'size', val2array(newSize, useNone), log, operation) def setOri(self, newOri, operation='', log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message """ setAttribute(self, 'ori', newOri, log, operation) def setOpacity(self, newOpacity, operation='', log=None): """Hard setter for opacity, allows the suppression of log messages and calls the update method """ if operation in ['', '=']: self.opacity = newOpacity elif operation in ['+']: self.opacity += newOpacity elif operation in ['-']: self.opacity -= newOpacity else: logging.error(f"Operation '{operation}' not recognised.") # Trigger color update for components like Textbox which have different behaviours for a hard setter self.updateOpacity() def _set(self, attrib, val, op='', log=None): """DEPRECATED since 1.80.04 + 1. Use setAttribute() and val2array() instead. """ # format the input value as float vectors if type(val) in [tuple, list, numpy.ndarray]: val = val2array(val, length=len(val)) # Set attribute with operation and log setAttribute(self, attrib, val, log, op) # For DotStim if attrib in ('nDots', 'coherence'): self.coherence = round(self.coherence * self.nDots) / self.nDots
74,709
Python
.py
1,665
34.272072
268
0.597842
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,728
dropdown.py
psychopy_psychopy/psychopy/visual/dropdown.py
from psychopy.visual.shape import ShapeStim from psychopy.visual.slider import Slider from psychopy.visual.button import ButtonStim class DropDownCtrl(ButtonStim): """ Class to create a "Drop Down" control, similar to a HTML <select> tag. Consists of a psychopy.visual.ButtonStim which, when clicked on, shows a psychopy.visual.Slider with style "choice", which closes again when a value is selected. This is a lazy-imported class, therefore import using full path `from psychopy.visual.dropdown import DropDownCtrl` when inheriting from it. win : psychopy.visual.Window Window to draw the control to startValue : str Which of the available values should be the starting value? Use `""` for no selection font : str Name of the font to display options in pos : tuple, list, np.ndarray, psychopy.layout.Position Position of the stimulus on screen size : tuple, list, np.ndarray, psychopy.layout.Position Size of the persistent control, size of the menu will be calculated according to this size and the number of options. anchor : str Which point on the stimulus should be at the point specified by pos? units : str, None Spatial units in which to interpret this stimulus' size and position, use None to use the window's units color : Color Color of the text in the control markerColor : Color Color of the highlight on the selected element in the drop down menu lineColor : Color Background color of both the persistent control and drop-down menu. Called "lineColor" for consistency with Slider, as the background is technically just a thick line on a Slider. colorSpace : str Color space in which to interpret stimulus colors padding : int, float, tuple Padding between edge and text on both the persistent control and each item in the drop down menu. choices : tuple, list, np.ndarray Options to choose from in the drop down menu labelHeight : int, float Height of text within both the persistent control and each item in the drop down menu name : str Name of this stimulus autoLog : bool Whether or not to log changes to this stimulus automatically """ def __init__(self, win, startValue="", font='Arvo', pos=(0, 0), size=(0.4, 0.2), anchor='center', units=None, color='black', markerColor='lightblue', lineColor='white', colorSpace='rgb', padding=None, choices=("one", "two", "three"), labelHeight=0.04, name="", autoLog=None): # Need to flip labels and add blank choices = [""] + list(choices) choices.reverse() self.choices = choices # Textbox to display current value ButtonStim.__init__( self, win, text=startValue, font=font, bold=False, name=name, letterHeight=labelHeight, padding=padding, pos=pos, size=size, anchor=anchor, units=units, color=color, fillColor=lineColor, borderColor=None, borderWidth=1, colorSpace=colorSpace, autoLog=autoLog ) # Dropdown icon self.icon = ShapeStim(win, size=labelHeight / 2, anchor="center right", vertices="triangle", fillColor=color) self.icon.flipVert = True # Menu object to show when clicked on self.menu = Slider( win, startValue=choices.index(startValue), labels=choices, ticks=list(range(len(choices))), labelColor=color, markerColor=markerColor, lineColor=lineColor, colorSpace=colorSpace, style="choice", granularity=1, font=font, labelHeight=labelHeight, labelWrapWidth=self.size[0] ) self.menu.active = False # Set size and pos self.size = size self.pos = pos @property def size(self): return ButtonStim.size.fget(self) @size.setter def size(self, value): ButtonStim.size.fset(self, value) if hasattr(self, "menu"): self.menu.size = self._size * (1, len(self.choices)) @property def pos(self): return ButtonStim.pos.fget(self) @pos.setter def pos(self, value): ButtonStim.pos.fset(self, value) # Set icon pos if hasattr(self, "icon"): self.icon.pos = (self.contentBox.pos[0] + self.contentBox.size[0] / 2, self.contentBox.pos[1]) # Set menu pos if hasattr(self, "menu"): pos = self.pos - (self.size * self._vertices.anchorAdjust) pos[1] -= self.menu.size[1] / 2 + self.size[1] self.menu.pos = pos def showMenu(self, value=True): # Show menu self.menu.active = value # Clear rating self.menu.rating = None # Set marker pos self.menu.markerPos = self.choices.index(self.text) # Rotate icon self.icon.flipVert = not value def hideMenu(self): self.showMenu(False) @property def value(self): return self.text @value.setter def value(self, value): if value is None: value = "" self.menu.rating = self.choices.index(value) def draw(self): # Check mouse clicks if self.isClicked: if not self.wasClicked and not self.menu.active: # If new click and menu inactive, show menu self.showMenu() elif not self.wasClicked: # If new click and menu active, hide menu self.hideMenu() # Mark as was clicked self.wasClicked = True else: # Mark as not clicked self.wasClicked = False # If menu is active, draw it if self.menu.active: self.menu.draw() # Update current value if self.menu.rating is not None: self.text = self.choices[self.menu.rating] self.hideMenu() # Draw self ButtonStim.draw(self) # Draw icon self.icon.draw()
6,283
Python
.py
150
32.1
116
0.61883
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,729
target.py
psychopy_psychopy/psychopy/visual/target.py
from .shape import ShapeStim from .basevisual import ColorMixin, WindowMixin, MinimalStim from psychopy.colors import Color from .. import layout knownStyles = ["circles", "cross", ] class TargetStim(MinimalStim, ColorMixin, WindowMixin): """ A target for use in eyetracker calibration, if converted to a dict will return in the correct format for ioHub """ def __init__(self, win, name=None, style="circles", radius=.05, fillColor=(1, 1, 1, 0.1), borderColor="white", lineWidth=2, innerRadius=.01, innerFillColor="red", innerBorderColor=None, innerLineWidth=None, pos=(0, 0), units=None, anchor="center", colorSpace="rgb", autoLog=None, autoDraw=False): self.win = win # Make sure name is a string if name is None: name = "target" # Create shapes self.outer = ShapeStim(win, name=name, vertices="circle", size=(radius*2, radius*2), pos=pos, lineWidth=lineWidth, units=units, fillColor=fillColor, lineColor=borderColor, colorSpace=colorSpace, autoLog=autoLog, autoDraw=autoDraw) self.outerRadius = radius self.inner = ShapeStim(win, name=name+"Inner", vertices="circle", size=(innerRadius*2, innerRadius*2), pos=pos, units=units, lineWidth=(innerLineWidth or lineWidth), fillColor=innerFillColor, lineColor=innerBorderColor, colorSpace=colorSpace, autoLog=autoLog, autoDraw=autoDraw) self.innerRadius = innerRadius self.style = style self.anchor = anchor @property def style(self): if hasattr(self, "_style"): return self._style @style.setter def style(self, value): self._style = value if value == "circles": # Two circles self.outer.vertices = self.inner.vertices = "circle" elif value == "cross": # Circle with a cross inside self.outer.vertices = "circle" self.inner.vertices = "cross" @property def anchor(self): return self.outer.anchor @anchor.setter def anchor(self, value): self.outer.anchor = value self.inner.pos = self.pos + self.size * self.outer._vertices.anchorAdjust @property def pos(self): """For target stims, pos is overloaded so that it moves both the inner and outer shapes.""" return self.outer.pos @pos.setter def pos(self, value): # Do base pos setting WindowMixin.size.fset(self, value) self.outer.pos = value self.inner.pos = value def setPos(self, value): self.pos = value @property def size(self): return self.outer.size @size.setter def size(self, value): # Do base size setting WindowMixin.size.fset(self, value) # Set new sizes self.outer.size = value @property def minSize(self): return self.inner.size @property def units(self): if hasattr(self, "outer"): return self.outer.units @units.setter def units(self, value): if hasattr(self, "outer"): self.outer.units = value if hasattr(self, "inner"): self.inner.units = value @property def win(self): return WindowMixin.win.fget(self) @win.setter def win(self, value): WindowMixin.win.fset(self, value) if hasattr(self, "inner"): self.inner.win = value if hasattr(self, "outer"): self.outer.win = value @property def lineWidth(self): return self.outer.lineWidth @lineWidth.setter def lineWidth(self, value): self.outer.lineWidth = value @property def radius(self): """ TODO: Deprecate use of radius in favor of using .size :return: """ return self.outerRadius @radius.setter def radius(self, value): # Set outer radius self.outerRadius = value @property def outerRadius(self): """ TODO: Deprecate use of outerRadius in favor of using .outer.size :return: """ return self.outer.size[1]/2 @outerRadius.setter def outerRadius(self, value): # Make buffer object to handle unit conversion _buffer = layout.Size((0, value * 2), units=self.units, win=self.win) # Use height of buffer object twice, so that size is always square even in norm self.outer.size = layout.Size((_buffer.pix[1], _buffer.pix[1]), units='pix', win=self.win) @property def innerRadius(self): """ TODO: Deprecate use of innerRadius in favor of using .inner.size :return: """ return self.inner.size[1] / 2 @innerRadius.setter def innerRadius(self, value): # Make buffer object to handle unit conversion _buffer = layout.Size((0, value * 2), units=self.units, win=self.win) # Use height of buffer object twice, so that size is always square even in norm self.inner.size = layout.Size((_buffer.pix[1], _buffer.pix[1]), units='pix', win=self.win) @property def foreColor(self): # Return whichever inner color is not None if self.inner.fillColor is not None: return self.inner.fillColor if self.inner.borderColor is not None: return self.inner.borderColor @foreColor.setter def foreColor(self, value): ColorMixin.foreColor.fset(self, value) # Set whichever inner color is not None if self.inner.fillColor is not None: self.inner.fillColor = value if self.inner.borderColor is not None: self.inner.borderColor = value @property def borderColor(self): return self.outer.borderColor @borderColor.setter def borderColor(self, value): ColorMixin.borderColor.fset(self, value) self.outer.borderColor = value @property def fillColor(self): return self.outer.fillColor @fillColor.setter def fillColor(self, value): ColorMixin.fillColor.fset(self, value) self.outer.fillColor = value @property def colorSpace(self): return self.outer.colorSpace @colorSpace.setter def colorSpace(self, value): self.outer.colorSpace = value self.inner.colorSpace = value @property def opacity(self): return self.outer.opacity @opacity.setter def opacity(self, value): self.outer.opacity = value self.inner.opacity = value def draw(self, win=None, keepMatrix=False): self.outer.draw(win, keepMatrix) self.inner.draw(win, keepMatrix) def __iter__(self): """Overload dict() method to return in ioHub format""" # ioHub doesn't treat None as transparent, so we need to handle transparency here # For outer circle, use window color as transparent fillColor = self.outer.fillColor if self.outer._fillColor else self.win.color borderColor = self.outer.borderColor if self.outer._borderColor else self.win.color # For inner circle, use outer circle fill as transparent innerFillColor = self.inner.fillColor if self.inner._fillColor else fillColor innerBorderColor = self.inner.borderColor if self.inner._borderColor else borderColor # Assemble dict asDict = { # Outer circle 'outer_diameter': self.radius * 2, 'outer_stroke_width': self.outer.lineWidth, 'outer_fill_color': fillColor, 'outer_line_color': borderColor, # Inner circle 'inner_diameter': self.innerRadius * 2, 'inner_stroke_width': self.inner.lineWidth, 'inner_fill_color': innerFillColor, 'inner_line_color': innerBorderColor, } for key, value in asDict.items(): yield key, value def targetFromDict(win, spec, name="target", style="circles", pos=(0, 0), units='height', colorSpace="rgb", autoLog=None, autoDraw=False): # Make sure spec has all the required keys, even if it just fills them with None required = [ 'outer_diameter', 'outer_stroke_width', 'outer_fill_color', 'outer_line_color', 'inner_diameter', 'inner_stroke_width', 'inner_fill_color', 'inner_line_color' ] for key in required: if key not in spec: spec[key] = None # Make a target stim from spec TargetStim(win, name=name, style=style, radius=spec['outer_diameter']/2, lineWidth=spec['outer_stroke_width'], fillColor=spec['outer_fill_color'], borderColor=spec['outer_line_color'], innerRadius=spec['inner_diameter']/2, innerLineWidth=spec['inner_stroke_width'], innerFillColor=spec['inner_fill_color'], innerBorderColor=spec['inner_line_color'], pos=pos, units=units, colorSpace=colorSpace, autoLog=autoLog, autoDraw=autoDraw)
9,431
Python
.py
237
30.063291
114
0.611864
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,730
bufferimage.py
psychopy_psychopy/psychopy/visual/bufferimage.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Take a "screen-shot" (full or partial), save to a ImageStim()-like RBGA object.`""" # 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). # Ensure setting pyglet.options['debug_gl'] to False is done prior to any # other calls to pyglet or pyglet submodules, otherwise it may not get picked # up by the pyglet GL engine and have no effect. # Shaders will work but require OpenGL2.0 drivers AND PyOpenGL3.0+ import pyglet pyglet.options['debug_gl'] = False GL = pyglet.gl import psychopy # so we can get the __path__ from psychopy import core, logging # tools must only be imported *after* event or MovieStim breaks on win32 # (JWP has no idea why!) from psychopy.tools.attributetools import attributeSetter, setAttribute from psychopy.tools.typetools import float_uint8 from psychopy.visual.image import ImageStim try: from PIL import Image except ImportError: from . import Image import numpy class BufferImageStim(ImageStim): """Take a "screen-shot", save as an ImageStim (RBGA object). This is a lazy-imported class, therefore import using full path `from psychopy.visual.bufferimage import BufferImageStim` when inheriting from it. The screen-shot is a single collage image composed of static elements that you can treat as being a single stimulus. The screen-shot can be of the visible screen (front buffer) or hidden (back buffer). BufferImageStim aims to provide fast rendering, while still allowing dynamic orientation, position, and opacity. It's fast to draw but slower to init (same as an ImageStim). You specify the part of the screen to capture (in norm units), and optionally the stimuli themselves (as a list of items to be drawn). You get a screenshot of those pixels. If your OpenGL does not support arbitrary sizes, the image will be larger, using square powers of two if needed, with the excess image being invisible (using alpha). The aim is to preserve the buffer contents as rendered. Checks for OpenGL 2.1+, or uses square-power-of-2 images. **Example**:: # define lots of stimuli, make a list: mySimpleImageStim = ... myTextStim = ... stimList = [mySimpleImageStim, myTextStim] # draw stim list items & capture (slow; see EXP log for times): screenshot = visual.BufferImageStim(myWin, stim=stimList) # render to screen (very fast, except for the first draw): while <conditions>: screenshot.draw() # fast; can vary .ori, .pos, .opacity other_stuff.draw() # dynamic myWin.flip() See coder Demos > stimuli > bufferImageStim.py for a demo, with timing stats. :Author: - 2010 Jeremy Gray, with on-going fixes """ def __init__(self, win, buffer='back', rect=(-1, 1, 1, -1), sqPower2=False, stim=(), interpolate=True, flipHoriz=False, flipVert=False, mask='None', pos=(0, 0), name=None, autoLog=None): """ :Parameters: buffer : the screen buffer to capture from, default is 'back' (hidden). 'front' is the buffer in view after win.flip() rect : a list of edges [left, top, right, bottom] defining a screen rectangle which is the area to capture from the screen, given in norm units. default is fullscreen: [-1, 1, 1, -1] stim : a list of item(s) to be drawn to the back buffer (in order). The back buffer is first cleared (without the win being flip()ed), then stim items are drawn, and finally the buffer (or part of it) is captured. Each item needs to have its own .draw() method, and have the same window as win. interpolate : whether to use interpolation (default = True, generally good, especially if you change the orientation) sqPower2 : - False (default) = use rect for size if OpenGL = 2.1+ - True = use square, power-of-two image sizes flipHoriz : horizontally flip (mirror) the captured image, default = False flipVert : vertically flip (mirror) the captured image; default = False """ # depends on: window._getRegionOfFrame # what local vars are defined (these are the init params) for use by # __repr__ self._initParams = dir() self._initParams.remove('self') self.autoLog = False # set this False first and change later _clock = core.Clock() if stim: # draw all stim to the back buffer win.clearBuffer() buffer = 'back' if hasattr(stim, '__iter__'): for stimulus in stim: try: if stimulus.win == win: stimulus.draw() else: msg = ('BufferImageStim.__init__: user ' 'requested "%s" drawn in another window') logging.warning(msg % repr(stimulus)) except AttributeError: msg = 'BufferImageStim.__init__: "%s" failed to draw' logging.warning(msg % repr(stimulus)) else: raise ValueError('Stim is not iterable in BufferImageStim. ' 'It should be a list of stimuli.') # take a screenshot of the buffer using win._getRegionOfFrame(): glversion = pyglet.gl.gl_info.get_version() if glversion >= '2.1' and not sqPower2: region = win._getRegionOfFrame(buffer=buffer, rect=rect) else: if not sqPower2: msg = ('BufferImageStim.__init__: defaulting to square ' 'power-of-2 sized image (%s)') logging.debug(msg % glversion) region = win._getRegionOfFrame(buffer=buffer, rect=rect, squarePower2=True) if stim: win.clearBuffer() # turn the RGBA region into an ImageStim() object: if win.units in ['norm']: pos *= win.size / 2. size = region.size / win.size / 2. super(BufferImageStim, self).__init__( win, image=region, units='pix', mask=mask, pos=pos, size=size, interpolate=interpolate, name=name, autoLog=False) self.size = region.size # to improve drawing speed, move these out of draw: self.thisScale = numpy.array([4, 4]) self.flipHoriz = flipHoriz self.flipVert = flipVert # set autoLog now that params have been initialised wantLog = autoLog is None and self.win.autoLog self.__dict__['autoLog'] = autoLog or wantLog if self.autoLog: logging.exp("Created %s = %s" % (self.name, str(self))) msg = 'BufferImageStim %s: took %.1fms to initialize' logging.exp(msg % (name, 1000 * _clock.getTime())) @attributeSetter def flipHoriz(self, flipHoriz): """If set to True then the image will be flipped horizontally (left-to-right). Note that this is relative to the original image, not relative to the current state. """ self.__dict__['flipHoriz'] = flipHoriz @attributeSetter def flipVert(self, flipVert): """If set to True then the image will be flipped vertically (left-to-right). Note that this is relative to the original image, not relative to the current state. """ self.__dict__['flipVert'] = flipVert def setFlipHoriz(self, newVal=True, log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message. """ setAttribute(self, 'flipHoriz', newVal, log) # call attributeSetter def setFlipVert(self, newVal=True, log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message. """ setAttribute(self, 'flipVert', newVal, log) # call attributeSetter def draw(self, win=None): """Draws the BufferImage on the screen, similar to :class:`~psychopy.visual.ImageStim` `.draw()`. Allows dynamic position, size, rotation, mirroring, and opacity. Limitations / bugs: not sure what happens with shaders and self._updateList() """ if win is None: win = self.win self._selectWindow(win) GL.glPushMatrix() # preserve state # GL.glLoadIdentity() # dynamic flip GL.glScalef(self.thisScale[0] * (1, -1)[self.flipHoriz], self.thisScale[1] * (1, -1)[self.flipVert], 1.0) # enable dynamic position, orientation, opacity; depth not working? GL.glColor4f(*self._foreColor.render('rgba1')) GL.glCallList(self._listID) # make it happen GL.glPopMatrix() # return the view to previous state
9,413
Python
.py
191
38.848168
81
0.616206
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,731
noise.py
psychopy_psychopy/psychopy/visual/noise.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. # some code provided by Andrew Schofield # Distributed under the terms of the GNU General Public License (GPL). """Stimulus object for drawing arbitrary bitmap carriers with an arbitrary second-order envelope carrier and envelope can vary independently for orientation, frequency and phase. Also does beat stimuli. These are optional components that can be obtained by installing the `psychopy-visionscience` extension into the current environment. """ from psychopy.tools.pkgtools import PluginStub # Requires shaders if you don't have them it will just throw and error. # Ensure setting pyglet.options['debug_gl'] to False is done prior to any # other calls to pyglet or pyglet submodules, otherwise it may not get picked # up by the pyglet GL engine and have no effect. # Shaders will work but require OpenGL2.0 drivers AND PyOpenGL3.0+ class NoiseStim( PluginStub, plugin="psychopy-visionscience", doclink="https://psychopy.github.io/psychopy-visionscience/coder/NoiseStim/" ): pass class NoiseStim: """ `psychopy.visual.NoiseStim` is now located within the `psychopy-visionscience` plugin. You can find the documentation for it `here <https://psychopy.github.io/psychopy-visionscience/coder/NoiseStim>`_ """ if __name__ == "__main__": pass
1,454
Python
.py
32
42.8125
94
0.77305
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,732
rift.py
psychopy_psychopy/psychopy/visual/rift.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Oculus Rift HMD support for PsychoPy. Copyright (C) 2019 - Matthew D. Cutone, The Centre for Vision Research, Toronto, Ontario, Canada Uses PsychXR to interface with the Oculus Rift runtime (LibOVR) and SDK. See http://psychxr.org for more information. The Oculus PC SDK is Copyright (c) Facebook Technologies, LLC and its affiliates. All rights reserved. """ # Part of the PsychoPy library # Copyright (C) 2018 Jonathan Peirce # Distributed under the terms of the GNU General Public License (GPL). __all__ = ['Rift'] # ---------- # Initialize # ---------- # Check if they system has PsychXR installed and is importable. If not, this # module will still load, but the `Rift` class will fail to load. This allows # the Rift library to be lazy-loaded on systems without PsychXR. # _HAS_PSYCHXR_ = True try: import psychxr.drivers.libovr as libovr except ImportError: _HAS_PSYCHXR_ = False # ------- # Imports # ------- import warnings import platform import ctypes import numpy as np import pyglet.gl as GL from psychopy.visual import window from psychopy import platform_specific, logging, core from psychopy.tools.attributetools import setAttribute try: from PIL import Image except ImportError: import Image reportNDroppedFrames = 5 # ------------------------------------------- # Look-up tables for PsychXR/LibOVR constants # if _HAS_PSYCHXR_: # Controller types supported by PsychXR RIFT_CONTROLLER_TYPES = { 'Xbox': libovr.CONTROLLER_TYPE_XBOX, 'Remote': libovr.CONTROLLER_TYPE_REMOTE, 'Touch': libovr.CONTROLLER_TYPE_TOUCH, 'LeftTouch': libovr.CONTROLLER_TYPE_LTOUCH, 'RightTouch': libovr.CONTROLLER_TYPE_RTOUCH, 'Object0': libovr.CONTROLLER_TYPE_OBJECT0, 'Object1': libovr.CONTROLLER_TYPE_OBJECT1, 'Object2': libovr.CONTROLLER_TYPE_OBJECT2, 'Object3': libovr.CONTROLLER_TYPE_OBJECT3, libovr.CONTROLLER_TYPE_XBOX: 'Xbox', libovr.CONTROLLER_TYPE_REMOTE: 'Remote', libovr.CONTROLLER_TYPE_TOUCH: 'Touch', libovr.CONTROLLER_TYPE_LTOUCH: 'LeftTouch', libovr.CONTROLLER_TYPE_RTOUCH: 'RightTouch', libovr.CONTROLLER_TYPE_OBJECT0: 'Object0', libovr.CONTROLLER_TYPE_OBJECT1: 'Object1', libovr.CONTROLLER_TYPE_OBJECT2: 'Object2', libovr.CONTROLLER_TYPE_OBJECT3: 'Object3' } # Button types supported by PsychXR RIFT_BUTTON_TYPES = { "A": libovr.BUTTON_A, "B": libovr.BUTTON_B, "RThumb": libovr.BUTTON_RTHUMB, "RShoulder": libovr.BUTTON_RSHOULDER, "X": libovr.BUTTON_X, "Y": libovr.BUTTON_Y, "LThumb": libovr.BUTTON_LTHUMB, "LShoulder": libovr.BUTTON_LSHOULDER, "Up": libovr.BUTTON_UP, "Down": libovr.BUTTON_DOWN, "Left": libovr.BUTTON_LEFT, "Right": libovr.BUTTON_RIGHT, "Enter": libovr.BUTTON_ENTER, "Back": libovr.BUTTON_BACK, "VolUp": libovr.BUTTON_VOLUP, "VolDown": libovr.BUTTON_VOLDOWN, "Home": libovr.BUTTON_HOME, } # Touch types supported by PsychXR RIFT_TOUCH_TYPES = { "A": libovr.TOUCH_A, "B": libovr.TOUCH_B, "RThumb": libovr.TOUCH_RTHUMB, "RThumbRest": libovr.TOUCH_RTHUMBREST, "RThumbUp": libovr.TOUCH_RTHUMBUP, "RIndexPointing": libovr.TOUCH_RINDEXPOINTING, "X": libovr.TOUCH_X, "Y": libovr.TOUCH_Y, "LThumb": libovr.TOUCH_LTHUMB, "LThumbRest": libovr.TOUCH_LTHUMBREST, "LThumbUp": libovr.TOUCH_LTHUMBUP, "LIndexPointing": libovr.TOUCH_LINDEXPOINTING } # Tracked device identifiers RIFT_TRACKED_DEVICE_TYPES = { "HMD": libovr.TRACKED_DEVICE_TYPE_HMD, "LTouch": libovr.TRACKED_DEVICE_TYPE_LTOUCH, "RTouch": libovr.TRACKED_DEVICE_TYPE_RTOUCH, "Touch": libovr.TRACKED_DEVICE_TYPE_TOUCH, "Object0": libovr.TRACKED_DEVICE_TYPE_OBJECT0, "Object1": libovr.TRACKED_DEVICE_TYPE_OBJECT1, "Object2": libovr.TRACKED_DEVICE_TYPE_OBJECT2, "Object3": libovr.TRACKED_DEVICE_TYPE_OBJECT3 } # Tracking origin types RIFT_TRACKING_ORIGIN_TYPE = { "floor": libovr.TRACKING_ORIGIN_FLOOR_LEVEL, "eye": libovr.TRACKING_ORIGIN_EYE_LEVEL } # Performance hud modes RIFT_PERF_HUD_MODES = { 'PerfSummary': libovr.PERF_HUD_PERF_SUMMARY, 'LatencyTiming': libovr.PERF_HUD_LATENCY_TIMING, 'AppRenderTiming': libovr.PERF_HUD_APP_RENDER_TIMING, 'CompRenderTiming': libovr.PERF_HUD_COMP_RENDER_TIMING, 'AswStats': libovr.PERF_HUD_ASW_STATS, 'VersionInfo': libovr.PERF_HUD_VERSION_INFO, 'Off': libovr.PERF_HUD_OFF } # stereo debug hud modes RIFT_STEREO_DEBUG_HUD_MODES = { 'Off': libovr.DEBUG_HUD_STEREO_MODE_OFF, 'Quad': libovr.DEBUG_HUD_STEREO_MODE_QUAD, 'QuadWithCrosshair': libovr.DEBUG_HUD_STEREO_MODE_QUAD_WITH_CROSSHAIR, 'CrosshairAtInfinity': libovr.DEBUG_HUD_STEREO_MODE_CROSSHAIR_AT_INFINITY } # Boundary types RIFT_BOUNDARY_TYPE = { 'PlayArea': libovr.BOUNDARY_PLAY_AREA, 'Outer': libovr.BOUNDARY_OUTER } # mirror modes RIFT_MIRROR_MODES = { 'left': libovr.MIRROR_OPTION_LEFT_EYE_ONLY, 'right': libovr.MIRROR_OPTION_RIGHT_EYE_ONLY, 'distortion': libovr.MIRROR_OPTION_POST_DISTORTION, 'default': libovr.MIRROR_OPTION_DEFAULT } # eye types RIFT_EYE_TYPE = {'left': libovr.EYE_LEFT, 'right': libovr.EYE_RIGHT} # ------------------------------------------------------------------------------ # LibOVR Error Handler # # Exceptions raised by LibOVR will wrapped with this Python exception. This will # display the error string passed from LibOVR. # class LibOVRError(Exception): """Exception for LibOVR errors.""" pass class Rift(window.Window): """Class provides a display and peripheral interface for the Oculus Rift (see: https://www.oculus.com/) head-mounted display. This is a lazy-imported class, therefore import using full path `from psychopy.visual.rift import Rift` when inheriting from it. Requires PsychXR 0.2.4 to be installed. Setting the `winType='glfw'` is preferred for VR applications. """ def __init__( self, fovType='recommended', trackingOriginType='floor', texelsPerPixel=1.0, headLocked=False, highQuality=True, monoscopic=False, samples=1, mirrorMode='default', mirrorRes=None, warnAppFrameDropped=True, autoUpdateInput=True, legacyOpenGL=True, *args, **kwargs): """ Parameters ---------- fovType : str Field-of-view (FOV) configuration type. Using 'recommended' auto-configures the FOV using the recommended parameters computed by the runtime. Using 'symmetric' forces a symmetric FOV using optimal parameters from the SDK, this mode is required for displaying 2D stimuli. Specifying 'max' will use the maximum FOVs supported by the HMD. trackingOriginType : str Specify the HMD origin type. If 'floor', the height of the user is added to the head tracker by LibOVR. texelsPerPixel : float Texture pixels per display pixel at FOV center. A value of 1.0 results in 1:1 mapping. A fractional value results in a lower resolution draw buffer which may increase performance. headLocked : bool Lock the compositor render layer in-place, disabling Asynchronous Space Warp (ASW). Enable this if you plan on computing eye poses using custom or modified head poses. highQuality : bool Configure the compositor to use anisotropic texture sampling (4x). This reduces aliasing artifacts resulting from high frequency details particularly in the periphery. nearClip, farClip : float Location of the near and far clipping plane in GL units (meters by default) from the viewer. These values can be updated after initialization. monoscopic : bool Enable monoscopic rendering mode which presents the same image to both eyes. Eye poses used will be both centered at the HMD origin. Monoscopic mode uses a separate rendering pipeline which reduces VRAM usage. When in monoscopic mode, you do not need to call 'setBuffer' prior to rendering (doing so will do have no effect). samples : int or str Specify the number of samples for multi-sample anti-aliasing (MSAA). When >1, multi-sampling logic is enabled in the rendering pipeline. If 'max' is specified, the largest number of samples supported by the platform is used. If floating point textures are used, MSAA sampling is disabled. Must be power of two value. mirrorMode : str On-screen mirror mode. Values 'left' and 'right' show rectilinear images of a single eye. Value 'distortion` shows the post-distortion image after being processed by the compositor. Value 'default' displays rectilinear images of both eyes side-by-side. mirrorRes : list of int Resolution of the mirror texture. If `None`, the resolution will match the window size. The value of `mirrorRes` is used for to define the resolution of movie frames. warnAppFrameDropped : bool Log a warning if the application drops a frame. This occurs when the application fails to submit a frame to the compositor on-time. Application frame drops can have many causes, such as running routines in your application loop that take too long to complete. However, frame drops can happen sporadically due to driver bugs and running background processes (such as Windows Update). Use the performance HUD to help diagnose the causes of frame drops. autoUpdateInput : bool Automatically update controller input states at the start of each frame. If `False`, you must manually call `updateInputState` before getting input values from `LibOVR` managed input devices. legacyOpenGL : bool Disable 'immediate mode' OpenGL calls in the rendering pipeline. Specifying False maintains compatibility with existing PsychoPy stimuli drawing routines. Use True when computing transformations using some other method and supplying shaders matrices directly. """ if not _HAS_PSYCHXR_: raise ModuleNotFoundError( "PsychXR must be installed to use the `Rift` class. Exiting.") self._closed = False self._legacyOpenGL = legacyOpenGL self._monoscopic = monoscopic self._texelsPerPixel = texelsPerPixel self._headLocked = headLocked self._highQuality = highQuality self._samples = samples self._mirrorRes = mirrorRes self._mirrorMode = mirrorMode self.autoUpdateInput = autoUpdateInput # performance statistics # this can be changed while running self.warnAppFrameDropped = warnAppFrameDropped # check if we are using Windows if platform.system() != 'Windows': raise RuntimeError("`Rift` class only supports Windows OS at this " + "time, exiting.") # check if we are using 64-bit Python if platform.architecture()[0] != '64bit': # sys.maxsize != 2**64 raise RuntimeError("`Rift` class only supports 64-bit Python, " + "exiting.") # check if the background service is running and an HMD is connected if not libovr.isOculusServiceRunning(): raise RuntimeError("HMD service is not available or started, " + "exiting.") if not libovr.isHmdConnected(): raise RuntimeError("Cannot find any connected HMD, check " + "connections and try again.") # create a VR session, do some initial configuration initResult = libovr.initialize() # removed logging callback if libovr.failure(initResult): _, msg = libovr.getLastErrorInfo() raise LibOVRError(msg) if libovr.failure(libovr.create()): libovr.shutdown() # shutdown the session _, msg = libovr.getLastErrorInfo() raise LibOVRError(msg) if libovr.failure(libovr.resetPerfStats()): logging.warn('Failed to reset performance stats.') self._perfStats = libovr.getPerfStats() self._lastAppDroppedFrameCount = 0 # update session status object _, status = libovr.getSessionStatus() self._sessionStatus = status # get HMD information self._hmdInfo = libovr.getHmdInfo() # configure the internal render descriptors based on the requested # viewing parameters. if fovType == 'symmetric' or self._monoscopic: # Use symmetric FOVs for cases where off-center frustums are not # desired. This is required for monoscopic rendering to permit # comfortable binocular fusion. eyeFovs = self._hmdInfo.symmetricEyeFov logging.info('Using symmetric eye FOVs.') elif fovType == 'recommended' or fovType == 'default': # use the recommended FOVs, these have wider FOVs looking outward # due to off-center frustums. eyeFovs = self._hmdInfo.defaultEyeFov logging.info('Using default/recommended eye FOVs.') elif fovType == 'max': # the maximum FOVs for the HMD supports eyeFovs = self._hmdInfo.maxEyeFov logging.info('Using maximum eye FOVs.') else: raise ValueError( "Invalid FOV type '{}' specified.".format(fovType)) # pass the FOVs to PsychXR for eye, fov in enumerate(eyeFovs): libovr.setEyeRenderFov(eye, fov) libovr.setHeadLocked(headLocked) # enable head locked mode libovr.setHighQuality(highQuality) # enable high quality mode # Compute texture sizes for render buffers, these are reported by the # LibOVR SDK based on the FOV settings specified above. texSizeLeft = libovr.calcEyeBufferSize(libovr.EYE_LEFT) texSizeRight = libovr.calcEyeBufferSize(libovr.EYE_RIGHT) # we are using a shared texture, so we need to combine dimensions if not self._monoscopic: hmdBufferWidth = texSizeLeft[0] + texSizeRight[0] else: hmdBufferWidth = max(texSizeLeft[0], texSizeRight[0]) hmdBufferHeight = max(texSizeLeft[1], texSizeRight[1]) # buffer viewport size self._hmdBufferSize = hmdBufferWidth, hmdBufferHeight logging.debug( 'Required HMD buffer size is {}x{}.'.format(*self._hmdBufferSize)) # Calculate the swap texture size. These can differ in later # configurations, right now they are the same. self._swapTextureSize = self._hmdBufferSize # Compute the required viewport parameters for the given buffer and # texture sizes. If we are using a power of two texture, we need to # centre the viewports on the textures. if not self._monoscopic: leftViewport = (0, 0, texSizeLeft[0], texSizeLeft[1]) rightViewport = (texSizeLeft[0], 0, texSizeRight[0], texSizeRight[1]) else: # In mono mode, we use the same viewport for both eyes. Therefore, # the swap texture only needs to be half as wide. This save VRAM # and does not require buffer changes when rendering. leftViewport = (0, 0, texSizeLeft[0], texSizeLeft[1]) rightViewport = (0, 0, texSizeRight[0], texSizeRight[1]) libovr.setEyeRenderViewport(libovr.EYE_LEFT, leftViewport) logging.debug( 'Set left eye viewport to: x={}, y={}, w={}, h={}.'.format( *leftViewport)) libovr.setEyeRenderViewport(libovr.EYE_RIGHT, rightViewport) logging.debug( 'Set right eye viewport to: x={}, y={}, w={}, h={}.'.format( *rightViewport)) self.scrWidthPIX = max(texSizeLeft[0], texSizeRight[0]) # frame index self._frameIndex = 0 # setup a mirror texture self._mirrorRes = mirrorRes # view buffer to divert operations to, if None, drawing is sent to the # on-screen window. self.buffer = None # View matrices, these are updated every frame based on computed head # position. Projection matrices need only to be computed once. if not self._monoscopic: self._projectionMatrix = [ np.identity(4, dtype=np.float32), np.identity(4, dtype=np.float32)] self._viewMatrix = [ np.identity(4, dtype=np.float32), np.identity(4, dtype=np.float32)] else: self._projectionMatrix = np.identity(4, dtype=np.float32) self._viewMatrix = np.identity(4, dtype=np.float32) # disable v-sync since the HMD runs at a different frequency kwargs['waitBlanking'] = False # force checkTiming and quad-buffer stereo off kwargs["checkTiming"] = False # not used here for now kwargs["stereo"] = False # false, using our own stuff for stereo kwargs['useFBO'] = True # true, but uses it's ow FBO logic kwargs['multiSample'] = False # not for the back buffer of the widow # do not allow 'endFrame' to be called until _startOfFlip is called self._allowHmdRendering = False # VR pose data, updated every frame self._headPose = libovr.LibOVRPose() # set the tracking origin type self.trackingOriginType = trackingOriginType # performance information self.nDroppedFrames = 0 self.controllerPollTimes = {} # call up a new window object super(Rift, self).__init__(*args, **kwargs) self._updateProjectionMatrix() def close(self): """Close the window and cleanly shutdown the LibOVR session. """ logging.info('Closing `Rift` window, de-allocating resources and ' 'shutting down VR session.') # switch off persistent HUD features self.perfHudMode = 'Off' self.stereoDebugHudMode = 'Off' # clean up allocated LibOVR resources before closing the window logging.debug('Destroying mirror texture.') libovr.destroyMirrorTexture() logging.debug('Destroying texture GL swap chain.') libovr.destroyTextureSwapChain(libovr.TEXTURE_SWAP_CHAIN0) logging.debug('Destroying LibOVR session.') libovr.destroy() # start closing the window self._closed = True logging.debug('Closing window associated with LibOVR session.') self.backend.close() try: core.openWindows.remove(self) except Exception: pass try: self.mouseVisible = True except Exception: pass # shutdown the session completely #libovr.shutdown() logging.info('LibOVR session shutdown cleanly.') try: logging.flush() except Exception: pass @property def size(self): """Size property to get the dimensions of the view buffer instead of the window. If there are no view buffers, always return the dims of the window. """ # this is a hack to get stimuli to draw correctly if self.buffer is None: return self.frameBufferSize else: if self._monoscopic: return np.array( (self._hmdBufferSize[0], self._hmdBufferSize[1]), int) else: return np.array( (int(self._hmdBufferSize[0] / 2), self._hmdBufferSize[1]), int) @size.setter def size(self, value): """Set the size of the window. """ self.__dict__['size'] = np.array(value, int) def setSize(self, value, log=True): setAttribute(self, 'size', value, log=log) def perfHudMode(self, mode='Off'): """Set the performance HUD mode. Parameters ---------- mode : str HUD mode to use. """ result = libovr.setInt(libovr.PERF_HUD_MODE, RIFT_PERF_HUD_MODES[mode]) if libovr.success(result): logging.info("Performance HUD mode set to '{}'.".format(mode)) else: logging.error('Failed to set performance HUD mode to "{}".'.format( mode)) def hidePerfHud(self): """Hide the performance HUD.""" libovr.setInt(libovr.PERF_HUD_MODE, libovr.PERF_HUD_OFF) logging.info('Performance HUD disabled.') def stereoDebugHudMode(self, mode): """Set the debug stereo HUD mode. This makes the compositor add stereoscopic reference guides to the scene. You can configure the HUD can be configured using other methods. Parameters ---------- mode : str Stereo debug mode to use. Valid options are `Off`, `Quad`, `QuadWithCrosshair`, and `CrosshairAtInfinity`. Examples -------- Enable a stereo debugging guide:: hmd.stereoDebugHudMode('CrosshairAtInfinity') Hide the debugging guide. Should be called before exiting the application since it's persistent until the Oculus service is restarted:: hmd.stereoDebugHudMode('Off') """ result = libovr.setInt( libovr.DEBUG_HUD_STEREO_MODE, RIFT_STEREO_DEBUG_HUD_MODES[mode]) if result: logging.info("Stereo debug HUD mode set to '{}'.".format(mode)) else: logging.warning( "Failed to set stereo debug HUD mode set to '{}'.".format(mode)) def setStereoDebugHudOption(self, option, value): """Configure stereo debug HUD guides. Parameters ---------- option : str Option to set. Valid options are `InfoEnable`, `Size`, `Position`, `YawPitchRoll`, and `Color`. value : array_like or bool Value to set for a given `option`. Appropriate types for each option are: * `InfoEnable` - bool, `True` to show, `False` to hide. * `Size` - array_like, [w, h] in meters. * `Position` - array_like, [x, y, z] in meters. * `YawPitchRoll` - array_like, [pitch, yaw, roll] in degrees. * `Color` - array_like, [r, g, b] as floats ranging 0.0 to 1.0. Returns ------- bool ``True`` if the option was successfully set. Examples -------- Configuring a stereo debug HUD guide:: # show a quad with a crosshair hmd.stereoDebugHudMode('QuadWithCrosshair') # enable displaying guide information hmd.setStereoDebugHudOption('InfoEnable', True) # set the position of the guide quad in the scene hmd.setStereoDebugHudOption('Position', [0.0, 1.7, -2.0]) """ if option == 'InfoEnable': result = libovr.setBool( libovr.DEBUG_HUD_STEREO_GUIDE_INFO_ENABLE, value) elif option == 'Size': value = np.asarray(value, dtype=np.float32) result = libovr.setFloatArray( libovr.DEBUG_HUD_STEREO_GUIDE_SIZE, value) elif option == 'Position': value = np.asarray(value, dtype=np.float32) result = libovr.setFloatArray( libovr.DEBUG_HUD_STEREO_GUIDE_POSITION, value) elif option == 'YawPitchRoll': value = np.asarray(value, dtype=np.float32) result = libovr.setFloatArray( libovr.DEBUG_HUD_STEREO_GUIDE_YAWPITCHROLL, value) elif option == 'Color' or option == 'Colour': value = np.asarray(value, dtype=np.float32) result = libovr.setFloatArray( libovr.DEBUG_HUD_STEREO_GUIDE_COLOR, value) else: raise ValueError("Invalid option `{}` specified.".format(option)) if result: logging.info( "Stereo debug HUD option '{}' set to {}.".format( option, str(value))) else: logging.warning( "Failed to set stereo debug HUD option '{}' set to {}.".format( option, str(value))) @property def userHeight(self): """Get user height in meters (`float`).""" return libovr.getFloat(libovr.KEY_PLAYER_HEIGHT, libovr.DEFAULT_PLAYER_HEIGHT) @property def eyeHeight(self): """Eye height in meters (`float`).""" return libovr.getFloat(libovr.KEY_EYE_HEIGHT, libovr.DEFAULT_EYE_HEIGHT) @property def eyeToNoseDistance(self): """Eye to nose distance in meters (`float`). Examples -------- Generate your own eye poses. These are used when :py:meth:`calcEyePoses` is called:: leftEyePose = Rift.createPose((-self.eyeToNoseDistance, 0., 0.)) rightEyePose = Rift.createPose((self.eyeToNoseDistance, 0., 0.)) Get the inter-axial separation (IAS) reported by `LibOVR`:: iad = self.eyeToNoseDistance * 2.0 """ eyeToNoseDist = np.zeros((2,), dtype=np.float32) libovr.getFloatArray(libovr.KEY_EYE_TO_NOSE_DISTANCE, eyeToNoseDist) return eyeToNoseDist @property def eyeOffset(self): """Eye separation in centimeters (`float`). """ leftEyeHmdPose = libovr.getHmdToEyePose(libovr.EYE_LEFT) rightEyeHmdPose = libovr.getHmdToEyePose(libovr.EYE_RIGHT) return (-leftEyeHmdPose.pos[0] + rightEyeHmdPose.pos[0]) / 100.0 @eyeOffset.setter def eyeOffset(self, value): halfIAS = (value / 2.0) * 100.0 libovr.setHmdToEyePose( libovr.EYE_LEFT, libovr.LibOVRPose((halfIAS, 0.0, 0.0))) libovr.setHmdToEyePose( libovr.EYE_RIGHT, libovr.LibOVRPose((-halfIAS, 0.0, 0.0))) logging.info( 'Eye separation set to {} centimeters.'.format(value)) @property def hasPositionTracking(self): """``True`` if the HMD is capable of tracking position.""" return self._hmdInfo.hasPositionTracking @property def hasOrientationTracking(self): """``True`` if the HMD is capable of tracking orientation.""" return self._hmdInfo.hasOrientationTracking @property def hasMagYawCorrection(self): """``True`` if this HMD supports yaw drift correction.""" return self._hmdInfo.hasMagYawCorrection @property def productName(self): """Get the HMD's product name (`str`). """ return self._hmdInfo.productName @property def manufacturer(self): """Get the connected HMD's manufacturer (`str`). """ return self._hmdInfo.manufacturer @property def serialNumber(self): """Get the connected HMD's unique serial number (`str`). Use this to identify a particular unit if you own many. """ return self._hmdInfo.serialNumber @property def hid(self): """USB human interface device (HID) identifiers (`int`, `int`). """ return self._hmdInfo.hid @property def firmwareVersion(self): """Get the firmware version of the active HMD (`int`, `int`). """ return self._hmdInfo.firmwareVersion @property def displayResolution(self): """Get the HMD's raster display size (`int`, `int`). """ return self._hmdInfo.resolution @property def displayRefreshRate(self): """Get the HMD's display refresh rate in Hz (`float`). """ return self._hmdInfo.refreshRate @property def pixelsPerTanAngleAtCenter(self): """Horizontal and vertical pixels per tangent angle (=1) at the center of the display. This can be used to compute pixels-per-degree for the display. """ return [libovr.getPixelsPerTanAngleAtCenter(libovr.EYE_LEFT), libovr.getPixelsPerTanAngleAtCenter(libovr.EYE_RIGHT)] def tanAngleToNDC(self, horzTan, vertTan): """Convert tan angles to the normalized device coordinates for the current buffer. Parameters ---------- horzTan : float Horizontal tan angle. vertTan : float Vertical tan angle. Returns ------- tuple of float Normalized device coordinates X, Y. Coordinates range between -1.0 and 1.0. Returns `None` if an invalid buffer is selected. """ if self.buffer == 'left': return libovr.getTanAngleToRenderTargetNDC( libovr.EYE_LEFT, (horzTan, vertTan)) elif self.buffer == 'right': return libovr.getTanAngleToRenderTargetNDC( libovr.EYE_RIGHT, (horzTan, vertTan)) @property def trackerCount(self): """Number of attached trackers.""" return libovr.getTrackerCount() def getTrackerInfo(self, trackerIdx): """Get tracker information. Parameters ---------- trackerIdx : int Tracker index, ranging from 0 to :py:class:`~Rift.trackerCount`. Returns ------- :py:class:`~psychxr.libovr.LibOVRTrackerInfo` Object containing tracker information. Raises ------ IndexError Raised when `trackerIdx` out of range. """ if 0 <= trackerIdx < libovr.getTrackerCount(): return libovr.getTrackerInfo(trackerIdx) else: raise IndexError( "Tracker index '{}' out of range.".format(trackerIdx)) @property def headLocked(self): """`True` if head locking is enabled.""" return libovr.isHeadLocked() @headLocked.setter def headLocked(self, value): libovr.setHeadLocked(bool(value)) @property def trackingOriginType(self): """Current tracking origin type (`str`). Valid tracking origin types are 'floor' and 'eye'. """ originType = libovr.getTrackingOriginType() if originType == libovr.TRACKING_ORIGIN_FLOOR_LEVEL: return 'floor' elif originType == libovr.TRACKING_ORIGIN_EYE_LEVEL: return 'eye' else: raise ValueError("LibOVR returned unknown tracking origin type.") @trackingOriginType.setter def trackingOriginType(self, value): libovr.setTrackingOriginType(RIFT_TRACKING_ORIGIN_TYPE[value]) def recenterTrackingOrigin(self): """Recenter the tracking origin using the current head position.""" libovr.recenterTrackingOrigin() def specifyTrackingOrigin(self, pose): """Specify a tracking origin. If `trackingOriginType='floor'`, this function sets the origin of the scene in the ground plane. If `trackingOriginType='eye'`, the scene origin is set to the known eye height. Parameters ---------- pose : LibOVRPose Tracking origin pose. """ libovr.specifyTrackingOrigin(pose) def specifyTrackingOriginPosOri(self, pos=(0., 0., 0.), ori=(0., 0., 0., 1.)): """Specify a tracking origin using a pose and orientation. This is the same as `specifyTrackingOrigin`, but accepts a position vector [x, y, z] and orientation quaternion [x, y, z, w]. Parameters ---------- pos : tuple or list of float, or ndarray Position coordinate of origin (x, y, z). ori : tuple or list of float, or ndarray Quaternion specifying orientation (x, y, z, w). """ libovr.specifyTrackingOrigin(libovr.LibOVRPose(pos, ori)) def clearShouldRecenterFlag(self): """Clear the 'shouldRecenter' status flag at the API level.""" libovr.clearShouldRecenterFlag() def testBoundary(self, deviceType, bounadryType='PlayArea'): """Test if tracked devices are colliding with the play area boundary. This returns an object containing test result data. Parameters ---------- deviceType : str, list or tuple The device to check for boundary collision. If a list of names is provided, they will be combined and all tested. boundaryType : str Boundary type to test. """ if isinstance(deviceType, (list, tuple,)): deviceBits = 0x00000000 for device in deviceType: deviceBits |= RIFT_TRACKED_DEVICE_TYPES[device] elif isinstance(deviceType, str): deviceBits = RIFT_TRACKED_DEVICE_TYPES[deviceType] elif isinstance(deviceType, int): deviceBits = deviceType else: raise TypeError("Invalid type specified for `deviceType`.") result, testResult = libovr.testBoundary( deviceBits, RIFT_BOUNDARY_TYPE[bounadryType]) if libovr.failure(result): raise RuntimeError('Failed to get boundary test result') return testResult @property def sensorSampleTime(self): """Sensor sample time (`float`). This value corresponds to the time the head (HMD) position was sampled, which is required for computing motion-to-photon latency. This does not need to be specified if `getTrackingState` was called with `latencyMarker=True`. """ return libovr.getSensorSampleTime() @sensorSampleTime.setter def sensorSampleTime(self, value): libovr.setSensorSampleTime(value) def getDevicePose(self, deviceName, absTime=None, latencyMarker=False): """Get the pose of a tracked device. For head (HMD) and hand poses (Touch controllers) it is better to use :py:meth:`getTrackingState` instead. Parameters ---------- deviceName : str Name of the device. Valid device names are: 'HMD', 'LTouch', 'RTouch', 'Touch', 'Object0', 'Object1', 'Object2', and 'Object3'. absTime : float, optional Absolute time in seconds the device pose refers to. If not specified, the predicted time is used. latencyMarker : bool Insert a marker for motion-to-photon latency calculation. Should only be `True` if the HMD pose is being used to compute eye poses. Returns ------- `LibOVRPoseState` or `None` Pose state object. `None` if device tracking was lost. """ if absTime is None: absTime = self.getPredictedDisplayTime() deviceStatus, devicePose = libovr.getDevicePoses( [RIFT_TRACKED_DEVICE_TYPES[deviceName]], absTime, latencyMarker) # check if tracking was lost if deviceStatus == libovr.ERROR_LOST_TRACKING: return None return devicePose[0] def getTrackingState(self, absTime=None, latencyMarker=True): """Get the tracking state of the head and hands. Calling this function retrieves the tracking state of the head (HMD) and hands at `absTime` from the `LibOVR` runtime. The returned object is a :py:class:`~psychxr.libovr.LibOVRTrackingState` instance with poses, motion derivatives (i.e. linear and angular velocity/acceleration), and tracking status flags accessible through its attributes. The pose states of the head and hands are available by accessing the `headPose` and `handPoses` attributes, respectively. Parameters ---------- absTime : float, optional Absolute time the tracking state refers to. If not specified, the predicted display time is used. latencyMarker : bool, optional Set a latency marker upon getting the tracking state. This is used for motion-to-photon calculations. Returns ------- :py:class:`~psychxr.libovr.LibOVRTrackingState` Tracking state object. For more information about this type see: See Also -------- getPredictedDisplayTime Time at mid-frame for the current frame index. Examples -------- Get the tracked head pose and use it to calculate render eye poses:: # get tracking state at predicted mid-frame time absTime = getPredictedDisplayTime() trackingState = hmd.getTrackingState(absTime) # get the head pose from the tracking state headPose = trackingState.headPose.thePose hmd.calcEyePoses(headPose) # compute eye poses Get linear/angular velocity and acceleration vectors of the right touch controller:: # right hand is the second value (index 1) at `handPoses` rightHandState = trackingState.handPoses[1] # is `LibOVRPoseState` # access `LibOVRPoseState` fields to get the data linearVel = rightHandState.linearVelocity # m/s angularVel = rightHandState.angularVelocity # rad/s linearAcc = rightHandState.linearAcceleration # m/s^2 angularAcc = rightHandState.angularAcceleration # rad/s^2 # extract components like this if desired vx, vy, vz = linearVel ax, ay, az = angularVel Above is useful for physics simulations, where one can compute the magnitude and direction of a force applied to a virtual object. It's often the case that object tracking becomes unreliable for some reason, for instance, if it becomes occluded and is no longer visible to the sensors. In such cases, the reported pose state is invalid and may not be useful. You can check if the position and orientation of a tracked object is invalid using flags associated with the tracking state. This shows how to check if head position and orientation tracking was valid when sampled:: if trackingState.positionValid and trackingState.orientationValid: print('Tracking valid.') It's up to the programmer to determine what to do in such cases. Note that tracking may still be valid even if Get the calibrated origin used for tracking during the sample period of the tracking state:: calibratedOrigin = trackingState.calibratedOrigin calibPos, calibOri = calibratedOrigin.posOri Time integrate a tracking state. This extrapolates the pose over time given the present computed motion derivatives. The contrived example below shows how to implement head pose forward prediction:: # get current system time absTime = getTimeInSeconds() # get the elapsed time from `absTime` to predicted v-sync time, # again this is an example, you would usually pass predicted time to # `getTrackingState` directly. dt = getPredictedDisplayTime() - absTime # get the tracking state for the current time, poses will lag where # they are expected at predicted time by `dt` seconds trackingState = hmd.getTrackingState(absTime) # time integrate a pose by `dt` headPoseState = trackingState.headPose headPosePredicted = headPoseState.timeIntegrate(dt) # calc eye poses with predicted head pose, this is a custom pose to # head-locking should be enabled! hmd.calcEyePoses(headPosePredicted) The resulting head pose is usually very close to what `getTrackingState` would return if the predicted time was used. Simple forward prediction with time integration becomes increasingly unstable as the prediction interval increases. Under normal circumstances, let the runtime handle forward prediction by using the pose states returned at the predicted display time. If you plan on doing your own forward prediction, you need enable head-locking, clamp the prediction interval, and apply some sort of smoothing to keep the image as stable as possible. """ if absTime is None: absTime = self.getPredictedDisplayTime() return libovr.getTrackingState(absTime, latencyMarker) def calcEyePoses(self, headPose, originPose=None): """Calculate eye poses for rendering. This function calculates the eye poses to define the viewpoint transformation for each eye buffer. Upon starting a new frame, the application loop is halted until this function is called and returns. Once this function returns, `setBuffer` may be called and frame rendering can commence. The computed eye pose for the selected buffer is accessible through the :py:attr:`eyeRenderPose` attribute after calling :py:meth:`setBuffer`. If `monoscopic=True`, the eye poses are set to the head pose. The source data specified to `headPose` can originate from the tracking state retrieved by calling :py:meth:`getTrackingState`, or from other sources. If a custom head pose is specified (for instance, from a motion tracker), you must ensure `head-locking` is enabled to prevent the ASW feature of the compositor from engaging. Furthermore, you must specify sensor sample time for motion-to-photon calculation derived from the sample time of the custom tracking source. Parameters ---------- headPose : LibOVRPose Head pose to use. originPose : LibOVRPose, optional Origin of tracking in the VR scene. Examples -------- Get the tracking state and calculate the eye poses:: # get tracking state at predicted mid-frame time trackingState = hmd.getTrackingState() # get the head pose from the tracking state headPose = trackingState.headPose.thePose hmd.calcEyePoses(headPose) # compute eye poses # begin rendering to each eye for eye in ('left', 'right'): hmd.setBuffer(eye) hmd.setRiftView() # draw stuff here ... Using a custom head pose (make sure ``headLocked=True`` before doing this):: headPose = createPose((0., 1.75, 0.)) hmd.calcEyePoses(headPose) # compute eye poses """ if not self._allowHmdRendering: return libovr.calcEyePoses(headPose, originPose) self._headPose = headPose # Calculate eye poses, this needs to be called every frame. # apply additional transformations to eye poses if not self._monoscopic: for eye, matrix in enumerate(self._viewMatrix): # compute each eye's transformation modelMatrix from returned poses libovr.getEyeViewMatrix(eye, matrix) else: # view modelMatrix derived from head position when in monoscopic mode self._viewMatrix = headPose.getViewMatrix() self._startHmdFrame() @property def eyeRenderPose(self): """Computed eye pose for the current buffer. Only valid after calling :func:`calcEyePoses`. """ if not self._monoscopic: if self.buffer == 'left': return libovr.getEyeRenderPose(libovr.EYE_LEFT) elif self.buffer == 'right': return libovr.getEyeRenderPose(libovr.EYE_RIGHT) else: return self._headPose @property def shouldQuit(self): """`True` if the user requested the application should quit through the headset's interface. """ return self._sessionStatus.shouldQuit @property def isVisible(self): """`True` if the app has focus in the HMD and is visible to the viewer. """ return self._sessionStatus.isVisible @property def hmdMounted(self): """`True` if the HMD is mounted on the user's head. """ return self._sessionStatus.hmdMounted @property def hmdPresent(self): """`True` if the HMD is present. """ return self._sessionStatus.hmdPresent @property def shouldRecenter(self): """`True` if the user requested the origin be re-centered through the headset's interface. """ return self._sessionStatus.shouldRecenter @property def hasInputFocus(self): """`True` if the application currently has input focus. """ return self._sessionStatus.hasInputFocus @property def overlayPresent(self): return self._sessionStatus.overlayPresent def _setupFrameBuffer(self): """Override the default framebuffer init code in window.Window to use the HMD swap chain. The HMD's swap texture and render buffer are configured here. If multisample anti-aliasing (MSAA) is enabled, a secondary render buffer is created. Rendering is diverted to the multi-sample buffer when drawing, which is then resolved into the HMD's swap chain texture prior to committing it to the chain. Consequently, you cannot pass the texture attached to the FBO specified by `frameBuffer` until the MSAA buffer is resolved. Doing so will result in a blank texture. """ # create a texture swap chain for both eye textures result = libovr.createTextureSwapChainGL( libovr.TEXTURE_SWAP_CHAIN0, self._swapTextureSize[0], self._swapTextureSize[1]) if libovr.success(result): logging.info( 'Created texture swap chain with dimensions {w}x{h}.'.format( w=self._swapTextureSize[0], h=self._swapTextureSize[1])) else: _, msg = libovr.getLastErrorInfo() raise LibOVRError(msg) # assign the same swap chain to both eyes for eye in range(libovr.EYE_COUNT): libovr.setEyeColorTextureSwapChain(eye, libovr.TEXTURE_SWAP_CHAIN0) # Use MSAA if more than one sample is specified. If enabled, a render # buffer will be created. # max_samples = GL.GLint() GL.glGetIntegerv(GL.GL_MAX_SAMPLES, max_samples) if isinstance(self._samples, int): if (self._samples & (self._samples - 1)) != 0: # power of two? logging.warning( 'Invalid number of MSAA samples provided, must be ' 'power of two. Disabling.') elif 0 > self._samples > max_samples.value: # check if within range logging.warning( 'Invalid number of MSAA samples provided, outside of valid ' 'range. Disabling.') elif isinstance(self._samples, str): if self._samples == 'max': self._samples = max_samples.value # create an MSAA render buffer if self._samples > 1 self.frameBufferMsaa = GL.GLuint() # is zero if not configured if self._samples > 1: logging.info( 'Samples > 1, creating multi-sample framebuffer with dimensions' '{w}x{h}.'.format(w=int(self._swapTextureSize[0]), h=int(self._swapTextureSize[1]))) # multi-sample FBO and rander buffer GL.glGenFramebuffers(1, ctypes.byref(self.frameBufferMsaa)) GL.glBindFramebuffer(GL.GL_FRAMEBUFFER, self.frameBufferMsaa) # we don't need a multi-sample texture rb_color_msaa_id = GL.GLuint() GL.glGenRenderbuffers(1, ctypes.byref(rb_color_msaa_id)) GL.glBindRenderbuffer(GL.GL_RENDERBUFFER, rb_color_msaa_id) GL.glRenderbufferStorageMultisample( GL.GL_RENDERBUFFER, self._samples, GL.GL_RGBA8, int(self._swapTextureSize[0]), int(self._swapTextureSize[1])) GL.glFramebufferRenderbuffer( GL.GL_FRAMEBUFFER, GL.GL_COLOR_ATTACHMENT0, GL.GL_RENDERBUFFER, rb_color_msaa_id) GL.glBindRenderbuffer(GL.GL_RENDERBUFFER, 0) rb_depth_msaa_id = GL.GLuint() GL.glGenRenderbuffers(1, ctypes.byref(rb_depth_msaa_id)) GL.glBindRenderbuffer(GL.GL_RENDERBUFFER, rb_depth_msaa_id) GL.glRenderbufferStorageMultisample( GL.GL_RENDERBUFFER, self._samples, GL.GL_DEPTH24_STENCIL8, int(self._swapTextureSize[0]), int(self._swapTextureSize[1])) GL.glFramebufferRenderbuffer( GL.GL_FRAMEBUFFER, GL.GL_DEPTH_ATTACHMENT, GL.GL_RENDERBUFFER, rb_depth_msaa_id) GL.glFramebufferRenderbuffer( GL.GL_FRAMEBUFFER, GL.GL_STENCIL_ATTACHMENT, GL.GL_RENDERBUFFER, rb_depth_msaa_id) GL.glBindRenderbuffer(GL.GL_RENDERBUFFER, 0) GL.glClear(GL.GL_STENCIL_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT) GL.glBindFramebuffer(GL.GL_FRAMEBUFFER, 0) # create a frame buffer object as a render target for the HMD textures self.frameBuffer = GL.GLuint() GL.glGenFramebuffers(1, ctypes.byref(self.frameBuffer)) GL.glBindFramebuffer(GL.GL_FRAMEBUFFER, self.frameBuffer) # initialize the frame texture variable self.frameTexture = 0 # create depth and stencil render buffers depth_rb_id = GL.GLuint() GL.glGenRenderbuffers(1, ctypes.byref(depth_rb_id)) GL.glBindRenderbuffer(GL.GL_RENDERBUFFER, depth_rb_id) GL.glRenderbufferStorage( GL.GL_RENDERBUFFER, GL.GL_DEPTH24_STENCIL8, int(self._swapTextureSize[0]), int(self._swapTextureSize[1])) GL.glFramebufferRenderbuffer( GL.GL_FRAMEBUFFER, GL.GL_DEPTH_ATTACHMENT, GL.GL_RENDERBUFFER, depth_rb_id) GL.glFramebufferRenderbuffer( GL.GL_FRAMEBUFFER, GL.GL_STENCIL_ATTACHMENT, GL.GL_RENDERBUFFER, depth_rb_id) GL.glBindRenderbuffer(GL.GL_RENDERBUFFER, 0) GL.glBindFramebuffer(GL.GL_FRAMEBUFFER, 0) self._frameStencil = depth_rb_id # should make this the MSAA's? GL.glClear(GL.GL_STENCIL_BUFFER_BIT) GL.glClear(GL.GL_DEPTH_BUFFER_BIT) # Setup the mirror texture framebuffer. The swap chain is managed # internally by PsychXR. self._mirrorFbo = GL.GLuint() GL.glGenFramebuffers(1, ctypes.byref(self._mirrorFbo)) if self._mirrorRes is None: self._mirrorRes = self.frameBufferSize mirrorW, mirrorH = self._mirrorRes if libovr.success(libovr.createMirrorTexture( mirrorW, mirrorH, mirrorOptions=RIFT_MIRROR_MODES[self._mirrorMode])): logging.info( 'Created mirror texture with dimensions {w} x {h}'.format( w=mirrorW, h=mirrorH)) else: _, msg = libovr.getLastErrorInfo() raise LibOVRError(msg) GL.glDisable(GL.GL_TEXTURE_2D) return True # assume the FBOs are complete for now def _resolveMSAA(self): """Resolve multisample anti-aliasing (MSAA). If MSAA is enabled, drawing operations are diverted to a special multisample render buffer. Pixel data must be 'resolved' by blitting it to the swap chain texture. If not, the texture will be blank. Notes ----- You cannot perform operations on the default FBO (at `frameBuffer`) when MSAA is enabled. Any changes will be over-written when 'flip' is called. """ # if multi-sampling is off just NOP if self._samples == 1: return # bind framebuffer GL.glBindFramebuffer(GL.GL_READ_FRAMEBUFFER, self.frameBufferMsaa) GL.glBindFramebuffer(GL.GL_DRAW_FRAMEBUFFER, self.frameBuffer) # bind the HMD swap texture to the draw buffer GL.glFramebufferTexture2D( GL.GL_DRAW_FRAMEBUFFER, GL.GL_COLOR_ATTACHMENT0, GL.GL_TEXTURE_2D, self.frameTexture, 0) # blit the texture fbo_w, fbo_h = self._swapTextureSize self.viewport = self.scissor = (0, 0, fbo_w, fbo_h) GL.glBlitFramebuffer( 0, 0, fbo_w, fbo_h, 0, 0, fbo_w, fbo_h, # flips texture GL.GL_COLOR_BUFFER_BIT, GL.GL_NEAREST) GL.glBindFramebuffer(GL.GL_FRAMEBUFFER, 0) def _prepareMonoFrame(self, clear=True): """Prepare a frame for monoscopic rendering. This is called automatically after :func:`_startHmdFrame` if monoscopic rendering is enabled. """ # bind the framebuffer, if MSAA is enabled binding the texture is # deferred until the MSAA buffer is resolved. if self._samples > 1: GL.glBindFramebuffer(GL.GL_FRAMEBUFFER, self.frameBufferMsaa) else: GL.glBindFramebuffer(GL.GL_FRAMEBUFFER, self.frameBuffer) GL.glFramebufferTexture2D( GL.GL_FRAMEBUFFER, GL.GL_COLOR_ATTACHMENT0, GL.GL_TEXTURE_2D, self.frameTexture, 0) # use the mono viewport self.buffer = 'mono' GL.glEnable(GL.GL_SCISSOR_TEST) self.viewport = self.scissor = \ libovr.getEyeRenderViewport(libovr.EYE_LEFT) # mono mode GL.glDepthMask(GL.GL_TRUE) if clear: self.setColor(self.color, colorSpace=self.colorSpace) # clear the texture to the window color GL.glClear( GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT | GL.GL_STENCIL_BUFFER_BIT ) # if self.sRGB: # GL.glDisable(GL.GL_FRAMEBUFFER_SRGB) if self._samples > 1: GL.glEnable(GL.GL_MULTISAMPLE) GL.glDisable(GL.GL_TEXTURE_2D) GL.glEnable(GL.GL_BLEND) def setBuffer(self, buffer, clear=True): """Set the active draw buffer. Warnings -------- The window.Window.size property will return the buffer's dimensions in pixels instead of the window's when `setBuffer` is set to 'left' or 'right'. Parameters ---------- buffer : str View buffer to divert successive drawing operations to, can be either 'left' or 'right'. clear : boolean Clear the color, stencil and depth buffer. """ # if monoscopic, nop if self._monoscopic: warnings.warn("`setBuffer` called in monoscopic mode.", RuntimeWarning) return # check if the buffer name is valid if buffer not in ('left', 'right'): raise RuntimeError("Invalid buffer name specified.") # bind the framebuffer, if MSAA is enabled binding the texture is # deferred until the MSAA buffer is resolved. if self._samples > 1: GL.glBindFramebuffer(GL.GL_FRAMEBUFFER, self.frameBufferMsaa) else: GL.glBindFramebuffer(GL.GL_FRAMEBUFFER, self.frameBuffer) GL.glFramebufferTexture2D( GL.GL_FRAMEBUFFER, GL.GL_COLOR_ATTACHMENT0, GL.GL_TEXTURE_2D, self.frameTexture, 0) self.buffer = buffer # set buffer string GL.glEnable(GL.GL_SCISSOR_TEST) # set the viewport and scissor rect for the buffer if buffer == 'left': self.viewport = self.scissor = libovr.getEyeRenderViewport( libovr.EYE_LEFT) elif buffer == 'right': self.viewport = self.scissor = libovr.getEyeRenderViewport( libovr.EYE_RIGHT) if clear: self.setColor(self.color, colorSpace=self.colorSpace) # clear the texture to the window color GL.glClearDepth(1.0) GL.glDepthMask(GL.GL_TRUE) GL.glClear( GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT | GL.GL_STENCIL_BUFFER_BIT) # if self.sRGB: # GL.glDisable(GL.GL_FRAMEBUFFER_SRGB) if self._samples > 1: GL.glEnable(GL.GL_MULTISAMPLE) GL.glDisable(GL.GL_TEXTURE_2D) GL.glEnable(GL.GL_BLEND) def getPredictedDisplayTime(self): """Get the predicted time the next frame will be displayed on the HMD. The returned time is referenced to the clock `LibOVR` is using. Returns ------- float Absolute frame mid-point time for the given frame index in seconds. """ return libovr.getPredictedDisplayTime(self._frameIndex) def getTimeInSeconds(self): """Absolute time in seconds. The returned time is referenced to the clock `LibOVR` is using. Returns ------- float Time in seconds. """ return libovr.timeInSeconds() @property def viewMatrix(self): """The view matrix for the current eye buffer. Only valid after a :py:meth:`calcEyePoses` call. Note that setting `viewMatrix` manually will break visibility culling. """ if not self._monoscopic: if self.buffer == 'left': return self._viewMatrix[libovr.EYE_LEFT] elif self.buffer == 'right': return self._viewMatrix[libovr.EYE_RIGHT] else: return self._viewMatrix @property def nearClip(self): """Distance to the near clipping plane in meters.""" return self._nearClip @nearClip.setter def nearClip(self, value): self._nearClip = value self._updateProjectionMatrix() @property def farClip(self): """Distance to the far clipping plane in meters.""" return self._farClip @farClip.setter def farClip(self, value): self._farClip = value self._updateProjectionMatrix() @property def projectionMatrix(self): """Get the projection matrix for the current eye buffer. Note that setting `projectionMatrix` manually will break visibility culling. """ if not self._monoscopic: if self.buffer == 'left': return self._projectionMatrix[libovr.EYE_LEFT] elif self.buffer == 'right': return self._projectionMatrix[libovr.EYE_RIGHT] else: return self._projectionMatrix @property def isBoundaryVisible(self): """True if the VR boundary is visible. """ result, isVisible = libovr.getBoundaryVisible() return bool(isVisible) def getBoundaryDimensions(self, boundaryType='PlayArea'): """Get boundary dimensions. Parameters ---------- boundaryType : str Boundary type, can be 'PlayArea' or 'Outer'. Returns ------- ndarray Dimensions of the boundary meters [x, y, z]. """ result, dims = libovr.getBoundaryDimensions( RIFT_BOUNDARY_TYPE[boundaryType]) return dims @property def connectedControllers(self): """Connected controller types (`list` of `str`)""" controllers = libovr.getConnectedControllerTypes() ctrlKeys = {val: key for key, val in RIFT_CONTROLLER_TYPES.items()} return [ctrlKeys[ctrl] for ctrl in controllers] def updateInputState(self, controllers=None): """Update all connected controller states. This updates controller input states for an input device managed by `LibOVR`. The polling time for each device is accessible through the `controllerPollTimes` attribute. This attribute returns a dictionary where the polling time from the last `updateInputState` call for a given controller can be retrieved by using the name as a key. Parameters ---------- controllers : tuple or list, optional List of controllers to poll. If `None`, all available controllers will be polled. Examples -------- Poll the state of specific controllers by name:: controllers = ['XBox', 'Touch'] updateInputState(controllers) """ if controllers is None: toPoll = libovr.getConnectedControllerTypes() elif isinstance(controllers, (list, tuple,)): toPoll = [RIFT_CONTROLLER_TYPES[ctrl] for ctrl in controllers] else: raise TypeError("Argument 'controllers' must be iterable type.") for i in toPoll: result, t_sec = libovr.updateInputState(i) self.controllerPollTimes[RIFT_CONTROLLER_TYPES[i]] = t_sec def _waitToBeginHmdFrame(self): """Wait until the HMD surfaces are available for rendering. """ # First time this function is called, make True. if not self._allowHmdRendering: self._allowHmdRendering = True # update session status result, status = libovr.getSessionStatus() self._sessionStatus = status # get performance stats for the last frame self._updatePerfStats() # Wait for the buffer to be freed by the compositor, this is like # waiting for v-sync. libovr.waitToBeginFrame(self._frameIndex) # update input states if self.autoUpdateInput: self.updateInputState() #if result == ovr.SUCCESS_NOT_VISIBLE: # pass #self.updateInputState() # poll controller states # # update the tracking state # if self.autoUpdatePoses: # # get the current frame time # absTime = libovr.getPredictedDisplayTime(self._frameIndex) # # Get the current tracking state structure, estimated poses for the # # head and hands are stored here. The latency marker for computing # # motion-to-photon latency is set when this function is called. # self.calcEyePoses() def _startHmdFrame(self): """Prepare to render an HMD frame. This must be called every frame before flipping or setting the view buffer. This function will wait until the HMD is ready to begin rendering before continuing. The current frame texture from the swap chain are pulled from the SDK and made available for binding. """ # begin frame libovr.beginFrame(self._frameIndex) # get the next available buffer texture in the swap chain result, swapChainIdx = libovr.getTextureSwapChainCurrentIndex( libovr.TEXTURE_SWAP_CHAIN0) result, colorTextureId = libovr.getTextureSwapChainBufferGL( libovr.TEXTURE_SWAP_CHAIN0, swapChainIdx) self.frameTexture = colorTextureId # If mono mode, we want to configure the render framebuffer at this # point since 'setBuffer' will not be called. if self._monoscopic: self._prepareMonoFrame() def _startOfFlip(self): """Custom :py:class:`~Rift._startOfFlip` for HMD rendering. This finalizes the HMD texture before diverting drawing operations back to the on-screen window. This allows :py:class:`~Rift.flip` to swap the on-screen and HMD buffers when called. This function always returns `True`. Returns ------- True """ # Switch off multi-sampling GL.glDisable(GL.GL_MULTISAMPLE) if self._allowHmdRendering: # resolve MSAA buffers self._resolveMSAA() # commit current texture buffer to the swap chain libovr.commitTextureSwapChain(libovr.TEXTURE_SWAP_CHAIN0) # Call end_frame and increment the frame index, no more rendering to # HMD's view texture at this point. result, _ = libovr.endFrame(self._frameIndex) if libovr.failure(result): if result == libovr.ERROR_DISPLAY_LOST: # display lost! libovr.destroyMirrorTexture() libovr.destroyTextureSwapChain(libovr.TEXTURE_SWAP_CHAIN0) libovr.destroy() #libovr.shutdown() # avoid error _, msg = libovr.getLastErrorInfo() raise LibOVRError(msg) self._frameIndex += 1 # increment frame index # Set to None so the 'size' attribute returns the on-screen window size. self.buffer = None # Make sure this is called after flipping, this updates VR information # and diverts rendering to the HMD texture. #self.callOnFlip(self._waitToBeginHmdFrame) # Call frame timing routines #self.callOnFlip(self._updatePerformanceStats) # This always returns True return True def flip(self, clearBuffer=True, drawMirror=True): """Submit view buffer images to the HMD's compositor for display at next V-SYNC and draw the mirror texture to the on-screen window. This must be called every frame. Parameters ---------- clearBuffer : bool Clear the frame after flipping. drawMirror : bool Draw the HMD mirror texture from the compositor to the window. Returns ------- float Absolute time in seconds when control was given back to the application. The difference between the current and previous values should be very close to 1 / refreshRate of the HMD. Notes ----- * The HMD compositor and application are asynchronous, therefore there is no guarantee that the timestamp returned by 'flip' corresponds to the exact vertical retrace time of the HMD. """ # NOTE: Most of this code is shared with the regular Window's flip # function for compatibility. We're only concerned with calling the # _startOfFlip function and drawing the mirror texture to the onscreen # window. Display timing functions are kept in for now, but they are not # active. # flipThisFrame = self._startOfFlip() if flipThisFrame: self._prepareFBOrender() # need blit the framebuffer object to the actual back buffer result, mirrorTexId = libovr.getMirrorTexture() if libovr.failure(result): _, msg = libovr.getLastErrorInfo() raise LibOVRError(msg) # unbind the framebuffer as the render target GL.glBindFramebufferEXT(GL.GL_FRAMEBUFFER_EXT, 0) GL.glDisable(GL.GL_BLEND) stencilOn = GL.glIsEnabled(GL.GL_STENCIL_TEST) GL.glDisable(GL.GL_STENCIL_TEST) win_w, win_h = self.frameBufferSize self.viewport = self.scissor = (0, 0, win_w, win_h) # draw the mirror texture, if not anything drawn to the backbuffer # will be displayed instead if drawMirror: # blit mirror texture GL.glBindFramebuffer(GL.GL_READ_FRAMEBUFFER, self._mirrorFbo) GL.glBindFramebuffer(GL.GL_DRAW_FRAMEBUFFER, 0) GL.glEnable(GL.GL_FRAMEBUFFER_SRGB) # bind the rift's texture to the framebuffer GL.glFramebufferTexture2D( GL.GL_READ_FRAMEBUFFER, GL.GL_COLOR_ATTACHMENT0, GL.GL_TEXTURE_2D, mirrorTexId, 0) win_w, win_h = self.frameBufferSize tex_w, tex_h = self._mirrorRes self.viewport = self.scissor = (0, 0, win_w, win_h) GL.glClearColor(0.0, 0.0, 0.0, 1.0) GL.glClear(GL.GL_COLOR_BUFFER_BIT) GL.glBlitFramebuffer(0, 0, tex_w, tex_h, 0, win_h, win_w, 0, # flips texture GL.GL_COLOR_BUFFER_BIT, GL.GL_LINEAR) GL.glDisable(GL.GL_FRAMEBUFFER_SRGB) GL.glBindFramebuffer(GL.GL_FRAMEBUFFER, 0) self._finishFBOrender() # call this before flip() whether FBO was used or not self._afterFBOrender() # flip the mirror window self.backend.swapBuffers(flipThisFrame) if flipThisFrame: # set rendering back to the framebuffer object GL.glBindFramebuffer(GL.GL_FRAMEBUFFER, 0) #GL.glReadBuffer(GL.GL_BACK) #GL.glDrawBuffer(GL.GL_BACK) GL.glClearColor(0.0, 0.0, 0.0, 1.0) GL.glClear(GL.GL_COLOR_BUFFER_BIT) # set to no active rendering texture GL.glActiveTexture(GL.GL_TEXTURE0) GL.glBindTexture(GL.GL_TEXTURE_2D, 0) if stencilOn: GL.glEnable(GL.GL_STENCIL_TEST) # reset returned buffer for next frame self._endOfFlip(clearBuffer) # wait until surfaces are available for drawing self._waitToBeginHmdFrame() # get timestamp at the point control is handed back to the application now = logging.defaultClock.getTime() # run other functions immediately after flip completes for callEntry in self._toCall: callEntry['function'](*callEntry['args'], **callEntry['kwargs']) del self._toCall[:] # do bookkeeping if self.recordFrameIntervals: self.frames += 1 deltaT = now - self.lastFrameT self.lastFrameT = now if self.recordFrameIntervalsJustTurnedOn: # don't do anything self.recordFrameIntervalsJustTurnedOn = False else: # past the first frame since turned on self.frameIntervals.append(deltaT) if deltaT > self.refreshThreshold: self.nDroppedFrames += 1 if self.nDroppedFrames < reportNDroppedFrames: txt = 't of last frame was %.2fms (=1/%i)' msg = txt % (deltaT * 1000, 1 / deltaT) logging.warning(msg, t=now) elif self.nDroppedFrames == reportNDroppedFrames: logging.warning("Multiple dropped frames have " "occurred - I'll stop bothering you " "about them!") # log events for logEntry in self._toLog: # {'msg':msg, 'level':level, 'obj':copy.copy(obj)} logging.log(msg=logEntry['msg'], level=logEntry['level'], t=now, obj=logEntry['obj']) del self._toLog[:] # keep the system awake (prevent screen-saver or sleep) platform_specific.sendStayAwake() return now def multiplyViewMatrixGL(self): """Multiply the local eye pose transformation modelMatrix obtained from the SDK using ``glMultMatrixf``. The modelMatrix used depends on the current eye buffer set by :func:`setBuffer`. Returns ------- None """ if not self._legacyOpenGL: return if not self._monoscopic: if self.buffer == 'left': GL.glMultTransposeMatrixf( self._viewMatrix[0].flatten().ctypes.data_as( ctypes.POINTER(ctypes.c_float))) elif self.buffer == 'right': GL.glMultTransposeMatrixf( self._viewMatrix[1].flatten().ctypes.data_as( ctypes.POINTER(ctypes.c_float))) else: GL.glMultTransposeMatrixf(self._viewMatrix.ctypes.data_as( ctypes.POINTER(ctypes.c_float))) def multiplyProjectionMatrixGL(self): """Multiply the current projection modelMatrix obtained from the SDK using ``glMultMatrixf``. The projection matrix used depends on the current eye buffer set by :func:`setBuffer`. """ if not self._legacyOpenGL: return if not self._monoscopic: if self.buffer == 'left': GL.glMultTransposeMatrixf( self._projectionMatrix[0].flatten().ctypes.data_as( ctypes.POINTER(ctypes.c_float))) elif self.buffer == 'right': GL.glMultTransposeMatrixf( self._projectionMatrix[1].flatten().ctypes.data_as( ctypes.POINTER(ctypes.c_float))) else: GL.glMultTransposeMatrixf( self._projectionMatrix.flatten().ctypes.data_as( ctypes.POINTER(ctypes.c_float))) def setRiftView(self, clearDepth=True): """Set head-mounted display view. Gets the projection and view matrices from the HMD and applies them. Note: This only has an effect if using Rift in legacy immediate mode OpenGL. Parameters ---------- clearDepth : bool Clear the depth buffer prior after configuring the view parameters. """ if self._legacyOpenGL: GL.glMatrixMode(GL.GL_PROJECTION) GL.glLoadIdentity() self.multiplyProjectionMatrixGL() GL.glMatrixMode(GL.GL_MODELVIEW) GL.glLoadIdentity() self.multiplyViewMatrixGL() if clearDepth: GL.glClear(GL.GL_DEPTH_BUFFER_BIT) def setDefaultView(self, clearDepth=True): """Return to default projection. Call this before drawing PsychoPy's 2D stimuli after a stereo projection change. Note: This only has an effect if using Rift in legacy immediate mode OpenGL. Parameters ---------- clearDepth : bool Clear the depth buffer prior after configuring the view parameters. """ if self._legacyOpenGL: GL.glMatrixMode(GL.GL_PROJECTION) GL.glLoadIdentity() GL.glOrtho(-1, 1, -1, 1, -1, 1) GL.glMatrixMode(GL.GL_MODELVIEW) GL.glLoadIdentity() if clearDepth: GL.glClear(GL.GL_DEPTH_BUFFER_BIT) def _updateProjectionMatrix(self): """Update or re-calculate projection matrices based on the current render descriptor configuration. """ if not self._monoscopic: libovr.getEyeProjectionMatrix( libovr.EYE_LEFT, self._projectionMatrix[0]) libovr.getEyeProjectionMatrix( libovr.EYE_RIGHT, self._projectionMatrix[1]) else: libovr.getEyeProjectionMatrix( libovr.EYE_LEFT, self._projectionMatrix) def getMovieFrame(self, buffer='mirror'): """Capture the current HMD frame as an image. Saves to stack for :py:attr:`~Window.saveMovieFrames()`. As of v1.81.00 this also returns the frame as a PIL image. This can be done at any time (usually after a :py:attr:`~Window.flip()` command). Frames are stored in memory until a :py:attr:`~Window.saveMovieFrames()` command is issued. You can issue :py:attr:`~Window.getMovieFrame()` as often as you like and then save them all in one go when finished. For HMD frames, you should call `getMovieFrame` after calling `flip` to ensure that the mirror texture saved reflects what is presently being shown on the HMD. Note, that this function is somewhat slow and may impact performance. Only call this function when you're not collecting experimental data. Parameters ---------- buffer : str, optional Buffer to capture. For the HMD, only 'mirror' is available at this time. Returns ------- Image Buffer pixel contents as a PIL/Pillow image object. """ im = self._getFrame(buffer=buffer) self.movieFrames.append(im) return im def _getFrame(self, rect=None, buffer='mirror'): """Return the current HMD view as an image. Parameters ---------- rect : array_like Rectangle [x, y, w, h] defining a sub-region of the frame to capture. This should remain `None` for HMD frames. buffer : str, optional Buffer to capture. For the HMD, only 'mirror' is available at this time. Returns ------- Image Buffer pixel contents as a PIL/Pillow image object. """ if buffer == 'mirror': result, mirrorTexId = libovr.getMirrorTexture() if libovr.failure(result): _, msg = libovr.getLastErrorInfo() raise LibOVRError(msg) GL.glBindFramebuffer(GL.GL_FRAMEBUFFER, self._mirrorFbo) # GL.glEnable(GL.GL_FRAMEBUFFER_SRGB) # bind the rift's texture to the framebuffer GL.glFramebufferTexture2D( GL.GL_READ_FRAMEBUFFER, GL.GL_COLOR_ATTACHMENT0, GL.GL_TEXTURE_2D, mirrorTexId, 0) else: raise ValueError("Requested read from buffer '{}' but should be " "'mirror'.".format(buffer)) if rect: x, y = self._mirrorRes # box corners in pix left = int((rect[0] / 2. + 0.5) * x) top = int((rect[1] / -2. + 0.5) * y) w = int((rect[2] / 2. + 0.5) * x) - left h = int((rect[3] / -2. + 0.5) * y) - top else: left = top = 0 w, h = self.size # of window, not image # http://www.opengl.org/sdk/docs/man/xhtml/glGetTexImage.xml bufferDat = (GL.GLubyte * (4 * w * h))() GL.glReadPixels(left, top, w, h, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, bufferDat) try: im = Image.fromstring(mode='RGBA', size=(w, h), data=bufferDat) except Exception: im = Image.frombytes(mode='RGBA', size=(w, h), data=bufferDat) im = im.transpose(Image.FLIP_TOP_BOTTOM) im = im.convert('RGB') if self.buffer is not None: self.setBuffer(self.buffer, clear=False) # go back to previous buffer else: GL.glBindFramebufferEXT(GL.GL_FRAMEBUFFER_EXT, self.frameBuffer) return im def getThumbstickValues(self, controller='Xbox', deadzone=False): """Get controller thumbstick values. Parameters ---------- controller : str Name of the controller to get thumbstick values. Possible values for `controller` are 'Xbox', 'Touch', 'RTouch', 'LTouch', 'Object0', 'Object1', 'Object2', and 'Object3'; the only devices with thumbsticks the SDK manages. For additional controllers, use PsychPy's built-in event or hardware support. deadzone : bool Apply the deadzone to thumbstick values. This pre-filters stick input to apply a dead-zone where 0.0 will be returned if the sticks return a displacement within -0.2746 to 0.2746. Returns ------- tuple Left and right, X and Y thumbstick values. Axis displacements are represented in each tuple by floats ranging from -1.0 (full left/down) to 1.0 (full right/up). The returned values reflect the controller state since the last :py:class:`~Rift.updateInputState` or :py:class:`~Rift.flip` call. """ return libovr.getThumbstickValues(RIFT_CONTROLLER_TYPES[controller], deadzone) def getIndexTriggerValues(self, controller='Xbox', deadzone=False): """Get the values of the index triggers. Parameters ---------- controller : str Name of the controller to get index trigger values. Possible values for `controller` are 'Xbox', 'Touch', 'RTouch', 'LTouch', 'Object0', 'Object1', 'Object2', and 'Object3'; the only devices with index triggers the SDK manages. For additional controllers, use PsychPy's built-in event or hardware support. deadzone : bool Apply the deadzone to index trigger values. This pre-filters stick input to apply a dead-zone where 0.0 will be returned if the trigger returns a displacement within 0.2746. Returns ------- tuple of float Left and right index trigger values. Displacements are represented as `tuple` of two float representing the left anr right displacement values, which range from 0.0 to 1.0. The returned values reflect the controller state since the last :py:class:`~Rift.updateInputState` or :py:class:`~Rift.flip` call. """ return libovr.getIndexTriggerValues(RIFT_CONTROLLER_TYPES[controller], deadzone) def getHandTriggerValues(self, controller='Touch', deadzone=False): """Get the values of the hand triggers. Parameters ---------- controller : str Name of the controller to get hand trigger values. Possible values for `controller` are 'Touch', 'RTouch', 'LTouch', 'Object0', 'Object1', 'Object2', and 'Object3'; the only devices with hand triggers the SDK manages. For additional controllers, use PsychPy's built-in event or hardware support. deadzone : bool Apply the deadzone to hand trigger values. This pre-filters stick input to apply a dead-zone where 0.0 will be returned if the trigger returns a displacement within 0.2746. Returns ------- tuple Left and right hand trigger values. Displacements are represented as `tuple` of two float representing the left anr right displacement values, which range from 0.0 to 1.0. The returned values reflect the controller state since the last :py:class:`~Rift.updateInputState` or :py:class:`~Rift.flip` call. """ return libovr.getHandTriggerValues(RIFT_CONTROLLER_TYPES[controller], deadzone) def getButtons(self, buttons, controller='Xbox', testState='continuous'): """Get button states from a controller. Returns `True` if any names specified to `buttons` reflect `testState` since the last :py:class:`~Rift.updateInputState` or :py:class:`~Rift.flip` call. If multiple button names are specified as a `list` or `tuple` to `buttons`, multiple button states are tested, returning `True` if all the buttons presently satisfy the `testState`. Note that not all controllers available share the same buttons. If a button is not available, this function will always return `False`. Parameters ---------- buttons : `list` of `str` or `str` Buttons to test. Valid `buttons` names are 'A', 'B', 'RThumb', 'RShoulder' 'X', 'Y', 'LThumb', 'LShoulder', 'Up', 'Down', 'Left', 'Right', 'Enter', 'Back', 'VolUp', 'VolDown', and 'Home'. Names can be passed as a `list` to test multiple button states. controller : `str` Controller name. testState : `str` State to test. Valid values are: * **continuous** - Button is presently being held down. * **rising** or **pressed** - Button has been *pressed* since the last update. * **falling** or **released** - Button has been *released* since the last update. Returns ------- tuple of bool, float Button state and timestamp in seconds the controller was polled. Examples -------- Check if the 'Enter' button on the Oculus remote was released:: isPressed, tsec = hmd.getButtons(['Enter'], 'Remote', 'falling') Check if the 'A' button was pressed on the touch controller:: isPressed, tsec = hmd.getButtons(['A'], 'Touch', 'pressed') """ if isinstance(buttons, str): # single value return libovr.getButton( RIFT_CONTROLLER_TYPES[controller], RIFT_BUTTON_TYPES[buttons], testState) elif isinstance(buttons, (list, tuple,)): # combine buttons buttonBits = 0x00000000 for buttonName in buttons: buttonBits |= RIFT_BUTTON_TYPES[buttonName] return libovr.getButton( RIFT_CONTROLLER_TYPES[controller], buttonBits, testState) elif isinstance(buttons, int): # using enums directly return libovr.getButton( RIFT_CONTROLLER_TYPES[controller], buttons, testState) else: raise ValueError("Invalid 'buttons' specified.") def getTouches(self, touches, controller='Touch', testState='continuous'): """Get touch states from a controller. Returns `True` if any names specified to `touches` reflect `testState` since the last :py:class:`~Rift.updateInputState` or :py:class:`~Rift.flip` call. If multiple button names are specified as a `list` or `tuple` to `touches`, multiple button states are tested, returning `True` if all the touches presently satisfy the `testState`. Note that not all controllers available support touches. If a touch is not supported or available, this function will always return `False`. Special states can be used for basic gesture recognition, such as 'LThumbUp', 'RThumbUp', 'LIndexPointing', and 'RIndexPointing'. Parameters ---------- touches : `list` of `str` or `str` Buttons to test. Valid `touches` names are 'A', 'B', 'RThumb', 'RThumbRest' 'RThumbUp', 'RIndexPointing', 'LThumb', 'LThumbRest', 'LThumbUp', 'LIndexPointing', 'X', and 'Y'. Names can be passed as a `list` to test multiple button states. controller : `str` Controller name. testState : `str` State to test. Valid values are: * **continuous** - User is touching something on the controller. * **rising** or **pressed** - User began touching something since the last call to `updateInputState`. * **falling** or **released** - User stopped touching something since the last call to `updateInputState`. Returns ------- tuple of bool, float Touch state and timestamp in seconds the controller was polled. Examples -------- Check if the 'Enter' button on the Oculus remote was released:: isPressed, tsec = hmd.getButtons(['Enter'], 'Remote', 'falling') Check if the 'A' button was pressed on the touch controller:: isPressed, tsec = hmd.getButtons(['A'], 'Touch', 'pressed') """ if isinstance(touches, str): # single value return libovr.getTouch( RIFT_CONTROLLER_TYPES[controller], RIFT_TOUCH_TYPES[touches], testState) elif isinstance(touches, (list, tuple,)): # combine buttons touchBits = 0x00000000 for buttonName in touches: touchBits |= RIFT_TOUCH_TYPES[buttonName] return libovr.getTouch( RIFT_CONTROLLER_TYPES[controller], touchBits, testState) elif isinstance(touches, int): # using enums directly return libovr.getTouch( RIFT_CONTROLLER_TYPES[controller], touches, testState) else: raise ValueError("Invalid 'touches' specified.") def startHaptics(self, controller, frequency='low', amplitude=1.0): """Start haptic feedback (vibration). Vibration is constant at fixed frequency and amplitude. Vibration lasts 2.5 seconds, so this function needs to be called more often than that for sustained vibration. Only controllers which support vibration can be used here. There are only two frequencies permitted 'high' and 'low', however, amplitude can vary from 0.0 to 1.0. Specifying `frequency`='off' stops vibration if in progress. Parameters ---------- controller : str Name of the controller to vibrate. frequency : str Vibration frequency. Valid values are: 'off', 'low', or 'high'. amplitude : float Vibration amplitude in the range of [0.0 and 1.0]. Values outside this range are clamped. """ libovr.setControllerVibration( RIFT_CONTROLLER_TYPES[controller], frequency, amplitude) def stopHaptics(self, controller): """Stop haptic feedback. Convenience function to stop controller vibration initiated by the last :py:class:`~Rift.vibrateController` call. This is the same as calling ``vibrateController(controller, frequency='off')``. Parameters ---------- controller : str Name of the controller to stop vibrating. """ libovr.setControllerVibration( RIFT_CONTROLLER_TYPES[controller], 'off', 0.0) @staticmethod def createHapticsBuffer(samples): """Create a new haptics buffer. A haptics buffer is object which stores vibration amplitude samples for playback through the Touch controllers. To play a haptics buffer, pass it to :py:meth:`submitHapticsBuffer`. Parameters ---------- samples : array_like 1-D array of amplitude samples, ranging from 0 to 1. Values outside of this range will be clipped. The buffer must not exceed `HAPTICS_BUFFER_SAMPLES_MAX` samples, any additional samples will be dropped. Returns ------- LibOVRHapticsBuffer Haptics buffer object. Notes ----- Methods `startHaptics` and `stopHaptics` cannot be used interchangeably with this function. Examples -------- Create a haptics buffer where vibration amplitude ramps down over the course of playback:: samples = np.linspace( 1.0, 0.0, num=HAPTICS_BUFFER_SAMPLES_MAX-1, dtype=np.float32) hbuff = Rift.createHapticsBuffer(samples) # vibrate right Touch controller hmd.submitControllerVibration(CONTROLLER_TYPE_RTOUCH, hbuff) """ if len(samples) > libovr.HAPTICS_BUFFER_SAMPLES_MAX: samples = samples[:libovr.HAPTICS_BUFFER_SAMPLES_MAX] return libovr.LibOVRHapticsBuffer(samples) def submitControllerVibration(self, controller, hapticsBuffer): """Submit a haptics buffer to begin controller vibration. Parameters ---------- controller : str Name of controller to vibrate. hapticsBuffer : LibOVRHapticsBuffer Haptics buffer to playback. Notes ----- Methods `startHaptics` and `stopHaptics` cannot be used interchangeably with this function. """ libovr.submitControllerVibration( RIFT_CONTROLLER_TYPES[controller], hapticsBuffer) @staticmethod def createPose(pos=(0., 0., 0.), ori=(0., 0., 0., 1.)): """Create a new Rift pose object (:py:class:`~psychxr.libovr.LibOVRPose`). :py:class:`~psychxr.libovr.LibOVRPose` is used to represent a rigid body pose mainly for use with the PsychXR's LibOVR module. There are several methods associated with the object to manipulate the pose. This function exposes the :py:class:`~psychxr.libovr.LibOVRPose` class so you don't need to access it by importing `psychxr`. Parameters ---------- pos : tuple, list, or ndarray of float Position vector/coordinate (x, y, z). ori : tuple, list, or ndarray of float Orientation quaternion (x, y, z, w). Returns ------- :py:class:`~psychxr.libovr.LibOVRPose` Object representing a rigid body pose for use with LibOVR. """ return libovr.LibOVRPose(pos, ori) @staticmethod def createBoundingBox(extents=None): """Create a new bounding box object (:py:class:`~psychxr.libovr.LibOVRBounds`). :py:class:`~psychxr.libovr.LibOVRBounds` represents an axis-aligned bounding box with dimensions defined by `extents`. Bounding boxes are primarily used for visibility testing and culling by `PsychXR`. The dimensions of the bounding box can be specified explicitly, or fitted to meshes by passing vertices to the :py:meth:`~psychxr.libovr.LibOVRBounds.fit` method after initialization. This function exposes the :py:class:`~psychxr.libovr.LibOVRBounds` class so you don't need to access it by importing `psychxr`. Parameters ---------- extents : array_like or None Extents of the bounding box as (`mins`, `maxs`). Where `mins` (x, y, z) is the minimum and `maxs` (x, y, z) is the maximum extents of the bounding box in world units. If `None` is specified, the returned bounding box will be invalid. The bounding box can be later constructed using the :py:meth:`~psychxr.libovr.LibOVRBounds.fit` method or the :py:attr:`~psychxr.libovr.LibOVRBounds.extents` attribute. Returns ------- `~psychxr.libovr.LibOVRBounds` Object representing a bounding box. Examples -------- Add a bounding box to a pose:: # create a 1 meter cube bounding box centered with the pose bbox = Rift.createBoundingBox(((-.5, -.5, -.5), (.5, .5, .5))) # create a pose and attach the bounding box modelPose = Rift.createPose() modelPose.boundingBox = bbox Perform visibility culling on the pose using the bounding box by using the :py:meth:`~psychxr.libovr.LibOVRBounds.isVisible` method:: if hmd.isPoseVisible(modelPose): modelPose.draw() """ return libovr.LibOVRBounds(extents) def isPoseVisible(self, pose): """Check if a pose object if visible to the present eye. This method can be used to perform visibility culling to avoid executing draw commands for objects that fall outside the FOV for the current eye buffer. If :py:attr:`~psychxr.libovr.LibOVRPose.boundingBox` has a valid bounding box object, this function will return `False` if all the box points fall completely to one side of the view frustum. If :py:attr:`~psychxr.libovr.LibOVRPose.boundingBox` is `None`, the point at :py:attr:`~psychxr.libovr.LibOVRPose.pos` is checked, returning `False` if it falls outside of the frustum. If the present buffer is not 'left' or 'right', this function will always return `False`. Parameters ---------- pose : :py:class:`~psychxr.libovr.LibOVRPose` Pose to test for visibility. Returns ------- bool `True` if pose's bounding box or origin is outside of the view frustum. """ if self.buffer == 'left' or self.buffer == 'mono': return pose.isVisible(libovr.EYE_LEFT) elif self.buffer == 'right': return pose.isVisible(libovr.EYE_RIGHT) return False def _updatePerfStats(self): """Update and process performance statistics obtained from LibOVR. This should be called at the beginning of each frame to get the stats of the last frame. This is called automatically when :py:meth:`~psychopy.visual.Rift._waitToBeginHmdFrame` is called at the beginning of each frame. """ # update perf stats self._perfStats = libovr.getPerfStats() # if we have more >1 stat available, process the stats if self._perfStats.frameStatsCount > 0: recentStat = self._perfStats.frameStats[0] # get the most recent # check for dropped frames since last call if self.warnAppFrameDropped and \ reportNDroppedFrames > self._lastAppDroppedFrameCount: appDroppedFrameCount = recentStat.appDroppedFrameCount if appDroppedFrameCount > self._lastAppDroppedFrameCount: logging.warn( 'Application failed to meet deadline to submit frame ' 'to HMD ({}).'.format(self._frameIndex)) self._lastAppDroppedFrameCount = appDroppedFrameCount if reportNDroppedFrames == self._lastAppDroppedFrameCount: logging.warn( "Maximum number of dropped frames detected. I'll stop " "warning you about them.") # def _logCallback(level, msg): # """Callback function for log messages generated by LibOVR.""" # if level == libovr.LOG_LEVEL_INFO: # logging.info(msg) # elif level == libovr.LOG_LEVEL_DEBUG: # logging.debug(msg) # elif level == libovr.LOG_LEVEL_ERROR: # logging.error(msg)
99,809
Python
.py
2,171
35.10456
106
0.617539
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,733
pie.py
psychopy_psychopy/psychopy/visual/pie.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Create a pie shape.""" # 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.visual.shape import BaseShapeStim from psychopy.tools.attributetools import attributeSetter, setAttribute import numpy as np class Pie(BaseShapeStim): """Creates a pie shape which is a circle with a wedge cut-out. This is a lazy-imported class, therefore import using full path `from psychopy.visual.pie import Pie` when inheriting from it. This shape is sometimes referred to as a Pac-Man shape which is often used for creating Kanizsa figures. However, the shape can be adapted for other uses. Parameters ---------- win : :class:`~psychopy.visual.Window` Window this shape is being drawn to. The stimulus instance will allocate its required resources using that Windows context. In many cases, a stimulus instance cannot be drawn on different windows unless those windows share the same OpenGL context, which permits resources to be shared between them. radius : float or int Radius of the shape. Avoid using `size` for adjusting figure dimensions if radius != 0.5 which will result in undefined behavior. start, end : float or int Start and end angles of the filled region of the shape in degrees. Shapes are filled counter clockwise between the specified angles. edges : int Number of edges to use when drawing the figure. A greater number of edges will result in smoother curves, but will require more time to compute. units : str Units to use when drawing. This will affect how parameters and attributes `pos`, `size` and `radius` are interpreted. lineWidth : float Width of the shape's outline. lineColor, fillColor : array_like, str, :class:`~psychopy.colors.Color` or None Color of the shape outline and fill. If `None`, a fully transparent color is used which makes the fill or outline invisible. lineColorSpace, fillColorSpace : str Colorspace to use for the outline and fill. These change how the values passed to `lineColor` and `fillColor` are interpreted. *Deprecated*. Please use `colorSpace` to set both outline and fill colorspace. These arguments may be removed in a future version. pos : array_like Initial position (`x`, `y`) of the shape on-screen relative to the origin located at the center of the window or buffer in `units`. This can be updated after initialization by setting the `pos` property. The default value is `(0.0, 0.0)` which results in no translation. size : array_like, float, int or None Width and height of the shape as `(w, h)` or `[w, h]`. If a single value is provided, the width and height will be set to the same specified value. If `None` is specified, the `size` will be set with values passed to `width` and `height`. ori : float Initial orientation of the shape in degrees about its origin. Positive values will rotate the shape clockwise, while negative values will rotate counterclockwise. The default value for `ori` is 0.0 degrees. opacity : float Opacity of the shape. A value of 1.0 indicates fully opaque and 0.0 is fully transparent (therefore invisible). Values between 1.0 and 0.0 will result in colors being blended with objects in the background. This value affects the fill (`fillColor`) and outline (`lineColor`) colors of the shape. contrast : float Contrast level of the shape (0.0 to 1.0). This value is used to modulate the contrast of colors passed to `lineColor` and `fillColor`. depth : int Depth layer to draw the shape when `autoDraw` is enabled. *DEPRECATED* interpolate : bool Enable smoothing (anti-aliasing) when drawing shape outlines. This produces a smoother (less-pixelated) outline of the shape. lineRGB, fillRGB: array_like, :class:`~psychopy.colors.Color` or None *Deprecated*. Please use `lineColor` and `fillColor`. These arguments may be removed in a future version. name : str Optional name of the stimuli for logging. autoLog : bool Enable auto-logging of events associated with this stimuli. Useful for debugging and to track timing when used in conjunction with `autoDraw`. autoDraw : bool Enable auto drawing. When `True`, the stimulus will be drawn every frame without the need to explicitly call the :py:meth:`~psychopy.visual.shape.ShapeStim.draw()` method. color : array_like, str, :class:`~psychopy.colors.Color` or None Sets both the initial `lineColor` and `fillColor` of the shape. colorSpace : str Sets the colorspace, changing how values passed to `lineColor` and `fillColor` are interpreted. Attributes ---------- start, end : float or int Start and end angles of the filled region of the shape in degrees. Shapes are filled counter clockwise between the specified angles. radius : float or int Radius of the shape. Avoid using `size` for adjusting figure dimensions if radius != 0.5 which will result in undefined behavior. """ _defaultFillColor = None _defaultLineColor = None def __init__(self, win, radius=.5, start=0.0, end=90.0, edges=32, units='', lineWidth=1.5, lineColor=False, fillColor=False, pos=(0, 0), size=1.0, ori=0.0, opacity=1.0, contrast=1.0, depth=0, interpolate=True, name=None, autoLog=None, autoDraw=False, colorSpace=None, # legacy color=False, fillColorSpace='rgb', lineColorSpace='rgb', lineRGB=False, fillRGB=False, ): self.__dict__['radius'] = radius self.__dict__['edges'] = edges self.__dict__['start'] = start self.__dict__['end'] = end self.vertices = self._calcVertices() super(Pie, self).__init__( win, units=units, lineWidth=lineWidth, lineColor=lineColor, lineColorSpace=lineColorSpace, fillColor=fillColor, fillColorSpace=fillColorSpace, vertices=self.vertices, closeShape=True, pos=pos, size=size, ori=ori, opacity=opacity, contrast=contrast, depth=depth, interpolate=interpolate, lineRGB=lineRGB, fillRGB=fillRGB, name=name, autoLog=autoLog, autoDraw=autoDraw, color=color, colorSpace=colorSpace) def _calcVertices(self): """Calculate the required vertices for the figure. """ startRadians = np.radians(self.start) endRadians = np.radians(self.end) # get number of steps for vertices edges = self.__dict__['edges'] steps = np.linspace(startRadians, endRadians, num=edges) # offset by 1 since the first vertex needs to be at centre verts = np.zeros((edges + 2, 2), float) verts[1:-1, 0] = np.sin(steps) verts[1:-1, 1] = np.cos(steps) verts *= self.radius return verts @attributeSetter def start(self, value): """Start angle of the slice/wedge in degrees (`float` or `int`). :ref:`Operations <attrib-operations>` supported. """ self.__dict__['start'] = value self.vertices = self._calcVertices() self.setVertices(self.vertices, log=False) def setStart(self, start, operation='', log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message """ setAttribute(self, 'start', start, log, operation) @attributeSetter def end(self, value): """End angle of the slice/wedge in degrees (`float` or `int`). :ref:`Operations <attrib-operations>` supported. """ self.__dict__['end'] = value self.vertices = self._calcVertices() self.setVertices(self.vertices, log=False) def setEnd(self, end, operation='', log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message """ setAttribute(self, 'end', end, log, operation) @attributeSetter def radius(self, value): """Radius of the shape in `units` (`float` or `int`). :ref:`Operations <attrib-operations>` supported. """ self.__dict__['radius'] = value self.vertices = self._calcVertices() self.setVertices(self.vertices, log=False) def setRadius(self, end, operation='', log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message """ setAttribute(self, 'radius', end, log, operation)
9,732
Python
.py
220
34.690909
83
0.627267
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,734
polygon.py
psychopy_psychopy/psychopy/visual/polygon.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Creates a regular polygon (triangles, pentagons, ...) as a special case of a :class:`~psychopy.visual.ShapeStim`""" # 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 psychopy # so we can get the __path__ from psychopy.visual.shape import BaseShapeStim from psychopy.tools.attributetools import attributeSetter, setAttribute import numpy as np class Polygon(BaseShapeStim): """Creates a regular polygon (triangles, pentagons, ...). This is a lazy-imported class, therefore import using full path `from psychopy.visual.polygon import Polygon` when inheriting from it. This class is a special case of a :class:`~psychopy.visual.ShapeStim` that accepts the same parameters except `closeShape` and `vertices`. Parameters ---------- win : :class:`~psychopy.visual.Window` Window this shape is being drawn to. The stimulus instance will allocate its required resources using that Windows context. In many cases, a stimulus instance cannot be drawn on different windows unless those windows share the same OpenGL context, which permits resources to be shared between them. edges : `int` Number of sides for the polygon (for instance, `edges=3` will result in a triangle). radius : float Initial radius of the polygon in `units`. This specifies how far out to place the corners (vertices) of the shape. units : str Units to use when drawing. This will affect how parameters and attributes `pos`, `size` and `radius` are interpreted. lineWidth : float Width of the polygon's outline. lineColor, fillColor : array_like, str, :class:`~psychopy.colors.Color` or `None` Color of the shape's outline and fill. If `None`, a fully transparent color is used which makes the fill or outline invisible. lineColorSpace, fillColorSpace : str Colorspace to use for the outline and fill. These change how the values passed to `lineColor` and `fillColor` are interpreted. *Deprecated*. Please use `colorSpace` to set both outline and fill colorspace. These arguments may be removed in a future version. pos : array_like Initial position (`x`, `y`) of the shape on-screen relative to the origin located at the center of the window or buffer in `units`. This can be updated after initialization by setting the `pos` property. The default value is `(0.0, 0.0)` which results in no translation. size : float or array_like Initial scale factor for adjusting the size of the shape. A single value (`float`) will apply uniform scaling, while an array (`sx`, `sy`) will result in anisotropic scaling in the horizontal (`sx`) and vertical (`sy`) direction. Providing negative values to `size` will cause the shape being mirrored. Scaling can be changed by setting the `size` property after initialization. The default value is `1.0` which results in no scaling. ori : float Initial orientation of the shape in degrees about its origin. Positive values will rotate the shape clockwise, while negative values will rotate counterclockwise. The default value for `ori` is 0.0 degrees. opacity : float Opacity of the shape. A value of 1.0 indicates fully opaque and 0.0 is fully transparent (therefore invisible). Values between 1.0 and 0.0 will result in colors being blended with objects in the background. This value affects the fill (`fillColor`) and outline (`lineColor`) colors of the shape. contrast : float Contrast level of the shape (0.0 to 1.0). This value is used to modulate the contrast of colors passed to `lineColor` and `fillColor`. depth : int Depth layer to draw the stimulus when `autoDraw` is enabled. interpolate : bool Enable smoothing (anti-aliasing) when drawing shape outlines. This produces a smoother (less-pixelated) outline of the shape. lineRGB, fillRGB: array_like, :class:`~psychopy.colors.Color` or None *Deprecated*. Please use `lineColor` and `fillColor`. These arguments may be removed in a future version. name : str Optional name of the stimuli for logging. autoLog : bool Enable auto-logging of events associated with this stimuli. Useful for debugging and to track timing when used in conjunction with `autoDraw`. autoDraw : bool Enable auto drawing. When `True`, the stimulus will be drawn every frame without the need to explicitly call the :py:meth:`~psychopy.visual.shape.ShapeStim.draw()` method. color : array_like, str, :class:`~psychopy.colors.Color` or `None` Sets both the initial `lineColor` and `fillColor` of the shape. colorSpace : str Sets the colorspace, changing how values passed to `lineColor` and `fillColor` are interpreted. draggable : bool Can this stimulus be dragged by a mouse click? """ _defaultFillColor = "white" _defaultLineColor = "white" def __init__(self, win, edges=3, radius=.5, units='', lineWidth=1.5, lineColor=False, fillColor=False, pos=(0, 0), size=1.0, anchor=None, ori=0.0, opacity=None, contrast=1.0, depth=0, interpolate=True, draggable=False, name=None, autoLog=None, autoDraw=False, colorSpace='rgb', # legacy color=False, fillColorSpace=None, lineColorSpace=None, lineRGB=False, fillRGB=False, ): # what local vars are defined (these are the init params) for use by # __repr__ self._initParams = dir() self._initParams.remove('self') self.autoLog = False # but will be changed if needed at end of init self.__dict__['edges'] = edges self.__dict__['lineWidth'] = lineWidth self.radius = np.asarray(radius) self._calcVertices() super(Polygon, self).__init__( win, units=units, lineWidth=lineWidth, lineColor=lineColor, lineColorSpace=lineColorSpace, fillColor=fillColor, fillColorSpace=fillColorSpace, vertices=self.vertices, closeShape=True, pos=pos, size=size, anchor=anchor, ori=ori, opacity=opacity, contrast=contrast, depth=depth, interpolate=interpolate, draggable=draggable, lineRGB=lineRGB, fillRGB=fillRGB, name=name, autoLog=autoLog, autoDraw=autoDraw, color=color, colorSpace=colorSpace) def _calcVertices(self): if self.edges == "circle": # If circle is requested, calculate min edges needed for it to appear smooth edges = self._calculateMinEdges(self.__dict__['lineWidth'], threshold=1) else: edges = self.edges self.vertices = self._calcEquilateralVertices(edges, self.radius) @attributeSetter def edges(self, edges): """Number of edges of the polygon. Floats are rounded to int. :ref:`Operations <attrib-operations>` supported. """ self.__dict__['edges'] = edges self._calcVertices() self.setVertices(self.vertices, log=False) def setEdges(self, edges, operation='', log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message""" setAttribute(self, 'edges', edges, log, operation) @attributeSetter def radius(self, radius): """float, int, tuple, list or 2x1 array Radius of the Polygon (distance from the center to the corners). May be a -2tuple or list to stretch the polygon asymmetrically. :ref:`Operations <attrib-operations>` supported. Usually there's a setAttribute(value, log=False) method for each attribute. Use this if you want to disable logging. """ self.__dict__['radius'] = np.array(radius) self._calcVertices() self.setVertices(self.vertices, log=False) def setRadius(self, radius, operation='', log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message """ setAttribute(self, 'radius', radius, log, operation) def setNVertices(self, nVerts, operation='', log=None): """ Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message """ setAttribute(self, 'vertices', nVerts, log, operation)
9,444
Python
.py
206
36.247573
88
0.63733
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,735
secondorder.py
psychopy_psychopy/psychopy/visual/secondorder.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. # some code provided by Andrew Schofield # Distributed under the terms of the GNU General Public License (GPL). """Stimulus object for drawing arbitrary bitmap carriers with an arbitrary second-order envelope carrier and envelope can vary independently for orientation, frequency and phase. Also does beat stimuli. These are optional components that can be obtained by installing the `psychopy-visionscience` extension into the current environment. """ from psychopy.tools.pkgtools import PluginStub class EnvelopeGrating( PluginStub, plugin="psychopy-visionscience", doclink="https://psychopy.github.io/psychopy-visionscience/coder/EnvelopeGrating" ): pass class EnvelopeGrating: """ `psychopy.visual.EnvelopeGrating` is now located within the `psychopy-visionscience` plugin. You can find the documentation for it `here <https://psychopy.github.io/psychopy-visionscience/coder/EnvelopeGrating>`_ """ if __name__ == "__main__": pass
1,143
Python
.py
27
39.407407
100
0.777174
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,736
shape.py
psychopy_psychopy/psychopy/visual/shape.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Create geometric (vector) shapes by defining vertex locations.""" # 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 copy import numpy # Ensure setting pyglet.options['debug_gl'] to False is done prior to any # other calls to pyglet or pyglet submodules, otherwise it may not get picked # up by the pyglet GL engine and have no effect. # Shaders will work but require OpenGL2.0 drivers AND PyOpenGL3.0+ import pyglet import psychopy # so we can get the __path__ from psychopy import logging from psychopy.colors import Color # tools must only be imported *after* event or MovieStim breaks on win32 # (JWP has no idea why!) # from psychopy.tools.monitorunittools import cm2pix, deg2pix from psychopy.tools.attributetools import (attributeSetter, # logAttrib, setAttribute) from psychopy.tools.arraytools import val2array from psychopy.visual.basevisual import ( BaseVisualStim, DraggingMixin, ColorMixin, ContainerMixin, WindowMixin ) # from psychopy.visual.helpers import setColor import psychopy.visual pyglet.options['debug_gl'] = False GL = pyglet.gl knownShapes = { "triangle": [ (+0.0, 0.5), # Point (-0.5, -0.5), # Bottom left (+0.5, -0.5), # Bottom right ], "rectangle": [ [-.5, .5], # Top left [ .5, .5], # Top right [ .5, -.5], # Bottom left [-.5, -.5], # Bottom right ], "circle": "circle", # Placeholder, value calculated on set based on line width "cross": [ (-0.1, +0.5), # up (+0.1, +0.5), (+0.1, +0.1), (+0.5, +0.1), # right (+0.5, -0.1), (+0.1, -0.1), (+0.1, -0.5), # down (-0.1, -0.5), (-0.1, -0.1), (-0.5, -0.1), # left (-0.5, +0.1), (-0.1, +0.1), ], "star7": [ (0.0, 0.5), (0.09, 0.18), (0.39, 0.31), (0.19, 0.04), (0.49, -0.11), (0.16, -0.12), (0.22, -0.45), (0.0, -0.2), (-0.22, -0.45), (-0.16, -0.12), (-0.49, -0.11), (-0.19, 0.04), (-0.39, 0.31), (-0.09, 0.18) ], "arrow": [ (0.0, 0.5), (-0.5, 0.0), (-1/6, 0.0), (-1/6, -0.5), (1/6, -0.5), (1/6, 0.0), (0.5, 0.0) ], } knownShapes['square'] = knownShapes['rectangle'] knownShapes['star'] = knownShapes['star7'] class BaseShapeStim(BaseVisualStim, DraggingMixin, ColorMixin, ContainerMixin): """Create geometric (vector) shapes by defining vertex locations. This is a lazy-imported class, therefore import using full path `from psychopy.visual.shape import BaseShapeStim` when inheriting from it. Shapes can be outlines or filled, set lineColor and fillColor to a color name, or None. They can also be rotated (stim.setOri(__)), translated (stim.setPos(__)), and scaled (stim.setSize(__)) like any other stimulus. BaseShapeStim is currently used by ShapeStim and Aperture (for basic shapes). It is also retained in case backwards compatibility is needed. v1.84.00: ShapeStim became BaseShapeStim. """ _defaultFillColor = None _defaultLineColor = "black" def __init__(self, win, units='', lineWidth=1.5, lineColor=False, # uses False in place of None to distinguish between "not set" and "transparent" fillColor=False, # uses False in place of None to distinguish between "not set" and "transparent" colorSpace='rgb', vertices=((-0.5, 0), (0, +0.5), (+0.5, 0)), closeShape=True, pos=(0, 0), size=1, anchor=None, ori=0.0, opacity=None, contrast=1.0, depth=0, interpolate=True, draggable=False, name=None, autoLog=None, autoDraw=False, # legacy color=False, lineRGB=False, fillRGB=False, fillColorSpace=None, lineColorSpace=None ): """ """ # all doc is in the attributes # what local vars are defined (these are the init params) for use by # __repr__ self._initParams = dir() self._initParams.remove('self') # Initialize inheritance and remove unwanted methods; autoLog is set # later super(BaseShapeStim, self).__init__(win, units=units, name=name, autoLog=False) self.draggable = draggable self.pos = pos self.closeShape = closeShape self.lineWidth = lineWidth self.interpolate = interpolate # Appearance self.colorSpace = colorSpace if fillColor is not False: self.fillColor = fillColor elif color is not False: # Override fillColor with color if not set self.fillColor = color else: # Default to None if neither are set self.fillColor = self._defaultFillColor if lineColor is not False: self.lineColor = lineColor elif color is not False: # Override lineColor with color if not set self.lineColor = color else: # Default to black if neither are set self.lineColor = self._defaultLineColor if lineRGB is not False: # Override with RGB if set logging.warning("Use of rgb arguments to stimuli are deprecated." " Please use color and colorSpace args instead") self.setLineColor(lineRGB, colorSpace='rgb', log=None) if fillRGB is not False: # Override with RGB if set logging.warning("Use of rgb arguments to stimuli are deprecated." " Please use color and colorSpace args instead") self.setFillColor(fillRGB, colorSpace='rgb', log=None) self.contrast = contrast if opacity is not None: self.opacity = opacity # Other stuff self.depth = depth self.ori = numpy.array(ori, float) self.size = size # make sure that it's 2D self.vertices = vertices # call attributeSetter self.anchor = anchor self.autoDraw = autoDraw # call attributeSetter # set autoLog now that params have been initialised wantLog = autoLog is None and self.win.autoLog self.__dict__['autoLog'] = autoLog or wantLog if self.autoLog: logging.exp("Created %s = %s" % (self.name, str(self))) @attributeSetter def lineWidth(self, value): """Width of the line in **pixels**. :ref:`Operations <attrib-operations>` supported. """ # Enforce float if not isinstance(value, (float, int)): value = float(value) if isinstance(self, psychopy.visual.Line): if value > 127: logging.warning("lineWidth is greater than max width supported by OpenGL. For lines thicker than 127px, please use a filled Rect instead.") self.__dict__['lineWidth'] = value def setLineWidth(self, value, operation='', log=None): setAttribute(self, 'lineWidth', value, log, operation) @attributeSetter def closeShape(self, value): """Should the last vertex be automatically connected to the first? If you're using `Polygon`, `Circle` or `Rect`, `closeShape=True` is assumed and shouldn't be changed. """ self.__dict__['closeShape'] = value @attributeSetter def interpolate(self, value): """If `True` the edge of the line will be anti-aliased. """ self.__dict__['interpolate'] = value @attributeSetter def color(self, color): """Set the color of the shape. Sets both `fillColor` and `lineColor` simultaneously if applicable. """ ColorMixin.foreColor.fset(self, color) self.fillColor = color self.lineColor = color return ColorMixin.foreColor.fget(self) #---legacy functions--- def setColor(self, color, colorSpace=None, operation='', log=None): """Sets both the line and fill to be the same color. """ ColorMixin.setForeColor(self, color, colorSpace, operation, log) self.setLineColor(color, colorSpace, operation, log) self.setFillColor(color, colorSpace, operation, log) @property def vertices(self): return BaseVisualStim.vertices.fget(self) @vertices.setter def vertices(self, value): if value is None: value = "rectangle" # check if this is a name of one of our known shapes if isinstance(value, str) and value in knownShapes: value = knownShapes[value] if value == "circle": # If circle is requested, calculate how many points are needed for the gap between line rects to be < 1px value = self._calculateMinEdges(self.lineWidth, threshold=5) if isinstance(value, int): value = self._calcEquilateralVertices(value) # Check shape WindowMixin.vertices.fset(self, value) self._needVertexUpdate = True def setVertices(self, value=None, operation='', log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message """ setAttribute(self, 'vertices', value, log, operation) @staticmethod def _calcEquilateralVertices(edges, radius=0.5): """ Get vertices for an equilateral shape with a given number of sides, will assume radius is 0.5 (relative) but can be manually specified """ d = numpy.pi * 2 / edges vertices = numpy.asarray( [numpy.asarray((numpy.sin(e * d), numpy.cos(e * d))) * radius for e in range(int(round(edges)))]) return vertices @staticmethod def _calculateMinEdges(lineWidth, threshold=180): """ Calculate how many points are needed in an equilateral polygon for the gap between line rects to be < 1px and for corner angles to exceed a threshold. In other words, how many edges does a polygon need to have to appear smooth? lineWidth : int, float, np.ndarray Width of the line in pixels threshold : int Maximum angle (degrees) for corners of the polygon, useful for drawing a circle. Supply 180 for no maximum angle. """ # sin(theta) = opp / hyp, we want opp to be 1/8 (meaning gap between rects is 1/4px, 1/2px in retina) opp = 1/8 hyp = lineWidth / 2 thetaR = numpy.arcsin(opp / hyp) theta = numpy.degrees(thetaR) # If theta is below threshold, use threshold instead theta = min(theta, threshold / 2) # Angles in a shape add up to 360, so theta is 360/2n, solve for n return int((360 / theta) / 2) def draw(self, win=None, keepMatrix=False): """Draw the stimulus in its relevant window. You must call this method after every MyWin.flip() if you want the stimulus to appear on that frame and then update the screen again. """ # The keepMatrix option is needed by Aperture if win is None: win = self.win self._selectWindow(win) if win._haveShaders: _prog = self.win._progSignedFrag GL.glUseProgram(_prog) # will check if it needs updating (check just once) vertsPix = self.verticesPix nVerts = vertsPix.shape[0] # scale the drawing frame etc... if not keepMatrix: GL.glPushMatrix() # push before drawing, pop after win.setScale('pix') # load Null textures into multitexteureARB - or they modulate glColor GL.glActiveTexture(GL.GL_TEXTURE0) GL.glEnable(GL.GL_TEXTURE_2D) GL.glBindTexture(GL.GL_TEXTURE_2D, 0) GL.glActiveTexture(GL.GL_TEXTURE1) GL.glEnable(GL.GL_TEXTURE_2D) GL.glBindTexture(GL.GL_TEXTURE_2D, 0) if self.interpolate: GL.glEnable(GL.GL_LINE_SMOOTH) GL.glEnable(GL.GL_MULTISAMPLE) else: GL.glDisable(GL.GL_LINE_SMOOTH) GL.glDisable(GL.GL_MULTISAMPLE) # .data_as(ctypes.POINTER(ctypes.c_float))) GL.glVertexPointer(2, GL.GL_DOUBLE, 0, vertsPix.ctypes) GL.glEnableClientState(GL.GL_VERTEX_ARRAY) if nVerts > 2: # draw a filled polygon first if self._fillColor != None: # then draw GL.glColor4f(*self._fillColor.render('rgba1')) GL.glDrawArrays(GL.GL_POLYGON, 0, nVerts) if self._borderColor != None and self.lineWidth != 0.0: # then draw GL.glLineWidth(self.lineWidth) if self.opacity is not None: borderRGBA = self._borderColor.render('rgba1') borderRGBA[-1] = self.opacity # override opacity GL.glColor4f(*borderRGBA) else: GL.glColor4f(*self._borderColor.render('rgba1')) if self.closeShape: GL.glDrawArrays(GL.GL_LINE_LOOP, 0, nVerts) else: GL.glDrawArrays(GL.GL_LINE_STRIP, 0, nVerts) GL.glDisableClientState(GL.GL_VERTEX_ARRAY) if win._haveShaders: GL.glUseProgram(0) if not keepMatrix: GL.glPopMatrix() class ShapeStim(BaseShapeStim): """A class for arbitrary shapes defined as lists of vertices (x,y). This is a lazy-imported class, therefore import using full path `from psychopy.visual.shape import ShapeStim` when inheriting from it. Shapes can be lines, polygons (concave, convex, self-crossing), or have holes or multiple regions. `vertices` is typically a list of points (x,y). By default, these are assumed to define a closed figure (polygon); set `closeShape=False` for a line. `closeShape` cannot be changed dynamically, but individual vertices can be changed on a frame-by-frame basis. The stimulus as a whole can be rotated, translated, or scaled dynamically (using .ori, .pos, .size). Vertices can be a string, giving the name of a known set of vertices, although "cross" is the only named shape available at present. Advanced shapes: `vertices` can also be a list of loops, where each loop is a list of points (x,y), e.g., to define a shape with a hole. Borders and contains() are not supported for multi-loop stimuli. `windingRule` is an advanced feature to allow control over the GLU tessellator winding rule (default: GLU_TESS_WINDING_ODD). This is relevant only for self-crossing or multi-loop shapes. Cannot be set dynamically. See Coder demo > stimuli > shapes.py Changed Nov 2015: v1.84.00. Now allows filling of complex shapes. This is almost completely backwards compatible (see changelog). The old version is accessible as `psychopy.visual.BaseShapeStim`. Parameters ---------- win : :class:`~psychopy.visual.Window` Window this shape is being drawn to. The stimulus instance will allocate its required resources using that Windows context. In many cases, a stimulus instance cannot be drawn on different windows unless those windows share the same OpenGL context, which permits resources to be shared between them. units : str Units to use when drawing. This will affect how parameters and attributes `pos`, `size` and `radius` are interpreted. colorSpace : str Sets the colorspace, changing how values passed to `lineColor` and `fillColor` are interpreted. lineWidth : float Width of the shape outline. lineColor, fillColor : array_like, str, :class:`~psychopy.colors.Color` or None Color of the shape outline and fill. If `None`, a fully transparent color is used which makes the fill or outline invisible. vertices : array_like Nx2 array of points (eg., `[[-0.5, 0], [0, 0.5], [0.5, 0]`). windingRule : :class:`~pyglet.gl.GLenum` or None Winding rule to use for tesselation, default is `GLU_TESS_WINDING_ODD` if `None` is specified. closeShape : bool Close the shape's outline. If `True` the first and last vertex will be joined by an edge. Must be `True` to use tesselation. Default is `True`. pos : array_like Initial position (`x`, `y`) of the shape on-screen relative to the origin located at the center of the window or buffer in `units`. This can be updated after initialization by setting the `pos` property. The default value is `(0.0, 0.0)` which results in no translation. size : array_like, float, int or None Width and height of the shape as `(w, h)` or `[w, h]`. If a single value is provided, the width and height will be set to the same specified value. If `None` is specified, the `size` will be set with values passed to `width` and `height`. ori : float Initial orientation of the shape in degrees about its origin. Positive values will rotate the shape clockwise, while negative values will rotate counterclockwise. The default value for `ori` is 0.0 degrees. opacity : float Opacity of the shape. A value of 1.0 indicates fully opaque and 0.0 is fully transparent (therefore invisible). Values between 1.0 and 0.0 will result in colors being blended with objects in the background. This value affects the fill (`fillColor`) and outline (`lineColor`) colors of the shape. contrast : float Contrast level of the shape (0.0 to 1.0). This value is used to modulate the contrast of colors passed to `lineColor` and `fillColor`. depth : int Depth layer to draw the shape when `autoDraw` is enabled. *DEPRECATED* interpolate : bool Enable smoothing (anti-aliasing) when drawing shape outlines. This produces a smoother (less-pixelated) outline of the shape. draggable : bool Can this stimulus be dragged by a mouse click? name : str Optional name of the stimuli for logging. autoLog : bool Enable auto-logging of events associated with this stimuli. Useful for debugging and to track timing when used in conjunction with `autoDraw`. autoDraw : bool Enable auto drawing. When `True`, the stimulus will be drawn every frame without the need to explicitly call the :py:meth:`~psychopy.visual.ShapeStim.draw` method. color : array_like, str, :class:`~psychopy.colors.Color` or None Sets both the initial `lineColor` and `fillColor` of the shape. lineRGB, fillRGB: array_like, :class:`~psychopy.colors.Color` or None *Deprecated*. Please use `lineColor` and `fillColor`. These arguments may be removed in a future version. lineColorSpace, fillColorSpace : str Colorspace to use for the outline and fill. These change how the values passed to `lineColor` and `fillColor` are interpreted. *Deprecated*. Please use `colorSpace` to set both outline and fill colorspace. These arguments may be removed in a future version. """ # Author: Jeremy Gray, November 2015, using psychopy.contrib.tesselate def __init__(self, win, units='', colorSpace='rgb', fillColor=False, lineColor=False, lineWidth=1.5, vertices=((-0.5, 0), (0, +0.5), (+0.5, 0)), windingRule=None, # default GL.GLU_TESS_WINDING_ODD closeShape=True, # False for a line pos=(0, 0), size=1, anchor=None, ori=0.0, opacity=1.0, contrast=1.0, depth=0, interpolate=True, draggable=False, name=None, autoLog=None, autoDraw=False, # legacy color=False, lineRGB=False, fillRGB=False, fillColorSpace=None, lineColorSpace=None ): # what local vars are defined (init params, for use by __repr__) self._initParamsOrig = dir() self._initParamsOrig.remove('self') super(ShapeStim, self).__init__(win, units=units, lineWidth=lineWidth, colorSpace=colorSpace, lineColor=lineColor, lineColorSpace=lineColorSpace, fillColor=fillColor, fillColorSpace=fillColorSpace, vertices=None, # dummy verts closeShape=self.closeShape, pos=pos, size=size, anchor=anchor, ori=ori, opacity=opacity, contrast=contrast, depth=depth, interpolate=interpolate, draggable=draggable, name=name, autoLog=False, autoDraw=autoDraw) self.closeShape = closeShape self.windingRule = windingRule self.vertices = vertices # remove deprecated params (from ShapeStim.__init__): self._initParams = self._initParamsOrig # set autoLog now that params have been initialised wantLog = autoLog or autoLog is None and self.win.autoLog self.__dict__['autoLog'] = wantLog if self.autoLog: logging.exp("Created %s = %s" % (self.name, str(self))) def _tesselate(self, newVertices): """Set the `.vertices` and `.border` to new values, invoking tessellation. """ # TO-DO: handle borders properly for multiloop stim like holes # likely requires changes in ContainerMixin to iterate over each # border loop from psychopy.contrib import tesselate self.border = copy.deepcopy(newVertices) tessVertices = [] # define to keep the linter happy if self.closeShape: # convert original vertices to triangles (= tesselation) if # possible. (not possible if closeShape is False, don't even try) GL.glPushMatrix() # seemed to help at one point, superfluous? if getattr(self, "windingRule", False): GL.gluTessProperty(tesselate.tess, GL.GLU_TESS_WINDING_RULE, self.windingRule) if hasattr(newVertices[0][0], '__iter__'): loops = newVertices else: loops = [newVertices] tessVertices = tesselate.tesselate(loops) GL.glPopMatrix() if getattr(self, "windingRule", False): GL.gluTessProperty(tesselate.tess, GL.GLU_TESS_WINDING_RULE, tesselate.default_winding_rule) if not self.closeShape or tessVertices == []: # probably got a line if tesselate returned [] initVertices = newVertices self.closeShape = False elif len(tessVertices) % 3: raise tesselate.TesselateError("Could not properly tesselate") else: initVertices = tessVertices self.__dict__['_tesselVertices'] = numpy.array(initVertices, float) @property def vertices(self): """A list of lists or a numpy array (Nx2) specifying xy positions of each vertex, relative to the center of the field. Assigning to vertices can be slow if there are many vertices. :ref:`Operations <attrib-operations>` supported with `.setVertices()`. """ return WindowMixin.vertices.fget(self) @vertices.setter def vertices(self, value): # check if this is a name of one of our known shapes if isinstance(value, str) and value in knownShapes: value = knownShapes[value] if isinstance(value, str) and value == "circle": # If circle is requested, calculate how many points are needed for the gap between line rects to be < 1px value = self._calculateMinEdges(self.lineWidth, threshold=5) if isinstance(value, int): value = self._calcEquilateralVertices(value) # Check shape WindowMixin.vertices.fset(self, value) self._needVertexUpdate = True self._tesselate(self.vertices) def draw(self, win=None, keepMatrix=False): """Draw the stimulus in the relevant window. You must call this method after every `win.flip()` if you want the stimulus to appear on that frame and then update the screen again. """ # mostly copied from BaseShapeStim. Uses GL_TRIANGLES and depends on # two arrays of vertices: tesselated (for fill) & original (for # border) keepMatrix is needed by Aperture, although Aperture # currently relies on BaseShapeStim instead if win is None: win = self.win self._selectWindow(win) # scale the drawing frame etc... if not keepMatrix: GL.glPushMatrix() win.setScale('pix') # setup the shaderprogram if win._haveShaders: _prog = self.win._progSignedFrag GL.glUseProgram(_prog) # load Null textures into multitexteureARB - or they modulate glColor GL.glActiveTexture(GL.GL_TEXTURE0) GL.glEnable(GL.GL_TEXTURE_2D) GL.glBindTexture(GL.GL_TEXTURE_2D, 0) GL.glActiveTexture(GL.GL_TEXTURE1) GL.glEnable(GL.GL_TEXTURE_2D) GL.glBindTexture(GL.GL_TEXTURE_2D, 0) if self.interpolate: GL.glEnable(GL.GL_LINE_SMOOTH) GL.glEnable(GL.GL_MULTISAMPLE) else: GL.glDisable(GL.GL_LINE_SMOOTH) GL.glDisable(GL.GL_MULTISAMPLE) GL.glEnableClientState(GL.GL_VERTEX_ARRAY) # fill interior triangles if there are any if (self.closeShape and self.verticesPix.shape[0] > 2 and self._fillColor != None): GL.glVertexPointer(2, GL.GL_DOUBLE, 0, self.verticesPix.ctypes) GL.glColor4f(*self._fillColor.render('rgba1')) GL.glDrawArrays(GL.GL_TRIANGLES, 0, self.verticesPix.shape[0]) # draw the border (= a line connecting the non-tesselated vertices) if self._borderColor != None and self.lineWidth: GL.glVertexPointer(2, GL.GL_DOUBLE, 0, self._borderPix.ctypes) GL.glLineWidth(self.lineWidth) GL.glColor4f(*self._borderColor.render('rgba1')) if self.closeShape: gl_line = GL.GL_LINE_LOOP else: gl_line = GL.GL_LINE_STRIP GL.glDrawArrays(gl_line, 0, self._borderPix.shape[0]) GL.glDisableClientState(GL.GL_VERTEX_ARRAY) if win._haveShaders: GL.glUseProgram(0) if not keepMatrix: GL.glPopMatrix()
28,269
Python
.py
626
34.185304
155
0.600022
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,737
rect.py
psychopy_psychopy/psychopy/visual/rect.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Creates a rectangle of given width and height as a special case of a :class:`~psychopy.visual.ShapeStim`""" # 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 as np import psychopy # so we can get the __path__ from psychopy.visual.shape import BaseShapeStim from psychopy.tools.attributetools import attributeSetter, setAttribute class Rect(BaseShapeStim): """Creates a rectangle of given width and height as a special case of a :class:`~psychopy.visual.ShapeStim`. This is a lazy-imported class, therefore import using full path `from psychopy.visual.rect import Rect` when inheriting from it. Parameters ---------- win : :class:`~psychopy.visual.Window` Window this shape is being drawn to. The stimulus instance will allocate its required resources using that Windows context. In many cases, a stimulus instance cannot be drawn on different windows unless those windows share the same OpenGL context, which permits resources to be shared between them. width, height : float or int The width or height of the shape. *DEPRECATED* use `size` to define the dimensions of the shape on initialization. If `size` is specified the values of `width` and `height` are ignored. This is to provide legacy compatibility for existing applications. units : str Units to use when drawing. This will affect how parameters and attributes `pos`, `size` and `radius` are interpreted. lineWidth : float Width of the shape's outline. lineColor, fillColor : array_like, str, :class:`~psychopy.colors.Color` or None Color of the shape outline and fill. If `None`, a fully transparent color is used which makes the fill or outline invisible. lineColorSpace, fillColorSpace : str Colorspace to use for the outline and fill. These change how the values passed to `lineColor` and `fillColor` are interpreted. *Deprecated*. Please use `colorSpace` to set both outline and fill colorspace. These arguments may be removed in a future version. pos : array_like Initial position (`x`, `y`) of the shape on-screen relative to the origin located at the center of the window or buffer in `units`. This can be updated after initialization by setting the `pos` property. The default value is `(0.0, 0.0)` which results in no translation. size : array_like, float, int or None Width and height of the shape as `(w, h)` or `[w, h]`. If a single value is provided, the width and height will be set to the same specified value. If `None` is specified, the `size` will be set with values passed to `width` and `height`. ori : float Initial orientation of the shape in degrees about its origin. Positive values will rotate the shape clockwise, while negative values will rotate counterclockwise. The default value for `ori` is 0.0 degrees. opacity : float Opacity of the shape. A value of 1.0 indicates fully opaque and 0.0 is fully transparent (therefore invisible). Values between 1.0 and 0.0 will result in colors being blended with objects in the background. This value affects the fill (`fillColor`) and outline (`lineColor`) colors of the shape. contrast : float Contrast level of the shape (0.0 to 1.0). This value is used to modulate the contrast of colors passed to `lineColor` and `fillColor`. depth : int Depth layer to draw the shape when `autoDraw` is enabled. *DEPRECATED* interpolate : bool Enable smoothing (anti-aliasing) when drawing shape outlines. This produces a smoother (less-pixelated) outline of the shape. lineRGB, fillRGB: array_like, :class:`~psychopy.colors.Color` or None *Deprecated*. Please use `lineColor` and `fillColor`. These arguments may be removed in a future version. name : str Optional name of the stimuli for logging. autoLog : bool Enable auto-logging of events associated with this stimuli. Useful for debugging and to track timing when used in conjunction with `autoDraw`. autoDraw : bool Enable auto drawing. When `True`, the stimulus will be drawn every frame without the need to explicitly call the :py:meth:`~psychopy.visual.shape.ShapeStim.draw()` method. color : array_like, str, :class:`~psychopy.colors.Color` or None Sets both the initial `lineColor` and `fillColor` of the shape. colorSpace : str Sets the colorspace, changing how values passed to `lineColor` and `fillColor` are interpreted. draggable : bool Can this stimulus be dragged by a mouse click? Attributes ---------- width, height : float or int The width and height of the rectangle. Values are aliased with fields in the `size` attribute. Use these values to adjust the size of the rectangle in a single dimension after initialization. """ _defaultFillColor = 'white' _defaultLineColor = None def __init__(self, win, width=.5, height=.5, units='', lineWidth=1.5, lineColor=False, fillColor=False, colorSpace='rgb', pos=(0, 0), size=None, anchor=None, ori=0.0, opacity=None, contrast=1.0, depth=0, interpolate=True, draggable=False, name=None, autoLog=None, autoDraw=False, # legacy color=None, lineColorSpace=None, fillColorSpace=None, lineRGB=False, fillRGB=False, ): # width and height attributes, these are later aliased with `size` self.__dict__['width'] = float(width) self.__dict__['height'] = float(height) # If the size argument was specified, override values of width and # height, this is to maintain legacy compatibility. Args width and # height should be deprecated in later releases. if size is None: size = (self.__dict__['width'], self.__dict__['height']) # vertices for rectangle, CCW winding order vertices = np.array([[-.5, .5], [ .5, .5], [ .5, -.5], [-.5, -.5]]) super(Rect, self).__init__( win, units=units, lineWidth=lineWidth, lineColor=lineColor, lineColorSpace=lineColorSpace, fillColor=fillColor, fillColorSpace=fillColorSpace, vertices=vertices, closeShape=True, pos=pos, size=size, anchor=anchor, ori=ori, opacity=opacity, contrast=contrast, depth=depth, interpolate=interpolate, draggable=draggable, lineRGB=lineRGB, fillRGB=fillRGB, name=name, autoLog=autoLog, autoDraw=autoDraw, color=color, colorSpace=colorSpace) def setSize(self, size, operation='', log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message :ref:`Operations <attrib-operations>` supported. """ setAttribute(self, 'size', size, log, operation) def setWidth(self, width, operation='', log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message """ setAttribute(self, 'width', width, log, operation) def setHeight(self, height, operation='', log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message """ setAttribute(self, 'height', height, log, operation)
8,555
Python
.py
187
35.684492
83
0.626033
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,738
line.py
psychopy_psychopy/psychopy/visual/line.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Creates a Line between two points as a special case of a :class:`~psychopy.visual.ShapeStim` """ # 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 psychopy # so we can get the __path__ from psychopy import logging import numpy from psychopy.visual.shape import ShapeStim from psychopy.tools.attributetools import attributeSetter, setAttribute class Line(ShapeStim): """Creates a Line between two points. This is a lazy-imported class, therefore import using full path `from psychopy.visual.line import Line` when inheriting from it. `Line` accepts all input parameters, that :class:`~psychopy.visual.ShapeStim` accepts, except for `vertices`, `closeShape` and `fillColor`. (New in version 1.72.00) Parameters ---------- win : :class:`~psychopy.visual.Window` Window this line is being drawn to. The stimulus instance will allocate its required resources using that Windows context. In many cases, a stimulus instance cannot be drawn on different windows unless those windows share the same OpenGL context, which permits resources to be shared between them. start : array_like Coordinate `(x, y)` of the starting point of the line. end : array_like Coordinate `(x, y)` of the end-point of the line. units : str Units to use when drawing. This will affect how parameters and attributes `pos`, `size` and `radius` are interpreted. lineWidth : float Width of the line. lineColor : array_like, str, :class:`~psychopy.colors.Color` or None Color of the line. If `None`, a fully transparent color is used which makes the line invisible. *Deprecated* use `color` instead. lineColorSpace : str or None Colorspace to use for the line. These change how the values passed to `lineColor` are interpreted. *Deprecated*. Please use `colorSpace` to set the line colorspace. This arguments may be removed in a future version. pos : array_like Initial translation (`x`, `y`) of the line on-screen relative to the origin located at the center of the window or buffer in `units`. This can be updated after initialization by setting the `pos` property. The default value is `(0.0, 0.0)` which results in no translation. size : float or array_like Initial scale factor for adjusting the size of the line. A single value (`float`) will apply uniform scaling, while an array (`sx`, `sy`) will result in anisotropic scaling in the horizontal (`sx`) and vertical (`sy`) direction. Providing negative values to `size` will cause the line to be mirrored. Scaling can be changed by setting the `size` property after initialization. The default value is `1.0` which results in no scaling. ori : float Initial orientation of the line in degrees about its origin. Positive values will rotate the line clockwise, while negative values will rotate counterclockwise. The default value for `ori` is 0.0 degrees. opacity : float Opacity of the line. A value of 1.0 indicates fully opaque and 0.0 is fully transparent (therefore invisible). Values between 1.0 and 0.0 will result in colors being blended with objects in the background. This value affects the fill (`fillColor`) and outline (`lineColor`) colors of the shape. contrast : float Contrast level of the line (0.0 to 1.0). This value is used to modulate the contrast of colors passed to `lineColor` and `fillColor`. depth : int Depth layer to draw the stimulus when `autoDraw` is enabled. interpolate : bool Enable smoothing (anti-aliasing) when drawing lines. This produces a smoother (less-pixelated) line. draggable : bool Can this stimulus be dragged by a mouse click? lineRGB: array_like, :class:`~psychopy.colors.Color` or None *Deprecated*. Please use `color` instead. This argument may be removed in a future version. name : str Optional name of the stimuli for logging. autoLog : bool Enable auto-logging of events associated with this stimuli. Useful for debugging and to track timing when used in conjunction with `autoDraw`. autoDraw : bool Enable auto drawing. When `True`, the stimulus will be drawn every frame without the need to explicitly call the :py:meth:`~psychopy.visual.shape.ShapeStim.draw()` method. color : array_like, str, :class:`~psychopy.colors.Color` or None Sets both the initial `lineColor` and `fillColor` of the shape. colorSpace : str Sets the colorspace, changing how values passed to `lineColor` and `fillColor` are interpreted. Notes ----- The `contains` method always return `False` because a line is not a proper (2D) polygon. Attributes ---------- start, end : array_like Coordinates `(x, y)` for the start- and end-point of the line. """ _defaultFillColor = None _defaultLineColor = "white" def __init__(self, win, start=(-.5, -.5), end=(.5, .5), units=None, lineWidth=1.5, lineColor=False, colorSpace='rgb', pos=(0, 0), size=1.0, anchor="center", ori=0.0, opacity=None, contrast=1.0, depth=0, interpolate=True, draggable=False, name=None, autoLog=None, autoDraw=False, # legacy color=False, fillColor=False, lineColorSpace=None, lineRGB=False, fillRGB=False, ): """ """ # what local vars are defined (these are the init params) for use by # __repr__ self._initParams = dir() self._initParams.remove('self') self.__dict__['start'] = numpy.array(start) self.__dict__['end'] = numpy.array(end) super(Line, self).__init__( win, units=units, lineWidth=lineWidth, lineColor=lineColor, lineColorSpace=None, fillColor=None, fillColorSpace=lineColorSpace, # have these set to the same vertices=(start, end), anchor=anchor, closeShape=False, pos=pos, size=size, ori=ori, opacity=opacity, contrast=contrast, depth=depth, interpolate=interpolate, draggable=draggable, lineRGB=lineRGB, fillRGB=fillRGB, name=name, autoLog=autoLog, autoDraw=autoDraw, color=color, colorSpace=colorSpace) del self._tesselVertices @property def color(self): return self.lineColor @color.setter def color(self, value): self.lineColor = value @attributeSetter def start(self, start): """tuple, list or 2x1 array. Specifies the position of the start of the line. :ref:`Operations <attrib-operations>` supported. """ self.__dict__['start'] = numpy.array(start) self.setVertices([self.start, self.end], log=False) def setStart(self, start, log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message. """ setAttribute(self, 'start', start, log) @attributeSetter def end(self, end): """tuple, list or 2x1 array Specifies the position of the end of the line. :ref:`Operations <attrib-operations>` supported.""" self.__dict__['end'] = numpy.array(end) self.setVertices([self.start, self.end], log=False) def setEnd(self, end, log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message. """ setAttribute(self, 'end', end, log) def contains(self, *args, **kwargs): return False
8,636
Python
.py
206
32.699029
81
0.625074
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,739
elementarray.py
psychopy_psychopy/psychopy/visual/elementarray.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """This stimulus class defines a field of elements whose behaviour can be independently controlled. Suitable for creating 'global form' stimuli or more detailed random dot stimuli.""" # 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). # Ensure setting pyglet.options['debug_gl'] to False is done prior to any # other calls to pyglet or pyglet submodules, otherwise it may not get picked # up by the pyglet GL engine and have no effect. # Shaders will work but require OpenGL2.0 drivers AND PyOpenGL3.0+ import pyglet from ..colors import Color pyglet.options['debug_gl'] = False import ctypes GL = pyglet.gl import psychopy # so we can get the __path__ from psychopy import logging from psychopy.visual import Window # tools must only be imported *after* event or MovieStim breaks on win32 # (JWP has no idea why!) from psychopy.tools.arraytools import val2array from psychopy.tools.attributetools import attributeSetter, logAttrib, setAttribute from psychopy.tools.monitorunittools import convertToPix from psychopy.visual.helpers import setColor from psychopy.visual.basevisual import MinimalStim, TextureMixin, ColorMixin from . import globalVars import numpy class ElementArrayStim(MinimalStim, TextureMixin, ColorMixin): """This stimulus class defines a field of elements whose behaviour can be independently controlled. Suitable for creating 'global form' stimuli or more detailed random dot stimuli. This is a lazy-imported class, therefore import using full path `from psychopy.visual.elementarray import ElementArrayStim` when inheriting from it. This stimulus can draw thousands of elements without dropping a frame, but in order to achieve this performance, uses several OpenGL extensions only available on modern graphics cards (supporting OpenGL2.0). See the ElementArray demo. """ def __init__(self, win, units=None, fieldPos=(0.0, 0.0), fieldSize=(1.0, 1.0), fieldShape='circle', nElements=100, sizes=2.0, xys=None, rgbs=None, colors=(1.0, 1.0, 1.0), colorSpace='rgb', opacities=1.0, depths=0, fieldDepth=0, oris=0, sfs=1.0, contrs=1, phases=0, elementTex='sin', elementMask='gauss', texRes=48, interpolate=True, name=None, autoLog=None, maskParams=None): """ :Parameters: win : a :class:`~psychopy.visual.Window` object (required) units : **None**, 'height', 'norm', 'cm', 'deg' or 'pix' If None then the current units of the :class:`~psychopy.visual.Window` will be used. See :ref:`units` for explanation of other options. nElements : number of elements in the array. """ # what local vars are defined (these are the init params) for use by # __repr__ self._initParams = dir() self._initParams.remove('self') super(ElementArrayStim, self).__init__(name=name, autoLog=False) self.autoLog = False # until all params are set self.win = win # Not pretty (redefined later) but it works! self.__dict__['texRes'] = texRes self.__dict__['maskParams'] = maskParams # unit conversions if units != None and len(units): self.units = units else: self.units = win.units self.__dict__['fieldShape'] = fieldShape self.nElements = nElements # info for each element self.__dict__['sizes'] = sizes self.verticesBase = xys self._needVertexUpdate = True self._needColorUpdate = True self._RGBAs = None self.interpolate = interpolate self.__dict__['fieldDepth'] = fieldDepth self.__dict__['depths'] = depths if self.win.winType == 'pygame': raise TypeError('ElementArrayStim is not supported in a pygame context') if not self.win._haveShaders: raise Exception("ElementArrayStim requires shaders support" " and floating point textures") self.colorSpace = colorSpace if rgbs != None: msg = ("Use of the rgb argument to ElementArrayStim is deprecated" ". Please use colors and colorSpace args instead") logging.warning(msg) self.setColors(rgbs, colorSpace='rgb', log=False) else: self.setColors(colors, colorSpace=colorSpace, log=False) # Deal with input for fieldpos and fieldsize self.__dict__['fieldPos'] = val2array(fieldPos, False, False) self.__dict__['fieldSize'] = val2array(fieldSize, False) # create textures self._texID = GL.GLuint() GL.glGenTextures(1, ctypes.byref(self._texID)) self._maskID = GL.GLuint() GL.glGenTextures(1, ctypes.byref(self._maskID)) self.setMask(elementMask, log=False) self.texRes = texRes self.setTex(elementTex, log=False) self.setContrs(contrs, log=False) # opacities is used by setRgbs, so this needs to be early self.setOpacities(opacities, log=False) self.setXYs(xys, log=False) self.setOris(oris, log=False) # set sizes before sfs (sfs may need it formatted) self.setSizes(sizes, log=False) self.setSfs(sfs, log=False) self.setPhases(phases, log=False) self._updateVertices() # set autoLog now that params have been initialised wantLog = autoLog is None and self.win.autoLog self.__dict__['autoLog'] = autoLog or wantLog if self.autoLog: logging.exp("Created %s = %s" % (self.name, str(self))) def _selectWindow(self, win): # don't call switch if it's already the curr window if win != globalVars.currWindow and win.winType == 'pyglet': win.winHandle.switch_to() globalVars.currWindow = win def _makeNx2(self, value, acceptedInput=('scalar', 'Nx1', 'Nx2')): """Helper function to change input to Nx2 arrays 'scalar': int/float, 1x1 and 2x1. 'Nx1': vector of values for each element. 'Nx2': x-y pair for each element """ # Make into an array if not already value = numpy.array(value, dtype=float) # Check shape and transform if not appropriate valShpElem = value.shape in [(self.nElements,), (self.nElements, 1)] if 'scalar' in acceptedInput and value.shape in [(), (1,), (2,)]: value = numpy.resize(value, [self.nElements, 2]) elif 'Nx1' in acceptedInput and valShpElem: value.shape = (self.nElements, 1) # set to be 2D value = value.repeat(2, 1) # repeat once on dim 1 elif 'Nx2' in acceptedInput and value.shape == (self.nElements, 2): pass # all is good else: msg = 'New value should be one of these: ' raise ValueError(msg + str(acceptedInput)) return value def _makeNx1(self, value, acceptedInput=('scalar', 'Nx1')): """Helper function to change input to Nx1 arrays 'scalar': int, 1x1 and 2x1. 'Nx1': vector of values for each element.""" # Make into an array if not already value = numpy.array(value, dtype=float) # Check shape and transform if not appropriate valShpElem = value.shape in [(self.nElements,), (self.nElements, 1)] if 'scalar' in acceptedInput and value.shape in [(), (1,)]: value = value.repeat(self.nElements) elif 'Nx1' in acceptedInput and valShpElem: pass # all is good else: msg = 'New value should be one of these: ' raise ValueError(msg + str(acceptedInput)) return value @attributeSetter def xys(self, value): """The xy positions of the elements centres, relative to the field centre. Values should be: - None - an array/list of Nx2 coordinates. If value is None then the xy positions will be generated automatically, based on the fieldSize and fieldPos. In this case opacity will also be overridden by this function (it is used to make elements outside the field invisible). :ref:`operations <attrib-operations>` are supported. """ if value is None: fsz = self.fieldSize rand = numpy.random.rand if self.fieldShape in ('sqr', 'square'): # initialise a random array of X,Y self.__dict__['xys'] = rand(self.nElements, 2) * fsz - (fsz / 2) # gone outside the square xxx = (self.xys[:, 0] + (fsz[0] / 2)) % fsz[0] yyy = (self.xys[:, 1] + (fsz[1] / 2)) % fsz[1] self.__dict__['xys'][:, 0] = xxx - (fsz[0] / 2) self.__dict__['xys'][:, 1] = yyy - (fsz[1] / 2) elif self.fieldShape == 'circle': # take twice as many elements as we need (and cull the ones # outside the circle) # initialise a random array of X,Y xys = rand(self.nElements * 2, 2) * fsz - (fsz / 2) # gone outside the square xys[:, 0] = ((xys[:, 0] + (fsz[0] / 2)) % fsz[0]) - (fsz[0] / 2) xys[:, 1] = ((xys[:, 1] + (fsz[1] / 2)) % fsz[1]) - (fsz[1] / 2) # use a circular envelope and flips dot to opposite edge # if they fall beyond radius. # NB always circular - uses fieldSize in X only normxy = xys / (fsz / 2.0) dotDist = numpy.sqrt((normxy[:, 0]**2.0 + normxy[:, 1]**2.0)) self.__dict__['xys'] = xys[dotDist < 1.0, :][0:self.nElements] else: self.__dict__['xys'] = self._makeNx2(value, ['Nx2']) # to keep a record if we are to alter things later. self._xysAsNone = value is None self._needVertexUpdate = True def setXYs(self, value=None, operation='', log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message. """ setAttribute(self, 'xys', value, log, operation) @attributeSetter def fieldShape(self, value): """The shape of the array ('circle' or 'sqr'). Will only have effect if xys=None.""" self.__dict__['fieldShape'] = value if self._xysAsNone: self.xys = None # call attributeSetter else: logging.warning("Tried to set FieldShape but XYs were given " "explicitly. This won't have any effect.") @attributeSetter def oris(self, value): """(Nx1 or a single value) The orientations of the elements. Oris are in degrees, and can be greater than 360 and smaller than 0. An ori of 0 is vertical, and increasing ori values are increasingly clockwise. :ref:`operations <attrib-operations>` are supported. """ self.__dict__['oris'] = self._makeNx1(value) # set self.oris self._needVertexUpdate = True def setOris(self, value, operation='', log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message. """ # call attributeSetter setAttribute(self, 'oris', value, log, operation) @attributeSetter def sfs(self, value): """The spatial frequency for each element. Should either be: - a single value - an Nx1 array/list - an Nx2 array/list (spatial frequency of the element in X and Y). If the units for the stimulus are 'pix' or 'norm' then the units of sf are cycles per stimulus width. For units of 'deg' or 'cm' the units are c/cm or c/deg respectively. :ref:`operations <attrib-operations>` are supported. """ self.__dict__['sfs'] = self._makeNx2(value) # set self.sfs self._needTexCoordUpdate = True def setSfs(self, value, operation='', log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message. """ # in the case of Nx1 list/array, setAttribute would fail if not this: value = self._makeNx2(value) # call attributeSetter setAttribute(self, 'sfs', value, log, operation) @attributeSetter def opacities(self, value): """Set the opacity for each element. Should either be a single value or an Nx1 array/list :ref:`Operations <attrib-operations>` are supported. """ self.__dict__['opacities'] = self._makeNx1(value) self._needColorUpdate = True def setOpacities(self, value, operation='', log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message. """ setAttribute(self, 'opacities', value, log, operation) # call attributeSetter @attributeSetter def sizes(self, value): """Set the size for each element. Should either be: - a single value - an Nx1 array/list - an Nx2 array/list :ref:`Operations <attrib-operations>` are supported. """ self.__dict__['sizes'] = self._makeNx2(value) self._needVertexUpdate = True self._needTexCoordUpdate = True def setSizes(self, value, operation='', log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message. """ # in the case of Nx1 list/array, setAttribute would fail if not this: value = self._makeNx2(value) # call attributeSetter setAttribute(self, 'sizes', value, log, operation) @attributeSetter def phases(self, value): """The spatial phase of the texture on each element. Should either be: - a single value - an Nx1 array/list - an Nx2 array/list (for separate X and Y phase) :ref:`Operations <attrib-operations>` are supported. """ self.__dict__['phases'] = self._makeNx2(value) self._needTexCoordUpdate = True def setPhases(self, value, operation='', log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message. """ # in the case of Nx1 list/array, setAttribute would fail if not this: value = self._makeNx2(value) setAttribute(self, 'phases', value, log, operation) # call attributeSetter def setRgbs(self, value, operation=''): """DEPRECATED (as of v1.74.00). Please use setColors() instead. """ self.setColors(value, operation) @property def colors(self): """Specifying the color(s) of the elements. Should be Nx1 (different intensities), Nx3 (different colors) or 1x3 (for a single color). See other stimuli (e.g. :ref:`GratingStim.color`) for more info on the color attribute which essentially works the same on all PsychoPy stimuli. Remember that they describe just this case but here you can provide a list of colors - one color for each element. Use ``setColors()`` if you want to set colors and colorSpace simultaneously or use operations on colors. """ if hasattr(self, '_colors'): # Return array of rendered colors return self._colors.render(self.colorSpace) @colors.setter def colors(self, value): # Create blank array of colors self._colors = Color(value, self.colorSpace, self.contrast) self._needColorUpdate = True def setColors(self, colors, colorSpace=None, operation='', log=None): """See ``color`` for more info on the color parameter and ``colorSpace`` for more info in the colorSpace parameter. """ self.colorSpace = colorSpace self.colors = colors @property def opacity(self): if hasattr(self, "_opacity"): return self._opacity @opacity.setter def opacity(self, value): self._opacity = value if hasattr(self, "_colors"): # Set the alpha value of each color to be the desired opacity self._colors.alpha = value @attributeSetter def contrs(self, value): """The contrasts of the elements, ranging -1 to +1. Should either be: - a single value - an Nx1 array/list :ref:`Operations <attrib-operations>` are supported. """ # Convert to an Nx1 numpy array value = self._makeNx1(value) # If colors is too short, extend it self._colors.rgb = numpy.resize(self._colors.rgb, (len(value), 3)) # Set self._colors.contrast = value # Store value and update self.__dict__['contrs'] = value self._needColorUpdate = True def setContrs(self, value, operation='', log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message. """ setAttribute(self, 'contrs', value, log, operation) @attributeSetter def fieldPos(self, value): """:ref:`x,y-pair <attrib-xy>`. Set the centre of the array of elements. :ref:`Operations <attrib-operations>` are supported. """ self.__dict__['fieldPos'] = val2array(value, False, False) self._needVertexUpdate = True def setFieldPos(self, value, operation='', log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message. """ setAttribute(self, 'fieldPos', value, log, operation) def setPos(self, newPos=None, operation='', units=None, log=None): """Obsolete - users should use setFieldPos or instead of setPos. """ logging.error("User called ElementArrayStim.setPos(pos). " "Use ElementArrayStim.setFieldPos(pos) instead.") @attributeSetter def fieldSize(self, value): """Scalar or :ref:`x,y-pair <attrib-xy>`. The size of the array of elements. This will be overridden by setting explicit xy positions for the elements. :ref:`Operations <attrib-operations>` are supported. """ self.__dict__['fieldSize'] = val2array(value, False) # to reflect new settings, overriding individual xys self.setXYs(log=False) def setFieldSize(self, value, operation='', log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message. """ setAttribute(self, 'fieldSize', value, log, operation) def draw(self, win=None): """Draw the stimulus in its relevant window. You must call this method after every MyWin.update() if you want the stimulus to appear on that frame and then update the screen again. """ if win is None: win = self.win self._selectWindow(win) if self._needVertexUpdate: self._updateVertices() if self._needColorUpdate: self.updateElementColors() if self._needTexCoordUpdate: self.updateTextureCoords() # scale the drawing frame and get to centre of field GL.glPushMatrix() # push before drawing, pop after # push the data for client attributes GL.glPushClientAttrib(GL.GL_CLIENT_ALL_ATTRIB_BITS) # GL.glLoadIdentity() self.win.setScale('pix') cpcd = ctypes.POINTER(ctypes.c_double) GL.glColorPointer(4, GL.GL_DOUBLE, 0, self._RGBAs.ctypes.data_as(cpcd)) GL.glVertexPointer(3, GL.GL_DOUBLE, 0, self.verticesPix.ctypes.data_as(cpcd)) # setup the shaderprogram _prog = self.win._progSignedTexMask GL.glUseProgram(_prog) # set the texture to be texture unit 0 GL.glUniform1i(GL.glGetUniformLocation(_prog, b"texture"), 0) # mask is texture unit 1 GL.glUniform1i(GL.glGetUniformLocation(_prog, b"mask"), 1) # bind textures GL.glActiveTexture(GL.GL_TEXTURE1) GL.glBindTexture(GL.GL_TEXTURE_2D, self._maskID) GL.glEnable(GL.GL_TEXTURE_2D) GL.glActiveTexture(GL.GL_TEXTURE0) GL.glBindTexture(GL.GL_TEXTURE_2D, self._texID) GL.glEnable(GL.GL_TEXTURE_2D) # setup client texture coordinates first GL.glClientActiveTexture(GL.GL_TEXTURE0) GL.glTexCoordPointer(2, GL.GL_DOUBLE, 0, self._texCoords.ctypes) GL.glEnableClientState(GL.GL_TEXTURE_COORD_ARRAY) GL.glClientActiveTexture(GL.GL_TEXTURE1) GL.glTexCoordPointer(2, GL.GL_DOUBLE, 0, self._maskCoords.ctypes) GL.glEnableClientState(GL.GL_TEXTURE_COORD_ARRAY) GL.glEnableClientState(GL.GL_COLOR_ARRAY) GL.glEnableClientState(GL.GL_VERTEX_ARRAY) GL.glDrawArrays(GL.GL_QUADS, 0, self.verticesPix.shape[0] * 4) # unbind the textures GL.glActiveTexture(GL.GL_TEXTURE1) GL.glBindTexture(GL.GL_TEXTURE_2D, 0) GL.glDisable(GL.GL_TEXTURE_2D) # main texture GL.glActiveTexture(GL.GL_TEXTURE0) GL.glBindTexture(GL.GL_TEXTURE_2D, 0) GL.glDisable(GL.GL_TEXTURE_2D) # disable states GL.glDisableClientState(GL.GL_COLOR_ARRAY) GL.glDisableClientState(GL.GL_VERTEX_ARRAY) GL.glDisableClientState(GL.GL_TEXTURE_COORD_ARRAY) GL.glUseProgram(0) GL.glPopClientAttrib() GL.glPopMatrix() def _updateVertices(self): """Sets Stim.verticesPix from fieldPos. """ # Handle the orientation, size and location of # each element in native units radians = 0.017453292519943295 # so we can do matrix rotation of coords we need shape=[n*4,3] # but we'll convert to [n,4,3] after matrix math verts = numpy.zeros([self.nElements * 4, 3], 'd') wx = -self.sizes[:, 0] * numpy.cos(self.oris[:] * radians) / 2 wy = self.sizes[:, 0] * numpy.sin(self.oris[:] * radians) / 2 hx = self.sizes[:, 1] * numpy.sin(self.oris[:] * radians) / 2 hy = self.sizes[:, 1] * numpy.cos(self.oris[:] * radians) / 2 # X vals of each vertex relative to the element's centroid verts[0::4, 0] = -wx - hx verts[1::4, 0] = +wx - hx verts[2::4, 0] = +wx + hx verts[3::4, 0] = -wx + hx # Y vals of each vertex relative to the element's centroid verts[0::4, 1] = -wy - hy verts[1::4, 1] = +wy - hy verts[2::4, 1] = +wy + hy verts[3::4, 1] = -wy + hy # set of positions across elements positions = self.xys + self.fieldPos # depth verts[:, 2] = self.depths + self.fieldDepth # rotate, translate, scale by units if positions.shape[0] * 4 == verts.shape[0]: positions = positions.repeat(4, 0) verts[:, :2] = convertToPix(vertices=verts[:, :2], pos=positions, units=self.units, win=self.win) verts = verts.reshape([self.nElements, 4, 3]) # assign to self attribute; make sure it's contiguous self.__dict__['verticesPix'] = numpy.require(verts, requirements=['C']) self._needVertexUpdate = False # ---------------------------------------------------------------------- def updateElementColors(self): """Create a new array of self._RGBAs based on self.rgbs. Not needed by the user (simple call setColors()) For element arrays the self.rgbs values correspond to one element so this function also converts them to be one for each vertex of each element. """ N = self.nElements _RGBAs = numpy.zeros([len(self.verticesPix), 4], 'd') _RGBAs[:,:] = self._colors.render('rgba1') _RGBAs[:, -1] = self.opacities.reshape([N, ]) self._RGBAs = _RGBAs.reshape([len(self.verticesPix), 1, 4]).repeat(4, 1) self._needColorUpdate = False def updateTextureCoords(self): """Create a new array of self._maskCoords """ N = self.nElements self._maskCoords = numpy.array([[1, 0], [0, 0], [0, 1], [1, 1]], 'd').reshape([1, 4, 2]) self._maskCoords = self._maskCoords.repeat(N, 0) # for the main texture # sf is dependent on size (openGL default) if self.units in ['norm', 'pix', 'height']: L = (-self.sfs[:, 0] / 2) - self.phases[:, 0] + 0.5 R = (+self.sfs[:, 0] / 2) - self.phases[:, 0] + 0.5 T = (+self.sfs[:, 1] / 2) - self.phases[:, 1] + 0.5 B = (-self.sfs[:, 1] / 2) - self.phases[:, 1] + 0.5 else: # we should scale to become independent of size L = (-self.sfs[:, 0] * self.sizes[:, 0] / 2 - self.phases[:, 0] + 0.5) R = (+self.sfs[:, 0] * self.sizes[:, 0] / 2 - self.phases[:, 0] + 0.5) T = (+self.sfs[:, 1] * self.sizes[:, 1] / 2 - self.phases[:, 1] + 0.5) B = (-self.sfs[:, 1] * self.sizes[:, 1] / 2 - self.phases[:, 1] + 0.5) # self._texCoords=numpy.array([[1,1],[1,0],[0,0],[0,1]], # 'd').reshape([1,4,2]) self._texCoords = (numpy.concatenate([[R, B], [L, B], [L, T], [R, T]]) .transpose().reshape([N, 4, 2]).astype('d')) self._texCoords = numpy.ascontiguousarray(self._texCoords) self._needTexCoordUpdate = False @attributeSetter def elementTex(self, value): """The texture, to be used by all elements (e.g. 'sin', 'sqr',.. , 'myTexture.tif', numpy.ones([48,48])). Avoid this during time-critical points in your script. Uploading new textures to the graphics card can be time-consuming. """ self.__dict__['tex'] = value self._createTexture(value, id=self._texID, pixFormat=GL.GL_RGB, stim=self, res=self.texRes, maskParams=self.maskParams) def setTex(self, value, log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message. """ setAttribute(self, 'elementTex', value, log) @attributeSetter def depth(self, value): """(Nx1) list/array of ints. The depths of the elements, relative the overall depth of the field (fieldDepth). :ref:`operations <attrib-operations>` are supported. """ self.__dict__['depth'] = value self._updateVertices() @attributeSetter def fieldDepth(self, value): """Int. The depth of the field (will be added to the depths of the elements). :ref:`operations <attrib-operations>` are supported. """ self.__dict__['fieldDepth'] = value self._updateVertices() @attributeSetter def elementMask(self, value): """The mask, to be used by all elements (e.g. 'circle', 'gauss',... , 'myTexture.tif', numpy.ones([48,48])). This is just a synonym for ElementArrayStim.mask. See doc there. """ self.mask = value def __del__(self): # remove textures from graphics card to prevent OpenGl memory leak try: self.clearTextures() except (ImportError, ModuleNotFoundError, TypeError): pass # has probably been garbage-collected already
28,638
Python
.py
616
36.568182
84
0.600322
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,740
vlcmoviestim.py
psychopy_psychopy/psychopy/visual/vlcmoviestim.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """A stimulus class for playing movies (mpeg, avi, etc...) in PsychoPy using a local installation of VLC media player (https://www.videolan.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). # # VlcMovieStim originally contributed by Dan Fitch, April 2019. The `MovieStim2` # class was taken and rewritten to use only VLC. # import os import sys import threading import ctypes import weakref from psychopy import core, logging from psychopy.tools.attributetools import logAttrib, setAttribute from psychopy.tools.filetools import pathToString from psychopy.visual.basevisual import BaseVisualStim, ContainerMixin from psychopy.constants import FINISHED, NOT_STARTED, PAUSED, PLAYING, STOPPED import numpy import pyglet pyglet.options['debug_gl'] = False GL = pyglet.gl try: # check if the lib can be loaded import vlc haveVLC = True except Exception as err: haveVLC = False # store the error but only raise it if the if "wrong architecture" in str(err): msg = ("Failed to import `vlc` module required by `vlcmoviestim`.\n" "You're using %i-bit python. Is your VLC install the same?" % 64 if sys.maxsize == 2 ** 64 else 32) _vlcImportErr = OSError(msg) else: _vlcImportErr = err # flip time, and time since last movie frame flip will be printed reportNDroppedFrames = 10 class VlcMovieStim(BaseVisualStim, ContainerMixin): """A stimulus class for playing movies in various formats (mpeg, avi, etc...) in PsychoPy using the VLC media player as a decoder. This is a lazy-imported class, therefore import using full path `from psychopy.visual.vlcmoviestim import VlcMovieStim` when inheriting from it. This movie class is very efficient and better suited for playing high-resolution videos (720p+) than the other movie classes. However, audio is only played using the default output device. This may be adequate for most applications where the user is not concerned about precision audio onset times. The VLC media player (https://www.videolan.org/) must be installed on the machine running PsychoPy to use this class. Make certain that the version of VLC installed matches the architecture of the Python interpreter hosting PsychoPy. Parameters ---------- win : :class:`~psychopy.visual.Window` Window the video is being drawn to. filename : str Name of the file or stream URL to play. If an empty string, no file will be loaded on initialization but can be set later. units : str Units to use when sizing the video frame on the window, affects how `size` is interpreted. size : ArrayLike or None Size of the video frame on the window in `units`. If `None`, the native size of the video will be used. flipVert : bool If `True` then the movie will be top-bottom flipped. flipHoriz : bool If `True` then the movie will be right-left flipped. volume : int or float If specifying an `int` the nominal level is 100, and 0 is silence. If a `float`, values between 0 and 1 may be used. loop : bool Whether to start the movie over from the beginning if draw is called and the movie is done. Default is `False. autoStart : bool Automatically begin playback of the video when `flip()` is called. Notes ----- * You may see error messages in your log output from VLC (e.g., `get_buffer() failed`, `no frame!`, etc.) after shutting down. These errors originate from the decoder and can be safely ignored. """ def __init__(self, win, filename="", units='pix', size=None, pos=(0.0, 0.0), ori=0.0, flipVert=False, flipHoriz=False, color=(1.0, 1.0, 1.0), # remove? colorSpace='rgb', opacity=1.0, volume=1.0, name='', loop=False, autoLog=True, depth=0.0, noAudio=False, interpolate=True, autoStart=True): # check if we have the VLC lib if not haveVLC: raise _vlcImportErr # what local vars are defined (these are the init params) for use # by __repr__ self._initParams = dir() self._initParams.remove('self') super(VlcMovieStim, self).__init__(win, units=units, name=name, autoLog=False) # check for pyglet if win.winType != 'pyglet': logging.error('Movie stimuli can only be used with a pyglet window') core.quit() # drawing stuff self.flipVert = flipVert self.flipHoriz = flipHoriz self.pos = numpy.asarray(pos, float) # original size to keep BaseVisualStim happy self._origSize = numpy.asarray((128, 128,), float) # Defer setting size until after the video is loaded to use it's native # size instead of the one set by the user. self._useFrameSizeFromVideo = size is None if not self._useFrameSizeFromVideo: self.size = numpy.asarray(size, float) self.depth = depth self.opacity = float(opacity) # playback stuff self._filename = pathToString(filename) self._volume = volume self._noAudio = noAudio # cannot be changed self._currentFrame = -1 self._loopCount = 0 self.loop = loop # video pixel and texture buffer variables, setup later self.interpolate = interpolate # use setter self._textureId = GL.GLuint() self._pixbuffId = GL.GLuint() # VLC related attributes self._instance = None self._player = None self._manager = None self._stream = None self._videoWidth = 0 self._videoHeight = 0 self._frameRate = 0.0 self._vlcInitialized = False self._pixelLock = threading.Lock() # semaphore for VLC pixel transfer self._framePixelBuffer = None # buffer pointer to draw to self._videoFrameBufferSize = None self._streamEnded = False # spawn a VLC instance for this class instance # self._createVLCInstance() # load a movie if provided if self._filename: self.loadMovie(self._filename) self.setVolume(volume) self.nDroppedFrames = 0 self._autoStart = autoStart self.ori = ori # set autoLog (now that params have been initialised) self.autoLog = autoLog if autoLog: logging.exp("Created {} = {}".format(self.name, self)) @property def filename(self): """File name for the loaded video (`str`).""" return self._filename @filename.setter def filename(self, value): self.loadMovie(value) @property def autoStart(self): """Start playback when `.draw()` is called (`bool`).""" return self._autoStart @autoStart.setter def autoStart(self, value): self._autoStart = bool(value) def setMovie(self, filename, log=True): """See `~MovieStim.loadMovie` (the functions are identical). This form is provided for syntactic consistency with other visual stimuli. """ self.loadMovie(filename, log=log) def loadMovie(self, filename, log=True): """Load a movie from file Parameters ---------- filename : str The name of the file or URL, including path if necessary. log : bool Log this event. Notes ----- * Due to VLC oddness, `.duration` is not correct until the movie starts playing. """ self._filename = pathToString(filename) # open the media using a new player self._openMedia() self.status = NOT_STARTED logAttrib(self, log, 'movie', filename) def _createVLCInstance(self): """Internal method to create a new VLC instance. Raises an error if an instance is already spawned and hasn't been released. """ logging.debug("Spawning new VLC instance ...") # Creating VLC instances is slow, so we want to create once per class # instantiation and reuse it as much as possible. Stopping and starting # instances too frequently can result in an errors and affect the # stability of the system. if self._instance is not None: self._releaseVLCInstance() # errmsg = ("Attempted to create another VLC instance without " # "releasing the previous one first!") # logging.fatal(errmsg, obj=self) # logging.flush() # raise RuntimeError(errmsg) # Using "--quiet" here is just sweeping anything VLC pukes out under the # rug. Most of the time the errors only look scary but can be ignored. params = " ".join( ["--no-audio" if self._noAudio else "", "--sout-keep", "--quiet"]) self._instance = vlc.Instance(params) # used to capture log messages from VLC self._instance.log_set(vlcLogCallback, None) # create a new player object, reusable by by just changing the stream self._player = self._instance.media_player_new() # setup the event manager self._manager = self._player.event_manager() # self._manager.event_attach( # vlc.EventType.MediaPlayerTimeChanged, vlcMediaEventCallback, # weakref.ref(self), self._player) self._manager.event_attach( vlc.EventType.MediaPlayerEndReached, vlcMediaEventCallback, weakref.ref(self), self._player) self._vlcInitialized = True logging.debug("VLC instance created.") def _releaseVLCInstance(self): """Internal method to release a VLC instance. Calling this implicitly stops and releases any stream presently loaded and playing. """ self._vlcInitialized = False if self._player is not None: self._player.stop() # shutdown the manager self._manager.event_detach(vlc.EventType.MediaPlayerEndReached) self._manager = None # Doing this here since I figured Python wasn't shutting down due to # callbacks remaining bound. Seems to actually fix the problem. self._player.video_set_callbacks(None, None, None, None) self._player.set_media(None) self._player.release() self._player = None # reset video information self._filename = None self._videoWidth = self._videoHeight = 0 self._frameCounter = self._loopCount = 0 self._frameRate = 0.0 self._framePixelBuffer = None if self._stream is not None: self._stream.release() self._streamEnded = False self._stream = None if self._instance is not None: self._instance.release() self._instance = None self.status = STOPPED def _openMedia(self, uri=None): """Internal method that opens a new stream using `filename`. This will close the previous stream. Raises an error if a VLC instance is not available. """ # if None, use `filename` uri = self.filename if uri is None else uri # create a fresh VLC instance self._createVLCInstance() # raise error if there is no VLC instance if self._instance is None: errmsg = "Cannot open a stream without a VLC instance started." logging.fatal(errmsg, obj=self) logging.flush() # check if we have a player, stop it if so if self._player is None: errmsg = "Cannot open a stream without a VLC media player." logging.fatal(errmsg, obj=self) logging.flush() else: self._player.stop() # stop any playback # check if the file is valid and readable if not os.access(uri, os.R_OK): raise RuntimeError('Error: %s file not readable' % uri) # close the previous VLC resources if needed if self._stream is not None: self._stream.release() # open the file and create a new stream try: self._stream = self._instance.media_new(uri) except NameError: raise ImportError('NameError: %s vs LibVLC %s' % ( vlc.__version__, vlc.libvlc_get_version())) # player object self._player.set_media(self._stream) # set media related attributes self._stream.parse() videoWidth, videoHeight = self._player.video_get_size() self._videoWidth = videoWidth self._videoHeight = videoHeight # set the video size if self._useFrameSizeFromVideo: self.size = self._origSize = numpy.array( (self._videoWidth, self._videoHeight), float) self._frameRate = self._player.get_fps() self._frameCounter = self._loopCount = 0 self._streamEnded = False # uncomment if not using direct GPU write, might be more thread-safe self._framePixelBuffer = ( ctypes.c_ubyte * self._videoWidth * self._videoHeight * 4)() # duration unavailable until started duration = self._player.get_length() logging.info("Video is %ix%i, duration %s, fps %s" % ( self._videoWidth, self._videoHeight, duration, self._frameRate)) logging.flush() # We assume we can use the RGBA format here self._player.video_set_format( "RGBA", self._videoWidth, self._videoHeight, self._videoWidth << 2) # setup texture buffers before binding the callbacks self._setupTextureBuffers() # Set callbacks since we have the resources to write to. thisInstance = ctypes.cast( ctypes.pointer(ctypes.py_object(self)), ctypes.c_void_p) # we need to increment the ref count ctypes.pythonapi.Py_IncRef(ctypes.py_object(thisInstance)) self._player.video_set_callbacks( vlcLockCallback, vlcUnlockCallback, vlcDisplayCallback, thisInstance) def _closeMedia(self): """Internal method to release the presently loaded stream (if any). """ self._vlcInitialized = False if self._player is not None: # stop any playback self._player.stop() self._player.set_media(None) if self._stream is None: return # nop self._stream.release() self._stream = self._player = None self._useFrameSizeFromVideo = True self._releaseVLCInstance() # unregister callbacks before freeing buffers self._freeBuffers() GL.glFlush() def _onEos(self): """Internal method called when the decoder encounters the end of the stream. """ # Do not call the libvlc API in this method, causes a deadlock which # freezes PsychoPy. Just set the flag below and the stream will restart # on the next `.draw()` call. self._streamEnded = True if not self.loop: self.status = FINISHED if self.autoLog: self.win.logOnFlip( "Set %s finished" % self.name, level=logging.EXP, obj=self) def _freeBuffers(self): """Free texture and pixel buffers. Call this when tearing down this class or if a movie is stopped. """ try: # delete buffers and textures if previously created if self._pixbuffId.value > 0: GL.glDeleteBuffers(1, self._pixbuffId) self._pixbuffId = GL.GLuint() # delete the old texture if present if self._textureId.value > 0: GL.glDeleteTextures(1, self._textureId) self._textureId = GL.GLuint() except TypeError: # can happen when unloading or shutting down pass def _setupTextureBuffers(self): """Setup texture buffers which hold frame data. This creates a 2D RGB texture and pixel buffer. The pixel buffer serves as the store for texture color data. Each frame, the pixel buffer memory is mapped and frame data is copied over to the GPU from the decoder. This is called every time a video file is loaded. The `_freeBuffers` method is called in this routine prior to creating new buffers, so it's safe to call this right after loading a new movie without having to `_freeBuffers` first. """ self._freeBuffers() # clean up any buffers previously allocated # Calculate the total size of the pixel store in bytes needed to hold a # single video frame. This value is reused during the pixel upload # process. Assumes RGBA color format. self._videoFrameBufferSize = \ self._videoWidth * self._videoHeight * 4 * ctypes.sizeof(GL.GLubyte) # Create the pixel buffer object which will serve as the texture memory # store. Pixel data will be copied to this buffer each frame. GL.glGenBuffers(1, ctypes.byref(self._pixbuffId)) GL.glBindBuffer(GL.GL_PIXEL_UNPACK_BUFFER, self._pixbuffId) GL.glBufferData( GL.GL_PIXEL_UNPACK_BUFFER, self._videoFrameBufferSize, None, GL.GL_STREAM_DRAW) # one-way app -> GL GL.glBindBuffer(GL.GL_PIXEL_UNPACK_BUFFER, 0) # Create a texture which will hold the data streamed to the pixel # buffer. Only one texture needs to be allocated. GL.glGenTextures(1, ctypes.byref(self._textureId)) GL.glBindTexture(GL.GL_TEXTURE_2D, self._textureId) GL.glTexImage2D( GL.GL_TEXTURE_2D, 0, GL.GL_RGBA8, self._videoWidth, self._videoHeight, # frame dims in pixels 0, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, None) GL.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, 1) # needs to be 1 # setup texture filtering if self.interpolate: texFilter = GL.GL_LINEAR else: texFilter = GL.GL_NEAREST GL.glTexParameteri( GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, texFilter) GL.glTexParameteri( GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, texFilter) GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, GL.GL_CLAMP) GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_CLAMP) GL.glBindTexture(GL.GL_TEXTURE_2D, 0) GL.glFlush() # make sure all buffers are ready @property def frameTexture(self): """Texture ID for the current video frame (`GLuint`). You can use this as a video texture. However, you must periodically call `updateTexture` to keep this up to date. """ return self._textureId def _pixelTransfer(self): """Internal method which maps the pixel buffer for the video texture to client memory, allowing for VLC to directly draw a video frame to it. This method is not thread-safe and should never be called without the pixel lock semaphore being first set by VLC. """ # bind pixel unpack buffer GL.glBindBuffer(GL.GL_PIXEL_UNPACK_BUFFER, self._pixbuffId) # Free last storage buffer before mapping and writing new frame data. # This allows the GPU to process the extant buffer in VRAM uploaded last # cycle without being stalled by the CPU accessing it. Also allows VLC # to access the buffer while the previous one is still in use. GL.glBufferData( GL.GL_PIXEL_UNPACK_BUFFER, self._videoFrameBufferSize, None, GL.GL_STREAM_DRAW) # Map the buffer to client memory, `GL_WRITE_ONLY` to tell the driver to # optimize for a one-way write operation if it can. bufferPtr = GL.glMapBuffer( GL.GL_PIXEL_UNPACK_BUFFER, GL.GL_WRITE_ONLY) # comment to disable direct VLC -> GPU frame write # self._framePixelBuffer = bufferPtr # uncomment if not using direct GPU write, might provide better thread # safety ... ctypes.memmove( bufferPtr, ctypes.byref(self._framePixelBuffer), ctypes.sizeof(self._framePixelBuffer)) # Very important that we unmap the buffer data after copying, but # keep the buffer bound for setting the texture. GL.glUnmapBuffer(GL.GL_PIXEL_UNPACK_BUFFER) # bind the texture in OpenGL GL.glEnable(GL.GL_TEXTURE_2D) # copy the PBO to the texture GL.glBindTexture(GL.GL_TEXTURE_2D, self._textureId) GL.glTexSubImage2D( GL.GL_TEXTURE_2D, 0, 0, 0, self._videoWidth, self._videoHeight, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, 0) # point to the presently bound buffer # update texture filtering only if needed if self._texFilterNeedsUpdate: if self.interpolate: texFilter = GL.GL_LINEAR else: texFilter = GL.GL_NEAREST GL.glTexParameteri( GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, texFilter) GL.glTexParameteri( GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, texFilter) self._texFilterNeedsUpdate = False # important to unbind the PBO GL.glBindBuffer(GL.GL_PIXEL_UNPACK_BUFFER, 0) GL.glBindTexture(GL.GL_TEXTURE_2D, 0) GL.glDisable(GL.GL_TEXTURE_2D) def updateTexture(self): """Update the video texture buffer to the most recent video frame. """ with self._pixelLock: self._pixelTransfer() # -------------------------------------------------------------------------- # Video playback controls and status # @property def isPlaying(self): """`True` if the video is presently playing (`bool`).""" # Status flags as properties are pretty useful for users since they are # self documenting and prevent the user from touching the status flag # attribute directly. # return self.status == PLAYING @property def isNotStarted(self): """`True` if the video has not be started yet (`bool`). This status is given after a video is loaded and play has yet to be called.""" return self.status == NOT_STARTED @property def isStopped(self): """`True` if the video is stopped (`bool`).""" return self.status == STOPPED @property def isPaused(self): """`True` if the video is presently paused (`bool`).""" return self.status == PAUSED @property def isFinished(self): """`True` if the video is finished (`bool`).""" # why is this the same as STOPPED? return self.status == FINISHED def play(self, log=True): """Start or continue a paused movie from current position. Parameters ---------- log : bool Log the play event. Returns ------- int or None Frame index playback started at. Should always be `0` if starting at the beginning of the video. Returns `None` if the player has not been initialized. """ if self.isNotStarted: # video has not been played yet if log and self.autoLog: self.win.logOnFlip( "Set %s playing" % self.name, level=logging.EXP, obj=self) self._player.play() elif self.isPaused: self.win.logOnFlip( "Resuming playback at position {:.4f}".format( self._player.get_time() / 1000.0), level=logging.EXP, obj=self) if self._player.will_play(): self._player.play() self.status = PLAYING return self._currentFrame def pause(self, log=True): """Pause the current point in the movie. Parameters ---------- log : bool Log the pause event. """ if self.isPlaying: self.status = PAUSED player = self._player if player and player.can_pause(): player.pause() if log and self.autoLog: self.win.logOnFlip("Set %s paused" % self.name, level=logging.EXP, obj=self) return True if log and self.autoLog: self.win.logOnFlip("Failed Set %s paused" % self.name, level=logging.EXP, obj=self) return False def stop(self, log=True): """Stop the current point in the movie (sound will stop, current frame will not advance). Once stopped the movie cannot be restarted - it must be loaded again. Use `pause()` instead if you may need to restart the movie. Parameters ---------- log : bool Log the stop event. """ if self._player is None: return self.status = STOPPED if log and self.autoLog: self.win.logOnFlip( "Set %s stopped" % self.name, level=logging.EXP, obj=self) self._releaseVLCInstance() def seek(self, timestamp, log=True): """Seek to a particular timestamp in the movie. Parameters ---------- timestamp : float Time in seconds. log : bool Log the seek event. """ if self.isPlaying or self.isPaused: player = self._player if player and player.is_seekable(): # pause while seeking player.set_time(int(timestamp * 1000.0)) if log: logAttrib(self, log, 'seek', timestamp) def rewind(self, seconds=5): """Rewind the video. Parameters ---------- seconds : float Time in seconds to rewind from the current position. Default is 5 seconds. Returns ------- float Timestamp after rewinding the video. """ self.seek(max(self.getCurrentFrameTime() - float(seconds), 0.0)) # after seeking return self.getCurrentFrameTime() def fastForward(self, seconds=5): """Fast-forward the video. Parameters ---------- seconds : float Time in seconds to fast forward from the current position. Default is 5 seconds. Returns ------- float Timestamp at new position after fast forwarding the video. """ self.seek( min(self.getCurrentFrameTime() + float(seconds), self.duration)) return self.getCurrentFrameTime() def replay(self, autoPlay=True): """Replay the movie from the beginning. Parameters ---------- autoPlay : bool Start playback immediately. If `False`, you must call `play()` afterwards to initiate playback. Notes ----- * This tears down the current VLC instance and creates a new one. Similar to calling `stop()` and `loadMovie()`. Use `seek(0.0)` if you would like to restart the movie without reloading. """ lastMovieFile = self._filename self.stop() self.loadMovie(lastMovieFile) if autoPlay: self.play() # -------------------------------------------------------------------------- # Volume controls # @property def volume(self): """Audio track volume (`int` or `float`). See `setVolume` for more information about valid values. """ return self.getVolume() @volume.setter def volume(self, value): self.setVolume(value) def setVolume(self, volume): """Set the audio track volume. Parameters ---------- volume : int or float Volume level to set. 0 = mute, 100 = 0 dB. float values between 0.0 and 1.0 are also accepted, and scaled to an int between 0 and 100. """ if self._player: if 0.0 <= volume <= 1.0 and isinstance(volume, float): v = int(volume * 100) else: v = int(volume) self._volume = v if self._player: self._player.audio_set_volume(v) def getVolume(self): """Returns the current movie audio volume. Returns ------- int Volume level, 0 is no audio, 100 is max audio volume. """ if self._player: self._volume = self._player.audio_get_volume() return self._volume def increaseVolume(self, amount=10): """Increase the volume. Parameters ---------- amount : int Increase the volume by this amount (percent). This gets added to the present volume level. If the value of `amount` and the current volume is outside the valid range of 0 to 100, the value will be clipped. The default value is 10 (or 10% increase). Returns ------- int Volume after changed. See also -------- getVolume setVolume decreaseVolume Examples -------- Adjust the volume of the current video using key presses:: # assume `mov` is an instance of this class defined previously for key in event.getKeys(): if key == 'minus': mov.decreaseVolume() elif key == 'equals': mov.increaseVolume() """ if not self._player: return 0 self.setVolume(min(max(self.getVolume() + int(amount), 0), 100)) return self._volume def decreaseVolume(self, amount=10): """Decrease the volume. Parameters ---------- amount : int Decrease the volume by this amount (percent). This gets subtracted from the present volume level. If the value of `amount` and the current volume is outside the valid range of 0 to 100, the value will be clipped. The default value is 10 (or 10% decrease). Returns ------- int Volume after changed. See also -------- getVolume setVolume increaseVolume Examples -------- Adjust the volume of the current video using key presses:: # assume `mov` is an instance of this class defined previously for key in event.getKeys(): if key == 'minus': mov.decreaseVolume() elif key == 'equals': mov.increaseVolume() """ if not self._player: return 0 self.setVolume(min(max(self.getVolume() - int(amount), 0), 100)) return self._volume # -------------------------------------------------------------------------- # Video and playback information # @property def frameIndex(self): """Current frame index being displayed (`int`).""" return self._currentFrame def getCurrentFrameNumber(self): """Get the current movie frame number (`int`), same as `frameIndex`. """ return self._frameCounter @property def percentageComplete(self): """Percentage of the video completed (`float`).""" return self.getPercentageComplete() @property def duration(self): """Duration of the loaded video in seconds (`float`). Not valid unless the video has been started. """ if not self.isNotStarted: return self._player.get_length() return 0.0 @property def loopCount(self): """Number of loops completed since playback started (`int`). This value is reset when either `stop` or `loadMovie` is called. """ return self._loopCount @property def fps(self): """Movie frames per second (`float`).""" return self.getFPS() def getFPS(self): """Movie frames per second. Returns ------- float Nominal number of frames to be displayed per second. """ return self._frameRate @property def frameTime(self): """Current frame time in seconds (`float`).""" return self.getCurrentFrameTime() def getCurrentFrameTime(self): """Get the time that the movie file specified the current video frame as having. Returns ------- float Current video time in seconds. """ if not self._player: return 0.0 return self._player.get_time() / 1000.0 def getPercentageComplete(self): """Provides a value between 0.0 and 100.0, indicating the amount of the movie that has been already played. """ return self._player.get_position() * 100.0 @property def videoSize(self): """Size of the video `(w, h)` in pixels (`tuple`). Returns `(0, 0)` if no video is loaded.""" if self._stream is not None: return self._videoWidth, self._videoHeight return 0, 0 # -------------------------------------------------------------------------- # Drawing methods and properties # @property def interpolate(self): """Enable linear interpolation (`bool'). If `True` linear filtering will be applied to the video making the image less pixelated if scaled. You may leave this off if the native size of the video is used. """ return self._interpolate @interpolate.setter def interpolate(self, value): self._interpolate = value self._texFilterNeedsUpdate = True def setFlipHoriz(self, newVal=True, log=True): """If set to True then the movie will be flipped horizontally (left-to-right). Note that this is relative to the original, not relative to the current state. """ self.flipHoriz = newVal logAttrib(self, log, 'flipHoriz') def setFlipVert(self, newVal=True, log=True): """If set to True then the movie will be flipped vertically (top-to-bottom). Note that this is relative to the original, not relative to the current state. """ self.flipVert = not newVal logAttrib(self, log, 'flipVert') def _drawRectangle(self): """Draw the frame to the window. This is called by the `draw()` method. """ # make sure that textures are on and GL_TEXTURE0 is activ GL.glEnable(GL.GL_TEXTURE_2D) GL.glActiveTexture(GL.GL_TEXTURE0) # sets opacity (1, 1, 1 = RGB placeholder) GL.glColor4f(1, 1, 1, self.opacity) GL.glPushMatrix() self.win.setScale('pix') # move to centre of stimulus and rotate vertsPix = self.verticesPix array = (GL.GLfloat * 32)( 1, 1, # texture coords vertsPix[0, 0], vertsPix[0, 1], 0., # vertex 0, 1, vertsPix[1, 0], vertsPix[1, 1], 0., 0, 0, vertsPix[2, 0], vertsPix[2, 1], 0., 1, 0, vertsPix[3, 0], vertsPix[3, 1], 0., ) GL.glPushAttrib(GL.GL_ENABLE_BIT) GL.glBindTexture(GL.GL_TEXTURE_2D, self._textureId) GL.glPushClientAttrib(GL.GL_CLIENT_VERTEX_ARRAY_BIT) # 2D texture array, 3D vertex array GL.glInterleavedArrays(GL.GL_T2F_V3F, 0, array) GL.glDrawArrays(GL.GL_QUADS, 0, 4) GL.glPopClientAttrib() GL.glPopAttrib() GL.glPopMatrix() GL.glBindTexture(GL.GL_TEXTURE_2D, 0) GL.glEnable(GL.GL_TEXTURE_2D) def draw(self, win=None): """Draw the current frame to a particular :class:`~psychopy.visual.Window` (or to the default win for this object if not specified). The current position in the movie will be determined automatically. This method should be called on every frame that the movie is meant to appear. Parameters ---------- win : :class:`~psychopy.visual.Window` or `None` Window the video is being drawn to. If `None`, the window specified at initialization will be used instead. Returns ------- bool `True` if the frame was updated this draw call. """ if self.isNotStarted and self._autoStart: self.play() elif self._streamEnded and self.loop: self._loopCount += 1 self._streamEnded = False self.replay() elif self.isFinished: self.stop() return False self._selectWindow(self.win if win is None else win) # check if we need to pull a new frame this round if self._currentFrame == self._frameCounter: # update the texture, getting the most recent frame self.updateTexture() # draw the frame to the window self._drawRectangle() return False # frame does not need an update this round # Below not called if the frame hasn't advanced yet ------ # update the current frame self._currentFrame = self._frameCounter # update the texture, getting the most recent frame self.updateTexture() # draw the frame to the window self._drawRectangle() # token gesture for existing code, we handle this logic internally now return True def setAutoDraw(self, val, log=None): """Add or remove a stimulus from the list of stimuli that will be automatically drawn on each flip :parameters: - val: True/False True to add the stimulus to the draw list, False to remove it """ if val: self.play(log=False) # set to play in case stopped else: self.pause(log=False) # add to drawing list and update status setAttribute(self, 'autoDraw', val, log) def __del__(self): try: if hasattr(self, '_player'): # false if crashed before creating instance self._releaseVLCInstance() except (ImportError, ModuleNotFoundError, TypeError): pass # has probably been garbage-collected already # ------------------------------------------------------------------------------ # Callback functions for `libvlc` # # WARNING: Due to a limitation of libvlc, you cannot call the API from within # the callbacks below. Doing so will result in a deadlock that stalls the # application. This applies to any method in the `VloMovieStim` class being # called within a callback too. They cannot have any libvlc calls anywhere in # the call stack. # @vlc.CallbackDecorators.VideoLockCb def vlcLockCallback(user_data, planes): """Callback invoked when VLC has new texture data. """ # Need to catch errors caused if a NULL object is passed. Not sure why this # happens but it might be due to the callback being invoked before the # movie stim class is fully realized. This may happen since the VLC library # operates in its own thread and may be processing frames before we are # ready to use them. This `try-except` structure is present in all callback # functions here that pass `user_data` which is a C pointer to the stim # object. Right now, these functions just return when we get a NULL object. # try: cls = ctypes.cast( user_data, ctypes.POINTER(ctypes.py_object)).contents.value except (ValueError, TypeError): return cls._pixelLock.acquire() # tell VLC to take the data and stuff it into the buffer planes[0] = ctypes.cast(cls._framePixelBuffer, ctypes.c_void_p) @vlc.CallbackDecorators.VideoUnlockCb def vlcUnlockCallback(user_data, picture, planes): """Called when VLC releases the frame draw buffer. """ try: cls = ctypes.cast( user_data, ctypes.POINTER(ctypes.py_object)).contents.value except (ValueError, TypeError): return cls._pixelLock.release() @vlc.CallbackDecorators.VideoDisplayCb def vlcDisplayCallback(user_data, picture): """Callback used by VLC when its ready to display a new frame. """ try: cls = ctypes.cast( user_data, ctypes.POINTER(ctypes.py_object)).contents.value except (ValueError, TypeError): return cls._frameCounter += 1 @vlc.CallbackDecorators.LogCb def vlcLogCallback(user_data, level, ctx, fmt, args): """Callback for logging messages emitted by VLC. Processed here and converted to PsychoPy logging format. """ # if level == vlc.DEBUG: # logging.debug() pass # suppress messages from VLC, look scary but can be mostly ignored def vlcMediaEventCallback(event, user_data, player): """Callback used by VLC for handling media player events. """ if not user_data(): return cls = user_data() # ref to movie class event = event.type if event == vlc.EventType.MediaPlayerEndReached: cls._onEos() if __name__ == "__main__": pass
42,414
Python
.py
1,041
31.095101
80
0.602107
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,741
globalVars.py
psychopy_psychopy/psychopy/visual/globalVars.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """This stores variables that are needed globally through the visual package. It needs to be imported by anything that uses those variables as: from psychopy.visual import globalVars print(globalVars.currWindow) # read it globalVars.currentWindow = newWin # change it Note that if you import using:: from psychopy.visual.globalVars import currWindow then if the variable changes your copy won't! """ currWindow = None # for logging purposes, how many times have we resized an image: nImageResizes = 0
575
Python
.py
14
38.214286
77
0.771325
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,742
dot.py
psychopy_psychopy/psychopy/visual/dot.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """This stimulus class defines a field of dots with an update rule that determines how they change on every call to the .draw() method. """ # 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). # Bugfix by Andrew Schofield. # Replaces out of bounds but still live dots at opposite edge of aperture # instead of randomly within the field. This stops the concentration of dots at # one side of field when lifetime is long. # Update the dot direction immediately for 'walk' as otherwise when the # coherence varies some signal dots will inherit the random directions of # previous walking dots. # Provide a visible wrapper function to refresh all the dot locations so that # the whole field can be more easily refreshed between trials. # Ensure setting pyglet.options['debug_gl'] to False is done prior to any # other calls to pyglet or pyglet submodules, otherwise it may not get picked # up by the pyglet GL engine and have no effect. # Shaders will work but require OpenGL2.0 drivers AND PyOpenGL3.0+ import pyglet pyglet.options['debug_gl'] = False import ctypes GL = pyglet.gl import psychopy # so we can get the __path__ from psychopy import logging # tools must only be imported *after* event or MovieStim breaks on win32 # (JWP has no idea why!) from psychopy.tools.attributetools import attributeSetter, setAttribute from psychopy.tools.arraytools import val2array from psychopy.visual.basevisual import (BaseVisualStim, ColorMixin, ContainerMixin, WindowMixin) from psychopy.layout import Size import numpy as np # some constants _piOver2 = np.pi / 2. _piOver180 = np.pi / 180. _2pi = 2 * np.pi class DotStim(BaseVisualStim, ColorMixin, ContainerMixin): """This stimulus class defines a field of dots with an update rule that determines how they change on every call to the .draw() method. This is a lazy-imported class, therefore import using full path `from psychopy.visual.dot import DotStim` when inheriting from it. This single class can be used to generate a wide variety of dot motion types. For a review of possible types and their pros and cons see Scase, Braddick & Raymond (1996). All six possible motions they describe can be generated with appropriate choices of the `signalDots` (which determines whether signal dots are the 'same' or 'different' on each frame), `noiseDots` (which determines the locations of the noise dots on each frame) and the `dotLife` (which determines for how many frames the dot will continue before being regenerated). The default settings (as of v1.70.00) is for the noise dots to have identical velocity but random direction and signal dots remain the 'same' (once a signal dot, always a signal dot). For further detail about the different configurations see :ref:`dots` in the Builder Components section of the documentation. If further customisation is required, then the DotStim should be subclassed and its _update_dotsXY and _newDotsXY methods overridden. The maximum number of dots that can be drawn is limited by system performance. Attributes ---------- fieldShape : str *'sqr'* or 'circle'. Defines the envelope used to present the dots. If changed while drawing, dots outside new envelope will be respawned. dotSize : float Dot size specified in pixels (overridden if `element` is specified). :ref:`operations <attrib-operations>` are supported. dotLife : int Number of frames each dot lives for (-1=infinite). Dot lives are initiated randomly from a uniform distribution from 0 to dotLife. If changed while drawing, the lives of all dots will be randomly initiated again. signalDots : str If 'same' then the signal and noise dots are constant. If 'different' then the choice of which is signal and which is noise gets randomised on each frame. This corresponds to Scase et al's (1996) categories of RDK. noiseDots : str Determines the behaviour of the noise dots, taken directly from Scase et al's (1996) categories. For 'position', noise dots take a random position every frame. For 'direction' noise dots follow a random, but constant direction. For 'walk' noise dots vary their direction every frame, but keep a constant speed. element : object This can be any object that has a ``.draw()`` method and a ``.setPos([x,y])`` method (e.g. a GratingStim, TextStim...)!! DotStim assumes that the element uses pixels as units. ``None`` defaults to dots. fieldPos : array_like Specifying the location of the centre of the stimulus using a :ref:`x,y-pair <attrib-xy>`. See e.g. :class:`.ShapeStim` for more documentation/examples on how to set position. :ref:`operations <attrib-operations>` are supported. fieldSize : array_like Specifying the size of the field of dots using a :ref:`x,y-pair <attrib-xy>`. See e.g. :class:`.ShapeStim` for more documentation/examples on how to set position. :ref:`operations <attrib-operations>` are supported. coherence : float Change the coherence (%) of the DotStim. This will be rounded according to the number of dots in the stimulus. dir : float Direction of the coherent dots in degrees. :ref:`operations <attrib-operations>` are supported. speed : float Speed of the dots (in *units*/frame). :ref:`operations <attrib-operations>` are supported. """ def __init__(self, win, units='', nDots=1, coherence=0.5, fieldPos=(0.0, 0.0), fieldSize=(1.0, 1.0), fieldShape='sqr', fieldAnchor="center", dotSize=2.0, dotLife=3, dir=0.0, speed=0.5, rgb=None, color=(1.0, 1.0, 1.0), colorSpace='rgb', opacity=None, contrast=1.0, depth=0, element=None, signalDots='same', noiseDots='direction', name=None, autoLog=None): """ Parameters ---------- win : window.Window Window this stimulus is associated with. units : str Units to use. nDots : int Number of dots to present in the field. coherence : float Proportion of dots which are coherent. This value can be set using the `coherence` property after initialization. fieldPos : array_like (x,y) or [x,y] position of the field. This value can be set using the `fieldPos` property after initialization. fieldSize : array_like, int or float (x,y) or [x,y] or single value (applied to both dimensions). Sizes can be negative and can extend beyond the window. This value can be set using the `fieldSize` property after initialization. fieldShape : str Defines the envelope used to present the dots. If changed while drawing by setting the `fieldShape` property, dots outside new envelope will be respawned., valid values are 'square', 'sqr' or 'circle'. dotSize : array_like or float Size of the dots. If given an array, the sizes of individual dots will be set. The array must have length `nDots`. If a single value is given, all dots will be set to the same size. dotLife : int Lifetime of a dot in frames. Dot lives are initiated randomly from a uniform distribution from 0 to dotLife. If changed while drawing, the lives of all dots will be randomly initiated again. A value of -1 results in dots having an infinite lifetime. This value can be set using the `dotLife` property after initialization. dir : float Direction of the coherent dots in degrees. At 0 degrees, coherent dots will move from left to right. Increasing the angle will rotate the direction counter-clockwise. This value can be set using the `dir` property after initialization. speed : float Speed of the dots (in *units* per frame). This value can be set using the `speed` property after initialization. rgb : array_like, optional Color of the dots in form (r, g, b) or [r, g, b]. **Deprecated**, use `color` instead. color : array_like or str Color of the dots in form (r, g, b) or [r, g, b]. colorSpace : str Colorspace to use. opacity : float Opacity of the dots from 0.0 to 1.0. contrast : float Contrast of the dots 0.0 to 1.0. This value is simply multiplied by the `color` value. depth : float **Deprecated**, depth is now controlled simply by drawing order. element : object This can be any object that has a ``.draw()`` method and a ``.setPos([x,y])`` method (e.g. a GratingStim, TextStim...)!! DotStim assumes that the element uses pixels as units. ``None`` defaults to dots. signalDots : str If 'same' then the signal and noise dots are constant. If different then the choice of which is signal and which is noise gets randomised on each frame. This corresponds to Scase et al's (1996) categories of RDK. This value can be set using the `signalDots` property after initialization. noiseDots : str Determines the behaviour of the noise dots, taken directly from Scase et al's (1996) categories. For 'position', noise dots take a random position every frame. For 'direction' noise dots follow a random, but constant direction. For 'walk' noise dots vary their direction every frame, but keep a constant speed. This value can be set using the `noiseDots` property after initialization. name : str, optional Optional name to use for logging. autoLog : bool Enable automatic logging. """ # what local vars are defined (these are the init params) for use by # __repr__ self._initParams = __builtins__['dir']() self._initParams.remove('self') super(DotStim, self).__init__(win, units=units, name=name, autoLog=False) # set at end of init self.nDots = nDots # pos and size are ambiguous for dots so DotStim explicitly has # fieldPos = pos, fieldSize=size and then dotSize as additional param self.fieldPos = fieldPos # self.pos is also set here self.fieldSize = val2array(fieldSize, False) # self.size is also set if type(dotSize) in (tuple, list): self.dotSize = np.array(dotSize) else: self.dotSize = dotSize if self.win.useRetina: self.dotSize *= 2 # double dot size to make up for 1/2-size pixels self.fieldShape = fieldShape self.__dict__['dir'] = dir self.speed = speed self.element = element self.dotLife = dotLife self.signalDots = signalDots if rgb != None: logging.warning("Use of rgb arguments to stimuli are deprecated." " Please use color and colorSpace args instead") self.colorSpace = 'rgba' self.color = rgb else: self.colorSpace = colorSpace self.color = color self.opacity = opacity self.contrast = float(contrast) self.depth = depth # initialise the dots themselves - give them all random dir and then # fix the first n in the array to have the direction specified self.coherence = coherence # using the attributeSetter self.noiseDots = noiseDots # initialise a random array of X,Y self.vertices = self._verticesBase = self._dotsXY = self._newDotsXY(self.nDots) # all dots have the same speed self._dotsSpeed = np.ones(self.nDots, dtype=float) * self.speed # abs() means we can ignore the -1 case (no life) self._dotsLife = np.abs(dotLife) * np.random.rand(self.nDots) # pre-allocate array for flagging dead dots self._deadDots = np.zeros(self.nDots, dtype=bool) # set directions (only used when self.noiseDots='direction') self._dotsDir = np.random.rand(self.nDots) * _2pi self._dotsDir[self._signalDots] = self.dir * _piOver180 self._update_dotsXY() self.anchor = fieldAnchor # set autoLog now that params have been initialised wantLog = autoLog is None and self.win.autoLog self.__dict__['autoLog'] = autoLog or wantLog if self.autoLog: logging.exp("Created %s = %s" % (self.name, str(self))) def set(self, attrib, val, op='', log=None): """DEPRECATED: DotStim.set() is obsolete and may not be supported in future versions of PsychoPy. Use the specific method for each parameter instead (e.g. setFieldPos(), setCoherence()...). """ self._set(attrib, val, op, log=log) @attributeSetter def fieldShape(self, fieldShape): """*'sqr'* or 'circle'. Defines the envelope used to present the dots. If changed while drawing, dots outside new envelope will be respawned. """ self.__dict__['fieldShape'] = fieldShape @property def anchor(self): return WindowMixin.anchor.fget(self) @anchor.setter def anchor(self, value): WindowMixin.anchor.fset(self, value) def setAnchor(self, value, log=None): setAttribute(self, 'anchor', value, log) @property def dotSize(self): """Float specified in pixels (overridden if `element` is specified). :ref:`operations <attrib-operations>` are supported.""" if hasattr(self, "_dotSize"): return getattr(self._dotSize, 'pix')[0] @dotSize.setter def dotSize(self, value): self._dotSize = Size(value, units='pix', win=self.win) @attributeSetter def dotLife(self, dotLife): """Int. Number of frames each dot lives for (-1=infinite). Dot lives are initiated randomly from a uniform distribution from 0 to dotLife. If changed while drawing, the lives of all dots will be randomly initiated again. :ref:`operations <attrib-operations>` are supported. """ self.__dict__['dotLife'] = dotLife self._dotsLife = abs(self.dotLife) * np.random.rand(self.nDots) @attributeSetter def signalDots(self, signalDots): """str - 'same' or *'different'* If 'same' then the signal and noise dots are constant. If different then the choice of which is signal and which is noise gets randomised on each frame. This corresponds to Scase et al's (1996) categories of RDK. """ self.__dict__['signalDots'] = signalDots @attributeSetter def noiseDots(self, noiseDots): """str - *'direction'*, 'position' or 'walk' Determines the behaviour of the noise dots, taken directly from Scase et al's (1996) categories. For 'position', noise dots take a random position every frame. For 'direction' noise dots follow a random, but constant direction. For 'walk' noise dots vary their direction every frame, but keep a constant speed. """ self.__dict__['noiseDots'] = noiseDots self.coherence = self.coherence # update using attributeSetter @attributeSetter def element(self, element): """*None* or a visual stimulus object This can be any object that has a ``.draw()`` method and a ``.setPos([x,y])`` method (e.g. a GratingStim, TextStim...)!! DotStim assumes that the element uses pixels as units. ``None`` defaults to dots. See `ElementArrayStim` for a faster implementation of this idea. """ self.__dict__['element'] = element @attributeSetter def fieldPos(self, pos): """Specifying the location of the centre of the stimulus using a :ref:`x,y-pair <attrib-xy>`. See e.g. :class:`.ShapeStim` for more documentation / examples on how to set position. :ref:`operations <attrib-operations>` are supported. """ # Isn't there a way to use BaseVisualStim.pos.__doc__ as docstring # here? self.pos = pos # using BaseVisualStim. we'll store this as both self.__dict__['fieldPos'] = self.pos def setFieldPos(self, val, op='', log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message. """ setAttribute(self, 'fieldPos', val, log, op) # calls attributeSetter def setPos(self, newPos=None, operation='', units=None, log=None): """Obsolete - users should use setFieldPos instead of setPos """ logging.error("User called DotStim.setPos(pos). " "Use DotStim.SetFieldPos(pos) instead.") def setFieldSize(self, val, op='', log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message. """ setAttribute(self, 'fieldSize', val, log, op) # calls attributeSetter @attributeSetter def fieldSize(self, size): """Specifying the size of the field of dots using a :ref:`x,y-pair <attrib-xy>`. See e.g. :class:`.ShapeStim` for more documentation/examples on how to set position. :ref:`operations <attrib-operations>` are supported. """ # Isn't there a way to use BaseVisualStim.pos.__doc__ as docstring # here? self.size = size # using BaseVisualStim. we'll store this as both self.__dict__['fieldSize'] = self.size @attributeSetter def coherence(self, coherence): """Scalar between 0 and 1. Change the coherence (%) of the DotStim. This will be rounded according to the number of dots in the stimulus. :ref:`operations <attrib-operations>` are supported. """ if not 0 <= coherence <= 1: raise ValueError('DotStim.coherence must be between 0 and 1') _cohDots = coherence * self.nDots self.__dict__['coherence'] = round(_cohDots) /self.nDots self._signalDots = np.zeros(self.nDots, dtype=bool) self._signalDots[0:int(self.coherence * self.nDots)] = True # for 'direction' method we need to update the direction of the number # of signal dots immediately, but for other methods it will be done # during updateXY # NB - AJS Actually you need to do this for 'walk' also # otherwise would be signal dots adopt random directions when the become # sinal dots in later trails if self.noiseDots in ('direction', 'position', 'walk'): self._dotsDir = np.random.rand(self.nDots) * _2pi self._dotsDir[self._signalDots] = self.dir * _piOver180 def setFieldCoherence(self, val, op='', log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message. """ setAttribute(self, 'coherence', val, log, op) # calls attributeSetter @attributeSetter def dir(self, dir): """float (degrees). direction of the coherent dots. :ref:`operations <attrib-operations>` are supported. """ # check which dots are signal before setting new dir signalDots = self._dotsDir == (self.dir * _piOver180) self.__dict__['dir'] = dir # dots currently moving in the signal direction also need to update # their direction self._dotsDir[signalDots] = self.dir * _piOver180 def setDir(self, val, op='', log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message. """ setAttribute(self, 'dir', val, log, op) @attributeSetter def speed(self, speed): """float. speed of the dots (in *units*/frame). :ref:`operations <attrib-operations>` are supported. """ self.__dict__['speed'] = speed def setSpeed(self, val, op='', log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message. """ setAttribute(self, 'speed', val, log, op) def draw(self, win=None): """Draw the stimulus in its relevant window. You must call this method after every MyWin.flip() if you want the stimulus to appear on that frame and then update the screen again. Parameters ---------- win : window.Window, optional Window to draw dots to. If `None`, dots will be drawn to the parent window. """ if win is None: win = self.win self._selectWindow(win) self._update_dotsXY() GL.glPushMatrix() # push before drawing, pop after # draw the dots if self.element is None: win.setScale('pix') GL.glPointSize(self.dotSize) # load Null textures into multitexteureARB - they modulate with # glColor GL.glActiveTexture(GL.GL_TEXTURE0) GL.glEnable(GL.GL_TEXTURE_2D) GL.glBindTexture(GL.GL_TEXTURE_2D, 0) GL.glActiveTexture(GL.GL_TEXTURE1) GL.glEnable(GL.GL_TEXTURE_2D) GL.glBindTexture(GL.GL_TEXTURE_2D, 0) CPCD = ctypes.POINTER(ctypes.c_double) GL.glVertexPointer(2, GL.GL_DOUBLE, 0, self.verticesPix.ctypes.data_as(CPCD)) GL.glColor4f(*self._foreColor.render('rgba1')) GL.glEnableClientState(GL.GL_VERTEX_ARRAY) GL.glDrawArrays(GL.GL_POINTS, 0, self.nDots) GL.glDisableClientState(GL.GL_VERTEX_ARRAY) else: # we don't want to do the screen scaling twice so for each dot # subtract the screen centre initialDepth = self.element.depth for pointN in range(0, self.nDots): _p = self.verticesPix[pointN, :] + self.fieldPos self.element.setPos(_p) self.element.draw() # reset depth before going to next frame self.element.setDepth(initialDepth) GL.glPopMatrix() def _newDotsXY(self, nDots): """Returns a uniform spread of dots, according to the `fieldShape` and `fieldSize`. Parameters ---------- nDots : int Number of dots to sample. Returns ------- ndarray Nx2 array of X and Y positions of dots. Examples -------- Create a new array of dot positions:: dots = self._newDots(nDots) """ if self.fieldShape == 'circle': length = np.sqrt(np.random.uniform(0, 1, (nDots,))) angle = np.random.uniform(0., _2pi, (nDots,)) newDots = np.zeros((nDots, 2)) newDots[:, 0] = length * np.cos(angle) newDots[:, 1] = length * np.sin(angle) newDots *= self.fieldSize * .5 else: newDots = np.random.uniform(-0.5, 0.5, size = (nDots, 2)) * self.fieldSize return newDots def refreshDots(self): """Callable user function to choose a new set of dots.""" self.vertices = self._verticesBase = self._dotsXY = self._newDotsXY(self.nDots) # Don't allocate another array if the new number of dots is equal to # the last. if self.nDots != len(self._deadDots): self._deadDots = np.zeros(self.nDots, dtype=bool) def _update_dotsXY(self): """The user shouldn't call this - its gets done within draw(). """ # Find dead dots, update positions, get new positions for # dead and out-of-bounds # renew dead dots if self.dotLife > 0: # if less than zero ignore it # decrement. Then dots to be reborn will be negative self._dotsLife -= 1 self._deadDots[:] = (self._dotsLife <= 0) self._dotsLife[self._deadDots] = self.dotLife else: self._deadDots[:] = False # update XY based on speed and dir # NB self._dotsDir is in radians, but self.dir is in degs # update which are the noise/signal dots if self.signalDots == 'different': # **up to version 1.70.00 this was the other way around, # not in keeping with Scase et al** # noise and signal dots change identity constantly np.random.shuffle(self._dotsDir) # and then update _signalDots from that self._signalDots = (self._dotsDir == (self.dir * _piOver180)) # update the locations of signal and noise; 0 radians=East! reshape = np.reshape if self.noiseDots == 'walk': # noise dots are ~self._signalDots sig = np.random.rand(np.sum(~self._signalDots)) self._dotsDir[~self._signalDots] = sig * _2pi # then update all positions from dir*speed cosDots = reshape(np.cos(self._dotsDir), (self.nDots,)) sinDots = reshape(np.sin(self._dotsDir), (self.nDots,)) self._verticesBase[:, 0] += self.speed * cosDots self._verticesBase[:, 1] += self.speed * sinDots elif self.noiseDots == 'direction': # simply use the stored directions to update position cosDots = reshape(np.cos(self._dotsDir), (self.nDots,)) sinDots = reshape(np.sin(self._dotsDir), (self.nDots,)) self._verticesBase[:, 0] += self.speed * cosDots self._verticesBase[:, 1] += self.speed * sinDots elif self.noiseDots == 'position': # update signal dots sd = self._signalDots sdSum = self._signalDots.sum() cosDots = reshape(np.cos(self._dotsDir[sd]), (sdSum,)) sinDots = reshape(np.sin(self._dotsDir[sd]), (sdSum,)) self._verticesBase[sd, 0] += self.speed * cosDots self._verticesBase[sd, 1] += self.speed * sinDots # update noise dots self._deadDots[:] = self._deadDots + (~self._signalDots) # handle boundaries of the field if self.fieldShape in (None, 'square', 'sqr'): out0 = (np.abs(self._verticesBase[:, 0]) > .5 * self.fieldSize[0]) out1 = (np.abs(self._verticesBase[:, 1]) > .5 * self.fieldSize[1]) outofbounds = out0 + out1 else: # transform to a normalised circle (radius = 1 all around) # then to polar coords to check # the normalised XY position (where radius should be < 1) normXY = self._verticesBase / .5 / self.fieldSize # add out-of-bounds to those that need replacing outofbounds = np.hypot(normXY[:, 0], normXY[:, 1]) > 1. # update any dead dots nDead = self._deadDots.sum() if nDead: self._verticesBase[self._deadDots, :] = self._newDotsXY(nDead) # Reposition any dots that have gone out of bounds. Net effect is to # place dot one step inside the boundary on the other side of the # aperture. nOutOfBounds = outofbounds.sum() if nOutOfBounds: self._verticesBase[outofbounds, :] = self._newDotsXY(nOutOfBounds) self.vertices = self._verticesBase / self.fieldSize # update the pixel XY coordinates in pixels (using _BaseVisual class) self._updateVertices()
28,569
Python
.py
582
39.353952
87
0.626752
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,743
text.py
psychopy_psychopy/psychopy/visual/text.py
#!/usr/bin/env python # -*- coding: utf-8 -*- '''Class of text stimuli to be displayed in a :class:`~psychopy.visual.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 os import glob import warnings # Ensure setting pyglet.options['debug_gl'] to False is done prior to any # other calls to pyglet or pyglet submodules, otherwise it may not get picked # up by the pyglet GL engine and have no effect. # Shaders will work but require OpenGL2.0 drivers AND PyOpenGL3.0+ import pyglet pyglet.options['debug_gl'] = False import ctypes GL = pyglet.gl import psychopy # so we can get the __path__ from psychopy import logging # tools must only be imported *after* event or MovieStim breaks on win32 # (JWP has no idea why!) from psychopy.tools.monitorunittools import cm2pix, deg2pix, convertToPix from psychopy.tools.attributetools import attributeSetter, setAttribute from psychopy.visual.basevisual import ( BaseVisualStim, DraggingMixin, ForeColorMixin, ContainerMixin, WindowMixin ) from psychopy.colors import Color # for displaying right-to-left (possibly bidirectional) text correctly: from bidi import algorithm as bidi_algorithm # sufficient for Hebrew # extra step needed to reshape Arabic/Farsi characters depending on # their neighbours: try: from arabic_reshaper import ArabicReshaper haveArabic = True except ImportError: haveArabic = False import numpy try: import pygame havePygame = True except Exception: havePygame = False defaultLetterHeight = {'cm': 1.0, 'deg': 1.0, 'degs': 1.0, 'degFlatPos': 1.0, 'degFlat': 1.0, 'norm': 0.1, 'height': 0.2, 'pix': 20, 'pixels': 20} defaultWrapWidth = {'cm': 15.0, 'deg': 15.0, 'degs': 15.0, 'degFlatPos': 15.0, 'degFlat': 15.0, 'norm': 1, 'height': 1, 'pix': 500, 'pixels': 500} class TextStim(BaseVisualStim, DraggingMixin, ForeColorMixin, ContainerMixin): """Class of text stimuli to be displayed in a :class:`~psychopy.visual.Window` """ def __init__(self, win, text="Hello World", font="", pos=(0.0, 0.0), depth=0, rgb=None, color=(1.0, 1.0, 1.0), colorSpace='rgb', opacity=1.0, contrast=1.0, units="", ori=0.0, height=None, antialias=True, bold=False, italic=False, alignHoriz=None, alignVert=None, alignText='center', anchorHoriz='center', anchorVert='center', fontFiles=(), wrapWidth=None, flipHoriz=False, flipVert=False, languageStyle='LTR', draggable=False, name=None, autoLog=None, autoDraw=False): """ **Performance OBS:** in general, TextStim is slower than many other visual stimuli, i.e. it takes longer to change some attributes. In general, it's the attributes that affect the shapes of the letters: ``text``, ``height``, ``font``, ``bold`` etc. These make the next .draw() slower because that sets the text again. You can make the draw() quick by calling re-setting the text (``myTextStim.text = myTextStim.text``) when you've changed the parameters. In general, other attributes which merely affect the presentation of unchanged shapes are as fast as usual. This includes ``pos``, ``opacity`` etc. The following attribute can only be set at initialization (see further down for a list of attributes which can be changed after initialization): **languageStyle** Apply settings to correctly display content from some languages that are written right-to-left. Currently there are three (case- insensitive) values for this parameter: - ``'LTR'`` is the default, for typical left-to-right, Latin-style languages. - ``'RTL'`` will correctly display text in right-to-left languages such as Hebrew. By applying the bidirectional algorithm, it allows mixing portions of left-to-right content (such as numbers or Latin script) within the string. - ``'Arabic'`` applies the bidirectional algorithm but additionally will _reshape_ Arabic characters so they appear in the cursive, linked form that depends on neighbouring characters, rather than in their isolated form. May also be applied in other scripts, such as Farsi or Urdu, that use Arabic-style alphabets. :Parameters: """ # what local vars are defined (these are the init params) for use by # __repr__ self._initParams = dir() self._initParams.remove('self') """ October 2018: In place to remove the deprecation warning for pyglet.font.Text. Temporary fix until pyglet.text.Label use is identical to pyglet.font.Text. """ warnings.filterwarnings(message='.*text.Label*', action='ignore') super(TextStim, self).__init__( win, units=units, name=name, autoLog=False) self.draggable = draggable if win.blendMode=='add': logging.warning("Pyglet text does not honor the Window setting " "`blendMode='add'` so 'avg' will be used for the " "text (but objects drawn after can be added)") self._needUpdate = True self._needVertexUpdate = True # use shaders if available by default, this is a good thing self.__dict__['antialias'] = antialias self.__dict__['font'] = font self.__dict__['bold'] = bold self.__dict__['italic'] = italic # NB just a placeholder - real value set below self.__dict__['text'] = '' self.__dict__['depth'] = depth self.__dict__['ori'] = ori self.__dict__['flipHoriz'] = flipHoriz self.__dict__['flipVert'] = flipVert self.__dict__['languageStyle'] = languageStyle if languageStyle.lower() == 'arabic': arabic_config = {'delete_harakat': False, # if present, retain any diacritics 'shift_harakat_position': True} # shift by 1 to be compatible with the bidi algorithm self.__dict__['arabic_reshaper'] = ArabicReshaper(configuration = arabic_config) self._pygletTextObj = None self.pos = pos # deprecated attributes if alignVert: self.__dict__['alignVert'] = alignVert logging.warning("TextStim.alignVert is deprecated. Use the " "anchorVert attribute instead") # for compatibility, alignText was historically 'left' anchorVert = alignHoriz if alignHoriz: self.__dict__['alignHoriz'] = alignHoriz logging.warning("TextStim.alignHoriz is deprecated. Use alignText " "and anchorHoriz attributes instead") # for compatibility, alignText was historically 'left' alignText, anchorHoriz = alignHoriz, alignHoriz # alignment and anchors self.alignText = alignText self.anchorHoriz = anchorHoriz self.anchorVert = anchorVert # generate the texture and list holders self._listID = GL.glGenLists(1) # pygame text needs a surface to render to: if not self.win.winType in ["pyglet", "glfw"]: self._texID = GL.GLuint() GL.glGenTextures(1, ctypes.byref(self._texID)) # Color stuff self.colorSpace = colorSpace self.color = color if rgb != None: logging.warning("Use of rgb arguments to stimuli are deprecated. Please " "use color and colorSpace args instead") self.color = Color(rgb, 'rgb') self.__dict__['fontFiles'] = [] self.fontFiles = list(fontFiles) # calls attributeSetter self.setHeight(height, log=False) # calls setFont() at some point # calls attributeSetter without log setAttribute(self, 'wrapWidth', wrapWidth, log=False) self.opacity = opacity self.contrast = contrast # self.width and self._fontHeightPix get set with text and # calcSizeRendered is called self.setText(text, log=False) self._needUpdate = True self.autoDraw = autoDraw # set autoLog now that params have been initialised wantLog = autoLog is None and self.win.autoLog self.__dict__['autoLog'] = autoLog or wantLog if self.autoLog: logging.exp("Created %s = %s" % (self.name, str(self))) def __del__(self): if GL: # because of pytest fail otherwise try: GL.glDeleteLists(self._listID, 1) except (ImportError, ModuleNotFoundError, TypeError, GL.lib.GLException): pass # if pyglet no longer exists @attributeSetter def height(self, height): """The height of the letters (Float/int or None = set default). Height includes the entire box that surrounds the letters in the font. The width of the letters is then defined by the font. :ref:`Operations <attrib-operations>` supported.""" # height in pix (needs to be done after units which is done during # _Base.__init__) if height is None: if self.units in defaultLetterHeight: height = defaultLetterHeight[self.units] else: msg = ("TextStim does now know a default letter height " "for units %s") raise AttributeError(msg % repr(self.units)) self.__dict__['height'] = height self._heightPix = convertToPix(pos=numpy.array([0, 0]), vertices=numpy.array([0, self.height]), units=self.units, win=self.win)[1] # need to update the font to reflect the change self.setFont(self.font, log=False) return self.__dict__['height'] @property def size(self): self.size = (self.height*len(self.text), self.height) return WindowMixin.size.fget(self) @size.setter def size(self, value): WindowMixin.size.fset(self, value) self.height = getattr(self._size, self.units)[1] def setHeight(self, height, log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message. """ setAttribute(self, 'height', height, log) def setLetterHeight(self, height, log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message. """ setAttribute(self, 'height', height, log) @attributeSetter def font(self, font): """String. Set the font to be used for text rendering. font should be a string specifying the name of the font (in system resources). """ self.__dict__['font'] = None # until we find one if self.win.winType in ["pyglet", "glfw"]: self._font = pyglet.font.load(font, int(self._heightPix), dpi=72, italic=self.italic, bold=self.bold) self.__dict__['font'] = font else: if font is None or len(font) == 0: self.__dict__['font'] = pygame.font.get_default_font() elif font in pygame.font.get_fonts(): self.__dict__['font'] = font elif type(font) == str: # try to find a xxx.ttf file for it # check for possible matching filenames fontFilenames = glob.glob(font + '*') if len(fontFilenames) > 0: for thisFont in fontFilenames: if thisFont[-4:] in ['.TTF', '.ttf']: # take the first match self.__dict__['font'] = thisFont break # stop at the first one we find # trhen check if we were successful if self.font is None and font != "": # we didn't find a ttf filename msg = ("Found %s but it doesn't end .ttf. " "Using default font.") logging.warning(msg % fontFilenames[0]) self.__dict__['font'] = pygame.font.get_default_font() if self.font is not None and os.path.isfile(self.font): self._font = pygame.font.Font(self.font, int( self._heightPix), italic=self.italic, bold=self.bold) else: try: self._font = pygame.font.SysFont( self.font, int(self._heightPix), italic=self.italic, bold=self.bold) self.__dict__['font'] = font logging.info('using sysFont ' + str(font)) except Exception: self.__dict__['font'] = pygame.font.get_default_font() msg = ("Couldn't find font %s on the system. Using %s " "instead! Font names should be written as " "concatenated names all in lower case.\ne.g. " "'arial', 'monotypecorsiva', 'rockwellextra', ...") logging.error(msg % (font, self.font)) self._font = pygame.font.SysFont( self.font, int(self._heightPix), italic=self.italic, bold=self.bold) # re-render text after a font change self._needSetText = True def setFont(self, font, log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message. """ setAttribute(self, 'font', font, log) @attributeSetter def text(self, text): """The text to be rendered. Use \\\\n to make new lines. Issues: May be slow, and pyglet has a memory leak when setting text. For these reasons, this function checks so that it only updates the text if it has changed. So scripts can safely set the text on every frame, with no need to check if it has actually altered. """ if text == self.text: # only update for a change return if text is not None: text = str(text) # make sure we have unicode object to render # deal with some international text issues. Only relevant for Python: # online experiments use web technologies and handle this seamlessly. style = self.languageStyle.lower() # be flexible with case if style == 'arabic' and haveArabic: # reshape Arabic characters from their isolated form so that # they flow and join correctly to their neighbours: text = self.arabic_reshaper.reshape(text) if style == 'rtl' or (style == 'arabic' and haveArabic): # deal with right-to-left text presentation by applying the # bidirectional algorithm: text = bidi_algorithm.get_display(text) # no action needed for default 'ltr' (left-to-right) option self.__dict__['text'] = text self._setTextShaders(text) self._needSetText = False return self.__dict__['text'] def setText(self, text=None, log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message. """ setAttribute(self, 'text', text, log) def _setTextShaders(self, value=None): """Set the text to be rendered using the current font """ if self.win.winType in ["pyglet", "glfw"]: rgba255 = self._foreColor.rgba255 rgba255[3] = rgba255[3]*255 rgba255 = [int(c) for c in rgba255] self._pygletTextObj = pyglet.text.Label( self.text, self.font, int(self._heightPix*0.75), italic=self.italic, bold=self.bold, anchor_x=self.anchorHoriz, anchor_y=self.anchorVert, # the point we rotate around align=self.alignText, color=rgba255, multiline=True, width=self._wrapWidthPix) # width of the frame self.width = self._pygletTextObj.width self._fontHeightPix = self._pygletTextObj.height else: self._surf = self._font.render(value, self.antialias, [255, 255, 255]) self.width, self._fontHeightPix = self._surf.get_size() if self.antialias: smoothing = GL.GL_LINEAR else: smoothing = GL.GL_NEAREST # generate the textures from pygame surface GL.glEnable(GL.GL_TEXTURE_2D) # bind that name to the target GL.glBindTexture(GL.GL_TEXTURE_2D, self._texID) GL.gluBuild2DMipmaps(GL.GL_TEXTURE_2D, 4, self.width, self._fontHeightPix, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, pygame.image.tostring(self._surf, "RGBA", 1)) # linear smoothing if texture is stretched? GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, smoothing) # but nearest pixel value if it's compressed? GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, smoothing) self._needSetText = False self._needUpdate = True def _updateListShaders(self): """Only used with pygame text - pyglet handles all from the draw() """ if self._needSetText: self.setText(log=False) GL.glNewList(self._listID, GL.GL_COMPILE) # GL.glPushMatrix() # setup the shaderprogram # no need to do texture maths so no need for programs? # If we're using pyglet then this list won't be called, and for pygame # shaders aren't enabled GL.glUseProgram(0) # self.win._progSignedTex) # GL.glUniform1i(GL.glGetUniformLocation(self.win._progSignedTex, # "texture"), 0) # set the texture to be texture unit 0 # coords: if self.alignHoriz in ['center', 'centre']: left = -self.width/2.0 right = self.width/2.0 elif self.alignHoriz == 'right': left = -self.width right = 0.0 else: left = 0.0 right = self.width # how much to move bottom if self.alignVert in ['center', 'centre']: bottom = -self._fontHeightPix/2.0 top = self._fontHeightPix/2.0 elif self.alignVert == 'top': bottom = -self._fontHeightPix top = 0 else: bottom = 0.0 top = self._fontHeightPix # there seems to be a rounding err in pygame font textures Btex, Ttex, Ltex, Rtex = -0.01, 0.98, 0, 1.0 # unbind the mask texture regardless GL.glActiveTexture(GL.GL_TEXTURE1) GL.glEnable(GL.GL_TEXTURE_2D) GL.glBindTexture(GL.GL_TEXTURE_2D, 0) if self.win.winType in ["pyglet", "glfw"]: # unbind the main texture GL.glActiveTexture(GL.GL_TEXTURE0) # GL.glActiveTextureARB(GL.GL_TEXTURE0_ARB) # the texture is specified by pyglet.font.GlyphString.draw() GL.glBindTexture(GL.GL_TEXTURE_2D, 0) GL.glEnable(GL.GL_TEXTURE_2D) else: # bind the appropriate main texture GL.glActiveTexture(GL.GL_TEXTURE0) GL.glBindTexture(GL.GL_TEXTURE_2D, self._texID) GL.glEnable(GL.GL_TEXTURE_2D) if self.win.winType in ["pyglet", "glfw"]: GL.glActiveTexture(GL.GL_TEXTURE0) GL.glEnable(GL.GL_TEXTURE_2D) self._pygletTextObj.draw() else: # draw a 4 sided polygon GL.glBegin(GL.GL_QUADS) # right bottom GL.glMultiTexCoord2f(GL.GL_TEXTURE0, Rtex, Btex) GL.glVertex3f(right, bottom, 0) # left bottom GL.glMultiTexCoord2f(GL.GL_TEXTURE0, Ltex, Btex) GL.glVertex3f(left, bottom, 0) # left top GL.glMultiTexCoord2f(GL.GL_TEXTURE0, Ltex, Ttex) GL.glVertex3f(left, top, 0) # right top GL.glMultiTexCoord2f(GL.GL_TEXTURE0, Rtex, Ttex) GL.glVertex3f(right, top, 0) GL.glEnd() GL.glDisable(GL.GL_TEXTURE_2D) GL.glUseProgram(0) # GL.glPopMatrix() GL.glEndList() self._needUpdate = False @attributeSetter def flipHoriz(self, value): """If set to True then the text will be flipped left-to-right. The flip is relative to the original, not relative to the current state. """ self.__dict__['flipHoriz'] = value def setFlipHoriz(self, newVal=True, log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message. """ setAttribute(self, 'flipHoriz', newVal, log) @attributeSetter def flipVert(self, value): """If set to True then the text will be flipped top-to-bottom. The flip is relative to the original, not relative to the current state. """ self.__dict__['flipVert'] = value def setFlipVert(self, newVal=True, log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message """ setAttribute(self, 'flipVert', newVal, log) def setFlip(self, direction, log=None): """(used by Builder to simplify the dialog) """ if direction == 'vert': self.setFlipVert(True, log=log) elif direction == 'horiz': self.setFlipHoriz(True, log=log) @attributeSetter def antialias(self, value): """Allow antialiasing the text (True or False). Sets text, slow. """ self.__dict__['antialias'] = value self._needSetText = True @attributeSetter def bold(self, value): """Make the text bold (True, False) (better to use a bold font name). """ self.__dict__['bold'] = value self.font = self.font # call attributeSetter @attributeSetter def italic(self, value): """True/False. Make the text italic (better to use a italic font name). """ self.__dict__['italic'] = value self.font = self.font # call attributeSetter @attributeSetter def alignHoriz(self, value): """Deprecated in PsychoPy 3.3. Use `alignText` and `anchorHoriz` instead """ self.__dict__['alignHoriz'] = value self._needSetText = True @attributeSetter def alignVert(self, value): """Deprecated in PsychoPy 3.3. Use `anchorVert` """ self.__dict__['alignVert'] = value self._needSetText = True @attributeSetter def alignText(self, value): """Aligns the text content within the bounding box ('left', 'right' or 'center') See also `anchorX` to set alignment of the box itself relative to pos """ self.__dict__['alignText'] = value self._needSetText = True @attributeSetter def anchorHoriz(self, value): """The horizontal alignment ('left', 'right' or 'center') """ self.__dict__['anchorHoriz'] = value self._needSetText = True @attributeSetter def anchorVert(self, value): """The vertical alignment ('top', 'bottom' or 'center') of the box relative to the text `pos`. """ self.__dict__['anchorVert'] = value self._needSetText = True @attributeSetter def fontFiles(self, fontFiles): """A list of additional files if the font is not in the standard system location (include the full path). OBS: fonts are added every time this value is set. Previous are not deleted. E.g.:: stim.fontFiles = ['SpringRage.ttf'] # load file(s) stim.font = 'SpringRage' # set to font """ self.__dict__['fontFiles'] += fontFiles for thisFont in fontFiles: pyglet.font.add_file(thisFont) @attributeSetter def wrapWidth(self, wrapWidth): """Int/float or None (set default). The width the text should run before wrapping. :ref:`Operations <attrib-operations>` supported. """ if wrapWidth is None: if self.units in defaultWrapWidth: wrapWidth = defaultWrapWidth[self.units] else: msg = "TextStim does now know a default wrap width for units %s" raise AttributeError(msg % repr(self.units)) self.__dict__['wrapWidth'] = wrapWidth verts = numpy.array([self.wrapWidth, 0]) self._wrapWidthPix = convertToPix(pos=numpy.array([0, 0]), vertices=verts, units=self.units, win=self.win)[0] self._needSetText = True @property def boundingBox(self): """(read only) attribute representing the bounding box of the text (w,h). This differs from `width` in that the width represents the width of the margins, which might differ from the width of the text within them. NOTE: currently always returns the size in pixels (this will change to return in stimulus units) """ if hasattr(self._pygletTextObj, 'content_width'): w, h = (self._pygletTextObj.content_width, self._pygletTextObj.content_height) else: w, h = (self._pygletTextObj._layout.content_width, self._pygletTextObj._layout.content_height) return w, h @property def posPix(self): """This determines the coordinates in pixels of the position for the current stimulus, accounting for pos and units. This property should automatically update if `pos` is changed""" # because this is a property getter we can check /on-access/ if it # needs updating :-) if self._needVertexUpdate: self.__dict__['posPix'] = self._pos.pix self._needVertexUpdate = False return self.__dict__['posPix'] def updateOpacity(self): self._setTextShaders(value=self.text) def draw(self, win=None): """ Draw the stimulus in its relevant window. You must call this method after every MyWin.flip() if you want the stimulus to appear on that frame and then update the screen again. If win is specified then override the normal window of this stimulus. """ if win is None: win = self.win self._selectWindow(win) blendMode = win.blendMode # keep track for reset later GL.glPushMatrix() # for PyOpenGL this is necessary despite pop/PushMatrix, (not for # pyglet) GL.glLoadIdentity() #scale and rotate prevScale = win.setScale('pix') # to units for translations # NB depth is set already GL.glTranslatef(self.posPix[0], self.posPix[1], 0) GL.glRotatef(-self.ori, 0.0, 0.0, 1.0) # back to pixels for drawing surface win.setScale('pix', None, prevScale) GL.glScalef((1, -1)[self.flipHoriz], (1, -1) [self.flipVert], 1) # x,y,z; -1=flipped # setup color GL.glColor4f(*self._foreColor.render('rgba1')) GL.glUseProgram(self.win._progSignedTexFont) # GL.glUniform3iv(GL.glGetUniformLocation( # self.win._progSignedTexFont, "rgb"), 1, # desiredRGB.ctypes.data_as(ctypes.POINTER(ctypes.c_float))) # # set the texture to be texture unit 0 GL.glUniform3f( GL.glGetUniformLocation(self.win._progSignedTexFont, b"rgb"), *self._foreColor.render('rgb1')) # should text have a depth or just on top? GL.glDisable(GL.GL_DEPTH_TEST) # update list if necss and then call it if win.winType in ["pyglet", "glfw"]: if self._needSetText: self.setText() # unbind the mask texture regardless GL.glActiveTexture(GL.GL_TEXTURE1) GL.glEnable(GL.GL_TEXTURE_2D) GL.glBindTexture(GL.GL_TEXTURE_2D, 0) # unbind the main texture GL.glActiveTexture(GL.GL_TEXTURE0) GL.glEnable(GL.GL_TEXTURE_2D) # then allow pyglet to bind and use texture during drawing self._pygletTextObj.draw() GL.glDisable(GL.GL_TEXTURE_2D) else: # for pygame we should (and can) use a drawing list if self._needUpdate: self._updateList() GL.glCallList(self._listID) # pyglets text.draw() method alters the blend func so reassert ours win.setBlendMode(blendMode, log=False) GL.glUseProgram(0) # GL.glEnable(GL.GL_DEPTH_TEST) # Enables Depth Testing GL.glPopMatrix()
30,584
Python
.py
670
33.958209
115
0.581593
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,744
__init__.py
psychopy_psychopy/psychopy/visual/__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). """Container for all visual-related functions and classes """ import sys if sys.platform == 'win32': from pyglet.libs import win32 # pyglet patch for ANACONDA install from ctypes import * from psychopy import prefs win32.PUINT = POINTER(wintypes.UINT) # get the preference for high DPI if 'highDPI' in prefs.hardware.keys(): # check if we have the option enableHighDPI = prefs.hardware['highDPI'] # check if we have OS support for it if enableHighDPI: try: windll.shcore.SetProcessDpiAwareness(enableHighDPI) except OSError: pass from psychopy import event # import before visual or from psychopy.visual import filters from psychopy.visual.backends import gamma # absolute essentials (nearly all experiments will need these) from .basevisual import BaseVisualStim # non-private helpers from .helpers import pointInPolygon, polygonsOverlap from .image import ImageStim from .text import TextStim from .form import Form from .brush import Brush from .textbox2.textbox2 import TextBox2 from .button import ButtonStim from .roi import ROI from .target import TargetStim # window, should always be loaded first from .window import Window, getMsPerFrame, openWindows # needed for backwards-compatibility # need absolute imports within lazyImports # A newer alternative lib is apipkg but then we have to specify all the vars # that will be included, not just the lazy ones? Syntax is: # import apipkg # apipkg.initpkg(__name__, { # 'GratingStim': "psychopy.visual.grating:GratingStim", # }) from psychopy.constants import STOPPED, FINISHED, PLAYING, NOT_STARTED lazyImports = """ # stimuli derived from object or MinimalStim from psychopy.visual.aperture import Aperture # uses BaseShapeStim, ImageStim from psychopy.visual.custommouse import CustomMouse from psychopy.visual.elementarray import ElementArrayStim from psychopy.visual.ratingscale import RatingScale from psychopy.visual.slider import Slider from psychopy.visual.progress import Progress from psychopy.visual.simpleimage import SimpleImageStim # stimuli derived from BaseVisualStim from psychopy.visual.dot import DotStim from psychopy.visual.grating import GratingStim from psychopy.visual.secondorder import EnvelopeGrating from psychopy.visual.movies import MovieStim from psychopy.visual.movie2 import MovieStim2 from psychopy.visual.movie3 import MovieStim3 from psychopy.visual.vlcmoviestim import VlcMovieStim from psychopy.visual.shape import BaseShapeStim # stimuli derived from GratingStim from psychopy.visual.bufferimage import BufferImageStim from psychopy.visual.patch import PatchStim from psychopy.visual.radial import RadialStim from psychopy.visual.noise import NoiseStim # stimuli derived from BaseShapeStim from psychopy.visual.shape import ShapeStim # stimuli derived from ShapeStim from psychopy.visual.line import Line from psychopy.visual.polygon import Polygon from psychopy.visual.rect import Rect from psychopy.visual.pie import Pie from psychopy.visual.button import CheckBoxStim # stimuli derived from Polygon from psychopy.visual.circle import Circle # stimuli derived from TextBox from psychopy.visual.textbox import TextBox from psychopy.visual.dropdown import DropDownCtrl # rift support from psychopy.visual.rift import Rift # VisualSystemHD support from psychopy.visual.nnlvs import VisualSystemHD # 3D stimuli support from psychopy.visual.panorama import PanoramicImageStim from psychopy.visual.stim3d import LightSource from psychopy.visual.stim3d import SceneSkybox from psychopy.visual.stim3d import BlinnPhongMaterial from psychopy.visual.stim3d import RigidBodyPose from psychopy.visual.stim3d import BoundingBox from psychopy.visual.stim3d import SphereStim from psychopy.visual.stim3d import BoxStim from psychopy.visual.stim3d import PlaneStim from psychopy.visual.stim3d import ObjMeshStim """ try: from psychopy.contrib.lazy_import import lazy_import lazy_import(globals(), lazyImports) except Exception: exec(lazyImports)
4,302
Python
.py
105
38.67619
79
0.822403
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,745
patch.py
psychopy_psychopy/psychopy/visual/patch.py
#!/usr/bin/env python # -*- coding: utf-8 -*- '''Deprecated (as of version 1.74.00): please use the :class:`~psychopy.visual.GratingStim` or the :class:`~psychopy.visual.ImageStim` classes.''' # 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.tools.pkgtools import PluginStub class PatchStim( PluginStub, plugin="psychopy-legacy", doclink="https://psychopy.github.io/psychopy-legacy/coder/visual/PatchStim" ): pass
582
Python
.py
15
36.4
79
0.752669
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,746
progress.py
psychopy_psychopy/psychopy/visual/progress.py
from . import shape from psychopy.tools.attributetools import attributeSetter, setAttribute # Aliases for directions _directionAliases = { # Horizontal "horizontal": "horizontal", "horiz": "horizontal", "x": "horizontal", "0": "horizontal", "False": "horizontal", 0: "horizontal", False: "horizontal", # Vertical "vertical": "vertical", "vert": "vertical", "y": "vertical", "1": "vertical", "True": "vertical", 1: "vertical", True: "vertical", } class Progress(shape.ShapeStim): """ A basic progress bar, consisting of two rectangles: A background and a foreground. The foreground rectangle fill the background as progress approaches 1. Parameters ========== win : :class:`~psychopy.visual.Window` Window this shape is being drawn to. The stimulus instance will allocate its required resources using that Windows context. In many cases, a stimulus instance cannot be drawn on different windows unless those windows share the same OpenGL context, which permits resources to be shared between them. name : str Name to refer to this Progress bar by progress : float Value between 0 (not started) and 1 (complete) to set the progress bar to. direction : str Which dimension the bar should fill along, either "horizontal" (also accepts "horiz", "x" or 0) or "vertical" (also accepts "vert", "y" or 1) pos : array_like Initial position (`x`, `y`) of the shape on-screen relative to the origin located at the center of the window or buffer in `units`. This can be updated after initialization by setting the `pos` property. The default value is `(0.0, 0.0)` which results in no translation. size : array_like, float, int or None Width and height of the shape as `(w, h)` or `[w, h]`. If a single value is provided, the width and height will be set to the same specified value. If `None` is specified, the `size` will be set with values passed to `width` and `height`. anchor : str Point within the shape where size and pos are set from. This also affects where the progress bar fills up from (e.g. if anchor is "left" and direction is "horizontal", then the bar will fill from left to right) units : str Units to use when drawing. This will affect how parameters and attributes `pos` and `size` are interpreted. barColor, foreColor : array_like, str, :class:`~psychopy.colors.Color` or None Color of the full part of the progress bar. backColor, fillColor : array_like, str, :class:`~psychopy.colors.Color` or None Color of the empty part of the progress bar. borderColor, lineColor : array_like, str, :class:`~psychopy.colors.Color` or None Color of the outline around the outside of the progress bar. colorSpace : str Sets the colorspace, changing how values passed to `foreColor`, `lineColor` and `fillColor` are interpreted. lineWidth : float Width of the shape outline. opacity : float Opacity of the shape. A value of 1.0 indicates fully opaque and 0.0 is fully transparent (therefore invisible). Values between 1.0 and 0.0 will result in colors being blended with objects in the background. """ def __init__( self, win, name="pb", progress=0, direction="horizontal", pos=(-.5, 0), size=(1, 0.1), anchor="center-left", units=None, barColor=False, backColor=False, borderColor=False, colorSpace=None, lineWidth=1.5, opacity=1.0, ori=0.0, depth=0, autoLog=None, autoDraw=False, # aliases foreColor="white", fillColor=False, lineColor="white", ): # Alias color names if backColor is False and fillColor is not False: backColor = fillColor if barColor is False and foreColor is not False: barColor = foreColor if borderColor is False and lineColor is not False: borderColor = lineColor # Create backboard shape.ShapeStim.__init__( self, win, name=name, pos=pos, size=size, anchor=anchor, units=units, fillColor=backColor, lineColor=borderColor, colorSpace=colorSpace, lineWidth=lineWidth, opacity=opacity, ori=ori, depth=depth, autoLog=autoLog, autoDraw=autoDraw, vertices="rectangle" ) # Create bar self.bar = shape.ShapeStim( win, name=f"{name}Bar", pos=pos, size=size, anchor=anchor, units=units, fillColor=barColor, lineColor=None, colorSpace=colorSpace, opacity=opacity, ori=ori, depth=depth, autoLog=autoLog, autoDraw=autoDraw, vertices="rectangle" ) # Store direction self.direction = direction self.progress = progress # --- Basic --- @attributeSetter def progress(self, value): """ How far along the progress bar is Parameters ========== value : float Between 0 (not complete) and 1 (fully complete) """ # Sanitize value value = float(value) value = max(value, 0) value = min(value, 1) # Store value self.__dict__['progress'] = value # Multiply size by progress to get bar size i = 0 if self.direction == "vertical": i = 1 sz = self.size.copy() sz[i] *= value self.bar.size = sz def setProgress(self, value, log=None, operation=False): setAttribute(self, "progress", value, log=log, operation=operation) @attributeSetter def direction(self, value): """ What direction is this progress bar progressing in? Use in combination with "anchor" to control which direction the bar fills up from. Parameters ========== value : str, int, bool Is progress bar horizontal or vertical? Accepts the following values: * horizontal: "horizontal", "horiz", "x", "0", "False", 0, False * vertical: "vertical", "vert", "y", "1", "True", 1, True """ # Set value (sanitized) self.__dict__['direction'] = self._sanitizeDirection(value) if not isinstance(self.progress, attributeSetter): # Get current progress progress = self.progress # Set progress to 1 so both dimensions are the same as box size self.setProgress(1, log=False) # Set progress back to layout self.setProgress(progress, log=False) def setDirection(self, value, log=None, operation=False): setAttribute(self, "direction", value, log=log, operation=operation) @staticmethod def _sanitizeDirection(direction): """ Take a value indicating direction and convert it to a human readable string """ # Ignore case for strings if isinstance(direction, str): direction = direction.lower().strip() # Return sanitized if valid, otherwise assume horizontal return _directionAliases.get(direction, "horizontal") @property def complete(self): return self.progress == 1 @complete.setter def complete(self, value): if value: # If True, set progress to full self.progress = 1 else: # If False and complete, set progress to 0 if self.progress == 1: self.progress = 0 def setComplete(self, value, log, operation=False): setAttribute(self, "complete", value, log=log, operation=operation) @property def win(self): return shape.ShapeStim.win.fget(self) @win.setter def win(self, value): shape.ShapeStim.win.fset(self, value) if hasattr(self, "bar"): self.bar.win = value def draw(self, win=None, keepMatrix=False): shape.ShapeStim.draw(self, win=win, keepMatrix=keepMatrix) self.bar.draw() # --- Appearance --- @property def barColor(self): return self.foreColor @barColor.setter def barColor(self, value): self.foreColor = value @property def foreColor(self): """ Color of the full part of the progress bar. """ if hasattr(self, "bar"): return self.bar.fillColor @foreColor.setter def foreColor(self, value): if hasattr(self, "bar"): self.bar.fillColor = value # Store bar color as protected attribute, mostly just for the test suite self._foreColor = self.bar._fillColor @property def opacity(self): return shape.ShapeStim.opacity.fget(self) @opacity.setter def opacity(self, value): shape.ShapeStim.opacity.fset(self, value) if hasattr(self, "bar"): self.bar.opacity = value @property def colorSpace(self): return shape.ShapeStim.colorSpace.fget(self) @colorSpace.setter def colorSpace(self, value): # Set color space for self and bar shape.ShapeStim.colorSpace.fset(self, value) if hasattr(self, "bar"): self.bar.colorSpace = value # --- Layout --- @property def pos(self): return shape.ShapeStim.pos.fget(self) @pos.setter def pos(self, value): shape.ShapeStim.pos.fset(self, value) if hasattr(self, "bar"): self.bar.pos = value @property def size(self): return shape.ShapeStim.size.fget(self) @size.setter def size(self, value): shape.ShapeStim.size.fset(self, value) if hasattr(self, "bar"): self.progress = self.progress @property def anchor(self): return shape.ShapeStim.anchor.fget(self) @anchor.setter def anchor(self, value): shape.ShapeStim.anchor.fset(self, value) if hasattr(self, "bar"): self.bar.anchor = value @property def units(self): return shape.ShapeStim.units.fget(self) @units.setter def units(self, value): shape.ShapeStim.units.fset(self, value) if hasattr(self, "bar"): self.bar.units = value @attributeSetter def ori(self, value): shape.ShapeStim.ori.func(self, value) if hasattr(self, "bar"): self.bar.ori = value
10,661
Python
.py
274
30.277372
111
0.620796
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,747
windowframepack.py
psychopy_psychopy/psychopy/visual/windowframepack.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Copyright (C) 2014 Allen Institute for Brain Science This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License Version 3 as published by the Free Software Foundation on 29 June 2007. This program is distributed WITHOUT WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE OR ANY OTHER WARRANTY, EXPRESSED OR IMPLIED. See the GNU General Public License Version 3 for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ """ import pyglet GL = pyglet.gl class ProjectorFramePacker: """Class which packs 3 monochrome images per RGB frame. Allowing 180Hz stimuli with DLP projectors such as TI LightCrafter 4500. The class overrides methods of the visual.Window class to pack a monochrome image into each RGB channel. PsychoPy is running at 180Hz. The display device is running at 60Hz. The output projector is producing images at 180Hz. Frame packing can work with any projector which can operate in 'structured light mode' where each RGB channel is presented sequentially as a monochrome image. Most home and office projectors cannot operate in this mode, but projectors designed for machine vision applications typically will offer this feature. Example usage to use ProjectorFramePacker:: from psychopy.visual.windowframepack import ProjectorFramePacker win = Window(monitor='testMonitor', screen=1, fullscr=True, useFBO = True) framePacker = ProjectorFramePacker (win) """ def __init__(self, win): """ :Parameters: win : Handle to the window. """ super(ProjectorFramePacker, self).__init__() self.win = win # monkey patch window win._startOfFlip = self.startOfFlip win._endOfFlip = self.endOfFlip # This part is increasingly ugly. Add a function to set these values? win._monitorFrameRate = 180.0 win.monitorFramePeriod = 1.0 / win._monitorFrameRate win.refreshThreshold = (1.0 / win._monitorFrameRate) * 1.2 # enable Blue initially, since projector output sequence is BGR GL.glColorMask(False, False, True, True) self.flipCounter = 0 def startOfFlip(self): """Return True if all channels of the RGB frame have been filled with monochrome images, and the associated window should perform a hardware flip""" return self.flipCounter % 3 == 2 def endOfFlip(self, clearBuffer): """Mask RGB cyclically after each flip. We ignore clearBuffer and just auto-clear after each hardware flip. """ if self.flipCounter % 3 == 2: GL.glClear(GL.GL_COLOR_BUFFER_BIT) self.flipCounter += 1 if self.flipCounter % 3 == 0: GL.glColorMask(False, True, False, True) # enable green elif self.flipCounter % 3 == 1: GL.glColorMask(True, False, False, True) # enable red elif self.flipCounter % 3 == 2: GL.glColorMask(False, False, True, True) # enable blue
3,260
Python
.py
68
41.014706
78
0.697858
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,748
custommouse.py
psychopy_psychopy/psychopy/visual/custommouse.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Class for more control over the mouse, including the pointer graphic and bounding box.""" # 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 psychopy # so we can get the __path__ from psychopy import event, logging, visual, layout from psychopy.visual.basevisual import MinimalStim import numpy class CustomMouse(MinimalStim): """Class for more control over the mouse, including the pointer graphic and bounding box. This is a lazy-imported class, therefore import using full path `from psychopy.visual.custommouse import CustomMouse` when inheriting from it. Seems to work with pyglet or pygame. Not completely tested. Known limitations: * only norm units are working * getRel() always returns [0,0] * mouseMoved() is always False; maybe due to `self.mouse.visible == False` -> held at [0,0] * no idea if clickReset() works Author: Jeremy Gray, 2011 """ def __init__(self, win, newPos=None, visible=True, leftLimit=None, topLimit=None, rightLimit=None, bottomLimit=None, showLimitBox=False, clickOnUp=False, pointer=None, name=None, autoLog=None): """Class for customizing the appearance and behavior of the mouse. Use a custom mouse for extra control over the pointer appearance and function. It's probably slower to render than the regular system mouse. Create your `visual.Window` before creating a CustomMouse. Parameters ---------- win : required, `visual.Window` the window to which this mouse is attached visible : **True** or False makes the mouse invisible if necessary newPos : **None** or [x,y] gives the mouse a particular starting position leftLimit : left edge of a virtual box within which the mouse can move topLimit : top edge of virtual box rightLimit : right edge of virtual box bottomLimit : lower edge of virtual box showLimitBox : default is False display the boundary within which the mouse can move. pointer : The visual display item to use as the pointer; must have .draw() and setPos() methods. If your item has .setOpacity(), you can alter the mouse's opacity. clickOnUp : when to count a mouse click as having occurred default is False, record a click when the mouse is first pressed down. True means record a click when the mouse button is released. """ # what local vars are defined (these are the init params) for use by # __repr__ self._initParams = dir() self._initParams.remove('self') super(CustomMouse, self).__init__(name=name, autoLog=False) self.autoLog = False # set properly at end of init self.win = win self.mouse = event.Mouse(win=self.win) # maybe inheriting from Mouse would be easier? its not that simple self.getRel = self.mouse.getRel self.getWheelRel = self.mouse.getWheelRel self.mouseMoved = self.mouse.mouseMoved # FAILS self.mouseMoveTime = self.mouse.mouseMoveTime self.getPressed = self.mouse.getPressed self.clickReset = self.mouse.clickReset # ??? self._pix2windowUnits = self.mouse._pix2windowUnits self._windowUnits2pix = self.mouse._windowUnits2pix # the graphic to use as the 'mouse' icon (pointer) if pointer: self.pointer = pointer else: self.pointer = vm = visual.ShapeStim( win, vertices=[ [-0.5, 0.5], [-0.5, -0.35], [-0.3, -0.15], [-0.1, -0.5], [0.025, -0.425], [-0.175, -0.1], [0.1, -0.1], [-0.5, 0.5], ], fillColor="white", lineColor="black", lineWidth=1, anchor="top left", size=layout.Size((20, 20), 'pix', win), ) self.mouse.setVisible(False) # hide the actual (system) mouse self.visible = visible # the custom (virtual) mouse self.leftLimit = self.rightLimit = None self.topLimit = self.bottomLimit = None self.setLimit(leftLimit=leftLimit, topLimit=topLimit, rightLimit=rightLimit, bottomLimit=bottomLimit) self.showLimitBox = showLimitBox self.lastPos = None self.prevPos = None if newPos is not None: self.lastPos = newPos else: self.lastPos = self.mouse.getPos() # for counting clicks: self.clickOnUp = clickOnUp self.wasDown = False # state of mouse 1 frame prior to current frame self.clicks = 0 # how many mouse clicks since last reset self.clickButton = 0 # which button to count clicks for; 0 = left # set autoLog now that params have been initialised wantLog = autoLog is None and self.win.autoLog self.__dict__['autoLog'] = autoLog or wantLog if self.autoLog: logging.exp("Created %s = %s" % (self.name, str(self))) def _setPos(self, pos=None): """internal mouse position management. setting a position here leads to the virtual mouse being out of alignment with the hardware mouse, which leads to an 'invisible wall' effect for the mouse. """ if pos is None: pos = self.getPos() else: self.lastPos = pos self.pointer.setPos(pos) def setPos(self, pos): """Not implemented yet. Place the mouse at a specific position. """ raise NotImplementedError('setPos is not available for custom mouse') def getPos(self): """Returns the mouse's current position. Influenced by changes in .getRel(), constrained to be in its virtual box. """ dx, dy = self.getRel() x = min(max(self.lastPos[0] + dx, self.leftLimit), self.rightLimit) y = min(max(self.lastPos[1] + dy, self.bottomLimit), self.topLimit) self.lastPos = numpy.array([x, y]) return self.lastPos def draw(self): """Draw mouse (if it's visible), show the limit box, update the click count. """ self._setPos() if self.showLimitBox: self.box.draw() if self.visible: self.pointer.draw() isDownNow = self.getPressed()[self.clickButton] if self.clickOnUp: if self.wasDown and not isDownNow: # newly up self.clicks += 1 else: if not self.wasDown and isDownNow: # newly down self.clicks += 1 self.wasDown = isDownNow def getClicks(self): """Return the number of clicks since the last reset""" return self.clicks def resetClicks(self): """Set click count to zero""" self.clicks = 0 def getVisible(self): """Return the mouse's visibility state""" return self.visible def setVisible(self, visible): """Make the mouse visible or not (pyglet or pygame).""" self.visible = visible def setPointer(self, pointer): """Set the visual item to be drawn as the mouse pointer.""" if hasattr(pointer, 'draw') and hasattr(pointer, 'setPos'): self.pointer = pointer else: raise AttributeError("need .draw() and .setPos() methods" " in pointer") def setLimit(self, leftLimit=None, topLimit=None, rightLimit=None, bottomLimit=None): """Set the mouse's bounding box by specifying the edges. """ if type(leftLimit) in (int, float): self.leftLimit = leftLimit elif self.leftLimit is None: self.leftLimit = -1 if self.win.units == 'pix': self.leftLimit = self.win.size[0] / -2. if type(rightLimit) in (int, float): self.rightLimit = rightLimit elif self.rightLimit is None: self.rightLimit = .99 if self.win.units == 'pix': self.rightLimit = self.win.size[0] / 2.0 - 5 if type(topLimit) in (int, float): self.topLimit = topLimit elif self.topLimit is None: self.topLimit = 1 if self.win.units == 'pix': self.topLimit = self.win.size[1] / 2.0 if type(bottomLimit) in (int, float): self.bottomLimit = bottomLimit elif self.bottomLimit is None: self.bottomLimit = -0.98 if self.win.units == 'pix': self.bottomLimit = self.win.size[1] / -2.0 + 10 self.box = psychopy.visual.ShapeStim( self.win, vertices=[[self.leftLimit, self.topLimit], [self.rightLimit, self.topLimit], [self.rightLimit, self.bottomLimit], [self.leftLimit, self.bottomLimit], [self.leftLimit, self.topLimit]], opacity=0.35, autoLog=False) # avoid accumulated relative-offsets producing a different effective # limit: self.mouse.setVisible(True) self.lastPos = self.mouse.getPos() # hardware mouse's position self.mouse.setVisible(False)
9,800
Python
.py
224
32.986607
95
0.594841
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,749
brush.py
psychopy_psychopy/psychopy/visual/brush.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """A PsychoPy drawing tool Inspired by rockNroll87q - https://github.com/rockNroll87q/pyDrawing """ # 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 event, logging from .shape import ShapeStim from .basevisual import MinimalStim __author__ = 'David Bridges' from ..tools.attributetools import attributeSetter class Brush(MinimalStim): """A class for creating a freehand drawing tool. """ def __init__(self, win, lineWidth=1.5, lineColor=(1.0, 1.0, 1.0), lineColorSpace='rgb', opacity=1.0, closeShape=False, buttonRequired=True, name=None, depth=0, autoLog=True, autoDraw=False ): super(Brush, self).__init__(name=name, autoLog=False) self.win = win self.name = name self.depth = depth self.lineColor = lineColor self.lineColorSpace = lineColorSpace self.lineWidth = lineWidth self.opacity = opacity self.closeShape = closeShape self.buttonRequired = buttonRequired self.pointer = event.Mouse(win=self.win) self.shapes = [] self.brushPos = [] self.strokeIndex = -1 self.atStartPoint = False self.autoLog = autoLog self.autoDraw = autoDraw if self.autoLog: logging.exp("Created {name} = {obj}".format(name=self.name, obj=str(self))) def _resetVertices(self): """ Resets list of vertices passed to ShapeStim. """ if self.autoLog: logging.exp("Resetting {name} parameter: brushPos.".format(name=self.name)) self.brushPos = [] def _createStroke(self): """ Creates ShapeStim for each stroke. """ if self.autoLog: logging.exp("Creating ShapeStim for {name}".format(name=self.name)) self.shapes.append(ShapeStim(self.win, vertices=[[0, 0]], closeShape=self.closeShape, lineWidth=self.lineWidth, lineColor=self.lineColor, colorSpace=self.lineColorSpace, opacity=self.opacity, autoLog=False, autoDraw=True)) @property def currentShape(self): """The index of current shape to be drawn. Returns ------- Int The index as length of shapes attribute - 1. """ return len(self.shapes) - 1 @property def brushDown(self): """ Checks whether the mouse button has been clicked in order to start drawing. Returns ------- Bool True if left mouse button is pressed or if no button press is required, otherwise False. """ if self.buttonRequired: return self.pointer.getPressed()[0] == 1 else: return True def onBrushDown(self): """ On first brush stroke, empty pointer position list, and create a new ShapeStim. """ if self.brushDown and not self.atStartPoint: self.atStartPoint = True self._resetVertices() self._createStroke() def onBrushDrag(self): """ Check whether the brush is down. If brushDown is True, the brush path is drawn on screen. """ if self.brushDown: self.brushPos.append(self.pointer.getPos()) self.shapes[self.currentShape].setVertices(self.brushPos) else: self.atStartPoint = False def draw(self): """ Get starting stroke and begin painting on screen. """ self.onBrushDown() self.onBrushDrag() def reset(self): """ Clear ShapeStim objects from shapes attribute. """ if self.autoLog: logging.exp("Resetting {name}".format(name=self.name)) if len(self.shapes): for shape in self.shapes: shape.setAutoDraw(False) self.atStartPoint = False self.shapes = [] @attributeSetter def autoDraw(self, value): # Do base setting MinimalStim.autoDraw.func(self, value) # Set autodraw on shapes for shape in self.shapes: shape.setAutoDraw(value) def setLineColor(self, value): """ Sets the line color passed to ShapeStim. Parameters ---------- value Line color """ self.lineColor = value def setLineWidth(self, value): """ Sets the line width passed to ShapeStim. Parameters ---------- value Line width in pixels """ self.lineWidth = value def setOpacity(self, value): """ Sets the line opacity passed to ShapeStim. Parameters ---------- value Opacity range(0, 1) """ self.opacity = value def setButtonRequired(self, value): """ Sets whether or not a button press is needed to draw the line.. Parameters ---------- value Button press required (True or False). """ self.buttonRequired = value
5,789
Python
.py
171
22.812865
100
0.544136
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,750
simpleimage.py
psychopy_psychopy/psychopy/visual/simpleimage.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """A simple stimulus for loading images from a file and presenting at exactly the resolution and color in the file (subject to gamma correction if set). """ # 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 # Ensure setting pyglet.options['debug_gl'] to False is done prior to any # other calls to pyglet or pyglet submodules, otherwise it may not get picked # up by the pyglet GL engine and have no effect. # Shaders will work but require OpenGL2.0 drivers AND PyOpenGL3.0+ import pyglet from ..layout import Size pyglet.options['debug_gl'] = False GL = pyglet.gl import psychopy # so we can get the __path__ from psychopy import core, logging # tools must only be imported *after* event or MovieStim breaks on win32 # (JWP has no idea why!) from psychopy.tools.arraytools import val2array from psychopy.tools.monitorunittools import convertToPix from psychopy.tools.attributetools import setAttribute, attributeSetter from psychopy.tools.filetools import pathToString from psychopy.visual.basevisual import MinimalStim, WindowMixin from . import globalVars try: from PIL import Image except ImportError: from . import Image import numpy class SimpleImageStim(MinimalStim, WindowMixin): """A simple stimulus for loading images from a file and presenting at exactly the resolution and color in the file (subject to gamma correction if set). This is a lazy-imported class, therefore import using full path `from psychopy.visual.simpleimage import SimpleImageStim` when inheriting from it. Unlike the ImageStim, this type of stimulus cannot be rescaled, rotated or masked (although flipping horizontally or vertically is possible). Drawing will also tend to be marginally slower, because the image isn't preloaded to the graphics card. The slight advantage, however is that the stimulus will always be in its original aspect ratio, with no interplotation or other transformation, and it is slightly faster to load into PsychoPy. """ def __init__(self, win, image="", units="", pos=(0.0, 0.0), flipHoriz=False, flipVert=False, name=None, autoLog=None): """ """ # all doc is in the attributeSetter # what local vars are defined (these are the init params) for use by # __repr__ self._initParams = dir() self._initParams.remove('self') self.autoLog = False self.__dict__['win'] = win super(SimpleImageStim, self).__init__(name=name) self.units = units # call attributeSetter # call attributeSetter. Use shaders if available by default, this is a # good thing self.pos = pos # call attributeSetter self.image = image # call attributeSetter # check image size against window size print(self.size) if (self.size[0] > self.win.size[0] or self.size[1] > self.win.size[1]): msg = ("Image size (%s, %s) was larger than window size " "(%s, %s). Will draw black screen.") logging.warning(msg % (self.size[0], self.size[1], self.win.size[0], self.win.size[1])) # check position with size, warn if stimuli not fully drawn if ((self.pos[0] + self.size[0]/2) > self.win.size[0]/2 or (self.pos[0] - self.size[0]/2) < -self.win.size[0]/2): logging.warning("The image does not completely fit inside " "the window in the X direction.") if ((self.pos[1] + self.size[1]/2) > self.win.size[1]/2 or (self.pos[1] - self.size[1]/2) < -self.win.size[1]/2): logging.warning("The image does not completely fit inside " "the window in the Y direction.") # flip if necessary # initially it is false, then so the flip according to arg above self.__dict__['flipHoriz'] = False self.flipHoriz = flipHoriz # call attributeSetter # initially it is false, then so the flip according to arg above self.__dict__['flipVert'] = False self.flipVert = flipVert # call attributeSetter self._calcPosRendered() # set autoLog (now that params have been initialised) wantLog = autoLog is None and self.win.autoLog self.__dict__['autoLog'] = autoLog or wantLog if self.autoLog: logging.exp("Created {} = {}".format(self.name, self)) @attributeSetter def flipHoriz(self, value): """True/False. If set to True then the image will be flipped horizontally (left-to-right). Note that this is relative to the original image, not relative to the current state. """ if value != self.flipHoriz: # We need to make the flip # Numpy and pyglet disagree about ori so ud<=>lr self.imArray = numpy.flipud(self.imArray) self.__dict__['flipHoriz'] = value self._needStrUpdate = True def setFlipHoriz(self, newVal=True, log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message.""" setAttribute(self, 'flipHoriz', newVal, log) @attributeSetter def flipVert(self, value): """True/False. If set to True then the image will be flipped vertically (top-to-bottom). Note that this is relative to the original image, not relative to the current state. """ if value != self.flipVert: # We need to make the flip # Numpy and pyglet disagree about ori so ud<=>lr self.imArray = numpy.fliplr(self.imArray) self.__dict__['flipVert'] = value self._needStrUpdate = True def setFlipVert(self, newVal=True, log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message. """ setAttribute(self, 'flipVert', newVal, log) def _updateImageStr(self): self._imStr = self.imArray.tobytes() self._needStrUpdate = False def draw(self, win=None): """ Draw the stimulus in its relevant window. You must call this method after every MyWin.flip() if you want the stimulus to appear on that frame and then update the screen again. """ if win is None: win = self.win self._selectWindow(win) # push the projection matrix and set to orthorgaphic GL.glMatrixMode(GL.GL_PROJECTION) GL.glPushMatrix() GL.glLoadIdentity() # this also sets the 0,0 to be top-left GL.glOrtho(0, self.win.size[0], 0, self.win.size[1], 0, 1) # but return to modelview for rendering GL.glMatrixMode(GL.GL_MODELVIEW) GL.glLoadIdentity() GL.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, 1) if self._needStrUpdate: self._updateImageStr() # unbind any textures GL.glActiveTexture(GL.GL_TEXTURE0) GL.glEnable(GL.GL_TEXTURE_2D) GL.glBindTexture(GL.GL_TEXTURE_2D, 0) GL.glActiveTexture(GL.GL_TEXTURE1) GL.glEnable(GL.GL_TEXTURE_2D) GL.glBindTexture(GL.GL_TEXTURE_2D, 0) # move to center of stimulus x, y = self._posRendered[:2] GL.glRasterPos2f(self.win.size[0]/2 - self._size.pix[0]/2 + x, self.win.size[1]/2 - self._size.pix[1]/2 + y) # GL.glDrawPixelsub(GL.GL_RGB, self.imArr) GL.glDrawPixels(int(self._size.pix[0]), int(self._size.pix[1]), self.internalFormat, self.dataType, self._imStr) # return to 3D mode (go and pop the projection matrix) GL.glMatrixMode(GL.GL_PROJECTION) GL.glPopMatrix() GL.glMatrixMode(GL.GL_MODELVIEW) def _set(self, attrib, val, op='', log=True): """Deprecated. Use methods specific to the parameter you want to set. e.g. :: stim.pos = [3,2.5] stim.ori = 45 stim.phase += 0.5 NB this method does not flag the need for updates any more - that is done by specific methods as described above. """ if op is None: op = '' # format the input value as float vectors if isinstance(val, (tuple, list)): val = numpy.array(val, float) setAttribute(self, attrib, val, log, op) @property def pos(self): """:ref:`x,y-pair <attrib-xy>` specifying the centre of the image relative to the window center. Stimuli can be positioned off-screen, beyond the window! :ref:`operations <attrib-operations>` are supported. """ return WindowMixin.pos.fget(self) @pos.setter def pos(self, value): WindowMixin.pos.fset(self, value) self._calcPosRendered() def setPos(self, newPos, operation='', log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message. """ setAttribute(self, 'pos', newPos, log, operation) @attributeSetter def depth(self, value): """DEPRECATED. Depth is now controlled simply by drawing order. """ self.__dict__['depth'] = value def setDepth(self, newDepth, operation='', log=None): """DEPRECATED. Depth is now controlled simply by drawing order. """ setAttribute(self, 'depth', newDepth, log, operation) def _calcPosRendered(self): """Calculate the pos of the stimulus in pixels""" self._posRendered = convertToPix(pos=self.pos, vertices=numpy.array([0, 0]), units=self.units, win=self.win) @attributeSetter def image(self, filename): """Filename, including relative or absolute path. The image can be any format that the Python Imaging Library can import (almost any). Can also be an image already loaded by PIL. """ filename = pathToString(filename) self.__dict__['image'] = filename if isinstance(filename, str): # is a string - see if it points to a file if os.path.isfile(filename): self.filename = filename im = Image.open(self.filename) im = im.transpose(Image.FLIP_TOP_BOTTOM) else: logging.error("couldn't find image...%s" % filename) core.quit() else: # not a string - have we been passed an image? try: im = filename.copy().transpose(Image.FLIP_TOP_BOTTOM) except AttributeError: # apparently not an image logging.error("couldn't find image...%s" % filename) core.quit() self.filename = repr(filename) # '<Image.Image image ...>' self._size = Size(im.size, units='pix', win=self.win) # set correct formats for bytes/floats if im.mode == 'RGBA': self.imArray = numpy.array(im).astype(numpy.ubyte) self.internalFormat = GL.GL_RGBA else: self.imArray = numpy.array(im.convert("RGB")).astype(numpy.ubyte) self.internalFormat = GL.GL_RGB self.dataType = GL.GL_UNSIGNED_BYTE self._needStrUpdate = True def setImage(self, filename=None, log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message. """ filename = pathToString(filename) setAttribute(self, 'image', filename, log)
12,029
Python
.py
258
37.228682
79
0.625874
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,751
nnlvs.py
psychopy_psychopy/psychopy/visual/nnlvs.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Window class for the NordicNeuralLab's VisualSystemHD(tm) fMRI display system. """ # 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 ctypes import numpy as np import pyglet.gl as GL from psychopy.visual import window from psychopy import logging import psychopy.tools.mathtools as mt import psychopy.tools.viewtools as vt import psychopy.tools.gltools as gt try: from PIL import Image except ImportError: import Image reportNDroppedFrames = 5 # ------------------------------------------------------------------------------ # Configurations for the model of VSHD # vshdModels = { 'vshd': { # store the configuration for FOV and viewing distance by diopters 'configByDiopters': { -9: {'vfov': 29.70, 'dist': 0.111}, -8: {'vfov': 29.75, 'dist': 0.125}, -7: {'vfov': 29.8, 'dist': 0.143}, -6: {'vfov': 29.86, 'dist': 0.167}, -5: {'vfov': 29.92, 'dist': 0.20}, -4: {'vfov': 29.98, 'dist': 0.25}, -3: {'vfov': 30.04, 'dist': 0.333}, -2: {'vfov': 30.08, 'dist': 0.5}, -1: {'vfov': 30.14, 'dist': 1.0}, 0: {'vfov': 30.18, 'dist': 1.0}, # TODO: handle this case 1: {'vfov': 30.24, 'dist': -1.0}, # image gets inverted 2: {'vfov': 30.3, 'dist': -0.5}, 3: {'vfov': 30.36, 'dist': -0.333}, 4: {'vfov': 30.42, 'dist': -0.25}, 5: {'vfov': 30.46, 'dist': -0.2}, }, 'scrHeightM': 9.6 * 1200. / 1e-6, # screen height in meters 'scrWidthM': 9.6 * 1920. / 1e-6, # screen width in meters 'distCoef': -0.02, # distortion coef. depends on screen size 'resolution': (1920, 1200) # resolution for the display per eye } } # ------------------------------------------------------------------------------ # Window subclass class for VSHD hardware # class VisualSystemHD(window.Window): """Class provides support for NordicNeuralLab's VisualSystemHD(tm) fMRI display hardware. This is a lazy-imported class, therefore import using full path `from psychopy.visual.nnlvs import VisualSystemHD` when inheriting from it. Use this class in-place of the `Window` class for use with the VSHD hardware. Ensure that the VSHD headset display output is configured in extended desktop mode (eg. nVidia Surround). Extended desktops are only supported on Windows and Linux systems. The VSHD is capable of both 2D and stereoscopic 3D rendering. You can select which eye to draw to by calling `setBuffer`, much like how stereoscopic rendering is implemented in the base `Window` class. Notes ----- * This class handles drawing differently than the default window class, as a result, stimuli `autoDraw` is not supported. * Edges of the warped image may appear jagged. To correct this, create a window using `multiSample=True` and `numSamples > 1` to smooth out these artifacts. Examples -------- Here is a basic example of 2D rendering using the VisualSystemHD(tm). This is the binocular version of the dynamic 'plaid.py' demo:: from psychopy import visual, core, event # Create a visual window win = visual.VisualSystemHD(fullscr=True, screen=1) # Initialize some stimuli, note contrast, opacity, ori grating1 = visual.GratingStim(win, mask="circle", color='white', contrast=0.5, size=(1.0, 1.0), sf=(4, 0), ori = 45, autoLog=False) grating2 = visual.GratingStim(win, mask="circle", color='white', opacity=0.5, size=(1.0, 1.0), sf=(4, 0), ori = -45, autoLog=False, pos=(0.1, 0.1)) trialClock = core.Clock() t = 0 while not event.getKeys() and t < 20: t = trialClock.getTime() for eye in ('left', 'right'): win.setBuffer(eye) # change the buffer grating1.phase = 1 * t # drift at 1Hz grating1.draw() # redraw it grating2.phase = 2 * t # drift at 2Hz grating2.draw() # redraw it win.flip() win.close() core.quit() As you can see above, there are few changes needed to convert an existing 2D experiment to run on the VSHD. For 3D rendering with perspective, you need set `eyeOffset` and apply the projection by calling `setPerspectiveView`. (other projection modes are not implemented or supported right now):: from psychopy import visual, core, event # Create a visual window win = visual.VisualSystemHD(fullscr=True, screen=1, multiSample=True, nSamples=8) # text to display instr = visual.TextStim(win, text="Any key to quit", pos=(0, -.7)) # create scene light at the pivot point win.lights = [ visual.LightSource(win, pos=(0.4, 4.0, -2.0), lightType='point', diffuseColor=(0, 0, 0), specularColor=(1, 1, 1)) ] win.ambientLight = (0.2, 0.2, 0.2) # Initialize some stimuli, note contrast, opacity, ori ball = visual.SphereStim(win, radius=0.1, pos=(0, 0, -2), color='green', useShaders=False) iod = 6.2 # interocular separation in CM win.setEyeOffset(-iod / 2.0, 'left') win.setEyeOffset(iod / 2.0, 'right') trialClock = core.Clock() t = 0 while not event.getKeys() and t < 20: t = trialClock.getTime() for eye in ('left', 'right'): win.setBuffer(eye) # change the buffer # setup drawing with perspective win.setPerspectiveView() win.useLights = True # switch on lights ball.draw() # draw the ball # shut the lights, needed to prevent light color from affecting # 2D stim win.useLights = False # reset transform to draw text correctly win.resetEyeTransform() instr.draw() win.flip() win.close() core.quit() """ def __init__(self, monoscopic=False, diopters=(-1, -1), lensCorrection=True, distCoef=None, directDraw=False, model='vshd', *args, **kwargs): """ Parameters ---------- monoscopic : bool Use monoscopic rendering. If `True`, the same image will be drawn to both eye buffers. You will not need to call `setBuffer`. It is not possible to set monoscopic mode after the window is created. It is recommended that you use monoscopic mode if you intend to display only 2D stimuli about the center of the display as it uses a less memory intensive rendering pipeline. diopters : tuple or list Initial diopter values for the left and right eye. Default is `(-1, -1)`, values must be integers. lensCorrection : bool Apply lens correction (barrel distortion) to the output. The amount of distortion applied can be specified using `distCoef`. If `False`, no distortion will be applied to the output and the entire display will be used. Not applying correction will result in pincushion distortion which produces a non-rectilinear output. distCoef : float Distortion coefficient for barrel distortion. If `None`, the recommended value will be used for the model of display. You can adjust the value to fine-tune the barrel distortion. directDraw : bool Direct drawing mode. Stimuli are drawn directly to the back buffer instead of creating separate buffer. This saves video memory but does not permit barrel distortion or monoscopic rendering. If `False`, drawing is done with two FBOs containing each eye's image. hwModel : str Model of the VisualSystemHD in use. Used to set viewing parameters accordingly. Default is 'vshd'. Cannot be changed after starting the application. """ # warn if given `useFBO` if kwargs.get('useFBO', False): logging.warning( "Creating a window with `useFBO` is not recommended.") # call up a new window object super(VisualSystemHD, self).__init__(*args, **kwargs) # direct draw mode self._directDraw = directDraw # is monoscopic mode enabled? self._monoscopic = monoscopic and not self._directDraw self._lensCorrection = lensCorrection and not self._directDraw # hardware information for a given model of the display, used for # configuration self._hwModel = model self._hwDesc = vshdModels[self._hwModel] # distortion coefficient self._distCoef = \ self._hwDesc['distCoef'] if distCoef is None else float(distCoef) # diopter settings for each eye, needed to compute actual FOV self._diopters = {'left': diopters[0], 'right': diopters[1]} # eye offsets, this will be standard when multi-buffer rendering gets # implemented in the main window class self._eyeOffsets = {'left': -3.1, 'right': 3.1} # look-up table of FOV values for each diopter setting self._fovLUT = self._hwDesc['configByDiopters'] # get the dimensions of the buffer for each eye bufferWidth, bufferHieght = self.frameBufferSize bufferWidth = int(bufferWidth / 2.0) # viewports for each buffer self._bufferViewports = dict() self._bufferViewports['left'] = (0, 0, bufferWidth, bufferHieght) self._bufferViewports['right'] = \ (bufferWidth if self._directDraw else 0, 0, bufferWidth, bufferHieght) self._bufferViewports['back'] = \ (0, 0, self.frameBufferSize[0], self.frameBufferSize[1]) # create render targets for each eye buffer self.buffer = None self._eyeBuffers = dict() # VAOs for distortion mesh self._warpVAOs = dict() # extents of the barrel distortion needed to compute FOV after # distortion self._distExtents = { 'left': np.array([[-1, 0], [1, 0], [0, 1], [0, -1]]), 'right': np.array([[-1, 0], [1, 0], [0, 1], [0, -1]]) } # if we are using an FBO, keep a reference to its handles if self.useFBO: self._eyeBuffers['back'] = { 'frameBuffer': self.frameBuffer, 'frameTexture': self.frameTexture, 'frameStencil': self._stencilTexture} self._setupEyeBuffers() # setup additional framebuffers self._setupLensCorrection() # setup lens correction meshes self.setBuffer('left') # set to the back buffer on start @property def monoscopic(self): """`True` if using monoscopic mode.""" return self._monoscopic @property def lensCorrection(self): """`True` if using lens correction.""" return self._lensCorrection @lensCorrection.setter def lensCorrection(self, value): self._lensCorrection = value @property def distCoef(self): """Distortion coefficient (`float`).""" return self._distCoef @distCoef.setter def distCoef(self, value): if isinstance(value, (float, int,)): self._distCoef = float(value) elif value is None: self._distCoef = self._hwDesc['distCoef'] else: raise ValueError('Invalid value for `distCoef`.') self._setupLensCorrection() # deletes old VAOs @property def diopters(self): """Diopters value of the current eye buffer.""" return self._diopters[self.buffer] @diopters.setter def diopters(self, value): self.setDiopters(value) def setDiopters(self, diopters, eye=None): """Set the diopters for a given eye. Parameters ---------- diopters : int Set diopters for a given eye, ranging between -7 and +5. eye : str or None Eye to set, either 'left' or 'right'. If `None`, the currently set buffer will be used. """ eye = self.buffer if eye is None else eye # check if diopters value in config if diopters not in self._hwDesc['configByDiopters'].keys(): raise ValueError("Diopter setting invalid for display model.") try: self._diopters[eye] = int(diopters) except KeyError: raise ValueError( "Invalid `eye` specified, must be 'left' or 'right'.") @property def eyeOffset(self): """Eye offset for the current buffer in centimeters used for stereoscopic rendering. This works differently than the main window class as it sets the offset for the current buffer. The offset is saved and automatically restored when the buffer is selected. """ return self._eyeOffsets[self.buffer] * 100. # to centimeters @eyeOffset.setter def eyeOffset(self, value): self._eyeOffsets[self.buffer] = float(value) / 100. # to meters def setEyeOffset(self, dist, eye=None): """Set the eye offset in centimeters. When set, successive rendering operations will use the new offset. Parameters ---------- dist : float or int Lateral offset in centimeters from the nose, usually half the interocular separation. The distance is signed. eye : str or None Eye offset to set. Can either be 'left', 'right' or `None`. If `None`, the offset of the current buffer is used. """ eye = self.buffer if eye is None else eye try: self._eyeOffsets[eye] = float(dist) / 100. # to meters except KeyError: raise ValueError( "Invalid `eye` specified, must be 'left' or 'right'.") # def _getFocalLength(self, eye=None): # """Get the focal length for a given `eye` in meters. # # Parameters # ---------- # eye : str or None # Eye to use, either 'left' or 'right'. If `None`, the currently # set buffer will be used. # # """ # try: # focalLength = 1. / self._diopters[eye] # except KeyError: # raise ValueError( # "Invalid value for `eye`, must be 'left' or 'right'.") # except ZeroDivisionError: # raise ValueError("Value for diopters cannot be zero.") # # return focalLength # # def _getMagFactor(self, eye=None): # """Get the magnification factor of the lens for a given eye. Used to # in part to compute the actual size of the object. # # Parameters # ---------- # eye : str or None # Eye to use, either 'left' or 'right'. If `None`, the currently # set buffer will be used. # # """ # eye = self.buffer if eye is None else eye # return (self._diopters[eye] / 4.) + 1. # # def _getScreenFOV(self, eye, direction='horizontal', degrees=True): # """Compute the FOV of the display.""" # if direction not in ('horizontal', 'vertical'): # raise ValueError("Invalid `direction` specified, must be " # "'horizontal' or 'vertical'.") # # # todo: figure this out # # def _getPredictedFOV(self, size, eye=None): # """Get the predicted vertical FOV of the display for a given eye. # # Parameters # ---------- # size : float # Size of the object on screen in meters. # eye : str or None # Eye to use, either 'left' or 'right'. If `None`, the currently # set buffer will be used. # # """ # return np.degrees(2. * np.arctan(size / (2. * self._getFocalLength(eye)))) # # def _getActualFOV(self, size, eye=None): # """Get the actual FOV of an object of `size` for a given eye.""" # if eye not in ('left', 'right'): # raise ValueError( # "Invalid value for `eye`, must be 'left' or 'right'.") # # # predFOV = self._getPredictedFOV(size, eye) # actualFOV = 0.0098 * size ** 3 - 0.0576 * size ** 2 + 2.6728 * size - 0.0942 # # return actualFOV # # def getDistortion(self, size, eye=None): # """Get the optical distortion amount (percent) for a stimulus of given # `size` in degrees positioned at the center of the display.""" # predFOV = self._getPredictedFOV(size, eye) # actualFOV = self._getActualFOV(size, eye) # # return ((actualFOV - predFOV) * predFOV) * 100. def _getWarpExtents(self, eye): """Get the horizontal and vertical extents of the barrel distortion in normalized device coordinates. This is used to determine the FOV along each axis after barrel distortion. Parameters ---------- eye : str Eye to compute the extents for. Returns ------- ndarray 2d array of coordinates [+X, -X, +Y, -Y] of the extents of the barrel distortion. """ coords = np.array([ [-1.0, 0.0], [ 1.0, 0.0], [ 0.0, 1.0], [ 0.0, -1.0]]) try: bufferW, bufferH = self._bufferViewports[eye][2:] except KeyError: raise ValueError("Invalid eye buffer specified.") warpedCoords = mt.lensCorrectionSpherical( coords, self._distCoef, bufferW / bufferH) return warpedCoords def _setupLensCorrection(self): """Setup the VAOs needed for lens correction. """ # don't create warp mesh if direct draw enabled if self._directDraw: return # clean up previous distortion data if self._warpVAOs: for vao in self._warpVAOs.values(): gt.deleteVAO(vao) self._warpVAOs = {} for eye in ('left', 'right'): # setup vertex arrays for the output quad bufferW, bufferH = self._bufferViewports[eye][2:] aspect = bufferW / bufferH vertices, texCoord, normals, faces = gt.createMeshGrid( (2.0, 2.0), subdiv=256, tessMode='radial') # recompute vertex positions vertices[:, :2] = mt.lensCorrectionSpherical( vertices[:, :2], coefK=self.distCoef, aspect=aspect) # create the VAO for the eye buffer vertexVBO = gt.createVBO(vertices, usage=GL.GL_DYNAMIC_DRAW) texCoordVBO = gt.createVBO(texCoord, usage=GL.GL_DYNAMIC_DRAW) indexBuffer = gt.createVBO( faces.flatten(), target=GL.GL_ELEMENT_ARRAY_BUFFER, dataType=GL.GL_UNSIGNED_INT) attribBuffers = {GL.GL_VERTEX_ARRAY: vertexVBO, GL.GL_TEXTURE_COORD_ARRAY: texCoordVBO} self._warpVAOs[eye] = gt.createVAO(attribBuffers, indexBuffer=indexBuffer, legacy=True) # get the extents of the warping self._distExtents[eye] = self._getWarpExtents(eye) def _setupEyeBuffers(self): """Setup additional buffers for rendering content to each eye. """ if self._directDraw: # don't create additional buffers is direct draw return def createFramebuffer(width, height): """Function for setting up additional buffer""" # create a new framebuffer fboId = GL.GLuint() GL.glGenFramebuffers(1, ctypes.byref(fboId)) GL.glBindFramebuffer(GL.GL_FRAMEBUFFER, fboId) # create a texture to render to, required for warping texId = GL.GLuint() GL.glGenTextures(1, ctypes.byref(texId)) GL.glBindTexture(GL.GL_TEXTURE_2D, texId) GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR) GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR) GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGBA32F_ARB, int(width), int(height), 0, GL.GL_RGBA, GL.GL_FLOAT, None) GL.glFramebufferTexture2D(GL.GL_FRAMEBUFFER, GL.GL_COLOR_ATTACHMENT0, GL.GL_TEXTURE_2D, texId, 0) # create a render buffer rbId = GL.GLuint() GL.glGenRenderbuffers(1, ctypes.byref(rbId)) GL.glBindRenderbuffer(GL.GL_RENDERBUFFER, rbId) GL.glRenderbufferStorage( GL.GL_RENDERBUFFER, GL.GL_DEPTH24_STENCIL8, int(width), int(height)) GL.glFramebufferRenderbuffer( GL.GL_FRAMEBUFFER, GL.GL_DEPTH_ATTACHMENT, GL.GL_RENDERBUFFER, rbId) GL.glFramebufferRenderbuffer( GL.GL_FRAMEBUFFER, GL.GL_STENCIL_ATTACHMENT, GL.GL_RENDERBUFFER, rbId) GL.glBindRenderbuffer(GL.GL_RENDERBUFFER, 0) # clear the buffer GL.glClear(GL.GL_COLOR_BUFFER_BIT) GL.glClear(GL.GL_STENCIL_BUFFER_BIT) GL.glClear(GL.GL_DEPTH_BUFFER_BIT) GL.glBindFramebuffer(GL.GL_FRAMEBUFFER, 0) return fboId, texId, rbId if not self._monoscopic: # create eye buffers for eye in ('left', 'right'): # get dimensions of required buffer bufferW, bufferH = self._bufferViewports[eye][2:] fboId, texId, rbId = createFramebuffer(bufferW, bufferH) # add new buffers self._eyeBuffers[eye] = { 'frameBuffer': fboId, 'frameTexture': texId, 'frameStencil': rbId} else: # only the left eye buffer is created bufferW, bufferH = self._bufferViewports['left'][2:] fboId, texId, rbId = createFramebuffer(bufferW, bufferH) self._eyeBuffers['left'] = { 'frameBuffer': fboId, 'frameTexture': texId, 'frameStencil': rbId} self._eyeBuffers['right'] = self._eyeBuffers['left'] def setBuffer(self, buffer, clear=True): """Set the eye buffer to draw to. Subsequent draw calls will be diverted to the specified eye. Parameters ---------- buffer : str Eye buffer to draw to. Values can either be 'left' or 'right'. clear : bool Clear the buffer prior to drawing. """ # check if the buffer name is valid if buffer not in ('left', 'right', 'back'): raise RuntimeError("Invalid buffer name specified.") # don't change the buffer if same, but allow clearing if buffer != self.buffer: if not self._directDraw: # handle when the back buffer is selected if buffer == 'back': if self.useFBO: GL.glBindFramebuffer( GL.GL_FRAMEBUFFER, self._eyeBuffers[buffer]['frameBuffer']) else: GL.glBindFramebuffer(GL.GL_FRAMEBUFFER, 0) else: GL.glBindFramebuffer( GL.GL_FRAMEBUFFER, self._eyeBuffers[buffer]['frameBuffer']) self.viewport = self.scissor = self._bufferViewports[buffer] GL.glEnable(GL.GL_SCISSOR_TEST) self.buffer = buffer # set buffer string if clear: self.setColor(self.color) # clear the buffer to the window color GL.glClearDepth(1.0) GL.glDepthMask(GL.GL_TRUE) GL.glClear( GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT | GL.GL_STENCIL_BUFFER_BIT) GL.glDisable(GL.GL_TEXTURE_2D) GL.glEnable(GL.GL_BLEND) def setPerspectiveView(self, applyTransform=True, clearDepth=True): """Set the projection and view matrix to render with perspective. Matrices are computed using values specified in the monitor configuration with the scene origin on the screen plane. Calculations assume units are in meters. If `eyeOffset != 0`, the view will be transformed laterally, however the frustum shape will remain the same. Note that the values of :py:attr:`~Window.projectionMatrix` and :py:attr:`~Window.viewMatrix` will be replaced when calling this function. Parameters ---------- applyTransform : bool Apply transformations after computing them in immediate mode. Same as calling :py:attr:`~Window.applyEyeTransform()` afterwards if `False`. clearDepth : bool, optional Clear the depth buffer. """ # Not in full screen mode? Need to compute the dimensions of the display # area to ensure disparities are correct even when in windowed-mode. aspect = self.size[0] / self.size[1] # use these instead of those from the monitor configuration vfov = self._fovLUT[self._diopters[self.buffer]]['vfov'] scrDist = self._fovLUT[self._diopters[self.buffer]]['dist'] frustum = vt.computeFrustumFOV( vfov, aspect, # aspect ratio scrDist, nearClip=self._nearClip, farClip=self._farClip) self._projectionMatrix = \ vt.perspectiveProjectionMatrix(*frustum, dtype=np.float32) # translate away from screen self._viewMatrix = np.identity(4, dtype=np.float32) self._viewMatrix[0, 3] = -self._eyeOffsets[self.buffer] # apply eye offset self._viewMatrix[2, 3] = -scrDist # displace scene away from viewer if applyTransform: self.applyEyeTransform(clearDepth=clearDepth) def _blitEyeBuffer(self, eye): """Warp and blit to the appropriate eye buffer. Parameters ---------- eye : str Eye buffer being used. """ GL.glBindTexture(GL.GL_TEXTURE_2D, self._eyeBuffers[eye]['frameTexture']) GL.glEnable(GL.GL_SCISSOR_TEST) # set the viewport and scissor rect for the buffer frameW, frameH = self._bufferViewports[eye][2:] offset = 0 if eye == 'left' else frameW self.viewport = self.scissor = (offset, 0, frameW, frameH) GL.glMatrixMode(GL.GL_PROJECTION) GL.glLoadIdentity() GL.glOrtho(-1, 1, -1, 1, -1, 1) GL.glMatrixMode(GL.GL_MODELVIEW) GL.glLoadIdentity() # anti-aliasing the edges of the polygon GL.glEnable(GL.GL_MULTISAMPLE) # blit the quad covering the side of the display the eye is viewing if self.lensCorrection: gt.drawVAO(self._warpVAOs[eye]) else: self._renderFBO() GL.glDisable(GL.GL_MULTISAMPLE) # reset GL.glDisable(GL.GL_SCISSOR_TEST) self.viewport = self.scissor = \ (0, 0, self.frameBufferSize[0], self.frameBufferSize[1]) def _startOfFlip(self): """Custom :py:class:`~Rift._startOfFlip` for HMD rendering. This finalizes the HMD texture before diverting drawing operations back to the on-screen window. This allows :py:class:`~Rift.flip` to swap the on-screen and HMD buffers when called. This function always returns `True`. Returns ------- True """ # nop if we are still setting up the window if not hasattr(self, '_eyeBuffers'): return True # direct draw being used, don't do FBO blit if self._directDraw: return True # Switch off multi-sampling # GL.glDisable(GL.GL_MULTISAMPLE) oldColor = self.color self.setColor((-1, -1, -1)) self.setBuffer('back', clear=True) self._prepareFBOrender() # need blit the framebuffer object to the actual back buffer # unbind the framebuffer as the render target GL.glDisable(GL.GL_BLEND) stencilOn = self.stencilTest self.stencilTest = False # before flipping need to copy the renderBuffer to the # frameBuffer GL.glActiveTexture(GL.GL_TEXTURE0) GL.glEnable(GL.GL_TEXTURE_2D) GL.glColor3f(1.0, 1.0, 1.0) # glColor multiplies with texture GL.glColorMask(True, True, True, True) # blit the textures to the back buffer for eye in ('left', 'right'): self._blitEyeBuffer(eye) GL.glEnable(GL.GL_BLEND) self._finishFBOrender() self.stencilTest = stencilOn self.setColor(oldColor) # This always returns True return True def _endOfFlip(self, clearBuffer): """Override end of flip with custom color channel masking if required. """ if clearBuffer: GL.glClear(GL.GL_COLOR_BUFFER_BIT) # nop if we are still setting up the window if hasattr(self, '_eyeBuffers'): self.setBuffer('left', clear=clearBuffer) if __name__ == "__main__": pass
30,335
Python
.py
682
33.963343
86
0.582859
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,752
movie2.py
psychopy_psychopy/psychopy/visual/movie2.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). # # Contributed by Sol Simpson, April 2014. # The MovieStim class was taken and rewritten to use cv2 and vlc instead # of avbin from psychopy.tools.pkgtools import PluginStub class MovieStim2( PluginStub, plugin="psychopy-legacy", doclink="https://psychopy.github.io/psychopy-legacy/coder/visual/MovieStim2" ): pass
564
Python
.py
16
33
80
0.761029
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,753
aperture.py
psychopy_psychopy/psychopy/visual/aperture.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Restrict a stimulus visibility area to a basic shape or list of vertices. """ # 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 # Ensure setting pyglet.options['debug_gl'] to False is done prior to any # other calls to pyglet or pyglet submodules, otherwise it may not get picked # up by the pyglet GL engine and have no effect. # Shaders will work but require OpenGL2.0 drivers AND PyOpenGL3.0+ import pyglet pyglet.options['debug_gl'] = False GL = pyglet.gl import psychopy # so we can get the __path__ from psychopy import logging, core import psychopy.event # tools must only be imported *after* event or MovieStim breaks on win32 # (JWP has no idea why!) from psychopy.tools.monitorunittools import cm2pix, deg2pix, convertToPix from psychopy.tools.attributetools import attributeSetter, setAttribute from psychopy.visual.shape import BaseShapeStim, knownShapes from psychopy.visual.image import ImageStim from psychopy.visual.basevisual import MinimalStim, ContainerMixin, WindowMixin import numpy from numpy import cos, sin, radians from psychopy.constants import STARTED, STOPPED class Aperture(MinimalStim, ContainerMixin): """Restrict a stimulus visibility area to a basic shape or list of vertices. When enabled, any drawing commands will only operate on pixels within the Aperture. Once disabled, subsequent draw operations affect the whole screen as usual. Supported shapes: * 'square', 'triangle', 'circle' or `None`: a polygon with appropriate nVerts will be used (120 for 'circle') * integer: a polygon with that many vertices will be used * list or numpy array (Nx2): it will be used directly as the vertices to a :class:`~psychopy.visual.ShapeStim` * a filename then it will be used to load and image as a :class:`~psychopy.visual.ImageStim`. Note that transparent parts in the image (e.g. in a PNG file) will not be included in the mask shape. The color of the image will be ignored. See demos/stimuli/aperture.py for example usage :Author: 2011, Yuri Spitsyn 2011, Jon Peirce added units options, Jeremy Gray added shape & orientation 2014, Jeremy Gray added .contains() option 2015, Thomas Emmerling added ImageStim option """ def __init__(self, win, size=1, pos=(0, 0), anchor=None, ori=0, nVert=120, shape='circle', inverted=False, units=None, name=None, depth=0, autoLog=None): # what local vars are defined (these are the init params) for use by # __repr__ self._initParams = dir() self._initParams.remove('self') super(Aperture, self).__init__(name=name, autoLog=False) # set self params self.autoLog = False # change after attribs are set self.depth = depth self.win = win if not win.allowStencil: logging.error('Aperture has no effect in a window created ' 'without allowStencil=True') core.quit() self.__dict__['ori'] = ori self.__dict__['inverted'] = inverted self.__dict__['filename'] = False # unit conversions if units != None and len(units): self.units = units else: self.units = win.units vertices = shape if isinstance(shape, str) and os.path.isfile(shape): # see if it points to a file self.__dict__['filename'] = shape if self.__dict__['filename']: self._shape = ImageStim( win=self.win, image=self.__dict__['filename'], pos=pos, size=size, autoLog=False, units=self.units) else: self._shape = BaseShapeStim( win=self.win, vertices=vertices, fillColor=1, lineColor=None, colorSpace='rgb', interpolate=False, pos=pos, size=size, anchor=anchor, autoLog=False, units=self.units) self.vertices = self._shape.vertices self._needVertexUpdate = True self._needReset = True # Default when setting attributes # implicitly runs a self.enabled = True. Also sets # self._needReset = True on every call self._reset() self.size = size self.pos = pos # set autoLog now that params have been initialised wantLog = autoLog is None and self.win.autoLog self.__dict__['autoLog'] = autoLog or wantLog if self.autoLog: logging.exp("Created {} = {}".format(self.name, self)) def _reset(self): """Internal method to rebuild the shape - shouldn't be called by the user. You have to explicitly turn resetting off by setting self._needReset = False """ if not self._needReset: self._needReset = True else: self.enabled = True # attributeSetter, turns on. GL.glClearStencil(0) GL.glClear(GL.GL_STENCIL_BUFFER_BIT) GL.glPushMatrix() if self.__dict__['filename'] == False: self.win.setScale('pix') GL.glDisable(GL.GL_LIGHTING) self.win.depthTest = False self.win.depthMask = False GL.glStencilFunc(GL.GL_NEVER, 0, 0) GL.glStencilOp(GL.GL_INCR, GL.GL_INCR, GL.GL_INCR) if isinstance(self._shape, ImageStim): GL.glEnable(GL.GL_ALPHA_TEST) GL.glAlphaFunc(GL.GL_GREATER, 0) self._shape.draw() GL.glDisable(GL.GL_ALPHA_TEST) else: # draw without push/pop matrix self._shape.draw(keepMatrix=True) if self.inverted: GL.glStencilFunc(GL.GL_EQUAL, 0, 1) else: GL.glStencilFunc(GL.GL_EQUAL, 1, 1) GL.glStencilOp(GL.GL_KEEP, GL.GL_KEEP, GL.GL_KEEP) GL.glPopMatrix() @property def size(self): """Set the size (diameter) of the Aperture. This essentially controls a :class:`.ShapeStim` so see documentation for ShapeStim.size. :ref:`Operations <attrib-operations>` supported here as well as ShapeStim. Use setSize() if you want to control logging and resetting. """ return WindowMixin.size.fget(self) @size.setter def size(self, value): WindowMixin.size.fset(self, value) self._shape.size = value # _shape is a ShapeStim self._reset() def setSize(self, size, needReset=True, log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message """ self._needReset = needReset setAttribute(self, 'size', size, log) @attributeSetter def ori(self, ori): """Set the orientation of the Aperture. This essentially controls a :class:`.ShapeStim` so see documentation for ShapeStim.ori. :ref:`Operations <attrib-operations>` supported here as well as ShapeStim. Use setOri() if you want to control logging and resetting. """ self.__dict__['ori'] = ori self._shape.ori = ori # a ShapeStim self._reset() def setOri(self, ori, needReset=True, log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message. """ self._needReset = needReset setAttribute(self, 'ori', ori, log) @property def pos(self): """Set the pos (centre) of the Aperture. :ref:`Operations <attrib-operations>` supported. This essentially controls a :class:`.ShapeStim` so see documentation for ShapeStim.pos. :ref:`Operations <attrib-operations>` supported here as well as ShapeStim. Use setPos() if you want to control logging and resetting. """ return WindowMixin.pos.fget(self) @pos.setter def pos(self, value): WindowMixin.pos.fset(self, value) self._shape.pos = value # a ShapeStim self._reset() def setPos(self, pos, needReset=True, log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message """ self._needReset = needReset setAttribute(self, 'pos', pos, log) @property def anchor(self): return WindowMixin.anchor.fget(self._shape) @anchor.setter def anchor(self, value): WindowMixin.anchor.fset(self._shape, value) def setAnchor(self, value, log=None): setAttribute(self, 'anchor', value, log) @property def vertices(self): return WindowMixin.vertices.fget(self._shape) @vertices.setter def vertices(self, value): WindowMixin.vertices.fset(self._shape, value) @property def flip(self): return WindowMixin.flip.fget(self) @flip.setter def flip(self, value): WindowMixin.flip.fset(self, value) self._shape.flip = value # a ShapeStim @attributeSetter def inverted(self, value): """True / False. Set to true to invert the aperture. A non-inverted aperture masks everything BUT the selected shape. An inverted aperture masks the selected shape. NB. The Aperture is not inverted by default, when created. """ self.__dict__['inverted'] = value self._reset() def invert(self): """Use Aperture.inverted = True instead. """ self.inverted = True @property def posPix(self): """The position of the aperture in pixels """ return self._shape._pos.pix @property def sizePix(self): """The size of the aperture in pixels """ return self._shape._size.pix @attributeSetter def enabled(self, value): """True / False. Enable or disable the aperture. Determines whether it is used in future drawing operations. NB. The Aperture is enabled by default, when created. """ if value: if self._shape._needVertexUpdate: self._shape._updateVertices() self.win.stencilTest = True self.status = STARTED else: self.win.stencilTest = False self.status = STOPPED self.__dict__['enabled'] = value def enable(self): """Use Aperture.enabled = True instead. """ self.enabled = True def disable(self): """Use Aperture.enabled = False instead. """ self.enabled = False def __del__(self): try: self.enabled = False except (ImportError, ModuleNotFoundError, TypeError): pass # trying to avoid 'Exception ignored in: ....' error from pyglet when experiment exits
11,120
Python
.py
266
33.18797
104
0.632994
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,754
roi.py
psychopy_psychopy/psychopy/visual/roi.py
import numpy as np from .shape import ShapeStim from ..event import Mouse from ..core import Clock class ROI(ShapeStim): """ A class to handle regions of interest for eyetracking, is essentially a :class:`~psychopy.visual.polygon` but with some extra methods and properties for interacting with eyetracking. Parameters ---------- win : :class:`~psychopy.visual.Window` Window which device position input will be relative to. The stimulus instance will allocate its required resources using that Windows context. In many cases, a stimulus instance cannot be drawn on different windows unless those windows share the same OpenGL context, which permits resources to be shared between them. name : str Optional name of the ROI for logging. device : :class:`~psychopy.iohub.devices.eyetracking.EyeTrackerDevice` The device which this ROI is getting position data from. debug : bool If True, then the ROI becomes visible as a red shape on screen. This is intended purely for debugging purposes, so that you can see where on screen the ROI is when building an expriment. shape : str The shape of this ROI, will accept an array of vertices pos : array_like Initial position (`x`, `y`) of the ROI on-screen relative to the origin located at the center of the window or buffer in `units`. This can be updated after initialization by setting the `pos` property. The default value is `(0.0, 0.0)` which results in no translation. size : float or array_like Initial scale factor for adjusting the size of the ROI. A single value (`float`) will apply uniform scaling, while an array (`sx`, `sy`) will result in anisotropic scaling in the horizontal (`sx`) and vertical (`sy`) direction. Providing negative values to `size` will cause the shape being mirrored. Scaling can be changed by setting the `size` property after initialization. The default value is `1.0` which results in no scaling. units : str Units to use when drawing. This will affect how parameters and attributes `pos`, `size` and `radius` are interpreted. ori : float Initial orientation of the shape in degrees about its origin. Positive values will rotate the shape clockwise, while negative values will rotate counterclockwise. The default value for `ori` is 0.0 degrees. isLookedIn : bool Returns True if participant is currently looking at the ROI. timesOn : list List of times when the participant's gaze entered the ROI. timesOff : list List of times when the participant's gaze left the ROI. """ def __init__(self, win, name=None, device=None, debug=False, shape="rectangle", units='', pos=(0, 0), size=(1, 1), anchor="center", ori=0.0, depth=0, autoLog=None, autoDraw=False): # Create red polygon which doesn't draw if `debug == False` ShapeStim.__init__(self, win, name=name, units=units, pos=pos, size=size, anchor=anchor, ori=ori, vertices=shape, fillColor='white', lineColor="#F2545B", lineWidth=2, opacity=0.5, autoLog=autoLog, autoDraw=autoDraw) self.depth = depth self.debug = debug if device is None: self.device = Mouse(win=win) else: self.device = device self.wasLookedIn = False self.clock = Clock() self.timesOn = [] self.timesOff = [] @property def numLooks(self): """How many times has this ROI been looked at""" return len(self.timesOn) @property def isLookedIn(self): """Is this ROI currently being looked at""" try: # Get current device position if hasattr(self.device, "getPos"): pos = self.device.getPos() elif hasattr(self.device, "pos"): pos = self.device.pos else: raise AttributeError(f"ROI device ({self.device}) does not have any method for getting position.") if not isinstance(pos, (list, tuple, np.ndarray)): # If there's no valid device position, assume False return False # Check contains return bool(self.contains(pos[0], pos[1], self.win.units)) except Exception: # If there's an exception getting device position, # assume False return False return False @property def currentLookTime(self): if self.isLookedIn and self.timesOn and self.timesOff: # If looked at, subtract most recent time from last time on return self.timesOff[-1] - self.timesOn[-1] else: # If not looked at, look time is 0 return 0 @property def lastLookTime(self): if self.timesOn and self.timesOff and not self.isLookedIn: # If not looked at, subtract most recent time from last time on return self.timesOff[-1] - self.timesOn[-1] elif len(self.timesOn) > 1 and len(self.timesOff) > 1: # If looked at, return previous look time return self.timesOff[-2] - self.timesOn[-2] else: # Otherwise, assume 0 return 0 def reset(self): """Clear stored data""" self.timesOn = [] self.timesOff = [] self.clock.reset() self.wasLookedIn = False def draw(self, win=None, keepMatrix=False): if self.debug: # Only draw if in debug mode ShapeStim.draw(self, win=win, keepMatrix=keepMatrix)
5,865
Python
.py
129
35.72093
114
0.628581
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,755
radial.py
psychopy_psychopy/psychopy/visual/radial.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). """Stimulus class for drawing radial stimuli. These are optional components that can be obtained by installing the `psychopy-visionscience` extension into the current environment. """ from psychopy.tools.pkgtools import PluginStub # Ensure setting pyglet.options['debug_gl'] to False is done prior to any # other calls to pyglet or pyglet submodules, otherwise it may not get picked # up by the pyglet GL engine and have no effect. # Shaders will work but require OpenGL2.0 drivers AND PyOpenGL3.0+ class RadialStim( PluginStub, plugin="psychopy-visionscience", doclink="https://psychopy.github.io/psychopy-visionscience/coder/RadialStim/" ): pass class RadialStim: """ `psychopy.visual.RadialStim` is now located within the `psychopy-visionscience` plugin. You can find the documentation for it `here <https://psychopy.github.io/psychopy-visionscience/coder/RadialStim>`_ """ if __name__ == "__main__": pass
1,189
Python
.py
27
41.111111
114
0.762653
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,756
helpers.py
psychopy_psychopy/psychopy/visual/helpers.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Helper functions shared by the visual classes """ # 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 copy from packaging.version import Version from pathlib import Path from psychopy import logging, colors, prefs # tools must only be imported *after* event or MovieStim breaks on win32 # (JWP has no idea why!) from psychopy.alerts import alert from psychopy.tools import filetools as ft from psychopy.tools.arraytools import val2array from psychopy.tools.attributetools import setAttribute from psychopy.tools.filetools import pathToString import numpy as np reportNImageResizes = 5 # stop raising warning after this # global _nImageResizes _nImageResizes = 0 try: import matplotlib if Version(matplotlib.__version__) > Version('1.2'): from matplotlib.path import Path as mplPath else: from matplotlib import nxutils haveMatplotlib = True except Exception: haveMatplotlib = False def pointInPolygon(x, y, poly): """Determine if a point is inside a polygon; returns True if inside. (`x`, `y`) is the point to test. `poly` is a list of 3 or more vertices as (x,y) pairs. If given an object, such as a `ShapeStim`, will try to use its vertices and position as the polygon. Same as the `.contains()` method elsewhere. """ try: # do this using try:...except rather than hasattr() for speed poly = poly.verticesPix # we want to access this only once except Exception: pass nVert = len(poly) if nVert < 3: msg = 'pointInPolygon expects a polygon with 3 or more vertices' logging.warning(msg) return False # faster if have matplotlib tools: if haveMatplotlib: if Version(matplotlib.__version__) > Version('1.2'): return mplPath(poly).contains_point([x, y]) else: try: return bool(nxutils.pnpoly(x, y, poly)) except Exception: pass # fall through to pure python: # adapted from http://local.wasp.uwa.edu.au/~pbourke/geometry/insidepoly/ # via http://www.ariel.com.au/a/python-point-int-poly.html inside = False # trace (horizontal?) rays, flip inside status if cross an edge: p1x, p1y = poly[-1] for p2x, p2y in poly: if y > min(p1y, p2y) and y <= max(p1y, p2y) and x <= max(p1x, p2x): if p1y != p2y: xints = (y - p1y) * (p2x - p1x) / (p2y - p1y) + p1x if p1x == p2x or x <= xints: inside = not inside p1x, p1y = p2x, p2y return inside def polygonsOverlap(poly1, poly2): """Determine if two polygons intersect; can fail for very pointy polygons. Accepts two polygons, as lists of vertices (x,y) pairs. If given an object with with (vertices + pos), will try to use that as the polygon. Checks if any vertex of one polygon is inside the other polygon. Same as the `.overlaps()` method elsewhere. :Notes: We implement special handling for the `Line` stimulus as it is not a proper polygon. We do not check for class instances because this would require importing of `visual.Line`, creating a circular import. Instead, we assume that a "polygon" with only two vertices is meant to specify a line. Pixels between the endpoints get interpolated before testing for overlap. """ try: # do this using try:...except rather than hasattr() for speed if poly1.verticesPix.shape == (2, 2): # Line # Interpolate pixels. x = np.arange(poly1.verticesPix[0, 0], poly1.verticesPix[1, 0] + 1) y = np.arange(poly1.verticesPix[0, 1], poly1.verticesPix[1, 1] + 1) poly1_vert_pix = np.column_stack((x,y)) else: poly1_vert_pix = poly1.verticesPix except AttributeError: poly1_vert_pix = poly1 try: # do this using try:...except rather than hasattr() for speed if poly2.verticesPix.shape == (2, 2): # Line # Interpolate pixels. x = np.arange(poly2.verticesPix[0, 0], poly2.verticesPix[1, 0] + 1) y = np.arange(poly2.verticesPix[0, 1], poly2.verticesPix[1, 1] + 1) poly2_vert_pix = np.column_stack((x,y)) else: poly2_vert_pix = poly2.verticesPix except AttributeError: poly2_vert_pix = poly2 # faster if have matplotlib tools: if haveMatplotlib: if Version(matplotlib.__version__) > Version('1.2'): if any(mplPath(poly1_vert_pix).contains_points(poly2_vert_pix)): return True return any(mplPath(poly2_vert_pix).contains_points(poly1_vert_pix)) else: try: # deprecated in matplotlib 1.2 if any(nxutils.points_inside_poly(poly1_vert_pix, poly2_vert_pix)): return True return any(nxutils.points_inside_poly(poly2_vert_pix, poly1_vert_pix)) except Exception: pass # fall through to pure python: for p1 in poly1_vert_pix: if pointInPolygon(p1[0], p1[1], poly2_vert_pix): return True for p2 in poly2_vert_pix: if pointInPolygon(p2[0], p2[1], poly1_vert_pix): return True return False def setTexIfNoShaders(obj): """Useful decorator for classes that need to update Texture after other properties. This doesn't actually perform the update, but sets a flag so the update occurs at draw time (in case multiple changes all need updates only do it once). """ if hasattr(obj, 'useShaders') and not obj.useShaders: # we aren't using shaders if hasattr(obj, '_needTextureUpdate'): obj._needTextureUpdate = True def setColor(obj, color, colorSpace=None, operation='', colorAttrib='color', # or 'fillColor' etc # legacy colorSpaceAttrib=None, rgbAttrib=None, log=True): """ Sets the given color attribute of an object. Obsolete as of 2021.1.0, as colors are now handled by Color objects, all of the necessary operations are called when setting directly via obj.color, obj.fillColor or obj.borderColor. obj : psychopy.visual object The object whose color you are changing color : color The color to use - can be a valid color value (e.g. (1,1,1), '#ffffff', 'white') or a psychopy.colors.Color object colorSpace : str The color space of the color value. Can be None for hex or named colors, otherwise must be specified. operation : str Can be '=', '+' or '-', or left blank for '='. '=' will set the color, '+' will add the color and '-' will subtract it. colorAttrib : str Name of the color attribute you are setting, e.g. 'color', 'fillColor', 'borderColor' log : bool Whether to write an update to the log about this change Legacy --- colorSpaceAttrib : str PsychoPy used to have a color space for each attribute, but color spaces are now handled by Color objects, so this input is no longer used. rgbAttrib : str PsychoPy used to handle color by converting to RGB and storing in an rgb attribute, now this conversion is done within Color objects so this input is no longer used. """ if colorSpaceAttrib is not None: alert(8105, strFields={'colorSpaceAttrib': colorSpaceAttrib}) if rgbAttrib is not None: alert(8110, strFields={'rgbAttrib': rgbAttrib}) # Make a Color object using supplied values raw = color color = colors.Color(raw, colorSpace) assert color.valid, f"Could not create valid Color object from value {raw} in space {colorSpace}" # Apply new value if operation in ('=', '', None): # If no operation, just set color from object setAttribute(obj, colorAttrib, color, log=log) elif operation == '+': # If +, add to old color setAttribute(obj, colorAttrib, getattr(obj, "_" + colorAttrib) + color, log=log) elif operation == '-': # If -, subtract from old color setAttribute(obj, colorAttrib, getattr(obj, "_" + colorAttrib) - color, log=log) else: # Any other operation is not supported msg = ('Unsupported value "%s" for operation when ' 'setting %s in %s') vals = (operation, colorAttrib, obj.__class__.__name__) raise ValueError(msg % vals) # set for groupFlipVert: immutables = {int, float, str, tuple, int, bool, np.float32, np.float64} def findImageFile(filename, checkResources=False): """Tests whether the filename is an image file. If not will try some common alternatives (e.g. extensions .jpg .tif...) as well as looking in the `psychopy/app/Resources` folder """ # if user supplied correct path then return quickly filename = pathToString(filename) isfile = os.path.isfile if isfile(filename): return filename # alias default names (so it always points to default.png) if filename in ft.defaultStim: filename = ft.defaultStim[filename] # store original orig = copy.copy(filename) # search for file using additional extensions extensions = ('.jpg', '.png', '.tif', '.bmp', '.gif', '.jpeg', '.tiff') # not supported: 'svg', 'eps' def logCorrected(orig, actual): logging.warn("Requested image {!r} not found but similar filename " "{!r} exists. This will be used instead but changing the " "filename is advised.".format(orig, actual)) # it already has one but maybe it's wrong? Remove it if filename.endswith(extensions): filename = os.path.splitext(orig)[0] if isfile(filename): # had an extension but didn't need one (mac?) logCorrected(orig, filename) return filename # try adding the standard set of extensions for ext in extensions: if isfile(filename+ext): filename += ext logCorrected(orig, filename) return filename # try doing the same in the Resources folder if checkResources: return findImageFile(Path(prefs.paths['assets']) / orig, checkResources=False) def groupFlipVert(flipList, yReflect=0): """Reverses the vertical mirroring of all items in list ``flipList``. Reverses the .flipVert status, vertical (y) positions, and angular rotation (.ori). Flipping preserves the relations among the group's visual elements. The parameter ``yReflect`` is the y-value of an imaginary horizontal line around which to reflect the items; default = 0 (screen center). Typical usage is to call once prior to any display; call again to un-flip. Can be called with a list of all stim to be presented in a given routine. Will flip a) all psychopy.visual.xyzStim that have a setFlipVert method, b) the y values of .vertices, and c) items in n x 2 lists that are mutable (i.e., list, np.array, no tuples): [[x1, y1], [x2, y2], ...] """ if type(flipList) != list: flipList = [flipList] for item in flipList: if type(item) in (list, np.ndarray): if type(item[0]) in (list, np.ndarray) and len(item[0]) == 2: for i in range(len(item)): item[i][1] = 2 * yReflect - item[i][1] else: msg = 'Cannot vert-flip elements in "{}", type={}' raise ValueError(msg.format(item, type(item[0]))) elif type(item) in immutables: raise ValueError('Cannot change immutable item "{}"'.format(item)) if hasattr(item, 'setPos'): item.setPos([1, -1], '*') item.setPos([0, 2 * yReflect], '+') elif hasattr(item, 'pos'): # only if no setPos available item.pos[1] *= -1 item.pos[1] += 2 * yReflect if hasattr(item, 'setFlipVert'): # eg TextStim, custom marker item.setFlipVert(not item.flipVert) elif hasattr(item, 'vertices'): # and lacks a setFlipVert method try: v = item.vertices * [1, -1] # np.array except Exception: v = [[item.vertices[i][0], -1 * item.vertices[i][1]] for i in range(len(item.vertices))] item.setVertices(v) if hasattr(item, 'setOri') and item.ori: # non-zero orientation angle item.setOri(-1, '*') item._needVertexUpdate = True
12,897
Python
.py
283
37.166078
120
0.634721
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,757
ratingscale.py
psychopy_psychopy/psychopy/visual/ratingscale.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """A class for getting numeric or categorical ratings, e.g., a 1-to-7 scale.""" # 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.tools.pkgtools import PluginStub class RatingScale( PluginStub, plugin="psychopy-legacy", doclink="https://psychopy.github.io/psychopy-legacy/coder/visual/RatingScale" ): pass
518
Python
.py
13
37.307692
81
0.746507
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,758
grating.py
psychopy_psychopy/psychopy/visual/grating.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Stimulus object for drawing arbitrary bitmaps that can repeat (cycle) in either dimension. One of the main stimuli for PsychoPy. """ # 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). # Ensure setting pyglet.options['debug_gl'] to False is done prior to any # other calls to pyglet or pyglet submodules, otherwise it may not get picked # up by the pyglet GL engine and have no effect. # Shaders will work but require OpenGL2.0 drivers AND PyOpenGL3.0+ import pyglet from psychopy.colors import Color pyglet.options['debug_gl'] = False import ctypes GL = pyglet.gl import psychopy # so we can get the __path__ from psychopy import logging from psychopy.tools.arraytools import val2array from psychopy.tools.attributetools import attributeSetter from psychopy.visual.basevisual import ( BaseVisualStim, DraggingMixin, ColorMixin, ContainerMixin, TextureMixin ) import numpy class GratingStim(BaseVisualStim, DraggingMixin, TextureMixin, ColorMixin, ContainerMixin): """Stimulus object for drawing arbitrary bitmaps that can repeat (cycle) in either dimension. This is a lazy-imported class, therefore import using full path `from psychopy.visual.grating import GratingStim` when inheriting from it. One of the main stimuli for PsychoPy. Formally `GratingStim` is just a texture behind an optional transparency mask (an 'alpha mask'). Both the texture and mask can be arbitrary bitmaps and their combination allows an enormous variety of stimuli to be drawn in realtime. A `GratingStim` can be rotated scaled and shifted in position, its texture can be drifted in X and/or Y and it can have a spatial frequency in X and/or Y (for an image file that simply draws multiple copies in the patch). Also since transparency can be controlled, two `GratingStim` objects can be combined (e.g. to form a plaid.) **Using GratingStim with images from disk (jpg, tif, png, ...)** Ideally texture images to be rendered should be square with 'power-of-2' dimensions e.g. 16 x 16, 128 x 128. Any image that is not will be up-scaled (with linear interpolation) to the nearest such texture by PsychoPy. The size of the stimulus should be specified in the normal way using the appropriate units (deg, pix, cm, ...). Be sure to get the aspect ratio the same as the image (if you don't want it stretched!). Parameters ---------- win : :class:`~psychopy.visual.Window` Window this shape is being drawn to. The stimulus instance will allocate its required resources using that Windows context. In many cases, a stimulus instance cannot be drawn on different windows unless those windows share the same OpenGL context, which permits resources to be shared between them. tex : str or None Texture to use for the primary carrier. Values may be one of `'sin'`, `'sin'`, `'sqr'`, `'saw'`, `'tri'`, or `None`. mask : str or None Optional mask to control the shape of the grating. Values may be one of `'circle'`, `'sin'`, `'sqr'`, `'saw'`, `'tri'`, or `None`. units : str Units to use when drawing. This will affect how parameters and attributes `pos`, `size` and `radius` are interpreted. anchor : str Anchor string to specify the origin of the stimulus. pos : array_like Initial position (`x`, `y`) of the shape on-screen relative to the origin located at the center of the window or buffer in `units`. This can be updated after initialization by setting the `pos` property. The default value is `(0.0, 0.0)` which results in no translation. size : array_like, float, int or None Width and height of the shape as `(w, h)` or `[w, h]`. If a single value is provided, the width and height will be set to the same specified value. If `None` is specified, the `size` will be set with values passed to `width` and `height`. sf : float Spatial frequency for the grating. Values are dependent on the units in use to draw the stimuli. ori : float Initial orientation of the shape in degrees about its origin. Positive values will rotate the shape clockwise, while negative values will rotate counterclockwise. The default value for `ori` is 0.0 degrees. phase : ArrayLike Initial phase of the grating along the vertical and horizontal dimension `(x, y)`. texRes : int Resolution of the texture. The higher the resolutions, the less aliasing artifacts will be visible. However, this comes at the expense of higher video memory use. Power-of-two values are recommended (e.g. 256, 512, 1024, etc.) color : array_like, str, :class:`~psychopy.colors.Color` or None Sets both the initial `lineColor` and `fillColor` of the shape. colorSpace : str Sets the colorspace, changing how values passed to `lineColor` and `fillColor` are interpreted. contrast : float Contrast level of the shape (0.0 to 1.0). This value is used to modulate the contrast of colors passed to `lineColor` and `fillColor`. opacity : float Opacity of the shape. A value of 1.0 indicates fully opaque and 0.0 is fully transparent (therefore invisible). Values between 1.0 and 0.0 will result in colors being blended with objects in the background. This value affects the fill (`fillColor`) and outline (`lineColor`) colors of the shape. depth : int Depth layer to draw the shape when `autoDraw` is enabled. *DEPRECATED* rgbPedestal : ArrayLike Pedestal color `(r, g, b)`, presently unused. interpolate : bool Enable smoothing (anti-aliasing) when drawing shape outlines. This produces a smoother (less-pixelated) outline of the shape. draggable : bool Can this stimulus be dragged by a mouse click? lineRGB, fillRGB: ArrayLike, :class:`~psychopy.colors.Color` or None *Deprecated*. Please use `lineColor` and `fillColor`. These arguments may be removed in a future version. name : str Optional name of the stimuli for logging. autoLog : bool Enable auto-logging of events associated with this stimuli. Useful for debugging and to track timing when used in conjunction with `autoDraw`. autoDraw : bool Enable auto drawing. When `True`, the stimulus will be drawn every frame without the need to explicitly call the :py:meth:`~psychopy.visual.shape.ShapeStim.draw()` method. Examples -------- Creating a circular grating with a sinusoidal pattern:: myGrat = GratingStim(tex='sin', mask='circle') Create a 'Gabor':: myGabor = GratingStim(tex='sin', mask='gauss') """ def __init__(self, win, tex="sin", mask="none", units=None, anchor="center", pos=(0.0, 0.0), size=None, sf=None, ori=0.0, phase=(0.0, 0.0), texRes=128, rgb=None, dkl=None, lms=None, color=(1.0, 1.0, 1.0), colorSpace='rgb', contrast=1.0, opacity=None, depth=0, rgbPedestal=(0.0, 0.0, 0.0), interpolate=False, draggable=False, blendmode='avg', name=None, autoLog=None, autoDraw=False, maskParams=None): """ """ # Empty docstring. All doc is in attributes # what local vars are defined (these are the init params) for use by # __repr__ self._initParams = dir() for unecess in ['self', 'rgb', 'dkl', 'lms']: self._initParams.remove(unecess) # initialise parent class super(GratingStim, self).__init__(win, units=units, name=name, autoLog=False) self.draggable = draggable # UGLY HACK: Some parameters depend on each other for processing. # They are set "superficially" here. # TO DO: postpone calls to _createTexture, setColor and # _calcCyclesPerStim whin initiating stimulus self.__dict__['contrast'] = 1 self.__dict__['size'] = 1 self.__dict__['sf'] = 1 self.__dict__['tex'] = tex self.__dict__['maskParams'] = maskParams # initialise textures and masks for stimulus self._texID = GL.GLuint() GL.glGenTextures(1, ctypes.byref(self._texID)) self._maskID = GL.GLuint() GL.glGenTextures(1, ctypes.byref(self._maskID)) self.__dict__['texRes'] = texRes # must be power of 2 self.interpolate = interpolate self._needTextureUpdate = True # NB Pedestal isn't currently being used during rendering - this is a # place-holder self.rgbPedestal = val2array(rgbPedestal, False, length=3) # No need to invoke decorator for color updating. It is done just # below. self.colorSpace = colorSpace self.color = color if rgb is not None: logging.warning("Use of rgb arguments to stimuli are deprecated." " Please use color and colorSpace args instead") self.color = Color(rgb, 'rgb') elif dkl is not None: logging.warning("Use of dkl arguments to stimuli are deprecated." " Please use color and colorSpace args instead") self.color = Color(dkl, 'dkl') elif lms is not None: logging.warning("Use of lms arguments to stimuli are deprecated." " Please use color and colorSpace args instead") self.color = Color(lms, 'lms') # set other parameters self.ori = float(ori) self.phase = val2array(phase, False) self._origSize = None # updated if an image texture is loaded self._requestedSize = size self.size = size self.sf = val2array(sf) self.pos = val2array(pos, False, False) self.depth = depth self.anchor = anchor # self.tex = tex self.mask = mask self.contrast = float(contrast) self.opacity = opacity self.autoLog = autoLog self.autoDraw = autoDraw self.blendmode = blendmode # fix scaling to window coords self._calcCyclesPerStim() # generate a displaylist ID self._listID = GL.glGenLists(1) # JRG: doing self._updateList() here means MRO issues for RadialStim, # which inherits from GratingStim but has its own _updateList code. # So don't want to do the update here (= ALSO the init of RadialStim). # Could potentially define a BaseGrating class without # updateListShaders code, and have GratingStim and RadialStim # inherit from it and add their own _updateList stuff. # Seems unnecessary. Instead, simply defer the update to the # first .draw(), should be fast: # self._updateList() # ie refresh display list self._needUpdate = True # set autoLog now that params have been initialised wantLog = autoLog is None and self.win.autoLog self.__dict__['autoLog'] = autoLog or wantLog if self.autoLog: logging.exp("Created {} = {}".format(self.name, self)) @attributeSetter def sf(self, value): """Spatial frequency of the grating texture. Should be a :ref:`x,y-pair <attrib-xy>` or :ref:`scalar <attrib-scalar>` or None. If `units` == 'deg' or 'cm' units are in cycles per deg or cm as appropriate. If `units` == 'norm' then sf units are in cycles per stimulus (and so SF scales with stimulus size). If texture is an image loaded from a file then sf=None defaults to 1/stimSize to give one cycle of the image. """ # Recode phase to numpy array if value is None: # Set the sf to default (e.g. to the 1.0/size of the loaded image if (self.units in ('pix', 'pixels') or self._origSize is not None and self.units in ('deg', 'cm')): value = 1.0 / self.size # default to one cycle else: value = numpy.array([1.0, 1.0]) else: value = val2array(value) # Set value and update stuff self.__dict__['sf'] = value self._calcCyclesPerStim() self._needUpdate = True @attributeSetter def phase(self, value): """Phase of the stimulus in each dimension of the texture. Should be an :ref:`x,y-pair <attrib-xy>` or :ref:`scalar <attrib-scalar>` **NB** phase has modulus 1 (rather than 360 or 2*pi) This is a little unconventional but has the nice effect that setting phase=t*n drifts a stimulus at *n* Hz. """ # Recode phase to numpy array value = val2array(value) self.__dict__['phase'] = value self._needUpdate = True @attributeSetter def tex(self, value): """Texture to used on the stimulus as a grating (aka carrier). This can be one of various options: + **'sin'**,'sqr', 'saw', 'tri', None (resets to default) + the name of an image file (most formats supported) + a numpy array (1xN or NxN) ranging -1:1 If specifying your own texture using an image or numpy array you should ensure that the image has square power-of-two dimensions (e.g. 256 x 256). If not then PsychoPy will up-sample your stimulus to the next larger power of two. """ self._createTexture( value, id=self._texID, pixFormat=GL.GL_RGB, stim=self, res=self.texRes, maskParams=self.maskParams) self.__dict__['tex'] = value self._needTextureUpdate = False @attributeSetter def blendmode(self, value): """The OpenGL mode in which the stimulus is draw Can the 'avg' or 'add'. Average (avg) places the new stimulus over the old one with a transparency given by its opacity. Opaque stimuli will hide other stimuli transparent stimuli won't. Add performs the arithmetic sum of the new stimulus and the ones already present. """ self.__dict__['blendmode'] = value self._needUpdate = True def setSF(self, value, operation='', log=None): """DEPRECATED. Use 'stim.parameter = value' syntax instead """ self._set('sf', value, operation, log=log) def setPhase(self, value, operation='', log=None): """DEPRECATED. Use 'stim.parameter = value' syntax instead """ self._set('phase', value, operation, log=log) def setTex(self, value, log=None): """DEPRECATED. Use 'stim.parameter = value' syntax instead """ self.tex = value def setBlendmode(self, value, log=None): """DEPRECATED. Use 'stim.parameter = value' syntax instead """ self._set('blendmode', value, log=log) def draw(self, win=None): """Draw the stimulus in its relevant window. You must call this method after every `MyWin.flip()` if you want the stimulus to appear on that frame and then update the screen again. Parameters ---------- win : `~psychopy.visual.Window` or `None` Window to draw the stimulus to. Context sharing must be enabled if any other window beside the one specified during creation of this stimulus is specified. """ if win is None: win = self.win self._selectWindow(win) saveBlendMode = win.blendMode win.setBlendMode(self.blendmode, log=False) # do scaling GL.glPushMatrix() # push before the list, pop after win.setScale('pix') # the list just does the texture mapping GL.glColor4f(*self._foreColor.render('rgba1')) if self._needTextureUpdate: self.setTex(value=self.tex, log=False) if self._needUpdate: self._updateList() GL.glCallList(self._listID) # return the view to previous state GL.glPopMatrix() win.setBlendMode(saveBlendMode, log=False) def _updateListShaders(self): """The user shouldn't need this method since it gets called after every call to .set() Basically it updates the OpenGL representation of your stimulus if some parameter of the stimulus changes. Call it if you change a property manually rather than using the .set() command """ self._needUpdate = False GL.glNewList(self._listID, GL.GL_COMPILE) # setup the shaderprogram _prog = self.win._progSignedTexMask GL.glUseProgram(_prog) # set the texture to be texture unit 0 GL.glUniform1i(GL.glGetUniformLocation(_prog, b"texture"), 0) # mask is texture unit 1 GL.glUniform1i(GL.glGetUniformLocation(_prog, b"mask"), 1) # mask GL.glActiveTexture(GL.GL_TEXTURE1) GL.glBindTexture(GL.GL_TEXTURE_2D, self._maskID) GL.glEnable(GL.GL_TEXTURE_2D) # implicitly disables 1D # main texture GL.glActiveTexture(GL.GL_TEXTURE0) GL.glBindTexture(GL.GL_TEXTURE_2D, self._texID) GL.glEnable(GL.GL_TEXTURE_2D) Ltex = (-self._cycles[0] / 2) - self.phase[0] + 0.5 Rtex = (+self._cycles[0] / 2) - self.phase[0] + 0.5 Ttex = (+self._cycles[1] / 2) - self.phase[1] + 0.5 Btex = (-self._cycles[1] / 2) - self.phase[1] + 0.5 Lmask = Bmask = 0.0 Tmask = Rmask = 1.0 # mask # access just once because it's slower than basic property vertsPix = self.verticesPix GL.glBegin(GL.GL_QUADS) # draw a 4 sided polygon # right bottom GL.glMultiTexCoord2f(GL.GL_TEXTURE0, Rtex, Btex) GL.glMultiTexCoord2f(GL.GL_TEXTURE1, Rmask, Bmask) GL.glVertex2f(vertsPix[0, 0], vertsPix[0, 1]) # left bottom GL.glMultiTexCoord2f(GL.GL_TEXTURE0, Ltex, Btex) GL.glMultiTexCoord2f(GL.GL_TEXTURE1, Lmask, Bmask) GL.glVertex2f(vertsPix[1, 0], vertsPix[1, 1]) # left top GL.glMultiTexCoord2f(GL.GL_TEXTURE0, Ltex, Ttex) GL.glMultiTexCoord2f(GL.GL_TEXTURE1, Lmask, Tmask) GL.glVertex2f(vertsPix[2, 0], vertsPix[2, 1]) # right top GL.glMultiTexCoord2f(GL.GL_TEXTURE0, Rtex, Ttex) GL.glMultiTexCoord2f(GL.GL_TEXTURE1, Rmask, Tmask) GL.glVertex2f(vertsPix[3, 0], vertsPix[3, 1]) GL.glEnd() # unbind the textures GL.glActiveTexture(GL.GL_TEXTURE1) GL.glBindTexture(GL.GL_TEXTURE_2D, 0) GL.glDisable(GL.GL_TEXTURE_2D) # implicitly disables 1D # main texture GL.glActiveTexture(GL.GL_TEXTURE0) GL.glBindTexture(GL.GL_TEXTURE_2D, 0) GL.glDisable(GL.GL_TEXTURE_2D) GL.glUseProgram(0) GL.glEndList() def __del__(self): try: GL.glDeleteLists(self._listID, 1) except Exception: pass # probably we don't have a _listID property try: # remove textures from graphics card to prevent crash self.clearTextures() except Exception: pass def _calcCyclesPerStim(self): if self.units in ('norm', 'height'): # this is the only form of sf that is not size dependent self._cycles = self.sf else: self._cycles = self.sf * self.size
20,198
Python
.py
434
37.264977
80
0.630248
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,759
movie3.py
psychopy_psychopy/psychopy/visual/movie3.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.tools.pkgtools import PluginStub class MovieStim3( PluginStub, plugin="psychopy-legacy", doclink="https://psychopy.github.io/psychopy-legacy/coder/visual/MovieStim3" ): pass
436
Python
.py
12
33.666667
80
0.754762
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,760
image.py
psychopy_psychopy/psychopy/visual/image.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Display an image on `psycopy.visual.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). # Ensure setting pyglet.options['debug_gl'] to False is done prior to any # other calls to pyglet or pyglet submodules, otherwise it may not get picked # up by the pyglet GL engine and have no effect. # Shaders will work but require OpenGL2.0 drivers AND PyOpenGL3.0+ import pyglet from psychopy.layout import Size pyglet.options['debug_gl'] = False import ctypes GL = pyglet.gl import numpy from fractions import Fraction import psychopy # so we can get the __path__ from psychopy import logging, colors, layout from psychopy.tools.attributetools import attributeSetter, setAttribute from psychopy.visual.basevisual import ( BaseVisualStim, DraggingMixin, ContainerMixin, ColorMixin, TextureMixin ) class ImageStim(BaseVisualStim, DraggingMixin, ContainerMixin, ColorMixin, TextureMixin): """Display an image on a :class:`psychopy.visual.Window` """ def __init__(self, win, image=None, mask=None, units="", pos=(0.0, 0.0), size=None, anchor="center", ori=0.0, color=(1.0, 1.0, 1.0), colorSpace='rgb', contrast=1.0, opacity=None, depth=0, interpolate=False, draggable=False, flipHoriz=False, flipVert=False, texRes=128, name=None, autoLog=None, maskParams=None): """ """ # Empty docstring. All doc is in attributes # what local vars are defined (these are the init params) for use by # __repr__ self._initParams = dir() self._initParams.remove('self') super(ImageStim, self).__init__(win, units=units, name=name, autoLog=False) # set at end of init self.draggable = draggable # use shaders if available by default, this is a good thing self.__dict__['useShaders'] = win._haveShaders # initialise textures for stimulus self._texID = GL.GLuint() GL.glGenTextures(1, ctypes.byref(self._texID)) self._maskID = GL.GLuint() GL.glGenTextures(1, ctypes.byref(self._maskID)) self._pixbuffID = GL.GLuint() GL.glGenBuffers(1, ctypes.byref(self._pixbuffID)) self.__dict__['maskParams'] = maskParams self.__dict__['mask'] = mask # Not pretty (redefined later) but it works! self.__dict__['texRes'] = texRes # Other stuff self._imName = image self.isLumImage = None self.interpolate = interpolate self.vertices = None self.anchor = anchor self.flipHoriz = flipHoriz self.flipVert = flipVert self._requestedSize = size self._origSize = None # updated if an image texture gets loaded self.size = size self.pos = numpy.array(pos, float) self.ori = float(ori) self.depth = depth # color and contrast etc self.rgbPedestal = [0, 0, 0] # does an rgb pedestal make sense for an image? self.colorSpace = colorSpace # omit decorator self.color = color self.contrast = float(contrast) self.opacity = opacity # Set the image and mask- self.setImage(image, log=False) self.texRes = texRes # rebuilds the mask self.size = size # generate a displaylist ID self._listID = GL.glGenLists(1) self._updateList() # ie refresh display list # set autoLog now that params have been initialised wantLog = autoLog is None and self.win.autoLog self.__dict__['autoLog'] = autoLog or wantLog if self.autoLog: logging.exp("Created %s = %s" % (self.name, str(self))) def _updateListShaders(self): """ The user shouldn't need this method since it gets called after every call to .set() Basically it updates the OpenGL representation of your stimulus if some parameter of the stimulus changes. Call it if you change a property manually rather than using the .set() command """ self._needUpdate = False GL.glNewList(self._listID, GL.GL_COMPILE) # setup the shaderprogram if self.isLumImage: # for a luminance image do recoloring _prog = self.win._progSignedTexMask GL.glUseProgram(_prog) # set the texture to be texture unit 0 GL.glUniform1i(GL.glGetUniformLocation(_prog, b"texture"), 0) # mask is texture unit 1 GL.glUniform1i(GL.glGetUniformLocation(_prog, b"mask"), 1) else: # for an rgb image there is no recoloring _prog = self.win._progImageStim GL.glUseProgram(_prog) # set the texture to be texture unit 0 GL.glUniform1i(GL.glGetUniformLocation(_prog, b"texture"), 0) # mask is texture unit 1 GL.glUniform1i(GL.glGetUniformLocation(_prog, b"mask"), 1) # mask GL.glActiveTexture(GL.GL_TEXTURE1) GL.glBindTexture(GL.GL_TEXTURE_2D, self._maskID) GL.glEnable(GL.GL_TEXTURE_2D) # implicitly disables 1D # main texture GL.glActiveTexture(GL.GL_TEXTURE0) GL.glBindTexture(GL.GL_TEXTURE_2D, self._texID) GL.glEnable(GL.GL_TEXTURE_2D) # access just once because it's slower than basic property vertsPix = self.verticesPix GL.glBegin(GL.GL_QUADS) # draw a 4 sided polygon # right bottom GL.glMultiTexCoord2f(GL.GL_TEXTURE0, 1, 0) GL.glMultiTexCoord2f(GL.GL_TEXTURE1, 1, 0) GL.glVertex2f(vertsPix[0, 0], vertsPix[0, 1]) # left bottom GL.glMultiTexCoord2f(GL.GL_TEXTURE0, 0, 0) GL.glMultiTexCoord2f(GL.GL_TEXTURE1, 0, 0) GL.glVertex2f(vertsPix[1, 0], vertsPix[1, 1]) # left top GL.glMultiTexCoord2f(GL.GL_TEXTURE0, 0, 1) GL.glMultiTexCoord2f(GL.GL_TEXTURE1, 0, 1) GL.glVertex2f(vertsPix[2, 0], vertsPix[2, 1]) # right top GL.glMultiTexCoord2f(GL.GL_TEXTURE0, 1, 1) GL.glMultiTexCoord2f(GL.GL_TEXTURE1, 1, 1) GL.glVertex2f(vertsPix[3, 0], vertsPix[3, 1]) GL.glEnd() # unbind the textures GL.glActiveTexture(GL.GL_TEXTURE1) GL.glBindTexture(GL.GL_TEXTURE_2D, 0) GL.glDisable(GL.GL_TEXTURE_2D) # implicitly disables 1D # main texture GL.glActiveTexture(GL.GL_TEXTURE0) GL.glBindTexture(GL.GL_TEXTURE_2D, 0) GL.glDisable(GL.GL_TEXTURE_2D) GL.glUseProgram(0) GL.glEndList() def __del__(self): """Remove textures from graphics card to prevent crash """ try: if hasattr(self, '_listID'): GL.glDeleteLists(self._listID, 1) self.clearTextures() except (ImportError, ModuleNotFoundError, TypeError): pass # has probably been garbage-collected already def draw(self, win=None): """Draw. """ # check the type of image we're dealing with if (type(self.image) != numpy.ndarray and self.image in (None, "None", "none")): return # make the context for the window current if win is None: win = self.win self._selectWindow(win) # If our image is a movie stim object, pull pixel data from the most # recent frame and write it to the memory if hasattr(self.image, 'getVideoFrame'): videoFrame = self.image.getVideoFrame() if videoFrame is not None: self._movieFrameToTexture(videoFrame) GL.glPushMatrix() # push before the list, pop after win.setScale('pix') GL.glColor4f(*self._foreColor.render('rgba1')) if self._needTextureUpdate: self.setImage(value=self._imName, log=False) if self._needUpdate: self._updateList() GL.glCallList(self._listID) # return the view to previous state GL.glPopMatrix() def _movieFrameToTexture(self, movieSrc): """Convert a movie frame to a texture and use it. This method is used internally to copy pixel data from a camera object into a texture. This enables the `ImageStim` to be used as a 'viewfinder' of sorts for the camera to view a live video stream on a window. Parameters ---------- movieSrc : `~psychopy.hardware.camera.Camera` Movie source object. """ # get the most recent video frame and extract color data colorData = movieSrc.colorData # get the size of the movie frame and compute the buffer size vidWidth, vidHeight = movieSrc.size nBufferBytes = vidWidth * vidHeight * 3 # bind pixel unpack buffer GL.glBindBuffer(GL.GL_PIXEL_UNPACK_BUFFER, self._pixbuffID) # Free last storage buffer before mapping and writing new frame # data. This allows the GPU to process the extant buffer in VRAM # uploaded last cycle without being stalled by the CPU accessing it. GL.glBufferData( GL.GL_PIXEL_UNPACK_BUFFER, nBufferBytes * ctypes.sizeof(GL.GLubyte), None, GL.GL_STREAM_DRAW) # Map the buffer to client memory, `GL_WRITE_ONLY` to tell the # driver to optimize for a one-way write operation if it can. bufferPtr = GL.glMapBuffer( GL.GL_PIXEL_UNPACK_BUFFER, GL.GL_WRITE_ONLY) bufferArray = numpy.ctypeslib.as_array( ctypes.cast(bufferPtr, ctypes.POINTER(GL.GLubyte)), shape=(nBufferBytes,)) # copy data bufferArray[:] = colorData[:] # Very important that we unmap the buffer data after copying, but # keep the buffer bound for setting the texture. GL.glUnmapBuffer(GL.GL_PIXEL_UNPACK_BUFFER) # bind the texture in OpenGL GL.glEnable(GL.GL_TEXTURE_2D) GL.glActiveTexture(GL.GL_TEXTURE0) GL.glBindTexture(GL.GL_TEXTURE_2D, self._texID) # copy the PBO to the texture GL.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, 1) GL.glTexSubImage2D( GL.GL_TEXTURE_2D, 0, 0, 0, vidWidth, vidHeight, GL.GL_RGB, GL.GL_UNSIGNED_BYTE, 0) # point to the presently bound buffer # update texture filtering only if needed if self.interpolate: texFilter = GL.GL_LINEAR else: texFilter = GL.GL_NEAREST GL.glTexParameteri( GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, texFilter) GL.glTexParameteri( GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, texFilter) # important to unbind the PBO GL.glBindBuffer(GL.GL_PIXEL_UNPACK_BUFFER, 0) GL.glBindTexture(GL.GL_TEXTURE_2D, 0) GL.glDisable(GL.GL_TEXTURE_2D) @attributeSetter def image(self, value): """The image file to be presented (most formats supported). This can be a path-like object to an image file, or a numpy array of shape [H, W, C] where C are channels. The third dim will usually have length 1 (defining an intensity-only image), 3 (defining an RGB image) or 4 (defining an RGBA image). If passing a numpy array to the image attribute, the size attribute of ImageStim must be set explicitly. """ self.__dict__['image'] = self._imName = value # If given a color array, get it in rgb1 if isinstance(value, colors.Color): value = value.render('rgb1') wasLumImage = self.isLumImage if type(value) != numpy.ndarray and value == "color": datatype = GL.GL_FLOAT else: datatype = GL.GL_UNSIGNED_BYTE if type(value) != numpy.ndarray and value in (None, "None", "none"): self.isLumImage = True else: self.isLumImage = self._createTexture( value, id=self._texID, stim=self, pixFormat=GL.GL_RGB, dataType=datatype, maskParams=self.maskParams, forcePOW2=False, wrapping=False) # update size self.size = self._requestedSize if hasattr(value, 'getVideoFrame'): # make sure we invert vertices self.flipVert = True # if we switched to/from lum image then need to update shader rule if wasLumImage != self.isLumImage: self._needUpdate = True self._needTextureUpdate = False def setImage(self, value, log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message. """ setAttribute(self, 'image', value, log) @property def aspectRatio(self): """ Aspect ratio of original image, before taking into account the `.size` attribute of this object. returns : Aspect ratio as a (w, h) tuple, simplified using the smallest common denominator (e.g. 1080x720 pixels becomes (3, 2)) """ # Return None if we don't have a texture yet if (not hasattr(self, "_origSize")) or self._origSize is None: return # Work out aspect ratio (w/h) frac = Fraction(*self._origSize) return frac.numerator, frac.denominator @property def size(self): return BaseVisualStim.size.fget(self) @size.setter def size(self, value): # store requested size self._requestedSize = value isNone = numpy.asarray(value) == None if (self.aspectRatio is not None) and (isNone.any()) and (not isNone.all()): # If only one value is None, replace it with a value which maintains aspect ratio pix = layout.Size(value, units=self.units, win=self.win).pix # Replace None value with scaled pix value i = isNone.argmax() ni = isNone.argmin() pix[i] = pix[ni] * self.aspectRatio[i] / self.aspectRatio[ni] # Recreate layout object from pix value = layout.Size(pix, units="pix", win=self.win) elif (self.aspectRatio is not None) and (isNone.all()): # If both values are None, use pixel size value = layout.Size(self._origSize, units="pix", win=self.win) # Do base setting BaseVisualStim.size.fset(self, value) @attributeSetter def mask(self, value): """The alpha mask that can be used to control the outer shape of the stimulus + **None**, 'circle', 'gauss', 'raisedCos' + or the name of an image file (most formats supported) + or a numpy array (1xN or NxN) ranging -1:1 """ self.__dict__['mask'] = value self._createTexture(value, id=self._maskID, pixFormat=GL.GL_ALPHA, dataType=GL.GL_UNSIGNED_BYTE, stim=self, res=self.texRes, maskParams=self.maskParams, forcePOW2=False, wrapping=True) def setMask(self, value, log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message. """ setAttribute(self, 'mask', value, log)
16,086
Python
.py
372
32.787634
114
0.603988
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,761
panorama.py
psychopy_psychopy/psychopy/visual/panorama.py
from . import stim3d from . import ImageStim from .. import constants from ..tools import gltools as gt, mathtools as mt, viewtools as vt import numpy as np import pyglet.gl as GL import psychopy.colors as colors from ..tools.attributetools import attributeSetter, setAttribute class PanoramicImageStim(ImageStim): """Map an image to the inside of a sphere and allow view to be changed via latitude and longitude coordinates (between -1 and 1). This is a lazy-imported class, therefore import using full path `from psychopy.visual.panorama import PanoramicImageStim` when inheriting from it. Parameters ---------- win : psychopy.visual.Window The window to draw the stimulus to. image : pathlike File path of image to present as a panorama. Most modern phones have a "panoramic" camera mode, which will output an image with all the correct warping applied. elevation : float (-1 to 1) Initial vertical look position. azimuth : float (-1 to 1) Initial horizontal look position. """ def __init__(self, win, image=None, elevation=None, azimuth=None, depth=0, interpolate=True, autoDraw=False, name=None, autoLog=False): self._initParams = dir() self._initParams.remove('self') super(PanoramicImageStim, self).__init__( win, image=image, units="", interpolate=interpolate, name=name, autoLog=autoLog) # internal object for storing information pose self._thePose = stim3d.RigidBodyPose() # Set starting lat- and long-itude self.elevation = elevation self.azimuth = azimuth # Set starting zoom self.zoom = 0 # Set starting status self.status = constants.NOT_STARTED self.autoDraw = autoDraw self.depth = 0 # Add default attribute for control handler (updated from Builder if used) self.ctrl = None # generate buffers for vertex data vertices, textureCoords, normals, faces = gt.createUVSphere( sectors=128, stacks=256, radius=1.0, flipFaces=True) # faces are on the inside of the sphere # flip verts vertices = np.ascontiguousarray( np.flipud(vertices), dtype=vertices.dtype) # flip texture coords to view upright textureCoords[:, 0] = np.flipud(textureCoords[:, 0]) textureCoords = np.ascontiguousarray( textureCoords, dtype=textureCoords.dtype) # handle to the VAO used to draw the sphere self._vao = None self._createVAO(vertices, textureCoords, normals, faces) # flag if orientation needs an update self._needsOriUpdate = True def _createVAO(self, vertices, textureCoords, normals, faces): """Create a vertex array object for handling vertex attribute data. """ # upload to buffers vertexVBO = gt.createVBO(vertices) texCoordVBO = gt.createVBO(textureCoords) normalsVBO = gt.createVBO(normals) # create an index buffer with faces indexBuffer = gt.createVBO( faces.flatten(), target=GL.GL_ELEMENT_ARRAY_BUFFER, dataType=GL.GL_UNSIGNED_INT) bufferMapping = { GL.GL_VERTEX_ARRAY: vertexVBO, GL.GL_TEXTURE_COORD_ARRAY: texCoordVBO, GL.GL_NORMAL_ARRAY: normalsVBO } self._vao = gt.createVAO( bufferMapping, indexBuffer=indexBuffer, legacy=True) @attributeSetter def azimuth(self, value): """Horizontal view point between -1 (180 degrees to the left) and +1 (180 degrees to the right). Values outside this range will still be accepted (e.g. -1.5 will be 270 degrees to the left). """ if value is None: value = 0 # Store value self.__dict__['azimuth'] = self.__dict__['longitude'] = value # Shift 90deg left so centre of image is azimuth 0 value = value + 0.5 # Get lat and long in degrees value = self._normToDegrees(value) # Calculate ori self.latQuat = mt.quatFromAxisAngle((0, 0, 1), value, degrees=True) self._needsOriUpdate = True @attributeSetter def longitude(self, value): """Alias of `azimuth`. """ self.azimuth = value def setAzimuth(self, value, operation='', log=False): setAttribute(self, "azimuth", value, operation=operation, log=log) def setLongitude(self, value, operation='', log=False): setAttribute(self, "longitude", value, operation=operation, log=log) @attributeSetter def elevation(self, value): """Vertical view point between -1 (directly downwards) and 1 (directly upwards). Values outside this range will be clipped to within range (e.g. -1.5 will be directly downwards). """ if value is None: value = 0 # Store value value = np.clip(value, -1, 1) self.__dict__['elevation'] = self.__dict__['latitude'] = value # Force to positive as we only need 180 degrees of rotation, and flip value = -value value += 1 value /= 2 value = np.clip(value, 0, 1) # Get lat and long in degrees value = self._normToDegrees(value) # Calculate ori self.longQuat = mt.quatFromAxisAngle((1, 0, 0), value, degrees=True) self._needsOriUpdate = True @attributeSetter def latitude(self, value): """Alias of `elevation`. """ self.elevation = value def setElevation(self, value, operation='', log=False): setAttribute(self, "elevation", value, operation=operation, log=log) def setLatitude(self, value, operation='', log=False): setAttribute(self, "latitude", value, operation=operation, log=log) @attributeSetter def zoom(self, value): value = max(value, 0) self.__dict__['zoom'] = value # Modify fov relative to actual view distance (in m) self.fov = value + self.win.monitor.getDistance() / 100 def setZoom(self, value, operation='', log=False): setAttribute(self, "zoom", value, operation=operation, log=log) @attributeSetter def fov(self, value): """Set the field-of-view (FOV). """ if 'fov' in self.__dict__ and value == self.__dict__['fov']: # Don't recalculate if value hasn't changed return self.__dict__['fov'] = value fov = vt.computeFrustumFOV( scrFOV=80, scrAspect=self.win.aspect, scrDist=value ) self._projectionMatrix = vt.perspectiveProjectionMatrix(*fov) def setFov(self, value, operation='', log=False): setAttribute(self, "fov", value, operation=operation, log=log) def draw(self, win=None): # substitute with own win if none given if win is None: win = self.win self._selectWindow(win) # check the type of image we're dealing with if (type(self.image) != np.ndarray and self.image in (None, "None", "none")): return # check if we need to update the texture if self._needTextureUpdate: self.setImage(value=self._imName, log=False) # Calculate ori from latitude and longitude quats if needed if self._needsOriUpdate: self._thePose.ori = mt.multQuat(self.longQuat, self.latQuat) win.viewMatrix = self._thePose.getViewMatrix(inverse=True) # Enter 3d perspective win.projectionMatrix = self._projectionMatrix win.applyEyeTransform() win.useLights = True # setup the shaderprogram if self.isLumImage: # for a luminance image do recoloring _prog = self.win._progSignedTexMask GL.glUseProgram(_prog) # set the texture to be texture unit 0 GL.glUniform1i(GL.glGetUniformLocation(_prog, b"texture"), 0) # mask is texture unit 1 GL.glUniform1i(GL.glGetUniformLocation(_prog, b"mask"), 1) else: # for an rgb image there is no recoloring _prog = self.win._progImageStim GL.glUseProgram(_prog) # set the texture to be texture unit 0 GL.glUniform1i(GL.glGetUniformLocation(_prog, b"texture"), 0) # mask is texture unit 1 GL.glUniform1i(GL.glGetUniformLocation(_prog, b"mask"), 1) # mask GL.glActiveTexture(GL.GL_TEXTURE1) GL.glBindTexture(GL.GL_TEXTURE_2D, self._maskID) GL.glEnable(GL.GL_TEXTURE_2D) # implicitly disables 1D # main texture GL.glActiveTexture(GL.GL_TEXTURE0) GL.glBindTexture(GL.GL_TEXTURE_2D, self._texID) GL.glEnable(GL.GL_TEXTURE_2D) GL.glFrontFace(GL.GL_CW) gt.useProgram(self.win._shaders['imageStim']) # pass values to OpenGL as material r, g, b = self._foreColor.render('rgb') color = np.ctypeslib.as_ctypes( np.array((r, g, b, 1.0), np.float32)) GL.glColor4f(*color) gt.drawVAO(self._vao, GL.GL_TRIANGLES) gt.useProgram(0) # unbind the textures GL.glActiveTexture(GL.GL_TEXTURE1) GL.glBindTexture(GL.GL_TEXTURE_2D, 0) GL.glDisable(GL.GL_TEXTURE_2D) # implicitly disables 1D # main texture GL.glActiveTexture(GL.GL_TEXTURE0) GL.glBindTexture(GL.GL_TEXTURE_2D, 0) GL.glDisable(GL.GL_TEXTURE_2D) GL.glFrontFace(GL.GL_CW) # Exit 3d perspective win.useLights = False win.resetEyeTransform() @staticmethod def _normToDegrees(value): # Convert to between 0 and 1 value += 1 value /= 2 # Convert to degrees value *= 360 return value @staticmethod def _degreesToNorm(value): # Convert from degrees value /= 360 # Convert to between -1 and 1 value *= 2 value -= 1 return value if __name__ == "__main__": pass
10,339
Python
.py
255
31.25098
82
0.617096
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,762
metadata.py
psychopy_psychopy/psychopy/visual/movies/metadata.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Class for storing and working with movie file metadata. """ # 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__ = ["MovieMetadata", "NULL_MOVIE_METADATA"] class MovieMetadata: """Class for storing metadata and other information associated with a movie. Some fields may not be populated if the video format or decoder cannot determine them from the stream. Parameters ---------- mediaPath : str Path to the file that has been loaded or is presently being played. This may be a file path or URI to the location of the media. title : str Title of the clip stored in the metadata. duration : float Total length of the loaded movie clip in seconds. size : tuple Width and height of the source video frame in pixels. frameRate : float or tuple Frame rate of the movie in Hertz (Hz). If a tuple is specified, the format should be `(numerator, denominator)`. movieLib : str or None Library used to obtain this metadata. Almost always will be the same value as `MovieStim.movieLib` if this metadata has been retrieved using that class. userData : dict or None Optional mapping for storing user defined data. Examples -------- Accessing metadata via the `MovieStim` class:: myMovie = MovieStim(win, '/path/to/my/movie.mpeg') clipDuration = myMovie.metadata.duration Check if metadata is valid:: metadataValid = myMovie.metadata is not NULL_MOVIE_METADATA """ __slots__ = [ '_mediaPath', '_title', '_duration', '_size', '_frameRate', '_frameInterval', '_pixelFormat', '_movieLib', '_userData' ] def __init__(self, mediaPath=u"", title=u"", duration=-1, size=(-1, -1), frameRate=-1, pixelFormat='unknown', movieLib=u"", userData=None): self.mediaPath = mediaPath self.title = title self.duration = duration self.frameRate = frameRate self.size = size self.pixelFormat = pixelFormat self.movieLib = movieLib self.userData = userData def __repr__(self): return (f"MovieMetadata(mediaPath={repr(self.mediaPath)}, " f"title={repr(self.title)}, " f"duration={self.duration}, " f"size={self.size}, " f"frameRate={self.frameRate}, " f"pixelFormat={self.pixelFormat}, " f"movieLib={repr(self.movieLib)}, " f"userData={repr(self.userData)})") def compare(self, metadata): """Get a list of attribute names that differ between this and another metadata object. Returns ------- list of str """ if not isinstance(metadata, MovieMetadata): raise TypeError( 'Value for `metadata` must have type `MovieMetadata`.') return [] @property def mediaPath(self): """Path to the video (`str`). May be either a path to a file on the local machine, URI, or camera enumeration. An empty string indicates this field is uninitialized. """ return self._mediaPath @mediaPath.setter def mediaPath(self, value): self._mediaPath = str(value) @property def title(self): """Title of the video (`str`). An empty string indicates this field is not initialized. """ return self._title @title.setter def title(self, value): self._title = str(value) @property def duration(self): """Total length of the loaded movie clip in seconds (`float`). A value of `-1` indicates that this value is uninitialized. """ return self._duration @duration.setter def duration(self, value): if value is None: value = 0.0 self._duration = float(value) @property def frameRate(self): """Framerate of the video (`float` or `tuple`). A value of `-1` indicates that this field is not initialized. """ return self._frameRate @frameRate.setter def frameRate(self, value): if isinstance(value, (tuple, list,)): self._frameRate = value[0] / float(value[1]) else: self._frameRate = float(value) # compute the frame interval from the frame rate self._frameInterval = 1.0 / self._frameRate @property def frameInterval(self): """Frame interval in seconds (`float`). This is the amount of time the frame is to remain onscreen given the framerate. This value is computed after the `frameRate` attribute is set. """ return self._frameInterval @property def size(self): """Source video size (w, h) in pixels (`tuple`). This value is uninitialized if `(-1, -1)` is returned. """ return self._size @size.setter def size(self, value): # format checking if not hasattr(value, '__len__'): raise TypeError('Value for `size` must be iterable.') if not len(value) == 2: raise ValueError( 'Invalid length for value `size`, must have length of 2.') if not all([isinstance(i, int) for i in value]): raise TypeError('Elements of `size` must all have type `int`.') self._size = tuple(value) @property def movieLib(self): """Movie library used to get this metadata (`str`). An empty string indicates this field is not initialized. """ return self._movieLib @movieLib.setter def movieLib(self, value): self._movieLib = str(value) @property def pixelFormat(self): """Video pixel format (`str`). An empty string indicates this field is not initialized. """ return self._pixelFormat @pixelFormat.setter def pixelFormat(self, value): self._pixelFormat = str(value) @property def userData(self): """Optional mapping for storing user defined data (`dict` or `None`). If set to `None`, an empty dictionary will be initialized and set as this value. """ return self._userData @userData.setter def userData(self, value): if value is None: self._userData = {} return if not isinstance(value, dict): raise TypeError( 'Value for `userData` must be type `dict` or `None`.') self._userData = value # Null movie metadata object, return a reference to this object instead of # `None` when no metadata is present. NULL_MOVIE_METADATA = MovieMetadata() if __name__ == "__main__": pass
7,118
Python
.py
195
27.979487
80
0.603839
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,763
__init__.py
psychopy_psychopy/psychopy/visual/movies/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """A stimulus class for playing movies (mpeg, avi, etc...) in PsychoPy. """ # 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__ = ['MovieStim'] import ctypes import os.path from pathlib import Path from psychopy import prefs from psychopy.tools.filetools import pathToString, defaultStim from psychopy.visual.basevisual import ( BaseVisualStim, DraggingMixin, ContainerMixin, ColorMixin ) from psychopy.constants import FINISHED, NOT_STARTED, PAUSED, PLAYING, STOPPED from .players import getMoviePlayer from .metadata import MovieMetadata, NULL_MOVIE_METADATA from .frame import MovieFrame, NULL_MOVIE_FRAME_INFO import numpy as np import pyglet pyglet.options['debug_gl'] = False GL = pyglet.gl # threshold to stop reporting dropped frames reportNDroppedFrames = 10 # constants for use with ffpyplayer FFPYPLAYER_STATUS_EOF = 'eof' FFPYPLAYER_STATUS_PAUSED = 'paused' PREFERRED_VIDEO_LIB = 'ffpyplayer' # ------------------------------------------------------------------------------ # Classes # class MovieStim(BaseVisualStim, DraggingMixin, ColorMixin, ContainerMixin): """Class for presenting movie clips as stimuli. Parameters ---------- win : :class:`~psychopy.visual.Window` Window the video is being drawn to. filename : str Name of the file or stream URL to play. If an empty string, no file will be loaded on initialization but can be set later. movieLib : str or None Library to use for video decoding. By default, the 'preferred' library by PsychoPy developers is used. Default is `'ffpyplayer'`. An alert is raised if you are not using the preferred player. units : str Units to use when sizing the video frame on the window, affects how `size` is interpreted. size : ArrayLike or None Size of the video frame on the window in `units`. If `None`, the native size of the video will be used. draggable : bool Can this stimulus be dragged by a mouse click? flipVert : bool If `True` then the movie will be top-bottom flipped. flipHoriz : bool If `True` then the movie will be right-left flipped. volume : int or float If specifying an `int` the nominal level is 100, and 0 is silence. If a `float`, values between 0 and 1 may be used. loop : bool Whether to start the movie over from the beginning if draw is called and the movie is done. Default is `False`. autoStart : bool Automatically begin playback of the video when `flip()` is called. """ def __init__(self, win, filename="", movieLib=u'ffpyplayer', units='pix', size=None, pos=(0.0, 0.0), ori=0.0, anchor="center", draggable=False, flipVert=False, flipHoriz=False, color=(1.0, 1.0, 1.0), # remove? colorSpace='rgb', opacity=1.0, contrast=1, volume=1.0, name='', loop=False, autoLog=True, depth=0.0, noAudio=False, interpolate=True, autoStart=True): # # check if we have the VLC lib # if not haveFFPyPlayer: # raise ImportError( # 'Cannot import package `ffpyplayer`, therefore `FFMovieStim` ' # 'cannot be used this session.') # what local vars are defined (these are the init params) for use self._initParams = dir() self._initParams.remove('self') super(MovieStim, self).__init__( win, units=units, name=name, autoLog=False) # drawing stuff self.draggable = draggable self.flipVert = flipVert self.flipHoriz = flipHoriz self.pos = pos self.ori = ori self.size = size self.depth = depth self.anchor = anchor self.colorSpace = colorSpace self.color = color self.opacity = opacity # playback stuff self._filename = pathToString(filename) self._volume = volume self._noAudio = noAudio # cannot be changed self.loop = loop self._recentFrame = None self._autoStart = autoStart self._isLoaded = False # OpenGL data self.interpolate = interpolate self._texFilterNeedsUpdate = True self._metadata = NULL_MOVIE_METADATA self._pixbuffId = GL.GLuint(0) self._textureId = GL.GLuint(0) # get the player interface for the desired `movieLib` and instance it self._player = getMoviePlayer(movieLib)(self) # load a file if provided, otherwise the user must call `setMovie()` self._filename = pathToString(filename) if self._filename: # load a movie if provided self.loadMovie(self._filename) self.autoLog = autoLog @property def filename(self): """File name for the loaded video (`str`).""" return self._filename @filename.setter def filename(self, value): self.loadMovie(value) def setMovie(self, value): if self._isLoaded: self.unload() self.loadMovie(value) @property def autoStart(self): """Start playback when `.draw()` is called (`bool`).""" return self._autoStart @autoStart.setter def autoStart(self, value): self._autoStart = bool(value) @property def frameRate(self): """Frame rate of the movie in Hertz (`float`). """ return self._player.metadata.frameRate @property def _hasPlayer(self): """`True` if a media player instance is started. """ # use this property to check if the player instance is started in # methods which require it return self._player is not None def loadMovie(self, filename): """Load a movie file from disk. Parameters ---------- filename : str Path to movie file. Must be a format that FFMPEG supports. """ # If given `default.mp4`, sub in full path if isinstance(filename, str): # alias default names (so it always points to default.png) if filename in defaultStim: filename = Path(prefs.paths['assets']) / defaultStim[filename] # check if the file has can be loaded if not os.path.isfile(filename): raise FileNotFoundError("Cannot open movie file `{}`".format( filename)) else: # If given a recording component, use its last clip if hasattr(filename, "lastClip"): filename = filename.lastClip self._filename = filename self._player.load(self._filename) self._freeBuffers() # free buffers (if any) before creating a new one self._setupTextureBuffers() self._isLoaded = True def load(self, filename): """Load a movie file from disk (alias of `loadMovie`). Parameters ---------- filename : str Path to movie file. Must be a format that FFMPEG supports. """ self.loadMovie(filename=filename) def unload(self, log=True): """Stop and unload the movie. Parameters ---------- log : bool Log this event. """ self._player.stop(log=log) self._player.unload() self._freeBuffers() # free buffer before creating a new one self._isLoaded = False @property def frameTexture(self): """Texture ID for the current video frame (`GLuint`). You can use this as a video texture. However, you must periodically call `updateVideoFrame` to keep this up to date. """ return self._textureId def updateVideoFrame(self): """Update the present video frame. The next call to `draw()` will make the retrieved frame appear. Returns ------- bool If `True`, the video texture has been updated and the frame index is advanced by one. If `False`, the last frame should be kept on-screen. """ # get the current movie frame for the video time newFrameFromPlayer = self._player.getMovieFrame() if newFrameFromPlayer is not None: self._recentFrame = newFrameFromPlayer # only do a pixel transfer on valid frames if self._recentFrame is not None: self._pixelTransfer() return self._recentFrame def draw(self, win=None): """Draw the current frame to a particular window. The current position in the movie will be determined automatically. This method should be called on every frame that the movie is meant to appear. If `.autoStart==True` the video will begin playing when this is called. Parameters ---------- win : :class:`~psychopy.visual.Window` or `None` Window the video is being drawn to. If `None`, the window specified at initialization will be used instead. Returns ------- bool `True` if the frame was updated this draw call. """ self._selectWindow(self.win if win is None else win) # handle autoplay if self._autoStart and self.isNotStarted: self.play() # update the video frame and draw it to a quad _ = self.updateVideoFrame() self._drawRectangle() # draw the texture to the target window return True # -------------------------------------------------------------------------- # Video playback controls and status # @property def isPlaying(self): """`True` if the video is presently playing (`bool`). """ # Status flags as properties are pretty useful for users since they are # self documenting and prevent the user from touching the status flag # attribute directly. # if self._player is not None: return self._player.isPlaying return False @property def isNotStarted(self): """`True` if the video may not have started yet (`bool`). This status is given after a video is loaded and play has yet to be called. """ if self._player is not None: return self._player.isNotStarted return True @property def isStopped(self): """`True` if the video is stopped (`bool`). It will resume from the beginning if `play()` is called. """ if self._player is not None: return self._player.isStopped return False @property def isPaused(self): """`True` if the video is presently paused (`bool`). """ if self._player is not None: return self._player.isPaused return False @property def isFinished(self): """`True` if the video is finished (`bool`). """ if self._player is not None: return self._player.isFinished return False def play(self, log=True): """Start or continue a paused movie from current position. Parameters ---------- log : bool Log the play event. """ # get the absolute experiment time the first frame is to be presented # if self.status == NOT_STARTED: # self._player.volume = self._volume self._player.play(log=log) def pause(self, log=True): """Pause the current point in the movie. The image of the last frame will persist on-screen until `play()` or `stop()` are called. Parameters ---------- log : bool Log this event. """ self._player.pause(log=log) def toggle(self, log=True): """Switch between playing and pausing the movie. If the movie is playing, this function will pause it. If the movie is paused, this function will play it. Parameters ---------- log : bool Log this event. """ if self.isPlaying: self.pause() else: self.play() def stop(self, log=True): """Stop the current point in the movie (sound will stop, current frame will not advance and remain on-screen). Once stopped the movie can be restarted from the beginning by calling `play()`. Parameters ---------- log : bool Log this event. """ # stop should reset the video to the start and pause if self._player is not None: self._player.stop() def seek(self, timestamp, log=True): """Seek to a particular timestamp in the movie. Parameters ---------- timestamp : float Time in seconds. log : bool Log this event. """ self._player.seek(timestamp, log=log) def rewind(self, seconds=5, log=True): """Rewind the video. Parameters ---------- seconds : float Time in seconds to rewind from the current position. Default is 5 seconds. log : bool Log this event. """ self._player.rewind(seconds, log=log) def fastForward(self, seconds=5, log=True): """Fast-forward the video. Parameters ---------- seconds : float Time in seconds to fast forward from the current position. Default is 5 seconds. log : bool Log this event. """ self._player.fastForward(seconds, log=log) def replay(self, log=True): """Replay the movie from the beginning. Parameters ---------- log : bool Log this event. Notes ----- * This tears down the current media player instance and creates a new one. Similar to calling `stop()` and `loadMovie()`. Use `seek(0.0)` if you would like to restart the movie without reloading. """ self._player.replay(log=log) # -------------------------------------------------------------------------- # Audio stream control methods # @property def muted(self): """`True` if the stream audio is muted (`bool`). """ return self._player.muted @muted.setter def muted(self, value): self._player.muted = value def volumeUp(self, amount=0.05): """Increase the volume by a fixed amount. Parameters ---------- amount : float or int Amount to increase the volume relative to the current volume. """ self._player.volumeUp(amount) def volumeDown(self, amount=0.05): """Decrease the volume by a fixed amount. Parameters ---------- amount : float or int Amount to decrease the volume relative to the current volume. """ self._player.volumeDown(amount) @property def volume(self): """Volume for the audio track for this movie (`int` or `float`). """ return self._player.volume @volume.setter def volume(self, value): self._player.volume = value # -------------------------------------------------------------------------- # Video and playback information # @property def frameIndex(self): """Current frame index being displayed (`int`).""" return self._player.frameIndex def getCurrentFrameNumber(self): """Get the current movie frame number (`int`), same as `frameIndex`. """ return self.frameIndex @property def duration(self): """Duration of the loaded video in seconds (`float`). Not valid unless the video has been started. """ if not self._player: return -1.0 return self._player.metadata.duration @property def loopCount(self): """Number of loops completed since playback started (`int`). Incremented each time the movie begins another loop. Examples -------- Compute how long a looping video has been playing until now:: totalMovieTime = (mov.loopCount + 1) * mov.pts """ if not self._player: return -1 return self._player.loopCount @property def fps(self): """Movie frames per second (`float`).""" return self.getFPS() def getFPS(self): """Movie frames per second. Returns ------- float Nominal number of frames to be displayed per second. """ if not self._player: return 1.0 return self._player.metadata.frameRate @property def videoSize(self): """Size of the video `(w, h)` in pixels (`tuple`). Returns `(0, 0)` if no video is loaded. """ if not self._player: return 0, 0 return self._player.metadata.size @property def origSize(self): """ Alias of videoSize """ return self.videoSize @property def frameSize(self): """Size of the video `(w, h)` in pixels (`tuple`). Alias of `videoSize`. """ if not self._player: return 0, 0 return self._player.metadata.size @property def pts(self): """Presentation timestamp of the most recent frame (`float`). This value corresponds to the time in movie/stream time the frame is scheduled to be presented. """ if not self._player: return -1.0 return self._player.pts def getPercentageComplete(self): """Provides a value between 0.0 and 100.0, indicating the amount of the movie that has been already played (`float`). """ return (self.pts / self.duration) * 100.0 # -------------------------------------------------------------------------- # OpenGL and rendering # def _freeBuffers(self): """Free texture and pixel buffers. Call this when tearing down this class or if a movie is stopped. """ try: # delete buffers and textures if previously created if self._pixbuffId.value > 0: GL.glDeleteBuffers(1, self._pixbuffId) self._pixbuffId = GL.GLuint() # delete the old texture if present if self._textureId.value > 0: GL.glDeleteTextures(1, self._textureId) self._textureId = GL.GLuint() except TypeError: # can happen when unloading or shutting down pass def _setupTextureBuffers(self): """Setup texture buffers which hold frame data. This creates a 2D RGB texture and pixel buffer. The pixel buffer serves as the store for texture color data. Each frame, the pixel buffer memory is mapped and frame data is copied over to the GPU from the decoder. This is called every time a video file is loaded. The `_freeBuffers` method is called in this routine prior to creating new buffers, so it's safe to call this right after loading a new movie without having to `_freeBuffers` first. """ # get the size of the movie frame and compute the buffer size vidWidth, vidHeight = self._player.getMetadata().size nBufferBytes = vidWidth * vidHeight * 4 # Create the pixel buffer object which will serve as the texture memory # store. Pixel data will be copied to this buffer each frame. GL.glGenBuffers(1, ctypes.byref(self._pixbuffId)) GL.glBindBuffer(GL.GL_PIXEL_UNPACK_BUFFER, self._pixbuffId) GL.glBufferData( GL.GL_PIXEL_UNPACK_BUFFER, nBufferBytes * ctypes.sizeof(GL.GLubyte), None, GL.GL_STREAM_DRAW) # one-way app -> GL GL.glBindBuffer(GL.GL_PIXEL_UNPACK_BUFFER, 0) # Create a texture which will hold the data streamed to the pixel # buffer. Only one texture needs to be allocated. GL.glEnable(GL.GL_TEXTURE_2D) GL.glGenTextures(1, ctypes.byref(self._textureId)) GL.glBindTexture(GL.GL_TEXTURE_2D, self._textureId) GL.glTexImage2D( GL.GL_TEXTURE_2D, 0, GL.GL_RGBA8, vidWidth, vidHeight, # frame dims in pixels 0, GL.GL_BGRA, GL.GL_UNSIGNED_BYTE, None) # setup texture filtering if self.interpolate: texFilter = GL.GL_LINEAR else: texFilter = GL.GL_NEAREST GL.glTexParameteri( GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, texFilter) GL.glTexParameteri( GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, texFilter) GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, GL.GL_CLAMP) GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_CLAMP) GL.glBindTexture(GL.GL_TEXTURE_2D, 0) GL.glDisable(GL.GL_TEXTURE_2D) GL.glFlush() # make sure all buffers are ready def _pixelTransfer(self): """Copy pixel data from video frame to texture. """ # get the size of the movie frame and compute the buffer size vidWidth, vidHeight = self._player.getMetadata().size nBufferBytes = vidWidth * vidHeight * 4 # bind pixel unpack buffer GL.glBindBuffer(GL.GL_PIXEL_UNPACK_BUFFER, self._pixbuffId) # Free last storage buffer before mapping and writing new frame # data. This allows the GPU to process the extant buffer in VRAM # uploaded last cycle without being stalled by the CPU accessing it. GL.glBufferData( GL.GL_PIXEL_UNPACK_BUFFER, nBufferBytes * ctypes.sizeof(GL.GLubyte), None, GL.GL_STREAM_DRAW) # Map the buffer to client memory, `GL_WRITE_ONLY` to tell the # driver to optimize for a one-way write operation if it can. bufferPtr = GL.glMapBuffer( GL.GL_PIXEL_UNPACK_BUFFER, GL.GL_WRITE_ONLY) bufferArray = np.ctypeslib.as_array( ctypes.cast(bufferPtr, ctypes.POINTER(GL.GLubyte)), shape=(nBufferBytes,)) # copy data bufferArray[:] = self._recentFrame.colorData[:] # Very important that we unmap the buffer data after copying, but # keep the buffer bound for setting the texture. GL.glUnmapBuffer(GL.GL_PIXEL_UNPACK_BUFFER) # bind the texture in OpenGL GL.glEnable(GL.GL_TEXTURE_2D) GL.glActiveTexture(GL.GL_TEXTURE0) GL.glBindTexture(GL.GL_TEXTURE_2D, self._textureId) # copy the PBO to the texture GL.glTexSubImage2D( GL.GL_TEXTURE_2D, 0, 0, 0, vidWidth, vidHeight, GL.GL_BGRA, GL.GL_UNSIGNED_INT_8_8_8_8_REV, 0) # point to the presently bound buffer # update texture filtering only if needed if self._texFilterNeedsUpdate: if self.interpolate: texFilter = GL.GL_LINEAR else: texFilter = GL.GL_NEAREST GL.glTexParameteri( GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, texFilter) GL.glTexParameteri( GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, texFilter) self._texFilterNeedsUpdate = False # important to unbind the PBO GL.glBindBuffer(GL.GL_PIXEL_UNPACK_BUFFER, 0) GL.glBindTexture(GL.GL_TEXTURE_2D, 0) GL.glDisable(GL.GL_TEXTURE_2D) def _drawRectangle(self): """Draw the video frame to the window. This is called by the `draw()` method to blit the video to the display window. """ # make sure that textures are on and GL_TEXTURE0 is active GL.glEnable(GL.GL_TEXTURE_2D) GL.glActiveTexture(GL.GL_TEXTURE0) # sets opacity (1, 1, 1 = RGB placeholder) GL.glColor4f(1, 1, 1, self.opacity) GL.glPushMatrix() self.win.setScale('pix') # move to centre of stimulus and rotate vertsPix = self.verticesPix array = (GL.GLfloat * 32)( 1, 1, # texture coords vertsPix[0, 0], vertsPix[0, 1], 0., # vertex 0, 1, vertsPix[1, 0], vertsPix[1, 1], 0., 0, 0, vertsPix[2, 0], vertsPix[2, 1], 0., 1, 0, vertsPix[3, 0], vertsPix[3, 1], 0., ) GL.glPushAttrib(GL.GL_ENABLE_BIT) GL.glActiveTexture(GL.GL_TEXTURE0) GL.glBindTexture(GL.GL_TEXTURE_2D, self._textureId) GL.glPushClientAttrib(GL.GL_CLIENT_VERTEX_ARRAY_BIT) # 2D texture array, 3D vertex array GL.glInterleavedArrays(GL.GL_T2F_V3F, 0, array) GL.glDrawArrays(GL.GL_QUADS, 0, 4) GL.glPopClientAttrib() GL.glPopAttrib() GL.glPopMatrix() GL.glBindTexture(GL.GL_TEXTURE_2D, 0) GL.glDisable(GL.GL_TEXTURE_2D) if __name__ == "__main__": pass
25,806
Python
.py
676
28.804734
81
0.588365
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,764
frame.py
psychopy_psychopy/psychopy/visual/movies/frame.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Class for video frames. """ # 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__ = ["MovieFrame", "NULL_MOVIE_FRAME_INFO", "MOVIE_FRAME_NOT_READY"] MOVIE_FRAME_NOT_READY = object() class MovieFrame: """Class containing data of a single movie frame. Parameters ---------- frameIndex : int The index for this frame in the movie. absTime : float Absolute time in seconds in movie time which the frame is to appear on-screen. displayTime : float Time in seconds the frame is intended to remain on screen after `absTime`. Usually equal to the frame period. size : ArrayLike Width and height of the source video frame in pixels. This is needed to correctly interpret `colorData`. colorFormat : str Color format identifier. This is used to ensure the correct format for the destination texture buffer that will contain `colorData`. Default is `'rgb8'` for 8-bit RGB. colorData : ArrayLike or None Movie frame color pixel data as an array. Set as `None` if no image data is available. audioChannels : int Number of audio channels present in `audioSamples` (`int`). Use `1` for mono and `2` for stereo. This is used to correctly format the data contained in `audioSamples` to pass to the desired audio sink. audioSamples : ArrayLike or None Audio samples as an array. Set as `None` if audio data is unavailable. metadata : MovieMetadata Metadata of the stream at the time this movie frame was obtained. movieLib : str or None Movie library used to obtain this frame (e.g., `'ffpyplayer'`). userData : dict or None Optional mapping for storing user defined data. """ __slots__ = [ "_metadata", "_frameIndex", "_absTime", "_displayTime", "_size", "_colorFormat", "_colorData", "_audioSamples", "_audioChannels", "_movieLib", "_userData", '_keepAlive' ] def __init__(self, frameIndex=-1, absTime=-1.0, displayTime=0.0, size=(-1, -1), colorFormat='rgb8', colorData=None, audioChannels=2, audioSamples=None, metadata=None, movieLib=u"", userData=None, keepAlive=None): self.frameIndex = frameIndex self.absTime = absTime self.displayTime = displayTime self.size = size self.colorFormat = colorFormat self.colorData = colorData self.audioSamples = audioSamples self.audioChannels = audioChannels self._metadata = metadata self.movieLib = movieLib self.userData = userData self._keepAlive = keepAlive def __repr__(self): return (f"MovieFrame(frameIndex={self.frameIndex}, " f"absTime={self.absTime}, " f"displayTime={self.displayTime}, " f"size={self.size}, " f"colorData={repr(self.colorData)}, " f"colorFormat={repr(self.colorFormat)}, " f"audioChannels={self.audioChannels}, " f"audioSamples={repr(self.audioSamples)}, " f"metadata={repr(self._metadata)}, " f"movieLib={repr(self.movieLib)}, " f"userData={repr(self.userData)})") @property def frameIndex(self): """The index for this frame in the movie (`int`). A value of `-1` indicates that this value is uninitialized. """ return self._frameIndex @frameIndex.setter def frameIndex(self, val): self._frameIndex = int(val) @property def absTime(self): """Absolute time in seconds in movie time which the frame is to appear on-screen (`float`). A value of -1.0 indicates that this value is not valid. """ return self._absTime @absTime.setter def absTime(self, val): self._absTime = float(val) @property def displayTime(self): """Time in seconds the frame is intended to remain on screen after `absTime` (`float`). Usually equal to the frame period. """ return self._displayTime @displayTime.setter def displayTime(self, val): self._displayTime = float(val) @property def size(self): """Source video size (frame size) (w, h) in pixels (`tuple`). This value is uninitialized if `(-1, -1)` is returned. """ return self._size @size.setter def size(self, value): # format checking if not hasattr(value, '__len__'): raise TypeError('Value for `size` must be iterable.') if not len(value) == 2: raise ValueError( 'Invalid length for value `size`, must have length of 2.') if not all([isinstance(i, int) for i in value]): raise TypeError('Elements of `size` must all have type `int`.') self._size = tuple(value) @property def colorFormat(self): """Color format of the frame color data (`str`). Default is `'rgb8'`. """ return self._colorFormat @colorFormat.setter def colorFormat(self, value): self._colorFormat = str(value) @property def colorData(self): """Movie frame color data as an array (`ArrayLike` or `None`). The format of this array is contingent on the `movieLib` in use. """ return self._colorData @colorData.setter def colorData(self, val): self._colorData = val @property def audioSamples(self): """Audio data as an array (`ArrayLike` or `None`). The format of this array is contingent on the `movieLib` in use. """ return self._audioSamples @audioSamples.setter def audioSamples(self, val): self._audioSamples = val @property def audioChannels(self): """Number of audio channels present in `audioSamples` (`int`). Use `1` for mono and `2` for stereo. This is used to correctly format the data contained in `audioSamples` to get past to the desired audio sink. """ return self._audioChannels @audioChannels.setter def audioChannels(self, val): self._audioChannels = int(val) @property def metadata(self): """Movie library used to get this metadata (`str`). An empty string indicates this field is not initialized. """ return self._metadata @metadata.setter def metadata(self, value): self._metadata = value @property def movieLib(self): """Movie library used to get this metadata (`str`). An empty string indicates this field is not initialized. """ return self._movieLib @movieLib.setter def movieLib(self, value): self._movieLib = str(value) @property def userData(self): """Optional mapping for storing user defined data (`dict` or `None`). If set to `None`, an empty dictionary will be initialized and set as this value. """ return self._userData @userData.setter def userData(self, value): if value is None: self._userData = {} return if not isinstance(value, dict): raise TypeError( 'Value for `userData` must be type `dict` or `None`.') self._userData = value # used to represent an empty frame NULL_MOVIE_FRAME_INFO = MovieFrame() if __name__ == "__main__": pass
7,932
Python
.py
215
28.306977
80
0.606463
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,765
__init__.py
psychopy_psychopy/psychopy/visual/movies/players/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Classes and functions for interfacing with movie player libraries. """ # 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__ = ["getMoviePlayer"] import psychopy.logging as logging from ._base import BaseMoviePlayer # Players available, you must update this list to make players discoverable by # the `MovieStim` class when the user specifies `movieLib`. _players = {'Null': None} PREFERRED_VIDEO_LIB = 'ffpyplayer' def getMoviePlayer(movieLib): """Get a movie player interface. Calling this returns a reference to the unbound class for the requested movie player interface. Parameters ---------- movieLib : str Name of the player interface to get. Returns ------- Subclass of BaseMoviePlayer """ if not isinstance(movieLib, str): # type check raise TypeError( "Invalid type for parameter `movieLib`. Must have type `str`.") global _players try: from .ffpyplayer_player import FFPyPlayer _players['ffpyplayer'] = FFPyPlayer except ImportError: logging.warn("Cannot import library `ffpyplayer`, backend is " "unavailable.") # get a reference to the player object reqPlayer = _players.get(movieLib, None) if reqPlayer is not None: return reqPlayer # error if the key is not in `reqPlayer` raise ValueError( "Cannot find matching video player interface for '{}'.".format( movieLib)) if __name__ == "__main__": pass
1,695
Python
.py
46
31.565217
79
0.685242
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,766
ffpyplayer_player.py
psychopy_psychopy/psychopy/visual/movies/players/ffpyplayer_player.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Classes for movie player interfaces. """ # 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__ = [ 'FFPyPlayer' ] import sys from ffpyplayer.player import MediaPlayer # very first thing to import import time import psychopy.logging as logging import math import numpy as np import threading import queue from psychopy.core import getTime from ._base import BaseMoviePlayer from ..metadata import MovieMetadata from ..frame import MovieFrame, NULL_MOVIE_FRAME_INFO from psychopy.constants import ( FINISHED, NOT_STARTED, PAUSED, PLAYING, STOPPED, STOPPING, INVALID, SEEKING) from psychopy.tools.filetools import pathToString import atexit # Options that PsychoPy devs picked to provide better performance, these can # be overridden, but it might result in undefined behavior. DEFAULT_FF_OPTS = { 'sync': 'audio', # sync to audio 'paused': True, # start paused 'autoexit': False, # don't exit ffmpeg automatically 'loop': 0 # enable looping } # default queue size for the stream reader DEFAULT_FRAME_QUEUE_SIZE = 1 # event to close all opened movie reader threads _evtCleanUpMovieEvent = threading.Event() _evtCleanUpMovieEvent.clear() # Cleanup routines for threads. This allows the app to crash gracefully rather # than locking up on error. def _closeMovieThreads(): """Callback function when the application exits which cleans up movie threads. When this function is called, any outstanding movie threads will be closed automatically. This must not be called at any other point of the program. """ global _evtCleanUpMovieEvent _evtCleanUpMovieEvent.set() atexit.register(_closeMovieThreads) # register the function class StreamStatus: """Descriptor class for stream status. This class is used to report the current status of the movie stream at the time the movie frame was obtained. Parameters ---------- status : int Status flag for the stream. streamTime : float Current stream (movie) time in seconds. Resets after a loop has completed. frameIndex : int Current frame index, increases monotonically as a movie plays and resets when finished or beginning another loop. loopCount : int If looping is enabled, this value increases by 1 each time the movie loops. Initial value is 0. """ __slots__ = ['_status', '_streamTime', '_frameIndex', '_loopCount'] def __init__(self, status=NOT_STARTED, streamTime=0.0, frameIndex=-1, loopCount=-1): self._status = int(status) self._streamTime = float(streamTime) self._frameIndex = frameIndex self._loopCount = loopCount @property def status(self): """Status flag for the stream (`int`). """ return self._status @property def streamTime(self): """Current stream time in seconds (`float`). This value increases monotonically and is common timebase for all cameras attached to the system. """ return self._streamTime @property def frameIndex(self): """Current frame in the stream (`float`). This value increases monotonically as the movie plays. The first frame has an index of 0. """ return self._frameIndex @property def loopCount(self): """Number of times the movie has looped (`float`). This value increases monotonically as the movie plays. This is incremented when the movie finishes. """ return self._loopCount class StreamData: """Descriptor class for movie stream data. Instances of this class are produced by the movie stream reader thread which contains metadata about the stream, frame image data (i.e. pixel values), and the stream status. Parameters ---------- metadata : MovieMetadata Stream metadata. frameImage : object Video frame image data. streamStatus : StreamStatus Video stream status. cameraLib : str Camera library in use to process the stream. """ __slots__ = ['_metadata', '_frameImage', '_streamStatus', '_cameraLib'] def __init__(self, metadata, frameImage, streamStatus, cameraLib): self._metadata = metadata self._frameImage = frameImage self._streamStatus = streamStatus self._cameraLib = cameraLib @property def metadata(self): """Stream metadata at the time the video frame was acquired (`MovieMetadata`). """ return self._metadata @metadata.setter def metadata(self, value): if not isinstance(value, MovieMetadata) or value is not None: raise TypeError("Incorrect type for property `metadata`, expected " "`MovieMetadata` or `None`.") self._metadata = value @property def frameImage(self): """Frame image data from the codec (`ffpyplayer.pic.Image`). """ return self._frameImage @frameImage.setter def frameImage(self, value): self._frameImage = value @property def streamStatus(self): """Stream status (`StreamStatus`). """ return self._streamStatus @streamStatus.setter def streamStatus(self, value): if not isinstance(value, StreamStatus) or value is not None: raise TypeError("Incorrect type for property `streamStatus`, " "expected `StreamStatus` or `None`.") self._streamStatus = value @property def cameraLib(self): """Camera library in use to obtain the stream (`str`). Value is blank if `metadata` is `None`. """ if self._metadata is not None: return self._metadata.movieLib return u'' class MovieStreamThreadFFPyPlayer(threading.Thread): """Class for reading movie streams asynchronously. The rate of which frames are read is controlled dynamically based on values within stream metadata. This will ensure that CPU load is kept to a minimum, only polling for new frames at the rate they are being made available. Parameters ---------- player : `ffpyplayer.player.MediaPlayer` Media player instance, should be configured and initialized. Note that player instance methods might not be thread-safe after handing off the object to this thread. bufferFrames : int Number of frames to buffer. Sets the frame queue size for the thread. Use a queue size >1 for video recorded with a framerate above 60Hz. """ def __init__(self, player, bufferFrames=DEFAULT_FRAME_QUEUE_SIZE): threading.Thread.__init__(self) # Make this thread daemonic since we don't yet have a way of tracking # them down. Since we're only reading resources, it's unlikely that # we'll break or corrupt something. Good practice is to call `stop()` # before exiting, this thread will join as usual and cleanly free up # any resources. self.daemon = True self._player = player # player interface to FFMPEG self._frameQueue = queue.Queue(maxsize=bufferFrames) self._cmdQueue = queue.Queue() # queue for player commands # some values the user might want self._status = NOT_STARTED self._streamTime = 0.0 self._isIdling = False self._isFinished = False # Locks for syncing the player and main application thread self._warmUpLock = threading.Lock() self._warmUpLock.acquire(blocking=False) def run(self): """Main sub-routine for this thread. When the thread is running, data about captured frames are put into the `frameQueue` as `(metadata, img, pts)`. If the queue is empty, that means the main application thread is running faster than the encoder can get frames. Recommended behaviour in such cases it to return the last valid frame when the queue is empty. """ global _evtCleanUpMovieEvent if self._player is None: return # exit thread if no player # these should stay within the scope of this subroutine frameInterval = 0.004 # frame interval, start at 4ms (250Hz) frameData = None # frame data from the reader val = '' # status value from reader statusFlag = NOT_STARTED # status flag for stream reader state frameIndex = -1 # frame index, 0 == first frame loopCount = 0 # number of movie loops so far mustShutdown = False # player thread should shut down # Subroutines for various player functions ----------------------------- def seekTo(player, ptsTarget, maxAttempts=16): """Seek to a position in the video. Return the frame at that position. Parameters ---------- player : `MediaPlayer` Handle to player. ptsTarget : float Location in the movie to seek to. Must be a positive number. maxAttempts : int Number of attempts to converge. Returns ------- tuple Frame data and value from the `MediaPlayer` after seeking to the position. """ wasPaused = player.get_pause() player.set_pause(False) player.set_mute(True) # issue seek command to the player player.seek(ptsTarget, relative=False, accurate=True) # wait until we are at the seek position n = 0 ptsLast = float(2 ** 32) while n < maxAttempts: # converge on position frameData_, val_ = player.get_frame(show=True) if frameData_ is None: time.sleep(0.0025) n += 1 continue _, pts_ = frameData_ ptsClock = player.get_pts() # Check if the PTS is the same as the last attempt, if so # we are likely not going to converge on some other value. if math.isclose(ptsClock, ptsLast): break # If the PTS is different than the last one, check if it's # close to the target. if math.isclose(pts_, ptsTarget) and math.isclose( ptsClock, ptsTarget): break ptsLast = ptsClock n += 1 else: frameData_, val_ = None, '' player.set_mute(False) player.set_pause(wasPaused) return frameData_, val_ def calcFrameIndex(pts_, frameInterval_): """Calculate the frame index from the presentation time stamp and frame interval. Parameters ---------- pts_ : float Presentation timestamp. frameInterval_ : float Frame interval of the movie in seconds. Returns ------- int Frame index. """ return int(math.floor(pts_ / frameInterval_)) - 1 # ---------------------------------------------------------------------- # Initialization # # Warmup the reader and get the first frame, this will be presented when # the player is first initialized, we should block until this process # completes using a lock object. To get the first frame we start the # video, acquire the frame, then seek to the beginning. The frame will # remain in the queue until accessed. The first frame is important since # it is needed to configure the texture buffers in the rendering thread. # # We need to start playback to access the first frame. This can be done # "silently" by muting the audio and playing the video for a single # frame. We then seek back to the beginning and pause the video. This # will ensure the first frame is presented. # self._player.set_mute(True) self._player.set_pause(False) # consume frames until we get a valid one, need its metadata while frameData is None or val == 'not ready': frameData, val = self._player.get_frame(show=True) # end of the file? ... at this point? something went wrong ... if val == 'eof': break time.sleep(frameInterval) # sleep a bit to avoid mashing the CPU # Obtain metadata from the frame now that we have a flowing stream. This # data is needed by the main thread to process to configure additional # resources needed to present the video. metadata = self._player.get_metadata() # Compute the frame interval that will be used, this is dynamically set # to reduce the amount of CPU load when obtaining new frames. Aliasing # may occur sometimes, possibly looking like a frame is being skipped, # but we're not sure if this actually happens in practice. frameRate = metadata['frame_rate'] numer, denom = frameRate try: frameInterval = 1.0 / (numer / float(denom)) except ZeroDivisionError: # likely won't happen since we always get a valid frame before # reaching here, but you never know ... raise RuntimeError( "Cannot play movie. Failed to acquire metadata from video " "stream!") # Get the movie duration, needed to determine when we get to the end of # movie. We need to reset some params when there. This is in seconds. duration = metadata['duration'] # Get color and timestamp data from the returned frame object, this will # be encapsulated in a `StreamData` object and passed back to the main # thread with status information. colorData, pts = frameData # Build up the object which we'll pass to the application thread. Stream # status information hold timestamp and playback information. streamStatus = StreamStatus( status=statusFlag, # current status flag, should be `NOT_STARTED` streamTime=pts) # frame timestamp # Put the frame in the frame queue so the main thread can read access it # safely. The main thread should hold onto any frame it gets when the # queue is empty. if self._frameQueue.full(): raise RuntimeError( "Movie decoder frame queue is full and it really shouldn't be " "at this point.") # Object to pass video frame data back to the application thread for # presentation or processing. lastFrame = StreamData( metadata, colorData, streamStatus, u'ffpyplayer') # Pass the object to the main thread using the frame queue. self._frameQueue.put(lastFrame) # put frame data in here # Rewind back to the beginning of the file, we should have the first # frame and metadata from the file by now. self._player.set_pause(True) # start paused self._player.set_mute(False) # frameData, val = seekTo(self._player, 0.0) # set the volume again because irt doesn't seem to remember it self._player.set_volume(self._player.get_volume()) # Release the lock to unblock the parent thread once we have the first # frame and valid metadata from the stream. After this returns the # main thread should call `getRecentFrame` to get the frame data. self._warmUpLock.release() # ---------------------------------------------------------------------- # Playback # # Main playback loop, this will continually pull frames from the stream # and push them into the frame queue. The user can pause and resume # playback. Avoid blocking anything outside the use of timers to prevent # stalling the thread. # while 1: # pull a new frame frameData, val = self._player.get_frame() # if no frame, just pause the thread and restart the loop if val == 'eof': # end of stream/file self._isFinished = self._isIdling = True time.sleep(frameInterval) elif frameData is None or val == 'paused': # paused or not ready self._isIdling = True self._isFinished = False time.sleep(frameInterval) else: # playing self._isIdling = self._isFinished = False colorData, pts = frameData # got a valid frame # updated last valid frame data lastFrame = StreamData( metadata, colorData, StreamStatus( status=statusFlag, # might remove streamTime=pts, frameIndex=calcFrameIndex(pts, frameInterval), loopCount=loopCount), u'ffpyplayer') # is the next frame the last? increment the number of loops then if pts + frameInterval * 1.5 >= duration: loopCount += 1 # inc number of loops if isinstance(val, float): time.sleep(val) # time to sleep else: time.sleep(frameInterval) # If the queue is full, just discard the frame and get the # next one to allow us to catch up. try: self._frameQueue.put_nowait(lastFrame) except queue.Full: pass # do nothing # ------------------------------------------------------------------ # Process playback controls # # Check the command queue for playback commands. Process all # commands in the queue before progressing. A command is a tuple put # into the queue where the first value is the op-code and the second # is the value: # # OPCODE, VALUE = COMMAND # # The op-code is a string specifying the command to execute, while # the value can be any object needed to carry out the command. # Possible opcodes and their values are shown in the table below: # # OPCODE | VALUE | DESCRIPTION # ------------+--------------------+------------------------------ # 'volume' | float (0.0 -> 1.0) | Set the volume # 'mute' | bool | Enable/disable sound # 'play' | None | Play a stream # 'pause' | None | Pause a stream # 'stop' | None | Pause and restart # 'seek' | pts, bool | Seek to a movie position # 'shutdown' | None | Kill the thread # needsWait = False if not self._cmdQueue.empty(): cmdOpCode, cmdVal = self._cmdQueue.get_nowait() # process the command if cmdOpCode == 'volume': # set the volume self._player.set_volume(float(cmdVal)) needsWait = True elif cmdOpCode == 'mute': self._player.set_mute(bool(cmdVal)) needsWait = True elif cmdOpCode == 'play': self._player.set_mute(False) self._player.set_pause(False) elif cmdOpCode == 'pause': self._player.set_mute(True) self._player.set_pause(True) elif cmdOpCode == 'seek': seekToPts, seekRel = cmdVal self._player.seek( seekToPts, relative=seekRel, accurate=True) time.sleep(0.1) # long wait for seeking elif cmdOpCode == 'stop': # stop playback, return to start self._player.set_mute(True) self._player.seek( -1.0, # seek to beginning relative=False, accurate=True) self._player.set_pause(True) loopCount = 0 # reset loop count time.sleep(0.1) elif cmdOpCode == 'shutdown': # shutdown the player mustShutdown = True # signal to the main thread that the command has been processed if not mustShutdown: self._cmdQueue.task_done() else: break # if the command needs some additional processing time if needsWait: time.sleep(frameInterval) # close the player when the thread exits self._player.close_player() self._cmdQueue.task_done() @property def isFinished(self): """Is the movie done playing (`bool`)? This is `True` if the movie stream is at EOF. """ return self._isFinished @property def isIdling(self): """Is the movie reader thread "idling" (`bool`)? If `True`, the movie is finished playing and no frames are being polled from FFMPEG. """ return self._isIdling @property def isReady(self): """`True` if the stream reader is ready (`bool`). """ return not self._warmUpLock.locked() def begin(self): """Call this to start the thread and begin reading frames. This will block until we get a valid frame. """ self.start() # start the thread, will begin decoding frames # hold until the lock is released when the thread gets a valid frame # this will prevent the main loop for executing until we're ready self._warmUpLock.acquire(blocking=True) def play(self): """Start playing the video from the stream. """ cmd = ('play', None) self._cmdQueue.put(cmd) self._cmdQueue.join() def pause(self): """Stop recording frames to the output file. """ cmd = ('pause', None) self._cmdQueue.put(cmd) self._cmdQueue.join() def seek(self, pts, relative=False): """Seek to a position in the video. """ cmd = ('seek', (pts, relative)) self._cmdQueue.put(cmd) self._cmdQueue.join() def stop(self): """Stop playback, reset the movie to the beginning. """ cmd = ('stop', None) self._cmdQueue.put(cmd) self._cmdQueue.join() def shutdown(self): """Shutdown the movie reader thread. """ cmd = ('shutdown', None) self._cmdQueue.put(cmd) self._cmdQueue.join() def isDone(self): """Check if the video is done playing. Returns ------- bool Is the video done? """ return not self.is_alive() def getVolume(self): """Get the current volume level.""" if self._player is not None: return self._player.get_volume() return 0.0 def setVolume(self, volume): """Set the volume for the video. Parameters ---------- volume : float New volume level, ranging between 0 and 1. """ cmd = ('volume', volume) self._cmdQueue.put(cmd) self._cmdQueue.join() def setMute(self, mute): """Set the volume for the video. Parameters ---------- mute : bool Mute state. If `True`, audio will be muted. """ cmd = ('mute', mute) self._cmdQueue.put(cmd) self._cmdQueue.join() def getRecentFrame(self): """Get the most recent frame data from the feed (`tuple`). Returns ------- tuple or None Frame data formatted as `(metadata, frameData, val)`. The `metadata` is a `dict`, `frameData` is a `tuple` with format (`colorData`, `pts`) and `val` is a `str` returned by the `MediaPlayer.get_frame()` method. Returns `None` if there is no frame data. """ if self._frameQueue.empty(): return None # hold only last frame and return that instead of None? return self._frameQueue.get() class FFPyPlayer(BaseMoviePlayer): """Interface class for the FFPyPlayer library for use with `MovieStim`. This class also serves as the reference implementation for classes which interface with movie codec libraries for use with `MovieStim`. Creating new player classes which closely replicate the behaviour of this one should allow them to smoothly plug into `MovieStim`. """ _movieLib = 'ffpyplayer' def __init__(self, parent): self._filename = u"" self.parent = parent # handle to `ffpyplayer` self._handle = None # thread for reading frames asynchronously self._tStream = None # data from stream thread self._lastFrame = NULL_MOVIE_FRAME_INFO self._frameIndex = -1 self._loopCount = 0 self._metadata = None # metadata from the stream self._lastPlayerOpts = DEFAULT_FF_OPTS.copy() self._lastPlayerOpts['out_fmt'] = 'bgra' # options from the parent if self.parent.loop: # infinite loop self._lastPlayerOpts['loop'] = 0 else: self._lastPlayerOpts['loop'] = 1 # play once if hasattr(self.parent, '_noAudio'): self._lastPlayerOpts['an'] = self.parent._noAudio # status flags self._status = NOT_STARTED def start(self, log=True): """Initialize and start the decoder. This method will return when a valid frame is made available. """ # clear queued data from previous streams self._lastFrame = None self._frameIndex = -1 # open the media player handle = MediaPlayer(self._filename, ff_opts=self._lastPlayerOpts) handle.set_pause(True) # Pull the first frame to get metadata. NB - `_enqueueFrame` should be # able to do this but the logic in there depends on having access to # metadata first. That may be rewritten at some point to reduce all of # this to just a single `_enqeueFrame` call. # self._status = NOT_STARTED # hand off the player interface to the thread self._tStream = MovieStreamThreadFFPyPlayer(handle) self._tStream.begin() # make sure we have metadata self.update() def load(self, pathToMovie): """Load a movie file from disk. Parameters ---------- pathToMovie : str Path to movie file, stream (URI) or camera. Must be a format that FFMPEG supports. """ # set the file path self._filename = pathToString(pathToMovie) # Check if the player is already started. Close it and load a new # instance if so. if self._tStream is not None: # player already started # make sure it's the correct type # if not isinstance(self._handle, MediaPlayer): # raise TypeError( # 'Incorrect type for `FFMovieStim._player`, expected ' # '`ffpyplayer.player.MediaPlayer`. Got type `{}` ' # 'instead.'.format(type(self._handle).__name__)) # close the player and reset self.unload() # self._selectWindow(self.win) # free buffers here !!! self.start() self._status = NOT_STARTED def unload(self): """Unload the video stream and reset. """ self._tStream.shutdown() self._tStream.join() # wait until thread exits self._tStream = None # if self._handle is not None: # self._handle.close_player() # self._handle = None # reset self._filename = u"" self._frameIndex = -1 self._handle = None # reset # @property # def handle(self): # """Handle to the `MediaPlayer` object exposed by FFPyPlayer. If `None`, # no media player object has yet been initialized. # """ # return self._handle @property def isLoaded(self): return self._tStream is not None @property def metadata(self): """Most recent metadata (`MovieMetadata`). """ return self.getMetadata() def getMetadata(self): """Get metadata from the movie stream. Returns ------- MovieMetadata Movie metadata object. If no movie is loaded, `NULL_MOVIE_METADATA` is returned. At a minimum, fields `duration`, `size`, and `frameRate` are populated if a valid movie has been previously loaded. """ self._assertMediaPlayer() metadata = self._metadata # write metadata to the fields of a `MovieMetadata` object toReturn = MovieMetadata( mediaPath=self._filename, title=metadata['title'], duration=metadata['duration'], frameRate=metadata['frame_rate'], size=metadata['src_vid_size'], pixelFormat=metadata['src_pix_fmt'], movieLib=self._movieLib, userData=None ) return toReturn def _assertMediaPlayer(self): """Ensure the media player instance is available. Raises a `RuntimeError` if no movie is loaded. """ if self._tStream is not None: return # nop if we're good raise RuntimeError( "Calling this class method requires a successful call to " "`load` first.") @property def status(self): """Player status flag (`int`). """ return self._status @property def isPlaying(self): """`True` if the video is presently playing (`bool`).""" # Status flags as properties are pretty useful for users since they are # self documenting and prevent the user from touching the status flag # attribute directly. # return self.status == PLAYING @property def isNotStarted(self): """`True` if the video has not be started yet (`bool`). This status is given after a video is loaded and play has yet to be called. """ return self.status == NOT_STARTED @property def isStopped(self): """`True` if the movie has been stopped. """ return self.status == STOPPED @property def isPaused(self): """`True` if the movie has been paused. """ self._assertMediaPlayer() return self._status == PAUSED @property def isFinished(self): """`True` if the video is finished (`bool`). """ # why is this the same as STOPPED? return self._status == FINISHED def play(self, log=False): """Start or continue a paused movie from current position. Parameters ---------- log : bool Log the play event. Returns ------- int or None Frame index playback started at. Should always be `0` if starting at the beginning of the video. Returns `None` if the player has not been initialized. """ self._assertMediaPlayer() self._tStream.play() self._status = PLAYING def stop(self, log=False): """Stop the current point in the movie (sound will stop, current frame will not advance). Once stopped the movie cannot be restarted - it must be loaded again. Use `pause()` instead if you may need to restart the movie. Parameters ---------- log : bool Log the stop event. """ self._tStream.stop() self._status = STOPPED def pause(self, log=False): """Pause the current point in the movie. The image of the last frame will persist on-screen until `play()` or `stop()` are called. Parameters ---------- log : bool Log this event. """ self._assertMediaPlayer() self._tStream.pause() self._enqueueFrame() self._status = PAUSED return False def seek(self, timestamp, log=False): """Seek to a particular timestamp in the movie. Parameters ---------- timestamp : float Time in seconds. log : bool Log the seek event. """ self._assertMediaPlayer() self._tStream.seek(timestamp, relative=False) self._enqueueFrame() def rewind(self, seconds=5, log=False): """Rewind the video. Parameters ---------- seconds : float Time in seconds to rewind from the current position. Default is 5 seconds. log : bool Log this event. Returns ------- float Timestamp after rewinding the video. """ self._assertMediaPlayer() self._tStream.seek(-seconds, relative=True) def fastForward(self, seconds=5, log=False): """Fast-forward the video. Parameters ---------- seconds : float Time in seconds to fast forward from the current position. Default is 5 seconds. log : bool Log this event. """ self._assertMediaPlayer() self._tStream.seek(seconds, relative=True) def replay(self, autoStart=False, log=False): """Replay the movie from the beginning. Parameters ---------- autoStart : bool Start playback immediately. If `False`, you must call `play()` afterwards to initiate playback. log : bool Log this event. """ self._assertMediaPlayer() self.pause(log=log) self.seek(0.0, log=log) if autoStart: self.play(log=log) def restart(self, autoStart=True, log=False): """Restart the movie from the beginning. Parameters ---------- autoStart : bool Start playback immediately. If `False`, you must call `play()` afterwards to initiate playback. log : bool Log this event. Notes ----- * This tears down the current media player instance and creates a new one. Similar to calling `stop()` and `loadMovie()`. Use `seek(0.0)` if you would like to restart the movie without reloading. """ lastMovieFile = self._filename self.load(lastMovieFile) # will play if auto start # -------------------------------------------------------------------------- # Audio stream control methods # # @property # def muted(self): # """`True` if the stream audio is muted (`bool`). # """ # return self._handle.get_mute() # thread-safe? # # @muted.setter # def muted(self, value): # self._tStream.setMute(value) def volumeUp(self, amount): """Increase the volume by a fixed amount. Parameters ---------- amount : float or int Amount to increase the volume relative to the current volume. """ self._assertMediaPlayer() # get the current volume from the player self.volume = self.volume + amount return self.volume def volumeDown(self, amount): """Decrease the volume by a fixed amount. Parameters ---------- amount : float or int Amount to decrease the volume relative to the current volume. """ self._assertMediaPlayer() # get the current volume from the player self.volume = self.volume - amount return self.volume @property def volume(self): """Volume for the audio track for this movie (`int` or `float`). """ self._assertMediaPlayer() return self._tStream.getVolume() @volume.setter def volume(self, value): self._assertMediaPlayer() self._tStream.setVolume(max(min(value, 1.0), 0.0)) @property def loopCount(self): """Number of loops completed since playback started (`int`). This value is reset when either `stop` or `loadMovie` is called. """ return self._loopCount # -------------------------------------------------------------------------- # Timing related methods # # The methods here are used to handle timing, such as converting between # movie and experiment timestamps. # @property def pts(self): """Presentation timestamp for the current movie frame in seconds (`float`). The value for this either comes from the decoder or some other time source. This should be synchronized to the start of the audio track. A value of `-1.0` is invalid. """ if self._tStream is None: return -1.0 return self._lastFrame.absTime def getStartAbsTime(self): """Get the absolute experiment time in seconds the movie starts at (`float`). This value reflects the time which the movie would have started if played continuously from the start. Seeking and pausing the movie causes this value to change. Returns ------- float Start time of the movie in absolute experiment time. """ self._assertMediaPlayer() return getTime() - self._lastFrame.absTime def movieToAbsTime(self, movieTime): """Convert a movie timestamp to absolute experiment timestamp. Parameters ---------- movieTime : float Movie timestamp to convert to absolute experiment time. Returns ------- float Timestamp in experiment time which is coincident with the provided `movieTime` timestamp. The returned value should usually be precise down to about five decimal places. """ self._assertMediaPlayer() # type checks on parameters if not isinstance(movieTime, float): raise TypeError( "Value for parameter `movieTime` must have type `float` or " "`int`.") return self.getStartAbsTime() + movieTime def absToMovieTime(self, absTime): """Convert absolute experiment timestamp to a movie timestamp. Parameters ---------- absTime : float Absolute experiment time to convert to movie time. Returns ------- float Movie time referenced to absolute experiment time. If the value is negative then provided `absTime` happens before the beginning of the movie from the current time stamp. The returned value should usually be precise down to about five decimal places. """ self._assertMediaPlayer() # type checks on parameters if not isinstance(absTime, float): raise TypeError( "Value for parameter `absTime` must have type `float` or " "`int`.") return absTime - self.getStartAbsTime() def movieTimeFromFrameIndex(self, frameIdx): """Get the movie time a specific a frame with a given index is scheduled to be presented. This is used to handle logic for seeking through a video feed (if permitted by the player). Parameters ---------- frameIdx : int Frame index. Negative values are accepted but they will return negative timestamps. """ self._assertMediaPlayer() return frameIdx * self._metadata.frameInterval def frameIndexFromMovieTime(self, movieTime): """Get the frame index of a given movie time. Parameters ---------- movieTime : float Timestamp in movie time to convert to a frame index. Returns ------- int Frame index that should be presented at the specified movie time. """ self._assertMediaPlayer() return math.floor(movieTime / self._metadata.frameInterval) @property def isSeekable(self): """Is seeking allowed for the video stream (`bool`)? If `False` then `frameIndex` will increase monotonically. """ return False # fixed for now @property def frameInterval(self): """Duration a single frame is to be presented in seconds (`float`). This is derived from the framerate information in the metadata. If not movie is loaded, the returned value will be invalid. """ return self.metadata.frameInterval @property def frameIndex(self): """Current frame index (`int`). Index of the current frame in the stream. If playing from a file or any other seekable source, this value may not increase monotonically with time. A value of `-1` is invalid, meaning either the video is not started or there is some issue with the stream. """ return self._lastFrame.frameIndex def getPercentageComplete(self): """Provides a value between 0.0 and 100.0, indicating the amount of the movie that has been already played (`float`). """ duration = self.metadata.duration return (self.pts / duration) * 100.0 # -------------------------------------------------------------------------- # Methods for getting video frames from the encoder # def _enqueueFrame(self): """Grab the latest frame from the stream. Returns ------- bool `True` if a frame has been enqueued. Returns `False` if the camera is not ready or if the stream was closed. """ self._assertMediaPlayer() # If the queue is empty, the decoder thread has not yielded a new frame # since the last call. enqueuedFrame = self._tStream.getRecentFrame() if enqueuedFrame is None: return False # Unpack the data we got back ... # Note - Bit messy here, we should just hold onto the `enqueuedFrame` # instance and reference its fields from properties. Keeping like this # for now. frameImage = enqueuedFrame.frameImage streamStatus = enqueuedFrame.streamStatus self._metadata = enqueuedFrame.metadata self._frameIndex = streamStatus.frameIndex self._loopCount = streamStatus.loopCount # status information self._streamTime = streamStatus.streamTime # stream time for the camera # if we have a new frame, update the frame information videoBuffer = frameImage.to_memoryview()[0].memview videoFrameArray = np.frombuffer(videoBuffer, dtype=np.uint8) # provide the last frame self._lastFrame = MovieFrame( frameIndex=self._frameIndex, absTime=self._streamTime, displayTime=self.metadata.frameInterval, size=frameImage.get_size(), colorData=videoFrameArray, audioChannels=0, # not populated yet ... audioSamples=None, metadata=self.metadata, movieLib=u'ffpyplayer', userData=None, keepAlive=frameImage) return True def update(self): """Update this player. This get the latest data from the video stream and updates the player accordingly. This should be called at a higher frequency than the frame rate of the movie to avoid frame skips. """ self._assertMediaPlayer() # check if the stream reader thread is present and alive, if not the # movie is finished self._enqueueFrame() if self._tStream.isFinished: # are we done? self._status = FINISHED def getMovieFrame(self): """Get the movie frame scheduled to be displayed at the current time. Returns ------- `~psychopy.visual.movies.frame.MovieFrame` Current movie frame. """ self.update() return self._lastFrame def __del__(self): """Cleanup when unloading. """ global _evtCleanUpMovieEvent if hasattr(self, '_tStream'): if self._tStream is not None: if not _evtCleanUpMovieEvent.is_set(): self._tStream.shutdown() self._tStream.join() if __name__ == "__main__": pass
45,899
Python
.py
1,123
30.816563
81
0.586287
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,767
_base.py
psychopy_psychopy/psychopy/visual/movies/players/_base.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Base class for player interfaces. """ # 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__ = ["BaseMoviePlayer"] from abc import ABC, abstractmethod class BaseMoviePlayer(ABC): """Base class for all movie players. This class specifies a standardized interface for movie player APIs. All movie player interface classes must be subclasses of `BaseMoviePlayer` and implement (override) the abstract attributes associated with it. Furthermore, methods of the subclass must be conformant to the behaviors outlined in documentation strings of each. """ _movieLib = u'' # -------------------------------------------------------------------------- # Movie loading and information # @abstractmethod def load(self, pathToMovie): """Load the movie stream. This must be called prior to using any playback control method. The property `isLoaded` should return `True` afterwards. Parameters ---------- pathToMovie : str Path to movie file. Must be a format that FFMPEG supports. """ pass @abstractmethod def unload(self): """Unload the movie stream. Similar to `stop()` but can contain additional cleanup routines. The value of `isLoaded` should be set to `False` after calling this. """ pass @property @abstractmethod def isLoaded(self): """`True` if a movie is loaded and playback controls are available.""" pass @abstractmethod def getMetadata(self): """Get metadata from the movie stream. This is only valid after `load()` has been called. Do not make any calls to `_setupBuffers()` until after the video stream has been loaded since the metadata is invalid until so for most streaming movie player APIs. Returns ------- MovieMetadata Movie metadata object. If no movie is loaded, return a `NULL_MOVIE_METADATA` object instead of `None`. At a minimum, ensure that fields `duration`, `size`, and `frameRate` are populated if a valid movie is loaded. """ pass @abstractmethod def _assertMediaPlayer(self): """Assert that a video is loaded and playback controls are available. This method must raise an error if the media player is not yet ready. Usually a `RuntimeError` will suffice. Any method which relies on the media player being open should make a call to this method prior to doing anything:: def play(self): self._assertMediaPlayer() # requires a stream to be opened # playback logic here ... """ pass # -------------------------------------------------------------------------- # Playback controls # @property @abstractmethod def status(self): """Playback status (`int`). Possible values are symbolic constants `PLAYING`, `FINISHED`, `NOT_STARTED`, `PAUSED`, `PLAYING` or `STOPPED`. """ pass @property @abstractmethod def isPlaying(self): """`True` if the video is presently playing (`bool`).""" pass @property @abstractmethod def isNotStarted(self): """`True` if the video has not be started yet (`bool`). This status is given after a video is loaded and play has yet to be called.""" pass @property @abstractmethod def isStopped(self): """`True` if the video is stopped (`bool`).""" pass @property @abstractmethod def isPaused(self): """`True` if the video is presently paused (`bool`).""" pass @property @abstractmethod def isFinished(self): """`True` if the video is finished (`bool`).""" pass @property @abstractmethod def frameIndex(self): """Index of the current movie frame (`int`).""" pass @abstractmethod def start(self, log=True): """Start decoding. Calling this method should begin decoding frames for the stream, making them available when requested. This is similar to `play()` but doesn't necessarily mean that the video is to be displayed, just that the decoder should start queuing frames up. """ pass @abstractmethod def play(self, log=True): """Begin playback. If playback is already started, this method should do nothing. If `pause()` was called previously, calling this method should resume playback. This should cause the decoder to start processing frames and making them available when `getMovieFrame` is called. Parameters ---------- log : bool Log the play event. Returns ------- int or None Frame index playback started at. Should always be `0` if starting at the beginning of the video. Returns `None` if the player has not been initialized. """ pass @abstractmethod def stop(self, log=True): """Stop playback. This should also unload the video (i.e. close the player stream). The return value of `getMetadata()` should be `NULL_MOVIE_METADATA`. Successive calls to this method should do nothing. The value returned by `isLoaded` should be `False`. """ pass @abstractmethod def pause(self, log=True): """Pause the video. Calling this should result in the video freezing on the current frame. The stream should not be closed during pause. Calling `play()` is the only way to unpause/resume the video. Parameters ---------- log : bool Log the pause event. """ pass @abstractmethod def replay(self, autoStart=True, log=True): """Replay the video. This is a convenience method to restart the stream. This is equivalent to calling `stop()`, reloading the current video, and calling `play()`. Parameters ---------- autoStart : bool Start playback immediately. If `False`, you must call `play()` afterwards to initiate playback. log : bool Log this event. """ pass @abstractmethod def seek(self, timestamp, log=True): """Skip to some position in the video. If playing, the video should advance to the new frame and continue playing. If paused, the video should advance to the required frame and the frame should appear static. Parameters ---------- timestamp : float Time in seconds. log : bool Log this event. """ pass @abstractmethod def rewind(self, seconds=5, log=True): """Rewind the movie. Parameters ---------- seconds : float Time in seconds to rewind from the current position. Default is 5 seconds. log : bool Log this event. Returns ------- float Timestamp after rewinding the video. """ pass @abstractmethod def fastForward(self, seconds=5, log=True): """Fast forward. Parameters ---------- seconds : float Time in seconds to fast forward from the current position. Default is 5 seconds. log : bool Log this event. Returns ------- float Timestamp at new position after fast forwarding the video. """ pass @abstractmethod def volumeUp(self, amount): """Increase the volume by a fixed amount. Parameters ---------- amount : float or int Amount to increase the volume relative to the current volume. """ pass @abstractmethod def volumeDown(self, amount): """Decrease the volume by a fixed amount. Parameters ---------- amount : float or int Amount to decrease the volume relative to the current volume. """ pass @property @abstractmethod def volume(self): """Volume for the audio track for this movie (`int` or `float`). """ pass @property @abstractmethod def isSeekable(self): """Is seeking allowed for the video stream (`bool`)? If `False` then `frameIndex` will increase monotonically. """ pass # -------------------------------------------------------------------------- # Video display and timing # @property @abstractmethod def pts(self): """Current movie time in seconds (`float`). The value for this either comes from the decoder or some other time source. This should be synchronized to the audio track. """ pass @property @abstractmethod def frameInterval(self): """Duration a single frame is to be presented in seconds (`float`). This is derived from the framerate information in the metadata. """ pass @abstractmethod def getMovieFrame(self): """Get the most recent movie frame from the player. Returns ------- `~psychopy.visual.movies.frame.MovieFrame` Current movie frame. """ pass if __name__ == "__main__": pass
9,782
Python
.py
282
26.460993
80
0.595031
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,768
textbox2.py
psychopy_psychopy/psychopy/visual/textbox2/textbox2.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # # FreeType high-level python API - Copyright 2011-2015 Nicolas P. Rougier # Distributed under the terms of the new BSD license. # # ----------------------------------------------------------------------------- r""" TextBox2 provides a combination of features from TextStim and TextBox and then some more added: - fast like TextBox (TextStim is pyglet-based and slow) - provides for fonts that aren't monospaced (unlike TextBox) - adds additional options to use <b>bold<\b>, <i>italic<\i>, <c=#ffffff>color</c> tags in text """ from ast import literal_eval import numpy as np from arabic_reshaper import ArabicReshaper from pyglet import gl from bidi import algorithm as bidi import re from ..aperture import Aperture from ..basevisual import ( BaseVisualStim, ColorMixin, ContainerMixin, WindowMixin, DraggingMixin ) from psychopy.tools.attributetools import attributeSetter, setAttribute from psychopy.tools import mathtools as mt from psychopy.colors import Color from psychopy.tools.fontmanager import FontManager, GLFont from .. import shaders from ..rect import Rect from ... import core, alerts, layout from psychopy.tools.linebreak import get_breakable_points, break_units allFonts = FontManager() # compile global shader programs later (when we're certain a GL context exists) rgbShader = None alphaShader = None showWhiteSpace = False codes = {'BOLD_START': u'\uE100', 'BOLD_END': u'\uE101', 'ITAL_START': u'\uE102', 'ITAL_END': u'\uE103', 'COLOR_START': u'\uE104', 'COLOR_END': u'\uE105'} # Compile regex pattern for color matching once re_color_pattern = re.compile('<c=[^>]*>') _colorCache = {} wordBreaks = " -\n" # what about ",."? END_OF_THIS_LINE = 983349843 # Setting debug to True will make the sub-elements on TextBox2 to be outlined in red, making it easier to determine their position debug = False # If text is ". " we don't want to start next line with single space? class TextBox2(BaseVisualStim, DraggingMixin, ContainerMixin, ColorMixin): def __init__(self, win, text, font="Open Sans", pos=(0, 0), units=None, letterHeight=None, ori=0, size=None, color=(1.0, 1.0, 1.0), colorSpace='rgb', fillColor=None, fillColorSpace=None, borderWidth=2, borderColor=None, borderColorSpace=None, contrast=1, opacity=None, bold=False, italic=False, placeholder="Type here...", lineSpacing=1.0, letterSpacing=None, padding=None, # gap between box and text speechPoint=None, anchor='center', alignment='left', flipHoriz=False, flipVert=False, languageStyle="LTR", editable=False, overflow="visible", lineBreaking='default', draggable=False, name='', autoLog=None, autoDraw=False, depth=0, onTextCallback=None): """ Parameters ---------- win text font pos units letterHeight size : Specifying None gets the default size for this type of unit. Specifying [None, None] gets a TextBox that's expandable in both dimensions. Specifying [0.75, None] gets a textbox that expands in the length but fixed at 0.75 units in the width color colorSpace contrast opacity bold italic lineSpacing padding speechPoint : list, tuple, np.ndarray or None Location of the end of a speech bubble tail on the textbox, in the same units as this textbox. If the point sits within the textbox, the tail will be inverted. Use `None` for no tail. anchor alignment fillColor borderWidth borderColor flipHoriz flipVert editable lineBreaking: Specifying 'default', text will be broken at a set of characters defined in the module. Specifying 'uax14', text will be broken in accordance with UAX#14 (Unicode Line Breaking Algorithm). draggable : bool Can this stimulus be dragged by a mouse click? name autoLog """ BaseVisualStim.__init__(self, win, units=units, name=name) self.depth = depth self.win = win self.colorSpace = colorSpace ColorMixin.foreColor.fset(self, color) # Have to call the superclass directly on init as text has not been set self.onTextCallback = onTextCallback self.draggable = draggable # Box around the whole textbox - drawn self.box = Rect( win, units=self.units, pos=(0, 0), size=(0, 0), # set later by self.size and self.pos colorSpace=colorSpace, lineColor=borderColor, fillColor=fillColor, lineWidth=borderWidth, opacity=self.opacity, autoLog=False, ) # Aperture & scrollbar self.container = None self.scrollbar = None # Box around just the content area, excluding padding - not drawn self.contentBox = Rect( win, units=self.units, pos=(0, 0), size=(0, 0), # set later by self.size and self.pos colorSpace=colorSpace, lineColor='red', fillColor=None, lineWidth=1, opacity=int(debug), autoLog=False ) # Box around current content, wrapped tight - not drawn self.boundingBox = Rect( win, units='pix', pos=(0, 0), size=(0, 0), # set later by self.size and self.pos colorSpace=colorSpace, lineColor='blue', fillColor=None, lineWidth=1, opacity=int(debug), autoLog=False ) # Sizing params self.letterHeight = letterHeight self.padding = padding self.size = size self.pos = pos # self._pixLetterHeight helps get font size right but not final layout if 'deg' in self.units: # treat deg, degFlat or degFlatPos the same scaleUnits = 'deg' # scale units are just for font resolution else: scaleUnits = self.units self._pixelScaling = self.letterHeightPix / self.letterHeight self.bold = bold self.italic = italic if lineSpacing is None: lineSpacing = 1.0 self.lineSpacing = lineSpacing self.glFont = None # will be set by the self.font attribute setter self.font = font self.letterSpacing = letterSpacing # If font not found, default to Open Sans Regular and raise alert if not self.glFont: alerts.alert(4325, self, { 'font': font, 'weight': 'bold' if self.bold is True else 'regular' if self.bold is False else self.bold, 'style': 'italic' if self.italic else '', 'name': self.name}) self.bold = False self.italic = False self.font = "Open Sans" # once font is set up we can set the shader (depends on rgb/a of font) if self.glFont.atlas.format == 'rgb': global rgbShader self.shader = rgbShader = shaders.Shader( shaders.vertSimple, shaders.fragTextBox2) else: global alphaShader self.shader = alphaShader = shaders.Shader( shaders.vertSimple, shaders.fragTextBox2alpha) self._needVertexUpdate = False # this will be set True during layout # standard stimulus params self.pos = pos self.ori = 0.0 # used at render time self._lines = None # np.array the line numbers for each char self._colors = None self._styles = None self.flipHoriz = flipHoriz self.flipVert = flipVert # params about positioning (after layout has occurred) self.anchor = anchor # 'center', 'top_left', 'bottom-center'... self.alignment = alignment # box border and fill self.borderWidth = borderWidth self.borderColor = borderColor self.fillColor = fillColor self.contrast = contrast self.opacity = opacity # set linebraking option if lineBreaking not in ('default', 'uax14'): raise ValueError("Unknown lineBreaking option ({}) is" "specified.".format(lineBreaking)) self._lineBreaking = lineBreaking # then layout the text (setting text triggers _layout()) self.languageStyle = languageStyle self._text = '' self.text = self.startText = text if text is not None else "" # now that we have text, set orientation self.ori = ori # Initialise arabic reshaper arabic_config = {'delete_harakat': False, # if present, retain any diacritics 'shift_harakat_position': False} # shift by 1 to be compatible with the bidi algorithm self.arabicReshaper = ArabicReshaper(configuration=arabic_config) # caret self.editable = editable self.overflow = overflow self.caret = Caret(self, color=self.color, width=2) # tail self.speechPoint = speechPoint # Placeholder text (don't create if this textbox IS the placeholder) if not isinstance(self, PlaceholderText): self._placeholder = PlaceholderText(self, placeholder) self.autoDraw = autoDraw self.autoLog = autoLog def __copy__(self): return TextBox2( self.win, self.text, self.font, pos=self.pos, units=self.units, letterHeight=self.letterHeight, size=self.size, color=self.color, colorSpace=self.colorSpace, fillColor=self.fillColor, borderWidth=self.borderWidth, borderColor=self.borderColor, contrast=self.contrast, opacity=self.opacity, bold=self.bold, italic=self.italic, lineSpacing=self.lineSpacing, padding=self.padding, # gap between box and text anchor=self.anchor, alignment=self.alignment, flipHoriz=self.flipHoriz, flipVert=self.flipVert, editable=self.editable, lineBreaking=self._lineBreaking, name=self.name, autoLog=self.autoLog, onTextCallback=self.onTextCallback ) @property def editable(self): """Determines whether or not the TextBox2 instance can receive typed text""" return self._editable @editable.setter def editable(self, editable): self._editable = editable if editable is False: if self.win: self.win.removeEditable(self) if editable is True: if self.win: self.win.addEditable(self) @property def palette(self): """Describes the current visual properties of the TextBox in a dict""" self._palette = { False: { 'lineColor': self._borderColor, 'lineWidth': self.borderWidth, 'fillColor': self._fillColor }, True: { 'lineColor': self._borderColor-0.1, 'lineWidth': self.borderWidth+1, 'fillColor': self._fillColor+0.1 } } return self._palette[self.hasFocus] @palette.setter def palette(self, value): self._palette = { False: value, True: value } @property def pallette(self): """ Disambiguation for palette. """ return self.palette @pallette.setter def pallette(self, value): self.palette = value @property def foreColor(self): return ColorMixin.foreColor.fget(self) @foreColor.setter def foreColor(self, value): ColorMixin.foreColor.fset(self, value) self._layout() if hasattr(self, "foreColor") and hasattr(self, 'caret'): self.caret.color = self._foreColor @attributeSetter def font(self, fontName): if isinstance(fontName, GLFont): self.glFont = fontName self.__dict__['font'] = fontName.name else: self.__dict__['font'] = fontName self.glFont = allFonts.getFont( fontName, size=self.letterHeightPix, bold=self.bold, italic=self.italic, lineSpacing=self.lineSpacing) @attributeSetter def overflow(self, value): if 'overflow' in self.__dict__ and value == self.__dict__['overflow']: return self.__dict__['overflow'] = value self.container = None self.scrollbar = None if value in ("hidden", "scroll"): # If needed, create Aperture self.container = Aperture( self.win, inverted=False, size=self.contentBox.size, pos=self.contentBox.pos, anchor=self.anchor, shape='square', units=self.units, autoLog=False ) self.container.disable() if value in ("scroll",): # If needed, create Slider from ..slider import Slider # Slider contains textboxes, so only import now self.scrollbar = Slider( self.win, ticks=(-1, 1), labels=None, startValue=1, pos=self.pos + (self.size[0] * 1.05 / 2, 0), size=self.size * (0.05, 1 / 1.2), units=self.units, style='scrollbar', granularity=0, labelColor=None, markerColor=self.color, lineColor=self.fillColor, colorSpace=self.colorSpace, opacity=self.opacity, autoLog=False ) @property def units(self): return WindowMixin.units.fget(self) @units.setter def units(self, value): if hasattr(self, "_placeholder"): self._placeholder.units = value WindowMixin.units.fset(self, value) if hasattr(self, "box"): self.box.units = value if hasattr(self, "contentBox"): self.contentBox.units = value if hasattr(self, "caret"): self.caret.units = value @property def size(self): """The (requested) size of the TextBox (w,h) in whatever units the stimulus is using This determines the outer extent of the area. If the width is set to None then the text will continue extending and not wrap. If the height is set to None then the text will continue to grow downwards as needed. """ return WindowMixin.size.fget(self) @size.setter def size(self, value): if hasattr(self, "_placeholder"): self._placeholder.size = value WindowMixin.size.fset(self, value) if hasattr(self, "box"): self.box.size = self._size if hasattr(self, "contentBox"): self.contentBox.size = self._size - self._padding * 2 # Refresh pos self.pos = self.pos @property def pos(self): """The position of the center of the TextBox in the stimulus :ref:`units <units>` `value` should be an :ref:`x,y-pair <attrib-xy>`. :ref:`Operations <attrib-operations>` are also supported. Example:: stim.pos = (0.5, 0) # Set slightly to the right of center stim.pos += (0.5, -1) # Increment pos rightwards and upwards. Is now (1.0, -1.0) stim.pos *= 0.2 # Move stim towards the center. Is now (0.2, -0.2) Tip: If you need the position of stim in pixels, you can obtain it like this: myTextbox._pos.pix """ return WindowMixin.pos.fget(self) @pos.setter def pos(self, value): WindowMixin.pos.fset(self, value) if hasattr(self, "box"): self.box.size = self._pos if hasattr(self, "contentBox"): # set content box pos with offset for anchor (accounting for orientation) self.contentBox.pos = self.pos + np.dot(self.size * self.box._vertices.anchorAdjust, self._rotationMatrix) self.contentBox._needVertexUpdate = True if hasattr(self, "_placeholder"): self._placeholder.pos = self._pos # Set caret pos again so it recalculates its vertices if hasattr(self, "caret"): self.caret.index = self.caret.index if hasattr(self, "_text"): self._layout() self._needVertexUpdate = True @property def vertices(self): return WindowMixin.vertices.fget(self) @vertices.setter def vertices(self, value): # If None, use defaut if value is None: value = [ [0.5, -0.5], [-0.5, -0.5], [-0.5, 0.5], [0.5, 0.5], ] # Create Vertices object self._vertices = layout.Vertices(value, obj=self.contentBox, flip=self.flip) @attributeSetter def speechPoint(self, value): self.__dict__['speechPoint'] = value # Match box size to own size self.box.size = self.size # No tail if value is None if value is None: self.box.vertices = [ [0.5, -0.5], [-0.5, -0.5], [-0.5, 0.5], [0.5, 0.5], ] return # Normalize point to vertex units _point = layout.Vertices( [[1, 1]], obj=self ) _point.setas([value], self.units) point = _point.base[0] # Square with snap points and tail point verts = [ # Top right -> Bottom right [0.5, 0.5], [0.5, 0.3], [0.5, 0.1], [0.5, -0.1], [0.5, -0.3], # Bottom right -> Bottom left [0.5, -0.5], [0.3, -0.5], [0.1, -0.5], [-0.1, -0.5], [-0.3, -0.5], # Bottom left -> Top left [-0.5, -0.5], [-0.5, -0.3], [-0.5, -0.1], [-0.5, 0.1], [-0.5, 0.3], # Top left -> Top right [-0.5, 0.5], [-0.3, 0.5], [-0.1, 0.5], [0.1, 0.5], [0.3, 0.5], # Tail point ] # Sort clockwise so tail point moves to correct place in vertices order verts = mt.sortClockwise(verts) verts.reverse() # Assign vertices self.box.vertices = verts def setSpeechPoint(self, value, log=None): setAttribute(self, 'speechPoint', value, log) @property def padding(self): if hasattr(self, "_padding"): return getattr(self._padding, self.units) @padding.setter def padding(self, value): # Substitute None for a default value if value is None: value = self.letterHeight / 2 # Create a Size object to handle padding self._padding = layout.Size(value, self.units, self.win) # Update size of bounding box if hasattr(self, "contentBox") and hasattr(self, "_size"): self.contentBox.size = self._size - self._padding * 2 @property def letterHeight(self): if hasattr(self, "_letterHeight"): return getattr(self._letterHeight, self.units)[1] @letterHeight.setter def letterHeight(self, value): # Cascade to placeholder if hasattr(self, "_placeholder"): self._placeholder.letterHeight = value if isinstance(value, layout.Vector): # If given a Vector, use it directly self._letterHeight = value elif isinstance(value, (int, float)): # If given an integer, convert it to a 2D Vector with width 0 self._letterHeight = layout.Size([0, value], units=self.units, win=self.win) elif value is None: # If None, use default (20px) self._letterHeight = layout.Size([0, 20], units='pix', win=self.win) elif isinstance(value, (list, tuple, np.ndarray)): # If given an array, convert it to a Vector self._letterHeight = layout.Size(value, units=self.units, win=self.win) def setLetterHeight(self, value, log=None): setAttribute( self, "letterHeight", value=value, log=log ) @property def letterHeightPix(self): """ Convenience function to get self._letterHeight.pix and be guaranteed a return that is a single integer """ return self._letterHeight.pix[1] @attributeSetter def letterSpacing(self, value): """ Distance between letters, relative to the current font's default. Set as None or 1 to use font default unchanged. """ # Default is 1 if value is None: value = 1 # Set self.__dict__['letterSpacing'] = value # If text has been set, layout if hasattr(self, "_text"): self._layout() @property def fontMGR(self): return allFonts @fontMGR.setter def fontMGR(self, mgr): global allFonts if isinstance(mgr, FontManager): allFonts = mgr else: raise TypeError(f"Could not set font manager for TextBox2 object `{self.name}`, must be supplied with a FontManager object") @property def languageStyle(self): """ How is text laid out? Left to right (LTR), right to left (RTL) or using Arabic layout rules? """ if hasattr(self, "_languageStyle"): return self._languageStyle @languageStyle.setter def languageStyle(self, value): self._languageStyle = value if hasattr(self, "_placeholder"): self._placeholder.languageStyle = value # If layout is anything other than LTR, mark that we need to use bidi to lay it out self._needsBidi = value != "LTR" self._needsArabic = value.lower() == "arabic" @property def anchor(self): return self.box.anchor @anchor.setter def anchor(self, anchor): # Box should use this anchor self.box.anchor = anchor # Set pos again to update sub-element vertices self.pos = self.pos @property def alignment(self): if hasattr(self, "_alignX") and hasattr(self, "_alignY"): return (self._alignX, self._alignY) else: return ("top", "left") @alignment.setter def alignment(self, alignment): if hasattr(self, "_placeholder"): self._placeholder.alignment = alignment # look for unambiguous terms first (top, bottom, left, right) self._alignY = None self._alignX = None if 'top' in alignment: self._alignY = 'top' elif 'bottom' in alignment: self._alignY = 'bottom' if 'right' in alignment: self._alignX = 'right' elif 'left' in alignment: self._alignX = 'left' # then 'center' can apply to either axis that isn't already set if self._alignX is None: self._alignX = 'center' if self._alignY is None: self._alignY = 'center' self._needVertexUpdate = True if hasattr(self, "_text"): # If text has been set, layout self._layout() @property def text(self): return self._styles.formatted_text @text.setter def text(self, text): # Convert to string text = str(text) original_text = text # Substitute HTML tags text = text.replace('<i>', codes['ITAL_START']) text = text.replace('</i>', codes['ITAL_END']) text = text.replace('<b>', codes['BOLD_START']) text = text.replace('</b>', codes['BOLD_END']) text = text.replace('</c>', codes['COLOR_END']) # Handle starting color tag colorMatches = re.findall(re_color_pattern, text) # Only execute if color codes are found to save a regex call if len(colorMatches) > 0: text = re.sub(re_color_pattern, codes['COLOR_START'], text) # Interpret colors from tags color_values = [] for match in colorMatches: # Strip C tag matchKey = match.replace("<c=", "").replace(">", "") # Convert to arrays as needed try: matchVal = literal_eval(matchKey) except (ValueError, SyntaxError): # If eval fails, use value as is matchVal = matchKey # Retrieve/cache color if matchKey not in _colorCache: _colorCache[matchKey] = Color(matchVal, self.colorSpace) if not _colorCache[matchKey].valid: raise ValueError(f"Could not interpret color value for `{matchKey}` in textbox.") color_values.append(_colorCache[matchKey].render('rgba1')) visible_text = ''.join([c for c in text if c not in codes.values()]) self._styles = Style(len(visible_text)) self._styles.formatted_text = original_text self._text = visible_text if self._needsArabic and hasattr(self, "arabicReshaper"): self._text = self.arabicReshaper.reshape(self._text) if self._needsBidi: self._text = bidi.get_display(self._text) color_iter = 0 # iterator for color_values list current_color = [()] # keeps track of color style(s) is_bold = False is_italic = False ci = 0 for c in text: if c == codes['ITAL_START']: is_italic = True elif c == codes['BOLD_START']: is_bold = True elif c == codes['COLOR_START']: current_color.append(color_values[color_iter]) color_iter += 1 elif c == codes['ITAL_END']: is_italic = False elif c == codes['BOLD_END']: is_bold = False elif c == codes['COLOR_END']: current_color.pop() else: self._styles.c[ci] = current_color[-1] self._styles.i[ci] = is_italic self._styles.b[ci] = is_bold ci += 1 self._layout() def addCharAtCaret(self, char): """Allows a character to be added programmatically at the current caret""" txt = self._text txt = txt[:self.caret.index] + char + txt[self.caret.index:] cstyle = Style(1) if len(self._styles) and self.caret.index <= len(self._styles): cstyle = self._styles[self.caret.index-1] self._styles.insert(self.caret.index, cstyle) self.caret.index += 1 self.text = txt self._layout() def deleteCaretLeft(self): """Deletes 1 character to the left of the caret""" if self.caret.index > 0: txt = self._text ci = self.caret.index txt = txt[:ci-1] + txt[ci:] self._styles = self._styles[:ci-1]+self._styles[ci:] self.caret.index -= 1 self.text = txt self._layout() def deleteCaretRight(self): """Deletes 1 character to the right of the caret""" ci = self.caret.index if ci < len(self._text): txt = self._text txt = txt[:ci] + txt[ci+1:] self._styles = self._styles[:ci]+self._styles[ci+1:] self.text = txt self._layout() def _layout(self): """Layout the text, calculating the vertex locations """ rgb = self._foreColor.render('rgba1') font = self.glFont # the vertices are initially pix (natural for freetype) # then we convert them to the requested units for self._vertices # then they are converted back during rendering using standard BaseStim visible_text = self._text vertices = np.zeros((len(visible_text) * 4, 2), dtype=np.float32) self._charIndices = np.zeros((len(visible_text)), dtype=int) self._colors = np.zeros((len(visible_text) * 4, 4), dtype=np.double) self._texcoords = np.zeros((len(visible_text) * 4, 2), dtype=np.double) self._glIndices = np.zeros((len(visible_text) * 4), dtype=int) self._renderChars = [] # the following are used internally for layout self._lineNs = np.zeros(len(visible_text), dtype=int) _lineBottoms = [] self._lineLenChars = [] # _lineWidths = [] # width in stim units of each line lineMax = self.contentBox._size.pix[0] current = [0, 0 - font.ascender] fakeItalic = 0.0 fakeBold = 0.0 # for some reason glyphs too wide when using alpha channel only if font.atlas.format == 'alpha': alphaCorrection = 1 / 3.0 else: alphaCorrection = 1 if self._lineBreaking == 'default': wordLen = 0 charsThisLine = 0 wordsThisLine = 0 lineN = 0 for i, charcode in enumerate(self._text): printable = True # unless we decide otherwise # handle formatting codes fakeItalic = 0.0 fakeBold = 0.0 if self._styles.i[i]: fakeItalic = 0.1 * font.size if self._styles.b[i]: fakeBold = 0.3 * font.size # handle newline if charcode == '\n': printable = False # handle printable characters if printable: glyph = font[charcode] if showWhiteSpace and charcode == " ": glyph = font[u"·"] elif charcode == " ": # glyph size of space is smaller than actual size, so use size of dot instead glyph.size = font[u"·"].size # Get top and bottom coords yTop = current[1] + glyph.offset[1] yBot = yTop - glyph.size[1] # Get x mid point xMid = current[0] + glyph.offset[0] + glyph.size[0] * alphaCorrection / 2 + fakeBold / 2 # Get left and right corners from midpoint xBotL = xMid - glyph.size[0] * alphaCorrection / 2 - fakeItalic - fakeBold / 2 xBotR = xMid + glyph.size[0] * alphaCorrection / 2 - fakeItalic + fakeBold / 2 xTopL = xMid - glyph.size[0] * alphaCorrection / 2 - fakeBold / 2 xTopR = xMid + glyph.size[0] * alphaCorrection / 2 + fakeBold / 2 u0 = glyph.texcoords[0] v0 = glyph.texcoords[1] u1 = glyph.texcoords[2] v1 = glyph.texcoords[3] else: glyph = font[u"·"] x = current[0] + glyph.offset[0] yTop = current[1] + glyph.offset[1] yBot = yTop - glyph.size[1] xBotL = x xTopL = x xBotR = x xTopR = x u0 = glyph.texcoords[0] v0 = glyph.texcoords[1] u1 = glyph.texcoords[2] v1 = glyph.texcoords[3] theseVertices = [[xTopL, yTop], [xBotL, yBot], [xBotR, yBot], [xTopR, yTop]] texcoords = [[u0, v0], [u0, v1], [u1, v1], [u1, v0]] vertices[i * 4:i * 4 + 4] = theseVertices self._texcoords[i * 4:i * 4 + 4] = texcoords # handle character color rgb_ = self._styles.c[i] if len(rgb_) > 0: self._colors[i*4 : i*4+4, :4] = rgb_ # set custom color else: self._colors[i*4 : i*4+4, :4] = rgb # set default color self._lineNs[i] = lineN current[0] = current[0] + (glyph.advance[0] + fakeBold / 2) * self.letterSpacing current[1] = current[1] + glyph.advance[1] # are we wrapping the line? if charcode == "\n": # check if we have stored the top/bottom of the previous line yet if lineN + 1 > len(_lineBottoms): _lineBottoms.append(current[1]) lineWPix = current[0] current[0] = 0 current[1] -= font.height lineN += 1 charsThisLine += 1 self._lineLenChars.append(charsThisLine) _lineWidths.append(lineWPix) charsThisLine = 0 wordsThisLine = 0 elif charcode in wordBreaks: wordLen = 0 charsThisLine += 1 wordsThisLine += 1 elif printable: wordLen += 1 charsThisLine += 1 # end line with auto-wrap on space if current[0] >= lineMax and wordLen > 0: # move the current word to next line lineBreakPt = vertices[(i - wordLen + 1) * 4, 0] if wordsThisLine <= 1: # if whole line is just 1 word, wrap regardless of presence of wordbreak wordLen = 0 charsThisLine += 1 wordsThisLine += 1 # add hyphen self._renderChars.append({ "i": i, "current": (current[0], current[1]), "glyph": font["-"] }) # store linebreak point lineBreakPt = current[0] wordWidth = current[0] - lineBreakPt # shift all chars of the word left by wordStartX vertices[(i - wordLen + 1) * 4: (i + 1) * 4, 0] -= lineBreakPt vertices[(i - wordLen + 1) * 4: (i + 1) * 4, 1] -= font.height # update line values self._lineNs[i - wordLen + 1: i + 1] += 1 self._lineLenChars.append(charsThisLine - wordLen) _lineWidths.append(lineBreakPt) lineN += 1 # and set current to correct location current[0] = wordWidth current[1] -= font.height charsThisLine = wordLen wordsThisLine = 1 # have we stored the top/bottom of this line yet if lineN + 1 > len(_lineBottoms): _lineBottoms.append(current[1]) # add length of this (unfinished) line _lineWidths.append(current[0]) self._lineLenChars.append(charsThisLine) elif self._lineBreaking == 'uax14': # get a list of line-breakable points according to UAX#14 breakable_points = list(get_breakable_points(self._text)) text_seg = list(break_units(self._text, breakable_points)) styles_seg = list(break_units(self._styles, breakable_points)) lineN = 0 charwidth_list = [] segwidth_list = [] y_advance_list = [] vertices_list = [] texcoords_list = [] # calculate width of each segments for this_seg in range(len(text_seg)): thisSegWidth = 0 # width of this segment for i, charcode in enumerate(text_seg[this_seg]): printable = True # unless we decide otherwise # handle formatting codes fakeItalic = 0.0 fakeBold = 0.0 if self._styles.i[i]: fakeItalic = 0.1 * font.size if self._styles.b[i]: fakeBold = 0.3 * font.size # handle newline if charcode == '\n': printable = False # handle printable characters if printable: if showWhiteSpace and charcode == " ": glyph = font[u"·"] else: glyph = font[charcode] xBotL = glyph.offset[0] - fakeItalic - fakeBold / 2 xTopL = glyph.offset[0] - fakeBold / 2 yTop = glyph.offset[1] xBotR = xBotL + glyph.size[0] * alphaCorrection + fakeBold xTopR = xTopL + glyph.size[0] * alphaCorrection + fakeBold yBot = yTop - glyph.size[1] u0 = glyph.texcoords[0] v0 = glyph.texcoords[1] u1 = glyph.texcoords[2] v1 = glyph.texcoords[3] else: glyph = font[u"·"] x = glyph.offset[0] yTop = glyph.offset[1] yBot = yTop - glyph.size[1] xBotL = x xTopL = x xBotR = x xTopR = x u0 = glyph.texcoords[0] v0 = glyph.texcoords[1] u1 = glyph.texcoords[2] v1 = glyph.texcoords[3] # calculate width and update segment width w = glyph.advance[0] + fakeBold / 2 thisSegWidth += w # keep vertices, texcoords, width and y_advance of this character vertices_list.append([[xTopL, yTop], [xBotL, yBot], [xBotR, yBot], [xTopR, yTop]]) texcoords_list.append([[u0, v0], [u0, v1], [u1, v1], [u1, v0]]) charwidth_list.append(w) y_advance_list.append(glyph.advance[1]) # append width of this segment to the list segwidth_list.append(thisSegWidth) # concatenate segments to build line lines = [] while text_seg: line_width = 0 for i in range(len(text_seg)): # if this segment is \n, break line here. if text_seg[i][-1] == '\n': i+=1 # increment index to include \n to current line break # concatenate next segment line_width += segwidth_list[i] # break if line_width is greater than lineMax if lineMax < line_width: break else: # if for sentence finished without break, all segments # should be concatenated. i = len(text_seg) p = max(1, i) # concatenate segments and remove from segment list lines.append("".join(text_seg[:p])) del text_seg[:p], segwidth_list[:p] #, avoid[:p] # build lines i = 0 # index of the current character if lines: for line in lines: for c in line: theseVertices = vertices_list[i] #update vertices for j in range(4): theseVertices[j][0] += current[0] theseVertices[j][1] += current[1] texcoords = texcoords_list[i] vertices[i * 4:i * 4 + 4] = theseVertices self._texcoords[i * 4:i * 4 + 4] = texcoords # handle character color rgb_ = self._styles.c[i] if len(rgb_) > 0: self._colors[i*4 : i*4+4, :4] = rgb_ # set custom color else: self._colors[i*4 : i*4+4, :4] = rgb # set default color self._lineNs[i] = lineN current[0] = current[0] + charwidth_list[i] current[1] = current[1] + y_advance_list[i] # have we stored the top/bottom of this line yet if lineN + 1 > len(_lineBottoms): _lineBottoms.append(current[1]) # next chacactor i += 1 # prepare for next line current[0] = 0 current[1] -= font.height lineBreakPt = vertices[(i-1) * 4, 0] self._lineLenChars.append(len(line)) _lineWidths.append(lineBreakPt) # need not increase lineN when the last line doesn't end with '\n' if lineN < len(lines)-1 or line[-1] == '\n' : lineN += 1 else: raise ValueError("Unknown lineBreaking option ({}) is" "specified.".format(self._lineBreaking)) # Add render-only characters for rend in self._renderChars: vertices = self._addRenderOnlyChar( i=rend['i'], x=rend['current'][0], y=rend['current'][1], vertices=vertices, glyph=rend['glyph'], alphaCorrection=alphaCorrection ) # Apply vertical alignment if self.alignment[1] in ("bottom", "center"): # Get bottom of last line (or starting line, if there are none) if len(_lineBottoms): lastLine = min(_lineBottoms) else: lastLine = current[1] if self.alignment[1] == "bottom": # Work out how much we need to adjust by for the bottom base line to sit at the bottom of the content box adjustY = lastLine + self.contentBox._size.pix[1] if self.alignment[1] == "center": # Work out how much we need to adjust by for the line midpoint (mean of ascender and descender) to sit in the middle of the content box adjustY = (lastLine + font.descender + self.contentBox._size.pix[1]) / 2 # Adjust vertices and line bottoms vertices[:, 1] = vertices[:, 1] - adjustY _lineBottoms -= adjustY # Apply horizontal alignment if self.alignment[0] in ("right", "center"): if self.alignment[0] == "right": # Calculate adjust value per line lineAdjustX = self.contentBox._size.pix[0] - np.array(_lineWidths) if self.alignment[0] == "center": # Calculate adjust value per line lineAdjustX = (self.contentBox._size.pix[0] - np.array(_lineWidths)) / 2 # Get adjust value per vertex adjustX = lineAdjustX[np.repeat(self._lineNs, 4)] # Adjust vertices vertices[:, 0] = vertices[:, 0] + adjustX # convert the vertices to be relative to content box and set vertices = vertices / self.contentBox._size.pix + (-0.5, 0.5) # apply orientation self.vertices = (vertices * self.size).dot(self._rotationMatrix) / self.size if len(_lineBottoms): if self.flipVert: self._lineBottoms = min(self.contentBox._vertices.pix[:, 1]) - np.array(_lineBottoms) else: self._lineBottoms = max(self.contentBox._vertices.pix[:, 1]) + np.array(_lineBottoms) self._lineWidths = min(self.contentBox._vertices.pix[:, 0]) + np.array(_lineWidths) else: self._lineBottoms = np.array(_lineBottoms) self._lineWidths = np.array(_lineWidths) # if we had to add more glyphs to make possible then if self.glFont._dirty: self.glFont.upload() self.glFont._dirty = False self._needVertexUpdate = True @attributeSetter def ori(self, value): # get previous orientaiton lastOri = self.__dict__.get("ori", 0) # set new value BaseVisualStim.ori.func(self, value) # set on all boxes self.box.ori = value self.boundingBox.ori = value self.contentBox.ori = value # trigger layout if value has changed if lastOri != value: self._layout() def draw(self): """Draw the text to the back buffer""" # Border width self.box.setLineWidth(self.palette['lineWidth']) # Use 1 as base if border width is none #self.borderWidth = self.box.lineWidth # Border colour self.box.setLineColor(self.palette['lineColor'], colorSpace='rgb') #self.borderColor = self.box.lineColor # Background self.box.setFillColor(self.palette['fillColor'], colorSpace='rgb') #self.fillColor = self.box.fillColor # Inherit win self.box.win = self.win self.contentBox.win = self.win self.boundingBox.win = self.win if self._needVertexUpdate: #print("Updating vertices...") self._updateVertices() if self.fillColor is not None or self.borderColor is not None: self.box.draw() # Draw sub-elements if in debug mode if debug: self.contentBox.draw() self.boundingBox.draw() tightH = self.boundingBox._size.pix[1] areaH = self.contentBox._size.pix[1] if self.overflow in ("scroll",) and tightH > areaH: # Draw scrollbar self.scrollbar.draw() # Scroll if self._alignY == "top": # Top aligned means scroll between 1 and 0, and no adjust for line height adjMulti = (-self.scrollbar.markerPos + 1) / 2 adjAdd = -self.glFont.descender elif self._alignY == "bottom": # Top aligned means scroll between -1 and 0, and adjust for line height adjMulti = (-self.scrollbar.markerPos - 1) / 2 adjAdd = -self.glFont.descender else: # Center aligned means scroll between -0.5 and 0.5, and 50% adjust for line height adjMulti = -self.scrollbar.markerPos / 2 adjAdd = 0 self.contentBox._pos.pix = self._pos.pix + ( 0, (tightH - areaH) * adjMulti + adjAdd ) self._needVertexUpdate = True if self.overflow in ("hidden", "scroll"): # Activate aperture self.container.enable() gl.glPushMatrix() self.win.setScale('pix') gl.glActiveTexture(gl.GL_TEXTURE0) gl.glBindTexture(gl.GL_TEXTURE_2D, self.glFont.textureID) gl.glEnable(gl.GL_TEXTURE_2D) gl.glDisable(gl.GL_DEPTH_TEST) gl.glEnableClientState(gl.GL_VERTEX_ARRAY) gl.glEnableClientState(gl.GL_COLOR_ARRAY) gl.glEnableClientState(gl.GL_TEXTURE_COORD_ARRAY) gl.glEnableClientState(gl.GL_VERTEX_ARRAY) gl.glVertexPointer(2, gl.GL_DOUBLE, 0, self.verticesPix.ctypes) gl.glColorPointer(4, gl.GL_DOUBLE, 0, self._colors.ctypes) gl.glTexCoordPointer(2, gl.GL_DOUBLE, 0, self._texcoords.ctypes) self.shader.bind() self.shader.setInt('texture', 0) self.shader.setFloat('pixel', [1.0 / 512, 1.0 / 512]) nVerts = (len(self._text) + len(self._renderChars)) * 4 gl.glDrawArrays(gl.GL_QUADS, 0, nVerts) self.shader.unbind() # removed the colors and font texture gl.glDisableClientState(gl.GL_COLOR_ARRAY) gl.glDisableClientState(gl.GL_TEXTURE_COORD_ARRAY) gl.glDisableVertexAttribArray(1) gl.glDisableClientState(gl.GL_VERTEX_ARRAY) gl.glActiveTexture(gl.GL_TEXTURE0) gl.glBindTexture(gl.GL_TEXTURE_2D, 0) gl.glDisable(gl.GL_TEXTURE_2D) if self.hasFocus: # draw caret line self.caret.draw() gl.glPopMatrix() # Draw placeholder if blank if self.editable and len(self.text) == 0: self._placeholder.draw() if self.container is not None: self.container.disable() def reset(self): """Resets the TextBox2 to hold **whatever it was given on initialisation**""" # Reset contents self.text = self.startText def clear(self): """Resets the TextBox2 to a blank string""" # Clear contents self.text = "" def contains(self, x, y=None, units=None, tight=False): """Returns True if a point x,y is inside the stimulus' border. Can accept variety of input options: + two separate args, x and y + one arg (list, tuple or array) containing two vals (x,y) + an object with a getPos() method that returns x,y, such as a :class:`~psychopy.event.Mouse`. Returns `True` if the point is within the area defined either by its `border` attribute (if one defined), or its `vertices` attribute if there is no .border. This method handles complex shapes, including concavities and self-crossings. Note that, if your stimulus uses a mask (such as a Gaussian) then this is not accounted for by the `contains` method; the extent of the stimulus is determined purely by the size, position (pos), and orientation (ori) settings (and by the vertices for shape stimuli). See Coder demos: shapeContains.py See Coder demos: shapeContains.py """ if tight: return self.boundingBox.contains(x, y, units) else: return self.box.contains(x, y, units) def overlaps(self, polygon, tight=False): """Returns `True` if this stimulus intersects another one. If `polygon` is another stimulus instance, then the vertices and location of that stimulus will be used as the polygon. Overlap detection is typically very good, but it can fail with very pointy shapes in a crossed-swords configuration. Note that, if your stimulus uses a mask (such as a Gaussian blob) then this is not accounted for by the `overlaps` method; the extent of the stimulus is determined purely by the size, pos, and orientation settings (and by the vertices for shape stimuli). Parameters See coder demo, shapeContains.py """ if tight: return self.boundingBox.overlaps(polygon) else: return self.box.overlaps(polygon) def _addRenderOnlyChar(self, i, x, y, vertices, glyph, alphaCorrection=1): """ Add a character at index i which is drawn but not actually part of the text """ i4 = i * 4 # Get coordinates of glyph texture self._texcoords = np.vstack([ self._texcoords[:i4], [glyph.texcoords[0], glyph.texcoords[1]], [glyph.texcoords[0], glyph.texcoords[3]], [glyph.texcoords[2], glyph.texcoords[3]], [glyph.texcoords[2], glyph.texcoords[1]], self._texcoords[i4:] ]) # Get coords of box corners top = y + glyph.offset[1] bot = top - glyph.size[1] mid = x + glyph.offset[0] + glyph.size[0] * alphaCorrection / 2 left = mid - glyph.size[0] * alphaCorrection / 2 right = mid + glyph.size[0] * alphaCorrection / 2 vertices = np.vstack([ vertices[:i4], [left, top], [left, bot], [right, bot], [right, top], vertices[i4:] ]) # Make same colour as other text self._colors = np.vstack([ self._colors[:i4], self._foreColor.render('rgba1'), self._foreColor.render('rgba1'), self._foreColor.render('rgba1'), self._foreColor.render('rgba1'), self._colors[i4:] ]) # Extend line numbers array self._lineNs = np.hstack([ self._lineNs[:i], self._lineNs[i-1], self._lineNs[i:] ]) return vertices def _updateVertices(self): """Sets Stim.verticesPix and ._borderPix from pos, size, ori, flipVert, flipHoriz """ # check whether stimulus needs flipping in either direction flip = np.array([1, 1]) if hasattr(self, 'flipHoriz') and self.flipHoriz: flip[0] = -1 # True=(-1), False->(+1) if hasattr(self, 'flipVert') and self.flipVert: flip[1] = -1 # True=(-1), False->(+1) self.__dict__['verticesPix'] = self._vertices.pix # tight bounding box if hasattr(self._vertices, self.units) and self.vertices.shape[0] >= 1: verts = self._vertices.pix L = verts[:, 0].min() R = verts[:, 0].max() B = verts[:, 1].min() T = verts[:, 1].max() tightW = R-L Xmid = (R+L)/2 tightH = T-B Ymid = (T+B)/2 # for the tight box anchor offset is included in vertex calcs self.boundingBox.size = tightW, tightH self.boundingBox.pos = self.pos + (Xmid, Ymid) else: self.boundingBox.size = 0, 0 self.boundingBox.pos = self.pos # box (larger than bounding box) needs anchor offest adding self.box.pos = self.pos self.box.size = self.size # this might have changed from _requested self._needVertexUpdate = False def _onText(self, chr): """Called by the window when characters are received""" if chr == '\t': self.win.nextEditable() return if chr == '\r': # make it newline not Carriage Return chr = '\n' self.addCharAtCaret(chr) if self.onTextCallback: self.onTextCallback() def _onCursorKeys(self, key): """Called by the window when cursor/del/backspace... are received""" if key == 'MOTION_UP': self.caret.row -= 1 elif key == 'MOTION_DOWN': self.caret.row += 1 elif key == 'MOTION_RIGHT': self.caret.char += 1 elif key == 'MOTION_LEFT': self.caret.char -= 1 elif key == 'MOTION_BACKSPACE': self.deleteCaretLeft() elif key == 'MOTION_DELETE': self.deleteCaretRight() elif key == 'MOTION_NEXT_WORD': pass elif key == 'MOTION_PREVIOUS_WORD': pass elif key == 'MOTION_BEGINNING_OF_LINE': self.caret.char = 0 elif key == 'MOTION_END_OF_LINE': self.caret.char = END_OF_THIS_LINE elif key == 'MOTION_NEXT_PAGE': pass elif key == 'MOTION_PREVIOUS_PAGE': pass elif key == 'MOTION_BEGINNING_OF_FILE': pass elif key == 'MOTION_END_OF_FILE': pass else: print("Received unhandled cursor motion type: ", key) @property def hasFocus(self): if self.win and self.win.currentEditable == self: return True return False @hasFocus.setter def hasFocus(self, focus): if focus is False and self.hasFocus: # If focus is being set to False, tell window to # give focus to next editable. if self.win: self.win.nextEditable() elif focus is True and self.hasFocus is False: # If focus is being set True, set textbox instance to be # window.currentEditable. if self.win: self.win.currentEditable=self return False def getText(self): """Returns the current text in the box, including formatting tokens.""" return self.text @property def visibleText(self): """Returns the current visible text in the box""" return self._text def getVisibleText(self): """Returns the current visible text in the box""" return self.visibleText def setText(self, text=None, log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message. """ setAttribute(self, 'text', text, log) def setHeight(self, height, log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message. """ setAttribute(self, 'height', height, log) def setFont(self, font, log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message. """ setAttribute(self, 'font', font, log) @attributeSetter def placeholder(self, value): """ Text to display when textbox is editable and has no content. """ # Store value self.__dict__['placeholder'] = value # Set placeholder object text if hasattr(self, "_placeholder"): self._placeholder.text = value def setPlaceholder(self, value, log=False): """ Set text to display when textbox is editable and has no content. """ self.placeholder = value class Caret(ColorMixin): """ Class to handle the caret (cursor) within a textbox. Do **not** call without a textbox. Parameters ---------- textbox : psychopy.visual.TextBox2 Textbox which caret corresponds to visible : bool Whether the caret is visible row : int Textbox row which caret is on char : int Text character within row which caret is on index : int Index of character which caret is on vertices : list, tuple Coordinates of each corner of caret width : int, float Width of caret line color : list, tuple, str Caret colour """ def __init__(self, textbox, color, width, colorSpace='rgb'): self.textbox = textbox self.index = len(textbox._text) # start off at the end self.autoLog = False self.width = width self.units = textbox.units self.colorSpace = colorSpace self.color = color def draw(self, override=None): """ Draw the caret Parameters ========== override : bool or None Set to True to always draw the caret, to False to never draw the caret, or leave as None to draw only according to the usual conditions (being visible and within the correct timeframe for the flashing effect) """ if override is None: # If no override, draw only if conditions are met if not self.visible: return # Flash every other second if core.getTime() % 1 > 0.6: return elif not override: # If override is False, never draw return # If no override and conditions are met, or override is True, draw gl.glLineWidth(self.width) gl.glColor4f( *self._foreColor.rgba1 ) gl.glBegin(gl.GL_LINES) gl.glVertex2f(self.vertices[0, 0], self.vertices[0, 1]) gl.glVertex2f(self.vertices[1, 0], self.vertices[1, 1]) gl.glEnd() @property def visible(self): return self.textbox.hasFocus @property def row(self): """What row is caret on?""" # Check that index is with range of all character indices if len(self.textbox._lineNs) == 0: # no chars at all return 0 elif self.index > len(self.textbox._lineNs): self.index = len(self.textbox._lineNs) # Get line of index if self.index >= len(self.textbox._lineNs): if len(self.textbox._lineBottoms) - 1 > self.textbox._lineNs[-1]: return len(self.textbox._lineBottoms) - 1 return self.textbox._lineNs[-1] else: return self.textbox._lineNs[self.index] @row.setter def row(self, value): """Use line to index conversion to set index according to row value""" # Figure out how many characters into previous row the cursor was charsIn = self.char nRows = len(self.textbox._lineLenChars) # If new row is more than total number of rows, move to end of last row if value >= nRows: value = nRows charsIn = self.textbox._lineLenChars[-1] # If new row is less than 0, move to beginning of first row elif value < 0: value = 0 charsIn = 0 elif value == nRows-1 and charsIn > self.textbox._lineLenChars[value]: # last row last char charsIn = self.textbox._lineLenChars[value] elif charsIn > self.textbox._lineLenChars[value]-1: # end of a middle row (account for the newline) charsIn = self.textbox._lineLenChars[value]-1 # Set new index in new row self.index = sum(self.textbox._lineLenChars[:value]) + charsIn @property def char(self): """What character within current line is caret on?""" # Check that index is with range of all character indices self.index = min(self.index, len(self.textbox._lineNs)) self.index = max(self.index, 0) # Get first index of line, subtract from index to get char return self.index - sum(self.textbox._lineLenChars[:self.row]) @char.setter def char(self, value): """Set character within row""" # If setting char to less than 0, move to last char on previous line row = self.row if value < 0: if row == 0: value = 0 else: row -= 1 value = self.textbox._lineLenChars[row]-1 # end of that row elif row >= len(self.textbox._lineLenChars)-1 and \ value >= self.textbox._lineLenChars[-1]: # this is the last row row = len(self.textbox._lineLenChars)-1 value = self.textbox._lineLenChars[-1] elif value == END_OF_THIS_LINE: value = self.textbox._lineLenChars[row]-1 elif value >= self.textbox._lineLenChars[row]: # end of this row (not the last) so go to next row += 1 value = 0 # then calculate index if row: # if not on first row self.index = sum(self.textbox._lineLenChars[:row]) + value else: self.index = value @property def vertices(self): textbox = self.textbox # check we have a caret index if self.index is None or self.index > len(textbox._text): self.index = len(textbox._text) if self.index < 0: self.index = 0 # Get vertices of caret based on characters and index ii = self.index if textbox.vertices.shape[0] == 0: # If there are no chars, put caret at start position (determined by alignment) if textbox.alignment[1] == "bottom": bottom = min(textbox.contentBox._vertices.pix[:, 1]) elif textbox.alignment[1] == "center": bottom = (min(textbox.contentBox._vertices.pix[:, 1]) + max(textbox.contentBox._vertices.pix[:, 1]) - textbox.glFont.ascender - textbox.glFont.descender) / 2 else: bottom = max(textbox.contentBox._vertices.pix[:, 1]) - textbox.glFont.ascender if textbox.alignment[0] == "right": x = max(textbox.contentBox._vertices.pix[:, 0]) elif textbox.alignment[0] == "center": x = (min(textbox.contentBox._vertices.pix[:, 0]) + max(textbox.contentBox._vertices.pix[:, 0])) / 2 else: x = min(textbox.contentBox._vertices.pix[:, 0]) else: # Otherwise, get caret position from character vertices if self.index >= len(textbox._lineNs): if len(textbox._lineBottoms) - 1 > textbox._lineNs[-1]: x = textbox._lineWidths[len(textbox._lineBottoms) - 1] else: # If the caret is after the last char, position it to the right chrVerts = textbox._vertices.pix[range((ii-1) * 4, (ii-1) * 4 + 4)] x = chrVerts[2, 0] # x-coord of left edge (of final char) else: # Otherwise, position it to the left chrVerts = textbox._vertices.pix[range(ii * 4, ii * 4 + 4)] x = chrVerts[1, 0] # x-coord of right edge # Get top of this line bottom = textbox._lineBottoms[self.row] # Top will always be line bottom + font height if self.textbox.flipVert: top = bottom - self.textbox.glFont.size else: top = bottom + self.textbox.glFont.size return np.array([ [x, bottom], [x, top] ]) class Style: # Define a simple Style class for storing information in text(). # Additional features exist to maintain extant edit/caret syntax def __init__(self, text_length, i=None, b=None, c=None): self.len = text_length self.i = i self.b = b self.c = c if i == None: self.i = [False]*text_length if b == None: self.b = [False]*text_length if c == None: self.c = [()]*text_length self.formatted_text = '' def __len__(self): return self.len def __getitem__(self, i): # Return a new Style object with data from current index if isinstance(i, int): s = Style(1, [self.i[i]], [self.b[i]], [self.c[i]]) else: s = Style(len(self.i[i]), self.i[i], self.b[i], self.c[i]) return s def __add__(self, c): s = self.copy() s.insert(len(s), c) return s def copy(self): s = Style(self.len, self.i.copy(), self.b.copy(), self.c.copy()) s.formatted_text = self.formatted_text return s def insert(self, i, style): # in-place, like list if not isinstance(style, Style): raise TypeError('Inserted object must be Style.') self.i[i:i] = style.i self.b[i:i] = style.b self.c[i:i] = style.c self.len += len(style) class PlaceholderText(TextBox2): """ Subclass of TextBox2 used only for presenting placeholder text, should never be called outside of TextBox2's init method. """ def __init__(self, parent, text): # Should only ever be called from a textbox, make sure parent is a textbox assert isinstance(parent, TextBox2), "Parent of PlaceholderText object must be of type visual.TextBox2" # Create textbox sdfs df TextBox2.__init__( self, parent.win, text, font=parent.font, bold=parent.bold, italic=parent.italic, units=parent.contentBox.units, anchor=parent.contentBox.anchor, pos=parent.contentBox.pos, size=parent.contentBox.size, letterHeight=parent.letterHeight, color=parent.color, colorSpace=parent.colorSpace, fillColor=None, borderColor=None, opacity=0.5, lineSpacing=parent.lineSpacing, padding=0, # gap between box and text alignment=parent.alignment, flipHoriz=parent.flipHoriz, flipVert=parent.flipVert, languageStyle=parent.languageStyle, editable=False, overflow=parent.overflow, lineBreaking=parent._lineBreaking, autoLog=False, autoDraw=False )
69,477
Python
.py
1,641
30.143815
173
0.549211
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,769
__init__.py
psychopy_psychopy/psychopy/visual/textbox2/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from .textbox2 import TextBox2, allFonts
87
Python
.py
3
28
40
0.702381
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,770
fontmanager.py
psychopy_psychopy/psychopy/visual/textbox/fontmanager.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Created on Sun Nov 10 12:18:45 2013 @author: Sol """ import os import sys from pathlib import Path import math import numpy as np import unicodedata as ud from freetype import Face, FT_LOAD_RENDER, FT_LOAD_FORCE_AUTOHINT, FT_Exception from .textureatlas import TextureAtlas from pyglet.gl import (glGenLists, glNewList, GL_COMPILE, GL_QUADS, glBegin, glTexCoord2f, glVertex2f, glEnd, glEndList, glTranslatef) # OS Font paths _X11FontDirectories = [ # an old standard installation point "/usr/X11R6/lib/X11/fonts/TTF", "/usr/X11/lib/X11/fonts", # here is the new standard location for fonts "/usr/share/fonts", # documented as a good place to install new fonts "/usr/local/share/fonts", # common application, not really useful "/usr/lib/openoffice/share/fonts/truetype", "" ] _OSXFontDirectories = [ "/Library/Fonts/", "/Network/Library/Fonts", "/System/Library/Fonts", # fonts installed via MacPorts "/opt/local/share/fonts", "" ] supportedExtensions = ['ttf', 'otf', 'ttc', 'dfont'] log = math.log ceil = math.ceil def bytesToStr(s): """Force to unicode if bytes""" if type(s) == bytes: return s.decode('utf-8') else: return s def nearestPow2(n): return pow(2, int(log(n, 2) + 0.5)) def nextPow2(n): return int(pow(2, ceil(log(n, 2)))) class FontManager: """FontManager provides a simple API for finding and loading font files (.ttf) via the FreeType lib The FontManager finds supported font files on the computer and initially creates a dictionary containing the information about available fonts. This can be used to quickly determine what font family names are available on the computer and what styles (bold, italic) are supported for each family. This font information can then be used to create the resources necessary to display text using a given font family, style, size, color, and dpi. The FontManager is currently used by the psychopy.visual.TextBox stim type. A user script can access the FontManager via: font_mngr=visual.textbox.getFontManager() A user script never creates an instance of the FontManager class and should always access it using visual.textbox.getFontManager(). Once a font of a given size and dpi has been created; it is cached by the FontManager and can be used by all TextBox instances created within the experiment. """ freetype_import_error = None font_atlas_dict = {} font_family_styles = [] _available_font_info = {} font_store = None def __init__(self, monospace_only=True): # if FontManager.freetype_import_error: # raise Exception('Appears the freetype library could not load. # Error: %s'%(str(FontManager.freetype_import_error))) self.load_monospace_only = monospace_only self.updateFontInfo(monospace_only) def getFontFamilyNames(self): """Returns a list of the available font family names. """ return list(self._available_font_info.keys()) def getFontStylesForFamily(self, family_name): """For the given family_name, a list of style names supported is returned. """ style_dict = self._available_font_info.get(family_name) if style_dict: return list(style_dict.keys()) def getFontFamilyStyles(self): """Returns a list where each element of the list is a itself a two element list of [font_family_name,[font_style_names_list]] """ return self.font_family_styles def getFontsMatching(self, font_family_name, bold=False, italic=False, font_style=None): """ Returns the list of FontInfo instances that match the provided font_family_name and style information. If no matching fonts are found, None is returned. """ style_dict = self._available_font_info.get(font_family_name) if style_dict is None: return None if font_style and font_style in style_dict: return style_dict[font_style] for style, fonts in style_dict.items(): b, i = self.booleansFromStyleName(style) if b == bold and i == italic: return fonts return None def addFontFile(self, font_path, monospace_only=True): """ Add a Font File to the FontManger font search space. The font_path must be a valid path including the font file name. Relative paths can be used, with the current working directory being the origin. If monospace_only is True, the font file will only be added if it is a monospace font (as only monospace fonts are currently supported by TextBox). Adding a Font to the FontManager is not persistent across runs of the script, so any extra font paths need to be added each time the script starts. """ return self.addFontFiles((font_path,), monospace_only) def addFontFiles(self, font_paths, monospace_only=True): """ Add a list of font files to the FontManger font search space. Each element of the font_paths list must be a valid path including the font file name. Relative paths can be used, with the current working directory being the origin. If monospace_only is True, each font file will only be added if it is a monospace font (as only monospace fonts are currently supported by TextBox). Adding fonts to the FontManager is not persistent across runs of the script, so any extra font paths need to be added each time the script starts. """ fi_list = [] for fp in font_paths: if os.path.isfile(fp) and os.path.exists(fp): face = Face(fp) if monospace_only: if face.is_fixed_width: fi_list.append(self._createFontInfo(fp, face)) else: fi_list.append(self._createFontInfo(fp, face)) self.font_family_styles.sort() return fi_list def addFontDirectory(self, font_dir, monospace_only=True, recursive=False): """ Add any font files found in font_dir to the FontManger font search space. Each element of the font_paths list must be a valid path including the font file name. Relative paths can be used, with the current working directory being the origin. If monospace_only is True, each font file will only be added if it is a monospace font (as only monospace fonts are currently supported by TextBox). Adding fonts to the FontManager is not persistent across runs of the script, so any extra font paths need to be added each time the script starts. """ from os import walk font_paths = [] for (dirpath, dirnames, filenames) in walk(font_dir): ttf_files = [] for fname in filenames: for fext in supportedExtensions: if fname.lower().endswith(fext): ttf_files.append(os.path.join(dirpath,fname)) font_paths.extend(ttf_files) if not recursive: break return self.addFontFiles(font_paths) # Class methods for FontManager below this comment should not need to be # used by user scripts in most situations. Accessing them is okay. @staticmethod def getGLFont(font_family_name, size=32, bold=False, italic=False, dpi=72): """ Return a FontAtlas object that matches the family name, style info, and size provided. FontAtlas objects are cached, so if multiple TextBox instances use the same font (with matching font properties) then the existing FontAtlas is returned. Otherwise, a new FontAtlas is created , added to the cache, and returned. """ from psychopy.visual.textbox import getFontManager fm = getFontManager() if fm: font_infos = fm.getFontsMatching(font_family_name, bold, italic) if len(font_infos) == 0: return False font_info = font_infos[0] fid = MonospaceFontAtlas.getIdFromArgs(font_info, size, dpi) font_atlas = fm.font_atlas_dict.get(fid) if font_atlas is None: font_atlas = fm.font_atlas_dict.setdefault( fid, MonospaceFontAtlas(font_info, size, dpi)) font_atlas.createFontAtlas() if fm.font_store: fm.font_store.addFontAtlas(font_atlas) return font_atlas def getFontInfo(self, refresh=False, monospace=True): """ Returns the available font information as a dict of dict's. The first level dict has keys for the available font families. The second level dict has keys for the available styles of the associated font family. The values in the second level font family - style dict are each a list containing FontInfo objects. There is one FontInfo object for each physical font file found that matches the associated font family and style. """ if refresh or not self._available_font_info: self.updateFontInfo(monospace) return self._available_font_info def findFontFiles(self, folders=(), recursive=True): """Search for font files in the folder (or system folders) Parameters ---------- folders: iterable folders to search. If empty then search typical system folders Returns ------- list of pathlib.Path objects """ searchPaths=folders if searchPaths is None or len(searchPaths) == 0: if sys.platform == 'win32': searchPaths = [] # just leave it to matplotlib as below elif sys.platform == 'darwin': # on mac matplotlib doesn't include 'ttc' files (which are fine) searchPaths = _OSXFontDirectories elif sys.platform.startswith('linux'): searchPaths = _X11FontDirectories # search those folders fontPaths = [] for thisFolder in searchPaths: thisFolder = Path(thisFolder) for thisExt in supportedExtensions: if recursive: fontPaths.extend([str(p.absolute()) for p in thisFolder.rglob("*.{}".format(thisExt))]) else: fontPaths.extend([str(p.absolute()) for p in thisFolder.glob("*.{}".format(thisExt))]) # if we failed let matplotlib have a go if fontPaths: return fontPaths else: from matplotlib import font_manager return font_manager.findSystemFonts() def updateFontInfo(self, monospace_only=True): self._available_font_info.clear() del self.font_family_styles[:] fonts_found = self.findFontFiles() self.addFontFiles(fonts_found, monospace_only) def booleansFromStyleName(self, style): """ For the given style name, return a bool indicating if the font is bold, and a second indicating if it is italics. """ italic = False bold = False s = style.lower().strip() if s == 'regular': return False, False if s.find('italic') >= 0 or s.find('oblique') >= 0: italic = True if s.find('bold') >= 0: bold = True return bold, italic def _createFontInfo(self, fp, fface): fns = (bytesToStr(fface.family_name), bytesToStr(fface.style_name)) if fns in self.font_family_styles: pass else: self.font_family_styles.append(fns) styles_for_font_dict = self._available_font_info.setdefault( fns[0], {}) fonts_for_style = styles_for_font_dict.setdefault(fns[1], []) fi = FontInfo(fp, fface) fonts_for_style.append(fi) return fi def __del__(self): self.font_store = None if self.font_atlas_dict: self.font_atlas_dict.clear() self.font_atlas_dict = None if self._available_font_info: self._available_font_info.clear() self._available_font_info = None class FontInfo: def __init__(self, fp, face): self.path = fp self.family_name = bytesToStr(face.family_name) self.style_name = bytesToStr(face.style_name) self.charmaps = [charmap.encoding_name for charmap in face.charmaps] self.num_faces = face.num_faces self.num_glyphs = face.num_glyphs #self.size_info= [dict(width=s.width,height=s.height, # x_ppem=s.x_ppem,y_ppem=s.y_ppem) for s in face.available_sizes] self.units_per_em = face.units_per_EM self.monospace = face.is_fixed_width self.charmap_id = face.charmap.index self.label = "%s_%s" % (self.family_name, self.style_name) self.id = self.label def getID(self): return self.id def asdict(self): d = {} for k, v in self.__dict__.items(): if k[0] != '_': d[k] = v return d class MonospaceFontAtlas: def __init__(self, font_info, size, dpi): self.font_info = font_info self.size = size self.dpi = dpi self.id = self.getIdFromArgs(font_info, size, dpi) self._face = Face(font_info.path) self._face.set_char_size(height=self.size * 64, vres=self.dpi) self.charcode2glyph = None self.charcode2unichr = None self.charcode2displaylist = None self.max_ascender = None self.max_descender = None self.max_tile_width = None self.max_tile_height = None self.max_bitmap_size = None self.total_bitmap_area = 0 self.atlas = None def getID(self): return self.id @staticmethod def getIdFromArgs(font_info, size, dpi): return "%s_%d_%d" % (font_info.getID(), size, dpi) def createFontAtlas(self): if self.atlas: self.atlas.free() self.atlas = None self.charcode2glyph = {} self.charcode2unichr = {} self.max_ascender = None self.max_descender = None self.max_tile_width = None self.max_tile_height = None self.max_bitmap_size = None self.total_bitmap_area = 0 # load font glyphs and calculate max. char size. # This is used when the altas is created to properly size the tex. # i.e. max glyph size * num glyphs max_w, max_h = 0, 0 max_ascender, max_descender, max_tile_width = 0, 0, 0 face = self._face face.set_char_size(height=self.size * 64, vres=self.dpi) # Create texAtlas for glyph set. x_ppem = face.size.x_ppem y_ppem = face.size.x_ppem units_ppem = self.font_info.units_per_em est_max_width = ((face.bbox.xMax - face.bbox.xMin) / float(units_ppem) * x_ppem) est_max_height = face.size.ascender / float(units_ppem) * y_ppem target_atlas_area = int( est_max_width * est_max_height) * face.num_glyphs # make sure it is big enough. ;) # height is trimmed before sending to video ram anyhow. target_atlas_area = target_atlas_area * 3.0 pow2_area = nextPow2(target_atlas_area) atlas_width = 2048 atlas_height = pow2_area / atlas_width self.atlas = TextureAtlas(atlas_width, atlas_height * 2) for gindex, charcode in face.get_chars(): uchar = chr(charcode) if ud.category(uchar) not in (u'Zl', u'Zp', u'Cc', u'Cf', u'Cs', u'Co', u'Cn'): try: #face.set_char_size( int(self.size * 64), 0, 16*72, 72 ) #face.set_pixel_sizes(int(self.size), int(self.size)) face.load_char(uchar, FT_LOAD_RENDER | FT_LOAD_FORCE_AUTOHINT) bitmap = face.glyph.bitmap self.charcode2unichr[charcode] = uchar self.total_bitmap_area += bitmap.width * bitmap.rows max_ascender = max(max_ascender, face.glyph.bitmap_top) max_descender = max( max_descender, bitmap.rows - face.glyph.bitmap_top) max_tile_width = max(max_tile_width, bitmap.width) max_w = max(bitmap.width, max_w) max_h = max(bitmap.rows, max_h) x, y, w, h = self.atlas.get_region( bitmap.width + 2, bitmap.rows + 2) if x < 0: msg = ("MonospaceFontAtlas.get_region failed " "for: {}, requested area: {},{}. Atlas Full!") vals = charcode, bitmap.width + 2, bitmap.rows + 2 raise Exception(msg.format(vals)) x, y = x + 1, y + 1 w, h = w - 2, h - 2 data = np.array(bitmap.buffer[:(bitmap.rows * bitmap.width)], dtype=np.ubyte).reshape(h, w, 1) self.atlas.set_region((x, y, w, h), data) self.charcode2glyph[charcode] = dict( offset=(face.glyph.bitmap_left, face.glyph.bitmap_top), size=(w, h), atlas_coords=(x, y, w, h), texcoords=[x, y, x + w, y + h], index=gindex, unichar=uchar) except (FT_Exception): print("Warning: TextBox stim could not load font face for charcode / uchar / category: ", charcode, " / ", uchar, " / ", ud.category(uchar)) #charcode, gindex = face.get_next_char(charcode, gindex) self.max_ascender = max_ascender self.max_descender = max_descender #print('linearHoriAdvance:', face.glyph.linearHoriAdvance/65536) #print('max_advance:', face.max_advance_width/64) self.max_tile_width = int(face.glyph.metrics.horiAdvance/64) self.max_tile_height = max_ascender + max_descender self.max_bitmap_size = max_w, max_h # resize atlas height = nextPow2(self.atlas.max_y + 1) self.atlas.resize(height) self.atlas.upload() self.createDisplayLists() self._face = None def createDisplayLists(self): glyph_count = len(self.charcode2unichr) max_tile_width = self.max_tile_width #max_tile_height = self.max_tile_height display_lists_for_chars = {} base = glGenLists(glyph_count) for i, (charcode, glyph) in enumerate(self.charcode2glyph.items()): dl_index = base + i uchar = self.charcode2unichr[charcode] # update tex coords to reflect earlier resize of atlas height. gx1, gy1, gx2, gy2 = glyph['texcoords'] gx1 = gx1/float(self.atlas.width) gy1 = gy1/float(self.atlas.height) gx2 = gx2/float(self.atlas.width) gy2 = gy2/float(self.atlas.height) glyph['texcoords'] = [gx1, gy1, gx2, gy2] glNewList(dl_index, GL_COMPILE) if uchar not in ['\t', '\n']: glBegin(GL_QUADS) x1 = glyph['offset'][0] x2 = x1 + glyph['size'][0] y1 = (self.max_ascender - glyph['offset'][1]) y2 = y1 + glyph['size'][1] glTexCoord2f(gx1, gy2), glVertex2f(x1, -y2) glTexCoord2f(gx1, gy1), glVertex2f(x1, -y1) glTexCoord2f(gx2, gy1), glVertex2f(x2, -y1) glTexCoord2f(gx2, gy2), glVertex2f(x2, -y2) glEnd() glTranslatef(max_tile_width, 0, 0) glEndList() display_lists_for_chars[charcode] = dl_index self.charcode2displaylist = display_lists_for_chars def saveGlyphBitmap(self, file_name=None): if file_name is None: import os file_name = os.path.join(os.getcwd(), self.getID().lower().replace(u' ', u'_') + '.png') from PIL import Image if self.atlas is None: self.loadAtlas() if self.atlas.depth == 1: Image.fromarray(self.atlas.data.reshape(self.atlas.data.shape[:2])).save(file_name) else: Image.fromarray(self.atlas.data).save(file_name) def __del__(self): self._face = None if self.atlas.texid is not None: #glDeleteTextures(1, self.atlas.texid) self.atlas.texid = None self.atlas = None if self.charcode2displaylist is not None: # for dl in self.charcode2displaylist.values(): # glDeleteLists(dl, 1) self.charcode2displaylist.clear() self.charcode2displaylist = None if self.charcode2glyph is not None: self.charcode2glyph.clear() self.charcode2glyph = None if self.charcode2unichr is not None: self.charcode2unichr.clear() self.charcode2unichr = None
21,695
Python
.py
485
33.919588
161
0.601579
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,771
parsedtext.py
psychopy_psychopy/psychopy/visual/textbox/parsedtext.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Created on Sat May 25 00:09:01 2013 @author: Sol """ from textwrap import TextWrapper import io import os from collections import deque from weakref import proxy class ParsedTextDocument: def __init__(self, text_data, text_grid): if os.path.isfile(text_data): with io.open(text_data, 'r', encoding='utf-8-sig') as f: text_data = f.read() self._text_grid = proxy(text_grid) self._num_columns, self._max_visible_rows = text_grid._shape text_data = text_data.replace('\r\n', '\n') # if len(text_data) and text_data[-1] != u'\n': # text_data=text_data+u'\n' self._text = text_data self._children = [] self._limit_text_length = self._max_visible_rows * self._num_columns if 0 < self._limit_text_length < len(self._text): self._text = self._text[:self._limit_text_length] self._default_parse_chunk_size = (self._num_columns * (self._max_visible_rows + 1)) self._text_wrapper = TextWrapper(width=self._num_columns, drop_whitespace=False, replace_whitespace=False, expand_tabs=False) self._text_parsed_to_index = 0 self._parse(0, len(self._text)) def getDisplayedText(self): lli = min(self._max_visible_rows, self.getChildCount()) - 1 lline = self.getParsedLine(lli) return self._text[:lline._index_range[1]] def addChild(self, c): self._children.append(c) def getChildren(self): return self._children def getChildCount(self): return len(self._children) def getText(self): return self._text def getCharAtIndex(self, text_index): try: return self._text[text_index] except Exception: print("WARNING: ParsedTextDocument.getCharAtIndex received " "out of bounds index: ", text_index, self.getTextLength()) return def getTextLength(self): return len(self._text) def deleteText(self, start_index, end_index, insertText=None): start_index = int(start_index) end_index = int(end_index) deleted_text = self._text[start_index:end_index] if insertText is None: self._text = ''.join([self._text[:start_index], self._text[end_index:]]) else: self._text = ''.join([self._text[:start_index], insertText, self._text[end_index:]]) self._parse(start_index) return deleted_text def insertText(self, text, start_index, end_index=None): start_index = int(start_index) if end_index is None: end_index = start_index else: end_index = int(end_index) self._text = ''.join([self._text[:int(start_index)], text, self._text[int(end_index):]]) return self._parse(start_index) def parseTextTo(self, requested_line_index): requested_line_index = int(requested_line_index) if self.getParsedLineCount() > requested_line_index: return requested_line_index add_line_count = requested_line_index - self.getParsedLineCount() + 1 max_chars_to_add = add_line_count * self._num_columns start_index = self._children[-1]._index_range[0] self._parse(start_index, start_index + max_chars_to_add) if self.getParsedLineCount() >= requested_line_index: return requested_line_index return self.getParsedLineCount() - 1 def _parse(self, from_text_index, to_text_index=None): from_text_index = 0 to_text_index = self.getTextLength() line_index = None if self._children: line_index = 0 update_lines = [] if line_index is not None: update_lines = deque(self._children[:]) para_split_text = self._text[from_text_index:to_text_index].splitlines(True) if len(para_split_text) == 0: return current_index = 0 for para_text in para_split_text: current_index = self._wrapText(para_text, current_index, update_lines) if len(update_lines) > 0: self._children = self._children[:-len(update_lines)] self._text_parsed_to_index = current_index def _wrapText(self, para_text, current_index, update_lines): rewrap = False para_text_index = 0 for linestr in self._text_wrapper.wrap(para_text): if (linestr[-1] != u' ' and len(self._text) > current_index + len(linestr) and self._text[current_index + len(linestr)] == u' '): last_space = linestr.rfind(u' ') if last_space > 0: linestr = linestr[:last_space + 1] rewrap = True if len(update_lines) > 0: line = update_lines.popleft() line._text = linestr line._index_range = [current_index, current_index + len(linestr)] line.updateOrds(linestr) line._gl_display_list[0] = 0 else: ParsedTextLine(self, linestr, [current_index, current_index + len(linestr)]) line = self._children[-1] current_index += len(linestr) para_text_index += len(linestr) if rewrap is True: return self._wrapText(para_text[para_text_index:], current_index, update_lines) return current_index def clearCachedLineDisplayLists(self, from_char_index, to_char_index): if from_char_index < 0: from_char_index = 0 elif from_char_index >= len(self._text): from_char_index = len(self._text) - 1 if to_char_index < 0: to_char_index = 0 elif to_char_index >= len(self._text): to_char_index = len(self._text) - 1 start_line = self.getLineIndex(from_char_index) to_line = self.getLineIndex(to_char_index) for l in range(start_line, to_line + 1): self._children[l]._gl_display_list[0] = 0 def getLineInfoByIndex(self, i): c = self._children[i] return c, c._length, c._gl_display_list, c._ords def getParsedLine(self, i): if i < len(self._children): return self._children[i] return None def getParsedLines(self): return self._children def getParsedLineCount(self): return self.getChildCount() def getTextGridCellForCharIndex(self, char_index): for line in self._children: rsi, rei = line._index_range if rsi <= char_index < rei: r = line._line_index c = char_index - rsi return c, r return None def getLineIndex(self, char_index): for line in self._children: rsi, rei = line._index_range if rsi <= char_index < rei: return line.getIndex() return None def getLineFromCharIndex(self, char_index): if char_index < 0: return None for line in self._children: rsi, rei = line._index_range if rsi <= char_index < rei: return line return None def _free(self): self._text = None self._text_wrapper = None del self._text_wrapper for c in self._children: c._free() del self._children[:] def __del__(self): if self._text is not None: self._free() import numpy class ParsedTextLine: charcodes_with_glyphs = None replacement_charcode = None def __init__(self, parent, source_text, index_range): if parent: self._parent = proxy(parent) self._parent.addChild(self) else: self._parent = None self._text = source_text self._index_range = index_range self._line_index = parent.getChildCount() - 1 self._trans_left = 0 self._trans_top = 0 self.updateOrds(self._text) self._gl_display_list = numpy.zeros(parent._num_columns, numpy.uint32) def updateOrds(self, text): if ParsedTextLine.charcodes_with_glyphs is None: active_text_style = self._parent._text_grid._text_box._current_glfont if active_text_style: ParsedTextLine.charcodes_with_glyphs = list(active_text_style.charcode2unichr.keys()) ok_charcodes = ParsedTextLine.charcodes_with_glyphs if ParsedTextLine.replacement_charcode is None: replacement_charcodes = [ord(cc) for cc in [u'?', u' ', u'_', u'-', u'0', u'='] if cc in ok_charcodes] if not replacement_charcodes: ParsedTextLine.replacement_charcode = ok_charcodes[0] else: ParsedTextLine.replacement_charcode = replacement_charcodes[0] self._ords = [] text = text.replace(u'\n', ' ').replace(u'\t', ' ') for c in text: ccode = ord(c) if ccode in ok_charcodes: self._ords.append(ccode) else: self._ords.append(self.replacement_charcode) self._length = len(self._ords) def getIndex(self): return self._line_index def getParent(self): return self._parent def getIndexRange(self): return self._index_range def getText(self): return self._text def getOrds(self): return self._ords def getLength(self): return self._length def getDisplayList(self): return self._gl_display_list def _free(self): self._text = None del self._index_range del self._ords del self._gl_display_list def __del__(self): if self._text is not None: self._free()
10,413
Python
.py
255
29.215686
101
0.557349
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,772
textureatlas.py
psychopy_psychopy/psychopy/visual/textbox/textureatlas.py
#!/usr/bin/env python # -*- coding: utf-8 -*- #pylint: skip-file # ----------------------------------------------------------------------------- # # FreeType high-level python API - Copyright 2011 Nicolas P. Rougier # Distributed under the terms of the new BSD license. # # ----------------------------------------------------------------------------- from pyglet.gl import (GLuint, glEnable, GL_TEXTURE_2D, glBindTexture, glTexParameteri, GL_TEXTURE_WRAP_S, GL_CLAMP, GL_TEXTURE_WRAP_T, glTexImage2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR, GL_TEXTURE_MAG_FILTER, GL_ALPHA, GL_UNSIGNED_BYTE, GL_RGB, GL_RGBA, glGenTextures) import ctypes import math import numpy as np import sys class TextureAtlas: ''' Group multiple small data regions into a larger texture. The algorithm is based on the article by Jukka Jylänki : "A Thousand Ways to Pack the Bin - A Practical Approach to Two-Dimensional Rectangle Bin Packing", February 27, 2010. More precisely, this is an implementation of the Skyline Bottom-Left algorithm based on C++ sources provided by Jukka Jylänki at: http://clb.demon.fi/files/RectangleBinPack/ Example usage: -------------- atlas = TextureAtlas(512,512,3) region = atlas.get_region(20,20) ... atlas.set_region(region, data) ''' def __init__(self, width=1024, height=1024, depth=1): ''' Initialize a new atlas of given size. Parameters ---------- width : int Width of the underlying texture height : int Height of the underlying texture depth : 1 or 3 Depth of the underlying texture ''' super(TextureAtlas, self).__init__() self.width = int(math.pow(2, int(math.log(width, 2) + 0.5))) self.height = int(math.pow(2, int(math.log(height, 2) + 0.5))) self.depth = depth self.nodes = [(0, 0, self.width), ] self.data = np.zeros((self.height, self.width, self.depth), dtype=np.ubyte) self.texid = None self.used = 0 self.max_y = 0 def getTextureID(self): return self.texid def upload(self): ''' Upload atlas data into video memory. ''' glEnable(GL_TEXTURE_2D) if self.texid is None: self.texid = GLuint(0) glGenTextures(1, ctypes.byref(self.texid)) glBindTexture(GL_TEXTURE_2D, self.texid) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) if self.depth == 1: glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, self.width, self.height, 0, GL_ALPHA, GL_UNSIGNED_BYTE, self.data.ctypes) elif self.depth == 3: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, self.width, self.height, 0, GL_RGB, GL_UNSIGNED_BYTE, self.data.ctypes) else: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, self.width, self.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, self.data.ctypes) glBindTexture(GL_TEXTURE_2D, 0) def resize(self, new_height): # np.zeros((self.height, self.width, self.depth), self.data = self.data[:new_height] # dtype=np.ubyte) self.height = new_height def set_region(self, region, data): ''' Set a given region width provided data. Parameters ---------- region : (int,int,int,int) an allocated region (x,y,width,height) data : numpy array data to be copied into given region ''' x, y, width, height = region self.data[y:y + height, x:x + width, :] = data def get_region(self, width, height): ''' Get a free region of given size and allocate it Parameters ---------- width : int Width of region to allocate height : int Height of region to allocate Return ------ A newly allocated region as (x,y,width,height) or (-1,-1,0,0) ''' best_height = sys.maxsize best_index = -1 best_width = sys.maxsize region = 0, 0, width, height for i in range(len(self.nodes)): y = self.fit(i, width, height) if y >= 0: node = self.nodes[i] if (y + height < best_height or (y + height == best_height and node[2] < best_width)): best_height = y + height best_index = i best_width = node[2] region = node[0], y, width, height if best_index == -1: return -1, -1, 0, 0 node = region[0], region[1] + height, width self.nodes.insert(best_index, node) i = best_index + 1 while i < len(self.nodes): node = self.nodes[i] prev_node = self.nodes[i - 1] if node[0] < prev_node[0] + prev_node[2]: shrink = prev_node[0] + prev_node[2] - node[0] x, y, w = self.nodes[i] self.nodes[i] = x + shrink, y, w - shrink if self.nodes[i][2] <= 0: del self.nodes[i] i -= 1 else: break else: break i += 1 self.max_y = region[1] + region[3] self.merge() self.used += width * height return region def fit(self, index, width, height): ''' Test if region (width,height) fit into self.nodes[index] Parameters ---------- index : int Index of the internal node to be tested width : int Width or the region to be tested height : int Height or the region to be tested ''' node = self.nodes[index] x, y = node[0], node[1] width_left = width if x + width > self.width: return -1 i = index while width_left > 0: node = self.nodes[i] y = max(y, node[1]) if y + height > self.height: return -1 width_left -= node[2] i += 1 return y def merge(self): ''' Merge nodes ''' i = 0 while i < len(self.nodes) - 1: node = self.nodes[i] next_node = self.nodes[i + 1] if node[1] == next_node[1]: self.nodes[i] = node[0], node[1], node[2] + next_node[2] del self.nodes[i + 1] else: i += 1 def totalArea(self): return self.width * self.height def usedArea(self): return self.used def freeArea(self): return self.totalArea() - self.usedArea() def __del__(self): self.texid = None self.data = None self.nodes = None
7,448
Python
.py
203
25.817734
89
0.511253
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,773
__init__.py
psychopy_psychopy/psychopy/visual/textbox/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Created on Thu Mar 21 18:38:35 2013 @author: Sol """ import os import inspect import numbers from weakref import proxy import time import numpy as np from psychopy import core, misc, colors, logging import psychopy.tools.colorspacetools as colortools import psychopy.tools.arraytools as arraytools import pyglet pyglet.options['debug_gl'] = False from pyglet.gl import (glCallList, glFinish, glGenLists, glNewList, glViewport, glMatrixMode, glLoadIdentity, glDisable, glEnable, glColorMaterial, glBlendFunc, glTranslatef, glColor4f, glRectf, glLineWidth, glBegin, GL_LINES, glVertex2d, glEndList, glClearColor, gluOrtho2D, glOrtho, glDeleteLists, GL_COMPILE, GL_PROJECTION, GL_MODELVIEW, glEnd, GL_DEPTH_TEST, GL_BLEND, GL_COLOR_MATERIAL, GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, glIsEnabled, GL_LINE_SMOOTH, GLint, GLfloat, glGetIntegerv, GL_LINE_WIDTH, glGetFloatv, GL_ALIASED_LINE_WIDTH_RANGE, GL_SMOOTH_LINE_WIDTH_RANGE, GL_SMOOTH_LINE_WIDTH_GRANULARITY, GL_POLYGON_SMOOTH) from .fontmanager import FontManager from .textgrid import TextGrid def getTime(): return core.getTime() def is_sequence(arg): return ( # not hasattr(arg, "strip") and hasattr(arg, "__getitem__") or hasattr(arg, "__iter__")) _system_font_manager = None def getFontManager(mono_only=True): global _system_font_manager if _system_font_manager is None: _system_font_manager = FontManager(mono_only) return _system_font_manager # check that font manager is working fm = getFontManager() font_names = fm.getFontFamilyNames() if len(font_names) == 0: logging.warn("TextBox Font Manager Found No Fonts.") def getGLInfo(): gl_info = dict() gl_info['GL_LINE_SMOOTH'] = glIsEnabled(GL_LINE_SMOOTH) lwidth = GLint() glGetIntegerv(GL_LINE_WIDTH, lwidth) gl_info['GL_LINE_WIDTH'] = lwidth awrange = (GLfloat * 2)(0.0, 0.0) glGetFloatv(GL_ALIASED_LINE_WIDTH_RANGE, awrange) gl_info['GL_ALIASED_LINE_WIDTH_RANGE'] = awrange[0], awrange[1] swrange = (GLfloat * 2)(0.0, 0.0) glGetFloatv(GL_SMOOTH_LINE_WIDTH_RANGE, swrange) gl_info['GL_SMOOTH_LINE_WIDTH_RANGE'] = swrange[0], swrange[1] swg = GLfloat() glGetFloatv(GL_SMOOTH_LINE_WIDTH_GRANULARITY, swg) gl_info['GL_SMOOTH_LINE_WIDTH_GRANULARITY'] = swg return gl_info class TextBox: """ Similar to the visual.TextStim component, TextBox can be used to display text within a psychopy window. TextBox and TextStim each have different strengths and weaknesses. You should select the most appropriate text component type based on how it will be used within the experiment. NOTE: As of PsychoPy 1.79, TextBox should be considered experimental. The two TextBox demo scripts provided have been tested on all PsychoPy supported OS's and run without exceptions. However there are very likely bugs in the existing TextBox code and the TextBox API will be further enhanced and improved (i.e. changed) over the next couple months. **TextBox Features** * Text character placement is very well defined, useful when the exact positioning of each letter needs to be known. * The text string that is displayed can be changed ( setText() ) and drawn ( win.draw() ) **very** quickly. See the TextBox vs. TextStim comparison table for details. * Built-in font manager; providing easy access to the font family names and styles that are available on the computer being used. * TextBox is a composite stimulus type, with the following graphical elements, many of which can be changed to control many aspects of how the TextBox is displayed.: - TextBox Border / Outline - TextBox Fill Area - Text Grid Cell Lines - Text Glyphs * When using 'rgb' or 'rgb255' color spaces, colors can be specified as a list/tuple of 3 elements (red, green, blue), or with four elements (reg, green, blue, alpha) which allows different elements of the TextBox to use different opacity settings if desired. For colors that include the alpha channel value, it will be applied instead of the opacity setting of the TextBox, effectively overriding the stimulus defined opacity for that part of the textbox graphics. Colors that do not include an alpha channel use the opacity setting as normal. * Text Line Spacing can be controlled. **Textbox Limitations** * Only Monospace Fonts are supported. * TextBox component is not a completely **standard** psychopy visual stim and has the following functional difference: - TextBox attributes are never accessed directly; get* and set* methods are always used (this will be changed to use class properties in the future). - Setting an attribute of a TextBox only supports value replacement, ( textbox.setFontColor([1.0,1.0,1.0]) ) and does not support specifying operators. * Some key word arguments supported by other stimulus types in general, or by TextStim itself, are not supported by TextBox. See the TextBox class definition for the arguments that are supported. * When a new font, style, and size are used it takes about 1 second to load and process the font. This is a one time delay for a given font name, style, and size. After first being loaded, the same font style can be used or re-applied to multiple TextBox components with no significant delay. * Auto logging or auto drawing is not currently supported. TextStim and TextBox Comparison: ============================ ============= =========== Feature TextBox TextStim ============================ ============= =========== Change text + redraw time^ 1.513 msec 28.537 msec No change + redraw time^ 0.240 msec 0.931 msec Initial Creation time^ 0.927 msec 0.194 msec MonoSpace Font Support Yes Yes Non MonoSpace Font Support No Yes Adjustable Line Spacing Yes No Precise Text Pos. Info Yes No Auto logging Support No Yes Rotation Support No Yes Word Wrapping Support Yes Yes ============================ ============= =========== ^ Times are in msec.usec format. Tested using the textstim_vs_textbox.py demo script provided with the PsychoPy distribution. Results are dependent on text length, video card, and OS. Displayed results are based on 120 character string with an average of 24 words. Test computer used Windows 7 64 bit, PsychoPy 1.79, with a i7 3.4 Ghz CPU, 8 GB RAM, and NVIDIA 480 GTX 2GB graphics card. Example:: from psychopy import visual win=visual.Window(...) # A Textbox stim that will look similar to a TextStim component textstimlike=visual.TextBox( window=win, text="This textbox looks most like a textstim.", font_size=18, font_color=[-1,-1,1], color_space='rgb', size=(1.8,.1), pos=(0.0,.5), units='norm') # A Textbox stim that uses more of the supported graphical features # textboxloaded=visual.TextBox( window=win text='TextBox showing all supported graphical elements', font_size=32, font_color=[1,1,1], border_color=[-1,-1,1], # draw a blue border around stim border_stroke_width=4, # border width of 4 pix. background_color=[-1,-1,-1], # fill the stim background grid_color=[1,-1,-1,0.5], # draw a red line around each # possible letter area, # 50% transparent grid_stroke_width=1, # with a width of 1 pix textgrid_shape=[20,2], # specify area of text box # by the number of cols x # number of rows of text to support # instead of by a screen # units width x height. pos=(0.0,-.5), # If the text string length < num rows * num cols in # textgrid_shape, how should text be justified? # grid_horz_justification='center', grid_vert_justification='center') textstimlike.draw() textboxloaded.draw() win.flip() """ _textbox_instances = {} _gl_info = None def __init__(self, window=None, # PsychoPy Window instance text='Default Test Text.', # Initial text to be displayed. font_name=None, # Family name of Font bold=False, # Bold and italics are used to italic=False, # determine style of font font_size=32, # Pt size to use for font. font_color=(0, 0, 0, 1), # Color to draw the text with. dpi=72, # DPI used to create font bitmaps line_spacing=0, # Amount of extra spacing to add between line_spacing_units='pix', # lines of text. background_color=None, # Color to use to fill the entire area # on the screen TextBox is using. border_color=None, # TextBox border color to use. border_stroke_width=1, # Stroke width of TextBox boarder (in pix) size=None, # (width,height) desired for the TextBox # stim to use. Specify using the unit # type the textBox is using. textgrid_shape=None, # (cols,rows) of characters to use when # creating the textgrid layout. # rows*cols = maximum number of chars # that can be displayed. If textgrid_shape # is not None, then the TextBox size # must be at least large enough to hold # the number of specified cols and rows. # If the size specified is less than # what is needed, the size will be increased # automatically. pos=(0.0, 0.0), # (x,y) screen position for the TextBox # stim. Specify using the unit # type the textBox is using. align_horz='center', # Determines how TextBox x pos is # should be interpreted to. # 'left', 'center', 'right' are valid options. align_vert='center', # Determines how TextBox y pos is # should be interpreted to. # 'left', 'center', 'right' are valid options. units='norm', # Coordinate unit type to use for position # and size related attributes. Valid # options are 'pix', 'cm', 'deg', 'norm' # Only pix is currently working though. grid_color=None, # Color to draw the TextBox text grid # lines with. grid_stroke_width=1, # Line thickness (in pix) to use when # displaying text grid lines. color_space='rgb', # PsychoPy color space to use for any # color attributes of TextBox. opacity=1.0, # Opacity (transparency) to use for # TextBox graphics, assuming alpha # channel was not specified in the color # attribute. grid_horz_justification='left', # 'left', 'center', 'right' grid_vert_justification='top', # 'top', 'bottom', 'center' autoLog=True, # Log each time stim is updated. interpolate=False, name=None ): self._window = proxy(window) self._font_name = font_name if self.getWindow().useRetina: self._font_size = font_size*2 else: self._font_size = font_size self._dpi = dpi self._bold = bold self._italic = italic self._text = text self._label = name self._line_spacing = line_spacing self._line_spacing_units = line_spacing_units self._border_color = border_color self._background_color = background_color self._border_stroke_width = border_stroke_width self._grid_horz_justification = grid_horz_justification self._grid_vert_justification = grid_vert_justification self._align_horz = align_horz self._align_vert = align_vert self._size = size self._position = pos self._textgrid_shape = textgrid_shape self._interpolate = interpolate self._draw_start_dlist = None self._draw_end_dlist = None self._draw_te_background_dlist = None if TextBox._gl_info is None: TextBox._gl_info = getGLInfo() aliased_wrange = TextBox._gl_info['GL_ALIASED_LINE_WIDTH_RANGE'] antia_wrange = TextBox._gl_info['GL_SMOOTH_LINE_WIDTH_RANGE'] if grid_stroke_width and grid_color: if interpolate: if grid_stroke_width < antia_wrange[0]: self._grid_stroke_width = antia_wrange[0] if grid_stroke_width > antia_wrange[1]: self._grid_stroke_width = antia_wrange[1] else: if grid_stroke_width < aliased_wrange[0]: self._grid_stroke_width = aliased_wrange[0] if grid_stroke_width > aliased_wrange[1]: self._grid_stroke_width = aliased_wrange[1] if border_stroke_width and border_color: if interpolate: if border_stroke_width < antia_wrange[0]: self._border_stroke_width = antia_wrange[0] if border_stroke_width > antia_wrange[1]: self._border_stroke_width = antia_wrange[1] else: if border_stroke_width < aliased_wrange[0]: self._border_stroke_width = aliased_wrange[0] if border_stroke_width > aliased_wrange[1]: self._border_stroke_width = aliased_wrange[1] self._units = units if self._units is None: self._units = self._window.units self._opacity = opacity if opacity is None: self._opacity = 1.0 elif float(opacity) and float(opacity) >= 0 and float(opacity) <= 1.0: self._opacity = float(opacity) else: raise ValueError( "Text Box: opacity must be a number between 0.0 and 1.0, or None (which == 1.0). %s is not valid" % (str(opacity))) self._color_space = color_space if self._color_space is None: self._color_space = self._window.colorSpace # TODO: Implement support for autoLog self._auto_log = autoLog self._current_glfont = None self._text_grid = None if self._label is None: self._label = 'TextBox_%s' % (str(int(time.time()))) fm = getFontManager() if self._font_name is None: self._font_name = fm.getFontFamilyStyles()[0][0] gl_font = fm.getGLFont( self._font_name, self._font_size, self._bold, self._italic, self._dpi) self._current_glfont = gl_font if size is None and textgrid_shape is None: print('WARNING (TextBox) - No `size` or `textgrid_shape` given. Defaulting to displaying all text in a single row.') textgrid_shape = (len(text), 1) self._text_grid = TextGrid(self, line_color=grid_color, line_width=grid_stroke_width, font_color=list( font_color), shape=textgrid_shape, grid_horz_justification=grid_horz_justification, grid_vert_justification=grid_vert_justification) self._text_grid.setCurrentFontDisplayLists( gl_font.charcode2displaylist) self._text = self._text.replace('\r\n', '\n') self._text_grid._createParsedTextDocument(self._text) self._textbox_instances[self.getLabel()] = proxy(self) def getWindow(self): """ Returns the psychopy window that the textBox is associated with. """ return self._window def getText(self): """ Return the text to display. """ return self._text def setText(self, text_source): """ Set the text to be displayed within the Textbox. Note that once a TextBox has been created, the number of character rows and columns is static. To change the size of a TextBox, a new TextBox stim must be created to replace the current Textbox stim. Therefore ensure that the textbox is large enough to display the largest length string to be presented in the TextBox. Characters that do not fit within the TextBox will not be displayed. Color value must be valid for the color space being used by the TextBox. """ if not self._text: raise ValueError( "TextBox.setText only accepts strings with a length > 0") self._text = text_source.replace('\r\n', '\n') return self._text_grid._setText(self._text) def getDisplayedText(self): """ Return the text that fits within the TextBox and therefore is actually seen. This is equal to:: text_length=len(self.getText()) cols,rows=self.getTextGridShape() displayed_text=self.getText()[0:min(text_length,rows*cols] """ return self._getTextWrappedDoc().getDisplayedText() def getTextGridCellPlacement(self): """Returns a 3D numpy array containing position information for each text grid cell in the TextBox. The array has the shape (`num_cols`, `num_rows`, `cell_bounds`), where num_cols is the number of `textgrid` columns in the TextBox. `num_rows` is the number of `textgrid` rows in the `TextBox`. `cell_bounds` is a 4 element array containing the (x pos, y pos, width, height) data for the given cell. Position fields are for the top left hand corner of the cell box. Column and Row indices start at 0. To get the shape of the textgrid in terms of columns and rows, use:: cell_pos_array=textbox.getTextGridCellPlacement() col_row_count=cell_pos_array.shape[:2] To access the position, width, and height for textgrid cell at column 0 and row 0 (so the top left cell in the textgrid):: cell00=cell_pos_array[0,0,:] For the cell at col 3, row 1 (so 4th cell on second row):: cell41=cell_pos_array[4,1,:] """ col_lines = self._text_grid._col_lines row_lines = self._text_grid._row_lines cellinfo = np.zeros( (len(col_lines[:-1]), len(row_lines[:-1]), 4), dtype=np.float32) tb_tl = self._getTopLeftPixPos() tg_tl = self._text_grid._position starting_x, starting_y = tb_tl[0] + tg_tl[0], tb_tl[1] - tg_tl[1] for i, x in enumerate(col_lines[:-1]): for j, y in enumerate(row_lines[:-1]): px, py = starting_x + x, starting_y + y w, h = col_lines[i + 1] - px, -(row_lines[j + 1] - py) cellinfo[i, j, 0] = px cellinfo[i, j, 1] = py cellinfo[i, j, 2] = w cellinfo[i, j, 3] = h for i, x in enumerate(col_lines[:-1]): for j, y in enumerate(row_lines[:-1]): x, y = self._pix2units( (float(cellinfo[i, j, 0]), float(cellinfo[i, j, 1]))) w, h = self._pix2units( (float(cellinfo[i, j, 2]), float(cellinfo[i, j, 3])), False) cellinfo[i, j, 0] = x cellinfo[i, j, 1] = y cellinfo[i, j, 2] = w cellinfo[i, j, 3] = h return cellinfo def getTextGridCellForCharIndex(self, char_index): return self._getTextWrappedDoc().getTextGridCellForCharIndex(char_index) def getGlyphPositionForTextIndex(self, char_index): """For the provided char_index, which is the index of one character in the current text being displayed by the TextBox ( getDisplayedText() ), return the bounding box position, width, and height for the associated glyph drawn to the screen. This factors in the glyphs position within the textgrid cell it is being drawn in, so the returned bounding box is for the actual glyph itself, not the textgrid cell. For textgrid cell placement information, see the getTextGridCellPlacement() method. The glyph position for the given text index is returned as a tuple (x,y,width,height), where x,y is the top left hand corner of the bounding box. Special Cases: * If the index provided is out of bounds for the currently displayed text, None is returned. * For u' ' (space) characters, the full textgrid cell bounding box is returned. * For u'\n' ( new line ) characters,the textgrid cell bounding box is returned, but with the box width set to 0. """ if char_index < 0 or char_index >= len(self.getDisplayedText()): raise IndexError( "The provided index of %d is out of range for the currently displayed text." % (char_index)) # Get the Glyph info for the char in question: gl_font = getFontManager().getGLFont(self._font_name, self._font_size, self._bold, self._italic, self._dpi) glyph_data = gl_font.charcode2glyph.get(ord(self._text[char_index])) ox, oy = glyph_data['offset'][ 0], gl_font.max_ascender - glyph_data['offset'][1] gw, gh = glyph_data['size'] # get the col,row for the xhar index provided col_row = self._getTextWrappedDoc().getTextGridCellForCharIndex(char_index) if col_row is None: return None cline = self._getTextWrappedDoc().getParsedLine(col_row[1]) c = col_row[0] + cline._trans_left r = col_row[1] + cline._trans_top x, y, width, height = self.getTextGridCellPlacement()[c, r, :] ox, oy = self._pix2units((ox, oy), False) gw, gh = self._pix2units((gw, gh), False) return x + ox, y - oy, gw, gh def _getTextWrappedDoc(self): return self._text_grid._text_document def getPosition(self): """Return the x,y position of the textbox, in getUnitType() coord space. """ return self._position def setPosition(self, pos): """ Set the (x,y) position of the TextBox on the Monitor. The position must be given using the unit coord type used by the stim. The TextBox position is interpreted differently depending on the Horizontal and Vertical Alignment settings of the stim. See getHorzAlignment() and getVertAlignment() for more information. For example, if the TextBox alignment is specified as left, top, then the position specifies the top left hand corner of where the stim will be drawn. An alignment of bottom,right indicates that the position value will define where the bottom right corner of the TextBox will be drawn. A horz., vert. alignment of center, center will place the center of the TextBox at pos. """ if pos[0] != self._position[0] or pos[1] != self._position[1]: self._position = pos[0], pos[1] self._deleteBackgroundDL() self._deleteStartDL() def getUnitType(self): """ Returns which of the psychopy coordinate systems are used by the TextBox. Position and size related attributes mush be specified relative to the unit type being used. Valid options are: * pix * norm * cm """ return self._units def getHorzAlign(self): """ Return what textbox x position should be interpreted as. Valid options are 'left', 'center', or 'right' . """ return self._align_horz def setHorzAlign(self, v): """ Specify how the horizontal (x) component of the TextBox position is to be interpreted. left = x position is the left edge, right = x position is the right edge x position, and center = the x position is used to center the stim horizontally. """ if v != self._align_horz: self._align_horz = v self._deleteBackgroundDL() self._deleteStartDL() def getVertAlign(self): """ Return what textbox y position should be interpreted as. Valid options are 'top', 'center', or 'bottom' . """ return self._align_vert def setVertAlign(self, v): """ Specify how the vertical (y) component of the TextBox position is to be interpreted. top = y position is the top edge, bottom = y position is the bottom edge y position, and center = the y position is used to center the stim vertically. """ if v != self._align_vert: self._align_vert = v self._deleteBackgroundDL() self._deleteStartDL() def getSize(self): """ Return the width,height of the TextBox, using the unit type being used by the stimulus. """ return self._size def getFontSize(self): if self.getWindow().useRetina: return self._font_size//2 return self._font_size def getFontColor(self): """ Return the color used when drawing text glyphs. """ return self._text_grid._font_color def setFontColor(self, c): """ Set the color to use when drawing text glyphs within the TextBox. Color value must be valid for the color space being used by the TextBox. For 'rgb', 'rgb255', and 'norm' based colors, three or four element lists are valid. Three element colors use the TextBox getOpacity() value to determine the alpha channel for the color. Four element colors use the value of the fourth element to set the alpha value for the color. """ if c != self._text_grid._font_color: self._text_grid._font_color = c self._text_grid._deleteTextDL() def getBorderColor(self): """ A border can be drawn around the perimeter of the TextBox. This method sets the color of that border. """ return self._border_color def setBorderColor(self, c): """ Set the color to use for the border of the textBox. The TextBox border is a rectangular outline drawn around the edges of the TextBox stim. Color value must be valid for the color space being used by the TextBox. A value of None will disable drawing of the border. """ if c != self._border_color: self._border_color = c self._deleteBackgroundDL() def getBackgroundColor(self): """ Get the color used to fill the rectangular area of the TextBox stim. All other graphical elements of the TextBox are drawn on top of the background. """ return self._background_color def setBackgroundColor(self, c): """ Set the fill color used to fill the rectangular area of the TextBox stim. Color value must be valid for the color space being used by the TextBox. A value of None will disable drawing of the TextBox background. """ if c != self._background_color: self._background_color = c self._deleteBackgroundDL() def getTextGridLineColor(self): """ Return the color used when drawing the outline of the text grid cells. Each letter displayed in a TextBox populates one of the text cells defined by the shape of the TextBox text grid. Color value must be valid for the color space being used by the TextBox. A value of None indicates drawing of the textgrid lines is disabled. """ return self._text_grid._line_color def setTextGridLineColor(self, c): """ Set the color used when drawing text grid lines. These are lines that can be drawn which mark the bounding box for each character within the TextBox text grid. Color value must be valid for the color space being used by the TextBox. Provide a value of None to disable drawing of textgrid lines. """ if c != self._text_grid._line_color: self._text_grid._line_color = c self._text_grid._deleteGridLinesDL() def getColorSpace(self): """Returns the psychopy color space used when specifying colors for the TextBox. Supported values are: * 'rgb' * 'rbg255' * 'norm' * hex (implicit) * html name (implicit) See the Color Space section of the PsychoPy docs for details. """ return self._color_space def getHorzJust(self): """Return how text should laid out horizontally when the number of columns of each text grid row is greater than the number needed to display the text for that text row. """ return self._text_grid._horz_justification def setHorzJust(self, v): """ Specify how text within the TextBox should be aligned horizontally. For example, if a text grid has 10 columns, and the text being displayed is 6 characters in length, the horizontal justification determines if the text should be draw starting at the left of the text columns (left), or should be centered on the columns ('center', in this example there would be two empty text cells to the left and right of the text.), or should be drawn such that the last letter of text is drawn in the last column of the text row ('right'). """ if v != self._text_grid._horz_justification: self._text_grid.setHorzJust(v) self._text_grid._deleteTextDL() def getVertJust(self): """ Return how text should laid out vertically when the number of text grid rows is greater than the number needed to display the current text """ return self._text_grid._vert_justification def setVertJust(self, v): """ Specify how text within the TextBox should be aligned vertically. For example, if a text grid has 3 rows for text, and the text being displayed all fits on one row, the vertical justification determines if the text should be draw on the top row of the text grid (top), or should be centered on the rows ('center', in this example there would be one row above and below the row used to draw the text), or should be drawn on the last row of the text grid, ('bottom'). """ if v != self._text_grid._vert_justification: self._text_grid.setVertJust(v) self._text_grid._deleteTextDL() def getBorderWidth(self): """ Get the stroke width of the optional TextBox area outline. This is always given in pixel units. """ return self._border_stroke_width def setBorderWidth(self, c): """ Set the stroke width (in pixels) to use for the border of the TextBox stim. Border values must be within the range of stroke widths supported by the OpenGL driver used by the graphics. Setting the width outside the valid range will result in the stroke width being clamped to the nearest end of the valid range. Use the TextBox.getValidStrokeWidths() to access the minimum - maximum range of valid line widths. """ if c != self._border_stroke_width: if self._interpolate: lrange = TextBox._gl_info['GL_SMOOTH_LINE_WIDTH_RANGE'] else: lrange = TextBox._gl_info['GL_ALIASED_LINE_WIDTH_RANGE'] if c < lrange[0]: c = lrange[0] elif c > lrange[1]: c = lrange[1] self._border_stroke_width = c self._deleteBackgroundDL() def getTextGridLineWidth(self): """ Return the stroke width (in pixels) of the optional lines drawn around the text grid cell areas. """ return self._text_grid._line_width def setTextGridLineWidth(self, c): """ Set the stroke width (in pixels) to use for the text grid character bounding boxes. Border values must be within the range of stroke widths supported by the OpenGL driver used by the computer graphics card. Setting the width outside the valid range will result in the stroke width being clamped to the nearest end of the valid range. Use the TextBox.getGLineRanges() to access a dict containing some OpenGL parameters which provide the minimum, maximum, and resolution of valid line widths. """ if c != self._text_grid._line_width: if self._interpolate: lrange = TextBox._gl_info['GL_SMOOTH_LINE_WIDTH_RANGE'] else: lrange = TextBox._gl_info['GL_ALIASED_LINE_WIDTH_RANGE'] if c < lrange[0]: c = lrange[0] elif c > lrange[1]: c = lrange[1] self._text_grid._line_width = c self._text_grid._deleteGridLinesDL() def getValidStrokeWidths(self): """ Returns the stroke width range supported by the graphics card being used. If the TextBox is Interpolated, a tuple is returns using float values, with the following structure: ((min_line_width, max_line_width), line_width_granularity) If Interpolation is disabled for the TextBox, the returned tuple elements are int values, with the following structure: (min_line_width, max_line_width) """ if self._interpolate: return (TextBox._gl_info['GL_SMOOTH_LINE_WIDTH_RANGE'], TextBox._gl_info['GL_SMOOTH_LINE_WIDTH_GRANULARITY']) else: return self._gl_info['GL_ALIASED_LINE_WIDTH_RANGE'] def getOpacity(self): """ Get the default TextBox transparency level used for color related attributes. 0.0 equals fully transparent, 1.0 equals fully opaque. """ return self._opacity def setOpacity(self, o): """ Sets the TextBox transparency level to use for color related attributes of the Textbox. 0.0 equals fully transparent, 1.0 equals fully opaque. If opacity is set to None, it is assumed to have a default value of 1.0. When a color is defined with a 4th element in the colors element list, then this opacity value is ignored and the alpha value provided in the color itself is used for that TextGrid element instead. """ if o != self._opacity and o >= 0.0 and o <= 1.0: self._text_grid._deleteTextDL() self._deleteBackgroundDL() self._text_grid._deleteGridLinesDL() self._deleteStartDL() self._deleteEndDL() self._opacity = o def getInterpolated(self): """ Returns whether interpolation is enabled for the TextBox when it is drawn. When True, GL_LINE_SMOOTH and GL_POLYGON_SMOOTH are enabled within OpenGL; otherwise they are disabled. """ return self._interpolate def setInterpolated(self, interpolate): """ Specify whether interpolation should be enabled for the TextBox when it is drawn. When interpolate == True, GL_LINE_SMOOTH and GL_POLYGON_SMOOTH are enabled within OpenGL. When interpolate is set to False, GL_POLYGON_SMOOTH and GL_LINE_SMOOTH are disabled. """ if interpolate != self._interpolate: self._deleteStartDL() self._interpolate = interpolate def getLabel(self): """ Return the label / name assigned to the textbox. This does not impact how the stimulus looks when drawn, and instead is used for internal purposes only. """ return self._label def getName(self): """ Same as the GetLabel method. """ return self._label def getAutoLog(self): """ Indicates if changes to textBox attribute values should be logged automatically by PsychoPy. *Currently not supported by TextBox.* """ return self._auto_log def setAutoLog(self, v): """ Specify if changes to textBox attribute values should be logged automatically by PsychoPy. True enables auto logging; False disables it. *Currently not supported by TextBox.* """ self._auto_log = v def getLineSpacing(self): """ Return the additional spacing being applied between rows of text. The value is in units specified by the textbox getUnits() method. """ return self._line_spacing def draw(self): """ Draws the TextBox to the back buffer of the graphics card. Then call win.flip() to display the changes drawn. If draw() is not called prior to a call to win.flip(), the textBox will not be displayed for that retrace. """ self._te_start_gl() self._te_bakground_dlist() self._text_grid._text_glyphs_gl() self._text_grid._textgrid_lines_gl() self._te_end_gl() def _te_start_gl(self): if not self._draw_start_dlist: dl_index = glGenLists(1) glNewList(dl_index, GL_COMPILE) glViewport(0, 0, self._window.size[0], self._window.size[1]) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0, self._window.size[0], 0, self._window.size[1], -1, 1) glMatrixMode(GL_MODELVIEW) glLoadIdentity() self._window.depthTest = False glEnable(GL_BLEND) glEnable(GL_COLOR_MATERIAL) glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) if self._interpolate: glEnable(GL_LINE_SMOOTH) glEnable(GL_POLYGON_SMOOTH) else: glDisable(GL_LINE_SMOOTH) glDisable(GL_POLYGON_SMOOTH) t, l = self._getTopLeftPixPos() glTranslatef(t, l, 0) glEndList() self._draw_start_dlist = dl_index glCallList(self._draw_start_dlist) def _deleteStartDL(self): if self._draw_start_dlist: glDeleteLists(self._draw_start_dlist, 1) self._draw_start_dlist = None def _te_bakground_dlist(self): if not self._draw_te_background_dlist and (self._background_color or self._border_color): dl_index = glGenLists(1) glNewList(dl_index, GL_COMPILE) # draw textbox_background and outline border_thickness = self._border_stroke_width size = self._getPixelSize() if self._border_stroke_width is None: border_thickness = 0 if self._background_color: bcolor = self._toRGBA(self._background_color) glColor4f(*bcolor) glRectf(0, 0, size[0], -size[1]) if self._border_color: glLineWidth(border_thickness) bcolor = self._toRGBA(self._border_color) glColor4f(*bcolor) glBegin(GL_LINES) x1 = 0 y1 = 0 x2, y2 = size x2, y2 = x2, y2 hbthick = border_thickness // 2 if hbthick < 1: hbthick = 1 glVertex2d(x1 - border_thickness, y1 + hbthick) glVertex2d(x2 + border_thickness, y1 + hbthick) glVertex2d(x2 + hbthick, y1) glVertex2d(x2 + hbthick, -y2) glVertex2d(x2 + border_thickness, -y2 - hbthick) glVertex2d(x1 - border_thickness, -y2 - hbthick) glVertex2d(x1 - hbthick, -y2) glVertex2d(x1 - hbthick, y1) glEnd() glColor4f(0.0, 0.0, 0.0, 1.0) glEndList() self._draw_te_background_dlist = dl_index if (self._background_color or self._border_color): glCallList(self._draw_te_background_dlist) def _deleteBackgroundDL(self): if self._draw_te_background_dlist: glDeleteLists(self._draw_te_background_dlist, 1) self._draw_te_background_dlist = None def _te_end_gl(self): if not self._draw_end_dlist: dl_index = glGenLists(1) glNewList(dl_index, GL_COMPILE) rgb = self._window.rgb rgb = TextBox._toRGBA2( rgb, 1, self._window.colorSpace, self._window) glClearColor(rgb[0], rgb[1], rgb[2], 1.0) glViewport(0, 0, int(self._window.size[0]), int( self._window.size[1])) glMatrixMode(GL_PROJECTION) # Reset The Projection Matrix glLoadIdentity() gluOrtho2D(-1, 1, -1, 1) glMatrixMode(GL_MODELVIEW) # Reset The Projection Matrix glLoadIdentity() glEndList() self._draw_end_dlist = dl_index glCallList(self._draw_end_dlist) def _deleteEndDL(self): if self._draw_end_dlist: glDeleteLists(self._draw_end_dlist, 1) self._draw_end_dlist = None @staticmethod def _toPix(xy, units, window): if isinstance(xy, numbers.Number): xy = xy, xy elif is_sequence(xy): if len(xy) == 1: xy = xy[0], xy[0] else: xy = xy[:2] else: return ValueError("TextBox: coord variables must be array-like or a single number. Invalid: %s" % (str(xy))) if not isinstance(xy[0], numbers.Number) or not isinstance(xy[1], numbers.Number): return ValueError("TextBox: coord variables must only contain numbers. Invalid: %s" % (str(xy))) if units in ('pix', 'pixs'): return xy if units in ['deg', 'degs']: return misc.deg2pix(xy[0], window.monitor), misc.deg2pix(xy[1], window.monitor) if units in ['cm']: return misc.cm2pix(xy[0], window.monitor), misc.cm2pix(xy[1], window.monitor) if units in ['norm']: # -1.0 to 1.0 if xy[0] <= 1.0 and xy[0] >= -1.0 and xy[1] <= 1.0 and xy[1] >= -1.0: return xy[0] * window.size[0] / 2.0, xy[1] * window.size[1] / 2.0 return ValueError("TextBox: %s, %s could not be converted to pix units" % (str(xy), str(units))) def _pix2units(self, xy, is_position=True): units = self._units window = self._window ww, wh = float(window.size[0]), float(window.size[1]) if isinstance(xy, numbers.Number): xy = xy, xy elif is_sequence(xy): if len(xy) == 1: xy = xy[0], xy[0] else: xy = xy[:2] else: raise ValueError( "TextBox: coord variables must be array-like or a single number. Invalid: %s" % (str(xy))) if not isinstance(xy[0], numbers.Number) or not isinstance(xy[1], numbers.Number): raise ValueError("TextBox: coord variables must only contain numbers. Invalid: %s, %s, %s" % ( str(xy), str(type(xy[0])), str(type(xy[1])))) x, y = xy if is_position: # convert to psychopy pix, origin is center of monitor. x, y = int(x - ww / 2), int(y - wh / 2) if units in ('pix', 'pixs'): return x, y if units in ['deg', 'degs']: return misc.pix2deg(x, window.monitor), misc.deg2pix(y, window.monitor) if units in ['cm']: return misc.pix2cm(x, window.monitor), misc.cm2pix(y, window.monitor) if units in ['norm']: return x / ww * 2.0, y / wh * 2.0 raise ValueError( "TextBox: %s, %s could not be converted to pix units" % (str(xy), str(units))) def _toRGBA(self, color): return self.__class__._toRGBA2(color, self._opacity, self._color_space, self._window) @classmethod def _toRGBA2(cls, color, opacity=None, color_space=None, window=None): if color is None: raise ValueError("TextBox: None is not a valid color input") #if not colors.isValidColor(color): # raise ValueError( # "TextBox: %s is not a valid color." % (str(color))) valid_opacity = opacity >= 0.0 and opacity <= 1.0 if isinstance(color, str): if color[0] == '#' or color[0:2].lower() == '0x': rgb255color = colors.hex2rgb255(color) if rgb255color and valid_opacity: return rgb255color[0] / 255.0, rgb255color[1] / 255.0, rgb255color[2] / 255.0, opacity else: raise ValueError( "TextBox: %s is not a valid hex color." % (str(color))) named_color = colors.colors.get(color.lower()) if named_color and valid_opacity: return (named_color[0] + 1.0) / 2.0, (named_color[1] + 1.0) / 2.0, (named_color[2] + 1.0) / 2.0, opacity raise ValueError( "TextBox: String color value could not be translated: %s" % (str(color))) if isinstance(color, (float, int, int)) or (is_sequence(color) and len(color) == 3): color = arraytools.val2array(color, length=3) if color_space == 'dkl' and valid_opacity: dkl_rgb = None if window: dkl_rgb = window.dkl_rgb rgb = colortools.dkl2rgb(color, dkl_rgb) return (rgb[0] + 1.0) / 2.0, (rgb[1] + 1.0) / 2.0, (rgb[2] + 1.0) / 2.0, opacity if color_space == 'lms' and valid_opacity: lms_rgb = None if window: lms_rgb = window.lms_rgb rgb = colortools.lms2rgb(color, lms_rgb) return (rgb[0] + 1.0) / 2.0, (rgb[1] + 1.0) / 2.0, (rgb[2] + 1.0) / 2.0, opacity if color_space == 'hsv' and valid_opacity: rgb = colortools.hsv2rgb(color) return (rgb[0] + 1.0) / 2.0, (rgb[1] + 1.0) / 2.0, (rgb[2] + 1.0) / 2.0, opacity if color_space == 'rgb255' and valid_opacity: rgb = color if [cc for cc in color if cc < 0 or cc > 255]: raise ValueError( 'TextBox: rgb255 colors must contain elements between 0 and 255. Value: ' + str(rgb)) return rgb[0] / 255.0, rgb[1] / 255.0, rgb[2] / 255.0, opacity if color_space == 'rgb' and valid_opacity: rgb = color if [cc for cc in color if cc < -1.0 or cc > 1.0]: raise ValueError( 'TextBox: rgb colors must contain elements between -1.0 and 1.0. Value: ' + str(rgb)) return (rgb[0] + 1.0) / 2.0, (rgb[1] + 1.0) / 2.0, (rgb[2] + 1.0) / 2.0, opacity if is_sequence(color) and len(color) == 4: if color_space == 'rgb255': if [cc for cc in color if cc < 0 or cc > 255]: raise ValueError( 'TextBox: rgb255 colors must contain elements between 0 and 255. Value: ' + str(color)) return color[0] / 255.0, color[1] / 255.0, color[2] / 255.0, color[3] / 255.0 if color_space == 'rgb': if [cc for cc in color if cc < -1.0 or cc > 1.0]: raise ValueError( 'TextBox: rgb colors must contain elements between -1.0 and 1.0. Value: ' + str(color)) return (color[0] + 1.0) / 2.0, (color[1] + 1.0) / 2.0, (color[2] + 1.0) / 2.0, (color[3] + 1.0) / 2.0 raise ValueError("TextBox: color: %s, opacity: %s, is not a valid color for color space %s." % ( str(color), str(opacity), color_space)) def _reset(self): self._text_grid.reset() def _getPixelSize(self): if self._units == 'norm': r = self._toPix( (self._size[0] - 1.0, self._size[1] - 1.0), self._units, self._window) return int(r[0] + self._window.size[0] / 2), int(r[1] + self._window.size[1] / 2) return [int(x) for x in self._toPix(self._size, self._units, self._window)] def _setSize(self, pix_sz): units = self._units if units in ('pix', 'pixs'): self._size = list(pix_sz) if units in ['deg', 'degs']: self._size = misc.pix2deg(pix_sz[0], self._window.monitor), misc.pix2deg( pix_sz[1], self._window.monitor) if units in ['cm']: self._size = misc.pix2cm(pix_sz[0], self._window.monitor), misc.pix2cm( pix_sz[1], self._window.monitor) if units in ['norm']: pw, ph = pix_sz dw, dh = self._window.size nw = (pw / float(dw)) * 2.0 nh = (ph / float(dh)) * 2.0 self._size = nw, nh def _getPixelPosition(self): ppos = self._toPix(self._position, self._units, self._window) return int(ppos[0]), int(ppos[1]) def _getPixelTextLineSpacing(self): if self._line_spacing: max_size = self._current_glfont.max_tile_width, self._current_glfont.max_tile_height line_spacing_units = self._line_spacing_units line_spacing_height = self._line_spacing if line_spacing_units == 'ratio': # run though _toPix to validate line_spacing value type only r = self._toPix(line_spacing_height, 'pix', self._window)[0] return int(max_size[1] * r) return self._toPix(line_spacing_height, line_spacing_units, self._window) return 0 def _getTopLeftPixPos(self): # Create a window position based on the window size, alignment types, # TextBox size, etc... win_w, win_h = self._window.size te_w, te_h = self._getPixelSize() te_x, te_y = self._getPixelPosition() # convert te_x,te_y from psychopy pix coord to gl pix coord te_x, te_y = te_x + win_w // 2, te_y + win_h // 2 # convert from alignment to top left horz_align, vert_align = self._align_horz, self._align_vert if horz_align.lower() == u'center': te_x = te_x - te_w // 2 elif horz_align.lower() == u'right': te_x = te_x - te_w if vert_align.lower() == u'center': te_y = te_y + te_h // 2 if vert_align.lower() == u'bottom': te_y = te_y + te_h return te_x, te_y def __del__(self): if hasattr(self, '_textbox_instance') and self.getName() in self._textbox_instance: del self._textbox_instances[self.getName()] del self._current_glfont del self._text_grid
53,776
Python
.py
1,084
37.547048
131
0.577065
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,774
textgrid.py
psychopy_psychopy/psychopy/visual/textbox/textgrid.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Created on Mon Jan 07 11:18:51 2013 @author: Sol """ import numpy as np from weakref import proxy from psychopy import core from pyglet.gl import (glCallList, glGenLists, glNewList, glDisable, glEnable, glTranslatef, glColor4f, glLineWidth, glBegin, GL_LINES, glEndList, glDeleteLists, GL_COMPILE, glEnd, GL_TEXTURE0, GL_TEXTURE_2D, GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE, GL_UNSIGNED_INT, glPopMatrix, glBindTexture, glActiveTexture, glTexEnvf, glPushMatrix, glCallLists, glVertex2i) from . import parsedtext getTime = core.getTime class TextGrid: def __init__(self, text_box, line_color=None, line_width=1, font_color=(1, 1, 1, 1), shape=None, grid_horz_justification='left', grid_vert_justification='top'): self._text_box = proxy(text_box) self._font_color = font_color if line_color: self._line_color = line_color self._line_width = line_width else: self._line_color = None self._line_width = None cfont = self._text_box._current_glfont max_size = cfont.max_tile_width, cfont.max_tile_height self._cell_size = (max_size[0], max_size[1] + self._text_box._getPixelTextLineSpacing()) if self._cell_size[0] == 0: print('ERROR WITH CELL SIZE!!!! ', self._text_box.getLabel()) self._text_dlist = None self._gridlines_dlist = None self._text_document = None # Text Grid line_spacing te_size = [0, 0] if self._text_box._size: te_size = list(self._text_box._getPixelSize()) if shape: self._shape = shape else: if (te_size[0] >= self._cell_size[0]) and (te_size[1] >= self._cell_size[1]): self._shape = (te_size[0] // self._cell_size[0], te_size[1] // self._cell_size[1]) else: raise ValueError(f"Invalid TextBox size provided. Increase size or use `textgrid_shape` for more precise control.") self._size = (self._cell_size[0] * self._shape[0], self._cell_size[1] * self._shape[1]) resized = False if shape and self._size[0] > te_size[0]: te_size[0] = self._size[0] resized = True if shape and self._size[1] > te_size[1]: te_size[1] = self._size[1] resized = True if resized: self._text_box._setSize(te_size) # For now, The text grid is centered in the TextBox area. dx = (te_size[0] - self._size[0]) // 2 dy = (te_size[1] - self._size[1]) // 2 # TextGrid Position is position within the TextBox component. self._position = dx, dy # TextGrid cell boundaries self._col_lines = [int(np.floor(x)) for x in range( 0, self._size[0] + 1, self._cell_size[0])] self._row_lines = [int(np.floor(y)) for y in range( 0, -self._size[1] - 1, -self._cell_size[1])] self._apply_padding = False self._pad_top_proportion = 0 self._pad_left_proportion = 0 self.setHorzJust(grid_horz_justification) self.setVertJust(grid_vert_justification) def getSize(self): return self._size def getCellSize(self): return self._cell_size def getShape(self): return self._shape def getPosition(self): return self._position def getLineColor(self): return self._line_color def getLineWidth(self): return self._line_width def getHorzJust(self): return self._horz_justification def getVertJust(self): return self._vert_justification def setHorzJust(self, j): self._horz_justification = j self._pad_left_proportion = 0 if j == 'center': self._pad_left_proportion = 0.5 elif j == 'right': self._pad_left_proportion = 1.0 self.applyPadding() def setVertJust(self, j): self._vert_justification = j self._pad_top_proportion = 0 if j == 'center': self._pad_top_proportion = 0.5 elif j == 'bottom': self._pad_top_proportion = 1.0 self.applyPadding() def applyPadding(self): self._apply_padding = self._pad_left_proportion or ( self._pad_top_proportion and self.getRowCountWithText() > 1) num_cols, num_rows = self._shape line_count = self.getRowCountWithText() for li in range(line_count): cline = self._text_document.getParsedLine(li) line_length = cline.getLength() if self._apply_padding: cline._trans_left = int( (num_cols - line_length + 1) * self._pad_left_proportion) cline._trans_top = int( (num_rows - line_count) * self._pad_top_proportion) else: cline._trans_left = 0 cline._trans_top = 0 def getRowCountWithText(self): if self._text_document: return min(self._shape[1], self._text_document.getParsedLineCount()) return 0 def _setText(self, text): self._text_document.deleteText(0, self._text_document.getTextLength(), text) self._deleteTextDL() self.applyPadding() return self._text_document.getDisplayedText() def setCurrentFontDisplayLists(self, dlists): self._current_font_display_lists = dlists def _deleteTextDL(self): if self._text_dlist: glDeleteLists(self._text_dlist, 1) self._text_dlist = 0 def _deleteGridLinesDL(self): if self._gridlines_dlist: glDeleteLists(self._gridlines_dlist, 1) self._gridlines_dlist = None def _createParsedTextDocument(self, f): if self._shape: self._text_document = parsedtext.ParsedTextDocument(f, self) self._deleteTextDL() self.applyPadding() else: raise AttributeError( "Could not create _text_document. num_columns needs to be known.") def _text_glyphs_gl(self): if not self._text_dlist: dl_index = glGenLists(1) glNewList(dl_index, GL_COMPILE) ### glActiveTexture(GL_TEXTURE0) glEnable(GL_TEXTURE_2D) glBindTexture( GL_TEXTURE_2D, self._text_box._current_glfont.atlas.texid) glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE) glTranslatef(self._position[0], -self._position[1], 0) glPushMatrix() ### getLineInfoByIndex = self._text_document.getLineInfoByIndex active_text_style_dlist = self._current_font_display_lists.get cell_width, cell_height = self._cell_size num_cols, num_rows = self._shape line_spacing = self._text_box._getPixelTextLineSpacing() line_count = self.getRowCountWithText() glColor4f(*self._text_box._toRGBA(self._font_color)) for r in range(line_count): cline, line_length, line_display_list, line_ords = getLineInfoByIndex( r) if line_display_list[0] == 0: line_display_list[0:line_length] = [ active_text_style_dlist(c) for c in line_ords] glTranslatef(cline._trans_left * cell_width, - int(line_spacing/2.0 + cline._trans_top * cell_height), 0) glCallLists(line_length, GL_UNSIGNED_INT, line_display_list[0:line_length].ctypes) cline._trans_left = 0 glTranslatef(-line_length * cell_width - cline._trans_left * cell_width, - cell_height + int(line_spacing/2.0 + cline._trans_top * cell_height), 0) ### glPopMatrix() glBindTexture(GL_TEXTURE_2D, 0) glDisable(GL_TEXTURE_2D) glEndList() self._text_dlist = dl_index glCallList(self._text_dlist) def _textgrid_lines_gl(self): if self._line_color: if not self._gridlines_dlist: dl_index = glGenLists(1) glNewList(dl_index, GL_COMPILE) glLineWidth(self._line_width) glColor4f(*self._text_box._toRGBA(self._line_color)) glBegin(GL_LINES) for x in self._col_lines: for y in self._row_lines: if x == 0: glVertex2i(x, y) glVertex2i(int(self._size[0]), y) if y == 0: glVertex2i(x, y) glVertex2i(x, int(-self._size[1])) glEnd() glColor4f(0.0, 0.0, 0.0, 1.0) glEndList() self._gridlines_dlist = dl_index glCallList(self._gridlines_dlist) # self._text_box._te_end_gl() # etime=getTime() def __del__(self): try: self._text_document._free() del self._text_document if self._text_dlist: glDeleteLists(self._text_dlist, 1) self._text_dlist = 0 self._current_font_display_lists = None except (ModuleNotFoundError, ImportError, AttributeError): pass
9,791
Python
.py
227
30.621145
131
0.551141
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,775
gamma.py
psychopy_psychopy/psychopy/visual/backends/gamma.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). # set the gamma LUT using platform-specific hardware calls import numpy import sys import platform import ctypes import ctypes.util from psychopy import logging, prefs from psychopy.tools import systemtools # import platform specific C++ libs for controlling gamma if sys.platform == 'win32': from ctypes import windll elif sys.platform == 'darwin': try: carbon = ctypes.CDLL( '/System/Library/Frameworks/CoreGraphics.framework/CoreGraphics') except OSError: try: carbon = ctypes.CDLL( '/System/Library/Frameworks/Carbon.framework/Carbon') except OSError: carbon = ctypes.CDLL('/System/Library/Carbon.framework/Carbon') elif sys.platform.startswith('linux'): # we need XF86VidMode xf86vm = ctypes.CDLL(ctypes.util.find_library('Xxf86vm')) # Handling what to do if gamma can't be set if prefs.general['gammaErrorPolicy'] == 'abort': # more clear to Builder users defaultGammaErrorPolicy = 'raise' # more clear to Python coders else: defaultGammaErrorPolicy = prefs.general['gammaErrorPolicy'] problem_msg = 'The hardware look-up table function ({func:s}) failed. ' raise_msg = (problem_msg + 'If you would like to proceed without look-up table ' '(gamma) changes, you can change your `defaultGammaFailPolicy` in the ' 'application preferences. For more information see\n' 'https://www.psychopy.org/troubleshooting.html#errors-with-getting-setting-the-gamma-ramp ' ) warn_msg = problem_msg + 'Proceeding without look-up table (gamma) changes.' def setGamma(screenID=None, newGamma=1.0, rampType=None, rampSize=None, driver=None, xDisplay=None, gammaErrorPolicy=None): """Sets gamma to a given value :param screenID: The screen ID in the Operating system :param newGamma: numeric or triplet (for independent RGB gamma vals) :param rampType: see :ref:`createLinearRamp` for possible ramp types :param rampSize: how large is the lookup table on your system? :param driver: string describing your gfx card driver (e.g. from pyglet) :param xDisplay: for linux only :param gammaErrorPolicy: whether you want to raise an error or warning :return: """ if not gammaErrorPolicy: gammaErrorPolicy = defaultGammaErrorPolicy # make sure gamma is 3x1 array if type(newGamma) in [float, int]: newGamma = numpy.tile(newGamma, [3, 1]) elif type(newGamma) in [list, tuple]: newGamma = numpy.array(newGamma) newGamma.shape = [3, 1] elif type(newGamma) is numpy.ndarray: newGamma.shape = [3, 1] # create LUT from gamma values newLUT = numpy.tile( createLinearRamp(rampType=rampType, rampSize=rampSize, driver=driver), (3, 1) ) if numpy.all(newGamma == 1.0) == False: # correctly handles 1 or 3x1 gamma vals newLUT = newLUT**(1.0/numpy.array(newGamma)) setGammaRamp(screenID, newLUT, xDisplay=xDisplay, gammaErrorPolicy=gammaErrorPolicy) def setGammaRamp(screenID, newRamp, nAttempts=3, xDisplay=None, gammaErrorPolicy=None): """Sets the hardware look-up table, using platform-specific functions. Ramp should be provided as 3xN array in range 0:1.0 On windows the first attempt to set the ramp doesn't always work. The parameter nAttemps allows the user to determine how many attempts should be made before failing """ if not gammaErrorPolicy: gammaErrorPolicy = defaultGammaErrorPolicy LUTlength = newRamp.shape[1] if newRamp.shape[0] != 3 and newRamp.shape[1] == 3: newRamp = numpy.ascontiguousarray(newRamp.transpose()) if sys.platform == 'win32': newRamp = (numpy.around(255.0 * newRamp)).astype(numpy.uint16) # necessary, according to pyglet post from Martin Spacek newRamp.byteswap(True) for n in range(nAttempts): success = windll.gdi32.SetDeviceGammaRamp( screenID, newRamp.ctypes) # FB 504 if success: break if not success: func = 'SetDeviceGammaRamp' if gammaErrorPolicy == 'raise': raise OSError(raise_msg.format(func=func)) elif gammaErrorPolicy == 'warn': logging.warning(warn_msg.format(func=func)) if sys.platform == 'darwin': newRamp = (newRamp).astype(numpy.float32) error = carbon.CGSetDisplayTransferByTable( screenID, LUTlength, newRamp[0, :].ctypes, newRamp[1, :].ctypes, newRamp[2, :].ctypes) if error: func = 'CGSetDisplayTransferByTable' if gammaErrorPolicy == 'raise': raise OSError(raise_msg.format(func=func)) elif gammaErrorPolicy == 'warn': logging.warning(warn_msg.format(func=func)) if sys.platform.startswith('linux') and not systemtools.isVM_CI(): newRamp = (numpy.around(65535 * newRamp)).astype(numpy.uint16) success = xf86vm.XF86VidModeSetGammaRamp( xDisplay, screenID, LUTlength, newRamp[0, :].ctypes, newRamp[1, :].ctypes, newRamp[2, :].ctypes) if not success: func = 'XF86VidModeSetGammaRamp' if gammaErrorPolicy == 'raise': raise OSError(raise_msg.format(func=func)) elif gammaErrorPolicy == 'warn': logging.warning(raise_msg.format(func=func)) elif systemtools.isVM_CI(): logging.warn("It looks like we're running in a Virtual Machine. " "Hardware gamma table cannot be set") def getGammaRamp(screenID, xDisplay=None, gammaErrorPolicy=None): """Ramp will be returned as 3xN array in range 0:1 screenID : ID of the given display as defined by the OS xDisplay : the identity (int?) of the X display gammaErrorPolicy : str 'raise' (ends the experiment) or 'warn' (logs a warning) """ if not gammaErrorPolicy: gammaErrorPolicy = defaultGammaErrorPolicy rampSize = getGammaRampSize(screenID, xDisplay=xDisplay) if sys.platform == 'win32': # init R, G, and B ramps origramps = numpy.empty((3, rampSize), dtype=numpy.uint16) success = windll.gdi32.GetDeviceGammaRamp( screenID, origramps.ctypes) # FB 504 if not success: func = 'GetDeviceGammaRamp' if gammaErrorPolicy == 'raise': raise OSError(raise_msg.format(func=func)) elif gammaErrorPolicy == 'warn': logging.warning(warn_msg.format(func=func)) else: origramps.byteswap(True) # back to 0:255 origramps = origramps/255.0 # rescale to 0:1 if sys.platform == 'darwin': # init R, G, and B ramps origramps = numpy.empty((3, rampSize), dtype=numpy.float32) n = numpy.empty([1], dtype=int) error = carbon.CGGetDisplayTransferByTable( screenID, rampSize, origramps[0, :].ctypes, origramps[1, :].ctypes, origramps[2, :].ctypes, n.ctypes) if error: func = 'CGSetDisplayTransferByTable' if gammaErrorPolicy == 'raise': raise OSError(raise_msg.format(func=func)) elif gammaErrorPolicy == 'warn': logging.warning(warn_msg.format(func=func)) if sys.platform.startswith('linux') and not systemtools.isVM_CI(): origramps = numpy.empty((3, rampSize), dtype=numpy.uint16) success = xf86vm.XF86VidModeGetGammaRamp( xDisplay, screenID, rampSize, origramps[0, :].ctypes, origramps[1, :].ctypes, origramps[2, :].ctypes) if not success: func = 'XF86VidModeGetGammaRamp' if gammaErrorPolicy == 'raise': raise OSError(raise_msg.format(func=func)) elif gammaErrorPolicy == 'warn': logging.warning(warn_msg.format(func=func)) else: origramps = origramps/65535.0 # rescale to 0:1 elif systemtools.isVM_CI(): logging.warn("It looks like we're running in a virtual machine. " "Hardware gamma table cannot be retrieved") origramps = None return origramps def createLinearRamp(rampType=None, rampSize=256, driver=None): """Generate the Nx3 values for a linear gamma ramp on the current platform. This uses heuristics about known graphics cards to guess the 'rampType' if none is explicitly given. Much of this work is ported from LoadIdentityClut.m, by Mario Kleiner for the psychtoolbox rampType 0 : an 8-bit CLUT ranging 0:1 This is seems correct for most windows machines and older macOS systems Known to be used by: OSX 10.4.9 PPC with GeForceFX-5200 rampType 1 : an 8-bit CLUT ranging (1/256.0):1 For some reason a number of macs then had a CLUT that (erroneously?) started with 1/256 rather than 0. Known to be used by: OSX 10.4.9 with ATI Mobility Radeon X1600 OSX 10.5.8 with ATI Radeon HD-2600 maybe all ATI cards? rampType 2 : a 10-bit CLUT ranging 0:(1023/1024) A slightly odd 10-bit CLUT that doesn't quite finish on 1.0! Known to be used by: OSX 10.5.8 with Geforce-9200M (MacMini) OSX 10.5.8 with Geforce-8800 rampType 3 : a nasty, bug-fixing 10bit CLUT for crumby macOS drivers Craziest of them all for Snow leopard. Like rampType 2, except that the upper half of the table has 1/256.0 removed?!! Known to be used by: OSX 10.6.0 with NVidia Geforce-9200M """ def _versionTuple(v): # for proper sorting: _versionTuple('10.8') < _versionTuple('10.10') return tuple(map(int, v.split('.'))) if rampType is None: # try to determine rampType from heuristics including sys info osxVer = platform.mac_ver()[0] # '' on non-Mac # OSX if osxVer: osxVerTuple = _versionTuple(osxVer) # driver provided if driver is not None: # nvidia if 'NVIDIA' in driver: # leopard nVidia cards don't finish at 1.0! if _versionTuple("10.5") < osxVerTuple < _versionTuple("10.6"): rampType = 2 # snow leopard cards are plain crazy! elif _versionTuple("10.6") < osxVerTuple: rampType = 3 else: rampType = 1 # non-nvidia else: # is ATI or unknown manufacturer, default to (1:256)/256 # this is certainly correct for radeon2600 on 10.5.8 and # radeonX1600 on 10.4.9 rampType = 1 # no driver info given else: # is ATI or unknown manufacturer, default to (1:256)/256 # this is certainly correct for radeon2600 on 10.5.8 and # radeonX1600 on 10.4.9 rampType = 1 # win32 or linux else: # for win32 and linux this is sensible, not clear about Vista and Windows7 rampType = 0 if rampType == 0: ramp = numpy.linspace(0.0, 1.0, num=rampSize) elif rampType == 1: ramp = numpy.linspace(1/256.0, 1.0, num=256) elif rampType == 2: ramp = numpy.linspace(0, 1023.0/1024, num=1024) elif rampType == 3: ramp = numpy.linspace(0, 1023.0/1024, num=1024) ramp[512:] = ramp[512:] - 1/256.0 logging.info('Using gamma ramp type: %i' % rampType) return ramp def getGammaRampSize(screenID, xDisplay=None, gammaErrorPolicy=None): """Returns the size of each channel of the gamma ramp.""" if not gammaErrorPolicy: gammaErrorPolicy = defaultGammaErrorPolicy if sys.platform == 'win32' or systemtools.isVM_CI(): # windows documentation (for SetDeviceGammaRamp) seems to indicate that # the LUT size is always 256 rampSize = 256 elif sys.platform == 'darwin': rampSize = carbon.CGDisplayGammaTableCapacity(screenID) elif sys.platform.startswith('linux'): rampSize = ctypes.c_int() success = xf86vm.XF86VidModeGetGammaRampSize( xDisplay, screenID, ctypes.byref(rampSize) ) if not success: func = 'XF86VidModeGetGammaRampSize' if gammaErrorPolicy == 'raise': raise OSError(raise_msg.format(func=func)) elif gammaErrorPolicy == 'warn': logging.warning(warn_msg.format(func=func)) else: rampSize = rampSize.value else: rampSize = 256 if rampSize == 0: logging.warn( "The size of the gamma ramp was reported as 0. This can " + "mean that gamma settings have no effect. Proceeding with " + "a default gamma ramp size." ) rampSize = 256 return rampSize
13,419
Python
.py
299
35.364548
99
0.631676
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,776
pygamebackend.py
psychopy_psychopy/psychopy/visual/backends/pygamebackend.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). """A Backend class defines the core low-level functions required by a Window class, such as the ability to create an OpenGL context and flip the window. Users simply call visual.Window(..., winType='pyglet') and the winType is then used by backends.getBackend(winType) which will locate the appropriate class and initialize an instance using the attributes of the Window. """ import os import sys import pygame from abc import abstractmethod from ._base import BaseBackend import psychopy from psychopy import core from psychopy.tools.attributetools import attributeSetter try: import pyglet GL = pyglet.gl except ImportError: import OpenGL GL = OpenGL class PygameBackend(BaseBackend): """The pygame backend is built on SDL for cross-platform controls """ GL = GL winTypeName = 'pygame' def __init__(self, win, backendConf=None): """Set up the backend window according the params of the PsychoPy win Before PsychoPy 1.90.0 this code was executed in Window._setupPygame() Parameters ---------- win : `psychopy.visual.Window` instance PsychoPy Window (usually not fully created yet). backendConf : `dict` or `None` Backend configuration options. Options are specified as a dictionary where keys are option names and values are settings. This backend currently takes no additional settings. Examples -------- Create a window using the Pygame backend:: import psychopy.visual as visual win = visual.Window(winType='glfw', backendOptions=options) """ BaseBackend.__init__(self, win) # sets up self.win=win as weakref # pygame.mixer.pre_init(22050,16,2) # set the values to initialise # sound system if it gets used pygame.init() if win.allowStencil: pygame.display.gl_set_attribute(pygame.locals.GL_STENCIL_SIZE, 8) try: # to load an icon for the window iconFile = os.path.join(psychopy.__path__[0], 'psychopy.png') icon = pygame.image.load(iconFile) pygame.display.set_icon(icon) except Exception: pass # doesn't matter win.useRetina = False # these are ints stored in pygame.locals winSettings = pygame.OPENGL | pygame.DOUBLEBUF if win._isFullScr: winSettings = winSettings | pygame.FULLSCREEN # check screen size if full screen scrInfo = pygame.display.Info() win._checkMatchingSizes(win.clientSize, [scrInfo.current_w, scrInfo.current_h]) elif not win.pos: # centre video os.environ['SDL_VIDEO_CENTERED'] = "1" else: os.environ['SDL_VIDEO_WINDOW_POS'] = '%i,%i' % (win.pos[0], win.pos[1]) if sys.platform == 'win32': os.environ['SDL_VIDEODRIVER'] = 'windib' if not win.allowGUI: winSettings = winSettings | pygame.NOFRAME self.setMouseVisibility(False) pygame.display.set_caption('PsychoPy (NB use with allowGUI=False ' 'when running properly)') else: self.setMouseVisibility(True) pygame.display.set_caption('PsychoPy') self.winHandle = pygame.display.set_mode(win.size.astype('i'), winSettings) self._frameBufferSize = win.clientSize pygame.display.set_gamma(1.0) # this will be set appropriately later # This is causing segfault although it used to be for pyglet only anyway # pygame under mac is not syncing to refresh although docs say it should # if sys.platform == 'darwin': # platform_specific.syncSwapBuffers(2) @property def frameBufferSize(self): """Framebuffer size (w, h).""" return self._frameBufferSize def swapBuffers(self, flipThisFrame=True): """Do the actual flipping of the buffers (Window will take care of additional things like timestamping. Keep this methods as short as poss :param flipThisFrame: has no effect on this backend """ if pygame.display.get_init(): if flipThisFrame: pygame.display.flip() # keeps us in synch with system event queue self.dispatchEvents() else: core.quit() # we've unitialised pygame so quit def close(self): """Close the window and uninitialize the resources """ pygame.display.quit() @property def shadersSupported(self): """This is a read-only property indicating whether or not this backend supports OpenGL shaders""" return False def setMouseVisibility(self, visibility): """Set visibility of the mouse to True or False""" pygame.mouse.set_visible(visibility) # Optional, depending on backend needs def dispatchEvents(self): """This method is not needed for all backends but for engines with an event loop it may be needed to pump for new events (e.g. pyglet) """ pygame.event.pump() def onResize(self, width, height): """This does nothing; not supported by our pygame backend at the moment """ pass # the pygame window doesn't currently support resizing @attributeSetter def gamma(self, gamma): self.__dict__['gamma'] = gamma # use pygame's own function for this pygame.display.set_gamma(gamma[0], gamma[1], gamma[2]) @attributeSetter def gammaRamp(self, gammaRamp): """Gets the gamma ramp or sets it to a new value (an Nx3 or Nx1 array) """ self.__dict__['gammaRamp'] = gammaRamp # use pygame's own function for this pygame.display.set_gamma_ramp( gammaRamp[:, 0], gammaRamp[:, 1], gammaRamp[:, 2]) def setFullScr(self, value): """Sets the window to/from full-screen mode""" raise NotImplementedError("Toggling fullscreen mode is not currently " "supported on pygame windows") # -------------------------------------------------------------------------- # Mouse related methods (e.g., event handlers) # # These methods are used to handle mouse events. Each function is bound to # the appropriate callback which registers the mouse event with the global # mouse event handler (psychopy.hardware.mouse.Mouse). Each callback has an # `*args` parameter which allows the backend to pass whatever parameters. # @abstractmethod def onMouseButton(self, *args, **kwargs): """Event handler for any mouse button event (pressed and released). This is used by backends which combine both button state changes into a single event. Usually this would pass events to the appropriate `onMouseButtonPress` and `onMouseButtonRelease` methods. """ raise NotImplementedError( "`onMouseButton` is not yet implemented for this backend.") @abstractmethod def onMouseButtonPress(self, *args, **kwargs): """Event handler for mouse press events. This handler can also be used for release events if the backend passes all button events to the same callback. """ raise NotImplementedError( "`onMouseButtonPress` is not yet implemented for this backend.") @abstractmethod def onMouseButtonRelease(self, *args, **kwargs): """Event handler for mouse release events.""" raise NotImplementedError( "`onMouseButtonRelease` is not yet implemented for this backend.") @abstractmethod def onMouseScroll(self, *args, **kwargs): """Event handler for mouse scroll events. Called when the mouse scroll wheel is moved.""" raise NotImplementedError( "`onMouseScroll` is not yet implemented for this backend.") @abstractmethod def onMouseMove(self, *args, **kwargs): """Event handler for mouse move events.""" raise NotImplementedError( "`onMouseMove` is not yet implemented for this backend.") @abstractmethod def onMouseEnter(self, *args, **kwargs): """Event called when the mouse enters the window. Some backends might combine enter and leave events to the same callback, this will handle both if so. """ raise NotImplementedError( "`onMouseEnter` is not yet implemented for this backend.") @abstractmethod def onMouseLeave(self, *args, **kwargs): """Event called when a mouse leaves the window.""" raise NotImplementedError( "`onMouseLeave` is not yet implemented for this backend.") @abstractmethod def getMousePos(self): """Get the position of the mouse on the current window. Returns ------- ndarray Position `(x, y)` in window coordinates. """ raise NotImplementedError( "`getMousePos` is not yet implemented for this backend.") @abstractmethod def setMousePos(self, pos): """Set/move the position of the mouse on the current window. Parameters ---------- pos : ArrayLike Position `(x, y)` in window coordinates. """ raise NotImplementedError( "`setMousePos` is not yet implemented for this backend.") def setMouseType(self, name='arrow'): """Change the appearance of the cursor for this window. Cursor types provide contextual hints about how to interact with on-screen objects. **Deprecated!** Use `setMouseCursor` instead. Parameters ---------- name : str Type of standard cursor to use. """ self.setMouseCursor(name) @abstractmethod def setMouseCursor(self, cursorType='default'): """Change the appearance of the cursor for this window. Cursor types provide contextual hints about how to interact with on-screen objects. The graphics used 'standard cursors' provided by the operating system. They may vary in appearance and hot spot location across platforms. The following names are valid on most platforms: * ``arrow`` or ``default`` : Default system pointer. * ``ibeam`` or ``text`` : Indicates text can be edited. * ``crosshair`` : Crosshair with hot-spot at center. * ``hand`` : A pointing hand. * ``hresize`` : Double arrows pointing horizontally. * ``vresize`` : Double arrows pointing vertically. * ``help`` : Arrow with a question mark beside it (Windows only). * ``no`` : 'No entry' sign or circle with diagonal bar. * ``size`` : Vertical and horizontal sizing. * ``downleft`` or ``upright`` : Double arrows pointing diagonally with positive slope (Windows only). * ``downright`` or ``upleft`` : Double arrows pointing diagonally with negative slope (Windows only). * ``lresize`` : Arrow pointing left (Mac OS X only). * ``rresize`` : Arrow pointing right (Mac OS X only). * ``uresize`` : Arrow pointing up (Mac OS X only). * ``dresize`` : Arrow pointing down (Mac OS X only). * ``wait`` : Hourglass (Windows) or watch (Mac OS X) to indicate the system is busy. * ``waitarrow`` : Hourglass beside a default pointer (Windows only). In cases where a cursor is not supported, the default for the system will be used. Parameters ---------- cursorType : str Type of standard cursor to use. If not specified, `'default'` is used. Notes ----- * On some platforms the 'crosshair' cursor may not be visible on uniform grey backgrounds. """ raise NotImplementedError( "`setMouseCursor` is not yet implemented for this backend.") @abstractmethod def setMouseExclusive(self, exclusive): """Set mouse exclusivity. Parameters ---------- exclusive : bool Mouse exclusivity mode. """ raise NotImplementedError( "`setMouseExclusive` is not yet implemented for this backend.") if __name__ == "__main__": pass
12,804
Python
.py
285
35.726316
80
0.630688
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,777
pygletbackend.py
psychopy_psychopy/psychopy/visual/backends/pygletbackend.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). """A Backend class defines the core low-level functions required by a Window class, such as the ability to create an OpenGL context and flip the window. Users simply call visual.Window(..., winType='pyglet') and the winType is then used by backends.getBackend(winType) which will locate the appropriate class and initialize an instance using the attributes of the Window. """ import sys import os import platform import numpy as np import psychopy from psychopy import core, prefs from psychopy.hardware import mouse from psychopy import logging, event, platform_specific from psychopy.tools.attributetools import attributeSetter from psychopy.tools import systemtools from .gamma import setGamma, setGammaRamp, getGammaRamp, getGammaRampSize from .. import globalVars from ._base import BaseBackend import pyglet import pyglet.window as pyglet_window import pyglet.window.mouse as pyglet_mouse # Ensure setting pyglet.options['debug_gl'] to False is done prior to any # other calls to pyglet or pyglet submodules, otherwise it may not get picked # up by the pyglet GL engine and have no effect. # Shaders will work but require OpenGL2.0 drivers AND PyOpenGL3.0+ pyglet.options['debug_gl'] = False GL = pyglet.gl retinaContext = None # it will be set to an actual context if needed # get the default display if pyglet.version < '1.4': _default_display_ = pyglet.window.get_platform().get_default_display() else: _default_display_ = pyglet.canvas.get_display() # Cursors available to pyglet. These are used to map string names to symbolic # constants used to specify which cursor to use. _PYGLET_CURSORS_ = { # common with GLFW 'default': pyglet_window.Window.CURSOR_DEFAULT, 'arrow': pyglet_window.Window.CURSOR_DEFAULT, 'ibeam': pyglet_window.Window.CURSOR_TEXT, 'text': pyglet_window.Window.CURSOR_TEXT, 'crosshair': pyglet_window.Window.CURSOR_CROSSHAIR, 'hand': pyglet_window.Window.CURSOR_HAND, 'hresize': pyglet_window.Window.CURSOR_SIZE_LEFT_RIGHT, 'vresize': pyglet_window.Window.CURSOR_SIZE_UP_DOWN, # pyglet only 'help': pyglet_window.Window.CURSOR_HELP, 'no': pyglet_window.Window.CURSOR_NO, 'size': pyglet_window.Window.CURSOR_SIZE, 'downleft': pyglet_window.Window.CURSOR_SIZE_DOWN_LEFT, 'downright': pyglet_window.Window.CURSOR_SIZE_DOWN_RIGHT, 'lresize': pyglet_window.Window.CURSOR_SIZE_LEFT, 'rresize': pyglet_window.Window.CURSOR_SIZE_RIGHT, 'uresize': pyglet_window.Window.CURSOR_SIZE_UP, 'upleft': pyglet_window.Window.CURSOR_SIZE_UP_LEFT, 'upright': pyglet_window.Window.CURSOR_SIZE_UP_RIGHT, 'wait': pyglet_window.Window.CURSOR_WAIT, 'waitarrow': pyglet_window.Window.CURSOR_WAIT_ARROW } _PYGLET_MOUSE_BUTTONS_ = { pyglet_mouse.LEFT: mouse.MOUSE_BUTTON_LEFT, pyglet_mouse.MIDDLE: mouse.MOUSE_BUTTON_MIDDLE, pyglet_mouse.RIGHT: mouse.MOUSE_BUTTON_RIGHT } class PygletBackend(BaseBackend): """The pyglet backend is the most used backend. It has no dependencies or C libs that need compiling, but may not be as fast or efficient as libs like GLFW. """ GL = pyglet.gl winTypeName = 'pyglet' def __init__(self, win, backendConf=None): """Set up the backend window according the params of the PsychoPy win Parameters ---------- win : `psychopy.visual.Window` instance PsychoPy Window (usually not fully created yet). backendConf : `dict` or `None` Backend configuration options. Options are specified as a dictionary where keys are option names and values are settings. For this backend the following options are available: * `bpc` (`array_like` of `int`) Bits per color (R, G, B). * `depthBits` (`int`) Framebuffer (back buffer) depth bits. * `stencilBits` (`int`) Framebuffer (back buffer) stencil bits. Examples -------- Create a window using the Pyglet backend and specify custom options:: import psychopy.visual as visual options = {'bpc': (8, 8, 8), 'depthBits': 24, 'stencilBits': 8} win = visual.Window(winType='pyglet', backendOptions=options) """ BaseBackend.__init__(self, win) # sets up self.win=win as weakref # if `None`, change to `dict` to extract options backendConf = backendConf if backendConf is not None else {} if not isinstance(backendConf, dict): # type check on options raise TypeError( 'Object passed to `backendConf` must be type `dict`.') self._gammaErrorPolicy = win.gammaErrorPolicy self._origGammaRamp = None self._rampSize = None vsync = 0 # provide warning if stereo buffers are requested but unavailable if win.stereo and not GL.gl_info.have_extension('GL_STEREO'): logging.warning( 'A stereo window was requested but the graphics ' 'card does not appear to support GL_STEREO') win.stereo = False if sys.platform == 'darwin' and not win.useRetina and pyglet.version >= "1.3": logging.warn( "As of PsychoPy 1.85.3 OSX windows should all be set to " "`useRetina=True` (or remove the argument). Pyglet 1.3 appears " "to be forcing us to use retina on any retina-capable screen " "so setting to False has no effect." ) win.useRetina = True # window framebuffer configuration bpc = backendConf.get('bpc', (8, 8, 8)) if isinstance(bpc, int): win.bpc = (bpc, bpc, bpc) else: win.bpc = bpc win.depthBits = int(backendConf.get('depthBits', 8)) if win.allowStencil: win.stencilBits = int(backendConf.get('stencilBits', 8)) else: win.stencilBits = 0 # multisampling sample_buffers = 0 aa_samples = 0 if win.multiSample: sample_buffers = 1 # get maximum number of samples the driver supports max_samples = GL.GLint() GL.glGetIntegerv(GL.GL_MAX_SAMPLES, max_samples) if (win.numSamples >= 2) and ( win.numSamples <= max_samples.value): # NB - also check if divisible by two and integer? aa_samples = win.numSamples else: logging.warning( 'Invalid number of MSAA samples provided, must be ' 'integer greater than two. Disabling.') win.multiSample = False skip_screen_warn = False if platform.system() == 'Linux': from pyglet.canvas.xlib import NoSuchDisplayException try: display = pyglet.canvas.Display(x_screen=win.screen) # in this case, we'll only get a single x-screen back skip_screen_warn = True except NoSuchDisplayException: # Maybe xinerama? Try again and get the specified screen later display = pyglet.canvas.Display(x_screen=0) allScrs = display.get_screens() else: allScrs = _default_display_.get_screens() # Screen (from Exp Settings) is 0-indexed, # so the second screen is Screen 1 if len(allScrs) < int(win.screen) + 1: if not skip_screen_warn: logging.warn("Requested an unavailable screen number - " "using first available.") thisScreen = allScrs[0] else: thisScreen = allScrs[win.screen] if win.autoLog: logging.info('configured pyglet screen %i' % win.screen) # configure the window context config = GL.Config( depth_size=win.depthBits, double_buffer=True, sample_buffers=sample_buffers, samples=aa_samples, stencil_size=win.stencilBits, stereo=win.stereo, vsync=vsync, red_size=win.bpc[0], green_size=win.bpc[1], blue_size=win.bpc[2]) # check if we can have this configuration validConfigs = thisScreen.get_matching_configs(config) if not validConfigs: # check which configs are invalid for the display raise RuntimeError( "Specified window configuration is not supported by this " "display.") # if fullscreen check screen size if win._isFullScr: win._checkMatchingSizes( win.clientSize, [thisScreen.width, thisScreen.height]) w = h = None else: w, h = win.clientSize if win.allowGUI: style = None else: style = 'borderless' # create the window try: self.winHandle = pyglet.window.Window( width=w, height=h, caption="PsychoPy", fullscreen=win._isFullScr, config=config, screen=thisScreen, style=style) except pyglet.gl.ContextException: # turn off the shadow window an try again pyglet.options['shadow_window'] = False self.winHandle = pyglet.window.Window( width=w, height=h, caption="PsychoPy", fullscreen=win._isFullScr, config=config, screen=thisScreen, style=style) logging.warning( "Pyglet shadow_window has been turned off. This is " "only an issue for you if you need multiple " "stimulus windows, in which case update your " "graphics card and/or graphics drivers.") try: icns = [ pyglet.image.load( prefs.paths['assets'] + os.sep + "Psychopy Window Favicon@16w.png" ), pyglet.image.load( prefs.paths['assets'] + os.sep + "Psychopy Window Favicon@32w.png" ), ] self.winHandle.set_icon(*icns) except BaseException: pass if sys.platform == 'win32': # pyHook window hwnd maps to: # pyglet 1.14 -> window._hwnd # pyglet 1.2a -> window._view_hwnd if pyglet.version > "1.2": win._hw_handle = self.winHandle._view_hwnd else: win._hw_handle = self.winHandle._hwnd self._frameBufferSize = win.clientSize elif sys.platform == 'darwin': if win.useRetina: global retinaContext retinaContext = self.winHandle.context._nscontext view = retinaContext.view() bounds = view.convertRectToBacking_(view.bounds()).size if win.clientSize[0] == bounds.width: win.useRetina = False # the screen is not a retina display self._frameBufferSize = np.array( [int(bounds.width), int(bounds.height)]) else: self._frameBufferSize = win.clientSize try: # python 32bit (1.4. or 1.2 pyglet) win._hw_handle = self.winHandle._window.value except Exception: # pyglet 1.2 with 64bit python? win._hw_handle = self.winHandle._nswindow.windowNumber() # Here we temporarily set the window to the bottom right corner of the # requested screen so the correct screen is always detected for NSWindow. # The actual location is then set below using the pyglet set_location() # method on the CocoaWindow object that wraps the NSWindow as _nswindow. # This is necessary because NSScreen origin is the bottom left corner of # the unshifted main screen and positive up, while pyglet origin is the top # left corner of the shifted main screen and positive down. If thisScreen is # not the main screen, we need to prevent self.winHandle._nswindow.screen() # from returning None, which can happen when the c binding returns nil if the # window is offscreen as a result of flipped y values of origins beween pyglet # and NSWindow coordinate systems. from pyglet.libs.darwin import cocoapy mainScreen_y_from_NSOrigin = allScrs[0].y + allScrs[0].height thisScreen_y_from_NSOrigin = thisScreen.y + thisScreen.height thisScreen_y = mainScreen_y_from_NSOrigin - thisScreen_y_from_NSOrigin temp_origin = cocoapy.NSPoint(thisScreen.x, thisScreen_y) self.winHandle._nswindow.setFrameOrigin_(temp_origin) elif sys.platform.startswith('linux'): win._hw_handle = self.winHandle._window self._frameBufferSize = win.clientSize if win.useFBO: # check for necessary extensions if not GL.gl_info.have_extension('GL_EXT_framebuffer_object'): msg = ("Trying to use a framebuffer object but " "GL_EXT_framebuffer_object is not supported. Disabled") logging.warn(msg) win.useFBO = False if not GL.gl_info.have_extension('GL_ARB_texture_float'): msg = ("Trying to use a framebuffer object but " "GL_ARB_texture_float is not supported. Disabling") logging.warn(msg) win.useFBO = False if pyglet.version < "1.2" and sys.platform == 'darwin': platform_specific.syncSwapBuffers(1) # add these methods to the pyglet window self.winHandle.setGamma = setGamma self.winHandle.setGammaRamp = setGammaRamp self.winHandle.getGammaRamp = getGammaRamp self.winHandle.set_vsync(True) self.winHandle.on_text = self.onText self.winHandle.on_move = self.onMove self.winHandle.on_resize = self.onResize self.winHandle.on_text_motion = self.onCursorKey self.winHandle.on_key_press = self.onKey self.winHandle.on_mouse_press = self.onMouseButtonPress self.winHandle.on_mouse_release = self.onMouseButtonRelease self.winHandle.on_mouse_scroll = self.onMouseScroll self.winHandle.on_mouse_motion = self.onMouseMove self.winHandle.on_mouse_enter = self.onMouseEnter self.winHandle.on_mouse_leave = self.onMouseLeave if not win.allowGUI: # make mouse invisible. Could go further and make it 'exclusive' # (but need to alter x,y handling then) self.winHandle.set_mouse_visible(False) if not win.pos: # work out the location of the top-left corner to place at the screen center win.pos = [(thisScreen.width - win.clientSize[0]) / 2, (thisScreen.height - win.clientSize[1]) / 2] if sys.platform == 'darwin': # always need to set the cocoa window location due to origin changes screenHeight_offset = thisScreen.height - allScrs[0].height self.winHandle.set_location(int(win.pos[0] + thisScreen.x), int(win.pos[1] + thisScreen.y + screenHeight_offset)) elif not win._isFullScr: # add the necessary amount for second screen self.winHandle.set_location(int(win.pos[0] + thisScreen.x), int(win.pos[1] + thisScreen.y)) try: # to load an icon for the window iconFile = os.path.join(psychopy.prefs.paths['assets'], 'window.ico') icon = pyglet.image.load(filename=iconFile) self.winHandle.set_icon(icon) except Exception: pass # doesn't matter # store properties of the system self._driver = pyglet.gl.gl_info.get_renderer() @property def frameBufferSize(self): """Size of the presently active framebuffer in pixels (w, h).""" return self._frameBufferSize @property def shadersSupported(self): # on pyglet shaders are fine so just check GL>2.0 return pyglet.gl.gl_info.get_version() >= '2.0' def swapBuffers(self, flipThisFrame=True): """Performs various hardware events around the window flip and then performs the actual flip itself (assuming that flipThisFrame is true) :param flipThisFrame: setting this to False treats this as a frame but doesn't actually trigger the flip itself (e.g. because the device needs multiple rendered frames per flip) """ # make sure this is current context if globalVars.currWindow != self: self.winHandle.switch_to() globalVars.currWindow = self GL.glTranslatef(0.0, 0.0, -5.0) for dispatcher in self.win._eventDispatchers: try: dispatcher.dispatch_events() except: dispatcher._dispatch_events() # this might need to be done even more often than once per frame? self.winHandle.dispatch_events() # for pyglet 1.1.4 you needed to call media.dispatch for # movie updating if pyglet.version < '1.2': pyglet.media.dispatch_events() # for sounds to be processed if flipThisFrame: self.winHandle.flip() def setCurrent(self): """Sets this window to be the current rendering target. Returns ------- bool ``True`` if the context was switched from another. ``False`` is returned if ``setCurrent`` was called on an already current window. """ if self != globalVars.currWindow: self.winHandle.switch_to() globalVars.currWindow = self return True return False def dispatchEvents(self): """Dispatch events to the event handler (typically called on each frame) :return: """ wins = _default_display_.get_windows() for win in wins: win.dispatch_events() def onResize(self, width, height): """A method that will be called if the window detects a resize event. This method is bound to the window backend resize event, data is formatted and forwarded to the user's callback function. """ # Call original _onResize handler _onResize(width, height) if self._onResizeCallback is not None: self._onResizeCallback(self.win, width, height) def onKey(self, evt, modifiers): """Check for tab key then pass all events to event package.""" if evt is not None: thisKey = pyglet.window.key.symbol_string(evt).lower() if thisKey == 'tab': self.onText('\t') event._onPygletKey(evt, modifiers) def onText(self, evt): """Retrieve the character event(s?) for this window""" if evt is not None: currentEditable = self.win.currentEditable if currentEditable: currentEditable._onText(evt) event._onPygletText(evt) # duplicate the event to the psychopy.events lib def onCursorKey(self, evt): """Processes the events from pyglet.window.on_text_motion which is keys like cursor, delete, backspace etc.""" currentEditable = self.win.currentEditable if currentEditable: keyName = pyglet.window.key.motion_string(evt) currentEditable._onCursorKeys(keyName) @attributeSetter def gamma(self, gamma): self.__dict__['gamma'] = gamma if systemtools.isVM_CI(): return if self._origGammaRamp is None: # get the original if we haven't yet self._getOrigGammaRamp() if gamma is not None: setGamma( screenID=self.screenID, newGamma=gamma, rampSize=self._rampSize, driver=self._driver, xDisplay=self.xDisplay, gammaErrorPolicy=self._gammaErrorPolicy ) @attributeSetter def gammaRamp(self, gammaRamp): """Gets the gamma ramp or sets it to a new value (an Nx3 or Nx1 array) """ self.__dict__['gammaRamp'] = gammaRamp if systemtools.isVM_CI(): return if self._origGammaRamp is None: # get the original if we haven't yet self._getOrigGammaRamp() setGammaRamp( self.screenID, gammaRamp, nAttempts=3, xDisplay=self.xDisplay, gammaErrorPolicy=self._gammaErrorPolicy ) def getGammaRamp(self): return getGammaRamp(self.screenID, self.xDisplay, gammaErrorPolicy=self._gammaErrorPolicy) def getGammaRampSize(self): return getGammaRampSize(self.screenID, self.xDisplay, gammaErrorPolicy=self._gammaErrorPolicy) def _getOrigGammaRamp(self): """This is just used to get origGammaRamp and will populate that if needed on the first call""" if self._origGammaRamp is None: self._origGammaRamp = self.getGammaRamp() self._rampSize = self.getGammaRampSize() else: return self._origGammaRamp @property def screenID(self): """Returns the screen ID or device context (depending on the platform) for the current Window """ if sys.platform == 'win32': scrBytes = self.winHandle._dc try: _screenID = 0xFFFFFFFF & int.from_bytes( scrBytes, byteorder='little') except TypeError: _screenID = 0xFFFFFFFF & scrBytes elif sys.platform == 'darwin': try: _screenID = self.winHandle._screen.id # pyglet1.2alpha1 except AttributeError: _screenID = self.winHandle._screen._cg_display_id # pyglet1.2 elif sys.platform.startswith('linux'): _screenID = self.winHandle._x_screen_id else: raise RuntimeError("Cannot get pyglet screen ID.") return _screenID @property def xDisplay(self): """On X11 systems this returns the XDisplay being used and None on all other platforms""" if sys.platform.startswith('linux'): return self.winHandle._x_display def close(self): """Close the window and uninitialize the resources """ # Check if window has device context and is thus not closed if self.winHandle.context is None: return # restore the gamma ramp that was active when window was opened if self._origGammaRamp is not None: self.gammaRamp = self._origGammaRamp try: self.winHandle.close() except Exception: pass def setFullScr(self, value): """Sets the window to/from full-screen mode. Parameters ---------- value : bool or int If `True`, resize the window to be fullscreen. """ self.winHandle.set_fullscreen(value) self.win.clientSize[:] = (self.winHandle.width, self.winHandle.height) # special handling for retina displays, if needed global retinaContext if retinaContext is not None: view = retinaContext.view() bounds = view.convertRectToBacking_(view.bounds()).size backWidth, backHeight = (int(bounds.width), int(bounds.height)) else: backWidth, backHeight = self.win.clientSize self._frameBufferSize[:] = (backWidth, backHeight) self.win.viewport = (0, 0, backWidth, backHeight) self.win.scissor = (0, 0, backWidth, backHeight) self.win.resetEyeTransform() def setMouseType(self, name='arrow'): """Change the appearance of the cursor for this window. Cursor types provide contextual hints about how to interact with on-screen objects. **Deprecated!** Use `setMouseCursor` instead. Parameters ---------- name : str Type of standard cursor to use. """ self.setMouseCursor(name) def setMouseCursor(self, cursorType='default'): """Change the appearance of the cursor for this window. Cursor types provide contextual hints about how to interact with on-screen objects. The graphics used 'standard cursors' provided by the operating system. They may vary in appearance and hot spot location across platforms. The following names are valid on most platforms: * ``arrow`` or ``default`` : Default system pointer. * ``ibeam`` or ``text`` : Indicates text can be edited. * ``crosshair`` : Crosshair with hot-spot at center. * ``hand`` : A pointing hand. * ``hresize`` : Double arrows pointing horizontally. * ``vresize`` : Double arrows pointing vertically. * ``help`` : Arrow with a question mark beside it (Windows only). * ``no`` : 'No entry' sign or circle with diagonal bar. * ``size`` : Vertical and horizontal sizing. * ``downleft`` or ``upright`` : Double arrows pointing diagonally with positive slope (Windows only). * ``downright`` or ``upleft`` : Double arrows pointing diagonally with negative slope (Windows only). * ``lresize`` : Arrow pointing left (Mac OS X only). * ``rresize`` : Arrow pointing right (Mac OS X only). * ``uresize`` : Arrow pointing up (Mac OS X only). * ``dresize`` : Arrow pointing down (Mac OS X only). * ``wait`` : Hourglass (Windows) or watch (Mac OS X) to indicate the system is busy. * ``waitarrow`` : Hourglass beside a default pointer (Windows only). In cases where a cursor is not supported, the default for the system will be used. Parameters ---------- cursorType : str Type of standard cursor to use. If not specified, `'default'` is used. Notes ----- * On some platforms the 'crosshair' cursor may not be visible on uniform grey backgrounds. """ try: cursor = _PYGLET_CURSORS_[cursorType] # get cursor if cursor is None: # check supported by backend logging.warn( "Cursor type name '{}', is not supported by this backend. " "Setting cursor to system default.".format(cursorType)) cursor = _PYGLET_CURSORS_['default'] # all backends define this except KeyError: logging.warn( "Invalid cursor type name '{}', using default.".format( cursorType)) cursor = _PYGLET_CURSORS_['default'] cursor = self.winHandle.get_system_mouse_cursor(cursor) self.winHandle.set_mouse_cursor(cursor) # -------------------------------------------------------------------------- # Window unit conversion # def _windowToBufferCoords(self, pos): """Convert window coordinates to OpenGL buffer coordinates. The standard convention for window coordinates is that the origin is at the top-left corner. The `y` coordinate increases in the downwards direction. OpenGL places the origin at bottom left corner, where `y` increases in the upwards direction. Parameters ---------- pos : ArrayLike Position `(x, y)` in window coordinates. Returns ------- ndarray Position `(x, y)` in buffer coordinates. """ # We override `_winToBufferCoords` here since Pyglet uses the OpenGL # window coordinate convention by default. scaleFactor = self.win.getContentScaleFactor() return np.asarray(pos, dtype=np.float32) * scaleFactor def _bufferToWindowCoords(self, pos): """OpenGL buffer coordinates to window coordinates. This is the inverse of `_windowToBufferCoords`. Parameters ---------- pos : ArrayLike Position `(x, y)` in window coordinates. Returns ------- ndarray Position `(x, y)` in buffer coordinates. """ invScaleFactor = 1.0 / self.win.getContentScaleFactor() return np.asarray(pos, dtype=np.float32) * invScaleFactor # -------------------------------------------------------------------------- # Mouse event handlers and utilities # @property def mouseVisible(self): """Get the visibility of the mouse cursor. Returns ------- bool `True` if the mouse cursor is visible. """ return self.winHandle._mouse_visible @mouseVisible.setter def mouseVisible(self, visibility): """Set the visibility of the mouse cursor. Parameters ---------- visibility : bool If `True`, the mouse cursor is visible. """ self.winHandle.set_mouse_visible(visibility) def setMouseVisibility(self, visibility): """Set the visibility of the mouse cursor. Parameters ---------- visibility : bool If `True`, the mouse cursor is visible. """ self.winHandle.set_mouse_visible(visibility) def onMouseButton(self, *args, **kwargs): """Event handler for any mouse button event (pressed and released). This is used by backends which combine both button state changes into a single event. Usually this would pass events to the appropriate `onMouseButtonPress` and `onMouseButtonRelease` events. """ pass def onMouseButtonPress(self, *args, **kwargs): """Event handler for mouse press events.""" # don't process mouse events until ready mouseEventHandler = mouse.Mouse.getInstance() if mouseEventHandler is None: event._onPygletMousePress(*args, **kwargs) return x, y, button, _ = args absTime = core.getTime() absPos = self._windowCoordsToPix((x, y)) mouseEventHandler.win = self.win mouseEventHandler.setMouseButtonState( _PYGLET_MOUSE_BUTTONS_[button], True, absPos, absTime) def onMouseButtonRelease(self, *args, **kwargs): """Event handler for mouse press events.""" # don't process mouse events until ready mouseEventHandler = mouse.Mouse.getInstance() if mouseEventHandler is None: event._onPygletMouseRelease(*args, **kwargs) return x, y, button, _ = args absTime = core.getTime() absPos = self._windowCoordsToPix((x, y)) mouseEventHandler.win = self.win mouseEventHandler.setMouseButtonState( _PYGLET_MOUSE_BUTTONS_[button], False, absPos, absTime) def onMouseScroll(self, *args, **kwargs): """Event handler for mouse scroll events.""" # don't process mouse events until ready mouseEventHandler = mouse.Mouse.getInstance() if mouseEventHandler is None: event._onPygletMouseWheel(*args, **kwargs) return # register mouse position associated with event x, y, scroll_x, scroll_y = args absTime = core.getTime() absPos = self._windowCoordsToPix((x, y)) mouseEventHandler.win = self.win mouseEventHandler.setMouseMotionState(absPos, absTime) def onMouseMove(self, *args, **kwargs): """Event handler for mouse move events.""" # don't process mouse events until ready mouseEventHandler = mouse.Mouse.getInstance() if mouseEventHandler is None: event._onPygletMouseMotion(*args, **kwargs) return x, y, _, _ = args absTime = core.getTime() absPos = self._windowCoordsToPix((x, y)) mouseEventHandler.win = self.win mouseEventHandler.setMouseMotionState(absPos, absTime) def onMouseEnter(self, *args, **kwargs): """Event called when the mouse enters the window.""" # don't process mouse events until ready mouseEventHandler = mouse.Mouse.getInstance() if mouseEventHandler is None: return absTime = core.getTime() absPos = self._windowCoordsToPix(args) # check if auto focus is enabled if mouseEventHandler.autoFocus: mouseEventHandler.win = self.win mouseEventHandler.setMouseMotionState(absPos, absTime) def onMouseLeave(self, *args, **kwargs): """Event called when the mouse enters the window.""" # don't process mouse events until ready mouseEventHandler = mouse.Mouse.getInstance() if mouseEventHandler is None: return absTime = core.getTime() absPos = self._windowCoordsToPix(args) mouseEventHandler.setMouseMotionState(absPos, absTime) if mouseEventHandler.autoFocus: mouseEventHandler.win = None def setMouseExclusive(self, exclusive): """Set mouse exclusivity. Parameters ---------- exclusive : bool Mouse exclusivity mode. """ self.winHandle.set_exclusive_mouse(bool(exclusive)) def getMousePos(self): """Get the position of the mouse on the current window. Returns ------- ndarray Position `(x, y)` in window coordinates. """ winX = self.winHandle._mouse_x winY = self.winHandle._mouse_y return self._windowCoordsToPix((winX, winY)) def setMousePos(self, pos): """Set/move the position of the mouse on the current window. Parameters ---------- pos : ArrayLike Position `(x, y)` in window coordinates. """ x, y = self._pixToWindowCoords(pos) self.winHandle.set_mouse_position(int(x), int(y)) def _onResize(width, height): """A default resize event handler. This default handler updates the GL viewport to cover the entire window and sets the ``GL_PROJECTION`` matrix to be orthogonal in window space. The bottom-left corner is (0, 0) and the top-right corner is the width and height of the :class:`~psychopy.visual.Window` in pixels. Override this event handler with your own to create another projection, for example in perspective. """ global retinaContext if height == 0: height = 1 if retinaContext is not None: view = retinaContext.view() bounds = view.convertRectToBacking_(view.bounds()).size back_width, back_height = (int(bounds.width), int(bounds.height)) else: back_width, back_height = width, height GL.glViewport(0, 0, back_width, back_height) GL.glMatrixMode(GL.GL_PROJECTION) GL.glLoadIdentity() GL.glOrtho(-1, 1, -1, 1, -1, 1) # GL.gluPerspective(90, 1.0 * width / height, 0.1, 100.0) GL.glMatrixMode(GL.GL_MODELVIEW) GL.glLoadIdentity()
35,729
Python
.py
793
34.64691
93
0.615418
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,778
glfwbackend.py
psychopy_psychopy/psychopy/visual/backends/glfwbackend.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). """A Backend class defines the core low-level functions required by a Window class, such as the ability to create an OpenGL context and flip the window. Users simply call visual.Window(..., winType='glfw') and the winType is then used by backends.getBackend(winType) which will locate the appropriate class and initialize an instance using the attributes of the Window. """ import psychopy.logging as logging try: from psychopy_glfw import GLFWBackend except (ModuleNotFoundError, ImportError): logging.warning( "GLFW window backend support is not installed. To get support, install " "the `psychopy-glfw` package and restart your session." ) logging.flush() if __name__ == "__main__": pass
961
Python
.py
22
40.772727
80
0.75134
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,779
__init__.py
psychopy_psychopy/psychopy/visual/backends/__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). """Backends provide the window creation and flipping commands. """ import psychopy.plugins as plugins from ._base import BaseBackend # Alias plugins.winTypes here, such that any plugins referencing visual.winTypes # will also update the matching dict in plugins winTypes = plugins._winTypes def getBackend(win, *args, **kwargs): """Retrieve the appropriate backend for the window. Parameters ---------- win : :class:`psychopy.visual.Window` Window requesting the backend. The `winType` attribute of the Window is used to determine which one to get. *args, **kwargs Optional positional and keyword arguments to pass to the backend constructor. These arguments are usually those passed to the constructor for the Window. Returns ------- :class:`~psychopy.visual.backends._base.BaseBackend` Backend class (subclass of BaseBackend). """ # Look-up the backend module name for `winType`, this is going to be used # when the plugin system goes live. For now, we're leaving it here. try: useBackend = winTypes[win.winType] except KeyError: raise KeyError( "User requested Window with winType='{}' but there is no backend " "definition to match that `winType`.".format(win.winType)) # this loads the backend dynamically from the FQN stored in `winTypes` Backend = plugins.resolveObjectFromName(useBackend, __name__) # Check if Backend is valid subclass of `BaseBackend`. If not, it should not # be used as a backend. if not issubclass(Backend, BaseBackend): raise TypeError("Requested backend is not subclass of `BaseBackend`.") return Backend(win, *args, **kwargs) def getAvailableWinTypes(): """Get a list of available window backends. This will also list backends provided by plugins if they have been loaded prior to calling this function. Returns ------- list List of possible values (`str`) to pass to the `winType` argument of `~:class:psychopy.visual.Window` . """ global winTypes return list(winTypes.keys()) # copy if __name__ == "__main__": pass
2,425
Python
.py
57
37.192982
80
0.70017
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,780
_base.py
psychopy_psychopy/psychopy/visual/backends/_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). """A Backend class defines the core low-level functions required by a Window class, such as the ability to create an OpenGL context and flip the window. Users simply call visual.Window(..., winType='pyglet') and the winType is then used by backends.getBackend(winType) which will locate the appropriate class and initialize an instance using the attributes of the Window. """ import weakref from abc import ABC, abstractmethod import numpy as np from psychopy import logging from psychopy.tools.attributetools import attributeSetter class BaseBackend(ABC): """The backend abstract base class that defines all the core low-level functions required by a :class:`~psychopy.visual.Window` class. Such methods as the ability to create an OpenGL context, process events, and flip the window are prototyped here. Sub-classes of this function must implement the abstract methods shown here to be complete. Users simply call visual.Window(..., winType='pyglet') and the `winType` is then used by `backends.getBackend(winType)` which will locate the appropriate class and initialize an instance using the attributes of the Window. """ # define GL here as a class attribute that includes all the opengl funcs # e.g. GL = pyglet.gl # define the name of the backend, used to register the name to use when # specifying `winType` # e.g. winTypeName = 'custom' def __init__(self, win): """Set up the backend window according the params of the PsychoPy win Before PsychoPy 1.90.0 this code was executed in Window._setupPyglet() :param: win is a PsychoPy Window (usually not fully created yet) """ self.win = win # this will use the @property to make/use a weakref # callback functions self._onMoveCallback = None self._onResizeCallback = None super().__init__() @abstractmethod def swapBuffers(self): """Set the gamma table for the graphics card """ raise NotImplementedError( "Backend has failed to override a necessary method") @abstractmethod def setCurrent(self): """Sets this window to be the current rendering target (for backends where 2 windows are permitted, e.g. not pygame) """ pass @attributeSetter def gamma(self, gamma): """Set the gamma table for the graphics card :param gamma: a single value or a triplet for separate RGB gamma values """ self.__dict__['gamma'] = gamma raise NotImplementedError( "Backend has failed to override a necessary method") @attributeSetter def gammaRamp(self, gammaRamp): """Gets the gamma ramp or sets it to a new value (an Nx3 or Nx1 array) """ self.__dict__['gammaRamp'] = gammaRamp raise NotImplementedError( "Backend has failed to override a necessary method") @property def shadersSupported(self): """This is a read-only property indicating whether or not this backend supports OpenGL shaders""" raise NotImplementedError( "Backend has failed to override a necessary method") # Optional, depending on backend needs def dispatchEvents(self): """This method is not needed for all backends but for engines with an event loop it may be needed to pump for new events (e.g. pyglet) """ logging.warning("dispatchEvents() method in {} was called " "but is not implemented. Is it needed?" .format(self.win.winType) ) @property def onMoveCallback(self): """Callback function for window move events (`callable` or `None`). Callback function must have the following signature:: callback(Any: winHandle, int: newPosX, int: newPosY) -> None """ return self._onMoveCallback @onMoveCallback.setter def onMoveCallback(self, value): if not (callable(value) or value is None): raise TypeError( 'Value for `onMoveCallback` must be callable or `None`.') self._onMoveCallback = value @property def onResizeCallback(self): """Callback function for window resize events (`callable` or `None`). Callback function must have the following signature:: callback(Any: winHandle, int: newSizeW, int: newSizeH) -> None """ return self._onResizeCallback @onResizeCallback.setter def onResizeCallback(self, value): if not (callable(value) or value is None): raise TypeError( 'Value for `onResizeCallback` must be callable or `None`.') self._onResizeCallback = value def onResize(self, width, height): """A method that will be called if the window detects a resize event. This method is bound to the window backend resize event, data is formatted and forwarded to the user's callback function. """ # When overriding this function, at the very minimum we must call the # user's function, passing the data they expect. if self._onResizeCallback is not None: self._onResizeCallback(self.win, width, height) def onMove(self, posX, posY): """A method called when the window is moved by the user. This method is bound to the window backend move event, data is formatted and forwarded to the user's callback function. """ if hasattr(self.win, 'pos'): # write the new position of the window self.win.pos = (posX, posY) if self._onMoveCallback is not None: self._onMoveCallback(self.win, posX, posY) # Helper methods that don't need converting @property def win(self): """The PsychoPy Window that this backend is supporting, which provides various important variables (like size, units, color etc). NB win is stored as a weakref to a psychopy.window and this property helpfully converts it back to a regular object so you don't need to think about it! """ ref = self.__dict__['win'] return ref() @win.setter def win(self, win): """The PsychoPy Window that this backend is supporting, which provides various important variables (like size, units, color etc). NB win is stored as a weakref to a psychopy.window and this property helpfully converts it back to a regular object so you don't need to think about it! """ self.__dict__['win'] = weakref.ref(win) @property def autoLog(self): """If the window has logging turned on then backend should too""" return self.win.autoLog @property def name(self): """Name of the backend is only used for logging purposes""" return "{}_backend".format(self.win.name) # -------------------------------------------------------------------------- # Window unit conversion # def _windowToBufferCoords(self, pos): """Convert window coordinates to OpenGL buffer coordinates. The standard convention for window coordinates is that the origin is at the top-left corner. The `y` coordinate increases in the downwards direction. OpenGL places the origin at bottom left corner, where `y` increases in the upwards direction. Parameters ---------- pos : ArrayLike Position `(x, y)` in window coordinates. Returns ------- ndarray Position `(x, y)` in buffer coordinates. """ # This conversion is typical for many frameworks. If the framework uses # some other convention, that backend class should override this method # to ensure `_windowToPixCoords` returns the correct value. # invSf = 1.0 / self.win.getContentScaleFactor() return np.array( (pos[0] * invSf, (self.win.size[1] - pos[1]) * invSf), dtype=np.float32) def _bufferToWindowCoords(self, pos): """OpenGL buffer coordinates to window coordinates. This is the inverse of `_windowToBufferCoords`. Parameters ---------- pos : ArrayLike Position `(x, y)` in window coordinates. Returns ------- ndarray Position `(x, y)` in buffer coordinates. """ # This conversion is typical for many frameworks. If the framework uses # some other convention, that backend class should override this method # to ensure `_windowToPixCoords` returns the correct value. # sf = self.win.getContentScaleFactor() return np.array( (pos[0] * sf, -pos[1] * sf + self.win.size[1]), dtype=np.float32) def _windowCoordsToPix(self, pos): """Convert window coordinates to the PsychoPy 'pix' coordinate system. This puts the origin at the center of the window. Parameters ---------- pos : ArrayLike Position `(x, y)` in window coordinates. Returns ------- ndarray Position `(x, y)` in PsychoPy pixel coordinates. """ return np.asarray(self._windowToBufferCoords(pos) - self.win.size / 2.0, dtype=np.float32) def _pixToWindowCoords(self, pos): """Convert PsychoPy 'pix' to the window coordinate system. This is the inverse of `_windowToPixCoords`. Parameters ---------- pos : ArrayLike Position `(x, y)` in PsychoPy pixel coordinates. Returns ------- ndarray Position `(x, y)` in window coordinates. """ return self._bufferToWindowCoords( np.asarray(pos, dtype=np.float32) + self.win.size / 2.0) # -------------------------------------------------------------------------- # Mouse related methods (e.g., event handlers) # # These methods are used to handle mouse events. Each function is bound to # the appropriate callback which registers the mouse event with the global # mouse event handler (psychopy.hardware.mouse.Mouse). Each callback has an # `*args` parameter which allows the backend to pass whatever parameters. # @abstractmethod def onMouseButton(self, *args, **kwargs): """Event handler for any mouse button event (pressed and released). This is used by backends which combine both button state changes into a single event. Usually this would pass events to the appropriate `onMouseButtonPress` and `onMouseButtonRelease` methods. """ raise NotImplementedError( "`onMouseButton` is not yet implemented for this backend.") @abstractmethod def onMouseButtonPress(self, *args, **kwargs): """Event handler for mouse press events. This handler can also be used for release events if the backend passes all button events to the same callback. """ raise NotImplementedError( "`onMouseButtonPress` is not yet implemented for this backend.") @abstractmethod def onMouseButtonRelease(self, *args, **kwargs): """Event handler for mouse release events.""" raise NotImplementedError( "`onMouseButtonRelease` is not yet implemented for this backend.") @abstractmethod def onMouseScroll(self, *args, **kwargs): """Event handler for mouse scroll events. Called when the mouse scroll wheel is moved.""" raise NotImplementedError( "`onMouseScroll` is not yet implemented for this backend.") @abstractmethod def onMouseMove(self, *args, **kwargs): """Event handler for mouse move events.""" raise NotImplementedError( "`onMouseMove` is not yet implemented for this backend.") @abstractmethod def onMouseEnter(self, *args, **kwargs): """Event called when the mouse enters the window. Some backends might combine enter and leave events to the same callback, this will handle both if so. """ raise NotImplementedError( "`onMouseEnter` is not yet implemented for this backend.") @abstractmethod def onMouseLeave(self, *args, **kwargs): """Event called when a mouse leaves the window.""" raise NotImplementedError( "`onMouseLeave` is not yet implemented for this backend.") @abstractmethod def getMousePos(self): """Get the position of the mouse on the current window. Returns ------- ndarray Position `(x, y)` in window coordinates. """ raise NotImplementedError( "`getMousePos` is not yet implemented for this backend.") @abstractmethod def setMousePos(self, pos): """Set/move the position of the mouse on the current window. Parameters ---------- pos : ArrayLike Position `(x, y)` in window coordinates. """ raise NotImplementedError( "`setMousePos` is not yet implemented for this backend.") def setMouseType(self, name='arrow'): """Change the appearance of the cursor for this window. Cursor types provide contextual hints about how to interact with on-screen objects. **Deprecated!** Use `setMouseCursor` instead. Parameters ---------- name : str Type of standard cursor to use. """ self.setMouseCursor(name) @abstractmethod def setMouseCursor(self, cursorType='default'): """Change the appearance of the cursor for this window. Cursor types provide contextual hints about how to interact with on-screen objects. The graphics used 'standard cursors' provided by the operating system. They may vary in appearance and hot spot location across platforms. The following names are valid on most platforms: * ``arrow`` or ``default`` : Default system pointer. * ``ibeam`` or ``text`` : Indicates text can be edited. * ``crosshair`` : Crosshair with hot-spot at center. * ``hand`` : A pointing hand. * ``hresize`` : Double arrows pointing horizontally. * ``vresize`` : Double arrows pointing vertically. * ``help`` : Arrow with a question mark beside it (Windows only). * ``no`` : 'No entry' sign or circle with diagonal bar. * ``size`` : Vertical and horizontal sizing. * ``downleft`` or ``upright`` : Double arrows pointing diagonally with positive slope (Windows only). * ``downright`` or ``upleft`` : Double arrows pointing diagonally with negative slope (Windows only). * ``lresize`` : Arrow pointing left (Mac OS X only). * ``rresize`` : Arrow pointing right (Mac OS X only). * ``uresize`` : Arrow pointing up (Mac OS X only). * ``dresize`` : Arrow pointing down (Mac OS X only). * ``wait`` : Hourglass (Windows) or watch (Mac OS X) to indicate the system is busy. * ``waitarrow`` : Hourglass beside a default pointer (Windows only). In cases where a cursor is not supported, the default for the system will be used. Parameters ---------- cursorType : str Type of standard cursor to use. If not specified, `'default'` is used. Notes ----- * On some platforms the 'crosshair' cursor may not be visible on uniform grey backgrounds. """ raise NotImplementedError( "`setMouseCursor` is not yet implemented for this backend.") @abstractmethod def setMouseVisibility(self, visible): """Set mouse visibility. Parameters ---------- visible : bool Mouse visibility mode. """ raise NotImplementedError( "`setMouseVisibility` is not yet implemented for this backend.") @abstractmethod def setMouseExclusive(self, exclusive): """Set mouse exclusivity. Parameters ---------- exclusive : bool Mouse exclusivity mode. """ raise NotImplementedError( "`setMouseExclusive` is not yet implemented for this backend.") if __name__ == "__main__": pass
16,791
Python
.py
377
35.838196
80
0.635438
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,781
_psychopyApp.py
psychopy_psychopy/psychopy/app/_psychopyApp.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 traceback from pathlib import Path from psychopy.app.colorpicker import PsychoColorPicker import sys import pickle import tempfile import mmap import time import io import argparse from psychopy.app.themes import icons, colors, handlers import psychopy from psychopy import prefs from packaging.version import Version from . import urls from . import frametracker from . import themes from . import console if not hasattr(sys, 'frozen'): try: import wxversion haveWxVersion = True except ImportError: haveWxVersion = False # if wxversion doesn't exist hope for the best if haveWxVersion: wxversion.ensureMinimal('2.8') # because this version has agw import wx try: from agw import advancedsplash as AS except ImportError: # if it's not there locally, try the wxPython lib. import wx.lib.agw.advancedsplash as AS # from .plugin_manager import saveStartUpPluginsConfig from psychopy.localization import _translate # NB keep imports to a minimum here because splash screen has not yet shown # e.g. coder and builder are imported during app.__init__ because they # take a while # needed by splash screen for the path to resources/psychopySplash.png import ctypes from psychopy import logging, __version__ from psychopy import projects from . import connections from .utils import FileDropTarget import os import weakref # knowing if the user has admin priv is generally a good idea for security. # not actually needed; psychopy should never need anything except normal user # see older versions for code to detect admin (e.g., v 1.80.00) # Enable high-dpi support if on Windows. This fixes blurry text rendering. if sys.platform == 'win32': # get the preference for high DPI if 'highDPI' in psychopy.prefs.app.keys(): # check if we have the option enableHighDPI = psychopy.prefs.app['highDPI'] # check if we have OS support for it if enableHighDPI: try: ctypes.windll.shcore.SetProcessDpiAwareness(enableHighDPI) except OSError: logging.warn( "High DPI support is not appear to be supported by this " "version of Windows. Disabling in preferences.") psychopy.prefs.app['highDPI'] = False psychopy.prefs.saveUserPrefs() class MenuFrame(wx.Frame, themes.handlers.ThemeMixin): """A simple empty frame with a menubar, should be last frame closed on mac """ def __init__(self, parent=None, ID=-1, app=None, title="PsychoPy"): wx.Frame.__init__(self, parent, ID, title, size=(1, 1)) self.app = app self.menuBar = wx.MenuBar() self.viewMenu = wx.Menu() self.menuBar.Append(self.viewMenu, _translate('&View')) mtxt = _translate("&Open Builder view\t") self.app.IDs.openBuilderView = self.viewMenu.Append( wx.ID_ANY, mtxt, _translate("Open a new Builder view")).GetId() self.Bind(wx.EVT_MENU, self.app.showBuilder, id=self.app.IDs.openBuilderView) mtxt = _translate("&Open Coder view\t") self.app.IDs.openCoderView = self.viewMenu.Append( wx.ID_ANY, mtxt, _translate("Open a new Coder view")).GetId() self.Bind(wx.EVT_MENU, self.app.showCoder, id=self.app.IDs.openCoderView) mtxt = _translate("&Quit\t%s") item = self.viewMenu.Append( wx.ID_EXIT, mtxt % self.app.keys['quit'], _translate("Terminate the program")) self.Bind(wx.EVT_MENU, self.app.quit, id=item.GetId()) self.SetMenuBar(self.menuBar) self.Show() class IDStore(dict): """A simpe class that works like a dict but you can access attributes like standard python attrs. Useful to replace the previous pre-made app.IDs (wx.NewIdRef(count=1) is no longer recommended or safe) """ def __getattr__(self, attr): return self[attr] def __setattr__(self, attr, value): self[attr] = value class _Showgui_Hack(): """Class with side-effect of restoring wx window switching under wx-3.0 - might only be needed on some platforms (Mac 10.9.4 needs it for me); - needs to be launched as an external script - needs to be separate: seg-faults as method of PsychoPyApp or in-lined - unlear why it works or what the deeper issue is, blah - called at end of PsychoPyApp.onInit() """ def __init__(self): super(_Showgui_Hack, self).__init__() from psychopy import core import os # should be writable: noopPath = os.path.join(psychopy.prefs.paths['userPrefsDir'], 'showgui_hack.py') # code to open & immediately close a gui (= invisibly): if not os.path.isfile(noopPath): code = """from psychopy import gui dlg = gui.Dlg().Show() # non-blocking try: dlg.Destroy() # might as well except Exception: pass""" with open(noopPath, 'wb') as fd: fd.write(bytes(code)) # append 'w' for pythonw seems not needed core.shellCall([sys.executable, noopPath]) class PsychoPyApp(wx.App, handlers.ThemeMixin): _called_from_test = False # pytest needs to change this def __init__(self, arg=0, testMode=False, startView=None, profiling=False, **kwargs): """With a wx.App some things get done here, before App.__init__ then some further code is launched in OnInit() which occurs after """ if profiling: import cProfile import time profile = cProfile.Profile() profile.enable() t0 = time.time() from . import setAppInstance setAppInstance(self) self._appLoaded = False # set to true when all frames are created self.builder = None self.coder = None self.runner = None self.version = psychopy.__version__ # array of handles to extant Pavlovia buttons self.pavloviaButtons = { 'user': [], 'project': [], } # set default paths and prefs self.prefs = psychopy.prefs self._currentThemeSpec = None self.keys = self.prefs.keys self.prefs.pageCurrent = 0 # track last-viewed page, can return there self.IDs = IDStore() self.urls = urls.urls self.quitting = False # check compatibility with last run version (before opening windows) self.firstRun = False self.testMode = testMode self._stdout = sys.stdout self._stderr = sys.stderr self._stdoutFrame = None # set as false to disable loading plugins on startup self._safeMode = kwargs.get('safeMode', True) self.firstRun = kwargs.get('firstRun', False) # Shared memory used for messaging between app instances, this gets # allocated when `OnInit` is called. self._sharedMemory = None self._singleInstanceChecker = None # checker for instances self._lastInstanceCheckTime = -1.0 # Size of the memory map buffer, needs to be large enough to hold UTF-8 # encoded long file paths. self.mmap_sz = 2048 # mdc - removed the following and put it in `app.startApp()` to have # error logging occur sooner. # # if not self.testMode: # self._lastRunLog = open(os.path.join( # self.prefs.paths['userPrefsDir'], 'last_app_load.log'), # 'w') # sys.stderr = sys.stdout = lastLoadErrs = self._lastRunLog # logging.console.setLevel(logging.DEBUG) # indicates whether we're running for testing purposes self.osfSession = None self.pavloviaSession = None self.copiedRoutine = None self.copiedCompon = None self._allFrames = frametracker.openFrames # ordered; order updated with self.onNewTopWindow wx.App.__init__(self, arg) # import localization after wx: from psychopy import localization # needed by splash screen self.localization = localization self.locale = localization.setLocaleWX() self.locale.AddCatalog(self.GetAppName()) logging.flush() self.onInit( testMode=testMode, startView=startView, **kwargs ) if profiling: profile.disable() print("time to load app = {:.2f}".format(time.time()-t0)) profile.dump_stats('profileLaunchApp.profile') logging.flush() # if we're on linux, check if we have the permissions file setup from psychopy.app.linuxconfig import ( LinuxConfigDialog, linuxRushAllowed) if not linuxRushAllowed(): linuxConfDlg = LinuxConfigDialog( None, timeout=1000 if self.testMode else None) linuxConfDlg.ShowModal() linuxConfDlg.Destroy() def _doSingleInstanceCheck(self): """Set up the routines which check for and communicate with other PsychoPy GUI processes. Single instance check is done here prior to loading any GUI stuff. This permits one instance of PsychoPy from running at any time. Clicking on files will open them in the extant instance rather than loading up a new one. Inter-process messaging is done via a memory-mapped file created by the first instance. Successive instances will write their args to this file and promptly close. The main instance will read this file periodically for data and open and file names stored to this buffer. This uses similar logic to this example: https://github.com/wxWidgets/wxPython-Classic/blob/master/wx/lib/pydocview.py """ # Create the memory-mapped file if not present, this is handled # differently between Windows and UNIX-likes. if wx.Platform == '__WXMSW__': tfile = tempfile.TemporaryFile(prefix="ag", suffix="tmp") fno = tfile.fileno() self._sharedMemory = mmap.mmap(fno, self.mmap_sz, "shared_memory") else: tfile = open( os.path.join( tempfile.gettempdir(), tempfile.gettempprefix() + self.GetAppName() + '-' + wx.GetUserId() + "AGSharedMemory"), 'w+b') # insert markers into the buffer tfile.write(b"*") tfile.seek(self.mmap_sz) tfile.write(b" ") tfile.flush() fno = tfile.fileno() self._sharedMemory = mmap.mmap(fno, self.mmap_sz) # use wx to determine if another instance is running self._singleInstanceChecker = wx.SingleInstanceChecker( self.GetAppName() + '-' + wx.GetUserId(), tempfile.gettempdir()) # If another instance is running, message our args to it by writing the # path the buffer. if self._singleInstanceChecker.IsAnotherRunning(): # Message the extant running instance the arguments we want to # process. args = sys.argv[1:] # if there are no args, tell the user another instance is running if not args: errMsg = "Another instance of PsychoPy is already running." errDlg = wx.MessageDialog( None, errMsg, caption="PsychoPy Error", style=wx.OK | wx.ICON_ERROR, pos=wx.DefaultPosition) errDlg.ShowModal() errDlg.Destroy() self.quit(None) # serialize the data data = pickle.dumps(args) # Keep alive until the buffer is free for writing, this allows # multiple files to be opened in succession. Times out after 5 # seconds. attempts = 0 while attempts < 5: # try to write to the buffer self._sharedMemory.seek(0) marker = self._sharedMemory.read(1) if marker == b'\0' or marker == b'*': self._sharedMemory.seek(0) self._sharedMemory.write(b'-') self._sharedMemory.write(data) self._sharedMemory.seek(0) self._sharedMemory.write(b'+') self._sharedMemory.flush() break else: # wait a bit for the buffer to become free time.sleep(1) attempts += 1 else: if not self.testMode: # error that we could not access the memory-mapped file errMsg = \ "Cannot communicate with running PsychoPy instance!" errDlg = wx.MessageDialog( None, errMsg, caption="PsychoPy Error", style=wx.OK | wx.ICON_ERROR, pos=wx.DefaultPosition) errDlg.ShowModal() errDlg.Destroy() # since were not the main instance, exit ... self.quit(None) def _refreshComponentPanels(self): """Refresh Builder component panels. Since panels are created before loading plugins, calling this method is required after loading plugins which contain components to have them appear. """ if not hasattr(self, 'builder') or self.builder is None: return # nop if we haven't realized the builder UI yet if not isinstance(self.builder, list): self.builder.componentButtons.populate() else: for builderFrame in self.builder: builderFrame.componentButtons.populate() def onInit( self, showSplash=True, testMode=False, safeMode=False, startView=None, startFiles=None, firstRun=False, ): """This is launched immediately *after* the app initialises with wxPython. Plugins are loaded at the very end of this routine if `safeMode==False`. Parameters ---------- showSplash : bool Display the splash screen on init. testMode : bool Are we running in test mode? If so, disable multi-instance checking and other features that depend on the `EVT_IDLE` event. safeMode : bool Run PsychoPy in safe mode. This temporarily disables plugins and resets configurations that may be causing problems running PsychoPy. """ self.SetAppName('PsychoPy3') # Check for other running instances and communicate with them. This is # done to allow a single instance to accept file open requests without # opening it in a seperate process. # self._doSingleInstanceCheck() if showSplash: # show splash screen splashFile = os.path.join( self.prefs.paths['resources'], 'psychopySplash.png') splashImage = wx.Image(name=splashFile) splashImage.ConvertAlphaToMask() splash = AS.AdvancedSplash( None, bitmap=splashImage.ConvertToBitmap(), timeout=3000, agwStyle=AS.AS_TIMEOUT | AS.AS_CENTER_ON_SCREEN ) w, h = splashImage.GetSize() splash.SetTextPosition((340, h - 30)) splash.SetText( _translate("Copyright (C) {year} OpenScienceTools.org").format(year=2024)) else: splash = None # SLOW IMPORTS - these need to be imported after splash screen starts # but then that they end up being local so keep track in self from psychopy.compatibility import checkCompatibility, checkUpdatesInfo # import coder and builder here but only use them later from psychopy.app import coder, builder, runner, dialogs if 'lastVersion' not in self.prefs.appData: # must be before 1.74.00 last = self.prefs.appData['lastVersion'] = '1.73.04' self.firstRun = True else: last = self.prefs.appData['lastVersion'] if self.firstRun and not self.testMode: pass # setup links for URLs # on a mac, don't exit when the last frame is deleted, just show menu if sys.platform == 'darwin': self.menuFrame = MenuFrame(parent=None, app=self) # load fonts if splash: splash.SetText(_translate(" Loading app fonts...")) self.dpi = int(wx.GetDisplaySize()[0] / float(wx.GetDisplaySizeMM()[0]) * 25.4) # detect retina displays self.isRetina = self.dpi > 80 and wx.Platform == '__WXMAC__' if self.isRetina: fontScale = 1.2 # fonts are looking tiny on macos (only retina?) right now # mark icons as being retina icons.retStr = "@2x" else: fontScale = 1 # adjust dpi to something reasonable if not (50 < self.dpi < 120): self.dpi = 80 # dpi was unreasonable, make one up # Manage fonts if sys.platform == 'win32': # wx.SYS_DEFAULT_GUI_FONT is default GUI font in Win32 self._mainFont = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT) else: self._mainFont = wx.SystemSettings.GetFont(wx.SYS_ANSI_FIXED_FONT) # rescale for tiny retina fonts if hasattr(wx.Font, "AddPrivateFont") and sys.platform != "darwin": # Load packaged fonts if possible for fontFile in (Path(__file__).parent / "Resources" / "fonts").glob("*"): if fontFile.suffix in ['.ttf', '.truetype']: wx.Font.AddPrivateFont(str(fontFile)) # Set fonts as those loaded self._codeFont = wx.Font( wx.FontInfo(self._mainFont.GetPointSize()).FaceName( "JetBrains Mono")) else: # Get system defaults if can't load fonts try: self._codeFont = wx.SystemSettings.GetFont(wx.SYS_ANSI_FIXED_FONT) except wx._core.wxAssertionError: # if no SYS_ANSI_FIXED_FONT then try generic FONTFAMILY_MODERN self._codeFont = wx.Font(self._mainFont.GetPointSize(), wx.FONTFAMILY_TELETYPE, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL) if self.isRetina: self._codeFont.SetPointSize(int(self._codeFont.GetPointSize()*fontScale)) self._mainFont.SetPointSize(int(self._mainFont.GetPointSize()*fontScale)) # that gets most of the properties of _codeFont but the FaceName # FaceName is set in the setting of the theme: self.theme = prefs.app['theme'] # load plugins so they're available before frames are created if splash: splash.SetText(_translate(" Loading plugins...")) from psychopy.plugins import activatePlugins activatePlugins() # load starting files if splash: splash.SetText(_translate(" Loading requested files...")) # get starting files if startFiles is None: startFiles = [] # get last coder files if self.prefs.coder['reloadPrevFiles']: for thisFile in self.prefs.appData['coder']['prevFiles']: startFiles.append(thisFile) # get last builder files if self.prefs.builder['reloadPrevExp'] and ('prevFiles' in self.prefs.appData['builder']): for thisFile in self.prefs.appData['builder']['prevFiles']: startFiles.append(thisFile) # open start files for thisFile in startFiles: # convert to file object & skip any which aren't paths try: thisFile = Path(thisFile) except: continue # skip nonexistent files if not thisFile.is_file(): logging.error(_translate( "Failed to open {}, file does not exist." ).format(thisFile)) continue try: # choose frame based on extension if thisFile.suffix == ".psyexp": # open .psyexp in Builder builder = self.showBuilder() if builder.fileExists: # if current builder file is a real file, open in new frame self.newBuilderFrame(fileName=str(thisFile)) else: # otherwise, open in current builder.fileOpen(filename=thisFile) elif thisFile.suffix == ".psyrun": # open .psyrun in Runner runner = self.showRunner() runner.fileOpen(filename=str(thisFile)) else: # open anything else in Coder coder = self.showCoder() coder.fileOpen(filename=str(thisFile)) except Exception as err: logging.error(_translate( "Failed to open file {}, reason: {}" ).format(thisFile, err)) # show frames if splash: splash.SetText(_translate(" Creating frames...")) # get starting windows if startView in (None, []): # if no window specified, use default from prefs if self.prefs.app['defaultView'] == 'all': startView = ["builder", "coder", "runner"] elif self.prefs.app['defaultView'] == "last": if self.prefs.appData['lastFrame'] == "both": self.prefs.appData['lastFrame'] = "builder-coder-runner" startView = self.prefs.appData['lastFrame'].split("-") elif self.prefs.app['defaultView'] in ["builder", "coder", "runner"]: startView = self.prefs.app['defaultView'] else: startView = ["builder"] # if specified as a single string, convert to list if isinstance(startView, str): startView = [startView] # if last open frame was no frame, use all instead if not startView: startView = ["builder", "coder", "runner"] # create windows if "runner" in startView: self.showRunner() if "coder" in startView: self.showCoder() if "builder" in startView: self.showBuilder() # # if told to directly run stuff, do it now # if "direct" in startView: # self.showRunner() # for exp in [file for file in sys.argv if file.endswith('.psyexp') or file.endswith('.py')]: # self.runner.panel.runFile(exp) # if we started a busy cursor which never finished, finish it now if wx.IsBusy(): wx.EndBusyCursor() # send anonymous info to https://usage.psychopy.org # please don't disable this, it's important for PsychoPy's development self._latestAvailableVersion = None self.updater = None self.news = None self.tasks = None prefsConn = self.prefs.connections # check for potential compatability issues ok, msg = checkCompatibility(last, self.version, self.prefs, fix=True) # tell the user what has changed if not ok and not self.firstRun and not self.testMode: title = _translate("Compatibility information") dlg = dialogs.MessageDialog(parent=None, message=msg, type='Info', title=title) dlg.ShowModal() # check for non-issue updates messages = checkUpdatesInfo(old=last, new=self.version) if messages: dlg = dialogs.RichMessageDialog( parent=None, message="\n\n".join(messages) ) dlg.Show() if self.prefs.app['showStartupTips'] and not self.testMode: tipFile = os.path.join( self.prefs.paths['resources'], _translate("tips.txt")) tipIndex = self.prefs.appData['tipIndex'] if Version(wx.__version__) >= Version('4.0.0a1'): tp = wx.adv.CreateFileTipProvider(tipFile, tipIndex) showTip = wx.adv.ShowTip(None, tp) else: tp = wx.CreateFileTipProvider(tipFile, tipIndex) showTip = wx.ShowTip(None, tp) self.prefs.appData['tipIndex'] = tp.GetCurrentTip() self.prefs.saveAppData() self.prefs.app['showStartupTips'] = showTip self.prefs.saveUserPrefs() self.Bind(wx.EVT_IDLE, self.onIdle) # doing this once subsequently enables the app to open & switch among # wx-windows on some platforms (Mac 10.9.4) with wx-3.0: v = Version if sys.platform == 'darwin': if v('3.0') <= v(wx.__version__) < v('4.0'): _Showgui_Hack() # returns ~immediately, no display # focus stays in never-land, so bring back to the app: if prefs.app['defaultView'] in ['all', 'builder', 'coder', 'runner']: self.showBuilder() else: self.showCoder() # after all windows are created (so errors flushed) create output self._appLoaded = True if self.coder: self.coder.setOutputWindow() # takes control of sys.stdout # flush any errors to the last run log file logging.flush() sys.stdout.flush() # we wanted debug mode while loading but safe to go back to info mode if not self.prefs.app['debugMode']: logging.console.setLevel(logging.INFO) return True def _bgCheckAndLoad(self, *args): """Check shared memory for messages from other instances. This only is called periodically in the first and only instance of PsychoPy running on the machine. This is called within the app's main idle event method, with a frequency no more that once per second. """ if not self._appLoaded: # only open files if we have a UI return self._sharedMemory.seek(0) if self._sharedMemory.read(1) == b'+': # available data data = self._sharedMemory.read(self.mmap_sz - 1) self._sharedMemory.seek(0) self._sharedMemory.write(b"*") self._sharedMemory.flush() # decode file path from data filePaths = pickle.loads(data) for fileName in filePaths: self.MacOpenFile(fileName) # force display of running app topWindow = wx.GetApp().GetTopWindow() if topWindow.IsIconized(): topWindow.Iconize(False) else: topWindow.Raise() @property def appLoaded(self): """`True` if the app has been fully loaded (`bool`).""" return self._appLoaded def _wizard(self, selector, arg=''): from psychopy import core wizard = os.path.join( self.prefs.paths['psychopy'], 'tools', 'wizard.py') so, se = core.shellCall( [sys.executable, wizard, selector, arg], stderr=True) if se and self.prefs.app['debugMode']: print(se) # stderr contents; sometimes meaningless def firstrunWizard(self): self._wizard('--config', '--firstrun') # wizard typically creates html report file but user can manually skip reportPath = os.path.join( self.prefs.paths['userPrefsDir'], 'firstrunReport.html') if os.path.exists(reportPath): with io.open(reportPath, 'r', encoding='utf-8-sig') as f: report = f.read() if 'Configuration problem' in report: # fatal error was encountered (currently only if bad drivers) # ensure wizard will be triggered again: del self.prefs.appData['lastVersion'] self.prefs.saveAppData() def benchmarkWizard(self, evt=None): self._wizard('--benchmark') def csvFromPsydat(self, evt=None): from psychopy import gui from psychopy.tools.filetools import fromFile prompt = _translate("Select .psydat file(s) to extract") names = gui.fileOpenDlg(allowed='*.psydat', prompt=prompt) for name in names or []: filePsydat = os.path.abspath(name) print("psydat: {0}".format(filePsydat)) exp = fromFile(filePsydat) if filePsydat.endswith('.psydat'): fileCsv = filePsydat[:-7] else: fileCsv = filePsydat fileCsv += '.csv' exp.saveAsWideText(fileCsv) print(' -->: {0}'.format(os.path.abspath(fileCsv))) def checkUpdates(self, evt): # if we have internet and haven't yet checked for updates then do so # we have a network connection but not yet tried an update if self._latestAvailableVersion not in [-1, None]: # change IDLE routine so we won't come back here self.Unbind(wx.EVT_IDLE) # unbind all EVT_IDLE methods from app self.Bind(wx.EVT_IDLE, self.onIdle) # create updater (which will create dialogs as needed) self.updater = connections.Updater(app=self) self.updater.latest = self._latestAvailableVersion self.updater.suggestUpdate(confirmationDlg=False) evt.Skip() def getPrimaryDisplaySize(self): """Get the size of the primary display (whose coords start (0,0)) """ return list(wx.Display(0).GetGeometry())[2:] def makeAccelTable(self): """Makes a standard accelorator table and returns it. This then needs to be set for the Frame using self.SetAccelerator(table) """ def parseStr(inStr): accel = 0 if 'ctrl' in inStr.lower(): accel += wx.ACCEL_CTRL if 'shift' in inStr.lower(): accel += wx.ACCEL_SHIFT if 'alt' in inStr.lower(): accel += wx.ACCEL_ALT return accel, ord(inStr[-1]) # create a list to link IDs to key strings keyCodesDict = {} keyCodesDict[self.keys['copy']] = wx.ID_COPY keyCodesDict[self.keys['cut']] = wx.ID_CUT keyCodesDict[self.keys['paste']] = wx.ID_PASTE keyCodesDict[self.keys['undo']] = wx.ID_UNDO keyCodesDict[self.keys['redo']] = wx.ID_REDO keyCodesDict[self.keys['save']] = wx.ID_SAVE keyCodesDict[self.keys['saveAs']] = wx.ID_SAVEAS keyCodesDict[self.keys['close']] = wx.ID_CLOSE keyCodesDict[self.keys['redo']] = wx.ID_REDO keyCodesDict[self.keys['quit']] = wx.ID_EXIT # parse the key strings and convert to accelerator entries entries = [] for keyStr, code in list(keyCodesDict.items()): mods, key = parseStr(keyStr) entry = wx.AcceleratorEntry(mods, key, code) entries.append(entry) table = wx.AcceleratorTable(entries) return table def updateWindowMenu(self): """Update items within Window menu to reflect open windows""" # Update checks on menus in all frames for frame in self.getAllFrames(): if hasattr(frame, "windowMenu"): frame.windowMenu.updateFrames() def showCoder(self, event=None, fileList=None): # have to reimport because it is only local to __init__ so far from . import coder if self.coder is None: title = "PsychoPy Coder (IDE) (v%s)" wx.BeginBusyCursor() self.coder = coder.CoderFrame(None, -1, title=title % self.version, files=fileList, app=self) self.updateWindowMenu() wx.EndBusyCursor() else: # set output window and standard streams self.coder.setOutputWindow(True) # open file list if fileList is None: fileList = [] for file in fileList: self.coder.fileOpen(filename=file) self.coder.Show(True) self.SetTopWindow(self.coder) self.coder.Raise() return self.coder def newBuilderFrame(self, event=None, fileName=None): # have to reimport because it is only local to __init__ so far wx.BeginBusyCursor() from .builder.builder import BuilderFrame title = "PsychoPy Builder (v%s)" self.builder = BuilderFrame(None, -1, title=title % self.version, fileName=fileName, app=self) self.builder.Show(True) self.builder.Raise() self.SetTopWindow(self.builder) self.updateWindowMenu() wx.EndBusyCursor() return self.builder def showBuilder(self, event=None, fileList=()): # have to reimport because it is only local to __init__ so far from psychopy.app import builder for fileName in fileList: if os.path.isfile(fileName): self.newBuilderFrame(fileName=fileName) # create an empty Builder view if needed if len(self.getAllFrames(frameType="builder")) == 0: self.newBuilderFrame() # loop through all frames, from the back bringing each forward thisFrame = None for thisFrame in self.getAllFrames(frameType='builder'): thisFrame.Show(True) thisFrame.Raise() self.builder = thisFrame self.SetTopWindow(thisFrame) return self.builder def showRunner(self, event=None, fileList=[]): """ Show the Runner window, if not shown already. Parameters ---------- event : wx.Event, optional wx event, if called by a UI element, by default None fileList : list[str or pathlib.Path], optional List of files to open Runner with, by default [] Returns ------- psychopy.app.runner.RunnerFrame Current Runner frame """ if not self.runner: self.runner = self.newRunnerFrame() if not self.testMode: self.runner.Show() self.runner.Raise() self.SetTopWindow(self.runner) # Runner captures standard streams until program closed # if self.runner and not self.testMode: # sys.stderr = sys.stdout = self.stdStreamDispatcher return self.runner def newRunnerFrame(self, event=None): # have to reimport because it is only local to __init__ so far from .runner.runner import RunnerFrame title = "PsychoPy Runner (v{})".format(self.version) wx.BeginBusyCursor() self.runner = RunnerFrame(parent=None, id=-1, title=title, app=self) self.updateWindowMenu() wx.EndBusyCursor() return self.runner def OnDrop(self, x, y, files): """Not clear this method ever gets called!""" logging.info("Got Files") def MacOpenFile(self, fileName): if fileName.endswith('psychopyApp.py'): # in wx4 on mac this is called erroneously by App.__init__ # if called like `python psychopyApp.py` return logging.debug('PsychoPyApp: Received Mac file dropped event') if fileName.endswith('.py'): if self.coder is None: self.showCoder() self.coder.setCurrentDoc(fileName) elif fileName.endswith('.psyexp'): self.newBuilderFrame(fileName=fileName) def MacReopenApp(self): """Called when the doc icon is clicked, and ???""" self.GetTopWindow().Raise() def openIPythonNotebook(self, event=None): """Note that right now this is bad because it ceases all activity in the main wx loop and the app has to be quit. We need it to run from a separate process? The necessary depends (zmq and tornado) were included from v1.78 onwards in the standalone """ import IPython.frontend.html.notebook.notebookapp as nb instance = nb.launch_new_instance() def openUpdater(self, event=None): from psychopy.app import connections dlg = connections.InstallUpdateDialog(parent=None, ID=-1, app=self) def colorPicker(self, event=None): """Open color-picker, sets clip-board to string [r,g,b]. Note: units are psychopy -1..+1 rgb units to three decimal places, preserving 24-bit color. """ if self.coder is None: return document = self.coder.currentDoc dlg = PsychoColorPicker(None, context=document) # doesn't need a parent dlg.ShowModal() dlg.Destroy() if event is not None: event.Skip() def openMonitorCenter(self, event): from psychopy.monitors import MonitorCenter self.monCenter = MonitorCenter.MainFrame( None, 'PsychoPy Monitor Center') self.monCenter.Show(True) def terminateHubProcess(self): """ Send a UDP message to iohub informing it to exit. Use this when force quitting the experiment script process so iohub knows to exit as well. If message is not sent within 1 second, or the iohub server address in incorrect,the issue is logged. """ sock = None try: logging.debug('PsychoPyApp: terminateHubProcess called.') import socket sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.settimeout(1.0) iohubAddress = '127.0.0.1', 9036 import msgpack txData = msgpack.Packer().pack(('STOP_IOHUB_SERVER',)) return sock.sendto(txData, iohubAddress) except socket.error as e: msg = 'PsychoPyApp: terminateHubProcess socket.error: %s' logging.debug(msg % str(e)) except socket.herror as e: msg = 'PsychoPyApp: terminateHubProcess socket.herror: %s' logging.debug(msg % str(e)) except socket.gaierror as e: msg = 'PsychoPyApp: terminateHubProcess socket.gaierror: %s' logging.debug(msg % str(e)) except socket.timeout as e: msg = 'PsychoPyApp: terminateHubProcess socket.timeout: %s' logging.debug(msg % str(e)) except Exception as e: msg = 'PsychoPyApp: terminateHubProcess exception: %s' logging.debug(msg % str(e)) finally: if sock: sock.close() logging.debug('PsychoPyApp: terminateHubProcess completed.') def quit(self, event=None): logging.debug('PsychoPyApp: Quitting...') self.quitting = True # garbage collect the projects before sys.exit projects.pavlovia.knownUsers = None projects.pavlovia.knownProjects = None # see whether any files need saving for frame in self.getAllFrames(): try: # will fail if the frame has been shut somehow elsewhere ok = frame.checkSave() except Exception: ok = False logging.debug("PsychopyApp: exception when saving") if not ok: logging.debug('PsychoPyApp: User cancelled shutdown') return # user cancelled quit # save info about current frames for next run openFrames = [] for frame in self.getAllFrames(): if type(frame).__name__ == "BuilderFrame" and "builder" not in openFrames: openFrames.append("builder") if type(frame).__name__ == "CoderFrame" and "coder" not in openFrames: openFrames.append("coder") if type(frame).__name__ == "RunnerFrame" and "runner" not in openFrames: openFrames.append("runner") self.prefs.appData['lastFrame'] = "-".join(openFrames) # save current version for next run self.prefs.appData['lastVersion'] = self.version # update app data while closing each frame # start with an empty list to be appended by each frame self.prefs.appData['builder']['prevFiles'] = [] self.prefs.appData['coder']['prevFiles'] = [] # write plugins config if changed during the session # saveStartUpPluginsConfig() for frame in self.getAllFrames(): try: frame.closeFrame(event=event, checkSave=False) except Exception: pass # we don't care if this fails - we're quitting anyway # must do this before destroying the frame? self.prefs.saveAppData() # self.Destroy() # Reset streams back to default sys.stdout = sys.__stdout__ sys.stderr = sys.__stderr__ if not self.testMode: sys.exit() def showPrefs(self, event): from psychopy.app.preferencesDlg import PreferencesDlg logging.debug('PsychoPyApp: Showing prefs dlg') prefsDlg = PreferencesDlg(app=self) prefsDlg.ShowModal() prefsDlg.Destroy() def showAbout(self, event): logging.debug('PsychoPyApp: Showing about dlg') with io.open(os.path.join(self.prefs.paths['psychopy'], 'LICENSE.txt'), 'r', encoding='utf-8-sig') as f: license = f.read() msg = _translate( "For stimulus generation and experimental control in Python.\n" "PsychoPy depends on your feedback. If something doesn't work\n" "then let us know at psychopy-users@googlegroups.com") if Version(wx.__version__) >= Version('4.0a1'): info = wx.adv.AboutDialogInfo() showAbout = wx.adv.AboutBox else: info = wx.AboutDialogInfo() showAbout = wx.AboutBox if wx.version() >= '3.': icon = os.path.join(self.prefs.paths['resources'], 'psychopy.png') info.SetIcon(wx.Icon(icon, wx.BITMAP_TYPE_PNG, 128, 128)) info.SetName('PsychoPy') info.SetVersion('v' + psychopy.__version__) info.SetDescription(msg) info.SetCopyright('(C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd.') info.SetWebSite('https://www.psychopy.org') info.SetLicence(license) # developers devNames = [ 'Jonathan Peirce', 'Jeremy Gray', 'Michael MacAskill', 'Sol Simpson', u'Jonas Lindel\xF8v', 'Yaroslav Halchenko', 'Erik Kastman', 'Hiroyuki Sogo', 'David Bridges', 'Matthew Cutone', 'Philipp Wiesemann', u'Richard Höchenberger', 'Andrew Schofield', 'Todd Parsons', 'Dan Fitch', 'Suddha Sourav', 'Philipp Wiesemann', 'Mark Hymers', 'Benjamin T. Vincent', 'Yaroslav Halchenko', 'Jay Borseth', 'chrisgatwin [@github.com]', 'toddrjen [@github.com]' ] docNames = [ 'Jonathan Peirce', 'Jeremy Gray', 'Rebecca Hirst', 'Rebecca Sharman', 'Matthew Cutone' ] devNames.sort() intNames = [ 'Hiroyuki Sogo (Japanese)' 'Shun Wang (Chinese)' ] intNames.sort() for name in devNames: info.AddDeveloper(name) for name in docNames: info.AddDocWriter(name) for name in intNames: info.AddTranslator(name) if not self.testMode: showAbout(info) def showNews(self, event=None): connections.showNews(self, checkPrev=False) def showSystemInfo(self, event=None): """Show system information.""" from psychopy.app.sysInfoDlg import SystemInfoDialog dlg = SystemInfoDialog(None) dlg.Show() def followLink(self, event=None, url=None): """Follow either an event id (= a key to an url defined in urls.py) or follow a complete url (a string beginning "http://") """ if event is not None: wx.LaunchDefaultBrowser(self.urls[event.GetId()]) elif url is not None: wx.LaunchDefaultBrowser(url) def getAllFrames(self, frameType=None): """Get a list of frames, optionally filtered by a particular kind (which can be "builder", "coder", "project") """ frames = [] for frameRef in self._allFrames: frame = frameRef() if (not frame): self._allFrames.remove(frameRef) # has been deleted continue elif frameType and frame.frameType != frameType: continue frames.append(frame) return frames def trackFrame(self, frame): """Keep track of an open frame (stores a weak reference to the frame which will probably have a regular reference to the app) """ self._allFrames.append(weakref.ref(frame)) def forgetFrame(self, frame): """Keep track of an open frame (stores a weak reference to the frame which will probably have a regular reference to the app) """ for entry in self._allFrames: if entry() == frame: # is a weakref self._allFrames.remove(entry) def onIdle(self, evt): """Run idle tasks, including background checks for new instances. Some of these run once while others are added as tasks to be run repeatedly. """ from . import idle idle.doIdleTasks(app=self) # run once # do the background check for new instances, check each second tNow = time.time() if tNow - self._lastInstanceCheckTime > 1.0: # every second if not self.testMode: self._bgCheckAndLoad() self._lastInstanceCheckTime = time.time() evt.Skip() @property def theme(self): """The theme to be used through the application""" return themes.theme @theme.setter def theme(self, value): """The theme to be used through the application""" # Make sure we just have a name if isinstance(value, themes.Theme): value = value.code # Store new theme prefs.app['theme'] = value prefs.saveUserPrefs() # Reset icon cache icons.iconCache.clear() # Set theme at module level themes.theme.set(value) # Apply to frames for frameRef in self._allFrames: frame = frameRef() if isinstance(frame, handlers.ThemeMixin): frame.theme = themes.theme # On OSX 10.15 Catalina at least calling SetFaceName with 'AppleSystemUIFont' fails. # So this fix checks to see if changing the font name invalidates the font. # if so rollback to the font before attempted change. # Note that wx.Font uses referencing and copy-on-write so we need to force creation of a copy # with the wx.Font() call. Otherwise you just get reference to the font that gets borked by SetFaceName() # -Justin Ales beforesetface = wx.Font(self._codeFont) success = self._codeFont.SetFaceName("JetBrains Mono") if not (success): self._codeFont = beforesetface if __name__ == '__main__': # never run; stopped earlier at cannot do relative import in a non-package sys.exit("Do not launch the app from this script -" "use python psychopyApp.py instead")
48,921
Python
.py
1,096
33.268248
113
0.594955
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,782
dialogs.py
psychopy_psychopy/psychopy/app/dialogs.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """This is for general purpose dialogs/widgets, not particular functionality MessageDialog: a drop-in replacement for wx message dialog (which was buggy on mac) GlobSizer: built on top of GridBagSizer but with ability to add/remove rows. Needed for the ListWidget ListWidget: takes a list of dictionaries (with identical fields) and allows the user to add/remove entries. e.g. expInfo control """ import wx from wx.lib.newevent import NewEvent from psychopy import logging from psychopy.localization import _translate from packaging.version import Version class MessageDialog(wx.Dialog): """For some reason the wx built-in message dialog has issues on macOS (buttons don't always work) so we need to use this instead. """ def __init__(self, parent=None, message='', type='Warning', title=None, timeout=None): # select and localize a title if not title: title = type labels = {'Warning': _translate('Warning'), 'Info': _translate('Info'), 'Query': _translate('Query')} try: label = labels[title] except Exception: label = title wx.Dialog.__init__(self, parent, -1, title=label) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(wx.StaticText(self, -1, message), flag=wx.ALL, border=15) # add buttons if type == 'Warning': # we need Yes,No,Cancel btnSizer = self.CreateStdDialogButtonSizer(flags=wx.YES | wx.NO | wx.CANCEL) elif type == 'Query': # we need Yes,No btnSizer = self.CreateStdDialogButtonSizer(flags=wx.YES | wx.NO) elif type == 'Info': # just an OK button btnSizer = self.CreateStdDialogButtonSizer(flags=wx.OK) else: raise NotImplementedError('Message type %s unknown' % type) for btn in btnSizer.GetChildren(): if hasattr(btn.Window, "Bind"): btn.Window.Bind(wx.EVT_BUTTON, self.onButton) # configure sizers and fit sizer.Add(btnSizer, flag=wx.ALL | wx.EXPAND, border=5) self.Center() self.SetSizerAndFit(sizer) self.timeout = timeout def onButton(self, event): self.EndModal(event.GetId()) def onEscape(self, event): self.EndModal(wx.ID_CANCEL) def onEnter(self, event=None): self.EndModal(wx.ID_OK) def ShowModal(self): if self.timeout: timeout = wx.CallLater(self.timeout, self.onEnter) timeout.Start() return wx.Dialog.ShowModal(self) # Event for GlobSizer----------------------------------------------------- (GBSizerExLayoutEvent, EVT_GBSIZEREX_LAYOUT) = NewEvent() class RichMessageDialog(wx.Dialog): def __init__( self, parent=None, message="", title="", size=(600, 500), style=wx.RESIZE_BORDER ): from psychopy.app.utils import MarkdownCtrl # initialise dialog wx.Dialog.__init__( self, parent, title=title, size=size, style=style ) # 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.EXPAND | wx.ALL) # add markdown ctrl self.ctrl = MarkdownCtrl( self, value=message, style=wx.TE_READONLY ) self.sizer.Add(self.ctrl, border=6, proportion=1, flag=wx.EXPAND | wx.ALL) # add OK button self.btns = self.CreateStdDialogButtonSizer(flags=wx.OK) self.border.Add(self.btns, border=12, flag=wx.EXPAND | wx.ALL) class GlobSizer(wx.GridBagSizer): """This is a GridBagSizer that supports adding/removing/inserting rows and columns. It was found online, with not clear use license (public domain?). Appears to have been written by e.a.tacao <at> estadao.com.br """ def __init__(self, *args, **kwargs): self.win = kwargs.pop("win", None) # This is here because we need to be able to find out whether a # row/col is growable. We also override the AddGrowableRow/Col and # RemoveGrowableRow/Col methods, as well as create new methods to # handle growable row/cols. self.growableRows = {} self.growableCols = {} wx.GridBagSizer.__init__(self, *args, **kwargs) def _resetSpan(self): # Unspans all spanned items; returns a reference to objects. objs = {} for item in self.GetChildren(): span = item.GetSpan().Get() if span != (1, 1): objs[item.GetWindow()] = span item.SetSpan((1, 1)) return objs def _setSpan(self, objs): # Respans all items containing the given objects. for obj, span in list(objs.items()): if obj: self.FindItem(obj).SetSpan(span) def GetClassName(self): return "GlobSizer" def GetAttributes(self): gap = self.GetGap() ecs = self.GetEmptyCellSize().Get() grows = self.GetGrowableRows() gcols = self.GetGrowableCols() return (gap, ecs, grows, gcols) def SetAttributes(self, attrs): gap, ecs, grows, gcols = attrs self.SetGap(gap) self.SetEmptyCellSize(ecs) [self.AddGrowableRow(row) for row in grows] [self.AddGrowableCol(col) for col in gcols] def Layout(self): wx.GridBagSizer.Layout(self) if self.win: wx.PostEvent(self.win, GBSizerExLayoutEvent(val=True)) def SetGap(self, gap=(0, 0)): v, h = gap self.SetVGap(v) self.SetHGap(h) def GetGap(self): return self.GetVGap(), self.GetHGap() def AddGrowableRow(self, *args, **kwargs): idx = kwargs.get("idx", args[0]) if not self.IsRowGrowable(idx): proportion = kwargs.get("proportion", (args + (0,))[1]) self.growableRows[idx] = proportion wx.GridBagSizer.AddGrowableRow(self, idx, proportion) def AddGrowableCol(self, *args, **kwargs): idx = kwargs.get("idx", args[0]) if not self.IsColGrowable(idx): proportion = kwargs.get("proportion", (args + (0,))[1]) self.growableCols[idx] = proportion wx.GridBagSizer.AddGrowableCol(self, idx, proportion) def RemoveGrowableRow(self, idx): if self.IsRowGrowable(idx): del self.growableRows[idx] wx.GridBagSizer.RemoveGrowableRow(self, idx) def RemoveGrowableCol(self, idx): if self.IsColGrowable(idx): del self.growableCols[idx] wx.GridBagSizer.RemoveGrowableCol(self, idx) def IsRowGrowable(self, idx): return idx in self.growableRows def IsColGrowable(self, idx): return idx in self.growableCols def GetGrowableRows(self): grows = list(self.growableRows.keys()) grows.sort() return grows def GetGrowableCols(self): gcols = list(self.growableCols.keys()) gcols.sort() return gcols def FindUnspannedItemAtPosition(self, *args, **kwargs): # FindItemAtPosition(r, c) will return a valid spanned item # even if (r, c) is not its top-left position. This method will only # return a valid item (spanned or not*) if the position passed is the # top-left. (*As for unspanned items, obviously it'll always return a # valid item). item = self.FindItemAtPosition(*args, **kwargs) if item: if item.GetSpan().Get() > (1, 1): if item.GetPos() == kwargs.get("pos", args[0]): r = item else: r = None else: r = item else: r = None return r def GetItemPositions(self, *args, **kwargs): # Returns all positions occupied by a spanned item, as GetItemPosition # only returns its top-left position. row, col = self.GetItemPosition(*args, **kwargs).Get() rspan, cspan = self.GetItemSpan(*args, **kwargs).Get() return [(row + r, col + c) for r, c in [(r, c) for r in range(0, rspan) for c in range(0, cspan)]] def InsertRow(self, row): # As for the vertically spanned objects in the given row, # we'll need to respan them later with an increased row span # (increased by 1 row). # 1. Get a reference of the vertically spanned objects on this row and # their span, incrementing their row span by 1. _update_span = {} for c in range(0, self.GetCols()): item = self.FindItemAtPosition((row, c)) if item: rs, cs = item.GetSpan().Get() if rs > 1 and item.GetPos().GetRow() != row: _update_span[item.GetWindow()] = (rs + 1, cs) # 2. Unspan all objects. objs = self._resetSpan() # 3. Shift rows down. self.ShiftRowsDown(row) # 4. Respan all objects. objs.update(_update_span) self._setSpan(objs) # 5. Update references to growable rows. grows = list(self.growableRows.keys()) for r in grows: if r >= row: self.RemoveGrowableRow(r) self.AddGrowableRow(r + 1) def InsertCol(self, col): # As for the horizontally spanned objects in the given col, # we'll need to respan them later with an increased col span # (increased by 1 col). # 1. Get a reference of the horizontally spanned objects on this col # and their span, incrementing their col span by 1. _update_span = {} for r in range(0, self.GetRows()): item = self.FindItemAtPosition((r, col)) if item: rs, cs = item.GetSpan().Get() if cs > 1 and item.GetPos().GetCol() != col: _update_span[item.GetWindow()] = (rs, cs + 1) # 2. Unspan all objects. objs = self._resetSpan() # 3. Shift cols right. self.ShiftColsRight(col) # 4. Respan all objects. objs.update(_update_span) self._setSpan(objs) # 5. Update references to growable cols. gcols = list(self.growableCols.keys()) for c in gcols: if c >= col: self.RemoveGrowableCol(c) self.AddGrowableCol(c + 1) def DeleteRow(self, row): """Deletes an entire row, destroying its objects (if any). """ # As for the vertically spanned objects in the given row, # we'll need to move them somewhere safe (so that their objects # won't be destroyed as we destroy the row itself) and respan # them later with a reduced row span (decreased by 1 row). # 1. Get a reference of the vertically spanned objects on this row and # their span, decrementing their row span by 1. _update_span = {} for c in range(0, self.GetCols()): item = self.FindItemAtPosition((row, c)) if item: rs, cs = item.GetSpan().Get() if rs > 1: _update_span[item.GetWindow()] = (rs - 1, cs) # 2. Unspan all objects. objs = self._resetSpan() # 3. Move the _update_span objects to an adjacent row somewhere safe. for obj in _update_span: item = self.FindItem(obj) org_r, org_c = item.GetPos().Get() if org_r == row: item.SetPos((org_r + 1, org_c)) # 4. Destroy all objects on this row. for c in range(0, self.GetCols()): item = self.FindItemAtPosition((row, c)) if item: obj = item.GetWindow() self.Detach(obj) obj.Destroy() # 5. Shift rows up. self.ShiftRowsUp(row + 1) # 6. Respan all objects. objs.update(_update_span) self._setSpan(objs) # 7. Update references to growable rows. grows = list(self.growableRows.keys()) for r in grows: if r >= row: self.RemoveGrowableRow(r) if r > row: self.AddGrowableRow(r - 1) def DeleteCol(self, col): """Deletes an entire col, destroying its objects (if any).""" # As for the horizontally spanned objects in the given col, # we'll need to move them somewhere safe (so that their objects # won't be destroyed as we destroy the row itself) and respan # them later with a reduced col span (decreased by 1 col). # 1. Get a reference of the horizontally spanned objects on this col # and their span, decrementing their col span by 1. _update_span = {} for r in range(0, self.GetRows()): item = self.FindItemAtPosition((r, col)) if item: rs, cs = item.GetSpan().Get() if cs > 1: _update_span[item.GetWindow()] = (rs, cs - 1) # 2. Unspan all objects. objs = self._resetSpan() # 3. Move the _update_span objects to an adjacent col somewhere safe. for obj in _update_span: item = self.FindItem(obj) org_r, org_c = item.GetPos().Get() if org_c == col: item.SetPos((org_r, org_c + 1)) # 4. Destroy all objects on this col. for r in range(0, self.GetRows()): item = self.FindItemAtPosition((r, col)) if item: obj = item.GetWindow() self.Detach(obj) obj.Destroy() # 5. Shift cols left. self.ShiftColsLeft(col + 1) # 6. Respan all objects. objs.update(_update_span) self._setSpan(objs) # 7. Update references to growable cols. gcols = list(self.growableCols.keys()) for c in gcols: if c >= col: self.RemoveGrowableCol(c) if c > col: self.AddGrowableCol(c - 1) def ShiftRowsUp(self, startRow, endRow=None, startCol=None, endCol=None): if endCol is None: endCol = self.GetCols() else: endCol += 1 if endRow is None: endRow = self.GetRows() else: endRow += 1 if startCol is None: startCol = 0 for c in range(startCol, endCol): for r in range(startRow, endRow): item = self.FindItemAtPosition((r, c)) if item: w = item.GetWindow() if w: self.SetItemPosition(w, (r - 1, c)) w.Refresh() def ShiftRowsDown(self, startRow, endRow=None, startCol=None, endCol=None): if endCol is None: endCol = self.GetCols() else: endCol += 1 if endRow is None: endRow = self.GetRows() else: endRow += 1 if startCol is None: startCol = 0 for c in range(startCol, endCol): for r in range(endRow, startRow, -1): item = self.FindItemAtPosition((r, c)) if item: w = item.GetWindow() if w: self.SetItemPosition(w, (r + 1, c)) w.Refresh() def ShiftColsLeft(self, startCol, endCol=None, startRow=None, endRow=None): if endCol is None: endCol = self.GetCols() else: endCol += 1 if endRow is None: endRow = self.GetRows() else: endRow += 1 if startRow is None: startRow = 0 for r in range(startRow, endRow): for c in range(startCol, endCol): item = self.FindItemAtPosition((r, c)) if item: w = item.GetWindow() if w: self.SetItemPosition(w, (r, c - 1)) w.Refresh() def ShiftColsRight(self, startCol, endCol=None, startRow=None, endRow=None): if endCol is None: endCol = self.GetCols() else: endCol += 1 if endRow is None: endRow = self.GetRows() else: endRow += 1 if startRow is None: startRow = 0 for r in range(startRow, endRow): for c in range(endCol, startCol - 1, -1): item = self.FindItemAtPosition((r, c)) if item: w = item.GetWindow() if w: self.SetItemPosition(w, (r, c + 1)) w.Refresh() def DeleteEmptyRows(self): rows2delete = [] for r in range(0, self.GetRows()): f = True for c in range(0, self.GetCols()): if self.FindItemAtPosition((r, c)) is not None: f = False if f: rows2delete.append(r) for i in range(0, len(rows2delete)): self.ShiftRowsUp(rows2delete[i] + 1) rows2delete = [x - 1 for x in rows2delete] def DeleteEmptyCols(self): cols2delete = [] for c in range(0, self.GetCols()): f = True for r in range(0, self.GetRows()): if self.FindItemAtPosition((r, c)) is not None: f = False if f: cols2delete.append(c) for i in range(0, len(cols2delete)): self.ShiftColsLeft(cols2delete[i] + 1) cols2delete = [x - 1 for x in cols2delete] def Insert(self, *args, **kwargs): # Uses the API for the Add method, plus a kwarg named shiftDirection, # which controls whether rows should be shifted down (shiftDirection = # wx.VERTICAL) or left (shiftDirection = wx.HORIZONTAL). # # That kwarg is just a hint and won't force shifting; shifting # will only take place if the position passed is already occupied by # another control. # pos = kwargs.get("pos", args[1]) shiftDirection = kwargs.pop("shiftDirection", wx.VERTICAL) if not self.FindItemAtPosition(pos): self.Add(*args, **kwargs) else: objs = self._resetSpan() r, c = pos if shiftDirection == wx.HORIZONTAL: self.ShiftColsRight(c, startRow=r, endRow=r) else: self.ShiftRowsDown(r, startCol=c, endCol=c) self.Add(*args, **kwargs) self._setSpan(objs) self.Layout() class ListWidget(GlobSizer): """A widget for handling a list of dicts of identical structure. Has one row per entry and a +/- buttons at end to add/insert/remove from the list """ def __init__(self, parent, value=None, order=None): """value should be a list of dictionaries with identical field names order should be used to specify the order in which the fields appear (left to right) """ GlobSizer.__init__(self, hgap=2, vgap=2) self.parent = parent if value is None: value = [{'Field': "", 'Default': ""}] self.value = value if type(value) != list: msg = 'The initial value for a ListWidget must be a list of dicts' raise AttributeError(msg) # sort fieldNames using order information where possible allNames = list(self.value[0].keys()) self.fieldNames = [] if order is None: order = [] for name in order: if name not in allNames: msg = ('psychopy.dialogs.ListWidget was given a field name ' '`%s` in order that was not in the dictionary') logging.error(msg % name) continue allNames.remove(name) self.fieldNames.append(name) # extend list by the remaining (no explicit order) self.fieldNames.extend(allNames) # set up controls self.createGrid() self.AddGrowableCol(0) self.AddGrowableCol(1) def createGrid(self): row = 0 if len(self.fieldNames) > 0: for col, field in enumerate(self.fieldNames): self.Add(wx.StaticText(self.parent, -1, label=_translate(field)), (row, col), flag=wx.ALL) for entry in self.value: row += 1 self.addEntryCtrls(row, entry) self.Layout() def addEntryCtrls(self, row, entry): for col, field in enumerate(self.fieldNames): c = wx.TextCtrl(self.parent, -1, str(entry[field])) self.Add(c, (row, col), flag=wx.ALL | wx.EXPAND) plusBtn = wx.Button(self.parent, -1, '+', style=wx.BU_EXACTFIT) self.Add(plusBtn, (row, col + 1), flag=wx.ALL) plusBtn.Bind(wx.EVT_BUTTON, self.onAddElement) minusBtn = wx.Button(self.parent, -1, '-', style=wx.BU_EXACTFIT) self.Add(minusBtn, (row, col + 2), flag=wx.ALL) minusBtn.Bind(wx.EVT_BUTTON, self.onRemoveElement) def onAddElement(self, event): """The plus button has been pressed """ btn = self.FindItem(event.GetEventObject()) row, col = btn.GetPos() self.InsertRow(row) newEntry = {} for fieldName in self.fieldNames: newEntry[fieldName] = "" self.addEntryCtrls(row + 1, newEntry) self.Layout() self.parent.Fit() def onRemoveElement(self, event=None): """Called when the minus button is pressed. """ btn = self.FindItem(event.GetEventObject()) row, col = btn.GetPos() self.DeleteRow(row) self.Layout() self.parent.Fit() def getListOfDicts(self): """Retrieve the current list of dicts from the grid """ currValue = [] # skipping the first row (headers) for rowN in range(self.GetRows())[1:]: thisEntry = {} for colN, fieldName in enumerate(self.fieldNames): ctrl = self.FindItemAtPosition((rowN, colN)).GetWindow() thisEntry[fieldName] = ctrl.GetValue() currValue.append(thisEntry) return currValue def getValue(self): """ Return value as a dict so it's label-agnostic. Returns ------- dict key:value pairs represented by the two columns of this ctrl """ currValue = {} # skipping the first row (headers) for rowN in range(self.GetRows())[1:]: keyCtrl = self.FindItemAtPosition((rowN, 0)).GetWindow() valCtrl = self.FindItemAtPosition((rowN, 1)).GetWindow() currValue[keyCtrl.GetValue()] = valCtrl.GetValue() return currValue def GetValue(self): """Provided for compatibility with other wx controls. Returns the current value of the list of dictionaries represented in the grid """ return self.getListOfDicts() def SetValidator(self, validator): # Set Validator on every applicable child element for child in self.Children: if hasattr(child.Window, "SetValidator"): child.Window.SetValidator(validator) def Validate(self): # Call Validate on every applicable child element for child in self.Children: if hasattr(child.Window, "Validate"): child.Window.Validate() if __name__ == '__main__': if Version(wx.__version__) < Version('2.9'): app = wx.PySimpleApp() else: app = wx.App(False) dlg = wx.Dialog(None) init = [{'Field': 'Participant', 'Default': ''}, {'Field': 'Session', 'Default': '001'}] listCtrl = ListWidget(dlg, value=init, order=['Field', 'Default']) dlg.SetSizerAndFit(listCtrl) dlg.ShowModal()
24,378
Python
.py
601
29.795341
88
0.566248
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,783
errorDlg.py
psychopy_psychopy/psychopy/app/errorDlg.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). """Error dialog for showing unhandled exceptions that occur within the PsychoPy app.""" from requests.exceptions import ConnectionError, ReadTimeout import wx import traceback import psychopy.preferences import sys from psychopy.localization import _translate _error_dlg = None # keep error dialogs from stacking class ErrorMsgDialog(wx.Dialog): """Class for creating an error report dialog. Should never be created directly. """ def __init__(self, parent, traceback=''): wx.Dialog.__init__(self, parent, id=wx.ID_ANY, title=_translate(u"PsychoPy3 Error"), pos=wx.DefaultPosition, size=wx.Size(750, -1), style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER) self.details = traceback # message to show at the top of the error box, needs translation msg = _translate(u"PsychoPy encountered an unhandled internal error! " \ u"Please send the report under \"Details\" to the " \ u"developers with a description of what you were doing " \ u"with the software when the error occurred.") self.SetSizeHints(wx.DefaultSize, wx.DefaultSize) szErrorMsg = wx.BoxSizer(wx.VERTICAL) szHeader = wx.FlexGridSizer(0, 3, 0, 0) szHeader.AddGrowableCol(1) szHeader.SetFlexibleDirection(wx.BOTH) szHeader.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED) self.imgErrorIcon = wx.StaticBitmap( self, wx.ID_ANY, wx.ArtProvider.GetBitmap( wx.ART_ERROR, wx.ART_MESSAGE_BOX), wx.DefaultPosition, wx.DefaultSize, 0) szHeader.Add(self.imgErrorIcon, 0, wx.ALL, 5) self.lblErrorMsg = wx.StaticText( self, wx.ID_ANY, msg, wx.DefaultPosition, wx.DefaultSize, 0) self.lblErrorMsg.Wrap(560) szHeader.Add(self.lblErrorMsg, 0, wx.ALL, 5) szHeaderButtons = wx.BoxSizer(wx.VERTICAL) self.cmdOK = wx.Button( self, wx.ID_OK, _translate(u"&OK"), wx.DefaultPosition, wx.DefaultSize, 0) szHeaderButtons.Add(self.cmdOK, 0, wx.LEFT | wx.EXPAND, 5) self.cmdExit = wx.Button( self, wx.ID_EXIT, _translate(u"E&xit PsychoPy"), wx.DefaultPosition, wx.DefaultSize, 0) szHeaderButtons.Add(self.cmdExit, 0, wx.TOP | wx.LEFT | wx.EXPAND, 5) szHeader.Add(szHeaderButtons, 0, wx.ALL | wx.EXPAND, 5) szErrorMsg.Add(szHeader, 0, wx.TOP | wx.LEFT | wx.RIGHT | wx.EXPAND, 5) self.pnlDetails = wx.CollapsiblePane( self, wx.ID_ANY, _translate(u"&Details"), wx.DefaultPosition, wx.DefaultSize, wx.CP_DEFAULT_STYLE) self.pnlDetails.Collapse(True) szDetailsPane = wx.BoxSizer(wx.VERTICAL) self.txtErrorOutput = wx.TextCtrl( self.pnlDetails.GetPane(), wx.ID_ANY, self.details, wx.DefaultPosition, wx.Size(640, 150), wx.TE_AUTO_URL | wx.TE_BESTWRAP | wx.TE_MULTILINE | wx.TE_READONLY | wx.TE_WORDWRAP) szDetailsPane.Add(self.txtErrorOutput, 1, wx.ALL | wx.EXPAND, 5) szTextButtons = wx.BoxSizer(wx.HORIZONTAL) self.cmdCopyError = wx.Button( self.pnlDetails.GetPane(), wx.ID_ANY, _translate(u"&Copy"), wx.DefaultPosition, wx.DefaultSize, 0) szTextButtons.Add(self.cmdCopyError, 0, wx.RIGHT, 5) self.cmdSaveError = wx.Button( self.pnlDetails.GetPane(), wx.ID_ANY, _translate(u"&Save"), wx.DefaultPosition, wx.DefaultSize, 0) szTextButtons.Add(self.cmdSaveError, 0) szDetailsPane.Add(szTextButtons, 0, wx.ALL | wx.ALIGN_RIGHT, 5) self.pnlDetails.Expand() self.pnlDetails.GetPane().SetSizer(szDetailsPane) self.pnlDetails.GetPane().Layout() szDetailsPane.Fit(self.pnlDetails.GetPane()) szErrorMsg.Add(self.pnlDetails, 1, wx.ALL | wx.BOTTOM | wx.EXPAND, 5) self.SetSizer(szErrorMsg) self.Layout() self.Fit() self.Centre(wx.BOTH) # Connect Events self.cmdOK.Bind(wx.EVT_BUTTON, self.onOkay) self.cmdExit.Bind(wx.EVT_BUTTON, self.onExit) self.cmdCopyError.Bind(wx.EVT_BUTTON, self.onCopyDetails) self.cmdSaveError.Bind(wx.EVT_BUTTON, self.onSaveDetails) # ding! wx.Bell() def __del__(self): pass def onOkay(self, event): """Called when OK is clicked.""" event.Skip() def onExit(self, event): """Called when the user requests to close PsychoPy. This can be called if the error if unrecoverable or if the errors are being constantly generated. Will try to close things safely, allowing the user to save files while suppressing further errors. """ dlg = wx.MessageDialog( self, _translate("Are you sure you want to exit PsychoPy? Unsaved work may be lost " "(but we'll try to save opened files)."), _translate("Exit PsychoPy?"), wx.YES_NO | wx.NO_DEFAULT | wx.ICON_WARNING | wx.CENTRE) if dlg.ShowModal() == wx.ID_YES: wx.GetApp().quit() # wx.Exit() # nuclear option else: dlg.Destroy() event.Skip() def onCopyDetails(self, event): """Copy the contents of the details text box to the clipboard. This is to allow the user to paste the traceback into an email, forum post, issue ticket, etc. to report the error to the developers. If there is a selection range, only that text will be copied. """ # check if we have a selection start, end = self.txtErrorOutput.GetSelection() if start != end: txt = self.txtErrorOutput.GetStringSelection() else: txt = self.txtErrorOutput.GetValue() if wx.TheClipboard.Open(): wx.TheClipboard.SetData(wx.TextDataObject(txt)) wx.TheClipboard.Close() event.Skip() def onSaveDetails(self, event): """Dump the traceback data to a file. This can be used to save the error data so it can be reported to the developers at a later time. Brings up a file save dialog to select where to write the file. """ with wx.FileDialog( self, _translate("Save error traceback"), wildcard="Text files (*.txt)|*.txt", defaultFile='psychopy_traceback.txt', style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) as fileDialog: if fileDialog.ShowModal() == wx.ID_CANCEL: return # the user changed their mind # dump traceback to file pathname = fileDialog.GetPath() try: with open(pathname, 'w') as file: file.write(self.txtErrorOutput.GetValue()) except IOError: # error in an error ... ;) errdlg = wx.MessageDialog( self, _translate("Cannot save to file '%s'.") % pathname, _translate("File save error"), wx.OK_DEFAULT | wx.ICON_ERROR | wx.CENTRE) errdlg.ShowModal() errdlg.Destroy() event.Skip() def isErrorDialogVisible(): """Check if the error dialog is open. This can be used to prevent background routines from running while the user deals with an error. Returns ------- bool Error dialog is currently active. """ return _error_dlg is not None def exceptionCallback(exc_type: object, exc_value: object, exc_traceback: object) -> object: """Hook when an unhandled exception is raised within the current application thread. Gets the exception message and creates an error dialog box. When this function is patched into `sys.excepthook`, all unhandled exceptions will result in a dialog being displayed. """ # Catch connection errors if exc_type in (ConnectionError, ReadTimeout): dlg = wx.MessageDialog(parent=None, caption=_translate("Connection Error"), message=_translate( "Could not connect to Pavlovia server. \n" "\n" "Please check that you are connected to the internet. If you are connected, then the Pavlovia servers may be down. You can check their status here: \n" "\n" "https://pavlovia.org/status" ), style=wx.ICON_ERROR) dlg.ShowModal() return if psychopy.preferences.prefs.app['errorDialog'] is False: # have the error go out to stdout if dialogs are disabled traceback.print_exception( exc_type, exc_value, exc_traceback, file=sys.stdout) return global _error_dlg if not isErrorDialogVisible(): # format the traceback text tbText = ''.join(traceback.format_exception( exc_type, exc_value, exc_traceback)) _error_dlg = ErrorMsgDialog(None, tbText) # show the dialog _error_dlg.ShowModal() _error_dlg.Destroy() _error_dlg = None
9,376
Python
.py
199
37.150754
163
0.629241
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,784
console.py
psychopy_psychopy/psychopy/app/console.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). """Classes and functions for broadcasting standard streams from external consoles/terminals within the PsychoPy GUI suite. """ # This module can be expanded to centralize management for all console related # actions in the future. # import os.path import sys import io class StdStreamDispatcher: """Class for broadcasting standard output to text boxes. This class serves to redirect and log standard streams within the PsychoPy GUI suite, usually from sub-processes (e.g., a running script) to display somewhere. An instance of this class is created on-startup and referenced by the main application instance. Only one instance of this class can be created per-session (singleton). Parameters ---------- app : :class:`~psychopy.app._psychopyApp.PsychoPyApp` Reference to the application instance. """ # Developer note: In the future we should be able to attach other listeners # dynamically. Right now they are hard-coded, being the runner output box # and coder output panel. This will allow changes being made on those # objects not requiring any changes here. # _instance = None _initialized = False _app = None # reference to parent app _logFile = None def __init__(self, app, logFile=None): # only setup if previously not instanced if not self._initialized: self._app = app self._logFile = logFile self._initialized = True def __new__(cls, *args, **kwargs): if cls._instance is None: cls._instance = super(StdStreamDispatcher, cls).__new__(cls) return cls._instance @classmethod def getInstance(cls): """Get the (singleton) instance of the `StdStreamDispatcher` class. Getting a reference to the `StdOutManager` class outside of the scope of the user's scripts should be done through this class method. Returns ------- StdStreamDispatcher or None Instance of the `Mouse` class created by the user. """ return cls._instance @classmethod def initialized(cls): """Check if this class has been initialized. Returns ------- bool `True` if the `StdStreamDispatcher` class has been already instanced. """ return cls._initialized @property def logFile(self): """Log file for standard streams (`str` or `None`). """ return self._logFile @logFile.setter def logFile(self, val): self._logFile = val def redirect(self): """Redirect `stdout` and `stderr` to listeners. """ sys.stdout = sys.stderr = self def write(self, text): """Send text standard output to all listeners (legacy). This method is used for compatibility for older code. This makes it so an instance of this object looks like a ... Parameters ---------- text : str Text to broadcast to all standard output windows. """ self.broadcast(text=text) def broadcast(self, text): """Send text standard output to all listeners. Parameters ---------- text : str Text to broadcast to all standard output windows. """ # do nothing is the app isn't fully realized if not self._app.appLoaded: return coder = self._app.coder if coder is not None: if hasattr(coder, 'consoleOutput'): coder.consoleOutput.write(text) runner = self._app.runner if runner is not None: runner.stdOut.write(text) # write to log file if self._logFile is not None: # with open(self._logFile, 'a') as lf: with io.open(self._logFile, 'a', encoding="utf-8") as lf: lf.write(text) lf.flush() def flush(self): pass def clear(self): """Clear all output windows.""" # do nothing is the app isn't fully realized if not self._app.appLoaded: return coder = self._app.coder if coder is not None: if hasattr(coder, 'consoleOutput'): coder.consoleOutput.Clear() runner = self._app.runner if runner is not None: runner.stdOut.Clear() if __name__ == "__main__": pass
4,684
Python
.py
127
28.913386
80
0.625442
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,785
urls.py
psychopy_psychopy/psychopy/app/urls.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """A central location to store information about urls """ urls = dict() # links based on string names urls['builder'] = "https://www.psychopy.org/builder" urls['builder.loops'] = "https://www.psychopy.org/builder/flow.html#loops" # NB. builder components get their urls defined by the component code # (so a custom component can have a url) urls['downloads'] = "https://github.com/psychopy/psychopy/releases" urls['changelog'] = "https://www.psychopy.org/changelog.html" general = "https://www.psychopy.org/general/" urls['prefs'] = general + "prefs.html" urls['prefs.general'] = general + "prefs.html#general-settings" urls['prefs.app'] = general + "prefs.html#application-settings" urls['prefs.coder'] = general + "prefs.html#coder-settings" urls['prefs.builder'] = general + "prefs.html#builder-settings" urls['prefs.connections'] = general + "prefs.html#connection-settings" # links keyed by wxIDs (e.g. menu item IDs) urls['psychopyHome'] = "https://www.psychopy.org/" urls['psychopyReference'] = "https://www.psychopy.org/api" urls['coderTutorial'] = "https://www.psychopy.org/coder/tutorial1.html" urls['builderHelp'] = urls['builder'] urls['builderDemos'] = "http://code.google.com/p/psychopy/downloads/list?can=2&q=demos" urls['projsAbout'] = "https://www.psychopy.org/general/projects.html"
1,352
Python
.py
26
50.807692
87
0.736563
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,786
frametracker.py
psychopy_psychopy/psychopy/app/frametracker.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). openFrames = []
246
Python
.py
6
39.666667
79
0.731092
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,787
utils.py
psychopy_psychopy/psychopy/app/utils.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). """utility classes for the Builder """ import glob import io import os import re import webbrowser from pathlib import Path import PIL import numpy import requests from wx.html import HtmlWindow try: import markdown_it as md except ImportError: md = None from wx.lib.agw.aui.aui_constants import * import wx.lib.statbmp from wx.lib.agw.aui.aui_utilities import IndentPressedBitmap, ChopText, TakeScreenShot import sys import wx import wx.stc import wx.lib.agw.aui as aui from wx.lib import platebtn from wx.lib.wordwrap import wordwrap from wx.lib.stattext import GenStaticText import wx.lib.mixins.listctrl as listmixin import psychopy from psychopy import logging from . import pavlovia_ui from .themes import colors, handlers, icons from psychopy.localization import _translate from psychopy.tools import stringtools as st from psychopy.tools.apptools import SortTerm from PIL import Image as pil class HoverMixin: """ Mixin providing methods to handle hover on/off events for a wx.Window based class. """ IsHovered = False def SetupHover(self): """ Helper method to setup hovering for this object """ # Bind both hover on and hover off events to the OnHover method self.Bind(wx.EVT_ENTER_WINDOW, self.OnHover) self.Bind(wx.EVT_LEAVE_WINDOW, self.OnHover) # Do first hover to apply styles self.OnHover(evt=None) def OnHover(self, evt=None): """ Method to handle hover events for buttons. To use, bind both `wx.EVT_ENTER_WINDOW` and `wx.EVT_LEAVE_WINDOW` events to this method. """ if evt is None: # If calling without event, style according to last IsHovered measurement if self.IsHovered: self.SetForegroundColour(self.ForegroundColourHover) self.SetBackgroundColour(self.BackgroundColourHover) else: self.SetForegroundColour(self.ForegroundColourNoHover) self.SetBackgroundColour(self.BackgroundColourNoHover) elif evt.EventType == wx.EVT_ENTER_WINDOW.typeId: # If hovered over currently, use hover colours self.SetForegroundColour(self.ForegroundColourHover) self.SetBackgroundColour(self.BackgroundColourHover) # and mark as hovered self.IsHovered = True else: # Otherwise, use regular colours self.SetForegroundColour(self.ForegroundColourNoHover) self.SetBackgroundColour(self.BackgroundColourNoHover) # and mark as unhovered self.IsHovered = False # Refresh self.Refresh() @property def ForegroundColourNoHover(self): if hasattr(self, "_ForegroundColourNoHover"): return self._ForegroundColourNoHover return colors.app['text'] @ForegroundColourNoHover.setter def ForegroundColourNoHover(self, value): self._ForegroundColourNoHover = value @property def BackgroundColourNoHover(self): if hasattr(self, "_BackgroundColourNoHover"): return self._BackgroundColourNoHover return colors.app['frame_bg'] @BackgroundColourNoHover.setter def BackgroundColourNoHover(self, value): self._BackgroundColourNoHover = value @property def ForegroundColourHover(self): if hasattr(self, "_ForegroundColourHover"): return self._ForegroundColourHover return colors.app['txtbutton_fg_hover'] @ForegroundColourHover.setter def ForegroundColourHover(self, value): self._ForegroundColourHover = value @property def BackgroundColourHover(self): if hasattr(self, "_BackgroundColourHover"): return self._BackgroundColourHover return colors.app['txtbutton_bg_hover'] @BackgroundColourHover.setter def BackgroundColourHover(self, value): self._BackgroundColourHover = value class ButtonSizerMixin: """ Overrides standard wx button layout to put Help on the left as it's historically been in PsychoPy. """ def CreatePsychoPyDialogButtonSizer(self, flags=wx.OK | wx.CANCEL | wx.HELP): # Do original wx method sizer = wx.Dialog.CreateStdDialogButtonSizer(self, flags) # Look for a help button helpBtn = None for child in sizer.GetChildren(): child = child.GetWindow() if hasattr(child, "GetId") and child.GetId() == wx.ID_HELP: helpBtn = child # Stop here if there's no help button if helpBtn is None: return # Detach from slider sizer.Detach(helpBtn) # Add stretch spacer to beginning sizer.PrependStretchSpacer(prop=1) # Add help button back at very beginning sizer.Prepend(helpBtn) # Layout and return self.Layout() return sizer class FileDropTarget(wx.FileDropTarget): """On Mac simply setting a handler for the EVT_DROP_FILES isn't enough. Need this too. """ def __init__(self, targetFrame): wx.FileDropTarget.__init__(self) self.target = targetFrame self.app = targetFrame.app def OnDropFiles(self, x, y, filenames): logging.debug( 'PsychoPyBuilder: received dropped files: %s' % filenames) for fname in filenames: if isinstance(self.target, psychopy.app.coder.CoderFrame) and wx.GetKeyState(wx.WXK_ALT): # If holding ALT and on coder, insert filename into current coder doc if self.app.coder: if self.app.coder.currentDoc: self.app.coder.currentDoc.AddText(fname) if isinstance(self.target, psychopy.app.runner.RunnerFrame): # If on Runner, load file to run self.app.showRunner() self.app.runner.addTask(fileName=fname) elif fname.lower().endswith('.psyexp'): # If they dragged on a .psyexp file, open it in in Builder self.app.showBuilder() self.app.builder.fileOpen(filename=fname) else: # If they dragged on any other file, try to open it in Coder (if it's not text, this will give error) self.app.showCoder() self.app.coder.fileOpen(filename=fname) return True class WindowFrozen(): """ Equivalent to wxWindowUpdateLocker. Usage:: with WindowFrozen(wxControl): update multiple things # will automatically thaw here """ def __init__(self, ctrl): self.ctrl = ctrl def __enter__(self): # started the with... statement # Freeze should not be called if platform is win32. if sys.platform == 'win32': return self.ctrl # check it hasn't been deleted # # Don't use StrictVersion() here, as `wx` doesn't follow the required # numbering scheme. if self.ctrl is not None and wx.__version__[:3] <= '2.8': self.ctrl.Freeze() return self.ctrl def __exit__(self, exc_type, exc_val, exc_tb): # Thaw should not be called if platform is win32. if sys.platform == 'win32': return # check it hasn't been deleted if self.ctrl is not None and self.ctrl.IsFrozen(): self.ctrl.Thaw() def getSystemFonts(encoding='system', fixedWidthOnly=False): """Get a list of installed system fonts. Parameters ---------- encoding : str Get fonts with matching encodings. fixedWidthOnly : bool Return on fixed width fonts. Returns ------- list List of font facenames. """ fontEnum = wx.FontEnumerator() encoding = "FONTENCODING_" + encoding.upper() if hasattr(wx, encoding): encoding = getattr(wx, encoding) return fontEnum.GetFacenames(encoding, fixedWidthOnly=fixedWidthOnly) class ImageData(pil.Image): def __new__(cls, source): # If given a PIL image, use it directly if isinstance(source, pil.Image): return source # If given None, use None if source in (None, "None", "none", ""): return None # If source is or looks like a file path, load from file if st.is_file(source): path = Path(source) # Only load if it looks like an image if path.suffix in pil.registered_extensions(): try: img = pil.open(source) if "A" not in img.getbands(): # Make sure there's an alpha channel to supply alpha = pil.new("L", img.size, 255) img.putalpha(alpha) return img except PIL.UnidentifiedImageError: return cls.createPlaceholder(source) # If source is a url, load from server if st.is_url(source): # Only load if looks like an image ext = "." + str(source).split(".")[-1] if ext in pil.registered_extensions(): content = requests.get(source).content data = io.BytesIO(content) try: img = pil.open(data) if "A" not in img.getbands(): # Make sure there's an alpha channel to supply alpha = pil.new("L", img.size, 255) img.putalpha(alpha) return img except PIL.UnidentifiedImageError: return cls.createPlaceholder(source) # If couldn't interpret, raise warning and return blank image return cls.createPlaceholder(source) @staticmethod def createPlaceholder(source): # Raise warning and return blank image logging.warning(_translate( "Could not get image from: {}, using blank image instead." ).format(source)) return pil.new('RGBA', size=(16, 16)) class BasePsychopyToolbar(wx.ToolBar, handlers.ThemeMixin): """Toolbar for the Builder/Coder Frame""" def __init__(self, frame): # Initialise superclass wx.ToolBar.__init__(self, frame) # Store necessary refs self.frame = frame self.app = self.frame.app # Configure toolbar appearance self.SetWindowStyle(wx.TB_HORIZONTAL | wx.NO_BORDER | wx.TB_FLAT | wx.TB_NODIVIDER | wx.TB_HORZ_TEXT) # Set icon size self.iconSize = 32 self.SetToolBitmapSize((self.iconSize, self.iconSize)) # OS-dependent tool-tips ctrlKey = 'Ctrl+' if sys.platform == 'darwin': ctrlKey = 'Cmd+' # keys are the keyboard keys, not the keys of the dict self.keys = {k: self.frame.app.keys[k].replace('Ctrl+', ctrlKey) for k in self.frame.app.keys} self.keys['none'] = '' self.buttons = {} self.makeTools() def makeTools(self): """ Make tools """ pass def makeTool(self, name, label="", shortcut=None, tooltip="", func=None): # Get icon icn = icons.ButtonIcon(name, size=self.iconSize) # Make button if 'phoenix' in wx.PlatformInfo: btn = self.AddTool( wx.ID_ANY, label="", bitmap=icn.bitmap, shortHelp=label, kind=wx.ITEM_NORMAL ) else: btn = self.AddSimpleTool( wx.ID_ANY, bitmap=icn.bitmap ) # Bind tool to function if func is None: func = self.none self.Bind(wx.EVT_TOOL, func, btn) return btn @staticmethod def none(): """ Blank function to use when bound function is None """ pass class ThemedPanel(wx.Panel, handlers.ThemeMixin): """ A wx.Panel object with themeing methods from ThemeMixin. """ pass class HoverButton(wx.Button, HoverMixin, handlers.ThemeMixin): def __init__(self, parent, id=wx.ID_ANY, label='', bmp=None, pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.BORDER_NONE, name=wx.ButtonNameStr): wx.Button.__init__( self, parent=parent, id=id, label=label, pos=pos, size=size, style=style, name=name ) if bmp is not None: self.SetBitmap(bmp) self.parent = parent self.SetupHover() def _applyAppTheme(self): self.ForegroundColourNoHover = colors.app['text'] self.ForegroundColourHover = colors.app['txtbutton_fg_hover'] self.BackgroundColourNoHover = colors.app['frame_bg'] self.BackgroundColourHover = colors.app['txtbutton_bg_hover'] # Refresh self.OnHover(evt=None) class ToggleLabelButton(wx.ToggleButton): def __init__( self, parent, id=wx.ID_ANY, label="", pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.DEFAULT, val=wx.DefaultValidator, name=wx.CheckBoxNameStr ): # Init ToggleButton as normal wx.ToggleButton.__init__( self, parent, id=id, label=label, pos=pos, size=size, style=style, val=val, name=name ) # Starting values for pressed/unpressed label self._pressedLabel = self._unPressedLabel = label # Bind label update to Toggle self.Bind(wx.EVT_TOGGLEBUTTON, self.UpdateLabel) def SetLabelUnpressed(self, label): self._unPressedLabel = label def SetLabelPressed(self, label): self._pressedLabel = label def UpdateLabel(self, evt=None): # Set label according to toggle state if self.GetValue(): self.SetLabel(self._pressedLabel) else: self.SetLabel(self._unPressedLabel) self.GetParent().Layout() # Do usual stuff evt.Skip() class MarkdownCtrl(wx.Panel, handlers.ThemeMixin): def __init__(self, parent, size=(-1, -1), value=None, file=None, style=wx.VERTICAL | wx.BU_NOTEXT): """ Multiline rich text editor for editing markdown. Includes (optional) buttons to: - If style is not wx.READONLY, toggle between editing markdown and viewing HTML - If file is not None, save the markdown file Parameters ---------- parent : wx.Window Window containing this control. size : wx.Size Size of this control (if not overridden by sizer) value : str Markdown content of this control (if not overridden by file) file : Path, str Path to markdown file to edit via this control. style : wx.Style Style tags for this control. Accepts the following: - wx.TE_READONLY: Hides all button controls and shows only the rendered HTML - wx.RIGHT: Arranges buttons vertically along the right hand side - wx.BOTTOM: Arranges buttons horizontally along the bottom - wx.BU_NOTEXT: Don't show any label on the buttons """ # Initialise superclass self.parent = parent wx.Panel.__init__(self, parent, size=size) # Manage readonly self.readonly = style | wx.TE_READONLY == style # Setup sizers if style | wx.BOTTOM == style: self.sizer = wx.BoxSizer(wx.VERTICAL) self.btnSizer = wx.BoxSizer(wx.HORIZONTAL) else: self.sizer = wx.BoxSizer(wx.HORIZONTAL) self.btnSizer = wx.BoxSizer(wx.VERTICAL) self.contentSizer = wx.BoxSizer(wx.VERTICAL) self.sizer.Add(self.contentSizer, proportion=1, flag=wx.EXPAND) self.sizer.Add(self.btnSizer, border=0, flag=wx.ALL) self.SetSizer(self.sizer) # Make text control self.rawTextCtrl = wx.stc.StyledTextCtrl(self, size=size, style=wx.TE_MULTILINE | style) self.rawTextCtrl.SetLexer(wx.stc.STC_LEX_MARKDOWN) self.rawTextCtrl.Bind(wx.stc.EVT_STC_MODIFIED, self.onEdit) self.contentSizer.Add(self.rawTextCtrl, proportion=1, border=3, flag=wx.ALL | wx.EXPAND) self.rawTextCtrl.SetReadOnly(self.readonly) self.rawTextCtrl.SetWrapMode(wx.stc.STC_WRAP_WORD) # Make HTML preview self.htmlPreview = HtmlWindow(self, wx.ID_ANY) self.htmlPreview.Bind(wx.html.EVT_HTML_LINK_CLICKED, self.onUrl) self.contentSizer.Add(self.htmlPreview, proportion=1, border=3, flag=wx.ALL | wx.EXPAND) # Choose button style if style | wx.BU_NOTEXT == style: _btnStyle = wx.BU_EXACTFIT | wx.BU_NOTEXT else: _btnStyle = wx.BU_EXACTFIT # Make edit button self.editBtn = wx.Button(self, label=_translate("Edit"), style=_btnStyle) self.editBtn.Bind(wx.EVT_BUTTON, self.showCode) self.btnSizer.Add(self.editBtn, border=3, flag=wx.ALL | wx.EXPAND) # Make view button self.previewBtn = wx.Button(self, label=_translate("Preview"), style=_btnStyle) self.previewBtn.Bind(wx.EVT_BUTTON, self.showHTML) self.btnSizer.Add(self.previewBtn, border=3, flag=wx.ALL | wx.EXPAND) # Make save button self.saveBtn = wx.Button(self, label=_translate("Save"), style=_btnStyle) self.saveBtn.Bind(wx.EVT_BUTTON, self.save) self.btnSizer.Add(self.saveBtn, border=3, flag=wx.ALL | wx.EXPAND) # Bind rightclick self.htmlPreview.Bind(wx.EVT_RIGHT_DOWN, self.onRightClick) self.rawTextCtrl.Bind(wx.EVT_RIGHT_DOWN, self.onRightClick) # Get starting value self.file = file if value is None and self.file is not None: self.load() elif value is not None: self.setValue(value) # Set initial view self.showHTML() self.saveBtn.Disable() self.saveBtn.Show(self.file is not None) self._applyAppTheme() def getValue(self): return self.rawTextCtrl.GetValue() def setValue(self, value): # Get original readonly value og = self.rawTextCtrl.GetReadOnly() # Disable read only so value can change self.rawTextCtrl.SetReadOnly(False) # Change value if value is None: value = "" self.rawTextCtrl.SetValue(value) # Restore readonly state self.rawTextCtrl.SetReadOnly(og) # Render self.render() def showCode(self, evt=None): # Show edit control and view button self.rawTextCtrl.Show(not self.readonly) self.previewBtn.Show(not self.readonly) # Hide preview control and edit button self.htmlPreview.Show(self.readonly) self.editBtn.Hide() # Refresh self.Layout() def showHTML(self, evt=None): # Hide edit control self.rawTextCtrl.Hide() self.previewBtn.Hide() # Render html self.render() # Show html control self.htmlPreview.Show() self.editBtn.Show(not self.readonly) # Refresh self.Layout() if hasattr(evt, "Skip"): evt.Skip() def render(self, evt=None): # Render HTML if md: # get raw text rawText = self.rawTextCtrl.Value # remove images (wx doesn't like rendering them) rawText = rawText.replace("![", "[") # render markdown renderedText = md.MarkdownIt("default").render(rawText) else: renderedText = self.rawTextCtrl.Value.replace("\n", "<br>") # Apply to preview ctrl self.htmlPreview.SetPage(renderedText) self.htmlPreview.Update() self.htmlPreview.Refresh() def load(self, evt=None): if self.file is None: return if not Path(self.file).is_file(): # If given a path to no file, enable save and load nothing self.rawTextCtrl.SetValue("") self.render() self.saveBtn.Enable() return # Set value from file with open(self.file, "r", encoding="utf-8") as f: self.rawTextCtrl.SetValue(f.read()) # Disable save button self.saveBtn.Disable() def save(self, evt=None): if self.file is None: # if no file, open dialog to choose one dlg = wx.FileDialog( self, message=_translate("Save file as..."), defaultDir=str(Path.home()), style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT, wildcard="Markdown file (*.md)|*.md|Text file (*.txt)|*.txt|Any file (*.*)|*.*") if dlg.ShowModal() == wx.ID_OK: self.file = dlg.GetPath() self.load() else: return # write current contents to file with open(self.file, "w") as f: f.write(self.rawTextCtrl.GetValue()) # disable save button self.saveBtn.Disable() def onEdit(self, evt=None): # Enable save button when edited self.saveBtn.Enable() # Post event evt = wx.CommandEvent(wx.EVT_TEXT.typeId) evt.SetEventObject(self) wx.PostEvent(self, evt) @staticmethod def onUrl(evt=None): webbrowser.open(evt.LinkInfo.Href) def onRightClick(self, evt=None): menu = wx.Menu() # Show raw code button if in HTML view if not self.rawTextCtrl.IsShown(): thisId = menu.Append(wx.ID_ANY, _translate("View raw code")) menu.Bind(wx.EVT_MENU, self.showCode, source=thisId) # Show HTML button if in code view if not self.htmlPreview.IsShown(): thisId = menu.Append(wx.ID_ANY, _translate("View styled HTML")) menu.Bind(wx.EVT_MENU, self.showHTML, source=thisId) self.PopupMenu(menu) def _applyAppTheme(self): from psychopy.app.themes import fonts spec = fonts.coderTheme.base # Set raw text font from coder theme self.rawTextCtrl.SetFont(spec.obj) # Always style text ctrl handlers.styleCodeEditor(self.rawTextCtrl) # Only style output if in a styled parent if isinstance(self.GetTopLevelParent(), handlers.ThemeMixin): handlers.styleHTMLCtrl(self.htmlPreview) # Set save button icon self.saveBtn.SetBitmap( icons.ButtonIcon(stem="savebtn", size=(16, 16)).bitmap ) # Set edit toggle icon self.editBtn.SetBitmap( icons.ButtonIcon(stem="editbtn", size=(16, 16)).bitmap ) self.previewBtn.SetBitmap( icons.ButtonIcon(stem="viewbtn", size=(16, 16)).bitmap ) self.Refresh() class HyperLinkCtrl(wx.Button): def __init__(self, parent, id=wx.ID_ANY, label="", URL="", pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.BU_LEFT, validator=wx.DefaultValidator, name=""): # Create button with no background wx.Button.__init__(self) self.SetBackgroundStyle(wx.BG_STYLE_TRANSPARENT) self.Create( parent=parent, id=id, label=label, pos=pos, size=size, style=wx.BORDER_NONE | style, validator=validator, name=name) # Style as link self.SetForegroundColour("blue") self._font = self.GetFont().MakeUnderlined() self.SetFont(self._font) # Setup hover/focus behaviour self.Bind(wx.EVT_SET_FOCUS, self.onFocus) self.Bind(wx.EVT_KILL_FOCUS, self.onFocus) self.Bind(wx.EVT_ENTER_WINDOW, self.onHover) self.Bind(wx.EVT_MOTION, self.onHover) self.Bind(wx.EVT_LEAVE_WINDOW, self.onHover) # Set URL self.URL = URL self.Bind(wx.EVT_BUTTON, self.onClick) def onClick(self, evt=None): webbrowser.open(self.URL) def onFocus(self, evt=None): if evt.EventType == wx.EVT_SET_FOCUS.typeId: self.SetFont(self._font.Bold()) elif evt.EventType == wx.EVT_KILL_FOCUS.typeId: self.SetFont(self._font) self.Update() self.Layout() def onHover(self, evt=None): if evt.EventType == wx.EVT_LEAVE_WINDOW.typeId: # If mouse is leaving window, reset cursor wx.SetCursor( wx.Cursor(wx.CURSOR_DEFAULT) ) else: # Otherwise, if a mouse event is received, it means the cursor is on this link wx.SetCursor( wx.Cursor(wx.CURSOR_HAND) ) class WrappedStaticText(GenStaticText): """ Similar to wx.StaticText, but wraps automatically. """ def __init__(self, parent, id=wx.ID_ANY, label="", pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.TEXT_ALIGNMENT_LEFT, name=""): GenStaticText.__init__( self, parent=parent, ID=id, label=label, pos=pos, size=size, style=style, name=name) # Store original label self._label = label # Bind to wrapping function self.Bind(wx.EVT_SIZE, self.onResize) def onResize(self, evt=None): # Get width to wrap to w, h = evt.GetSize() # Wrap evt.Skip() self.Wrap(w) def Wrap(self, width): """ Stolen from wx.lib.agw.infobar.AutoWrapStaticText """ if width < 0: return self.Freeze() dc = wx.ClientDC(self) dc.SetFont(self.GetFont()) text = wordwrap(self._label, width, dc) self.SetLabel(text) self.Thaw() class HyperLinkCtrl(wx.Button): def __init__(self, parent, id=wx.ID_ANY, label="", URL="", pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.BU_LEFT, validator=wx.DefaultValidator, name=""): # Create button with no background wx.Button.__init__(self) self.SetBackgroundStyle(wx.BG_STYLE_TRANSPARENT) self.Create( parent=parent, id=id, label=label, pos=pos, size=size, style=wx.BORDER_NONE | style, validator=validator, name=name) # Style as link self.SetForegroundColour("blue") self._font = self.GetFont().MakeUnderlined() self.SetFont(self._font) # Setup hover/focus behaviour self.Bind(wx.EVT_SET_FOCUS, self.onFocus) self.Bind(wx.EVT_KILL_FOCUS, self.onFocus) self.Bind(wx.EVT_ENTER_WINDOW, self.onHover) self.Bind(wx.EVT_MOTION, self.onHover) self.Bind(wx.EVT_LEAVE_WINDOW, self.onHover) # Set URL self.URL = URL self.Bind(wx.EVT_BUTTON, self.onClick) def onClick(self, evt=None): webbrowser.open(self.URL) def onFocus(self, evt=None): if evt.EventType == wx.EVT_SET_FOCUS.typeId: self.SetFont(self._font.Bold()) elif evt.EventType == wx.EVT_KILL_FOCUS.typeId: self.SetFont(self._font) self.Update() self.Layout() def onHover(self, evt=None): if evt.EventType == wx.EVT_LEAVE_WINDOW.typeId: # If mouse is leaving window, reset cursor wx.SetCursor( wx.Cursor(wx.CURSOR_DEFAULT) ) else: # Otherwise, if a mouse event is received, it means the cursor is on this link wx.SetCursor( wx.Cursor(wx.CURSOR_HAND) ) class ButtonArray(wx.Window): class ArrayBtn(wx.Window): def __init__(self, parent, label="", readonly=False): wx.Window.__init__(self, parent) self.parent = parent # Setup sizer self.sizer = wx.BoxSizer(wx.HORIZONTAL) self.SetSizer(self.sizer) # Create button self.button = wx.Button(self, label=label, style=wx.BORDER_NONE) self.sizer.Add(self.button, border=4, flag=wx.LEFT | wx.EXPAND) self.label = wx.StaticText(self, label=label) self.sizer.Add(self.label, border=6, flag=wx.LEFT | wx.EXPAND) # Create remove btn self.removeBtn = wx.Button(self, label="×", size=(24, -1)) self.sizer.Add(self.removeBtn, border=4, flag=wx.RIGHT | wx.EXPAND) # Bind remove btn to remove function self.removeBtn.Bind(wx.EVT_BUTTON, self.remove) # Bind button to button function self.button.Bind(wx.EVT_BUTTON, self.onClick) # Set readonly self.readonly = readonly self.SetBackgroundColour(self.parent.GetBackgroundColour()) def remove(self, evt=None): self.parent.removeItem(self) def onClick(self, evt=None): evt = wx.CommandEvent(wx.EVT_BUTTON.typeId) evt.SetString(self.button.GetLabel()) evt.SetEventObject(self) wx.PostEvent(self.parent, evt) @property def readonly(self): return self._readonly @readonly.setter def readonly(self, value): # Store value self._readonly = value # Show/hide controls self.removeBtn.Show(not value) # Show/hide button and label self.button.Show(not value) self.label.Show(value) # Layout self.Layout() def __init__(self, parent, orient=wx.HORIZONTAL, items=(), options=None, itemAlias=_translate("item"), readonly=False): # Create self wx.Window.__init__(self, parent) self.SetBackgroundColour(parent.GetBackgroundColour()) self.parent = parent self.itemAlias = itemAlias self.options = options # Create sizer self.sizer = wx.WrapSizer(orient=orient) self.SetSizer(self.sizer) # Create add button self.addBtn = wx.Button(self, size=(24, 24), label="+", style=wx.BORDER_NONE) self.addBtn.Bind(wx.EVT_BUTTON, self.newItem) self.sizer.Add(self.addBtn, border=3, flag=wx.EXPAND | wx.ALL) # Add items self.items = items # Set readonly self.readonly = readonly def _applyAppTheme(self, target=None): for child in self.sizer.Children: if hasattr(child.Window, "_applyAppTheme"): child.Window._applyAppTheme() @property def items(self): items = {} for child in self.sizer.Children: if not child.Window == self.addBtn: items[child.Window.button.Label] = child.Window return items @items.setter def items(self, value): if isinstance(value, str): value = [value] if value is None or value is numpy.nan: value = [] if isinstance(value, tuple): value = list(value) assert isinstance(value, list) value.reverse() self.clear() for item in value: self.addItem(item) @property def readonly(self): return self._readonly @readonly.setter def readonly(self, value): # Store value self._readonly = value # Show/hide controls self.addBtn.Show(not value) # Cascade readonly down for item in self.items: item.readonly = value # Layout self.Layout() def newItem(self, evt=None): msg = _translate("Add {}...").format(self.itemAlias) if self.options is None: _dlg = wx.TextEntryDialog(self.parent, message=msg) else: _dlg = wx.SingleChoiceDialog(self.parent, msg, "Input Text", choices=self.options) if _dlg.ShowModal() != wx.ID_OK: return if self.options is None: self.addItem(_dlg.GetValue()) else: self.addItem(_dlg.GetStringSelection()) def addItem(self, item): if not isinstance(item, wx.Window): item = self.ArrayBtn(self, label=item, readonly=self.readonly) self.sizer.Insert(0, item, border=3, flag=wx.EXPAND | wx.TOP | wx.BOTTOM | wx.RIGHT) self.Layout() # Raise event evt = wx.ListEvent(wx.EVT_LIST_INSERT_ITEM.typeId) evt.SetEventObject(self) wx.PostEvent(self, evt) def removeItem(self, item): items = self.items.copy() # Get value from key if needed if item in items: item = items[item] # Delete object and item in dict if item in list(items.values()): i = self.sizer.Children.index(self.sizer.GetItem(item)) self.sizer.Remove(i) item.Hide() self.Layout() # Raise event evt = wx.ListEvent(wx.EVT_LIST_DELETE_ITEM.typeId) evt.SetEventObject(self) wx.PostEvent(self, evt) def clear(self): # Raise event evt = wx.ListEvent(wx.EVT_LIST_DELETE_ALL_ITEMS.typeId) evt.SetEventObject(self) wx.PostEvent(self, evt) # Delete all items for item in self.items: self.removeItem(item) def Enable(self, enable=True): for child in self.Children: child.Enable(enable) def Disable(self): self.Enable(False) def GetValue(self): return list(self.items) class SortCtrl(wx.Window): class SortItem(wx.Window): def __init__(self, parent, item, showSelect=False, selected=True, showFlip=False ): # Create self wx.Window.__init__(self, parent, style=wx.BORDER_NONE) self.SetBackgroundColour("white") self.parent = parent # Make sure we've been given a SortTerm assert isinstance(item, SortTerm) self.item = item # Setup sizer self.sizer = wx.BoxSizer(wx.HORIZONTAL) self.SetSizer(self.sizer) # Add tickbox (if select) self.selectCtrl = wx.CheckBox(self) self.selectCtrl.Bind(wx.EVT_CHECKBOX, self.onSelect) self.selectCtrl.SetValue(selected) self.selectCtrl.Show(showSelect) self.sizer.Add(self.selectCtrl, border=6, flag=wx.ALL | wx.EXPAND) # Add label self.labelObj = wx.StaticText(self, label=self.item.label) self.sizer.Add(self.labelObj, proportion=1, border=6, flag=wx.ALL | wx.EXPAND) # Add flip button self.flipBtn = wx.Button(self, size=(16, 8), label="⇵", style=wx.BORDER_NONE) self.flipBtn.SetBackgroundColour(self.GetBackgroundColour()) self.flipBtn.Bind(wx.EVT_BUTTON, self.flip) self.flipBtn.Show(showFlip) self.sizer.Add(self.flipBtn, border=6, flag=wx.ALL | wx.EXPAND) # Add ctrls sizer self.ctrlsSizer = wx.BoxSizer(wx.VERTICAL) self.sizer.Add(self.ctrlsSizer, border=6, flag=wx.ALL | wx.EXPAND) # Add up button self.upBtn = wx.Button(self, size=(16, 8), label="▲", style=wx.BORDER_NONE) self.upBtn.SetBackgroundColour(self.GetBackgroundColour()) self.upBtn.Bind(wx.EVT_BUTTON, self.moveUp) self.ctrlsSizer.Add(self.upBtn, border=0, flag=wx.ALL | wx.EXPAND) # Add stretch spacer inbetween self.ctrlsSizer.AddStretchSpacer(1) # Add up button self.downBtn = wx.Button(self, size=(16, 8), label="▼", style=wx.BORDER_NONE) self.downBtn.SetBackgroundColour(self.GetBackgroundColour()) self.downBtn.Bind(wx.EVT_BUTTON, self.moveDown) self.ctrlsSizer.Add(self.downBtn, border=0, flag=wx.ALL | wx.EXPAND) # Do initial select self.onSelect() @property def label(self): return self.item.label @property def value(self): return self.item.value def flip(self, evt=None): # Flip state self.item.ascending = not self.item.ascending # Change label self.labelObj.SetLabel(self.label) def moveUp(self, evt=None): # Get own index i = self.parent.items.index(self) # Insert popped self before previous position self.parent.items.insert(max(i-1, 0), self.parent.items.pop(i)) # Layout self.parent.Layout() def moveDown(self, evt=None): # Get own index i = self.parent.items.index(self) # Insert popped self before previous position self.parent.items.insert(min(i+1, len(self.parent.items)), self.parent.items.pop(i)) # Layout self.parent.Layout() @property def selected(self): return self.selectCtrl.GetValue() def onSelect(self, evt=None): self.Enable(self.selected) def Enable(self, enable=True): self.labelObj.Enable(enable) def Disable(self): self.Enable(False) def __init__(self, parent, items, showSelect=False, selected=True, showFlip=False, orient=wx.VERTICAL): wx.Window.__init__(self, parent) # Make sure we've been given an array if not isinstance(items, (list, tuple)): items = [items] # Setup sizer self.sizer = wx.BoxSizer(orient) self.SetSizer(self.sizer) # If given a bool for select, apply it to all items if isinstance(selected, bool): selected = [selected] * len(items) assert isinstance(selected, (list, tuple)) and len(selected) == len(items) # Setup items self.items = [] for i, item in enumerate(items): self.items.append(self.SortItem(self, item=item, showSelect=showSelect, selected=selected[i], showFlip=showFlip)) self.sizer.Add(self.items[i], border=6, flag=wx.ALL | wx.EXPAND) # Layout self.Layout() def GetValue(self): items = [] for item in self.items: if item.selected: items.append(item.item) return items def Layout(self): # Get order of items in reverse items = self.items.copy() items.reverse() # Remove each item for item in items: self.sizer.Remove(self.sizer.Children.index(self.sizer.GetItem(item))) # Add items back in oder for i, item in enumerate(items): self.sizer.Prepend(item, border=6, flag=wx.ALL | wx.EXPAND) item.upBtn.Show(i != len(items)-1) item.downBtn.Show(i != 0) # Disable appropriate buttons # Do base layout wx.Window.Layout(self) class ImageCtrl(wx.lib.statbmp.GenStaticBitmap): def __init__(self, parent, bitmap, size=(128, 128)): wx.lib.statbmp.GenStaticBitmap.__init__(self, parent, ID=wx.ID_ANY, bitmap=wx.Bitmap(), size=size) self.parent = parent self.iconCache = icons.iconCache # Create a frame timer for animated GIFs self.frameTimer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self._advanceFrame) # Set bitmap self.setImage(bitmap) # Setup sizer self.sizer = wx.BoxSizer(wx.HORIZONTAL) self.sizer.AddStretchSpacer(1) self.SetSizer(self.sizer) # Add edit button self.editBtn = wx.Button(self, style=wx.BU_EXACTFIT) self.editBtn.SetBitmap(icons.ButtonIcon("editbtn", size=16, theme="light").bitmap) self.editBtn.Bind(wx.EVT_BUTTON, self.LoadBitmap) self.sizer.Add(self.editBtn, border=6, flag=wx.ALIGN_BOTTOM | wx.ALL) def _advanceFrame(self, evt=None): if len(self._frames) <= 1: # Do nothing for static images return else: # Advance the frame self._frameI += 1 if self._frameI >= len(self._frames): self._frameI = 0 # Update bitmap self.SetBitmap(self._frames[self._frameI]) self.Update() def setImage(self, data): self.frameTimer.Stop() # Substitute paths and Image objects if isinstance(data, (str, Path, wx.Image)): data = wx.Bitmap(data) # Store raw data self._imageData = data # Reset frames self._frames = [] self._frameI = 0 fr = [] if isinstance(data, wx.Bitmap): # Sub in blank bitmaps if not data.IsOk(): data = icons.ButtonIcon(stem="user_none", size=128, theme="light").bitmap # Store full size bitmap self._imageData = data # Resize bitmap buffer = data.ConvertToImage() buffer = buffer.Scale(*self.Size, quality=wx.IMAGE_QUALITY_HIGH) scaledBitmap = wx.Bitmap(buffer) # If given a wx.Bitmap directly, use it self._frames.append(scaledBitmap) else: # Otherwise, extract frames try: img = pil.open(data) for i in range(getattr(img, "n_frames", 1)): # Seek to frame img.seek(i) if 'duration' in img.info: fr.append(img.info['duration']) # Create wx.Bitmap from frame frame = img.resize(self.Size).convert("RGBA") # Ensure an alpha channel if "A" not in frame.getbands(): # Make sure there's an alpha channel to supply alpha = pil.new("L", frame.size, 255) frame.putalpha(alpha) alpha = frame.tobytes("raw", "A") bmp = wx.Bitmap.FromBufferAndAlpha( *frame.size, data=frame.tobytes("raw", "RGB"), alpha=alpha) # Store bitmap self._frames.append(bmp) except PIL.UnidentifiedImageError as err: # If image read fails, show warning msg = _translate("Inavlid image format, could not set image.") dlg = wx.MessageDialog(None, msg, style=wx.ICON_WARNING) dlg.ShowModal() # then use a blank image self._frames = [icons.ButtonIcon(stem="invalid_img", size=128, theme="light").bitmap] # Set first frame (updates non-animated images) self.SetBitmap(self._frames[self._frameI]) # If animated... if len(self._frames) > 1: # Make sure we have a frame rate if not len(fr): fr.append(200) # Start animation (average framerate across frames) self.frameTimer.Start(int(numpy.mean(fr)), oneShot=False) def LoadBitmap(self, evt=None): # Open file dlg _dlg = wx.FileDialog(self.parent, message=_translate("Select image...")) if _dlg.ShowModal() != wx.ID_OK: return # Get value path = str(Path(_dlg.GetPath())) self.setImage(path) # Post event evt = wx.FileDirPickerEvent(wx.EVT_FILEPICKER_CHANGED.typeId, self, -1, path) evt.SetEventObject(self) wx.PostEvent(self, evt) @property def path(self): """ If current bitmap is from a file, returns the filepath. Otherwise, returns None. """ if hasattr(self, "_path"): return self._path @path.setter def path(self, value): self._path = value def GetBitmapFull(self): return self._imageData @property def BitmapFull(self): return self.GetBitmapFull() def Enable(self, enable=True): wx.StaticBitmap.Enable(self, enable) self.editBtn.Enable(enable) def Disable(self): self.Enable(False) class PsychopyScrollbar(wx.ScrollBar): def __init__(self, parent, ori=wx.VERTICAL): wx.ScrollBar.__init__(self) if ori == wx.HORIZONTAL: style = wx.SB_HORIZONTAL else: style = wx.SB_VERTICAL self.Create(parent, style=style) self.ori = ori self.parent = parent self.Bind(wx.EVT_SCROLL, self.DoScroll) self.Resize() def DoScroll(self, event): if self.ori == wx.HORIZONTAL: w = event.GetPosition() h = self.parent.GetScrollPos(wx.VERTICAL) elif self.ori == wx.VERTICAL: w = self.parent.GetScrollPos(wx.HORIZONTAL) h = event.GetPosition() else: return self.parent.Scroll(w, h) self.Resize() def Resize(self): sz = self.parent.GetSize() vsz = self.parent.GetVirtualSize() start = self.parent.GetViewStart() if self.ori == wx.HORIZONTAL: sz = (sz.GetWidth(), 20) vsz = vsz.GetWidth() elif self.ori == wx.VERTICAL: sz = (20, sz.GetHeight()) vsz = vsz.GetHeight() self.SetDimensions(start[0], start[1], sz[0], sz[1]) self.SetScrollbar( position=self.GetScrollPos(self.ori), thumbSize=10, range=1, pageSize=vsz ) class FileCtrl(wx.TextCtrl): def __init__(self, parent, dlgtype="file", value=""): wx.TextCtrl.__init__(self, parent, value=value, size=(-1, 24)) # Store type self.dlgtype = dlgtype # Setup sizer self.sizer = wx.BoxSizer(wx.HORIZONTAL) self.SetSizer(self.sizer) self.sizer.AddStretchSpacer(1) # Add button self.fileBtn = wx.Button(self, size=(16, 16), style=wx.BORDER_NONE) self.fileBtn.SetBackgroundColour(self.GetBackgroundColour()) self.fileBtn.SetBitmap(icons.ButtonIcon(stem="folder", size=16, theme="light").bitmap) self.sizer.Add(self.fileBtn, border=4, flag=wx.ALL) # Bind browse function self.fileBtn.Bind(wx.EVT_BUTTON, self.browse) def browse(self, evt=None): file = Path(self.GetValue()) # Sub in a / for blank paths to force the better folder navigator if file == Path(): file = Path("/") # Open file or dir dlg if self.dlgtype == "dir": dlg = wx.DirDialog(self, message=_translate("Specify folder..."), defaultPath=str(file)) else: dlg = wx.FileDialog(self, message=_translate("Specify file..."), defaultDir=str(file)) if dlg.ShowModal() != wx.ID_OK: return # Get data from dlg file = Path(dlg.GetPath()) # Set data self.SetValue(str(file)) def SetValue(self, value): # Replace backslashes with forward slashes value = value.replace("\\", "/") # Do base value setting wx.TextCtrl.SetValue(self, value) # Post event evt = wx.FileDirPickerEvent(wx.EVT_FILEPICKER_CHANGED.typeId, self, -1, value) evt.SetEventObject(self) wx.PostEvent(self, evt) def Enable(self, enable=True): wx.TextCtrl.Enable(self, enable) self.fileBtn.Enable(enable) self.fileBtn.SetBackgroundColour(self.GetBackgroundColour()) def Disable(self): self.Enable(False) def Show(self, show=True): wx.TextCtrl.Show(self, show) self.fileBtn.Show(show) def Hide(self): self.Show(False) def updateDemosMenu(frame, menu, folder, ext): """Update Demos menu as needed.""" def _makeButton(parent, menu, demo): # Skip if demo name starts with _ if demo.name.startswith("_"): return # Create menu button item = menu.Append(wx.ID_ANY, demo.name) # Store in window's demos list parent.demos.update({item.Id: demo}) # Link button to demo opening function parent.Bind(wx.EVT_MENU, parent.demoLoad, item) def _makeFolder(parent, menu, folder, ext): # Skip if underscore in folder name if folder.name.startswith("_"): return # Create and append menu for this folder submenu = wx.Menu() menu.AppendSubMenu(submenu, folder.name) # Get folder contents folderContents = glob.glob(str(folder / '*')) for subfolder in sorted(folderContents): subfolder = Path(subfolder) # Make menu/button for each: # subfolder according to whether it contains a psyexp, or... # subfile according to whether it matches the ext if subfolder.is_dir(): subContents = glob.glob(str(subfolder / '*')) if any(file.endswith(".psyexp") and not file.startswith("_") for file in subContents): _makeButton(parent, submenu, subfolder) else: _makeFolder(parent, submenu, subfolder, ext) elif subfolder.suffix == ext and not subfolder.name.startswith("_"): _makeButton(parent, submenu, subfolder) # Make blank dict to store demo details in frame.demos = {} if not folder: # if there is no unpacked demos folder then just return return # Get root folders rootGlob = glob.glob(str(Path(folder) / '*')) for fdr in rootGlob: fdr = Path(fdr) # Make menus/buttons recursively for each folder according to whether it contains a psyexp if fdr.is_dir(): folderContents = glob.glob(str(fdr / '*')) if any(file.endswith(".psyexp") for file in folderContents): _makeButton(frame, menu, fdr) else: _makeFolder(frame, menu, fdr, ext) class FrameSwitcher(wx.Menu): """Menu for switching between different frames""" def __init__(self, parent): wx.Menu.__init__(self) self.parent = parent self.app = parent.app self.itemFrames = {} self.next = self.Append( wx.ID_MDI_WINDOW_NEXT, _translate("&Next window\t%s") % self.app.keys['cycleWindows'], _translate("&Next window\t%s") % self.app.keys['cycleWindows']) self.Bind(wx.EVT_MENU, self.nextWindow, self.next) self.AppendSeparator() self.makeViewSwitcherButtons(self, frame=self.Window, app=self.app) self.updateFrames() @staticmethod def makeViewSwitcherButtons(parent, frame, app): """ Make buttons to show Builder, Coder & Runner Parameters ========== parent : wx.Menu Menu to append these buttons to frame : wx.Frame Frame for the menu to be attached to - used to check whether we need to skip one option app : wx.App Current PsychoPy app instance, from which to get showBuilder/showCoder/showRunner methods """ items = {} # Builder if not isinstance(frame, psychopy.app.builder.BuilderFrame): items['builder'] = parent.Append( wx.ID_ANY, _translate("Show &builder"), _translate("Show Builder") ) parent.Bind(wx.EVT_MENU, app.showBuilder, items['builder']) # Coder if not isinstance(frame, psychopy.app.coder.CoderFrame): items['coder'] = parent.Append( wx.ID_ANY, _translate("Show &coder"), _translate("Show Coder") ) parent.Bind(wx.EVT_MENU, app.showCoder, items['coder']) # Runner if not isinstance(frame, psychopy.app.runner.RunnerFrame): items['runner'] = parent.Append( wx.ID_ANY, _translate("Show &runner"), _translate("Show Runner") ) parent.Bind(wx.EVT_MENU, app.showRunner, items['runner']) parent.AppendSeparator() return items @property def frames(self): return self.parent.app.getAllFrames() def updateFrames(self): """Set items according to which windows are open""" self.next.Enable(len(self.frames) > 1) # Make new items if needed for frame in self.frames: if frame not in self.itemFrames: if frame.filename: label = type(frame).__name__.replace("Frame", "") + ": " + os.path.basename(frame.filename) else: label = type(frame).__name__.replace("Frame", "") self.itemFrames[frame] = self.AppendRadioItem(wx.ID_ANY, label, label) self.Bind(wx.EVT_MENU, self.showFrame, self.itemFrames[frame]) # Edit items to match frames for frame in self.itemFrames: item = self.itemFrames[frame] if not item: continue if frame not in self.frames: # Disable unused items item.Enable(False) else: # Rename item if frame.filename: self.itemFrames[frame].SetItemLabel( type(frame).__name__.replace("Frame", "") + ": " + os.path.basename(frame.filename) ) else: self.itemFrames[frame].SetItemLabel( type(frame).__name__.replace("Frame", "") + ": None" ) item.Check(frame == self.Window) self.itemFrames = {key: self.itemFrames[key] for key in self.itemFrames if self.itemFrames[key] is not None} def showFrame(self, event=None): itemFrames = event.EventObject.itemFrames frame = [key for key in itemFrames if itemFrames[key].Id == event.Id][0] frame.Show(True) frame.Raise() self.parent.app.SetTopWindow(frame) self.updateFrames() def nextWindow(self, event=None): """Cycle through list of open windows""" current = event.EventObject.Window i = self.frames.index(current) while self.frames[i] == current: i -= 1 self.frames[i].Raise() self.frames[i].Show() self.updateFrames() def sanitize(inStr): """ Process a string to remove any sensitive information, i.e. OAUTH keys """ # Key-value pairs of patterns with what to replace them with patterns = { "https\:\/\/oauth2\:[\d\w]{64}@gitlab\.pavlovia\.org\/.*\.git": "[[OAUTH key hidden]]" # Remove any oauth keys } # Replace each pattern for pattern, repl in patterns.items(): inStr = re.sub(pattern, repl, inStr) return inStr class ToggleButton(wx.ToggleButton, HoverMixin): """ Extends wx.ToggleButton to give methods for handling color changes relating to hover events and value setting. """ @property def BackgroundColourNoHover(self): if self.GetValue(): # Return a darker color if selected return colors.app['docker_bg'] else: # Return the default color otherwise return HoverMixin.BackgroundColourNoHover.fget(self) class ToggleButtonArray(wx.Window, handlers.ThemeMixin): def __init__(self, parent, labels=None, values=None, multi=False, ori=wx.HORIZONTAL): wx.Window.__init__(self, parent) self.parent = parent self.multi = multi # Setup sizer self.sizer = wx.BoxSizer(ori) self.SetSizer(self.sizer) # Alias values and labels if labels is None: labels = values if values is None: values = labels if values is None and labels is None: values = labels = [] # Make buttons self.buttons = {} for i, val in enumerate(values): self.buttons[val] = ToggleButton(self, style=wx.BORDER_NONE) self.buttons[val].SetupHover() self.buttons[val].SetLabelText(labels[i]) self.buttons[val].Bind(wx.EVT_TOGGLEBUTTON, self.processToggle) self.sizer.Add(self.buttons[val], border=6, proportion=1, flag=wx.ALL | wx.EXPAND) def processToggle(self, evt): obj = evt.GetEventObject() if self.multi: # Toggle self self.SetValue(self.GetValue()) else: # Selectself and deselect other buttons for key, btn in self.buttons.items(): if btn == obj: self.SetValue(key) def SetValue(self, value): if not isinstance(value, (list, tuple)): value = [value] if not self.multi: assert len(value) == 1, "When multi is False, ToggleButtonArray value must be a single value" # Set corresponding button's value to be True and all others to be False for key, btn in self.buttons.items(): btn.SetValue(key in value) # Restyle self._applyAppTheme() # Emit event evt = wx.CommandEvent(wx.EVT_CHOICE.typeId) evt.SetEventObject(self) wx.PostEvent(self, evt) def GetValue(self): # Return key of button(s) whose value is True values = [] for key, btn in self.buttons.items(): if btn.GetValue(): values.append(key) # If single select, only return first value if not self.multi: values = values[0] return values def _applyAppTheme(self, target=None): # Set panel background self.SetBackgroundColour(colors.app['panel_bg']) # Use OnHover event to set buttons to their default colors for btn in self.buttons.values(): btn.OnHover() class ListCtrl(wx.ListCtrl, listmixin.ListCtrlAutoWidthMixin): def __init__(self, parent=None, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.LC_REPORT, validator=wx.DefaultValidator, name=""): wx.ListCtrl.__init__( self, parent, id=id, pos=pos, size=size, style=style, validator=validator, name=name ) listmixin.ListCtrlAutoWidthMixin.__init__(self) def sanitize(inStr): """ Process a string to remove any sensitive information, i.e. OAUTH keys """ # Key-value pairs of patterns with what to replace them with patterns = { r"https:\/\/oauth2:[\d\w]{64}@gitlab\.pavlovia\.org\/.*\.git": "[[OAUTH key hidden]]" # Remove any oauth keys } # Replace each pattern for pattern, repl in patterns.items(): inStr = re.sub(pattern, repl, inStr) return inStr
59,388
Python
.py
1,479
29.80595
139
0.594201
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,788
__init__.py
psychopy_psychopy/psychopy/app/__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). """Module for the PsychoPy GUI application. """ __all__ = [ 'startApp', 'quitApp', 'restartApp', 'setRestartRequired', 'isRestartRequired', 'getAppInstance', 'getAppFrame', 'isAppStarted'] import sys import os from .console import StdStreamDispatcher from .frametracker import openFrames # Handle to the PsychoPy GUI application instance. We need to have this mainly # to allow the plugin system to access GUI to allow for changes after startup. _psychopyAppInstance = None # Flag to indicate if the app requires a restart. This is set by the app when # it needs to restart after an update or plugin installation. We can check this # flag to determine if the app is in a state that it is recommended to restart. REQUIRES_RESTART = False # Adapted from # https://code.activestate.com/recipes/580767-unix-tee-like-functionality-via-a-python-class/ # (BSD 3-Clause) class _Tee(object): def __init__(self, fid): self._other_fid = fid def write(self, s): sys.__stdout__.write(s) self._other_fid.write(s) def writeln(self, s): self.write(s + '\n') def close(self): self._other_fid.close() def flush(self): self._other_fid.flush() sys.__stdout__.flush() def startApp( showSplash=True, testMode=False, safeMode=False, startView=None, startFiles=None, firstRun=False, profiling=False, ): """Start the PsychoPy GUI. This function is idempotent, where additional calls after the app starts will have no effect unless `quitApp()` was previously called. After this function returns, you can get the handle to the created `PsychoPyApp` instance by calling :func:`getAppInstance` (returns `None` otherwise). Errors raised during initialization due to unhandled exceptions with respect to the GUI application are usually fatal. You can examine 'last_app_load.log' inside the 'psychopy3' user directory (specified by preference 'userPrefsDir') to see the traceback. After startup, unhandled exceptions will appear in a special dialog box that shows the error traceback and provides some means to recover their work. Regular logging messages will appear in the log file or GUI. We use a separate error dialog here is delineate errors occurring in the user's experiment scripts and those of the application itself. Parameters ---------- showSplash : bool Show the splash screen on start. testMode : bool Must be `True` if creating an instance for unit testing. safeMode : bool Start PsychoPy in safe-mode. If `True`, the GUI application will launch with without loading plugins. startView : str, None Name of the view to start the app with. Valid values are 'coder', 'builder' or 'runner'. If `None`, the app will start with the default view or the view specifed with the `PSYCHOPYSTARTVIEW` environment variable. """ global _psychopyAppInstance if isAppStarted(): # do nothing it the app is already loaded return # NOP # Make sure logging is started before loading the bulk of the main # application UI to catch as many errors as possible. After the app is # loaded, messages are handled by the `StdStreamDispatcher` instance. prefLogFilePath = None if not testMode: from psychopy.preferences import prefs from psychopy.logging import console, DEBUG # construct path to log file from preferences userPrefsDir = prefs.paths['userPrefsDir'] prefLogFilePath = os.path.join(userPrefsDir, 'last_app_load.log') lastRunLog = open(prefLogFilePath, 'w') # open the file for writing console.setLevel(DEBUG) # NOTE - messages and errors cropping up before this point will go to # console, afterwards to 'last_app_load.log'. sys.stderr = sys.stdout = _Tee(lastRunLog) # redirect output to file # Create the application instance which starts loading it. # If `testMode==True`, all messages and errors (i.e. exceptions) will log to # console. from psychopy.app._psychopyApp import PsychoPyApp _psychopyAppInstance = PsychoPyApp( 0, testMode=testMode, showSplash=showSplash, safeMode=safeMode, startView=startView, startFiles=startFiles, firstRun=firstRun, profiling=profiling, ) # After the app is loaded, we hand off logging to the stream dispatcher # using the provided log file path. The dispatcher will write out any log # messages to the extant log file and any GUI windows to show them to the # user. # ensure no instance was created before this one if StdStreamDispatcher.getInstance() is not None: raise RuntimeError( '`StdStreamDispatcher` instance initialized outside of `startApp`, ' 'this is not permitted.') stdDisp = StdStreamDispatcher(_psychopyAppInstance, prefLogFilePath) stdDisp.redirect() if not testMode: # Setup redirection of errors to the error reporting dialog box. We # don't want this in the test environment since the box will cause the # app to stall on error. from psychopy.app.errorDlg import exceptionCallback # After this point, errors will appear in a dialog box. Messages will # continue to be written to the dialog. sys.excepthook = exceptionCallback # Allow the UI to refresh itself. Don't do this during testing where the # UI is exercised programmatically. _psychopyAppInstance.MainLoop() def quitApp(): """Quit the running PsychoPy application instance. Will have no effect if `startApp()` has not been called previously. """ if not isAppStarted(): return global _psychopyAppInstance if hasattr(_psychopyAppInstance, 'quit'): # type check _psychopyAppInstance.quit() # PsychoPyApp._called_from_test = False # reset _psychopyAppInstance = None else: raise AttributeError('Object `_psychopyApp` has no attribute `quit`.') def restartApp(): """Restart the PsychoPy application instance. This will write a file named '.restart' to the user preferences directory and quit the application. The presence of this file will indicate to the launcher parent process that the app should restart. The app restarts with the same arguments as the original launch. This is useful for updating the application or plugins without requiring the user to manually restart the app. The user will be prompted to save any unsaved work before the app restarts. """ if not isAppStarted(): return # write a restart file to the user preferences directory from psychopy.preferences import prefs restartFilePath = os.path.join(prefs.paths['userPrefsDir'], '.restart') with open(restartFilePath, 'w') as restartFile: restartFile.write('') # empty file quitApp() def setRestartRequired(state=True): """Set the flag to indicate that the app requires a restart. This function is used by the app to indicate that a restart is required after an update or plugin installation. The flag is checked by the launcher parent process to determine if the app should restart. Parameters ---------- state : bool Set the restart flag. If `True`, the app will restart after quitting. """ global REQUIRES_RESTART REQUIRES_RESTART = bool(state) def isRestartRequired(): """Check if the app requires a restart. Parts of the application may set this flag to indicate that a restart is required after an update or plugin installation. Returns ------- bool `True` if the app requires a restart else `False`. """ return REQUIRES_RESTART def getAppInstance(): """Get a reference to the `PsychoPyApp` object. This function will return `None` if PsychoPy has been imported as a library or the app has not been fully realized. Returns ------- PsychoPyApp or None Handle to the application instance. Returns `None` if the app has not been started yet or the PsychoPy is being used without a GUI. Examples -------- Get the coder frame (if any):: import psychopy.app as app coder = app.getAppInstance().coder """ return _psychopyAppInstance # use a function here to protect the reference def setAppInstance(obj): """ Define a reference to the current PsychoPyApp object. Parameters ---------- obj : psychopy.app._psychopyApp.PsychoPyApp Current instance of the PsychoPy app """ global _psychopyAppInstance _psychopyAppInstance = obj def isAppStarted(): """Check if the GUI portion of PsychoPy is running. Returns ------- bool `True` if the GUI is started else `False`. """ return _psychopyAppInstance is not None def getAppFrame(frameName): """Get the reference to one of PsychoPy's application frames. Returns `None` if the specified frame has not been fully realized yet or PsychoPy is not in GUI mode. Parameters ---------- frameName : str Identifier for the frame to get a reference to. Valid names are 'coder', 'builder' or 'runner'. Returns ------- object or None Reference to the frame instance (i.e. `CoderFrame`, `BuilderFrame` or `RunnerFrame`). `None` is returned if the frame has not been created or the app is not running. May return a list if more than one window is opened. """ if not isAppStarted(): # PsychoPy is not in GUI mode return None if frameName not in ('builder', 'coder', 'runner'): raise ValueError('Invalid identifier specified as `frameName`.') # open the requested frame if no yet loaded frameRef = getattr(_psychopyAppInstance, frameName, None) if frameRef is None: if frameName == 'builder' and hasattr(_psychopyAppInstance, 'showBuilder'): _psychopyAppInstance.showBuilder() elif frameName == 'coder' and hasattr(_psychopyAppInstance, 'showCoder'): _psychopyAppInstance.showCoder() elif frameName == 'runner' and hasattr(_psychopyAppInstance, 'showRunner'): _psychopyAppInstance.showRunner() else: raise AttributeError('Cannot load frame. Method not available.') frameRef = getattr(_psychopyAppInstance, frameName, None) return frameRef if __name__ == "__main__": pass
10,939
Python
.py
258
36.155039
93
0.697067
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,789
ribbon.py
psychopy_psychopy/psychopy/app/ribbon.py
import sys import webbrowser from pathlib import Path import numpy import requests import wx from psychopy.app import utils from psychopy.app import pavlovia_ui as pavui from psychopy.app.pavlovia_ui import sync from psychopy.app.themes import icons, handlers, colors from psychopy.localization import _translate from psychopy.projects import pavlovia class FrameRibbon(wx.Panel, handlers.ThemeMixin): """ Similar to a wx.Toolbar but with labelled sections and the option to add any wx.Window as a ctrl. """ def __init__(self, parent): # initialize panel wx.Panel.__init__(self, parent) # setup sizer self.sizer = wx.BoxSizer(wx.HORIZONTAL) self.SetSizer(self.sizer) # dicts in which to store sections and buttons self.sections = {} self.buttons = {} def addSection(self, name, label=None, icon=None): """ Add a section to the ribbon. Parameters ---------- name : str Name by which to internally refer to this section label : str Label to display on the section icon : str or None File stem of the icon for the section's label Returns ------- FrameRibbonSection The created section handle """ # create section self.sections[name] = sct = FrameRibbonSection( self, label=label, icon=icon ) # add section to sizer self.sizer.Add(sct, border=0, flag=wx.EXPAND | wx.ALL) return sct def addPluginSections(self, group): """ Add any sections to the ribbon which are defined by plugins, targeting the given entry point group. Parameters ---------- group : str Entry point group to look for plugin sections in. Returns ------- list[FrameRubbinPluginSection] List of section objects which were added """ from importlib import metadata # start off with no entry points or sections entryPoints = [] sections = [] # iterate through all entry point groups for thisGroup, eps in metadata.entry_points().items(): # get entry points for matching group if thisGroup == group: # add to list of all entry points entryPoints += eps # iterate through found entry points for ep in entryPoints: try: # load (import) module cls = ep.load() except: # if failed for any reason, skip it continue # if the target is not a subclass of FrameRibbonPluginSection, discard it if not isinstance(cls, type) or not issubclass(cls, FrameRibbonPluginSection): continue # if it's a section, add it sct = cls(parent=self) self.sections[sct.name] = sct sections.append(sct) # add to sizer self.sizer.Add(sct, border=0, flag=wx.EXPAND | wx.ALL) # add separator self.addSeparator() return sections def addButton(self, section, name, label="", icon=None, tooltip="", callback=None, style=wx.BU_NOTEXT): """ Add a button to a given section. Parameters ---------- section : str Name of section to add button to name : str Name by which to internally refer to this button label : str Label to display on this button icon : str Stem of icon to use for this button tooltip : str Tooltip to display on hover callback : function Function to call when this button is clicked style : wx.StyleFlag Style flags from wx to control button appearance Returns ------- FrameRibbonButton The created button handle """ # if section doesn't exist, make it if section not in self.sections: self.addSection(section, label=section) # call addButton method from given section btn = self.sections[section].addButton( name, label=label, icon=icon, tooltip=tooltip, callback=callback, style=style ) return btn def addDropdownButton(self, section, name, label, icon=None, callback=None, menu=None): """ Add a dropdown button to a given section. Parameters ---------- section : str Name of section to add button to name : str Name by which to internally refer to this button label : str Label to display on this button icon : str Stem of icon to use for this button callback : function Function to call when this button is clicked menu : wx.Menu or function Menu to show when the dropdown arrow is clicked, or a function to generate this menu Returns ------- FrameRibbonDropdownButton The created button handle """ # if section doesn't exist, make it if section not in self.sections: self.addSection(section, label=section) # call addButton method from given section btn = self.sections[section].addDropdownButton( name, label=label, icon=icon, callback=callback, menu=menu ) return btn def addSwitchCtrl( self, section, name, labels=("", ""), startMode=0, callback=None, style=wx.HORIZONTAL ): # if section doesn't exist, make it if section not in self.sections: self.addSection(section, label=section) btn = self.sections[section].addSwitchCtrl( name, labels, startMode=startMode, callback=callback, style=style ) return btn def addPavloviaUserCtrl(self, section="pavlovia", name="pavuser", frame=None): # if section doesn't exist, make it if section not in self.sections: self.addSection(section, label=section) # call addButton method from given section btn = self.sections[section].addPavloviaUserCtrl(name=name, ribbon=self, frame=frame) return btn def addPavloviaProjectCtrl(self, section="pavlovia", name="pavproject", frame=None): # if section doesn't exist, make it if section not in self.sections: self.addSection(section, label=section) # call addButton method from given section btn = self.sections[section].addPavloviaProjectCtrl(name=name, ribbon=self, frame=frame) return btn def addSeparator(self): """ Add a vertical line. """ if sys.platform == "win32": # make separator sep = wx.StaticLine(self, style=wx.LI_VERTICAL) # add separator self.sizer.Add(sep, border=6, flag=wx.EXPAND | wx.ALL) else: # on non-Windows, just use a big space self.sizer.AddSpacer(36) def addSpacer(self, size=6, section=None): """ Add a non-streching space. """ # choose sizer to add to if section is None: sizer = self.sizer else: sizer = self.sections[section].sizer # add space sizer.AddSpacer(size=size) def addStretchSpacer(self, prop=1, section=None): """ Add a stretching space. """ # choose sizer to add to if section is None: sizer = self.sizer else: sizer = self.sections[section].sizer # add space sizer.AddStretchSpacer(prop=prop) def _applyAppTheme(self): self.SetBackgroundColour(colors.app['frame_bg']) self.Refresh() class FrameRibbonSection(wx.Panel, handlers.ThemeMixin): """ Section within a FrameRibbon, containing controls marked by a label. Parameters ---------- parent : FrameRibbon Ribbon containing this section label : str Label to display on this section icon : str or None File stem of the icon for the section's label """ def __init__(self, parent, label=None, icon=None): wx.Panel.__init__(self, parent) self.ribbon = 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=0, flag=( wx.EXPAND | wx.ALL | wx.RESERVE_SPACE_EVEN_IF_HIDDEN )) # add label sizer self.labelSizer = wx.BoxSizer(wx.HORIZONTAL) self.border.Add( self.labelSizer, border=6, flag=wx.ALIGN_CENTRE | wx.TOP ) # add label icon self._icon = icons.ButtonIcon(icon, size=16) self.icon = wx.StaticBitmap( self, bitmap=self._icon.bitmap ) if icon is None: self.icon.Hide() self.labelSizer.Add( self.icon, border=6, flag=wx.EXPAND | wx.RIGHT ) # add label text if label is None: label = "" self.label = wx.StaticText(self, label=label, style=wx.ALIGN_CENTRE_HORIZONTAL) self.labelSizer.Add( self.label, flag=wx.EXPAND ) # add space self.border.AddSpacer(6) # dict in which to store buttons self.buttons = {} self._applyAppTheme() def addButton(self, name, label="", icon=None, tooltip="", callback=None, style=wx.BU_NOTEXT): """ Add a button to this section. Parameters ---------- name : str Name by which to internally refer to this button label : str Label to display on this button icon : str Stem of icon to use for this button tooltip : str Tooltip to display on hover callback : function Function to call when this button is clicked style : wx.StyleFlag Style flags from wx to control button appearance Returns ------- FrameRibbonButton The created button handle """ # create button btn = FrameRibbonButton( self, label=label, icon=icon, tooltip=tooltip, callback=callback, style=style ) # store references self.buttons[name] = self.ribbon.buttons[name] = btn # add button to sizer flags = wx.EXPAND if sys.platform == "darwin": # add top padding on Mac flags |= wx.TOP self.sizer.Add(btn, border=12, flag=flags) return btn def addDropdownButton(self, name, label, icon=None, callback=None, menu=None): """ Add a dropdown button to this section. Parameters ---------- name : str Name by which to internally refer to this button label : str Label to display on this button icon : str Stem of icon to use for this button callback : function Function to call when this button is clicked menu : wx.Menu or function Menu to show when the dropdown arrow is clicked, or a function to generate this menu Returns ------- FrameRibbonDropdownButton The created button handle """ # create button btn = FrameRibbonDropdownButton( self, label=label, icon=icon, callback=callback, menu=menu ) # store references self.buttons[name] = self.ribbon.buttons[name] = btn # add button to sizer self.sizer.Add(btn, border=0, flag=wx.EXPAND | wx.ALL) return btn def addSwitchCtrl(self, name, labels=("", ""), startMode=0, callback=None, style=wx.HORIZONTAL): # create button btn = FrameRibbonSwitchCtrl( self, labels, startMode=startMode, callback=callback, style=style ) # store references self.buttons[name] = self.ribbon.buttons[name] = btn # add button to sizer self.sizer.Add(btn, border=0, flag=wx.EXPAND | wx.ALL) return btn def addPavloviaUserCtrl(self, name="pavuser", ribbon=None, frame=None): # substitute ribbon if not given if ribbon is None: ribbon = self.GetParent() # create button btn = PavloviaUserCtrl(self, ribbon=ribbon, frame=frame) # store references self.buttons[name] = self.ribbon.buttons[name] = btn # add button to sizer self.sizer.Add(btn, border=0, flag=wx.EXPAND | wx.ALL) return btn def addPavloviaProjectCtrl(self, name="pavproject", ribbon=None, frame=None): # substitute ribbon if not given if ribbon is None: ribbon = self.GetParent() # create button btn = PavloviaProjectCtrl(self, ribbon=ribbon, frame=frame) # store references self.buttons[name] = self.ribbon.buttons[name] = btn # add button to sizer self.sizer.Add(btn, border=0, flag=wx.EXPAND | wx.ALL) return btn def _applyAppTheme(self): # set color self.SetBackgroundColour(colors.app['frame_bg']) self.SetForegroundColour(colors.app['text']) # set bitmaps again self._icon.reload() self.icon.SetBitmap(self._icon.bitmap) # refresh self.Refresh() class FrameRibbonPluginSection(FrameRibbonSection): """ Subclass of FrameRibbonSection specifically for adding sections to the ribbon via plugins. To add a section, create a subclass of FrameRibbonPluginSection in your plugin and add any buttons you want it to have in the `__init__` function. Then give it an entry point in either "psychopy.app.builder", "psychopy.app.coder" or "psychopy.app.runner" to tell PsychoPy which frame to add it to. """ def __init__(self, parent, name, label=None): # if not given a label, use name if label is None: label = name # store name self.name = name # initialise subclass FrameRibbonSection.__init__( self, parent, label=label, icon="plugin" ) class FrameRibbonButton(wx.Button, handlers.ThemeMixin): """ Button on a FrameRibbon. Parameters ---------- parent : FrameRibbonSection Section containing this button label : str Label to display on this button icon : str Stem of icon to use for this button tooltip : str Tooltip to display on hover callback : function Function to call when this button is clicked style : int Combination of wx button styles to apply """ def __init__(self, parent, label, icon=None, tooltip="", callback=None, style=wx.BU_NOTEXT): # figure out width w = -1 if style | wx.BU_NOTEXT == style: w = 40 # initialize wx.Button.__init__(self, parent, style=wx.BORDER_NONE | style, size=(w, 44)) self.SetMinSize((40, 44)) # set label if label and style | wx.BU_NOTEXT != style: self.SetLabelText(label) # set tooltip if tooltip and style | wx.BU_NOTEXT == style: # if there's no label, include it in the tooltip tooltip = f"{label}: {tooltip}" self.SetToolTip(tooltip) # set icon self._icon = icons.ButtonIcon(icon, size=32) bmpStyle = style & (wx.TOP | wx.BOTTOM | wx.LEFT | wx.RIGHT) # if given, bind callback if callback is not None: self.Bind(wx.EVT_BUTTON, callback) # setup hover behaviour self.Bind(wx.EVT_ENTER_WINDOW, self.onHover) self.Bind(wx.EVT_LEAVE_WINDOW, self.onHover) self._applyAppTheme() def _applyAppTheme(self): # set color self.SetBackgroundColour(colors.app['frame_bg']) self.SetForegroundColour(colors.app['text']) # set bitmaps again self._icon.reload() self.SetBitmap(self._icon.bitmap) self.SetBitmapCurrent(self._icon.bitmap) self.SetBitmapPressed(self._icon.bitmap) self.SetBitmapFocus(self._icon.bitmap) # refresh self.Refresh() def onHover(self, evt): if evt.EventType == wx.EVT_ENTER_WINDOW.typeId: # on hover, lighten background self.SetBackgroundColour(colors.app['panel_bg']) else: # otherwise, keep same colour as parent self.SetBackgroundColour(colors.app['frame_bg']) class FrameRibbonDropdownButton(wx.Panel, handlers.ThemeMixin): def __init__(self, parent, label, icon=None, callback=None, menu=None): wx.Panel.__init__(self, parent) # setup sizer self.sizer = wx.BoxSizer(wx.HORIZONTAL) self.SetSizer(self.sizer) # make button self.button = wx.Button(self, label=label, style=wx.BORDER_NONE) self.sizer.Add(self.button, proportion=1, border=0, flag=wx.EXPAND | wx.ALL) # set icon self._icon = icons.ButtonIcon(icon, size=32) # bind button callback if callback is not None: self.button.Bind(wx.EVT_BUTTON, callback) # make dropdown self.drop = wx.Button(self, label="â–¾", style=wx.BU_EXACTFIT | wx.BORDER_NONE) self.sizer.Add(self.drop, border=0, flag=wx.EXPAND | wx.ALL) # bind menu self.drop.Bind(wx.EVT_BUTTON, self.onMenu) self.menu = menu # setup hover behaviour self.button.Bind(wx.EVT_ENTER_WINDOW, self.onHover) self.button.Bind(wx.EVT_LEAVE_WINDOW, self.onHover) self.drop.Bind(wx.EVT_ENTER_WINDOW, self.onHover) self.drop.Bind(wx.EVT_LEAVE_WINDOW, self.onHover) self._applyAppTheme() def onMenu(self, evt): menu = self.menu # skip if there's no menu if menu is None: return # if menu is created live, create it if callable(menu): menu = menu(self, evt) # show menu self.PopupMenu(menu) def _applyAppTheme(self): # set color for obj in (self, self.button, self.drop): obj.SetBackgroundColour(colors.app['frame_bg']) obj.SetForegroundColour(colors.app['text']) # set bitmaps again self._icon.reload() self.button.SetBitmap(self._icon.bitmap) self.button.SetBitmapCurrent(self._icon.bitmap) self.button.SetBitmapPressed(self._icon.bitmap) self.button.SetBitmapFocus(self._icon.bitmap) # refresh self.Refresh() def onHover(self, evt): if evt.EventType == wx.EVT_ENTER_WINDOW.typeId: # on hover, lighten background evt.EventObject.SetBackgroundColour(colors.app['panel_bg']) else: # otherwise, keep same colour as parent evt.EventObject.SetBackgroundColour(colors.app['frame_bg']) EVT_RIBBON_SWITCH = wx.PyEventBinder(wx.IdManager.ReserveId()) class FrameRibbonSwitchCtrl(wx.Panel, handlers.ThemeMixin): """ A switch with two modes. Use `addDependency` to make presentation of other buttons conditional on this control's state. """ def __init__( self, parent, labels=("", ""), startMode=0, callback=None, style=wx.HORIZONTAL ): wx.Panel.__init__(self, parent) self.parent = parent # use style tag to get text alignment and control orientation alignh = style & (wx.BU_LEFT | wx.BU_RIGHT) alignv = style & (wx.BU_TOP | wx.BU_BOTTOM) alignEach = [alignh | alignv, alignh | alignv] orientation = style & (wx.HORIZONTAL | wx.VERTICAL) # if orientation is horizontal and no h alignment set, wrap text around button if orientation == wx.HORIZONTAL and not alignh: alignEach = [wx.BU_RIGHT | alignv, wx.BU_LEFT | alignv] # setup sizers self.sizer = wx.BoxSizer(wx.HORIZONTAL) self.SetSizer(self.sizer) self.btnSizer = wx.BoxSizer(orientation) # setup depends dict self.depends = [] # make icon self.icon = wx.Button(self, style=wx.BORDER_NONE | wx.BU_NOTEXT | wx.BU_EXACTFIT) self.icon.Bind(wx.EVT_BUTTON, self.onModeToggle) self.icon.Bind(wx.EVT_ENTER_WINDOW, self.onHover) self.icon.Bind(wx.EVT_LEAVE_WINDOW, self.onHover) # make switcher buttons self.btns = [] for i in range(2): btn = wx.Button( self, label=labels[i], size=(-1, 16), style=wx.BORDER_NONE | wx.BU_EXACTFIT | alignEach[i] ) if style & wx.BU_NOTEXT: btn.Hide() self.btnSizer.Add(btn, proportion=orientation == wx.VERTICAL, flag=wx.EXPAND) btn.Bind(wx.EVT_BUTTON, self.onModeSwitch) btn.Bind(wx.EVT_ENTER_WINDOW, self.onHover) btn.Bind(wx.EVT_LEAVE_WINDOW, self.onHover) self.btns.append(btn) # arrange icon/buttons according to style self.sizer.Add(self.btnSizer, proportion=1, border=3, flag=wx.EXPAND | wx.ALL) params = {'border': 6, 'flag': wx.EXPAND | wx.ALL} if orientation == wx.HORIZONTAL: # if horizontal, always put icon in the middle self.btnSizer.Insert(1, self.icon, **params) elif alignh == wx.BU_LEFT: # if left, put icon on left self.sizer.Insert(0, self.icon, **params) else: # if right, put icon on right self.sizer.Insert(1, self.icon, **params) # make icons if orientation == wx.HORIZONTAL: stems = ["switchCtrlLeft", "switchCtrlRight"] size = (32, 16) else: stems = ["switchCtrlTop", "switchCtrlBot"] size = (16, 32) self.icons = [ icons.ButtonIcon(stem, size=size) for stem in stems ] # set starting mode self.setMode(startMode, silent=True) # bind callback if callback is not None: self.Bind(EVT_RIBBON_SWITCH, callback) self.Layout() def _applyAppTheme(self): self.SetBackgroundColour(colors.app['frame_bg']) self.icon.SetBackgroundColour(colors.app['frame_bg']) for mode, btn in enumerate(self.btns): btn.SetBackgroundColour(colors.app['frame_bg']) if mode == self.mode: btn.SetForegroundColour(colors.app['text']) else: btn.SetForegroundColour(colors.app['rt_timegrid']) def onModeSwitch(self, evt): evtBtn = evt.GetEventObject() # iterate through switch buttons for mode, btn in enumerate(self.btns): # if button matches this event... if btn is evtBtn: # change mode self.setMode(mode) def onModeToggle(self, evt=None): if self.mode == 0: self.setMode(1) else: self.setMode(0) def setMode(self, mode, silent=False): # set mode self.mode = mode # iterate through switch buttons for btnMode, btn in enumerate(self.btns): # if it's the correct button... if btnMode == mode: # style accordingly btn.SetForegroundColour(colors.app['text']) else: btn.SetForegroundColour(colors.app['rt_timegrid']) # set icon self.icon.SetBitmap(self.icons[mode].bitmap) # handle depends for depend in self.depends: # get linked ctrl ctrl = depend['ctrl'] # show/enable according to mode if depend['action'] == "show": ctrl.Show(mode == depend['mode']) if depend['action'] == "enable": ctrl.Enable(mode == depend['mode']) # emit event if not silent: evt = wx.CommandEvent(EVT_RIBBON_SWITCH.typeId) evt.SetInt(mode) evt.SetString(self.btns[mode].GetLabel()) wx.PostEvent(self, evt) # refresh self.Refresh() self.Update() self.GetTopLevelParent().Layout() def onHover(self, evt): if evt.EventType == wx.EVT_ENTER_WINDOW.typeId: # on hover, lighten background evt.EventObject.SetForegroundColour(colors.app['text']) else: # otherwise, keep same colour as parent if evt.EventObject is self.btns[self.mode]: evt.EventObject.SetForegroundColour(colors.app['text']) else: evt.EventObject.SetForegroundColour(colors.app['rt_timegrid']) def addDependant(self, ctrl, mode, action="show"): """ Connect another button to one mode of this ctrl such that it is shown/enabled only when this ctrl is in that mode. Parameters ---------- ctrl : wx.Window Control to act upon mode : str The mode in which to show/enable the linked ctrl action : str One of: - "show" Show the control - "enable" Enable the control """ self.depends.append( { 'mode': mode, # when in mode... 'action': action, # then... 'ctrl': ctrl, # to... } ) class PavloviaUserCtrl(FrameRibbonDropdownButton): def __init__(self, parent, ribbon=None, frame=None): # make button FrameRibbonDropdownButton.__init__( self, parent, label=_translate("No user"), icon=None, callback=self.onClick, menu=self.makeMenu ) # add left space self.sizer.InsertSpacer(0, size=6) # store reference to frame and ribbon self.frame = frame self.ribbon = ribbon # let app know about this button self.frame.app.pavloviaButtons['user'].append(self) # update info once now (in case creation happens after logging in) self.updateInfo() # bind deletion behaviour self.Bind(wx.EVT_WINDOW_DESTROY, self.onDelete) self._applyAppTheme() def _applyAppTheme(self): # set color for obj in (self, self.button, self.drop): obj.SetBackgroundColour(colors.app['frame_bg']) obj.SetForegroundColour(colors.app['text']) # refresh self.Refresh() def onDelete(self, evt=None): i = self.frame.app.pavloviaButtons['user'].index(self) self.frame.app.pavloviaButtons['user'].pop(i) def onClick(self, evt): # get user user = pavlovia.getCurrentSession().user # if we have a user, go to profile if user is None: self.onPavloviaLogin() else: webbrowser.open("https://pavlovia.org/%(username)s" % user) @staticmethod def makeMenu(self, evt): # get user user = pavlovia.getCurrentSession().user # make menu menu = wx.Menu() # edit user btn = menu.Append(wx.ID_ANY, _translate("Edit user...")) btn.SetBitmap(icons.ButtonIcon("editbtn", size=16).bitmap) menu.Bind(wx.EVT_MENU, self.onEditPavloviaUser, btn) menu.Enable(btn.GetId(), user is not None) # switch user switchTo = wx.Menu() item = menu.AppendSubMenu(switchTo, _translate("Switch user")) item.SetBitmap(icons.ButtonIcon("view-refresh", size=16).bitmap) for name in pavlovia.knownUsers: if user is None or name != user['username']: btn = switchTo.Append(wx.ID_ANY, name) switchTo.Bind(wx.EVT_MENU, self.onPavloviaSwitchUser, btn) # log in to new user switchTo.AppendSeparator() btn = switchTo.Append(wx.ID_ANY, _translate("New user...")) btn.SetBitmap(icons.ButtonIcon("plus", size=16).bitmap) menu.Bind(wx.EVT_MENU, self.onPavloviaLogin, btn) # log in/out menu.AppendSeparator() if user is not None: btn = menu.Append(wx.ID_ANY, _translate("Log out")) menu.Bind(wx.EVT_MENU, self.onPavloviaLogout, btn) else: btn = menu.Append(wx.ID_ANY, _translate("Log in")) menu.Bind(wx.EVT_MENU, self.onPavloviaLogin, btn) return menu def updateInfo(self): # get user user = pavlovia.getCurrentSession().user if user is None: # if no user, set as defaults self.button.SetLabel(_translate("No user")) icon = icons.ButtonIcon("user_none", size=32).bitmap else: # if there us a user, set username self.button.SetLabel(user['username']) # get icon (use blank if failed) try: content = utils.ImageData(user['avatar_url']) content = content.resize(size=(32, 32)) icon = wx.Bitmap.FromBufferAndAlpha( width=content.size[0], height=content.size[1], data=content.tobytes("raw", "RGB"), alpha=content.tobytes("raw", "A") ) except requests.exceptions.MissingSchema: icon = icons.ButtonIcon("user_none", size=32).bitmap # apply circle mask mask = icons.ButtonIcon("circle_mask", size=32).bitmap.ConvertToImage() icon = icon.ConvertToImage() maskAlpha = numpy.array(mask.GetAlpha(), dtype=int) icon.SetAlpha(numpy.uint8(maskAlpha)) # set icon self.button.SetBitmap(wx.Bitmap(icon)) self.Layout() if self.ribbon is not None: self.ribbon.Layout() def onEditPavloviaUser(self, evt=None): # open edit window dlg = pavui.PavloviaMiniBrowser(parent=self, loginOnly=False) dlg.editUserPage() dlg.ShowModal() # refresh user on close user = pavlovia.getCurrentSession().user user.user = user.user def onPavloviaSwitchUser(self, evt): menu = evt.GetEventObject() item = menu.FindItem(evt.GetId())[0] username = item.GetItemLabel() pavlovia.logout() pavlovia.login(username) def onPavloviaLogin(self, evt=None): pavui.logInPavlovia(self, evt) def onPavloviaLogout(self, evt=None): pavlovia.logout() class PavloviaProjectCtrl(FrameRibbonDropdownButton): def __init__(self, parent, ribbon=None, frame=None): # make button FrameRibbonDropdownButton.__init__( self, parent, label=_translate("No project"), icon=None, callback=self.onClick, menu=self.makeMenu ) # store reference to frame and ribbon self.frame = frame self.ribbon = ribbon # let app know about this button self.frame.app.pavloviaButtons['project'].append(self) # update info once now (in case creation happens after logging in) self.updateInfo() # bind deletion behaviour self.Bind(wx.EVT_WINDOW_DESTROY, self.onDelete) self._applyAppTheme() def _applyAppTheme(self): # set color for obj in (self, self.button, self.drop): obj.SetBackgroundColour(colors.app['frame_bg']) obj.SetForegroundColour(colors.app['text']) # refresh self.Refresh() def onDelete(self, evt=None): i = self.frame.app.pavloviaButtons['project'].index(self) self.frame.app.pavloviaButtons['project'].pop(i) def onClick(self, evt): # get project project = self.GetTopLevelParent().project # if we have a user, go to profile if project is None: webbrowser.open("https://pavlovia.org") else: webbrowser.open(f"https://pavlovia.org/{project.stringId}") @staticmethod def makeMenu(self, evt): # get project project = self.GetTopLevelParent().project # make menu menu = wx.Menu() # create project if project is None: btn = menu.Append(wx.ID_ANY, _translate("New project")) btn.SetBitmap(icons.ButtonIcon("plus", size=16).bitmap) menu.Bind(wx.EVT_MENU, self.onPavloviaCreate, btn) # edit project btn = menu.Append(wx.ID_ANY, _translate("Edit project...")) btn.SetBitmap(icons.ButtonIcon("editbtn", size=16).bitmap) menu.Bind(wx.EVT_MENU, self.onPavloviaProject, btn) menu.Enable(btn.GetId(), project is not None) # search projects menu.AppendSeparator() btn = menu.Append(wx.ID_ANY, _translate("Search projects...")) btn.SetBitmap(icons.ButtonIcon("search", size=16).bitmap) menu.Bind(wx.EVT_MENU, self.onPavloviaSearch, btn) return menu def updateInfo(self): # get project project = self.GetTopLevelParent().project if project is None or project['path_with_namespace'] is None: self.button.SetLabel(_translate("No project")) else: self.button.SetLabel(project['path_with_namespace']) self.Layout() if self.ribbon is not None: self.ribbon.Layout() def onPavloviaSearch(self, evt=None): searchDlg = pavui.search.SearchFrame( app=self.frame.app, parent=self.frame, pos=self.frame.GetPosition()) searchDlg.Show() def onPavloviaProject(self, evt=None): # search again for project if needed (user may have logged in since last looked) if self.frame.filename: self.frame.project = pavlovia.getProject(self.frame.filename) # get project if self.frame.project is not None: self.frame.project.refresh() dlg = pavui.project.ProjectFrame( app=self.frame.app, project=self.frame.project, parent=self.frame ) else: dlg = pavui.project.ProjectFrame(app=self.frame.app) dlg.Show() def onPavloviaCreate(self, evt=None): if Path(self.frame.filename).is_file(): # save file self.frame.fileSave(self.frame.filename) # if allowed by prefs, export html and js files if self.frame._getExportPref('on sync'): htmlPath = self.frame._getHtmlPath(self.frame.filename) if htmlPath: self.frame.fileExport(htmlPath=htmlPath) else: return # get start path and name from builder/coder if possible if self.frame.filename: file = Path(self.frame.filename) name = file.stem path = file.parent else: name = path = "" # open dlg to create new project createDlg = sync.CreateDlg(self.frame, user=pavlovia.getCurrentSession().user, name=name, path=path) if createDlg.ShowModal() == wx.ID_OK and createDlg.project is not None: self.frame.project = createDlg.project else: return # do first sync self.frame.onPavloviaSync()
35,556
Python
.py
901
29.477248
107
0.599131
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,790
psychopyApp.py
psychopy_psychopy/psychopy/app/psychopyApp.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 argparse from pathlib import Path import sys # fix macOS locale-bug on startup: sets locale to LC_ALL (must be defined!) import psychopy.locale_setup # noqa # NB the PsychoPyApp classes moved to _psychopyApp.py as of version 1.78.00 # to allow for better upgrading possibilities from the mac app bundle. this # file now used solely as a launcher for the app, not as the app itself. def main(): from psychopy.app import startApp, quitApp from psychopy.preferences import prefs # parser to process input arguments argParser = argparse.ArgumentParser( prog="PsychoPyApp", description=( """Starts the PsychoPy application. Usage: python psychopy.app [options] [files] Without options or files provided this starts PsychoPy using prefs to decide on the view(s) to open. If optional [files] is provided action depends on the type of the [files]: Python script 'file.py' -- opens coder Experiment design 'file.psyexp' -- opens builder """ ) ) # first argument is always the calling script argParser.add_argument("callscript") # recognise version query argParser.add_argument( "--version", "-v", dest="version", action="store_true", help=( "Print the current PsychoPy version." )) # add option to directly run a script argParser.add_argument( "--direct", "-x", dest="direct", action="store_true", help=( "Use PsychoPy to run a Python script (.py) or a PsychoPy experiment (.psyexp), without " "opening the app." ) ) # add options for starting view argParser.add_argument( "--builder", "-b", dest="startView", const="builder", action="append_const", help=( "Open PsychoPy with a Builder window open. Combine with --coder/-c and --runner/-r " "to open a specific set of frames." ) ) argParser.add_argument( "--coder", "-c", dest="startView", const="coder", action="append_const", help=( "Open PsychoPy with the Coder window open. Combine with --builder/-b and --runner/-r " "to open a specific set of frames." ) ) argParser.add_argument( "--runner", "-r", dest="startView", const="runner", action="append_const", help=( "Open PsychoPy with the Runner window open. Combine with --coder/-c and --builder/-b " "to open a specific set of frames." ) ) # add option to show config wizard argParser.add_argument( "--firstrun", dest="firstRun", action="store_true", help=( "Launches configuration wizard" ) ) # add option to hide splash argParser.add_argument( "--no-splash", dest="showSplash", action="store_false", default=prefs.app['showSplash'], help=( "Suppresses splash screen" ) ) # add option to include app profiling argParser.add_argument( "--profiling", dest="profiling", action="store_true", help=( "Launches app with profiling to see what specific processes are taking up resources." ) ) # parse args args, startFilesRaw = argParser.parse_known_args(sys.argv) # pathify startFiles startFiles = None for thisFile in startFilesRaw: if startFiles is None: startFiles = [] try: startFiles.append(Path(thisFile)) except: print( "Could not interpret {} as a path.".format(thisFile) ) continue # run files directly if requested if args.direct: from psychopy import core import os # make sure there's a file to run assert startFiles, ( "Argument -x was used to directly run a script or experiment, but no script or " "experiment path was given." ) # run all .py scripts from the command line using StandAlone python for targetScript in startFiles: # skip non-runnable files if targetScript.suffix not in (".psyexp", ".py"): print( "Could not run file '{}' as it is not a Python script or PsychoPy experiment." .format(targetScript) ) continue # compile Python code if given a psyexp if targetScript.suffix == ".psyexp": from psychopy import experiment exp = experiment.Experiment.fromFile(targetScript) script = exp.writeScript() targetScript = targetScript.parent / (targetScript.stem + ".py") targetScript.write_text(script, encoding="utf-8") # run file stderr = core.shellCall([sys.executable, targetScript.absolute()], stderr=True) for line in stderr: print(line) sys.exit() # print version info if requested if '-v' in sys.argv or '--version' in sys.argv: from psychopy import __version__ msg = ('PsychoPy3, version %s (c)Jonathan Peirce 2018, GNU GPL license' % __version__) print(msg) sys.exit() if (sys.platform == 'darwin' and ('| packaged by conda-forge |' in sys.version or '|Anaconda' in sys.version)): # On macOS with Anaconda, GUI applications used to need to be run using # `pythonw`. Since we have no way to determine whether this is currently # the case, we run this script again -- ensuring we're definitely using # pythonw. import os env = os.environ PYTHONW = env.get('PYTHONW', 'False') pyw_exe = sys.executable + 'w' # Updated 2024.1.6: as of Python 3, `pythonw` and `python` can be used # interchangeably for wxPython applications on macOS with GUI support. # The defaults and conda-forge channels no longer install python with a # framework build (to do so: `conda install python=3.8 python.app`). # Therefore `pythonw` often doesn't exist, and we can just use `python`. if PYTHONW != 'True' and os.path.isfile(pyw_exe): from psychopy import core cmd = [pyw_exe] + sys.argv stdout, stderr = core.shellCall(cmd, env=dict(env, PYTHONW='True'), stderr=True) print(stdout, file=sys.stdout) print(stderr, file=sys.stderr) sys.exit() else: startApp( startView=args.startView, showSplash=args.showSplash, startFiles=startFiles, firstRun=args.firstRun, profiling=args.profiling ) else: # start app _ = startApp( startView=args.startView, showSplash=args.showSplash, startFiles=startFiles, firstRun=args.firstRun, profiling=args.profiling ) quitApp() if __name__ == '__main__': main()
7,294
Python
.py
176
32.096591
103
0.607887
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,791
preferencesDlg.py
psychopy_psychopy/psychopy/app/preferencesDlg.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import json import sys from pathlib import Path import wx import wx.propgrid as pg import wx.py import platform import re import os from psychopy.app.themes import icons from . import dialogs from psychopy import localization, prefs from psychopy.localization import _translate from packaging.version import Version from psychopy import sound from psychopy.app.utils import getSystemFonts import collections audioLatencyLabels = {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')} class PrefPropGrid(wx.Panel): """Class for the property grid portion of the preference window.""" def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.TAB_TRAVERSAL, name=wx.EmptyString): wx.Panel.__init__( self, parent, id=id, pos=pos, size=size, style=style, name=name) bSizer1 = wx.BoxSizer(wx.HORIZONTAL) self.app = wx.GetApp() # make splitter so panels are resizable self.splitter = wx.SplitterWindow(self) bSizer1.Add(self.splitter, proportion=1, border=6, flag=wx.EXPAND | wx.ALL) # tabs panel self.lstPrefPages = wx.ListCtrl( self.splitter, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.LC_ALIGN_TOP | wx.LC_LIST | wx.LC_SINGLE_SEL) # images for tabs panel prefsImageSize = wx.Size(48, 48) self.prefsIndex = 0 self.prefsImages = wx.ImageList( prefsImageSize.GetWidth(), prefsImageSize.GetHeight()) self.lstPrefPages.AssignImageList(self.prefsImages, wx.IMAGE_LIST_SMALL) # property grid self.proPrefs = pg.PropertyGridManager( self.splitter, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.propgrid.PGMAN_DEFAULT_STYLE | wx.propgrid.PG_BOLD_MODIFIED | wx.propgrid.PG_DESCRIPTION | wx.TAB_TRAVERSAL) self.proPrefs.SetExtraStyle(wx.propgrid.PG_EX_MODE_BUTTONS) # assign panels to splitter self.splitter.SplitVertically( self.lstPrefPages, self.proPrefs ) # move sash to min extent of page ctrls self.splitter.SetMinimumPaneSize(prefsImageSize[0] + 2) if sys.platform == 'win32': # works on windows only since it has a column self.splitter.SetSashPosition(self.lstPrefPages.GetColumnWidth(0)) else: # size that make sense on other platforms self.splitter.SetSashPosition(150) self.SetSizer(bSizer1) self.Layout() # Connect Events self.lstPrefPages.Bind( wx.EVT_LIST_ITEM_DESELECTED, self.OnPrefPageDeselected) self.lstPrefPages.Bind( wx.EVT_LIST_ITEM_SELECTED, self.OnPrefPageSelected) self.proPrefs.Bind(pg.EVT_PG_CHANGED, self.OnPropPageChanged) self.proPrefs.Bind(pg.EVT_PG_CHANGING, self.OnPropPageChanging) # categories and their items are stored here self.sections = collections.OrderedDict() # pages in the property manager self.pages = dict() self.pageNames = dict() # help text self.helpText = dict() self.pageIdx = 0 def __del__(self): pass def setSelection(self, page): """Select the page.""" # set the page self.lstPrefPages.Focus(1) self.lstPrefPages.Select(page) def addPage(self, label, name, sections=(), bitmap=None): """Add a page to the property grid manager.""" if name in self.pages.keys(): raise ValueError("Page already exists.") for s in sections: if s not in self.sections.keys(): self.sections[s] = dict() nbBitmap = icons.ButtonIcon(stem=bitmap, size=(48, 48)).bitmap if nbBitmap.IsOk(): self.prefsImages.Add(nbBitmap) self.pages[self.pageIdx] = (self.proPrefs.AddPage(name, wx.NullBitmap), list(sections)) self.pageNames[name] = self.pageIdx self.lstPrefPages.InsertItem( self.lstPrefPages.GetItemCount(), label, self.pageIdx) self.pageIdx += 1 def addStringItem(self, section, label=wx.propgrid.PG_LABEL, name=wx.propgrid.PG_LABEL, value='', helpText=""): """Add a string property to a category. Parameters ---------- section : str Category name to add the item too. label : str Label to be displayed in the property grid. name : str Internal name for the property. value : str Default value for the property. helpText: str Help text for this item. """ # create a new category if not present if section not in self.sections.keys(): self.sections[section] = dict() # if isinstance(page, str): # page = self.proPrefs.GetPageByName(page) # else # page = self.proPrefs.GetPage(page) self.sections[section].update( {name: wx.propgrid.StringProperty(label, name, value=str(value))}) self.helpText[name] = helpText def addStringArrayItem(self, section, label=wx.propgrid.PG_LABEL, name=wx.propgrid.PG_LABEL, values=(), helpText=""): """Add a string array item.""" if section not in self.sections.keys(): self.sections[section] = dict() self.sections[section].update( {name: wx.propgrid.ArrayStringProperty( label, name, value=[str(i) for i in values])}) self.helpText[name] = helpText def addBoolItem(self, section, label=wx.propgrid.PG_LABEL, name=wx.propgrid.PG_LABEL, value=False, helpText=""): if section not in self.sections.keys(): self.sections[section] = dict() self.sections[section].update( {name: wx.propgrid.BoolProperty(label, name, value)}) self.helpText[name] = helpText def addFileItem(self, section, label=wx.propgrid.PG_LABEL, name=wx.propgrid.PG_LABEL, value='', helpText=""): if section not in self.sections.keys(): self.sections[section] = [] prop = wx.propgrid.FileProperty(label, name, value) self.sections[section].update({name: prop}) prop.SetAttribute(wx.propgrid.PG_FILE_SHOW_FULL_PATH, True) self.helpText[name] = helpText def addDirItem(self, section, label=wx.propgrid.PG_LABEL, name=wx.propgrid.PG_LABEL, value='', helpText=""): if section not in self.sections.keys(): self.sections[section] = dict() self.sections[section].update( {name: wx.propgrid.DirProperty(label, name, value)}) self.helpText[name] = helpText def addIntegerItem(self, section, label=wx.propgrid.PG_LABEL, name=wx.propgrid.PG_LABEL, value=0, helpText=""): """Add an integer property to a category. Parameters ---------- section : str Category name to add the item too. label : str Label to be displayed in the property grid. name : str Internal name for the property. value : int Default value for the property. helpText: str Help text for this item. """ if section not in self.sections.keys(): self.sections[section] = dict() self.sections[section].update( {name: wx.propgrid.IntProperty(label, name, value=int(value))}) self.helpText[name] = helpText def addEnumItem(self, section, label=wx.propgrid.PG_LABEL, name=wx.propgrid.PG_LABEL, labels=(), values=(), value=0, helpText=""): if section not in self.sections.keys(): self.sections[section] = dict() self.sections[section].update({ name: wx.propgrid.EnumProperty(label, name, labels, values, value)}) self.helpText[name] = helpText def populateGrid(self): """Go over pages and add items to the property grid.""" for i in range(self.proPrefs.GetPageCount()): pagePtr, sections = self.pages[i] pagePtr.Clear() for s in sections: _ = pagePtr.Append(pg.PropertyCategory(s, s)) for name, prop in self.sections[s].items(): if name in prefs.legacy: # If this is included in the config file only for legacy, don't show it continue item = pagePtr.Append(prop) # set the appropriate control to edit the attribute if isinstance(prop, wx.propgrid.IntProperty): self.proPrefs.SetPropertyEditor(item, "SpinCtrl") elif isinstance(prop, wx.propgrid.BoolProperty): self.proPrefs.SetPropertyAttribute( item, "UseCheckbox", True) try: self.proPrefs.SetPropertyHelpString( item, self.helpText[item.GetName()]) except KeyError: pass self.proPrefs.SetSplitterLeft() self.setSelection(0) def setPrefVal(self, section, name, value): """Set the value of a preference.""" try: self.sections[section][name].SetValue(value) return True except KeyError: return False def getPrefVal(self, section, name): """Get the value of a preference.""" try: return self.sections[section][name].GetValue() except KeyError: return None def OnPrefPageDeselected(self, event): event.Skip() def OnPrefPageSelected(self, event): sel = self.lstPrefPages.GetFirstSelected() if sel >= 0: self.proPrefs.SelectPage(sel) event.Skip() def OnPropPageChanged(self, event): event.Skip() def OnPropPageChanging(self, event): event.Skip() def isModified(self): return self.proPrefs.IsAnyModified() class PreferencesDlg(wx.Dialog): """Class for a dialog which edits PsychoPy's preferences. """ def __init__(self, app): wx.Dialog.__init__( self, None, id=wx.ID_ANY, title=_translate('PsychoPy Preferences'), pos=wx.DefaultPosition, size=wx.Size(800, 600), style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER) self.app = app self.prefsCfg = self.app.prefs.userPrefsCfg self.prefsSpec = self.app.prefs.prefsSpec self._pages = {} # property grids for each page self.SetSizeHints(wx.DefaultSize, wx.DefaultSize) sbMain = wx.BoxSizer(wx.VERTICAL) self.pnlMain = wx.Panel( self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL) sbPrefs = wx.BoxSizer(wx.VERTICAL) self.proPrefs = PrefPropGrid( self.pnlMain, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.LB_DEFAULT) # add property pages to the manager self.proPrefs.addPage( label=_translate('General'), name='general', sections=['general'], bitmap='preferences-general') self.proPrefs.addPage( label=_translate('Application'), name='app', sections=['app', 'builder', 'coder'], bitmap='preferences-app' ) self.proPrefs.addPage( label=_translate('Pilot mode'), name='piloting', sections=['piloting'], bitmap='preferences-pilot' ) self.proPrefs.addPage( label=_translate('Key Bindings'), name='keyBindings', sections=['keyBindings'], bitmap='preferences-keyboard' ) self.proPrefs.addPage( label=_translate('Hardware'), name='hardware', sections=['hardware'], bitmap='preferences-hardware' ) self.proPrefs.addPage( label=_translate('Connections'), name='connections', sections=['connections'], bitmap='preferences-conn' ) self.proPrefs.populateGrid() sbPrefs.Add(self.proPrefs, 1, wx.EXPAND) self.stlMain = wx.StaticLine( self.pnlMain, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.LI_HORIZONTAL) sbPrefs.Add(self.stlMain, 0, wx.EXPAND | wx.ALL, 5) # dialog controls, have builtin localization sdbControls = wx.BoxSizer(wx.HORIZONTAL) self.sdbControlsHelp = wx.Button(self.pnlMain, wx.ID_HELP, _translate(" Help ")) sdbControls.Add(self.sdbControlsHelp, 0, wx.LEFT | wx.ALL | wx.ALIGN_CENTER_VERTICAL, border=3) sdbControls.AddStretchSpacer() # Add Okay and Cancel buttons self.sdbControlsApply = wx.Button(self.pnlMain, wx.ID_APPLY, _translate(" Apply ")) self.sdbControlsOK = wx.Button(self.pnlMain, wx.ID_OK, _translate(" OK ")) self.sdbControlsCancel = wx.Button(self.pnlMain, wx.ID_CANCEL, _translate(" Cancel ")) if sys.platform == "win32": btns = [self.sdbControlsOK, self.sdbControlsApply, self.sdbControlsCancel] else: btns = [self.sdbControlsCancel, self.sdbControlsApply, self.sdbControlsOK] sdbControls.Add(btns[0], 0, wx.ALL | wx.RIGHT | wx.ALIGN_CENTER_VERTICAL, border=3) sdbControls.Add(btns[1], 0, wx.ALL | wx.RIGHT | wx.ALIGN_CENTER_VERTICAL, border=3) sdbControls.Add(btns[2], 0, wx.ALL | wx.RIGHT | wx.ALIGN_CENTER_VERTICAL, border=3) sbPrefs.Add(sdbControls, flag=wx.ALL | wx.EXPAND, border=3) self.pnlMain.SetSizer(sbPrefs) self.pnlMain.Layout() sbPrefs.Fit(self.pnlMain) sbMain.Add(self.pnlMain, 1, wx.EXPAND | wx.ALL, 8) self.SetSizer(sbMain) self.Layout() self.Centre(wx.BOTH) # Connect Events self.sdbControlsApply.Bind(wx.EVT_BUTTON, self.OnApplyClicked) self.sdbControlsCancel.Bind(wx.EVT_BUTTON, self.OnCancelClicked) self.sdbControlsHelp.Bind(wx.EVT_BUTTON, self.OnHelpClicked) self.sdbControlsOK.Bind(wx.EVT_BUTTON, self.OnOKClicked) # system fonts for font properties self.fontList = ['From theme...'] + list(getSystemFonts(fixedWidthOnly=True)) # valid themes themePath = self.GetTopLevelParent().app.prefs.paths['themes'] self.themeList = [] for file in Path(themePath).glob("*.json"): self.themeList.append(file.stem) # get sound devices for "audioDevice" property try: devnames = sorted(sound.getDevices('output')) except (ValueError, OSError, ImportError, AttributeError): devnames = [] audioConf = self.prefsCfg['hardware']['audioDevice'] self.audioDevDefault = audioConf \ if type(audioConf) is list else list(audioConf) self.audioDevNames = [ dev.replace('\r\n', '') for dev in devnames if dev != self.audioDevDefault] self.populatePrefs() def __del__(self): pass def populatePrefs(self): """Populate pages with property items for each preference.""" # clear pages for sectionName in self.prefsSpec.keys(): prefsSection = self.prefsCfg[sectionName] specSection = self.prefsSpec[sectionName] for prefName in specSection: if prefName in ['version']: # any other prefs not to show? continue # allowModuleImports pref is handled by generateSpec.py # NB if something is in prefs but not in spec then it won't be # shown (removes outdated prefs) thisPref = prefsSection[prefName] thisSpec = specSection[prefName] # for keybindings replace Ctrl with Cmd on Mac if platform.system() == 'Darwin' and \ sectionName == 'keyBindings': if thisSpec.startswith('string'): thisPref = thisPref.replace('Ctrl+', 'Cmd+') # can we translate this pref? pLabel = prefName # get tooltips from comment lines from the spec, as parsed by # configobj helpText = '' hints = self.prefsSpec[sectionName].comments[prefName] # a list if len(hints): # use only one comment line, from right above the pref hint = hints[-1].lstrip().lstrip('#').lstrip() helpText = _translate(hint) if type(thisPref) is bool: # only True or False - use a checkbox self.proPrefs.addBoolItem( sectionName, pLabel, prefName, thisPref, helpText=helpText) # # properties for fonts, dropdown gives a list of system fonts elif prefName in ('codeFont', 'commentFont', 'outputFont'): try: default = self.fontList.index(thisPref) except ValueError: default = 0 labels = [_translate(font) for font in self.fontList] self.proPrefs.addEnumItem( sectionName, pLabel, prefName, labels=labels, values=[i for i in range(len(self.fontList))], value=default, helpText=helpText) elif prefName in ('theme',): try: default = self.themeList.index(thisPref) except ValueError: default = self.themeList.index("PsychopyLight") self.proPrefs.addEnumItem( sectionName, pLabel, prefName, labels=self.themeList, values=[i for i in range(len(self.themeList))], value=default, helpText=helpText) elif prefName == 'locale': thisPref = self.app.prefs.app['locale'] # '' corresponds to system locale locales = [''] + self.app.localization.available try: default = locales.index(thisPref) except ValueError: # set default locale '' default = locales.index('') # '' must be appended after other labels are translated labels = self.app.localization.available.copy() labels.insert(0, _translate('system locale')) self.proPrefs.addEnumItem( sectionName, pLabel, prefName, labels=labels, values=[i for i in range(len(locales))], value=default, helpText=helpText) # # single directory elif prefName in ('unpackedDemosDir',): self.proPrefs.addDirItem( sectionName, pLabel, prefName, thisPref, helpText=helpText) # single file elif prefName in ('flac', 'appKeyGoogleCloud',): self.proPrefs.addFileItem( sectionName, pLabel, prefName, thisPref, helpText=helpText) # window backend items elif prefName == 'winType': from psychopy.visual.backends import getAvailableWinTypes labels = getAvailableWinTypes() default = labels.index('pyglet') # is always included self.proPrefs.addEnumItem( sectionName, pLabel, prefName, labels=labels, values=[i for i in range(len(labels))], value=default, helpText=helpText) # # audio latency mode for the PTB driver elif prefName == 'audioLatencyMode': # get the labels from above labels = [] for val, labl in audioLatencyLabels.items(): labels.append(u'{}: {}'.format(val, labl)) # get the options from the config file spec vals = thisSpec.replace("option(", "").replace("'", "") # item -1 is 'default=x' from spec vals = vals.replace(", ", ",").split(',') try: # set the field to the value in the pref default = int(thisPref) except ValueError: try: # use first if default not in list default = int(vals[-1].strip('()').split('=')[1]) except (IndexError, TypeError, ValueError): # no default default = 0 self.proPrefs.addEnumItem( sectionName, pLabel, prefName, labels=labels, values=[i for i in range(len(labels))], value=default, helpText=helpText) # # option items are given a dropdown, current value is shown # # in the box elif thisSpec.startswith('option') or prefName == 'audioDevice': if prefName == 'audioDevice': options = self.audioDevNames try: default = self.audioDevNames.index( self.audioDevDefault[0]) except ValueError: default = 0 else: vals = thisSpec.replace("option(", "").replace("'", "") # item -1 is 'default=x' from spec vals = vals.replace(", ", ",").split(',') options = vals[:-1] try: # set the field to the value in the pref default = options.index(thisPref) except ValueError: try: # use first if default not in list default = vals[-1].strip('()').split('=')[1] except IndexError: # no default default = 0 labels = [] # display only for opt in options: labels.append(opt) self.proPrefs.addEnumItem( sectionName, pLabel, prefName, labels=labels, values=[i for i in range(len(labels))], value=default, helpText=helpText) if prefName == 'builderLayout': item = self.proPrefs.sections[sectionName][prefName] for i in range(len(item.GetChoices())): choice = item.GetChoices()[i] icon = icons.ButtonIcon(stem=choice.Text).bitmap choice.SetBitmap(icon) # # lists are given a property that can edit and reorder items elif thisSpec.startswith('list'): # list self.proPrefs.addStringArrayItem( sectionName, pLabel, prefName, [str(i) for i in thisPref], helpText) # integer items elif thisSpec.startswith('integer'): # integer self.proPrefs.addIntegerItem( sectionName, pLabel, prefName, thisPref, helpText) # # all other items just use a string field else: self.proPrefs.addStringItem( sectionName, pLabel, prefName, thisPref, helpText) self.proPrefs.populateGrid() def applyPrefs(self): """Write preferences to the current configuration.""" if not self.proPrefs.isModified(): return if platform.system() == 'Darwin': re_cmd2ctrl = re.compile(r'^Cmd\+', re.I) for sectionName in self.prefsSpec: for prefName in self.prefsSpec[sectionName]: if prefName in ['version']: # any other prefs not to show? continue thisPref = self.proPrefs.getPrefVal(sectionName, prefName) # handle special cases if prefName in ('codeFont', 'commentFont', 'outputFont'): self.prefsCfg[sectionName][prefName] = \ self.fontList[thisPref] continue if prefName in ('theme',): self.app.theme = self.prefsCfg[sectionName][prefName] = self.themeList[thisPref] continue elif prefName == 'audioDevice': self.audioDevDefault = [self.audioDevNames[thisPref]] self.prefsCfg[sectionName][prefName] = self.audioDevDefault continue elif prefName == 'locale': # '' corresponds to system locale locales = [''] + self.app.localization.available self.app.prefs.app['locale'] = \ locales[thisPref] self.prefsCfg[sectionName][prefName] = \ locales[thisPref] continue # remove invisible trailing whitespace: if hasattr(thisPref, 'strip'): thisPref = thisPref.strip() # regularize the display format for keybindings if sectionName == 'keyBindings': thisPref = thisPref.replace(' ', '') thisPref = '+'.join([part.capitalize() for part in thisPref.split('+')]) if platform.system() == 'Darwin': # key-bindings were displayed as 'Cmd+O', revert to # 'Ctrl+O' internally thisPref = re_cmd2ctrl.sub('Ctrl+', thisPref) self.prefsCfg[sectionName][prefName] = thisPref # make sure list values are converted back to lists (from str) if self.prefsSpec[sectionName][prefName].startswith('list'): try: # if thisPref is not a null string, do eval() to get a # list. if thisPref == '' or type(thisPref) is list: newVal = thisPref else: newVal = eval(thisPref) except Exception: # if eval() failed, show warning dialog and return pLabel = prefName sLabel = sectionName txt = _translate( 'Invalid value in "%(pref)s" ("%(section)s" Tab)') msg = txt % {'pref': pLabel, 'section': sLabel} title = _translate('Error') warnDlg = dialogs.MessageDialog(parent=self, message=msg, type='Info', title=title) warnDlg.ShowModal() return if type(newVal) is not list: self.prefsCfg[sectionName][prefName] = [newVal] else: self.prefsCfg[sectionName][prefName] = newVal elif self.prefsSpec[sectionName][prefName].startswith('option'): vals = self.prefsSpec[sectionName][prefName].replace( "option(", "").replace("'", "") # item -1 is 'default=x' from spec options = vals.replace(", ", ",").split(',')[:-1] self.prefsCfg[sectionName][prefName] = options[thisPref] self.app.prefs.saveUserPrefs() # includes a validation # maybe then go back and set GUI from prefs again, because validation # may have changed vals? # > sure, why not? - mdc self.populatePrefs() # Update Builder window if needed if self.app.builder: self.app.builder.updateAllViews() # after validation, update the UI self.updateFramesUI() def updateFramesUI(self): """Update the Coder UI (eg. fonts, themes, etc.) from prefs.""" for frame in self.app.getAllFrames(): if frame.frameType == 'builder': frame.layoutPanes() elif frame.frameType == 'coder': # apply settings over document pages for ii in range(frame.notebook.GetPageCount()): doc = frame.notebook.GetPage(ii) doc.theme = prefs.app['theme'] for ii in range(frame.shelf.GetPageCount()): doc = frame.shelf.GetPage(ii) doc.theme = prefs.app['theme'] # apply console font, not handled by theme system ATM if hasattr(frame, 'shell'): frame.shell.setFonts() def OnApplyClicked(self, event): """Apply button clicked, this makes changes to the UI without leaving the preference dialog. This can be used to see the effects of setting changes before closing the dialog. """ self.applyPrefs() # saves the preferences event.Skip() def OnCancelClicked(self, event): event.Skip() def OnHelpClicked(self, event): self.app.followLink(url=self.app.urls["prefs"]) event.Skip() def OnOKClicked(self, event): """Called when OK is clicked. This closes the dialog after applying the settings. """ self.applyPrefs() event.Skip() if __name__ == '__main__': from psychopy import preferences if Version(wx.__version__) < Version('2.9'): app = wx.PySimpleApp() else: app = wx.App(False) # don't do this normally - use the existing psychopy.prefs instance app.prefs = preferences.Preferences() dlg = PreferencesDlg(app) dlg.ShowModal()
32,033
Python
.py
677
31.763663
100
0.534825
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,792
idle.py
psychopy_psychopy/psychopy/app/idle.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 threading import time from collections import OrderedDict import wx from psychopy import prefs, logging from psychopy.constants import NOT_STARTED, STARTED, SKIP, FINISHED from . import connections from psychopy.tools import versionchooser as vc from ..app import pavlovia_ui _t0 = time.time() tasks = OrderedDict() if prefs.connections['allowUsageStats']: tasks['sendUsageStats'] = { 'status': NOT_STARTED, 'func': connections.sendUsageStats, 'tstart': None, 'tEnd': None, 'thread': True, } else: tasks['sendUsageStats'] = { 'status': SKIP, 'func': connections.sendUsageStats, 'tstart': None, 'tEnd': None, 'thread': True, } if prefs.connections['checkForUpdates']: tasks['checkForUpdates'] = { 'status': NOT_STARTED, 'func': connections.getLatestVersionInfo, 'tstart': None, 'tEnd': None, 'thread': True, } else: tasks['checkForUpdates'] = { 'status': SKIP, 'func': connections.getLatestVersionInfo, 'tstart': None, 'tEnd': None, 'thread': True, } tasks['checkNews'] = { 'status': NOT_STARTED, 'func': connections.getNewsItems, 'tstart': None, 'tEnd': None, 'thread': True, } tasks['showTips'] = { 'status': NOT_STARTED, 'func': None, 'tstart': None, 'tEnd': None, 'thread': True, } tasks['updateVersionChooser'] = { 'status': NOT_STARTED, 'func': vc._remoteVersions, 'tstart': None, 'tEnd': None, 'thread': True, } tasks['showNews'] = { 'status': NOT_STARTED, 'func': connections.showNews, 'tstart': None, 'tEnd': None, 'thread': False, } tasks['getPavloviaUser'] = { 'status': NOT_STARTED, 'func': pavlovia_ui.menu.PavloviaMenu.setUser, 'tstart': None, 'tEnd': None, 'thread': False, } currentTask = None def addTask(taskName, func, tstart=None, tend=None, thread=True): """Add an idle task. Parameters ---------- taskName : str Name of the task. func : function Function to be executed. tstart : float, optional Start time of the task. tend : float, optional End time of the task. thread : bool, optional Whether to run the task in a separate thread. """ global tasks if taskName in tasks: logging.warning('Task {} already exists'.format(taskName)) return tasks[taskName] = { 'status': NOT_STARTED, 'func': func, 'tstart': tstart, 'tEnd': tend, 'thread': thread, } def doIdleTasks(app=None): global currentTask if currentTask and currentTask['thread'] and \ currentTask['thread'].is_alive(): # is currently running in a thread return 0 for taskName in tasks: thisTask = tasks[taskName] thisStatus = tasks[taskName]['status'] if thisStatus == NOT_STARTED: currentTask = thisTask currentTask['tStart'] = time.time() - _t0 currentTask['status'] = STARTED logging.debug('Started {} at {}'.format(taskName, currentTask['tStart'])) _doTask(taskName, app) return 0 # something is in motion elif thisStatus == STARTED: if not currentTask['thread'] \ or not currentTask['thread'].is_alive(): # task finished so take note and pick another currentTask['status'] = FINISHED currentTask['thread'] = None currentTask['tEnd'] = time.time() - _t0 logging.debug('Finished {} at {}'.format(taskName, currentTask['tEnd'])) currentTask = None continue else: return 0 logging.flush() return 1 def _doTask(taskName, app): currentTask = tasks[taskName] # what args are needed if taskName == 'updateVersionChooser': args = (True,) else: args = (app,) # if we need a thread then create one and keep track of it if currentTask['thread'] == True: currentTask['thread'] = threading.Thread( target=currentTask['func'], args=args) # currentTask['thread'].daemon = True # kill if the app quits currentTask['thread'].start() else: # otherwise run immediately currentTask['func'](*args) currentTask['status'] = FINISHED currentTask['tEnd'] = time.time() - _t0 logging.debug('Finished {} at {}'.format(taskName, currentTask['tEnd']))
4,960
Python
.py
152
24.940789
79
0.592089
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,793
sysInfoDlg.py
psychopy_psychopy/psychopy/app/sysInfoDlg.py
# -*- coding: utf-8 -*- import wx from pyglet.gl import gl_info, GLint, glGetIntegerv, GL_MAX_ELEMENTS_VERTICES from psychopy import visual, preferences import sys import os import platform class SystemInfoDialog(wx.Dialog): """Dialog for retrieving system information within the PsychoPy app suite. Shows the same information as the 'sysinfo.py' script and provide options to save details to a file or copy them to the clipboard. """ def __init__(self, parent): wx.Dialog.__init__( self, parent, id=wx.ID_ANY, title=u"System Information", pos=wx.DefaultPosition, size=wx.Size(575, 575), style=wx.DEFAULT_DIALOG_STYLE | wx.DIALOG_NO_PARENT) self.SetSizeHintsSz(wx.DefaultSize, wx.DefaultSize) bszMain = wx.BoxSizer(wx.VERTICAL) self.txtSystemInfo = wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, wx.TE_MULTILINE | wx.TE_READONLY) bszMain.Add(self.txtSystemInfo, 1, wx.ALL | wx.EXPAND, 5) gszControls = wx.GridSizer(0, 3, 0, 0) self.cmdCopy = wx.Button( self, wx.ID_ANY, u"C&opy", wx.DefaultPosition, wx.DefaultSize, 0) self.cmdSave = wx.Button( self, wx.ID_ANY, u"&Save", wx.DefaultPosition, wx.DefaultSize, 0) self.cmdClose = wx.Button( self, wx.ID_ANY, u"&Close", wx.DefaultPosition, wx.DefaultSize, 0) self.cmdClose.SetDefault() if sys.platform == "win32": btns = [self.cmdCopy, self.cmdSave, self.cmdClose] else: btns = [self.cmdClose, self.cmdCopy, self.cmdSave] gszControls.Add(btns[0], 0, wx.ALL, 5) gszControls.Add(btns[1], 0, wx.ALL, 5) gszControls.Add(btns[2], 0, wx.ALL, 5) bszMain.Add(gszControls, 0, wx.ALIGN_RIGHT, 5) self.SetSizer(bszMain) self.Layout() self.Centre(wx.BOTH) # Connect Events self.cmdCopy.Bind(wx.EVT_BUTTON, self.OnCopy) self.cmdSave.Bind(wx.EVT_BUTTON, self.OnSave) self.cmdClose.Bind(wx.EVT_BUTTON, self.OnClose) self.txtSystemInfo.SetValue(self.getInfoText()) def getLine(self, *args): """Get a line of text to append to the output.""" return ' '.join([str(i) for i in args]) + '\n' def getInfoText(self): """Get system information text.""" outputText = "" # text to return # show the PsychoPy version from psychopy import __version__ outputText += self.getLine("PsychoPy", __version__) # get system paths outputText += self.getLine("\nPaths to files on the system:") for key in ['userPrefsFile', 'appDataFile', 'demos', 'appFile']: outputText += self.getLine( " %s: %s" % (key, preferences.prefs.paths[key])) # system information such as OS, CPU and memory outputText += self.getLine("\nSystem Info:") outputText += self.getLine( ' '*4, 'Operating System: {}'.format(platform.platform())) outputText += self.getLine( ' ' * 4, 'Processor: {}'.format(platform.processor())) # requires psutil try: import psutil outputText += self.getLine( ' ' * 4, 'CPU freq (MHz): {}'.format(psutil.cpu_freq().max)) outputText += self.getLine( ' ' * 4, 'CPU cores: {} (physical), {} (logical)'.format( psutil.cpu_count(False), psutil.cpu_count())) outputText += self.getLine( ' ' * 4, 'Installed memory: {} (Total), {} (Available)'.format( *psutil.virtual_memory())) except ImportError: outputText += self.getLine(' ' * 4, 'CPU freq (MHz): N/A') outputText += self.getLine( ' ' * 4, 'CPU cores: {} (logical)'.format(os.cpu_count())) outputText += self.getLine(' ' * 4, 'Installed memory: N/A') # if on MacOS if sys.platform == 'darwin': OSXver, junk, architecture = platform.mac_ver() outputText += self.getLine( ' ' * 4, "macOS %s running on %s" % (OSXver, architecture)) # Python information outputText += self.getLine("\nPython info:") outputText += self.getLine(' '*4, 'Executable path:', sys.executable) outputText += self.getLine(' '*4, 'Version:', sys.version) outputText += self.getLine(' ' * 4, '(Selected) Installed Packages:') import numpy outputText += self.getLine(' '*8, "numpy ({})".format( numpy.__version__)) import scipy outputText += self.getLine(' '*8, "scipy ({})".format( scipy.__version__)) import matplotlib outputText += self.getLine(' '*8, "matplotlib ({})".format( matplotlib.__version__)) import pyglet outputText += self.getLine(' '*8, "pyglet ({})".format(pyglet.version)) try: import glfw outputText += self.getLine(' '*8, "PyGLFW ({})".format( glfw.__version__)) except Exception: outputText += self.getLine(' '*8, 'PyGLFW [not installed]') # sound related try: import pyo outputText += self.getLine( ' '*8, "pyo", ('%i.%i.%i' % pyo.getVersion())) except Exception: outputText += self.getLine(' '*8, 'pyo [not installed]') try: import psychtoolbox outputText += self.getLine(' '*8, "psychtoolbox ({})".format( psychtoolbox._version.__version__)) except Exception: outputText += self.getLine(' '*8, 'psychtoolbox [not installed]') # wxpython version try: import wx outputText += self.getLine(' '*8, "wxPython ({})".format( wx.__version__)) except Exception: outputText += self.getLine(' '*8, 'wxPython [not installed]') # get OpenGL details win = visual.Window([100, 100]) # some drivers want a window open first outputText += self.getLine("\nOpenGL Info:") # # get info about the graphics card and drivers outputText += self.getLine( ' '*4, "Vendor:", gl_info.get_vendor()) outputText += self.getLine( ' '*4, "Rendering engine:", gl_info.get_renderer()) outputText += self.getLine( ' '*4, "OpenGL version:", gl_info.get_version()) outputText += self.getLine( ' '*4, "Shaders supported: ", win._haveShaders) # get opengl extensions outputText += self.getLine(' '*4, "(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: outputText += self.getLine( ' '*8, ext + ':', bool(gl_info.have_extension(ext))) # also determine nVertices that can be used in vertex arrays maxVerts = GLint() glGetIntegerv(GL_MAX_ELEMENTS_VERTICES, maxVerts) outputText += self.getLine( ' '*4, 'max vertices in vertex array:', maxVerts.value) win.close() return outputText def OnCopy(self, event): """Copy system information to clipboard.""" # check if we have a selection start, end = self.txtSystemInfo.GetSelection() if start != end: txt = self.txtSystemInfo.GetStringSelection() else: txt = self.txtSystemInfo.GetValue() if wx.TheClipboard.Open(): wx.TheClipboard.SetData(wx.TextDataObject(txt)) wx.TheClipboard.Close() event.Skip() def OnSave(self, event): """Save system information report to a file.""" with wx.FileDialog( self, "Save system information report", wildcard="Text files (*.txt)|*.txt", defaultFile='psychopy_sysinfo.txt', style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) as fileDialog: if fileDialog.ShowModal() == wx.ID_CANCEL: return # the user changed their mind pathname = fileDialog.GetPath() try: with open(pathname, 'w') as file: file.write(self.txtSystemInfo.GetValue()) except IOError: errdlg = wx.MessageDialog( self, "Cannot save to file '%s'." % pathname, "File save error", wx.OK_DEFAULT | wx.ICON_ERROR | wx.CENTRE) errdlg.ShowModal() errdlg.Destroy() event.Skip() def OnClose(self, event): self.Destroy() event.Skip()
9,058
Python
.py
200
34.2
80
0.56681
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,794
jobs.py
psychopy_psychopy/psychopy/app/jobs.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). """Classes and functions for creating and managing subprocesses spawned by the GUI application. These subprocesses are mainly used to perform 'jobs' asynchronously without blocking the main application loop which would otherwise render the UI unresponsive. """ __all__ = [ 'EXEC_SYNC', 'EXEC_ASYNC', 'EXEC_SHOW_CONSOLE', 'EXEC_HIDE_CONSOLE', 'EXEC_MAKE_GROUP_LEADER', 'EXEC_NODISABLE', 'EXEC_NOEVENTS', 'EXEC_BLOCK', 'SIGTERM', 'SIGKILL', 'SIGINT', 'KILL_NOCHILDREN', 'KILL_CHILDREN', 'KILL_OK', 'KILL_BAD_SIGNAL', 'KILL_ACCESS_DENIED', 'KILL_NO_PROCESS', 'KILL_ERROR', 'Job' ] import os.path import wx import os import sys from subprocess import Popen, PIPE from threading import Thread, Event from queue import Queue, Empty import time # Aliases so we don't need to explicitly import `wx`. EXEC_ASYNC = wx.EXEC_ASYNC EXEC_SYNC = wx.EXEC_SYNC EXEC_SHOW_CONSOLE = wx.EXEC_SHOW_CONSOLE EXEC_HIDE_CONSOLE = wx.EXEC_HIDE_CONSOLE EXEC_MAKE_GROUP_LEADER = wx.EXEC_MAKE_GROUP_LEADER EXEC_NODISABLE = wx.EXEC_NODISABLE EXEC_NOEVENTS = wx.EXEC_NOEVENTS EXEC_BLOCK = wx.EXEC_BLOCK # Signal enumerations for `wx.Process.Kill`, only use the one here that work on # all platforms. SIGTERM = wx.SIGTERM SIGKILL = wx.SIGKILL SIGINT = wx.SIGINT # Flags for wx.Process.Kill`. KILL_NOCHILDREN = wx.KILL_NOCHILDREN KILL_CHILDREN = wx.KILL_CHILDREN # yeesh ... # Error values for `wx.Process.Kill` KILL_OK = wx.KILL_OK KILL_BAD_SIGNAL = wx.KILL_BAD_SIGNAL KILL_ACCESS_DENIED = wx.KILL_ACCESS_DENIED KILL_NO_PROCESS = wx.KILL_NO_PROCESS KILL_ERROR = wx.KILL_ERROR # PIPE_READER_POLL_INTERVAL = 0.025 # seconds class PipeReader(Thread): """Thread for reading standard stream pipes. This is used by the `Job` class to provide non-blocking reads of pipes. Parameters ---------- fdpipe : Any File descriptor for the pipe, either `Popen.stdout` or `Popen.stderr`. """ def __init__(self, fdpipe): # setup the `Thread` stuff super(PipeReader, self).__init__() self.daemon = True self._fdpipe = fdpipe # pipe file descriptor # queue objects for passing bytes to the main thread self._queue = Queue(maxsize=1) # Overflow buffer if the queue is full, prevents data loss if the # application isn't reading the pipe quick enough. self._overflowBuffer = [] # used to signal to the thread that it's time to stop self._stopSignal = Event() self._closedSignal = Event() @property def isAvailable(self): """Are there bytes available to be read (`bool`)?""" if self._queue.full(): return True elif self._overflowBuffer: # have leftover bytes self._queue.put("".join(self._overflowBuffer)) self._overflowBuffer = [] # clear the overflow buffer return True else: return False def read(self): """Read all bytes enqueued by the thread coming off the pipe. This is a non-blocking operation. The value `''` is returned if there is no new data on the pipe since the last `read()` call. Returns ------- bytes Most recent data passed from the subprocess since the last `read()` call. """ try: return self._queue.get_nowait() except Empty: return '' def run(self): """Payload routine for the thread. This reads bytes from the pipe and enqueues them. """ # read bytes in chunks until EOF for pipeBytes in iter(self._fdpipe.readline, b''): # put bytes into the queue, handle overflows if the queue is full if not self._queue.full(): # we have room, check if we have a backlog of bytes to send if self._overflowBuffer: pipeBytes = "".join(self._overflowBuffer) + pipeBytes self._overflowBuffer = [] # clear the overflow buffer # write bytes to the queue self._queue.put(pipeBytes) else: # Put bytes into buffer if the queue hasn't been emptied quick # enough. These bytes will be passed along once the queue has # space. self._overflowBuffer.append(pipeBytes) if self._stopSignal.is_set(): break self._closedSignal.set() def stop(self): """Call this to signal the thread to stop reading bytes.""" self._stopSignal.set() while not self._closedSignal.is_set(): time.sleep(0.01) return self._fdpipe class Job: """General purpose class for running subprocesses using wxPython's subprocess framework. This class should only be instanced and used if the GUI is present. Parameters ---------- command : list or tuple Command to execute when the job is started. Similar to who you would specify the command to `Popen`. terminateCallback : callable Callback function to call when the process exits. This can be used to inform the application that the subprocess is done. inputCallback : callable Callback function called when `poll` is invoked and the input pipe has data. Data is passed to the first argument of the callable object. errorCallback : callable Callback function called when `poll` is invoked and the error pipe has data. Data is passed to the first argument of the callable object. You may set `inputCallback` and `errorCallback` using the same function. extra : dict or None Dict of extra variables to be accessed by callback functions, use None for a blank dict. Examples -------- Spawn a new subprocess:: # command to execute command = 'python3 myScript.py' # create a new job object job = Job(command, flags=EXEC_ASYNC) # start it pid = job.start() # returns a PID for the sub process """ def __init__(self, parent, command='', terminateCallback=None, inputCallback=None, errorCallback=None, extra=None): # use the app instance if parent isn't given if parent is None: from psychopy.app import getAppInstance parent = getAppInstance() # command to be called, cannot be changed after spawning the process self.parent = parent self._command = command self._pid = None # self._flags = flags # unused right now self._process = None # self._pollMillis = None # self._pollTimer = wx.Timer() # user defined callbacks self._inputCallback = None self._errorCallback = None self._terminateCallback = None self.inputCallback = inputCallback self.errorCallback = errorCallback self.terminateCallback = terminateCallback # user defined additional info if extra is None: extra = {} self.extra = extra # non-blocking pipe reading threads and FIFOs self._stdoutReader = None self._stderrReader = None def start(self, cwd=None, env=None): """Start the subprocess. Parameters ---------- cwd : str or None Working directory for the subprocess. Leave `None` to use the same as the application. env : dict or None Environment variables to pass to the subprocess. Leave `None` to use the same as the application. Returns ------- int Process ID assigned by the operating system. """ # NB - keep these lines since we will use them once the bug in # `wx.Execute` is fixed. # # create a new process object, this handles streams and stuff # self._process = wx.Process(None, -1) # self._process.Redirect() # redirect streams from subprocess # start the sub-process command = self._command # # subprocess inherits the environment of the parent process if env is None: scriptEnv = os.environ.copy() else: scriptEnv = env # remove some environment variables that can cause issues if 'PYTHONSTARTUP' in scriptEnv: del scriptEnv['PYTHONSTARTUP'] # Set encoding for text mode pipes, needs to be explicitly set or we # crash on windows scriptEnv['PYTHONIOENCODING'] = 'utf-8' if sys.platform == 'win32': scriptEnv['PYTHONLEGACYWINDOWSSTDIO'] = 'utf-8' try: self._process = Popen( args=command, bufsize=1, executable=None, stdin=None, stdout=PIPE, stderr=PIPE, preexec_fn=None, shell=False, cwd=cwd, env=scriptEnv, # universal_newlines=True, # gives us back a string instead of bytes creationflags=0, text=False, encoding='utf-8' ) except FileNotFoundError: return -1 # negative PID means failure # get the PID self._pid = self._process.pid # setup asynchronous readers of the subprocess pipes self._stdoutReader = PipeReader(self._process.stdout) self._stderrReader = PipeReader(self._process.stderr) self._stdoutReader.start() self._stderrReader.start() # bind the event called when the process ends # self._process.Bind(wx.EVT_END_PROCESS, self.onTerminate) self.parent.Bind(wx.EVT_IDLE, self.poll) return self._pid def terminate(self): """Terminate the subprocess associated with this object. Return ------ bool `True` if the terminate call was successful in ending the subprocess. If `False`, something went wrong and you should try and figure it out. """ if not self.isRunning: return False # nop self.parent.Unbind(wx.EVT_IDLE) # isOk = wx.Process.Kill(self._pid, signal, flags) is wx.KILL_OK self._process.kill() # kill the process #self._pollTimer.Stop() # Wait for the process to exit completely, return code will be incorrect # if we don't. if self._process is not None: processStillRunning = True while processStillRunning: wx.Yield() # yield to the GUI main loop if self._process is None: processStillRunning = False continue processStillRunning = self._process.poll() is None time.sleep(0.1) # sleep a bit to avoid CPU over-utilization # get the return code of the subprocess retcode = self._process.returncode else: retcode = 0 self.onTerminate(retcode) return retcode is None @property def command(self): """Shell command to execute (`list`). Same as the `command` argument. Raises an error if this value is changed after `start()` was called. """ return self._command @command.setter def command(self, val): if self.isRunning: raise AttributeError( 'Cannot set property `command` if the subprocess is running!') self._command = val @property def flags(self): """Subprocess execution option flags (`int`). """ return self._flags @flags.setter def flags(self, val): if self.isRunning: raise AttributeError( 'Cannot set property `flags` if the subprocess is running!') self._flags = val @property def isRunning(self): """Is the subprocess running (`bool`)? If `True` the value of the `command` property cannot be changed. """ return self._pid != 0 and self._process is not None @property def pid(self): """Process ID for the active subprocess (`int`). Only valid after the process has been started. """ return self._pid def getPid(self): """Process ID for the active subprocess. Only valid after the process has been started. Returns ------- int or None Process ID assigned to the subprocess by the system. Returns `None` if the process has not been started. """ return self._pid # def setPriority(self, priority): # """Set the subprocess priority. Has no effect if the process has not # been started. # # Parameters # ---------- # priority : int # Process priority from 0 to 100, where 100 is the highest. Values # will be clipped between 0 and 100. # # """ # if self._process is None: # return # # priority = max(min(int(priority), 100), 0) # clip range # self._process.SetPriority(priority) # set it @property def inputCallback(self): """Callback function called when data is available on the input stream pipe (`callable` or `None`). """ return self._inputCallback @inputCallback.setter def inputCallback(self, val): self._inputCallback = val @property def errorCallback(self): """Callback function called when data is available on the error stream pipe (`callable` or `None`). """ return self._errorCallback @errorCallback.setter def errorCallback(self, val): self._errorCallback = val @property def terminateCallback(self): """Callback function called when the subprocess is terminated (`callable` or `None`). """ return self._terminateCallback @terminateCallback.setter def terminateCallback(self, val): self._terminateCallback = val # @property # def pollMillis(self): # """Polling interval for input and error pipes (`int` or `None`). # """ # return self._pollMillis # @pollMillis.setter # def pollMillis(self, val): # if isinstance(val, (int, float)): # self._pollMillis = int(val) # elif val is None: # self._pollMillis = None # else: # raise TypeError("Value must be must be `int` or `None`.") # # if not self._pollTimer.IsRunning(): # return # # if self._pollMillis is None: # if `None`, stop the timer # self._pollTimer.Stop() # else: # self._pollTimer.Start(self._pollMillis, oneShot=wx.TIMER_CONTINUOUS) # ~~~ # NB - Keep these here commented until wxPython fixes the `env` bug with # `wx.Execute`. Hopefully someday we can use that again and remove all # this stuff with threads which greatly simplifies this class. # ~~~ # # @property # def isOutputAvailable(self): # """`True` if the output pipe to the subprocess is opened (therefore # writeable). If not, you cannot write any bytes to 'outputStream'. Some # subprocesses may signal to the parent process that its done processing # data by closing its input. # """ # if self._process is None: # return False # # return self._process.IsInputOpened() # # @property # def outputStream(self): # """Handle to the file-like object handling the standard output stream # (`ww.OutputStream`). This is used to write bytes which will show up in # the 'stdin' pipe of the subprocess. # """ # if not self.isRunning: # return None # # return self._process.OutputStream @property def isInputAvailable(self): """Check if there are bytes available to be read from the input stream (`bool`). """ if self._process is None: return False return self._stdoutReader.isAvailable def getInputData(self): """Get any new data which has shown up on the input pipe (stdout of the subprocess). Returns ------- str Data as a string. Returns and empty string if there is no new data. """ if self._process is None: return if self._stdoutReader.isAvailable: return self._stdoutReader.read() return '' # @property # def inputStream(self): # """Handle to the file-like object handling the standard input stream # (`wx.InputStream`). This is used to read bytes which the subprocess is # writing to 'stdout'. # """ # if not self.isRunning: # return None # # return self._process.InputStream @property def isErrorAvailable(self): """Check if there are bytes available to be read from the error stream (`bool`). """ if self._process is None: return False return self._stderrReader.isAvailable def getErrorData(self): """Get any new data which has shown up on the error pipe (stderr of the subprocess). Returns ------- str Data as a string. Returns and empty string if there is no new data. """ if self._process is None: return if self._stderrReader.isAvailable: return self._stderrReader.read() return '' # @property # def errorStream(self): # """Handle to the file-like object handling the standard error stream # (`wx.InputStream`). This is used to read bytes which the subprocess is # writing to 'stderr'. # """ # if not self.isRunning: # return None # # return self._process.ErrorStream def _readPipes(self): """Read data available on the pipes.""" # get data from pipes if self.isInputAvailable: stdinText = self.getInputData() if self._inputCallback is not None: wx.CallAfter(self._inputCallback, stdinText) if self.isErrorAvailable: stderrText = self.getErrorData() if self._errorCallback is not None: wx.CallAfter(self._errorCallback, stderrText) def poll(self, evt=None): """Poll input and error streams for data, pass them to callbacks if specified. Input stream data is processed before error. """ if self._process is None: # do nothing if there is no process return # poll the subprocess retCode = self._process.poll() if retCode is not None: # process has exited? # unbind the idle loop used to poll the subprocess self.parent.Bind(wx.EVT_IDLE, None) time.sleep(0.1) # give time for pipes to flush wx.CallAfter(self.onTerminate, retCode) # get data from pipes self._readPipes() def onTerminate(self, exitCode): """Called when the process exits. Override for custom functionality. Right now we're just stopping the polling timer, doing a final `poll` to empty out the remaining data from the pipes and calling the user specified `terminateCallback`. If there is any data left in the pipes, it will be passed to the `_inputCallback` and `_errorCallback` before `_terminateCallback` is called. """ # if self._pollTimer.IsRunning(): # self._pollTimer.Stop() self._readPipes() # read remaining data # catch remaining data for i, p in enumerate((self._stdoutReader, self._stderrReader)): subprocPipeFd = p.stop() subprocPipeFd.flush() pipeBytes = subprocPipeFd.read() wx.CallAfter( self._inputCallback if i == 0 else self._errorCallback, pipeBytes) # flush remaining bytes, write out self._stdoutReader.join(timeout=1) self._stderrReader.join(timeout=1) # if callback is provided, else nop if self._terminateCallback is not None: wx.CallAfter(self._terminateCallback, self._pid, exitCode) self._process = self._pid = None # reset # self._flags = 0 # def onNotify(self): # """Called when the polling timer elapses. # # Default action is to read input and error streams and broadcast any data # to user defined callbacks (if `poll()` has not been overwritten). # """ # self.poll() def __del__(self): """Called when the object is garbage collected or deleted.""" try: if hasattr(self, '_process'): if self._process is not None: self._process.kill() except (ValueError, AttributeError): pass if __name__ == "__main__": pass
21,514
Python
.py
565
29.716814
85
0.609128
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,795
codeEditorBase.py
psychopy_psychopy/psychopy/app/coder/codeEditorBase.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Provides class BaseCodeEditor; base class for CodeEditor class in Coder and CodeBox class in dlgCode (code component) """ # 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.stc from ..themes import handlers from psychopy.localization import _translate class BaseCodeEditor(wx.stc.StyledTextCtrl, handlers.ThemeMixin): """Provides base class for code editors See the wxPython demo styledTextCtrl 2. """ def __init__(self, parent, ID, pos, size, style): wx.stc.StyledTextCtrl.__init__(self, parent, ID, pos, size, style) self.notebook = parent self.UNSAVED = False self.filename = "" self.fileModTime = None # was file modified outside of CodeEditor self.AUTOCOMPLETE = True self.autoCompleteDict = {} self._commentType = {'Py': '#', 'JS': '//', 'Both': '//' or '#'} # doesn't pause strangely self.locals = None # will contain the local environment of the script self.prevWord = None # remove some annoying stc key commands CTRL = wx.stc.STC_SCMOD_CTRL self.CmdKeyClear(ord('['), CTRL) self.CmdKeyClear(ord(']'), CTRL) self.CmdKeyClear(ord('/'), CTRL) self.CmdKeyClear(ord('/'), CTRL | wx.stc.STC_SCMOD_SHIFT) # 4 means 'tabs are bad'; 1 means 'flag inconsistency' self.SetMargins(0, 0) self.SetUseTabs(False) self.SetTabWidth(4) self.SetIndent(4) self.SetBufferedDraw(False) self.SetEOLMode(wx.stc.STC_EOL_LF) # setup margins for line numbers self.SetMarginType(0, wx.stc.STC_MARGIN_NUMBER) self.Bind(wx.EVT_IDLE, self.onIdle) # Setup a margin to hold fold markers self.SetMarginType(1, wx.stc.STC_MARGIN_SYMBOL) self.SetMarginMask(1, wx.stc.STC_MASK_FOLDERS) self.SetMarginSensitive(1, True) self.SetMarginWidth(1, 12) # Set what kind of events will trigger a modified event self.SetModEventMask(wx.stc.STC_MOD_DELETETEXT | wx.stc.STC_MOD_INSERTTEXT) # Bind context menu self.Bind(wx.EVT_CONTEXT_MENU, self.OnContextMenu) def onIdle(self, evt): # update margin width to fit number of characters in biggest line num n = len(str(self.GetNumberOfLines())) self.SetMarginWidth(0, self.GetTextExtent("M")[0] * n) evt.Skip() def OnContextMenu(self, event): """Sets the context menu for components using code editor base class""" if not hasattr(self, "UndoID"): # Create a new ID for all items self.UndoID = wx.NewIdRef(count=1) self.RedoID = wx.NewIdRef(count=1) self.CutID = wx.NewIdRef(count=1) self.CopyID = wx.NewIdRef(count=1) self.PasteID = wx.NewIdRef(count=1) self.DeleteID = wx.NewIdRef(count=1) self.SelectAllID = wx.NewIdRef(count=1) # Bind items to relevant method self.Bind(wx.EVT_MENU, self.onUndo, id=self.UndoID) self.Bind(wx.EVT_MENU, self.onRedo, id=self.RedoID) self.Bind(wx.EVT_MENU, self.onCut, id=self.CutID) self.Bind(wx.EVT_MENU, self.onCopy, id=self.CopyID) self.Bind(wx.EVT_MENU, self.onPaste, id=self.PasteID) self.Bind(wx.EVT_MENU, self.onDelete, id=self.DeleteID) self.Bind(wx.EVT_MENU, self.onSelectAll, id=self.SelectAllID) # Create menu and menu items menu = wx.Menu() undoItem = wx.MenuItem(menu, self.UndoID, _translate("Undo")) redoItem = wx.MenuItem(menu, self.RedoID, _translate("Redo")) cutItem = wx.MenuItem(menu, self.CutID, _translate("Cut")) copyItem = wx.MenuItem(menu, self.CopyID, _translate("Copy")) pasteItem = wx.MenuItem(menu, self.PasteID, _translate("Paste")) deleteItem = wx.MenuItem(menu, self.DeleteID, _translate("Delete")) selectItem = wx.MenuItem(menu, self.SelectAllID, _translate("Select All")) # Append items to menu menu.Append(undoItem) menu.Append(redoItem) menu.AppendSeparator() menu.Append(cutItem) menu.Append(copyItem) menu.Append(pasteItem) menu.AppendSeparator() menu.Append(deleteItem) menu.Append(selectItem) # Check whether items should be enabled undoItem.Enable(self.CanUndo()) redoItem.Enable(self.CanRedo()) cutItem.Enable(self.CanCut()) copyItem.Enable(self.CanCopy()) pasteItem.Enable(self.CanPaste()) deleteItem.Enable(self.CanCopy()) self.PopupMenu(menu) menu.Destroy() def onUndo(self, event): """For context menu Undo""" foc = self.FindFocus() if hasattr(foc, 'Undo'): foc.Undo() def onRedo(self, event): """For context menu Redo""" foc = self.FindFocus() if hasattr(foc, 'Redo'): foc.Redo() def onCut(self, event): """For context menu Cut""" foc = self.FindFocus() if hasattr(foc, 'Cut'): foc.Cut() def onCopy(self, event): """For context menu Copy""" foc = self.FindFocus() if hasattr(foc, 'Copy'): foc.Copy() def onPaste(self, event): """For context menu Paste""" foc = self.FindFocus() if hasattr(foc, 'Paste'): foc.Paste() def onSelectAll(self, event): """For context menu Select All""" foc = self.FindFocus() if hasattr(foc, 'SelectAll'): foc.SelectAll() def onDelete(self, event): """For context menu Delete""" foc = self.FindFocus() if hasattr(foc, 'DeleteBack'): foc.DeleteBack() def OnKeyPressed(self, event): pass def HashtagCounter(self, text, nTags=0): # Hashtag counter - counts lines beginning with hashtags in selected text for lines in text.splitlines(): if lines.startswith('#'): nTags += 1 elif lines.startswith('//'): nTags += 2 return nTags def toggleCommentLines(self): codeType = "Py" if hasattr(self, "codeType"): codeType = self.codeType startText, endText = self._GetPositionsBoundingSelectedLines() nLines = len(self._GetSelectedLineNumbers()) nHashtags = self.HashtagCounter(self.GetTextRange(startText, endText)) passDec = False # pass decision - only pass if line is blank # Test decision criteria, and catch division errors # when caret starts at line with no text, or at beginning of line... try: devCrit, decVal = .6, nHashtags / nLines # Decision criteria and value except ZeroDivisionError: if self.LineLength(self.GetCurrentLine()) == 1: self._ReplaceSelectedLines(self._commentType[codeType]) devCrit, decVal, passDec = 1, 0, True else: self.CharRightExtend() # Move caret so line is counted devCrit, decVal = .6, nHashtags / len(self._GetSelectedLineNumbers()) newText = '' # Add or remove hashtags/JS comments from selected text, but pass if # added tp blank line if decVal < devCrit and passDec == False: for lineNo in self._GetSelectedLineNumbers(): lineText = self.GetLine(lineNo) newText = newText + self._commentType[codeType] + lineText elif decVal >= devCrit and passDec == False: for lineNo in self._GetSelectedLineNumbers(): lineText = self.GetLine(lineNo) if lineText.startswith(self._commentType[codeType]): lineText = lineText[len(self._commentType[codeType]):] newText = newText + lineText self._ReplaceSelectedLines(newText) def _GetSelectedLineNumbers(self): # used for the comment/uncomment machinery from ActiveGrid selStart, selEnd = self._GetPositionsBoundingSelectedLines() start = self.LineFromPosition(selStart) end = self.LineFromPosition(selEnd) if selEnd == self.GetTextLength(): end += 1 return list(range(start, end)) def _GetPositionsBoundingSelectedLines(self): # used for the comment/uncomment machinery from ActiveGrid startPos = self.GetCurrentPos() endPos = self.GetAnchor() if startPos > endPos: startPos, endPos = endPos, startPos if endPos == self.PositionFromLine(self.LineFromPosition(endPos)): # If it's at the very beginning of a line, use the line above it # as the ending line endPos = endPos - 1 selStart = self.PositionFromLine(self.LineFromPosition(startPos)) selEnd = self.PositionFromLine(self.LineFromPosition(endPos) + 1) return selStart, selEnd def _ReplaceSelectedLines(self, text): # used for the comment/uncomment machinery from ActiveGrid # If multi line selection - keep lines selected # For single lines, move to next line and select that line if len(text) == 0: return selStart, selEnd = self._GetPositionsBoundingSelectedLines() self.SetSelection(selStart, selEnd) self.ReplaceSelection(text) if len(text.splitlines()) > 1: self.SetSelection(selStart, selStart + len(text)) else: self.SetSelection( self.GetCurrentPos(), self.GetLineEndPosition(self.GetCurrentLine())) def smartIdentThisLine(self): codeType = "Py" if hasattr(self, "codeType"): codeType = self.codeType startLineNum = self.LineFromPosition(self.GetSelectionStart()) endLineNum = self.LineFromPosition(self.GetSelectionEnd()) prevLine = self.GetLine(startLineNum - 1) prevIndent = self.GetLineIndentation(startLineNum - 1) signal = {'Py': ':', 'JS': '{'} # set the indent self.SetLineIndentation(startLineNum, prevIndent) self.VCHome() # check for a colon (Python) or curly brace (JavaScript) to signal an indent prevLogical = prevLine.split(self._commentType[codeType])[0] prevLogical = prevLogical.strip() if len(prevLogical) > 0 and prevLogical[-1] == signal[codeType]: self.CmdKeyExecute(wx.stc.STC_CMD_TAB) elif len(prevLogical) > 0 and prevLogical[-1] == '}' and codeType == 'JS': self.CmdKeyExecute(wx.stc.STC_SCMOD_SHIFT + wx.stc.STC_CMD_TAB) def smartIndent(self): # find out about current positions and indentation startLineNum = self.LineFromPosition(self.GetSelectionStart()) endLineNum = self.LineFromPosition(self.GetSelectionEnd()) prevLine = self.GetLine(startLineNum - 1) prevIndent = self.GetLineIndentation(startLineNum - 1) startLineIndent = self.GetLineIndentation(startLineNum) # calculate how much we need to increment/decrement the current lines incr = prevIndent - startLineIndent # check for a colon to signal an indent decrease prevLogical = prevLine.split('#')[0] prevLogical = prevLogical.strip() if len(prevLogical) > 0 and prevLogical[-1] == ':': incr = incr + 4 # set each line to the correct indentation self.BeginUndoAction() for lineNum in range(startLineNum, endLineNum + 1): thisIndent = self.GetLineIndentation(lineNum) self.SetLineIndentation(lineNum, thisIndent + incr) self.EndUndoAction() def shouldTrySmartIndent(self): # used when the user presses tab key: decide whether to insert # a tab char or whether to smart indent text # if some text has been selected then use indentation if len(self.GetSelectedText()) > 0: return True # test whether any text precedes current pos lineText, posOnLine = self.GetCurLine() textBeforeCaret = lineText[:posOnLine] if textBeforeCaret.split() == []: return True else: return False def indentSelection(self, howFar=4): # Indent or outdent current selection by 'howFar' spaces # (which could be positive or negative int). startLineNum = self.LineFromPosition(self.GetSelectionStart()) endLineNum = self.LineFromPosition(self.GetSelectionEnd()) # go through line-by-line self.BeginUndoAction() for lineN in range(startLineNum, endLineNum + 1): newIndent = self.GetLineIndentation(lineN) + howFar if newIndent < 0: newIndent = 0 self.SetLineIndentation(lineN, newIndent) self.EndUndoAction() def Paste(self, event=None): dataObj = wx.TextDataObject() clip = wx.Clipboard().Get() clip.Open() success = clip.GetData(dataObj) clip.Close() if success: txt = dataObj.GetText() self.ReplaceSelection(txt.replace("\r\n", "\n").replace("\r", "\n")) self.analyseScript() def analyseScript(self): """Analyse the script.""" pass @property def edgeGuideVisible(self): return self.GetEdgeMode() != wx.stc.STC_EDGE_NONE @edgeGuideVisible.setter def edgeGuideVisible(self, value): if value is True: self.SetEdgeMode(wx.stc.STC_EDGE_LINE) else: self.SetEdgeMode(wx.stc.STC_EDGE_NONE) @property def edgeGuideColumn(self): return self.GetEdgeColumn() @edgeGuideColumn.setter def edgeGuideColumn(self, value): self.SetEdgeColumn(value) # def _applyAppTheme(self, target=None): # """Overrides theme change from ThemeMixin. # Don't call - this is called at the end of theme.setter""" # # ThemeMixin._applyAppTheme() # only needed for children # spec = ThemeMixin.codeColors # base = spec['base'] # # # Check for language specific spec # if self.GetLexer() in self.lexers: # lexer = self.lexers[self.GetLexer()] # else: # lexer = 'invlex' # if lexer in spec: # # If there is lang specific spec, delete subkey... # lang = spec[lexer] # del spec[lexer] # #...and append spec to root, overriding any generic spec # spec.update({key: lang[key] for key in lang}) # else: # lang = {} # # # Override base font with user spec if present # key = 'outputFont' if isinstance(self, wx.py.shell.Shell) else 'codeFont' # if prefs.coder[key] != "From theme...": # base['font'] = prefs.coder[key] # # # Pythonise the universal data (hex -> rgb, tag -> wx int) # invalid = [] # for key in spec: # # Check that key is in tag list and full spec is defined, discard if not # if key in self.tags \ # and all(subkey in spec[key] for subkey in ['bg', 'fg', 'font']): # spec[key]['bg'] = self.hex2rgb(spec[key]['bg'], base['bg']) # spec[key]['fg'] = self.hex2rgb(spec[key]['fg'], base['fg']) # if not spec[key]['font']: # spec[key]['font'] = base['font'] # spec[key]['size'] = int(self.prefs['codeFontSize']) # else: # invalid += [key] # for key in invalid: # del spec[key] # # Set style for undefined lexers # for key in [getattr(wx._stc, item) for item in dir(wx._stc) if item.startswith("STC_LEX")]: # self.StyleSetBackground(key, base['bg']) # self.StyleSetForeground(key, base['fg']) # self.StyleSetSpec(key, "face:%(font)s,size:%(size)d" % base) # # Set style from universal data # for key in spec: # if self.tags[key] is not None: # self.StyleSetBackground(self.tags[key], spec[key]['bg']) # self.StyleSetForeground(self.tags[key], spec[key]['fg']) # self.StyleSetSpec(self.tags[key], "face:%(font)s,size:%(size)d" % spec[key]) # # Apply keywords # for level, val in self.lexkw.items(): # self.SetKeyWords(level, " ".join(val)) # # # Make sure there's some spec for margins # if 'margin' not in spec: # spec['margin'] = base # # Set margin colours to match linenumbers if set # if 'margin' in spec: # mar = spec['margin']['bg'] # else: # mar = base['bg'] # self.SetFoldMarginColour(True, mar) # self.SetFoldMarginHiColour(True, mar) # # # Make sure there's some spec for caret # if 'caret' not in spec: # spec['caret'] = base # # Set caret colour # self.SetCaretForeground(spec['caret']['fg']) # self.SetCaretLineBackground(spec['caret']['bg']) # self.SetCaretWidth(1 + ('bold' in spec['caret']['font'])) # # # Make sure there's some spec for selection # if 'select' not in spec: # spec['select'] = base # spec['select']['bg'] = self.shiftColour(base['bg'], 30) # # Set selection colour # self.SetSelForeground(True, spec['select']['fg']) # self.SetSelBackground(True, spec['select']['bg']) # # # Set wrap point # self.edgeGuideColumn = self.prefs['edgeGuideColumn'] # self.edgeGuideVisible = self.edgeGuideColumn > 0 # # # Set line spacing # spacing = min(int(self.prefs['lineSpacing'] / 2), 64) # Max out at 64 # self.SetExtraAscent(spacing) # self.SetExtraDescent(spacing)
18,086
Python
.py
404
36.30198
101
0.611483
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,796
psychoParser.py
psychopy_psychopy/psychopy/app/coder/psychoParser.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). # python text parser # this is really just for the purpose of constructing code analysis in # python scripts import tokenize import re # xx = pyclbr.readmodule_ex('psychopy.visual') # #xx = pyclbr.tokenize('psychopy') # print(xx['makeRadialMatrix'].__doc__) class tokenBuffer(): # simple buffer to provide mechanism to step backwards through previous # tokens def __init__(self, token, prev): super(tokenBuffer, self).__init__() self.tok = token self.prev = prev def getTokensAndImports(buffer): # f = open(filename, 'r') # gen=tokenize.generate_tokens(f.readline) gen = tokenize.generate_tokens(buffer.readline) importLines = [] equalLines = {} definedTokens = {} prev = None for token in gen: if token[1] == 'import': # runs any line that contains the word import importLines.append(token[4].replace('\r', '')) elif token[1] == '=': equalLines[token[2][0]] = token[4] defineStr = '' prevTok = prev # fetch the name of the object ( while prevTok is not None: if prevTok.tok[0] != 1 and prevTok.tok[1] != '.': prevTok = None # we have the full name else: defineStr = prevTok.tok[1] + defineStr prevTok = prevTok.prev # do we have that token already? if defineStr in definedTokens: continue else: # try to identify what new token = definingStr = '' while True: # fetch the name of the object being defined nextTok = next(gen) if nextTok[0] != 1 and nextTok[1] != '.': break # we have the full name else: definingStr += nextTok[1] definedTokens[defineStr] = {'is': definingStr} thisToken = tokenBuffer(token, prev) prev = thisToken return importLines, definedTokens def parsePyScript(src, indentSpaces=4): """Parse a Python script for the source tree viewer. Quick-and-dirty parser for Python files which retrieves declarations in the file. Used by the source tree viewer to build a structure tree. This is intended to work really quickly so it can handle very large Python files in realtime without eating up CPU resources. The parser is very conservative and can't handle conditional declarations or nested objects greater than one indent level from its parent. Parameters ---------- src : str Python source code to parse. indentSpaces : int Indent spaces used by this file, default is 4. Returns ------- list List of found items. """ foundDefs = [] for nLine, line in enumerate(src.split('\n')): lineno = nLine + 1 lineFullLen = len(line) lineText = line.lstrip() lineIndent = int((lineFullLen - len(lineText)) / indentSpaces) # to indent level # filter out defs that are nested in if statements if nLine > 0 and foundDefs: lastIndent = foundDefs[-1][2] if lineIndent - lastIndent > 1: continue # is definition? if lineText.startswith('class ') or lineText.startswith('def '): # slice off comment lineText = lineText.split('#')[0] lineTokens = [ tok.strip() for tok in re.split(r' |\(|\)', lineText) if tok] defType, defName = lineTokens[:2] foundDefs.append((defType, defName, lineIndent, lineno)) # mdc - holding off on showing attributes and imports for now # elif lineText.startswith('import ') and lineIndent == 0: # lineText = lineText.split('#')[0] # clean the line # # check if we have a regular import statement or an 'as' one # if ' as ' not in lineText: # lineTokens = [ # tok.strip() for tok in re.split( # ' |,', lineText[len('import '):]) if tok] # # # create a new import declaration for import if a list # for name in lineTokens: # foundDefs.append(('import', name, lineIndent, lineno)) # else: # impStmt = lineText[len('import '):].strip().split(' as ') # name, attrs = impStmt # # foundDefs.append(('importas', name, lineIndent, lineno, attrs)) # elif lineText.startswith('from ') and lineIndent == 0: # pass return foundDefs
4,940
Python
.py
117
33.068376
89
0.58217
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,797
sourceTree.py
psychopy_psychopy/psychopy/app/coder/sourceTree.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Classes and functions for the coder source tree.""" # 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 collections import deque from ..themes import icons, colors, handlers import wx import wx.stc import os import re import string CPP_DEFS = ['void', 'int', 'float', 'double', 'short', 'byte', 'struct', 'enum', 'function', 'async function', 'class'] # javascript tokens PYTHON_DEFS = ['def', 'class'] class SourceTreePanel(wx.Panel, handlers.ThemeMixin): """Panel for the source tree browser.""" def __init__(self, parent, frame): wx.Panel.__init__(self, parent, -1) self.parent = parent self.coder = frame self.app = frame.app self.tabIcon = "coderclass" # double buffered better rendering except if retina self.SetDoubleBuffered(self.coder.IsDoubleBuffered()) # create the source tree control self.treeId = wx.NewIdRef() self.srcTree = wx.TreeCtrl( self, self.treeId, pos=(0, 0), size=wx.Size(300, 300), style=wx.TR_HAS_BUTTONS | wx.BORDER_NONE) # do layout szr = wx.BoxSizer(wx.VERTICAL) szr.Add(self.srcTree, flag=wx.EXPAND, proportion=1) self.SetSizer(szr) # bind events self.Bind( wx.EVT_TREE_ITEM_ACTIVATED, self.OnItemActivate, self.srcTree) self.Bind( wx.EVT_TREE_SEL_CHANGED, self.OnItemSelected, self.srcTree) self.Bind( wx.EVT_TREE_ITEM_EXPANDED, self.OnItemExpanded, self.srcTree) self.Bind( wx.EVT_TREE_ITEM_COLLAPSED, self.OnItemCollapsed, self.srcTree) self._applyAppTheme() def _applyAppTheme(self): self.srcTree.SetOwnBackgroundColour(colors.app['tab_bg']) self.srcTree.SetOwnForegroundColour(colors.app['text']) # get graphics for toolbars and tree items self._treeImgList = wx.ImageList(16, 16) self._treeGfx = { 'class': self._treeImgList.Add( icons.ButtonIcon('coderclass', size=16).bitmap), 'def': self._treeImgList.Add( icons.ButtonIcon('coderfunc', size=16).bitmap), 'attr': self._treeImgList.Add( icons.ButtonIcon('codervar', size=16).bitmap), 'pyModule': self._treeImgList.Add( icons.ButtonIcon('coderpython', size=16).bitmap), 'jsModule': self._treeImgList.Add( icons.ButtonIcon('coderjs', size=16).bitmap), 'noDoc': self._treeImgList.Add( icons.ButtonIcon('docclose', size=16).bitmap) # 'import': self._treeImgList.Add( # wx.Bitmap(os.path.join(rc, 'coderimport16.png'), wx.BITMAP_TYPE_PNG)), # 'treeFolderClosed': _treeImgList.Add( # wx.Bitmap(os.path.join(rc, 'folder16.png'), wx.BITMAP_TYPE_PNG)), # 'treeFolderOpened': _treeImgList.Add( # wx.Bitmap(os.path.join(rc, 'folder-open16.png'), wx.BITMAP_TYPE_PNG)) } # for non-python functions self._treeGfx['function'] = self._treeGfx['def'] self.srcTree.SetImageList(self._treeImgList) def OnItemSelected(self, evt=None): """When a tree item is clicked on.""" item = evt.GetItem() itemData = self.srcTree.GetItemData(item) if itemData is not None: self.coder.currentDoc.SetFirstVisibleLine(itemData[2] - 1) self.coder.currentDoc.GotoLine(itemData[2]) wx.CallAfter(self.coder.currentDoc.SetFocus) else: evt.Skip() def OnItemActivate(self, evt=None): """When a tree item is clicked on.""" evt.Skip() def OnItemExpanded(self, evt): itemData = self.srcTree.GetItemData(evt.GetItem()) if itemData is not None: self.coder.currentDoc.expandedItems[itemData] = True def OnItemCollapsed(self, evt): itemData = self.srcTree.GetItemData(evt.GetItem()) if itemData is not None: self.coder.currentDoc.expandedItems[itemData] = False def GetScrollVert(self): """Get the vertical scrolling position for the tree. This is used to keep track of where we are in the tree by the code editor. This prevents the tree viewer from moving back to the top when returning to a document, which may be jarring for users.""" return self.srcTree.GetScrollPos(wx.VERTICAL) def refresh(self): """Update the source tree using the current document. Examines all the fold levels and tries to create a tree with them.""" doc = self.coder.currentDoc if doc is None: return # check if we can parse this file if self.coder.currentDoc.GetLexer() not in [wx.stc.STC_LEX_PYTHON, wx.stc.STC_LEX_CPP]: self.srcTree.DeleteAllItems() root = self.srcTree.AddRoot( 'Source tree unavailable for this file type.') self.srcTree.SetItemImage( root, self._treeGfx['noDoc'], wx.TreeItemIcon_Normal) return # Go over file and get all the folds. # We do this instead of parsing the files ourselves since Scintilla # lexers are probably better than anything *I* can come up with. -mdc foldLines = [] for lineno in range(doc.GetLineCount()): foldLevelFlags = doc.GetFoldLevel(lineno) foldLevel = \ (foldLevelFlags & wx.stc.STC_FOLDLEVELNUMBERMASK) - \ wx.stc.STC_FOLDLEVELBASE # offset isFoldStart = (foldLevelFlags & wx.stc.STC_FOLDLEVELHEADERFLAG) > 0 if isFoldStart: foldLines.append( (foldLevel, lineno, doc.GetLineText(lineno).lstrip())) # Build the trees for the given language, this is a dictionary which # represents the hierarchy of the document. This system is dead simple, # determining what's a function/class based on what the Scintilla lexer # thinks should be folded. This is really fast and works most of the # time (perfectly for Python). In the future, we may need to specify # additional code to handle languages which don't have strict whitespace # requirements. # currentLexer = self.coder.currentDoc.GetLexer() if currentLexer == wx.stc.STC_LEX_CPP: stripChars = string.whitespace kwrds = CPP_DEFS elif currentLexer == wx.stc.STC_LEX_PYTHON: stripChars = string.whitespace + ':' kwrds = PYTHON_DEFS else: return # do nothing here indent = doc.GetIndent() # filter out only definitions defineList = [] lastItem = None for df in foldLines: lineText = doc.GetLineText(df[1]).lstrip() # work out which keyword the line starts with kwrd = None for i in kwrds: i += " " # add a space to avoid e.g. `defaultKeyboard` being read as a keyword if lineText.startswith(i): kwrd = i # skip if it starts with no keywords if kwrd is None: continue if lastItem is not None: if df[0] > lastItem[3] + indent: continue # slice off comment lineText = lineText.split('#')[0] # split into tokens lineTokens = [ tok.strip(stripChars) for tok in re.split( r' |\(|\)', lineText) if tok] # take value before keyword end as def type, value after as def name kwrdEnd = len(re.findall(r' |\(|\)', kwrd)) try: defType = lineTokens[kwrdEnd-1] defName = lineTokens[kwrdEnd] except ValueError: # if for some reason the line is valid but cannot be parsed, ignore it continue lastItem = (defType, defName, df[1], df[0]) defineList.append(lastItem) self.createSourceTree(defineList, doc.GetIndent()) self.srcTree.Refresh() def createSourceTree(self, foldDefs, indents=4): """Create a Python source tree. This is called when code analysis runs and the document type is 'Python'. """ # create the root item which is just the file name self.srcTree.Freeze() self.srcTree.DeleteAllItems() self.root = self.srcTree.AddRoot( os.path.split(self.coder.currentDoc.filename)[-1]) if self.coder.currentDoc.filename.endswith('.py'): self.srcTree.SetItemImage( self.root, self._treeGfx['pyModule'], wx.TreeItemIcon_Normal) elif self.coder.currentDoc.filename.endswith('.js'): self.srcTree.SetItemImage( self.root, self._treeGfx['jsModule'], wx.TreeItemIcon_Normal) else: self.srcTree.SetItemImage( self.root, self._treeGfx['noDoc'], wx.TreeItemIcon_Normal) # start building the source tree nodes = deque([self.root]) for i, foldLine in enumerate(foldDefs): defType, defName, lineno, foldLevel = foldLine foldLevel = int(foldLevel / indents) # Get the next level of the tree, we use this to determine if we # should create a new level or move down a few. try: lookAheadLevel = int(foldDefs[i + 1][3] / indents) except IndexError: lookAheadLevel = 0 try: # catch an error if the deque is empty, this means something # went wrong itemIdx = self.srcTree.AppendItem(nodes[0], defName) except IndexError: self.srcTree.DeleteAllItems() root = self.srcTree.AddRoot( 'Error parsing current document.') self.srcTree.SetItemImage( root, self._treeGfx['noDoc'], wx.TreeItemIcon_Normal) return self.srcTree.SetItemImage( itemIdx, self._treeGfx.get(defType, self._treeGfx['function']), wx.TreeItemIcon_Normal) self.srcTree.SetItemData(itemIdx, foldLine) if lookAheadLevel > foldLevel: # create a new branch if the next item is at higher indent level nodes.appendleft(itemIdx) elif lookAheadLevel < foldLevel: # remove nodes to match next indent level indentDiff = foldLevel - lookAheadLevel for _ in range(int(indentDiff)): # check if we need to expand the item we dropped down from itemData = self.srcTree.GetItemData(nodes[0]) if itemData is not None: try: if self.coder.currentDoc.expandedItems[itemData]: self.srcTree.Expand(nodes.popleft()) else: nodes.popleft() except KeyError: if len(nodes) > 1: nodes.popleft() else: self.srcTree.DeleteAllItems() root = self.srcTree.AddRoot( 'Error parsing current document.') self.srcTree.SetItemImage( root, self._treeGfx['noDoc'], wx.TreeItemIcon_Normal) return # clean up expanded items list temp = dict(self.coder.currentDoc.expandedItems) for itemData in self.coder.currentDoc.expandedItems.keys(): if itemData not in foldDefs: del temp[itemData] self.coder.currentDoc.expandedItems = temp self.srcTree.Expand(self.root) self.srcTree.Thaw()
12,414
Python
.py
264
34.121212
95
0.57926
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,798
folding.py
psychopy_psychopy/psychopy/app/coder/folding.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Functions and classes related to code folding with Scintilla.""" # 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.stc class CodeEditorFoldingMixin(): """Mixin for adding code folding functionality to a CodeEditor control. """ def OnMarginClick(self, evt): """Event for when a margin is clicked.""" # fold and unfold as needed if evt.GetMargin() == 1: if evt.GetShift() and evt.GetControl(): self.FoldAll() else: 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) def FoldAll(self): """Fold all code blocks.""" lineCount = self.GetLineCount() expanding = True # find out if we are folding or unfolding for lineNum in range(lineCount): if self.GetFoldLevel(lineNum) & wx.stc.STC_FOLDLEVELHEADERFLAG: expanding = not self.GetFoldExpanded(lineNum) break lineNum = 0 _flag = wx.stc.STC_FOLDLEVELHEADERFLAG _mask = wx.stc.STC_FOLDLEVELNUMBERMASK _base = wx.stc.STC_FOLDLEVELBASE while lineNum < lineCount: level = self.GetFoldLevel(lineNum) if level & _flag and level & _mask == _base: if expanding: self.SetFoldExpanded(lineNum, True) lineNum = self.Expand(lineNum, True) lineNum -= 1 else: lastChild = self.GetLastChild(lineNum, -1) self.SetFoldExpanded(lineNum, False) if lastChild > lineNum: self.HideLines(lineNum + 1, lastChild) lineNum += 1 def Expand(self, line, doExpand, force=False, visLevels=0, level=-1): lastChild = self.GetLastChild(line, level) line += 1 while line <= lastChild: if force: if visLevels > 0: self.ShowLines(line, line) else: self.HideLines(line, line) else: if doExpand: self.ShowLines(line, line) if level == -1: level = self.GetFoldLevel(line) if level & wx.stc.STC_FOLDLEVELHEADERFLAG: if force: if visLevels > 1: self.SetFoldExpanded(line, True) else: self.SetFoldExpanded(line, False) line = self.Expand(line, doExpand, force, visLevels - 1) else: if doExpand and self.GetFoldExpanded(line): line = self.Expand(line, True, force, visLevels - 1) else: line = self.Expand(line, False, force, visLevels - 1) else: line += 1 return line def getFolds(doc): """Get the lines and levels of folds found by the Scintilla. This can be used to create parsers for the source tree among other things. Parameters ---------- doc : wx.stc.StyledText Styled text object. Returns ------- list List of fold levels and line numbers. """ # Go over file and get all the folds. foldLines = [] for lineno in range(doc.GetLineCount()): foldLevelFlags = doc.GetFoldLevel(lineno) foldLevel = \ (foldLevelFlags & wx.stc.STC_FOLDLEVELNUMBERMASK) - \ wx.stc.STC_FOLDLEVELBASE # offset isFoldStart = (foldLevelFlags & wx.stc.STC_FOLDLEVELHEADERFLAG) > 0 if isFoldStart: foldLines.append((foldLevel, lineno)) return foldLines
4,643
Python
.py
110
28.718182
79
0.545736
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,799
coder.py
psychopy_psychopy/psychopy/app/coder/coder.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2009 Jonathan Peirce # Distributed under the terms of the GNU General Public License (GPL). from pathlib import Path import wx import wx.stc import wx.richtext import wx.py import psychopy.app from ..pavlovia_ui.search import SearchFrame from ..pavlovia_ui.user import UserFrame from ..themes.ui import ThemeSwitcher from wx.html import HtmlEasyPrinting from wx._core import wxAssertionError import wx.lib.agw.aui as aui # some versions of phoenix import os import sys import glob import io import threading import bdb import pickle import time import textwrap import codecs from .. import dialogs, ribbon from ..stdout import stdOutRich from .. import pavlovia_ui from psychopy import logging, prefs from psychopy.alerts._alerts import alert from psychopy.localization import _translate from ..utils import FileDropTarget, BasePsychopyToolbar, FrameSwitcher, updateDemosMenu from ..ui import BaseAuiFrame from psychopy.projects import pavlovia import psychopy.app.pavlovia_ui.menu import psychopy.app.plugin_manager.dialog from psychopy.app.errorDlg import exceptionCallback from psychopy.app.coder.codeEditorBase import BaseCodeEditor from psychopy.app.coder.fileBrowser import FileBrowserPanel from psychopy.app.coder.sourceTree import SourceTreePanel from psychopy.app.themes import handlers, colors from psychopy.app.coder.folding import CodeEditorFoldingMixin from psychopy.app.stdout.stdOutRich import ScriptOutputPanel from psychopy.app.coder.repl import PythonREPLCtrl # from ..plugin_manager import PluginManagerFrame try: import jedi if jedi.__version__ < "0.16": logging.error( "Need a newer version of package `jedi`. Currently using {}" .format(jedi.__version__) ) _hasJedi = True jedi.settings.fast_parser = True except ImportError: logging.error( "Package `jedi` not installed, code auto-completion and calltips will " "not be available.") _hasJedi = False # advanced prefs (not set in prefs files) prefTestSubset = "" analysisLevel = 1 analyseAuto = True runScripts = 'process' try: # needed for wx.py shell import code haveCode = True except Exception: haveCode = False def toPickle(filename, data): """save data (of any sort) as a pickle file simple wrapper of the cPickle module in core python """ with io.open(filename, 'wb') as f: pickle.dump(data, f) def fromPickle(filename): """load data (of any sort) from a pickle file simple wrapper of the cPickle module in core python """ with io.open(filename, 'rb') as f: contents = pickle.load(f) return contents class Printer(HtmlEasyPrinting): """bare-bones printing, no control over anything from https://wiki.wxpython.org/Printing """ def __init__(self): HtmlEasyPrinting.__init__(self) def GetHtmlText(self, text): """Simple conversion of text.""" text = text.replace('&', '&amp;') text = text.replace('<P>', '&#60;P&#62;') text = text.replace('<BR>', '&#60;BR&#62;') text = text.replace('<HR>', '&#60;HR&#62;') text = text.replace('<p>', '&#60;p&#62;') text = text.replace('<br>', '&#60;br&#62;') text = text.replace('<hr>', '&#60;hr&#62;') text = text.replace('\n\n', '<P>') text = text.replace('\t', ' ') # tabs -> 4 spaces text = text.replace(' ', '&nbsp;') # preserve indentation html_text = text.replace('\n', '<BR>') return html_text def Print(self, text, doc_name): self.SetStandardFonts(size=prefs.coder['codeFontSize'], normal_face="", fixed_face=prefs.coder['codeFont']) _, fname = os.path.split(doc_name) self.SetHeader("Page @PAGENUM@ of @PAGESCNT@ - " + fname + " (@DATE@ @TIME@)<HR>") # use <tt> tag since we're dealing with old school HTML here self.PrintText("<tt>" + self.GetHtmlText(text) + '</tt>', doc_name) class ScriptThread(threading.Thread): """A subclass of threading.Thread, with a kill() method. """ def __init__(self, target, gui): threading.Thread.__init__(self, target=target) self.killed = False self.gui = gui def start(self): """Start the thread. """ self.__run_backup = self.run self.run = self.__run # force the Thread to install our trace. threading.Thread.start(self) def __run(self): """Hacked run function, which installs the trace. """ sys.settrace(self.globaltrace) self.__run_backup() self.run = self.__run_backup # we're done - send the App a message self.gui.onProcessEnded(event=None) def globaltrace(self, frame, why, arg): if why == 'call': return self.localtrace else: return None def localtrace(self, frame, why, arg): if self.killed: if why == 'line': raise SystemExit() return self.localtrace def kill(self): self.killed = True class PsychoDebugger(bdb.Bdb): # this is based on effbot: http://effbot.org/librarybook/bdb.htm def __init__(self): bdb.Bdb.__init__(self) self.starting = True def user_call(self, frame, args): name = frame.f_code.co_name or "<unknown>" self.set_continue() # continue def user_line(self, frame): if self.starting: self.starting = False self.set_trace() # start tracing else: # arrived at breakpoint name = frame.f_code.co_name or "<unknown>" filename = self.canonic(frame.f_code.co_filename) print("break at %s %i in %s" % (filename, frame.f_lineno, name)) self.set_continue() # continue to next breakpoint def user_return(self, frame, value): name = frame.f_code.co_name or "<unknown>" self.set_continue() # continue def user_exception(self, frame, exception): name = frame.f_code.co_name or "<unknown>" self.set_continue() # continue def quit(self): self._user_requested_quit = 1 self.set_quit() return 1 class UnitTestFrame(wx.Frame): class _unitTestOutRich(stdOutRich.StdOutRich): """richTextCtrl window for unit test output""" def __init__(self, parent, style, size=None, **kwargs): stdOutRich.StdOutRich.__init__(self, parent=parent, style=style, size=size) self.bad = [150, 0, 0] self.good = [0, 150, 0] self.skip = [170, 170, 170] self.png = [] def write(self, inStr): self.MoveEnd() # always 'append' text rather than 'writing' it for thisLine in inStr.splitlines(True): if not isinstance(thisLine, str): thisLine = str(thisLine) if thisLine.startswith('OK'): self.BeginBold() self.BeginTextColour(self.good) self.WriteText("OK") self.EndTextColour() self.EndBold() self.WriteText(thisLine[2:]) # for OK (SKIP=xx) self.parent.status = 1 elif thisLine.startswith('#####'): self.BeginBold() self.WriteText(thisLine) self.EndBold() elif 'FAIL' in thisLine or 'ERROR' in thisLine: self.BeginTextColour(self.bad) self.WriteText(thisLine) self.EndTextColour() self.parent.status = -1 elif thisLine.find('SKIP') > -1: self.BeginTextColour(self.skip) self.WriteText(thisLine.strip()) # show the new image, double size for easier viewing: if thisLine.strip().endswith('.png'): newImg = thisLine.split()[-1] img = os.path.join(self.parent.paths['tests'], 'data', newImg) self.png.append(wx.Image(img, wx.BITMAP_TYPE_ANY)) self.MoveEnd() self.WriteImage(self.png[-1]) self.MoveEnd() self.WriteText('\n') self.EndTextColour() else: # line to write as simple text self.WriteText(thisLine) if thisLine.find('Saved copy of actual frame') > -1: # show the new images, double size for easier viewing: newImg = [f for f in thisLine.split() if f.find('_local.png') > -1] newFile = newImg[0] origFile = newFile.replace('_local.png', '.png') img = os.path.join(self.parent.paths['tests'], origFile) self.png.append(wx.Image(img, wx.BITMAP_TYPE_ANY)) self.MoveEnd() self.WriteImage(self.png[-1]) self.MoveEnd() self.WriteText('= ' + origFile + '; ') img = os.path.join(self.parent.paths['tests'], newFile) self.png.append(wx.Image(img, wx.BITMAP_TYPE_ANY)) self.MoveEnd() self.WriteImage(self.png[-1]) self.MoveEnd() self.WriteText('= ' + newFile + '; ') self.MoveEnd() # go to end of stdout so user can see updated text self.ShowPosition(self.GetLastPosition()) def __init__(self, parent=None, ID=-1, title=_translate('PsychoPy unit testing'), files=(), app=None): self.app = app self.frameType = 'unittest' self.prefs = self.app.prefs self.paths = self.app.prefs.paths # deduce the script for running the tests try: import pytest havePytest = True except Exception: havePytest = False self.runpyPath = os.path.join(self.prefs.paths['tests'], 'run.py') if sys.platform != 'win32': self.runpyPath = self.runpyPath.replace(' ', r'\ ') # setup the frame self.IDs = self.app.IDs # to right, so Cancel button is clickable during a long test wx.Frame.__init__(self, parent, ID, title, pos=(450, 45)) self.scriptProcess = None self.runAllText = 'all tests' border = 10 # status = outcome of the last test run: -1 fail, 0 not run, +1 ok: self.status = 0 # create menu items menuBar = wx.MenuBar() self.menuTests = wx.Menu() menuBar.Append(self.menuTests, _translate('&Tests')) _run = self.app.keys['runScript'] self.menuTests.Append(wx.ID_APPLY, _translate("&Run tests\t%s") % _run) self.Bind(wx.EVT_MENU, self.onRunTests, id=wx.ID_APPLY) self.menuTests.AppendSeparator() self.menuTests.Append(wx.ID_CLOSE, _translate( "&Close tests panel\t%s") % self.app.keys['close']) self.Bind(wx.EVT_MENU, self.onCloseTests, id=wx.ID_CLOSE) _switch = self.app.keys['switchToCoder'] self.menuTests.Append(wx.ID_ANY, _translate("Go to &Coder view\t%s") % _switch, _translate("Go to the Coder view")) self.Bind(wx.EVT_MENU, self.app.showCoder) # -------------quit self.menuTests.AppendSeparator() _quit = self.app.keys['quit'] self.menuTests.Append(wx.ID_EXIT, _translate("&Quit\t%s") % _quit, _translate("Terminate PsychoPy")) self.Bind(wx.EVT_MENU, self.app.quit, id=wx.ID_EXIT) item = self.menuTests.Append( wx.ID_PREFERENCES, _translate("&Preferences")) self.Bind(wx.EVT_MENU, self.app.showPrefs, item) self.SetMenuBar(menuBar) # create controls buttonsSizer = wx.BoxSizer(wx.HORIZONTAL) _style = wx.TE_MULTILINE | wx.TE_READONLY | wx.EXPAND | wx.GROW _font = self.prefs.coder['outputFont'] _fsize = self.prefs.coder['outputFontSize'] self.outputWindow = self._unitTestOutRich(self, style=_style, size=wx.Size(750, 500), font=_font, fontSize=_fsize) knownTests = glob.glob(os.path.join(self.paths['tests'], 'test*')) knownTestList = [t.split(os.sep)[-1] for t in knownTests if t.endswith('.py') or os.path.isdir(t)] self.knownTestList = [self.runAllText] + knownTestList self.testSelect = wx.Choice(parent=self, id=-1, pos=(border, border), choices=self.knownTestList) tip = _translate( "Select the test(s) to run, from:\npsychopy/tests/test*") self.testSelect.SetToolTip(wx.ToolTip(tip)) prefTestSubset = self.prefs.appData['testSubset'] # preselect the testGroup in the drop-down menu for display: if prefTestSubset in self.knownTestList: self.testSelect.SetStringSelection(prefTestSubset) self.btnRun = wx.Button(parent=self, label=_translate("Run tests")) self.btnRun.Bind(wx.EVT_BUTTON, self.onRunTests) self.btnCancel = wx.Button(parent=self, label=_translate("Cancel")) self.btnCancel.Bind(wx.EVT_BUTTON, self.onCancelTests) self.btnCancel.Disable() self.Bind(wx.EVT_END_PROCESS, self.onTestsEnded) self.chkCoverage = wx.CheckBox( parent=self, label=_translate("Coverage Report")) _tip = _translate("Include coverage report (requires coverage module)") self.chkCoverage.SetToolTip(wx.ToolTip(_tip)) self.chkCoverage.Disable() self.chkAllStdOut = wx.CheckBox( parent=self, label=_translate("ALL stdout")) _tip = _translate( "Report all printed output & show any new rms-test images") self.chkAllStdOut.SetToolTip(wx.ToolTip(_tip)) self.chkAllStdOut.Disable() self.Bind(wx.EVT_IDLE, self.onIdle) self.SetDefaultItem(self.btnRun) # arrange controls buttonsSizer.Add(self.chkCoverage, 0, wx.LEFT | wx.RIGHT | wx.TOP, border=border) buttonsSizer.Add(self.chkAllStdOut, 0, wx.LEFT | wx.RIGHT | wx.TOP, border=border) buttonsSizer.Add(self.btnRun, 0, wx.LEFT | wx.RIGHT | wx.TOP, border=border) buttonsSizer.Add(self.btnCancel, 0, wx.LEFT | wx.RIGHT | wx.TOP, border=border) self.sizer = wx.BoxSizer(orient=wx.VERTICAL) self.sizer.Add(buttonsSizer, 0, wx.ALIGN_RIGHT) self.sizer.Add(self.outputWindow, 0, wx.ALL | wx.EXPAND | wx.GROW, border=border) self.SetSizerAndFit(self.sizer) self.Show() def onRunTests(self, event=None): """Run the unit tests """ self.status = 0 # create process # self is the parent (which will receive an event when the process # ends) self.scriptProcess = wx.Process(self) self.scriptProcess.Redirect() # catch the stdout/stdin # include coverage report? if self.chkCoverage.GetValue(): coverage = ' cover' else: coverage = '' # printing ALL output? if self.chkAllStdOut.GetValue(): allStdout = ' -s' else: allStdout = '' # what subset of tests? (all tests == '') tselect = self.knownTestList[self.testSelect.GetCurrentSelection()] if tselect == self.runAllText: tselect = '' testSubset = tselect # self.prefs.appData['testSubset'] = tselect # in onIdle # launch the tests using wx.Execute(): self.btnRun.Disable() self.btnCancel.Enable() if sys.platform == 'win32': testSubset = ' ' + testSubset args = (sys.executable, self.runpyPath, coverage, allStdout, testSubset) command = '"%s" -u "%s" %s%s%s' % args # quotes handle spaces print(command) self.scriptProcessID = wx.Execute( command, wx.EXEC_ASYNC, self.scriptProcess) # self.scriptProcessID = wx.Execute(command, # # wx.EXEC_ASYNC| wx.EXEC_NOHIDE, self.scriptProcess) else: testSubset = ' ' + testSubset.replace(' ', r'\ ') # protect spaces args = (sys.executable, self.runpyPath, coverage, allStdout, testSubset) command = '%s -u %s%s%s%s' % args _opt = wx.EXEC_ASYNC | wx.EXEC_MAKE_GROUP_LEADER self.scriptProcessID = wx.Execute(command, _opt, self.scriptProcess) msg = "\n##### Testing: %s%s%s%s #####\n\n" % ( self.runpyPath, coverage, allStdout, testSubset) self.outputWindow.write(msg) _notNormUnits = self.app.prefs.general['units'] != 'norm' if _notNormUnits and 'testVisual' in testSubset: msg = "Note: default window units = '%s' (in prefs); for visual tests 'norm' is recommended.\n\n" self.outputWindow.write(msg % self.app.prefs.general['units']) def onCancelTests(self, event=None): if self.scriptProcess != None: self.scriptProcess.Kill( self.scriptProcessID, wx.SIGTERM, wx.SIGKILL) self.scriptProcess = None self.scriptProcessID = None self.outputWindow.write("\n --->> cancelled <<---\n\n") self.status = 0 self.onTestsEnded() def onIdle(self, event=None): # auto-save last selected subset: self.prefs.appData['testSubset'] = self.knownTestList[ self.testSelect.GetCurrentSelection()] if self.scriptProcess != None: if self.scriptProcess.IsInputAvailable(): stream = self.scriptProcess.GetInputStream() text = stream.read() self.outputWindow.write(text) if self.scriptProcess.IsErrorAvailable(): stream = self.scriptProcess.GetErrorStream() text = stream.read() self.outputWindow.write(text) def onTestsEnded(self, event=None): self.onIdle() # so that any final stdout/err gets written self.outputWindow.flush() self.btnRun.Enable() self.btnCancel.Disable() def onURL(self, evt): """decompose the URL of a file and line number""" # "C:\Program Files\wxPython2.8 Docs and Demos\samples\hangman\hangman.py" tmpFilename, tmpLineNumber = evt.GetString().rsplit('", line ', 1) filename = tmpFilename.split('File "', 1)[1] try: lineNumber = int(tmpLineNumber.split(',')[0]) except ValueError: lineNumber = int(tmpLineNumber.split()[0]) self.app.coder.gotoLine(filename, lineNumber) def onCloseTests(self, evt): self.Destroy() class CodeEditor(BaseCodeEditor, CodeEditorFoldingMixin, handlers.ThemeMixin): """Code editor class for the Coder GUI. """ def __init__(self, parent, ID, frame, # set the viewer to be small, then it will increase with aui # control pos=wx.DefaultPosition, size=wx.Size(100, 100), style=wx.BORDER_NONE, readonly=False): BaseCodeEditor.__init__(self, parent, ID, pos, size, style) self.coder = frame self.prefs = self.coder.prefs self.paths = self.coder.paths self.app = self.coder.app self.SetViewWhiteSpace(self.coder.appData['showWhitespace']) self.SetViewEOL(self.coder.appData['showEOLs']) self.Bind(wx.stc.EVT_STC_MODIFIED, self.onModified) self.Bind(wx.stc.EVT_STC_UPDATEUI, self.OnUpdateUI) self.Bind(wx.EVT_KEY_DOWN, self.OnKeyPressed) self.Bind(wx.EVT_KEY_UP, self.OnKeyReleased) if hasattr(self, 'OnMarginClick'): self.Bind(wx.stc.EVT_STC_MARGINCLICK, self.OnMarginClick) # black-and-white text signals read-only file open in Coder window # if not readonly: # self.setFonts() self.SetDropTarget(FileDropTarget(targetFrame=self.coder)) # set to python syntax code coloring self.setLexerFromFileName() # Keep track of visual aspects of the source tree viewer when working # with this document. This makes sure the tree maintains it's state when # moving between documents. self.expandedItems = {} # show the long line edge guide, enabled if >0 self.edgeGuideColumn = self.coder.prefs['edgeGuideColumn'] self.edgeGuideVisible = self.edgeGuideColumn > 0 # give a little space between the margin and text self.SetMarginLeft(4) # whitespace information self.indentSize = self.GetIndent() self.newlines = '/n' # caret info, these are updated by calling updateCaretInfo() self.caretCurrentPos = self.GetCurrentPos() self.caretVisible, caretColumn, caretLine = self.PositionToXY( self.caretCurrentPos) if self.caretVisible: self.caretColumn = caretColumn self.caretLine = caretLine else: self.caretLine = self.GetCurrentLine() self.caretColumn = self.GetLineLength(self.caretLine) # where does the line text start? self.caretLineIndentCol = \ self.GetColumn(self.GetLineIndentPosition(self.caretLine)) # what is the indent level of the line the caret is located self.caretLineIndentLevel = self.caretLineIndentCol / self.indentSize # is the caret at an indentation level? self.caretAtIndentLevel = \ (self.caretLineIndentCol % self.indentSize) == 0 # # should hitting backspace result in an untab? # self.shouldBackspaceUntab = \ # self.caretAtIndentLevel and \ # 0 < self.caretColumn <= self.caretLineIndentCol self.SetBackSpaceUnIndents(True) # set the current line and column in the status bar self.coder.SetStatusText( 'Line: {} Col: {}'.format( self.caretLine + 1, self.caretColumn + 1), 1) # calltips self.CallTipSetBackground(colors.app['tab_bg']) self.CallTipSetForeground(colors.app['text']) self.CallTipSetForegroundHighlight(colors.app['text']) self.AutoCompSetIgnoreCase(True) self.AutoCompSetAutoHide(True) self.AutoCompStops('. ') self.openBrackets = 0 # better font rendering and less flicker on Windows by using Direct2D # for rendering instead of GDI if wx.Platform == '__WXMSW__': self.SetTechnology(3) # double buffered better rendering except if retina self.SetDoubleBuffered(not self.coder.isRetina) self.theme = self.app.prefs.app['theme'] def setFonts(self): """Make some styles, The lexer defines what each style is used for, we just have to define what each style looks like. This set is adapted from Scintilla sample property files.""" if wx.Platform == '__WXMSW__': faces = {'size': 10} elif wx.Platform == '__WXMAC__': faces = {'size': 14} else: faces = {'size': 12} if self.coder.prefs['codeFontSize']: faces['size'] = int(self.coder.prefs['codeFontSize']) faces['small'] = faces['size'] - 2 # Global default styles for all languages # ,'Arial'] # use arial as backup faces['code'] = self.coder.prefs['codeFont'] # ,'Arial'] # use arial as backup faces['comment'] = self.coder.prefs['codeFont'] # apply the theme to the lexer self.theme = self.coder.app.prefs.app['theme'] def setLexerFromFileName(self): """Set the lexer to one that best matches the file name.""" # best matching lexers for a given file type lexers = {'Python': 'python', 'HTML': 'html', 'C/C++': 'cpp', 'GLSL': 'cpp', 'Arduino': 'cpp', 'MATLAB': 'matlab', 'YAML': 'yaml', 'R': 'R', 'JavaScript': 'cpp', 'JSON': 'json', 'Markdown': 'markdown', 'Plain Text': 'null', } self.setLexer(lexers[self.getFileType()]) def getFileType(self): """Get the file type from the extension.""" if os.path.isabs(self.filename): _, filen = os.path.split(self.filename) else: filen = self.filename # lower case the file name filen = filen.lower() if any([filen.endswith(i) for i in ( # python/cython files '.py', '.pyx', '.pxd', '.pxi')]): return 'Python' elif filen.endswith('html'): # html file return 'HTML' elif any([filen.endswith(i) for i in ( '.cpp', '.c', '.h', '.cxx', '.hxx' '.mex', '.hpp')]): # c-like return 'C/C++' elif any([filen.endswith(i) for i in ( '.glsl', '.vert', '.frag')]): # OpenGL shader program return 'GLSL' elif filen.endswith('.m'): # MATLAB return 'MATLAB' elif filen.endswith('.ino'): # Arduino return 'Arduino' elif filen.endswith('.r'): # R return 'R' elif filen.endswith('.yaml'): # YAML return 'YAML' elif filen.endswith('.js'): # JavaScript return 'JavaScript' elif filen.endswith('.json'): # JSON return 'JSON' elif filen.endswith('.md'): # Markdown return 'Markdown' else: return 'Plain Text' # default, null lexer used def getTextUptoCaret(self): """Get the text up to the caret.""" return self.GetTextRange(0, self.caretCurrentPos) def OnKeyReleased(self, event): """Called after a key is released.""" if hasattr(self.coder, "useAutoComp"): keyCode = event.GetKeyCode() _mods = event.GetModifiers() if keyCode == ord('.'): if self.coder.useAutoComp: # A dot was entered, get suggestions if part of a qualified name wx.CallAfter(self.ShowAutoCompleteList) # defer else: self.coder.SetStatusText( 'Press Ctrl+Space to show code completions', 0) elif keyCode == ord('9') and wx.MOD_SHIFT == _mods: # A left bracket was entered, check if there is a calltip available if self.coder.useAutoComp: if not self.CallTipActive(): wx.CallAfter(self.ShowCalltip) self.openBrackets += 1 else: self.coder.SetStatusText( 'Press Ctrl+Space to show calltip', 0) elif keyCode == ord('0') and wx.MOD_SHIFT == _mods: # close if brace matches if self.CallTipActive(): self.openBrackets -= 1 if self.openBrackets <= 0: self.CallTipCancel() self.openBrackets = 0 else: self.coder.SetStatusText('', 0) event.Skip() def OnKeyPressed(self, event): """Called when a key is pressed.""" # various stuff to handle code completion and tooltips # enable in the _-init__ keyCode = event.GetKeyCode() _mods = event.GetModifiers() # handle some special keys if keyCode == ord('[') and wx.MOD_CONTROL == _mods: self.indentSelection(-4) # if there are no characters on the line then also move caret to # end of indentation txt, charPos = self.GetCurLine() if charPos == 0: # if caret is at start of line, move to start of text instead self.VCHome() elif keyCode == ord(']') and wx.MOD_CONTROL == _mods: self.indentSelection(4) # if there are no characters on the line then also move caret to # end of indentation txt, charPos = self.GetCurLine() if charPos == 0: # if caret is at start of line, move to start of text instead self.VCHome() elif keyCode == ord('/') and wx.MOD_CONTROL == _mods: self.commentLines() elif keyCode == ord('/') and wx.MOD_CONTROL | wx.MOD_SHIFT == _mods: self.uncommentLines() # show completions, very simple at this point elif keyCode == wx.WXK_SPACE and wx.MOD_CONTROL == _mods: self.ShowAutoCompleteList() # show a calltip with signiture elif keyCode == wx.WXK_SPACE and wx.MOD_CONTROL | wx.MOD_SHIFT == _mods: self.ShowCalltip() elif keyCode == wx.WXK_ESCAPE: # close overlays if self.AutoCompActive(): self.AutoCompCancel() # close the auto completion list if self.CallTipActive(): self.CallTipCancel() self.openBrackets = 0 elif keyCode == wx.WXK_BACK: if self.CallTipActive(): # check if we deleted any brackets if self.GetCharAt(self.GetCurrentPos()-1) == ord('('): self.openBrackets -= 1 elif self.GetCharAt(self.GetCurrentPos()-1) == ord(')'): self.openBrackets += 1 # cancel the calltip if we deleted al the brackets if self.openBrackets <= 0: self.CallTipCancel() self.openBrackets = 0 elif keyCode == wx.WXK_RETURN: # and not self.AutoCompActive(): if not self.AutoCompActive(): # process end of line and then do smart indentation event.Skip(False) self.CmdKeyExecute(wx.stc.STC_CMD_NEWLINE) self.smartIdentThisLine() # only analyse on new line if not at end of file if self.GetCurrentPos() < self.GetLastPosition() - 1: self.analyseScript() return # so that we don't reach the skip line at end if self.CallTipActive(): self.CallTipCancel() self.openBrackets = 0 # quote line elif keyCode == ord("'"): #raise RuntimeError start, end = self.GetSelection() if end - start > 0: txt = self.GetSelectedText() txt = "'" + txt.replace('\n', "'\n'") + "'" self.ReplaceSelection(txt) event.Skip(False) return event.Skip() def ShowAutoCompleteList(self): """Show autocomplete list at the current caret position.""" if _hasJedi and self.getFileType() == 'Python': self.coder.SetStatusText( 'Retrieving code completions, please wait ...', 0) script = jedi.Script( self.GetText(), path=self.filename if os.path.isabs(self.filename) else None) # todo - create Script() periodically compList = [i.name for i in script.complete( self.caretLine + 1, self.caretColumn, fuzzy=False)] # todo - check if have a perfect match and veto AC self.coder.SetStatusText('', 0) if compList: self.AutoCompShow(0, " ".join(compList)) def ShowCalltip(self): """Show a calltip at the current caret position.""" if _hasJedi and self.getFileType() == 'Python': self.coder.SetStatusText('Retrieving calltip, please wait ...', 0) thisObj = jedi.Script(self.getTextUptoCaret()) if hasattr(thisObj, 'get_signatures'): foundRefs = thisObj.get_signatures() elif hasattr(thisObj, 'call_signatures'): # call_signatures deprecated in jedi 0.16.0 (2020) foundRefs = thisObj.call_signatures() else: foundRefs = None self.coder.SetStatusText('', 0) if foundRefs: # enable text wrapping calltipText = foundRefs[0].to_string() if calltipText: calltipText = '\n '.join( textwrap.wrap(calltipText, 76)) # 80 cols after indent y, x = foundRefs[0].bracket_start callTipPos = self.XYToPosition(x, y) self.CallTipShow(callTipPos, calltipText) def MacOpenFile(self, evt): logging.debug('PsychoPyCoder: got MacOpenFile event') def OnUpdateUI(self, evt): """Runs when the editor is changed in any way.""" # check for matching braces braceAtCaret = -1 braceOpposite = -1 charBefore = None caretPos = self.GetCurrentPos() if caretPos > 0: charBefore = self.GetCharAt(caretPos - 1) styleBefore = self.GetStyleAt(caretPos - 1) # check before if charBefore and chr(charBefore) in "[]{}()": if styleBefore == wx.stc.STC_P_OPERATOR: braceAtCaret = caretPos - 1 # check after if braceAtCaret < 0: charAfter = self.GetCharAt(caretPos) styleAfter = self.GetStyleAt(caretPos) if charAfter and chr(charAfter) in "[]{}()": if styleAfter == wx.stc.STC_P_OPERATOR: braceAtCaret = caretPos if braceAtCaret >= 0: braceOpposite = self.BraceMatch(braceAtCaret) if braceAtCaret != -1 and braceOpposite == -1: self.BraceBadLight(braceAtCaret) else: self.BraceHighlight(braceAtCaret, braceOpposite) # Update data about caret position, this can be done once per UI update # to eliminate the need to recalculate these values when needed # elsewhere. self.updateCaretInfo() # set the current line and column in the status bar self.coder.SetStatusText('Line: {} Col: {}'.format( self.caretLine + 1, self.caretColumn + 1), 1) def updateCaretInfo(self): """Update information related to the current caret position in the text. This is done once per UI update which reduces redundant calculations of these values. """ self.indentSize = self.GetIndent() self.caretCurrentPos = self.GetCurrentPos() self.caretVisible, caretColumn, caretLine = self.PositionToXY( self.caretCurrentPos) if self.caretVisible: self.caretColumn = caretColumn self.caretLine = caretLine else: self.caretLine = self.GetCurrentLine() self.caretColumn = self.GetLineLength(self.caretLine) self.caretLineIndentCol = \ self.GetColumn(self.GetLineIndentPosition(self.caretLine)) self.caretLineIndentLevel = self.caretLineIndentCol / self.indentSize self.caretAtIndentLevel = \ (self.caretLineIndentCol % self.indentSize) == 0 # self.shouldBackspaceUntab = \ # self.caretAtIndentLevel and \ # 0 < self.caretColumn <= self.caretLineIndentCol def commentLines(self): # used for the comment/uncomment machinery from ActiveGrid newText = "" for lineNo in self._GetSelectedLineNumbers(): lineText = self.GetLine(lineNo) oneSharp = bool(len(lineText) > 1 and lineText[0] == '#') # todo: is twoSharp ever True when oneSharp is not? twoSharp = bool(len(lineText) > 2 and lineText[:2] == '##') lastLine = bool(lineNo == self.GetLineCount() - 1 and self.GetLineLength(lineNo) == 0) if oneSharp or twoSharp or lastLine: newText = newText + lineText else: newText = newText + "#" + lineText self._ReplaceSelectedLines(newText) def uncommentLines(self): # used for the comment/uncomment machinery from ActiveGrid newText = "" for lineNo in self._GetSelectedLineNumbers(): lineText = self.GetLine(lineNo) # todo: is the next line ever True? seems like should be == '##' if len(lineText) >= 2 and lineText[:2] == "#": lineText = lineText[2:] elif len(lineText) >= 1 and lineText[:1] == "#": lineText = lineText[1:] newText = newText + lineText self._ReplaceSelectedLines(newText) def increaseFontSize(self): self.SetZoom(self.GetZoom() + 1) def decreaseFontSize(self): # Minimum zoom set to - 6 if self.GetZoom() == -6: self.SetZoom(self.GetZoom()) else: self.SetZoom(self.GetZoom() - 1) def resetFontSize(self): """Reset the zoom level.""" self.SetZoom(0) def analyseScript(self): """Parse the document and update the source tree if present. The script is analysed when loaded or when the user interact with it in a way that can potentially change the number of lines of executable code (cutting, pasting, newline, etc.) This may get slow on larger files on older machines. So we may want to change there heuristic a bit to determine when to analyse code in the future. """ if hasattr(self.coder, 'structureWindow'): self.coder.statusBar.SetStatusText(_translate('Analyzing code')) self.coder.structureWindow.refresh() self.coder.statusBar.SetStatusText('') def setLexer(self, lexer=None): """Lexer is a simple string (e.g. 'python', 'html') that will be converted to use the right STC_LEXER_XXXX value """ lexer = 'null' if lexer is None else lexer try: lex = getattr(wx.stc, "STC_LEX_%s" % (lexer.upper())) except AttributeError: logging.warn("Unknown lexer %r. Using plain text." % lexer) lex = wx.stc.STC_LEX_NULL lexer = 'null' # then actually set it self.SetLexer(lex) self.setFonts() if lexer == 'python': self.SetIndentationGuides(self.coder.appData['showIndentGuides']) self.SetProperty("fold", "1") # allow folding self.SetProperty("tab.timmy.whinge.level", "1") elif lexer.lower() == 'html': self.SetProperty("fold", "1") # allow folding # 4 means 'tabs are bad'; 1 means 'flag inconsistency' self.SetProperty("tab.timmy.whinge.level", "1") elif lexer == 'cpp': # JS, C/C++, GLSL, mex, arduino self.SetIndentationGuides(self.coder.appData['showIndentGuides']) self.SetProperty("fold", "1") self.SetProperty("tab.timmy.whinge.level", "1") # don't grey out preprocessor lines self.SetProperty("lexer.cpp.track.preprocessor", "0") elif lexer == 'R': self.SetIndentationGuides(self.coder.appData['showIndentGuides']) self.SetProperty("fold", "1") self.SetProperty("tab.timmy.whinge.level", "1") else: self.SetIndentationGuides(0) self.SetProperty("tab.timmy.whinge.level", "0") # deprecated in newer versions of Scintilla self.SetStyleBits(self.GetStyleBitsNeeded()) # keep text from being squashed and hard to read spacing = self.coder.prefs['lineSpacing'] / 2. self.SetExtraAscent(int(spacing)) self.SetExtraDescent(int(spacing)) self.Colourise(0, -1) self._applyAppTheme() def onModified(self, event): # update the UNSAVED flag and the save icons #notebook = self.GetParent() #mainFrame = notebook.GetParent() self.coder.setFileModified(True) def DoFindNext(self, findData, findDlg=None): # this comes straight from wx.py.editwindow (which is a subclass of # STC control) backward = not (findData.GetFlags() & wx.FR_DOWN) matchcase = (findData.GetFlags() & wx.FR_MATCHCASE) != 0 end = self.GetLength() # Byte string is necessary to let SetSelection() work properly textstring = self.GetTextRangeRaw(0, end) findstring = findData.GetFindString().encode('utf-8') if not matchcase: textstring = textstring.lower() findstring = findstring.lower() if backward: start = self.GetSelection()[0] loc = textstring.rfind(findstring, 0, start) else: start = self.GetSelection()[1] loc = textstring.find(findstring, start) # if it wasn't found then restart at beginning if loc == -1 and start != 0: if backward: start = end loc = textstring.rfind(findstring, 0, start) else: start = 0 loc = textstring.find(findstring, start) # was it still not found? if loc == -1: dlg = dialogs.MessageDialog(self, message=_translate( 'Unable to find "%s"') % findstring.decode('utf-8'), type='Info') dlg.ShowModal() dlg.Destroy() else: # show and select the found text line = self.LineFromPosition(loc) # self.EnsureVisible(line) self.GotoLine(line) self.SetSelection(loc, loc + len(findstring)) if findDlg: if loc == -1: wx.CallAfter(findDlg.SetFocus) return # else: # findDlg.Close() class CoderFrame(BaseAuiFrame, handlers.ThemeMixin): def __init__(self, parent, ID, title, files=(), app=None): self.app = app # type: psychopy.app.PsychoPyApp self.frameType = 'coder' # things the user doesn't set like winsize etc self.appData = self.app.prefs.appData['coder'] self.prefs = self.app.prefs.coder # things about coder that get set self.appPrefs = self.app.prefs.app self.paths = self.app.prefs.paths self.IDs = self.app.IDs self.currentDoc = None self.project = None self.ignoreErrors = False self.fileStatusLastChecked = time.time() self.fileStatusCheckInterval = 5 * 60 # sec self.showingReloadDialog = False # default window title string self.winTitle = "PsychoPy Coder (v{})".format(self.app.version) # we didn't have the key or the win was minimized/invalid if self.appData['winH'] == 0 or self.appData['winW'] == 0: self.appData['winH'], self.appData['winW'] = wx.DefaultSize self.appData['winX'], self.appData['winY'] = wx.DefaultPosition if self.appData['winY'] < 20: self.appData['winY'] = 20 # fix issue in Windows when frame was closed while iconized if self.appData['winX'] == -32000: self.appData['winX'], self.appData['winY'] = wx.DefaultPosition self.appData['winH'], self.appData['winW'] = wx.DefaultSize BaseAuiFrame.__init__( self, parent, ID, title, (self.appData['winX'], self.appData['winY']), (self.appData['winW'], self.appData['winH'])) # detect retina displays (then don't use double-buffering) self.isRetina = \ self.GetContentScaleFactor() != 1 and wx.Platform == '__WXMAC__' self.Hide() # ugly to see it all initialise # create icon if sys.platform == 'darwin': pass # doesn't work and not necessary - handled by app bundle else: iconFile = os.path.join(self.paths['resources'], 'coder.ico') if os.path.isfile(iconFile): self.SetIcon(wx.Icon(iconFile, wx.BITMAP_TYPE_ICO)) # NB not the same as quit - just close the window self.Bind(wx.EVT_CLOSE, self.closeFrame) self.Bind(wx.EVT_IDLE, self.onIdle) if 'state' in self.appData and self.appData['state'] == 'maxim': self.Maximize() # initialise some attributes self.modulesLoaded = False # goes true when loading thread completes self.findDlg = None self.findData = wx.FindReplaceData() self.findData.SetFlags(wx.FR_DOWN) self.importedScripts = {} self.scriptProcess = None self.scriptProcessID = None self.db = None # debugger self._lastCaretPos = None # setup universal shortcuts accelTable = self.app.makeAccelTable() self.SetAcceleratorTable(accelTable) # Setup pane and art managers self.paneManager = self.getAuiManager() # Create menus and status bar self.fileMenu = self.editMenu = self.viewMenu = None self.helpMenu = self.toolsMenu = None self.makeMenus() self.makeStatusBar() self.pavloviaMenu.syncBtn.Enable(bool(self.filename)) self.pavloviaMenu.newBtn.Enable(bool(self.filename)) # Link to file drop function self.SetDropTarget(FileDropTarget(targetFrame=self)) # Create editor notebook self.notebook = StyledNotebook( self, -1, size=wx.Size(480, 480), agwStyle=aui.AUI_NB_TAB_MOVE | aui.AUI_NB_CLOSE_ON_ACTIVE_TAB) # add ribbon self.ribbon = CoderRibbon(self) self.paneManager.AddPane(self.ribbon, aui.AuiPaneInfo(). Name("Ribbon"). DockFixed(True). CloseButton(False).MaximizeButton(True).PaneBorder(False).CaptionVisible(False). Top()) # Add editor panel self.paneManager.AddPane(self.notebook, aui.AuiPaneInfo(). Name("Editor"). Caption(_translate("Editor")). BestSize((480, 480)). Floatable(False). Movable(False). Center(). PaneBorder(True). # 'center panes' expand CloseButton(False). MaximizeButton(True)) # Create source assistant notebook self.sourceAsst = StyledNotebook( self, wx.ID_ANY, size=wx.Size(500, 600), agwStyle=aui.AUI_NB_CLOSE_ON_ALL_TABS | aui.AUI_NB_TAB_SPLIT | aui.AUI_NB_TAB_MOVE) self.sourceAsst.GetAuiManager().SetArtProvider(handlers.PsychopyDockArt()) self.structureWindow = SourceTreePanel(self.sourceAsst, self) self.fileBrowserWindow = FileBrowserPanel(self.sourceAsst, self) # Add structure page to source assistant self.structureWindow.SetName("Structure") self.sourceAsst.AddPage(self.structureWindow, "Structure") # Add file browser page to source assistant self.fileBrowserWindow.SetName("FileBrowser") self.sourceAsst.AddPage(self.fileBrowserWindow, "File Browser") # remove close buttons for i in range(self.sourceAsst.GetPageCount()): self.sourceAsst.SetCloseButton(i, False) # Add source assistant panel self.paneManager.AddPane(self.sourceAsst, aui.AuiPaneInfo(). BestSize((500, 600)). Floatable(False). BottomDockable(False).TopDockable(False). CloseButton(False).PaneBorder(False). Name("SourceAsst"). Caption(_translate("Source Assistant")). Left()) self.notebook.SetFocus() # Link functions self.notebook.Bind(aui.EVT_AUINOTEBOOK_PAGE_CLOSE, self.fileClose) self.notebook.Bind(aui.EVT_AUINOTEBOOK_PAGE_CHANGED, self.pageChanged) self.Bind(wx.EVT_FIND, self.OnFindNext) self.Bind(wx.EVT_FIND_NEXT, self.OnFindNext) #self.Bind(wx.EVT_FIND_CLOSE, self.OnFindClose) self.Bind(wx.EVT_END_PROCESS, self.onProcessEnded) # take files from arguments and append the previously opened files filename = "" if files not in [None, [], ()]: for filename in files: if not os.path.isfile(filename): continue self.setCurrentDoc(filename, keepHidden=True) # Create shelf notebook self.shelf = StyledNotebook( self, wx.ID_ANY, size=wx.Size(600, 600), agwStyle=aui.AUI_NB_CLOSE_ON_ALL_TABS) self.shelf.GetAuiManager().SetArtProvider(handlers.PsychopyDockArt()) # Create shell self._useShell = 'pyshell' self.shell = PythonREPLCtrl(self) # Add shell to output pane self.shell.SetName("PythonShell") self.shelf.AddPage(self.shell, _translate('Shell')) # script output panel self.consoleOutputPanel = ScriptOutputPanel(self.shelf) self.consoleOutput = self.consoleOutputPanel.ctrl self.consoleOutput.SetName("ConsoleOutput") self.shelf.AddPage(self.consoleOutputPanel, _translate('Output')) for i in range(self.shelf.GetPageCount()): self.shelf.SetCloseButton(i, False) # Add shelf panel self.paneManager.AddPane(self.shelf, aui.AuiPaneInfo(). Name("Shelf"). Caption(_translate("Shelf")). BestSize((600, 250)).PaneBorder(False). Floatable(False). Movable(True). BottomDockable(True).TopDockable(True). CloseButton(False). Bottom()) self.unitTestFrame = None # Link to Runner output if self.app.runner is None: self.app.showRunner() self.outputWindow = self.consoleOutput self.outputWindow.write(_translate('Welcome to PsychoPy3!') + '\n') self.outputWindow.write("v%s\n" % self.app.version) # Manage perspective self.SetMinSize(wx.Size(640, 480)) # min size for whole window if (self.appData['auiPerspective'] and 'Shelf' in self.appData['auiPerspective']): try: self.paneManager.LoadPerspective(self.appData['auiPerspective']) except Exception as err: logging.error("Error loading perspective: %s" % err) # defaults for the window if the perspective fails self.SetSize(wx.Size(1024, 800)) self.Fit() self.paneManager.GetPane('SourceAsst').Caption(_translate("Source Assistant")) self.paneManager.GetPane('Editor').Caption(_translate("Editor")) else: self.SetSize(wx.Size(1024, 800)) self.Fit() # Update panes PsychopyToolbar isExp = filename.endswith(".py") or filename.endswith(".psyexp") # Hide panels as specified self.paneManager.GetPane("SourceAsst").Show(self.prefs['showSourceAsst']) self.paneManager.GetPane("Shelf").Show(self.prefs['showOutput']) self.paneManager.GetPane("Ribbon").Show() self.paneManager.Update() #self.chkShowAutoComp.Check(self.prefs['autocomplete']) self.SendSizeEvent() self.app.trackFrame(self) self.theme = colors.theme # disable save buttons if currentDoc is None if self.currentDoc is None: self.ribbon.buttons['save'].Disable() self.ribbon.buttons['saveas'].Disable() @property def useAutoComp(self): """Show autocomplete while typing.""" return self.prefs['autocomplete'] def GetAuiManager(self): return self.paneManager @property def session(self): """ Current Pavlovia session """ return pavlovia.getCurrentSession() def outputContextMenu(self, event): """Custom context menu for output window. Provides menu items to clear all, select all and copy selected text.""" if not hasattr(self, "outputMenuID1"): self.outputMenuID1 = wx.NewIdRef(count=1) self.outputMenuID2 = wx.NewIdRef(count=1) self.outputMenuID3 = wx.NewIdRef(count=1) self.Bind(wx.EVT_MENU, self.outputClear, id=self.outputMenuID1) self.Bind(wx.EVT_MENU, self.outputSelectAll, id=self.outputMenuID2) self.Bind(wx.EVT_MENU, self.outputCopy, id=self.outputMenuID3) menu = wx.Menu() itemClear = wx.MenuItem(menu, self.outputMenuID1, "Clear All") itemSelect = wx.MenuItem(menu, self.outputMenuID2, "Select All") itemCopy = wx.MenuItem(menu, self.outputMenuID3, "Copy") menu.Append(itemClear) menu.AppendSeparator() menu.Append(itemSelect) menu.Append(itemCopy) # Popup the menu. If an item is selected then its handler # will be called before PopupMenu returns. self.PopupMenu(menu) menu.Destroy() def outputClear(self, event): """Clears the output window in Coder""" self.outputWindow.Clear() def outputSelectAll(self, event): """Selects all text from the output window in Coder""" self.outputWindow.SelectAll() def outputCopy(self, event): """Copies all text from the output window in Coder""" self.outputWindow.Copy() def makeMenus(self): # ---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.fileHistory = wx.FileHistory(maxFiles=10) self.recentFilesMenu = wx.Menu() self.fileHistory.UseMenu(self.recentFilesMenu) for filename in self.appData['fileHistory']: self.fileHistory.AddFileToHistory(filename) self.Bind(wx.EVT_MENU_RANGE, self.OnFileHistory, id=wx.ID_FILE1, id2=wx.ID_FILE9) # add items to file menu keyCodes = self.app.keys menu = self.fileMenu menu.Append(wx.ID_NEW, _translate("&New\t%s") % keyCodes['new']) menu.Append(wx.ID_OPEN, _translate("&Open...\t%s") % keyCodes['open']) menu.AppendSubMenu(self.recentFilesMenu, _translate("Open &Recent")) menu.Append(wx.ID_SAVE, _translate("&Save\t%s") % keyCodes['save'], _translate("Save current file")) menu.Enable(wx.ID_SAVE, False) menu.Append(wx.ID_SAVEAS, _translate("Save &as...\t%s") % keyCodes['saveAs'], _translate("Save current python file as...")) menu.Enable(wx.ID_SAVEAS, False) menu.Append(wx.ID_CLOSE, _translate("&Close file\t%s") % keyCodes['close'], _translate("Close current file")) menu.Append(wx.ID_CLOSE_ALL, _translate("Close all files"), _translate("Close all files in the editor.")) menu.AppendSeparator() self.Bind(wx.EVT_MENU, self.fileNew, id=wx.ID_NEW) self.Bind(wx.EVT_MENU, self.fileOpen, id=wx.ID_OPEN) self.Bind(wx.EVT_MENU, self.fileSave, id=wx.ID_SAVE) self.Bind(wx.EVT_MENU, self.fileSaveAs, id=wx.ID_SAVEAS) self.Bind(wx.EVT_MENU, self.fileClose, id=wx.ID_CLOSE) self.Bind(wx.EVT_MENU, self.fileCloseAll, id=wx.ID_CLOSE_ALL) item = menu.Append(wx.ID_ANY, _translate("Print\t%s") % keyCodes['print']) self.Bind(wx.EVT_MENU, self.filePrint, id=item.GetId()) menu.AppendSeparator() msg = _translate("&Preferences\t%s") item = menu.Append(wx.ID_PREFERENCES, msg % keyCodes['preferences']) self.Bind(wx.EVT_MENU, self.app.showPrefs, id=item.GetId()) 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, id=item.GetId()) # -------------Close coder frame menu.AppendSeparator() msg = _translate("Close PsychoPy Coder") item = menu.Append(wx.ID_ANY, msg) self.Bind(wx.EVT_MENU, self.closeFrame, id=item.GetId()) # -------------quit menu.AppendSeparator() menu.Append(wx.ID_EXIT, _translate("&Quit\t%s") % keyCodes['quit'], _translate("Terminate the program")) self.Bind(wx.EVT_MENU, self.quit, id=wx.ID_EXIT) # ---_edit---#000000#FFFFFF------------------------------------------- self.editMenu = wx.Menu() menu = self.editMenu menuBar.Append(self.editMenu, _translate('&Edit')) menu.Append(wx.ID_CUT, _translate("Cu&t\t%s") % keyCodes['cut']) self.Bind(wx.EVT_MENU, self.cut, id=wx.ID_CUT) menu.Append(wx.ID_COPY, _translate("&Copy\t%s") % keyCodes['copy']) self.Bind(wx.EVT_MENU, self.copy, id=wx.ID_COPY) menu.Append(wx.ID_PASTE, _translate("&Paste\t%s") % keyCodes['paste']) self.Bind(wx.EVT_MENU, self.paste, id=wx.ID_PASTE) hnt = _translate("Duplicate the current line (or current selection)") menu.Append(wx.ID_DUPLICATE, _translate("&Duplicate\t%s") % keyCodes['duplicate'], hnt) self.Bind(wx.EVT_MENU, self.duplicateLine, id=wx.ID_DUPLICATE) menu.AppendSeparator() item = menu.Append(wx.ID_ANY, _translate("&Find\t%s") % keyCodes['find']) self.Bind(wx.EVT_MENU, self.OnFindOpen, id=item.GetId()) item = menu.Append(wx.ID_ANY, _translate("Find &Next\t%s") % keyCodes['findAgain']) self.Bind(wx.EVT_MENU, self.OnFindNext, id=item.GetId()) menu.AppendSeparator() item = menu.Append(wx.ID_ANY, _translate("Comment\t%s") % keyCodes['comment'], _translate("Comment selected lines"), wx.ITEM_NORMAL) self.Bind(wx.EVT_MENU, self.commentSelected, id=item.GetId()) item = menu.Append(wx.ID_ANY, _translate("Uncomment\t%s") % keyCodes['uncomment'], _translate("Un-comment selected lines"), wx.ITEM_NORMAL) self.Bind(wx.EVT_MENU, self.uncommentSelected, id=item.GetId()) item = menu.Append(wx.ID_ANY, _translate("Toggle comment\t%s") % keyCodes['toggle comment'], _translate("Toggle commenting of selected lines"), wx.ITEM_NORMAL) self.Bind(wx.EVT_MENU, self.toggleComments, id=item.GetId()) item = menu.Append(wx.ID_ANY, _translate("Toggle fold\t%s") % keyCodes['fold'], _translate("Toggle folding of top level"), wx.ITEM_NORMAL) self.Bind(wx.EVT_MENU, self.foldAll, id=item.GetId()) menu.AppendSeparator() item = menu.Append(wx.ID_ANY, _translate("Indent selection\t%s") % keyCodes['indent'], _translate("Increase indentation of current line"), wx.ITEM_NORMAL) self.Bind(wx.EVT_MENU, self.indent, id=item.GetId()) item = menu.Append(wx.ID_ANY, _translate("Dedent selection\t%s") % keyCodes['dedent'], _translate("Decrease indentation of current line"), wx.ITEM_NORMAL) self.Bind(wx.EVT_MENU, self.dedent, id=item.GetId()) hnt = _translate("Try to indent to the correct position w.r.t. " "last line") item = menu.Append(wx.ID_ANY, _translate("SmartIndent\t%s") % keyCodes['smartIndent'], hnt, wx.ITEM_NORMAL) self.Bind(wx.EVT_MENU, self.smartIndent, id=item.GetId()) menu.AppendSeparator() menu.Append(wx.ID_UNDO, _translate("Undo\t%s") % self.app.keys['undo'], _translate("Undo last action"), wx.ITEM_NORMAL) self.Bind(wx.EVT_MENU, self.undo, id=wx.ID_UNDO) menu.Append(wx.ID_REDO, _translate("Redo\t%s") % self.app.keys['redo'], _translate("Redo last action"), wx.ITEM_NORMAL) self.Bind(wx.EVT_MENU, self.redo, id=wx.ID_REDO) menu.AppendSeparator() item = menu.Append(wx.ID_ANY, _translate("Enlarge font\t%s") % self.app.keys['enlargeFont'], _translate("Increase font size"), wx.ITEM_NORMAL) self.Bind(wx.EVT_MENU, self.bigFont, id=item.GetId()) item = menu.Append(wx.ID_ANY, _translate("Shrink font\t%s") % self.app.keys['shrinkFont'], _translate("Decrease font size"), wx.ITEM_NORMAL) self.Bind(wx.EVT_MENU, self.smallFont, id=item.GetId()) item = menu.Append(wx.ID_ANY, _translate("Reset font"), _translate("Return fonts to their original size."), wx.ITEM_NORMAL) self.Bind(wx.EVT_MENU, self.resetFont, id=item.GetId()) menu.AppendSeparator() # submenu for changing working directory sm = wx.Menu() item = sm.Append( wx.ID_ANY, _translate("Editor file location"), "", wx.ITEM_NORMAL) self.Bind(wx.EVT_MENU, self.onSetCWDFromEditor, id=item.GetId()) item = sm.Append( wx.ID_ANY, _translate("File browser pane location"), "", wx.ITEM_NORMAL) self.Bind(wx.EVT_MENU, self.onSetCWDFromBrowserPane, id=item.GetId()) sm.AppendSeparator() item = sm.Append( wx.ID_ANY, _translate("Choose directory ..."), "", wx.ITEM_NORMAL) self.Bind(wx.EVT_MENU, self.onSetCWDFromBrowse, id=item.GetId()) menu.Append(wx.ID_ANY, _translate("Change working directory to ..."), sm) # ---_view---#000000#FFFFFF------------------------------------------- self.viewMenu = wx.Menu() menu = self.viewMenu menuBar.Append(self.viewMenu, _translate('&View')) # Panel switcher self.panelsMenu = wx.Menu() menu.AppendSubMenu(self.panelsMenu, _translate("Panels")) # output window key = keyCodes['toggleOutputPanel'] hint = _translate("Shows the output and shell panes (and starts " "capturing stdout)") self.outputChk = self.panelsMenu.AppendCheckItem( wx.ID_ANY, _translate("&Output/Shell\t%s") % key, hint) self.outputChk.Check(self.prefs['showOutput']) self.Bind(wx.EVT_MENU, self.setOutputWindow, id=self.outputChk.GetId()) # source assistant hint = _translate("Hide/show the source assistant pane.") self.sourceAsstChk = self.panelsMenu.AppendCheckItem(wx.ID_ANY, _translate("Source Assistant"), hint) self.sourceAsstChk.Check(self.prefs['showSourceAsst']) self.Bind(wx.EVT_MENU, self.setSourceAsst, id=self.sourceAsstChk.GetId()) # indent guides key = keyCodes['toggleIndentGuides'] hint = _translate("Shows guides in the editor for your " "indentation level") self.indentGuideChk = menu.AppendCheckItem(wx.ID_ANY, _translate("&Indentation guides\t%s") % key, hint) self.indentGuideChk.Check(self.appData['showIndentGuides']) self.Bind(wx.EVT_MENU, self.setShowIndentGuides, self.indentGuideChk) # whitespace key = keyCodes['toggleWhitespace'] hint = _translate("Show whitespace characters in the code") self.showWhitespaceChk = menu.AppendCheckItem(wx.ID_ANY, _translate("&Whitespace\t%s") % key, hint) self.showWhitespaceChk.Check(self.appData['showWhitespace']) self.Bind(wx.EVT_MENU, self.setShowWhitespace, self.showWhitespaceChk) # EOL markers key = keyCodes['toggleEOLs'] hint = _translate("Show End Of Line markers in the code") self.showEOLsChk = menu.AppendCheckItem( wx.ID_ANY, _translate("Show &EOLs\t%s") % key, hint) self.showEOLsChk.Check(self.appData['showEOLs']) self.Bind(wx.EVT_MENU, self.setShowEOLs, id=self.showEOLsChk.GetId()) menu.AppendSeparator() hint = _translate("Enable/disable line wrapping in editors.") self.lineWrapChk = menu.AppendCheckItem( wx.ID_ANY, _translate("Line wrapping"), hint) self.lineWrapChk.Check(False) self.Bind(wx.EVT_MENU, self.onWordWrapCheck, self.lineWrapChk) menu.AppendSeparator() # Theme Switcher self.themesMenu = ThemeSwitcher(app=self.app) menu.AppendSubMenu(self.themesMenu, _translate("&Themes")) # Frame switcher FrameSwitcher.makeViewSwitcherButtons(menu, frame=self, app=self.app) # ---_view---#000000#FFFFFF------------------------------------------- # self.shellMenu = wx.Menu() # menuBar.Append(self.shellMenu, _translate('&Shell')) # # menu = self.shellMenu # item = menu.Append( # wx.ID_ANY, # _translate("Start Python Session"), # _translate("Start a new Python session in the shell."), # wx.ITEM_NORMAL) # self.Bind(wx.EVT_MENU, self.onStartShellSession, id=item.GetId()) # menu.AppendSeparator() # item = menu.Append( # wx.ID_ANY, # _translate("Run Line\tF6"), # _translate("Push the line at the caret to the shell."), # wx.ITEM_NORMAL) # self.Bind(wx.EVT_MENU, self.onPushLineToShell, id=item.GetId()) # menu.Append(ID_UNFOLDALL, "Unfold All\tF3", # "Unfold all lines", wx.ITEM_NORMAL) # self.Bind(wx.EVT_MENU, self.unfoldAll, id=ID_UNFOLDALL) # ---_tools---#000000#FFFFFF------------------------------------------ self.toolsMenu = wx.Menu() menu = self.toolsMenu menuBar.Append(self.toolsMenu, _translate('&Tools')) item = menu.Append(wx.ID_ANY, _translate("Monitor Center"), _translate("To set information about your monitor")) self.Bind(wx.EVT_MENU, self.app.openMonitorCenter, id=item.GetId()) # self.analyseAutoChk = self.toolsMenu.AppendCheckItem(self.IDs.analyzeAuto, # "Analyse on file save/open", # "Automatically analyse source (for autocomplete etc...). # Can slow down the editor on a slow machine or with large files") # self.Bind(wx.EVT_MENU, self.setAnalyseAuto, id=self.IDs.analyzeAuto) # self.analyseAutoChk.Check(self.prefs['analyseAuto']) # self.toolsMenu.Append(self.IDs.analyzeNow, # "Analyse now\t%s" %self.app.keys['analyseCode'], # "Force a reananalysis of the code now") # self.Bind(wx.EVT_MENU, self.analyseCodeNow, id=self.IDs.analyzeNow) self.IDs.cdrRun = menu.Append(wx.ID_ANY, _translate("Run/pilot\t%s") % keyCodes['runScript'], _translate("Run the current script")).GetId() self.Bind(wx.EVT_MENU, self.onRunShortcut, id=self.IDs.cdrRun) item = menu.Append(wx.ID_ANY, _translate("Send to runner\t%s") % keyCodes['runnerScript'], _translate("Send current script to runner")).GetId() self.Bind(wx.EVT_MENU, self.runFile, id=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, id=item.GetId()) 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) item = menu.Append(wx.ID_ANY, _translate("Benchmark wizard"), _translate("Check software & hardware, generate report")) self.Bind(wx.EVT_MENU, self.app.benchmarkWizard, id=item.GetId()) item = menu.Append(wx.ID_ANY, _translate("csv from psydat"), _translate("Create a .csv file from an existing .psydat file")) self.Bind(wx.EVT_MENU, self.app.csvFromPsydat, id=item.GetId()) if self.appPrefs['debugMode']: item = menu.Append(wx.ID_ANY, _translate("Unit &testing...\tCtrl-T"), _translate("Show dialog to run unit tests")) self.Bind(wx.EVT_MENU, self.onUnitTests, id=item.GetId()) # ---_demos---#000000#FFFFFF------------------------------------------ self.demosMenu = wx.Menu() menuBar.Append(self.demosMenu, _translate('&Demos')) # Make demos menu updateDemosMenu(self, self.demosMenu, str(Path(self.paths['demos']) / "coder"), ext=".py") # also add simple demos to root self.demosMenu.AppendSeparator() demos = glob.glob(os.path.join(self.paths['demos'], 'coder', '*.py')) for thisFile in demos: shortname = thisFile.split(os.path.sep)[-1] if shortname.startswith('_'): continue # remove any 'private' files item = self.demosMenu.Append(wx.ID_ANY, shortname) thisID = item.GetId() self.demos[thisID] = thisFile self.Bind(wx.EVT_MENU, self.demoLoad, id=thisID) # ---_shell---#000000#FFFFFF-------------------------------------------- # self.shellMenu = wx.Menu() # menu = self.shellMenu # menuBar.Append(menu, '&Shell') # # item = menu.Append( # wx.ID_ANY, # "Run selected line\tCtrl+Enter", # "Pushes selected lines to the shell and executes them.") # self.Bind(wx.EVT_MENU, self.onPushLineToShell, id=item.GetId()) # ---_projects---#000000#FFFFFF--------------------------------------- self.pavloviaMenu = psychopy.app.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')) item = self.helpMenu.Append(wx.ID_ANY, _translate("&PsychoPy Homepage"), _translate("Go to the PsychoPy homepage")) self.Bind(wx.EVT_MENU, self.app.followLink, id=item.GetId()) self.app.urls[item.GetId()] = self.app.urls['psychopyHome'] item = self.helpMenu.Append(wx.ID_ANY, _translate("&PsychoPy Coder Tutorial"), _translate("Go to the online PsychoPy tutorial")) self.Bind(wx.EVT_MENU, self.app.followLink, id=item.GetId()) self.app.urls[item.GetId()] = self.app.urls['coderTutorial'] item = self.helpMenu.Append(wx.ID_ANY, _translate("&PsychoPy API (reference)"), _translate("Go to the online PsychoPy reference manual")) self.Bind(wx.EVT_MENU, self.app.followLink, id=item.GetId()) self.app.urls[item.GetId()] = self.app.urls['psychopyReference'] self.helpMenu.AppendSeparator() item = self.helpMenu.Append(wx.ID_ANY, _translate("&System Info..."), _translate("Get system information.")) self.Bind(wx.EVT_MENU, self.app.showSystemInfo, id=item.GetId()) self.helpMenu.AppendSeparator() # on mac this will move to the application menu self.helpMenu.Append(wx.ID_ABOUT, _translate("&About..."), _translate("About PsychoPy")) self.Bind(wx.EVT_MENU, self.app.showAbout, id=wx.ID_ABOUT) item = self.helpMenu.Append(wx.ID_ANY, _translate("&News..."), _translate("News")) self.Bind(wx.EVT_MENU, self.app.showNews, id=item.GetId()) self.SetMenuBar(menuBar) def makeStatusBar(self): """Make the status bar for Coder.""" self.statusBar = wx.StatusBar(self, wx.ID_ANY) self.statusBar.SetFieldsCount(4) self.statusBar.SetStatusWidths([-2, 160, 160, 160]) self.SetStatusBar(self.statusBar) def onWordWrapCheck(self, event): """Enable/disable word wrapping when the menu item is checked.""" checked = event.IsChecked() for pageId in range(self.notebook.GetPageCount()): page = self.notebook.GetPage(pageId) page.SetWrapMode( wx.stc.STC_WRAP_WORD if checked else wx.stc.STC_WRAP_NONE) event.Skip() def onSetCWDFromEditor(self, event): """Set the current working directory to the location of the current file in the editor.""" if self.currentDoc is None: dlg = wx.MessageDialog( self, "Cannot set working directory, no document open in editor.", style=wx.ICON_ERROR | wx.OK) dlg.ShowModal() dlg.Destroy() event.Skip() return if not os.path.isabs(self.currentDoc.filename): dlg = wx.MessageDialog( self, "Cannot change working directory to location of file `{}`. It" " needs to be saved first.".format(self.currentDoc.filename), style=wx.ICON_ERROR | wx.OK) dlg.ShowModal() dlg.Destroy() event.Skip() return # split the file off the path cwdpath, _ = os.path.split(self.currentDoc.filename) # set the working directory try: os.chdir(cwdpath) except OSError: dlg = wx.MessageDialog( self, "Cannot set `{}` as working directory.".format(cwdpath), style=wx.ICON_ERROR | wx.OK) dlg.ShowModal() dlg.Destroy() event.Skip() return if hasattr(self, 'fileBrowserWindow'): dlg = wx.MessageDialog( self, "Working directory changed, would you like to display it in " "the file browser pane?", 'Question', style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION) if dlg.ShowModal() == wx.ID_YES: self.fileBrowserWindow.gotoDir(cwdpath) def onStartShellSession(self, event): """Start a new Python session in the shell.""" if hasattr(self, 'shell'): self.shell.start() self.shell.SetFocus() def onPushLineToShell(self, event): """Push the currently selected line in the editor to the console and run it..""" if hasattr(self, 'shell'): ed = self.currentDoc if ed is None: # no document selected return lineText, _ = ed.GetCurLine() self.shell.clearAndReplaceTyped(lineText) self.shell.submit(self.shell.getTyped()) ed.LineDown() def onSetCWDFromBrowserPane(self, event): """Set the current working directory by browsing for it.""" if not hasattr(self, 'fileBrowserWindow'): dlg = wx.MessageDialog( self, "Cannot set working directory, file browser pane unavailable.", "Error", style=wx.ICON_ERROR | wx.OK) dlg.ShowModal() dlg.Destroy() event.Skip() cwdpath = self.fileBrowserWindow.currentPath try: os.chdir(cwdpath) except OSError: dlg = wx.MessageDialog( self, "Cannot set `{}` as working directory.".format(cwdpath), "Error", style=wx.ICON_ERROR | wx.OK) dlg.ShowModal() dlg.Destroy() event.Skip() return def onSetCWDFromBrowse(self, event): """Set the current working directory by browsing for it.""" dlg = wx.DirDialog(self, "Choose directory ...", "", wx.DD_DEFAULT_STYLE | wx.DD_DIR_MUST_EXIST) if dlg.ShowModal() == wx.ID_OK: cwdpath = dlg.GetPath() dlg.Destroy() else: dlg.Destroy() event.Skip() # user canceled return try: os.chdir(cwdpath) except OSError: dlg = wx.MessageDialog( self, "Cannot set `{}` as working directory.".format(cwdpath), "Error", style=wx.ICON_ERROR | wx.OK) dlg.ShowModal() dlg.Destroy() event.Skip() return if hasattr(self, 'fileBrowserWindow'): dlg = wx.MessageDialog( self, "Working directory changed, would you like to display it in " "the file browser pane?", 'Question', style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION) if dlg.ShowModal() == wx.ID_YES: self.fileBrowserWindow.gotoDir(cwdpath) # mdc - potential feature for the future # def onPushLineToShell(self, event=None): # """Run a line in the code editor in the shell.""" # if self.currentDoc is None: # return # # lineno = self.currentDoc.GetCurrentLine() # cmdText = self.currentDoc.GetLineText(lineno) # # if self._useShell == 'pyshell': # self.shell.run(cmdText, prompt=False) # # self.currentDoc.GotoLine(lineno + 1) def onIdle(self, event): # check the script outputs to see if anything has been written to # stdout if self.scriptProcess is not None: if self.scriptProcess.IsInputAvailable(): stream = self.scriptProcess.GetInputStream() text = stream.read() self.outputWindow.write(text) if self.scriptProcess.IsErrorAvailable(): stream = self.scriptProcess.GetErrorStream() text = stream.read() self.outputWindow.write(text) # check if we're in the same place as before if self.currentDoc is not None: if hasattr(self.currentDoc, 'GetCurrentPos'): pos = self.currentDoc.GetCurrentPos() if self._lastCaretPos != pos: self.currentDoc.OnUpdateUI(evt=None) self._lastCaretPos = pos last = self.fileStatusLastChecked interval = self.fileStatusCheckInterval if time.time() - last > interval and not self.showingReloadDialog: if not self.expectedModTime(self.currentDoc): self.showingReloadDialog = True filename = os.path.basename(self.currentDoc.filename) msg = _translate("'%s' was modified outside of PsychoPy:\n\n" "Reload (without saving)?") % filename dlg = dialogs.MessageDialog(self, message=msg, type='Warning') if dlg.ShowModal() == wx.ID_YES: self.statusBar.SetStatusText(_translate('Reloading file')) self.fileReload(event, filename=self.currentDoc.filename, checkSave=False) self.showingReloadDialog = False self.statusBar.SetStatusText('') dlg.Destroy() self.fileStatusLastChecked = time.time() # Enable / disable save button self.ribbon.buttons['save'].Enable(self.currentDoc.UNSAVED) self.fileMenu.Enable(wx.ID_SAVE, self.currentDoc.UNSAVED) def pageChanged(self, event): """Event called when the user switches between editor tabs.""" old = event.GetOldSelection() # close any auto-complete or calltips when switching pages if old != wx.NOT_FOUND: oldPage = None try: # last page was closed, this will raise and error oldPage = self.notebook.GetPage(old) except Exception: pass if oldPage is not None: if hasattr(oldPage, 'CallTipActive'): if oldPage.CallTipActive(): oldPage.CallTipCancel() oldPage.openBrackets = 0 if hasattr(oldPage, 'AutoCompActive'): if oldPage.AutoCompActive(): oldPage.AutoCompCancel() new = event.GetSelection() self.currentDoc = self.notebook.GetPage(new) self.app.updateWindowMenu() self.setFileModified(self.currentDoc.UNSAVED) self.setTitle(title=self.winTitle, document=self.currentDoc.filename) self.currentDoc.analyseScript() fileType = self.currentDoc.getFileType() # enable run buttons if current file is a Python script if 'sendRunner' in self.ribbon.buttons: isExp = fileType == 'Python' self.ribbon.buttons['sendRunner'].Enable(isExp) self.ribbon.buttons['pilotRunner'].Enable(isExp) self.statusBar.SetStatusText(fileType, 2) # todo: reduce redundancy w.r.t OnIdle() if not self.expectedModTime(self.currentDoc): filename = os.path.basename(self.currentDoc.filename) msg = _translate("'%s' was modified outside of PsychoPy:\n\n" "Reload (without saving)?") % filename dlg = dialogs.MessageDialog(self, message=msg, type='Warning') if dlg.ShowModal() == wx.ID_YES: self.statusBar.SetStatusText(_translate('Reloading file')) self.fileReload(event, filename=self.currentDoc.filename, checkSave=False) self.setFileModified(False) self.statusBar.SetStatusText('') dlg.Destroy() # def pluginManager(self, evt=None, value=True): # """Show the plugin manager frame.""" # PluginManagerFrame(self).ShowModal() def OnFindOpen(self, event): if not self.currentDoc: # don't do anything if there's no document to search return if self.findDlg is not None: # if find dlg already exists, show it and give it focus self.findDlg.Show() self.findDlg.Raise() self.findDlg.SetFocus() else: # if not, make one now win = wx.Window.FindFocus() self.findData.SetFindString(self.currentDoc.GetSelectedText()) self.findDlg = wx.FindReplaceDialog(win, self.findData, "Find", wx.FR_NOWHOLEWORD) self.findDlg.Bind(wx.EVT_FIND_CLOSE, self.OnFindClose) self.findDlg.Show() def OnFindNext(self, event): # find the next occurrence of text according to last find dialogue data if not self.findData.GetFindString(): self.OnFindOpen(event) return self.currentDoc.DoFindNext(self.findData, self.findDlg) # if self.findDlg is not None: # self.OnFindClose(None) def OnFindClose(self, event): self.findDlg.Destroy() self.findDlg = None 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.setCurrentDoc(path) # load the file # add it back to the history so it will be moved up the list self.fileHistory.AddFileToHistory(path) def gotoLine(self, filename=None, line=0): # goto a specific line in a specific file and select all text in it self.setCurrentDoc(filename) self.currentDoc.EnsureVisible(line) self.currentDoc.GotoLine(line) endPos = self.currentDoc.GetCurrentPos() self.currentDoc.GotoLine(line - 1) stPos = self.currentDoc.GetCurrentPos() self.currentDoc.SetSelection(stPos, endPos) def getOpenFilenames(self): """Return the full filename of each open tab""" names = [] for ii in range(self.notebook.GetPageCount()): names.append(self.notebook.GetPage(ii).filename) return names def quit(self, event): self.app.quit() def checkSave(self): """Loop through all open files checking whether they need save """ for ii in range(self.notebook.GetPageCount()): doc = self.notebook.GetPage(ii) filename = doc.filename if doc.UNSAVED: self.notebook.SetSelection(ii) # fetch that page and show it # make sure frame is at front self.Show(True) self.Raise() self.app.SetTopWindow(self) # then bring up dialog msg = _translate('Save changes to %s before quitting?') dlg = dialogs.MessageDialog(self, message=msg % filename, type='Warning') resp = dlg.ShowModal() sys.stdout.flush() dlg.Destroy() if resp == wx.ID_CANCEL: return 0 # return, don't quit elif resp == wx.ID_YES: self.fileSave() # save then quit elif resp == wx.ID_NO: pass # don't save just quit return 1 def closeFrame(self, event=None, checkSave=True): """Close open windows, update prefs.appData (but don't save) and either close the frame or hide it """ if (len(self.app.getAllFrames(frameType="builder")) == 0 and len(self.app.getAllFrames(frameType="runner")) == 0 and sys.platform != 'darwin'): if not self.app.quitting: # send the event so it can be vetoed if needed self.app.quit(event) return # app.quit() will have closed the frame already # check all files before initiating close of any if checkSave and self.checkSave() == 0: return 0 # this signals user cancelled wasShown = self.IsShown() self.Hide() # ugly to see it close all the files independently # store current appData self.appData['prevFiles'] = [] currFiles = self.getOpenFilenames() for thisFileName in currFiles: self.appData['prevFiles'].append(thisFileName) # get size and window layout info if self.IsIconized(): self.Iconize(False) # will return to normal mode to get size info self.appData['state'] = 'normal' elif self.IsMaximized(): # will briefly return to normal mode to get size info self.Maximize(False) self.appData['state'] = 'maxim' else: self.appData['state'] = 'normal' self.appData['auiPerspective'] = self.paneManager.SavePerspective() self.appData['winW'], self.appData['winH'] = self.GetSize() self.appData['winX'], self.appData['winY'] = self.GetPosition() if sys.platform == 'darwin': # for some reason mac wxpython <=2.8 gets this wrong (toolbar?) self.appData['winH'] -= 39 self.appData['fileHistory'] = [] for ii in range(self.fileHistory.GetCount()): self.appData['fileHistory'].append( self.fileHistory.GetHistoryFile(ii)) # as of wx3.0 the AUI manager needs to be uninitialised explicitly self.paneManager.UnInit() self.app.forgetFrame(self) self.Destroy() self.app.coder = None self.app.updateWindowMenu() def filePrint(self, event=None): pr = Printer() docName = self.currentDoc.filename text = codecs.open(docName, 'r', 'utf-8').read() pr.Print(text, docName) def fileNew(self, event=None, filepath=""): self.setCurrentDoc(filepath) def fileReload(self, event, filename=None, checkSave=False): if filename is None: return # should raise an exception docId = self.findDocID(filename) if docId == -1: return doc = self.notebook.GetPage(docId) # is the file still there if os.path.isfile(filename): with io.open(filename, 'r', encoding='utf-8-sig') as f: doc.SetText(f.read()) doc.fileModTime = os.path.getmtime(filename) doc.EmptyUndoBuffer() doc.Colourise(0, -1) doc.UNSAVED = False else: # file was removed after we found the changes, lets # give the user a chance to save his file. self.UNSAVED = True if doc == self.currentDoc: # Enable / disable save button self.ribbon.buttons['save'].Enable(self.currentDoc.UNSAVED) self.fileMenu.Enable(wx.ID_SAVE, self.currentDoc.UNSAVED) self.currentDoc.analyseScript() @property def filename(self): if self.currentDoc: return self.currentDoc.filename def findDocID(self, filename): # find the ID of the current doc for ii in range(self.notebook.GetPageCount()): if self.notebook.GetPage(ii).filename == filename: return ii return -1 def setCurrentDoc(self, filename, keepHidden=False): # check if this file is already open docID = self.findDocID(filename) readOnlyPref = 'readonly' in self.app.prefs.coder readonly = readOnlyPref and self.app.prefs.coder['readonly'] path, shortName = os.path.split(filename) if docID >= 0: self.currentDoc = self.notebook.GetPage(docID) self.notebook.SetSelection(docID) else: # create new page and load document # if there is only a placeholder document then close it if len(self.getOpenFilenames()) == 1: if (len(self.currentDoc.GetText()) == 0 and self.currentDoc.filename.startswith('untitled')): self.fileClose(self.currentDoc.filename) # load text from document if os.path.isfile(filename): try: with io.open(filename, 'r', encoding='utf-8-sig') as f: fileText = f.read() newlines = f.newlines except UnicodeDecodeError: dlg = dialogs.MessageDialog(self, message=_translate( 'Failed to open `{}`. Make sure that encoding of ' 'the file is utf-8.').format(filename), type='Info') dlg.ShowModal() dlg.Destroy() return elif filename == '': pass # user requested a new document else: dlg = dialogs.MessageDialog( self, message='Failed to open {}. Not a file.'.format(filename), type='Info') dlg.ShowModal() dlg.Destroy() return # do nothing # create an editor window to put the text in p = self.currentDoc = CodeEditor(self.notebook, -1, frame=self, readonly=readonly) # load text if filename != '': # put the text in editor self.currentDoc.SetText(fileText) self.currentDoc.newlines = newlines del fileText # delete the buffer self.currentDoc.fileModTime = os.path.getmtime(filename) self.fileHistory.AddFileToHistory(filename) else: # set name for an untitled document filename = shortName = 'untitled.py' allFileNames = self.getOpenFilenames() n = 1 while filename in allFileNames: filename = 'untitled%i.py' % n n += 1 # create modification time for in memory document self.currentDoc.fileModTime = time.time() self.currentDoc.EmptyUndoBuffer() self.notebook.AddPage(p, shortName) nbIndex = len(self.getOpenFilenames()) - 1 if isinstance(self.notebook, wx.Notebook): self.notebook.ChangeSelection(nbIndex) elif isinstance(self.notebook, aui.AuiNotebook): self.notebook.SetSelection(nbIndex) self.currentDoc.filename = filename self.currentDoc.setLexerFromFileName() # chose the best lexer #self.currentDoc.cacheAutoComplete() self.setFileModified(False) self.currentDoc.SetFocus() fileType = self.currentDoc.getFileType() # line wrapping self.currentDoc.SetWrapMode( wx.stc.STC_WRAP_WORD if self.lineWrapChk.IsChecked() else wx.stc.STC_WRAP_NONE) self.statusBar.SetStatusText(fileType, 2) fname = Path(self.currentDoc.filename).name self.setTitle(title=self.winTitle, document=fname) #if len(self.getOpenFilenames()) > 0: self.currentDoc.analyseScript() if os.path.isdir(path): self.fileBrowserWindow.gotoDir(path) if not keepHidden: self.Show() # if the user had closed the frame it might be hidden if readonly: self.currentDoc.SetReadOnly(True) #self.currentDoc._applyAppTheme() isExp = filename.endswith(".py") or filename.endswith(".psyexp") # if the toolbar is done then adjust buttons for key in ("sendRunner", "pilotRunner", "pyrun", "pypilot"): if key in self.ribbon.buttons: self.ribbon.buttons[key].Enable(isExp) # update save/saveas buttons self.ribbon.buttons['save'].Enable(readonly and self.currentDoc.UNSAVED) self.fileMenu.Enable(wx.ID_SAVE, readonly and self.currentDoc.UNSAVED) self.ribbon.buttons['saveas'].Enable(bool(self.filename)) self.fileMenu.Enable(wx.ID_SAVEAS, bool(self.filename)) # update menu items self.pavloviaMenu.syncBtn.Enable(bool(self.filename)) self.pavloviaMenu.newBtn.Enable(bool(self.filename)) self.app.updateWindowMenu() self.fileBrowserWindow.updateFileBrowser() # update pavlovia project self.project = pavlovia.getProject(self.currentDoc.filename) self.ribbon.buttons['pavproject'].updateInfo() def fileOpen(self, event=None, filename=None): if not filename: # get path of current file (empty if current file is '') if hasattr(self.currentDoc, 'filename'): initPath = str(Path(self.currentDoc.filename).parent) else: initPath = "" # Open dlg dlg = wx.FileDialog( self, message=_translate("Open file ..."), defaultDir=initPath, style=wx.FD_OPEN ) if dlg.ShowModal() == wx.ID_OK: filename = dlg.GetPath() self.statusBar.SetStatusText(_translate('Loading file')) else: return -1 if filename and os.path.isfile(filename): if filename.lower().endswith('.psyexp'): self.app.newBuilderFrame(fileName=filename) else: self.setCurrentDoc(filename) # don't do the next step if no file was opened (hack!!) if self.notebook.GetPageCount() > 0: if self.notebook.GetCurrentPage().filename == filename: self.setFileModified(False) self.statusBar.SetStatusText('') # don't do this, this will add unwanted files to the task list - mdc # self.app.runner.addTask(fileName=filename) def expectedModTime(self, doc): # check for possible external changes to the file, based on # mtime-stamps if doc is None: return True # we have no file loaded # files that don't exist DO have the expected mod-time filename = Path(doc.filename) if not filename.is_file(): return True actualModTime = os.path.getmtime(filename) expectedModTime = doc.fileModTime if abs(float(actualModTime) - float(expectedModTime)) > 1: msg = 'File %s modified outside of the Coder (IDE).' % filename print(msg) return False return True def fileSave(self, event=None, filename=None, doc=None): """Save a ``doc`` with a particular ``filename``. If ``doc`` is ``None`` then the current active doc is used. If the current active doc is also ``None``, then quit early. If the ``filename`` is ``None`` then the ``doc``'s current filename is used or a dlg is presented to get a new filename. """ if hasattr(self.currentDoc, 'AutoCompActive'): if self.currentDoc.AutoCompActive(): self.currentDoc.AutoCompCancel() if doc is None: if self.currentDoc is None: return doc = self.currentDoc if filename is None: filename = doc.filename if filename.startswith('untitled'): self.fileSaveAs(filename) # self.setFileModified(False) # done in save-as if saved; don't # want here if not saved there else: # here detect odd conditions, and set failToSave = True to try # 'Save-as' rather than 'Save' failToSave = False if not self.expectedModTime(doc) and os.path.exists(filename): msg = _translate("File appears to have been modified outside " "of PsychoPy:\n %s\nOK to overwrite?") basefile = os.path.basename(doc.filename) dlg = dialogs.MessageDialog(self, message=msg % basefile, type='Warning') if dlg.ShowModal() != wx.ID_YES: failToSave = True dlg.Destroy() if os.path.exists(filename) and not os.access(filename, os.W_OK): msg = _translate("File '%s' lacks write-permission:\n" "Will try save-as instead.") basefile = os.path.basename(doc.filename) dlg = dialogs.MessageDialog(self, message=msg % basefile, type='Info') dlg.ShowModal() failToSave = True dlg.Destroy() try: if failToSave: raise IOError self.statusBar.SetStatusText(_translate('Saving file')) newlines = '\n' # system default, os.linesep with io.open(filename, 'w', encoding='utf-8', newline=newlines) as f: f.write(doc.GetText()) self.setFileModified(False) doc.fileModTime = os.path.getmtime(filename) # JRG except Exception: print("Unable to save %s... trying save-as instead." % os.path.basename(doc.filename)) self.fileSaveAs(filename) if analyseAuto and len(self.getOpenFilenames()) > 0: self.currentDoc.analyseScript() # reset status text self.statusBar.SetStatusText('') self.fileHistory.AddFileToHistory(filename) def fileSaveAs(self, event, filename=None, doc=None): """Save a ``doc`` with a new ``filename``, after presenting a dlg to get a new filename. If ``doc`` is ``None`` then the current active doc is used. If the ``filename`` is not ``None`` then this will be the initial value for the filename in the dlg. """ # cancel autocomplete if active if self.currentDoc.AutoCompActive(): self.currentDoc.AutoCompCancel() if doc is None: doc = self.currentDoc docId = self.notebook.GetSelection() else: docId = self.findDocID(doc.filename) if filename is None: filename = doc.filename # if we have an absolute path then split it initPath, filename = os.path.split(filename) # set wildcards; need strings to appear inside _translate if sys.platform != 'darwin': wildcard = _translate("Python script (*.py)|*.py|" "JavaScript file (*.js)|*.js|" "Text file (*.txt)|*.txt|" "Any file (*.*)|*.*") else: wildcard = _translate("Python script (*.py)|*.py|" "JavaScript file (*.js)|*.js|" "Text file (*.txt)|*.txt|" "Any file (*.*)|*") dlg = wx.FileDialog( self, message=_translate("Save file as ..."), defaultDir=initPath, defaultFile=filename, style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT, wildcard=wildcard) if dlg.ShowModal() == wx.ID_OK: newPath = dlg.GetPath() doc.filename = newPath self.fileSave(event=None, filename=newPath, doc=doc) path, shortName = os.path.split(newPath) self.notebook.SetPageText(docId, shortName) self.setFileModified(False) # JRG: 'doc.filename' should = newPath = dlg.getPath() doc.fileModTime = os.path.getmtime(doc.filename) # update the lexer since the extension could have changed self.currentDoc.setLexerFromFileName() # re-analyse the document self.currentDoc.analyseScript() # Update status bar and title bar labels self.statusBar.SetStatusText(self.currentDoc.getFileType(), 2) self.setTitle(title=self.winTitle, document=self.currentDoc.filename) dlg.Destroy() def fileClose(self, event, filename=None, checkSave=True): if self.currentDoc is None: # so a coder window with no files responds like the builder window # to self.keys.close self.closeFrame() return if filename is None: filename = self.currentDoc.filename self.currentDoc = self.notebook.GetPage(self.notebook.GetSelection()) if self.currentDoc.UNSAVED and checkSave: sys.stdout.flush() msg = _translate('Save changes to %s before quitting?') % filename dlg = dialogs.MessageDialog(self, message=msg, type='Warning') resp = dlg.ShowModal() sys.stdout.flush() dlg.Destroy() if resp == wx.ID_CANCEL: if isinstance(event, aui.AuiNotebookEvent): event.Veto() return -1 # return, don't quit elif resp == wx.ID_YES: # save then quit self.fileSave(None) elif resp == wx.ID_NO: pass # don't save just quit # remove the document and its record currId = self.notebook.GetSelection() # if this was called by AuiNotebookEvent, then page has closed already if not isinstance(event, aui.AuiNotebookEvent): self.notebook.DeletePage(currId) newPageID = self.notebook.GetSelection() else: newPageID = self.notebook.GetSelection() - 1 # set new current doc if newPageID < 0: self.currentDoc = None self.statusBar.SetStatusText("", 1) # clear line pos self.statusBar.SetStatusText("", 2) # clear file type in status bar self.statusBar.SetStatusText("", 3) # psyhcopy version # set window title self.setTitle(title=self.winTitle, document=self.currentDoc) # clear the source tree self.structureWindow.srcTree.DeleteAllItems() # disable save buttons self.ribbon.buttons['save'].Disable() self.ribbon.buttons['saveas'].Disable() else: self.setCurrentDoc(self.getOpenFilenames()[newPageID]) self.structureWindow.refresh() # set to current file status self.setFileModified(self.currentDoc.UNSAVED) # update file browser buttons self.fileBrowserWindow.updateFileBrowser() def fileCloseAll(self, event, checkSave=True): """Close all files open in the editor.""" if self.currentDoc is None: event.Skip() return for fname in self.getOpenFilenames(): self.fileClose(event, fname, checkSave) def sendToRunner(self, evt=None): """ Send the current file to the Runner. """ fullPath = Path(self.currentDoc.filename) # does the file need saving before running? if self.currentDoc.UNSAVED or not fullPath.is_file(): sys.stdout.flush() msg = _translate('Save changes to %s before running?') % fullPath.name dlg = dialogs.MessageDialog(self, message=msg, type='Warning') resp = dlg.ShowModal() sys.stdout.flush() dlg.Destroy() if resp == wx.ID_CANCEL: return False # return, don't run elif resp == wx.ID_YES: self.fileSave(None) # save then run elif resp == wx.ID_NO: pass # just run fullPath = Path(self.currentDoc.filename) # Get full path again in case it has changed if self.app.runner == None: self.app.showRunner() if fullPath.is_file(): if self.ribbon.buttons['pyswitch'].mode: runMode = "run" else: runMode = "pilot" self.app.runner.addTask(fileName=fullPath, runMode=runMode) else: alert(code=6105, strFields={'path': str(fullPath)}) self.app.runner.Raise() self.app.showRunner() return True def onRunShortcut(self, evt=None): """ Callback for when the run shortcut is pressed - will either run or pilot depending on run mode """ if self.currentDoc is None: return # run/pilot according to mode if self.ribbon.buttons['pyswitch'].mode: self.runFile(evt) else: self.pilotFile(evt) def runFile(self, event=None): """ Send the current file to the Runner and run it. """ if self.currentDoc is None: # do nothing if no file is present return if self.sendToRunner(event): self.app.runner.panel.runLocal(event, focusOnExit='coder') self.Raise() def pilotFile(self, event=None): if self.currentDoc is None: return if self.sendToRunner(event): self.app.runner.panel.pilotLocal(event, focusOnExit='coder') self.Raise() def duplicateLine(self, event): """Duplicate the current line.""" self.currentDoc.LineDuplicate() def copy(self, event): """Copy text to the clipboard from the focused widget.""" foc = self.FindFocus() if isinstance(foc, CodeEditor): self.currentDoc.Copy() # let the text ctrl handle this elif hasattr(foc, 'Copy'): # handle any other widget foc.Copy() def cut(self, event): """Cut text from the focused widget to clipboard.""" foc = self.FindFocus() if isinstance(foc, CodeEditor): self.currentDoc.Cut() self.currentDoc.analyseScript() elif hasattr(foc, 'Cut'): foc.Cut() def paste(self, event): """Paste text from the clipboard to the focused object.""" foc = self.FindFocus() if isinstance(foc, CodeEditor): self.currentDoc.Paste() self.currentDoc.analyseScript() elif hasattr(foc, 'Paste'): foc.Paste() def undo(self, event): if self.currentDoc: self.currentDoc.Undo() self.currentDoc.analyseScript() def redo(self, event): if self.currentDoc: self.currentDoc.Redo() self.currentDoc.analyseScript() def commentSelected(self, event): self.currentDoc.commentLines() self.currentDoc.analyseScript() def uncommentSelected(self, event): self.currentDoc.uncommentLines() self.currentDoc.analyseScript() def toggleComments(self, event): self.currentDoc.toggleCommentLines() self.currentDoc.analyseScript() def bigFont(self, event): self.currentDoc.increaseFontSize() def smallFont(self, event): self.currentDoc.decreaseFontSize() def resetFont(self, event): self.currentDoc.resetFontSize() def foldAll(self, event): self.currentDoc.FoldAll(wx.stc.STC_FOLDACTION_TOGGLE) # def unfoldAll(self, event): # self.currentDoc.ToggleFoldAll(expand = False) def setOutputWindow(self, event=None, value=None): # show/hide the output window (from the view menu control) if value is None: value = self.outputChk.IsChecked() self.outputChk.Check(value) if value: # show the pane self.prefs['showOutput'] = True self.paneManager.GetPane('Shelf').Show() else: # hide the pane self.prefs['showOutput'] = False self.paneManager.GetPane('Shelf').Hide() self.app.prefs.saveUserPrefs() try: # includes a validation self.paneManager.Update() except wxAssertionError as err: logging.warn("Exception caught: " + str(err)) def setShowIndentGuides(self, event): # show/hide the source assistant (from the view menu control) newVal = self.indentGuideChk.IsChecked() self.appData['showIndentGuides'] = newVal for ii in range(self.notebook.GetPageCount()): self.notebook.GetPage(ii).SetIndentationGuides(newVal) def setShowWhitespace(self, event): newVal = self.showWhitespaceChk.IsChecked() self.appData['showWhitespace'] = newVal for ii in range(self.notebook.GetPageCount()): self.notebook.GetPage(ii).SetViewWhiteSpace(newVal) def setShowEOLs(self, event): newVal = self.showEOLsChk.IsChecked() self.appData['showEOLs'] = newVal for ii in range(self.notebook.GetPageCount()): self.notebook.GetPage(ii).SetViewEOL(newVal) def onCloseSourceAsst(self, event): """Called when the source assisant is closed.""" pass def setSourceAsst(self, event): # show/hide the source assistant (from the view menu control) if not self.sourceAsstChk.IsChecked(): self.paneManager.GetPane("SourceAsst").Hide() self.prefs['showSourceAsst'] = False else: self.paneManager.GetPane("SourceAsst").Show() self.prefs['showSourceAsst'] = True self.paneManager.Update() # def setAutoComplete(self, event=None): # # show/hide the source assistant (from the view menu control) # self.prefs['autocomplete'] = self.useAutoComp = \ # self.chkShowAutoComp.IsChecked() # def setFileBrowser(self, event): # # show/hide the source file browser # if not self.fileBrowserChk.IsChecked(): # self.paneManager.GetPane("FileBrowser").Hide() # self.prefs['showFileBrowser'] = False # else: # self.paneManager.GetPane("FileBrowser").Show() # self.prefs['showFileBrowser'] = True # self.paneManager.Update() def analyseCodeNow(self, event): self.currentDoc.analyseScript() # def setAnalyseAuto(self, event): # set autoanalysis (from the check control in the tools menu) # if self.analyseAutoChk.IsChecked(): # self.prefs['analyseAuto']=True # else: # self.prefs['analyseAuto']=False def demoLoad(self, event): self.setCurrentDoc(str(self.demos[event.GetId()])) def tabKeyPressed(self, event): # if several chars are selected then smartIndent # if we're at the start of the line then smartIndent if self.currentDoc.shouldTrySmartIndent(): self.smartIndent(event=None) else: # self.currentDoc.CmdKeyExecute(wx.stc.STC_CMD_TAB) pos = self.currentDoc.GetCurrentPos() self.currentDoc.InsertText(pos, '\t') self.currentDoc.SetCurrentPos(pos + 1) self.currentDoc.SetSelection(pos + 1, pos + 1) def smartIndent(self, event): self.currentDoc.smartIndent() def indent(self, event): self.currentDoc.indentSelection(4) def dedent(self, event): self.currentDoc.indentSelection(-4) def setFileModified(self, isModified): # changes the document flag, updates save buttons self.currentDoc.UNSAVED = isModified # Enable / disable save button self.ribbon.buttons['save'].Enable(self.currentDoc.UNSAVED) self.fileMenu.Enable(wx.ID_SAVE, self.currentDoc.UNSAVED) def onProcessEnded(self, event): # this is will check the stdout and stderr for any last messages self.onIdle(event=None) self.scriptProcess = None self.scriptProcessID = None self.ribbon.buttons['sendRunner'].Enable(True) self.ribbon.buttons['pilotRunner'].Enable(True) def onURL(self, evt): """decompose the URL of a file and line number""" # "C:\Program Files\wxPython2.8 Docs and Demos\samples\hangman\hangman.py" tmpFilename, tmpLineNumber = evt.GetString().rsplit('", line ', 1) filename = tmpFilename.split('File "', 1)[1] try: lineNumber = int(tmpLineNumber.split(',')[0]) except ValueError: lineNumber = int(tmpLineNumber.split()[0]) self.gotoLine(filename, lineNumber) def onUnitTests(self, evt=None): """Show the unit tests frame""" if self.unitTestFrame: self.unitTestFrame.Raise() else: self.unitTestFrame = UnitTestFrame(app=self.app) # UnitTestFrame.Show() def openPluginManager(self, evt=None): dlg = psychopy.app.plugin_manager.dialog.EnvironmentManagerDlg(self) dlg.Show() # Do post-close checks dlg.onClose() def onPavloviaSync(self, evt=None): """Push changes to project repo, or create new proj if proj is None""" self.project = pavlovia.getProject(self.currentDoc.filename) self.fileSave(self.currentDoc.filename) # Must save on sync else changes not pushed pavlovia_ui.syncProject(parent=self, file=self.currentDoc.filename, project=self.project) def onPavloviaRun(self, evt=None): # TODO: Allow user to run project from coder pass 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 class StyledNotebook(aui.AuiNotebook, handlers.ThemeMixin): """ Exactly the same as an aui.AuiNotebook, but with methods from handlers.ThemeMixin """ pass class CoderRibbon(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 text file"), callback=parent.fileNew ) # file open self.addButton( section="file", name="open", label=_translate("Open"), icon="fileopen", tooltip=_translate("Open an existing text file"), callback=parent.fileOpen ) # file save self.addButton( section="file", name="save", label=_translate("Save"), icon="filesave", tooltip=_translate("Save current text file"), callback=parent.fileSave ).Disable() # file save as self.addButton( section="file", name="saveas", label=_translate("Save as..."), icon="filesaveas", tooltip=_translate("Save current text file as..."), callback=parent.fileSaveAs ).Disable() 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" ) # settings self.addButton( section="experiment", name='color', label=_translate('Color picker'), icon="color", tooltip=_translate("Open a tool for choosing colors"), callback=parent.app.colorPicker ) # switch run/pilot runPilotSwitch = self.addSwitchCtrl( section="experiment", name="pyswitch", labels=(_translate("Pilot"), _translate("Run")), 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 ).Disable() # 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 ).Disable() # link runner buttons to switch runPilotSwitch.addDependant(self.buttons['sendRunner'], mode=1, action="show") runPilotSwitch.addDependant(self.buttons['pilotRunner'], mode=0, action="show") self.addSeparator() # --- Python --- self.addSection(name="py", label=_translate("Desktop"), icon="desktop") # monitor center self.addButton( section="py", name='monitor', label=_translate('Monitor center'), icon="monitors", tooltip=_translate("Monitor settings and calibration"), callback=parent.app.openMonitorCenter ) # 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 ).Disable() # run Py self.addButton( section="py", name="pyrun", label=_translate("Run"), icon='pyRun', tooltip=_translate("Run the current script in Python"), callback=parent.runFile ).Disable() # link run buttons to switch runPilotSwitch.addDependant(self.buttons['pyrun'], mode=1, action="show") runPilotSwitch.addDependant(self.buttons['pypilot'], mode=0, action="show") self.addSeparator() # --- Browser --- self.addSection( name="browser", label=_translate("Browser"), icon="browser" ) # sync project self.addButton( section="browser", name="pavsync", label=_translate("Sync"), icon='pavsync', tooltip=_translate("Sync project with Pavlovia"), callback=parent.onPavloviaSync ) self.addSeparator() # --- Pavlovia --- self.addSection( name="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 ) # show Coder self.addButton( section="views", name="coder", label=_translate("Show Coder"), icon="showCoder", tooltip=_translate("Switch to Coder view"), callback=parent.app.showCoder ).Disable() # show Runner self.addButton( section="views", name="runner", label=_translate("Show Runner"), icon="showRunner", tooltip=_translate("Switch to Runner view"), callback=parent.app.showRunner ) # start off in run mode runPilotSwitch.setMode(1)
126,503
Python
.py
2,716
34.268041
113
0.57629
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)