<commit_before># Helper class to access the restroom monitor api
# Copyright 2015 Ethan Smith

import urllib
import urllib2
import json
import jwt

class MonitorAPI(object):

   def __init__(self, url, secret, identifier, expiration):
      self.server = url.rstrip('/')
      self.secret = secret
      self.identifier = identifier
      self.expiration = expiration

   def sendMessage(self, method, command, jwt):
      url = self.server+command
      print "Request: " + method + " " + url
      req = urllib2.Request(url)
      req.add_header('identifier', self.identifier)
      req.add_header('jwt', jwt)
      req.get_method = lambda: method
      response = urllib2.urlopen(req)
      data = response.read()
      return json.loads(data)

   def ping(self):
      response = self.sendMessage('GET', '/v1/ping', '')
      return response

   def status(self):
      response = self.sendMessage('GET', '/v1/status', '')
      return response

   def updateStatus(self, status):
      response = self.ping()
      serverTime = response['time']
      jwt = self.createStatusJWT(status, serverTime)
      response = self.sendMessage('POST', '/v1/update', jwt)
      return response

   def createStatusJWT(self, status, currentTime):
      return self.createJWT({
         'status': status,
         'time': currentTime,
         'exp': currentTime+self.expiration
      })

   def createJWT(self, data):
      return jwt.encode(data, self.secret, algorithm='HS512')
<commit_msg>Allow passing of voltage and remote ident in jwt<commit_after># Helper class to access the restroom monitor api
# Copyright 2015 Ethan Smith

import urllib
import urllib2
import json
import jwt

class MonitorAPI(object):

   def __init__(self, url, secret, identifier, expiration):
      self.server = url.rstrip('/')
      self.secret = secret
      self.identifier = identifier
      self.expiration = expiration

   def sendMessage(self, method, command, jwt):
      url = self.server+command
      print "Request: " + method + " " + url
      req = urllib2.Request(url)
      req.add_header('identifier', self.identifier)
      req.add_header('jwt', jwt)
      req.get_method = lambda: method
      response = urllib2.urlopen(req)
      data = response.read()
      return json.loads(data)

   def ping(self):
      response = self.sendMessage('GET', '/v1/ping', '')
      return response

   def status(self):
      response = self.sendMessage('GET', '/v1/status', '')
      return response

   def updateStatus(self, status, voltage = "", remoteIdent = ""):
      response = self.ping()
      serverTime = response['time']
      jwt = self.createStatusJWT(status, voltage, remoteIdent, serverTime)
      response = self.sendMessage('POST', '/v1/update', jwt)
      return response

   def createStatusJWT(self, status, voltage, remoteIdent, currentTime):
      return self.createJWT({
         'status': status,
         'voltage': voltage,
         'remoteIdent': remoteIdent,
         'time': currentTime,
         'identifier': self.identifier,
         'exp': currentTime+self.expiration
      })

   def createJWT(self, data):
      return jwt.encode(data, self.secret, algorithm='HS512')
<|endoftext|>


<commit_before>import os
import sys

#Danica is cool.
DIR = os.path.join(os.path.dirname(__file__), '..')
sys.path.insert(0, DIR)

from OScan import ui
reload(ui)
from PySide import QtGui

if __name__ == '__main__':
    qtapp = QtGui.QApplication(sys.argv)
    app = ui.UI()
    app.show()
    sys.exit(qtapp.exec_())
<commit_msg>Removed danica comment. She stinks.<commit_after>import os
import sys

DIR = os.path.join(os.path.dirname(__file__), '..')
sys.path.insert(0, DIR)

from OScan import ui
reload(ui)
from PySide import QtGui

if __name__ == '__main__':
    qtapp = QtGui.QApplication(sys.argv)
    app = ui.UI()
    app.show()
    sys.exit(qtapp.exec_())
<|endoftext|>


<commit_before>############################################################
# FlatCAM: 2D Post-processing for Manufacturing            #
# http://caram.cl/software/flatcam                         #
# Author: Juan Pablo Caram (c)                             #
# Date: 2/5/2014                                           #
# MIT Licence                                              #
############################################################

from PyQt4 import QtGui, QtCore

# Prevent conflict with Qt5 and above.
from matplotlib import use as mpl_use
mpl_use("Qt4Agg")

import FlatCAMApp
from cStringIO import StringIO
import matplotlib.image as mpimg
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureOffscreenCanvas

