Exemple #1
0
class EthernetTransport(DeviceTransport):
    config = Instance(EthernetConfig, ()).tag(config=True)
    connection = Instance(socket.socket)

    #: Whether a serial connection spools depends on the device (configuration)
    always_spools = set_default(False)

    def connect(self):
        print("SeroIP connected")
        print(self.config.ip)
        print(self.config.port)
        self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.connection.connect((self.config.ip, int(self.config.port)))
        self.connected = True

    def write(self, data):
        print("SeroIP printing " + data)
        self.connection.send(data.encode())

    def disconnect(self):
        print("SeroIP disconnected")
        self.connection.close()
        self.connected = False

        # if self.connection:
        #     self.connection.close()

    def repr(self):
        return self.config
Exemple #2
0
class Measurement(LogicalChannel):
    '''
    A class for measurement channels.
    Measurements are special because they can be different types:
    autodyne which needs an IQ pair or hetero/homodyne which needs just a marker channel.
    '''
    meas_type = Enum(
        'autodyne',
        'homodyne').tag(desc='Type of measurement (autodyne, homodyne)')

    autodyne_freq = Float(0.0).tag(
        desc=
        'use to bake the modulation into the pulse, so that it has constant phase'
    )
    frequency = Float(0.0).tag(
        desc='use frequency to asssociate modulation with the channel')
    pulse_params = Dict(
        default={
            'length': 100e-9,
            'amp': 1.0,
            'shape_fun': PulseShapes.tanh,
            'cutoff': 2,
            'sigma': 1e-9
        })
    gate_chan = Instance((str, LogicalMarkerChannel))
    trig_chan = Instance((str, LogicalMarkerChannel))
    receiver_chan = Instance((str, ReceiverChannel))

    def __init__(self, **kwargs):
        super(Measurement, self).__init__(**kwargs)
        if self.trig_chan is None:
            self.trig_chan = LogicalMarkerChannel(label='digitizerTrig')
Exemple #3
0
class SerialTransport(DeviceTransport):

    #: Default config
    config = Instance(SerialConfig, ())

    #: Connection port
    connection = Instance(SerialPort)

    #: Whether a serial connection spools depends on the device (configuration)
    always_spools = set_default(False)

    #: Wrapper
    _protocol = Instance(InkcutProtocol)

    def connect(self):
        try:
            config = self.config

            #: Save a reference
            self.protocol.transport = self

            #: Make the wrapper
            self._protocol = InkcutProtocol(self, self.protocol)

            self.connection = SerialPort(
                self._protocol,
                config.port,
                reactor,
                baudrate=config.baudrate,
                bytesize=config.bytesize,
                parity=SERIAL_PARITIES[config.parity],
                stopbits=config.stopbits,
                xonxoff=config.xonxoff,
                rtscts=config.rtscts
            )
            log.debug("{} | opened".format(self.config.port))
        except Exception as e:
            #: Make sure to log any issues as these tracebacks can get
            #: squashed by twisted
            log.error("{} | {}".format(
                self.config.port, traceback.format_exc()
            ))
            raise

    def write(self, data):
        if not self.connection:
            raise IOError("Port is not opened")
        log.debug("-> {} | {}".format(self.config.port, data))
        if hasattr(data, 'encode'):
            data = data.encode()
        self._protocol.transport.write(data)

    def disconnect(self):
        if self.connection:
            log.debug("{} | closed".format(self.config.port))
            self.connection.loseConnection()
            self.connection = None

    def __repr__(self):
        return self.config.port
Exemple #4
0
class AbstractQtWidgetItem(AbstractQtWidgetItemGroup, ProxyAbstractWidgetItem):
    #:
    is_destroyed = Bool()

    #: Index within the view
    index = Instance(QModelIndex)

    #: Delegate widget to display when editing the cell
    #: if the widget is editable
    delegate = Instance(QtWidget)

    #: Reference to view
    view = ForwardInstance(_abstract_item_view)

    def create_widget(self):
        # View items have no widget!
        for child in self.children():
            if isinstance(child, (Pattern, QtWidget)):
                self.delegate = child

    def init_widget(self):
        pass

    def init_layout(self):
        super(AbstractQtWidgetItem, self).init_layout()
        self._update_index()

    def _update_index(self):
        """ Update where this item is within the model"""
        raise NotImplementedError

    def destroy(self):
        """ Set the flag so we know when this item is destroyed """
        self.is_destroyed = True
        super(AbstractQtWidgetItem, self).destroy()
