예제 #1
0
파일: main.py 프로젝트: ktosiek/spanel
import gtk
import gobject
import dbus
import dbus.service
from dbus.mainloop.glib import DBusGMainLoop

from utils import Enum, GdkLock

# setting DEBUG for pre-main initialization, it will be changed in main()
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

height = 16

Positions = Enum(('TOP', 'BOTTOM'))

class PanelWindow(gtk.Window):

    def __init__(self, position=Positions.TOP, widgets=[]):
        super(PanelWindow, self).__init__(gtk.WINDOW_TOPLEVEL)
        self.set_default_size(gtk.gdk.screen_width(), height)
        self.set_type_hint(gtk.gdk.WINDOW_TYPE_HINT_DOCK)
        self._box = gtk.HBox()
        self.add(self._box)
        self.setup_widgets(widgets)
        self.show_all()
        for w, _ in widgets:  # TODO: create widget protocol
            if hasattr(w, 'on_visible'):
                w.on_visible()
        if position == Positions.TOP:
예제 #2
0
from utils import Enum

Direction = Enum('North', 'NorthEast', 'East', 'SouthEast', 'South',
                 'SouthWest', 'West', 'NorthWest')


class Action:
    """
        This class represents interface of an action.
        It should be derived from but never instantiated directly.
    """
    def __init__(self):
        pass


class Shot(Action):
    def __init__(self, direction):
        """
            Args:
                direction (Direction): enum value
        """
        Action.__init__(self)
        self.direction = direction


class Move(Action):
    def __init__(self, direction):
        """
            Args:
                direction (Direction): enum value
        """
예제 #3
0
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
###############################################################################

from utils import Enum

Command = Enum('FORWARD', 'BACKWARD', 'SHOOT')

Facing = Enum('UP', 'DOWN', 'LEFT', 'RIGHT')

TankState = Enum('IDLE', 'MOVING', 'TURNING', 'SHOOTING', 'DEAD')

# make sure Tiles and Items match what world contains!

Tile = Enum('GRASS', 'DIRT', 'WATER', 'PLAIN')

Item = Enum('TREE', 'ROCK', 'TANK_RED', 'TANK_BLUE')