class PlotCanvas:
    """
    Class handling the plotting area in the application.
    """

    app = None

    def __init__(self, container):
        """
        The constructor configures the Matplotlib figure that
        will contain all plots, creates the base axes and connects
        events to the plotting area.

        :param container: The parent container in which to draw plots.
        :rtype: PlotCanvas
        """
        # Options
        self.x_margin = 15  # pixels
        self.y_margin = 25  # Pixels

        # Parent container
        self.container = container

        # Plots go onto a single matplotlib.figure
        self.figure = Figure(dpi=50)  # TODO: dpi needed?
        self.figure.patch.set_visible(False)

        # Offscreen figure
        self.offscreen_figure = Figure(dpi=50)
        self.offscreen_figure.patch.set_visible(False)

        # These axes show the ticks and grid. No plotting done here.
        # New axes must have a label, otherwise mpl returns an existing one.
        self.axes = self.figure.add_axes([0.05, 0.05, 0.9, 0.9], label="base", alpha=0.0)
        self.axes.set_aspect(1)
        self.axes.grid(True)

        # The canvas is the top level container (Gtk.DrawingArea)
        self.canvas = FigureCanvas(self.figure)
        self.offscreen_canvas = FigureOffscreenCanvas(self.offscreen_figure)
        # self.canvas.setFocusPolicy(QtCore.Qt.ClickFocus)
        # self.canvas.setFocus()

        # Image
        self.image = None

        #self.canvas.set_hexpand(1)
        #self.canvas.set_vexpand(1)
        #self.canvas.set_can_focus(True)  # For key press

        # Attach to parent
        #self.container.attach(self.canvas, 0, 0, 600, 400)  # TODO: Height and width are num. columns??
        self.container.addWidget(self.canvas)  # Qt

        # Copy a bitmap of the canvas for quick animation.
        # Update every time the canvas is re-drawn.
        self.background = self.canvas.copy_from_bbox(self.axes.bbox)

        # Events
        self.canvas.mpl_connect('button_press_event', self.on_mouse_press)
        self.canvas.mpl_connect('button_release_event', self.on_mouse_release)
        self.canvas.mpl_connect('motion_notify_event', self.on_mouse_move)
        #self.canvas.connect('configure-event', self.auto_adjust_axes)
        self.canvas.mpl_connect('resize_event', self.auto_adjust_axes)
        #self.canvas.add_events(Gdk.EventMask.SMOOTH_SCROLL_MASK)
        #self.canvas.connect("scroll-event", self.on_scroll)
        self.canvas.mpl_connect('scroll_event', self.on_scroll)
        self.canvas.mpl_connect('key_press_event', self.on_key_down)
        self.canvas.mpl_connect('key_release_event', self.on_key_up)
        self.canvas.mpl_connect('draw_event', self.on_draw)

        self.mouse = [0, 0]
        self.key = None

        self.pan_axes = []
        self.panning = False

    def on_key_down(self, event):
        """

        :param event:
        :return:
        """
        FlatCAMApp.App.log.debug('on_key_down(): ' + str(event.key))
        self.key = event.key

    def on_key_up(self, event):
        """

        :param event:
        :return:
        """
        self.key = None

    def mpl_connect(self, event_name, callback):
        """
        Attach an event handler to the canvas through the Matplotlib interface.

        :param event_name: Name of the event
        :type event_name: str
        :param callback: Function to call
        :type callback: func
        :return: Connection id
        :rtype: int
        """
        return self.canvas.mpl_connect(event_name, callback)

    def mpl_disconnect(self, cid):
        """
        Disconnect callback with the give id.
        :param cid: Callback id.
        :return: None
        """
        self.canvas.mpl_disconnect(cid)

    def connect(self, event_name, callback):
        """
        Attach an event handler to the canvas through the native GTK interface.

        :param event_name: Name of the event
        :type event_name: str
        :param callback: Function to call
        :type callback: function
        :return: Nothing
        """
        self.canvas.connect(event_name, callback)

    def clear(self):
        """
        Clears axes and figure.

        :return: None
        """

        # Clear
        self.axes.cla()
        try:
            self.figure.clf()
            self.offscreen_figure.clf()
        except KeyError:
            FlatCAMApp.App.log.warning("KeyError in MPL figure.clf()")

        # Re-build
        self.figure.add_axes(self.axes)
        self.axes.set_aspect(1)
        self.axes.grid(True)

        # Prepare offscreen base axes
        ax = self.offscreen_figure.add_axes([0.0, 0.0, 1.0, 1.0], label='base')
        ax.set_frame_on(True)
        ax.patch.set_color("white")
        # Hide frame edge
        for spine in ax.spines:
            ax.spines[spine].set_visible(False)
        ax.set_aspect(1)

        # Re-draw
        self.canvas.draw_idle()

    def adjust_axes(self, xmin, ymin, xmax, ymax):
        """
        Adjusts all axes while maintaining the use of the whole canvas
        and an aspect ratio to 1:1 between x and y axes. The parameters are an original
        request that will be modified to fit these restrictions.

        :param xmin: Requested minimum value for the X axis.
        :type xmin: float
        :param ymin: Requested minimum value for the Y axis.
        :type ymin: float
        :param xmax: Requested maximum value for the X axis.
        :type xmax: float
        :param ymax: Requested maximum value for the Y axis.
        :type ymax: float
        :return: None
        """

        # FlatCAMApp.App.log.debug("PC.adjust_axes()")

        width = xmax - xmin
        height = ymax - ymin
        try:
            r = width / height
        except ZeroDivisionError:
            FlatCAMApp.App.log.error("Height is %f" % height)
            return
        canvas_w, canvas_h = self.canvas.get_width_height()
        canvas_r = float(canvas_w) / canvas_h
        x_ratio = float(self.x_margin) / canvas_w
        y_ratio = float(self.y_margin) / canvas_h

        if r > canvas_r:
            ycenter = (ymin + ymax) / 2.0
            newheight = height * r / canvas_r
            ymin = ycenter - newheight / 2.0
            ymax = ycenter + newheight / 2.0
        else:
            xcenter = (xmax + xmin) / 2.0
            newwidth = width * canvas_r / r
            xmin = xcenter - newwidth / 2.0
            xmax = xcenter + newwidth / 2.0

        # Adjust axes
        for ax in self.figure.get_axes():
            if ax._label != 'base':
                ax.set_frame_on(False)  # No frame
                ax.set_xticks([])  # No tick
                ax.set_yticks([])  # No ticks
                ax.patch.set_visible(False)  # No background
                ax.set_aspect(1)
            ax.set_xlim((xmin, xmax))
            ax.set_ylim((ymin, ymax))
            ax.set_position([x_ratio, y_ratio, 1 - 2 * x_ratio, 1 - 2 * y_ratio])

        # Sync re-draw to proper paint on form resize
        self.canvas.draw()

    def auto_adjust_axes(self, *args):
        """
        Calls ``adjust_axes()`` using the extents of the base axes.

        :rtype : None
        :return: None
        """

        xmin, xmax = self.axes.get_xlim()
        ymin, ymax = self.axes.get_ylim()
        self.adjust_axes(xmin, ymin, xmax, ymax)

    def zoom(self, factor, center=None):
        """
        Zooms the plot by factor around a given
        center point. Takes care of re-drawing.

        :param factor: Number by which to scale the plot.
        :type factor: float
        :param center: Coordinates [x, y] of the point around which to scale the plot.
        :type center: list
        :return: None
        """

        xmin, xmax = self.axes.get_xlim()
        ymin, ymax = self.axes.get_ylim()

        width = xmax - xmin
        height = ymax - ymin

        if center is None or center == [None, None]:
            center = [(xmin + xmax) / 2.0, (ymin + ymax) / 2.0]

        # For keeping the point at the pointer location
        relx = (xmax - center[0]) / width
        rely = (ymax - center[1]) / height

        new_width = width / factor
        new_height = height / factor

        xmin = center[0] - new_width * (1 - relx)
        xmax = center[0] + new_width * relx
        ymin = center[1] - new_height * (1 - rely)
        ymax = center[1] + new_height * rely

        # Adjust axes
        for ax in self.figure.get_axes():
            ax.set_xlim((xmin, xmax))
            ax.set_ylim((ymin, ymax))

        # Async re-draw
        self.canvas.draw_idle()

        # Get bounds
        margin = 2
        x1, y1, x2, y2 = self.app.collection.get_bounds()
        x1, y1, x2, y2 = x1 - margin, y1 - margin, x2 + margin, y2 + margin

        # Calculate bounds in screen space
        points = self.axes.transData.transform([(x1, y1), (x2, y2)]);

        # Calculate width/height of image
        w, h = round(points[1][0] - points[0][0]), round(points[1][1] - points[0][1])

        # Rescale axes
        for ax in self.offscreen_figure.get_axes():
            ax.set_xlim(x1, x2)
            ax.set_ylim(y1, y2)
            ax.set_xticks([])
            ax.set_yticks([])

        # Resize figure
        dpi = self.offscreen_figure.dpi
        self.offscreen_figure.set_size_inches(w / dpi, h / dpi)

        # Draw to image
        cache = StringIO()
        self.offscreen_canvas.print_png(cache, format="png")
        cache.seek(0)
        image = mpimg.imread(cache, format="png")

        # Add image to canvas
        try:
            self.image.remove()
        finally:
            self.image = self.axes.imshow(image, extent=(x1, x2, y1, y2), interpolation="nearest")

    def pan(self, x, y):
        xmin, xmax = self.axes.get_xlim()
        ymin, ymax = self.axes.get_ylim()
        width = xmax - xmin
        height = ymax - ymin

        # Adjust axes
        for ax in self.figure.get_axes():
            ax.set_xlim((xmin + x * width, xmax + x * width))
            ax.set_ylim((ymin + y * height, ymax + y * height))

        # Re-draw
        self.canvas.draw_idle()

    def new_axes(self, name):
        """
        Creates and returns an Axes object attached to this object's Figure.

        :param name: Unique label for the axes.
        :return: Axes attached to the figure.
        :rtype: Axes
        """

        ax = self.offscreen_figure.add_axes([0.0, 0.0, 1.0, 1.0], label=name)

        ax.set_frame_on(False)  # No frame
        ax.patch.set_visible(False)  # No background
        ax.set_aspect(1)

        return ax

    def on_scroll(self, event):
        """
        Scroll event handler.

        :param event: Event object containing the event information.
        :return: None
        """

        # So it can receive key presses
        # self.canvas.grab_focus()
        self.canvas.setFocus()

        # Event info
        # z, direction = event.get_scroll_direction()

        if self.key is None:

            if event.button == 'up':
                self.zoom(1.5, self.mouse)
            else:
                self.zoom(1 / 1.5, self.mouse)
            return

        if self.key == 'shift':

            if event.button == 'up':
                self.pan(0.3, 0)
            else:
                self.pan(-0.3, 0)
            return

        if self.key == 'control':

            if event.button == 'up':
                self.pan(0, 0.3)
            else:
                self.pan(0, -0.3)
            return

    def on_mouse_press(self, event):

        # Check for middle mouse button press
        if event.button == 2:

            # Prepare axes for pan (using 'matplotlib' pan function)
            self.pan_axes = []
            for a in self.figure.get_axes():
                if (event.x is not None and event.y is not None and a.in_axes(event) and
                        a.get_navigate() and a.can_pan()):
                    a.start_pan(event.x, event.y, 1)
                    self.pan_axes.append(a)

            # Set pan view flag
            if len(self.pan_axes) > 0:
                self.panning = True;

    def on_mouse_release(self, event):

        # Check for middle mouse button release to complete pan procedure
        if event.button == 2:
            for a in self.pan_axes:
                a.end_pan()

            # Clear pan flag
            self.panning = False

    def on_mouse_move(self, event):
        """
        Mouse movement event hadler. Stores the coordinates. Updates view on pan.

        :param event: Contains information about the event.
        :return: None
        """
        self.mouse = [event.xdata, event.ydata]

        # Update pan view on mouse move
        if self.panning is True:
            for a in self.pan_axes:
                a.drag_pan(1, event.key, event.x, event.y)

            # Async re-draw (redraws only on thread idle state, uses timer on backend)
            self.canvas.draw_idle()

    def on_draw(self, renderer):

        # Store background on canvas redraw
        self.background = self.canvas.copy_from_bbox(self.axes.bbox)
<commit_msg>Numpy array as image source.<commit_after>############################################################
# FlatCAM: 2D Post-processing for Manufacturing            #
# http://caram.cl/software/flatcam                         #
# Author: Juan Pablo Caram (c)                             #
# Date: 2/5/2014                                           #
# MIT Licence                                              #
############################################################

from PyQt4 import QtGui, QtCore

# Prevent conflict with Qt5 and above.
from matplotlib import use as mpl_use
mpl_use("Qt4Agg")

import FlatCAMApp
from cStringIO import StringIO
import matplotlib.image as mpimg
import numpy as np
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureOffscreenCanvas

class PlotCanvas:
    """
    Class handling the plotting area in the application.
    """

    app = None

    def __init__(self, container):
        """
        The constructor configures the Matplotlib figure that
        will contain all plots, creates the base axes and connects
        events to the plotting area.

        :param container: The parent container in which to draw plots.
        :rtype: PlotCanvas
        """
        # Options
        self.x_margin = 15  # pixels
        self.y_margin = 25  # Pixels

        # Parent container
        self.container = container

        # Plots go onto a single matplotlib.figure
        self.figure = Figure(dpi=50)  # TODO: dpi needed?
        self.figure.patch.set_visible(False)

        # Offscreen figure
        self.offscreen_figure = Figure(dpi=50)
        self.offscreen_figure.patch.set_visible(False)

        # These axes show the ticks and grid. No plotting done here.
        # New axes must have a label, otherwise mpl returns an existing one.
        self.axes = self.figure.add_axes([0.05, 0.05, 0.9, 0.9], label="base", alpha=0.0)
        self.axes.set_aspect(1)
        self.axes.grid(True)

        # The canvas is the top level container (Gtk.DrawingArea)
        self.canvas = FigureCanvas(self.figure)
        self.offscreen_canvas = FigureOffscreenCanvas(self.offscreen_figure)
        # self.canvas.setFocusPolicy(QtCore.Qt.ClickFocus)
        # self.canvas.setFocus()

        # Image
        self.image = None

        #self.canvas.set_hexpand(1)
        #self.canvas.set_vexpand(1)
        #self.canvas.set_can_focus(True)  # For key press

        # Attach to parent
        #self.container.attach(self.canvas, 0, 0, 600, 400)  # TODO: Height and width are num. columns??
        self.container.addWidget(self.canvas)  # Qt

        # Copy a bitmap of the canvas for quick animation.
        # Update every time the canvas is re-drawn.
        self.background = self.canvas.copy_from_bbox(self.axes.bbox)

        # Events
        self.canvas.mpl_connect('button_press_event', self.on_mouse_press)
        self.canvas.mpl_connect('button_release_event', self.on_mouse_release)
        self.canvas.mpl_connect('motion_notify_event', self.on_mouse_move)
        #self.canvas.connect('configure-event', self.auto_adjust_axes)
        self.canvas.mpl_connect('resize_event', self.auto_adjust_axes)
        #self.canvas.add_events(Gdk.EventMask.SMOOTH_SCROLL_MASK)
        #self.canvas.connect("scroll-event", self.on_scroll)
        self.canvas.mpl_connect('scroll_event', self.on_scroll)
        self.canvas.mpl_connect('key_press_event', self.on_key_down)
        self.canvas.mpl_connect('key_release_event', self.on_key_up)
        self.canvas.mpl_connect('draw_event', self.on_draw)

        self.mouse = [0, 0]
        self.key = None

        self.pan_axes = []
        self.panning = False

    def on_key_down(self, event):
        """

        :param event:
        :return:
        """
        FlatCAMApp.App.log.debug('on_key_down(): ' + str(event.key))
        self.key = event.key

    def on_key_up(self, event):
        """

        :param event:
        :return:
        """
        self.key = None

    def mpl_connect(self, event_name, callback):
        """
        Attach an event handler to the canvas through the Matplotlib interface.

        :param event_name: Name of the event
        :type event_name: str
        :param callback: Function to call
        :type callback: func
        :return: Connection id
        :rtype: int
        """
        return self.canvas.mpl_connect(event_name, callback)

    def mpl_disconnect(self, cid):
        """
        Disconnect callback with the give id.
        :param cid: Callback id.
        :return: None
        """
        self.canvas.mpl_disconnect(cid)

    def connect(self, event_name, callback):
        """
        Attach an event handler to the canvas through the native GTK interface.

        :param event_name: Name of the event
        :type event_name: str
        :param callback: Function to call
        :type callback: function
        :return: Nothing
        """
        self.canvas.connect(event_name, callback)

    def clear(self):
        """
        Clears axes and figure.

        :return: None
        """

        # Clear
        self.axes.cla()
        try:
            self.figure.clf()
            self.offscreen_figure.clf()
        except KeyError:
            FlatCAMApp.App.log.warning("KeyError in MPL figure.clf()")

        # Re-build
        self.figure.add_axes(self.axes)
        self.axes.set_aspect(1)
        self.axes.grid(True)

        # Prepare offscreen base axes
        ax = self.offscreen_figure.add_axes([0.0, 0.0, 1.0, 1.0], label='base')
        ax.set_frame_on(True)
        ax.patch.set_color("white")
        # Hide frame edge
        for spine in ax.spines:
            ax.spines[spine].set_visible(False)
        ax.set_aspect(1)

        # Re-draw
        self.canvas.draw_idle()

    def adjust_axes(self, xmin, ymin, xmax, ymax):
        """
        Adjusts all axes while maintaining the use of the whole canvas
        and an aspect ratio to 1:1 between x and y axes. The parameters are an original
        request that will be modified to fit these restrictions.

        :param xmin: Requested minimum value for the X axis.
        :type xmin: float
        :param ymin: Requested minimum value for the Y axis.
        :type ymin: float
        :param xmax: Requested maximum value for the X axis.
        :type xmax: float
        :param ymax: Requested maximum value for the Y axis.
        :type ymax: float
        :return: None
        """

        # FlatCAMApp.App.log.debug("PC.adjust_axes()")

        width = xmax - xmin
        height = ymax - ymin
        try:
            r = width / height
        except ZeroDivisionError:
            FlatCAMApp.App.log.error("Height is %f" % height)
            return
        canvas_w, canvas_h = self.canvas.get_width_height()
        canvas_r = float(canvas_w) / canvas_h
        x_ratio = float(self.x_margin) / canvas_w
        y_ratio = float(self.y_margin) / canvas_h

        if r > canvas_r:
            ycenter = (ymin + ymax) / 2.0
            newheight = height * r / canvas_r
            ymin = ycenter - newheight / 2.0
            ymax = ycenter + newheight / 2.0
        else:
            xcenter = (xmax + xmin) / 2.0
            newwidth = width * canvas_r / r
            xmin = xcenter - newwidth / 2.0
            xmax = xcenter + newwidth / 2.0

        # Adjust axes
        for ax in self.figure.get_axes():
            if ax._label != 'base':
                ax.set_frame_on(False)  # No frame
                ax.set_xticks([])  # No tick
                ax.set_yticks([])  # No ticks
                ax.patch.set_visible(False)  # No background
                ax.set_aspect(1)
            ax.set_xlim((xmin, xmax))
            ax.set_ylim((ymin, ymax))
            ax.set_position([x_ratio, y_ratio, 1 - 2 * x_ratio, 1 - 2 * y_ratio])

        # Sync re-draw to proper paint on form resize
        self.canvas.draw()

    def auto_adjust_axes(self, *args):
        """
        Calls ``adjust_axes()`` using the extents of the base axes.

        :rtype : None
        :return: None
        """

        xmin, xmax = self.axes.get_xlim()
        ymin, ymax = self.axes.get_ylim()
        self.adjust_axes(xmin, ymin, xmax, ymax)

    def zoom(self, factor, center=None):
        """
        Zooms the plot by factor around a given
        center point. Takes care of re-drawing.

        :param factor: Number by which to scale the plot.
        :type factor: float
        :param center: Coordinates [x, y] of the point around which to scale the plot.
        :type center: list
        :return: None
        """

        xmin, xmax = self.axes.get_xlim()
        ymin, ymax = self.axes.get_ylim()

        width = xmax - xmin
        height = ymax - ymin

        if center is None or center == [None, None]:
            center = [(xmin + xmax) / 2.0, (ymin + ymax) / 2.0]

        # For keeping the point at the pointer location
        relx = (xmax - center[0]) / width
        rely = (ymax - center[1]) / height

        new_width = width / factor
        new_height = height / factor

        xmin = center[0] - new_width * (1 - relx)
        xmax = center[0] + new_width * relx
        ymin = center[1] - new_height * (1 - rely)
        ymax = center[1] + new_height * rely

        # Adjust axes
        for ax in self.figure.get_axes():
            ax.set_xlim((xmin, xmax))
            ax.set_ylim((ymin, ymax))

        # Async re-draw
        self.canvas.draw_idle()

        # Get bounds
        margin = 2
        x1, y1, x2, y2 = self.app.collection.get_bounds()
        x1, y1, x2, y2 = x1 - margin, y1 - margin, x2 + margin, y2 + margin

        # Calculate bounds in screen space
        points = self.axes.transData.transform([(x1, y1), (x2, y2)]);

        # Calculate width/height of image
        w, h = round(points[1][0] - points[0][0]), round(points[1][1] - points[0][1])

        def update_image():

            # Rescale axes
            for ax in self.offscreen_figure.get_axes():
                ax.set_xlim(x1, x2)
                ax.set_ylim(y1, y2)
                ax.set_xticks([])
                ax.set_yticks([])

            # Resize figure
            dpi = self.offscreen_figure.dpi
            self.offscreen_figure.set_size_inches(w / dpi, h / dpi)

            # Draw to buffer
            self.offscreen_canvas.draw()

            buf = self.offscreen_canvas.buffer_rgba()
            ncols, nrows = self.offscreen_canvas.get_width_height()
            image = np.frombuffer(buf, dtype=np.uint8).reshape(nrows, ncols, 4)

            # Remove previous image if exists
            try:
                self.image.remove()
            except:
                pass

            # Set new image
            self.image = self.axes.imshow(image, extent=(x1, x2, y1, y2), interpolation="nearest")

            # Update canvas
            self.canvas.draw_idle()

        # Do job in background
        proc = self.app.proc_container.new("Updating view.")

        def job_thread(app_obj):
            try:
                update_image()
            except Exception as e:
                proc.done()
                raise e
            proc.done()

        self.app.inform.emit("View update starting ...")
        self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})

    def pan(self, x, y):
        xmin, xmax = self.axes.get_xlim()
        ymin, ymax = self.axes.get_ylim()
        width = xmax - xmin
        height = ymax - ymin

        # Adjust axes
        for ax in self.figure.get_axes():
            ax.set_xlim((xmin + x * width, xmax + x * width))
            ax.set_ylim((ymin + y * height, ymax + y * height))

        # Re-draw
        self.canvas.draw_idle()

    def new_axes(self, name):
        """
        Creates and returns an Axes object attached to this object's Figure.

        :param name: Unique label for the axes.
        :return: Axes attached to the figure.
        :rtype: Axes
        """

        ax = self.offscreen_figure.add_axes([0.0, 0.0, 1.0, 1.0], label=name)

        ax.set_frame_on(False)  # No frame
        ax.patch.set_visible(False)  # No background
        ax.set_aspect(1)

        return ax

    def on_scroll(self, event):
        """
        Scroll event handler.

        :param event: Event object containing the event information.
        :return: None
        """

        # So it can receive key presses
        # self.canvas.grab_focus()
        self.canvas.setFocus()

        # Event info
        # z, direction = event.get_scroll_direction()

        if self.key is None:

            if event.button == 'up':
                self.zoom(1.5, self.mouse)
            else:
                self.zoom(1 / 1.5, self.mouse)
            return

        if self.key == 'shift':

            if event.button == 'up':
                self.pan(0.3, 0)
            else:
                self.pan(-0.3, 0)
            return

        if self.key == 'control':

            if event.button == 'up':
                self.pan(0, 0.3)
            else:
                self.pan(0, -0.3)
            return

    def on_mouse_press(self, event):

        # Check for middle mouse button press
        if event.button == 2:

            # Prepare axes for pan (using 'matplotlib' pan function)
            self.pan_axes = []
            for a in self.figure.get_axes():
                if (event.x is not None and event.y is not None and a.in_axes(event) and
                        a.get_navigate() and a.can_pan()):
                    a.start_pan(event.x, event.y, 1)
                    self.pan_axes.append(a)

            # Set pan view flag
            if len(self.pan_axes) > 0:
                self.panning = True;

    def on_mouse_release(self, event):

        # Check for middle mouse button release to complete pan procedure
        if event.button == 2:
            for a in self.pan_axes:
                a.end_pan()

            # Clear pan flag
            self.panning = False

    def on_mouse_move(self, event):
        """
        Mouse movement event hadler. Stores the coordinates. Updates view on pan.

        :param event: Contains information about the event.
        :return: None
        """
        self.mouse = [event.xdata, event.ydata]

        # Update pan view on mouse move
        if self.panning is True:
            for a in self.pan_axes:
                a.drag_pan(1, event.key, event.x, event.y)

            # Async re-draw (redraws only on thread idle state, uses timer on backend)
            self.canvas.draw_idle()

    def on_draw(self, renderer):

        # Store background on canvas redraw
        self.background = self.canvas.copy_from_bbox(self.axes.bbox)