class CalendarView(FrameLayout):
    """ CalendarView is a view group that displays
    child views in relative positions.

    """
    #: Selected date
    date = d_(Instance(datetime))

    #: Max date
    max_date = d_(Instance(datetime))

    #: Min date
    min_date = d_(Instance(datetime))

    #: First day of week
    first_day_of_week = d_(Range(1, 7))

    #: A reference to the ProxyLabel object.
    proxy = Typed(ProxyCalendarView)

    # -------------------------------------------------------------------------
    # Observers
    # -------------------------------------------------------------------------
    @observe('date', 'max_date', 'min_date', 'first_day_of_week')
    def _update_proxy(self, change):
        """ An observer which sends the state change to the proxy.

        """
        # The superclass implementation is sufficient.
        super(CalendarView, self)._update_proxy(change)
Exemple #6
0
class DatePicker(FrameLayout):
    """A simple control for displaying read-only text."""

    #: Update the current year.
    date = d_(Instance(datetime, factory=datetime.now))

    #: Sets the minimal date supported by this DatePicker in milliseconds
    #: since January 1, 1970 00:00:00 in getDefault() time zone.
    min_date = d_(Instance(datetime, factory=datetime.now))

    #: Sets the maximal date supported by this DatePicker in milliseconds
    #: since January 1, 1970 00:00:00 in getDefault() time zone.
    max_date = d_(Instance(datetime, factory=datetime.now))

    #: Sets the first day of week.
    first_day_of_week = d_(Range(1, 7))

    #: A reference to the ProxyLabel object.
    proxy = Typed(ProxyDatePicker)

    # -------------------------------------------------------------------------
    # Observers
    # -------------------------------------------------------------------------
    @observe("date", "min_date", "max_date", "first_day_of_week")
    def _update_proxy(self, change):

        super()._update_proxy(change)
Exemple #7
0
class CalendarView(FrameLayout):
    """CalendarView is a view group that displays
    child views in relative positions.

    """

    #: Selected date
    date = d_(Instance(datetime, factory=datetime.now))

    #: Max date
    max_date = d_(Instance(datetime, factory=datetime.now))

    #: Min date
    min_date = d_(Instance(datetime, factory=datetime.now))

    #: First day of week
    first_day_of_week = d_(Range(1, 7))

    #: A reference to the ProxyLabel object.
    proxy = Typed(ProxyCalendarView)

    # -------------------------------------------------------------------------
    # Observers
    # -------------------------------------------------------------------------
    @observe("date", "max_date", "min_date", "first_day_of_week")
    def _update_proxy(self, change):

        super()._update_proxy(change)
Exemple #8
0
class CodeComponent(RawComponent, ProxyCode):
    #: Lexer used
    lexer = Instance(Lexer)

    #: HTML Formatter
    formatter = Instance(HtmlFormatter)

    def _default_formatter(self):
        return HtmlFormatter(style=self.declaration.highlight_style)

    def _default_lexer(self):
        d = self.declaration
        if d.language:
            return lexers.find_lexer_class_by_name(d.language)()
        return lexers.guess_lexer(d.source)

    def set_source(self, source):
        super(CodeComponent, self).set_source(
            highlight(source, lexer=self.lexer, formatter=self.formatter))

    def set_language(self, language):
        self.lexer = self._default_lexer()
        self.set_source(self.declaration.source)

    def set_highlight_style(self, style):
        self.formatter = self._default_formatter()
        self.set_source(self.declaration.source)
Exemple #9
0
class Comment(SQLModel):
    page = Instance(Page)
    author = Instance(User)
    status = Enum("pending", "approved")
    body = Str().tag(type=sa.UnicodeText())
    reply_to = ForwardInstance(lambda: Comment).tag(nullable=True)
    when = Instance(time)
