Example #1
0
 def _create_parent_chooser(self, sizer, default_dir):
     browser = DirBrowseButton(self, labelText="Parent Directory",
                               dialogTitle="Choose Parent Directory",
                               startDirectory=default_dir,
                               size=(600, -1), newDirectory=True,
                               changeCallback=self.OnPathChanged)
     browser.SetValue(default_dir)
     sizer.Add(browser, 1, wx.EXPAND)
     return browser
Example #2
0
    def _init_ctrls(self, parent):
        self.DecYear = wx.Button(self, -1, '<<', size=(48, 36))
        self.DecYear.Bind(wx.EVT_BUTTON, self.OnDecYear)
        self.DecMonth = wx.Button(self, -1, ' < ', size=(48, 36))
        self.DecMonth.Bind(wx.EVT_BUTTON, self.OnDecMonth)
        self.Current = wx.Button(self, -1, 'Today')
        self.Current.Bind(wx.EVT_BUTTON, self.OnCurrent)
        self.IncMonth = wx.Button(self, -1, ' > ', size=(48, 36))
        self.IncMonth.Bind(wx.EVT_BUTTON, self.OnIncMonth)
        self.IncYear = wx.Button(self, -1, '>>', size=(48, 36))
        self.IncYear.Bind(wx.EVT_BUTTON, self.OnIncYear)
        bsizer = wx.BoxSizer(wx.HORIZONTAL)
        bsizer.Add(self.DecYear, 0, wx.ALL, 2)
        bsizer.Add(self.DecMonth, 0, wx.ALL, 2)
        bsizer.Add(self.Current, 1, wx.ALL | wx.EXPAND, 2)
        bsizer.Add(self.IncMonth, 0, wx.ALL, 2)
        bsizer.Add(self.IncYear, 0, wx.ALL, 2)

        self.Calendar = Calendar(self, -1, size=(200, 300))
        self.Calendar.Bind(wx.lib.calendar.EVT_CALENDAR, self.OnCalendarChange)
        self.Calendar.SetCurrentDay()
        self.Calendar.grid_color = 'BLUE'
        self.Calendar.SetBusType()

        self.FBB = FileBrowseButton(self,
                                    size=(450, -1),
                                    changeCallback=self.OnFBBChange)
        self.FBB.SetLabel('Symbols File:')

        self.DBB = DirBrowseButton(self,
                                   size=(450, -1),
                                   changeCallback=self.OnDBBChange)
        self.DBB.SetLabel('Prices Folder:')

        self.ListBox = gizmos.EditableListBox(
            self,
            -1,
            #              style=gizmos.EL_DEFAULT_STYLE | gizmos.EL_NO_REORDER
        )
        self.ListBox.GetUpButton().Show(False)
        self.ListBox.GetDownButton().Show(False)
        self.ListBox.Bind(wx.EVT_LIST_DELETE_ITEM, self.OnSymbolListChange)
        self.ListBox.Bind(wx.EVT_LIST_INSERT_ITEM, self.OnSymbolListChange)

        self.Download = wx.Button(self, wx.OK, 'Download Prices')
        self.Download.Bind(wx.EVT_BUTTON, self.OnDownload)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.AddSizer(bsizer, 0, wx.LEFT | wx.RIGHT | wx.EXPAND, 5)
        sizer.AddWindow(self.Calendar, 0, wx.LEFT | wx.RIGHT | wx.EXPAND, 5)
        sizer.AddWindow(self.FBB, 0, wx.ALL | wx.EXPAND, 5)
        sizer.AddWindow(self.DBB, 0, wx.ALL | wx.EXPAND, 5)
        sizer.AddWindow(self.ListBox, 1, wx.ALL | wx.EXPAND, 5)
        sizer.AddWindow(self.Download, 0, wx.ALL | wx.ALIGN_RIGHT, 5)
        self.SetSizer(sizer)
	def __init__(self, parent, global_store, *args, **kwargs):
		wx.Panel.__init__(self, parent, *args, **kwargs)

		self.global_store = global_store

		self.capture_dialogs = 0

		# Panel.
		panel_box = wx.BoxSizer(wx.HORIZONTAL)

		## Capture.
		capture_static_box = wx.StaticBox(self, label='Capture')
		capture_box = wx.StaticBoxSizer(capture_static_box, wx.VERTICAL)
		panel_box.Add(capture_box, flag=wx.CENTER|wx.ALL, border=5)

		### Start.
		self.start_button = wx.Button(self, label='Start')
		self.Bind(wx.EVT_BUTTON, self.OnBeginCapture, self.start_button)
		capture_box.Add(self.start_button, flag=wx.CENTER)

		### Continuous.
		self.continuous_checkbox = wx.CheckBox(self, label='Continuous')
		capture_box.Add(self.continuous_checkbox, flag=wx.CENTER)

		## Export.
		export_static_box = wx.StaticBox(self, label='Export')
		export_box = wx.StaticBoxSizer(export_static_box, wx.HORIZONTAL)
		panel_box.Add(export_box, proportion=1, flag=wx.CENTER|wx.ALL, border=5)

		### Enabled.
		self.export_enabled = wx.CheckBox(self, label='')
		self.export_enabled.Value = True
		export_box.Add(self.export_enabled, flag=wx.CENTER)

		### Export path.
		export_path_box = wx.BoxSizer(wx.VERTICAL)
		export_box.Add(export_path_box, proportion=1, flag=wx.CENTER)

		#### Directory.
		self.directory_browse_button = DirBrowseButton(self, labelText='Directory:')
		export_path_box.Add(self.directory_browse_button, flag=wx.EXPAND)

		#### Last file.
		last_file_box = wx.BoxSizer(wx.HORIZONTAL)
		export_path_box.Add(last_file_box, flag=wx.EXPAND)

		last_file_box.Add(wx.StaticText(self, label='Last output: '),flag=wx.ALIGN_CENTER_VERTICAL)#|) wx.ALIGN_RIGHT)
		self.last_file_name = wx.TextCtrl(self, style=wx.TE_READONLY)
		self.last_file_name.BackgroundColour = wx.LIGHT_GREY
		last_file_box.Add(self.last_file_name, proportion=1)

		self.SetSizer(panel_box)