<|endoftext|>


<commit_before>import pylab
import matplotlib
from matplotlib import pyplot
import sys
import os

from Utils import getGoldenRatioDimensions

class PlotLayout(object):
    def __init__(self):
        self.groupedPlots = {}
        self.plots = []
        self.groupOrder = None

        self.width = 1
        self.plotParams = None

        self.dimensions = None
        self.figdimensions = None

        self.figLegendLoc = None
        self.figLegendCols = None

        self.rcParams = None

    def __setRCParam(self, param, value):
        if self.rcParams is None:
            self.rcParams = {}

        self.rcParams[param] = value

    def useLatexLabels(self):
        print >>sys.stderr, "WARNING: Using LaTeX labels requires dvipng and ghostscript"
        self.__setRCParam("font.family", "serif")
        self.__setRCParam("font.serif", "Times, Palatino, New Century Schoolbook, Bookman, Computer Modern Roman")
        self.__setRCParam("font.sans-serif", "Helvetica, Avant Garde, Computer Modern Sans serif")
        self.__setRCParam("font.cursive", "Zapf Chancery")
        self.__setRCParam("font.monospace", "Courier, Computer Modern Typewriter")
        self.__setRCParam("text.usetex", True)

    # def useStandardFont(self):
    #     self.__setRCParam("font.family", "serif")
    #     self.__setRCParam("font.style", "normal")
    #     self.__setRCParam("font.variant", "normal")
    #     self.__setRCParam("font.weight", "normal")
    #     self.__setRCParam("font.stretch", "normal")

    def setAxesLabelSize(self, size):
        self.__setRCParam("axes.labelsize", size)

    def setXTickLabelSize(self, size):
        self.__setRCParam("xtick.labelsize", size)

    def setYTickLabelSize(self, size):
        self.__setRCParam("ytick.labelsize", size)

    def setLegendLabelSize(self, size):
        self.__setRCParam("legend.fontsize", size)

    def setWidth(self, width):
        self.width = int(width)

    def hasFigLegend(self, loc="best", numcols=1):
        self.figLegendLoc = loc
        self.figLegendCols = numcols

    def addPlot(self, plot, grouping=None):
        if grouping == None:
            self.plots.append(plot)
        else:
            if grouping not in self.groupedPlots:
                self.groupedPlots[grouping] = []

            self.groupedPlots[grouping].append(plot)

    def setGroupOrder(self, groupOrder):
        self.groupOrder = groupOrder

    def setPlotDimensions(self, x, y):
        self.dimensions = (x,y)

    def setFigureDimensions(self, x, y):
        self.figdimensions = (x,y)

    def setPlotParameters(self, **kwdict):
        self.plotParams = dict(kwdict)

        if "left" not in self.plotParams:
            self.plotParams["left"] = 0.12

        if "bottom" not in self.plotParams:
            self.plotParams["bottom"] = 0.10

        if "right" not in self.plotParams:
            self.plotParams["right"] = 0.90

        if "top" not in self.plotParams:
            self.plotParams["top"] = 0.90

        if "wspace" not in self.plotParams:
            self.plotParams["wspace"] = 0.20

        if "hspace" not in self.plotParams:
            self.plotParams["hspace"] = 0.20

    def _doPlot(self):
        if len(self.groupedPlots) + len(self.plots) == 0:
            print "PlotLayout.plot(): No data to plot!"
            return

        if self.rcParams is not None:
            pylab.rcParams.update(self.rcParams)

        groupedPlotLengths = [len(plots) for plots in self.groupedPlots.values()]

        if len(groupedPlotLengths) == 0:
            maxRowLength = self.width
        else:
            maxRowLength = max(groupedPlotLengths)

        numPlots = len(self.plots)

        if numPlots == 0:
            numExcessRows = 0
        elif numPlots <= maxRowLength:
            numExcessRows = 1
        elif numPlots % maxRowLength == 0:
            numExcessRows = numPlots / maxRowLength
        else:
            numExcessRows = (numPlots / maxRowLength) + 1

        numRows = len(self.groupedPlots.keys()) + numExcessRows

        if self.groupOrder is not None:
            keyList = self.groupOrder
        else:
            keyList = self.groupedPlots.keys()

        currentRow = 0

        if self.figdimensions is not None:
            fig = pyplot.figure(figsize=(self.figdimensions[0],
                                         self.figdimensions[1]))
        elif self.dimensions is not None:
            fig = pyplot.figure(figsize=(self.dimensions[0] * maxRowLength,
                                         self.dimensions[1] * numRows))
        else:
            (figWidth, figHeight) = getGoldenRatioDimensions(8.0)
            figWidth *= maxRowLength
            figHeight *= numRows
            fig = pyplot.figure(figsize=(figWidth, figHeight))
            # figWidth = fig.get_figwidth()
            # print figWidth
            # print fig.get_figheight()
            # (goldenWidth, goldenHeight) = getGoldenRatioDimensions(figWidth)
            # fig.set_figheight(goldenHeight)
            # print fig.get_figheight()

        plotHandles = []
        plotLabels = []

        for grouping in keyList:
            currentColumn = 1
            plots = self.groupedPlots[grouping]

            numPlots = len(plots)

            for plot in plots:
                myRows = numRows
                myCols = numPlots
                myPos = (currentRow * numPlots) + currentColumn

                (currPlotHandles, currPlotLabels) = plot.subplot(
                    myRows, myCols, myPos)

                for i in xrange(len(currPlotHandles)):
                    if currPlotLabels[i] in plotLabels:
                        continue

                    if isinstance(currPlotHandles[i], list):
                        plotHandles.append(currPlotHandles[i][0])
                    else:
                        plotHandles.append(currPlotHandles[i])

                    plotLabels.append(currPlotLabels[i])

#                plotHandles.extend(currPlotHandles)
#                plotLabels.extend(currPlotLabels)

                currentColumn += 1
            currentRow += 1

        ungroupedPlotsRemaining = len(self.plots)
        if ungroupedPlotsRemaining > 0:
            currentColumn = 1

            for plot in self.plots:
                if currentColumn == 1:
                    numColumns = min(maxRowLength, ungroupedPlotsRemaining)

                myRows = numRows
                myCols = numColumns
                myPos = (currentRow * numColumns) + currentColumn

                (currPlotHandles, currPlotLabels) = plot.subplot(
                    myRows, myCols, myPos)
                for i in xrange(len(currPlotHandles)):
                    if currPlotLabels[i] in plotLabels:
                        continue

                    if isinstance(currPlotHandles[i], list):
                        plotHandles.append(currPlotHandles[i][0])
                    else:
                        plotHandles.append(currPlotHandles[i])

                    plotLabels.append(currPlotLabels[i])

                currentColumn += 1

                if currentColumn > numColumns:
                    currentRow += 1
                    currentColumn = 1

                ungroupedPlotsRemaining -= 1

        if self.figLegendLoc is not None:
            figLegendKeywords = {}

            if self.figLegendCols is not None:
                versionPieces = [int(x) for x in matplotlib.__version__.split('.')]

                (superMajor, major, minor) = versionPieces[0:3]

                if superMajor == 0 and major < 98:
                    print >>sys.stderr, "Number of columns support not available in versions of matplotlib prior to 0.98"
                else:
                    figLegendKeywords["ncol"] = self.figLegendCols

            pylab.figlegend(plotHandles, plotLabels,
                            self.figLegendLoc,
                            **figLegendKeywords)

        if self.plotParams is not None:
            pylab.subplots_adjust(left=self.plotParams["left"],
                                  bottom=self.plotParams["bottom"],
                                  right=self.plotParams["right"],
                                  top=self.plotParams["top"],
                                  wspace=self.plotParams["wspace"],
                                  hspace=self.plotParams["hspace"])

    def plot(self):
        self._doPlot()
        if not pylab.isinteractive():
            pylab.show()
        else:
            pylab.draw()

    def save(self, filename, **kwargs):
        print >>sys.stderr, "Saving %s ..." % filename

        tempDisplayHack = False

        if "DISPLAY" not in os.environ:
            tempDisplayHack = True
            os.environ["DISPLAY"] = ":0.0"
        self._doPlot()
        pylab.savefig(filename,**kwargs)
        pylab.clf()

        if tempDisplayHack == True:
            del os.environ["DISPLAY"]
<commit_msg>Making hasLegend/hasFigLegend consistent w/columns vs numcols. Added deprecation warning<commit_after>import pylab
import matplotlib
from matplotlib import pyplot
import sys
import os
import warnings

from Utils import getGoldenRatioDimensions