Exemple #10
0
class Bookmark(Atom):
    #: Name of it
    name = Unicode()

    #: Bible
    bible = ForwardInstance(lambda: Bible)

    #: Book
    book = Instance(Book)

    #: Chapter
    chapter = Instance(Chapter)

    #: Verse
    #verse = Instance(Verse)

    #: Save / load state
    state = Dict()

    def __init__(self, *args, **kwargs):
        super(Bookmark, self).__init__(*args, **kwargs)
        if kwargs.get('state') is None:
            #: If we're not loading from state
            self.state = {
                'bible': self.bible.version.key,
                'book': self.book.name,
                'chapter': self.chapter.number,
                #'verse': self.verse.number
            }

    def _default_name(self):
        return u"{} {}".format(self.book.name, self.chapter.number)

    def _default_bible(self):
        try:
            #: Prevent loading two bibles if it was bookmarked in a different bible
            bible = AppState.instance().bible
            if bible is not None:
                return bible
            return AppState.instance().get_bible(self.state['bible'])
        except KeyError:
            return None

    def _default_book(self):
        if not self.bible:
            return None
        try:
            return self.bible.get_book(self.state['book'])
        except KeyError:
            return None

    def _default_chapter(self):
        if not self.book:
            return None
        try:
            #: They're supposed to be in order
            return self.book.chapters[self.state['chapter'] - 1]
        except KeyError:
            return None
Exemple #11
0
class OccSvg(OccShape, ProxySvg):
    #: Update the class reference
    reference = set_default('https://dev.opencascade.org/doc/refman/html/'
                            'class_b_rep_builder_a_p_i___make_wire.html')

    #: Make wire
    shape = Instance(TopoDS_Shape)

    #: The document
    doc = Instance(OccSvgDoc)

    def create_shape(self):
        d = self.declaration
        if not d.source:
            return
        if os.path.exists(os.path.expanduser(d.source)):
            svg = etree.parse(os.path.expanduser(d.source)).getroot()
        else:
            svg = etree.fromstring(d.source)
        node = self.doc = OccSvgDoc(element=svg)
        viewbox = svg.attrib.get('viewBox')
        x, y = (0, 0)
        sx, sy = (1, 1)
        if viewbox:
            ow = parse_unit(svg.attrib.get('width'))
            oh = parse_unit(svg.attrib.get('height'))
            x, y, iw, ih = map(parse_unit, viewbox.split())
            sx = ow / iw
            sy = oh / ih

        builder = BRep_Builder()
        shape = TopoDS_Compound()
        builder.MakeCompound(shape)

        shapes = node.create_shape()
        for s in shapes:
            builder.Add(shape, s)

        bbox = self.get_bounding_box(shape)

        # Move to position and align along direction axis
        t = self.get_transform()
        if d.mirror:
            m = gp_Trsf()
            m.SetMirror(gp_Ax2(gp_Pnt(*bbox.center), gp_Dir(0, 1, 0)))
            t.Multiply(m)

        # Apply viewport scale
        s = gp_Trsf()
        s.SetValues(sx, 0, 0, x, 0, sy, 0, y, 0, 0, 1, 0)
        t.Multiply(s)

        self.shape = BRepBuilderAPI_Transform(shape, t, False).Shape()

    def set_source(self, source):
        self.create_shape()

    def set_mirror(self, mirror):
        self.create_shape()