Example #4
0
    def createWizard(self):
        # Create the wizard and the pages
        wizard = Wizard(self, -1, "Opal welcome wizard",
                        wx.EmptyBitmap(200, 200))
        page1 = TitledPage(wizard, "Welcome to Opal")
        page2 = TitledPage(wizard, "Page 2")
        page3 = TitledPage(wizard, "Page 3")
        page4 = TitledPage(wizard, "Page 4")
        self.page1 = page1
        self.page1 = page1

        vbox = wx.BoxSizer(wx.HORIZONTAL)
        lable = wx.StaticText(page1, -1, "Choose your language:")
        choice = wx.Choice(page1, -1, (0, 0), choices=['English'])
        choice.SetSelection(0)
        vbox.Add(lable, 0, wx.ALIGN_CENTRE | wx.ALL, 5)
        vbox.Add(choice, 0, wx.ALIGN_CENTRE | wx.ALL, 5)

        page1.sizer.Add(vbox)
        #         vbox = wx.BoxSizer(wx.HORIZONTAL)
        #         t1 = wx.TextCtrl(page1, -1, "Test it out and see", size=(125, -1))
        #         vbox.Add(t1, 0, wx.ALIGN_CENTRE | wx.ALL, 5)
        #         page1.sizer.Add(vbox)

        page1.sizer.Add(
            wx.StaticText(
                page1, -1, """
            Choose a location of your workspace. 
            When you add books to Opal, they will be copied here. 
            Use an empty folder for a new Opal workspace."""), 0,
            wx.ALIGN_LEFT | wx.ALL, 1)
        dbb = DirBrowseButton(page1,
                              -1,
                              size=(450, -1),
                              changeCallback=self.dbbCallback)
        dbb.SetFocus()
        dbb.SetLabel("Book Library Location")
        dbb.SetHelpText('Please set your default workspace location.')
        dbb.textControl.SetValue(Workspace().path)

        page1.sizer.Add(dbb, 0, wx.ALIGN_CENTRE | wx.ALL, 5)

        wizard.FitToPage(page1)

        # Use the convenience Chain function to connect the pages
        WizardPageSimple.Chain(page1, page2)
        #         WizardPageSimple.Chain(page2, page3)
        #         WizardPageSimple.Chain(page3, page4)

        wizard.GetPageAreaSizer().Add(page1)
        if wizard.RunWizard(page1):
            pass
Example #5
0
 def _create_parent_chooser(self, sizer, default_dir):
     browser = DirBrowseButton(self,
                               labelText="Parent Directory",
                               dialogTitle="Choose Parent Directory",
                               startDirectory=default_dir,
                               size=(600, -1),
                               newDirectory=True,
                               changeCallback=self.OnPathChanged)
     browser.SetBackgroundColour(Colour(self.color_background))
     browser.SetForegroundColour(Colour(self.color_foreground))
     # TODO: Change colors on buttons and text field
     # browser.SetOwnBackgroundColour(Colour(self.color_secondary_background))
     # browser.SetOwnForegroundColour(Colour(self.color_secondary_foreground))
     browser.SetValue(default_dir)
     sizer.Add(browser, 1, wx.EXPAND)
     return browser
Example #6
0
def createDirBrowseButton(parent, label, callback):
    sizer = wx.BoxSizer(wx.VERTICAL)
    sizer2 = wx.BoxSizer(wx.HORIZONTAL)
    lbl = wx.StaticText(parent, -1, label)
    sizer.Add(lbl)
    field = wx.TextCtrl(parent, -1, "")
    sizer2.Add(field)
    btn = DirBrowseButton(parent, -1, changeCallback=callback)
    sizer2.Add(btn)
    sizer.Add(sizer2)
    return sizer
Example #7
0
    def __init__(self, parent):
        wx.Dialog.__init__(self, parent, -1, "Node Selector",
                           wx.DefaultPosition, (400, 200),
                           wx.DEFAULT_DIALOG_STYLE)

        sizer = wx.BoxSizer(wx.VERTICAL)

        self.dbb = DirBrowseButton(self,
                                   -1,
                                   wx.Point(20, 80),
                                   wx.Size(450, -1),
                                   changeCallback=self.OnDbb)

        self.SetModal(False)

        wx.EVT_CLOSE(self, self.OnClose)

        self.node_list = []