class PlotLayout(object):
    def __init__(self):
        self.groupedPlots = {}
        self.plots = []
        self.groupOrder = None

        self.width = 1
        self.plotParams = None

        self.dimensions = None
        self.figdimensions = None

        self.figLegendLoc = None
        self.figLegendCols = None

        self.rcParams = None

    def __setRCParam(self, param, value):
        if self.rcParams is None:
            self.rcParams = {}

        self.rcParams[param] = value

    def useLatexLabels(self):
        print >>sys.stderr, "WARNING: Using LaTeX labels requires dvipng and ghostscript"
        self.__setRCParam("font.family", "serif")
        self.__setRCParam("font.serif", "Times, Palatino, New Century Schoolbook, Bookman, Computer Modern Roman")
        self.__setRCParam("font.sans-serif", "Helvetica, Avant Garde, Computer Modern Sans serif")
        self.__setRCParam("font.cursive", "Zapf Chancery")
        self.__setRCParam("font.monospace", "Courier, Computer Modern Typewriter")
        self.__setRCParam("text.usetex", True)

    # def useStandardFont(self):
    #     self.__setRCParam("font.family", "serif")
    #     self.__setRCParam("font.style", "normal")
    #     self.__setRCParam("font.variant", "normal")
    #     self.__setRCParam("font.weight", "normal")
    #     self.__setRCParam("font.stretch", "normal")

    def setAxesLabelSize(self, size):
        self.__setRCParam("axes.labelsize", size)

    def setXTickLabelSize(self, size):
        self.__setRCParam("xtick.labelsize", size)

    def setYTickLabelSize(self, size):
        self.__setRCParam("ytick.labelsize", size)

    def setLegendLabelSize(self, size):
        self.__setRCParam("legend.fontsize", size)

    def setWidth(self, width):
        self.width = int(width)

    def hasFigLegend(self, loc="best", columns=1, numcols=None):
        if numcols is not None:
            # hasLegend uses columns, rather than numcols.
            # trying to make this consistent.
            # this should catch named parameter usage
            columns = numcols
            warnings.warn("numcols deprecated for hasFigLegend", Warning)

        self.figLegendLoc = loc
        self.figLegendCols = numcols

    def addPlot(self, plot, grouping=None):
        if grouping == None:
            self.plots.append(plot)
        else:
            if grouping not in self.groupedPlots:
                self.groupedPlots[grouping] = []

            self.groupedPlots[grouping].append(plot)

    def setGroupOrder(self, groupOrder):
        self.groupOrder = groupOrder

    def setPlotDimensions(self, x, y):
        self.dimensions = (x,y)

    def setFigureDimensions(self, x, y):
        self.figdimensions = (x,y)

    def setPlotParameters(self, **kwdict):
        self.plotParams = dict(kwdict)

        if "left" not in self.plotParams:
            self.plotParams["left"] = 0.12

        if "bottom" not in self.plotParams:
            self.plotParams["bottom"] = 0.10

        if "right" not in self.plotParams:
            self.plotParams["right"] = 0.90

        if "top" not in self.plotParams:
            self.plotParams["top"] = 0.90

        if "wspace" not in self.plotParams:
            self.plotParams["wspace"] = 0.20

        if "hspace" not in self.plotParams:
            self.plotParams["hspace"] = 0.20

    def _doPlot(self):
        if len(self.groupedPlots) + len(self.plots) == 0:
            print "PlotLayout.plot(): No data to plot!"
            return

        if self.rcParams is not None:
            pylab.rcParams.update(self.rcParams)

        groupedPlotLengths = [len(plots) for plots in self.groupedPlots.values()]

        if len(groupedPlotLengths) == 0:
            maxRowLength = self.width
        else:
            maxRowLength = max(groupedPlotLengths)

        numPlots = len(self.plots)

        if numPlots == 0:
            numExcessRows = 0
        elif numPlots <= maxRowLength:
            numExcessRows = 1
        elif numPlots % maxRowLength == 0:
            numExcessRows = numPlots / maxRowLength
        else:
            numExcessRows = (numPlots / maxRowLength) + 1

        numRows = len(self.groupedPlots.keys()) + numExcessRows

        if self.groupOrder is not None:
            keyList = self.groupOrder
        else:
            keyList = self.groupedPlots.keys()

        currentRow = 0

        if self.figdimensions is not None:
            fig = pyplot.figure(figsize=(self.figdimensions[0],
                                         self.figdimensions[1]))
        elif self.dimensions is not None:
            fig = pyplot.figure(figsize=(self.dimensions[0] * maxRowLength,
                                         self.dimensions[1] * numRows))
        else:
            (figWidth, figHeight) = getGoldenRatioDimensions(8.0)
            figWidth *= maxRowLength
            figHeight *= numRows
            fig = pyplot.figure(figsize=(figWidth, figHeight))
            # figWidth = fig.get_figwidth()
            # print figWidth
            # print fig.get_figheight()
            # (goldenWidth, goldenHeight) = getGoldenRatioDimensions(figWidth)
            # fig.set_figheight(goldenHeight)
            # print fig.get_figheight()

        plotHandles = []
        plotLabels = []

        for grouping in keyList:
            currentColumn = 1
            plots = self.groupedPlots[grouping]

            numPlots = len(plots)

            for plot in plots:
                myRows = numRows
                myCols = numPlots
                myPos = (currentRow * numPlots) + currentColumn

                (currPlotHandles, currPlotLabels) = plot.subplot(
                    myRows, myCols, myPos)

                for i in xrange(len(currPlotHandles)):
                    if currPlotLabels[i] in plotLabels:
                        continue

                    if isinstance(currPlotHandles[i], list):
                        plotHandles.append(currPlotHandles[i][0])
                    else:
                        plotHandles.append(currPlotHandles[i])

                    plotLabels.append(currPlotLabels[i])

#                plotHandles.extend(currPlotHandles)
#                plotLabels.extend(currPlotLabels)

                currentColumn += 1
            currentRow += 1

        ungroupedPlotsRemaining = len(self.plots)
        if ungroupedPlotsRemaining > 0:
            currentColumn = 1

            for plot in self.plots:
                if currentColumn == 1:
                    numColumns = min(maxRowLength, ungroupedPlotsRemaining)

                myRows = numRows
                myCols = numColumns
                myPos = (currentRow * numColumns) + currentColumn

                (currPlotHandles, currPlotLabels) = plot.subplot(
                    myRows, myCols, myPos)
                for i in xrange(len(currPlotHandles)):
                    if currPlotLabels[i] in plotLabels:
                        continue

                    if isinstance(currPlotHandles[i], list):
                        plotHandles.append(currPlotHandles[i][0])
                    else:
                        plotHandles.append(currPlotHandles[i])

                    plotLabels.append(currPlotLabels[i])

                currentColumn += 1

                if currentColumn > numColumns:
                    currentRow += 1
                    currentColumn = 1

                ungroupedPlotsRemaining -= 1

        if self.figLegendLoc is not None:
            figLegendKeywords = {}

            if self.figLegendCols is not None:
                versionPieces = [int(x) for x in matplotlib.__version__.split('.')]

                (superMajor, major, minor) = versionPieces[0:3]

                if superMajor == 0 and major < 98:
                    print >>sys.stderr, "Number of columns support not available in versions of matplotlib prior to 0.98"
                else:
                    figLegendKeywords["ncol"] = self.figLegendCols

            pylab.figlegend(plotHandles, plotLabels,
                            self.figLegendLoc,
                            **figLegendKeywords)

        if self.plotParams is not None:
            pylab.subplots_adjust(left=self.plotParams["left"],
                                  bottom=self.plotParams["bottom"],
                                  right=self.plotParams["right"],
                                  top=self.plotParams["top"],
                                  wspace=self.plotParams["wspace"],
                                  hspace=self.plotParams["hspace"])

    def plot(self):
        self._doPlot()
        if not pylab.isinteractive():
            pylab.show()
        else:
            pylab.draw()

    def save(self, filename, **kwargs):
        print >>sys.stderr, "Saving %s ..." % filename

        tempDisplayHack = False

        if "DISPLAY" not in os.environ:
            tempDisplayHack = True
            os.environ["DISPLAY"] = ":0.0"
        self._doPlot()
        pylab.savefig(filename,**kwargs)
        pylab.clf()

        if tempDisplayHack == True:
            del os.environ["DISPLAY"]
<|endoftext|>