Exemple #12
0
class MatPlot(Atom):
    """
    Overall class for matplotlib figure. can have several child axes instances.

    allow slider and next/prev buttons, interactive fitting?
    """

    fig = Typed(Figure)
    _axes = Instance(subplot_class_factory(), np.ndarray)
    axes = Instance(AtomAxes, np.ndarray)

    def __init__(self,
                 nrows=1,
                 ncols=1,
                 sharex=False,
                 sharey=False,
                 squeeze=True,
                 subplot_kw=None,
                 gridspec_kw=None,
                 **fig_kw):
        super(MatPlot, self).__init__()

        self.fig, self._axes = plt.subplots(nrows=1,
                                            ncols=1,
                                            sharex=sharex,
                                            sharey=sharey,
                                            squeeze=squeeze,
                                            subplot_kw=subplot_kw,
                                            gridspec_kw=gridspec_kw,
                                            **fig_kw)

        if isinstance(self._axes, np.ndarray):
            self.axes = np.array([AtomAxes(self, ax)
                                  for ax in self._axes]).reshape(nrows, ncols)
        else:
            self.axes = AtomAxes(self, self._axes)

    def __iadd__(self, other):
        if isinstance(self.axes, AtomAxes):
            self.axes.add_dataobject(other)
        else:
            raise ValueError(
                'Please add the DataObject to the appropriate axes')
        return self

    def __isub__(self, other):
        if isinstance(self.axes, AtomAxes):
            self.axes.remove_dataobject(other)
        else:
            raise ValueError(
                'Please add the DataObject to the appropriate axes')

    @staticmethod
    def show(*args, **kwargs):
        plt.show(*args, **kwargs)

    @staticmethod
    def savefig(*args, **kwargs):
        plt.savefig(*args, **kwargs)
Exemple #13
0
class AreaBase(Model):
    #: Size (in px)
    size = ContainerList(Float(), default=[1800, 2700]).tag(config=True)

    # Left, Top, Right, Bottom (in px)
    padding = ContainerList(Float(), default=[10, 10, 10, 10]).tag(config=True)

    area = Instance(QtCore.QRectF)
    path = Instance(QtGui.QPainterPath)
    padding_path = Instance(QtGui.QPainterPath)

    def _default_area(self):
        return QtCore.QRectF(0, 0, self.size[0], self.size[1])

    def _default_path(self):
        p = QtGui.QPainterPath()
        p.addRect(self.area)
        return p

    def _default_padding_path(self):
        p = QtGui.QPainterPath()
        p.addRect(self.available_area)
        return p

    @observe('size', 'padding')
    def _sync_size(self, change):
        self.area.setWidth(self.size[0])
        self.area.setHeight(self.size[1])
        self.path = self._default_path()
        self.padding_path = self._default_padding_path()

    @property
    def padding_left(self):
        return self.padding[0]

    @property
    def padding_top(self):
        return self.padding[1]

    @property
    def padding_right(self):
        return self.padding[2]

    @property
    def padding_bottom(self):
        return self.padding[3]

    def width(self):
        return self.size[0]

    def height(self):
        return self.size[1]

    @property
    def available_area(self):
        x, y = self.padding_left, self.padding_bottom
        w, h = (self.size[0] - (self.padding_right + self.padding_left),
                self.size[1] - (self.padding_bottom + self.padding_top))
        return QtCore.QRectF(x, y, w, h)
Exemple #14
0
class PageImage(SQLModel):
    # Example through table for job role
    page = Instance(Page).tag(nullable=False)
    image = Instance(Page).tag(nullable=False)

    class Meta:
        db_table = "page_image_m2m"
        unique_together = ("page", "image")
Exemple #15
0
class OccPipe(OccOperation, ProxyPipe):
    reference = set_default('https://dev.opencascade.org/doc/refman/html/'
                            'class_b_rep_offset_a_p_i___make_pipe.html')

    #: References to observed shapes
    _old_spline = Instance(OccShape)
    _old_profile = Instance(OccShape)

    fill_modes = Dict(
        default={
            'corrected_frenet': GeomFill_IsCorrectedFrenet,
            'fixed': GeomFill_IsFixed,
            'frenet': GeomFill_IsFrenet,
            'constant_normal': GeomFill_IsConstantNormal,
            'darboux': GeomFill_IsDarboux,
            'guide_ac': GeomFill_IsGuideAC,
            'guide_plan': GeomFill_IsGuidePlan,
            'guide_ac_contact': GeomFill_IsGuideACWithContact,
            'guide_plan_contact': GeomFill_IsGuidePlanWithContact,
            'discrete_trihedron': GeomFill_IsDiscreteTrihedron
        })

    def update_shape(self, change=None):
        d = self.declaration

        if d.spline and d.profile:
            spline, profile = d.spline, d.profile
        elif d.spline:
            spline = d.spline
            profile = self.get_first_child().shape
        elif d.profile:
            profile = d.profile
            spline = self.get_first_child().shape
        else:
            shapes = [
                c.shape for c in self.children() if isinstance(c, OccShape)
            ]
            spline, profile = shapes[0:2]

        args = [coerce_shape(spline), coerce_shape(profile)]

        # Make sure spline is a wire
        if isinstance(args[0], TopoDS_Edge):
            args[0] = BRepBuilderAPI_MakeWire(args[0]).Wire()

        if d.fill_mode:
            args.append(self.fill_modes[d.fill_mode])
        pipe = BRepOffsetAPI_MakePipe(*args)
        self.shape = pipe.Shape()

    def set_spline(self, spline):
        self.update_shape()

    def set_profile(self, profile):
        self.update_shape()

    def set_fill_mode(self, mode):
        self.update_shape()