class DataCapturePanel(wx.Panel):
	"""
	A panel to start the data capture process, optionally exporting the results to a file.
	"""

	def __init__(self, parent, global_store, *args, **kwargs):
		wx.Panel.__init__(self, parent, *args, **kwargs)

		self.global_store = global_store

		self.capture_dialogs = 0

		# Panel.
		panel_box = wx.BoxSizer(wx.HORIZONTAL)

		## Capture.
		capture_static_box = wx.StaticBox(self, label='Capture')
		capture_box = wx.StaticBoxSizer(capture_static_box, wx.VERTICAL)
		panel_box.Add(capture_box, flag=wx.CENTER|wx.ALL, border=5)

		### Start.
		self.start_button = wx.Button(self, label='Start')
		self.Bind(wx.EVT_BUTTON, self.OnBeginCapture, self.start_button)
		capture_box.Add(self.start_button, flag=wx.CENTER)

		### Continuous.
		self.continuous_checkbox = wx.CheckBox(self, label='Continuous')
		capture_box.Add(self.continuous_checkbox, flag=wx.CENTER)

		## Export.
		export_static_box = wx.StaticBox(self, label='Export')
		export_box = wx.StaticBoxSizer(export_static_box, wx.HORIZONTAL)
		panel_box.Add(export_box, proportion=1, flag=wx.CENTER|wx.ALL, border=5)

		### Enabled.
		self.export_enabled = wx.CheckBox(self, label='')
		self.export_enabled.Value = True
		export_box.Add(self.export_enabled, flag=wx.CENTER)

		### Export path.
		export_path_box = wx.BoxSizer(wx.VERTICAL)
		export_box.Add(export_path_box, proportion=1, flag=wx.CENTER)

		#### Directory.
		self.directory_browse_button = DirBrowseButton(self, labelText='Directory:')
		export_path_box.Add(self.directory_browse_button, flag=wx.EXPAND)

		#### Last file.
		last_file_box = wx.BoxSizer(wx.HORIZONTAL)
		export_path_box.Add(last_file_box, flag=wx.EXPAND)

		last_file_box.Add(wx.StaticText(self, label='Last output: '),flag=wx.ALIGN_CENTER_VERTICAL)#|) wx.ALIGN_RIGHT)
		self.last_file_name = wx.TextCtrl(self, style=wx.TE_READONLY)
		self.last_file_name.BackgroundColour = wx.LIGHT_GREY
		last_file_box.Add(self.last_file_name, proportion=1)

		self.SetSizer(panel_box)

	def OnBeginCapture(self, evt=None):
		# Prevent accidental double-clicking.
		self.start_button.Disable()
		def enable_button():
			sleep(1)
			wx.CallAfter(self.start_button.Enable)
		thr = Thread(target=enable_button)
		thr.daemon = True
		thr.start()

		all_variables = [var for var in list(self.global_store.variables.values()) if var.enabled]
		output_variables = sift(all_variables, OutputVariable)
		input_variables = [var for var in sift(all_variables, InputVariable) if var.resource_name != '']
		condition_variables =  sift(all_variables, ConditionVariable)

		if not output_variables:
			output_variables.append(OutputVariable(order=0, name='<Dummy>', enabled=True))

		output_variables, num_items = sort_output_variables(output_variables)
		condition_variables = sort_condition_variables(condition_variables)

		resource_names = [tuple(var.resource_name for var in group) for group in output_variables]
		measurement_resource_names = [var.resource_name for var in input_variables]
		condition_resource_names = [tuple(set(flatten([var.resource_names for var in group]))) for group in condition_variables]


		continuous = self.continuous_checkbox.Value

		missing_resources = set()
		unreadable_resources = set()
		unwritable_resources = set()
		missing_devices = set()

		pulse_program = self.global_store.pulse_program

		if pulse_program is not None:
			pulse_program = pulse_program.with_resources

			try:
				pulse_program.generate_waveforms(dry_run=True)
			except PulseError as e:
				MessageDialog(self, '\n'.join(e[0]), 'Pulse program error', monospace=True).Show()
				return
			except Exception as e:
				MessageDialog(self, str(e), 'Pulse program error').Show()
				return

			pulse_awg, pulse_oscilloscope = None, None
			pulse_channels = {}

			try:
				pulse_awg = self.global_store.devices[pulse_program.awg].device
				if pulse_awg is None:
					raise KeyError
			except KeyError:
				missing_devices.add(pulse_program.awg)
			else:
				# Gather used channel numbers.
				pulse_channels = dict((k, v) for k, v in list(pulse_program.output_channels.items()) if v is not None)

				actual_channels = list(range(1, len(pulse_awg.channels)))
				invalid_channels = [k for k, v in list(pulse_channels.items()) if v not in actual_channels]

				if invalid_channels:
					MessageDialog(self, 'Invalid channels for: {0}'.format(', '.join(invalid_channels)), 'Invalid channels').Show()
					return

			try:
				pulse_oscilloscope = self.global_store.devices[pulse_program.oscilloscope].device
				if pulse_oscilloscope is None:
					raise KeyError
			except KeyError:
				missing_devices.add(pulse_program.oscilloscope)

			try:
				pulse_config = PulseConfiguration(pulse_program, pulse_channels, pulse_awg, pulse_oscilloscope)
			except TypeError as e:
				MessageDialog(self, str(e), 'Device configuration error').Show()
				return
		else:
			pulse_config = None

		resources = []
		for group in resource_names:
			group_resources = []

			for name in group:
				if name == '':
					group_resources.append((str(len(resources)), None))
				elif name not in self.global_store.resources:
					missing_resources.add(name)
				else:
					resource = self.global_store.resources[name]

					if resource.writable:
						group_resources.append((name, resource))
					else:
						unwritable_resources.add(name)

			resources.append(tuple(group_resources))
			
		measurement_resources = []
		measurement_units = []
		for name in measurement_resource_names:
			if name not in self.global_store.resources:
				missing_resources.add(name)
			else:
				resource = self.global_store.resources[name]

				if resource.readable:
					measurement_resources.append((name, resource))
					measurement_units.append(resource.display_units)
				else:
					unreadable_resources.add(name)
				
		condition_resources = []
		for group in condition_resource_names:
			group_resources = []
			
			for name in group:
				if name not in self.global_store.resources:
					missing_resources.add(name)
				else:
					resource = self.global_store.resources[name]

					if resource.readable:
						group_resources.append((name, resource))
					else:
						#the name may already have been put here by the loop assigning
						#to measurement_resources
						if name not in unreadable_resources:
							unreadable_resources.add(name)

			condition_resources.append(tuple(group_resources))

		mismatched_resources = []
		for (res_name, resource), var in zip(flatten(resources), flatten(output_variables)):
			if resource is None:
				continue

			if resource.units is not None:
				if not (var.type == 'quantity' and
						resource.verify_dimensions(var.units, exception=False, from_string=True)):
					mismatched_resources.append((res_name, var.name))
			else:
				if var.type not in ['float', 'integer']:
					mismatched_resources.append((res_name, var.name))

		for items, msg in [
			(missing_resources, 'Missing resources'),
			(unreadable_resources, 'Unreadable resources'),
			(unwritable_resources, 'Unwritable resources'),
			(missing_devices, 'Missing devices')]:

			if items:
				MessageDialog(self, ', '.join('"{0}"'.format(x) for x in sorted(items)), msg).Show()

		if mismatched_resources:
			MessageDialog(self, ', '.join('Mismatched resource type for resource name {0} with variable name {1}'.format(x[0], x[1]) for x in mismatched_resources),
					'Mismatched resources').Show()

		if (missing_resources or unreadable_resources or unwritable_resources or
				missing_devices or mismatched_resources):
			return
		
		# Check that all the condition arguments are compatible with one another.
		
		for cvar in flatten(condition_variables):
			
			# Get a condition.
			for cond in cvar.conditions:
								
				value1 = cond.arg1
				value2 = cond.arg2
				resource1 = None
				resource2 = None
				
				# If working with resources, use their values as the values, and make the resource available
				
				if cond.type1 == 'resource name':
					resource1 = [resource for (name, resource) in flatten(condition_resources) if name == cond.arg1][0]
					value1 = resource1.value
				if cond.type2 == 'resource name':
					resource2 = [resource for (name, resource) in flatten(condition_resources) if name == cond.arg2][0]
					value2 = resource2.value
				
				# Check if the other argument is in the allowed values
				
				if hasattr(resource1,'allowed_values') and resource1.allowed_values is not None:
					if value2 not in resource1.allowed_values:
						MessageDialog(self, 'In the condition {0}, {1} is not in allowed_values of {2}.'.format(cond, value2, cond.arg1),'Condition error').Show()
						return
				if hasattr(resource2,'allowed_values') and resource2.allowed_values is not None:
					if value1 not in resource2.allowed_values:
						MessageDialog(self, 'In the condition {0}, {1} is not in allowed_values of {2}.'.format(cond, value1, cond.arg2),'Condition error').Show()
						return

				# Check if units agree.
				
				if resource1 is not None and resource1.units is not None:
					try:
						value1.assert_dimensions(value2)
					except ValueError:
						MessageDialog(self, 'In the condition {0}, {1} does not have a dimension.'.format(cond, value2),'Condition error').Show()
						return
					except IncompatibleDimensions:
						MessageDialog(self, 'In the condition {0}, {1} and {2} do not have matching dimensions.'.format(cond, value1, value2),'Condition error').Show()
						return
				if resource2 is not None and resource2.units is not None:
					try:
						value2.assert_dimensions(value1)
					except ValueError:
						MessageDialog(self, 'In the condition {0}, {1} does not have a dimension.'.format(cond, value1),'Condition error').Show()
						return
					except IncompatibleDimensions:
						MessageDialog(self, 'In the condition {0}, {1} and {2} do not have matching dimensions.'.format(cond, value1, value2),'Condition error').Show()
						return


		exporting = False
		if self.export_enabled.Value:
			dir = self.directory_browse_button.GetValue()
			# YYYY-MM-DD_HH-MM-SS.csv
			name = '{0:04}-{1:02}-{2:02}_{3:02}-{4:02}-{5:02}.csv'.format(*localtime())

			if not dir:
				MessageDialog(self, 'No directory selected.', 'Export path').Show()
				return

			if not os.path.isdir(dir):
				MessageDialog(self, 'Invalid directory selected', 'Export path').Show()
				return

			file_path = os.path.join(dir, name)
			if os.path.exists(file_path):
				MessageDialog(self, file_path, 'File exists').Show()
				return

			# Everything looks alright, so open the file.
			export_file = open(file_path, 'w')
			export_csv = csv.writer(export_file)
			exporting = True

			# Show the path in the GUI.
			self.last_file_name.Value = file_path

			# Write the header.
			export_csv.writerow(['Time (s)'] +
					['{0.name} ({0.units})'.format(var) if var.units is not None else var.name
							for var in flatten(output_variables)] +
					['{0.name} ({1})'.format(var, units) if units is not None else var.name
						for var, units in zip(input_variables, measurement_units)])

		self.capture_dialogs += 1

		dlg = DataCaptureDialog(self, resources, output_variables, num_items, measurement_resources,
				input_variables, condition_resources, condition_variables, pulse_config, continuous=continuous)
		dlg.SetMinSize((500, -1))

		for name in measurement_resource_names:
			wx.CallAfter(pub.sendMessage, 'data_capture.start', name=name)

		# Export buffer.
		max_buf_size = 10
		buf = []
		buf_lock = Lock()

		def flush():
			export_csv.writerows(buf)
			export_file.flush()

			while buf:
				buf.pop()

		def data_callback(cur_time, values, measurement_values):
			for name, value in zip(measurement_resource_names, measurement_values):
				wx.CallAfter(pub.sendMessage, 'data_capture.data', name=name, value=value)

			# Extract values out of quantities, since the units have already been taken care of in the header.
			values = [x.original_value if hasattr(x, 'original_value') else x for x in values]
			measurement_values = [x.original_value if hasattr(x, 'original_value') else x for x in measurement_values]

			if exporting:
				with buf_lock:
					buf.append([cur_time] + values + measurement_values)

					if len(buf) >= max_buf_size:
						flush()

		def close_callback():
			self.capture_dialogs -= 1

			if exporting:
				with buf_lock:
					flush()
					export_file.close()

			for name in measurement_resource_names:
				wx.CallAfter(pub.sendMessage, 'data_capture.stop', name=name)

		dlg.data_callback = data_callback
		dlg.close_callback = close_callback
		dlg.Show()
		dlg.start()
    def __init__(self, parent):
        """
        """
        wx.Panel.__init__(self,
                          parent,
                          wx.ID_ANY,
                          size=(-1, 300),
                          style=wx.SUNKEN_BORDER | wx.TAB_TRAVERSAL)
        self.parent = parent

        self.thumbnail = None
        self.mask_file = None
        self.source = None
        self.sourceType = None
        self.track = None
        self.trackType = None

        lowerSizer = wx.BoxSizer(wx.HORIZONTAL)

        #Static box1 (LEFT)
        sb_1 = wx.StaticBox(self, -1, "Select Monitor")  #, size=(250,-1))
        sbSizer_1 = wx.StaticBoxSizer(sb_1, wx.VERTICAL)

        n_monitors = options.GetOption("Monitors")
        self.MonitorList = [
            'Monitor %s' % (int(m) + 1) for m in range(n_monitors)
        ]
        self.thumbnailNumber = wx.ComboBox(self,
                                           -1,
                                           size=(-1, -1),
                                           choices=self.MonitorList,
                                           style=wx.CB_DROPDOWN
                                           | wx.CB_READONLY | wx.CB_SORT)
        self.Bind(wx.EVT_COMBOBOX, self.onChangingMonitor,
                  self.thumbnailNumber)

        self.currentSource = wx.TextCtrl(self,
                                         -1,
                                         "No Source Selected",
                                         style=wx.TE_READONLY)

        btnSizer_1 = wx.BoxSizer(wx.HORIZONTAL)
        self.btnPlay = wx.Button(self, wx.ID_FORWARD, label="Play")
        self.btnStop = wx.Button(self, wx.ID_STOP, label="Stop")
        self.Bind(wx.EVT_BUTTON, self.onPlay, self.btnPlay)
        self.Bind(wx.EVT_BUTTON, self.onStop, self.btnStop)
        self.btnPlay.Enable(False)
        self.btnStop.Enable(False)
        self.applyButton = wx.Button(self, wx.ID_APPLY)
        self.applyButton.SetToolTip(wx.ToolTip("Apply and Save to file"))
        self.Bind(wx.EVT_BUTTON, self.onApplySource, self.applyButton)

        btnSizer_1.Add(self.btnPlay, 0, wx.ALIGN_LEFT | wx.ALL, 5)
        btnSizer_1.Add(self.btnStop, 0,
                       wx.ALIGN_CENTER | wx.LEFT | wx.TOP | wx.DOWN, 5)
        btnSizer_1.Add(self.applyButton, 0,
                       wx.ALIGN_RIGHT | wx.LEFT | wx.RIGHT | wx.TOP, 5)

        sbSizer_1.Add(self.thumbnailNumber, 0,
                      wx.ALIGN_CENTRE | wx.LEFT | wx.RIGHT | wx.TOP, 5)
        sbSizer_1.Add(
            self.currentSource, 0,
            wx.EXPAND | wx.ALIGN_CENTRE | wx.LEFT | wx.RIGHT | wx.TOP, 5)
        sbSizer_1.Add(btnSizer_1, 0, wx.EXPAND | wx.ALIGN_BOTTOM | wx.TOP, 5)

        lowerSizer.Add(sbSizer_1, 0, wx.EXPAND | wx.ALL, 5)

        #Static box2 (CENTER)
        sb_2 = wx.StaticBox(self, -1, "Select Video input")
        sbSizer_2 = wx.StaticBoxSizer(sb_2, wx.VERTICAL)
        grid2 = wx.FlexGridSizer(0, 2, 0, 0)

        n_cams = options.GetOption("Webcams")
        self.WebcamsList = ['Webcam %s' % (int(w) + 1) for w in range(n_cams)]
        rb1 = wx.RadioButton(self, -1, 'Camera', style=wx.RB_GROUP)
        source1 = wx.ComboBox(self,
                              -1,
                              size=(285, -1),
                              choices=self.WebcamsList,
                              style=wx.CB_DROPDOWN | wx.CB_READONLY
                              | wx.CB_SORT)
        self.Bind(wx.EVT_COMBOBOX, self.sourceCallback, source1)

        rb2 = wx.RadioButton(self, -1, 'File')
        source2 = FileBrowseButton(self,
                                   -1,
                                   labelText='',
                                   size=(300, -1),
                                   changeCallback=self.sourceCallback)

        rb3 = wx.RadioButton(self, -1, 'Folder')
        source3 = DirBrowseButton(self,
                                  style=wx.DD_DIR_MUST_EXIST,
                                  labelText='',
                                  size=(300, -1),
                                  changeCallback=self.sourceCallback)

        self.controls = []
        self.controls.append((rb1, source1))
        self.controls.append((rb2, source2))
        self.controls.append((rb3, source3))

        for radio, source in self.controls:
            grid2.Add(radio, 0,
                      wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, 2)
            grid2.Add(source, 0,
                      wx.ALIGN_CENTRE | wx.ALIGN_CENTER_VERTICAL | wx.ALL, 2)
            self.Bind(wx.EVT_RADIOBUTTON, self.onChangeSource, radio)
            source.Enable(False)

        self.controls[0][1].Enable(True)

        #grid2.Add(wx.StaticText(self, -1, ""))

        sbSizer_2.Add(grid2)
        lowerSizer.Add(sbSizer_2, 0, wx.EXPAND | wx.ALL, 5)

        #Static box3 (RIGHT)
        sb_3 = wx.StaticBox(self, -1, "Set Tracking Parameters")
        sbSizer_3 = wx.StaticBoxSizer(sb_3, wx.VERTICAL)

        sbSizer_31 = wx.BoxSizer(wx.HORIZONTAL)

        self.activateTracking = wx.CheckBox(self, -1, "Activate Tracking")
        self.activateTracking.SetValue(False)
        self.activateTracking.Bind(wx.EVT_CHECKBOX, self.onActivateTracking)

        self.isSDMonitor = wx.CheckBox(self, -1, "Sleep Deprivation Monitor")
        self.isSDMonitor.SetValue(False)
        self.isSDMonitor.Bind(wx.EVT_CHECKBOX, self.onSDMonitor)
        self.isSDMonitor.Enable(False)

        sbSizer_31.Add(self.activateTracking, 0,
                       wx.ALIGN_LEFT | wx.LEFT | wx.RIGHT | wx.TOP, 5)
        sbSizer_31.Add(self.isSDMonitor, 0,
                       wx.ALIGN_LEFT | wx.LEFT | wx.RIGHT | wx.TOP, 5)

        self.pickMaskBrowser = FileBrowseButton(self,
                                                -1,
                                                labelText='Mask File')

        #sbSizer_3.Add ( self.activateTracking , 0, wx.ALIGN_LEFT|wx.LEFT|wx.RIGHT|wx.TOP, 5 )
        sbSizer_3.Add(sbSizer_31, 0,
                      wx.ALIGN_LEFT | wx.LEFT | wx.RIGHT | wx.TOP, 5)
        sbSizer_3.Add(self.pickMaskBrowser, 0,
                      wx.ALIGN_LEFT | wx.LEFT | wx.RIGHT | wx.TOP | wx.EXPAND,
                      5)

        #trackingTypeSizer = wx.Sizer(wx.HORIZONTAL)
        self.trackDistanceRadio = wx.RadioButton(
            self, -1, "Activity as distance traveled", style=wx.RB_GROUP)
        self.trackVirtualBM = wx.RadioButton(
            self, -1, "Activity as midline crossings count")
        self.trackPosition = wx.RadioButton(self, -1, "Only position of flies")
        sbSizer_3.Add(wx.StaticText(self, -1, "Calculate fly activity as..."),
                      0, wx.ALIGN_LEFT | wx.LEFT | wx.RIGHT | wx.TOP, 5)
        sbSizer_3.Add(self.trackDistanceRadio, 0,
                      wx.ALIGN_LEFT | wx.LEFT | wx.RIGHT | wx.TOP, 2)
        sbSizer_3.Add(self.trackVirtualBM, 0,
                      wx.ALIGN_LEFT | wx.LEFT | wx.RIGHT | wx.TOP, 2)
        sbSizer_3.Add(self.trackPosition, 0,
                      wx.ALIGN_LEFT | wx.LEFT | wx.RIGHT | wx.TOP, 2)

        lowerSizer.Add(sbSizer_3, -1, wx.EXPAND | wx.ALL, 5)

        self.SetSizer(lowerSizer)
        self.Bind(EVT_THUMBNAIL_CLICKED, self.onThumbnailClicked)