<commit_before>#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
Script to read out the TIScamera using python.
"""

from optparse import OptionParser
import sys
import os
import subprocess
import time
import matplotlib.pylab as plt

# Use Pythons Optionparser to define and read the options, and also
# give some help to the user
parser = OptionParser()
usage = "usage: %prog [options] arg1 arg2"
parser = OptionParser(usage=usage)
parser.add_option("-c", "--camera", dest="camera",
                  default="tis", type='str', metavar='name',
                  help="Camera to use; at the moment 'tis', 'aptina' and "
                       "'awaiba', even when the two latter options are not "
                       "implemented yet... (default: %default)")
parser.add_option("-e", "--exposure", dest="exposuretime",
                  metavar='125', type='float',
                  help="Exposure time [ms]")
parser.add_option("-f", "--framerate", dest="framerate",
                  metavar='30', type='int',
                  help="Framerate of the ffmpeg-process at the end")
parser.add_option("-i", "--images", dest="images",
                  default=5, type="int",
                  help="How many images should ffmpeg save at the end? "
                       "(default: %default)")
parser.add_option("-p", "--preview", dest="preview",
                  action="store_true", default=False,
                  help="Preview image (default: %default)")
parser.add_option("-s", "--suffix", dest="suffix",
                  type='str', metavar='Suffix',
                  help="Suffix to add after the foldername")
parser.add_option("-v", "--verbose", dest="verbose",
                  action="store_true", default=False,
                  help="Be chatty. (default: %default)")
(options, args) = parser.parse_args()

if len(sys.argv[1:]) == 0:
    print "You need to enter at least one option, here's the help"
    parser.print_help()
    sys.exit()

if not options.exposuretime:
    print 'You need to supply an exposure time we should use.'
    print 'Enter the command like so:'
    print '    ', ' '.join(sys.argv), "-e exposuretime"
    sys.exit()

print 80 * "-"
print "Hey ho, let's go!"

# Check at which /dev/video we have a camera
for device in range(5):
    if os.path.exists('/dev/video' + str(device)):
        CameraPath = '/dev/video' + str(device)
        if options.verbose:
            print 'Found a camera on', CameraPath
        break
    else:
        if options.verbose:
            print 'Nothing found at /dev/video' + str(device)

if options.verbose:
    print "We are trying to work with the '" + options.camera + "' camera"
    print
    print "Getting available sizes"

# Get available output sizes of the currently connected camera using v4l2-ctl
process = subprocess.Popen(['v4l2-ctl', '--device=' + CameraPath,
                            '--list-formats-ext'], stdout=subprocess.PIPE)
output, error = process.communicate()
width = []
height = []
for line in output.split("\n"):
    if line and line.split()[0].startswith("Size"):
        width.append(int(line.split()[2].split("x")[0]))
        height.append(int(line.split()[2].split("x")[1]))
for size in range(len(width)):
    if options.verbose:
        print "    *", width[size], "x", height[size], "px"
if options.camera == "tis":
    CMOSwidth = max(width)
    CMOSheight = max(height)
elif options.camera == 'aptina':
    CMOSwidth = 123
    CMOSheight = 456
elif options.camera == 'awaiba':
    CMOSwidth = 123
    CMOSheight = 456
print "We are using a", CMOSwidth, "x", CMOSheight, "px detector size to",\
    "proceed."

#~ Set exposure time
#~ According to http://goo.gl/D8MHsW and http://is.gd/zaxWn7, the exposure time
#~ is set in "100 µs units, where the value 1 stands for 1/10000th of a second,
#~ 10000 for 1 second [...]". The user sets the exposure time in ms (1000 µs)
#~ 1 s = 10⁶ µs = 10⁴ units -> 1000 ms = 10⁴ units. From ms to units -> * 10
if options.verbose:
    print 'The desired exposure time is', options.exposuretime, 'ms',
else:
    print 'Setting exposure time to', options.exposuretime, 'ms'
options.exposuretime = options.exposuretime * 10
if options.verbose:
    print '(corresponding to', int(options.exposuretime), '"100 µs units").'

if options.verbose:
    process = subprocess.Popen(['v4l2-ctl', '--device=' + CameraPath, '-L'],
                               stdout=subprocess.PIPE)
    output, error = process.communicate()
    for line in output.split("\n"):
        if line and line.split()[0].startswith("exp"):
            print "The camera was set from an exposure time of",\
                line.split("=")[-1], "units",

#~ Use 'v4l2-ctl -c exposure_absolute=time' to set exposure time
process = subprocess.Popen(["v4l2-ctl", '--device=' + CameraPath,
                            "-c", "exposure_absolute=" +
                            str(options.exposuretime)], stdout=subprocess.PIPE)
if options.verbose:
    process = subprocess.Popen(['v4l2-ctl', '--device=' + CameraPath, '-L'],
                               stdout=subprocess.PIPE)
    output, error = process.communicate()
    for line in output.split("\n"):
        if line and line.split()[0].startswith("exp"):
            print "to", line.split("=")[-1], "units."

# Construct a general NULL pointer, used for the subprocesses
DEVNULL = open(os.devnull, 'w')
# Show the stream if desired
if options.preview:
    # Setting preview to 720p, since bigger doesn't work with mplayer
    previewwidth = 1280
    previewheight = 720
    print "I'm now showing you a", previewwidth, "x", previewheight, "px",\
        "preview image from the upper left corner of the sensor."
    # mplayer command based on TIScamera page: http://is.gd/5mJEM7
    mplayercommand = "mplayer tv:// -tv width=" + str(previewwidth) +\
        ":device=" + CameraPath + " -geometry 50%:50% -title 'Previewing" +\
        " top left edge (" + str(previewwidth) + "x" + str(previewwidth) +\
        " px), with an exposure time of " + str(options.exposuretime / 10) +\
        " ms' -nosound"
    if options.verbose:
        print 'Previewing images with'
        print
        print mplayercommand
        print
    print "Exit with pressing the 'q' key!"
    subprocess.call(mplayercommand, stdout=DEVNULL, stderr=subprocess.STDOUT,
                    shell=True)

# Save output to a file, load that and display it.
# We save option.images images, since we often demand an image from the camera
# while it is in the middle of a circle, thus it's a corrupted image...

# Construct path
FileSavePath = os.path.join('Images', options.camera, str(int(time.time())))
if options.suffix:
    FileSavePath += '_' + str(options.suffix)
if options.exposuretime:
    # Go back from 100 us units to real time
    FileSavePath += '_' + str(options.exposuretime / 10) + 'ms'
if options.framerate:
    FileSavePath += '_' + str(options.framerate) + 'fps'
try:
    # Generating necessary directories
    os.makedirs(FileSavePath)
except:
    print FileSavePath, 'cannot be generated'
    sys.exit(1)

# Use ffmpeg to save video stream to lossless video, then extract single frames
# from this video
print "Getting", options.images, "images from the camera"
VideoTime = options.images * options.exposuretime
print 'Corresponding to', round(VideoTime), 'seconds of video'
# Command based on https://trac.ffmpeg.org/wiki/x264EncodingGuide#LosslessH.264
# ffmpeg -i input -c:v libx264 -preset ultrafast -qp 0 output.mkv
ffmpegcommand = "ffmpeg -f video4linux2 -s " + str(CMOSwidth) + "x" +\
    str(CMOSheight) + " -i " + CameraPath +  " -c:v libx264 -preset " +\
    "ultrafast -qp 0 output.mkv -t 10"
if options.verbose:
    print 'Saving images with'
    print
    print ffmpegcommand
    print
t0 = time.time()
subprocess.call(ffmpegcommand, stdout=DEVNULL, stderr=subprocess.STDOUT,
                shell=True)
t1 = time.time()
print "in", str(round(t1 - t0, 3)), "seconds (" +\
    str(round(options.images / (t1-t0), 3)) + " images per second)"

#~ filename = os.path.join(FileSavePath,
                        #~ "snapshot_%03d" % (int(round(options.images / 2.0))) +
                        #~ ".jpg")
#~
#~ image = plt.imread(filename)
#~ plt.imshow(image, origin="lower")
#~ figuretitle = "Snapshot", str(int(round(options.images / 2.0))), "of",\
    #~ str(options.images), "from", FileSavePath, "\nwith an exposure time of",\
    #~ str(options.exposuretime / 10), "ms",
#~ if options.preview:
    #~ plt.axhspan(ymin=CMOSheight-previewheight, ymax=CMOSheight,
                #~ xmin=0, xmax=float(previewwidth)/CMOSwidth,
                #~ facecolor='r', alpha=0.5)
    #~ plt.xlim([0, CMOSwidth])
    #~ plt.ylim([0, CMOSheight])
    #~ figuretitle += "\nred=preview area",
#~ plt.title(' '.join(figuretitle))
#~ plt.show()
#~
#~ print 'Images saved to',
#~ print os.path.abspath(os.path.join(FileSavePath, 'snapshot*.jpg'))

print 80 * "-"
print "done"
<commit_msg>ReadCamera updated to save lossless video<commit_after>#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
Script to read out the TIScamera using python.
"""

from optparse import OptionParser
import sys
import os
import shutil
import subprocess
import time
import matplotlib.pylab as plt

# Use Pythons Optionparser to define and read the options, and also
# give some help to the user
parser = OptionParser()
usage = "usage: %prog [options] arg1 arg2"
parser = OptionParser(usage=usage)
parser.add_option("-c", "--camera", dest="camera",
                  default="tis", type='str', metavar='name',
                  help="Camera to use; at the moment 'tis', 'aptina' and "
                       "'awaiba', even when the two latter options are not "
                       "implemented yet... (default: %default)")
parser.add_option("-e", "--exposure", dest="exposuretime",
                  metavar='125', type='float',
                  help="Exposure time [ms]")
parser.add_option("-p", "--preview", dest="preview",
                  action="store_true", default=False,
                  help="Preview image (default: %default)")
parser.add_option("-s", "--suffix", dest="suffix",
                  type='str', metavar='SomeSuffix',
                  help="Suffix to add after the foldername")
parser.add_option("-t", "--time", dest="videotime",
                  default=5, type="float", metavar=12.3,
                  help="How many seconds of video shall I record? "
                  "(default: %default)")
parser.add_option("-v", "--verbose", dest="verbose",
                  action="store_true", default=False,
                  help="Be chatty. (default: %default)")
(options, args) = parser.parse_args()

if len(sys.argv[1:]) == 0:
    print "You need to enter at least one option, here's the help"
    parser.print_help()
    sys.exit()

if not options.exposuretime:
    print 'You need to supply an exposure time we should use.'
    print 'Enter the command like so:'
    print '    ', ' '.join(sys.argv), "-e exposuretime"
    sys.exit()

print 80 * "-"
print "Hey ho, let's go!"

# Check at which /dev/video we have a camera
for device in range(5):
    if os.path.exists('/dev/video' + str(device)):
        CameraPath = '/dev/video' + str(device)
        if options.verbose:
            print 'Found a camera on', CameraPath
        break
    else:
        if options.verbose:
            print 'Nothing found at /dev/video' + str(device)

if options.verbose:
    print "We are trying to work with the '" + options.camera + "' camera"
    print
    print "Getting available sizes"

# Get available output sizes of the currently connected camera using v4l2-ctl
process = subprocess.Popen(['v4l2-ctl', '--device=' + CameraPath,
                            '--list-formats-ext'], stdout=subprocess.PIPE)
output, error = process.communicate()
width = []
height = []
for line in output.split("\n"):
    if line and line.split()[0].startswith("Size"):
        width.append(int(line.split()[2].split("x")[0]))
        height.append(int(line.split()[2].split("x")[1]))
for size in range(len(width)):
    if options.verbose:
        print "    *", width[size], "x", height[size], "px"
if options.camera == "tis":
    CMOSwidth = max(width)
    CMOSheight = max(height)
elif options.camera == 'aptina':
    CMOSwidth = 123
    CMOSheight = 456
elif options.camera == 'awaiba':
    CMOSwidth = 123
    CMOSheight = 456
print "We are using a", CMOSwidth, "x", CMOSheight, "px detector size to",\
    "proceed."

#~ Set exposure time
#~ According to http://goo.gl/D8MHsW and http://is.gd/zaxWn7, the exposure time
#~ is set in "100 µs units, where the value 1 stands for 1/10000th of a second,
#~ 10000 for 1 second [...]". The user sets the exposure time in ms (1000 µs)
#~ 1 s = 10⁶ µs = 10⁴ units -> 1000 ms = 10⁴ units. From ms to units -> * 10
if options.verbose:
    print 'The desired exposure time is', options.exposuretime, 'ms',