Exemple #16
0
class ViewerSelection(Atom):
    #: Selected shape or shapes
    selection = Dict()

    #: Selection position, may be None
    position = Instance(tuple)

    #: Selection area, may be None
    area = Instance(tuple)
Exemple #17
0
class UserSettings(Model):
    PasswordMode = BInt()
    Email = Instance(Email)
    News = Int()
    Locale = Str()
    LogAuth = BInt()
    InvoiceText = Str()
    TwoFactor = BInt()
    Phone = Instance(Phone)
class AndroidDataSet(AndroidToolkitObject, ProxyDataSet):

    #: Holds the data
    data = Instance(EntryList)

    #: Holds settings and such for the data
    data_set = Instance(DataSet)

    def create_widget(self):
        self.data = EntryList()
        self.data.entry_factory = self.parent().entry_factory

    def init_widget(self):
        super(AndroidDataSet, self).init_widget()
        d = self.declaration
        if d.data:
            self.set_data(d.data)

        #: Let the parent choose the type
        chart = self.parent()
        chart.make_data_set(self)

        #: Now update the data set
        if d.colors:
            self.set_colors(d.colors)
        if d.text_color:
            self.set_text_color(d.text_color)
        #: Text is set when the data set is created
        if d.show_icons is not None:
            self.set_show_icons(d.show_icons)

    # --------------------------------------------------------------------------
    # DataSet API
    # --------------------------------------------------------------------------
    def set_data(self, data):
        self.data.refresh_data(data)

    def update_data(self, change):
        self.data.handle_change(change)
        self.parent().handle_data_set_change(change)

    def set_colors(self, colors):
        if isinstance(colors, list):
            self.data_set.setColors(colors)
        else:
            self.data_set.setColor(colors)

    def set_text(self, text):
        self.data_set.setLabel(text)

    def set_text_color(self, color):
        self.data_set.setValueTextColor(color)

    def set_show_icons(self, show):
        self.data_set.setDrawIcons(show)
Exemple #19
0
class BooleanOperation(Operation):
    shape1 = d_(Instance(object))

    shape2 = d_(Instance(object))

    #: Optional pave filler
    pave_filler = d_(Instance(object))  #BOPAlgo_PaveFiller))

    @observe('shape1', 'shape2', 'pave_filler')
    def _update_proxy(self, change):
        super(BooleanOperation, self)._update_proxy(change)
Exemple #20
0
class FileTransport(DeviceTransport):

    #: Default config
    config = Instance(FileConfig, ()).tag(config=True)

    #: The OS spools file writes
    always_spools = set_default(True)

    #: The output buffer
    file = Instance(object)

    #: Current path
    path = Unicode()

    def _default_path(self):
        config = self.config
        params = dict(time=str(time.time()).split(".")[0],
                      protocol=str(self.protocol.declaration.id).lower())
        return join(config.directory, config.format.format(**params))

    def connect(self):
        config = self.config
        path = self.path = self._default_path()
        if not exists(config.directory):
            os.makedirs(config.directory)
        log.debug("-- File | Writing to '{}'".format(path))
        self.file = open(path, 'wb')
        self.connected = True
        #: Save a reference
        self.protocol.transport = self
        self.protocol.connection_made()

    def write(self, data):
        log.debug("-> File | {}".format(data))

        #: Python 3 is annoying
        if hasattr(data, 'encode'):
            data = data.encode()

        self.file.write(data)

    def read(self, size=None):
        return ""

    def disconnect(self):
        log.debug("-- File | Closed '{}'".format(self.path))
        self.connected = False
        self.protocol.connection_lost()
        if self.file:
            self.file.close()
            self.file = None

    def __repr__(self):
        return self.path