Example #10
0
    def __init__(self, **kwargs):
        DirBrowseButton.__init__(self, changeCallback=self._on_changed,
                                 buttonText=_('Browse'), **kwargs)

        self._share_name = ''
        self._parent_folder = kwargs.get('startDirectory', '.')
Example #11
0
class MainFrame(wx.Frame):
    def _init_ctrls(self, parent):
        self.DecYear = wx.Button(self, -1, '<<', size=(48, 36))
        self.DecYear.Bind(wx.EVT_BUTTON, self.OnDecYear)
        self.DecMonth = wx.Button(self, -1, ' < ', size=(48, 36))
        self.DecMonth.Bind(wx.EVT_BUTTON, self.OnDecMonth)
        self.Current = wx.Button(self, -1, 'Today')
        self.Current.Bind(wx.EVT_BUTTON, self.OnCurrent)
        self.IncMonth = wx.Button(self, -1, ' > ', size=(48, 36))
        self.IncMonth.Bind(wx.EVT_BUTTON, self.OnIncMonth)
        self.IncYear = wx.Button(self, -1, '>>', size=(48, 36))
        self.IncYear.Bind(wx.EVT_BUTTON, self.OnIncYear)
        bsizer = wx.BoxSizer(wx.HORIZONTAL)
        bsizer.Add(self.DecYear, 0, wx.ALL, 2)
        bsizer.Add(self.DecMonth, 0, wx.ALL, 2)
        bsizer.Add(self.Current, 1, wx.ALL | wx.EXPAND, 2)
        bsizer.Add(self.IncMonth, 0, wx.ALL, 2)
        bsizer.Add(self.IncYear, 0, wx.ALL, 2)

        self.Calendar = Calendar(self, -1, size=(200, 300))
        self.Calendar.Bind(wx.lib.calendar.EVT_CALENDAR, self.OnCalendarChange)
        self.Calendar.SetCurrentDay()
        self.Calendar.grid_color = 'BLUE'
        self.Calendar.SetBusType()

        self.FBB = FileBrowseButton(self,
                                    size=(450, -1),
                                    changeCallback=self.OnFBBChange)
        self.FBB.SetLabel('Symbols File:')

        self.DBB = DirBrowseButton(self,
                                   size=(450, -1),
                                   changeCallback=self.OnDBBChange)
        self.DBB.SetLabel('Prices Folder:')

        self.ListBox = gizmos.EditableListBox(
            self,
            -1,
            #              style=gizmos.EL_DEFAULT_STYLE | gizmos.EL_NO_REORDER
        )
        self.ListBox.GetUpButton().Show(False)
        self.ListBox.GetDownButton().Show(False)
        self.ListBox.Bind(wx.EVT_LIST_DELETE_ITEM, self.OnSymbolListChange)
        self.ListBox.Bind(wx.EVT_LIST_INSERT_ITEM, self.OnSymbolListChange)

        self.Download = wx.Button(self, wx.OK, 'Download Prices')
        self.Download.Bind(wx.EVT_BUTTON, self.OnDownload)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.AddSizer(bsizer, 0, wx.LEFT | wx.RIGHT | wx.EXPAND, 5)
        sizer.AddWindow(self.Calendar, 0, wx.LEFT | wx.RIGHT | wx.EXPAND, 5)
        sizer.AddWindow(self.FBB, 0, wx.ALL | wx.EXPAND, 5)
        sizer.AddWindow(self.DBB, 0, wx.ALL | wx.EXPAND, 5)
        sizer.AddWindow(self.ListBox, 1, wx.ALL | wx.EXPAND, 5)
        sizer.AddWindow(self.Download, 0, wx.ALL | wx.ALIGN_RIGHT, 5)
        self.SetSizer(sizer)

    def __init__(self, parent=None):
        wx.Frame.__init__(self, parent=parent, size=(800, 600))
        self._init_ctrls(self)

        self._blocking = Blocker()
        self._clean = True

        # Get download directory and symbol filename
        download_dir = ''
        symbol_file = ''

        if os.path.exists('settings.ini'):
            with file('settings.ini', 'r') as settings:
                symbol_file = settings.readline().strip()
                download_dir = settings.readline().strip()
            if not os.path.exists(symbol_file):
                symbol_file = ''
            if not os.path.exists(download_dir):
                download_dir = ''

        download_dir = download_dir or os.path.realpath('.')
        symbol_file = symbol_file or os.path.join(download_dir, 'symbols.txt')

        self.SetDownloadDir(download_dir)
        if os.path.exists(symbol_file):
            self.SetSymbolFile(symbol_file)

        # Update the calendar
        self.Download.SetFocus()
        self.OnCalendarChange(None)

    def OnCalendarChange(self, event):
        self.day = self.Calendar.day
        self.month = self.Calendar.month
        self.year = self.Calendar.year

    def OnCurrent(self, event):
        self.Calendar.SetCurrentDay()
        self.ResetDisplay()

    def OnDBBChange(self, event):
        if self._blocking:
            return
        self.SetDownloadDir(event.GetString())

    def OnDecMonth(self, event):
        self.Calendar.DecMonth()
        self.ResetDisplay()

    def OnDecYear(self, event):
        self.Calendar.DecYear()
        self.ResetDisplay()

    def OnDownload(self, event):
        if not self._clean:
            with file(self.symbol_file, 'w') as symbols:
                symbols.write('\n'.join(self.ListBox.GetStrings()))
            self._clean = True

        dt = datetime.date(self.year, self.month, self.day)
        pricer.download_date(self.ListBox.GetStrings(), dt, self.download_dir)

        with file('settings.ini', 'w') as settings:
            settings.write(self.symbol_file + '\n')
            settings.write(self.download_dir + '\n')

    def OnFBBChange(self, event):
        if self._blocking:
            return
        self.ListBox.SetStrings([])
        self.SetSymbolFile(event.GetString())

    def OnIncMonth(self, event):
        self.Calendar.IncMonth()
        self.ResetDisplay()

    def OnIncYear(self, event):
        self.Calendar.IncYear()
        self.ResetDisplay()

    def OnSymbolListChange(self, event):
        self._clean = False
        self.Download.Enable(len(self.ListBox.GetStrings()) > 0)

    def ResetDisplay(self):
        self.Calendar.Refresh()

    def SetDownloadDir(self, download_dir):
        with self._blocking:
            self.download_dir = download_dir
            self.DBB.SetValue(self.download_dir)

    def SetSymbolFile(self, symbol_file):
        self.Download.Enable(False)
        with self._blocking:
            if not os.path.exists(symbol_file):
                return
            self.symbol_file = symbol_file

            with file(self.symbol_file, 'r') as symbols:
                l = []
                for symbol in symbols:
                    s = symbol.strip().upper()
                    if len(s) and not s.startswith('#'):
                        l.append(s)
                l.sort()
                self.ListBox.SetStrings(l)
                self._clean = True
            self.FBB.SetValue(self.symbol_file)