else:
    print 'Setting exposure time to', options.exposuretime, 'ms'
exposureunits = options.exposuretime * 10
if options.verbose:
    print '(corresponding to', int(exposureunits), '"100 µs units").'

if options.verbose:
    process = subprocess.Popen(['v4l2-ctl', '--device=' + CameraPath, '-L'],
                               stdout=subprocess.PIPE)
    output, error = process.communicate()
    for line in output.split("\n"):
        if line and line.split()[0].startswith("exp"):
            print "The camera was set from an exposure time of",\
                line.split("=")[-1], "units",

#~ Use 'v4l2-ctl -c exposure_absolute=time' to set exposure time
process = subprocess.Popen(["v4l2-ctl", '--device=' + CameraPath,
                            "-c", "exposure_absolute=" +
                            str(exposureunits)], stdout=subprocess.PIPE)
if options.verbose:
    process = subprocess.Popen(['v4l2-ctl', '--device=' + CameraPath, '-L'],
                               stdout=subprocess.PIPE)
    output, error = process.communicate()
    for line in output.split("\n"):
        if line and line.split()[0].startswith("exp"):
            print "to", line.split("=")[-1], "units."

# Construct a general NULL pointer, used for the subprocesses
DEVNULL = open(os.devnull, 'w')
# Show the stream if desired
if options.preview:
    # Setting preview to 720p, since bigger doesn't work with mplayer
    previewwidth = 1280
    previewheight = 720
    print "I'm now showing you a", previewwidth, "x", previewheight, "px",\
        "preview image from the upper left corner of the sensor."
    # mplayer command based on TIScamera page: http://is.gd/5mJEM7
    mplayercommand = "mplayer tv:// -tv width=" + str(previewwidth) +\
        ":device=" + CameraPath + " -geometry 50%:50% -title 'Previewing" +\
        " top left edge (" + str(previewwidth) + "x" + str(previewwidth) +\
        " px), with an exposure time of " + str(options.exposuretime) +\
        " ms' -nosound"
    if options.verbose:
        print 'Previewing images with'
        print
        print mplayercommand
        print
    print "Exit with pressing the 'q' key!"
    subprocess.call(mplayercommand, stdout=DEVNULL, stderr=subprocess.STDOUT,
                    shell=True)

# Save output to a file, load that and display it.
# We save option.images images, since we often demand an image from the camera
# while it is in the middle of a circle, thus it's a corrupted image...

# Construct path
FileSavePath = os.path.join('Images', options.camera, str(int(time.time())))
if options.suffix:
    FileSavePath += '_' + str(options.suffix)
if options.exposuretime:
    FileSavePath += '_' + str(options.exposuretime) + 'ms'
try:
    # Generating necessary directories
    os.makedirs(FileSavePath)
except:
    print FileSavePath, 'cannot be generated'
    sys.exit(1)

# Use ffmpeg to save video stream to lossless video, then extract single frames
# from this video
print 'Saving', options.videotime, 'seconds of video',
# Exposure time in ms -> theoretical FPS
TheoreticalFPS = 1000 / options.exposuretime
print 'with (theoretically)', round(TheoreticalFPS,2), 'fps'
if TheoreticalFPS > 7.5:
	print 'According to "v4l2-ctl --list-formats-ext" we can reach 7.5 fps max.'

# Command based on https://trac.ffmpeg.org/wiki/x264EncodingGuide#LosslessH.264
# ffmpeg -i input -c:v libx264 -preset ultrafast -qp 0 output.mkv
ffmpegcommand = "ffmpeg -y -f video4linux2 -s " + str(CMOSwidth) + "x" +\
    str(CMOSheight) + " -i " + CameraPath +  " -vcodec libx264 -preset " +\
    "ultrafast -qp 0 -t " + str(options.videotime) + " " + \
    os.path.join(FileSavePath,'video.mkv')

# -preset ultrafast -qp 0 -> lossless
# -t $time$ -> save $time$ seconds of video
# -y overwrite always
if options.verbose:
    print 'Recording video with'
    print 20 * '-'
    print ffmpegcommand
    print 20 * '-'
print 'Saving video now!'
print 'Please stand by for at least', int(round(options.videotime)),\
	'seconds...'
print 'Press the trigger while doing this!'
t0 = time.time()
subprocess.call(ffmpegcommand, stdout=DEVNULL, stderr=subprocess.STDOUT,
                shell=True)
t1 = time.time()
if t1 - t0 < options.videotime:
	print
	print 'It seems that I was saving faster than possible, the process',\
		'probably failed'
	print 'I am deleting',FileSavePath
	print
	print 'Please restart acquisition by repeating your last command.'
	shutil.rmtree(FileSavePath)
	sys.exit(1)
print "Recording and saving the video took me", str(round(t1 - t0, 2)),\
	"seconds"

# Converting above video to tiff-files
convertcommand = "ffmpeg -i " + os.path.join(FileSavePath,'video.mkv') +\
	" -pix_fmt gray " + os.path.join(FileSavePath,'frame_%05d.tif')
if options.verbose:
	print 'Converting video to images with'
	print 20 * '-'
	print convertcommand
	print 20 * '-'

print 'Converting the video into single frames'
t0 = time.time()
subprocess.call(convertcommand, stdout=DEVNULL, stderr=subprocess.STDOUT,
                shell=True)
t1 = time.time()
print "Converting the video took me", str(round(t1 - t0, 2)), "seconds"

# Save 'Log'-file
logfile = open(os.path.join(FileSavePath,'_log.txt'), "w")
logfile.write('The files in this directory were generated by this command:\n')
logfile.write(' '.join(sys.argv))
logfile.close()

print
print 'In the directory', FileSavePath, 'you now have'
print '    * a logfile (_log.txt)'
print '    * the raw video from the camera (video.mkv)'
# Count only certain files (http://stackoverflow.com/a/1321138)
NumberOfFrames = len([f for f in os.listdir(FileSavePath)
	if f.endswith('.tif') and os.path.isfile(os.path.join(FileSavePath, f))])
print '    * and', NumberOfFrames, 'frames of the video (frame*.tif), thus',\
	'a (calculated)', str(round(NumberOfFrames / options.videotime,2)), 'fps.'
print 'Have fun with this!'

print 80 * "-"
print "done"
<|endoftext|>


<commit_before>from lib.common import helpers

class Module:

    def __init__(self, mainMenu, params=[]):

        self.info = {
            'Name': 'Invoke-Netview',

            'Author': ['@harmj0y'],

            'Description': ('Queries the domain for all hosts, and retrieves open shares, '
                            'sessions, and logged on users for each host. Part of PowerView.'),

            'Background' : True,

            'OutputExtension' : None,

            'NeedsAdmin' : False,

            'OpsecSafe' : True,

            'MinPSVersion' : '2',

            'Comments': [
                'https://github.com/Veil-Framework/PowerTools/tree/master/PowerView',
                'https://github.com/mubix/netview'
            ]
        }

        # any options needed by the module, settable during runtime
        self.options = {
            # format:
            #   value_name : {description, required, default_value}
            'Agent' : {
                'Description'   :   'Agent to run module on.',
                'Required'      :   True,
                'Value'         :   ''
            },
            'Hosts' : {
                'Description'   :   'Hosts to enumerate.',
                'Required'      :   False,
                'Value'         :   ''
            },
            'HostList' : {
                'Description'   :   'Hostlist to enumerate.',
                'Required'      :   False,
                'Value'         :   ''
            },
            'HostFilter' : {
                'Description'   :   'Host filter name to query AD for, wildcards accepted.',
                'Required'      :   False,
                'Value'         :   ''
            },
            'NoPing' : {
                'Description'   :   'Don\'t ping each host to ensure it\'s up before enumerating.',
                'Required'      :   False,
                'Value'         :   ''
            },
            'CheckShareAccess' : {
                'Description'   :   'Switch. Only display found shares that the local user has access to.',
                'Required'      :   False,
                'Value'         :   ''
            },
            'Delay' : {
                'Description'   :   'Delay between enumerating hosts, defaults to 0.',
                'Required'      :   False,
                'Value'         :   ''
            },
            'Domain' : {
                'Description'   :   'Domain to enumerate for hosts.',
                'Required'      :   False,
                'Value'         :   ''
            }
        }

        # save off a copy of the mainMenu object to access external functionality
        #   like listeners/agent handlers/etc.
        self.mainMenu = mainMenu

        for param in params:
            # parameter format is [Name, Value]
            option, value = param
            if option in self.options:
                self.options[option]['Value'] = value

    def generate(self):

        # read in the common module source code
        moduleSource = self.mainMenu.installPath + "/data/module_source/situational_awareness/Network/Invoke-Netview.ps1"

        try:
            f = open(moduleSource, 'r')
        except:
            print helpers.color("[!] Could not read module source path at: " + str(moduleSource))
            return ""

        moduleCode = f.read()
        f.close()

        script = moduleCode

        script += "Invoke-NetView "

        for option,values in self.options.iteritems():
            if option.lower() != "agent":
                if values['Value'] and values['Value'] != '':
                    if values['Value'].lower() == "true":
                        # if we're just adding a switch
                        script += " -" + str(option)
                    else:
                        script += " -" + str(option) + " " + str(values['Value'])

        script += '| Out-String | %{$_ + \"`n\"};"`nInvoke-Netview completed"'

        return script<commit_msg>Update netview.py<commit_after>from lib.common import helpers