FACING_TO_VEC = {
    Facing.UP: (0, -1),
    Facing.DOWN: (0, 1),
    Facing.LEFT: (-1, 0),
예제 #4
0
from utils import Enum

TokenType = Enum("SLASH",
				 "LBRACKET",
				 "RBRACKET",
				 "COMMA",
				 "DOT",
				 "NUMBER",
				 "WORD",
				 "QUOTED",
				 "WHITESPACE",
				 "BINARYOPERATOR",
				 "UNARYOPERATOR",
				 "UNKNOWN"
				)

class Token(object):
	""" A simple Token structure. Token type, value and position.
	"""
	def __init__(self, token_type, val, pos):
		self.type = token_type
		self.val = val
		self.pos = pos

	def __str__(self):
		return '%s(%s) at %s' % (TokenType.name_of(self.type), self.val, self.pos)


class LexerError(Exception):
	def __init__(self, pos):
		self.pos = pos
예제 #5
0
import os

from itertools import izip, chain, imap

import cherrypy

from base import Widget
from utils import OrderedSet
from utils import Enum

locations = Enum(["head", "bodytop", "bodybottom"])


class Resource(Widget):

    location = locations.head

    @property
    def name(self):
        return None


class Link(Resource):

    params = {
        'link': None,
    }

    filename = None
    modname = None
예제 #6
0
파일: tray.py 프로젝트: ktosiek/spanel
class TrayWidget(gtk.EventBox):
    _metaclass_ = Singleton

    OpCode = Enum((
        'REQUEST_DOCK',
        'BEGIN_MESSAGE',
        'CANCEL_MESSAGE',
    ))

    def __init__(self):
        super(TrayWidget, self).__init__()
        self._box = gtk.HBox()
        self.add(self._box)
        self.connect("client-event", self.client_event)

    def on_visible(self):
        if not gtk.selection_owner_set_for_display(
            gtk.gdk.display_get_default(),
            self,
            "_NET_SYSTEM_TRAY_S0", # TODO: this should be the actual screen
            gtk.gdk.CURRENT_TIME):
            raise Exception("Cannot get _NET_SYSTEM_TRAY_S0")

    def client_event(self, widget, event):
        logger.debug("received client event of type %s from %s",
                     event.message_type, event.window)
        if event.message_type == "_NET_SYSTEM_TRAY_OPCODE":
            data = TrayWidget.parse_xevent_data(event.data, event.data_format)
            timestamp = data[0]
            opcode = data[1]
            logger.debug("...with opcode %i (%s)", opcode,
                         self.OpCode[opcode])
            if opcode == self.OpCode.REQUEST_DOCK:
                icon_wid = data[2]
                self.add_icon(timestamp, icon_wid)
            elif opcode == self.OpCode.BEGIN_MESSAGE:
                timeout, msg_len, msg_id = data[2:5]
                self.receive_message(event.window, msg_len, msg_id, timeout)
            elif opcode == self.OpCode.CANCEL_MESSAGE:
                msg_id = data[2]
                self.cancel_message(event.window, msg_id)
            return True  # This event was handled here, so stop propagation
        elif event.message_type == "_NET_SYSTEM_TRAY_MESSAGE_DATA":
            data = TrayWidget.parse_xevent_data(event.data, event.data_format)
            raw_data = ''.join(imap(chr, takewhile(lambda x: x, data)))
            self.continue_message(event.window, raw_data)
            return True

    def add_icon(self, timestamp, icon_window_id):
        logger.debug("Icon 0x%x", icon_window_id)
        socket = IconSocket()
        logger.debug("...installed in socket %s", repr(socket))
        self._box.pack_end(socket, expand=False)
        socket.show()
        socket.add_id(icon_window_id)
        self.queue_draw()

    def receive_message(self, window, msg_len, msg_id, timeout):
        # TODO
        logger.warning("Msg %i from %s", msg_id, window)

    def continue_message(self, window, data):
        # TODO
        logger.warning("Msg data from %s: '%s'", window, data)

    def cancel_message(self, window, msg_id):
        # TODO
        logger.warning("Cancel msg %i from %s", msg_id, window)

    @staticmethod
    def parse_xevent_data(raw_data, data_format):
        # values may be 64 bit for 32 bit format somehow,
        # so I'm baseing length of value on length of data.
        # Data should be 20 elements long.
        v_len = (len(raw_data)/20) * (data_format/8)
        data = [0] * (len(raw_data)/v_len)
        # reversed because of endianness
        for i, c in reversed(list(enumerate(raw_data))):
            data[i/v_len] <<= v_len
            data[i/v_len] |= ord(c)
        return data
예제 #7
0
import types
import re
from utils import Enum

match = Enum(["NEVER", "NO", "YES"])


class demand(object):
    """
    Base class for what a task may demand
    """
    def matches(self, subject):
        raise NotImplementedError("Need must implement matches")


class predicateObjectDemand(demand):
    """
    Base class for demands which matches against predicates and possibly objects
    """
    def __init__(self, predicate, object=None):
        self.predicate = predicate
        self.object = object  # if object != None else ""

        # TODO This should be in task rather
        #        if isinstance(self.predicate, types.ListType) or isinstance(self.predicate, types.TupleType):
        #            self.predicate = self.predicate[0]
        #            self.object = self.predicate[1]

        if not isinstance(self.predicate, types.StringTypes):
            raise ValueError("Predicate must be string type")
예제 #8
0
from scheduling import ScheduledFunc
import ujson as json
from utils import Enum
import config

logger_types = Enum(["SERIAL", "MQTT", "HTTP"])


class BaseLogger(ScheduledFunc):
    def __init__(self, period_sec, decoded_ref, raw_data_ref, timer_num=1):
        super().__init__(timer_num, 1 / period_sec)
        self.raw_data = raw_data_ref
        self.decoded_data = decoded_ref

    def log(self, *args):
        print(self.raw_data)

    def start(self):
        self.tim.init(freq=self.freq, callback=self.log)


class AbstractWebLogger(BaseLogger):
    def __init__(
        self,
        period_sec,
        decoded_ref,
        raw_data_ref,
        timer_num=1,
        server=None,
        send_raw=False,
        session_id=None,
예제 #9
0
#
# Visits SCCD-domain constructs (see sccd_constructs.py) and converts them
# to a generic language AST (see generic_language_constructs.py), that can
# then be visited by a target language writer.

import traceback

import time
from utils import Enum, Logger

from visitor import Visitor
from sccd_constructs import FormalParameter
from stateful_writer import StatefulWriter
import generic_language_constructs as GLC

Platforms = Enum("Threads", "GameLoop", "EventLoop")


class GenericGenerator(Visitor):
    def __init__(self, platform):
        self.platform = platform
        self.writer = StatefulWriter()

    def generic_visit(self, node):
        Logger.showWarning(
            "GenericGenerator has no visit method for node of type '" +
            str(type(node)) + "'.")

    def get(self):
        return self.writer.get()
예제 #10
0
    def __init__(self):
        for k in ElaErrors.__dict__:
            v = ElaErrors.__dict__[k]
            if isinstance(v, (int, long)):
                self[v] = k
                self[k] = v

    def hex(self, v):
        return '{0:08X}'.format(v)


NONE = 0
AWAY = 1
BUSY = 2
Presence = Enum(none=NONE, away=AWAY, busy=BUSY)

CONNECTED = 0
DISCONNECTED = 1
ConnectionState = Enum(connected=CONNECTED, disconnected=DISCONNECTED)

FATAL = 1
ERROR = 2
WARNING = 3
INFO = 4
DEBUG = 5
TRACE = 6
VERBOSE = 7
LogLevel = Enum(none=NONE,
                fatal=FATAL,
                warning=WARNING,