Example #12
0
    def __init__(self,parent,prefs=None,tablist=None):

                
        if not prefs:
            prefs = neveredit.util.Preferences.getPreferences()
        self.preferences = prefs
        if not tablist:
            tablist = ["GeneralPanel","ScriptEditorPanel","TextPanel", "UserControlsPanel"]
            # tablist list all tabs that will be activated, the other ones do
            # not show
        self.tablist = tablist
        resourceText = PreferencesDialog_xrc.data
#        resource = wx.xrc.EmptyXmlResource()
        resource = wx.xrc.XmlResource()
#        resource.LoadFromString(resourceText)
        resource.LoadFromBuffer(resourceText)

        dialog = resource.LoadDialog(parent,"PrefDialog")
        notebook = wx.xrc.XRCCTRL(dialog,"PrefNotebook")
        
        generalPanel = wx.xrc.XRCCTRL(dialog,"GeneralPanel")
        if "GeneralPanel" in self.tablist:
            self.appDirButton = DirBrowseButton(generalPanel,-1,(500,30),
                                                labelText=_('NWN Directory'),
                                                buttonText=_('Select...'),
                                                startDirectory=
                                                prefs['NWNAppDir'])
            self.appDirButton.SetValue(prefs['NWNAppDir'])            
            resource.AttachUnknownControl('AppDir',
                                          self.appDirButton,
                                          generalPanel)
        else:
            index = self.__getPanelIndex(notebook,generalPanel)
            notebook.DeletePage(index)
        if "ScriptEditorPanel" in self.tablist:
            self.scriptAntiAlias = wx.xrc.XRCCTRL(dialog,"ScriptAntiAlias")
            self.scriptAntiAlias.SetValue(prefs['ScriptAntiAlias'])
            self.scriptAutoCompile = wx.xrc.XRCCTRL(dialog,"ScriptAutoCompile")
            self.scriptAutoCompile.SetValue(prefs['ScriptAutoCompile'])
        else:
            index = self.__getPanelIndex(notebook,
                                         wx.xrc.XRCCTRL(dialog,
                                                        "ScriptEditorPanel"))
            notebook.DeletePage(index)
        if "TextPanel" in self.tablist :
                self.DefaultLocStringLang = wx.xrc.XRCCTRL(
                                        dialog,"DefaultLocStringLang")
                self.DefaultLocStringLang.SetSelection(neveredit.file.Language.\
                        convertFromBIOCode(prefs["DefaultLocStringLang"]))
        else:
                index = self.__getPanelIndex(notebook,
                                         wx.xrc.XRCCTRL(dialog, "TextPanel"))
                notebook.DeletePage(index)

        # Set up the User Controls Panel
        # Create Controls
        # Fix length 
        # Set value
        if "UserControlsPanel" in self.tablist :
                self.mwUpKey = wx.xrc.XRCCTRL(dialog,"mwUpKey")
                self.mwUpKey.SetMaxLength(1)
                self.mwUpKey.SetValue(prefs['GLW_UP'])
                self.mwDownKey = wx.xrc.XRCCTRL(dialog,"mwDownKey")
                self.mwDownKey.SetMaxLength(1)
                self.mwDownKey.SetValue(prefs['GLW_DOWN'])
                self.mwLeftKey = wx.xrc.XRCCTRL(dialog,"mwLeftKey")
                self.mwLeftKey.SetMaxLength(1)
                self.mwLeftKey.SetValue(prefs['GLW_LEFT'])
                self.mwRightKey = wx.xrc.XRCCTRL(dialog,"mwRightKey")
                self.mwRightKey.SetMaxLength(1)
                self.mwRightKey.SetValue(prefs['GLW_RIGHT'])
                
        else:
                index = self.__getPanelIndex(notebook,
                                         wx.xrc.XRCCTRL(dialog, "UserControlsPanel"))
                notebook.DeletePage(index)

        dialog.Bind(wx.EVT_BUTTON, self.OnOk, id=wx.xrc.XRCID("ID_OK"))
        dialog.Bind(wx.EVT_BUTTON, self.OnCancel, id=wx.xrc.XRCID("ID_CANCEL"))