class Module:

    def __init__(self, mainMenu, params=[]):

        self.info = {
            'Name': 'Invoke-Netview',

            'Author': ['@harmj0y'],

            'Description': ('Queries the domain for all hosts, and retrieves open shares, '
                            'sessions, and logged on users for each host. Part of PowerView.'),

            'Background' : True,

            'OutputExtension' : None,

            'NeedsAdmin' : False,

            'OpsecSafe' : True,

            'MinPSVersion' : '2',

            'Comments': [
                'https://github.com/Veil-Framework/PowerTools/tree/master/PowerView',
                'https://github.com/mubix/netview'
            ]
        }

        # any options needed by the module, settable during runtime
        self.options = {
            # format:
            #   value_name : {description, required, default_value}
            'Agent' : {
                'Description'   :   'Agent to run module on.',
                'Required'      :   True,
                'Value'         :   ''
            },
            'Hosts' : {
                'Description'   :   'Hosts to enumerate.',
                'Required'      :   False,
                'Value'         :   ''
            },
            'HostList' : {
                'Description'   :   'Hostlist to enumerate.',
                'Required'      :   False,
                'Value'         :   ''
            },
            'HostFilter' : {
                'Description'   :   'Host filter name to query AD for, wildcards accepted.',
                'Required'      :   False,
                'Value'         :   ''
            },
            'NoPing' : {
                'Description'   :   'Don\'t ping each host to ensure it\'s up before enumerating.',
                'Required'      :   False,
                'Value'         :   ''
            },
            'CheckShareAccess' : {
                'Description'   :   'Switch. Only display found shares that the local user has access to.',
                'Required'      :   False,
                'Value'         :   ''
            },
            'Delay' : {
                'Description'   :   'Delay between enumerating hosts, defaults to 0.',
                'Required'      :   False,
                'Value'         :   ''
            },
            'Domain' : {
                'Description'   :   'Domain to enumerate for hosts.',
                'Required'      :   False,
                'Value'         :   ''
            }
        }

        # save off a copy of the mainMenu object to access external functionality
        #   like listeners/agent handlers/etc.
        self.mainMenu = mainMenu

        for param in params:
            # parameter format is [Name, Value]
            option, value = param
            if option in self.options:
                self.options[option]['Value'] = value

    def generate(self):

        # read in the common module source code
        moduleSource = self.mainMenu.installPath + "/data/module_source/situational_awareness/network/Invoke-Netview.ps1"

        try:
            f = open(moduleSource, 'r')
        except:
            print helpers.color("[!] Could not read module source path at: " + str(moduleSource))
            return ""

        moduleCode = f.read()
        f.close()

        script = moduleCode

        script += "Invoke-NetView "

        for option,values in self.options.iteritems():
            if option.lower() != "agent":
                if values['Value'] and values['Value'] != '':
                    if values['Value'].lower() == "true":
                        # if we're just adding a switch
                        script += " -" + str(option)
                    else:
                        script += " -" + str(option) + " " + str(values['Value'])

        script += '| Out-String | %{$_ + \"`n\"};"`nInvoke-Netview completed"'

        return script
<|endoftext|>


<commit_before>from marionette_driver import By
from marionette_driver.errors import MarionetteException

from marionette import MarionetteTestCase

import testsuite

class Test(MarionetteTestCase):

    def setUp(self):
        MarionetteTestCase.setUp(self)

        ts = testsuite.TestSuite()
        self.ts = ts

        # The torbutton_sec_* variables have been copy pasted from
        # torbutton/src/chrome/content/torbutton.js

        self.torbutton_sec_ml_bool_prefs = {
                "javascript.options.ion.content" : False,
                "javascript.options.typeinference" : False,
                "javascript.options.asmjs" : False,
                "noscript.forbidMedia" : True,
                "media.webaudio.enabled" : False,
                "mathml.disabled" : True
                }

        self.torbutton_sec_mh_bool_prefs = {
                "javascript.options.baselinejit.content" : False,
                "gfx.font_rendering.opentype_svg.enabled" : False,
                "noscript.global" : False,
                "noscript.globalHttpsWhitelist" : True
                }

        self.torbutton_sec_h_bool_prefs = {
                "noscript.forbidFonts" : True,
                "noscript.global" : False,
                "svg.in-content.enabled" : False
                };

    def test_slider_settings(self):
        with self.marionette.using_context('content'):
            self.marionette.navigate('about:robots')

            slider_mode = int(self.ts.t['test']['slider_mode'])
            self.assertEqual(slider_mode,
                self.marionette.get_pref('extensions.torbutton.security_slider'),
                msg='Slider mode is not set correctly')

            expected_prefs = {}

            if slider_mode == 1:
                for name, val in self.torbutton_sec_ml_bool_prefs.iteritems():
                        expected_prefs[name] = val
                for name, val in self.torbutton_sec_mh_bool_prefs.iteritems():
                        expected_prefs[name] = val
                        # noscript.globalHttpsWhitelist is special: We don't want it in this
                        # mode.
                        if name == "noscript.globalHttpsWhitelist":
                                expected_prefs[name] = not val
                for name, val in self.torbutton_sec_h_bool_prefs.iteritems():
                    expected_prefs[name] = val

            elif slider_mode == 2:
                for name, val in self.torbutton_sec_ml_bool_prefs.iteritems():
                    expected_prefs[name] = val
                # Order matters here as both the high mode and the medium-high mode
                # share some preferences/values. So, let's revert the high mode
                # preferences first and set the medium-high mode ones afterwards.
                for name, val in self.torbutton_sec_h_bool_prefs.iteritems():
                    expected_prefs[name] = not val
                for name, val in self.torbutton_sec_mh_bool_prefs.iteritems():
                    expected_prefs[name] = val

            elif slider_mode == 3:
                for name, val in self.torbutton_sec_ml_bool_prefs.iteritems():
                    expected_prefs[name] = val
                for name, val in self.torbutton_sec_mh_bool_prefs.iteritems():
                    expected_prefs[name] = not val
                for name, val in self.torbutton_sec_h_bool_prefs.iteritems():
                    expected_prefs[name] = not val

            elif slider_mode == 4:
                for name, val in self.torbutton_sec_ml_bool_prefs.iteritems():
                    expected_prefs[name] = not val
                for name, val in self.torbutton_sec_mh_bool_prefs.iteritems():
                    expected_prefs[name] = not val
                for name, val in self.torbutton_sec_h_bool_prefs.iteritems():
                    expected_prefs[name] = not val

            errors = ''
            for name, val in expected_prefs.iteritems():
                if self.marionette.get_pref(name) != val:
                    errors += "%s: %s != %s\n" % (name, self.marionette.get_pref(name), val)

            self.assertEqual(errors, '', msg=errors)
<commit_msg>Bug 19417: remove asmjs from slider settings tests<commit_after>from marionette_driver import By
from marionette_driver.errors import MarionetteException

from marionette import MarionetteTestCase

import testsuite

class Test(MarionetteTestCase):

    def setUp(self):
        MarionetteTestCase.setUp(self)

        ts = testsuite.TestSuite()
        self.ts = ts

        # The torbutton_sec_* variables have been copy pasted from
        # torbutton/src/chrome/content/torbutton.js

        self.torbutton_sec_ml_bool_prefs = {
                "javascript.options.ion.content" : False,
                "javascript.options.typeinference" : False,
                "noscript.forbidMedia" : True,
                "media.webaudio.enabled" : False,
                "mathml.disabled" : True
                }

        self.torbutton_sec_mh_bool_prefs = {
                "javascript.options.baselinejit.content" : False,
                "gfx.font_rendering.opentype_svg.enabled" : False,
                "noscript.global" : False,
                "noscript.globalHttpsWhitelist" : True
                }

        self.torbutton_sec_h_bool_prefs = {
                "noscript.forbidFonts" : True,
                "noscript.global" : False,
                "svg.in-content.enabled" : False
                };

    def test_slider_settings(self):
        with self.marionette.using_context('content'):
            self.marionette.navigate('about:robots')

            slider_mode = int(self.ts.t['test']['slider_mode'])
            self.assertEqual(slider_mode,
                self.marionette.get_pref('extensions.torbutton.security_slider'),
                msg='Slider mode is not set correctly')

            expected_prefs = {}

            if slider_mode == 1:
                for name, val in self.torbutton_sec_ml_bool_prefs.iteritems():
                        expected_prefs[name] = val
                for name, val in self.torbutton_sec_mh_bool_prefs.iteritems():
                        expected_prefs[name] = val
                        # noscript.globalHttpsWhitelist is special: We don't want it in this
                        # mode.
                        if name == "noscript.globalHttpsWhitelist":
                                expected_prefs[name] = not val
                for name, val in self.torbutton_sec_h_bool_prefs.iteritems():
                    expected_prefs[name] = val

            elif slider_mode == 2:
                for name, val in self.torbutton_sec_ml_bool_prefs.iteritems():
                    expected_prefs[name] = val
                # Order matters here as both the high mode and the medium-high mode
                # share some preferences/values. So, let's revert the high mode
                # preferences first and set the medium-high mode ones afterwards.
                for name, val in self.torbutton_sec_h_bool_prefs.iteritems():
                    expected_prefs[name] = not val
                for name, val in self.torbutton_sec_mh_bool_prefs.iteritems():
                    expected_prefs[name] = val

            elif slider_mode == 3:
                for name, val in self.torbutton_sec_ml_bool_prefs.iteritems():
                    expected_prefs[name] = val
                for name, val in self.torbutton_sec_mh_bool_prefs.iteritems():
                    expected_prefs[name] = not val
                for name, val in self.torbutton_sec_h_bool_prefs.iteritems():
                    expected_prefs[name] = not val

            elif slider_mode == 4:
                for name, val in self.torbutton_sec_ml_bool_prefs.iteritems():
                    expected_prefs[name] = not val
                for name, val in self.torbutton_sec_mh_bool_prefs.iteritems():
                    expected_prefs[name] = not val
                for name, val in self.torbutton_sec_h_bool_prefs.iteritems():
                    expected_prefs[name] = not val

            errors = ''
            for name, val in expected_prefs.iteritems():
                if self.marionette.get_pref(name) != val:
                    errors += "%s: %s != %s\n" % (name, self.marionette.get_pref(name), val)

            self.assertEqual(errors, '', msg=errors)
<|endoftext|>