Exemple #21
0
class PrinterTransport(DeviceTransport):

    #: Default config
    config = Instance(PrinterConfig).tag(config=True)

    #: Delegate to the implementation based on the current platform
    connection = Instance(PrinterConnection)

    #: The OS printing subsystem will take care of spooling
    always_spools = set_default(True)

    def _default_config(self):
        if sys.platform == 'win32':
            return Win32PrinterConfig()
        else:
            return CupsPrinterConfig()

    def _default_connection(self):
        if sys.platform == 'win32':
            return Win32PrinterConnection()
        else:
            return LPRPrinterConnection()

    def connect(self):
        try:
            # Always create a new connection
            self.connection = self._default_connection()

            # Save a reference
            self.protocol.transport = self
            self.connection.transport = self
            self.connection.open()
            log.debug("{} | opened".format(self.config.printer))
        except Exception as e:
            # Make sure to log any issues as these tracebacks can get
            # squashed by twisted
            log.error("{} | {}".format(
                self.config.printer, traceback.format_exc()
            ))
            raise

    def write(self, data):
        if not self.connection:
            raise IOError("Port is not opened")
        self.connection.write(data)

    def disconnect(self):
        if self.connection:
            self.connection.close()
            log.debug("{} | closed".format(self.config.printer))
            self.connection = None

    def __repr__(self):
        return self.config.printer
Exemple #22
0
class Tweet(SQLModel):

    id = Typed(int).tag(type=sa.BigInteger(), primary_key=True)
    text = Unicode()
    retweet = Bool(False)
    created_at = Instance(datetime)
    user = Instance(User).tag(nullable=False)
    coin = Unicode(default='')

    class Meta:
        db_table = 'tweet'
Exemple #23
0
class AbstractRibSlot(Operation):
    #: Base shape
    shape = d_(Instance(Shape))

    #: Profile to make the pipe from
    contour = d_(Instance(Shape))

    #: Profile to make the pipe from
    plane = d_(Instance(Shape))

    #: Fuse (False to remove, True to add)
    fuse = d_(Bool(False)).tag(view=True)
Exemple #24
0
class RawFdTransport(DeviceTransport):

    #: Default config
    config = Instance(RawFdConfig, ()).tag(config=True)

    #: The device handles
    fd = Value()

    #: Current path
    device_path = Unicode()

    #: Wrapper
    _protocol = Instance(RawFdProtocol)

    #: A raw device connection
    connection = Instance(stdio.StandardIO)

    def connect(self):
        config = self.config
        device_path = self.device_path = config.device_path
        if 'win32' in sys.platform:
            # Well, technically it works, but only with stdin and stdout
            raise OSError("Raw device support cannot be used on Windows")

        try:
            self.fd = open(device_path, config.mode)
            fd = self.fd.fileno()
            log.debug("-- {} | opened".format(device_path))
            self._protocol = RawFdProtocol(self, self.protocol)
            self.connection = stdio.StandardIO(self._protocol, fd, fd)
        except Exception as e:
            #: Make sure to log any issues as these tracebacks can get
            #: squashed by twisted
            log.error("{} | {}".format(device_path, traceback.format_exc()))
            raise

    def write(self, data):
        if not self.connection:
            raise IOError("{} is not opened".format(self.device_path))
        log.debug("-> {} | {}".format(self.device_path, data))
        if hasattr(data, 'encode'):
            data = data.encode()
        self.last_write = data
        self.connection.write(data)

    def disconnect(self):
        if self.connection:
            log.debug("-- {} | closed by request".format(self.device_path))
            self.connection.loseConnection()
            self.connection = None

    def __repr__(self):
        return self.device_path