Example #13
0
class PreferencesDialog(wx.Dialog):
    __doc__ = globals()['__doc__']
    def __init__(self,parent,prefs=None,tablist=None):

                
        if not prefs:
            prefs = neveredit.util.Preferences.getPreferences()
        self.preferences = prefs
        if not tablist:
            tablist = ["GeneralPanel","ScriptEditorPanel","TextPanel", "UserControlsPanel"]
            # tablist list all tabs that will be activated, the other ones do
            # not show
        self.tablist = tablist
        resourceText = PreferencesDialog_xrc.data
#        resource = wx.xrc.EmptyXmlResource()
        resource = wx.xrc.XmlResource()
#        resource.LoadFromString(resourceText)
        resource.LoadFromBuffer(resourceText)

        dialog = resource.LoadDialog(parent,"PrefDialog")
        notebook = wx.xrc.XRCCTRL(dialog,"PrefNotebook")
        
        generalPanel = wx.xrc.XRCCTRL(dialog,"GeneralPanel")
        if "GeneralPanel" in self.tablist:
            self.appDirButton = DirBrowseButton(generalPanel,-1,(500,30),
                                                labelText=_('NWN Directory'),
                                                buttonText=_('Select...'),
                                                startDirectory=
                                                prefs['NWNAppDir'])
            self.appDirButton.SetValue(prefs['NWNAppDir'])            
            resource.AttachUnknownControl('AppDir',
                                          self.appDirButton,
                                          generalPanel)
        else:
            index = self.__getPanelIndex(notebook,generalPanel)
            notebook.DeletePage(index)
        if "ScriptEditorPanel" in self.tablist:
            self.scriptAntiAlias = wx.xrc.XRCCTRL(dialog,"ScriptAntiAlias")
            self.scriptAntiAlias.SetValue(prefs['ScriptAntiAlias'])
            self.scriptAutoCompile = wx.xrc.XRCCTRL(dialog,"ScriptAutoCompile")
            self.scriptAutoCompile.SetValue(prefs['ScriptAutoCompile'])
        else:
            index = self.__getPanelIndex(notebook,
                                         wx.xrc.XRCCTRL(dialog,
                                                        "ScriptEditorPanel"))
            notebook.DeletePage(index)
        if "TextPanel" in self.tablist :
                self.DefaultLocStringLang = wx.xrc.XRCCTRL(
                                        dialog,"DefaultLocStringLang")
                self.DefaultLocStringLang.SetSelection(neveredit.file.Language.\
                        convertFromBIOCode(prefs["DefaultLocStringLang"]))
        else:
                index = self.__getPanelIndex(notebook,
                                         wx.xrc.XRCCTRL(dialog, "TextPanel"))
                notebook.DeletePage(index)

        # Set up the User Controls Panel
        # Create Controls
        # Fix length 
        # Set value
        if "UserControlsPanel" in self.tablist :
                self.mwUpKey = wx.xrc.XRCCTRL(dialog,"mwUpKey")
                self.mwUpKey.SetMaxLength(1)
                self.mwUpKey.SetValue(prefs['GLW_UP'])
                self.mwDownKey = wx.xrc.XRCCTRL(dialog,"mwDownKey")
                self.mwDownKey.SetMaxLength(1)
                self.mwDownKey.SetValue(prefs['GLW_DOWN'])
                self.mwLeftKey = wx.xrc.XRCCTRL(dialog,"mwLeftKey")
                self.mwLeftKey.SetMaxLength(1)
                self.mwLeftKey.SetValue(prefs['GLW_LEFT'])
                self.mwRightKey = wx.xrc.XRCCTRL(dialog,"mwRightKey")
                self.mwRightKey.SetMaxLength(1)
                self.mwRightKey.SetValue(prefs['GLW_RIGHT'])
                
        else:
                index = self.__getPanelIndex(notebook,
                                         wx.xrc.XRCCTRL(dialog, "UserControlsPanel"))
                notebook.DeletePage(index)

        dialog.Bind(wx.EVT_BUTTON, self.OnOk, id=wx.xrc.XRCID("ID_OK"))
        dialog.Bind(wx.EVT_BUTTON, self.OnCancel, id=wx.xrc.XRCID("ID_CANCEL"))
