INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
draw a series of connected lines on the map, calling callback when done
def draw_lines(self, callback): '''draw a series of connected lines on the map, calling callback when done''' from MAVProxy.modules.mavproxy_map import mp_slipmap self.draw_callback = callback self.draw_line = [] self.map.add_object(mp_slipmap.SlipDefaultPopup(None))
called when user selects "Set Home" on map
def cmd_set_homepos(self, args): '''called when user selects "Set Home" on map''' (lat, lon) = (self.click_position[0], self.click_position[1]) print("Setting home to: ", lat, lon) self.master.mav.command_int_send( self.settings.target_system, self.settings.target_component, ...
called when user selects "Set Origin (with height)" on map
def cmd_set_origin(self, args): '''called when user selects "Set Origin (with height)" on map''' (lat, lon) = (self.click_position[0], self.click_position[1]) alt = self.ElevationMap.GetElevation(lat, lon) print("Setting origin to: ", lat, lon, alt) self.master.mav.set_gps_global...
called when user selects "Set Origin" on map
def cmd_set_originpos(self, args): '''called when user selects "Set Origin" on map''' (lat, lon) = (self.click_position[0], self.click_position[1]) print("Setting origin to: ", lat, lon) self.master.mav.set_gps_global_origin_send( self.settings.target_system, lat*...
control zoom
def cmd_zoom(self, args): '''control zoom''' if len(args) < 2: print("map zoom WIDTH(m)") return ground_width = float(args[1]) self.map.set_zoom(ground_width)
control center of view
def cmd_center(self, args): '''control center of view''' if len(args) < 3: print("map center LAT LON") return lat = float(args[1]) lon = float(args[2]) self.map.set_center(lat, lon)
control following of vehicle
def cmd_follow(self, args): '''control following of vehicle''' if len(args) < 2: print("map follow 0|1") return follow = int(args[1]) self.map.set_follow(follow)
show 2nd vehicle on map
def set_secondary_vehicle_position(self, m): '''show 2nd vehicle on map''' if m.get_type() != 'GLOBAL_POSITION_INT': return (lat, lon, heading) = (m.lat*1.0e-7, m.lon*1.0e-7, m.hdg*0.01) if abs(lat) < 1.0e-3 and abs(lon) > 1.0e-3: return # hack for OBC2016...
handle an incoming mavlink packet
def mavlink_packet(self, m): '''handle an incoming mavlink packet''' from MAVProxy.modules.mavproxy_map import mp_slipmap mtype = m.get_type() sysid = m.get_srcSystem() if mtype == "HEARTBEAT": vname = 'plane' if m.type in [mavutil.mavlink.MAV_TYPE_FIXED_...
control kml reading
def cmd_param(self, args): '''control kml reading''' usage = "Usage: kml <clear | load (filename) | layers | toggle (layername) | fence (layername)>" if len(args) < 1: print(usage) return elif args[0] == "clear": self.clearkml() elif args[0] ==...
snap waypoints to KML
def cmd_snap_wp(self, args): '''snap waypoints to KML''' threshold = 10.0 if len(args) > 0: threshold = float(args[0]) wpmod = self.module('wp') wploader = wpmod.wploader changed = False for i in range(1,wploader.count()): w = wploader.wp(i...
snap fence to KML
def cmd_snap_fence(self, args): '''snap fence to KML''' threshold = 10.0 if len(args) > 0: threshold = float(args[0]) fencemod = self.module('fence') loader = fencemod.fenceloader changed = False for i in range(0,loader.count()): fp = loade...
set a layer as the geofence
def fencekml(self, layername): '''set a layer as the geofence''' #Strip quotation marks if neccessary if layername.startswith('"') and layername.endswith('"'): layername = layername[1:-1] #for each point in the layer, add it in for layer in self.allayers: ...
toggle the display of a kml
def togglekml(self, layername): '''toggle the display of a kml''' #Strip quotation marks if neccessary if layername.startswith('"') and layername.endswith('"'): layername = layername[1:-1] #toggle layer off (plus associated text element) if layername in self.curlayers...
Clear the kmls from the map
def clearkml(self): '''Clear the kmls from the map''' #go through all the current layers and remove them for layer in self.curlayers: self.mpstate.map.remove_object(layer) for layer in self.curtextlayers: self.mpstate.map.remove_object(layer) self.allayers...
Load a kml from file and put it on the map
def loadkml(self, filename): '''Load a kml from file and put it on the map''' #Open the zip file nodes = self.readkmz(filename) self.snap_points = [] #go through each object in the kml... for n in nodes: point = self.readObject(n) #and plac...
handle GUI elements
def idle_task(self): '''handle GUI elements''' if not self.menu_needs_refreshing: return if self.module('map') is not None and not self.menu_added_map: self.menu_added_map = True self.module('map').add_menu(self.menu) #(re)create the menu if mp...
reads in a kmz file and returns xml nodes
def readkmz(self, filename): '''reads in a kmz file and returns xml nodes''' #Strip quotation marks if neccessary filename.strip('"') #Open the zip file (as applicable) if filename[-4:] == '.kml': fo = open(filename, "r") fstring = fo.read() ...
reads in a node and returns as a tuple: (type, name, points[])
def readObject(self, innode): '''reads in a node and returns as a tuple: (type, name, points[])''' #get name names=innode.getElementsByTagName('name')[0].childNodes[0].data.strip() #get type pointType = 'Unknown' if len(innode.getElementsByTagName('LineString')) ...
asterix command parser
def cmd_asterix(self, args): '''asterix command parser''' usage = "usage: asterix <set|start|stop|restart|status>" if len(args) == 0: print(usage) return if args[0] == "set": self.asterix_settings.command(args[1:]) elif args[0] == "start": ...
start listening for packets
def start_listener(self): '''start listening for packets''' if self.sock is not None: self.sock.close() self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.sock.bind(('',...
stop listening for packets
def stop_listener(self): '''stop listening for packets''' if self.sock is not None: self.sock.close() self.sock = None self.tracks = {}
store second vehicle position for filtering purposes
def set_secondary_vehicle_position(self, m): '''store second vehicle position for filtering purposes''' if m.get_type() != 'GLOBAL_POSITION_INT': return (lat, lon, heading) = (m.lat*1.0e-7, m.lon*1.0e-7, m.hdg*0.01) if abs(lat) < 1.0e-3 and abs(lon) < 1.0e-3: retu...
return true if vehicle could come within filter_dist_xy meters of adsb vehicle in timeout seconds
def could_collide_hor(self, vpos, adsb_pkt): '''return true if vehicle could come within filter_dist_xy meters of adsb vehicle in timeout seconds''' margin = self.asterix_settings.filter_dist_xy timeout = self.asterix_settings.filter_time alat = adsb_pkt.lat * 1.0e-7 alon = adsb_...
return true if vehicle could come within filter_dist_z meters of adsb vehicle in timeout seconds
def could_collide_ver(self, vpos, adsb_pkt): '''return true if vehicle could come within filter_dist_z meters of adsb vehicle in timeout seconds''' if adsb_pkt.emitter_type < 100 or adsb_pkt.emitter_type > 104: return True margin = self.asterix_settings.filter_dist_z vtype = ...
called on idle
def idle_task(self): '''called on idle''' if self.sock is None: return try: pkt = self.sock.recv(10240) except Exception: return try: if pkt.startswith(b'PICKLED:'): pkt = pkt[8:] # pickled packet ...
get time from mavlink ATTITUDE
def mavlink_packet(self, m): '''get time from mavlink ATTITUDE''' if m.get_type() == 'GLOBAL_POSITION_INT': if abs(m.lat) < 1000 and abs(m.lon) < 1000: return self.vehicle_pos = VehiclePos(m)
control behaviour of the module
def cmd_system_time(self, args): '''control behaviour of the module''' if len(args) == 0: print(self.usage()) elif args[0] == "status": print(self.status()) elif args[0] == "set": self.system_time_settings.command(args[1:]) else: pr...
called rapidly by mavproxy
def idle_task(self): '''called rapidly by mavproxy''' now = time.time() if now-self.last_sent > self.system_time_settings.interval: self.last_sent = now time_us = time.time() * 1000000 if self.system_time_settings.verbose: print("ST: Sending s...
handle mavlink packets
def mavlink_packet(self, m): '''handle mavlink packets''' if m.get_type() == 'SYSTEM_TIME': if self.system_time_settings.verbose: print("ST: Received from (%u/%u): %s" % (m.get_srcSystem(), m.get_srcComponent(), m)) if m.get_type() == 'TIMESYNC':...
set relays
def cmd_relay(self, args): '''set relays''' if len(args) == 0 or args[0] not in ['set', 'repeat']: print("Usage: relay <set|repeat>") return if args[0] == "set": if len(args) < 3: print("Usage: relay set <RELAY_NUM> <0|1>") retu...
set servos
def cmd_servo(self, args): '''set servos''' if len(args) == 0 or args[0] not in ['set', 'repeat']: print("Usage: servo <set|repeat>") return if args[0] == "set": if len(args) < 3: print("Usage: servo set <SERVO_NUM> <PWM>") retu...
return list of serial ports
def complete_serial_ports(self, text): '''return list of serial ports''' ports = mavutil.auto_detect_serial(preferred_list=preferred_ports) return [ p.device for p in ports ]
return list of links
def complete_links(self, text): '''return list of links''' try: ret = [ m.address for m in self.mpstate.mav_master ] for m in self.mpstate.mav_master: ret.append(m.address) if hasattr(m, 'label'): ret.append(m.label) ...
show link information
def show_link(self): '''show link information''' for master in self.mpstate.mav_master: linkdelay = (self.status.highest_msec - master.highest_msec)*1.0e-3 if master.linkerror: status = "DOWN" else: status = "OK" sign_string...
return a dict based on some_json (empty if json invalid)
def parse_link_attributes(self, some_json): '''return a dict based on some_json (empty if json invalid)''' try: return json.loads(some_json) except ValueError: print('Invalid JSON argument: {0}'.format(some_json)) return {}
parse e.g. 'udpin:127.0.0.1:9877:{"foo":"bar"}' into python structure ("udpin:127.0.0.1:9877", {"foo":"bar"})
def parse_link_descriptor(self, descriptor): '''parse e.g. 'udpin:127.0.0.1:9877:{"foo":"bar"}' into python structure ("udpin:127.0.0.1:9877", {"foo":"bar"})''' optional_attributes = {} link_components = descriptor.split(":{", 1) device = link_components[0] if (len(link_c...
add new link
def cmd_link_add(self, args): '''add new link''' descriptor = args[0] print("Adding link %s" % descriptor) self.link_add(descriptor)
change optional link attributes
def cmd_link_attributes(self, args): '''change optional link attributes''' link = args[0] attributes = args[1] print("Setting link %s attributes (%s)" % (link, attributes)) self.link_attributes(link, attributes)
find a device based on number, name or label
def find_link(self, device): '''find a device based on number, name or label''' for i in range(len(self.mpstate.mav_master)): conn = self.mpstate.mav_master[i] if (str(i) == device or conn.address == device or getattr(conn, 'label', None) == device...
remove an link
def cmd_link_remove(self, args): '''remove an link''' device = args[0] if len(self.mpstate.mav_master) <= 1: print("Not removing last link") return i = self.find_link(device) if i is None: return conn = self.mpstate.mav_master[i] ...
called on sending a message
def master_send_callback(self, m, master): '''called on sending a message''' if self.status.watch is not None: for msg_type in self.status.watch: if fnmatch.fnmatch(m.get_type().upper(), msg_type.upper()): self.mpstate.console.writeln('> '+ str(m)) ...
special handling for MAVLink packets with a time_boot_ms field
def handle_msec_timestamp(self, m, master): '''special handling for MAVLink packets with a time_boot_ms field''' if m.get_type() == 'GLOBAL_POSITION_INT': # this is fix time, not boot time return msec = m.time_boot_ms if msec + 30000 < master.highest_msec: ...
possibly report a new altitude
def report_altitude(self, altitude): '''possibly report a new altitude''' master = self.master if getattr(self.console, 'ElevationMap', None) is not None and self.mpstate.settings.basealt != 0: lat = master.field('GLOBAL_POSITION_INT', 'lat', 0)*1.0e-7 lon = master.field(...
link message handling for an upstream link
def master_msg_handling(self, m, master): '''link message handling for an upstream link''' if self.settings.target_system != 0 and m.get_srcSystem() != self.settings.target_system: # don't process messages not from our target if m.get_type() == "BAD_DATA": if self...
process mavlink message m on master, sending any messages to recipients
def master_callback(self, m, master): '''process mavlink message m on master, sending any messages to recipients''' # see if it is handled by a specialised sysid connection sysid = m.get_srcSystem() mtype = m.get_type() if sysid in self.mpstate.sysid_outputs: self.mp...
handle vehicle commands
def cmd_vehicle(self, args): '''handle vehicle commands''' if len(args) < 1: print("Usage: vehicle SYSID[:COMPID]") return a = args[0].split(':') self.mpstate.settings.target_system = int(a[0]) if len(a) > 1: self.mpstate.settings.target_compon...
device operations
def cmd_devop(self, args): '''device operations''' usage = "Usage: devop <read|write> <spi|i2c> name bus address" if len(args) < 5: print(usage) return if args[1] == 'spi': bustype = mavutil.mavlink.DEVICE_OP_BUSTYPE_SPI elif args[1] == 'i2c':...
read from device
def devop_read(self, args, bustype): '''read from device''' if len(args) < 5: print("Usage: devop read <spi|i2c> name bus address regstart count") return name = args[0] bus = int(args[1],base=0) address = int(args[2],base=0) reg = int(args[3],base=...
write to a device
def devop_write(self, args, bustype): '''write to a device''' usage = "Usage: devop write <spi|i2c> name bus address regstart count <bytes>" if len(args) < 5: print(usage) return name = args[0] bus = int(args[1],base=0) address = int(args[2],base=0...
Given a set of points geo referenced to this instance, return the points as absolute values.
def get_absolute(self, points): """Given a set of points geo referenced to this instance, return the points as absolute values. """ # remember if we got a list is_list = isinstance(points, list) points = ensure_numeric(points, num.float) if len(points.shape) == ...
camera view commands
def cmd_cameraview(self, args): '''camera view commands''' state = self if args and args[0] == 'set': if len(args) < 3: state.view_settings.show_all() else: state.view_settings.set(args[1], args[2]) state.update_col() ...
scale a PWM value
def scale_rc(self, servo, min, max, param): '''scale a PWM value''' # default to servo range of 1000 to 2000 min_pwm = self.get_mav_param('%s_MIN' % param, 0) max_pwm = self.get_mav_param('%s_MAX' % param, 0) if min_pwm == 0 or max_pwm == 0: return 0 if ma...
handle an incoming mavlink packet
def mavlink_packet(self, m): '''handle an incoming mavlink packet''' state = self mtype = m.get_type() if mtype == 'GLOBAL_POSITION_INT': state.lat, state.lon = m.lat*scale_latlon, m.lon*scale_latlon state.hdg = m.hdg*scale_hdg agl = state.elevation_mo...
Code due to Thomas Heller - published in Python Cookbook (O'Reilley)
def debug_on_error(type, value, tb): """Code due to Thomas Heller - published in Python Cookbook (O'Reilley)""" traceback.print_exc(type, value, tb) print() pdb.pm()
Signal an error condition -- in a GUI, popup a error dialog
def error_msg_wx(msg, parent=None): """ Signal an error condition -- in a GUI, popup a error dialog """ dialog =wx.MessageDialog(parent = parent, message = msg, caption = 'Matplotlib backend_wx error', style=wx.OK | ...
msg is a return arg from a raise. Join with new lines
def raise_msg_to_str(msg): """msg is a return arg from a raise. Join with new lines""" if not is_string_like(msg): msg = '\n'.join(map(str, msg)) return msg
Creates a wx.App instance if it has not been created sofar.
def _create_wx_app(): """ Creates a wx.App instance if it has not been created sofar. """ wxapp = wx.GetApp() if wxapp is None: wxapp = wx.App(False) wxapp.SetExitOnFrameDelete(True) # retain a reference to the app object so it does not get garbage # collected and cau...
This should be overriden in a windowing environment if drawing should be done in interactive python mode
def draw_if_interactive(): """ This should be overriden in a windowing environment if drawing should be done in interactive python mode """ DEBUG_MSG("draw_if_interactive()", 1, None) if matplotlib.is_interactive(): figManager = Gcf.get_active() if figManager is not None: ...
Create a new figure manager instance
def new_figure_manager(num, *args, **kwargs): """ Create a new figure manager instance """ # in order to expose the Figure constructor to the pylab # interface we need to create the figure here DEBUG_MSG("new_figure_manager()", 3, None) _create_wx_app() FigureClass = kwargs.pop('FigureC...
Create a new figure manager instance for the given figure.
def new_figure_manager_given_figure(num, figure): """ Create a new figure manager instance for the given figure. """ fig = figure frame = FigureFrameWx(num, fig) figmgr = frame.get_figure_manager() if matplotlib.is_interactive(): figmgr.frame.Show() return figmgr
Load a bitmap file from the backends/images subdirectory in which the matplotlib library is installed. The filename parameter should not contain any path information as this is determined automatically. Returns a wx.Bitmap object
def _load_bitmap(filename): """ Load a bitmap file from the backends/images subdirectory in which the matplotlib library is installed. The filename parameter should not contain any path information as this is determined automatically. Returns a wx.Bitmap object """ basedir = os.path.join(r...
get the width and height in display coords of the string s with FontPropertry prop
def get_text_width_height_descent(self, s, prop, ismath): """ get the width and height in display coords of the string s with FontPropertry prop """ #return 1, 1 if ismath: s = self.strip_math(s) if self.gc is None: gc = self.new_gc() else: ...
Return an instance of a GraphicsContextWx, and sets the current gc copy
def new_gc(self): """ Return an instance of a GraphicsContextWx, and sets the current gc copy """ DEBUG_MSG('new_gc()', 2, self) self.gc = GraphicsContextWx(self.bitmap, self) self.gc.select() self.gc.unselect() return self.gc
Return a wx font. Cache instances in a font dictionary for efficiency
def get_wx_font(self, s, prop): """ Return a wx font. Cache instances in a font dictionary for efficiency """ DEBUG_MSG("get_wx_font()", 1, self) key = hash(prop) fontprop = prop fontname = fontprop.get_name() font = self.fontd.get(key) ...
Select the current bitmap into this wxDC instance
def select(self): """ Select the current bitmap into this wxDC instance """ if sys.platform=='win32': self.dc.SelectObject(self.bitmap) self.IsSelected = True
Select a Null bitmasp into this wxDC instance
def unselect(self): """ Select a Null bitmasp into this wxDC instance """ if sys.platform=='win32': self.dc.SelectObject(wx.NullBitmap) self.IsSelected = False
Set the foreground color. fg can be a matlab format string, a html hex color string, an rgb unit tuple, or a float between 0 and 1. In the latter case, grayscale is used.
def set_foreground(self, fg, isRGBA=None): """ Set the foreground color. fg can be a matlab format string, a html hex color string, an rgb unit tuple, or a float between 0 and 1. In the latter case, grayscale is used. """ # Implementation note: wxPython has a separate c...
Set the foreground color. fg can be a matlab format string, a html hex color string, an rgb unit tuple, or a float between 0 and 1. In the latter case, grayscale is used.
def set_graylevel(self, frac): """ Set the foreground color. fg can be a matlab format string, a html hex color string, an rgb unit tuple, or a float between 0 and 1. In the latter case, grayscale is used. """ DEBUG_MSG("set_graylevel()", 1, self) self.select() ...
Set the line width.
def set_linewidth(self, w): """ Set the line width. """ DEBUG_MSG("set_linewidth()", 1, self) self.select() if w>0 and w<1: w = 1 GraphicsContextBase.set_linewidth(self, w) lw = int(self.renderer.points_to_pixels(self._linewidth)) if lw==0: lw = 1 ...
Set the capstyle as a string in ('butt', 'round', 'projecting')
def set_capstyle(self, cs): """ Set the capstyle as a string in ('butt', 'round', 'projecting') """ DEBUG_MSG("set_capstyle()", 1, self) self.select() GraphicsContextBase.set_capstyle(self, cs) self._pen.SetCap(GraphicsContextWx._capd[self._capstyle]) self...
Set the join style to be one of ('miter', 'round', 'bevel')
def set_joinstyle(self, js): """ Set the join style to be one of ('miter', 'round', 'bevel') """ DEBUG_MSG("set_joinstyle()", 1, self) self.select() GraphicsContextBase.set_joinstyle(self, js) self._pen.SetJoin(GraphicsContextWx._joind[self._joinstyle]) se...
Set the line style to be one of
def set_linestyle(self, ls): """ Set the line style to be one of """ DEBUG_MSG("set_linestyle()", 1, self) self.select() GraphicsContextBase.set_linestyle(self, ls) try: self._style = GraphicsContextWx._dashd_wx[ls] except KeyError: ...
return a wx.Colour from RGB format
def get_wxcolour(self, color): """return a wx.Colour from RGB format""" DEBUG_MSG("get_wx_color()", 1, self) if len(color) == 3: r, g, b = color r *= 255 g *= 255 b *= 255 return wx.Colour(red=int(r), green=int(g), blue=int(b)) ...
copy bitmap of canvas to system clipboard
def Copy_to_Clipboard(self, event=None): "copy bitmap of canvas to system clipboard" bmp_obj = wx.BitmapDataObject() bmp_obj.SetBitmap(self.bitmap) if not wx.TheClipboard.IsOpened(): open_success = wx.TheClipboard.Open() if open_success: wx.TheClipboa...
Delay rendering until the GUI is idle.
def draw_idle(self): """ Delay rendering until the GUI is idle. """ DEBUG_MSG("draw_idle()", 1, self) self._isDrawn = False # Force redraw # Create a timer for handling draw_idle requests # If there are events pending when the timer is # complete, reset t...
Render the figure using RendererWx instance renderer, or using a previously defined renderer if none is specified.
def draw(self, drawDC=None): """ Render the figure using RendererWx instance renderer, or using a previously defined renderer if none is specified. """ DEBUG_MSG("draw()", 1, self) self.renderer = RendererWx(self.bitmap, self.figure.dpi) self.figure.draw(self.rend...
Start an event loop. This is used to start a blocking event loop so that interactive functions, such as ginput and waitforbuttonpress, can wait for events. This should not be confused with the main GUI event loop, which is always running and has nothing to do with this. Call s...
def start_event_loop(self, timeout=0): """ Start an event loop. This is used to start a blocking event loop so that interactive functions, such as ginput and waitforbuttonpress, can wait for events. This should not be confused with the main GUI event loop, which is always runni...
Stop an event loop. This is used to stop a blocking event loop so that interactive functions, such as ginput and waitforbuttonpress, can wait for events. Call signature:: stop_event_loop_default(self)
def stop_event_loop(self, event=None): """ Stop an event loop. This is used to stop a blocking event loop so that interactive functions, such as ginput and waitforbuttonpress, can wait for events. Call signature:: stop_event_loop_default(self) """ if ha...
return the wildcard string for the filesave dialog
def _get_imagesave_wildcards(self): 'return the wildcard string for the filesave dialog' default_filetype = self.get_default_filetype() filetypes = self.get_supported_filetypes_grouped() sorted_filetypes = filetypes.items() sorted_filetypes.sort() wildcards = [] e...
Performs update of the displayed image on the GUI canvas, using the supplied device context. If drawDC is None, a ClientDC will be used to redraw the image.
def gui_repaint(self, drawDC=None): """ Performs update of the displayed image on the GUI canvas, using the supplied device context. If drawDC is None, a ClientDC will be used to redraw the image. """ DEBUG_MSG("gui_repaint()", 1, self) if self.IsShownOnScreen():...
Called when wxPaintEvt is generated
def _onPaint(self, evt): """ Called when wxPaintEvt is generated """ DEBUG_MSG("_onPaint()", 1, self) drawDC = wx.PaintDC(self) if not self._isDrawn: self.draw(drawDC=drawDC) else: self.gui_repaint(drawDC=drawDC) evt.Skip()
Called when wxEventSize is generated. In this application we attempt to resize to fit the window, so it is better to take the performance hit and redraw the whole window.
def _onSize(self, evt): """ Called when wxEventSize is generated. In this application we attempt to resize to fit the window, so it is better to take the performance hit and redraw the whole window. """ DEBUG_MSG("_onSize()", 2, self) # Create a new, correctly s...
a GUI idle event
def _onIdle(self, evt): 'a GUI idle event' evt.Skip() FigureCanvasBase.idle_event(self, guiEvent=evt)
Capture key press.
def _onKeyDown(self, evt): """Capture key press.""" key = self._get_key(evt) evt.Skip() FigureCanvasBase.key_press_event(self, key, guiEvent=evt)
Release key.
def _onKeyUp(self, evt): """Release key.""" key = self._get_key(evt) #print 'release key', key evt.Skip() FigureCanvasBase.key_release_event(self, key, guiEvent=evt)
Start measuring on an axis.
def _onLeftButtonDown(self, evt): """Start measuring on an axis.""" x = evt.GetX() y = self.figure.bbox.height - evt.GetY() evt.Skip() self.CaptureMouse() FigureCanvasBase.button_press_event(self, x, y, 1, guiEvent=evt)
Start measuring on an axis.
def _onLeftButtonDClick(self, evt): """Start measuring on an axis.""" x = evt.GetX() y = self.figure.bbox.height - evt.GetY() evt.Skip() self.CaptureMouse() FigureCanvasBase.button_press_event(self, x, y, 1, dblclick=True, guiEvent=evt)
End measuring on an axis.
def _onLeftButtonUp(self, evt): """End measuring on an axis.""" x = evt.GetX() y = self.figure.bbox.height - evt.GetY() #print 'release button', 1 evt.Skip() if self.HasCapture(): self.ReleaseMouse() FigureCanvasBase.button_release_event(self, x, y, 1, guiEvent=ev...
Translate mouse wheel events into matplotlib events
def _onMouseWheel(self, evt): """Translate mouse wheel events into matplotlib events""" # Determine mouse location x = evt.GetX() y = self.figure.bbox.height - evt.GetY() # Convert delta/rotation/rate into a floating point step size delta = evt.GetWheelDelta() r...
Start measuring on an axis.
def _onMotion(self, evt): """Start measuring on an axis.""" x = evt.GetX() y = self.figure.bbox.height - evt.GetY() evt.Skip() FigureCanvasBase.motion_notify_event(self, x, y, guiEvent=evt)
Mouse has left the window.
def _onLeave(self, evt): """Mouse has left the window.""" evt.Skip() FigureCanvasBase.leave_notify_event(self, guiEvent = evt)
Set the canvas size in pixels
def resize(self, width, height): 'Set the canvas size in pixels' self.canvas.SetInitialSize(wx.Size(width, height)) self.window.GetSizer().Fit(self.window)
Handle menu button pressed.
def _onMenuButton(self, evt): """Handle menu button pressed.""" x, y = self.GetPositionTuple() w, h = self.GetSizeTuple() self.PopupMenuXY(self._menu, x, y+h-4) # When menu returned, indicate selection in button evt.Skip()
Called when the 'select all axes' menu item is selected.
def _handleSelectAllAxes(self, evt): """Called when the 'select all axes' menu item is selected.""" if len(self._axisId) == 0: return for i in range(len(self._axisId)): self._menu.Check(self._axisId[i], True) self._toolbar.set_active(self.getActiveAxes()) ...
Called when the invert all menu item is selected
def _handleInvertAxesSelected(self, evt): """Called when the invert all menu item is selected""" if len(self._axisId) == 0: return for i in range(len(self._axisId)): if self._menu.IsChecked(self._axisId[i]): self._menu.Check(self._axisId[i], False) else: ...
Called whenever one of the specific axis menu items is selected
def _onMenuItemSelected(self, evt): """Called whenever one of the specific axis menu items is selected""" current = self._menu.IsChecked(evt.GetId()) if current: new = False else: new = True self._menu.Check(evt.GetId(), new) # Lines above would be...
Ensures that there are entries for max_axis axes in the menu (selected by default).
def updateAxes(self, maxAxis): """Ensures that there are entries for max_axis axes in the menu (selected by default).""" if maxAxis > len(self._axisId): for i in range(len(self._axisId) + 1, maxAxis + 1, 1): menuId =wx.NewId() self._axisId.append(menuI...
Return a list of the selected axes.
def getActiveAxes(self): """Return a list of the selected axes.""" active = [] for i in range(len(self._axisId)): if self._menu.IsChecked(self._axisId[i]): active.append(i) return active
Update the list of selected axes in the menu button
def updateButtonText(self, lst): """Update the list of selected axes in the menu button""" axis_txt = '' for e in lst: axis_txt += '%d,' % (e+1) # remove trailing ',' and add to button string self.SetLabel("Axes: %s" % axis_txt[:-1])