Exemple #25
0
class Image(SQLModel):
    name = Str().tag(length=100)
    path = Str().tag(length=200)
    metadata = Typed(dict).tag(nullable=True)
    alpha = Range(low=0, high=255)
    data = Instance(bytes).tag(nullable=True)

    # Maps to sa.ARRAY, must include the item_type tag
    # size = Tuple(int).tag(nullable=True)

    #: Maps to sa.JSON
    info = Instance(ImageInfo, ())
Exemple #26
0
class EventsResponse(Response):
    """ Expected response from api/events/<id> """
    EventID = Str()
    Refresh = BInt()
    More = BInt()
    Notices = List(Notice)
    UsedSpace = Int()
    Messages = List(MessageEvent)
    MessageCounts = List(UnreadCount)
    ConversationCounts = List(UnreadCount)
    Conversations = List(ConversationEvent)
    Total = Instance(EventsResult)
    Unread = Instance(EventsResult)
Exemple #27
0
class PreviewPlugin(Plugin):

    #: Set's the plot that is drawn in the preview
    preview = Instance(PreviewModel, ())

    #: Plot for showing live status
    live_preview = Instance(PreviewModel, ())

    #: Transform applied to all view items
    transform = Instance(QtGui.QTransform)

    def _default_transform(self):
        """ Qt displays top to bottom so this can be used to flip it. 
        
        """
        return QtGui.QTransform.fromScale(1, -1)

    def set_preview(self, *items):
        """ Sets the items that will be displayed in the plot
        
        Parameters
        ----------
        items: list of kwargs
            A list of kwargs to to pass to each plot item 

        """
        t = self.transform
        view_items = [
            PainterPathPlotItem(kwargs.pop('path'), **kwargs)
            for kwargs in items
        ]
        self.preview.plot = view_items

    def set_live_preview(self, *items):
        """ Set the items that will be displayed in the live plot preview.
        After set, use live_preview.update(position) to update it.
        
        Parameters
        ----------
        items: list of kwargs
            A list of kwargs to to pass to each plot item 

        
        """
        view_items = [
            PainterPathPlotItem(kwargs.pop('path'), **kwargs)
            for kwargs in items
        ]
        self.live_preview.init(view_items)
Exemple #28
0
class AbstractGraphicsShapeItem(GraphicsItem):
    """A common base for all path items."""

    #: Proxy reference
    proxy = Typed(ProxyAbstractGraphicsShapeItem)

    #: Set the pen or "line" style.
    pen = d_(Instance(Pen))

    #: Set the brush or "fill" style.
    brush = d_(Instance(Brush))

    @observe("pen", "brush")
    def _update_proxy(self, change):
        super(AbstractGraphicsShapeItem, self)._update_proxy(change)
Exemple #29
0
class NoSQLModel(Model):
    """ An atom model that can be serialized and deserialized to and from 
    MongoDB.
    
    """

    #: ID of this object in the database
    _id = Instance(bson.ObjectId)

    #: Handles encoding and decoding
    serializer = NoSQLModelSerializer.instance()

    #: Handles database access
    objects = NoSQLModelManager.instance()

    async def save(self):
        """ Alias to delete this object to the database """
        db = self.objects
        state = self.__getstate__()
        if self._id is not None:
            return await db.replace_one({'_id': self._id}, state, upsert=True)
        else:
            r = await db.insert_one(state)
            self._id = r.inserted_id
            return r

    async def delete(self):
        """ Alias to delete this object in the database """
        db = self.objects
        if self._id:
            return await db.delete_one({'_id': self._id})
Exemple #30
0
class Brush(Atom):
    """Defines the fill pattern"""

    #: Color
    color = ColorMember()

    #: Image
    image = Instance(Image)

    #: Style
    style = Enum(
        "solid",
        "dense1",
        "dense2",
        "dense3",
        "dense4",
        "dense5",
        "dense6",
        "dense7",
        "horizontal",
        "vertical",
        "cross",
        "diag",
        "bdiag",
        "fdiag",
        "linear",
        "radial",
        "conical",
        "texture",
        "none",
    )

    #: Internal data
    _tkdata = Value()