#        self.PostCreate(dialog)

    def __getPanelIndex(self,notebook,panel):
        index = [notebook.GetPage(i).GetId() for i in
                 range(notebook.GetPageCount())]\
                 .index(panel.GetId())
        return index
                
    def getValues(self):
        values = {}
        if "GeneralPanel" in self.tablist:
            values.update({'NWNAppDir':self.appDirButton.GetValue()})
        if "ScriptEditorPanel" in self.tablist:
            values.update({'ScriptAntiAlias':
                           self.scriptAntiAlias.GetValue(),
                           'ScriptAutoCompile':
                           self.scriptAutoCompile.GetValue()})
        if "TextPanel" in self.tablist:
            values.update({"DefaultLocStringLang":neveredit.file.Language.\
                           convertToBIOCode(self.DefaultLocStringLang.GetSelection())})
            
        # Update value of direction keys for Model/GLWindow
        if "UserControlsPanel" in self.tablist:
            values.update({'GLW_UP': self.mwUpKey.GetValue(),
                           'GLW_DOWN': self.mwDownKey.GetValue(),
                           'GLW_LEFT': self.mwLeftKey.GetValue(),
                           'GLW_RIGHT': self.mwRightKey.GetValue()})
        return values

    def ShowAndInterpret(self):
        self.CentreOnParent()
        if self.ShowModal() == wx.ID_OK:
            result = self.getValues()
            self.preferences.values.update(result)
            self.preferences.save()
            return True
        else:
            return False

    def OnCancel(self, event):
        self.EndModal(wx.ID_CANCEL)

    def OnOk(self, event):
        self.EndModal(wx.ID_OK)